lgwks_bot 2.2.0

Capability-gated automation bots on a change-detecting ECS schedule: Observe, Evaluate, Execute, and Query, with an async runtime facade.
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
//! The interface model: how a step recognizes the element it names.
//!
//! A recorded or authored step does not name an element by one selector. It
//! names it by a *recognition vector*: a set of facts observed about the
//! element, scored against the same facts observed now, with a decision made on
//! the score. This module is that model. It is pure — no I/O, no clock, no DOM —
//! because the facts arrive from a snapshot the caller already took.
//!
//! # Why the verdict is three-way
//!
//! [`Recognition`] is `Resolved` / `Ambiguous` / `Absent`, never
//! `Option<usize>`. A bare `Option` collapses two unlike situations into one
//! `None`: *nothing matched* and *several matched equally well*. The second is
//! the dangerous one. A page with two identical "Submit" buttons yields a
//! confident-looking best candidate, and a two-way verdict reports it as
//! success. The margin requirement is what makes that case unrepresentable: the
//! best candidate must lead the runner-up by a declared amount, or the result is
//! `Ambiguous` and the caller must re-ask rather than commit.
//!
//! This is the same distinction `docs/bot-on-ecs.md` §8.1 derives for a crawl
//! frontier — *a record that cannot distinguish "done" from "never started"* —
//! and the same one [`crate::error::BotError`] lacks for a timed-out `Execute`.
//! One invariant, four arrivals, and the fourth closed first: a resolver that
//! could not run at all reported a score of `0.0`, which is the same value as a
//! resolver that ran and found nothing, so `Resolution::Degraded` now carries
//! the cause instead.
//!
//! # The document boundary is a gate, not a score
//!
//! Two elements in different frames are in different documents. Scoring across
//! that boundary is how a look-alike in an advertisement iframe outranks the
//! real control, so a candidate whose piercing path differs from the target's is
//! excluded before it is scored. Similarity is for choosing within a document;
//! identity of document is not a similarity question.
//!
//! The tag is the other gate. A `button` and an `img` are not the same control
//! however alike their boxes are, and "both of these are buttons" is not a
//! degree of similarity that a weight should be able to outvote.
//!
//! # Missing evidence is not matching evidence
//!
//! A fingerprint compares two snapshots of the same element taken at different
//! moments. A fact that neither snapshot reports is not a fact the two
//! *agree* on: it is a comparison that was never made. The underlying metrics
//! cannot draw that distinction — [`Jaccard`] scores two empty sets as `1.0` by
//! the set convention every other consumer relies on, and an edit distance
//! scores two empty strings as `1.0` for the same reason — so it is drawn
//! here, at the component, where the meaning of the field is known. A fact
//! absent on either side contributes `0.0` and never more.
//!
//! Unobserved facts are not renormalized away either. Redistributing a missing
//! component's weight across the ones that remain would make a snapshot
//! carrying *less* evidence easier to match rather than harder, and geometry
//! alone could score a perfect `1.0`. The weights are fixed and the missing
//! weight stays missing, which is what lets the acceptance threshold say what
//! it means: `identity` is half the vector, so an element with no identifying
//! attribute cannot reach a threshold of three quarters however well the rest
//! of it lines up.
//!
//! [`Jaccard`]: lgwks_std::similarity::Jaccard
//! [`Recognition`]: crate::interface::Recognition

use std::fmt;

use lgwks_std::similarity::{
    BoundingBox, EditDistance, Geometry, Jaccard, PathSimilarity, Similarity, Weighted,
    WeightedError,
};

/// The largest text length the default fingerprint will compare.
pub const MAX_TEXT_CHARS: usize = 512;

/// The score at or above which the default fingerprint accepts a candidate.
pub const FINGERPRINT_THRESHOLD: f64 = 0.75;

/// The lead the default fingerprint requires over the runner-up.
pub const FINGERPRINT_MARGIN: f64 = 0.1;

/// Why a recognition vector could not be constructed.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum RecognitionError {
    /// The weighted composition of the vector was rejected.
    ///
    /// Carried rather than re-stated: the component rules (non-empty, weights
    /// summing to at most `1.0`, a threshold inside `[0.0, 1.0]`) belong to
    /// [`Weighted`], and duplicating them here would be a second policy that
    /// drifts from the first.
    Weights(WeightedError),
    /// The required lead over the runner-up was not a finite value in `[0.0, 1.0]`.
    InvalidMargin {
        /// The rejected margin.
        margin: f64,
    },
}

impl fmt::Display for RecognitionError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Self::Weights(ref cause) => write!(formatter, "recognition vector rejected: {cause}"),
            Self::InvalidMargin { margin } => write!(
                formatter,
                "recognition margin {margin} must be finite and within [0, 1]"
            ),
        }
    }
}

impl std::error::Error for RecognitionError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match *self {
            Self::Weights(ref cause) => Some(cause),
            Self::InvalidMargin { .. } => None,
        }
    }
}

impl From<WeightedError> for RecognitionError {
    fn from(cause: WeightedError) -> Self {
        Self::Weights(cause)
    }
}

/// The facts observed about one element: the recognition vector's input.
///
/// Each field is a thing a snapshot reports and a fingerprint can be computed
/// over, and nothing else. Identity and mutable content are separate on purpose:
/// `tag`, `identity` and `frames` survive a redeploy, while `text` and `bounds`
/// move whenever the page's data changes. A single fused field would make every
/// data change look like a structural change — the same measured failure
/// `docs/bot-on-ecs.md` §4 records for a fused `Endpoint`.
#[derive(Debug, Clone, Default, PartialEq)]
#[non_exhaustive]
pub struct ElementFacts {
    /// The element's tag name, normalized to lower case.
    tag: String,
    /// Normalized `name=value` attribute pairs, with volatile values removed.
    identity: Vec<String>,
    /// The structural path, with numeric ids and generated hashes stripped.
    path: String,
    /// The element's normalized visible text.
    text: String,
    /// The normalized bounding box, as `(x, y, width, height)`.
    bounds: [f64; 4],
    /// The piercing path: frame indexes from the top document downwards.
    frames: Vec<usize>,
    /// Locator anchors this element offers, in the order the snapshot reported
    /// them. Carried rather than derived so the snapshot layer — the only part
    /// that knows how a `data-testid` was found — decides what counts as one.
    anchors: Vec<(Anchor, String)>,
}

impl ElementFacts {
    /// Creates the facts for one element from the fields every snapshot carries.
    #[must_use]
    pub fn new(
        tag: impl Into<String>,
        path: impl Into<String>,
        text: impl Into<String>,
        bounds: [f64; 4],
    ) -> Self {
        Self {
            tag: tag.into(),
            identity: Vec::new(),
            path: path.into(),
            text: text.into(),
            bounds,
            frames: Vec::new(),
            anchors: Vec::new(),
        }
    }

    /// Returns the same facts with the given normalized identity attributes.
    #[must_use]
    pub fn with_identity(mut self, identity: Vec<String>) -> Self {
        self.identity = identity;
        self
    }

    /// Returns the same facts with one more locator anchor.
    ///
    /// An empty value is stored as written and reads back as `None` from
    /// [`Self::anchor`], so a snapshot that could not name the element's id
    /// does not offer `Anchor::Id` rather than offering a blank one that every
    /// other blank id would match.
    #[must_use]
    pub fn with_anchor(mut self, kind: Anchor, value: impl Into<String>) -> Self {
        self.anchors.push((kind, value.into()));
        self
    }

    /// Returns the same facts with the given document-piercing path.
    #[must_use]
    pub fn with_frames(mut self, frames: Vec<usize>) -> Self {
        self.frames = frames;
        self
    }

    /// Returns the element's lower-case tag name.
    #[must_use]
    pub fn tag(&self) -> &str {
        &self.tag
    }

    /// Returns the normalized identity attributes.
    #[must_use]
    pub fn identity(&self) -> &[String] {
        &self.identity
    }

    /// Returns the structural path.
    #[must_use]
    pub fn path(&self) -> &str {
        &self.path
    }

    /// Returns the visible text.
    #[must_use]
    pub fn text(&self) -> &str {
        &self.text
    }

    /// Returns the normalized bounding box as `(x, y, width, height)`.
    #[must_use]
    pub const fn bounds(&self) -> [f64; 4] {
        self.bounds
    }

    /// Returns the piercing path from the top document downwards.
    #[must_use]
    pub fn frames(&self) -> &[usize] {
        &self.frames
    }

    /// Returns the value of this element's first `kind` anchor, if it offers
    /// one with a non-empty value.
    #[must_use]
    pub fn anchor(&self, kind: Anchor) -> Option<&str> {
        self.anchors
            .iter()
            .find(|entry| entry.0 == kind && !entry.1.is_empty())
            .map(|entry| entry.1.as_str())
    }
}

/// One rung of a locator ladder: the kind of fact an anchor names.
///
/// The order is the one `docs/general-bot-fold.md` §3.2 takes from the
/// described platform's generator: a stable `id`, then a `data-testid`, then
/// the ARIA role (with its accessible name, which the snapshot layer folds into
/// the value), then visible text, then a class path. Strongest first, because
/// a class path is what survives least and is what a redeploy breaks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Anchor {
    /// A stable `id` attribute.
    Id,
    /// A `data-testid` or equivalent test hook.
    TestId,
    /// An ARIA role, optionally with its accessible name in the value.
    Role,
    /// The element's visible text.
    Text,
    /// A structural class or CSS path.
    ClassPath,
}

impl Anchor {
    /// Returns the rung's strength: lower is stronger.
    ///
    /// Explicit rather than a derived `Ord`, because a derived order puts the
    /// strongest variant first or last depending on declaration order, and that
    /// is a coin-flip a reader should not have to resolve.
    #[must_use]
    pub const fn rank(self) -> u8 {
        match self {
            Self::Id => 0,
            Self::TestId => 1,
            Self::Role => 2,
            Self::Text => 3,
            Self::ClassPath => 4,
        }
    }
}

impl PartialOrd for Anchor {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Anchor {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.rank().cmp(&other.rank())
    }
}

/// Why a [`Ladder`] could not be constructed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum LadderError {
    /// No anchors were given. A ladder with no rungs is not a search order.
    Empty,
}

impl fmt::Display for LadderError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Self::Empty => formatter.write_str("a locator ladder needs at least one anchor"),
        }
    }
}

impl std::error::Error for LadderError {}

/// An ordered locator ladder: anchors, strongest first, deduplicated.
///
/// The walk is `RecognitionVector::recognize_with_ladder`. This type only owns
/// the order, so a caller cannot construct a ladder whose "strongest" rung is
/// whatever happened to be declared first.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Ladder {
    /// Rungs, strongest first, each kind appearing once.
    anchors: Vec<Anchor>,
}

impl Ladder {
    /// Builds a ladder from any anchor list: sorted strongest-first and
    /// deduplicated, or [`LadderError::Empty`] when nothing was given.
    ///
    /// Deduplicated because two `Anchor::Text` rungs in a row are one rung and
    /// a repeated fall-through is a bug the walk should not have to notice.
    pub fn new(anchors: impl IntoIterator<Item = Anchor>) -> Result<Self, LadderError> {
        let mut sorted: Vec<Anchor> = anchors.into_iter().collect();
        if sorted.is_empty() {
            let refusal = Err(LadderError::Empty);
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "new: returning an error to the caller");
            return refusal;
        }
        sorted.sort_unstable_by_key(|anchor| anchor.rank());
        sorted.dedup();
        Ok(Self { anchors: sorted })
    }

    /// Returns the rungs, strongest first.
    #[must_use]
    pub fn anchors(&self) -> &[Anchor] {
        &self.anchors
    }
}

/// Scores two elements by their normalized identity attributes.
///
/// Identity is the strongest structural signal available: a `data-testid` or a
/// stable `id` is authored to be unique and to survive a restyle, which is
/// exactly what a locator needs and what a class path is not.
///
/// Not `Copy`, and the reason is worth recording: `Jaccard<T>` derives `Copy`
/// conservatively as `impl<T: Copy> Copy`, and `String` is not `Copy`, so the
/// `Jaccard<String>` this holds is not either. `Clone` is available and is all
/// the component needs.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct IdentityComponent {
    /// The set-similarity metric applied to the attribute collections.
    metric: Jaccard<String>,
}

impl IdentityComponent {
    /// Creates an identity component.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            metric: Jaccard::new(),
        }
    }
}

impl Default for IdentityComponent {
    fn default() -> Self {
        Self::new()
    }
}

impl Similarity for IdentityComponent {
    type Value = ElementFacts;

    fn score(&self, left: &Self::Value, right: &Self::Value) -> f64 {
        // No identifying attribute on either side is not agreement about an
        // empty set of attributes. `Jaccard` reads it as `1.0`, correctly for
        // every consumer that means set equality, and here it would hand an
        // element with nothing to identify it by the *maximum* identity
        // confidence — half the fingerprint's weight, for a fact neither
        // snapshot observed. So the presence of the evidence is decided before
        // the metric is consulted: absent on either side is no confidence.
        if left.identity.is_empty() || right.identity.is_empty() {
            return 0.0;
        }
        self.metric.score(&left.identity, &right.identity)
    }
}

/// Scores two elements by their structural path, ignoring volatile segments.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct PathComponent {
    /// The structural metric applied to the two paths.
    metric: PathSimilarity,
}

impl PathComponent {
    /// Creates a structural-path component.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            metric: PathSimilarity::new(),
        }
    }
}

impl Default for PathComponent {
    fn default() -> Self {
        Self::new()
    }
}

impl Similarity for PathComponent {
    type Value = ElementFacts;

    fn score(&self, left: &Self::Value, right: &Self::Value) -> f64 {
        // The same rule as identity, for the same reason: two empty paths are
        // not a structural agreement, they are a snapshot that reported no
        // structure. `PathSimilarity` scores the pair `1.0`.
        if left.path.is_empty() || right.path.is_empty() {
            return 0.0;
        }
        self.metric.score(&left.path, &right.path)
    }
}

/// Scores two elements by their visible text.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct TextComponent {
    /// The bounded lexical metric applied to the two texts.
    metric: EditDistance,
}

impl TextComponent {
    /// Creates a text component bounded by `maximum_length` characters per side.
    #[must_use]
    pub const fn new(maximum_length: usize) -> Self {
        Self {
            metric: EditDistance::new(maximum_length),
        }
    }
}

impl Similarity for TextComponent {
    type Value = ElementFacts;

    fn score(&self, left: &Self::Value, right: &Self::Value) -> f64 {
        // An element with no visible text is ordinary — an icon-only control,
        // a spacer, an image — and two of them do not agree about their text,
        // they both have none. `EditDistance` scores the empty pair `1.0`; the
        // presence rule refuses it. An icon-only control is recognized by its
        // identity and its structure, which is what those facts are for.
        if left.text.is_empty() || right.text.is_empty() {
            return 0.0;
        }
        self.metric.score(&left.text, &right.text)
    }
}

/// Scores two elements by where they sit in the layout.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct GeometryComponent {
    /// The geometric metric applied to the two boxes.
    metric: Geometry,
}

impl GeometryComponent {
    /// Creates a geometry component whose distance `maximum_distance` scores zero.
    #[must_use]
    pub const fn new(maximum_distance: f64) -> Self {
        Self {
            metric: Geometry::new(maximum_distance),
        }
    }
}

impl Similarity for GeometryComponent {
    type Value = ElementFacts;

    fn score(&self, left: &Self::Value, right: &Self::Value) -> f64 {
        // Geometry is the one component with no absence rule, and the reason is
        // that a bounding box has no unobserved state to confuse with an
        // observed one: every snapshot reports a box for every element it
        // reports at all, and `[0.0, 0.0, 0.0, 0.0]` is the position of an
        // element at the origin rather than a fact nobody looked at. If that
        // ever stops being true the field has to become an `Option`, because a
        // sentinel value is not a presence rule.
        let left_bounds = BoundingBox::from(left.bounds);
        let right_bounds = BoundingBox::from(right.bounds);
        self.metric.score(&left_bounds, &right_bounds)
    }
}

/// A weighted recognition vector, plus the lead it requires before committing.
///
/// `Debug` is derived and prints the scorer through [`Weighted`]'s own manual
/// impl, which reports the composition — how many components, their weights,
/// the acceptance threshold — rather than the `dyn` trait objects behind them.
/// The margin is printed alongside it. Nothing here prints an address.
#[derive(Debug)]
pub struct RecognitionVector {
    /// The composed scorer, already validated against the unit interval.
    scorer: Weighted<ElementFacts>,
    /// The minimum lead the best candidate must hold over the runner-up.
    margin: f64,
}

impl RecognitionVector {
    /// Builds a recognition vector from weighted components and its two rules.
    ///
    /// `threshold` is the score at or above which a candidate is a match at all;
    /// `margin` is the lead it must then hold over the runner-up to be the only
    /// match. Both are validated here rather than at first use, so a vector that
    /// cannot decide is refused where it is declared.
    pub fn new(
        components: Vec<(f64, Box<dyn Similarity<Value = ElementFacts>>)>,
        threshold: f64,
        margin: f64,
    ) -> Result<Self, RecognitionError> {
        if !margin.is_finite() || !(0.0..=1.0).contains(&margin) {
            let refusal = Err(RecognitionError::InvalidMargin { margin });
            lgwks_std::trace::debug!(error = ?refusal.as_ref().err(), "new: returning an error to the caller");
            return refusal;
        }
        Ok(Self {
            scorer: Weighted::new(components, threshold)?,
            margin,
        })
    }

    /// Builds the shipped default vector for a DOM element fingerprint.
    ///
    /// The weights are `1/2` identity, `1/4` structural path, `1/8` text and
    /// `1/8` geometry. They are powers of two so they sum to exactly `1.0` in
    /// binary floating point: a perfect match scores exactly `1.0`, and the
    /// `sum(w) <= 1.0` rule [`Weighted`] enforces holds by construction rather
    /// than by rounding luck. Every other constructor below relies on that —
    /// the weight set is not a tuning knob to nudge.
    ///
    /// The ordering states an opinion rather than balancing a grid: attributes
    /// authored to be stable outrank a class path, and layout is the weakest
    /// signal because it is the one that moves when a banner loads.
    ///
    /// The weights also settle which facts a match *requires*, and that is not
    /// an accident of the numbers: a component contributes nothing when the
    /// fact is absent on either side, so a score is at most the weight of the
    /// facts both elements actually reported. Identity and path together are
    /// `3/4`, exactly the threshold, so a candidate has to carry a genuinely
    /// observed matching identifier *and* a matching structure to be accepted
    /// at all — text and layout can never make up the difference. A vector
    /// built with different weights has a different set of required facts, and
    /// `RecognitionVector::new` is where that is declared.
    pub fn fingerprint() -> Result<Self, RecognitionError> {
        let components: Vec<(f64, Box<dyn Similarity<Value = ElementFacts>>)> = vec![
            (0.5, Box::new(IdentityComponent::new())),
            (0.25, Box::new(PathComponent::new())),
            (0.125, Box::new(TextComponent::new(MAX_TEXT_CHARS))),
            (0.125, Box::new(GeometryComponent::new(1.0))),
        ];
        Self::new(components, FINGERPRINT_THRESHOLD, FINGERPRINT_MARGIN)
    }

    /// Returns the score at or above which a candidate is a match at all.
    #[must_use]
    pub fn threshold(&self) -> f64 {
        self.scorer.threshold()
    }

    /// Returns the lead the best candidate must hold over the runner-up.
    #[must_use]
    pub const fn margin(&self) -> f64 {
        self.margin
    }

    /// Resolves which candidate the target names, as a three-way verdict.
    ///
    /// Candidates are compared in the order given and the lowest index wins a
    /// tie, so the result does not depend on iteration order — the comparator
    /// rule `docs/bot-on-ecs.md` §8 takes from Heritrix. Two candidates are
    /// excluded before they are scored rather than down-weighted: one whose
    /// piercing path differs from the target's, and one whose tag is an
    /// incompatible kind of thing. See the module documentation for why those
    /// are gates and not weights.
    #[must_use]
    pub fn recognize(&self, target: &ElementFacts, candidates: &[ElementFacts]) -> Recognition {
        let mut best: Option<(usize, f64)> = None;
        let mut next: Option<(usize, f64)> = None;

        for (index, candidate) in candidates.iter().enumerate() {
            if !is_eligible(target, candidate) {
                continue;
            }
            let score = self.scorer.score(target, candidate);
            match best {
                Some((_, best_score)) if score > best_score => {
                    next = best;
                    best = Some((index, score));
                }
                Some(_) => {
                    if next.is_none_or(|(_, next_score)| score > next_score) {
                        next = Some((index, score));
                    }
                }
                None => best = Some((index, score)),
            }
        }

        let Some((index, score)) = best else {
            return Recognition::Absent { best_score: 0.0 };
        };
        if score < self.scorer.threshold() {
            return Recognition::Absent { best_score: score };
        }

        let (runner_up, lead) = match next {
            Some((runner_up_index, runner_up_score)) => {
                (Some(runner_up_index), score - runner_up_score)
            }
            None => (None, score),
        };
        if lead < self.margin {
            return Recognition::Ambiguous {
                best: index,
                runner_up,
                score,
                lead,
            };
        }
        Recognition::Resolved { index, score, lead }
    }

    /// Resolves a target by walking `ladder` strongest-first.
    ///
    /// A rung decides by its own anchor and by nothing else. Candidates that
    /// are eligible, offer a non-empty value of that kind, and whose value
    /// equals the target's are the rung's hits; the fingerprint supplies the
    /// score fields but does not get to overrule the rung. The verdict:
    ///
    /// - **One hit** is [`Recognition::Resolved`]. A unique strong hit is the
    ///   ladder working, and its `index` is into `candidates`, not into the
    ///   rung's hit list.
    /// - **Two or more hits** is [`Recognition::Ambiguous`], returned at once
    ///   and **not** retried at a weaker rung. A weak anchor that succeeds
    ///   where a strong one was ambiguous is a likely mis-match, not a recovery:
    ///   two elements that share an `id` are not disambiguated by the fact that
    ///   only one of them happens to say "Submit" today.
    /// - **No hits** falls through. A weaker fact gets its chance. The rung
    ///   still contributes its measured `best_score` — how close the eligible
    ///   offerers came — so the final `Absent` is the strongest near-miss any
    ///   rung observed rather than a bare zero. A high-scoring candidate with
    ///   the wrong anchor remains absent: the score is evidence, not an anchor
    ///   match.
    ///
    /// A rung the target itself does not offer is skipped: there is nothing to
    /// match against, which is the same rule [`ElementFacts::anchor`] states
    /// for an empty value.
    #[must_use]
    pub fn recognize_with_ladder(
        &self,
        ladder: &Ladder,
        target: &ElementFacts,
        candidates: &[ElementFacts],
    ) -> Recognition {
        let mut strongest_absent = Recognition::Absent { best_score: 0.0 };
        for kind in ladder.anchors() {
            let Some(wanted) = target.anchor(*kind) else {
                continue;
            };
            let hits: Vec<usize> = candidates
                .iter()
                .enumerate()
                .filter(|entry| {
                    is_eligible(target, entry.1) && entry.1.anchor(*kind) == Some(wanted)
                })
                .map(|(index, _)| index)
                .collect();

            match hits.len() {
                0 => {
                    let near_miss = candidates
                        .iter()
                        .filter(|candidate| {
                            is_eligible(target, candidate) && candidate.anchor(*kind).is_some()
                        })
                        .map(|candidate| self.scorer.score(target, candidate))
                        .fold(0.0_f64, f64::max);
                    if let Recognition::Absent { best_score: prior } = strongest_absent
                        && near_miss > prior
                    {
                        strongest_absent = Recognition::Absent {
                            best_score: near_miss,
                        };
                    }
                }
                1 => {
                    let index = hits[0];
                    let score = self.scorer.score(target, &candidates[index]);
                    return Recognition::Resolved {
                        index,
                        score,
                        lead: score,
                    };
                }
                _ => {
                    let mut scored: Vec<(usize, f64)> = hits
                        .iter()
                        .map(|&index| (index, self.scorer.score(target, &candidates[index])))
                        .collect();
                    scored.sort_by(|left, right| {
                        right.1.total_cmp(&left.1).then(left.0.cmp(&right.0))
                    });
                    let (best, score) = scored[0];
                    let (runner_up, runner_up_score) = scored[1];
                    return Recognition::Ambiguous {
                        best,
                        runner_up: Some(runner_up),
                        score,
                        lead: score - runner_up_score,
                    };
                }
            }
        }
        strongest_absent
    }
}

/// Whether a candidate belongs to the target's document and kind.
///
/// This is the single eligibility gate shared by flat recognition and every
/// ladder rung. Similarity may rank eligible candidates, but it cannot grant
/// ownership across a frame boundary or between incompatible elements.
fn is_eligible(target: &ElementFacts, candidate: &ElementFacts) -> bool {
    candidate.frames == target.frames && tags_compatible(target, candidate)
}

/// Whether two elements are the same kind of thing.
///
/// The tag is the coarsest structural fact a snapshot reports and the cheapest
/// way for two elements to be obviously different. It is a gate rather than a
/// weighted component for the same reason the frame path is: "both of these are
/// buttons" is not a degree of similarity, and a weight would let a strong
/// enough identifier score outvote a candidate that is a different HTML
/// element entirely.
///
/// An empty tag is an unreported fact rather than a claim of incompatibility,
/// so it excludes nothing. It also cannot help: the tag is not one of the
/// components, so an unknown tag leaves the candidate with exactly the evidence
/// the remaining facts supply. A *role* is not consulted here because a snapshot
/// carries it inside `identity` (`role=button`, an ARIA role attribute) and it
/// is scored there as an identifying attribute, with half the vector's weight
/// behind it.
fn tags_compatible(target: &ElementFacts, candidate: &ElementFacts) -> bool {
    target.tag.is_empty() || candidate.tag.is_empty() || target.tag == candidate.tag
}

/// The outcome of resolving a target element against a set of candidates.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum Recognition {
    /// One candidate cleared the threshold and led by at least the margin.
    Resolved {
        /// Index of the selected candidate.
        index: usize,
        /// The selected candidate's score.
        score: f64,
        /// The lead it held over the runner-up.
        lead: f64,
    },
    /// Candidates cleared the threshold but none led by the margin.
    ///
    /// Not a failure and not a success. It is the state that must produce a
    /// re-ask, and it exists so that a caller cannot take the best of an
    /// indistinguishable field and call it a match. `runner_up` is `None` when
    /// the sole candidate's own score fell short of the margin.
    Ambiguous {
        /// Index of the highest-scoring candidate.
        best: usize,
        /// Index of the candidate it failed to separate from.
        runner_up: Option<usize>,
        /// The highest score observed.
        score: f64,
        /// The lead held over the runner-up.
        lead: f64,
    },
    /// No candidate satisfied the recognizer's decision rule.
    ///
    /// Flat recognition uses this when no eligible candidate reaches the
    /// fingerprint threshold. A ladder also uses it when eligible candidates
    /// offer the wrong anchor; in that case `best_score` preserves the actual
    /// fingerprint evidence even though the anchor verdict remains absent.
    Absent {
        /// The highest fingerprint score observed for a candidate that did
        /// not satisfy the recognizer's decision rule.
        best_score: f64,
    },
}

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

    /// Asserts two scores agree to within the tolerance float arithmetic needs.
    ///
    /// An epsilon rather than `==`: `clippy::float_cmp` is forbidden workspace
    /// wide, and exact float equality in a test is a claim the test cannot
    /// actually check.
    fn assert_close(left: f64, right: f64) {
        assert!(
            (left - right).abs() < 1e-9,
            "expected {right}, observed {left}"
        );
    }

    /// Builds a candidate carrying one identity attribute and some visible text.
    fn candidate(identity: &str, text: &str) -> ElementFacts {
        ElementFacts::new(
            "button",
            "html > body > form > button",
            text,
            [0.5, 0.5, 0.1, 0.05],
        )
        .with_identity(vec![String::from(identity)])
    }

    /// Builds the shipped default vector.
    fn vector() -> Result<RecognitionVector, RecognitionError> {
        RecognitionVector::fingerprint()
    }

    #[test]
    fn identical_facts_resolve_with_a_full_score() -> Result<(), RecognitionError> {
        let target = candidate("data-testid=submit", "Submit");
        assert_eq!(
            vector()?.recognize(&target, std::slice::from_ref(&target)),
            Recognition::Resolved {
                index: 0,
                score: 1.0,
                lead: 1.0,
            }
        );
        Ok(())
    }

    #[test]
    fn an_empty_candidate_set_is_absent_not_a_panic() -> Result<(), RecognitionError> {
        let target = candidate("data-testid=submit", "Submit");
        assert_eq!(
            vector()?.recognize(&target, &[]),
            Recognition::Absent { best_score: 0.0 }
        );
        Ok(())
    }

    #[test]
    fn two_indistinguishable_candidates_are_ambiguous() -> Result<(), RecognitionError> {
        let target = candidate("data-testid=submit", "Submit");
        let twin = candidate("data-testid=submit", "Submit");
        assert_eq!(
            vector()?.recognize(&target, &[twin.clone(), twin]),
            Recognition::Ambiguous {
                best: 0,
                runner_up: Some(1),
                score: 1.0,
                lead: 0.0,
            },
            "the lowest index must win a tie, and the pair must not resolve"
        );
        Ok(())
    }

    /// Builds facts for an element that carries a tag and a path and nothing
    /// else: no identity attributes, no text.
    fn bare(tag: &str, path: &str) -> ElementFacts {
        ElementFacts::new(tag, path, "", [0.5, 0.5, 0.1, 0.05])
    }

    /// Builds facts for an icon-only control: an identifier, a path and a box,
    /// and no visible text.
    fn icon(identifier: &str) -> ElementFacts {
        bare("button", "html > body > nav > button").with_identity(vec![String::from(identifier)])
    }

    #[test]
    fn absent_identity_is_not_evidence_that_an_unrelated_element_matches()
    -> Result<(), RecognitionError> {
        // GitHub issue #39's counterexample, verbatim. Neither fact carries an
        // identifying attribute and neither carries text; the two boxes and the
        // two paths are identical; the tags differ. This used to score
        // `Resolved { index: 0, score: 0.75, lead: 0.75 }` — identity `1.0` from
        // `Jaccard`'s empty-set convention, text `1.0` from the edit distance's,
        // geometry `1.0`, path `0.0` — a confident locator decision for an
        // element that is not even the same kind of thing.
        let target = ElementFacts::new("button", "button", "", [0.5, 0.5, 0.1, 0.05]);
        let unrelated = ElementFacts::new("img", "img", "", [0.5, 0.5, 0.1, 0.05]);
        let result = vector()?.recognize(&target, &[unrelated]);
        assert!(matches!(result, Recognition::Absent { .. }), "{result:?}");
        Ok(())
    }

    #[test]
    fn the_metric_convention_is_intact_where_it_belongs() {
        // The rule being corrected lives one layer down, and it is still
        // correct there: two empty sets are the same set and two empty strings
        // are the same string. What element recognition changes is the reading
        // of "empty" — *nothing to compare* rather than *identical* — and this
        // asserts both halves, so a future repair cannot quietly change the
        // shared metric to fix a consumer.
        let no_attributes: [String; 0] = [];
        assert_close(
            Jaccard::<String>::new().score(&no_attributes, &no_attributes),
            1.0,
        );
        assert_close(EditDistance::new(8).score("", ""), 1.0);
        assert_close(PathSimilarity::new().score("", ""), 1.0);

        let blank = bare("button", "");
        assert_close(IdentityComponent::new().score(&blank, &blank), 0.0);
        assert_close(TextComponent::new(8).score(&blank, &blank), 0.0);
        assert_close(PathComponent::new().score(&blank, &blank), 0.0);
    }

    #[test]
    fn an_element_with_nothing_to_identify_it_by_cannot_resolve() -> Result<(), RecognitionError> {
        // Same tag, same path, same box, no text, and no identity attributes on
        // either side. Every fact that is present agrees perfectly, and the two
        // snapshots still say nothing about which element this is: the absent
        // facts are comparisons that were not made, not comparisons that
        // succeeded. Identity is half the vector and the threshold is three
        // quarters, so it cannot resolve however well the rest lines up.
        let recognition = vector()?.recognize(
            &bare("button", "html > body > form > button"),
            &[bare("button", "html > body > form > button")],
        );
        assert!(
            matches!(
                recognition,
                Recognition::Absent { best_score } if best_score < FINGERPRINT_THRESHOLD
            ),
            "two elements with no identifying evidence must not match, got {recognition:?}"
        );
        Ok(())
    }

    #[test]
    fn an_icon_only_control_resolves_on_its_identifier() -> Result<(), RecognitionError> {
        // The positive case the presence rule must not break: no visible text
        // at all, and a genuinely observed matching stable identifier. Text is
        // absent on both sides and contributes nothing; identity and structure
        // carry the decision, which is what those facts are for.
        let target = icon("data-testid=menu");
        let recognition = vector()?.recognize(&target, std::slice::from_ref(&target));
        assert!(
            matches!(
                recognition,
                Recognition::Resolved { index: 0, score, lead }
                    if (score - 0.875).abs() < 1e-9 && lead >= FINGERPRINT_MARGIN
            ),
            "a matching identifier must still resolve an icon-only control, got {recognition:?}"
        );
        Ok(())
    }

    #[test]
    fn an_icon_only_control_does_not_match_on_layout() -> Result<(), RecognitionError> {
        // The same icon-only pair with different identifiers. Identity is
        // unobserved-in-effect (both sides report one, and they disagree) and
        // text is absent, so the only facts left are the path and the box, worth
        // a quarter of the vector between them — nowhere near three quarters.
        // Layout alone cannot locate a control.
        let target = icon("data-testid=menu");
        let other = icon("data-testid=close");
        let recognition = vector()?.recognize(&target, &[other]);
        assert!(
            matches!(
                recognition,
                Recognition::Absent { best_score } if best_score < FINGERPRINT_THRESHOLD
            ),
            "a quarter of the vector must not resolve, got {recognition:?}"
        );
        Ok(())
    }

    #[test]
    fn an_unrelated_tag_is_excluded_however_well_the_rest_agrees() -> Result<(), RecognitionError> {
        // Every component in the vector agrees perfectly, including a genuinely
        // observed matching identifier and matching text. The tag disagrees, and
        // the tag is a gate, so the candidate is never scored. The mirror case
        // below is what shows the gate is the cause rather than the scoring.
        let facts = |tag: &str| {
            ElementFacts::new(
                tag,
                "html > body > form > button",
                "Submit",
                [0.5, 0.5, 0.1, 0.05],
            )
            .with_identity(vec![String::from("data-testid=submit")])
        };
        let target = facts("button");
        let impostor = facts("img");
        assert_eq!(
            vector()?.recognize(&target, &[impostor]),
            Recognition::Absent { best_score: 0.0 },
            "a different element kind is not a candidate"
        );
        let twin = facts("button");
        assert!(
            matches!(
                vector()?.recognize(&target, &[twin]),
                Recognition::Resolved { score, .. } if (score - 1.0).abs() < 1e-9
            ),
            "the identical element on the same facts still resolves"
        );
        Ok(())
    }

    #[test]
    fn an_unreported_tag_excludes_nothing() -> Result<(), RecognitionError> {
        // An empty tag is a fact nobody reported, not a competing one, so it
        // cannot be an incompatibility. It cannot help either: the tag is not a
        // component, so the candidate has exactly the evidence its other facts
        // supply, and it still has to clear the threshold on those.
        let target = ElementFacts::new(
            "button",
            "html > body > form > button",
            "Submit",
            [0.5, 0.5, 0.1, 0.05],
        )
        .with_identity(vec![String::from("data-testid=submit")]);
        let unlabelled = ElementFacts::new(
            "",
            "html > body > form > button",
            "Submit",
            [0.5, 0.5, 0.1, 0.05],
        )
        .with_identity(vec![String::from("data-testid=submit")]);
        let recognition = vector()?.recognize(&target, &[unlabelled]);
        assert!(
            matches!(recognition, Recognition::Resolved { index: 0, .. }),
            "an unreported tag must not exclude an otherwise matching element, got {recognition:?}"
        );
        Ok(())
    }

    #[test]
    fn structurally_distinct_candidates_are_measured_and_rejected() -> Result<(), RecognitionError>
    {
        // Same tag, so the candidate is scored rather than gated, and every
        // fact it reports differs. The score is a real measurement below the
        // threshold, which is the difference between "looked at and rejected"
        // and "never looked at".
        let target = ElementFacts::new(
            "button",
            "html > body > form > button",
            "Submit order",
            [0.5, 0.5, 0.1, 0.05],
        )
        .with_identity(vec![String::from("data-testid=submit")]);
        let elsewhere = ElementFacts::new(
            "button",
            "html > body > article > aside > button",
            "Terms and conditions",
            [900.0, 900.0, 0.1, 0.05],
        )
        .with_identity(vec![String::from("data-testid=legal")]);
        let recognition = vector()?.recognize(&target, &[elsewhere]);
        assert!(
            matches!(
                recognition,
                Recognition::Absent { best_score }
                    if best_score < FINGERPRINT_THRESHOLD && best_score > 0.0
            ),
            "a scored near-miss is Absent at its measured score, got {recognition:?}"
        );
        Ok(())
    }

    #[test]
    fn two_indistinguishable_icon_only_candidates_are_ambiguous() -> Result<(), RecognitionError> {
        // The same absence rules, with a field instead of a lone candidate: two
        // identical icon-only controls carry the same observed identifier, so
        // neither can be separated from the other, and the verdict is the one
        // that forces a re-ask rather than a guess.
        let target = icon("data-testid=menu");
        let recognition = vector()?.recognize(&target, &[target.clone(), target.clone()]);
        assert!(
            matches!(
                &recognition,
                Recognition::Ambiguous { best: 0, runner_up: Some(1), score, lead }
                    if (score - 0.875).abs() < 1e-9 && lead.abs() < 1e-9
            ),
            "two indistinguishable icon-only controls are a tie, got {recognition:?}"
        );
        Ok(())
    }

    #[test]
    fn a_clear_winner_resolves() -> Result<(), RecognitionError> {
        let target = candidate("data-testid=submit", "Submit order");
        let candidates = [candidate("data-testid=cancel", "Cancel"), target.clone()];
        let recognition = vector()?.recognize(&target, &candidates);
        // `lead` is the gap to the runner-up, not the score: with a competitor
        // present it is `best - next`, so this cannot be asserted as `1.0` the
        // way the no-competitor case above can. Asserting the property rather
        // than a transcribed float also keeps this test from breaking on a
        // legitimate reweight of the default vector.
        assert!(
            matches!(
                recognition,
                Recognition::Resolved { index: 1, score, lead }
                    if (score - 1.0).abs() < 1e-9 && lead >= FINGERPRINT_MARGIN
            ),
            "the second candidate must win outright with a lead over the margin, got {recognition:?}"
        );
        Ok(())
    }

    #[test]
    fn a_candidate_in_another_document_is_excluded_before_scoring() -> Result<(), RecognitionError>
    {
        let target = candidate("data-testid=submit", "Submit").with_frames(vec![0]);
        let look_alike = candidate("data-testid=submit", "Submit").with_frames(vec![3]);
        assert_eq!(
            vector()?.recognize(&target, &[look_alike]),
            Recognition::Absent { best_score: 0.0 },
            "a perfect score across a frame boundary must not be reachable"
        );
        Ok(())
    }

    #[test]
    fn a_weak_candidate_is_absent_below_the_threshold() -> Result<(), RecognitionError> {
        let target = candidate("data-testid=submit", "Submit order");
        let unrelated = ElementFacts::new(
            "section",
            "html > body > article",
            "Terms and conditions",
            [0.0, 0.0, 0.1, 0.1],
        )
        .with_identity(vec![String::from("data-testid=legal")]);
        let recognition = vector()?.recognize(&target, &[unrelated]);
        assert!(
            matches!(
                recognition,
                Recognition::Absent { best_score } if best_score < FINGERPRINT_THRESHOLD
            ),
            "an unrelated element must be Absent below the threshold, got {recognition:?}"
        );
        Ok(())
    }

    #[test]
    fn an_empty_component_set_is_refused() {
        let components: Vec<(f64, Box<dyn Similarity<Value = ElementFacts>>)> = Vec::new();
        assert_eq!(
            RecognitionVector::new(components, 0.5, 0.1).err(),
            Some(RecognitionError::Weights(WeightedError::Empty))
        );
    }

    #[test]
    fn weights_above_one_are_refused() {
        let components: Vec<(f64, Box<dyn Similarity<Value = ElementFacts>>)> = vec![
            (0.75, Box::new(IdentityComponent::new())),
            (0.75, Box::new(PathComponent::new())),
        ];
        assert_eq!(
            RecognitionVector::new(components, 0.5, 0.1).err(),
            Some(RecognitionError::Weights(
                WeightedError::WeightSumExceedsOne
            ))
        );
    }

    #[test]
    fn a_margin_outside_the_unit_interval_is_refused() {
        let components: Vec<(f64, Box<dyn Similarity<Value = ElementFacts>>)> =
            vec![(0.5, Box::new(IdentityComponent::new()))];
        assert_eq!(
            RecognitionVector::new(components, 0.5, 1.5).err(),
            Some(RecognitionError::InvalidMargin { margin: 1.5 })
        );
    }

    #[test]
    fn the_shipped_vector_carries_its_declared_rules() -> Result<(), RecognitionError> {
        let vector = vector()?;
        assert_close(vector.threshold(), FINGERPRINT_THRESHOLD);
        assert_close(vector.margin(), FINGERPRINT_MARGIN);
        assert_close(0.5 + 0.25 + 0.125 + 0.125, 1.0);
        Ok(())
    }

    /// Builds facts offering one anchor value, plus the shared shell every
    /// ladder test needs so the fingerprint can score at all.
    fn anchored(tag: &str, kind: Anchor, value: &str, text: &str) -> ElementFacts {
        ElementFacts::new(
            tag,
            "html > body > form > button",
            text,
            [0.5, 0.5, 0.1, 0.05],
        )
        .with_anchor(kind, value)
        .with_identity(vec![format!("{kind:?}={value}")])
    }

    #[test]
    fn an_empty_ladder_is_an_error() {
        assert_eq!(Ladder::new([]), Err(LadderError::Empty));
    }

    #[test]
    fn a_ladder_is_sorted_and_deduplicated_strongest_first() -> Result<(), LadderError> {
        let ladder = Ladder::new([
            Anchor::ClassPath,
            Anchor::Id,
            Anchor::Text,
            Anchor::Id,
            Anchor::TestId,
        ])?;
        assert_eq!(
            ladder.anchors(),
            &[Anchor::Id, Anchor::TestId, Anchor::Text, Anchor::ClassPath],
            "input order must not decide rank, and a repeated rung is one rung"
        );
        Ok(())
    }

    #[test]
    fn an_empty_anchor_value_is_not_offered() {
        let facts = anchored("button", Anchor::Id, "", "Submit");
        assert_eq!(facts.anchor(Anchor::Id), None);
        assert_eq!(facts.anchor(Anchor::TestId), None);
    }

    #[test]
    fn a_unique_strong_anchor_resolves_at_the_first_rung() -> Result<(), Box<dyn std::error::Error>>
    {
        let target = anchored("button", Anchor::Id, "submit", "Submit");
        let other = anchored("button", Anchor::Id, "cancel", "Cancel");
        let ladder = Ladder::new([Anchor::Id, Anchor::Text])?;
        let recognition =
            vector()?.recognize_with_ladder(&ladder, &target, &[other, target.clone()]);
        assert!(
            matches!(recognition, Recognition::Resolved { index: 1, .. }),
            "the sole id match must resolve, got {recognition:?}"
        );
        Ok(())
    }

    #[test]
    fn ambiguous_at_a_strong_anchor_is_not_retried_at_a_weak_one()
    -> Result<(), Box<dyn std::error::Error>> {
        // Two candidates share the target's id, so the strongest rung cannot
        // separate them. Their texts differ, and the weaker text rung would
        // pick one of them. That "recovery" is exactly what the walk must
        // refuse: a weak anchor succeeding where a strong one was ambiguous is
        // a likely mis-match, not a resolution.
        let target = anchored("button", Anchor::Id, "submit", "Submit");
        let twin = anchored("button", Anchor::Id, "submit", "Delete");
        let ladder = Ladder::new([Anchor::Id, Anchor::Text])?;
        let recognition =
            vector()?.recognize_with_ladder(&ladder, &target, &[twin, target.clone()]);
        assert!(
            matches!(recognition, Recognition::Ambiguous { .. }),
            "a strong-rung ambiguity must stand, got {recognition:?}"
        );
        Ok(())
    }

    #[test]
    fn the_ladder_falls_through_when_the_strong_anchor_is_absent()
    -> Result<(), Box<dyn std::error::Error>> {
        // Neither element carries an id, so the first rung offers nobody. The
        // test-id rung has exactly one match and must take the decision.
        let target = anchored("button", Anchor::TestId, "checkout", "Submit");
        let other = anchored("button", Anchor::TestId, "cancel", "Cancel");
        let ladder = Ladder::new([Anchor::Id, Anchor::TestId])?;
        let recognition =
            vector()?.recognize_with_ladder(&ladder, &target, &[other, target.clone()]);
        assert!(
            matches!(recognition, Recognition::Resolved { index: 1, .. }),
            "the fall-down must reach the test-id rung, got {recognition:?}"
        );
        Ok(())
    }

    #[test]
    fn every_rung_absent_reports_the_strongest_absent() -> Result<(), Box<dyn std::error::Error>> {
        // Nothing matches on any rung. The return is the highest `best_score`
        // any rung reached, so the caller can see how close the strongest
        // evidence came rather than a bare zero.
        let target = ElementFacts::new(
            "button",
            "html > body > form > button",
            "Submit",
            [0.5, 0.5, 0.1, 0.05],
        )
        .with_anchor(Anchor::Id, "submit")
        .with_anchor(Anchor::ClassPath, "html > body > form > button");
        let unrelated = ElementFacts::new(
            "button",
            "html > body > footer > button",
            "Cancel",
            [0.1, 0.9, 0.1, 0.05],
        )
        .with_anchor(Anchor::Id, "cancel")
        .with_anchor(Anchor::ClassPath, "html > body > footer > button");
        let ladder = Ladder::new([Anchor::Id, Anchor::ClassPath])?;
        let recognition = vector()?.recognize_with_ladder(&ladder, &target, &[unrelated]);
        assert!(
            matches!(
                recognition,
                Recognition::Absent { best_score }
                    if (0.0..FINGERPRINT_THRESHOLD).contains(&best_score)
            ),
            "absent must report a sub-threshold score, got {recognition:?}"
        );
        Ok(())
    }

    #[test]
    fn a_candidate_that_offers_no_matching_anchor_is_never_scored()
    -> Result<(), Box<dyn std::error::Error>> {
        let target = anchored("button", Anchor::Id, "submit", "Submit");
        let blank = bare("button", "html > body > form > button");
        let ladder = Ladder::new([Anchor::Id])?;
        assert_eq!(
            vector()?.recognize_with_ladder(&ladder, &target, &[blank]),
            Recognition::Absent { best_score: 0.0 },
            "an id rung with nobody in it is a fall-through to a finished ladder"
        );
        Ok(())
    }
}