keel-core-api 0.4.1

Keel core API contract types (contracts-v1). Single source of truth: contracts/core_api.rs.
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
//! Typed policy model: `keel.toml` (in its JSON form) deserialized straight
//! into structs. Validation *is* the type system — `NonZero*` integers make
//! zero counts unrepresentable, newtypes parse duration/rate/schedule
//! literals in their `Deserialize` impls, and retry conditions are a closed
//! enum. A document that deserializes is a valid policy; anything else is
//! `KEEL-E001` with a precise field path (via `serde_path_to_error`).

use core::fmt;
use core::num::{NonZeroU32, NonZeroU64};
use core::str::FromStr;
use std::collections::BTreeMap;

use crate::ErrorClass;
use serde::Deserialize;

/// A literal that failed to parse; surfaces through serde as the
/// deserialization error message for the offending field.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseError {
    what: &'static str,
    input: String,
    /// For literals that are grammatical but invalid (e.g. a schedule
    /// composition whose segments can never all be reached): the reason,
    /// appended so the KEEL-E001 first line says what to fix.
    note: Option<&'static str>,
}

impl ParseError {
    fn new(what: &'static str, input: &str) -> Self {
        Self {
            what,
            input: input.to_owned(),
            note: None,
        }
    }

    fn with_note(what: &'static str, input: &str, note: &'static str) -> Self {
        Self {
            what,
            input: input.to_owned(),
            note: Some(note),
        }
    }
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.note {
            None => write!(f, "unparseable {} literal: {:?}", self.what, self.input),
            Some(note) => write!(
                f,
                "invalid {} literal: {:?} — {note}",
                self.what, self.input
            ),
        }
    }
}

impl core::error::Error for ParseError {}

/// A duration literal: `200ms`, `30s`, `5m`, `2h`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize)]
#[serde(try_from = "String")]
pub struct DurationMs(pub u64);

impl FromStr for DurationMs {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let err = || ParseError::new("duration", s);
        let s = s.trim();
        let unit_at = s.find(|c: char| !c.is_ascii_digit()).ok_or_else(err)?;
        let (number, unit) = s.split_at(unit_at);
        let n: u64 = number.parse().map_err(|_| err())?;
        let mult = match unit {
            "ms" => 1,
            "s" => 1_000,
            "m" => 60_000,
            "h" => 3_600_000,
            _ => return Err(err()),
        };
        Ok(Self(n * mult))
    }
}

impl TryFrom<String> for DurationMs {
    type Error = ParseError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        s.parse()
    }
}

/// A rate literal: `90/s`, `60/min`, `10/h`. A zero limit is unrepresentable.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(try_from = "String")]
pub struct Rate {
    pub limit: NonZeroU64,
    pub window_ms: u64,
}

impl FromStr for Rate {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let err = || ParseError::new("rate", s);
        let (limit, window) = s.trim().split_once('/').ok_or_else(err)?;
        let limit: NonZeroU64 = limit.trim().parse().map_err(|_| err())?;
        let window_ms = match window.trim() {
            "s" | "sec" => 1_000,
            "min" => 60_000,
            "h" | "hour" => 3_600_000,
            _ => return Err(err()),
        };
        Ok(Self { limit, window_ms })
    }
}

impl TryFrom<String> for Rate {
    type Error = ParseError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        s.parse()
    }
}

/// A retry schedule per contracts/schedule-grammar.ebnf — the full algebra:
/// one or more `andThen`-separated segments, each an `exp`/`fixed` primary
/// with an optional cumulative-wait bound (`upTo`). Semantics are pinned
/// normatively in conformance/README.md ("Schedule algebra"): `upTo` bounds
/// the segment's cumulative *natural* wait and hands off to the next segment;
/// every segment except the last must be bounded and the last never is (both
/// degenerate shapes are configure-time `KEEL-E001`), so a schedule is always
/// a total mapping attempt → wait.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(try_from = "String")]
pub struct Schedule {
    /// Non-empty; the parser enforces `up_to_ms.is_some()` on every segment
    /// except the last and `None` on the last.
    pub segments: Vec<ScheduleSegment>,
}

/// One `andThen` segment: a primary plus its optional `upTo` bound.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ScheduleSegment {
    pub primary: SchedulePrimary,
    /// `upTo` bound on this segment's cumulative natural wait, in ms.
    pub up_to_ms: Option<u64>,
}

/// A schedule primary (`exp` / `fixed`) from the frozen grammar.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SchedulePrimary {
    Exp {
        base_ms: u64,
        factor: f64,
        cap_ms: u64,
        jitter: bool,
    },
    Fixed {
        period_ms: u64,
    },
}

impl SchedulePrimary {
    /// Deterministic natural wait at local attempt `a` (1-based):
    /// `min(base * factor^(a-1), cap)`, before any jitter.
    #[expect(
        clippy::cast_precision_loss,
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        clippy::cast_possible_wrap,
        reason = "backoff arithmetic: values are small and non-negative by construction"
    )]
    fn wait_ms(self, attempt: u32) -> u64 {
        match self {
            Self::Exp {
                base_ms,
                factor,
                cap_ms,
                ..
            } => {
                let wait = base_ms as f64 * factor.powi(attempt as i32 - 1);
                wait.min(cap_ms as f64).round() as u64
            }
            Self::Fixed { period_ms } => period_ms,
        }
    }

    fn jitter(self) -> bool {
        matches!(self, Self::Exp { jitter: true, .. })
    }
}

impl Default for Schedule {
    /// The contract default: `exp(200ms, x2, max 30s, jitter)`.
    fn default() -> Self {
        Self {
            segments: vec![ScheduleSegment {
                primary: SchedulePrimary::Exp {
                    base_ms: 200,
                    factor: 2.0,
                    cap_ms: 30_000,
                    jitter: true,
                },
                up_to_ms: None,
            }],
        }
    }
}

impl Schedule {
    /// Deterministic wait after failed attempt `n` (1-based), before any
    /// jitter or `Retry-After` override.
    #[must_use]
    pub fn wait_ms(&self, attempt: u32) -> u64 {
        self.wait_and_jitter(attempt).0
    }

    /// `(wait, jitter?)` for retry attempt `n` — a pure function of `n`, per
    /// the normative walk in conformance/README.md ("Schedule algebra"):
    /// segments hand off when the next natural wait would push the segment's
    /// cumulative emitted total past its `upTo` bound (an exact fit stays;
    /// handoffs cascade past segments whose bound is below their first wait),
    /// and each segment restarts at local attempt 1 on entry. The jitter flag
    /// is the emitting segment's — the stubs ignore it (virtual clocks); the
    /// real core samples equal jitter, uniform in `[w/2, w]`.
    ///
    /// # Panics
    /// If `segments` is empty (unrepresentable via the parser).
    #[must_use]
    pub fn wait_and_jitter(&self, attempt: u32) -> (u64, bool) {
        let attempt = attempt.max(1);
        let last = self.segments.len() - 1;
        let (mut i, mut a, mut e) = (0_usize, 1_u32, 0_u64);
        let mut emitted = 0_u32;
        loop {
            let segment = self.segments[i];
            let wait = segment.primary.wait_ms(a);
            // A bound on the final segment is unrepresentable via the parser;
            // `i < last` keeps hand-constructed values total anyway.
            if i < last
                && let Some(bound) = segment.up_to_ms
                && e.saturating_add(wait) > bound
            {
                (i, a, e) = (i + 1, 1, 0);
                continue;
            }
            emitted += 1;
            if emitted == attempt {
                return (wait, segment.primary.jitter());
            }
            a += 1;
            e = e.saturating_add(wait);
        }
    }
}

impl FromStr for SchedulePrimary {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let err = || ParseError::new("schedule", s);
        let s = s.trim();
        if let Some(inner) = s.strip_prefix("exp(").and_then(|r| r.strip_suffix(')')) {
            let parts: Vec<&str> = inner.split(',').map(str::trim).collect();
            let [base, factor, rest @ ..] = parts.as_slice() else {
                return Err(err());
            };
            let base_ms = base.parse::<DurationMs>().map_err(|_| err())?.0;
            let factor: f64 = factor
                .strip_prefix('x')
                .ok_or_else(err)?
                .parse()
                .map_err(|_| err())?;
            let mut cap_ms = u64::MAX;
            let mut jitter = false;
            for part in rest {
                if let Some(d) = part.strip_prefix("max ") {
                    cap_ms = d.parse::<DurationMs>().map_err(|_| err())?.0;
                } else if *part == "jitter" {
                    jitter = true;
                } else {
                    return Err(err());
                }
            }
            Ok(Self::Exp {
                base_ms,
                factor,
                cap_ms,
                jitter,
            })
        } else if let Some(inner) = s.strip_prefix("fixed(").and_then(|r| r.strip_suffix(')')) {
            let period_ms = inner.parse::<DurationMs>().map_err(|_| err())?.0;
            Ok(Self::Fixed { period_ms })
        } else {
            Err(err())
        }
    }
}

impl FromStr for Schedule {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let err = || ParseError::new("schedule", s);
        // The grammar's `ws` makes `upTo` / `andThen` space-separated tokens;
        // tokenizing on whitespace runs and rejoining a primary's tokens with
        // single spaces is lossless for the primary parsers (they trim around
        // commas). Keywords never occur inside `exp(…)`/`fixed(…)` in a valid
        // literal, so no paren tracking is needed — misplaced keywords make
        // the primary unparseable, which is the same KEEL-E001.
        let tokens: Vec<&str> = s.split_whitespace().collect();
        if tokens.is_empty() {
            return Err(err());
        }
        let mut segments = Vec::new();
        for segment_tokens in tokens.split(|t| *t == "andThen") {
            let (primary_tokens, up_to_ms) = match segment_tokens.iter().position(|t| *t == "upTo")
            {
                None => (segment_tokens, None),
                Some(pos) => {
                    // exactly `upTo <duration>`, at the segment's tail
                    let [duration] = &segment_tokens[pos + 1..] else {
                        return Err(err());
                    };
                    let bound = duration.parse::<DurationMs>().map_err(|_| err())?.0;
                    (&segment_tokens[..pos], Some(bound))
                }
            };
            if primary_tokens.is_empty() {
                return Err(err());
            }
            let primary: SchedulePrimary = primary_tokens.join(" ").parse().map_err(|_| err())?;
            segments.push(ScheduleSegment { primary, up_to_ms });
        }
        // Shape rule (normative, conformance/README.md "Schedule algebra"):
        // bounded exactly on the non-final segments, so every segment is
        // reachable and every attempt has a wait.
        let last = segments.len() - 1;
        if segments
            .iter()
            .enumerate()
            .any(|(i, segment)| (i < last) != segment.up_to_ms.is_some())
        {
            return Err(ParseError::with_note(
                "schedule",
                s,
                "`upTo` must bound every segment except the last, and never the last \
                 (an unbounded segment never hands off; a bounded tail would leave \
                 attempts without a wait — cap total retrying with `attempts`)",
            ));
        }
        Ok(Self { segments })
    }
}

impl TryFrom<String> for Schedule {
    type Error = ParseError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        s.parse()
    }
}

/// One retryable-error condition from `retry.on` (closed set; unknown
/// conditions fail configuration instead of silently never matching).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(try_from = "String")]
pub enum Condition {
    Conn,
    Timeout,
    Cancelled,
    Other,
    Class4xx,
    Class5xx,
    Status(u16),
}

impl Condition {
    pub fn matches(self, class: ErrorClass, http_status: Option<u16>) -> bool {
        match self {
            Self::Conn => class == ErrorClass::Conn,
            Self::Timeout => class == ErrorClass::Timeout,
            Self::Cancelled => class == ErrorClass::Cancelled,
            Self::Other => class == ErrorClass::Other,
            Self::Class4xx => {
                class == ErrorClass::Http && http_status.is_some_and(|s| (400..=499).contains(&s))
            }
            Self::Class5xx => {
                class == ErrorClass::Http && http_status.is_some_and(|s| (500..=599).contains(&s))
            }
            Self::Status(want) => class == ErrorClass::Http && http_status == Some(want),
        }
    }
}

impl FromStr for Condition {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "conn" => Ok(Self::Conn),
            "timeout" => Ok(Self::Timeout),
            "cancelled" => Ok(Self::Cancelled),
            "other" => Ok(Self::Other),
            "4xx" => Ok(Self::Class4xx),
            "5xx" => Ok(Self::Class5xx),
            // Frozen schema errorCondition grammar is `[1-5][0-9][0-9]` (100–599):
            // require three ASCII digits in range, not any 3-char u16 (which
            // accepted `099`→99 and `999`, outside the contract).
            exact if exact.len() == 3 && exact.bytes().all(|b| b.is_ascii_digit()) => {
                let code: u16 = exact
                    .parse()
                    .map_err(|_| ParseError::new("retry condition", s))?;
                if (100..=599).contains(&code) {
                    Ok(Self::Status(code))
                } else {
                    Err(ParseError::new("retry condition", s))
                }
            }
            _ => Err(ParseError::new("retry condition", s)),
        }
    }
}

impl TryFrom<String> for Condition {
    type Error = ParseError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        s.parse()
    }
}

/// `retry = { attempts, schedule, on }`. `attempts` is the TOTAL attempt
/// budget (first call included) — zero is unrepresentable by type.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct RetryPolicy {
    pub attempts: NonZeroU32,
    pub schedule: Schedule,
    pub on: Vec<Condition>,
}

impl RetryPolicy {
    pub const DEFAULT_ATTEMPTS: NonZeroU32 = NonZeroU32::new(3).unwrap();

    /// The contract default retryable set: `["conn", "timeout", "429", "5xx"]`.
    pub fn default_on() -> Vec<Condition> {
        vec![
            Condition::Conn,
            Condition::Timeout,
            Condition::Status(429),
            Condition::Class5xx,
        ]
    }

    pub fn is_retryable(&self, class: ErrorClass, http_status: Option<u16>) -> bool {
        self.on.iter().any(|c| c.matches(class, http_status))
    }
}

impl Default for RetryPolicy {
    fn default() -> Self {
        Self {
            attempts: Self::DEFAULT_ATTEMPTS,
            schedule: Schedule::default(),
            on: Self::default_on(),
        }
    }
}

/// `breaker = { failures, cooldown, window, failure_rate, min_calls }`.
///
/// Two modes per the frozen schema (`$defs/breaker`), enforced identically by
/// the real core and every stub — normative rules in `conformance/README.md`:
/// - **count mode**: selected when `failures` is set (or no rate knob is set;
///   `failures` then defaults to 5) — `failures` consecutive terminal failures
///   open the breaker.
/// - **rate mode**: selected when `failures` is absent and both `window` and
///   `failure_rate` are set — trips when the trailing `window` holds at least
///   `min_calls` outcomes (default 10) with `failed/total >= failure_rate`.
///
/// A rate-mode knob without both `window` and `failure_rate` (and without
/// `failures`) is rejected at deserialize time (KEEL-E001): a half-configured
/// mode must fail loudly, never silently degrade to count-mode defaults.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(try_from = "BreakerPolicyDe")]
pub struct BreakerPolicy {
    /// Count-mode threshold. `None` means "not set by the user" — see
    /// [`BreakerPolicy::mode`] for how that selects the mode.
    pub failures: Option<NonZeroU64>,
    pub cooldown: DurationMs,
    pub window: Option<DurationMs>,
    pub failure_rate: Option<f64>,
    pub min_calls: Option<NonZeroU32>,
}

/// The breaker mode a [`BreakerPolicy`] resolves to, with every default
/// applied — the engine/stubs consume this, never the raw knobs.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum BreakerMode {
    /// `failures` consecutive terminal failures open the breaker.
    Count { failures: NonZeroU64 },
    /// Failure-rate tripping over a sliding window of post-retry outcomes.
    Rate {
        window: DurationMs,
        failure_rate: f64,
        min_calls: NonZeroU32,
    },
}

impl BreakerPolicy {
    /// Schema default for count mode's `failures`.
    pub const DEFAULT_FAILURES: NonZeroU64 = NonZeroU64::new(5).unwrap();
    /// Schema default for rate mode's `min_calls`.
    pub const DEFAULT_MIN_CALLS: NonZeroU32 = NonZeroU32::new(10).unwrap();

    /// The mode this policy selects (schema: "Setting `failures` selects count
    /// mode"), with defaults applied. Deserialization already rejected
    /// half-configured rate mode, so `window`+`failure_rate` are either both
    /// present or irrelevant here.
    #[must_use]
    pub fn mode(&self) -> BreakerMode {
        match (self.failures, self.window, self.failure_rate) {
            (None, Some(window), Some(failure_rate)) => BreakerMode::Rate {
                window,
                failure_rate,
                min_calls: self.min_calls.unwrap_or(Self::DEFAULT_MIN_CALLS),
            },
            (failures, _, _) => BreakerMode::Count {
                failures: failures.unwrap_or(Self::DEFAULT_FAILURES),
            },
        }
    }

    /// Whether count mode was selected *while* rate-mode knobs are present —
    /// those knobs are inert (the schema's precedence), which callers may want
    /// to surface loudly rather than leave silent.
    #[must_use]
    pub fn has_inert_rate_knobs(&self) -> bool {
        self.failures.is_some()
            && (self.window.is_some() || self.failure_rate.is_some() || self.min_calls.is_some())
    }
}

/// The raw deserialized shape of `breaker`, before mode-completeness
/// validation promotes it to [`BreakerPolicy`].
#[derive(Deserialize)]
#[serde(default, deny_unknown_fields)]
struct BreakerPolicyDe {
    failures: Option<NonZeroU64>,
    cooldown: DurationMs,
    window: Option<DurationMs>,
    #[serde(deserialize_with = "de_failure_rate")]
    failure_rate: Option<f64>,
    min_calls: Option<NonZeroU32>,
}

impl Default for BreakerPolicyDe {
    fn default() -> Self {
        Self {
            failures: None,
            cooldown: DurationMs(15_000),
            window: None,
            failure_rate: None,
            min_calls: None,
        }
    }
}

impl TryFrom<BreakerPolicyDe> for BreakerPolicy {
    type Error = String;

    fn try_from(de: BreakerPolicyDe) -> Result<Self, Self::Error> {
        let rate_pair = de.window.is_some() && de.failure_rate.is_some();
        let any_rate_knob =
            de.window.is_some() || de.failure_rate.is_some() || de.min_calls.is_some();
        if de.failures.is_none() && any_rate_knob && !rate_pair {
            return Err(String::from(
                "breaker rate mode requires both `window` and `failure_rate` \
                 (count mode sets `failures` instead)",
            ));
        }
        Ok(Self {
            failures: de.failures,
            cooldown: de.cooldown,
            window: de.window,
            failure_rate: de.failure_rate,
            min_calls: de.min_calls,
        })
    }
}

/// Validate `breaker.failure_rate` against the frozen schema range
/// (`exclusiveMinimum: 0, maximum: 1`) at deserialize time, so an out-of-range or
/// NaN value fails configuration with a precise field path (`KEEL-E001`) instead
/// of being silently accepted — the bare `f64` used to take any value.
fn de_failure_rate<'de, D>(deserializer: D) -> Result<Option<f64>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let value = Option::<f64>::deserialize(deserializer)?;
    if let Some(rate) = value
        && !(rate > 0.0 && rate <= 1.0)
    {
        return Err(serde::de::Error::custom(format!(
            "breaker.failure_rate must be greater than 0 and at most 1 (got {rate})"
        )));
    }
    Ok(value)
}

impl Default for BreakerPolicy {
    fn default() -> Self {
        Self {
            failures: None,
            cooldown: DurationMs(15_000),
            window: None,
            failure_rate: None,
            min_calls: None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CacheScope {
    #[default]
    Memory,
    Persistent,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CacheMode {
    #[default]
    Always,
    /// Caches only when `KEEL_ENV != prod` — the LLM dev-loop cache.
    Dev,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CacheKeySource {
    #[default]
    Args,
    Url,
}

/// `cache = { ttl, scope, mode, key }`. Caching activates only with a `ttl`.
#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct CachePolicy {
    pub ttl: Option<DurationMs>,
    pub scope: CacheScope,
    pub mode: CacheMode,
    pub key: CacheKeySource,
}

/// `idempotency = { header }` — the header is required by the schema.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct IdempotencyPolicy {
    pub header: String,
}

/// `until = { field, terminal }` — the poll's terminal predicate (CCR-3).
/// Non-emptiness is enforced at deserialize so an unpollable predicate is
/// KEEL-E001 at configure, never a silent never-terminal loop.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(try_from = "PollUntilRaw")]
pub struct PollUntil {
    pub field: String,
    pub terminal: Vec<String>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PollUntilRaw {
    field: String,
    terminal: Vec<String>,
}

impl TryFrom<PollUntilRaw> for PollUntil {
    type Error = ParseError;

    fn try_from(raw: PollUntilRaw) -> Result<Self, Self::Error> {
        if raw.field.is_empty() {
            return Err(ParseError::new("poll until.field", "(empty)"));
        }
        if raw.terminal.is_empty() {
            return Err(ParseError::new("poll until.terminal", "(empty array)"));
        }
        Ok(Self {
            field: raw.field,
            terminal: raw.terminal,
        })
    }
}

/// `poll = { interval, deadline, until }` — poll-until-terminal (CCR-3).
/// GET/HEAD at Level 0 only; semantics in conformance/README.md ("Poll").
/// `interval` must be nonzero: on a virtual clock a zero interval never
/// approaches `deadline`, looping forever, so it is rejected at deserialize
/// (KEEL-E001) rather than left to hang at runtime.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(try_from = "PollPolicyRaw")]
pub struct PollPolicy {
    pub interval: DurationMs,
    pub deadline: DurationMs,
    pub until: PollUntil,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct PollPolicyRaw {
    interval: DurationMs,
    deadline: DurationMs,
    until: PollUntil,
}

impl TryFrom<PollPolicyRaw> for PollPolicy {
    type Error = ParseError;

    fn try_from(raw: PollPolicyRaw) -> Result<Self, Self::Error> {
        if raw.interval.0 == 0 {
            return Err(ParseError::with_note(
                "poll.interval",
                "0",
                "must be a nonzero duration",
            ));
        }
        Ok(Self {
            interval: raw.interval,
            deadline: raw.deadline,
            until: raw.until,
        })
    }
}

/// One target's policy table. Every layer is optional; a layer set at a more
/// specific level replaces the whole layer table (no deep merge).
#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct TargetPolicy {
    pub timeout: Option<DurationMs>,
    pub retry: Option<RetryPolicy>,
    pub breaker: Option<BreakerPolicy>,
    pub rate: Option<Rate>,
    pub cache: Option<CachePolicy>,
    pub idempotency: Option<IdempotencyPolicy>,
    pub poll: Option<PollPolicy>,
    pub fallback: Option<Vec<String>>,
    pub budget: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Defaults {
    pub outbound: Option<TargetPolicy>,
    pub llm: Option<TargetPolicy>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NondeterminismResponse {
    #[default]
    Fail,
    Warn,
    Branch,
}

/// What a concurrent same-identity `keel exec` does while the lease is held
/// by a live process (CCR-4). Default `skip` — the mkdir-mutex pattern.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum OnBusy {
    #[default]
    Skip,
    Wait,
    Fail,
}

/// One `[flows.match."cmd:<name>"]` rule (CCR-5): the argv patterns an
/// in-process subprocess call site must match to be dispatched as this `cmd:`
/// flow. `argv` is a list of per-position patterns (single-`*` wildcard
/// dialect, docs/targeting.md); parsed and carried here, the matching itself
/// lives in the front-end interceptors. Only in-process interception consults
/// these — `keel exec` matches the argv typed after `--`.
#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct FlowMatchRule {
    pub argv: Vec<String>,
}

/// Tier 2 flow designation — parsed and carried, enforced by the real core.
#[derive(Debug, Clone, PartialEq, Eq, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct FlowsPolicy {
    pub entrypoints: Vec<String>,
    pub on_nondeterminism: NondeterminismResponse,
    pub on_busy: OnBusy,
    /// `[flows.match."cmd:<name>"]` argv match rules (CCR-5), keyed by the
    /// `cmd:<name>` entrypoint string. Parsed and carried structurally so a
    /// keel.toml with a `[flows.match]` table configures cleanly; the
    /// front-end subprocess interceptors are the only consumers, not the
    /// core. `None` when the table is absent. A `BTreeMap` (not `HashMap`)
    /// so iteration is deterministic, matching `Policy::target`.
    #[serde(rename = "match")]
    pub match_: Option<BTreeMap<String, FlowMatchRule>>,
}

/// A journal location literal (`policy.journal`), validated against the frozen
/// schema pattern `^(file:.+|postgres://.+)$` at parse time so a malformed value
/// fails configuration (KEEL-E001) rather than being silently ignored. The real
/// core honors it at configure time: `file:` attaches a SQLite journal at that
/// path (replacing the construction-time default), and `postgres://` fails
/// loudly with KEEL-E005 until a Postgres backend ships.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(try_from = "String")]
pub struct JournalLocation(pub String);

impl FromStr for JournalLocation {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let valid = s.strip_prefix("file:").is_some_and(|rest| !rest.is_empty())
            || s.strip_prefix("postgres://")
                .is_some_and(|rest| !rest.is_empty());
        if valid {
            Ok(Self(s.to_owned()))
        } else {
            Err(ParseError::new("journal location", s))
        }
    }
}

impl TryFrom<String> for JournalLocation {
    type Error = ParseError;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        s.parse()
    }
}

/// `[telemetry]` (`otlp_endpoint`, `console`). Parsed and carried; `Engine`
/// exposes `otlp_endpoint` back to native front ends (`telemetry_otlp_endpoint`)
/// which feed it to `keel-core`'s `otel::init_otlp` when built with the `otel`
/// feature — the standard `OTEL_*` environment variables take precedence over
/// this table (see `keel-core`'s otel module for the exact precedence rules).
/// `console` (the local pretty-console-summary switch) is validated and
/// carried but has no consumer yet; `Engine::configure` warns on an explicit
/// `false` so the user is not silently surprised.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct TelemetryPolicy {
    pub otlp_endpoint: Option<String>,
    pub console: bool,
}

impl Default for TelemetryPolicy {
    fn default() -> Self {
        // Schema default: console = true.
        Self {
            otlp_endpoint: None,
            console: true,
        }
    }
}

/// The whole `keel.toml` document (contracts/policy.schema.json), typed.
///
/// `deny_unknown_fields` at every object level (here and on the layer structs)
/// makes a typo'd or unknown key a configuration error (KEEL-E001 with the exact
/// path via `serde_path_to_error`), honoring the frozen schema's
/// `additionalProperties: false` and E001's "an unknown key was used" — instead
/// of the previous silent drop that ran the target on defaults the user never
/// asked for.
#[derive(Debug, Clone, PartialEq, Default, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Policy {
    pub defaults: Defaults,
    pub target: BTreeMap<String, TargetPolicy>,
    pub flows: Option<FlowsPolicy>,
    /// Journal location (schema-validated), honored by the real core at
    /// configure time (see [`JournalLocation`]).
    pub journal: Option<JournalLocation>,
    /// Telemetry config (schema-validated); `otlp_endpoint` is honored by
    /// native front ends (env still wins), `console` is not yet wired — see
    /// [`TelemetryPolicy`].
    pub telemetry: Option<TelemetryPolicy>,
}

/// The per-layer config resolved for one target: target entry, else
/// `defaults.llm` for `llm:*` targets, else `defaults.outbound`.
#[derive(Debug, Clone, Default)]
pub struct ResolvedPolicy {
    pub timeout: Option<DurationMs>,
    pub retry: Option<RetryPolicy>,
    pub breaker: Option<BreakerPolicy>,
    pub rate: Option<Rate>,
    pub cache: Option<CachePolicy>,
    /// `idempotency = { header }` — the knob adapters consult to *inject* a
    /// minted idempotency key on unsafe-method calls (and to recognize a
    /// caller-supplied one). The core itself never injects; injection lives in
    /// the adapter per contracts/adapter-pack.md ("Idempotency-key injection").
    pub idempotency: Option<IdempotencyPolicy>,
    /// `poll = { interval, deadline, until }` — poll-until-terminal (CCR-3).
    pub poll: Option<PollPolicy>,
}

impl Policy {
    pub fn resolve(&self, target: &str) -> ResolvedPolicy {
        ResolvedPolicy {
            timeout: self.layer(target, |t| t.timeout.as_ref()).copied(),
            retry: self.layer(target, |t| t.retry.as_ref()).cloned(),
            breaker: self.layer(target, |t| t.breaker.as_ref()).cloned(),
            rate: self.layer(target, |t| t.rate.as_ref()).copied(),
            cache: self.layer(target, |t| t.cache.as_ref()).cloned(),
            idempotency: self.layer(target, |t| t.idempotency.as_ref()).cloned(),
            poll: self.layer(target, |t| t.poll.as_ref()).cloned(),
        }
    }

    fn layer<'a, T>(
        &'a self,
        target: &str,
        pick: impl Fn(&'a TargetPolicy) -> Option<&'a T>,
    ) -> Option<&'a T> {
        if let Some(t) = self.target.get(target)
            && let Some(v) = pick(t)
        {
            return Some(v);
        }
        if target.starts_with("llm:")
            && let Some(llm) = self.defaults.llm.as_ref()
            && let Some(v) = pick(llm)
        {
            return Some(v);
        }
        self.defaults.outbound.as_ref().and_then(pick)
    }
}

// --- outbound target resolution (SP-1) ---------------------------------
//
// Ported from the front-end duplicates `python/keel/src/keel/_targets.py`
// (the `[target]` host/URL-pattern matcher) and
// `python/keel/src/keel/adapters/_http.py` (`LLM_HOST_PROVIDERS`,
// `VERTEX_REGIONAL_SUFFIX`, `resolve_policy_target`), unified into one core
// function. The two front-end functions this replaces each had a gap the
// other didn't: the old host-only `resolve_target` never consulted the
// `[target]` pattern tier, and the old `resolve_policy_target` checked the
// LLM host map by exact host only, missing the Vertex regional-endpoint
// suffix rule. `Policy::resolve_target` below applies both on every call.
//
// Precedence, per `docs/targeting.md` (the cross-language parity contract
// with the Node twin's `judge.mjs`):
//   1. LLM host map — exact provider host, or a Vertex regional endpoint via
//      the `-aiplatform.googleapis.com` suffix rule.
//   2. Exact bare-host `[target]` key (no method/port/path/`*`).
//   3. The most specific matching host/URL pattern key: fewest `*`, then most
//      literal characters, then method-prefixed over unprefixed, then
//      lexicographically smallest key (a total, deterministic tie-break).
//   4. The bare host (falls through to `[defaults.outbound]` as before).

/// Methods the frozen targetKey grammar admits as a key prefix.
const OUTBOUND_METHODS: [&str; 7] = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"];

/// Non-outbound target classes (function + semantic targets) — never host keys.
const CLASS_PREFIXES: [&str; 6] = ["py:", "ts:", "rs:", "llm:", "tool:", "mcp:"];

/// Suffix matching any Vertex AI REGIONAL endpoint host, e.g.
/// `us-central1-aiplatform.googleapis.com`. Parity contract with the Python
/// (`adapters/_http.py`) and Node (`judge.mjs`) twins' identical suffix check.
const VERTEX_REGIONAL_SUFFIX: &str = "-aiplatform.googleapis.com";

/// Host → LLM provider. Ported verbatim from `adapters/_http.py:61-68`
/// (`LLM_HOST_PROVIDERS`) — a cross-language parity contract with the Node
/// front end (`LLM_HOST_PROVIDERS` in `judge.mjs`); extend in lockstep across
/// languages, since adding a host here changes which default pack applies.
const LLM_HOST_PROVIDERS: &[(&str, &str)] = &[
    ("api.openai.com", "openai"),
    ("api.anthropic.com", "anthropic"),
    ("generativelanguage.googleapis.com", "google-genai"),
    ("aiplatform.googleapis.com", "google-genai"),
];

/// Default port for a `:port`-less key, by scheme (parity with the Python
/// `_SCHEME_PORTS` / Node twin). `None` for anything else (or no scheme).
fn scheme_port(scheme: Option<&str>) -> Option<u16> {
    match scheme {
        Some("http") => Some(80),
        Some("https") => Some(443),
        _ => None,
    }
}

/// `*`-only wildcard match, anchored end-to-end: `*` matches any byte
/// sequence (including `.` in hosts and `/` in paths), every other byte is
/// literal. Byte-for-byte equivalent to the Python `_glob_regex` (`^` +
/// `re.escape`-parts joined by `.*` + `$`) without a regex dependency —
/// classic two-pointer wildcard matching with backtracking (correct for a
/// `*`-only alphabet: on a literal mismatch, retry the most recent `*` one
/// character further into the text).
fn glob_match(pattern: &[u8], text: &[u8]) -> bool {
    let (mut p, mut t) = (0usize, 0usize);
    let (mut star, mut mark) = (None::<usize>, 0usize);
    while t < text.len() {
        if p < pattern.len() && pattern[p] == b'*' {
            star = Some(p);
            mark = t;
            p += 1;
        } else if p < pattern.len() && pattern[p] == text[t] {
            p += 1;
            t += 1;
        } else if let Some(sp) = star {
            p = sp + 1;
            mark += 1;
            t = mark;
        } else {
            return false;
        }
    }
    while p < pattern.len() && pattern[p] == b'*' {
        p += 1;
    }
    p == pattern.len()
}

/// (method, host, port, path) parsed out of one outbound-shaped `[target]`
/// key, per the frozen grammar — mirrors `_parse_outbound_key`. `None` when
/// the key is not outbound-shaped (an empty host after stripping method/
/// port/path; defensive, since the schema validates keys before this ever
/// runs).
#[allow(clippy::type_complexity)]
fn parse_outbound_key(key: &str) -> Option<(Option<String>, String, Option<u16>, Option<String>)> {
    let mut method: Option<String> = None;
    let mut rest = key;
    for m in OUTBOUND_METHODS {
        if let Some(stripped) = rest.strip_prefix(m).and_then(|s| s.strip_prefix(' ')) {
            method = Some(m.to_owned());
            rest = stripped;
            break;
        }
    }
    let mut path: Option<String> = None;
    if let Some(slash) = rest.find('/') {
        path = Some(rest[slash..].to_owned());
        rest = &rest[..slash];
    }
    let (mut host, mut port) = (rest.to_owned(), None);
    if let Some((head, tail)) = rest.rsplit_once(':')
        && !tail.is_empty()
        && tail.bytes().all(|b| b.is_ascii_digit())
        && let Ok(n) = tail.parse::<u16>()
    {
        head.clone_into(&mut host);
        port = Some(n);
    }
    if host.is_empty() {
        return None;
    }
    Some((method, host, port, path))
}

/// True iff `key` is a bare host — an outbound-shaped key with no method
/// prefix, port, path, or `*` — the tier-1 "exact" classification `_targets.
/// compile_outbound_targets` applies once per key, used identically here for
/// both the exact-match short-circuit and excluding these keys from the
/// pattern tier.
fn is_bare_host_key(key: &str) -> bool {
    !key.contains('*')
        && parse_outbound_key(key)
            .is_some_and(|(m, _, port, path)| m.is_none() && port.is_none() && path.is_none())
}

/// One compiled pattern-tier `[target]` key. Mirrors the Python
/// `OutboundPattern` NamedTuple.
struct OutboundPattern {
    key: String,
    method: Option<String>,
    host_glob: String, // lowercased; matched with glob_match
    port: Option<u16>,
    path_glob: Option<String>,
    wildcards: usize,
    literal: usize,
}

impl Policy {
    /// The policy target key for one outbound request. See the module-level
    /// precedence comment above `OUTBOUND_METHODS` for the four tiers.
    #[must_use]
    pub fn resolve_target(
        &self,
        method: &str,
        host: &str,
        scheme: Option<&str>,
        port: Option<u16>,
        path: Option<&str>,
    ) -> String {
        // 1. LLM host map (exact host, then the Vertex regional suffix rule).
        let provider = LLM_HOST_PROVIDERS
            .iter()
            .find(|(h, _)| *h == host)
            .map(|(_, p)| *p)
            .or_else(|| {
                host.ends_with(VERTEX_REGIONAL_SUFFIX)
                    .then_some("google-genai")
            });
        if let Some(p) = provider {
            return format!("llm:{p}");
        }
        // 2. Exact bare-host [target] key.
        if !CLASS_PREFIXES.iter().any(|c| host.starts_with(c))
            && self.target.contains_key(host)
            && is_bare_host_key(host)
        {
            return host.to_owned();
        }
        // 3. Compile the pattern tier and pick the most specific match.
        let mut patterns: Vec<OutboundPattern> = Vec::new();
        for key in self.target.keys() {
            if CLASS_PREFIXES.iter().any(|c| key.starts_with(c)) || is_bare_host_key(key) {
                continue;
            }
            let Some((m, h, pt, pa)) = parse_outbound_key(key) else {
                continue;
            };
            let wildcards = key.matches('*').count();
            patterns.push(OutboundPattern {
                key: key.clone(),
                method: m,
                host_glob: h.to_lowercase(),
                port: pt,
                path_glob: pa,
                wildcards,
                literal: key.chars().count() - wildcards,
            });
        }
        // Most specific first, then a total lexicographic tail:
        // (wildcards asc, literal desc, method-prefixed first, key asc).
        patterns.sort_by(|a, b| {
            a.wildcards
                .cmp(&b.wildcards)
                .then(b.literal.cmp(&a.literal))
                .then(a.method.is_none().cmp(&b.method.is_none()))
                .then(a.key.cmp(&b.key))
        });
        let effective_port = port.or_else(|| scheme_port(scheme));
        let host_l = host.to_lowercase();
        let method_u = if method.is_empty() {
            "GET".to_owned()
        } else {
            method.to_uppercase()
        };
        let path_n = match path {
            Some(p) if !p.is_empty() => p,
            _ => "/",
        };
        for p in &patterns {
            if let Some(m) = &p.method
                && *m != method_u
            {
                continue;
            }
            if !glob_match(p.host_glob.as_bytes(), host_l.as_bytes()) {
                continue;
            }
            if let Some(pt) = p.port
                && Some(pt) != effective_port
            {
                continue;
            }
            if let Some(pg) = &p.path_glob
                && !glob_match(pg.as_bytes(), path_n.as_bytes())
            {
                continue;
            }
            return p.key.clone();
        }
        // 4. No pattern matched: fall through to the bare host.
        host.to_owned()
    }

    /// Every host the LLM host map (tier 1 of `resolve_target`'s precedence)
    /// knows about, as `(host, provider)` pairs — the enumeration twin of
    /// `resolve_target`'s single-lookup form. Not tied to any policy
    /// instance: the map is a hardcoded constant, identical for every
    /// `Policy`. Lets front-end packs' `targets()` (consumed by `keel
    /// doctor`/`keel init` documentation output) enumerate every known LLM
    /// provider host without holding their own copy (issue #49). Vertex's
    /// REGIONAL endpoints are matched by suffix (`VERTEX_REGIONAL_SUFFIX`),
    /// not enumerated here — there is no fixed list of regions to list.
    #[must_use]
    pub fn known_llm_hosts() -> Vec<(&'static str, &'static str)> {
        LLM_HOST_PROVIDERS.to_vec()
    }
}

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

    #[test]
    fn duration_literals() {
        assert_eq!("200ms".parse(), Ok(DurationMs(200)));
        assert_eq!("30s".parse(), Ok(DurationMs(30_000)));
        assert_eq!("5m".parse(), Ok(DurationMs(300_000)));
        assert_eq!("2h".parse(), Ok(DurationMs(7_200_000)));
        assert!("30".parse::<DurationMs>().is_err());
        assert!("30sec".parse::<DurationMs>().is_err());
        assert!("-1s".parse::<DurationMs>().is_err());
    }

    #[test]
    fn rate_literals() {
        let rate: Rate = "90/s".parse().unwrap();
        assert_eq!((rate.limit.get(), rate.window_ms), (90, 1_000));
        let rate: Rate = "60/min".parse().unwrap();
        assert_eq!((rate.limit.get(), rate.window_ms), (60, 60_000));
        assert!("0/s".parse::<Rate>().is_err(), "zero limit unrepresentable");
        assert!("10/day".parse::<Rate>().is_err());
    }

    #[test]
    fn schedule_exp_waits_and_cap() {
        let schedule: Schedule = "exp(1s, x2, max 4s)".parse().unwrap();
        let waits: Vec<u64> = (1..=4).map(|n| schedule.wait_ms(n)).collect();
        assert_eq!(waits, [1_000, 2_000, 4_000, 4_000]);
    }

    #[test]
    fn schedule_fixed_and_rejections() {
        assert_eq!(
            "fixed(1s)".parse::<Schedule>(),
            Ok(Schedule {
                segments: vec![ScheduleSegment {
                    primary: SchedulePrimary::Fixed { period_ms: 1_000 },
                    up_to_ms: None,
                }],
            })
        );
        assert!("linear(1s)".parse::<Schedule>().is_err());
    }

    #[test]
    fn schedule_composition_parses_the_spec_example() {
        // architecture-spec §4.1 / the frozen grammar's own example
        let schedule: Schedule = "exp(1s, x2, max 5m) upTo 10m andThen fixed(1m)"
            .parse()
            .unwrap();
        assert_eq!(
            schedule.segments,
            vec![
                ScheduleSegment {
                    primary: SchedulePrimary::Exp {
                        base_ms: 1_000,
                        factor: 2.0,
                        cap_ms: 300_000,
                        jitter: false,
                    },
                    up_to_ms: Some(600_000),
                },
                ScheduleSegment {
                    primary: SchedulePrimary::Fixed { period_ms: 60_000 },
                    up_to_ms: None,
                },
            ]
        );
        // The grammar's ws is "one or more spaces": extra spacing still parses.
        assert_eq!(
            "exp(1s, x2, max 5m)  upTo  10m  andThen  fixed(1m)".parse::<Schedule>(),
            Ok(schedule)
        );
    }

    #[test]
    fn schedule_composition_hands_off_when_the_bound_would_be_overshot() {
        let schedule: Schedule = "exp(1s, x2) upTo 4s andThen fixed(500ms)".parse().unwrap();
        let waits: Vec<u64> = (1..=5).map(|n| schedule.wait_ms(n)).collect();
        // 1s + 2s = 3s fits; the natural 4s would overshoot the 4s bound.
        assert_eq!(waits, [1_000, 2_000, 500, 500, 500]);
    }

    #[test]
    fn schedule_composition_exact_fit_stays_and_cascade_skips() {
        let schedule: Schedule =
            "fixed(1s) upTo 3s andThen fixed(10s) upTo 5s andThen fixed(250ms)"
                .parse()
                .unwrap();
        let waits: Vec<u64> = (1..=6).map(|n| schedule.wait_ms(n)).collect();
        // Three 1s waits fill upTo 3s exactly (e + w == bound stays); the 10s
        // segment's first wait exceeds its own 5s bound, so it contributes
        // zero waits and the handoff cascades to the 250ms tail.
        assert_eq!(waits, [1_000, 1_000, 1_000, 250, 250, 250]);
    }

    #[test]
    fn schedule_composition_restarts_exp_and_tracks_jitter_per_segment() {
        let schedule: Schedule = "fixed(1s) upTo 2s andThen exp(100ms, x3, jitter)"
            .parse()
            .unwrap();
        // exp restarts at local attempt 1 after the handoff.
        let waits: Vec<u64> = (1..=5).map(|n| schedule.wait_ms(n)).collect();
        assert_eq!(waits, [1_000, 1_000, 100, 300, 900]);
        // jitter is the emitting segment's flag, not schedule-global.
        assert_eq!(schedule.wait_and_jitter(1), (1_000, false));
        assert_eq!(schedule.wait_and_jitter(3), (100, true));
    }

    #[test]
    fn schedule_composition_shape_rule_rejections() {
        // Grammatical but invalid shapes fail configure-time (KEEL-E001), per
        // conformance/README.md "Schedule algebra": a non-final segment
        // without upTo never hands off; a bounded final segment would leave
        // attempts without a wait.
        for degenerate in [
            "fixed(1s) andThen fixed(2s)",
            "exp(1s, x2, max 5m) upTo 10m",
            "fixed(1s) upTo 3s andThen fixed(2s) andThen fixed(4s)",
            "fixed(1s) upTo 3s andThen fixed(2s) upTo 5s",
        ] {
            let error = degenerate.parse::<Schedule>().unwrap_err();
            assert!(
                error.to_string().contains("upTo"),
                "{degenerate}: expected the shape-rule note, got {error}"
            );
        }
        // Broken composition syntax stays a plain parse rejection.
        for broken in [
            "fixed(1s) upTo",
            "upTo 3s andThen fixed(1s)",
            "fixed(1s) upTo 1s upTo 2s andThen fixed(1s)",
            "fixed(1s) andThen",
            "andThen fixed(1s)",
            "fixed(1s) upTo 3s fixed(2s)",
        ] {
            assert!(
                broken.parse::<Schedule>().is_err(),
                "{broken} must be rejected"
            );
        }
    }

    #[test]
    fn condition_matching() {
        let on = RetryPolicy::default_on();
        let matches = |class, status| on.iter().any(|c| c.matches(class, status));
        assert!(matches(ErrorClass::Conn, None));
        assert!(matches(ErrorClass::Http, Some(429)));
        assert!(matches(ErrorClass::Http, Some(503)));
        assert!(!matches(ErrorClass::Http, Some(400)));
        assert!(!matches(ErrorClass::Cancelled, None));
        assert!("teapot".parse::<Condition>().is_err());
        // Exact-status literals follow the frozen schema grammar [1-5][0-9][0-9].
        assert_eq!("429".parse::<Condition>(), Ok(Condition::Status(429)));
        assert_eq!("100".parse::<Condition>(), Ok(Condition::Status(100)));
        assert_eq!("599".parse::<Condition>(), Ok(Condition::Status(599)));
        for bad in ["999", "099", "600", "000", "12", "1234", "1x9"] {
            assert!(bad.parse::<Condition>().is_err(), "{bad} must be rejected");
        }
    }

    #[test]
    fn zero_attempts_is_unrepresentable() {
        let doc = json!({ "target": { "x": { "retry": { "attempts": 0 } } } });
        let err = serde_path_to_error::deserialize::<_, Policy>(&doc).unwrap_err();
        assert_eq!(err.path().to_string(), "target.x.retry.attempts");
    }

    #[test]
    fn breaker_failure_rate_range_is_enforced() {
        // Frozen schema: breaker.failure_rate is exclusiveMinimum 0, maximum 1.
        let bad = |rate: serde_json::Value| {
            let doc = json!({ "target": { "x": { "breaker": { "failure_rate": rate } } } });
            serde_path_to_error::deserialize::<_, Policy>(&doc)
        };
        for rate in [json!(0.0), json!(-0.1), json!(1.5), json!(2.0)] {
            let err = bad(rate.clone()).unwrap_err();
            assert_eq!(
                err.path().to_string(),
                "target.x.breaker.failure_rate",
                "out-of-range failure_rate {rate} must fail at its path"
            );
        }
        // In-range values (0, 1] deserialize fine (paired with `window`:
        // rate mode requires both knobs).
        for rate in [0.01_f64, 0.5, 1.0] {
            let doc = json!({
                "target": { "x": { "breaker": { "window": "30s", "failure_rate": rate } } }
            });
            let policy = serde_path_to_error::deserialize::<_, Policy>(&doc).unwrap();
            let breaker = policy.target["x"].breaker.as_ref().unwrap();
            assert_eq!(breaker.failure_rate, Some(rate));
        }
    }

    #[test]
    fn breaker_mode_selection_follows_the_schema() {
        let breaker = |doc: serde_json::Value| -> BreakerPolicy {
            let doc = json!({ "target": { "x": { "breaker": doc } } });
            let policy: Policy = serde_path_to_error::deserialize(&doc).unwrap();
            policy.target["x"].breaker.clone().unwrap()
        };

        // Empty table: count mode on the schema default (failures = 5).
        assert_eq!(
            breaker(json!({})).mode(),
            BreakerMode::Count {
                failures: BreakerPolicy::DEFAULT_FAILURES
            }
        );

        // Both rate knobs, no `failures`: rate mode, min_calls defaults to 10.
        assert_eq!(
            breaker(json!({ "window": "30s", "failure_rate": 0.5 })).mode(),
            BreakerMode::Rate {
                window: DurationMs(30_000),
                failure_rate: 0.5,
                min_calls: BreakerPolicy::DEFAULT_MIN_CALLS,
            }
        );
        assert_eq!(
            breaker(json!({ "window": "10s", "failure_rate": 1.0, "min_calls": 4 })).mode(),
            BreakerMode::Rate {
                window: DurationMs(10_000),
                failure_rate: 1.0,
                min_calls: NonZeroU32::new(4).unwrap(),
            }
        );

        // "Setting `failures` selects count mode" (frozen schema): rate knobs
        // present alongside it are inert, and the policy says so.
        let mixed = breaker(json!({ "failures": 3, "window": "30s", "failure_rate": 0.5 }));
        assert_eq!(
            mixed.mode(),
            BreakerMode::Count {
                failures: NonZeroU64::new(3).unwrap()
            }
        );
        assert!(mixed.has_inert_rate_knobs());
        assert!(!breaker(json!({ "failures": 3 })).has_inert_rate_knobs());
    }

    #[test]
    fn half_configured_breaker_rate_mode_is_rejected() {
        // A rate-mode knob without both `window` and `failure_rate` (and
        // without `failures`) must fail at configure, not silently run count
        // mode the user never asked for.
        for doc in [
            json!({ "window": "30s" }),
            json!({ "failure_rate": 0.5 }),
            json!({ "min_calls": 10 }),
            json!({ "window": "30s", "min_calls": 10 }),
            json!({ "failure_rate": 0.5, "min_calls": 10 }),
        ] {
            let policy = json!({ "target": { "x": { "breaker": doc } } });
            let err = serde_path_to_error::deserialize::<_, Policy>(&policy).unwrap_err();
            assert_eq!(err.path().to_string(), "target.x.breaker", "doc: {doc}");
            assert!(
                err.inner().to_string().contains("rate mode requires both"),
                "doc {doc}: got {}",
                err.inner()
            );
        }
        // `failures` present makes any knob combination count mode (schema
        // precedence), so those documents stay valid.
        let policy =
            json!({ "target": { "x": { "breaker": { "failures": 3, "window": "30s" } } } });
        assert!(serde_path_to_error::deserialize::<_, Policy>(&policy).is_ok());
    }

    #[test]
    fn unknown_key_is_rejected_with_its_path() {
        // A typo'd nested key: the frozen schema's additionalProperties:false and
        // E001's "an unknown key was used" mean this must fail, not silently run
        // on the defaults.
        let doc = json!({ "target": { "api.stripe.com": { "retry": { "atempts": 10 } } } });
        let err = serde_path_to_error::deserialize::<_, Policy>(&doc).unwrap_err();
        assert!(
            err.inner().to_string().contains("atempts")
                || err.inner().to_string().contains("unknown field"),
            "expected an unknown-field error, got {}",
            err.inner()
        );
    }

    #[test]
    fn unknown_top_level_and_layer_keys_are_rejected() {
        assert!(
            serde_path_to_error::deserialize::<_, Policy>(&json!({ "bogus_top": true })).is_err()
        );
        assert!(
            serde_path_to_error::deserialize::<_, Policy>(
                &json!({ "target": { "api.x": { "retrys": {} } } })
            )
            .is_err(),
            "a mistyped layer table must be rejected, not dropped"
        );
    }

    #[test]
    fn journal_and_telemetry_parse_and_validate() {
        let doc = json!({
            "journal": "file:/srv/keel/journal.db",
            "telemetry": { "otlp_endpoint": "http://collector:4317" }
        });
        let policy: Policy = serde_path_to_error::deserialize(&doc).unwrap();
        assert_eq!(
            policy.journal.unwrap(),
            JournalLocation("file:/srv/keel/journal.db".to_owned())
        );
        let telemetry = policy.telemetry.unwrap();
        assert_eq!(
            telemetry.otlp_endpoint.as_deref(),
            Some("http://collector:4317")
        );
        assert!(telemetry.console, "schema default console = true");

        // A journal string that matches neither `file:` nor `postgres://` fails.
        let bad = json!({ "journal": "sqlite:/tmp/x.db" });
        assert!(serde_path_to_error::deserialize::<_, Policy>(&bad).is_err());
    }

    #[test]
    fn idempotency_resolves_like_any_other_layer() {
        // The `idempotency` layer must surface through `resolve()` so adapters
        // (via the front ends) and the engine can honor the injection contract
        // (contracts/adapter-pack.md "Idempotency-key injection").
        let doc = json!({
            "defaults": {
                "outbound": { "idempotency": { "header": "X-Idem" } },
                "llm": { "idempotency": { "header": "X-Llm-Idem" } }
            },
            "target": {
                "api.stripe.com": { "idempotency": { "header": "Idempotency-Key" } },
                "api.plain.example": { "timeout": "1s" }
            }
        });
        let policy: Policy = serde_path_to_error::deserialize(&doc).unwrap();

        // Exact target entry wins.
        let stripe = policy.resolve("api.stripe.com");
        assert_eq!(
            stripe.idempotency.as_ref().map(|i| i.header.as_str()),
            Some("Idempotency-Key")
        );
        // llm:* falls to defaults.llm, then anything else to defaults.outbound.
        let llm = policy.resolve("llm:openai");
        assert_eq!(
            llm.idempotency.as_ref().map(|i| i.header.as_str()),
            Some("X-Llm-Idem")
        );
        let plain = policy.resolve("api.plain.example");
        assert_eq!(
            plain.idempotency.as_ref().map(|i| i.header.as_str()),
            Some("X-Idem")
        );
        // No idempotency anywhere: resolves to None.
        let empty: Policy = serde_path_to_error::deserialize(&json!({})).unwrap();
        assert!(empty.resolve("api.stripe.com").idempotency.is_none());
    }

    #[test]
    fn poll_policy_parses_and_resolves() {
        let policy: Policy = serde_json::from_value(serde_json::json!({
            "target": { "api.jobs.example": { "poll": {
                "interval": "10s", "deadline": "90s",
                "until": { "field": "status", "terminal": ["completed", "failed"] }
            } } }
        }))
        .expect("valid poll policy");
        let resolved = policy.resolve("api.jobs.example");
        let poll = resolved.poll.expect("poll resolved");
        assert_eq!(poll.interval.0, 10_000);
        assert_eq!(poll.deadline.0, 90_000);
        assert_eq!(poll.until.field, "status");
        assert_eq!(poll.until.terminal, vec!["completed", "failed"]);
    }

    #[test]
    fn poll_rejects_empty_terminal_and_empty_field() {
        for bad in [
            serde_json::json!({ "interval": "10s", "deadline": "90s",
                "until": { "field": "status", "terminal": [] } }),
            serde_json::json!({ "interval": "10s", "deadline": "90s",
                "until": { "field": "", "terminal": ["done"] } }),
            serde_json::json!({ "interval": "10s",
                "until": { "field": "status", "terminal": ["done"] } }),
        ] {
            let doc = serde_json::json!({ "target": { "x": { "poll": bad } } });
            assert!(serde_json::from_value::<Policy>(doc).is_err());
        }
    }

    #[test]
    fn poll_rejects_zero_interval() {
        let doc = serde_json::json!({ "target": { "x": { "poll": {
            "interval": "0ms", "deadline": "90s",
            "until": { "field": "status", "terminal": ["done"] }
        } } } });
        assert!(serde_json::from_value::<Policy>(doc).is_err());

        let doc = serde_json::json!({ "target": { "x": { "poll": {
            "interval": "1ms", "deadline": "90s",
            "until": { "field": "status", "terminal": ["done"] }
        } } } });
        assert!(serde_json::from_value::<Policy>(doc).is_ok());
    }

    #[test]
    fn layer_resolution_precedence() {
        let doc = json!({
            "defaults": {
                "outbound": { "retry": { "attempts": 3 }, "rate": "9/s" },
                "llm": { "retry": { "attempts": 6 } }
            },
            "target": { "llm:openai": { "cache": { "ttl": "10m" } } }
        });
        let policy: Policy = serde_path_to_error::deserialize(&doc).unwrap();

        // llm:* target: cache from its own entry, retry from defaults.llm,
        // rate falls through to defaults.outbound
        let llm = policy.resolve("llm:openai");
        assert_eq!(llm.cache.unwrap().ttl, Some(DurationMs(600_000)));
        assert_eq!(llm.retry.unwrap().attempts.get(), 6);
        assert_eq!(llm.rate.unwrap().limit.get(), 9);

        // plain target: everything from defaults.outbound
        let plain = policy.resolve("api.example.com");
        assert_eq!(plain.retry.unwrap().attempts.get(), 3);
        assert!(plain.cache.is_none());
    }

    #[test]
    fn flows_on_busy_parses_with_skip_default() {
        let p: Policy = serde_json::from_value(serde_json::json!({
            "flows": { "entrypoints": ["cmd:autonomous-run"], "on_busy": "wait" }
        }))
        .unwrap();
        assert_eq!(p.flows.as_ref().unwrap().on_busy, OnBusy::Wait);
        let p: Policy = serde_json::from_value(serde_json::json!({ "flows": {} })).unwrap();
        assert_eq!(p.flows.unwrap().on_busy, OnBusy::Skip);
    }

    #[test]
    fn flows_match_cmd_rules_parse() {
        // CCR-5: `[flows.match."cmd:<name>"] argv = [...]` parses structurally
        // into the carried `match_` map (renamed from the reserved `match`).
        let p: Policy = serde_json::from_value(serde_json::json!({
            "flows": {
                "entrypoints": ["cmd:nightly-etl"],
                "match": { "cmd:nightly-etl": { "argv": ["*/run_etl.sh", "--env=prod"] } }
            }
        }))
        .unwrap();
        let flows = p.flows.unwrap();
        let rules = flows.match_.expect("match table carried");
        assert_eq!(
            rules["cmd:nightly-etl"].argv,
            vec!["*/run_etl.sh".to_owned(), "--env=prod".to_owned()]
        );
        // Absent `[flows.match]` leaves `match_` None (struct-level default).
        let p: Policy = serde_json::from_value(serde_json::json!({ "flows": {} })).unwrap();
        assert!(p.flows.unwrap().match_.is_none());
        // An unknown key inside a rule is rejected (deny_unknown_fields).
        assert!(
            serde_json::from_value::<Policy>(serde_json::json!({
                "flows": { "match": { "cmd:x": { "argv": ["a"], "bogus": 1 } } }
            }))
            .is_err()
        );
    }
}

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

    fn policy(keys: &[&str]) -> Policy {
        let mut p = Policy::default();
        for k in keys {
            p.target.insert((*k).to_owned(), TargetPolicy::default());
        }
        p
    }

    #[test]
    fn no_table_returns_bare_host() {
        assert_eq!(
            Policy::default().resolve_target("GET", "api.example.com", None, None, None),
            "api.example.com"
        );
    }
    #[test]
    fn exact_beats_pattern() {
        let p = policy(&["api.example.com", "*.example.com"]);
        assert_eq!(
            p.resolve_target("GET", "api.example.com", None, None, None),
            "api.example.com"
        );
    }
    #[test]
    fn host_wildcard_crosses_dots() {
        let p = policy(&["*.internal.corp"]);
        assert_eq!(
            p.resolve_target("GET", "a.b.internal.corp", None, None, None),
            "*.internal.corp"
        );
        assert_eq!(
            p.resolve_target("GET", "internal.corp", None, None, None),
            "internal.corp"
        );
    }
    #[test]
    fn host_is_case_insensitive() {
        let p = policy(&["*.Internal.Corp"]);
        assert_eq!(
            p.resolve_target("GET", "DB.INTERNAL.CORP", None, None, None),
            "*.Internal.Corp"
        );
    }
    #[test]
    fn path_glob_crosses_slashes_case_sensitive() {
        let p = policy(&["api.catalog.internal/*"]);
        assert_eq!(
            p.resolve_target("GET", "api.catalog.internal", None, None, Some("/a/b/c")),
            "api.catalog.internal/*"
        );
        let p2 = policy(&["api.x/A/*"]);
        assert_eq!(
            p2.resolve_target("GET", "api.x", None, None, Some("/a/y")),
            "api.x"
        );
    }
    #[test]
    fn missing_path_normalizes_to_slash() {
        let p = policy(&["api.x/*"]);
        assert_eq!(
            p.resolve_target("GET", "api.x", None, None, None),
            "api.x/*"
        );
        assert_eq!(
            p.resolve_target("GET", "api.x", None, None, Some("")),
            "api.x/*"
        );
    }
    #[test]
    fn method_prefix_must_match() {
        let p = policy(&["POST api.example.com"]);
        assert_eq!(
            p.resolve_target("GET", "api.example.com", None, None, None),
            "api.example.com"
        );
        assert_eq!(
            p.resolve_target("POST", "api.example.com", None, None, None),
            "POST api.example.com"
        );
        assert_eq!(
            p.resolve_target("post", "api.example.com", None, None, None),
            "POST api.example.com"
        );
    }
    #[test]
    fn port_uses_scheme_default() {
        let p = policy(&["api.example.com:443"]);
        assert_eq!(
            p.resolve_target("GET", "api.example.com", Some("https"), None, None),
            "api.example.com:443"
        );
        assert_eq!(
            p.resolve_target("GET", "api.example.com", Some("http"), None, None),
            "api.example.com"
        );
    }
    #[test]
    fn explicit_port_overrides_scheme() {
        let p = policy(&["api.example.com:8443"]);
        assert_eq!(
            p.resolve_target("GET", "api.example.com", Some("https"), Some(8443), None),
            "api.example.com:8443"
        );
        assert_eq!(
            p.resolve_target("GET", "api.example.com", Some("https"), Some(443), None),
            "api.example.com"
        );
    }
    #[test]
    fn most_specific_by_literal_length() {
        let p = policy(&["*.example.com", "GET api.example.com/*"]);
        assert_eq!(
            p.resolve_target("GET", "api.example.com", None, None, Some("/v1/x")),
            "GET api.example.com/*"
        );
    }
    #[test]
    fn lexicographic_tie_break_is_total() {
        let p = policy(&["api.example.com/x/*", "api.example.com/*/y"]);
        assert_eq!(
            p.resolve_target("GET", "api.example.com", None, None, Some("/x/y")),
            "api.example.com/*/y"
        );
    }
    #[test]
    fn class_prefixed_keys_are_not_hosts() {
        let p = policy(&["py:pkg.mod.fn", "llm:openai"]);
        assert_eq!(
            p.resolve_target("GET", "py:pkg.mod.fn", None, None, None),
            "py:pkg.mod.fn"
        );
    }
    #[test]
    fn llm_host_map_wins_over_patterns() {
        let p = policy(&["*.openai.com"]);
        assert_eq!(
            p.resolve_target("POST", "api.openai.com", None, None, None),
            "llm:openai"
        );
    }
    #[test]
    fn vertex_regional_suffix_maps_to_google_genai() {
        assert_eq!(
            Policy::default().resolve_target(
                "POST",
                "us-central1-aiplatform.googleapis.com",
                None,
                None,
                None
            ),
            "llm:google-genai"
        );
    }

    #[test]
    fn known_llm_hosts_matches_resolve_target_for_every_pair() {
        let hosts = Policy::known_llm_hosts();
        assert!(hosts.contains(&("api.openai.com", "openai")));
        assert!(hosts.contains(&("api.anthropic.com", "anthropic")));
        assert!(hosts.contains(&("generativelanguage.googleapis.com", "google-genai")));
        for (host, provider) in hosts {
            assert_eq!(
                Policy::default().resolve_target("GET", host, None, None, None),
                format!("llm:{provider}")
            );
        }
    }
}