cpa-core 0.4.1

Part of cliproxy: config, credentials, formats and the execution envelope
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
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
//! `config.yaml`, read the way CLIProxyAPI v8 reads it (internal/config/config_v8.go,
//! config_load.go).
//!
//! Both the v8 layout (`server.port`, `access.api-keys`, `oauth.auth-dir`) and the
//! legacy top-level spellings are accepted. Presence decides: a v8 key that is present
//! wins even when it is `null`, `0`, `false` or empty. A v8 parent that is present but
//! not a mapping is an error, so `access: null` is rejected instead of silently opening
//! the proxy.

use std::path::{Path, PathBuf};

use anyhow::{Context, bail};
use serde::{Deserialize, Serialize};
use serde_yaml_ng::{Mapping, Value};

mod binary;
pub mod credentials;
mod document;
pub mod go_url;
mod sanitize;
mod schema;
mod text;
mod timestamp;
mod trusted;
mod validate;
pub use binary::{PLAIN as PLAIN_SCALAR, double_quoted as yaml_double_quoted};
pub use document::{ConfigDocument, archive_comments, credential_error, is_v8_layout, v8_group_error, v8_layout_error};
pub use schema::validate as validate_config_fields;
pub use schema::{coerce_typed_scalars, go_bool, go_int};
pub use timestamp::{AsJson, TAG as TIMESTAMP_TAG};

/// `text` parsed as serde_yaml_ng does, except for plain scalars it reads otherwise
/// than yaml.v3: an integer beyond int64 and uint64, which serde_yaml_ng refuses when
/// it fits 128 bits (yaml.v3 reads a decimal one as a float and any other, `0x…` or
/// `0o…`, as text), and a number with underscores (`1_000`) or a leading zero (`007`,
/// `08`), which serde_yaml_ng reads as text and yaml.v3 as a number. Those scalars are
/// read as yaml.v3 reads them, and a timestamp (`2001-12-14`), which yaml.v3 reads into
/// an untyped value as a `time.Time`, is its RFC 3339 text tagged [`TIMESTAMP_TAG`]. A
/// string setting still gets the scalar's text from the literal walk, which reads `text`
/// itself; such a mapping key stays text, as yaml.v3 reads it into a string-keyed map.
pub fn parse_yaml(text: &str) -> Result<Value, serde_yaml_ng::Error> {
    // serde_yaml_ng, like libyaml with its encoding set, reads a leading BOM as part of
    // the first line, which then fails a second top-level key; yaml.v3 skips it.
    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
    let parse = |text: &str| serde_yaml_ng::from_str::<Value>(text);
    // Without an underscore or a leading zero, only a failed parse needs a second look;
    // it keeps its error when no scalar is rewritten.
    let err = if may_resolve(text) {
        None
    } else {
        match parse(text) {
            Ok(value) if !needs_scan(&value) => return Ok(value),
            Ok(_) => None,
            Err(err) => Some(err),
        }
    };
    let as_is = |err: Option<serde_yaml_ng::Error>| err.map_or_else(|| parse(text), Err);
    let Ok(scalars) = binary::plain_scalars(text) else {
        return as_is(err);
    };
    // One pass over the scalars, then one parse.
    let mut out = String::with_capacity(text.len());
    let mut last = 0;
    for plain in scalars.into_iter().filter(|p| p.timestamp_tag.is_none()) {
        let read = std::str::from_utf8(&plain.value)
            .ok()
            .and_then(|s| go_read(s, plain.key));
        let (Some(read), Some(before)) = (read, text.get(last..plain.span.start)) else {
            continue;
        };
        out.push_str(before);
        out.push_str(&read);
        last = plain.span.end;
    }
    if last == 0 {
        return as_is(err);
    }
    out.push_str(&text[last.min(text.len())..]);
    parse(&out)
}

/// `value` as serde_yaml_ng writes it, except that a string [`parse_yaml`] would read
/// back as a number or timestamp when written plain (`1_000`, `0_8`, `0b-1`,
/// `2001-12-14`) is double-quoted, as yaml.v3 quotes it, and a [`TIMESTAMP_TAG`] value
/// is its text, plain, as yaml.v3 writes a `time.Time`. serde_yaml_ng quotes only the
/// strings it reads as something else itself.
pub fn yaml_string(value: &Value) -> Result<String, serde_yaml_ng::Error> {
    let text = serde_yaml_ng::to_string(value)?;
    // A number serde_yaml_ng writes has no underscore or leading zero, so each scalar
    // flagged here is a string. It quotes a string beyond 64 bits (`'18446744073709551616'`)
    // itself.
    if !may_resolve(&text) && !needs_scan(value) {
        return Ok(text);
    }
    let Ok(scalars) = binary::plain_scalars(&text) else {
        return Ok(text);
    };
    let mut out = String::with_capacity(text.len() + 2);
    let mut last = 0;
    for plain in scalars {
        if let Some(tag) = plain.timestamp_tag {
            out.push_str(&text[last..tag]);
            out.push_str(&text[plain.span.clone()]);
            last = plain.span.end;
            continue;
        }
        // A key is checked as a value: yaml.v3 reads a plain `1_000:` key as a number,
        // which in an untyped map is no longer the string key it was.
        let flagged = std::str::from_utf8(&plain.value).ok().and_then(|s| go_read(s, false));
        if flagged.is_none() {
            continue;
        }
        // The flagged spellings hold only ASCII letters, digits, spaces and `_.,:+-`.
        out.push_str(&text[last..plain.span.start]);
        out.push('"');
        out.push_str(&text[plain.span.clone()]);
        out.push('"');
        last = plain.span.end;
    }
    out.push_str(&text[last..]);
    Ok(out)
}

/// Whether `text` may hold a plain scalar with an underscore or a leading zero, which
/// [`go_read`] rewrites without a parse error to point at it.
fn may_resolve(text: &str) -> bool {
    let zero = |w: &[u8]| w[0] == b'0' && (w[1].is_ascii_digit() || matches!(w[1], b'b' | b'o' | b'X' | b'O' | b'B'));
    text.contains('_')
        || text.as_bytes().starts_with(b"0")
        || text
            .as_bytes()
            .windows(3)
            .any(|w| zero(&w[1..]) && !(w[0].is_ascii_alphanumeric() || w[0] == b'.'))
}

/// Whether `value` holds a string, key or value, that may be a plain timestamp, a
/// [`TIMESTAMP_TAG`] value, or an integer past int64, which `+` makes a float in Go.
fn needs_scan(value: &Value) -> bool {
    match value {
        Value::String(s) => timestamp::go_timestamp(s).is_some(),
        Value::Number(n) => n.as_i64().is_none() && n.as_u64().is_some(),
        Value::Sequence(items) => items.iter().any(needs_scan),
        Value::Mapping(m) => m.iter().any(|(k, v)| needs_scan(k) || needs_scan(v)),
        Value::Tagged(t) => t.tag == timestamp::TAG || needs_scan(&t.value),
        _ => false,
    }
}

/// What [`parse_yaml`] writes for a plain scalar so that serde_yaml_ng reads it as
/// yaml.v3 does; `None` where they agree. A mapping key keeps its text unless
/// serde_yaml_ng would refuse it.
fn go_read(scalar: &str, key: bool) -> Option<String> {
    if !key && let Some(time) = timestamp::go_timestamp(scalar) {
        // Verbatim, so a `%TAG !` directive cannot redefine it.
        return Some(format!("!<{}> {time}", timestamp::TAG));
    }
    let unsigned = scalar.strip_prefix(['+', '-']).unwrap_or(scalar).as_bytes();
    let leading_zero = unsigned.first() == Some(&b'0')
        && unsigned
            .get(1)
            .is_some_and(|b| b.is_ascii_digit() || matches!(b, b'b' | b'o' | b'X' | b'O' | b'B'));
    if scalar.contains('_') || leading_zero {
        // A `0o` or `0b` integer beyond 64 bits that Go reads as text.
        (!key)
            .then(|| go_resolved(scalar))
            .flatten()
            .or_else(|| go_big_integer(scalar, key))
    } else {
        go_big_integer(scalar, key)
    }
}

/// yaml.v3's reading of a plain scalar with underscores or a leading zero (its
/// `resolve`), written so that serde_yaml_ng reads the same; `None` where yaml.v3 reads
/// text or a timestamp (`0001-01-01`), which serde_yaml_ng reads as text. A scalar that
/// starts with a digit or sign drops its underscores and reads as an integer (`0x`,
/// `0o`, `0b` or a leading `0` for octal), else as a float in YAML's float syntax; one
/// that starts with `.` reads as a float when each underscore sits between digits.
fn go_resolved(text: &str) -> Option<String> {
    let plain = text.replace('_', "");
    let float = |s: &str| {
        let f = go_yaml_float(s)?;
        Some(format!("{f:e}"))
    };
    match text.as_bytes().first()? {
        b'.' => {
            let bytes = text.as_bytes();
            let between_digits = bytes.iter().enumerate().all(|(i, &b)| {
                b != b'_'
                    || (i > 0 && bytes[i - 1].is_ascii_digit() && bytes.get(i + 1).is_some_and(u8::is_ascii_digit))
            });
            if between_digits { float(&plain) } else { None }
        }
        b'0'..=b'9' | b'+' | b'-' => {
            let negative = plain.starts_with('-');
            let signed = plain.starts_with(['+', '-']);
            let unsigned = plain.strip_prefix(['+', '-']).unwrap_or(&plain);
            let (radix, digits) = match unsigned.get(..2) {
                Some("0x" | "0X") => (16, &unsigned[2..]),
                Some("0o" | "0O") => (8, &unsigned[2..]),
                Some("0b" | "0B") => (2, &unsigned[2..]),
                _ if unsigned.len() > 1 && unsigned.starts_with('0') => (8, &unsigned[1..]),
                _ => (10, unsigned),
            };
            if !digits.is_empty() && digits.chars().all(|c| c.is_digit(radix)) {
                // Go's ParseInt, then ParseUint (which takes no sign).
                if let Ok(n) = u64::from_str_radix(digits, radix) {
                    if negative && n <= 1 << 63 {
                        return Some(format!("-{n}"));
                    }
                    if !negative && (n <= i64::MAX as u64 || !signed) {
                        return Some(n.to_string());
                    }
                    // `+0x…`, `+0o…` or `+0b…` past int64: ParseInt overflows and
                    // ParseUint takes no sign, so Go reads text; serde_yaml_ng a u64.
                    if !negative && unsigned.as_bytes().get(1).is_some_and(u8::is_ascii_alphabetic) {
                        return Some(format!("'{text}'"));
                    }
                }
            }
            if let Some(f) = float(&plain) {
                return Some(f);
            }
            // Go's last resort: `0b` or `0o` then ParseInt of the rest, which takes a
            // sign (`0b-1` is -1), then ParseUint.
            let (radix, rest) = match plain.get(..2)? {
                "0b" => (2, &plain[2..]),
                "0o" => (8, &plain[2..]),
                _ => return None,
            };
            let n = i64::from_str_radix(rest, radix).map(|n| n.to_string());
            let unsigned = || {
                (!rest.starts_with('+'))
                    .then(|| u64::from_str_radix(rest, radix).ok())
                    .flatten()
            };
            n.ok().or_else(|| unsigned().map(|n| n.to_string()))
        }
        _ => None,
    }
}

/// `s` as a float when it has yaml.v3's float syntax and Go parses it in range.
fn go_yaml_float(s: &str) -> Option<f64> {
    let digits = |s: &str| s.len() - s.trim_start_matches(|c: char| c.is_ascii_digit()).len();
    let rest = s.strip_prefix(['+', '-']).unwrap_or(s);
    let (mantissa, exponent) = match rest.find(['e', 'E']) {
        Some(at) => (&rest[..at], Some(&rest[at + 1..])),
        None => (rest, None),
    };
    let mantissa_ok = match mantissa.split_once('.') {
        Some(("", frac)) => !frac.is_empty() && digits(frac) == frac.len(),
        Some((int, frac)) => !int.is_empty() && digits(int) == int.len() && digits(frac) == frac.len(),
        None => !mantissa.is_empty() && digits(mantissa) == mantissa.len(),
    };
    let exponent_ok = exponent.is_none_or(|e| {
        let e = e.strip_prefix(['+', '-']).unwrap_or(e);
        !e.is_empty() && digits(e) == e.len()
    });
    if !(mantissa_ok && exponent_ok) {
        return None;
    }
    s.parse::<f64>().ok().filter(|f| f.is_finite())
}

/// yaml.v3's reading of a plain integer beyond int64 and uint64 that serde_yaml_ng
/// refuses (one that fits u128, or i128 when negative, and is not a decimal with a
/// leading zero), written so that serde_yaml_ng reads the same: a decimal one as its
/// float, any other quoted. A value with a `+` past int64 reads so too: Go's ParseUint
/// takes no sign, where serde_yaml_ng reads a u64. `None` for any other scalar, which
/// serde_yaml_ng reads.
fn go_big_integer(text: &str, key: bool) -> Option<String> {
    let negative = text.starts_with('-');
    let unsigned = text.strip_prefix(['+', '-']).unwrap_or(text);
    let (radix, digits) = match unsigned.get(..2) {
        Some("0x" | "0X") => (16, &unsigned[2..]),
        Some("0o" | "0O") => (8, &unsigned[2..]),
        Some("0b" | "0B") => (2, &unsigned[2..]),
        _ => (10, unsigned),
    };
    if digits.is_empty() || (radix == 10 && digits.len() > 1 && digits.starts_with('0')) {
        return None;
    }
    let magnitude = u128::from_str_radix(digits, radix).ok()?;
    if negative && magnitude > 1 << 127 {
        return None;
    }
    let fits = if negative {
        i64::from_str_radix(&format!("-{digits}"), radix).is_ok()
    } else if text.starts_with('+') && !key {
        i64::from_str_radix(digits, radix).is_ok()
    } else {
        u64::from_str_radix(digits, radix).is_ok()
    };
    if fits {
        return None;
    }
    Some(if radix == 10 {
        format!("{:e}", text.parse::<f64>().ok()?)
    } else {
        format!("'{text}'")
    })
}

/// A config text with its tagged scalars as yaml.v3 decodes them (`!!binary` values
/// base64-decoded, aliases of them included), merges not yet expanded. The management
/// document reads config text through here and the loader through [`config_value`], so
/// a view or a save candidate sees the tagged values the loader sees.
pub fn yaml_value(text: &str) -> anyhow::Result<Value> {
    let mut value = parse_yaml(text)?;
    timestamp::refuse_wide_offsets(&value)?;
    binary::decode(text, &mut value, None, binary::Mode::File)?;
    Ok(value)
}

/// [`yaml_value`] as Go's typed decode reads it into the config: a plain scalar in a Go
/// string setting is its text (`1.50`, `0x1F`, `true`), where serde_yaml_ng reads a
/// number or boolean. The management views keep [`yaml_value`]'s YAML types, as Go's
/// read the file's nodes.
pub fn config_value(text: &str) -> anyhow::Result<Value> {
    let mut value = parse_yaml(text)?;
    timestamp::refuse_wide_offsets(&value)?;
    binary::decode(text, &mut value, Some(&[]), binary::Mode::File)?;
    Ok(value)
}

/// [`Config::plugin_configs`] of `text`, whose parsed root is `root`.
fn plugin_configs(text: &str, root: &Mapping) -> Value {
    if !lookup(root, "plugins.configs").is_some_and(|c| c.as_mapping().is_some_and(|m| !m.is_empty())) {
        return Value::Null;
    }
    let raw = || {
        let mut value = parse_yaml(text)?;
        binary::decode(text, &mut value, Some(&[]), binary::Mode::Plugins)?;
        expand_merges(&mut value)?;
        anyhow::Ok(value)
    };
    match raw() {
        Ok(v) => v
            .get("plugins")
            .and_then(|p| p.get("configs"))
            .cloned()
            .unwrap_or(Value::Null),
        // The same text loaded, so only a limit this read alone hits (alias copies of
        // plugin scalars) gets here.
        Err(e) => {
            // Management reads re-parse the file: warn once per text.
            static WARNED: std::sync::Mutex<u64> = std::sync::Mutex::new(0);
            let hash = {
                use std::hash::{Hash, Hasher};
                let mut h = std::collections::hash_map::DefaultHasher::new();
                text.hash(&mut h);
                h.finish()
            };
            let mut warned = WARNED.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
            if *warned != hash {
                *warned = hash;
                tracing::warn!("plugin configs keep their parsed values: {e:#}");
            }
            Value::Null
        }
    }
}

/// A management write's body, the value at `keys` of the config: Go parses it as YAML
/// nodes and saves their text, so a number or boolean in a string setting whose text the
/// save would not write back (`1.50`, `1e3`) is that text. One the save writes back as
/// it is (`5`, `true`) keeps its YAML type, so the saved file and its views stay Go's.
pub fn body_value(text: &str, keys: &[&str]) -> anyhow::Result<Value> {
    fn keep_written(literal: &mut Value, parsed: Value) {
        match (literal, parsed) {
            (Value::Mapping(l), Value::Mapping(p)) => {
                for ((_, l), (_, p)) in l.iter_mut().zip(p) {
                    keep_written(l, p);
                }
            }
            (Value::Sequence(l), Value::Sequence(p)) => {
                for (l, p) in l.iter_mut().zip(p) {
                    keep_written(l, p);
                }
            }
            (l @ Value::String(_), p @ (Value::Number(_) | Value::Bool(_)))
                if l.as_str() == Some(go_string(&p).as_str()) =>
            {
                *l = p;
            }
            _ => {}
        }
    }
    let parsed = parse_yaml(text)?;
    let mut value = parsed.clone();
    binary::decode(text, &mut value, Some(keys), binary::Mode::Body)?;
    keep_written(&mut value, parsed);
    Ok(value)
}

/// yaml.v3's error for a merge value that is not a mapping or a list of mappings.
const MERGE_NOT_MAPS: &str = "yaml: map merge requires map or sequence of maps as the value";

/// Go `expandConfigAliases` plus yaml.v3's merge rules: `<<` keys expand bottom-up
/// (nested merges first); explicit keys win, then earlier merged mappings. A merge
/// value that is not a mapping or a list of mappings is yaml.v3's decode error, even in
/// a merge source an explicit key or an earlier source shadows, which yaml.v3 never
/// decodes.
/// (Aliases are already expanded by the parser.) The parsed value no longer says whether
/// a key was quoted or a merge operand an alias, so [`yaml_value`] refuses a quoted
/// `<<` key (yaml.v3 reads it as a plain key) and fails an alias of a sequence as a
/// merge operand. A JSON management body, which is not read through it, keeps `<<`
/// literal until the completed candidate is expanded, as Go's save ends up writing it plain.
pub fn expand_merges(value: &mut Value) -> anyhow::Result<()> {
    match value {
        Value::Mapping(map) => {
            for (_, child) in map.iter_mut() {
                expand_merges(child)?;
            }
            if let Some(merge) = map.shift_remove("<<") {
                let sources: Vec<Mapping> = match untagged(merge) {
                    Value::Mapping(m) => vec![m],
                    Value::Sequence(items) => items
                        .into_iter()
                        .map(|item| match untagged(item) {
                            Value::Mapping(m) => Ok(m),
                            _ => Err(anyhow::anyhow!(MERGE_NOT_MAPS)),
                        })
                        .collect::<anyhow::Result<_>>()?,
                    _ => bail!(MERGE_NOT_MAPS),
                };
                for source in sources {
                    for (key, item) in source {
                        map.entry(key).or_insert(item);
                    }
                }
            }
        }
        Value::Sequence(items) => {
            for item in items {
                expand_merges(item)?;
            }
        }
        Value::Tagged(tagged) => expand_merges(&mut tagged.value)?,
        _ => {}
    }
    Ok(())
}

/// A merge operand without its local tags: yaml.v3 merges a tagged mapping by its kind.
fn untagged(value: Value) -> Value {
    match value {
        Value::Tagged(tagged) => untagged(tagged.value),
        other => other,
    }
}
pub use trusted::{TrustedProxies, go_trim_space};
pub use validate::{catalog_sources as validate_catalog_sources, go_is_abs, parse_duration};

/// Default port used only where CLIProxyAPI falls back to it (management base URL).
/// The loader itself leaves an omitted port at 0, as Go does.
pub const DEFAULT_PORT: u16 = 8317;
pub const DEFAULT_AUTH_DIR: &str = "~/.cli-proxy-api";

#[derive(Clone, PartialEq, Eq)]
pub struct Config {
    /// Bind address. Empty binds all interfaces.
    pub host: String,
    /// 0 when omitted, like Go: the listener then gets an ephemeral port.
    pub port: u16,
    /// Client keys for the proxy API, trimmed and de-duplicated. Empty disables client auth.
    pub api_keys: Vec<String>,
    /// `server.trusted-proxies`, validated. Go applies it at startup only.
    pub trusted_proxies: Vec<String>,
    pub auth_dir: PathBuf,
    pub routing: RoutingConfig,
    pub management: ManagementConfig,
    /// Presence-preserving v8 view, including fields not yet wired into executors.
    pub document: Value,
    /// v8 `oauth.providers.*` leaf paths present in the source text (Go
    /// `Config.OAuthOnlyFields`, keyed by v8 path rather than legacy name). They
    /// apply to OAuth credentials only; see [`Config::for_api_key`]. Settings written
    /// in the legacy layout stay global, as in Go.
    pub oauth_only: std::collections::BTreeSet<String>,
    /// `plugins.configs` as Go hands each plugin its raw node (pluginhost
    /// `runtimeConfigYAML`): a plain scalar that is not plain text to serde_yaml_ng is its
    /// YAML text tagged [`PLAIN_SCALAR`] (`1.50`, `1e3`, `0x1F`, `007`, `!!float 1`), where
    /// [`Config::document`] holds what serde_yaml_ng reads. Null without plugin configs.
    pub plugin_configs: Value,
    /// Values derived from this snapshot, built on first use ([`Config::derived`]).
    pub derived: Derived,
}

/// A per-snapshot cache of values computed from a [`Config`] (for example parsed payload
/// rules), one per type. Everyone holding the same snapshot shares them. A clone starts
/// empty and the cache never affects equality. Derive from configs that will not be
/// mutated afterwards; the runtime's published snapshots are immutable.
#[derive(Default)]
pub struct Derived(std::sync::Mutex<Vec<std::sync::Arc<dyn std::any::Any + Send + Sync>>>);

impl Clone for Derived {
    fn clone(&self) -> Self {
        Self::default()
    }
}

impl PartialEq for Derived {
    fn eq(&self, _: &Self) -> bool {
        true
    }
}

impl Eq for Derived {}

impl Config {
    /// `models.catalog`, `models.codex-catalog` and `models.devin-catalog` (Go
    /// `CatalogSources`); empty when unset.
    pub fn catalog_sources(&self) -> [String; 3] {
        ["catalog", "codex-catalog", "devin-catalog"].map(|name| {
            self.document
                .get("models")
                .and_then(|models| models.get(name))
                .filter(|v| !v.is_null())
                .map(go_string)
                .unwrap_or_default()
        })
    }

    /// The value of type `T` derived from this snapshot, computing it with `init` on first
    /// use. Concurrent first uses may both compute; the first stored value wins.
    pub fn derived<T: std::any::Any + Send + Sync>(&self, init: impl FnOnce(&Config) -> T) -> std::sync::Arc<T> {
        let find = |slots: &[std::sync::Arc<dyn std::any::Any + Send + Sync>]| {
            slots.iter().find_map(|v| v.clone().downcast::<T>().ok())
        };
        let lock = || self.derived.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
        if let Some(found) = find(&lock()) {
            return found;
        }
        let value = std::sync::Arc::new(init(self));
        let mut slots = lock();
        if let Some(found) = find(&slots) {
            return found;
        }
        slots.push(value.clone());
        value
    }
}

impl std::fmt::Debug for Config {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Config")
            .field("host", &self.host)
            .field("port", &self.port)
            .field("routing", &self.routing)
            .finish_non_exhaustive()
    }
}

/// yaml.v3 decodes any scalar into a Go `string` field; serde would reject numbers.
fn de_go_string<'de, D: serde::Deserializer<'de>>(d: D) -> Result<String, D::Error> {
    Ok(go_string(&Value::deserialize(d)?))
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(default, rename_all = "kebab-case")]
pub struct RoutingConfig {
    #[serde(deserialize_with = "de_go_string")]
    pub strategy: String,
    pub force_model_prefix: bool,
    pub session_affinity: bool,
    #[serde(deserialize_with = "de_go_string")]
    pub session_affinity_ttl: String,
    pub session_affinity_subagents: Option<bool>,
    pub retry: RetryConfig,
    pub cooldown: CooldownConfig,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(default, rename_all = "kebab-case")]
pub struct RetryConfig {
    pub request_retry: i64,
    pub max_retry_credentials: i64,
    pub max_retry_interval: i64,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(default, rename_all = "kebab-case")]
pub struct CooldownConfig {
    pub disable_cooling: bool,
    pub save_cooldown_status: bool,
    pub transient_error_cooldown_seconds: i64,
    /// cliproxy-rs only: the longest quota reset trusted at first, as a duration
    /// (`"1h"`) or seconds; empty means one hour, `0` trusts every reset (Go).
    #[serde(deserialize_with = "de_go_string", skip_serializing_if = "String::is_empty")]
    pub max_trusted_cooldown: String,
}

// Do not derive Debug: the key must never appear in diagnostic output.
#[derive(Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(default, rename_all = "kebab-case")]
pub struct ManagementConfig {
    pub allow_remote: bool,
    #[serde(deserialize_with = "de_go_string")]
    pub secret_key: String,
    pub disable_control_panel: bool,
    pub disable_auto_update_panel: bool,
    #[serde(deserialize_with = "de_go_string")]
    pub panel_github_repository: String,
}

impl std::fmt::Debug for ManagementConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ManagementConfig")
            .field("allow_remote", &self.allow_remote)
            .field("disable_control_panel", &self.disable_control_panel)
            .finish_non_exhaustive()
    }
}

impl Default for Config {
    fn default() -> Self {
        Self::parse("{}").expect("empty mapping is valid")
    }
}

/// Writes `hash` over the plaintext `secret-key` (see [`with_secret_hash`]).
fn persist_secret_hash(path: &Path, text: &str, hash: &str) -> anyhow::Result<()> {
    ConfigDocument::write(path, &with_secret_hash(text, hash)?)
}

/// `text` with `hash` over the effective `secret-key`: in place when the key is written
/// literally and nothing else shares it, else the merge- and alias-expanded tree, as
/// Go's `updateNestedScalarYAML` writes it. ponytail: that fallback re-emits without
/// comments; Go keeps the node comments.
fn with_secret_hash(text: &str, hash: &str) -> anyhow::Result<String> {
    // Go's save writes its parsed nodes, which drops a leading BOM.
    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
    let expanded = |t: &str| -> anyhow::Result<Value> {
        let mut root: Value = parse_yaml(t)?;
        expand_merges(&mut root)?;
        Ok(root)
    };
    let mut want = expanded(text)?;
    let mapping = want.as_mapping().context("config must be a mapping")?;
    let v8 = lookup(mapping, "management.secret-key").is_some();
    let parent = if v8 { "management" } else { "remote-management" };
    // In place only over a literal key: an inherited one would stay in the merge.
    let literal = parse_yaml(text)
        .ok()
        .and_then(|raw| raw.get(parent)?.as_mapping()?.get("secret-key").cloned())
        .is_some();
    let in_place = literal.then(|| {
        let file: yaml_edit::YamlFile = text.parse().ok()?;
        file.document()?.get_mapping(parent)?.set("secret-key", hash);
        Some(file.to_string())
    });
    want.get_mut(parent)
        .and_then(Value::as_mapping_mut)
        .context("management must be a mapping")?
        .insert(Value::from("secret-key"), Value::from(hash));
    // An anchored key edited in place would also change every alias of it.
    let updated = match in_place.flatten().filter(|t| expanded(t).is_ok_and(|v| v == want)) {
        Some(t) => t,
        None => {
            let t = yaml_string(&want)?;
            // The re-emitted tree writes parsed values (`0x1F` becomes `31`) and drops
            // tags; Go keeps each node's text and tag. Refuse rather than change
            // another setting: on any explicit tag, any key that is not a string, or
            // any other scalar whose text would change.
            fn plain_keys(v: &Value) -> bool {
                match v {
                    Value::Mapping(m) => m.iter().all(|(k, v)| matches!(k, Value::String(_)) && plain_keys(v)),
                    Value::Sequence(items) => items.iter().all(plain_keys),
                    Value::Tagged(_) => false,
                    _ => true,
                }
            }
            let tagged = yaml_edit::lex(text)
                .iter()
                .any(|(kind, _)| *kind == yaml_edit::SyntaxKind::TAG);
            anyhow::ensure!(
                !tagged && plain_keys(&want),
                "rewriting the config file would change the text of another setting"
            );
            let others = |t: &str| -> anyhow::Result<Value> {
                let mut tree = scalar_texts(t)?;
                expand_merges(&mut tree)?;
                if let Some(m) = tree.get_mut(parent).and_then(Value::as_mapping_mut) {
                    m.remove("secret-key");
                }
                Ok(tree)
            };
            anyhow::ensure!(
                others(text)? == others(&t)?,
                "rewriting the config file would change the text of another setting"
            );
            t
        }
    };
    let stored = scalar_texts(&updated).ok().map(|tree| effective_secret(&tree));
    anyhow::ensure!(stored.as_deref() == Some(hash), "secret key not updated");
    Ok(updated)
}

/// Go `PrepareConfigFileForUpload` (f9437700): applies the rewrites of a startup load
/// before the file seeds a remote store, so a plaintext management secret never leaves
/// the machine. The effective plaintext secret is hashed and the legacy fields a v8
/// field overrides are dropped. Fails, leaving the file untouched, when the file does
/// not decode, the secret cannot be hashed, or the effective or a legacy secret value
/// would still be a scalar value elsewhere in it (a YAML anchor or a copy). A failure
/// of the write itself can leave a partial file, as in Go.
///
/// Like Go, this only decodes the file: the validators of a startup load, and its
/// credential weight preflight, do not run, so their messages, which quote setting
/// values, cannot carry a secret into the log.
pub fn prepare_for_upload(path: &Path) -> anyhow::Result<()> {
    let text = String::from_utf8(std::fs::read(path)?).context("failed to parse config file")?;
    let prepared = prepared_for_upload(&text)?;
    if prepared != text {
        ConfigDocument::write(path, &prepared).context("failed to write prepared config file")?;
    }
    Ok(())
}

fn prepared_for_upload(text: &str) -> anyhow::Result<String> {
    decode(text, Decode::Upload).context("failed to parse config file")?;
    // yaml.v3 and libyaml end a line at NEL, LS and PS too; yaml-edit, which places
    // the edits and reads the secret's tag, does not, so a comment would hide what
    // follows it. Refuse rather than misread the file.
    anyhow::ensure!(
        !text.contains(['\u{85}', '\u{2028}', '\u{2029}']),
        "the config file contains a Unicode line separator yaml-edit cannot read"
    );
    let mut tree = scalar_texts(text).context("failed to parse config file")?;
    expand_merges(&mut tree).context("failed to parse config file")?;
    let mut secret = effective_secret(&tree).into_bytes();
    if !secret.is_empty() && binary_secret(text, &tree)? {
        // yaml.v3 decodes a `!!binary` scalar into a string field, any bytes.
        secret = binary::go_base64(&secret)
            .context("failed to parse config file: yaml: !!binary value contains invalid base64 data")?;
    }
    let mut prepared = text.to_owned();
    if !secret.is_empty() && !looks_like_bcrypt(&secret) {
        // bcrypt 0.19's non-truncating hash also refuses exactly 72 bytes; Go does not.
        anyhow::ensure!(
            secret.len() <= 72,
            "failed to hash remote management key: bcrypt: password length exceeds 72 bytes"
        );
        let hash = bcrypt::hash(&secret, 10).context("failed to hash remote management key")?;
        prepared = with_secret_hash(text, &hash).context("failed to update remote management key")?;
    }
    if let Some(cleaned) = ConfigDocument::without_conflicts(&prepared)? {
        prepared = cleaned;
    }
    // Go `plaintextManagementSecrets`: the effective secret and the values of both
    // secret keys, since an overridden legacy key still holds its own.
    let mut plaintexts: Vec<String> = String::from_utf8(secret).into_iter().collect();
    for path in ["remote-management.secret-key", "management.secret-key"] {
        if let Some(Value::String(value)) = tree.as_mapping().and_then(|m| lookup(m, path)) {
            plaintexts.push(value.clone());
        }
    }
    plaintexts.retain(|p| !p.is_empty() && !is_bcrypt(p));
    if !plaintexts.is_empty() {
        let doc = scalar_texts(&prepared).context("failed to parse prepared config")?;
        if plaintexts.iter().any(|p| scalar_exists(&doc, p)) {
            bail!(
                "plaintext remote management key is still present elsewhere in the config file, for example through a YAML anchor or as another setting's value"
            );
        }
    }
    Ok(prepared)
}

/// The management secret as Go's `Config` decodes it from a [`scalar_texts`] tree
/// with merges expanded: `management.secret-key` when present (presence wins, even
/// when null), else `remote-management.secret-key`.
fn effective_secret(tree: &Value) -> String {
    let root = tree.as_mapping();
    let at = |path| root.and_then(|m| lookup(m, path));
    match at("management.secret-key").or_else(|| at("remote-management.secret-key")) {
        Some(Value::String(s)) => s.clone(),
        _ => String::new(),
    }
}

/// Whether the effective `secret-key` of a [`scalar_texts`] tree carries yaml.v3's
/// binary tag, resolved as its scanner does: `!!` expands to `tag:yaml.org,2002:`
/// and `%XX` escapes are decoded, so `!!bin%61ry` and `!<tag:yaml.org,2002:binary>`
/// are binary too, as are the tags that resolve to the short spelling `!!binary`
/// (`!<!!binary>`, `!%21binary`), which yaml.v3 also decodes. Fails closed where that
/// resolution is not followed: a `%TAG` directive beside a tagged secret, a named
/// handle, a malformed escape, or a file the syntax tree cannot read. A secret
/// reached through an alias or merge is not resolved: it is refused when any tag in
/// the file could be binary, since the anchor holding the base64 may be dropped by the
/// layout cleanup.
fn binary_secret(text: &str, tree: &Value) -> anyhow::Result<bool> {
    let v8 = tree
        .as_mapping()
        .and_then(|m| lookup(m, "management.secret-key"))
        .is_some();
    let parent = if v8 { "management" } else { "remote-management" };
    let unresolved = || anyhow::anyhow!("the management key's YAML tag cannot be resolved for upload");
    let file: yaml_edit::YamlFile = text.parse().map_err(|_| unresolved())?;
    let tokens = yaml_edit::lex(text);
    let directives = tokens
        .iter()
        .any(|(kind, token)| *kind == yaml_edit::SyntaxKind::DIRECTIVE && token.starts_with("%TAG"));
    let binary = |raw: &str| -> anyhow::Result<bool> {
        anyhow::ensure!(!directives, unresolved());
        let tag = if let Some(uri) = raw.strip_prefix("!<").and_then(|t| t.strip_suffix('>')) {
            uri.to_owned()
        } else if let Some(suffix) = raw.strip_prefix("!!") {
            format!("tag:yaml.org,2002:{suffix}")
        } else if raw[1..].contains('!') {
            anyhow::bail!(unresolved());
        } else {
            raw.to_owned()
        };
        let mut bytes = Vec::with_capacity(tag.len());
        let mut rest = tag.as_bytes();
        while let Some((&b, tail)) = rest.split_first() {
            if b == b'%' {
                let hex = tail.get(..2).and_then(|h| std::str::from_utf8(h).ok());
                bytes.push(
                    hex.and_then(|h| u8::from_str_radix(h, 16).ok())
                        .ok_or_else(unresolved)?,
                );
                rest = &tail[2..];
            } else {
                bytes.push(b);
                rest = tail;
            }
        }
        Ok(bytes == b"tag:yaml.org,2002:binary" || bytes == b"!!binary")
    };
    match file.document().and_then(|d| d.get_mapping(parent)?.get("secret-key")) {
        Some(yaml_edit::YamlNode::TaggedNode(node)) => binary(&node.tag().ok_or_else(unresolved)?),
        Some(yaml_edit::YamlNode::Scalar(_)) => Ok(false),
        // Through an alias, a merge or an aliased section.
        _ => {
            for (kind, token) in &tokens {
                if *kind == yaml_edit::SyntaxKind::TAG && binary(token).unwrap_or(true) {
                    anyhow::bail!(unresolved());
                }
            }
            Ok(false)
        }
    }
}

/// `text` as a tree whose scalars are their decoded text, as yaml.v3's `Node.Value`
/// holds it (`0x1F` stays `0x1F`, `'31'` is `31`, `!!binary c2VjcmV0` is `c2VjcmV0`),
/// and whose nulls stay null. Custom tags are dropped. Keys are kept as parsed;
/// aliases are expanded, merges are not.
fn scalar_texts(text: &str) -> anyhow::Result<Value> {
    use serde::de::{DeserializeSeed, Deserializer, IgnoredAny, MapAccess, SeqAccess, Visitor};
    struct Shaped<'a>(&'a Value);
    struct Entries<'a>(&'a Mapping);
    struct Items<'a>(&'a [Value]);
    impl<'de> DeserializeSeed<'de> for Shaped<'_> {
        type Value = Value;
        fn deserialize<D: Deserializer<'de>>(self, d: D) -> Result<Value, D::Error> {
            match self.0 {
                Value::Mapping(map) => d.deserialize_map(Entries(map)),
                Value::Sequence(items) => d.deserialize_seq(Items(items)),
                Value::Null => IgnoredAny::deserialize(d).map(|_| Value::Null),
                // A plain timestamp, which parse_yaml tags; the text holds no tag.
                Value::Tagged(tagged) if tagged.tag == timestamp::TAG => String::deserialize(d).map(Value::String),
                // A custom tag reaches serde as an enum variant; Go reads the node.
                Value::Tagged(tagged) => d.deserialize_any(Untagged(&tagged.value)),
                _ => String::deserialize(d).map(Value::String),
            }
        }
    }
    struct Untagged<'a>(&'a Value);
    impl<'de> Visitor<'de> for Untagged<'_> {
        type Value = Value;
        fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            f.write_str("a tagged node")
        }
        fn visit_enum<A: serde::de::EnumAccess<'de>>(self, access: A) -> Result<Value, A::Error> {
            use serde::de::VariantAccess as _;
            let (IgnoredAny, variant) = access.variant()?;
            match self.0 {
                Value::Mapping(_) | Value::Sequence(_) => variant.newtype_variant_seed(Shaped(self.0)),
                // Text even when spelled `null` or `~`: only a `!!null` node is null.
                _ => variant.newtype_variant::<String>().map(Value::String),
            }
        }
    }
    impl<'de> Visitor<'de> for Entries<'_> {
        type Value = Value;
        fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            f.write_str("a mapping")
        }
        fn visit_map<A: MapAccess<'de>>(self, mut access: A) -> Result<Value, A::Error> {
            let mut out = Mapping::new();
            for (key, value) in self.0 {
                access.next_key::<IgnoredAny>()?;
                out.insert(key.clone(), access.next_value_seed(Shaped(value))?);
            }
            Ok(Value::Mapping(out))
        }
    }
    impl<'de> Visitor<'de> for Items<'_> {
        type Value = Value;
        fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            f.write_str("a sequence")
        }
        fn visit_seq<A: SeqAccess<'de>>(self, mut access: A) -> Result<Value, A::Error> {
            let mut out = Vec::with_capacity(self.0.len());
            for item in self.0 {
                out.push(access.next_element_seed(Shaped(item))?.unwrap_or(Value::Null));
            }
            Ok(Value::Sequence(out))
        }
    }
    use serde::Deserialize as _;
    // The shape and the text must hold the same nodes; parse_yaml skips a BOM.
    let text = text.strip_prefix('\u{feff}').unwrap_or(text);
    let shape: Value = parse_yaml(text)?;
    Ok(Shaped(&shape).deserialize(serde_yaml_ng::Deserializer::from_str(text))?)
}

/// Go `yamlScalarExists`: a non-null scalar whose text is `value` anywhere below `node`
/// (a [`scalar_texts`] tree). Mapping keys only name settings and are skipped.
fn scalar_exists(node: &Value, value: &str) -> bool {
    match node {
        Value::Mapping(map) => map.values().any(|v| scalar_exists(v, value)),
        Value::Sequence(items) => items.iter().any(|v| scalar_exists(v, value)),
        Value::String(text) => text == value,
        _ => false,
    }
}

/// Which Go entry point [`decode`] follows.
#[derive(Clone, Copy, PartialEq)]
enum Decode {
    /// `LoadConfig`: the credential preflight (`validateCredentialWeightYAML`), then the
    /// typed decode.
    Load,
    /// `ParseConfigBytes`: as `Load`, with typed-decode errors wrapped as
    /// `parse config payload: ...` (Go wraps its `yaml.Unmarshal`).
    Payload,
    /// `prepareConfigForUpload`: the typed decode only, so of the credential checks only
    /// the v8 key groups, which `flattenV8` makes while decoding.
    Upload,
}

/// The decoding part of [`Config::parse`]: the YAML, its layout and the setting types,
/// before the validators. Its errors name settings, not their values. The layout checks
/// come first, unwrapped, as in Go.
fn decode(text: &str, mode: Decode) -> anyhow::Result<(Mapping, ConfigDocument)> {
    let mut parsed = config_value(text)?;
    // Before any migration, as Go expands aliases first.
    expand_merges(&mut parsed)?;
    let root = match parsed {
        Value::Null if text.trim().is_empty() => Mapping::new(),
        Value::Mapping(m) => m,
        _ => bail!("config must be a mapping"),
    };
    validate_shape(&root)?;
    let credentials = if mode == Decode::Upload {
        v8_group_error(&root)
    } else {
        credential_error(&root)
    };
    if let Some(e) = credentials {
        bail!(e);
    }
    let mut document = ConfigDocument::from_mapping(root.clone())?;
    document.coerce_typed_scalars();
    schema::validate(document.value(), false)
        .and_then(|()| validate::decoded(document.value()))
        .map_err(|e| {
            if mode == Decode::Payload {
                anyhow::anyhow!("parse config payload: {e}")
            } else {
                e
            }
        })?;
    Ok((root, document))
}

impl Config {
    pub fn load(path: &Path) -> anyhow::Result<Self> {
        Self::load_text(path, &std::fs::read_to_string(path)?)
    }

    /// [`Config::load`] of text already read from `path`, so a caller knows exactly which
    /// bytes it parsed.
    pub fn load_text(path: &Path, text: &str) -> anyhow::Result<Self> {
        let mut config = Self::parse(text)?;
        if !config.management.secret_key.is_empty() && !is_bcrypt(&config.management.secret_key) {
            let hash = bcrypt::hash(&config.management.secret_key, 10)?;
            // Go hashes in memory and persists best-effort (a read-only mount starts).
            let _ = persist_secret_hash(path, text, &hash);
            config.management.secret_key = hash.clone();
            if let Some(management) = config.document.get_mut("management").and_then(Value::as_mapping_mut) {
                management.insert(Value::from("secret-key"), Value::from(hash));
            }
        }
        Ok(config)
    }

    /// Go `ParseConfigBytes`, as the v8 config writer reports it: [`Config::parse`] with
    /// typed-decode errors wrapped as `parse config payload: ...` (see [`decode`]).
    pub fn parse_payload(text: &str) -> anyhow::Result<Self> {
        Self::parse_as(text, Decode::Payload)
    }

    pub fn parse(text: &str) -> anyhow::Result<Self> {
        Self::parse_as(text, Decode::Load)
    }

    fn parse_as(text: &str, mode: Decode) -> anyhow::Result<Self> {
        let (root, document) = decode(text, mode)?;
        let canonical = document.value().as_mapping().expect("document is a mapping");
        let routing = decode_section::<RoutingConfig>(canonical, "routing")?;
        let mut routing = routing;
        routing.retry.max_retry_credentials = routing.retry.max_retry_credentials.max(0);
        let management = decode_section::<ManagementConfig>(canonical, "management")?;
        let pick = |v8: &str, legacy: &str| lookup(&root, v8).or_else(|| lookup(&root, legacy));
        let host = string_or_empty(pick("server.host", "host"), "server.host")?;
        let port = match pick("server.port", "port") {
            None | Some(Value::Null) => 0,
            // yaml.v3 truncates a float into Go's int port.
            Some(v) => go_int(v)
                .and_then(|p| u16::try_from(p).ok())
                .context("server.port must be an integer port number")?,
        };
        // A top-level `api-keys` mapping is the v8 upstream key map, not client keys.
        let legacy_keys = lookup(&root, "api-keys").filter(|v| !v.is_mapping());
        let api_keys = match lookup(&root, "access.api-keys").or(legacy_keys) {
            None | Some(Value::Null) => Vec::new(),
            Some(Value::Sequence(seq)) => seq
                .iter()
                .map(|k| {
                    k.as_str()
                        .map(str::to_owned)
                        .context("access.api-keys must be a list of strings")
                })
                .collect::<anyhow::Result<_>>()?,
            Some(_) => bail!("access.api-keys must be a list of strings"),
        };
        let auth_dir = string_or_empty(pick("oauth.auth-dir", "auth-dir"), "oauth.auth-dir")?;
        let trusted_proxies: Vec<String> = match lookup(canonical, "server.trusted-proxies") {
            Some(Value::Sequence(seq)) => seq.iter().map(go_string).collect(),
            _ => Vec::new(),
        };
        trusted::validate(&trusted_proxies)?;
        validate::go_custom(document.value())?;
        let oauth_only = schema::oauth_only_paths(&Value::Mapping(root.clone()));
        let plugin_configs = plugin_configs(text, &root);
        Ok(Config {
            host,
            port,
            api_keys: normalize_keys(api_keys),
            trusted_proxies,
            auth_dir: resolve_auth_dir(&auth_dir),
            routing,
            management,
            document: document.into_value(),
            oauth_only,
            plugin_configs,
            derived: Derived::default(),
        })
    }

    /// `server.max-request-body-bytes` (legacy root `max-request-body-bytes`), Go
    /// `SDKConfig.MaxRequestBodyBytes`: the request body limit in bytes. `None` when
    /// omitted or not positive, which disables it (Go's default 0).
    pub fn max_request_body_bytes(&self) -> Option<u64> {
        let value = self.document.get("server")?.get("max-request-body-bytes")?;
        u64::try_from(go_int(value)?).ok().filter(|&n| n > 0)
    }

    /// Go `Config.ForAPIKey`: the view an API-key credential sees, with the v8
    /// OAuth-only provider settings set to their typed zero. Borrowed when there are
    /// none.
    pub fn for_api_key(&self) -> std::borrow::Cow<'_, Config> {
        if self.oauth_only.is_empty() {
            return std::borrow::Cow::Borrowed(self);
        }
        let mut view = self.clone();
        for path in &self.oauth_only {
            schema::zero_at(&mut view.document, path);
        }
        view.oauth_only.clear();
        std::borrow::Cow::Owned(view)
    }
}

/// Go `looksLikeBcrypt`.
pub fn is_bcrypt(key: &str) -> bool {
    looks_like_bcrypt(key.as_bytes())
}

fn looks_like_bcrypt(key: &[u8]) -> bool {
    key.len() > 4 && [b"$2a$", b"$2b$", b"$2y$"].iter().any(|p| key.starts_with(*p))
}

fn decode_section<T: serde::de::DeserializeOwned + Default>(root: &Mapping, name: &str) -> anyhow::Result<T> {
    match lookup(root, name) {
        None | Some(Value::Null) => Ok(T::default()),
        Some(value) => Ok(serde_yaml_ng::from_value(null_scalars_to_zero(value.clone()))?),
    }
}

// Go YAML decoding null into a non-pointer field leaves its zero/default value.
// Omit nulls when decoding the typed runtime view; the document keeps them intact.
fn null_scalars_to_zero(mut value: Value) -> Value {
    if let Value::Mapping(ref mut map) = value {
        map.retain(|_, v| !v.is_null());
        for (_, v) in map {
            *v = null_scalars_to_zero(v.clone());
        }
    }
    value
}

fn validate_shape(root: &Mapping) -> anyhow::Result<()> {
    if let Some(e) = document::shape_error(root) {
        bail!(e);
    }
    if let Some(version) = lookup(root, "config-version")
        && version.as_u64() != Some(8)
    {
        bail!("unsupported config-version (expected 8)");
    }
    Ok(())
}

/// Value at a dotted path, or `None` when any segment is absent or a parent is not a
/// mapping. Present-but-null returns `Some(Value::Null)`.
fn lookup<'a>(root: &'a Mapping, path: &str) -> Option<&'a Value> {
    let mut parts = path.split('.');
    let mut cur = root.get(parts.next()?)?;
    for part in parts {
        cur = cur.as_mapping()?.get(part)?;
    }
    Some(cur)
}

/// A YAML scalar decoded into a Go `string` field (yaml.v3 accepts numbers/bools).
pub fn go_string(value: &Value) -> String {
    match value {
        Value::String(s) => s.clone(),
        Value::Number(n) => n.to_string(),
        Value::Bool(b) => b.to_string(),
        _ => String::new(),
    }
}

fn string_or_empty(value: Option<&Value>, name: &str) -> anyhow::Result<String> {
    match value {
        None | Some(Value::Null) => Ok(String::new()),
        Some(Value::String(s)) => Ok(s.clone()),
        // yaml.v3 decodes any scalar into a Go string field as its text.
        Some(v @ (Value::Number(_) | Value::Bool(_))) => Ok(go_string(v)),
        Some(_) => bail!("{name} must be a string"),
    }
}

fn normalize_keys(keys: Vec<String>) -> Vec<String> {
    let mut out: Vec<String> = Vec::with_capacity(keys.len());
    for key in keys {
        let key = key.trim();
        if !key.is_empty() && !out.iter().any(|k| k == key) {
            out.push(key.to_owned());
        }
    }
    out
}

/// Go's util.ResolveAuthDir: empty means the default, and a leading `~` is the home
/// directory with any following slashes dropped (so `~other/x` is `$HOME/other/x`).
fn resolve_auth_dir(dir: &str) -> PathBuf {
    let dir = if dir.is_empty() { DEFAULT_AUTH_DIR } else { dir };
    let (Some(rest), Some(home)) = (dir.strip_prefix('~'), std::env::var_os("HOME")) else {
        return PathBuf::from(dir);
    };
    let rest = rest.trim_start_matches(['/', '\\']).replace('\\', "/");
    if rest.is_empty() {
        PathBuf::from(home)
    } else {
        PathBuf::from(home).join(rest)
    }
}

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

    /// Go `TestPrepareConfigFileForUploadReportsSecretItCannotHash` "read-only file";
    /// tests/prepare_upload_go.rs replays the other Go cases.
    #[cfg(unix)]
    #[test]
    fn prepare_for_upload_refuses_a_file_it_cannot_write() {
        use std::os::unix::fs::PermissionsExt as _;
        let dir = std::env::temp_dir().join(format!("cpa-prepare-ro-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.yaml");
        let content = "remote-management:\n  secret-key: upload-plaintext-secret\n";
        std::fs::write(&path, content).unwrap();
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o400)).unwrap();
        // Root can write anyway; Go skips there too.
        if std::fs::OpenOptions::new().write(true).open(&path).is_err() {
            assert!(prepare_for_upload(&path).is_err());
            assert_eq!(std::fs::read_to_string(&path).unwrap(), content);
        }
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
        std::fs::remove_dir_all(&dir).unwrap();
    }

    fn home() -> PathBuf {
        PathBuf::from(std::env::var("HOME").unwrap())
    }

    #[test]
    fn v8_wins_by_presence_even_when_null_or_empty() {
        let cfg = Config::parse(
            "port: 9000\napi-keys: [legacy]\nauth-dir: /legacy\nhost: legacyhost\n\
             server: {port: 9100, host: null}\naccess: {api-keys: []}\noauth: {auth-dir: /v8}\n\
             remote-management: {allow-remote: true}\nmanagement: {allow-remote: false, disable-auto-update-panel: true}\n",
        )
        .unwrap();
        assert_eq!(cfg.port, 9100);
        assert_eq!(cfg.host, "", "present null beats legacy");
        assert!(cfg.api_keys.is_empty(), "present empty list beats legacy");
        assert_eq!(cfg.auth_dir, PathBuf::from("/v8"));
        assert!(!cfg.management.allow_remote, "present false beats legacy");
        assert!(cfg.management.disable_auto_update_panel);
        let cfg = Config::parse("api-keys: [legacy]\naccess: {api-keys: null}\n").unwrap();
        assert!(cfg.api_keys.is_empty(), "present null list beats legacy");
    }

    /// `worker-threads` is cliproxy-rs only: a whole-file upload through the Management
    /// API keeps it (Go's v8 upload refuses unknown sections), and its type is checked.
    #[test]
    fn worker_threads_is_a_known_int() {
        let doc = |text: &str| serde_yaml_ng::from_str::<serde_yaml_ng::Value>(text).unwrap();
        validate_config_fields(&doc("config-version: 8\nworker-threads: 3\n"), true).unwrap();
        assert!(validate_config_fields(&doc("worker-threads: many\n"), true).is_err());
        assert!(validate_config_fields(&doc("worker-thread: 3\n"), true).is_err());
    }

    #[test]
    fn legacy_spellings_still_work() {
        let cfg = Config::parse("host: 127.0.0.1\nport: 9000\napi-keys: [' a ', a, '', b]\nauth-dir: /x\n").unwrap();
        assert_eq!((cfg.host.as_str(), cfg.port), ("127.0.0.1", 9000));
        assert_eq!(cfg.api_keys, ["a", "b"]);
        assert_eq!(cfg.auth_dir, PathBuf::from("/x"));
    }

    #[test]
    fn null_or_scalar_parents_are_rejected() {
        for (yaml, want) in [
            ("access: null\n", "access must be a mapping"),
            ("access: [a]\n", "access must be a mapping"),
            ("server: 5\n", "server must be a mapping"),
            ("oauth:\n  providers: null\n", "oauth.providers must be a mapping"),
            ("config-version: 7\n", "unsupported config-version (expected 8)"),
            ("- a\n", "config must be a mapping"),
        ] {
            assert_eq!(Config::parse(yaml).unwrap_err().to_string(), want, "{yaml:?}");
        }
        assert!(
            Config::parse("routing: null\nconfig-version: 8\n").is_ok(),
            "routing: null means defaults"
        );
    }

    #[test]
    fn image_generation_mode_reads_go_spellings() {
        let mode = |yaml: &str| {
            Config::parse(&format!("multimedia:\n  disable-image-generation: {yaml}\n"))
                .map(|c| c.document["multimedia"]["disable-image-generation"].clone())
                .map_err(|e| e.to_string())
        };
        assert_eq!(mode("' Off '"), Ok(Value::Bool(false)));
        assert_eq!(mode("~"), Ok(Value::Bool(false)));
        assert_eq!(mode("YES"), Ok(Value::Bool(true)));
        assert_eq!(mode("' Chat'"), Ok(Value::from("chat")));
        assert_eq!(
            mode("\"\\u00dc\\u0001\""),
            Err(
                "invalid disable-image-generation value \"\u{fc}\\x01\" (allowed: true, false, chat, passthrough)"
                    .into()
            )
        );
    }

    #[test]
    fn v8_upstream_key_map_is_not_client_keys() {
        let cfg = Config::parse("api-keys:\n  claude:\n    - keys: [{api-key: fake-key}]\n").unwrap();
        assert!(cfg.api_keys.is_empty());
        for yaml in [
            "api-keys: {claude: [{api-key: fake-key}]}",
            "api-keys: {claude: null}",
            "api-keys: {claude: [{keys: null}]}",
            "api-keys: {claude: [{weight: 2, keys: []}]}",
            "api-keys: {claude: [{keys: [{base-url: https://example.invalid}]}]}",
            "api-keys: {claude: [{keys: [{weight: 1000001}]}]}",
        ] {
            assert!(Config::parse(yaml).is_err(), "{yaml}");
        }
        assert!(Config::parse("api-keys: {claude: [{keys: [{weight: 0}]}]}").is_ok());
    }

    #[test]
    fn scheduler_legacy_keys_and_v8_presence_share_one_typed_view() {
        let cfg = Config::parse(
            "request-retry: 7\nmax-retry-credentials: -2\nmax-retry-interval: 41\n\
             disable-cooling: true\nsave-cooldown-status: true\n\
             transient-error-cooldown-seconds: -3\nforce-model-prefix: true\n\
             routing:\n  strategy: fill-first\n  session-affinity: true\n\
             \x20 session-affinity-ttl: 37m\n  session-affinity-subagents: false\n\
             \x20 retry: {request-retry: 0}\n  cooldown: {disable-cooling: false}\n",
        )
        .unwrap();
        assert_eq!(cfg.routing.strategy, "fill-first");
        assert!(cfg.routing.force_model_prefix && cfg.routing.session_affinity);
        assert_eq!(cfg.routing.session_affinity_ttl, "37m");
        assert_eq!(cfg.routing.session_affinity_subagents, Some(false));
        assert_eq!(cfg.routing.retry.request_retry, 0);
        assert_eq!(cfg.routing.retry.max_retry_credentials, 0);
        assert_eq!(cfg.routing.retry.max_retry_interval, 41);
        assert!(!cfg.routing.cooldown.disable_cooling);
        assert!(cfg.routing.cooldown.save_cooldown_status);
        assert_eq!(cfg.routing.cooldown.transient_error_cooldown_seconds, -3);
        // cliproxy-rs's own cooldown key: an int or a duration, kept as written, and
        // part of the schema so management writes do not archive it.
        for (yaml, expect) in [("0", "0"), ("90m", "90m")] {
            let text = format!("routing:\n  cooldown:\n    max-trusted-cooldown: {yaml}\n");
            let cfg = Config::parse(&text).unwrap();
            assert_eq!(cfg.routing.cooldown.max_trusted_cooldown, expect);
            assert!(ConfigDocument::parse(&text).unwrap().archive_unknown().is_empty());
        }
        assert!(Config::parse("routing: {cooldown: {max-trusted-cooldown: [1]}}").is_err());
        let empty = Config::default();
        assert_eq!(empty.routing, RoutingConfig::default());
        assert_eq!(empty.routing.session_affinity_subagents, None);
        let null = Config::parse("request-retry: 7\nrouting: {retry: {request-retry: null}}\n").unwrap();
        assert_eq!(null.routing.retry.request_retry, 0);
    }

    /// v8.0.35 `buildV8Paths` moves the legacy `claude.session-date-pin-days` to
    /// `upstream.claude`.
    #[test]
    fn legacy_session_date_pin_days_migrates() {
        let doc = ConfigDocument::parse("claude: {tool-search: true, session-date-pin-days: 3}\n").unwrap();
        assert!(doc.value().get("claude").is_none(), "{:?}", doc.value());
        assert_eq!(doc.value()["upstream"]["claude"]["session-date-pin-days"], 3);
    }

    /// Go `shared_upstream_test.go` (52d5507d): the legacy, canonical `upstream` and
    /// historical `oauth.providers` layouts load the same shared settings for OAuth and
    /// API-key views alike, migrate without their aliases, and keep the Codex header
    /// defaults OAuth-only.
    #[test]
    fn shared_upstream_layouts_agree_and_migrate() {
        let keys = "api-keys: {codex: [{base-url: https://example.invalid, keys: [{api-key: test-key, disable-codex-cloaking: false}]}]}\n";
        let codex = "{disable-codex-cloaking: true, stream-bootstrap-buffering: true, stream-bootstrap-timeout: 10s, orphan-delegation-compatibility: true, model-level-cooling: true, response-steering: true";
        let headers = "{user-agent: client-agent, package-version: 1.2.3, runtime-version: v22.1.0, os: Linux, arch: arm64, timeout: '123', timezone: Asia/Shanghai, stabilize-device-profile: true}";
        let oauth = "oauth: {auth-dir: client-auth, auth-auto-refresh-workers: 3, providers: {codex: {header-defaults: {user-agent: oauth-agent, beta-features: oauth-beta}}}}\n";
        let legacy = format!(
            "auth-dir: client-auth\nauth-auto-refresh-workers: 3\ncodex: {codex}}}\nclaude: {{model-level-cooling: true}}\nclaude-code: {{disable-cloaking-model-list: true}}\ndisable-claude-cloak-mode: true\nclaude-header-defaults: {headers}\nxai: {{inject-x-search: true}}\n{oauth}{keys}"
        );
        let canonical = format!(
            "upstream:\n  codex: {codex}}}\n  claude:\n    model-level-cooling: true\n    disable-cloaking-model-list: true\n    disable-claude-cloak-mode: true\n    header-defaults: {headers}\n  xai: {{inject-x-search: true}}\n{oauth}{keys}"
        );
        let historical = format!(
            "oauth:\n  auth-dir: client-auth\n  auth-auto-refresh-workers: 3\n  providers:\n    codex: {codex}, header-defaults: {{user-agent: oauth-agent, beta-features: oauth-beta}}}}\n    claude:\n      model-level-cooling: true\n      claude-code: {{disable-cloaking-model-list: true}}\n      disable-claude-cloak-mode: true\n      header-defaults: {headers}\n    xai: {{inject-x-search: true}}\n{keys}"
        );
        let expected = Config::parse(&canonical).unwrap().document;
        assert_eq!(
            expected["upstream"]["claude"]["header-defaults"]["timezone"],
            "Asia/Shanghai"
        );
        for raw in [&legacy, &canonical, &historical] {
            let doc = ConfigDocument::parse(raw).unwrap();
            schema::validate(doc.value(), true).unwrap();
            for alias in ["codex", "claude", "claude-code", "xai", "claude-header-defaults"] {
                assert!(doc.value().get(alias).is_none(), "{alias} survived: {raw}");
            }
            let providers = &doc.value()["oauth"]["providers"];
            assert!(
                providers.get("claude").is_none() && providers.get("xai").is_none(),
                "{raw}"
            );
            let codex = providers["codex"].as_mapping().unwrap();
            assert_eq!(
                codex.keys().collect::<Vec<_>>(),
                [&Value::from("header-defaults")],
                "{raw}"
            );
            for text in [raw.to_string(), doc.yaml().unwrap()] {
                let cfg = Config::parse(&text).unwrap();
                for view in [&cfg, &*cfg.for_api_key()] {
                    assert_eq!(view.document["upstream"], expected["upstream"], "{text}");
                    assert_eq!(view.document["oauth"]["auth-auto-refresh-workers"], 3);
                    let key = &view.document["api-keys"]["codex"][0]["keys"][0];
                    assert_eq!(key["disable-codex-cloaking"], Value::Bool(false));
                }
                let user_agent =
                    |c: &Config| c.document["oauth"]["providers"]["codex"]["header-defaults"]["user-agent"].clone();
                assert_eq!(user_agent(&cfg), "oauth-agent");
                assert_eq!(user_agent(&cfg.for_api_key()), "");
            }
        }
    }

    /// Go `TestSharedUpstreamPresenceWinsOverHistoricalAliases` and
    /// `TestSharedUpstreamEmptyHistoricalContainers`.
    #[test]
    fn shared_upstream_presence_wins_and_empty_containers_move() {
        for value in ["false", "null"] {
            let raw = format!(
                "codex: {{response-steering: true}}\noauth: {{providers: {{codex: {{response-steering: true}}, claude: {{header-defaults: {{user-agent: historical-agent, stabilize-device-profile: true}}}}}}}}\nupstream: {{codex: {{response-steering: {value}}}, claude: {{header-defaults: {{user-agent: '', stabilize-device-profile: {value}}}}}}}\n"
            );
            let cfg = Config::parse(&raw).unwrap();
            let upstream = &cfg.document["upstream"];
            assert_ne!(upstream["codex"]["response-steering"], Value::Bool(true), "{raw}");
            assert_eq!(upstream["claude"]["header-defaults"]["user-agent"], "", "{raw}");
            assert_ne!(
                upstream["claude"]["header-defaults"]["stabilize-device-profile"],
                Value::Bool(true)
            );
            schema::validate(ConfigDocument::parse(&raw).unwrap().value(), true).unwrap();
        }
        for (historical, current) in [
            (
                "oauth.providers.claude.header-defaults",
                "upstream.claude.header-defaults",
            ),
            ("oauth.providers.claude.claude-code", "upstream.claude"),
            ("oauth.providers.claude", "upstream.claude"),
            ("oauth.providers.xai", "upstream.xai"),
        ] {
            for value in ["{}", "null"] {
                let parts: Vec<&str> = historical.split('.').collect();
                let raw = parts
                    .iter()
                    .rev()
                    .fold(value.to_owned(), |inner, key| format!("{{{key}: {inner}}}"));
                let doc = ConfigDocument::parse(&raw).unwrap();
                schema::validate(doc.value(), true).unwrap();
                assert!(lookup(doc.value().as_mapping().unwrap(), historical).is_none(), "{raw}");
                assert!(lookup(doc.value().as_mapping().unwrap(), current).is_some(), "{raw}");
            }
        }
        // The legacy Claude structs move by their declared fields only: Go has no
        // `claude.disable-cloaking-model-list` or `claude-code.model-level-cooling`.
        let cfg = Config::parse(
            "claude: {disable-cloaking-model-list: true, model-level-cooling: true}\nclaude-code: {disable-cloaking-model-list: false, model-level-cooling: true}\n",
        )
        .unwrap();
        let claude = &cfg.document["upstream"]["claude"];
        assert_eq!(claude["disable-cloaking-model-list"], Value::Bool(false));
        assert_eq!(claude["model-level-cooling"], Value::Bool(true));
        assert_eq!(cfg.document["claude"]["disable-cloaking-model-list"], Value::Bool(true));
        assert_eq!(cfg.document["claude-code"]["model-level-cooling"], Value::Bool(true));
        let cfg = Config::parse("claude-code: {model-level-cooling: true}\n").unwrap();
        assert!(cfg.document.get("upstream").is_none(), "{:?}", cfg.document);
        for legacy in ["claude: null\n", "claude-code: {}\n"] {
            let doc = ConfigDocument::parse(legacy).unwrap();
            assert_eq!(
                doc.value()["upstream"]["claude"],
                Value::Mapping(Mapping::new()),
                "{legacy}"
            );
            assert!(doc.value().get("claude").is_none() && doc.value().get("claude-code").is_none());
        }
        let err = Config::parse("oauth: {providers: {xai: true}}\n").unwrap_err();
        assert_eq!(err.to_string(), "oauth.providers.xai must be a mapping");
    }

    /// Go `TestIsV8ConfigLayout` (3be5fa44).
    #[test]
    fn v8_layout_is_recognised_by_version_sections_and_paths() {
        for (raw, v8) in [
            ("request-retry: 3\ncodex: {response-steering: true}\n", false),
            (
                "routing: {strategy: fill-first}\nplugins: {configs: {example: {enabled: true}}}\nquota-exceeded: {switch-project: true}\nclient: {codex: {enable-apply-patch: true}}\napi-keys: [client-key]\n",
                false,
            ),
            ("codex: {optimize-multi-agent-v2: true}\n", false),
            ("config-version: 8\nrequest-retry: 3\n", true),
            ("oauth: {providers: {codex: {response-steering: true}}}\n", true),
            ("server: {}\n", true),
            ("upstream: {xai: {inject-x-search: false}}\n", true),
            ("api-keys: {}\n", true),
            ("request-retry: 3\nrouting: {retry: {max-retry-credentials: 2}}\n", true),
            ("routing: {retry: {}}\n", true),
            ("providers: {codex: {optimize-multi-agent-v2: true}}\n", true),
            ("client: {codex: {optimize-multi-agent-v2: false}}\n", true),
        ] {
            let value: Value = serde_yaml_ng::from_str(raw).unwrap();
            assert_eq!(is_v8_layout(&value), v8, "{raw}");
        }
    }

    #[test]
    fn defaults_match_go_loader() {
        let cfg = Config::parse("").unwrap();
        assert_eq!((cfg.port, cfg.host.as_str()), (0, ""));
        assert_eq!(cfg.auth_dir, home().join(".cli-proxy-api"));
        assert_eq!(
            Config::parse("auth-dir: ''\n").unwrap().auth_dir,
            home().join(".cli-proxy-api")
        );
        assert_eq!(resolve_auth_dir("~"), home());
        assert_eq!(resolve_auth_dir("~other/x"), home().join("other/x"));
        assert_eq!(resolve_auth_dir("/abs"), PathBuf::from("/abs"));
    }

    /// Plain numbers that are no model name, alias or exclusion cost one step each: 16
    /// times the entries must cost far less than 256 times the time (a search from the
    /// root per number). Both sizes run in this process, so the ratio does not depend on
    /// the machine.
    #[test]
    fn yaml_literals_scale_linearly() {
        let time = |n: usize| {
            let params: Vec<String> = (0..n).map(|i| format!("k{i}: 1.50")).collect();
            let text = format!(
                "x: &a 1\nrequests: {{payload: {{override: [{{models: [{{name: 0x1F}}], params: {{{}}}}}]}}}}\n",
                params.join(", ")
            );
            (0..3)
                .map(|_| {
                    let start = std::time::Instant::now();
                    let doc = config_value(&text).unwrap();
                    let rule = &doc["requests"]["payload"]["override"][0];
                    assert_eq!(rule["models"][0]["name"], Value::from("0x1F"));
                    assert_eq!(rule["params"][format!("k{}", n - 1).as_str()], Value::from(1.5));
                    start.elapsed()
                })
                .min()
                .unwrap()
        };
        let (small, large) = (time(1000), time(16000));
        let ratio = large.as_secs_f64() / small.as_secs_f64().max(1e-9);
        assert!(
            ratio < 64.0,
            "16x the entries took {ratio:.0}x the time ({small:?} to {large:?})"
        );
    }

    /// The aliases of an anchored list of numbers count toward the alias limit only where
    /// they land in a model name, alias or exclusion. (yaml.v3 refuses this many aliases
    /// as excessive aliasing; the limit here is the copies they make.)
    #[test]
    fn unused_number_aliases_do_not_expand_too_far() {
        let numbers: Vec<String> = (0..1024).map(|i| i.to_string()).collect();
        let text = format!(
            "a: &l [{}]\nb: [{}]\noauth-excluded-models: {{c: *l}}\n",
            numbers.join(", "),
            vec!["*l"; 1024].join(", ")
        );
        let doc = config_value(&text).unwrap();
        assert_eq!(doc["b"][1023][1023], Value::from(1023));
        assert_eq!(doc["oauth-excluded-models"]["c"][7], Value::from("7"));
    }

    /// Aliases whose copies no string setting keeps are bounded too: 2,048 aliases of a
    /// 2,049-number anchor outside any string setting visit just over the limit and are
    /// refused, where each would otherwise copy the whole anchor. Go refuses such a file
    /// as excessive aliasing.
    #[test]
    fn dropped_alias_copies_are_bounded() {
        let numbers = vec!["0"; 2049].join(", ");
        let text = format!("x: &x [{numbers}]\nzz-ignored: [{}]\n", vec!["*x"; 2048].join(", "));
        let err = config_value(&text).unwrap_err();
        assert_eq!(err.to_string(), "config YAML aliases expand too far");
    }

    /// Only alias copies count toward the alias limit: a list of more numbers than that,
    /// anchored (so kept for its aliases) or an exclusion list, loads as in Go.
    #[test]
    fn written_numbers_do_not_count_toward_the_alias_limit() {
        let numbers = vec!["0"; (1 << 20) + 1].join(", ");
        let doc = config_value(&format!(
            "x: &l [{numbers}]
oauth-excluded-models: {{c: [{numbers}]}}
"
        ))
        .unwrap();
        assert_eq!(doc["x"][1 << 20], Value::from(0));
        assert_eq!(doc["oauth-excluded-models"]["c"][1 << 20], Value::from("0"));
    }

    /// yaml.v3 (v8.0.35) reads a plain integer beyond int64 and uint64 as a float when it
    /// is decimal and as text otherwise, and a string setting as its text; serde_yaml_ng
    /// refused one that fits 128 bits, failing the load.
    #[test]
    fn integers_beyond_64_bits_read_as_in_go() {
        let token = "123456789012345678901234567890";
        let cfg = Config::parse(&format!("server:\n  github-token: {token}\n")).unwrap();
        assert_eq!(cfg.document["server"]["github-token"].as_str(), Some(token));
        assert_eq!(
            body_value(token, &["server", "github-token"]).unwrap(),
            Value::from(token)
        );
        let any = yaml_value("x: [18446744073709551616, -9223372036854775809, 0x1FFFFFFFFFFFFFFFFF]\n").unwrap();
        let want: Vec<Value> = vec![
            1.8446744073709552e19.into(),
            (-9.223372036854776e18).into(),
            "0x1FFFFFFFFFFFFFFFFF".into(),
        ];
        assert_eq!(any["x"].as_sequence().unwrap(), &want);
        // A plugin gets the text, which its yaml.v3 reads as Go's float.
        let cfg = Config::parse(&format!("plugins: {{configs: {{p: {{n: {token}}}}}}}\n")).unwrap();
        let Value::Tagged(n) = &cfg.plugin_configs["p"]["n"] else {
            panic!("{:?}", cfg.plugin_configs)
        };
        assert_eq!(n.value, Value::from(token));
        // Any number of them, read in one pass; marks after a BOM still line up.
        let many = yaml_value(&format!("x: [{}]\n", vec!["-18446744073709551616"; 100].join(", "))).unwrap();
        assert!(
            many["x"]
                .as_sequence()
                .unwrap()
                .iter()
                .all(|v| v.as_f64() == Some(-1.8446744073709552e19))
        );
        // An anchored one keeps its anchor, on its line or the line above.
        for text in [
            "a: &n 18446744073709551616\nb: *n\n",
            "a: &n\n  18446744073709551616\nb: *n\n",
        ] {
            let anchored = yaml_value(text).unwrap();
            assert_eq!(anchored["b"].as_f64(), Some(1.8446744073709552e19), "{text}");
        }
        // Integers serde_yaml_ng reads are read the same beside one it refuses: past
        // f64's range the text, as in Go, and a decimal with a leading zero.
        let huge = format!("1{}", "0".repeat(400));
        for other in [huge.as_str(), "01000000000000000000000"] {
            let both = yaml_value(&format!("x: [18446744073709551616, {other}]\n")).unwrap();
            assert_eq!(
                both["x"][1],
                yaml_value(&format!("x: {other}\n")).unwrap()["x"],
                "{other}"
            );
        }
        assert_eq!(
            yaml_value(&format!("x: {huge}\n")).unwrap()["x"].as_str(),
            Some(huge.as_str())
        );
        let bom = yaml_value("\u{feff}a: [0x1FFFFFFFFFFFFFFFFF, x]\n").unwrap();
        assert_eq!(bom["a"], yaml_value("['0x1FFFFFFFFFFFFFFFFF', x]").unwrap());
        // Go: cannot unmarshal !!float into int.
        assert!(Config::parse("routing: {retry: {request-retry: 18446744073709551616}}\n").is_err());
    }

    /// yaml.v3 (v3.0.1, Go 1.26.4) drops a plain number's underscores before resolving
    /// it and reads a leading zero as octal (or decimal, failing that); serde_yaml_ng
    /// read each of these as text.
    #[test]
    fn underscore_numbers_read_as_in_go() {
        let go: [(&str, Value); 20] = [
            ("1_000", 1000.into()),
            ("+_1", 1.into()),
            ("-1_000", (-1000).into()),
            ("1__0", 10.into()),
            ("1_", 1.into()),
            ("0_x1F", 31.into()),
            ("-0x1_F", (-31).into()),
            ("007_1", 57.into()),
            ("-0b1_0", (-2).into()),
            ("18_446_744_073_709_551_615", u64::MAX.into()),
            ("1_0.5", 10.5.into()),
            ("1_0e1_0", 1e11.into()),
            ("1._5", 1.5.into()),
            (".5_0", 0.5.into()),
            ("-.5_0", (-0.5).into()),
            ("1_000_000_000_000_000_000_000", 1e21.into()),
            ("_1", "_1".into()),
            (".5_", ".5_".into()),
            ("._5", "._5".into()),
            ("0x1_FFFF_FFFF_FFFF_FFFF_FF", "0x1_FFFF_FFFF_FFFF_FFFF_FF".into()),
        ];
        let leading_zero: [(&str, Value); 10] = [
            ("007", 7.into()),
            ("-007", (-7).into()),
            ("00", 0.into()),
            ("08", 8.0.into()),
            ("09.5", 9.5.into()),
            ("07e1", 70.0.into()),
            ("01000000000000000000000", 9223372036854775808u64.into()),
            ("01777777777777777777777", u64::MAX.into()),
            ("02000000000000000000000", 2e21.into()),
            ("0111111111111111111111111", 1.1111111111111111e23.into()),
        ];
        // Go's last resort reads a sign after `0b` or `0o`.
        let signed: [(&str, Value); 7] = [
            ("0b_-1", (-1).into()),
            ("0o_+17", 15.into()),
            ("0o_-7", (-7).into()),
            ("0b-1", (-1).into()),
            ("0o+17", 15.into()),
            ("+0b-1", "+0b-1".into()),
            (
                "0b+1111111111111111111111111111111111111111111111111111111111111111",
                "0b+1111111111111111111111111111111111111111111111111111111111111111".into(),
            ),
        ];
        // Go's text: beyond 64 bits, or a `+` past int64.
        let zeros = "0".repeat(64);
        let wide = [
            "0o2000000000000000000000".to_owned(),
            "+0o2000000000000000000000".to_owned(),
            format!("-0b1{zeros}"),
            "+0o1000000000000000000000".to_owned(),
            "+0b1_000000000000000000000000000000000000000000000000000000000000000".to_owned(),
        ];
        let wide: Vec<(&str, Value)> = wide.iter().map(|t| (t.as_str(), Value::from(t.as_str()))).collect();
        // Upper-case prefixes, which Go's ParseInt takes, and a `+` past int64, which its
        // ParseUint does not, so a decimal one is a float and any other text.
        let prefixes: [(&str, Value); 16] = [
            ("0X1F", 31.into()),
            ("-0X1F", (-31).into()),
            ("+0X1F", 31.into()),
            ("0O17", 15.into()),
            ("0B10", 2.into()),
            ("-0B10", (-2).into()),
            ("0X", "0X".into()),
            ("0O8", "0O8".into()),
            ("0B2", "0B2".into()),
            ("0X8000000000000000", (1u64 << 63).into()),
            ("0XFFFFFFFFFFFFFFFF", u64::MAX.into()),
            ("0X10000000000000000", "0X10000000000000000".into()),
            ("+9223372036854775807", i64::MAX.into()),
            ("+9223372036854775808", 9223372036854775808f64.into()),
            ("+18446744073709551615", 18446744073709551615f64.into()),
            ("+0x8000000000000000", "+0x8000000000000000".into()),
        ];
        let go = go
            .into_iter()
            .chain(leading_zero)
            .chain(signed)
            .chain(wide)
            .chain(prefixes)
            .collect::<Vec<_>>();
        let list = go.iter().map(|(text, _)| *text).collect::<Vec<_>>().join(", ");
        let any = yaml_value(&format!("x: [{list}]\n")).unwrap();
        for ((text, want), got) in go.iter().zip(any["x"].as_sequence().unwrap()) {
            assert_eq!(got, want, "{text}");
        }
        // Without an underscore in the file too.
        assert_eq!(yaml_value("x: 007\n").unwrap()["x"], Value::from(7));
        assert_eq!(yaml_value("x: 0X1F\n").unwrap()["x"], Value::from(31));
        assert_eq!(
            yaml_value("x: +9223372036854775808\n").unwrap()["x"],
            Value::from(9223372036854775808f64)
        );
        assert_eq!(
            yaml_value("x: 9223372036854775808\n").unwrap()["x"],
            Value::from(1u64 << 63)
        );
        let cfg = Config::parse("server: {github-token: 0X1F}\nrouting: {retry: {request-retry: 0X1F}}\n").unwrap();
        assert_eq!(cfg.document["server"]["github-token"].as_str(), Some("0X1F"));
        assert_eq!(cfg.routing.retry.request_retry, 31);
        assert_eq!(yaml_value("007").unwrap(), Value::from(7));
        // A string setting keeps the text, an int setting gets the number, and a key
        // stays text, as yaml.v3 reads it into a string-keyed map.
        let cfg = Config::parse(
            "server: {github-token: 1_000}\nrouting: {retry: {request-retry: 1_0}}\n\
             oauth-excluded-models: {1_0: [a], 007: [b]}\n",
        )
        .unwrap();
        assert_eq!(cfg.document["server"]["github-token"].as_str(), Some("1_000"));
        assert_eq!(cfg.routing.retry.request_retry, 10);
        assert!(cfg.document["oauth"]["excluded-models"].get("1_0").is_some());
        assert!(cfg.document["oauth"]["excluded-models"].get("007").is_some());
        let key = yaml_value(&format!("0o2000000000000000000000: a\n-0b1{zeros}: b\n")).unwrap();
        assert_eq!(key["0o2000000000000000000000"], Value::from("a"));
        assert_eq!(key[format!("-0b1{zeros}").as_str()], Value::from("b"));
        assert_eq!(
            body_value("1_000", &["server", "github-token"]).unwrap(),
            Value::from("1_000")
        );
    }

    /// yaml.v3 reads a plain timestamp in an untyped value as a `time.Time`, which Go
    /// marshals as RFC 3339 text (recorded with yaml.v3 v3.0.1 and Go 1.26.4); a string
    /// setting and a mapping key keep the text.
    #[test]
    fn plain_timestamps_read_as_in_go() {
        let go = [
            ("2001-12-14", Some("2001-12-14T00:00:00Z")),
            ("2001-1-2", Some("2001-01-02T00:00:00Z")),
            ("2001-12-14 21:59:43.10", Some("2001-12-14T21:59:43.1Z")),
            ("2001-12-14T21:59:43.10-05:00", Some("2001-12-14T21:59:43.1-05:00")),
            ("2001-12-14t21:59:43,5+00:60", Some("2001-12-14T21:59:43.5+01:00")),
            (
                "2001-12-14T21:59:43.123456789123Z",
                Some("2001-12-14T21:59:43.123456789Z"),
            ),
            ("2001-12-14T21:59:43-00:00", Some("2001-12-14T21:59:43Z")),
            ("2004-2-29   1:2:3", Some("2004-02-29T01:02:03Z")),
            ("0001-01-01", Some("0001-01-01T00:00:00Z")),
            ("2001-12-14 21:59:43.10 -5", None),
            ("2001-12-14x", None),
            ("2001-02-29", None),
            ("2001-12-14t21:59:43.10z", None),
            ("2001-12-14 21:59:43.10Z", None),
            ("2001-12-14T24:00:00Z", None),
            ("2001-12-14 \t21:59:43", None),
        ];
        // A block list: a flow one would split `43,5` at the comma.
        let list: String = go.iter().map(|(text, _)| format!("  - {text}\n")).collect();
        let any = yaml_value(&format!("x:\n{list}  - '2001-12-14'\n")).unwrap();
        let json = serde_json::to_value(AsJson(&any)).unwrap();
        for (i, (text, want)) in go.iter().enumerate() {
            let tagged = matches!(&any["x"][i], Value::Tagged(t) if t.tag == TIMESTAMP_TAG);
            assert_eq!(tagged, want.is_some(), "{text}");
            assert_eq!(json["x"][i], want.unwrap_or(text), "{text}");
        }
        assert_eq!(any["x"][go.len()], Value::from("2001-12-14"));
        // Written back plain, as yaml.v3 writes a `time.Time`, and read back the same.
        let text = yaml_string(&any).unwrap();
        assert!(text.contains("\n- 2001-12-14T00:00:00Z\n"), "{text}");
        assert_eq!(yaml_value(&text).unwrap(), any, "{text}");
        let cfg =
            Config::parse("server: {github-token: 2001-12-14}\noauth-excluded-models: {2001-12-14: [a]}\n").unwrap();
        assert_eq!(cfg.document["server"]["github-token"].as_str(), Some("2001-12-14"));
        assert!(cfg.document["oauth"]["excluded-models"].get("2001-12-14").is_some());
        // The management key is still found and hashed beside a plain timestamp.
        let hash = "$2a$10$abcdefghijklmnopqrstuuvwxyzabcdefghijklmnopqrstuvwxy";
        let saved = with_secret_hash("management: {secret-key: plain}\nx: [2001-12-14]\n", hash).unwrap();
        assert!(saved.contains(hash), "{saved}");
        let prepared = prepared_for_upload("management: {secret-key: plain}\nx: [2001-12-14]\n").unwrap();
        assert!(prepared.contains("$2"), "{prepared}");
        // Folded over lines, under a `%TAG !` directive, and inside a local tag, which
        // Go's `any` prints as its value (all recorded with yaml.v3).
        for (text, want) in [
            (
                "x: 2001-12-14\n  21:59:43\n",
                serde_json::json!({"x": "2001-12-14T21:59:43Z"}),
            ),
            (
                "x: [2001-12-14\n  21:59:43]\n",
                serde_json::json!({"x": ["2001-12-14T21:59:43Z"]}),
            ),
            // Anchored too, with the anchor on the scalar's line or its own.
            (
                "x: &a 2001-12-14\n  21:59:43\ny: *a\n",
                serde_json::json!({"x": "2001-12-14T21:59:43Z", "y": "2001-12-14T21:59:43Z"}),
            ),
            (
                "x: &a\n  2001-12-14\n  21:59:43\ny: *a\n",
                serde_json::json!({"x": "2001-12-14T21:59:43Z", "y": "2001-12-14T21:59:43Z"}),
            ),
            (
                "x: &a # c\n  # d\n  2001-12-14\n  21:59:43\ny: *a\n",
                serde_json::json!({"x": "2001-12-14T21:59:43Z", "y": "2001-12-14T21:59:43Z"}),
            ),
            (
                "x: &a\u{2028}  2001-12-14\n  21:59:43\ny: *a\n",
                serde_json::json!({"x": "2001-12-14T21:59:43Z", "y": "2001-12-14T21:59:43Z"}),
            ),
            (
                "x: &a\n  # c\n  2001-12-14\n  21:59:43\ny: *a\n",
                serde_json::json!({"x": "2001-12-14T21:59:43Z", "y": "2001-12-14T21:59:43Z"}),
            ),
            (
                "x: &a\u{2029}  2001-12-14\n  21:59:43\ny: *a\n",
                serde_json::json!({"x": "2001-12-14T21:59:43Z", "y": "2001-12-14T21:59:43Z"}),
            ),
            (
                "x: &a\u{85}  2001-12-14\n  21:59:43\ny: *a\n",
                serde_json::json!({"x": "2001-12-14T21:59:43Z", "y": "2001-12-14T21:59:43Z"}),
            ),
            (
                "x: [&a 2001-12-14\n  21:59:43, *a]\n",
                serde_json::json!({"x": ["2001-12-14T21:59:43Z", "2001-12-14T21:59:43Z"]}),
            ),
            (
                "%TAG ! tag:example.com,2000:\n---\nx: 2001-12-14\n",
                serde_json::json!({"x": "2001-12-14T00:00:00Z"}),
            ),
            (
                "x: !y {at: 2001-12-14}\n",
                serde_json::json!({"x": {"at": "2001-12-14T00:00:00Z"}}),
            ),
        ] {
            let json = serde_json::to_value(AsJson(&yaml_value(text).unwrap())).unwrap();
            assert_eq!(json, want, "{text}");
        }
        let directive = yaml_value("%TAG ! tag:example.com,2000:\n---\nx: 2001-12-14\n").unwrap();
        assert!(
            matches!(&directive["x"], Value::Tagged(t) if t.tag == TIMESTAMP_TAG),
            "{directive:?}"
        );
        // A string key that reads as a timestamp is quoted, as Go's Marshal quotes it.
        let key = yaml_string(&yaml_value("{'2001-12-14': a}").unwrap()).unwrap();
        assert_eq!(key, "\"2001-12-14\": a\n");
        // Go cannot marshal an offset of 24 hours or more as JSON. The config decode
        // refuses it; a reader of other settings, such as discovery's, still parses.
        let wide = "x: 2001-12-14T21:59:43+24:00\n";
        let err = yaml_value(wide).unwrap_err();
        assert!(format!("{err:#}").contains("24 hours"), "{err:#}");
        assert!(config_value(wide).is_err() && parse_yaml(wide).is_ok());
    }

    /// yaml.v3 skips a leading BOM; serde_yaml_ng and libyaml read it as part of the
    /// first line, so a second top-level key failed the load.
    #[test]
    fn a_leading_bom_is_skipped() {
        let cfg = Config::parse(
            "\u{feff}server: {github-token: !!binary dG9r}\nrouting: {retry: {request-retry: 3}}\n\
             x: [18446744073709551616, 007]\n",
        )
        .unwrap();
        assert_eq!(cfg.document["server"]["github-token"].as_str(), Some("tok"));
        assert_eq!(cfg.routing.retry.request_retry, 3);
        let x = yaml_value("\u{feff}a: b\nx: [18446744073709551616, 007]\n").unwrap();
        assert_eq!(x["x"], yaml_value("[1.8446744073709552e19, 7]").unwrap());
        // Go's save (SaveConfigPreserveComments, recorded at ae3ee3be) drops the BOM and
        // keeps the head comment, in the v8 layout and when it migrates a legacy one.
        for original in [
            "\u{feff}# head\nserver:\n  port: 1\n",
            "\u{feff}# head\nport: 1\nhost: x\n",
        ] {
            let mut doc = ConfigDocument::parse(original).unwrap();
            doc.update(&["server", "port"], Value::from(2), false).unwrap();
            let basis = doc.migrated_text(original).unwrap_or_else(|| original.to_owned());
            let saved = doc.render_preserving(&basis).unwrap();
            assert!(saved.starts_with("# head\n"), "{saved:?}");
            assert_eq!(Config::parse(&saved).unwrap().port, 2, "{saved:?}");
        }
        // The plaintext management key is hashed in place, and through a merge.
        let hash = "$2a$10$abcdefghijklmnopqrstuuvwxyzabcdefghijklmnopqrstuvwxy";
        for text in [
            "\u{feff}management:\n  secret-key: plain\n",
            "\u{feff}b: &b {secret-key: plain}\nmanagement: {<<: *b}\n",
        ] {
            let saved = with_secret_hash(text, hash).unwrap();
            assert!(!saved.starts_with('\u{feff}') && saved.contains(hash), "{saved:?}");
        }
        let prepared = prepared_for_upload("\u{feff}management:\n  secret-key: plain\nport: 1\n").unwrap();
        assert!(
            !prepared.starts_with('\u{feff}') && prepared.contains("$2"),
            "{prepared:?}"
        );
    }

    /// A string that would read back as a number when written plain is double-quoted
    /// where a write re-emits it, as yaml.v3 quotes it, so it stays that string.
    #[test]
    fn re_emitted_strings_read_back_as_strings() {
        let strings = [
            "1_000",
            "0_7",
            "0_8",
            "1_0.5",
            "0x_1F",
            ".5_0",
            "007",
            "0b-1",
            "0o+17",
            "0X1F",
            "0O17",
            "+9223372036854775808",
            "18446744073709551616",
            "-18446744073709551616",
            "2001-12-14",
            "2001-12-14 21:59:43.10",
        ];
        let value = Value::Sequence(strings.iter().map(|s| Value::from(*s)).collect());
        let text = yaml_string(&value).unwrap();
        assert_eq!(parse_yaml(&text).unwrap(), value, "{text}");
        // String keys too, which Go would otherwise read as numbers.
        let keys = yaml_value("{'1_000': a, '007': b, 7: c}").unwrap();
        let text = yaml_string(&keys).unwrap();
        assert_eq!(text, "\"1_000\": a\n'007': b\n7: c\n");
        assert_eq!(parse_yaml(&text).unwrap(), keys, "{text}");
        assert_eq!(
            yaml_string(&yaml_value("[7, 1000, 0.5]").unwrap()).unwrap(),
            "- 7\n- 1000\n- 0.5\n"
        );
        // The secret-key fallback re-emits the whole file.
        let text = "base: &b {secret-key: plain}\nmanagement: {<<: *b}\n\
                    requests: {payload: {default: [{models: [{name: m}], params: {a: '1_000', b: '007'}}]}}\n";
        let saved = with_secret_hash(text, "$2a$10$abcdefghijklmnopqrstuuvwxyzabcdefghijklmnopqrstuvwxy").unwrap();
        let params = &parse_yaml(&saved).unwrap()["requests"]["payload"]["default"][0]["params"];
        assert_eq!(params["a"], Value::from("1_000"), "{saved}");
        assert_eq!(params["b"], Value::from("007"), "{saved}");
    }

    /// yaml.v3 reads a plain scalar into any Go string setting as its text, so a setting
    /// written as a number or boolean (`0x1F`, `1.50`, `007`, `true`) keeps it, in the v8
    /// and legacy layouts and through an anchored key (tests/reference/scalar_settings).
    #[test]
    fn scalar_settings_keep_their_yaml_text() {
        let go: serde_json::Value =
            serde_json::from_str(include_str!("../tests/fixtures/scalar_settings_go.json")).unwrap();
        for case in go["cases"].as_array().unwrap() {
            let cfg = Config::parse(case["yaml"].as_str().unwrap()).unwrap();
            for check in case["checks"].as_array().unwrap() {
                let path = check["rust"].as_str().unwrap();
                let mut node = &cfg.document;
                for part in path.split('.') {
                    node = match part.parse::<usize>() {
                        Ok(i) => &node[i],
                        Err(_) => &node[part],
                    };
                }
                assert_eq!(node.as_str(), check["value"].as_str(), "{}: {path}", case["name"]);
            }
        }
        // A model with a display name written as a number registers under its prefix,
        // both as Go reads them.
        let cfg = Config::parse(go["cases"][0]["yaml"].as_str().unwrap()).unwrap();
        let aliases = crate::registry::dynamic::global_aliases(&cfg);
        let models: Vec<(String, String)> = credentials::from_config(&cfg)
            .iter()
            .flat_map(|c| crate::registry::dynamic::models_for(&cfg, &aliases, c, 0))
            .map(|m| (m.id, m.display_name))
            .collect();
        assert!(models.contains(&("0x1F/a".into(), "1.50".into())), "{models:?}");
    }
}