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
//! OS discovery — precedence tier 5 of the frozen resolver contract, plus the tier-4
//! standard-environment rung that sits directly above it.
//!
//! The ladder is walked one rung at a time and **lazily**: a rung is only evaluated when
//! every rung above it has already failed its probe. That laziness is load-bearing rather
//! than an optimisation — the bottom rungs are WPAD and PAC evaluation, which reach the
//! network and can block for seconds, and a host whose first rung already works must never
//! pay for them.
//!
//! Three properties this module exists to guarantee:
//!
//! - **A PAC win never materialises a URL.** PAC may legally return a different proxy, or
//!   `DIRECT`, for every destination, so discovery persists the PAC *source* and the
//!   factory re-evaluates per destination through the OS at request time. [`Route`] makes
//!   that type-level: [`Route::PacSource`] has nowhere to put a proxy URL.
//! - **Every rung the ladder reaches leaves exactly one [`CandidateAttempt`]**, win or
//!   lose, gated or empty. The trace is a first-class output — `init --json`, `proxy
//!   discover`, `proxy test` and I-3's self-heal log all render it — and it cannot be
//!   recomputed after the fact.
//! - **WPAD happens only by OS delegation, and only when the OS says it may.** We never
//!   speak the protocol ourselves and never re-enable one a security baseline turned off.
//!
//! Module shape follows the repo's multi-backend pattern (`core::supervision`):
//! unconditional `mod` declarations with `#[cfg]` *inside*, so every ladder's logic
//! type-checks on every host and only the OS calls behind each backend's seam are
//! platform-specific.

pub mod env;
pub mod linux;
pub mod macos;
pub mod windows;

use std::collections::HashMap;
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};

use reqwest::Url;

use crate::core::error::{
    OlError, ERR_EGRESS_TLS_FAILED, ERR_EGRESS_UNREACHABLE, ERR_PAC_UNAVAILABLE,
    ERR_PROXY_AUTH_FAILED, ERR_PROXY_UNREACHABLE,
};

use super::config::{EgressConfig, ProxyMode, ProxySource};
use super::factory::{build_client, Consumer};
use super::{mask_userinfo, ProxyCandidate, ProxyResolver};

/// The complete rung vocabulary — one tag per ladder position, across all three OSes.
///
/// These are trace labels, not an enum, because their only consumers are a log line and a
/// test assertion, and a closed constant set gives both without a conversion layer. Adding
/// a rung means adding a constant here first: the inline `every_rung_tag_is_known` test
/// fails on a tag that is not in this list.
pub mod rung {
    /// Tier 4 — the standard `https_proxy` / `HTTP_PROXY` family.
    pub const ENV: &str = "env";
    /// Windows, user session — `WinHttpGetIEProxyConfigForCurrentUser` static settings.
    pub const WININET_USER: &str = "wininet-user";
    /// Windows, user session — the per-user `AutoConfigURL` PAC.
    pub const IE_PAC: &str = "ie-pac";
    /// Windows — machine WinHTTP defaults (`WinHttpGetDefaultProxyConfiguration`).
    pub const WINHTTP_MACHINE: &str = "winhttp-machine";
    /// Windows, service context — `HKLM` Internet Settings under `ProxySettingsPerUser=0`.
    pub const HKLM_INETSETTINGS: &str = "hklm-inetsettings";
    /// Windows — WPAD auto-detect, delegated to WinHTTP and gated.
    pub const WPAD: &str = "wpad";
    /// macOS — the global `SCDynamicStore` proxy dictionary.
    pub const SC_STATIC: &str = "sc-static";
    /// macOS — a `__SCOPED__` per-interface dictionary.
    pub const SC_SCOPED: &str = "sc-scoped";
    /// macOS — PAC evaluated through CFNetwork.
    pub const CFNET_PAC: &str = "cfnet-pac";
    /// Linux — GNOME `org.gnome.system.proxy`.
    pub const GSETTINGS: &str = "gsettings";

    /// Every tag above, for the trace-vocabulary test and for diagnostics that want to
    /// render an empty row per rung.
    pub const ALL: &[&str] = &[
        ENV,
        WININET_USER,
        IE_PAC,
        WINHTTP_MACHINE,
        HKLM_INETSETTINGS,
        WPAD,
        SC_STATIC,
        SC_SCOPED,
        CFNET_PAC,
        GSETTINGS,
    ];
}

/// Which session the ladder is being walked in.
///
/// The two contexts see genuinely different settings, not merely different permissions: a
/// service running as `SYSTEM` has no per-user hive to read, and reading one anyway would
/// pick up whichever profile happened to be loaded.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Context {
    /// `init`, `proxy discover`, and every other interactive CLI invocation.
    UserSession,
    /// The daemon, which on Windows may be running as a service.
    DaemonService,
}

/// What happened to one rung.
///
/// Serialises as the single string the frozen CLI-JSON candidate object specifies —
/// `"ok"`, or the `OL-` code — with one addition: a rung that ran and simply found nothing
/// configured is [`CandidateOutcome::NotConfigured`], which is neither. It renders as
/// `"none"`, and the `candidates` array in `init --json` filters it out (see
/// [`CandidateAttempt::was_probed`]), because a rung that produced no candidate never was
/// one. The trace keeps it, since "we looked here and it was empty" is exactly what makes
/// a failed discovery diagnosable.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CandidateOutcome {
    /// The candidate answered the health probe.
    Ok,
    /// The candidate was probed and failed. Carries the `OL-` code.
    Failed(&'static str),
    /// Never probed: the rung was gated shut, refused, or its settings were incomplete.
    /// Carries the `OL-` code naming why.
    Skipped(&'static str),
    /// Never probed: the rung ran and this host has nothing configured there.
    NotConfigured,
}

impl CandidateOutcome {
    /// The wire value.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Ok => "ok",
            Self::Failed(code) | Self::Skipped(code) => code,
            Self::NotConfigured => "none",
        }
    }

    /// Did this rung win?
    pub fn is_ok(&self) -> bool {
        matches!(self, Self::Ok)
    }
}

impl serde::Serialize for CandidateOutcome {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(self.as_str())
    }
}

/// One rung of the ladder, recorded.
///
/// The serialised fields are exactly the frozen CLI-JSON candidate object — `source`,
/// `url_masked`, `probe`, `latency_ms` — so one shape serves all four consumers (the
/// `init` JSON report, `proxy discover`, `proxy test`'s source hop, and I-3's self-heal
/// log). `rung` and `detail` are the human trace's, and are deliberately not on the wire:
/// the JSON shape is frozen, and a diagnostic that grows a field is a contract change.
#[derive(Debug, Clone, serde::Serialize)]
pub struct CandidateAttempt {
    /// Where this candidate would have come from.
    pub source: ProxySource,
    /// The candidate route, userinfo masked. Empty when the rung produced none.
    pub url_masked: String,
    /// See [`CandidateOutcome`].
    pub probe: CandidateOutcome,
    /// Round-trip of the probe, or time spent failing. Zero when nothing was probed.
    pub latency_ms: u64,
    /// The rung tag — one of [`rung::ALL`].
    #[serde(skip)]
    pub rung: &'static str,
    /// Free-text detail for the human trace: which gate closed, what the PAC returned,
    /// what remedy applies. Never on the wire.
    #[serde(skip)]
    pub detail: Option<String>,
}

impl CandidateAttempt {
    /// Was this rung actually probed? False for gated and empty rungs.
    ///
    /// This is the filter the `init --json` `candidates` array applies, so the array holds
    /// only things that really were candidates.
    pub fn was_probed(&self) -> bool {
        matches!(
            self.probe,
            CandidateOutcome::Ok | CandidateOutcome::Failed(_)
        )
    }

    /// One line for the human trace.
    pub fn trace_line(&self) -> String {
        let mut line = format!("{:<18} {}", self.rung, self.probe.as_str());
        if !self.url_masked.is_empty() {
            line.push_str(&format!(" {}", self.url_masked));
        }
        if self.was_probed() {
            line.push_str(&format!(" [{} ms]", self.latency_ms));
        }
        if let Some(d) = &self.detail {
            line.push_str(&format!("{d}"));
        }
        line
    }
}

/// How the winning candidate reaches a destination.
///
/// The PAC persistence rule, made unrepresentable-otherwise: a PAC or WPAD win carries the
/// *source* and nothing else. There is no field on [`Route::PacSource`] for a proxy URL,
/// so no amount of downstream code can persist one.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Route {
    /// One concrete proxy, the same for every destination.
    Static(Url),
    /// A PAC script the OS re-evaluates per destination. `pac_url` is `None` for WPAD,
    /// where the OS also owns discovering the script's location.
    PacSource {
        /// The explicit PAC URL, when there is one.
        pac_url: Option<Url>,
    },
}

/// The winning rung.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Discovered {
    /// Provenance, written to `[proxy] source`.
    pub source: ProxySource,
    /// See [`Route`].
    pub route: Route,
}

/// Validates one candidate before it can win.
///
/// A trait with one method so tests inject outcomes instead of standing up a proxy per
/// case. The production implementation is [`HealthProbe`].
///
/// `proxy` is `None` for a direct route, which is a real answer rather than an absence: a
/// PAC that returns `DIRECT` for the probe target has answered correctly, and validating
/// that answer means probing without a proxy.
pub trait CandidateProbe {
    /// Reach the health endpoint through `proxy`, returning the round trip in ms.
    fn probe(&self, proxy: Option<&Url>) -> Result<u64, OlError>;
}

/// What one rung produced, before probing.
///
/// Every rung the ladder reaches returns exactly one of these, which is what makes "one
/// trace entry per reached rung" an invariant of the type rather than of the call sites.
pub enum RungResult {
    /// The rung produced a route. `route` is what a win persists; `probe_via` is what the
    /// probe dials, which differs on a PAC rung — there the route is the PAC source and
    /// `probe_via` is the answer the PAC gave *for the probe target only*.
    Candidate {
        /// Provenance to persist on a win.
        source: ProxySource,
        /// What a win persists. See [`Route`].
        route: Route,
        /// What the probe dials. `None` means direct.
        probe_via: Option<Url>,
    },
    /// The rung could not run, or refused to: a closed gate, an unsupported facility,
    /// settings too incomplete to use.
    Skipped {
        /// Provenance the rung would have had.
        source: ProxySource,
        /// The `OL-` code naming the refusal.
        code: &'static str,
        /// What closed the rung, and where it lives.
        detail: String,
    },
    /// The rung ran and this host has nothing configured there.
    NotConfigured {
        /// Provenance the rung would have had.
        source: ProxySource,
        /// Why it was empty, when that is worth saying.
        detail: Option<String>,
    },
}

impl RungResult {
    /// A gated or refused rung, with the reason that goes in the trace.
    ///
    /// Reserved for decisions: a policy that closed the rung, a facility this build has
    /// no evaluator for, settings too incomplete to use. A rung that merely holds nothing
    /// is [`RungResult::empty`], because an operator sent hunting for a gate that does not
    /// exist has been sent to the wrong place.
    pub fn skipped(source: ProxySource, code: &'static str, detail: impl Into<String>) -> Self {
        Self::Skipped {
            source,
            code,
            detail: detail.into(),
        }
    }

    /// A rung that ran and found nothing.
    pub fn empty(source: ProxySource) -> Self {
        Self::NotConfigured {
            source,
            detail: None,
        }
    }

    /// A rung that found nothing, with the reason worth saying out loud.
    pub fn empty_with(source: ProxySource, detail: impl Into<String>) -> Self {
        Self::NotConfigured {
            source,
            detail: Some(detail.into()),
        }
    }

    /// A static proxy candidate — the route and the probe target are the same thing.
    pub fn static_route(source: ProxySource, url: Url) -> Self {
        Self::Candidate {
            source,
            probe_via: Some(url.clone()),
            route: Route::Static(url),
        }
    }
}

/// Walks the ladder: probes each rung's candidate, records the attempt, and reports
/// whether the walk is over.
pub struct Ladder<'a> {
    probe: &'a dyn CandidateProbe,
    attempts: Vec<CandidateAttempt>,
    winner: Option<Discovered>,
    /// When true the ladder records candidates without ever declaring a winner. This is
    /// how [`ProxyResolver::candidates`] enumerates the whole ladder instead of selecting
    /// from it — see the impl for why enumeration and selection are the same walk.
    enumerate: bool,
}

impl<'a> Ladder<'a> {
    pub fn new(probe: &'a dyn CandidateProbe) -> Self {
        Self {
            probe,
            attempts: Vec::new(),
            winner: None,
            enumerate: false,
        }
    }

    fn enumerating(probe: &'a dyn CandidateProbe) -> Self {
        Self {
            enumerate: true,
            ..Self::new(probe)
        }
    }

    /// Offer one rung. `true` means the ladder is finished and no lower rung should even
    /// be *computed* — which is what keeps WPAD and PAC evaluation off the fast path.
    pub fn offer(&mut self, tag: &'static str, result: RungResult) -> bool {
        let attempt = match result {
            RungResult::NotConfigured { source, detail } => CandidateAttempt {
                source,
                url_masked: String::new(),
                probe: CandidateOutcome::NotConfigured,
                latency_ms: 0,
                rung: tag,
                detail,
            },
            RungResult::Skipped {
                source,
                code,
                detail,
            } => CandidateAttempt {
                source,
                url_masked: String::new(),
                probe: CandidateOutcome::Skipped(code),
                latency_ms: 0,
                rung: tag,
                detail: Some(detail),
            },
            RungResult::Candidate {
                source,
                route,
                probe_via,
            } => {
                let detail = probe_detail(&route, probe_via.as_ref());
                let started = Instant::now();
                let (probe, latency_ms) = match self.probe.probe(probe_via.as_ref()) {
                    Ok(ms) => (CandidateOutcome::Ok, ms),
                    Err(e) => (CandidateOutcome::Failed(e.code), elapsed_ms(started)),
                };
                if probe.is_ok() && !self.enumerate {
                    self.winner = Some(Discovered {
                        source,
                        route: route.clone(),
                    });
                }
                CandidateAttempt {
                    source,
                    url_masked: mask_userinfo(&route_display(&route)),
                    probe,
                    latency_ms,
                    rung: tag,
                    detail,
                }
            }
        };
        self.attempts.push(attempt);
        self.winner.is_some()
    }

    pub fn finish(self) -> (Option<Discovered>, Vec<CandidateAttempt>) {
        (self.winner, self.attempts)
    }
}

fn elapsed_ms(started: Instant) -> u64 {
    u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)
}

/// What a route is called in the trace.
///
/// A PAC route is named by its script, never by the proxy the script happened to return —
/// rendering the answer here is how a copy-paste turns into a materialised URL.
fn route_display(route: &Route) -> String {
    match route {
        Route::Static(u) => authority_form(u),
        Route::PacSource { pac_url: Some(u) } => format!("pac:{u}"),
        Route::PacSource { pac_url: None } => "pac:wpad".to_string(),
    }
}

/// The per-target answer, for the human trace only.
fn probe_detail(route: &Route, probe_via: Option<&Url>) -> Option<String> {
    match route {
        Route::Static(_) => None,
        Route::PacSource { .. } => Some(match probe_via {
            Some(u) => format!("pac answered {} for the probe target", authority_form(u)),
            None => "pac answered DIRECT for the probe target".to_string(),
        }),
    }
}

/// `scheme://host:port` — the form a proxy URL is written and persisted in.
///
/// [`Url::as_str`] appends the empty path (`http://proxy:8080/`). That is the same route,
/// but not the string an operator typed, and `[proxy] url` should carry what they typed.
pub fn authority_form(u: &Url) -> String {
    let host = u.host_str().unwrap_or_default();
    // `port_or_known_default`, never `port`: the latter is `None` when the port equals the
    // scheme's own default, which would silently drop the `:443` an operator typed.
    match u.port_or_known_default() {
        Some(p) => format!("{}://{host}:{p}", u.scheme()),
        None => format!("{}://{host}", u.scheme()),
    }
}

/// Parse one discovered proxy string into a URL, applying the discovery-only rules.
///
/// Two things happen here that never happen to a *configured* URL:
///
/// - A bare `host:port` gets `http://`, because that is what every OS proxy field means
///   when it omits a scheme.
/// - A bare `socks5://` becomes `socks5h://`. Resolving the destination name locally and
///   handing the proxy an address is exactly wrong on a network where the proxy is the
///   only thing that can resolve internal names. A URL the operator *configured* is left
///   alone — they asked for that scheme — but a discovered one carries no such intent.
pub fn parse_discovered(raw: &str) -> Option<Url> {
    let raw = raw.trim();
    if raw.is_empty() {
        return None;
    }
    let with_scheme = if raw.contains("://") {
        raw.to_string()
    } else {
        format!("http://{raw}")
    };
    let mut url = Url::parse(&with_scheme).ok()?;
    if !matches!(url.scheme(), "http" | "https" | "socks5" | "socks5h") {
        return None;
    }
    if url.host_str().is_none_or(str::is_empty) {
        return None;
    }
    if url.scheme() == "socks5" {
        url.set_scheme("socks5h").ok()?;
    }
    Some(url)
}

/// Walk the ladder for `target` and return the winner plus the full trace.
///
/// `cfg` is carried explicitly so the tier-4 rung reports the resolution
/// [`EgressConfig::resolve`] already performed rather than re-reading the environment —
/// re-reading would duplicate, and could contradict, its lowercase-wins rule and its Unix
/// disagreement warning.
pub fn discover(
    ctx: Context,
    cfg: &EgressConfig,
    target: &Url,
    probe: &dyn CandidateProbe,
) -> (Option<Discovered>, Vec<CandidateAttempt>) {
    // `direct` is a decision, not an absence: walking the ladder under it would spend
    // network on candidates the config has already refused to use.
    if cfg.mode == ProxyMode::Direct {
        return (None, Vec::new());
    }
    let mut ladder = Ladder::new(probe);
    walk(&mut ladder, ctx, cfg, target);
    ladder.finish()
}

fn walk(ladder: &mut Ladder, ctx: Context, cfg: &EgressConfig, target: &Url) {
    if ladder.offer(rung::ENV, env::rung(cfg)) {
        return;
    }
    os_rungs(ladder, ctx, target);
}

/// Dispatch to the OS ladder. Rung *order* lives inside each OS file, where the frozen
/// contract row for that OS can be read next to the code implementing it.
fn os_rungs(ladder: &mut Ladder, ctx: Context, target: &Url) {
    #[cfg(windows)]
    {
        windows::walk(ladder, ctx, windows::native(), target);
    }
    #[cfg(target_os = "macos")]
    {
        macos::walk(ladder, ctx, &macos::native(), target);
    }
    #[cfg(target_os = "linux")]
    {
        linux::walk(ladder, ctx, &linux::native(), target);
    }
    #[cfg(not(any(windows, target_os = "macos", target_os = "linux")))]
    {
        // No OS discovery facility we support. Tier 4 above and DIRECT below still apply.
        let _ = (ladder, ctx, target);
    }
}

// ---------------------------------------------------------------------------
// PAC, per destination (F-05)
// ---------------------------------------------------------------------------

/// What an OS PAC evaluator answered for one URL. An empty list means `DIRECT`.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PacAnswer {
    /// The proxy list, in the OS's preference order.
    pub proxies: Vec<String>,
}

impl PacAnswer {
    /// The first proxy this answer names, or `None` when it says `DIRECT`.
    pub fn first_route(&self) -> Option<Url> {
        self.proxies.iter().find_map(|e| parse_pac_entry(e))
    }

    /// Does the answer name a proxy at all, as opposed to `DIRECT`?
    ///
    /// The distinction decides whether an unparsable answer is a misconfiguration worth
    /// reporting or simply a destination the PAC sends direct.
    pub fn names_a_proxy(&self) -> bool {
        self.proxies.iter().any(|e| !is_direct(e))
    }
}

fn is_direct(entry: &str) -> bool {
    pac_keyword(entry).0 == "DIRECT"
}

fn pac_keyword(entry: &str) -> (String, &str) {
    let e = entry.trim();
    match e.split_once(char::is_whitespace) {
        Some((k, rest)) => (k.to_ascii_uppercase(), rest.trim()),
        None => (e.to_ascii_uppercase(), ""),
    }
}

/// One entry of a PAC answer.
///
/// The OS evaluators mostly hand back a bare `host:port` list -- WinHTTP's
/// `WINHTTP_PROXY_INFO` certainly does -- but accepting the script's own `FindProxyForURL`
/// grammar as well costs one split, and it is what a fixture in a test can be written in.
fn parse_pac_entry(entry: &str) -> Option<Url> {
    let (keyword, rest) = pac_keyword(entry);
    match keyword.as_str() {
        "DIRECT" => None,
        "PROXY" | "HTTP" => parse_discovered(rest),
        // `HTTPS` means TLS to the proxy itself, which is a different thing from proxying
        // https traffic.
        "HTTPS" => parse_discovered(&format!("https://{rest}")),
        "SOCKS" | "SOCKS4" | "SOCKS5" => parse_discovered(&format!("socks5h://{rest}")),
        _ => parse_discovered(entry),
    }
}

/// Which OS facility evaluates the PAC.
///
/// We ship no PAC engine: JavaScript in the egress path of a security client is a new
/// attack surface and a new maintenance burden, and both platforms that have PAC already
/// have an audited evaluator.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PacFacility {
    /// `WinHttpGetProxyForUrl` against a process-lived session.
    WinHttp,
    /// `CFNetworkExecuteProxyAutoConfigurationURL` on a bounded run loop.
    CfNetwork,
}

/// Everything the factory needs to ask the OS for a per-destination route.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PacBinding {
    /// See [`PacFacility`].
    pub facility: PacFacility,
    /// The explicit PAC URL, or `None` for WPAD.
    pub pac_url: Option<Url>,
}

/// The PAC facility this host has, if any.
pub fn native_pac_facility() -> Option<PacFacility> {
    #[cfg(windows)]
    {
        Some(PacFacility::WinHttp)
    }
    #[cfg(target_os = "macos")]
    {
        Some(PacFacility::CfNetwork)
    }
    #[cfg(not(any(windows, target_os = "macos")))]
    {
        None
    }
}

/// The binding a PAC-sourced configuration implies, or `None` when this config routes
/// statically (or when this OS has no PAC facility, which on Linux is the whole of D-20).
pub fn pac_binding(cfg: &EgressConfig) -> Option<PacBinding> {
    if cfg.mode == ProxyMode::Direct {
        return None;
    }
    if !matches!(cfg.source, Some(ProxySource::Pac) | Some(ProxySource::Wpad)) {
        return None;
    }
    Some(PacBinding {
        facility: native_pac_facility()?,
        pac_url: cfg.pac_url.as_deref().and_then(|u| Url::parse(u).ok()),
    })
}

/// How long a PAC answer is reused for one destination host.
const PAC_TTL: Duration = Duration::from_secs(60);

type PacCache = Mutex<HashMap<String, (Instant, Option<Url>)>>;

fn pac_cache() -> &'static PacCache {
    static CACHE: OnceLock<PacCache> = OnceLock::new();
    CACHE.get_or_init(|| Mutex::new(HashMap::new()))
}

/// The proxy the PAC names for `target`, or `None` for `DIRECT`.
///
/// This is what the factory's custom-proxy closure calls, once per request. A short TTL
/// dedupe fronts it, keyed by destination host: on macOS it is load-bearing (every
/// `CFNetworkExecuteProxyAutoConfigurationURL` leaks a `CFRunLoopSourceRef` — FB12170226),
/// and on Windows it is cheap insurance on top of the session's own cache.
pub fn pac_route_for(target: &Url, binding: &PacBinding) -> Result<Option<Url>, OlError> {
    pac_route_with(target, binding, &NativePac)
}

/// Answers "what proxy for this destination?" — the OS in production, a fixture in tests.
///
/// The seam exists because the per-destination rule and its TTL are the parts most likely
/// to break, and neither can be exercised through a real corporate PAC server in CI.
pub trait PacEvaluator {
    /// The proxy for `target` under `binding`, or `None` for `DIRECT`.
    fn evaluate(&self, target: &Url, binding: &PacBinding) -> Result<Option<Url>, OlError>;
}

/// The OS PAC facility.
pub struct NativePac;

impl PacEvaluator for NativePac {
    fn evaluate(&self, target: &Url, binding: &PacBinding) -> Result<Option<Url>, OlError> {
        eval_pac_native(target, binding)
    }
}

/// [`pac_route_for`] over an explicit evaluator.
///
/// A failure is deliberately **not** cached: a PAC server that blinked would otherwise pin
/// the wrong answer for a full TTL, and the next request is the cheapest possible retry.
pub fn pac_route_with(
    target: &Url,
    binding: &PacBinding,
    eval: &dyn PacEvaluator,
) -> Result<Option<Url>, OlError> {
    let key = target.host_str().unwrap_or_default().to_ascii_lowercase();
    if let Ok(cache) = pac_cache().lock() {
        if let Some((at, route)) = cache.get(&key) {
            if at.elapsed() < PAC_TTL {
                return Ok(route.clone());
            }
        }
    }
    let route = eval.evaluate(target, binding)?;
    if let Ok(mut cache) = pac_cache().lock() {
        // Unbounded growth is not a concern: the key set is the set of destinations this
        // process talks to, which the egress inventory fixes at a handful.
        cache.insert(key, (Instant::now(), route.clone()));
    }
    Ok(route)
}

/// Drop every cached PAC answer. Exposed for tests and for I-3's self-heal, which must
/// not act on an answer from before the network changed under it.
pub fn clear_pac_cache() {
    if let Ok(mut cache) = pac_cache().lock() {
        cache.clear();
    }
}

fn eval_pac_native(target: &Url, binding: &PacBinding) -> Result<Option<Url>, OlError> {
    match binding.facility {
        #[cfg(windows)]
        PacFacility::WinHttp => windows::eval_pac(windows::native(), target, binding),
        #[cfg(target_os = "macos")]
        PacFacility::CfNetwork => macos::eval_pac(&macos::native(), target, binding),
        // Reached on every host that has no PAC facility at all, which on Linux is the
        // whole of D-20. Naming the destination keeps the message useful in a log line
        // that has no other context.
        other => Err(OlError::new(
            ERR_PAC_UNAVAILABLE,
            format!(
                "no {other:?} PAC evaluator exists on this platform, so {} has no route",
                target.host_str().unwrap_or("the destination")
            ),
        )
        .with_suggestion(
            "Set an explicit proxy with `openlatch proxy set <url>`, or [proxy] url in \
             config.toml.",
        )),
    }
}

// ---------------------------------------------------------------------------
// The production probe
// ---------------------------------------------------------------------------

/// `GET {api_url}/api/v1/health` through the candidate, on an async factory client.
///
/// Async, never [`super::build_blocking_client`], and that is a correctness requirement
/// rather than a style preference: the blocking client has no Negotiate transport, so on a
/// Kerberos-only estate every *correct* candidate would fail its probe and discovery could
/// never succeed — on exactly the estates Negotiate exists for.
///
/// The runtime is owned here because `discover` is synchronous and its first caller is
/// `init`. A caller already inside a Tokio runtime must reach this through
/// `spawn_blocking`; `block_on` inside a runtime panics, and that is the one way to misuse
/// this type.
pub struct HealthProbe {
    base: EgressConfig,
    health_url: String,
    runtime: tokio::runtime::Runtime,
    strict: bool,
}

impl HealthProbe {
    /// Probe against `{api_url}/api/v1/health`, inheriting trust, bypass and auth settings
    /// from `base` while replacing its route with each candidate in turn.
    ///
    /// **Lenient about `407`**: a proxy that demands authentication has passed. That is the
    /// right answer when *ranking* candidates — see [`classify_probe`] — and the wrong one
    /// when *validating* the route an install is about to run on. Use [`HealthProbe::strict`]
    /// for the latter.
    pub fn new(api_url: &str, base: EgressConfig) -> Result<Self, OlError> {
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .map_err(|e| {
                OlError::new(
                    ERR_EGRESS_UNREACHABLE,
                    format!("could not start a runtime for the discovery probe: {e}"),
                )
            })?;
        Ok(Self {
            base,
            health_url: format!("{}/api/v1/health", api_url.trim_end_matches('/')),
            runtime,
            strict: false,
        })
    }

    /// A probe that only passes on a real `2xx` from the platform.
    ///
    /// The difference from [`HealthProbe::new`] is `407`, and it decides whether an install
    /// behind an authenticating proxy works or merely looks like it does. The lenient rule
    /// exists so discovery can rank a corporate proxy that challenges every request as the
    /// right rung — most of them do, and rejecting them would eliminate most estates. But a
    /// `407` means the health endpoint was never reached, so an install that accepted one as
    /// proof would report a working route, persist it, and forward nothing: the credential
    /// prompt that exists for exactly this case would be unreachable, because the code that
    /// triggers it never sees a failure.
    ///
    /// Ranking is lenient; validating is strict. Same request, same client, same trust —
    /// only the verdict on `407` differs.
    pub fn strict(api_url: &str, base: EgressConfig) -> Result<Self, OlError> {
        let mut probe = Self::new(api_url, base)?;
        probe.strict = true;
        Ok(probe)
    }
}

impl CandidateProbe for HealthProbe {
    fn probe(&self, proxy: Option<&Url>) -> Result<u64, OlError> {
        let mut cfg = self.base.clone();
        match proxy {
            Some(u) => {
                cfg.mode = ProxyMode::Auto;
                cfg.url = Some(authority_form(u));
            }
            None => {
                // A PAC that answered DIRECT for this destination. `allow_direct = false`
                // refusing here is the right answer, not an error to route around.
                cfg.mode = ProxyMode::Direct;
                cfg.url = None;
            }
        }
        let client = build_client(Consumer::StatusProbe, &cfg)?;
        let url = self.health_url.clone();
        let started = Instant::now();
        let result = self
            .runtime
            .block_on(async move { client.get(&url).send().await });
        classify_probe(result, proxy.is_some(), elapsed_ms(started), self.strict)
    }
}

/// Turn a probe result into a verdict.
///
/// The load-bearing rule: **a proxy that demands authentication has passed.** It answered,
/// it speaks HTTP, and it is the proxy this host is meant to use — refusing it would
/// eliminate every authenticating corporate proxy, which is most of them. Credentials are
/// a separate, configurable concern that `init` prompts for and the credential store
/// holds.
fn classify_probe(
    result: Result<reqwest::Response, reqwest::Error>,
    via_proxy: bool,
    ms: u64,
    strict: bool,
) -> Result<u64, OlError> {
    match result {
        Ok(resp) => {
            if resp.status() == reqwest::StatusCode::PROXY_AUTHENTICATION_REQUIRED {
                let offered = resp
                    .headers()
                    .get_all(reqwest::header::PROXY_AUTHENTICATE)
                    .iter()
                    .filter_map(|v| v.to_str().ok())
                    .collect::<Vec<_>>()
                    .join(", ");
                if strict {
                    return Err(needs_credential(&offered));
                }
                return auth_required(&offered, ms);
            }
            if resp.status().is_success() {
                return Ok(ms);
            }
            // `/api/v1/health` is unauthenticated and answers 2xx, so anything else did not
            // come from it: a proxy's own refusal, or an interception page standing in for
            // the platform. Either way this candidate is not a working route, and the
            // ladder should try the next rung rather than persist it.
            Err(OlError::new(
                if via_proxy {
                    ERR_PROXY_UNREACHABLE
                } else {
                    ERR_EGRESS_UNREACHABLE
                },
                format!(
                    "the platform health endpoint answered {} through this candidate",
                    resp.status().as_u16()
                ),
            ))
        }
        Err(e) => {
            let chain = error_chain(&e);
            // A `CONNECT` that 407s surfaces as a tunnel *error*, and hyper-util's
            // `TunnelError` carries no headers, so the offered scheme is unreadable here.
            // We accept it anyway, for the reason above; the integration test pins the
            // wording so a hyper-util rename breaks a test rather than silently turning
            // every authenticating proxy into a failed candidate.
            if chain.contains("proxy authorization required") || chain.contains("407") {
                if strict {
                    return Err(needs_credential("(unreadable through the tunnel error)"));
                }
                return Ok(ms);
            }
            Err(transport_error(&e, &chain, via_proxy))
        }
    }
}

/// A `407` a strict probe will not accept.
///
/// The offered scheme list rides the message, because the remedy for `Basic` (enter a
/// credential) and the remedy for `NTLM` (ask for a Negotiate-capable path) are different
/// things to do.
fn needs_credential(offered: &str) -> OlError {
    OlError::new(
        ERR_PROXY_AUTH_FAILED,
        format!("the proxy answered 407 and offers: {offered}"),
    )
    .with_suggestion(
        "Provide the proxy credential — `openlatch proxy set <url>` prompts for it, and \
         `OPENLATCH_PROXY` accepts it inline. It is stored in the OS credential store, \
         never in config.toml.",
    )
}

/// Schemes we can actually present. NTLM is absent on purpose — Microsoft deprecated it in
/// 2024, and a proxy offering only NTLM is one this client cannot authenticate to.
fn auth_required(offered: &str, ms: u64) -> Result<u64, OlError> {
    let lower = offered.to_ascii_lowercase();
    let viable =
        lower.contains("basic") || lower.contains("negotiate") || lower.contains("kerberos");
    if viable {
        // Negotiate counts as viable even in a build without `proxy-negotiate`: the
        // candidate is still the right proxy, and a missing transport is a build problem
        // that `check_scheme` names precisely (OL-1223). Failing the probe instead would
        // report "no proxy found" on a domain-joined laptop that has one.
        return Ok(ms);
    }
    Err(OlError::new(
        ERR_PROXY_AUTH_FAILED,
        format!("the proxy requires authentication and offers only: {offered}"),
    )
    .with_suggestion(
        "This client speaks Basic and Negotiate (Kerberos). NTLM is not supported — ask \
         for a Negotiate-capable path through the proxy.",
    ))
}

fn transport_error(e: &reqwest::Error, chain: &str, via_proxy: bool) -> OlError {
    let unreachable = if via_proxy {
        ERR_PROXY_UNREACHABLE
    } else {
        ERR_EGRESS_UNREACHABLE
    };
    if chain.contains("certificate") || chain.contains("tls") || chain.contains("handshake") {
        return OlError::new(
            ERR_EGRESS_TLS_FAILED,
            format!("TLS to the platform failed through this candidate: {e}"),
        )
        .with_suggestion(
            "An intercepting proxy re-signs traffic with its own CA. Point [proxy] \
             ca_bundle at that root.",
        );
    }
    OlError::new(
        unreachable,
        format!("the platform was not reachable through this candidate: {e}"),
    )
}

/// The full `Display` chain, lowercased. reqwest hides the interesting cause — a tunnel
/// error, a rustls alert — behind two or three layers of source.
fn error_chain(e: &(dyn std::error::Error + 'static)) -> String {
    let mut out = e.to_string().to_ascii_lowercase();
    let mut source = e.source();
    while let Some(inner) = source {
        out.push_str("; ");
        out.push_str(&inner.to_string().to_ascii_lowercase());
        source = inner.source();
    }
    out
}

// ---------------------------------------------------------------------------
// The narrow cross-initiative seam
// ---------------------------------------------------------------------------

/// A probe that refuses everything, so a ladder walk enumerates instead of selecting.
struct RejectAll;

impl CandidateProbe for RejectAll {
    fn probe(&self, _proxy: Option<&Url>) -> Result<u64, OlError> {
        Err(OlError::new(
            ERR_EGRESS_UNREACHABLE,
            "enumeration only, not probed",
        ))
    }
}

/// The OS ladder behind I-1's [`ProxyResolver`] seam.
///
/// The trait answers a narrower question than [`discover`] does — "what could reach
/// `target`?", with no probing and no trace — which is what I-3's self-heal wants when it
/// is re-deciding a route it already knows is broken. Enumeration and selection are the
/// same walk with a different probe, so there is one ladder, not two.
///
/// PAC rungs contribute the proxy the script named **for that target**, which is correct
/// here and only here: `candidates(target)` is a per-destination question, so a
/// per-destination answer is the honest one. The persistence rule lives on [`discover`]'s
/// [`Route`], which is what ever reaches `[proxy] url`.
pub struct OsResolver {
    ctx: Context,
    cfg: EgressConfig,
}

impl OsResolver {
    /// A resolver for one context and one resolved configuration.
    pub fn new(ctx: Context, cfg: EgressConfig) -> Self {
        Self { ctx, cfg }
    }
}

impl ProxyResolver for OsResolver {
    fn candidates(&self, target: &str) -> Vec<ProxyCandidate> {
        let Ok(url) = Url::parse(target) else {
            return Vec::new();
        };
        let probe = RejectAll;
        let mut ladder = Ladder::enumerating(&probe);
        walk(&mut ladder, self.ctx, &self.cfg, &url);
        let (_, attempts) = ladder.finish();
        attempts
            .into_iter()
            .filter(|a| a.was_probed())
            .map(|a| ProxyCandidate {
                url: a.url_masked,
                source: a.source,
            })
            .collect()
    }
}

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

    /// A probe driven by a script of outcomes, so a test states the ladder's shape rather
    /// than standing up a proxy per rung.
    pub(crate) struct ScriptedProbe {
        outcomes: RefCell<Vec<Result<u64, OlError>>>,
        pub seen: RefCell<Vec<Option<String>>>,
    }

    impl ScriptedProbe {
        pub(crate) fn new(outcomes: Vec<Result<u64, OlError>>) -> Self {
            Self {
                outcomes: RefCell::new(outcomes),
                seen: RefCell::new(Vec::new()),
            }
        }

        pub(crate) fn always_fails() -> Self {
            Self::new(Vec::new())
        }
    }

    impl CandidateProbe for ScriptedProbe {
        fn probe(&self, proxy: Option<&Url>) -> Result<u64, OlError> {
            self.seen.borrow_mut().push(proxy.map(authority_form));
            let mut outcomes = self.outcomes.borrow_mut();
            if outcomes.is_empty() {
                return Err(OlError::new(ERR_PROXY_UNREACHABLE, "scripted failure"));
            }
            outcomes.remove(0)
        }
    }

    fn cfg_with_env_proxy(url: &str) -> EgressConfig {
        let mut cfg = EgressConfig::direct();
        cfg.mode = ProxyMode::Auto;
        cfg.url = Some(url.to_string());
        cfg
    }

    fn target() -> Url {
        Url::parse("https://app.openlatch.ai").expect("target url")
    }

    /// Every OS backend, called exactly as [`os_rungs`] calls it.
    ///
    /// The `#[cfg]` dispatch in `os_rungs` type-checks only on the host it is compiled for,
    /// so two of its three arms are invisible to any single build. Calling the same
    /// expressions from an uncfg'd test type-checks all three backends against their seams
    /// on every host — and, because none of the ladder logic in `macos.rs` or `linux.rs`
    /// is platform-gated at all, it also *runs* them: the macOS backend reports nothing,
    /// and the Linux one finds no `gsettings` here and says so.
    #[test]
    fn every_os_backend_satisfies_its_seam_on_every_host() {
        let probe = ScriptedProbe::always_fails();
        let t = target();

        let mut ladder = Ladder::new(&probe);
        macos::walk(&mut ladder, Context::UserSession, &macos::native(), &t);
        let (won, trace) = ladder.finish();
        assert!(won.is_none());
        assert!(!trace.is_empty(), "the macOS ladder must leave a trace");

        let mut ladder = Ladder::new(&probe);
        linux::walk(&mut ladder, Context::UserSession, &linux::native(), &t);
        let (won, trace) = ladder.finish();
        assert!(won.is_none());
        assert_eq!(trace.len(), 1, "the Linux ladder is one rung");

        // The Windows backend is type-checked but deliberately not walked. On a host with
        // "Automatically detect settings" on — the Windows default — the WPAD rung reaches
        // DHCP and DNS, and a unit test has no business making a live network lookup or
        // paying its five-second watchdog. The fixture ladders in `windows::tests` cover
        // the behaviour; this line covers the dispatch expression.
        #[cfg(windows)]
        {
            let _: &dyn windows::WinSource = windows::native();
        }
    }

    #[test]
    fn every_rung_tag_is_in_the_vocabulary() {
        // The trace's consumers key on these strings; a rung that invents its own is a
        // silent hole in the doctor's rendering.
        let mut seen = std::collections::HashSet::new();
        for tag in rung::ALL {
            assert!(seen.insert(*tag), "duplicate rung tag: {tag}");
            assert!(!tag.is_empty());
        }
        assert_eq!(rung::ALL.len(), 10);
    }

    #[test]
    fn the_env_rung_reuses_the_resolved_config_and_wins_first() {
        let cfg = cfg_with_env_proxy("http://ambient.corp:3128");
        let probe = ScriptedProbe::new(vec![Ok(12)]);
        let (won, trace) = discover(Context::UserSession, &cfg, &target(), &probe);

        let won = won.expect("the env rung must win when its probe passes");
        assert_eq!(won.source, ProxySource::Env);
        assert_eq!(
            won.route,
            Route::Static(Url::parse("http://ambient.corp:3128").expect("url"))
        );
        assert_eq!(trace.len(), 1, "no rung below the winner may be evaluated");
        assert_eq!(trace[0].rung, rung::ENV);
        assert_eq!(trace[0].probe, CandidateOutcome::Ok);
        assert_eq!(trace[0].latency_ms, 12);
        assert_eq!(trace[0].url_masked, "http://ambient.corp:3128");
    }

    #[test]
    fn a_discovered_bare_socks5_becomes_socks5h() {
        // Resolving the destination name locally defeats the proxy on a network where the
        // proxy is the only resolver that can see internal names.
        let cfg = cfg_with_env_proxy("socks5://socks.corp:1080");
        let probe = ScriptedProbe::new(vec![Ok(3)]);
        let (won, _) = discover(Context::UserSession, &cfg, &target(), &probe);
        let Some(Discovered {
            route: Route::Static(u),
            ..
        }) = won
        else {
            panic!("expected a static socks candidate");
        };
        assert_eq!(u.scheme(), "socks5h");
    }

    #[test]
    fn a_failed_rung_is_still_recorded() {
        let cfg = cfg_with_env_proxy("http://ambient.corp:3128");
        let probe = ScriptedProbe::always_fails();
        let (won, trace) = discover(Context::UserSession, &cfg, &target(), &probe);
        assert!(won.is_none());
        let env_entry = trace
            .iter()
            .find(|a| a.rung == rung::ENV)
            .expect("the env rung must appear in the trace even when it loses");
        assert_eq!(
            env_entry.probe,
            CandidateOutcome::Failed(ERR_PROXY_UNREACHABLE)
        );
        assert!(env_entry.was_probed());
    }

    #[test]
    fn direct_mode_never_walks_the_ladder() {
        let cfg = EgressConfig::direct();
        let probe = ScriptedProbe::new(vec![Ok(1)]);
        let (won, trace) = discover(Context::UserSession, &cfg, &target(), &probe);
        assert!(won.is_none());
        assert!(trace.is_empty(), "direct mode must cost no probe at all");
        assert!(probe.seen.borrow().is_empty());
    }

    #[test]
    fn a_pac_win_carries_no_url_to_persist() {
        // The type-level half of the PAC persistence rule: a caller holding the winner has
        // no proxy URL available to write into `[proxy] url`.
        let route = Route::PacSource {
            pac_url: Url::parse("http://wpad.corp/proxy.pac").ok(),
        };
        let won = Discovered {
            source: ProxySource::Pac,
            route,
        };
        match won.route {
            Route::Static(_) => panic!("a PAC win must never be a static route"),
            Route::PacSource { pac_url } => {
                assert_eq!(
                    pac_url.map(|u| u.to_string()).as_deref(),
                    Some("http://wpad.corp/proxy.pac")
                );
            }
        }
    }

    #[test]
    fn the_trace_serialises_as_the_frozen_candidate_object() {
        let attempt = CandidateAttempt {
            source: ProxySource::Env,
            url_masked: "http://alice:*****@proxy.corp:8080".to_string(),
            probe: CandidateOutcome::Failed(ERR_PROXY_UNREACHABLE),
            latency_ms: 41,
            rung: rung::ENV,
            detail: Some("not on the wire".to_string()),
        };
        let json = serde_json::to_value(&attempt).expect("serialize");
        let obj = json.as_object().expect("object");
        let mut keys: Vec<_> = obj.keys().map(String::as_str).collect();
        keys.sort_unstable();
        assert_eq!(keys, ["latency_ms", "probe", "source", "url_masked"]);
        assert_eq!(obj["probe"], serde_json::json!("OL-1221"));
        assert_eq!(obj["source"], serde_json::json!("env"));
    }

    #[test]
    fn a_skipped_rung_is_not_a_candidate() {
        let attempt = CandidateAttempt {
            source: ProxySource::Wpad,
            url_masked: String::new(),
            probe: CandidateOutcome::Skipped(ERR_PAC_UNAVAILABLE),
            latency_ms: 0,
            rung: rung::WPAD,
            detail: Some("DisableWpad = 1".to_string()),
        };
        assert!(!attempt.was_probed());
        assert!(attempt.trace_line().contains("DisableWpad = 1"));
        assert!(
            !attempt.trace_line().contains("ms]"),
            "a rung that never ran must not claim a latency"
        );
    }

    #[test]
    fn parse_discovered_accepts_the_os_forms_and_refuses_the_rest() {
        assert_eq!(
            parse_discovered("proxy.corp:8080").map(|u| authority_form(&u)),
            Some("http://proxy.corp:8080".to_string())
        );
        assert_eq!(
            parse_discovered(" https://secure.corp:443 ").map(|u| authority_form(&u)),
            Some("https://secure.corp:443".to_string())
        );
        assert!(parse_discovered("").is_none());
        assert!(parse_discovered("ftp://proxy.corp:21").is_none());
        assert!(parse_discovered("http://").is_none());
    }

    #[test]
    fn a_pac_answer_is_read_in_the_scripts_own_grammar() {
        let answer = PacAnswer {
            proxies: vec!["PROXY pac.corp:3128".into(), "DIRECT".into()],
        };
        assert_eq!(
            answer.first_route().map(|u| authority_form(&u)).as_deref(),
            Some("http://pac.corp:3128")
        );
        assert!(answer.names_a_proxy());

        // DIRECT is an answer, not an absence.
        let direct = PacAnswer {
            proxies: vec!["DIRECT".into()],
        };
        assert!(direct.first_route().is_none());
        assert!(!direct.names_a_proxy());
        assert!(!PacAnswer::default().names_a_proxy());

        // A bare host:port is what WinHTTP's own list looks like.
        let bare = PacAnswer {
            proxies: vec!["winhttp.corp:8080".into()],
        };
        assert_eq!(
            bare.first_route().map(|u| authority_form(&u)).as_deref(),
            Some("http://winhttp.corp:8080")
        );

        // SOCKS defers name resolution to the proxy; HTTPS means TLS to the proxy itself.
        let socks = PacAnswer {
            proxies: vec!["SOCKS5 socks.corp:1080".into()],
        };
        assert_eq!(
            socks
                .first_route()
                .map(|u| u.scheme().to_string())
                .as_deref(),
            Some("socks5h")
        );
        let tls = PacAnswer {
            proxies: vec!["HTTPS secure.corp:443".into()],
        };
        assert_eq!(
            tls.first_route().map(|u| u.scheme().to_string()).as_deref(),
            Some("https")
        );
    }

    #[test]
    fn a_pac_binding_only_exists_for_a_pac_source() {
        let mut cfg = EgressConfig::direct();
        cfg.mode = ProxyMode::Auto;
        assert!(
            pac_binding(&cfg).is_none(),
            "no source means no PAC binding"
        );

        cfg.source = Some(ProxySource::Windows);
        assert!(pac_binding(&cfg).is_none(), "a static source is not a PAC");

        cfg.source = Some(ProxySource::Pac);
        cfg.pac_url = Some("http://wpad.corp/proxy.pac".to_string());
        let binding = pac_binding(&cfg);
        if native_pac_facility().is_some() {
            let binding = binding.expect("a PAC source binds on a PAC-capable OS");
            assert_eq!(
                binding.pac_url.map(|u| u.to_string()).as_deref(),
                Some("http://wpad.corp/proxy.pac")
            );
        } else {
            // Linux: D-20. There is no PAC evaluator, so there is nothing to bind, and the
            // factory falls through to whatever static route the config declares.
            assert!(binding.is_none());
        }

        cfg.mode = ProxyMode::Direct;
        assert!(pac_binding(&cfg).is_none(), "direct outranks a PAC source");
    }

    #[test]
    fn a_pac_answer_is_reused_within_the_ttl() {
        clear_pac_cache();
        let binding = PacBinding {
            // Deliberately the facility this host does NOT have, so the evaluation is
            // guaranteed to fail: the assertion is about caching, not about PAC.
            facility: PacFacility::CfNetwork,
            pac_url: None,
        };
        let t = Url::parse("https://cached.example/x").expect("url");
        if cfg!(target_os = "macos") {
            // The negative path is not available on the host that has this facility.
            return;
        }
        assert!(pac_route_for(&t, &binding).is_err());
        // A failure is not cached — a transient PAC outage must not pin DIRECT for a
        // minute — so the second call evaluates again and fails again.
        assert!(pac_route_for(&t, &binding).is_err());
        clear_pac_cache();
    }

    #[test]
    fn the_resolver_seam_enumerates_instead_of_selecting() {
        let cfg = cfg_with_env_proxy("http://ambient.corp:3128");
        let resolver = OsResolver::new(Context::UserSession, cfg);
        let candidates = resolver.candidates("https://app.openlatch.ai");
        assert!(
            candidates
                .iter()
                .any(|c| c.source == ProxySource::Env && c.url == "http://ambient.corp:3128"),
            "the env candidate must be enumerated: {candidates:?}"
        );
    }

    #[test]
    fn classify_treats_an_authenticating_proxy_as_a_pass() {
        // The estate this protects: a proxy that always 407s first. Failing it would make
        // discovery report "no proxy found" on a host that plainly has one.
        assert_eq!(auth_required("Basic realm=\"corp\"", 7).ok(), Some(7));
        assert_eq!(auth_required("Negotiate", 9).ok(), Some(9));
        let ntlm = auth_required("NTLM", 3).expect_err("NTLM alone is not viable");
        assert_eq!(ntlm.code, ERR_PROXY_AUTH_FAILED);
    }
}