openlatch-client 0.3.3

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
//! `openlatch proxy <status|discover|set|clear|test>` — and the egress gate `init` runs.
//!
//! Everything that *decides* a proxy route lives here, so `init` and the five verbs cannot
//! drift into two answers for the same host. The division of labour is:
//!
//! | Piece | Job |
//! |---|---|
//! | [`ProxyOverrides`] | Precedence tier 1 — the CLI flags, overlaid per key on top of `EgressConfig::resolve`'s tiers 2–4 |
//! | [`refuse_linux_pac`] | D-20: an explicit `pac_url` on Linux is refused at validation, not discovered around |
//! | [`run_gate`] | resolve → probe → discover → prompt, the sequence `init` runs before it touches anything destructive |
//! | [`persist_route`] | The one place `[proxy]` keys are written |
//! | the verbs | Read (`status`, `test`) or write (`discover`, `set`, `clear`) |
//!
//! **`source = "manual"` is never overwritten by automation.** A human who typed a proxy
//! URL knows something the ladder does not; `discover` refuses without `--force`, the gate
//! never re-persists over it, and I-3's self-heal keys on the same field.

use secrecy::SecretString;

use crate::cli::output::{OutputConfig, OutputFormat};
use crate::cli::prompt::{self, PromptResult, Prompter};
use crate::cli::{ProxyCommands, ProxyDiscoverArgs, ProxySetArgs, ProxyTestArgs};
use crate::egress::{
    self, mask_userinfo, CandidateAttempt, Context, EgressConfig, ProxyAuth, ProxyMode, ProxySource,
};
use crate::error::{OlError, ERR_EGRESS_UNREACHABLE, ERR_INVALID_CONFIG, ERR_PROXY_CONFIG_INVALID};

/// Dispatch `openlatch proxy <sub>`.
///
/// # Errors
///
/// Propagates the verb's own failure. A read-only verb that merely finds a broken route
/// records a degraded exit code rather than returning `Err` — a diagnosis that ran is a
/// success (`.claude/rules/cli-output-contract.md`).
pub fn run(cmd: &ProxyCommands, output: &OutputConfig) -> Result<(), OlError> {
    match cmd {
        ProxyCommands::Status => status(output),
        ProxyCommands::Discover(args) => discover(args, output),
        ProxyCommands::Set(args) => set(args, output),
        ProxyCommands::Clear => clear(output),
        ProxyCommands::Test(args) => test(args, output),
    }
}

// ---------------------------------------------------------------------------
// Precedence tier 1 — the CLI flags
// ---------------------------------------------------------------------------

/// The proxy flags of one CLI invocation, as a per-key overlay.
///
/// `EgressConfig::resolve` implements tiers 2 through 4 and knows nothing about argv, so
/// tier 1 is applied on top of its output here. **Per key, never per block** (D-6): passing
/// `--proxy` alone leaves `[proxy] auth` and the ambient `no_proxy` exactly where they were.
#[derive(Debug, Default, Clone)]
pub struct ProxyOverrides {
    /// `--proxy` — a concrete route. Rejected if it carries userinfo.
    pub url: Option<String>,
    /// `--no-proxy`
    pub no_proxy: Option<String>,
    /// `--ca-bundle`
    pub ca_bundle: Option<String>,
    /// `--proxy-mode`
    pub mode: Option<String>,
    /// `--proxy-auth`
    pub auth: Option<String>,
    /// `--proxy-spn`
    pub spn: Option<String>,
}

impl ProxyOverrides {
    /// The flags `openlatch init` was given.
    pub fn from_init(args: &crate::cli::InitArgs) -> Self {
        Self {
            url: args.proxy.clone(),
            no_proxy: args.no_proxy.clone(),
            ca_bundle: args.ca_bundle.clone(),
            mode: args.proxy_mode.clone(),
            auth: args.proxy_auth.clone(),
            spn: args.proxy_spn.clone(),
        }
    }

    /// Reject what argv must never carry, **before any step of the command runs**.
    ///
    /// `--proxy http://user:pass@host` is refused with `OL-1226`, and the refusal has to
    /// happen at argument-processing time rather than at use time: argv is world-readable
    /// through `/proc/<pid>/cmdline` and Win32 `CommandLine` from the instant the process
    /// starts, so by the time a later step would notice, every process on the host has
    /// already had the chance to read it. Failing early does not un-leak the password —
    /// nothing can — but it stops the command from *also* persisting a route built on one,
    /// and it names the two channels that do keep a credential private.
    ///
    /// # Errors
    ///
    /// `OL-1226` for userinfo in `--proxy`, or an enum value outside the frozen set.
    pub fn validate(&self) -> Result<(), OlError> {
        if let Some(url) = &self.url {
            if authority_of(url).is_some_and(|a| a.contains('@')) {
                return Err(OlError::new(
                    ERR_PROXY_CONFIG_INVALID,
                    "--proxy must not contain a username or password: command-line arguments \
                     are readable by every process on this host",
                )
                .with_suggestion(
                    "Pass the credential through OPENLATCH_PROXY instead, or omit it and let \
                     `openlatch init` prompt on the 407 — both store it in the OS credential \
                     store and never write it to config.toml.",
                )
                .with_docs("https://docs.openlatch.ai/errors/OL-1226"));
            }
        }
        if let Some(m) = &self.mode {
            if !matches!(m.as_str(), "auto" | "manual" | "direct") {
                return Err(invalid_flag("--proxy-mode", m, "auto, manual or direct"));
            }
        }
        if let Some(a) = &self.auth {
            if !matches!(a.as_str(), "auto" | "none" | "basic" | "negotiate") {
                return Err(invalid_flag(
                    "--proxy-auth",
                    a,
                    "auto, none, basic or negotiate (NTLM is not supported)",
                ));
            }
        }
        Ok(())
    }

    /// Overlay these flags onto a configuration resolved from tiers 2–4.
    ///
    /// # Errors
    ///
    /// `OL-1226` when a flag value cannot be turned into its frozen enum, or when
    /// `--ca-bundle` names a file that is not there.
    pub fn apply(&self, cfg: &mut EgressConfig) -> Result<(), OlError> {
        if let Some(m) = &self.mode {
            cfg.mode = match m.as_str() {
                "manual" => ProxyMode::Manual,
                "direct" => ProxyMode::Direct,
                _ => ProxyMode::Auto,
            };
        }
        if let Some(a) = &self.auth {
            cfg.auth = match a.as_str() {
                "none" => ProxyAuth::None,
                "basic" => ProxyAuth::Basic,
                "negotiate" => ProxyAuth::Negotiate,
                _ => ProxyAuth::Auto,
            };
        }
        if let Some(u) = &self.url {
            let parsed = parse_proxy_url(u)?;
            cfg.url = Some(parsed);
            // A flag win is an explicit human-provided route — the same row as the prompt
            // and `proxy set`, so it carries the same provenance. The frozen `source` enum
            // has no `cli` value by design: every gate that protects a human's choice
            // (D-7, D-18, the discovery skip) keys on `manual`, and a fourth spelling for
            // "a person typed this" would be a fourth thing each of them has to know.
            cfg.mode = match &self.mode {
                Some(m) if m == "direct" => ProxyMode::Direct,
                _ => ProxyMode::Manual,
            };
            cfg.source = Some(ProxySource::Manual);
        }
        if let Some(list) = &self.no_proxy {
            let (matcher, unsupported) = egress::NoProxyMatcher::new(list);
            for entry in unsupported {
                cfg.warnings
                    .push(egress::EgressWarning::UnsupportedNoProxyEntry(entry));
            }
            cfg.no_proxy = matcher;
        }
        if let Some(p) = &self.ca_bundle {
            let path = std::path::PathBuf::from(p);
            if !path.is_file() {
                return Err(OlError::new(
                    ERR_PROXY_CONFIG_INVALID,
                    format!("--ca-bundle '{p}' is not a readable file"),
                )
                .with_suggestion("Point it at the intercepting proxy's root certificate, in PEM.")
                .with_docs("https://docs.openlatch.ai/errors/OL-1226"));
            }
            cfg.ca_bundle = Some(path);
        }
        if let Some(s) = &self.spn {
            cfg.spn = Some(s.clone());
        }
        Ok(())
    }

    /// The `[proxy]` keys these flags persist, beyond `url`/`source` which the gate owns.
    fn persistable(&self) -> Vec<(&'static str, String)> {
        let mut out = Vec::new();
        if let Some(v) = &self.no_proxy {
            out.push(("no_proxy", quoted(v)));
        }
        if let Some(v) = &self.ca_bundle {
            out.push(("ca_bundle", quoted(v)));
        }
        if let Some(v) = &self.auth {
            out.push(("auth", quoted(v)));
        }
        if let Some(v) = &self.spn {
            out.push(("spn", quoted(v)));
        }
        out
    }
}

fn invalid_flag(flag: &str, got: &str, expected: &str) -> OlError {
    OlError::new(
        ERR_PROXY_CONFIG_INVALID,
        format!("{flag} = \"{got}\" is not a valid value"),
    )
    .with_suggestion(format!("Expected one of: {expected}."))
    .with_docs("https://docs.openlatch.ai/errors/OL-1226")
}

/// The authority of a URL string — `user:pass@host:port` — without parsing it.
///
/// Deliberately not `Url::parse`: the check that runs on it is "does argv contain a
/// credential", and a URL malformed enough to fail parsing can still have leaked one.
fn authority_of(url: &str) -> Option<&str> {
    let (_, rest) = url.split_once("://")?;
    Some(rest.split('/').next().unwrap_or(rest))
}

/// Parse and normalise a proxy URL an operator typed.
///
/// # Errors
///
/// `OL-1226` for a missing or unsupported scheme, or a URL with no host.
pub fn parse_proxy_url(raw: &str) -> Result<String, OlError> {
    let bad = || {
        OlError::new(
            ERR_PROXY_CONFIG_INVALID,
            format!("'{raw}' is not a usable proxy URL"),
        )
        .with_suggestion(
            "Use http://host:port, https://host:port, socks5://host:port or \
             socks5h://host:port.",
        )
        .with_docs("https://docs.openlatch.ai/errors/OL-1226")
    };
    let parsed = reqwest::Url::parse(raw.trim()).map_err(|_| bad())?;
    if !matches!(parsed.scheme(), "http" | "https" | "socks5" | "socks5h") {
        return Err(bad());
    }
    if parsed.host_str().is_none_or(str::is_empty) {
        return Err(bad());
    }
    Ok(egress::discovery::authority_form(&parsed))
}

fn quoted(v: &str) -> String {
    format!("\"{}\"", v.replace('\\', "\\\\").replace('"', "\\\""))
}

// ---------------------------------------------------------------------------
// D-20 — an explicit PAC URL on Linux is refused, not routed around
// ---------------------------------------------------------------------------

/// Refuse a configured `pac_url` on Linux, at gate-validation time.
///
/// Two tiers can supply one — `OPENLATCH_PROXY_PAC_URL` (tier 2) and `[proxy] pac_url`
/// (tier 3) — and I-1 parses the key inert on every platform. The Linux discovery rung
/// already refuses the *GNOME* `mode = 'auto'` variant in the trace; this is the other
/// half, and it has to be an error rather than a skipped rung: the operator wrote the PAC
/// URL down on purpose, and quietly falling through to DIRECT would send corporate traffic
/// past the proxy their PAC exists to route it through.
///
/// A no-op everywhere else. Windows and macOS have audited PAC evaluators, and I-1's
/// factory drives them per destination.
///
/// # Errors
///
/// `OL-1225` naming the key and the D-20 remedy.
pub fn refuse_linux_pac(cfg: &EgressConfig) -> Result<(), OlError> {
    if !cfg!(target_os = "linux") {
        return Ok(());
    }
    match cfg.pac_url.as_deref().filter(|u| !u.is_empty()) {
        Some(url) => Err(egress::discovery::linux::pac_refusal(url)),
        None => Ok(()),
    }
}

// ---------------------------------------------------------------------------
// The gate
// ---------------------------------------------------------------------------

/// What the gate decided, and what the caller owes the config as a result.
pub struct GateOutcome {
    /// The configuration that actually reached the platform.
    pub config: EgressConfig,
    /// Keys to persist, pre-quoted. Empty when nothing changed.
    pub sets: Vec<(&'static str, String)>,
    /// Keys to delete. Non-empty on the static→PAC transition and on `clear`.
    pub removes: Vec<&'static str>,
    /// Every rung and prompt attempt, in order. Rendered by `--json` on failure.
    pub attempts: Vec<CandidateAttempt>,
    /// Did a human answer a prompt on this run?
    pub prompted: bool,
    /// A credential the prompt captured, to store once the route is persisted.
    pub captured: Option<(String, String, SecretString)>,
}

impl GateOutcome {
    /// Nothing to write: the route already in effect reached the platform.
    fn unchanged(config: EgressConfig, attempts: Vec<CandidateAttempt>) -> Self {
        Self {
            config,
            sets: Vec::new(),
            removes: Vec::new(),
            attempts,
            prompted: false,
            captured: None,
        }
    }

    /// The `source` this run ends on, as the wire string.
    pub fn source_str(&self) -> Option<&'static str> {
        self.config.source.map(source_str)
    }
}

/// The `[proxy]` route as `config.toml` currently records it.
///
/// The gate needs this to answer a question a *resolved* configuration cannot: did the
/// working route come out of the file, or out of the environment this run happens to have?
/// Once tiers 2 through 4 have merged, a persisted route and an ambient `HTTPS_PROXY` look
/// identical — and the difference decides whether anything is written at all.
///
/// It is load-bearing rather than an optimisation. **The daemon does not inherit the shell
/// that ran `init`.** An `OPENLATCH_PROXY` that made this install work and was never written
/// down leaves a daemon that goes direct, on an estate where direct does not work — an
/// install that passes every check at install time and forwards nothing an hour later.
#[derive(Debug, Default, Clone)]
pub struct PersistedProxy {
    /// `[proxy] url`, or `None` when the key is absent or empty.
    pub url: Option<String>,
    /// `[proxy] source`, or `None` when discovery has never run.
    pub source: Option<String>,
}

impl PersistedProxy {
    /// Read the two keys straight out of `config.toml`.
    ///
    /// Deliberately a raw read rather than a `Config::load`: by the time the loader is done,
    /// the environment has already merged over the file and the distinction this type exists
    /// for is gone.
    pub fn read(config_path: &std::path::Path) -> Self {
        #[derive(serde::Deserialize)]
        struct Wrapper {
            proxy: Option<egress::ProxyToml>,
        }
        let Ok(raw) = std::fs::read_to_string(config_path) else {
            return Self::default();
        };
        let Ok(wrapper) = toml::from_str::<Wrapper>(&raw) else {
            return Self::default();
        };
        let Some(toml) = wrapper.proxy else {
            return Self::default();
        };
        Self {
            url: toml.url.filter(|u| !u.is_empty()),
            source: toml.source.filter(|s| !s.is_empty()),
        }
    }

    /// Is `url` exactly the route already written down, under a recorded source?
    fn already_records(&self, url: Option<&str>) -> bool {
        self.source.is_some() && self.url.as_deref() == url
    }
}

/// A gate walk that reached nothing, with the trace that proves it tried.
///
/// The trace is part of the failure, not a side channel: `init --json`'s egress-failure
/// document is required to list every candidate and its per-rung result, and a plain
/// `OlError` has nowhere to put them. Carrying them in the error type is what stops the
/// report from being reconstructed after the fact — by then the ladder has been walked and
/// the timings are gone.
pub struct GateFailure {
    /// The `OL-122x` this failed with.
    pub error: OlError,
    /// Every rung and prompt attempt, in order.
    pub attempts: Vec<CandidateAttempt>,
}

impl GateFailure {
    fn new(error: OlError, attempts: Vec<CandidateAttempt>) -> Self {
        Self { error, attempts }
    }
}

impl From<GateFailure> for OlError {
    fn from(f: GateFailure) -> Self {
        f.error
    }
}

/// The wire value of a [`ProxySource`].
pub fn source_str(s: ProxySource) -> &'static str {
    match s {
        ProxySource::Manual => "manual",
        ProxySource::Env => "env",
        ProxySource::Windows => "windows",
        ProxySource::Macos => "macos",
        ProxySource::Gnome => "gnome",
        ProxySource::Pac => "pac",
        ProxySource::Wpad => "wpad",
    }
}

/// Resolve tiers 1–4, probe, discover, and — when there is a human — prompt.
///
/// This is the sequence the PRD's Init & Discovery Flow describes, and the order is the
/// contract:
///
/// 1. **Resolve and probe what is already explicit.** A `[proxy]` block that works, or an
///    env-derived route that works, wins without touching the network any further than one
///    health request.
/// 2. **Walk the discovery ladder** only when nothing explicit reached the platform.
/// 3. **Ask**, once, with up to three attempts — and only when [`prompt::interactive`]
///    says there is somebody there.
///
/// A route whose `source` is already `manual` is probed like any other, but its failure
/// never triggers discovery: the failure message names the manual source instead, because
/// silently replacing a human's route is exactly what D-7 forbids.
///
/// # Errors
///
/// `OL-1220` when nothing reached the platform. The error is the *caller's* signal to
/// unwind; this function writes nothing itself.
pub fn run_gate(
    api_url: &str,
    base: EgressConfig,
    overrides: &ProxyOverrides,
    persisted: &PersistedProxy,
    prompter: Option<&mut dyn Prompter>,
    output: &OutputConfig,
) -> Result<GateOutcome, GateFailure> {
    let mut cfg = base;
    let bare = |e: OlError| GateFailure::new(e, Vec::new());
    overrides.apply(&mut cfg).map_err(bare)?;
    refuse_linux_pac(&cfg).map_err(bare)?;

    let target = reqwest::Url::parse(api_url)
        .map_err(|_| {
            OlError::new(
                ERR_INVALID_CONFIG,
                format!("[cloud] api_url = '{api_url}' is not a URL"),
            )
            .with_suggestion("Set it with `openlatch init --api-url <url>`.")
        })
        .map_err(bare)?;
    // Strict: this probe decides whether the install *works*, and a 407 means the health
    // endpoint was never reached. The ladder below builds its own lenient probe, because
    // ranking a challenging corporate proxy as the right rung is the correct answer there.
    let probe = egress::HealthProbe::strict(api_url, cfg.clone()).map_err(bare)?;
    let ranking_probe = egress::HealthProbe::new(api_url, cfg.clone()).map_err(bare)?;

    // Step 1 — what is already explicit.
    let explicit = match cfg.mode {
        // `direct` is a decision. Probing it still matters (the platform may simply be
        // down), but no ladder walk follows a deliberate refusal to use a proxy.
        ProxyMode::Direct => probe_route(&probe, &cfg, None),
        _ => match cfg.url.as_deref() {
            Some(u) => {
                let parsed = reqwest::Url::parse(u).ok();
                probe_route(&probe, &cfg, parsed.as_ref())
            }
            None => probe_route(&probe, &cfg, None),
        },
    };
    let mut attempts = vec![explicit.clone()];
    if explicit.probe.is_ok() {
        let mut outcome = GateOutcome::unchanged(cfg, attempts);
        outcome.sets = overrides.persistable();
        if overrides.url.is_some() {
            // A `--proxy` flag win. Same provenance as the prompt and `proxy set`: a human
            // typed it.
            outcome
                .sets
                .push(("url", quoted(outcome.config.url.as_deref().unwrap_or(""))));
            outcome.sets.push(("mode", quoted("manual")));
            outcome.sets.push(("source", quoted("manual")));
        } else if !persisted.already_records(outcome.config.url.as_deref()) {
            if let Some(url) = outcome.config.url.clone() {
                // The route worked and came out of the environment. It has to be written
                // down: the daemon runs under a supervisor with none of this shell's
                // variables, so a route that lives only in `OPENLATCH_PROXY` is a route the
                // daemon does not have.
                //
                // The provenance is stamped in memory as well as on disk. `EgressConfig::
                // resolve` reads `source` from the `[proxy]` block alone — it is the one
                // field that is not resolved per tier, because it describes the *winning
                // candidate* rather than a setting — so a route that arrived through the
                // environment reaches this line with no source at all, and everything
                // downstream (the JSON report, the telemetry shape, the log line) would
                // report a proxy with no provenance.
                outcome.config.source = Some(ProxySource::Env);
                outcome.sets.push(("url", quoted(&url)));
                outcome.sets.push(("source", quoted("env")));
                // D-7: the *credential* goes to the credential store, never to
                // `config.toml`. The username is not a secret and is written, because it is
                // what makes a wrong credential recognisable later.
                if let Some(user) = outcome.config.username.clone() {
                    outcome.sets.push(("username", quoted(&user)));
                    if let Some(pass) = outcome.config.env_password.clone() {
                        outcome.captured = Some((
                            egress::credential_authority(&url),
                            user,
                            SecretString::from(pass),
                        ));
                    }
                }
            }
        }
        // Otherwise: the file already records this exact route. `init` writes nothing, which
        // is what makes it idempotent on `[proxy]`.
        return Ok(outcome);
    }

    // D-7: a human's route is reported, never replaced.
    if cfg.source == Some(ProxySource::Manual) || cfg.mode == ProxyMode::Manual {
        let e = manual_route_failed(&cfg);
        return Err(GateFailure::new(e, attempts));
    }

    // Step 2 — the discovery ladder.
    output.print_substep("Cloud unreachable — running proxy discovery");
    let (winner, trace) = egress::discover(Context::UserSession, &cfg, &target, &ranking_probe);
    attempts.extend(trace);
    if let Some(found) = winner {
        let (sets, removes) = route_writes(&found);
        let mut config = cfg.clone();
        apply_discovered(&mut config, &found);
        let mut all = overrides.persistable();
        all.extend(sets);
        return Ok(GateOutcome {
            config,
            sets: all,
            removes,
            attempts,
            prompted: false,
            captured: None,
        });
    }

    // Step 3 — ask, if anyone is there.
    let Some(prompter) = prompter else {
        let e = nothing_reached(api_url, &attempts);
        return Err(GateFailure::new(e, attempts));
    };
    prompt_loop(api_url, cfg, overrides, prompter, attempts)
}

/// Probe one route and record it as a [`CandidateAttempt`], win or lose.
fn probe_route(
    probe: &egress::HealthProbe,
    cfg: &EgressConfig,
    via: Option<&reqwest::Url>,
) -> CandidateAttempt {
    use egress::{CandidateOutcome, CandidateProbe};
    let started = std::time::Instant::now();
    let (outcome, latency_ms) = match probe.probe(via) {
        Ok(ms) => (CandidateOutcome::Ok, ms),
        Err(e) => (
            CandidateOutcome::Failed(e.code),
            u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
        ),
    };
    CandidateAttempt {
        source: cfg.source.unwrap_or(ProxySource::Env),
        url_masked: via.map(mask_url).unwrap_or_default(),
        probe: outcome,
        latency_ms,
        rung: "configured",
        detail: None,
    }
}

fn mask_url(u: &reqwest::Url) -> String {
    mask_userinfo(&egress::discovery::authority_form(u))
}

/// Fold a discovery winner into the configuration it will be used under.
fn apply_discovered(cfg: &mut EgressConfig, found: &egress::Discovered) {
    cfg.source = Some(found.source);
    match &found.route {
        egress::Route::Static(u) => {
            cfg.mode = ProxyMode::Auto;
            cfg.url = Some(egress::discovery::authority_form(u));
            cfg.pac_url = None;
        }
        egress::Route::PacSource { pac_url } => {
            cfg.mode = ProxyMode::Auto;
            // The PAC persistence rule, in memory as well as on disk: a PAC route carries
            // no concrete url, and leaving a stale one here would make the very next
            // client build route statically past the script.
            cfg.url = None;
            cfg.pac_url = pac_url.as_ref().map(ToString::to_string);
        }
    }
}

/// The `[proxy]` writes a discovery winner implies.
///
/// A static win writes `url` + `source`. A PAC win writes `source` (+ `pac_url` when the
/// script location is explicit) and **removes any stale `url`** — that removal is the
/// static→PAC transition, and without it the next process reads the old concrete proxy as
/// a static route and never consults the script.
fn route_writes(found: &egress::Discovered) -> (Vec<(&'static str, String)>, Vec<&'static str>) {
    let source = quoted(source_str(found.source));
    match &found.route {
        egress::Route::Static(u) => (
            vec![
                ("url", quoted(&egress::discovery::authority_form(u))),
                ("source", source),
            ],
            vec!["pac_url"],
        ),
        egress::Route::PacSource { pac_url } => {
            let mut sets = vec![("source", source)];
            if let Some(p) = pac_url {
                sets.push(("pac_url", quoted(p.as_str())));
            }
            let removes = if pac_url.is_some() {
                vec!["url"]
            } else {
                vec!["url", "pac_url"]
            };
            (sets, removes)
        }
    }
}

/// Ask for a proxy URL, up to [`prompt::MAX_URL_ATTEMPTS`] times.
///
/// An answer carrying `user:pass@` is **stripped before the probe**: the credential goes to
/// the keyed store, the clean URL goes to the probe, and `config.toml` never sees either.
/// A 407-shaped failure asks for the credential and re-probes once, because the proxy the
/// operator just named is almost always the right one and a wrong password is the likely
/// mistake.
fn prompt_loop(
    api_url: &str,
    base: EgressConfig,
    overrides: &ProxyOverrides,
    prompter: &mut dyn Prompter,
    mut attempts: Vec<CandidateAttempt>,
) -> Result<GateOutcome, GateFailure> {
    for attempt in 1..=prompt::MAX_URL_ATTEMPTS {
        let answer = match prompter.ask_url(attempt) {
            PromptResult::Answered(a) => a,
            PromptResult::Aborted => return Err(GateFailure::new(aborted(api_url), attempts)),
            PromptResult::NotATty => {
                let e = nothing_reached(api_url, &attempts);
                return Err(GateFailure::new(e, attempts));
            }
        };

        // AC #6, first clause: userinfo never survives past this line.
        let (clean, user, pass) = split_userinfo(&answer);
        let url = match parse_proxy_url(&clean) {
            Ok(u) => u,
            Err(e) => {
                eprintln!("  {}", e.message);
                continue;
            }
        };
        let parsed = match reqwest::Url::parse(&url) {
            Ok(p) => p,
            Err(_) => continue,
        };

        let mut cfg = base.clone();
        cfg.mode = ProxyMode::Manual;
        cfg.source = Some(ProxySource::Manual);
        cfg.url = Some(url.clone());
        cfg.username = user.clone().or(cfg.username);
        cfg.env_password = pass.clone();
        // A credential the operator typed is a credential they mean to present. `auth =
        // "none"` is the one value that would silently discard it, and it is the default
        // a configuration that has never seen a proxy carries.
        if cfg.env_password.is_some() && cfg.auth == ProxyAuth::None {
            cfg.auth = ProxyAuth::Basic;
        }

        // A probe per attempt, built from THIS attempt's configuration.
        //
        // `HealthProbe` carries its own base config and overrides only the route, so a probe
        // built once at the top of the gate would never present the credential this loop just
        // captured — every authenticated proxy would 407 forever, and the branch that exists
        // to ask for the password would look like it had asked for nothing.
        let mut record = match egress::HealthProbe::strict(api_url, cfg.clone()) {
            Ok(p) => probe_route(&p, &cfg, Some(&parsed)),
            Err(e) => return Err(GateFailure::new(e, attempts)),
        };
        record.rung = "prompt";
        record.source = ProxySource::Manual;
        attempts.push(record.clone());

        // A 407 is not a wrong proxy, it is a proxy that wants a credential. Asking is the
        // whole reason this branch exists; treating it as a failed attempt would burn one
        // of three tries on the right answer.
        let needs_credential = matches!(
            record.probe,
            egress::CandidateOutcome::Failed(code) if code == crate::error::ERR_PROXY_AUTH_FAILED
        );
        if needs_credential && cfg.env_password.is_none() {
            let username = match &cfg.username {
                Some(u) => u.clone(),
                None => match prompter.ask_username(&url) {
                    PromptResult::Answered(u) => u,
                    _ => return Err(GateFailure::new(aborted(api_url), attempts)),
                },
            };
            let secret = match prompter.ask_password(&url, &username) {
                PromptResult::Answered(s) => s,
                _ => return Err(GateFailure::new(aborted(api_url), attempts)),
            };
            cfg.username = Some(username.clone());
            cfg.auth = match cfg.auth {
                ProxyAuth::None => ProxyAuth::Basic,
                other => other,
            };
            cfg.env_password = Some(secrecy::ExposeSecret::expose_secret(&secret).to_string());

            let mut retry = match egress::HealthProbe::strict(api_url, cfg.clone()) {
                Ok(p) => probe_route(&p, &cfg, Some(&parsed)),
                Err(e) => return Err(GateFailure::new(e, attempts)),
            };
            retry.rung = "prompt-auth";
            retry.source = ProxySource::Manual;
            attempts.push(retry.clone());
            if retry.probe.is_ok() {
                return Ok(prompt_outcome(
                    cfg,
                    overrides,
                    attempts,
                    Some((url, username, secret)),
                ));
            }
            continue;
        }

        if record.probe.is_ok() {
            let captured = match (user, pass) {
                (Some(u), Some(p)) => Some((url.clone(), u, SecretString::from(p))),
                _ => None,
            };
            return Ok(prompt_outcome(cfg, overrides, attempts, captured));
        }
    }
    Err(GateFailure::new(exhausted(api_url), attempts))
}

fn prompt_outcome(
    cfg: EgressConfig,
    overrides: &ProxyOverrides,
    attempts: Vec<CandidateAttempt>,
    captured: Option<(String, String, SecretString)>,
) -> GateOutcome {
    let mut sets = overrides.persistable();
    sets.push(("url", quoted(cfg.url.as_deref().unwrap_or(""))));
    sets.push(("mode", quoted("manual")));
    sets.push(("source", quoted("manual")));
    if let Some(user) = &cfg.username {
        sets.push(("username", quoted(user)));
    }
    GateOutcome {
        config: cfg,
        sets,
        removes: vec!["pac_url"],
        attempts,
        prompted: true,
        captured,
    }
}

/// Split `scheme://user:pass@host` into the clean URL, the user and the password.
///
/// The one place a credential is taken out of something an operator typed. It runs before
/// the probe, not after, so no code path downstream ever holds the composite string.
fn split_userinfo(raw: &str) -> (String, Option<String>, Option<String>) {
    let Some((scheme, rest)) = raw.trim().split_once("://") else {
        return (raw.trim().to_string(), None, None);
    };
    let (authority, path) = match rest.split_once('/') {
        Some((a, p)) => (a, Some(p)),
        None => (rest, None),
    };
    // `rsplit_once`, so a `@` inside the password does not split the authority early.
    let Some((userinfo, host)) = authority.rsplit_once('@') else {
        return (raw.trim().to_string(), None, None);
    };
    let (user, pass) = match userinfo.split_once(':') {
        Some((u, p)) => (u.to_string(), Some(p.to_string())),
        None => (userinfo.to_string(), None),
    };
    let clean = match path {
        Some(p) => format!("{scheme}://{host}/{p}"),
        None => format!("{scheme}://{host}"),
    };
    (clean, Some(user), pass)
}

// ---------------------------------------------------------------------------
// Failures — every one carries the candidate trace
// ---------------------------------------------------------------------------

fn nothing_reached(api_url: &str, attempts: &[CandidateAttempt]) -> OlError {
    OlError::new(
        ERR_EGRESS_UNREACHABLE,
        format!(
            "cannot reach {api_url}: {} candidate route(s) tried, none worked",
            attempts.iter().filter(|a| a.was_probed()).count()
        ),
    )
    .with_suggestion(
        "Set the proxy explicitly with `openlatch proxy set <url>`, or re-run with a \
         terminal so `openlatch init` can prompt for one. If this host has no proxy, ask \
         IT for an egress rule for app.openlatch.ai. `--yes` suppresses the prompt.",
    )
    .with_docs("https://docs.openlatch.ai/errors/OL-1220")
}

fn aborted(api_url: &str) -> OlError {
    OlError::new(
        ERR_EGRESS_UNREACHABLE,
        format!("cancelled: {api_url} was not reachable and no proxy was given"),
    )
    .with_suggestion(
        "Re-run `openlatch init` when you have the proxy URL, or set it directly with \
         `openlatch proxy set <url>`.",
    )
    .with_docs("https://docs.openlatch.ai/errors/OL-1220")
}

fn exhausted(api_url: &str) -> OlError {
    OlError::new(
        ERR_EGRESS_UNREACHABLE,
        format!(
            "cannot reach {api_url} after {} proxy attempts",
            prompt::MAX_URL_ATTEMPTS
        ),
    )
    .with_suggestion(
        "Check the proxy URL and port with whoever runs egress on this network, then \
         `openlatch proxy set <url>`.",
    )
    .with_docs("https://docs.openlatch.ai/errors/OL-1220")
}

fn manual_route_failed(cfg: &EgressConfig) -> OlError {
    let route = cfg
        .url
        .as_deref()
        .map(mask_userinfo)
        .unwrap_or_else(|| "direct".to_string());
    OlError::new(
        crate::error::ERR_PROXY_UNREACHABLE,
        format!("the proxy set by hand ({route}) did not reach the platform"),
    )
    .with_suggestion(
        "`[proxy] source = \"manual\"` means discovery will not replace it. Fix the URL \
         with `openlatch proxy set <url>`, or hand the route back to discovery with \
         `openlatch proxy discover --force`.",
    )
    .with_docs("https://docs.openlatch.ai/errors/OL-1221")
}

/// The frozen `candidates` array of `init --json`'s egress-failure document.
///
/// Only rungs that really were probed appear: a gated or empty rung never was a candidate,
/// and listing it would make a host look like it had options it did not.
pub fn candidates_json(attempts: &[CandidateAttempt]) -> serde_json::Value {
    serde_json::Value::Array(
        attempts
            .iter()
            .filter(|a| a.was_probed())
            .map(|a| {
                serde_json::json!({
                    "source": source_str(a.source),
                    "url_masked": a.url_masked,
                    "probe": a.probe.as_str(),
                    "latency_ms": a.latency_ms,
                })
            })
            .collect(),
    )
}

// ---------------------------------------------------------------------------
// Persistence + telemetry
// ---------------------------------------------------------------------------

/// Write a gate outcome's keys into `[proxy]`, and store any captured credential.
///
/// The credential is stored **after** the route is persisted, deliberately: the store is
/// keyed by authority, so a credential written before the route it belongs to could
/// outlive a failed config write and sit there matching nothing.
///
/// # Errors
///
/// Propagates the config write. A credential that cannot be stored is a warning, not a
/// failure: the route is correct and usable, and the operator can re-enter the password.
pub fn persist_outcome(
    config_path: &std::path::Path,
    outcome: &GateOutcome,
    output: &OutputConfig,
) -> Result<(), OlError> {
    if outcome.sets.is_empty() && outcome.removes.is_empty() {
        return Ok(());
    }
    crate::config::persist_proxy_config(config_path, &outcome.sets, &outcome.removes)?;
    // The username is not part of the credential key -- the read ladder in
    // `resolve_password` keys on the authority alone, and a writer that keyed on more
    // would store a credential nothing ever reads. It is recorded in `config.toml`
    // instead, where it belongs: it is not a secret, and it is what makes a wrong
    // credential recognisable later.
    if let Some((authority, _username, secret)) = &outcome.captured {
        let store = credential_store();
        if let Err(e) = store.store(authority, secret) {
            output.print_substep(&format!(
                "Proxy credential could not be stored ({}); re-enter it with `openlatch proxy set`",
                e.code
            ));
        }
    }
    Ok(())
}

/// The proxy credential store for this install.
pub fn credential_store() -> egress::credentials::ProxyCredentialStore {
    let dir = crate::config::openlatch_dir();
    let agent_id = crate::config::Config::load(None, None, false)
        .ok()
        .and_then(|c| c.agent_id)
        .unwrap_or_default();
    egress::credentials::ProxyCredentialStore::new(&dir, agent_id)
}

/// `proxy_type`, from the frozen enum. `pac` whenever the route came through a PAC file,
/// **whatever scheme the script returned** — the script is the route, not its answer.
pub fn proxy_type(cfg: &EgressConfig) -> &'static str {
    if matches!(cfg.source, Some(ProxySource::Pac) | Some(ProxySource::Wpad)) {
        return "pac";
    }
    match cfg.url.as_deref().and_then(|u| u.split_once("://")) {
        Some(("https", _)) => "https",
        Some(("socks5" | "socks5h", _)) => "socks5",
        Some(("http", _)) => "http",
        _ => "direct",
    }
}

/// The `auth_scheme` property. `auto` is not one of the three wire values: it is a
/// *policy* ("answer whatever is offered"), and what gets reported is what will actually
/// be presented.
fn auth_scheme(cfg: &EgressConfig) -> &'static str {
    match cfg.auth {
        ProxyAuth::None => "none",
        ProxyAuth::Negotiate => "negotiate",
        ProxyAuth::Basic => "basic",
        ProxyAuth::Auto if cfg.username.is_some() => "basic",
        ProxyAuth::Auto => "none",
    }
}

/// Emit `proxy_configured` for a route that was just decided.
///
/// Shape only — never an address. `tls_intercepted` is omitted rather than sent as `false`
/// when no handshake has been observed: `false` would assert an observation this run does
/// not have.
pub fn emit_proxy_configured(
    cfg: &EgressConfig,
    discovery_attempts: usize,
    tls_intercepted: Option<bool>,
) {
    let in_use = cfg.mode != ProxyMode::Direct
        && (cfg.url.is_some()
            || matches!(cfg.source, Some(ProxySource::Pac) | Some(ProxySource::Wpad)));
    crate::telemetry::capture_global(crate::telemetry::Event::proxy_configured(
        in_use,
        proxy_type(cfg),
        cfg.source.map(source_str),
        auth_scheme(cfg),
        egress::tls::ca_source(cfg).as_str(),
        tls_intercepted,
        // The event's contract types this as a small counter; the caller counts probe
        // attempts, of which there are a handful. Saturating rather than casting so a
        // pathological count reports a large number instead of a wrapped small one.
        u32::try_from(discovery_attempts).unwrap_or(u32::MAX),
        crate::telemetry::telemetry_os(),
    ));
}

// ---------------------------------------------------------------------------
// The verbs
// ---------------------------------------------------------------------------

/// The resolved egress config plus the platform origin it targets.
fn current() -> Result<(crate::config::Config, EgressConfig), OlError> {
    // `Config::load` already attached the stored proxy password, so this is the resolved
    // route exactly as the daemon would build it.
    let cfg = crate::config::Config::load(None, None, false)?;
    let egress_cfg = cfg.egress.clone();
    Ok((cfg, egress_cfg))
}

fn config_path() -> std::path::PathBuf {
    crate::config::openlatch_dir().join("config.toml")
}

/// `openlatch proxy status` — what route is in effect, in both contexts.
///
/// Renders the Cloud section through the shared detectors (one detector set — a command
/// with a private opinion about health is what the CLI Output Contract forbids), then adds
/// the resolution lines only this command has: the CLI-context route always, and the
/// daemon's when it differs.
fn status(output: &OutputConfig) -> Result<(), OlError> {
    crate::cli::header::print(output, &["proxy", "status"]);
    let (cfg, egress_cfg) = current()?;

    let cli_source = egress_cfg.source.map(source_str).unwrap_or("unset");
    let cli_route = egress_cfg
        .url
        .as_deref()
        .map(mask_userinfo)
        .unwrap_or_else(|| "direct".to_string());

    // I-3 TOUCHPOINT 2 — the daemon-context row.
    //
    // The daemon resolves its own route in its own session, and on Windows a service
    // context sees genuinely different settings from this one. Reading it requires
    // `GET /admin/egress/status`, which is I-3's endpoint (`EgressState` in the frozen
    // contract). Until it exists this row renders `unknown`, which is the honest answer and
    // the same anti-cascade answer the report model gives for anything the daemon owns.
    // Do NOT synthesize it from this process's resolution: the split between the two
    // contexts is the exact thing an operator cannot self-diagnose today, and inventing
    // agreement would erase it.
    let daemon_route = "unknown";

    if output.format == OutputFormat::Json {
        let body = serde_json::json!({
            "status": "unknown",
            "proxy_in_use": egress_cfg.has_proxy(),
            "proxy_url": egress_cfg.url.as_deref().map(mask_userinfo),
            "source": egress_cfg.source.map(source_str),
            "auth_scheme": auth_scheme(&egress_cfg),
            "ca_source": egress::tls::ca_source(&egress_cfg).as_str(),
            "tls_intercepted": serde_json::Value::Null,
            "last_ok_at": serde_json::Value::Null,
            "last_error": serde_json::Value::Null,
            "consecutive_failures": 0,
            "probing": false,
            "cli_resolution": {
                "source": cli_source,
                "url_masked": cli_route,
            },
            "daemon_resolution": daemon_route,
        });
        let doc = crate::cli::commands::doctor::with_section_verdict(
            body,
            crate::cli::report::Section::Connection,
            output,
        )?;
        output.print_json(&doc);
        return Ok(());
    }

    // Verdict first, in the shape `doctor` uses — same detectors, same marks, same
    // layout. Works with the daemon down: `Connection` resolves the route from config,
    // so the row still says how this host would connect.
    crate::cli::commands::doctor::append_section_verdict(
        crate::cli::report::Section::Connection,
        output,
    )?;

    if output.quiet {
        return Ok(());
    }

    // The resolution detail only this command has. `Route (your shell)` is named for the
    // session it was resolved in, not for the binary: on Windows a service account sees
    // different environment variables from an interactive shell, and the `Connection`
    // check above calls out the disagreement when there is one.
    eprintln!();
    eprintln!("  {:<21}{}", "OpenLatch platform", cfg.cloud.api_url);
    eprintln!(
        "  {:<21}{}",
        "Route (your shell)",
        crate::cli::commands::doctor::cli_route_line(&cfg)
    );
    for warning in &egress_cfg.warnings {
        match warning {
            egress::EgressWarning::EnvCaseMismatch { lower, upper } => eprintln!(
                "  {:<21}{lower} and {upper} disagree — {lower} wins (OL-1226, warning form)",
                "Setting conflict"
            ),
            egress::EgressWarning::UnsupportedNoProxyEntry(e) => eprintln!(
                "  {:<21}no_proxy entry '{e}' is not a form this client matches",
                "Setting ignored"
            ),
        }
    }
    Ok(())
}

/// `openlatch proxy discover` — re-run the ladder and persist the winner.
fn discover(args: &ProxyDiscoverArgs, output: &OutputConfig) -> Result<(), OlError> {
    crate::cli::header::print(output, &["proxy", "discover"]);
    let (cfg, egress_cfg) = current()?;

    // D-7 / D-18: a human's route is never replaced by automation. `--force` is the human
    // saying so again, out loud.
    if egress_cfg.source == Some(ProxySource::Manual) && !args.force {
        return Err(OlError::new(
            ERR_PROXY_CONFIG_INVALID,
            "[proxy] source = \"manual\" — discovery will not overwrite a route you set",
        )
        .with_suggestion(
            "Re-run with `--force` to hand the route back to discovery, or change it \
             directly with `openlatch proxy set <url>`.",
        )
        .with_docs("https://docs.openlatch.ai/errors/OL-1226"));
    }

    refuse_linux_pac(&egress_cfg)?;
    let target = reqwest::Url::parse(&cfg.cloud.api_url).map_err(|_| {
        OlError::new(
            ERR_INVALID_CONFIG,
            format!("[cloud] api_url = '{}' is not a URL", cfg.cloud.api_url),
        )
    })?;
    let probe = egress::HealthProbe::new(&cfg.cloud.api_url, egress_cfg.clone())?;
    let (winner, trace) = egress::discover(Context::UserSession, &egress_cfg, &target, &probe);

    for attempt in &trace {
        output.print_substep(&attempt.trace_line());
    }

    // F-16: an elevated session can see what the daemon's context would see. Printed under
    // its own label and NEVER persisted — the daemon resolves its own route, and a
    // service-context candidate written into the shared `[proxy]` block would be a route
    // this session cannot itself use.
    let mut daemon_trace = Vec::new();
    if is_elevated() {
        let (_, service_trace) =
            egress::discover(Context::DaemonService, &egress_cfg, &target, &probe);
        if !service_trace.is_empty() {
            output.print_substep("daemon context:");
            for attempt in &service_trace {
                output.print_substep(&format!("  {}", attempt.trace_line()));
            }
        }
        daemon_trace = service_trace;
    }

    let Some(found) = winner else {
        // The ladder only ever proposes *proxies*, so an empty ladder means "there is no
        // proxy on this host" — a finding, not a failure. The honest next question is
        // whether a direct route reaches the platform, not whether a proxy that does not
        // exist does.
        //
        // `run_gate` — the path `init` takes — has probed direct before walking the ladder
        // since it was written; only `discover` skipped it. That omission is what made this
        // command answer `OL-1220 — 0 candidate route(s) tried, none worked` on hosts where
        // `openlatch proxy test` reports the very same direct route working: a command
        // declaring the platform unreachable without ever having tried to reach it. The
        // count in that message said so out loud — zero.
        let mut trace = trace;
        trace.push(probe_route(&probe, &egress_cfg, None));
        let direct_works = trace.last().is_some_and(|a| a.probe.is_ok());

        if !direct_works {
            if output.format == OutputFormat::Json {
                output.print_json(&serde_json::json!({
                    "status": "failed",
                    "error": { "code": ERR_EGRESS_UNREACHABLE },
                    "candidates": candidates_json(&trace),
                    "daemon_candidates": candidates_json(&daemon_trace),
                }));
            }
            return Err(nothing_reached(&cfg.cloud.api_url, &trace));
        }

        output.print_step("no proxy needed — this host reaches the platform directly");
        // Nothing is written. There is no route to record, and a `[proxy] url` still on
        // disk is a human's decision that discovery does not get to erase behind their
        // back (D-7) — so it is named instead, with the command that clears it.
        if let Some(stale) = egress_cfg.url.as_deref() {
            output.print_substep(&format!(
                "note: [proxy] url is still set to {} — clear it with `openlatch proxy clear`",
                mask_userinfo(stale)
            ));
        }
        if output.format == OutputFormat::Json {
            output.print_json(&serde_json::json!({
                "status": "ok",
                "source": "direct",
                "url_masked": serde_json::Value::Null,
                "candidates": candidates_json(&trace),
                "daemon_candidates": candidates_json(&daemon_trace),
            }));
        }
        return Ok(());
    };

    let (sets, removes) = route_writes(&found);
    crate::config::persist_proxy_config(&config_path(), &sets, &removes)?;
    let mut resolved = egress_cfg.clone();
    apply_discovered(&mut resolved, &found);
    emit_proxy_configured(
        &resolved,
        trace.iter().filter(|a| a.was_probed()).count(),
        None,
    );

    let source = source_str(found.source);
    let route = resolved
        .url
        .as_deref()
        .map(mask_userinfo)
        .unwrap_or_else(|| "pac".to_string());
    output.print_step(&format!("proxy via {route} ({source})"));
    if output.format == OutputFormat::Json {
        output.print_json(&serde_json::json!({
            "status": "ok",
            "source": source,
            "url_masked": resolved.url.as_deref().map(mask_userinfo),
            "candidates": candidates_json(&trace),
            "daemon_candidates": candidates_json(&daemon_trace),
        }));
    }
    Ok(())
}

/// Are we running with enough privilege to preview the service context?
///
/// A best-effort check, and deliberately so: a false negative costs one extra block of
/// diagnostic output, never correctness. The service-context preview is read-only.
fn is_elevated() -> bool {
    #[cfg(windows)]
    {
        // The service-context rungs read HKLM, which an unelevated process can also read.
        // The preview is worth running whenever it might differ, so this is permissive.
        true
    }
    #[cfg(not(windows))]
    {
        false
    }
}

/// `openlatch proxy set <url>` — the human's route.
fn set(args: &ProxySetArgs, output: &OutputConfig) -> Result<(), OlError> {
    crate::cli::header::print(output, &["proxy", "set"]);

    // argv is world-readable, so this runs before anything else this command does.
    let overrides = ProxyOverrides {
        url: Some(args.url.clone()),
        no_proxy: args.no_proxy.clone(),
        ca_bundle: args.ca_bundle.clone(),
        spn: args.spn.clone(),
        ..Default::default()
    };
    overrides.validate()?;
    let url = parse_proxy_url(&args.url)?;

    let path = config_path();
    if !path.exists() {
        crate::config::ensure_config(crate::config::Config::defaults().port)?;
    }
    let (cfg, base) = current()?;

    let mut resolved = base.clone();
    overrides.apply(&mut resolved)?;
    resolved.mode = ProxyMode::Manual;
    resolved.source = Some(ProxySource::Manual);
    resolved.url = Some(url.clone());

    // Probe once, so the command can prompt for the credential the proxy asks for rather
    // than persisting a route that 407s on every later request with nothing to explain it.
    let mut captured = None;
    let probe = egress::HealthProbe::strict(&cfg.cloud.api_url, resolved.clone())?;
    let parsed = reqwest::Url::parse(&url)
        .map_err(|_| OlError::new(ERR_PROXY_CONFIG_INVALID, format!("'{url}' is not a URL")))?;
    let attempt = probe_route(&probe, &resolved, Some(&parsed));
    let needs_credential = matches!(
        attempt.probe,
        egress::CandidateOutcome::Failed(code) if code == crate::error::ERR_PROXY_AUTH_FAILED
    );
    if needs_credential && prompt::interactive(output, false) {
        let mut prompter = prompt::TerminalPrompter::new(cfg.cloud.api_url.clone());
        if let PromptResult::Answered(user) = prompter.ask_username(&url) {
            if let PromptResult::Answered(secret) = prompter.ask_password(&url, &user) {
                resolved.username = Some(user.clone());
                resolved.env_password =
                    Some(secrecy::ExposeSecret::expose_secret(&secret).to_string());
                if resolved.auth == ProxyAuth::None {
                    resolved.auth = ProxyAuth::Basic;
                }
                // Confirm it before persisting. A credential that is written down and
                // does not work produces a 407 on every later request with nothing on
                // screen to explain it, which is the state this prompt exists to prevent.
                match egress::HealthProbe::strict(&cfg.cloud.api_url, resolved.clone())
                    .map(|p| probe_route(&p, &resolved, Some(&parsed)))
                {
                    Ok(retry) if retry.probe.is_ok() => {
                        captured = Some((url.clone(), user, secret));
                    }
                    _ => {
                        output.print_substep(
                            "That credential did not get through the proxy — the route is \
                             saved, the credential is not. Re-run `openlatch proxy set` to \
                             try again.",
                        );
                        resolved.username = None;
                        resolved.env_password = None;
                    }
                }
            }
        }
    }

    // Both keys, always. Every protection gate in the product keys on
    // `source = "manual"`, and `mode = "manual"` alone would leave discovery free to
    // overwrite the route a human just typed.
    let mut sets = overrides.persistable();
    sets.push(("url", quoted(&url)));
    sets.push(("mode", quoted("manual")));
    sets.push(("source", quoted("manual")));
    if let Some(user) = &resolved.username {
        sets.push(("username", quoted(user)));
    }
    let outcome = GateOutcome {
        config: resolved,
        sets,
        removes: vec!["pac_url"],
        attempts: vec![attempt],
        prompted: captured.is_some(),
        captured,
    };
    persist_outcome(&path, &outcome, output)?;
    emit_proxy_configured(&outcome.config, 1, None);

    output.print_step(&format!("proxy set to {} (manual)", mask_userinfo(&url)));
    output.print_substep("The daemon picks this up at its next start — `openlatch restart`.");
    if output.format == OutputFormat::Json {
        output.print_json(&serde_json::json!({
            "status": "ok",
            "source": "manual",
            "mode": "manual",
            "url_masked": mask_userinfo(&url),
        }));
    }
    Ok(())
}

/// `openlatch proxy clear` — go direct, and take the credential with it.
fn clear(output: &OutputConfig) -> Result<(), OlError> {
    crate::cli::header::print(output, &["proxy", "clear"]);
    let path = config_path();
    if !path.exists() {
        crate::config::ensure_config(crate::config::Config::defaults().port)?;
    }

    // Read the authority BEFORE the route is erased. Credentials are keyed by it, and once
    // `persist_proxy_config` has dropped `url` there is nothing left to name them by — a
    // corporate password left in the keychain is then an orphan nobody can find to remove.
    let authority = crate::config::Config::load(None, None, false)
        .ok()
        .and_then(|c| c.egress.url)
        .and_then(|url| egress::authority_key(&url));

    crate::config::persist_proxy_config(
        &path,
        &[("mode", quoted("direct"))],
        &["url", "source", "pac_url", "username"],
    )?;
    if let Some(authority) = authority.as_deref() {
        credential_store().clear(authority);
    }

    let mut direct = EgressConfig::direct();
    direct.mode = ProxyMode::Direct;
    emit_proxy_configured(&direct, 0, None);

    output.print_step("proxy cleared — outbound requests go direct");
    output.print_substep("The daemon picks this up at its next start — `openlatch restart`.");
    if output.format == OutputFormat::Json {
        output.print_json(&serde_json::json!({
            "status": "ok",
            "mode": "direct",
        }));
    }
    Ok(())
}

/// `openlatch proxy test` — the chain, hop by hop.
///
/// Exit codes follow the CLI Output Contract: `0` when every hop passed, `7` when the
/// chain works but something is degraded, `1` when a hop failed.
fn test(args: &ProxyTestArgs, output: &OutputConfig) -> Result<(), OlError> {
    crate::cli::header::print(output, &["proxy", "test"]);
    let (cfg, egress_cfg) = current()?;
    let target = args
        .url
        .clone()
        .unwrap_or_else(|| cfg.cloud.api_url.clone());

    let source = egress_cfg.source.map(source_str).unwrap_or("none");
    let route = egress_cfg.url.as_deref().map(mask_userinfo);

    let probe = egress::HealthProbe::new(&target, egress_cfg.clone())?;
    let parsed = egress_cfg
        .url
        .as_deref()
        .and_then(|u| reqwest::Url::parse(u).ok());
    let attempt = probe_route(&probe, &egress_cfg, parsed.as_ref());

    // I-3 TOUCHPOINT 1 — the streaming leg's verdict.
    //
    // Production has no streaming target to aim at: the client holds no provider
    // credential, and a credential-less POST to api.anthropic.com is answered 401 without
    // ever streaming — that classifies the proxy, not the stream. `Skipped` is the enum's
    // own word for it ("no valid streaming target was available, so nothing was
    // attempted"), and it is the verdict `StreamVerdict::Skipped` is documented to carry
    // in production.
    //
    // It says nothing about this host, so it must not colour the exit code. `unclassified`
    // used to stand here and did, which made every healthy chain exit 7.
    //
    // When I-3's detector lands it calls `egress::stream_probe(&client, target)` here and
    // renders the returned `StreamProbe`. Do NOT infer `streaming` from a 200.
    let stream = egress::StreamVerdict::Skipped;

    let failed = !attempt.probe.is_ok();
    if output.format == OutputFormat::Json {
        let mut doc = serde_json::json!({
            "status": if failed { "failed" } else { "ok" },
            "source": source,
            "proxy": {
                "url_masked": route,
                "connect_ms": attempt.latency_ms,
                "auth_scheme": auth_scheme(&egress_cfg),
            },
            "tls": {
                // Readable only on a SUCCESSFUL handshake — reqwest's TlsInfo exposes
                // nothing on failure — so both fields stay null until I-3's diagnostic
                // read lands. A guessed issuer in a security tool is worse than none.
                "issuer": serde_json::Value::Null,
                "intercepted": serde_json::Value::Null,
            },
            "http": {
                "code": if failed { serde_json::Value::Null } else { serde_json::json!(200) },
                "ms": attempt.latency_ms,
            },
            "stream": { "verdict": stream.as_str() },
        });
        if failed {
            doc["error"] = serde_json::json!({
                "code": attempt.probe.as_str(),
                "message": format!("{target} was not reachable through this route"),
            });
        }
        output.print_json(&doc);
    } else {
        let via = route.clone().unwrap_or_else(|| "direct".to_string());
        let ms = attempt.latency_ms;
        let rows = [
            ("source", source.to_string(), String::new()),
            (
                "proxy",
                via,
                format!("{} · {ms} ms", if failed { "failed" } else { "CONNECT ok" }),
            ),
            (
                "http",
                "GET /api/v1/health".to_string(),
                format!("{} · {ms} ms", attempt.probe.as_str()),
            ),
            ("stream", target.clone(), stream.as_str().to_string()),
        ];
        // One width for the whole table, measured from the rows themselves. The
        // padding used to be spaces typed into each format string, so the verdict
        // column drifted the moment a proxy URL or an api_url was longer than the
        // guess — which is every host whose route is not exactly `direct`.
        let width = rows
            .iter()
            .filter(|(_, _, verdict)| !verdict.is_empty())
            .map(|(_, detail, _)| detail.chars().count())
            .max()
            .unwrap_or(0);
        let label_width = LABEL_WIDTH;
        for (label, detail, verdict) in &rows {
            if verdict.is_empty() {
                output.print_substep(&format!("{label:<label_width$}{detail}"));
            } else {
                output.print_substep(&format!(
                    "{label:<label_width$}{detail:<width$}  [{verdict}]"
                ));
            }
        }
    }

    if failed {
        crate::cli::report::record_exit_code(1);
    } else if stream_degrades(stream) {
        crate::cli::report::record_exit_code(crate::cli::report::EXIT_DEGRADED);
    }
    Ok(())
}

/// Width of the `source` / `proxy` / `http` / `stream` label column, gutter included.
const LABEL_WIDTH: usize = 10;

/// Whether a streaming verdict means this host is running below full capability.
///
/// Only a hop that reassembles the stream does: the request still succeeds, so
/// `OL-1228` is a warning rather than a failure — exit `7`, by the contract's
/// definition of it. A leg that was never attempted says nothing about the host
/// and must not cost the operator their exit `0`.
fn stream_degrades(verdict: egress::StreamVerdict) -> bool {
    use egress::StreamVerdict as V;
    match verdict {
        V::Buffered => true,
        V::Streaming | V::Skipped => false,
        // The leg ran and could not be read — a refused connection, a non-2xx, a
        // body that closed empty. Something in the path answered oddly, and that
        // is worth the warning even though the chain itself stands.
        V::Unclassified => true,
    }
}

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

    /// argv is world-readable from the instant the process starts, so the refusal has to
    /// name the two channels that are not.
    #[test]
    fn userinfo_in_the_proxy_flag_is_rejected_naming_the_alternatives() {
        let o = ProxyOverrides {
            url: Some("http://alice:s3cr3t@proxy.corp:8080".into()),
            ..Default::default()
        };
        let err = o.validate().expect_err("userinfo in argv must be refused");
        assert_eq!(err.code, ERR_PROXY_CONFIG_INVALID);
        let suggestion = err.suggestion.unwrap_or_default();
        assert!(
            suggestion.contains("OPENLATCH_PROXY"),
            "the remedy must name the env var: {suggestion}"
        );
        assert!(
            suggestion.contains("prompt"),
            "the remedy must name the prompt: {suggestion}"
        );
        assert!(
            !err.message.contains("s3cr3t") && !suggestion.contains("s3cr3t"),
            "the refusal must not repeat the password back"
        );
    }

    #[test]
    fn a_clean_proxy_flag_passes() {
        let o = ProxyOverrides {
            url: Some("http://proxy.corp:8080".into()),
            ..Default::default()
        };
        assert!(o.validate().is_ok());
    }

    /// The frozen `source` enum has no `cli` value: a flag win is a human-provided route,
    /// same as the prompt and `proxy set`, and every protection gate keys on `manual`.
    #[test]
    fn a_proxy_flag_win_persists_as_manual() {
        let o = ProxyOverrides {
            url: Some("http://proxy.corp:8080".into()),
            ..Default::default()
        };
        let mut cfg = EgressConfig::direct();
        o.apply(&mut cfg).expect("apply");
        assert_eq!(cfg.mode, ProxyMode::Manual);
        assert_eq!(cfg.source, Some(ProxySource::Manual));
        assert_eq!(cfg.url.as_deref(), Some("http://proxy.corp:8080"));
    }

    /// Per key, never per block: `--proxy-auth` alone must not invent a route.
    #[test]
    fn overrides_apply_per_key() {
        let o = ProxyOverrides {
            auth: Some("basic".into()),
            ..Default::default()
        };
        let mut cfg = EgressConfig::direct();
        cfg.url = Some("http://from-config:8080".into());
        o.apply(&mut cfg).expect("apply");
        assert_eq!(cfg.auth, ProxyAuth::Basic);
        assert_eq!(
            cfg.url.as_deref(),
            Some("http://from-config:8080"),
            "a flag that says nothing about the url must leave it alone"
        );
    }

    #[test]
    fn bad_enum_values_are_refused_by_name() {
        for (o, flag) in [
            (
                ProxyOverrides {
                    mode: Some("sometimes".into()),
                    ..Default::default()
                },
                "--proxy-mode",
            ),
            (
                ProxyOverrides {
                    auth: Some("ntlm".into()),
                    ..Default::default()
                },
                "--proxy-auth",
            ),
        ] {
            let err = o.validate().expect_err("an off-enum value must be refused");
            assert_eq!(err.code, ERR_PROXY_CONFIG_INVALID);
            assert!(err.message.contains(flag), "{}", err.message);
        }
    }

    /// The credential comes out of the typed string before anything downstream sees it.
    #[test]
    fn userinfo_is_split_off_a_prompt_answer() {
        let (clean, user, pass) = split_userinfo("http://alice:s3cr3t@proxy.corp:8080");
        assert_eq!(clean, "http://proxy.corp:8080");
        assert_eq!(user.as_deref(), Some("alice"));
        assert_eq!(pass.as_deref(), Some("s3cr3t"));

        // A `@` inside the password must not split the authority early.
        let (clean, _, pass) = split_userinfo("http://alice:p@ss@proxy.corp:8080");
        assert_eq!(clean, "http://proxy.corp:8080");
        assert_eq!(pass.as_deref(), Some("p@ss"));

        // The common case, untouched.
        let (clean, user, pass) = split_userinfo("http://proxy.corp:8080");
        assert_eq!(clean, "http://proxy.corp:8080");
        assert!(user.is_none() && pass.is_none());
    }

    /// The static→PAC transition. A stale `url` left behind is read by the next process as
    /// a static route, and the PAC script is never consulted again.
    #[test]
    fn a_pac_win_removes_the_stale_url() {
        let found = egress::Discovered {
            source: ProxySource::Wpad,
            route: egress::Route::PacSource { pac_url: None },
        };
        let (sets, removes) = route_writes(&found);
        assert!(
            sets.iter().all(|(k, _)| *k != "url"),
            "a PAC win must never write a concrete url: {sets:?}"
        );
        assert!(removes.contains(&"url"), "{removes:?}");
    }

    #[test]
    fn a_static_win_writes_url_and_source() {
        let found = egress::Discovered {
            source: ProxySource::Gnome,
            route: egress::Route::Static(
                reqwest::Url::parse("http://proxy.corp:8080").expect("url"),
            ),
        };
        let (sets, _) = route_writes(&found);
        assert!(
            sets.contains(&("url", "\"http://proxy.corp:8080\"".to_string())),
            "{sets:?}"
        );
        assert!(
            sets.contains(&("source", "\"gnome\"".to_string())),
            "{sets:?}"
        );
    }

    /// `pac` regardless of the scheme the script returned — the script is the route.
    #[test]
    fn proxy_type_reports_pac_for_a_pac_source() {
        let mut cfg = EgressConfig::direct();
        cfg.mode = ProxyMode::Auto;
        cfg.source = Some(ProxySource::Pac);
        cfg.url = Some("http://whatever-the-script-said:8080".into());
        assert_eq!(proxy_type(&cfg), "pac");
    }

    #[test]
    fn proxy_type_reports_the_scheme_otherwise() {
        let mut cfg = EgressConfig::direct();
        cfg.mode = ProxyMode::Manual;
        cfg.source = Some(ProxySource::Manual);
        for (url, expected) in [
            ("http://p:8080", "http"),
            ("https://p:8443", "https"),
            ("socks5h://p:1080", "socks5"),
        ] {
            cfg.url = Some(url.into());
            assert_eq!(proxy_type(&cfg), expected, "{url}");
        }
        cfg.url = None;
        assert_eq!(proxy_type(&cfg), "direct");
    }

    /// Only rungs that really were probed are candidates. A gated rung listed here would
    /// make a host look like it had options it did not.
    #[test]
    fn the_candidate_array_holds_only_probed_rungs() {
        let attempts = vec![
            CandidateAttempt {
                source: ProxySource::Env,
                url_masked: "http://a:1".into(),
                probe: egress::CandidateOutcome::Failed("OL-1221"),
                latency_ms: 4,
                rung: "env",
                detail: None,
            },
            CandidateAttempt {
                source: ProxySource::Wpad,
                url_masked: String::new(),
                probe: egress::CandidateOutcome::Skipped("OL-1225"),
                latency_ms: 0,
                rung: "wpad",
                detail: None,
            },
        ];
        let json = candidates_json(&attempts);
        let arr = json.as_array().expect("array");
        assert_eq!(arr.len(), 1, "{json}");
        assert_eq!(arr[0]["probe"], "OL-1221");
    }

    #[test]
    fn a_ca_bundle_that_is_not_there_is_refused_at_parse_time() {
        let o = ProxyOverrides {
            ca_bundle: Some("definitely-not-a-file.pem".into()),
            ..Default::default()
        };
        let mut cfg = EgressConfig::direct();
        let err = o.apply(&mut cfg).expect_err("a missing bundle must fail");
        assert_eq!(err.code, ERR_PROXY_CONFIG_INVALID);
    }

    /// D-20's other half: the discovery rung refuses GNOME's `mode = 'auto'`; this refuses
    /// a `pac_url` the operator configured outright.
    #[test]
    fn an_explicit_pac_url_is_refused_on_linux_only() {
        let mut cfg = EgressConfig::direct();
        cfg.pac_url = Some("http://wpad.corp/proxy.pac".into());
        let result = refuse_linux_pac(&cfg);
        if cfg!(target_os = "linux") {
            let err = result.expect_err("Linux has no PAC evaluator");
            assert_eq!(err.code, crate::error::ERR_PAC_UNAVAILABLE);
            assert!(
                err.suggestion.unwrap_or_default().contains("[proxy] url"),
                "the D-20 remedy must name the key that replaces it"
            );
        } else {
            assert!(
                result.is_ok(),
                "Windows and macOS have audited PAC evaluators"
            );
        }
    }

    /// A streaming leg that was never attempted is not a degradation of the host.
    ///
    /// This is the whole exit-code rule for that leg, and getting it wrong cost
    /// every healthy host a `7`. `Skipped` is what production reports — no
    /// provider credential means no streaming target to aim at — so if it ever
    /// degrades again, `proxy test` stops being able to exit `0` at all.
    #[test]
    fn only_a_stream_that_actually_misbehaved_costs_the_exit_code() {
        use egress::StreamVerdict as V;
        assert!(
            !stream_degrades(V::Skipped),
            "the production verdict: nothing ran, so nothing is wrong here"
        );
        assert!(!stream_degrades(V::Streaming), "the leg worked");
        assert!(
            stream_degrades(V::Buffered),
            "a hop reassembling the stream is OL-1228 — a warning, and warnings are 7"
        );
        assert!(
            stream_degrades(V::Unclassified),
            "the leg ran and could not be read: something in the path answered oddly"
        );
    }
}