captchaforge 0.2.35

[DO NOT USE — UNDER ACTIVE DEVELOPMENT, NOT PRODUCTION-READY] Captcha solver scaffolding for chromiumoxide-driven browsers. The architecture is in place (vendor solvers, retry-loop iframe walking, VLM provider abstraction, real-WAF bench harness) but the live-vendor success rate is still 0% — Cloudflare Turnstile / hCaptcha / reCAPTCHA detect us at a TLS / CDP fingerprint layer that no flag-based stealth has cleared. Watch the repo; do not depend on this for any real workload.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
use chromiumoxide::Page;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tracing::{info, warn};

use super::{
    screenshot_b64, AkamaiInterstitialSolver, ArkoseSolver, AudioCaptchaSolver, AwsWafSolver,
    BehavioralCaptchaSolver, CaptchaInfo, CaptchaSolveResult, CaptchaSolver, CaptchaType,
    CloudflareInterstitialSolver, DataDomeSolver, GeeTestSolver, MathCaptchaSolver, PatternStore,
    PerimeterXSolver, PowCaptchaSolver, RecaptchaAudioSolver, SliderCaptchaSolver, SolveMethod,
    ThirdPartyCaptchaSolver, TokenCache, TurnstileInteractiveSolver, VlmCaptchaSolver,
    WaitForTokenSolver,
};
use crate::captcha_detect::DetectedCaptcha;
use crate::provider::ProviderRegistry;
use crate::solver::util::{detected_to_type, extract_domain};
use crate::telemetry::{NoopTelemetry, SolveEvent, SolveOutcome, SolverTelemetry};

/// Runtime configuration for the solver chain.
#[derive(Debug, Clone, Copy)]
pub struct ChainConfig {
    /// Maximum time allowed for a single solver attempt (ms).
    pub per_solver_timeout_ms: u64,
    /// Whether to capture a screenshot when all solvers fail.
    pub screenshot_on_failure: bool,
    /// Verify outcome via [`crate::solver::oracle`] — snapshot page
    /// state before and after each solver attempt and downgrade
    /// `success` to `false` when the oracle classifies the result as
    /// HardBlock / Recycled / SilentFail. On by default — the cost
    /// is two cheap CDP evals per attempt and it eliminates the
    /// "solver lied" failure mode entirely. Opt out only for synthetic
    /// fixtures where you want to inspect the raw solver claim.
    pub verify_outcome: bool,
    /// Whether the oracle's `Unknown` verdict is treated as
    /// success-preserving (default `false` — STRICT) or
    /// success-keeping (compatibility for CDP-flaky environments).
    ///
    /// `Unknown` happens when the post-solve snapshot returns all
    /// empty fields (rare in production — only when the page is
    /// already torn down). Treating it as success was the historical
    /// behavior; it lets opaque outcomes through as "verified". The
    /// strict default (`false`) downgrades `Unknown` to failure so
    /// the chain falls through to the next solver. Set to `true`
    /// only when running against environments where snapshot CDP
    /// flakiness is expected.
    pub allow_unknown_outcome: bool,
}

impl Default for ChainConfig {
    fn default() -> Self {
        Self {
            per_solver_timeout_ms: 180_000,
            screenshot_on_failure: true,
            verify_outcome: true,
            allow_unknown_outcome: false,
        }
    }
}

/// Tries registered solvers in order; returns the first successful result.
/// If all solvers fail, returns an unsolved result signalling human fallback.
pub struct CaptchaSolverChain {
    pub(crate) solvers: Vec<Box<dyn CaptchaSolver>>,
    /// Optional crowd-sourced pattern store for reordering by domain intelligence.
    pub(crate) patterns: PatternStore,
    pub(crate) config: ChainConfig,
    /// Telemetry sink — fires once per solver attempt. Default is
    /// [`NoopTelemetry`] so existing callers see no change; opt in via
    /// [`Self::with_telemetry`] to capture metrics.
    pub(crate) telemetry: Arc<dyn SolverTelemetry>,
    /// Per-domain solved-token cache. `None` disables caching (the
    /// default — backward-compatible). Opt in via
    /// [`Self::with_token_cache`].
    pub(crate) cache: Option<Arc<TokenCache>>,
    /// Optional provider registry. When installed, [`DetectedCaptcha::Custom`]
    /// captchas (the TOML-rule layer) route solvers through the
    /// vendor's recommended_solver_methods — without it, Custom
    /// captchas detect successfully but never get solved because the
    /// built-in solvers' `supports()` returns false for Custom kinds.
    pub(crate) providers: Option<Arc<ProviderRegistry>>,
    /// Optional adversarial training corpus. When installed, every
    /// failed solve auto-appends a [`crate::training_corpus::TrainingSample`]
    /// for downstream re-training pipelines. Default is `None` so
    /// existing callers see no behaviour delta. Opt in via
    /// [`Self::with_training_corpus`].
    pub(crate) training_corpus: Option<Arc<crate::training_corpus::TrainingCorpus>>,
}

impl CaptchaSolverChain {
    /// Number of solvers wired into the chain. Useful for `selftest`
    /// CLI / observability.
    pub fn solver_count(&self) -> usize {
        self.solvers.len()
    }

    /// Names of every solver in the chain, in execution order. Used
    /// by the CLI's `selftest` to confirm the expected wiring.
    pub fn solver_names(&self) -> Vec<&'static str> {
        self.solvers.iter().map(|s| s.name()).collect()
    }

    /// Build the default chain in the recommended order:
    /// WaitForToken → Behavioral → VLM → Audio → ThirdParty.
    ///
    /// `WaitForTokenSolver` runs first with a short max-wait
    /// (3 seconds) — the common case in production is a passive
    /// auto-pass widget (Turnstile passive mode, reCAPTCHA v3,
    /// hCaptcha invisible) where the response field populates on
    /// its own. When that happens the chain short-circuits and the
    /// expensive solvers (mouse simulation, VLM, third-party API)
    /// never run. When the field stays empty, the chain falls
    /// through to behavioural simulation as before — no behaviour
    /// regression for sites that need real interaction.
    #[must_use = "default_chain returns the chain by value; assign or chain it."]
    pub fn default_chain() -> Self {
        let mut chain = Self {
            solvers: Vec::new(),
            patterns: PatternStore::default(),
            config: ChainConfig::default(),
            telemetry: Arc::new(NoopTelemetry),
            cache: None,
            providers: None,
            training_corpus: None,
        };
        chain.add_solver(WaitForTokenSolver::new().with_max_wait_ms(3_000));
        // Cloudflare interstitial — the "Just a moment..." 5-second
        // JS challenge page that fronts CF-protected sites BEFORE
        // any Turnstile widget. Solver waits for CF's own challenge
        // to complete and harvests the cf_clearance cookie. With
        // proper stealth, the challenge actually passes; without
        // stealth, this returns failure within the budget and the
        // chain falls through to behavioural simulation.
        chain.add_solver(CloudflareInterstitialSolver::new());
        // Akamai Bot Manager interstitial — fronts ~30% of the
        // Fortune-500 web footprint with a sensor-data POST that
        // sets the _abck cookie. With a coherent stealth profile,
        // Akamai's own JS measurements pass; we just wait for the
        // sensor POST and harvest the cookie. Returns failure on
        // suspicious / blocked outcomes so the chain falls through.
        chain.add_solver(AkamaiInterstitialSolver::new());
        // DataDome — largest pure-play bot-management vendor outside
        // CF/Akamai (~7%% of top-1M). Cookie-pass + interstitial wait;
        // yields to SliderCaptchaSolver via screenshot+failure when
        // it sees the captcha-delivery.com slider iframe.
        chain.add_solver(DataDomeSolver::new());
        // PerimeterX / HUMAN Security — _px3 cookie + sensor-script
        // wait. Yields to VLM via screenshot+failure when the
        // press-and-hold (#px-captcha) widget appears.
        chain.add_solver(PerimeterXSolver::new());
        // GeeTest v3 + v4 token-watch — dominant CN bot-management
        // vendor. Returns success on the v3 triple
        // (challenge/validate/seccode) or v4 quad
        // (lot_number/pass_token/gen_time/captcha_output) populating;
        // falls through to slider/VLM for the actual interaction.
        chain.add_solver(GeeTestSolver::new());
        // AWS WAF Captcha — cookie-pass watcher for `aws-waf-token`.
        // Yields to slider/VLM via screenshot+failure when the
        // visible puzzle iframe surfaces. Surfaces iv+context as
        // JSON solution payload when the SDK stages them before the
        // cookie lands.
        chain.add_solver(AwsWafSolver::new());
        // Arkose Labs / FunCaptcha — silent enforcement token-watch
        // for verification-token / fc-token. Yields to VLM via
        // screenshot+failure when the rotation/orientation puzzle
        // iframe surfaces.
        chain.add_solver(ArkoseSolver::new());
        // Math captcha is cheap (parses page text, computes, types).
        // Runs second so trivial WP-style captchas are handled
        // before heavier solvers fire.
        chain.add_solver(MathCaptchaSolver::new());
        // PoW solver handles ALTCHA / Friendly / MCaptcha / Cap.dev
        // by computing the SHA-256 proof in-page or polling for the
        // widget's own worker. Faster than waiting for the chain to
        // fall through to behavioural simulation.
        chain.add_solver(PowCaptchaSolver::new());
        // Slider solver covers GeeTest / DataDome / PerimeterX /
        // AWS WAF Captcha / Akamai's slider variant. Generic
        // gap-detection + bezier drag with overshoot.
        chain.add_solver(SliderCaptchaSolver::new());
        // Turnstile-interactive — dedicated solver for the
        // managed/interactive Turnstile widget. Locates the
        // cross-origin iframe by geometry, warms up the mouse,
        // clicks with realistic timing, escalates to VLM when
        // Cloudflare turns the screws. Runs BEFORE the generic
        // BehavioralCaptchaSolver so Turnstile-specific logic wins.
        chain.add_solver(TurnstileInteractiveSolver::new());
        chain.add_solver(BehavioralCaptchaSolver::new());
        chain.add_solver(VlmCaptchaSolver::new());
        // reCAPTCHA-dedicated audio fallback. Runs BEFORE the generic
        // AudioCaptchaSolver so the v2 bframe path (cross-origin
        // iframe — generic page.find_element can't see it) gets first
        // crack at any RecaptchaV2 detection. Falls through cleanly
        // when the bframe isn't open or the audio path is rate-limited,
        // letting the generic AudioCaptchaSolver and ThirdParty take
        // their turns.
        chain.add_solver(RecaptchaAudioSolver::new());
        chain.add_solver(AudioCaptchaSolver::new());
        // ThirdParty appears in the chain unconditionally but its
        // `supports()` returns false unless an API key is configured
        // (via CAPTCHAFORGE_THIRDPARTY_API_KEY), so a no-key install
        // sees no behaviour change. With a key present, every TOML
        // vendor that recommends ThirdPartyService now actually has
        // a solver to land on.
        chain.add_solver(ThirdPartyCaptchaSolver::two_captcha());
        chain
    }

    #[must_use = "empty returns the chain by value; assign or chain it. An unowned empty chain has no solvers and can't solve anything."]
    pub fn empty() -> Self {
        Self {
            solvers: Vec::new(),
            patterns: PatternStore::default(),
            config: ChainConfig::default(),
            telemetry: Arc::new(NoopTelemetry),
            cache: None,
            providers: None,
            training_corpus: None,
        }
    }

    /// Install an adversarial-training corpus. Every failed solve
    /// auto-appends a [`crate::training_corpus::TrainingSample`]
    /// for downstream re-training. Best-effort: a corpus write
    /// failure logs at debug level and does NOT propagate (we'd
    /// rather drop a sample than fail an end-user solve over a
    /// disk-full event).
    #[must_use = "with_training_corpus returns a new chain by value; assign or chain it. Dropping the result silently discards the corpus install."]
    pub fn with_training_corpus(
        mut self,
        corpus: Arc<crate::training_corpus::TrainingCorpus>,
    ) -> Self {
        self.training_corpus = Some(corpus);
        self
    }

    /// Install a [`ProviderRegistry`] so the chain can route
    /// [`DetectedCaptcha::Custom`] captchas through their declared
    /// `recommended_solver_methods`. Without a registry installed,
    /// Custom captchas (the TOML rule layer) detect successfully but
    /// no built-in solver's `supports()` returns true for them, so
    /// the chain returns "unsolved" without trying anything.
    #[must_use = "with_provider_registry returns a new chain by value; assign or chain it."]
    pub fn with_provider_registry(mut self, providers: Arc<ProviderRegistry>) -> Self {
        self.providers = Some(providers);
        self
    }

    /// Install a per-domain solved-token cache. When set, `solve()`
    /// checks the cache first and returns a `CrowdSourced` result
    /// when a fresh token exists, skipping the solver chain entirely.
    /// Production deployments hit the cache for the typical
    /// 60-second token-validity window and avoid redundant solves
    /// against the same site.
    #[must_use = "with_token_cache returns a new chain by value; assign or chain it."]
    pub fn with_token_cache(mut self, cache: Arc<TokenCache>) -> Self {
        self.cache = Some(cache);
        self
    }

    /// Append a solver to the chain.
    pub fn add_solver<S: CaptchaSolver + 'static>(&mut self, solver: S) {
        self.solvers.push(Box::new(solver));
    }

    /// Provide a custom pattern store (e.g. loaded from disk / shared across workers).
    #[must_use = "with_pattern_store returns a new chain by value; assign or chain it."]
    pub fn with_pattern_store(mut self, store: PatternStore) -> Self {
        self.patterns = store;
        self
    }

    /// Provide a custom chain configuration.
    #[must_use = "with_config returns a new chain by value; assign or chain it."]
    pub fn with_config(mut self, config: ChainConfig) -> Self {
        self.config = config;
        self
    }

    /// Install a telemetry sink. Called once per solver attempt with a
    /// [`SolveEvent`] describing outcome + timing + metadata. Used by
    /// production deployments to capture per-domain success rates,
    /// p50/p95 latency, and fallback frequency for routing decisions
    /// outside the local pattern store.
    #[must_use = "with_telemetry returns a new chain by value; assign or chain it. Dropping silently discards the telemetry hook."]
    pub fn with_telemetry(mut self, telemetry: Arc<dyn SolverTelemetry>) -> Self {
        self.telemetry = telemetry;
        self
    }

    /// Check the token cache for a fresh entry matching this captcha
    /// without invoking any solver. Returns `Some` on cache hit (and
    /// fires a `Success` telemetry event tagged with
    /// `solver: "TokenCache"`); `None` on miss or when no cache is
    /// installed.
    ///
    /// Useful as a public API: callers that want to short-circuit
    /// before reaching for a `Page` (e.g. retry loops that already
    /// know the captcha info) can poll this directly. Internally,
    /// [`Self::solve`] calls this as its first step.
    pub fn cached_solution(&self, captcha_info: &CaptchaInfo) -> Option<CaptchaSolveResult> {
        let cache = self.cache.as_ref()?;
        let domain = extract_domain(&captcha_info.page_url);
        let captcha_type = detected_to_type(&captcha_info.kind);
        let entry = cache.get(&domain, &captcha_type)?;
        let elapsed_ms = 0;
        self.telemetry.record(&SolveEvent {
            solver: "TokenCache",
            captcha_type: &captcha_type,
            kind: &captcha_info.kind,
            domain: &domain,
            outcome: SolveOutcome::Success,
            time_ms: elapsed_ms,
            confidence: Some(1.0),
            method: &SolveMethod::CrowdSourced,
        });
        Some(CaptchaSolveResult {
            solution: entry.token().to_owned(),
            confidence: 1.0,
            method: SolveMethod::CrowdSourced,
            time_ms: elapsed_ms,
            success: true,
            screenshot: None,
            // Replay the cookies captured at the original solve so the
            // WAF/vendor's trusted session rides along with the token.
            // Empty when the cache entry was put via the back-compat
            // no-cookies path.
            cookies: entry.cookies().to_vec(),
            verified_outcome: None,
        })
    }

    /// Run the chain. Returns the first successful `CaptchaSolveResult`,
    /// or an unsolved result (optionally with a screenshot) if all strategies are exhausted.
    pub async fn solve(&self, page: &Page, captcha_info: &CaptchaInfo) -> CaptchaSolveResult {
        let domain = extract_domain(&captcha_info.page_url);
        let captcha_type = detected_to_type(&captcha_info.kind);
        let t0 = Instant::now();

        // Outcome-verification baseline. Snapshot the page BEFORE any
        // solver runs so we can classify whether the page actually
        // advanced after the solver claims success. Two cheap CDP
        // evals; skipped entirely when verify_outcome is off.
        //
        // Snapshot BEFORE the cache short-circuit so cache hits also
        // get verified by the oracle. Previously `cached_solution`
        // returned immediately without snapshotting, so cache hits
        // were trusted on the cache's word alone — a stale token
        // for a captcha that's since regenerated would silently
        // "succeed" without any post-state evidence.
        let baseline = if self.config.verify_outcome {
            Some(super::oracle::take_snapshot(page).await)
        } else {
            None
        };

        // Cache short-circuit — see [`Self::cached_solution`] for the
        // standalone path. Done here too so `solve()` is a complete
        // top-level entry point.
        if let Some(mut hit) = self.cached_solution(captcha_info) {
            hit.time_ms = t0.elapsed().as_millis() as u64;
            // Verify the cached result against fresh page state when
            // verify_outcome is on. A stale cache that no longer
            // matches the page (e.g. token expired, widget recycled)
            // gets downgraded here instead of being trusted blindly.
            if let Some(before) = &baseline {
                let after = super::oracle::take_snapshot(page).await;
                let outcome = super::oracle::classify(before, &after);
                hit.verified_outcome = Some(outcome);
                let is_verified = matches!(
                    outcome,
                    super::oracle::OutcomeClassification::Advanced
                ) || (self.config.allow_unknown_outcome
                    && matches!(
                        outcome,
                        super::oracle::OutcomeClassification::Unknown
                    ));
                if !is_verified {
                    warn!(
                        outcome = ?outcome,
                        "token cache hit but oracle disagrees — not trusting cache"
                    );
                    hit.success = false;
                    // Fall through to the real solver chain below
                    // instead of returning the failed cache row.
                } else {
                    return hit;
                }
            } else {
                return hit;
            }
        }

        // Re-order solvers so the historically-best method for this domain runs first.
        let ordered = self.ordered_solvers(&domain, &captcha_type, &captcha_info.kind);

        for solver in &ordered {
            info!(solver = solver.name(), "attempting captcha solve");
            let timeout = Duration::from_millis(self.config.per_solver_timeout_ms);
            let result = tokio::time::timeout(timeout, solver.solve(page, captcha_info)).await;

            match result {
                Ok(Ok(mut r)) if r.success => {
                    // Token-shape oracle (E2 wiring): when the
                    // detected captcha kind has a documented token
                    // shape, sanity-check the solver's returned
                    // string against it. Decoy = clearly malformed;
                    // soft-failure decoy tokens (vendors return
                    // these to make scrapers report success then
                    // bounce them at validation time) get
                    // intercepted HERE instead of two requests
                    // later when the token is rejected. Suspect =
                    // unrecognised but plausible — keep, log.
                    if let Some(oracle) = oracle_for_kind(&captcha_info.kind) {
                        match oracle.classify(&r.solution) {
                            super::token_shapes::TokenShape::Decoy => {
                                warn!(
                                    solver = solver.name(),
                                    vendor = oracle.vendor(),
                                    solution_len = r.solution.len(),
                                    "solver claimed success but token shape is decoy — \
                                     downgrading (likely vendor soft-failure response)"
                                );
                                r.success = false;
                                self.patterns.record(
                                    &domain,
                                    &captcha_type,
                                    false,
                                    r.time_ms,
                                    r.method.clone(),
                                );
                                self.telemetry.record(&SolveEvent {
                                    solver: solver.name(),
                                    captcha_type: &captcha_type,
                                    kind: &captcha_info.kind,
                                    domain: &domain,
                                    outcome: SolveOutcome::Failure,
                                    time_ms: r.time_ms,
                                    confidence: None,
                                    method: &r.method,
                                });
                                continue;
                            }
                            super::token_shapes::TokenShape::Suspect => {
                                tracing::debug!(
                                    solver = solver.name(),
                                    vendor = oracle.vendor(),
                                    "token shape Suspect — keeping success but flagging for re-verification"
                                );
                            }
                            super::token_shapes::TokenShape::Plausible => {}
                        }
                    }
                    // Verify outcome — the solver claims success, but
                    // does the page state agree? A token in hand is
                    // not the same as a page past the challenge.
                    if let Some(before) = &baseline {
                        let after = super::oracle::take_snapshot(page).await;
                        let outcome = super::oracle::classify(before, &after);
                        r.verified_outcome = Some(outcome);
                        // Strict-by-default: only Advanced verifies
                        // success. `Unknown` is downgraded unless the
                        // operator explicitly opted in via
                        // `allow_unknown_outcome` (for CDP-flaky test
                        // environments). Previously Unknown was
                        // implicitly trusted, which let solver
                        // attempts succeed against snapshots where
                        // we couldn't actually verify anything.
                        let is_verified = matches!(
                            outcome,
                            super::oracle::OutcomeClassification::Advanced
                        ) || (self.config.allow_unknown_outcome
                            && matches!(
                                outcome,
                                super::oracle::OutcomeClassification::Unknown
                            ));
                        if !is_verified {
                            warn!(
                                solver = solver.name(),
                                outcome = ?outcome,
                                "solver claimed success but oracle disagrees — downgrading to failure"
                            );
                            r.success = false;
                            // Fall through to the failure-path arm below
                            // by re-binding via a continue. We can't
                            // mutate the match arm, so manually drive
                            // the failure-path side effects here:
                            self.patterns.record(
                                &domain,
                                &captcha_type,
                                false,
                                r.time_ms,
                                r.method.clone(),
                            );
                            self.telemetry.record(&SolveEvent {
                                solver: solver.name(),
                                captcha_type: &captcha_type,
                                kind: &captcha_info.kind,
                                domain: &domain,
                                outcome: SolveOutcome::Failure,
                                time_ms: r.time_ms,
                                confidence: None,
                                method: &r.method,
                            });
                            continue;
                        }
                    }

                    info!(
                        solver = solver.name(),
                        confidence = r.confidence,
                        time_ms = r.time_ms,
                        verified = ?r.verified_outcome,
                        "captcha solved"
                    );
                    self.patterns
                        .record(&domain, &captcha_type, true, r.time_ms, r.method.clone());
                    self.telemetry.record(&SolveEvent {
                        solver: solver.name(),
                        captcha_type: &captcha_type,
                        kind: &captcha_info.kind,
                        domain: &domain,
                        outcome: SolveOutcome::Success,
                        time_ms: r.time_ms,
                        confidence: Some(r.confidence),
                        method: &r.method,
                    });
                    if let Some(cache) = &self.cache {
                        // Persist the cookies alongside the token so a
                        // future cache hit replays the same trusted
                        // session — without this the cache layer
                        // returned only the token and the next request
                        // immediately re-triggered the captcha.
                        cache.put_full(
                            &domain,
                            &captcha_type,
                            r.solution.clone(),
                            solver.name(),
                            cache.ttl(),
                            r.cookies.clone(),
                        );
                    }
                    return r;
                }
                Ok(Ok(r)) => {
                    warn!(solver = solver.name(), "solver returned failure result");
                    self.patterns.record(
                        &domain,
                        &captcha_type,
                        false,
                        r.time_ms,
                        r.method.clone(),
                    );
                    self.telemetry.record(&SolveEvent {
                        solver: solver.name(),
                        captcha_type: &captcha_type,
                        kind: &captcha_info.kind,
                        domain: &domain,
                        outcome: SolveOutcome::Failure,
                        time_ms: r.time_ms,
                        confidence: None,
                        method: &r.method,
                    });
                }
                Ok(Err(e)) => {
                    warn!(solver = solver.name(), error = %e, "solver error");
                    let method = solver.method();
                    self.telemetry.record(&SolveEvent {
                        solver: solver.name(),
                        captcha_type: &captcha_type,
                        kind: &captcha_info.kind,
                        domain: &domain,
                        outcome: SolveOutcome::Error,
                        time_ms: 0,
                        confidence: None,
                        method: &method,
                    });
                }
                Err(_) => {
                    warn!(solver = solver.name(), "solver timed out");
                    self.patterns.record(
                        &domain,
                        &captcha_type,
                        false,
                        self.config.per_solver_timeout_ms,
                        solver.method(),
                    );
                    let method = solver.method();
                    self.telemetry.record(&SolveEvent {
                        solver: solver.name(),
                        captcha_type: &captcha_type,
                        kind: &captcha_info.kind,
                        domain: &domain,
                        outcome: SolveOutcome::Timeout,
                        time_ms: self.config.per_solver_timeout_ms,
                        confidence: None,
                        method: &method,
                    });
                }
            }
        }

        // All solvers exhausted — optionally grab a screenshot for human review.
        warn!("all captcha solvers failed, human fallback required");
        let screenshot = if self.config.screenshot_on_failure {
            screenshot_b64(page).await.ok()
        } else {
            None
        };

        // Adversarial-training capture (H2): when a TrainingCorpus
        // is configured, persist this terminal failure as a sample
        // so downstream re-training pipelines see it. Best-effort —
        // disk failure logs at debug, never propagates.
        if let Some(corpus) = &self.training_corpus {
            let sample = crate::training_corpus::TrainingSample {
                solver: "(chain-terminal)".into(),
                vendor: detected_kind_canonical_name(&captcha_info.kind),
                detected_kind: format!("{:?}", captcha_info.kind),
                url: captcha_info.page_url.clone(),
                outcome: "failure".into(),
                confidence: None,
                time_ms: t0.elapsed().as_millis() as u64,
                screenshot_b64: screenshot.clone(),
                dom_snapshot: None,
                verified_outcome: None,
                captured_at_unix: std::time::SystemTime::now()
                    .duration_since(std::time::UNIX_EPOCH)
                    .map(|d| d.as_secs() as i64)
                    .unwrap_or(0),
            };
            if let Err(e) = corpus.append(&sample) {
                tracing::debug!(error = %e, "training corpus append failed (continuing)");
            }
        }

        CaptchaSolveResult::unsolved(t0.elapsed().as_millis() as u64, screenshot)
    }

    /// Return solvers ordered by routing intelligence:
    ///
    /// 1. If a [`crate::provider::ProviderRegistry`] is installed AND
    ///    the kind has a registered provider, **provider routing** wins:
    ///    - Provider's `recommended_solver_names()` (when non-empty)
    ///      gives an exact, name-keyed list — best for vendors with
    ///      dedicated solvers.
    ///    - Else the provider's `recommended_solver_methods()` is
    ///      consulted — method-keyed, fragile when multiple solvers
    ///      share a method but kept for backwards compat.
    /// 2. Otherwise, fall back to the legacy `supports()`-scan path
    ///    with PatternStore-based reordering.
    ///
    /// Provider routing applies to **all** kinds (built-in AND
    /// `Custom(_)`) — adding a dedicated `TurnstileInteractiveSolver`
    /// no longer collides with `BehavioralCaptchaSolver` because the
    /// provider names which solver to prefer.
    pub(crate) fn ordered_solvers(
        &self,
        domain: &str,
        captcha_type: &CaptchaType,
        kind: &crate::captcha_detect::DetectedCaptcha,
    ) -> Vec<&dyn CaptchaSolver> {
        // Provider-routing path. Three cases:
        //
        // - Provider declares `recommended_solver_names()` (any kind)
        //   → strict name-keyed routing.
        // - Custom kind with a registered provider (no names, just
        //   methods) → method-keyed routing (legacy behaviour).
        // - Custom kind WITHOUT a registered provider → empty list,
        //   so the chain reports "no applicable solvers".
        //
        // For built-in kinds we INTENTIONALLY don't route via
        // method-only providers — the existing macro-emitted
        // `recommended_solver_methods` lists were shipped before name
        // routing existed, and method routing would over-narrow to a
        // single solver per method (vs the supports-scan path which
        // returns every eligible solver). Built-ins fall through to
        // supports-scan unless a provider opts in via names.
        if let Some(reg) = &self.providers {
            if let Some(provider) = reg.find_by_kind(kind) {
                let names = provider.recommended_solver_names();
                if !names.is_empty() {
                    return self.solvers_by_name(names, kind);
                }
                if matches!(kind, DetectedCaptcha::Custom(_)) {
                    let methods = provider.recommended_solver_methods();
                    return self.solvers_by_method(methods, kind);
                }
                // Built-in kind, no names declared → fall through to
                // supports-scan below.
            } else if matches!(kind, DetectedCaptcha::Custom(_)) {
                return Vec::new();
            }
        } else if matches!(kind, DetectedCaptcha::Custom(_)) {
            return Vec::new();
        }

        // Legacy supports-scan + PatternStore reorder.
        let preferred = self.patterns.best_method(domain, captcha_type);
        let mut ordered: Vec<&dyn CaptchaSolver> = self
            .solvers
            .iter()
            .filter(|s| s.supports(kind))
            .map(|s| s.as_ref())
            .collect();

        if let Some(pref) = preferred {
            if let Some(pos) = ordered.iter().position(|s| s.method() == pref) {
                if pos > 0 {
                    let item = ordered.remove(pos);
                    ordered.insert(0, item);
                }
            }
        }
        ordered
    }

    /// Resolve a name-keyed recommendation list to actual solvers.
    /// Each name is matched against `solver.name()` exactly. Solvers
    /// must additionally pass `supports(kind)` so an unkeyed
    /// third-party solver (which says `supports = false` without an
    /// API key) doesn't get picked.
    fn solvers_by_name(
        &self,
        names: &[&'static str],
        kind: &crate::captcha_detect::DetectedCaptcha,
    ) -> Vec<&dyn CaptchaSolver> {
        let mut ordered: Vec<&dyn CaptchaSolver> = Vec::with_capacity(names.len());
        for name in names {
            if let Some(s) = self
                .solvers
                .iter()
                .find(|s| s.name() == *name && s.supports(kind))
            {
                let s_ref: &dyn CaptchaSolver = s.as_ref();
                if !ordered
                    .iter()
                    .any(|existing| std::ptr::eq(*existing, s_ref))
                {
                    ordered.push(s_ref);
                }
            }
        }
        ordered
    }

    /// Resolve a method-keyed recommendation list to actual solvers.
    /// Method-based routing collides when multiple solvers share a
    /// `SolveMethod`; the FIRST chain entry wins. Prefer
    /// [`Self::solvers_by_name`] for vendors with dedicated solvers.
    fn solvers_by_method(
        &self,
        methods: &[SolveMethod],
        kind: &crate::captcha_detect::DetectedCaptcha,
    ) -> Vec<&dyn CaptchaSolver> {
        let mut ordered: Vec<&dyn CaptchaSolver> = Vec::with_capacity(methods.len());
        for method in methods {
            if let Some(s) = self
                .solvers
                .iter()
                .find(|s| s.method() == *method && s.supports(kind))
            {
                let s_ref: &dyn CaptchaSolver = s.as_ref();
                if !ordered
                    .iter()
                    .any(|existing| std::ptr::eq(*existing, s_ref))
                {
                    ordered.push(s_ref);
                }
            }
        }
        ordered
    }
}

/// Canonical short vendor name for a [`DetectedCaptcha`] kind —
/// used by the training-corpus persistence path so all samples
/// from "Cloudflare Turnstile" land under the same vendor key
/// regardless of how the detector phrased it. For
/// [`DetectedCaptcha::Custom`] entries the rule-pack-supplied name
/// IS the canonical key (and is already lowercase + hyphen-safe).
fn detected_kind_canonical_name(kind: &crate::captcha_detect::DetectedCaptcha) -> String {
    use crate::captcha_detect::DetectedCaptcha as K;
    match kind {
        K::Turnstile => "cloudflare-turnstile".to_string(),
        K::RecaptchaV2 => "recaptcha-v2".to_string(),
        K::RecaptchaV3 => "recaptcha-v3".to_string(),
        K::HCaptcha => "hcaptcha".to_string(),
        K::ImageCaptcha => "image-captcha".to_string(),
        K::AudioCaptcha => "audio-captcha".to_string(),
        K::SliderCaptcha => "slider-captcha".to_string(),
        K::CanvasCaptcha => "canvas-captcha".to_string(),
        K::MultiStepCaptcha => "multi-step".to_string(),
        K::PowCaptcha => "pow-captcha".to_string(),
        K::ShadowDomCaptcha => "shadow-dom".to_string(),
        K::Custom(name) => name.clone(),
        K::None => "none".to_string(),
    }
}

/// Map a [`DetectedCaptcha`] kind to its [`super::token_shapes`]
/// oracle, when one exists. Returns `None` for kinds without a
/// documented token shape (e.g. canvas / slider / multi-step
/// captchas whose "token" is application-defined). Single source
/// of truth for the chain's E2 wiring; keeps the kind→oracle
/// matcher in one place so adding a new vendor oracle only
/// touches `token_shapes::for_vendor` AND this matcher.
fn oracle_for_kind(
    kind: &crate::captcha_detect::DetectedCaptcha,
) -> Option<super::token_shapes::TokenOracle> {
    use crate::captcha_detect::DetectedCaptcha as K;
    let vendor = match kind {
        K::Turnstile => "cloudflare-turnstile",
        K::RecaptchaV2 => "recaptcha-v2",
        K::RecaptchaV3 => "recaptcha-v3",
        K::HCaptcha => "hcaptcha",
        // Custom rules from the TOML pack — name-match against the
        // bundled enterprise / vendor variants we registered in E2.
        K::Custom(name) => match name.as_str() {
            "recaptcha_enterprise" | "recaptcha-enterprise" => "recaptcha-enterprise",
            "hcaptcha_enterprise" | "hcaptcha-enterprise" => "hcaptcha",
            _ => return None,
        },
        _ => return None,
    };
    super::token_shapes::for_vendor(vendor)
}

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

    #[test]
    fn solver_chain_add_and_count() {
        let mut chain = CaptchaSolverChain::empty();
        chain.add_solver(BehavioralCaptchaSolver::new());
        chain.add_solver(AudioCaptchaSolver::new());
        assert_eq!(chain.solvers.len(), 2);
    }

    #[test]
    fn default_chain_has_seventeen_solvers_in_documented_order() {
        let chain = CaptchaSolverChain::default_chain();
        assert_eq!(chain.solvers.len(), 17);
        assert_eq!(chain.solvers[0].name(), "WaitForTokenSolver");
        assert_eq!(chain.solvers[1].name(), "CloudflareInterstitialSolver");
        assert_eq!(chain.solvers[2].name(), "AkamaiInterstitialSolver");
        assert_eq!(chain.solvers[3].name(), "DataDomeSolver");
        assert_eq!(chain.solvers[4].name(), "PerimeterXSolver");
        assert_eq!(chain.solvers[5].name(), "GeeTestSolver");
        assert_eq!(chain.solvers[6].name(), "AwsWafSolver");
        assert_eq!(chain.solvers[7].name(), "ArkoseSolver");
        assert_eq!(chain.solvers[8].name(), "MathCaptchaSolver");
        assert_eq!(chain.solvers[9].name(), "PowCaptchaSolver");
        assert_eq!(chain.solvers[10].name(), "SliderCaptchaSolver");
        assert_eq!(chain.solvers[11].name(), "TurnstileInteractiveSolver");
        assert_eq!(chain.solvers[12].name(), "BehavioralCaptchaSolver");
        assert_eq!(chain.solvers[13].name(), "VlmCaptchaSolver");
        // Vendor-specific reCAPTCHA audio comes BEFORE the generic
        // AudioCaptchaSolver so the bframe-aware path wins.
        assert_eq!(chain.solvers[14].name(), "RecaptchaAudioSolver");
        assert_eq!(chain.solvers[15].name(), "AudioCaptchaSolver");
        assert_eq!(chain.solvers[16].name(), "ThirdPartyCaptchaSolver");
    }

    #[test]
    fn default_chain_third_party_inert_without_api_key() {
        // Without CAPTCHAFORGE_THIRDPARTY_API_KEY, the third-party solver's
        // supports() returns false everywhere, so adding it to the default
        // chain doesn't surface in ordered_solvers for any kind.
        // (We rely on the env-var being unset in CI; we can't safely set
        // it within a test without affecting other tests in the same
        // process.)
        if std::env::var("CAPTCHAFORGE_THIRDPARTY_API_KEY").is_ok() {
            return;
        }
        let chain = CaptchaSolverChain::default_chain();
        let ordered = chain.ordered_solvers(
            "example.com",
            &CaptchaType::CloudflareTurnstile,
            &crate::captcha_detect::DetectedCaptcha::Turnstile,
        );
        for s in ordered {
            assert_ne!(
                s.name(),
                "ThirdPartyCaptchaSolver",
                "third-party should be filtered out without an API key",
            );
        }
    }

    #[test]
    fn custom_captcha_routes_through_third_party_when_key_present() {
        use crate::provider::ProviderRegistry;
        use crate::solver::ThirdPartyCaptchaSolver;
        // Construct a chain with a third-party solver that has a key,
        // and a provider registry. DataDome recommends
        // [BehavioralBypass, ThirdPartyService] — the chain should now
        // surface BOTH (Behavioral first, ThirdParty second).
        let registry = Arc::new(ProviderRegistry::with_built_in_rules().unwrap());
        let mut chain = CaptchaSolverChain::empty().with_provider_registry(registry);
        chain.add_solver(BehavioralCaptchaSolver::new());
        chain.add_solver(ThirdPartyCaptchaSolver::two_captcha().with_api_key("test-key"));

        let ordered = chain.ordered_solvers(
            "datadome.test",
            &CaptchaType::Custom("datadome".into()),
            &crate::captcha_detect::DetectedCaptcha::Custom("datadome".into()),
        );
        assert_eq!(
            ordered.len(),
            2,
            "with API key, both Behavioral and ThirdParty should be eligible",
        );
        assert_eq!(ordered[0].method(), SolveMethod::BehavioralBypass);
        assert_eq!(ordered[1].method(), SolveMethod::ThirdPartyService);
    }

    #[test]
    fn default_chain_timeout_is_sane() {
        let chain = CaptchaSolverChain::default_chain();
        assert_eq!(chain.config.per_solver_timeout_ms, 180_000);
        assert!(chain.config.screenshot_on_failure);
        // Outcome verification is on by default — that's the
        // "no green-checkmark lies" guarantee. If this assertion
        // ever flips to assert!(!) without explicit user request,
        // it's a regression that silently re-enables the failure
        // mode the oracle was built to close.
        assert!(chain.config.verify_outcome);
    }

    #[test]
    fn oracle_for_kind_resolves_each_built_in_to_a_documented_oracle() {
        use crate::captcha_detect::DetectedCaptcha as K;
        // Each built-in vendor with a documented token shape MUST
        // resolve. Adding a new vendor variant without registering
        // here would silently bypass the decoy check — this test
        // catches that.
        for kind in [K::Turnstile, K::RecaptchaV2, K::RecaptchaV3, K::HCaptcha] {
            assert!(
                oracle_for_kind(&kind).is_some(),
                "{kind:?} must have a token-shape oracle wired"
            );
        }
    }

    #[test]
    fn oracle_for_kind_returns_none_for_kinds_without_documented_token_shape() {
        use crate::captcha_detect::DetectedCaptcha as K;
        // Captchas whose "token" is application-defined (canvas /
        // slider / multi-step / image-grid VLM) deliberately have
        // no oracle. The chain skips the decoy check and falls
        // through to the existing oracle::classify path.
        for kind in [
            K::SliderCaptcha,
            K::CanvasCaptcha,
            K::MultiStepCaptcha,
            K::ImageCaptcha,
            K::PowCaptcha,
        ] {
            assert!(
                oracle_for_kind(&kind).is_none(),
                "{kind:?} must NOT have a token-shape oracle (token is app-defined)"
            );
        }
    }

    #[test]
    fn oracle_for_kind_resolves_recaptcha_enterprise_custom_rule_to_enterprise_oracle() {
        use crate::captcha_detect::DetectedCaptcha as K;
        let oracle = oracle_for_kind(&K::Custom("recaptcha_enterprise".into()))
            .expect("recaptcha_enterprise must resolve via Custom-name match");
        assert_eq!(oracle.vendor(), "recaptcha-enterprise");
    }

    #[test]
    fn oracle_for_kind_resolves_hcaptcha_enterprise_to_hcaptcha_oracle() {
        // hCaptcha Enterprise tokens have the same wire shape as
        // free-tier hCaptcha tokens — both share one oracle.
        use crate::captcha_detect::DetectedCaptcha as K;
        let oracle = oracle_for_kind(&K::Custom("hcaptcha_enterprise".into()))
            .expect("hcaptcha_enterprise must resolve");
        assert_eq!(oracle.vendor(), "hcaptcha");
    }

    #[test]
    fn oracle_for_kind_returns_none_for_unrecognised_custom_rule() {
        use crate::captcha_detect::DetectedCaptcha as K;
        assert!(oracle_for_kind(&K::Custom("totally_unknown_vendor".into())).is_none());
    }

    #[test]
    fn verify_outcome_downgrades_success_when_oracle_disagrees() {
        // Exercise the REAL classify() function with real PageSnapshot
        // values rather than asserting that
        // `matches!(Advanced, Advanced)` is true (which it always is).
        // This catches a refactor that breaks the verdict mapping.
        use crate::solver::oracle::{classify, OutcomeClassification, PageSnapshot};

        // Cookie-only change → Advanced (success-keep).
        let before = PageSnapshot {
            url: "/x".into(),
            title: "T".into(),
            body_excerpt: "b".into(),
            captcha_present: true,
            cookie_names: vec!["__cf_bm".into()],
        };
        let after_advanced = PageSnapshot {
            captcha_present: false,
            cookie_names: vec!["__cf_bm".into(), "sessionid".into()],
            ..before.clone()
        };
        assert_eq!(
            classify(&before, &after_advanced),
            OutcomeClassification::Advanced
        );

        // Widget still present → Recycled (success-downgrade).
        let after_recycled = PageSnapshot {
            captcha_present: true,
            ..before.clone()
        };
        assert_eq!(
            classify(&before, &after_recycled),
            OutcomeClassification::Recycled
        );

        // Body says "access denied" → HardBlock.
        let after_blocked = PageSnapshot {
            captcha_present: false,
            body_excerpt: "access denied — bot detected".into(),
            ..before.clone()
        };
        assert_eq!(
            classify(&before, &after_blocked),
            OutcomeClassification::HardBlock
        );

        // Nothing moved → SilentFail.
        let after_silent = PageSnapshot {
            captcha_present: false,
            ..before.clone()
        };
        assert_eq!(
            classify(&before, &after_silent),
            OutcomeClassification::SilentFail
        );
    }

    #[test]
    fn chain_with_custom_config() {
        let chain = CaptchaSolverChain::empty().with_config(ChainConfig {
            per_solver_timeout_ms: 30_000,
            screenshot_on_failure: false,
            verify_outcome: true,
            allow_unknown_outcome: false,
        });
        assert_eq!(chain.config.per_solver_timeout_ms, 30_000);
        assert!(!chain.config.screenshot_on_failure);
        assert!(chain.config.verify_outcome);
        assert!(!chain.config.allow_unknown_outcome);
    }

    #[test]
    fn ordered_solvers_puts_preferred_first() {
        let mut chain = CaptchaSolverChain::empty();
        chain.add_solver(BehavioralCaptchaSolver::new());
        chain.add_solver(VlmCaptchaSolver::new());
        chain.add_solver(AudioCaptchaSolver::new());

        // Seed the pattern store so VisionLLM is preferred for example.com
        chain.patterns.record(
            "example.com",
            &CaptchaType::RecaptchaV2,
            true,
            1000,
            SolveMethod::VisionLLM,
        );

        let ordered = chain.ordered_solvers(
            "example.com",
            &CaptchaType::RecaptchaV2,
            &crate::captcha_detect::DetectedCaptcha::RecaptchaV2,
        );
        assert_eq!(ordered.len(), 3);
        assert_eq!(ordered[0].name(), "VlmCaptchaSolver");
        assert_eq!(ordered[1].name(), "BehavioralCaptchaSolver");
        assert_eq!(ordered[2].name(), "AudioCaptchaSolver");
    }

    #[test]
    fn ordered_solvers_keeps_original_order_when_no_preference() {
        let chain = CaptchaSolverChain::default_chain();
        let ordered = chain.ordered_solvers(
            "unknown.com",
            &CaptchaType::RecaptchaV2,
            &crate::captcha_detect::DetectedCaptcha::RecaptchaV2,
        );
        // WaitForToken now leads the chain; passive-pass widgets get
        // first crack at issuing a token without interaction.
        assert_eq!(ordered[0].name(), "WaitForTokenSolver");
        assert_eq!(ordered[1].name(), "BehavioralCaptchaSolver");
        assert_eq!(ordered[2].name(), "VlmCaptchaSolver");
        // Vendor-specific reCAPTCHA audio routes BEFORE the generic
        // AudioCaptchaSolver — the bframe-aware path needs first crack
        // before the generic page-only fallback gets a turn.
        assert_eq!(ordered[3].name(), "RecaptchaAudioSolver");
        assert_eq!(ordered[4].name(), "AudioCaptchaSolver");
    }

    #[test]
    fn custom_captcha_returns_no_solvers_without_provider_registry() {
        let chain = CaptchaSolverChain::default_chain();
        let ordered = chain.ordered_solvers(
            "datadome.test",
            &CaptchaType::Custom("datadome".into()),
            &crate::captcha_detect::DetectedCaptcha::Custom("datadome".into()),
        );
        assert!(
            ordered.is_empty(),
            "without a ProviderRegistry the chain has no way to know which solver to try for a Custom captcha",
        );
    }

    #[test]
    fn custom_captcha_routes_through_provider_recommended_methods() {
        use crate::provider::ProviderRegistry;
        // DataDome recommends [BehavioralBypass, ThirdPartyService].
        // Default chain has multiple BehavioralBypass solvers: Slider
        // (which legitimately handles datadome's slider widget) and
        // Behavioural. The routing finds the FIRST BehavioralBypass
        // solver whose supports(kind) returns true — Slider wins for
        // datadome since it claims the vendor explicitly. Without an
        // API key, ThirdParty filters out, so we get exactly 1 solver.
        let registry = Arc::new(ProviderRegistry::with_built_in_rules().unwrap());
        let chain = CaptchaSolverChain::default_chain().with_provider_registry(registry);

        let ordered = chain.ordered_solvers(
            "datadome.test",
            &CaptchaType::Custom("datadome".into()),
            &crate::captcha_detect::DetectedCaptcha::Custom("datadome".into()),
        );
        assert_eq!(
            ordered.len(),
            1,
            "only one BehavioralBypass solver supports datadome; \
             ThirdPartyService filters out without API key",
        );
        assert_eq!(ordered[0].name(), "SliderCaptchaSolver");
    }

    #[test]
    fn custom_captcha_routes_to_vision_first_when_provider_recommends_it() {
        use crate::provider::ProviderRegistry;
        // arkose_funcaptcha (and others) recommend VisionLLM somewhere
        // in the list. Looking at community.toml: arkose recommends
        // [Behavioral, ThirdParty] same as datadome. Use a vendor
        // whose first recommendation IS in the default chain.
        // Actually all bundled rules recommend Behavioral first; let's
        // just verify the order is preserved as the provider declared.
        let registry = Arc::new(ProviderRegistry::with_built_in_rules().unwrap());
        let chain = CaptchaSolverChain::default_chain().with_provider_registry(registry);

        let ordered = chain.ordered_solvers(
            "x.test",
            &CaptchaType::Custom("perimeterx_human".into()),
            &crate::captcha_detect::DetectedCaptcha::Custom("perimeterx_human".into()),
        );
        // perimeterx_human recommends [BehavioralBypass, ThirdPartyService]
        // — only Behavioral is in the default chain, so we get one solver.
        assert_eq!(ordered.len(), 1);
        assert_eq!(ordered[0].method(), SolveMethod::BehavioralBypass);
    }

    #[test]
    fn custom_captcha_with_unknown_name_returns_no_solvers() {
        use crate::provider::ProviderRegistry;
        let registry = Arc::new(ProviderRegistry::with_built_in_rules().unwrap());
        let chain = CaptchaSolverChain::default_chain().with_provider_registry(registry);

        let ordered = chain.ordered_solvers(
            "unknown.test",
            &CaptchaType::Custom("never-heard-of-it".into()),
            &crate::captcha_detect::DetectedCaptcha::Custom("never-heard-of-it".into()),
        );
        assert!(
            ordered.is_empty(),
            "unknown Custom name has no provider entry → no solvers",
        );
    }

    #[test]
    fn ordered_solvers_keeps_original_order_when_preference_not_in_chain() {
        let mut chain = CaptchaSolverChain::empty();
        chain.add_solver(BehavioralCaptchaSolver::new());
        chain.add_solver(VlmCaptchaSolver::new());

        // Record a preference for AudioBypass, which isn't in the chain
        chain.patterns.record(
            "example.com",
            &CaptchaType::RecaptchaV2,
            true,
            1000,
            SolveMethod::AudioBypass,
        );

        let ordered = chain.ordered_solvers(
            "example.com",
            &CaptchaType::RecaptchaV2,
            &crate::captcha_detect::DetectedCaptcha::RecaptchaV2,
        );
        assert_eq!(ordered[0].name(), "BehavioralCaptchaSolver");
        assert_eq!(ordered[1].name(), "VlmCaptchaSolver");
    }

    #[test]
    fn ordered_solvers_filters_by_supports() {
        let chain = CaptchaSolverChain::default_chain();
        // HCaptcha is supported by WaitForTokenSolver (passive-pass
        // path) and VlmCaptchaSolver (vision fallback). Behavioural
        // and Audio don't claim hCaptcha; Third-party is keyless in
        // tests so it filters out.
        let ordered = chain.ordered_solvers(
            "example.com",
            &CaptchaType::HCaptcha,
            &crate::captcha_detect::DetectedCaptcha::HCaptcha,
        );
        assert_eq!(ordered.len(), 2);
        assert_eq!(ordered[0].name(), "WaitForTokenSolver");
        assert_eq!(ordered[1].name(), "VlmCaptchaSolver");
    }

    #[test]
    fn ordered_solvers_empty_when_no_solver_supports() {
        let chain = CaptchaSolverChain::default_chain();
        // DetectedCaptcha::None genuinely matches no solver — used as
        // the no-captcha sentinel. Slider/Multi-step etc. are now
        // supported by Behavioral and VLM (provider-routed solvers
        // need to attempt page-visible challenges).
        let ordered = chain.ordered_solvers(
            "example.com",
            &CaptchaType::Custom("none".into()),
            &crate::captcha_detect::DetectedCaptcha::None,
        );
        assert!(ordered.is_empty());
    }
}