pi_agent_rust 0.1.7

High-performance AI coding agent CLI - Rust port of Pi Agent
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
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
//! Error types for the Pi application.

use crate::provider_metadata::{canonical_provider_id, provider_auth_env_keys};
use std::sync::OnceLock;
use thiserror::Error;

/// Result type alias using our error type.
pub type Result<T> = std::result::Result<T, Error>;

/// Main error type for the Pi application.
#[derive(Error, Debug)]
pub enum Error {
    /// Configuration errors
    #[error("Configuration error: {0}")]
    Config(String),

    /// Session errors
    #[error("Session error: {0}")]
    Session(String),

    /// Session not found
    #[error("Session not found: {path}")]
    SessionNotFound { path: String },

    /// Provider/API errors
    #[error("Provider error: {provider}: {message}")]
    Provider { provider: String, message: String },

    /// Authentication errors
    #[error("Authentication error: {0}")]
    Auth(String),

    /// Tool execution errors
    #[error("Tool error: {tool}: {message}")]
    Tool { tool: String, message: String },

    /// Validation errors
    #[error("Validation error: {0}")]
    Validation(String),

    /// Extension errors
    #[error("Extension error: {0}")]
    Extension(String),

    /// IO errors
    #[error("IO error: {0}")]
    Io(#[from] Box<std::io::Error>),

    /// JSON errors
    #[error("JSON error: {0}")]
    Json(#[from] Box<serde_json::Error>),

    /// SQLite errors
    #[error("SQLite error: {0}")]
    Sqlite(#[from] Box<sqlmodel_core::Error>),

    /// User aborted operation
    #[error("Operation aborted")]
    Aborted,

    /// API errors (generic)
    #[error("API error: {0}")]
    Api(String),
}

/// Stable machine codes for auth/config diagnostics across provider families.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthDiagnosticCode {
    MissingApiKey,
    InvalidApiKey,
    QuotaExceeded,
    MissingOAuthAuthorizationCode,
    OAuthTokenExchangeFailed,
    OAuthTokenRefreshFailed,
    MissingAzureDeployment,
    MissingRegion,
    MissingProject,
    MissingProfile,
    MissingEndpoint,
    MissingCredentialChain,
    UnknownAuthFailure,
}

impl AuthDiagnosticCode {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::MissingApiKey => "auth.missing_api_key",
            Self::InvalidApiKey => "auth.invalid_api_key",
            Self::QuotaExceeded => "auth.quota_exceeded",
            Self::MissingOAuthAuthorizationCode => "auth.oauth.missing_authorization_code",
            Self::OAuthTokenExchangeFailed => "auth.oauth.token_exchange_failed",
            Self::OAuthTokenRefreshFailed => "auth.oauth.token_refresh_failed",
            Self::MissingAzureDeployment => "config.azure.missing_deployment",
            Self::MissingRegion => "config.auth.missing_region",
            Self::MissingProject => "config.auth.missing_project",
            Self::MissingProfile => "config.auth.missing_profile",
            Self::MissingEndpoint => "config.auth.missing_endpoint",
            Self::MissingCredentialChain => "auth.credential_chain.missing",
            Self::UnknownAuthFailure => "auth.unknown_failure",
        }
    }

    #[must_use]
    pub const fn remediation(self) -> &'static str {
        match self {
            Self::MissingApiKey => "Set the provider API key env var or run `/login <provider>`.",
            Self::InvalidApiKey => "Rotate or replace the API key and verify provider permissions.",
            Self::QuotaExceeded => {
                "Verify billing/quota limits for this API key or organization, then retry."
            }
            Self::MissingOAuthAuthorizationCode => {
                "Re-run `/login` and paste a full callback URL or authorization code."
            }
            Self::OAuthTokenExchangeFailed => {
                "Retry login flow and verify token endpoint/client configuration."
            }
            Self::OAuthTokenRefreshFailed => {
                "Re-authenticate with `/login` and confirm refresh-token validity."
            }
            Self::MissingAzureDeployment => {
                "Configure Azure resource+deployment in models.json before dispatch."
            }
            Self::MissingRegion => "Set provider region/cluster configuration before retrying.",
            Self::MissingProject => "Set provider project/workspace identifier before retrying.",
            Self::MissingProfile => "Set credential profile/source configuration before retrying.",
            Self::MissingEndpoint => "Configure provider base URL/endpoint in models.json.",
            Self::MissingCredentialChain => {
                "Configure credential-chain sources (env/profile/role) before retrying."
            }
            Self::UnknownAuthFailure => {
                "Inspect auth diagnostics and retry with explicit credentials."
            }
        }
    }

    #[must_use]
    pub const fn redaction_policy(self) -> &'static str {
        match self {
            Self::MissingApiKey
            | Self::InvalidApiKey
            | Self::QuotaExceeded
            | Self::MissingOAuthAuthorizationCode
            | Self::OAuthTokenExchangeFailed
            | Self::OAuthTokenRefreshFailed
            | Self::MissingAzureDeployment
            | Self::MissingRegion
            | Self::MissingProject
            | Self::MissingProfile
            | Self::MissingEndpoint
            | Self::MissingCredentialChain
            | Self::UnknownAuthFailure => "redact-secrets",
        }
    }
}

/// Structured auth/config diagnostic metadata for downstream tooling.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AuthDiagnostic {
    pub code: AuthDiagnosticCode,
    pub remediation: &'static str,
    pub redaction_policy: &'static str,
}

impl Error {
    /// Create a configuration error.
    pub fn config(message: impl Into<String>) -> Self {
        Self::Config(message.into())
    }

    /// Create a session error.
    pub fn session(message: impl Into<String>) -> Self {
        Self::Session(message.into())
    }

    /// Create a provider error.
    pub fn provider(provider: impl Into<String>, message: impl Into<String>) -> Self {
        Self::Provider {
            provider: provider.into(),
            message: message.into(),
        }
    }

    /// Create an authentication error.
    pub fn auth(message: impl Into<String>) -> Self {
        Self::Auth(message.into())
    }

    /// Create a tool error.
    pub fn tool(tool: impl Into<String>, message: impl Into<String>) -> Self {
        Self::Tool {
            tool: tool.into(),
            message: message.into(),
        }
    }

    /// Create a validation error.
    pub fn validation(message: impl Into<String>) -> Self {
        Self::Validation(message.into())
    }

    /// Create an extension error.
    pub fn extension(message: impl Into<String>) -> Self {
        Self::Extension(message.into())
    }

    /// Create an API error.
    pub fn api(message: impl Into<String>) -> Self {
        Self::Api(message.into())
    }

    /// Map this error to a hostcall taxonomy code.
    ///
    /// The hostcall ABI requires every error to be one of:
    /// `timeout`, `denied`, `io`, `invalid_request`, or `internal`.
    pub const fn hostcall_error_code(&self) -> &'static str {
        match self {
            Self::Validation(_) => "invalid_request",
            Self::Io(_) | Self::Session(_) | Self::SessionNotFound { .. } | Self::Sqlite(_) => "io",
            Self::Auth(_) => "denied",
            Self::Aborted => "timeout",
            Self::Json(_)
            | Self::Extension(_)
            | Self::Config(_)
            | Self::Provider { .. }
            | Self::Tool { .. }
            | Self::Api(_) => "internal",
        }
    }

    /// Stable machine-readable error category for automation and diagnostics.
    #[must_use]
    pub const fn category_code(&self) -> &'static str {
        match self {
            Self::Config(_) => "config",
            Self::Session(_) | Self::SessionNotFound { .. } => "session",
            Self::Provider { .. } => "provider",
            Self::Auth(_) => "auth",
            Self::Tool { .. } => "tool",
            Self::Validation(_) => "validation",
            Self::Extension(_) => "extension",
            Self::Io(_) => "io",
            Self::Json(_) => "json",
            Self::Sqlite(_) => "sqlite",
            Self::Aborted => "runtime",
            Self::Api(_) => "api",
        }
    }

    /// Classify auth/config errors into stable machine-readable diagnostics.
    #[must_use]
    pub fn auth_diagnostic(&self) -> Option<AuthDiagnostic> {
        match self {
            Self::Auth(message) => classify_auth_diagnostic(None, message),
            Self::Provider { provider, message } => {
                classify_auth_diagnostic(Some(provider.as_str()), message)
            }
            _ => None,
        }
    }

    /// Map internal errors to a stable, user-facing hint taxonomy.
    #[must_use]
    pub fn hints(&self) -> ErrorHints {
        let mut hints = match self {
            Self::Config(message) => config_hints(message),
            Self::Session(message) => session_hints(message),
            Self::SessionNotFound { path } => build_hints(
                "Session file not found.",
                vec![
                    "Use `pi --continue` to open the most recent session.".to_string(),
                    "Verify the path or move the session back into the sessions directory."
                        .to_string(),
                ],
                vec![("path", path.clone())],
            ),
            Self::Provider { provider, message } => provider_hints(provider, message),
            Self::Auth(message) => auth_hints(message),
            Self::Tool { tool, message } => tool_hints(tool, message),
            Self::Validation(message) => build_hints(
                "Validation failed for input or config.",
                vec![
                    "Check the specific fields mentioned in the error.".to_string(),
                    "Review CLI flags or settings for typos.".to_string(),
                ],
                vec![("details", message.clone())],
            ),
            Self::Extension(message) => build_hints(
                "Extension failed to load or run.",
                vec![
                    "Try `--no-extensions` to isolate the issue.".to_string(),
                    "Check the extension manifest and dependencies.".to_string(),
                ],
                vec![("details", message.clone())],
            ),
            Self::Io(err) => io_hints(err),
            Self::Json(err) => build_hints(
                "JSON parsing failed.",
                vec![
                    "Validate the JSON syntax (no trailing commas).".to_string(),
                    "Check that the file is UTF-8 and not truncated.".to_string(),
                ],
                vec![("details", err.to_string())],
            ),
            Self::Sqlite(err) => sqlite_hints(err),
            Self::Aborted => build_hints(
                "Operation aborted.",
                Vec::new(),
                vec![(
                    "details",
                    "Operation cancelled by user or runtime.".to_string(),
                )],
            ),
            Self::Api(message) => build_hints(
                "API request failed.",
                vec![
                    "Check your network connection and retry.".to_string(),
                    "Verify your API key and provider selection.".to_string(),
                ],
                vec![("details", message.clone())],
            ),
        };

        hints.context.push((
            "error_category".to_string(),
            self.category_code().to_string(),
        ));

        if let Some(diagnostic) = self.auth_diagnostic() {
            hints.context.push((
                "diagnostic_code".to_string(),
                diagnostic.code.as_str().to_string(),
            ));
            hints.context.push((
                "diagnostic_remediation".to_string(),
                diagnostic.remediation.to_string(),
            ));
            hints.context.push((
                "redaction_policy".to_string(),
                diagnostic.redaction_policy.to_string(),
            ));
        }

        hints
    }
}

/// Structured hints for error remediation.
#[derive(Debug, Clone)]
pub struct ErrorHints {
    /// Brief summary of the error category.
    pub summary: String,
    /// Actionable hints for the user.
    pub hints: Vec<String>,
    /// Key-value context pairs for display.
    pub context: Vec<(String, String)>,
}

fn build_hints(summary: &str, hints: Vec<String>, context: Vec<(&str, String)>) -> ErrorHints {
    ErrorHints {
        summary: summary.to_string(),
        hints,
        context: context
            .into_iter()
            .map(|(label, value)| (label.to_string(), value))
            .collect(),
    }
}

fn contains_any(haystack: &str, needles: &[&str]) -> bool {
    needles.iter().any(|needle| haystack.contains(needle))
}

const fn build_auth_diagnostic(code: AuthDiagnosticCode) -> AuthDiagnostic {
    AuthDiagnostic {
        code,
        remediation: code.remediation(),
        redaction_policy: code.redaction_policy(),
    }
}

#[allow(clippy::too_many_lines)]
fn classify_auth_diagnostic(provider: Option<&str>, message: &str) -> Option<AuthDiagnostic> {
    let lower = message.to_lowercase();
    let provider_lower = provider.map(str::to_lowercase);
    if contains_any(
        &lower,
        &[
            "missing authorization code",
            "authorization code is missing",
        ],
    ) {
        return Some(build_auth_diagnostic(
            AuthDiagnosticCode::MissingOAuthAuthorizationCode,
        ));
    }
    if contains_any(&lower, &["token exchange failed", "invalid token response"]) {
        return Some(build_auth_diagnostic(
            AuthDiagnosticCode::OAuthTokenExchangeFailed,
        ));
    }
    if contains_any(
        &lower,
        &[
            "token refresh failed",
            "oauth token refresh failed",
            "refresh token",
        ],
    ) {
        return Some(build_auth_diagnostic(
            AuthDiagnosticCode::OAuthTokenRefreshFailed,
        ));
    }
    if contains_any(
        &lower,
        &[
            "missing api key",
            "api key not configured",
            "api key is required",
            "you didn't provide an api key",
            "no api key provided",
            "missing bearer",
            "authorization header missing",
        ],
    ) {
        return Some(build_auth_diagnostic(AuthDiagnosticCode::MissingApiKey));
    }
    if contains_any(
        &lower,
        &[
            "insufficient_quota",
            "quota exceeded",
            "quota has been exceeded",
            "billing hard limit",
            "billing_not_active",
            "not enough credits",
            "credit balance is too low",
        ],
    ) {
        return Some(build_auth_diagnostic(AuthDiagnosticCode::QuotaExceeded));
    }
    if contains_any(
        &lower,
        &[
            "401",
            "unauthorized",
            "403",
            "forbidden",
            "invalid api key",
            "incorrect api key",
            "malformed api key",
            "api key is malformed",
            "revoked",
            "deactivated",
            "disabled api key",
            "expired api key",
        ],
    ) {
        return Some(build_auth_diagnostic(AuthDiagnosticCode::InvalidApiKey));
    }
    if contains_any(&lower, &["resource+deployment", "missing deployment"]) {
        return Some(build_auth_diagnostic(
            AuthDiagnosticCode::MissingAzureDeployment,
        ));
    }
    if contains_any(&lower, &["missing region", "region is required"]) {
        return Some(build_auth_diagnostic(AuthDiagnosticCode::MissingRegion));
    }
    if contains_any(&lower, &["missing project", "project is required"]) {
        return Some(build_auth_diagnostic(AuthDiagnosticCode::MissingProject));
    }
    if contains_any(&lower, &["missing profile", "profile is required"]) {
        return Some(build_auth_diagnostic(AuthDiagnosticCode::MissingProfile));
    }
    if contains_any(
        &lower,
        &[
            "missing endpoint",
            "missing base url",
            "base url is required",
        ],
    ) {
        return Some(build_auth_diagnostic(AuthDiagnosticCode::MissingEndpoint));
    }
    if contains_any(
        &lower,
        &[
            "credential chain",
            "aws_access_key_id",
            "credential source",
            "missing credentials",
        ],
    ) || provider_lower
        .as_deref()
        .is_some_and(|provider_id| provider_id.contains("bedrock") && lower.contains("credential"))
    {
        return Some(build_auth_diagnostic(
            AuthDiagnosticCode::MissingCredentialChain,
        ));
    }

    if lower.contains("oauth")
        || lower.contains("authentication")
        || lower.contains("credential")
        || lower.contains("api key")
    {
        return Some(build_auth_diagnostic(
            AuthDiagnosticCode::UnknownAuthFailure,
        ));
    }

    None
}

fn config_hints(message: &str) -> ErrorHints {
    let lower = message.to_lowercase();
    if contains_any(&lower, &["json", "parse", "serde"]) {
        return build_hints(
            "Configuration file is not valid JSON.",
            vec![
                "Fix JSON formatting in the active settings file.".to_string(),
                "Run `pi config` to see which settings file is in use.".to_string(),
            ],
            vec![("details", message.to_string())],
        );
    }
    if contains_any(&lower, &["missing", "not found", "no such file"]) {
        return build_hints(
            "Configuration file is missing.",
            vec![
                "Create `~/.pi/agent/settings.json` or set `PI_CONFIG_PATH`.".to_string(),
                "Run `pi config` to confirm the resolved path.".to_string(),
            ],
            vec![("details", message.to_string())],
        );
    }
    build_hints(
        "Configuration error.",
        vec![
            "Review your settings file for incorrect values.".to_string(),
            "Run `pi config` to verify settings precedence.".to_string(),
        ],
        vec![("details", message.to_string())],
    )
}

fn session_hints(message: &str) -> ErrorHints {
    let lower = message.to_lowercase();
    if contains_any(&lower, &["empty session file", "empty session"]) {
        return build_hints(
            "Session file is empty or corrupted.",
            vec![
                "Start a new session with `pi --no-session`.".to_string(),
                "Inspect the session file for truncation.".to_string(),
            ],
            vec![("details", message.to_string())],
        );
    }
    if contains_any(&lower, &["failed to read", "read dir", "read session"]) {
        return build_hints(
            "Failed to read session data.",
            vec![
                "Check file permissions for the sessions directory.".to_string(),
                "Verify `PI_SESSIONS_DIR` if you set it.".to_string(),
            ],
            vec![("details", message.to_string())],
        );
    }
    build_hints(
        "Session error.",
        vec![
            "Try `pi --continue` or specify `--session <path>`.".to_string(),
            "Check session file integrity in the sessions directory.".to_string(),
        ],
        vec![("details", message.to_string())],
    )
}

#[allow(clippy::too_many_lines)]
fn provider_hints(provider: &str, message: &str) -> ErrorHints {
    let lower = message.to_lowercase();
    let key_hint = provider_key_hint(provider);
    let context = vec![
        ("provider", provider.to_string()),
        ("details", message.to_string()),
    ];

    if contains_any(
        &lower,
        &[
            "missing api key",
            "you didn't provide an api key",
            "no api key provided",
            "authorization header missing",
        ],
    ) {
        return build_hints(
            "Provider API key is missing.",
            vec![
                key_hint,
                "Set the API key and retry the request.".to_string(),
            ],
            context,
        );
    }
    if contains_any(
        &lower,
        &["401", "unauthorized", "invalid api key", "api key"],
    ) {
        return build_hints(
            "Provider authentication failed.",
            vec![key_hint, "If using OAuth, run `/login` again.".to_string()],
            context,
        );
    }
    if contains_any(&lower, &["403", "forbidden"]) {
        return build_hints(
            "Provider access forbidden.",
            vec![
                "Verify the account has access to the requested model.".to_string(),
                "Check organization/project permissions for the API key.".to_string(),
            ],
            context,
        );
    }
    if contains_any(
        &lower,
        &[
            "insufficient_quota",
            "quota exceeded",
            "quota has been exceeded",
            "billing hard limit",
            "billing_not_active",
            "not enough credits",
            "credit balance is too low",
        ],
    ) {
        return build_hints(
            "Provider quota or billing limit reached.",
            vec![
                "Verify billing/credits and organization quota for this API key.".to_string(),
                key_hint,
            ],
            context,
        );
    }
    if contains_any(&lower, &["429", "rate limit", "too many requests"]) {
        return build_hints(
            "Provider rate limited the request.",
            vec![
                "Wait and retry, or reduce request rate.".to_string(),
                "Consider smaller max_tokens to lower load.".to_string(),
            ],
            context,
        );
    }
    if contains_any(&lower, &["529", "overloaded"]) {
        return build_hints(
            "Provider is overloaded.",
            vec![
                "Retry after a short delay.".to_string(),
                "Switch to a different model if available.".to_string(),
            ],
            context,
        );
    }
    if contains_any(&lower, &["timeout", "timed out"]) {
        return build_hints(
            "Provider request timed out.",
            vec![
                "Check network stability and retry.".to_string(),
                "Lower max_tokens to shorten responses.".to_string(),
            ],
            context,
        );
    }
    if contains_any(&lower, &["400", "bad request", "invalid request"]) {
        return build_hints(
            "Provider rejected the request.",
            vec![
                "Check model name, tools schema, and request size.".to_string(),
                "Reduce message size or tool payloads.".to_string(),
            ],
            context,
        );
    }
    if contains_any(&lower, &["500", "internal server error", "server error"]) {
        return build_hints(
            "Provider encountered a server error.",
            vec![
                "Retry after a short delay.".to_string(),
                "If persistent, try a different model/provider.".to_string(),
            ],
            context,
        );
    }
    build_hints(
        "Provider request failed.",
        vec![
            key_hint,
            "Check network connectivity and provider status.".to_string(),
        ],
        context,
    )
}

fn provider_key_hint(provider: &str) -> String {
    let canonical = canonical_provider_id(provider).unwrap_or(provider);
    let env_keys = provider_auth_env_keys(provider);
    if !env_keys.is_empty() {
        let key_list = env_keys
            .iter()
            .map(|key| format!("`{key}`"))
            .collect::<Vec<_>>()
            .join(" or ");
        if canonical == "anthropic" {
            return format!("Set {key_list} (or use `/login anthropic`).");
        }
        if canonical == "github-copilot" {
            return format!("Set {key_list} (or use `/login github-copilot`).");
        }
        return format!("Set {key_list} for provider `{canonical}`.");
    }

    format!("Check API key configuration for provider `{provider}`.")
}

fn auth_hints(message: &str) -> ErrorHints {
    let lower = message.to_lowercase();
    if contains_any(
        &lower,
        &["missing authorization code", "authorization code"],
    ) {
        return build_hints(
            "OAuth login did not complete.",
            vec![
                "Run `/login` again to restart the flow.".to_string(),
                "Ensure the browser redirect URL was opened.".to_string(),
            ],
            vec![("details", message.to_string())],
        );
    }
    if contains_any(&lower, &["token exchange failed", "invalid token response"]) {
        return build_hints(
            "OAuth token exchange failed.",
            vec![
                "Retry `/login` to refresh credentials.".to_string(),
                "Check network connectivity during the login flow.".to_string(),
            ],
            vec![("details", message.to_string())],
        );
    }
    build_hints(
        "Authentication error.",
        vec![
            "Verify API keys or run `/login`.".to_string(),
            "Check auth.json permissions in the Pi config directory.".to_string(),
        ],
        vec![("details", message.to_string())],
    )
}

fn tool_hints(tool: &str, message: &str) -> ErrorHints {
    let lower = message.to_lowercase();
    if contains_any(&lower, &["not found", "no such file", "command not found"]) {
        return build_hints(
            "Tool executable or target not found.",
            vec![
                "Check PATH and tool installation.".to_string(),
                "Verify the tool input path exists.".to_string(),
            ],
            vec![("tool", tool.to_string()), ("details", message.to_string())],
        );
    }
    build_hints(
        "Tool execution failed.",
        vec![
            "Check the tool output for details.".to_string(),
            "Re-run with simpler inputs to isolate the failure.".to_string(),
        ],
        vec![("tool", tool.to_string()), ("details", message.to_string())],
    )
}

fn io_hints(err: &std::io::Error) -> ErrorHints {
    let details = err.to_string();
    match err.kind() {
        std::io::ErrorKind::NotFound => build_hints(
            "Required file or directory not found.",
            vec![
                "Verify the path exists and is spelled correctly.".to_string(),
                "Check `PI_CONFIG_PATH` or `PI_SESSIONS_DIR` overrides.".to_string(),
            ],
            vec![
                ("error_kind", format!("{:?}", err.kind())),
                ("details", details),
            ],
        ),
        std::io::ErrorKind::PermissionDenied => build_hints(
            "Permission denied while accessing a file.",
            vec![
                "Check file permissions or ownership.".to_string(),
                "Try a different location with write access.".to_string(),
            ],
            vec![
                ("error_kind", format!("{:?}", err.kind())),
                ("details", details),
            ],
        ),
        std::io::ErrorKind::TimedOut => build_hints(
            "I/O operation timed out.",
            vec![
                "Check network or filesystem latency.".to_string(),
                "Retry after confirming connectivity.".to_string(),
            ],
            vec![
                ("error_kind", format!("{:?}", err.kind())),
                ("details", details),
            ],
        ),
        std::io::ErrorKind::ConnectionRefused => build_hints(
            "Connection refused.",
            vec![
                "Check network connectivity or proxy settings.".to_string(),
                "Verify the target service is reachable.".to_string(),
            ],
            vec![
                ("error_kind", format!("{:?}", err.kind())),
                ("details", details),
            ],
        ),
        _ => build_hints(
            "I/O error occurred.",
            vec![
                "Check file paths and permissions.".to_string(),
                "Retry after resolving any transient issues.".to_string(),
            ],
            vec![
                ("error_kind", format!("{:?}", err.kind())),
                ("details", details),
            ],
        ),
    }
}

fn sqlite_hints(err: &sqlmodel_core::Error) -> ErrorHints {
    let details = err.to_string();
    let lower = details.to_lowercase();
    if contains_any(&lower, &["database is locked", "busy"]) {
        return build_hints(
            "SQLite database is locked.",
            vec![
                "Close other Pi instances using the same database.".to_string(),
                "Retry once the lock clears.".to_string(),
            ],
            vec![("details", details)],
        );
    }
    build_hints(
        "SQLite error.",
        vec![
            "Ensure the database path is writable.".to_string(),
            "Check for schema or migration issues.".to_string(),
        ],
        vec![("details", details)],
    )
}

impl From<std::io::Error> for Error {
    fn from(value: std::io::Error) -> Self {
        Self::Io(Box::new(value))
    }
}

impl From<asupersync::sync::LockError> for Error {
    fn from(value: asupersync::sync::LockError) -> Self {
        match value {
            asupersync::sync::LockError::Cancelled => Self::Aborted,
            asupersync::sync::LockError::Poisoned => Self::session(value.to_string()),
        }
    }
}

impl From<serde_json::Error> for Error {
    fn from(value: serde_json::Error) -> Self {
        Self::Json(Box::new(value))
    }
}

impl From<sqlmodel_core::Error> for Error {
    fn from(value: sqlmodel_core::Error) -> Self {
        Self::Sqlite(Box::new(value))
    }
}

// ─── Context overflow detection ─────────────────────────────────────────

/// All 15 pi-mono overflow substring patterns (case-insensitive).
const OVERFLOW_PATTERNS: &[&str] = &[
    "prompt is too long",
    "input is too long for requested model",
    "exceeds the context window",
    // "input token count.*exceeds the maximum" handled by regex below
    // "maximum prompt length is \\d+" handled by regex below
    "reduce the length of the messages",
    // "maximum context length is \\d+ tokens" handled by regex below
    // "exceeds the limit of \\d+" handled by regex below
    "exceeds the available context size",
    "greater than the context length",
    "context window exceeds limit",
    "exceeded model token limit",
    // "context[_ ]length[_ ]exceeded" handled by regex below
    "too many tokens",
    "token limit exceeded",
];

static OVERFLOW_RE: OnceLock<regex::RegexSet> = OnceLock::new();
static RETRYABLE_RE: OnceLock<regex::Regex> = OnceLock::new();

/// Check whether an error message indicates the prompt exceeded the context
/// window. Matches the 15 pi-mono overflow patterns plus Cerebras/Mistral
/// status code pattern.
///
/// Also detects "silent" overflow when `usage_input_tokens` exceeds
/// `context_window`.
pub fn is_context_overflow(
    error_message: &str,
    usage_input_tokens: Option<u64>,
    context_window: Option<u32>,
) -> bool {
    // Silent overflow: usage exceeds context window.
    if let (Some(input_tokens), Some(window)) = (usage_input_tokens, context_window) {
        if input_tokens > u64::from(window) {
            return true;
        }
    }

    let lower = error_message.to_lowercase();

    // Simple substring checks.
    if OVERFLOW_PATTERNS
        .iter()
        .any(|pattern| lower.contains(pattern))
    {
        return true;
    }

    // Regex patterns for the remaining pi-mono checks.
    let re = OVERFLOW_RE.get_or_init(|| {
        regex::RegexSet::new([
            r"input token count.*exceeds the maximum",
            r"maximum prompt length is \d+",
            r"maximum context length is \d+ tokens",
            r"exceeds the limit of \d+",
            r"context[_ ]length[_ ]exceeded",
            // Cerebras/Mistral: "4XX (no body)" pattern.
            r"^4(00|13)\s*(status code)?\s*\(no body\)",
        ])
        .expect("overflow regex set")
    });

    re.is_match(&lower)
}

// ─── Retryable error classification ─────────────────────────────────────

/// Check whether an error is retryable (transient). Matches pi-mono's
/// `_isRetryableError()` logic:
///
/// 1. Error message must be non-empty.
/// 2. Must NOT be context overflow (those need compaction, not retry).
/// 3. Must match a retryable pattern (rate limit, server error, etc.).
pub fn is_retryable_error(
    error_message: &str,
    usage_input_tokens: Option<u64>,
    context_window: Option<u32>,
) -> bool {
    if error_message.is_empty() {
        return false;
    }

    // Context overflow is NOT retryable.
    if is_context_overflow(error_message, usage_input_tokens, context_window) {
        return false;
    }

    let lower = error_message.to_lowercase();

    let re = RETRYABLE_RE.get_or_init(|| {
        regex::Regex::new(
            r"overloaded|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server error|internal error|connection.?error|connection.?refused|other side closed|fetch failed|upstream.?connect|reset before headers|terminated|retry delay",
        )
        .expect("retryable regex")
    });

    re.is_match(&lower)
}

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

    fn context_value<'a>(hints: &'a ErrorHints, key: &str) -> Option<&'a str> {
        hints
            .context
            .iter()
            .find(|(k, _)| k == key)
            .map(|(_, value)| value.as_str())
    }

    // ─── Constructor tests ──────────────────────────────────────────────

    #[test]
    fn error_config_constructor() {
        let err = Error::config("bad config");
        assert!(matches!(err, Error::Config(ref msg) if msg == "bad config"));
    }

    #[test]
    fn error_session_constructor() {
        let err = Error::session("session corrupted");
        assert!(matches!(err, Error::Session(ref msg) if msg == "session corrupted"));
    }

    #[test]
    fn error_provider_constructor() {
        let err = Error::provider("anthropic", "timeout");
        assert!(matches!(err, Error::Provider { ref provider, ref message }
            if provider == "anthropic" && message == "timeout"));
    }

    #[test]
    fn error_auth_constructor() {
        let err = Error::auth("missing key");
        assert!(matches!(err, Error::Auth(ref msg) if msg == "missing key"));
    }

    #[test]
    fn error_tool_constructor() {
        let err = Error::tool("bash", "exit code 1");
        assert!(matches!(err, Error::Tool { ref tool, ref message }
            if tool == "bash" && message == "exit code 1"));
    }

    #[test]
    fn error_validation_constructor() {
        let err = Error::validation("field required");
        assert!(matches!(err, Error::Validation(ref msg) if msg == "field required"));
    }

    #[test]
    fn error_extension_constructor() {
        let err = Error::extension("manifest invalid");
        assert!(matches!(err, Error::Extension(ref msg) if msg == "manifest invalid"));
    }

    #[test]
    fn error_api_constructor() {
        let err = Error::api("404 not found");
        assert!(matches!(err, Error::Api(ref msg) if msg == "404 not found"));
    }

    #[test]
    fn error_category_code_is_stable() {
        assert_eq!(Error::auth("missing").category_code(), "auth");
        assert_eq!(Error::provider("openai", "429").category_code(), "provider");
        assert_eq!(Error::tool("bash", "failed").category_code(), "tool");
        assert_eq!(Error::Aborted.category_code(), "runtime");
    }

    #[test]
    fn hints_include_error_category_context() {
        let hints = Error::tool("bash", "exit code 1").hints();
        assert_eq!(context_value(&hints, "error_category"), Some("tool"));
    }

    // ─── Display message tests ──────────────────────────────────────────

    #[test]
    fn error_config_display() {
        let err = Error::config("missing settings.json");
        let msg = err.to_string();
        assert!(msg.contains("Configuration error"));
        assert!(msg.contains("missing settings.json"));
    }

    #[test]
    fn error_session_display() {
        let err = Error::session("tree corrupted");
        let msg = err.to_string();
        assert!(msg.contains("Session error"));
        assert!(msg.contains("tree corrupted"));
    }

    #[test]
    fn error_session_not_found_display() {
        let err = Error::SessionNotFound {
            path: "/home/user/.pi/sessions/abc.jsonl".to_string(),
        };
        let msg = err.to_string();
        assert!(msg.contains("Session not found"));
        assert!(msg.contains("/home/user/.pi/sessions/abc.jsonl"));
    }

    #[test]
    fn error_provider_display() {
        let err = Error::provider("openai", "429 too many requests");
        let msg = err.to_string();
        assert!(msg.contains("Provider error"));
        assert!(msg.contains("openai"));
        assert!(msg.contains("429 too many requests"));
    }

    #[test]
    fn error_auth_display() {
        let err = Error::auth("API key expired");
        let msg = err.to_string();
        assert!(msg.contains("Authentication error"));
        assert!(msg.contains("API key expired"));
    }

    #[test]
    fn error_tool_display() {
        let err = Error::tool("read", "file not found: /tmp/x.txt");
        let msg = err.to_string();
        assert!(msg.contains("Tool error"));
        assert!(msg.contains("read"));
        assert!(msg.contains("file not found: /tmp/x.txt"));
    }

    #[test]
    fn error_validation_display() {
        let err = Error::validation("temperature must be 0-2");
        let msg = err.to_string();
        assert!(msg.contains("Validation error"));
        assert!(msg.contains("temperature must be 0-2"));
    }

    #[test]
    fn error_extension_display() {
        let err = Error::extension("manifest parse failed");
        let msg = err.to_string();
        assert!(msg.contains("Extension error"));
        assert!(msg.contains("manifest parse failed"));
    }

    #[test]
    fn error_aborted_display() {
        let err = Error::Aborted;
        let msg = err.to_string();
        assert!(msg.contains("Operation aborted"));
    }

    #[test]
    fn error_api_display() {
        let err = Error::api("GitHub API error 403");
        let msg = err.to_string();
        assert!(msg.contains("API error"));
        assert!(msg.contains("GitHub API error 403"));
    }

    #[test]
    fn error_io_display() {
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "no such file");
        let err = Error::from(io_err);
        let msg = err.to_string();
        assert!(msg.contains("IO error"));
    }

    #[test]
    fn error_json_display() {
        let json_err = serde_json::from_str::<serde_json::Value>("not json").unwrap_err();
        let err = Error::from(json_err);
        let msg = err.to_string();
        assert!(msg.contains("JSON error"));
    }

    // ─── From impls ─────────────────────────────────────────────────────

    #[test]
    fn error_from_io_error() {
        let io_err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "access denied");
        let err: Error = io_err.into();
        assert!(matches!(err, Error::Io(_)));
    }

    #[test]
    fn error_from_serde_json_error() {
        let json_err = serde_json::from_str::<serde_json::Value>("{invalid").unwrap_err();
        let err: Error = json_err.into();
        assert!(matches!(err, Error::Json(_)));
    }

    // ─── Hints method tests (error.rs hints) ────────────────────────────

    #[test]
    fn hints_config_json_parse_error() {
        let err = Error::config("JSON parse error in settings.json");
        let h = err.hints();
        assert!(h.summary.contains("not valid JSON"));
        assert!(h.hints.iter().any(|s| s.contains("JSON formatting")));
    }

    #[test]
    fn hints_config_missing_file() {
        let err = Error::config("config file not found: ~/.pi/settings");
        let h = err.hints();
        assert!(h.summary.contains("missing"));
    }

    #[test]
    fn hints_config_generic() {
        let err = Error::config("unknown config issue");
        let h = err.hints();
        assert!(h.summary.contains("Configuration error"));
    }

    #[test]
    fn hints_session_empty() {
        let err = Error::session("empty session file");
        let h = err.hints();
        assert!(h.summary.contains("empty") || h.summary.contains("corrupted"));
    }

    #[test]
    fn hints_session_read_failure() {
        let err = Error::session("failed to read session directory");
        let h = err.hints();
        assert!(h.summary.contains("Failed to read"));
    }

    #[test]
    fn hints_session_not_found() {
        let err = Error::SessionNotFound {
            path: "/tmp/session.jsonl".to_string(),
        };
        let h = err.hints();
        assert!(h.summary.contains("not found"));
        assert!(
            h.context
                .iter()
                .any(|(k, v)| k == "path" && v.contains("/tmp/session.jsonl"))
        );
    }

    #[test]
    fn hints_provider_401() {
        let err = Error::provider("anthropic", "HTTP 401 unauthorized");
        let h = err.hints();
        assert!(h.summary.contains("authentication failed"));
        assert!(h.hints.iter().any(|s| s.contains("ANTHROPIC_API_KEY")));
    }

    #[test]
    fn hints_provider_403() {
        let err = Error::provider("openai", "403 forbidden");
        let h = err.hints();
        assert!(h.summary.contains("forbidden"));
    }

    #[test]
    fn hints_provider_429() {
        let err = Error::provider("anthropic", "429 rate limit");
        let h = err.hints();
        assert!(h.summary.contains("rate limited"));
    }

    #[test]
    fn hints_provider_529() {
        let err = Error::provider("anthropic", "529 overloaded");
        let h = err.hints();
        assert!(h.summary.contains("overloaded"));
    }

    #[test]
    fn hints_provider_timeout() {
        let err = Error::provider("openai", "request timed out");
        let h = err.hints();
        assert!(h.summary.contains("timed out"));
    }

    #[test]
    fn hints_provider_400() {
        let err = Error::provider("gemini", "400 bad request");
        let h = err.hints();
        assert!(h.summary.contains("rejected"));
    }

    #[test]
    fn hints_provider_500() {
        let err = Error::provider("cohere", "500 internal server error");
        let h = err.hints();
        assert!(h.summary.contains("server error"));
    }

    #[test]
    fn hints_provider_generic() {
        let err = Error::provider("custom", "unknown issue");
        let h = err.hints();
        assert!(h.summary.contains("failed"));
        assert!(h.context.iter().any(|(k, _)| k == "provider"));
    }

    #[test]
    fn hints_provider_key_hint_openai() {
        let err = Error::provider("openai", "401 invalid api key");
        let h = err.hints();
        assert!(h.hints.iter().any(|s| s.contains("OPENAI_API_KEY")));
    }

    #[test]
    fn hints_provider_key_hint_gemini() {
        let err = Error::provider("gemini", "401 api key invalid");
        let h = err.hints();
        assert!(h.hints.iter().any(|s| s.contains("GOOGLE_API_KEY")));
    }

    #[test]
    fn hints_provider_key_hint_openrouter() {
        let err = Error::provider("openrouter", "401 unauthorized");
        let h = err.hints();
        assert!(h.hints.iter().any(|s| s.contains("OPENROUTER_API_KEY")));
    }

    #[test]
    fn hints_provider_key_hint_groq() {
        let err = Error::provider("groq", "401 unauthorized");
        let h = err.hints();
        assert!(h.hints.iter().any(|s| s.contains("GROQ_API_KEY")));
    }

    #[test]
    fn hints_provider_key_hint_alias_dashscope() {
        let err = Error::provider("dashscope", "401 invalid api key");
        let h = err.hints();
        assert!(h.hints.iter().any(|s| s.contains("DASHSCOPE_API_KEY")));
        assert!(h.hints.iter().any(|s| s.contains("QWEN_API_KEY")));
    }

    #[test]
    fn hints_provider_key_hint_alias_kimi() {
        let err = Error::provider("kimi", "401 invalid api key");
        let h = err.hints();
        assert!(h.hints.iter().any(|s| s.contains("MOONSHOT_API_KEY")));
        assert!(h.hints.iter().any(|s| s.contains("KIMI_API_KEY")));
    }

    #[test]
    fn hints_provider_key_hint_azure() {
        let err = Error::provider("azure-openai", "401 unauthorized");
        let h = err.hints();
        assert!(h.hints.iter().any(|s| s.contains("AZURE_OPENAI_API_KEY")));
    }

    #[test]
    fn hints_provider_key_hint_unknown() {
        let err = Error::provider("my-proxy", "401 unauthorized");
        let h = err.hints();
        assert!(h.hints.iter().any(|s| s.contains("my-proxy")));
    }

    #[test]
    fn hints_auth_authorization_code() {
        let err = Error::auth("missing authorization code");
        let h = err.hints();
        assert!(h.summary.contains("OAuth"));
    }

    #[test]
    fn hints_auth_token_exchange() {
        let err = Error::auth("token exchange failed");
        let h = err.hints();
        assert!(h.summary.contains("token exchange"));
    }

    #[test]
    fn hints_auth_generic() {
        let err = Error::auth("unknown auth issue");
        let h = err.hints();
        assert!(h.summary.contains("Authentication error"));
    }

    #[test]
    fn auth_diagnostic_provider_invalid_key_code_and_context() {
        let err = Error::provider("openai", "HTTP 401 unauthorized");
        let diagnostic = err.auth_diagnostic().expect("diagnostic should be present");
        assert_eq!(diagnostic.code, AuthDiagnosticCode::InvalidApiKey);
        assert_eq!(diagnostic.code.as_str(), "auth.invalid_api_key");
        assert_eq!(diagnostic.redaction_policy, "redact-secrets");

        let hints = err.hints();
        assert_eq!(
            context_value(&hints, "diagnostic_code"),
            Some("auth.invalid_api_key")
        );
        assert_eq!(
            context_value(&hints, "redaction_policy"),
            Some("redact-secrets")
        );
    }

    #[test]
    fn auth_diagnostic_missing_key_phrase_for_oai_provider() {
        let err = Error::provider(
            "openrouter",
            "You didn't provide an API key in the Authorization header",
        );
        let diagnostic = err.auth_diagnostic().expect("diagnostic should be present");
        assert_eq!(diagnostic.code, AuthDiagnosticCode::MissingApiKey);
        assert_eq!(diagnostic.code.as_str(), "auth.missing_api_key");
    }

    #[test]
    fn auth_diagnostic_revoked_key_maps_invalid() {
        let err = Error::provider("deepseek", "API key revoked for this project");
        let diagnostic = err.auth_diagnostic().expect("diagnostic should be present");
        assert_eq!(diagnostic.code, AuthDiagnosticCode::InvalidApiKey);
        assert_eq!(diagnostic.code.as_str(), "auth.invalid_api_key");
    }

    #[test]
    fn auth_diagnostic_quota_exceeded_code_and_context() {
        let err = Error::provider(
            "openai",
            "HTTP 429 insufficient_quota: You exceeded your current quota",
        );
        let diagnostic = err.auth_diagnostic().expect("diagnostic should be present");
        assert_eq!(diagnostic.code, AuthDiagnosticCode::QuotaExceeded);
        assert_eq!(diagnostic.code.as_str(), "auth.quota_exceeded");
        assert_eq!(
            diagnostic.remediation,
            "Verify billing/quota limits for this API key or organization, then retry."
        );

        let hints = err.hints();
        assert_eq!(
            context_value(&hints, "diagnostic_code"),
            Some("auth.quota_exceeded")
        );
        assert!(
            hints
                .hints
                .iter()
                .any(|s| s.contains("billing") || s.contains("quota")),
            "quota/billing guidance should be present"
        );
    }

    #[test]
    fn auth_diagnostic_oauth_exchange_failure_code() {
        let err = Error::auth("Token exchange failed: invalid_grant");
        let diagnostic = err.auth_diagnostic().expect("diagnostic should be present");
        assert_eq!(
            diagnostic.code,
            AuthDiagnosticCode::OAuthTokenExchangeFailed
        );
        assert_eq!(
            diagnostic.remediation,
            "Retry login flow and verify token endpoint/client configuration."
        );

        let hints = err.hints();
        assert_eq!(
            context_value(&hints, "diagnostic_code"),
            Some("auth.oauth.token_exchange_failed")
        );
    }

    #[test]
    fn auth_diagnostic_azure_missing_deployment_code() {
        let err = Error::provider(
            "azure-openai",
            "Azure OpenAI provider requires resource+deployment; configure via models.json",
        );
        let diagnostic = err.auth_diagnostic().expect("diagnostic should be present");
        assert_eq!(diagnostic.code, AuthDiagnosticCode::MissingAzureDeployment);
        assert_eq!(diagnostic.code.as_str(), "config.azure.missing_deployment");
    }

    #[test]
    fn auth_diagnostic_bedrock_missing_credential_chain_code() {
        let err = Error::provider(
            "amazon-bedrock",
            "AWS credential chain not configured for provider",
        );
        let diagnostic = err.auth_diagnostic().expect("diagnostic should be present");
        assert_eq!(diagnostic.code, AuthDiagnosticCode::MissingCredentialChain);
        assert_eq!(diagnostic.code.as_str(), "auth.credential_chain.missing");
    }

    #[test]
    fn auth_diagnostic_absent_for_non_auth_provider_error() {
        let err = Error::provider("anthropic", "429 rate limit");
        assert!(err.auth_diagnostic().is_none());

        let hints = err.hints();
        assert!(context_value(&hints, "diagnostic_code").is_none());
    }

    // ── Native provider diagnostic integration tests ─────────────────
    // Verify that actual provider error messages (as emitted by providers/*.rs
    // after the Error::config→Error::provider migration) are correctly classified
    // by the diagnostic taxonomy.

    #[test]
    fn native_provider_missing_key_anthropic() {
        let err = Error::provider(
            "anthropic",
            "Missing API key for Anthropic. Set ANTHROPIC_API_KEY or use `pi auth`.",
        );
        let d = err.auth_diagnostic().expect("diagnostic");
        assert_eq!(d.code, AuthDiagnosticCode::MissingApiKey);
        let hints = err.hints();
        assert_eq!(context_value(&hints, "provider"), Some("anthropic"));
        assert!(
            hints.summary.contains("missing"),
            "summary: {}",
            hints.summary
        );
    }

    #[test]
    fn native_provider_missing_key_openai() {
        let err = Error::provider(
            "openai",
            "Missing API key for OpenAI. Set OPENAI_API_KEY or configure in settings.",
        );
        let d = err.auth_diagnostic().expect("diagnostic");
        assert_eq!(d.code, AuthDiagnosticCode::MissingApiKey);
    }

    #[test]
    fn native_provider_missing_key_azure() {
        let err = Error::provider(
            "azure-openai",
            "Missing API key for Azure OpenAI. Set AZURE_OPENAI_API_KEY or configure in settings.",
        );
        let d = err.auth_diagnostic().expect("diagnostic");
        assert_eq!(d.code, AuthDiagnosticCode::MissingApiKey);
    }

    #[test]
    fn native_provider_missing_key_cohere() {
        let err = Error::provider(
            "cohere",
            "Missing API key for Cohere. Set COHERE_API_KEY or configure in settings.",
        );
        let d = err.auth_diagnostic().expect("diagnostic");
        assert_eq!(d.code, AuthDiagnosticCode::MissingApiKey);
    }

    #[test]
    fn native_provider_missing_key_gemini() {
        let err = Error::provider(
            "google",
            "Missing API key for Google/Gemini. Set GOOGLE_API_KEY or GEMINI_API_KEY.",
        );
        let d = err.auth_diagnostic().expect("diagnostic");
        assert_eq!(d.code, AuthDiagnosticCode::MissingApiKey);
    }

    #[test]
    fn native_provider_http_401_anthropic() {
        let err = Error::provider(
            "anthropic",
            "Anthropic API error (HTTP 401): {\"error\":{\"type\":\"authentication_error\"}}",
        );
        let d = err.auth_diagnostic().expect("diagnostic");
        assert_eq!(d.code, AuthDiagnosticCode::InvalidApiKey);
        let hints = err.hints();
        assert!(hints.summary.contains("authentication failed"));
    }

    #[test]
    fn native_provider_http_401_openai() {
        let err = Error::provider(
            "openai",
            "OpenAI API error (HTTP 401): Incorrect API key provided",
        );
        let d = err.auth_diagnostic().expect("diagnostic");
        assert_eq!(d.code, AuthDiagnosticCode::InvalidApiKey);
    }

    #[test]
    fn native_provider_http_403_azure() {
        let err = Error::provider(
            "azure-openai",
            "Azure OpenAI API error (HTTP 403): Access denied",
        );
        let d = err.auth_diagnostic().expect("diagnostic");
        assert_eq!(d.code, AuthDiagnosticCode::InvalidApiKey);
    }

    #[test]
    fn native_provider_http_429_quota_openai() {
        let err = Error::provider("openai", "OpenAI API error (HTTP 429): insufficient_quota");
        let d = err.auth_diagnostic().expect("diagnostic");
        assert_eq!(d.code, AuthDiagnosticCode::QuotaExceeded);
    }

    #[test]
    fn native_provider_http_500_no_diagnostic() {
        // Non-auth HTTP errors should NOT produce auth diagnostics.
        let err = Error::provider(
            "anthropic",
            "Anthropic API error (HTTP 500): Internal server error",
        );
        assert!(err.auth_diagnostic().is_none());
    }

    #[test]
    fn native_provider_hints_include_provider_context() {
        let err = Error::provider("cohere", "Cohere API error (HTTP 401): unauthorized");
        let hints = err.hints();
        assert_eq!(context_value(&hints, "provider"), Some("cohere"));
        assert!(context_value(&hints, "details").is_some());
    }

    #[test]
    fn native_provider_diagnostic_enriches_hints_context() {
        let err = Error::provider(
            "google",
            "Missing API key for Google/Gemini. Set GOOGLE_API_KEY or GEMINI_API_KEY.",
        );
        let hints = err.hints();
        assert_eq!(
            context_value(&hints, "diagnostic_code"),
            Some("auth.missing_api_key")
        );
        assert_eq!(
            context_value(&hints, "redaction_policy"),
            Some("redact-secrets")
        );
        assert!(context_value(&hints, "diagnostic_remediation").is_some());
    }

    #[test]
    fn hints_tool_not_found() {
        let err = Error::tool("bash", "command not found: xyz");
        let h = err.hints();
        assert!(h.summary.contains("not found"));
    }

    #[test]
    fn hints_tool_generic() {
        let err = Error::tool("read", "unexpected error");
        let h = err.hints();
        assert!(h.summary.contains("execution failed"));
    }

    #[test]
    fn hints_validation() {
        let err = Error::validation("invalid input");
        let h = err.hints();
        assert!(h.summary.contains("Validation"));
    }

    #[test]
    fn hints_extension() {
        let err = Error::extension("load error");
        let h = err.hints();
        assert!(h.summary.contains("Extension"));
    }

    #[test]
    fn hints_io_not_found() {
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "no such file");
        let err = Error::from(io_err);
        let h = err.hints();
        assert!(h.summary.contains("not found"));
    }

    #[test]
    fn hints_io_permission_denied() {
        let io_err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied");
        let err = Error::from(io_err);
        let h = err.hints();
        assert!(h.summary.contains("Permission denied"));
    }

    #[test]
    fn hints_io_timed_out() {
        let io_err = std::io::Error::new(std::io::ErrorKind::TimedOut, "timed out");
        let err = Error::from(io_err);
        let h = err.hints();
        assert!(h.summary.contains("timed out"));
    }

    #[test]
    fn hints_io_connection_refused() {
        let io_err = std::io::Error::new(std::io::ErrorKind::ConnectionRefused, "refused");
        let err = Error::from(io_err);
        let h = err.hints();
        assert!(h.summary.contains("Connection refused"));
    }

    #[test]
    fn hints_io_generic() {
        let io_err = std::io::Error::other("something");
        let err = Error::from(io_err);
        let h = err.hints();
        assert!(h.summary.contains("I/O error"));
    }

    #[test]
    fn hints_json() {
        let json_err = serde_json::from_str::<serde_json::Value>("broken").unwrap_err();
        let err = Error::from(json_err);
        let h = err.hints();
        assert!(h.summary.contains("JSON"));
    }

    #[test]
    fn hints_aborted() {
        let err = Error::Aborted;
        let h = err.hints();
        assert!(h.summary.contains("aborted"));
    }

    #[test]
    fn hints_api() {
        let err = Error::api("connection reset");
        let h = err.hints();
        assert!(h.summary.contains("API"));
    }

    // ── E2E cross-provider diagnostic validation ────────────────────

    /// Every provider family's *actual* error message must produce the correct
    /// `AuthDiagnosticCode`. This matrix validates classifier + message alignment.
    #[test]
    fn e2e_all_native_providers_missing_key_diagnostic() {
        let cases: &[(&str, &str)] = &[
            (
                "anthropic",
                "Missing API key for Anthropic. Set ANTHROPIC_API_KEY or use `pi auth`.",
            ),
            (
                "openai",
                "Missing API key for OpenAI. Set OPENAI_API_KEY or configure in settings.",
            ),
            (
                "azure-openai",
                "Missing API key for Azure OpenAI. Set AZURE_OPENAI_API_KEY or configure in settings.",
            ),
            (
                "cohere",
                "Missing API key for Cohere. Set COHERE_API_KEY or configure in settings.",
            ),
            (
                "google",
                "Missing API key for Google/Gemini. Set GOOGLE_API_KEY or GEMINI_API_KEY.",
            ),
        ];
        for (provider, message) in cases {
            let err = Error::provider(*provider, *message);
            let d = err
                .auth_diagnostic()
                .unwrap_or_else(|| panic!("expected MissingApiKey diagnostic for {provider}"));
            assert_eq!(
                d.code,
                AuthDiagnosticCode::MissingApiKey,
                "wrong code for {provider}: {:?}",
                d.code
            );
        }
    }

    #[test]
    fn e2e_all_native_providers_401_diagnostic() {
        let cases: &[(&str, &str)] = &[
            (
                "anthropic",
                "Anthropic API error (HTTP 401): invalid x-api-key",
            ),
            (
                "openai",
                "OpenAI API error (HTTP 401): Incorrect API key provided",
            ),
            (
                "azure-openai",
                "Azure OpenAI API error (HTTP 401): unauthorized",
            ),
            ("cohere", "Cohere API error (HTTP 401): unauthorized"),
            ("google", "Gemini API error (HTTP 401): API key not valid"),
        ];
        for (provider, message) in cases {
            let err = Error::provider(*provider, *message);
            let d = err
                .auth_diagnostic()
                .unwrap_or_else(|| panic!("expected InvalidApiKey diagnostic for {provider}"));
            assert_eq!(
                d.code,
                AuthDiagnosticCode::InvalidApiKey,
                "wrong code for {provider}: {:?}",
                d.code
            );
        }
    }

    /// Non-auth HTTP errors (5xx) must NOT produce auth diagnostics.
    #[test]
    fn e2e_non_auth_errors_no_diagnostic() {
        let cases: &[(&str, &str)] = &[
            (
                "anthropic",
                "Anthropic API error (HTTP 500): Internal server error",
            ),
            ("openai", "OpenAI API error (HTTP 503): Service unavailable"),
            ("google", "Gemini API error (HTTP 502): Bad gateway"),
            ("cohere", "Cohere API error (HTTP 504): Gateway timeout"),
        ];
        for (provider, message) in cases {
            let err = Error::provider(*provider, *message);
            assert!(
                err.auth_diagnostic().is_none(),
                "unexpected diagnostic for {provider} with message: {message}"
            );
        }
    }

    /// All auth diagnostics must carry the `redact-secrets` redaction policy.
    #[test]
    fn e2e_all_diagnostic_codes_have_redact_secrets_policy() {
        let codes = [
            AuthDiagnosticCode::MissingApiKey,
            AuthDiagnosticCode::InvalidApiKey,
            AuthDiagnosticCode::QuotaExceeded,
            AuthDiagnosticCode::MissingOAuthAuthorizationCode,
            AuthDiagnosticCode::OAuthTokenExchangeFailed,
            AuthDiagnosticCode::OAuthTokenRefreshFailed,
            AuthDiagnosticCode::MissingAzureDeployment,
            AuthDiagnosticCode::MissingRegion,
            AuthDiagnosticCode::MissingProject,
            AuthDiagnosticCode::MissingProfile,
            AuthDiagnosticCode::MissingEndpoint,
            AuthDiagnosticCode::MissingCredentialChain,
            AuthDiagnosticCode::UnknownAuthFailure,
        ];
        for code in &codes {
            assert_eq!(
                code.redaction_policy(),
                "redact-secrets",
                "code {code:?} missing redact-secrets policy",
            );
        }
    }

    /// `hints()` must always include diagnostic enrichment when auth diagnostics
    /// are present, and the enrichment must include code + remediation + policy.
    #[test]
    fn e2e_hints_enrichment_completeness() {
        let providers: &[(&str, &str)] = &[
            ("anthropic", "Missing API key for Anthropic"),
            ("openai", "OpenAI API error (HTTP 401): invalid key"),
            ("cohere", "insufficient_quota"),
            ("google", "Missing API key for Google"),
        ];
        for (provider, message) in providers {
            let err = Error::provider(*provider, *message);
            let hints = err.hints();
            assert!(
                context_value(&hints, "diagnostic_code").is_some(),
                "missing diagnostic_code for {provider}"
            );
            assert!(
                context_value(&hints, "diagnostic_remediation").is_some(),
                "missing diagnostic_remediation for {provider}"
            );
            assert_eq!(
                context_value(&hints, "redaction_policy"),
                Some("redact-secrets"),
                "wrong redaction_policy for {provider}"
            );
        }
    }

    /// Provider context must always appear in hints for provider errors.
    #[test]
    fn e2e_hints_always_include_provider_context() {
        let providers = [
            "anthropic",
            "openai",
            "azure-openai",
            "cohere",
            "google",
            "groq",
            "deepseek",
        ];
        for provider in &providers {
            let err = Error::provider(*provider, "some error");
            let hints = err.hints();
            assert_eq!(
                context_value(&hints, "provider"),
                Some(*provider),
                "missing provider context for {provider}"
            );
        }
    }

    /// Provider aliases must produce the same env key hints as canonical IDs.
    #[test]
    fn e2e_alias_env_key_consistency() {
        let alias_to_canonical: &[(&str, &str)] = &[
            ("gemini", "google"),
            ("azure", "azure-openai"),
            ("copilot", "github-copilot"),
            ("dashscope", "alibaba"),
            ("qwen", "alibaba"),
            ("kimi", "moonshotai"),
            ("moonshot", "moonshotai"),
            ("bedrock", "amazon-bedrock"),
            ("sap", "sap-ai-core"),
        ];
        for (alias, canonical) in alias_to_canonical {
            let alias_keys = crate::provider_metadata::provider_auth_env_keys(alias);
            let canonical_keys = crate::provider_metadata::provider_auth_env_keys(canonical);
            assert_eq!(
                alias_keys, canonical_keys,
                "alias {alias} env keys differ from canonical {canonical}"
            );
        }
    }

    /// Every native provider's env key list must be non-empty.
    #[test]
    fn e2e_all_native_providers_have_env_keys() {
        let native_providers = [
            "anthropic",
            "openai",
            "google",
            "cohere",
            "azure-openai",
            "amazon-bedrock",
            "github-copilot",
            "sap-ai-core",
        ];
        for provider in &native_providers {
            let keys = crate::provider_metadata::provider_auth_env_keys(provider);
            assert!(!keys.is_empty(), "provider {provider} has no auth env keys");
        }
    }

    /// Error messages must never contain raw API key values. This test verifies
    /// that provider error constructors don't embed secrets.
    #[test]
    fn e2e_error_messages_never_contain_secrets() {
        let fake_key = "sk-proj-FAKE123456789abcdef";
        // Construct errors the way providers do (from HTTP responses, not from keys).
        let err1 = Error::provider("openai", "OpenAI API error (HTTP 401): Invalid API key");
        let err2 = Error::provider("anthropic", "Missing API key for Anthropic");
        let err3 = Error::auth("OAuth token exchange failed");

        for err in [&err1, &err2, &err3] {
            let display = err.to_string();
            assert!(
                !display.contains(fake_key),
                "error message contains secret: {display}"
            );
            let hints = err.hints();
            for hint in &hints.hints {
                assert!(!hint.contains(fake_key), "hint contains secret: {hint}");
            }
            for (key, value) in &hints.context {
                assert!(
                    !value.contains(fake_key),
                    "context {key} contains secret: {value}"
                );
            }
        }
    }

    /// Bedrock credential-chain special handling: "credential" in message +
    /// "bedrock" in provider must produce `MissingCredentialChain`.
    #[test]
    fn e2e_bedrock_credential_chain_diagnostic() {
        let err = Error::provider("amazon-bedrock", "No credential source configured");
        let d = err
            .auth_diagnostic()
            .expect("expected credential chain diagnostic");
        assert_eq!(d.code, AuthDiagnosticCode::MissingCredentialChain);
    }

    /// Auth errors (not provider errors) must also produce diagnostics.
    #[test]
    fn e2e_auth_variant_diagnostics() {
        let cases: &[(&str, AuthDiagnosticCode)] = &[
            ("Missing API key", AuthDiagnosticCode::MissingApiKey),
            ("401 unauthorized", AuthDiagnosticCode::InvalidApiKey),
            ("insufficient_quota", AuthDiagnosticCode::QuotaExceeded),
            (
                "Missing authorization code",
                AuthDiagnosticCode::MissingOAuthAuthorizationCode,
            ),
            (
                "Token exchange failed",
                AuthDiagnosticCode::OAuthTokenExchangeFailed,
            ),
            (
                "OAuth token refresh failed",
                AuthDiagnosticCode::OAuthTokenRefreshFailed,
            ),
            (
                "Missing deployment",
                AuthDiagnosticCode::MissingAzureDeployment,
            ),
            ("Missing region", AuthDiagnosticCode::MissingRegion),
            ("Missing project", AuthDiagnosticCode::MissingProject),
            ("Missing profile", AuthDiagnosticCode::MissingProfile),
            ("Missing endpoint", AuthDiagnosticCode::MissingEndpoint),
            (
                "credential chain not configured",
                AuthDiagnosticCode::MissingCredentialChain,
            ),
        ];
        for (message, expected_code) in cases {
            let err = Error::auth(*message);
            let d = err
                .auth_diagnostic()
                .unwrap_or_else(|| panic!("expected diagnostic for Auth({message})"));
            assert_eq!(
                d.code, *expected_code,
                "wrong code for Auth({message}): {:?}",
                d.code
            );
        }
    }

    /// Classifier must be case-insensitive.
    #[test]
    fn e2e_classifier_case_insensitive() {
        let variants = ["MISSING API KEY", "Missing Api Key", "missing api key"];
        for msg in &variants {
            let err = Error::provider("openai", *msg);
            let d = err
                .auth_diagnostic()
                .unwrap_or_else(|| panic!("no diagnostic for: {msg}"));
            assert_eq!(
                d.code,
                AuthDiagnosticCode::MissingApiKey,
                "failed for: {msg}"
            );
        }
    }

    /// Non-auth error variants must never produce diagnostics.
    #[test]
    fn e2e_non_auth_variants_no_diagnostic() {
        let errors: Vec<Error> = vec![
            Error::config("bad json"),
            Error::session("timeout"),
            Error::tool("bash", "not found"),
            Error::validation("missing field"),
            Error::extension("crash"),
            Error::api("network error"),
            Error::Aborted,
        ];
        for err in &errors {
            assert!(
                err.auth_diagnostic().is_none(),
                "unexpected diagnostic for: {err}"
            );
        }
    }

    /// Quota-exceeded messages from different providers produce the same code.
    #[test]
    fn e2e_quota_messages_cross_provider() {
        let messages = [
            "insufficient_quota",
            "quota exceeded",
            "billing hard limit reached",
            "billing_not_active",
            "not enough credits",
            "credit balance is too low",
        ];
        for msg in &messages {
            let err = Error::provider("openai", *msg);
            let d = err
                .auth_diagnostic()
                .unwrap_or_else(|| panic!("no diagnostic for: {msg}"));
            assert_eq!(
                d.code,
                AuthDiagnosticCode::QuotaExceeded,
                "wrong code for: {msg}"
            );
        }
    }

    /// OpenAI-compatible providers must resolve env keys through alias mapping.
    #[test]
    fn e2e_openai_compatible_providers_env_keys() {
        let providers_and_keys: &[(&str, &str)] = &[
            ("groq", "GROQ_API_KEY"),
            ("deepinfra", "DEEPINFRA_API_KEY"),
            ("cerebras", "CEREBRAS_API_KEY"),
            ("openrouter", "OPENROUTER_API_KEY"),
            ("mistral", "MISTRAL_API_KEY"),
            ("moonshotai", "MOONSHOT_API_KEY"),
            ("moonshotai", "KIMI_API_KEY"),
            ("alibaba", "DASHSCOPE_API_KEY"),
            ("alibaba", "QWEN_API_KEY"),
            ("deepseek", "DEEPSEEK_API_KEY"),
            ("perplexity", "PERPLEXITY_API_KEY"),
            ("xai", "XAI_API_KEY"),
        ];
        for (provider, expected_key) in providers_and_keys {
            let keys = crate::provider_metadata::provider_auth_env_keys(provider);
            assert!(
                keys.contains(expected_key),
                "provider {provider} missing env key {expected_key}, got: {keys:?}"
            );
        }
    }

    /// `provider_key_hint()` uses canonical ID and includes env vars in output.
    #[test]
    fn e2e_key_hint_format_consistency() {
        // Anthropic gets special `/login` hint.
        let hint = provider_key_hint("anthropic");
        assert!(hint.contains("ANTHROPIC_API_KEY"), "hint: {hint}");
        assert!(hint.contains("/login"), "hint: {hint}");

        // Copilot gets `/login` hint.
        let hint = provider_key_hint("github-copilot");
        assert!(hint.contains("/login"), "hint: {hint}");

        // OpenAI gets standard format.
        let hint = provider_key_hint("openai");
        assert!(hint.contains("OPENAI_API_KEY"), "hint: {hint}");
        assert!(!hint.contains("/login"), "hint: {hint}");

        // Unknown provider gets fallback.
        let hint = provider_key_hint("my-custom-proxy");
        assert!(hint.contains("my-custom-proxy"), "hint: {hint}");
    }

    /// Empty messages produce no diagnostic (no false positives).
    #[test]
    fn e2e_empty_message_no_diagnostic() {
        let err = Error::provider("openai", "");
        assert!(err.auth_diagnostic().is_none());
    }

    // ─── Context overflow detection tests ────────────────────────────

    #[test]
    fn overflow_prompt_is_too_long() {
        assert!(is_context_overflow(
            "prompt is too long: 150000 tokens",
            None,
            None
        ));
    }

    #[test]
    fn overflow_input_too_long_for_model() {
        assert!(is_context_overflow(
            "input is too long for requested model",
            None,
            None,
        ));
    }

    #[test]
    fn overflow_exceeds_context_window() {
        assert!(is_context_overflow(
            "exceeds the context window",
            None,
            None
        ));
    }

    #[test]
    fn overflow_input_token_count_exceeds_maximum() {
        assert!(is_context_overflow(
            "input token count of 50000 exceeds the maximum of 32000",
            None,
            None,
        ));
    }

    #[test]
    fn overflow_maximum_prompt_length() {
        assert!(is_context_overflow(
            "maximum prompt length is 32000",
            None,
            None,
        ));
    }

    #[test]
    fn overflow_reduce_length_of_messages() {
        assert!(is_context_overflow(
            "reduce the length of the messages",
            None,
            None,
        ));
    }

    #[test]
    fn overflow_maximum_context_length() {
        assert!(is_context_overflow(
            "maximum context length is 128000 tokens",
            None,
            None,
        ));
    }

    #[test]
    fn overflow_exceeds_limit_of() {
        assert!(is_context_overflow(
            "exceeds the limit of 200000",
            None,
            None,
        ));
    }

    #[test]
    fn overflow_exceeds_available_context_size() {
        assert!(is_context_overflow(
            "exceeds the available context size",
            None,
            None,
        ));
    }

    #[test]
    fn overflow_greater_than_context_length() {
        assert!(is_context_overflow(
            "greater than the context length",
            None,
            None,
        ));
    }

    #[test]
    fn overflow_context_window_exceeds_limit() {
        assert!(is_context_overflow(
            "context window exceeds limit",
            None,
            None,
        ));
    }

    #[test]
    fn overflow_exceeded_model_token_limit() {
        assert!(is_context_overflow(
            "exceeded model token limit",
            None,
            None,
        ));
    }

    #[test]
    fn overflow_context_length_exceeded_underscore() {
        assert!(is_context_overflow("context_length_exceeded", None, None));
    }

    #[test]
    fn overflow_context_length_exceeded_space() {
        assert!(is_context_overflow("context length exceeded", None, None));
    }

    #[test]
    fn overflow_too_many_tokens() {
        assert!(is_context_overflow("too many tokens", None, None));
    }

    #[test]
    fn overflow_token_limit_exceeded() {
        assert!(is_context_overflow("token limit exceeded", None, None));
    }

    #[test]
    fn overflow_cerebras_400_no_body() {
        assert!(is_context_overflow("400 (no body)", None, None));
    }

    #[test]
    fn overflow_cerebras_413_no_body() {
        assert!(is_context_overflow("413 (no body)", None, None));
    }

    #[test]
    fn overflow_mistral_status_code_pattern() {
        assert!(is_context_overflow("413 status code (no body)", None, None,));
    }

    #[test]
    fn overflow_case_insensitive() {
        assert!(is_context_overflow("PROMPT IS TOO LONG", None, None));
        assert!(is_context_overflow("Token Limit Exceeded", None, None));
    }

    #[test]
    fn overflow_silent_usage_exceeds_window() {
        assert!(is_context_overflow(
            "some error",
            Some(250_000),
            Some(200_000),
        ));
    }

    #[test]
    fn overflow_usage_within_window() {
        assert!(!is_context_overflow(
            "some error",
            Some(100_000),
            Some(200_000),
        ));
    }

    #[test]
    fn overflow_no_usage_info() {
        assert!(!is_context_overflow("some error", None, None));
    }

    #[test]
    fn overflow_negative_not_matched() {
        assert!(!is_context_overflow("rate limit exceeded", None, None));
        assert!(!is_context_overflow("server error 500", None, None));
        assert!(!is_context_overflow("authentication error", None, None));
        assert!(!is_context_overflow("", None, None));
    }

    // ─── Retryable error classification tests ────────────────────────

    #[test]
    fn retryable_rate_limit() {
        assert!(is_retryable_error("429 rate limit exceeded", None, None));
    }

    #[test]
    fn retryable_too_many_requests() {
        assert!(is_retryable_error("too many requests", None, None));
    }

    #[test]
    fn retryable_overloaded() {
        assert!(is_retryable_error("API overloaded", None, None));
    }

    #[test]
    fn retryable_server_500() {
        assert!(is_retryable_error(
            "HTTP 500 internal server error",
            None,
            None
        ));
    }

    #[test]
    fn retryable_server_502() {
        assert!(is_retryable_error("502 bad gateway", None, None));
    }

    #[test]
    fn retryable_server_503() {
        assert!(is_retryable_error("503 service unavailable", None, None));
    }

    #[test]
    fn retryable_server_504() {
        assert!(is_retryable_error("504 gateway timeout", None, None));
    }

    #[test]
    fn retryable_service_unavailable() {
        assert!(is_retryable_error("service unavailable", None, None));
    }

    #[test]
    fn retryable_server_error() {
        assert!(is_retryable_error("server error", None, None));
    }

    #[test]
    fn retryable_internal_error() {
        assert!(is_retryable_error("internal error occurred", None, None));
    }

    #[test]
    fn retryable_connection_error() {
        assert!(is_retryable_error("connection error", None, None));
    }

    #[test]
    fn retryable_connection_refused() {
        assert!(is_retryable_error("connection refused", None, None));
    }

    #[test]
    fn retryable_other_side_closed() {
        assert!(is_retryable_error("other side closed", None, None));
    }

    #[test]
    fn retryable_fetch_failed() {
        assert!(is_retryable_error("fetch failed", None, None));
    }

    #[test]
    fn retryable_upstream_connect() {
        assert!(is_retryable_error("upstream connect error", None, None));
    }

    #[test]
    fn retryable_reset_before_headers() {
        assert!(is_retryable_error("reset before headers", None, None));
    }

    #[test]
    fn retryable_terminated() {
        assert!(is_retryable_error("request terminated", None, None));
    }

    #[test]
    fn retryable_retry_delay() {
        assert!(is_retryable_error("retry delay 30s", None, None));
    }

    #[test]
    fn not_retryable_context_overflow() {
        // Context overflow should NOT be retried.
        assert!(!is_retryable_error("prompt is too long", None, None));
        assert!(!is_retryable_error(
            "exceeds the context window",
            None,
            None,
        ));
        assert!(!is_retryable_error("too many tokens", None, None));
    }

    #[test]
    fn not_retryable_auth_errors() {
        assert!(!is_retryable_error("invalid api key", None, None));
        assert!(!is_retryable_error("unauthorized access", None, None));
        assert!(!is_retryable_error("permission denied", None, None));
    }

    #[test]
    fn not_retryable_empty_message() {
        assert!(!is_retryable_error("", None, None));
    }

    #[test]
    fn not_retryable_generic_error() {
        assert!(!is_retryable_error("something went wrong", None, None));
    }

    #[test]
    fn not_retryable_silent_overflow() {
        // Even if the message looks retryable, if usage > context window,
        // it's overflow, not retryable.
        assert!(!is_retryable_error(
            "500 server error",
            Some(250_000),
            Some(200_000),
        ));
    }

    #[test]
    fn retryable_case_insensitive() {
        assert!(is_retryable_error("RATE LIMIT", None, None));
        assert!(is_retryable_error("Service Unavailable", None, None));
    }

    mod proptest_error {
        use super::*;
        use proptest::prelude::*;

        const ALL_DIAGNOSTIC_CODES: &[AuthDiagnosticCode] = &[
            AuthDiagnosticCode::MissingApiKey,
            AuthDiagnosticCode::InvalidApiKey,
            AuthDiagnosticCode::QuotaExceeded,
            AuthDiagnosticCode::MissingOAuthAuthorizationCode,
            AuthDiagnosticCode::OAuthTokenExchangeFailed,
            AuthDiagnosticCode::OAuthTokenRefreshFailed,
            AuthDiagnosticCode::MissingAzureDeployment,
            AuthDiagnosticCode::MissingRegion,
            AuthDiagnosticCode::MissingProject,
            AuthDiagnosticCode::MissingProfile,
            AuthDiagnosticCode::MissingEndpoint,
            AuthDiagnosticCode::MissingCredentialChain,
            AuthDiagnosticCode::UnknownAuthFailure,
        ];

        proptest! {
            /// `as_str` always returns a non-empty dotted path.
            #[test]
            fn as_str_non_empty_dotted(idx in 0..13usize) {
                let code = ALL_DIAGNOSTIC_CODES[idx];
                let s = code.as_str();
                assert!(!s.is_empty());
                assert!(s.contains('.'), "diagnostic code should be dotted: {s}");
            }

            /// `as_str` values are unique across all codes.
            #[test]
            fn as_str_unique(a in 0..13usize, b in 0..13usize) {
                if a != b {
                    assert_ne!(
                        ALL_DIAGNOSTIC_CODES[a].as_str(),
                        ALL_DIAGNOSTIC_CODES[b].as_str()
                    );
                }
            }

            /// `remediation` always returns a non-empty string.
            #[test]
            fn remediation_non_empty(idx in 0..13usize) {
                let code = ALL_DIAGNOSTIC_CODES[idx];
                assert!(!code.remediation().is_empty());
            }

            /// `redaction_policy` is always `"redact-secrets"`.
            #[test]
            fn redaction_policy_constant(idx in 0..13usize) {
                let code = ALL_DIAGNOSTIC_CODES[idx];
                assert_eq!(code.redaction_policy(), "redact-secrets");
            }

            /// `hostcall_error_code` is one of the 5 known codes.
            #[test]
            fn hostcall_code_known(msg in "[a-z ]{1,20}") {
                let known = ["invalid_request", "io", "denied", "timeout", "internal"];
                let errors = [
                    Error::config(msg.clone()),
                    Error::session(msg.clone()),
                    Error::auth(msg.clone()),
                    Error::validation(msg.clone()),
                    Error::api(msg),
                ];
                for e in &errors {
                    assert!(known.contains(&e.hostcall_error_code()));
                }
            }

            /// `category_code` is a non-empty ASCII lowercase string.
            #[test]
            fn category_code_format(msg in "[a-z ]{1,20}") {
                let errors = [
                    Error::config(msg.clone()),
                    Error::session(msg.clone()),
                    Error::auth(msg.clone()),
                    Error::validation(msg.clone()),
                    Error::extension(msg.clone()),
                    Error::api(msg),
                ];
                for e in &errors {
                    let code = e.category_code();
                    assert!(!code.is_empty());
                    assert!(code.chars().all(|c| c.is_ascii_lowercase()));
                }
            }

            /// `is_context_overflow` detects token-based overflow.
            #[test]
            fn context_overflow_token_based(
                input_tokens in 100_001..500_000u64,
                window in 1..100_000u32
            ) {
                assert!(is_context_overflow(
                    "",
                    Some(input_tokens),
                    Some(window)
                ));
            }

            /// `is_context_overflow` does not fire when tokens are within window.
            #[test]
            fn context_overflow_within_window(
                window in 100..200_000u32,
                offset in 0..100u64
            ) {
                let input = u64::from(window).saturating_sub(offset);
                assert!(!is_context_overflow(
                    "some normal error",
                    Some(input),
                    Some(window)
                ));
            }

            /// `is_context_overflow` detects all substring patterns.
            #[test]
            fn context_overflow_pattern_detection(idx in 0..OVERFLOW_PATTERNS.len()) {
                let pattern = OVERFLOW_PATTERNS[idx];
                assert!(is_context_overflow(pattern, None, None));
            }

            /// `is_context_overflow` is case-insensitive for patterns.
            #[test]
            fn context_overflow_case_insensitive(idx in 0..OVERFLOW_PATTERNS.len()) {
                let pattern = OVERFLOW_PATTERNS[idx];
                assert!(is_context_overflow(&pattern.to_uppercase(), None, None));
            }

            /// `is_retryable_error` rejects empty messages.
            #[test]
            fn retryable_empty_is_false(_dummy in 0..1u8) {
                assert!(!is_retryable_error("", None, None));
            }

            /// Context overflow errors are NOT retryable.
            #[test]
            fn overflow_not_retryable(idx in 0..OVERFLOW_PATTERNS.len()) {
                let pattern = OVERFLOW_PATTERNS[idx];
                assert!(!is_retryable_error(pattern, None, None));
            }

            /// Known retryable patterns are detected.
            #[test]
            fn retryable_known_patterns(idx in 0..8usize) {
                let patterns = [
                    "overloaded",
                    "rate limit exceeded",
                    "too many requests",
                    "429 status code",
                    "502 bad gateway",
                    "503 service unavailable",
                    "connection error",
                    "fetch failed",
                ];
                assert!(is_retryable_error(patterns[idx], None, None));
            }

            /// Random gibberish is not retryable.
            #[test]
            fn random_not_retryable(s in "[a-z]{20,40}") {
                assert!(!is_retryable_error(&s, None, None));
            }

            /// Error constructors produce correct category codes.
            #[test]
            fn constructor_category_consistency(msg in "[a-z]{1,10}") {
                assert_eq!(Error::config(&msg).category_code(), "config");
                assert_eq!(Error::session(&msg).category_code(), "session");
                assert_eq!(Error::auth(&msg).category_code(), "auth");
                assert_eq!(Error::validation(&msg).category_code(), "validation");
                assert_eq!(Error::extension(&msg).category_code(), "extension");
                assert_eq!(Error::api(&msg).category_code(), "api");
            }
        }
    }
}