axterminator 0.7.1

macOS GUI testing framework with background testing, sub-millisecond element access, and self-healing locators
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
//! Triple Understanding — Visual + Semantic + Structural cross-validation.
//!
//! Combines three independent perception signals to produce a robust
//! [`ElementUnderstanding`] with a blended confidence score.
//!
//! # Signal weights
//!
//! | Signal     | Weight |
//! |------------|--------|
//! | Visual     |  0.20  |
//! | Semantic   |  0.50  |
//! | Structural |  0.30  |
//!
//! # Usage
//!
//! ```rust
//! use axterminator::triple_understanding::{
//!     ElementUnderstanding, VisualSignal, SemanticSignal, StructuralSignal,
//!     Rect, Position, SizeClass, TripleUnderstanding,
//! };
//!
//! let understanding = TripleUnderstanding::build(
//!     VisualSignal {
//!         bounds: Rect { x: 10.0, y: 20.0, width: 80.0, height: 30.0 },
//!         relative_position: Position::TopLeft,
//!         size_class: SizeClass::Medium,
//!     },
//!     SemanticSignal {
//!         role: "AXButton".into(),
//!         label: "Submit".into(),
//!         value: None,
//!     },
//!     StructuralSignal {
//!         depth: 3,
//!         parent_role: "AXGroup".into(),
//!         sibling_index: 0,
//!         child_count: 0,
//!     },
//! );
//!
//! assert!(understanding.combined_confidence > 0.0);
//! ```

// ── Types ─────────────────────────────────────────────────────────────────────

/// Axis-aligned bounding rectangle in screen coordinates.
#[derive(Debug, Clone, PartialEq)]
pub struct Rect {
    /// Left edge in points.
    pub x: f64,
    /// Top edge in points.
    pub y: f64,
    /// Width in points.
    pub width: f64,
    /// Height in points.
    pub height: f64,
}

impl Rect {
    /// Compute the center point.
    #[must_use]
    pub fn center(&self) -> (f64, f64) {
        (self.x + self.width / 2.0, self.y + self.height / 2.0)
    }

    /// Area in square points.
    #[must_use]
    pub fn area(&self) -> f64 {
        self.width * self.height
    }
}

/// Coarse relative placement of the element within its container.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Position {
    /// Upper-left quadrant.
    TopLeft,
    /// Upper-right quadrant.
    TopRight,
    /// Vertically and horizontally centred.
    Center,
    /// Lower-left quadrant.
    BottomLeft,
    /// Lower-right quadrant.
    BottomRight,
}

/// Coarse size bucket for quick visual classification.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SizeClass {
    /// Area < 1 000 pt².
    Small,
    /// Area between 1 000 and 10 000 pt².
    Medium,
    /// Area between 10 000 and 100 000 pt².
    Large,
    /// Area ≥ 100 000 pt² — typically occupies the full window.
    FullWidth,
}

impl SizeClass {
    /// Classify a [`Rect`] into a [`SizeClass`] based on area.
    #[must_use]
    pub fn from_rect(rect: &Rect) -> Self {
        match rect.area() {
            a if a < 1_000.0 => Self::Small,
            a if a < 10_000.0 => Self::Medium,
            a if a < 100_000.0 => Self::Large,
            _ => Self::FullWidth,
        }
    }

    /// Numeric confidence contribution for this size class (used in scoring).
    ///
    /// Smaller elements carry lower visual confidence because they are harder
    /// to locate precisely on screen.
    #[must_use]
    fn confidence(&self) -> f64 {
        match self {
            Self::Small => 0.5,
            Self::Medium => 0.8,
            Self::Large => 0.9,
            Self::FullWidth => 1.0,
        }
    }
}

/// Visual perception signal — pixel-level evidence from the screen.
#[derive(Debug, Clone, PartialEq)]
pub struct VisualSignal {
    /// Screen bounding rectangle.
    pub bounds: Rect,
    /// Coarse placement relative to the containing window / viewport.
    pub relative_position: Position,
    /// Coarse size category.
    pub size_class: SizeClass,
}

impl VisualSignal {
    /// Compute a visual confidence score in `[0.0, 1.0]`.
    ///
    /// Confidence is high when the element has a non-trivial size and a
    /// well-defined position.
    #[must_use]
    pub fn confidence(&self) -> f64 {
        let area_factor = (self.bounds.area() / 10_000.0).min(1.0).sqrt();
        // Blend area factor with size-class heuristic for robustness.
        (area_factor + self.size_class.confidence()) / 2.0
    }
}

/// Semantic perception signal — accessibility labels and roles.
#[derive(Debug, Clone, PartialEq)]
pub struct SemanticSignal {
    /// Accessibility role (e.g., `"AXButton"`).
    pub role: String,
    /// Human-readable label or title.
    pub label: String,
    /// Current value of the element, if any.
    pub value: Option<String>,
}

impl SemanticSignal {
    /// Compute a semantic confidence score in `[0.0, 1.0]`.
    ///
    /// Confidence increases when both role and label are non-empty,
    /// and further when a value is present.
    #[must_use]
    pub fn confidence(&self) -> f64 {
        let role_score: f64 = if self.role.is_empty() { 0.0 } else { 0.4 };
        let label_score: f64 = match self.label.len() {
            0 => 0.0,
            1..=3 => 0.2,
            4..=20 => 0.5,
            _ => 0.4, // Very long labels are slightly less reliable
        };
        let value_bonus: f64 = if self.value.is_some() { 0.1 } else { 0.0 };
        (role_score + label_score + value_bonus).min(1.0_f64)
    }
}

/// Structural perception signal — position in the accessibility/DOM tree.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StructuralSignal {
    /// Depth from root (root = 0).
    pub depth: usize,
    /// Role of the immediate parent element.
    pub parent_role: String,
    /// Zero-based index among siblings with the same parent.
    pub sibling_index: usize,
    /// Number of direct children.
    pub child_count: usize,
}

impl StructuralSignal {
    /// Compute a structural confidence score in `[0.0, 1.0]`.
    ///
    /// Leaf nodes at moderate depth with a known parent role are more
    /// structurally specific and thus carry higher confidence.
    #[must_use]
    pub fn confidence(&self) -> f64 {
        let parent_score: f64 = if self.parent_role.is_empty() {
            0.3
        } else {
            0.6
        };
        // Leaf nodes are more unique; deep nodes are more specific.
        let leaf_bonus: f64 = if self.child_count == 0 { 0.2 } else { 0.0 };
        let depth_score: f64 = match self.depth {
            0 => 0.1, // Root — not specific at all
            1..=2 => 0.3,
            3..=6 => 0.5,
            _ => 0.4, // Very deep nesting is uncommon and slightly less stable
        };
        (parent_score + leaf_bonus + depth_score).min(1.0_f64)
    }
}

/// Inconsistency between two perception sources for the same element.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Inconsistency {
    /// Element appears visually disabled but a11y reports it as enabled.
    VisuallyDisabledButA11yEnabled,
    /// Element is not in the accessibility tree despite being on screen.
    NotInA11yTree,
    /// Element appears to be loading / transitioning.
    LoadingState,
    /// An unrecognised discrepancy between sources.
    Other(String),
}

/// Full tri-source understanding of a single UI element.
#[derive(Debug, Clone)]
pub struct ElementUnderstanding {
    /// Pixel-level signal.
    pub visual: VisualSignal,
    /// Accessibility-API signal.
    pub semantic: SemanticSignal,
    /// AX-tree structural signal.
    pub structural: StructuralSignal,
    /// Blended confidence score in `[0.0, 1.0]`.
    pub combined_confidence: f64,
    /// Cross-source inconsistencies detected, if any.
    pub inconsistencies: Vec<Inconsistency>,
}

// ── Weight constants ───────────────────────────────────────────────────────────

const VISUAL_WEIGHT: f64 = 0.20;
const SEMANTIC_WEIGHT: f64 = 0.50;
const STRUCTURAL_WEIGHT: f64 = 0.30;

// ── TripleUnderstanding builder ───────────────────────────────────────────────

/// Builder that combines visual, semantic, and structural signals.
///
/// # Example
///
/// ```rust
/// use axterminator::triple_understanding::*;
///
/// let understanding = TripleUnderstanding::build(
///     VisualSignal {
///         bounds: Rect { x: 0.0, y: 0.0, width: 100.0, height: 30.0 },
///         relative_position: Position::TopLeft,
///         size_class: SizeClass::Medium,
///     },
///     SemanticSignal { role: "AXButton".into(), label: "OK".into(), value: None },
///     StructuralSignal {
///         depth: 3,
///         parent_role: "AXWindow".into(),
///         sibling_index: 0,
///         child_count: 0,
///     },
/// );
/// assert!(understanding.combined_confidence > 0.0);
/// ```
pub struct TripleUnderstanding;

impl TripleUnderstanding {
    /// Combine three signals into an [`ElementUnderstanding`].
    ///
    /// Combined confidence is the weighted average:
    /// `0.20 × visual + 0.50 × semantic + 0.30 × structural`.
    #[must_use]
    pub fn build(
        visual: VisualSignal,
        semantic: SemanticSignal,
        structural: StructuralSignal,
    ) -> ElementUnderstanding {
        let combined_confidence = Self::weighted_confidence(&visual, &semantic, &structural);
        let inconsistencies = Self::detect_inconsistencies(&visual, &semantic);

        ElementUnderstanding {
            visual,
            semantic,
            structural,
            combined_confidence,
            inconsistencies,
        }
    }

    /// Compute blended confidence from the three signals.
    fn weighted_confidence(
        visual: &VisualSignal,
        semantic: &SemanticSignal,
        structural: &StructuralSignal,
    ) -> f64 {
        VISUAL_WEIGHT * visual.confidence()
            + SEMANTIC_WEIGHT * semantic.confidence()
            + STRUCTURAL_WEIGHT * structural.confidence()
    }

    /// Detect cross-source inconsistencies.
    ///
    /// Currently catches three types:
    /// - Visually disabled but a11y says enabled (tiny area + "Button" role)
    /// - Not in a11y tree (empty role while having a non-trivial visual footprint)
    /// - Loading state (label contains loading keywords)
    fn detect_inconsistencies(
        visual: &VisualSignal,
        semantic: &SemanticSignal,
    ) -> Vec<Inconsistency> {
        let mut found = Vec::new();

        if Self::looks_disabled_visually(visual) && Self::looks_enabled_semantically(semantic) {
            found.push(Inconsistency::VisuallyDisabledButA11yEnabled);
        }

        if semantic.role.is_empty() && visual.bounds.area() > 100.0 {
            found.push(Inconsistency::NotInA11yTree);
        }

        if Self::label_suggests_loading(&semantic.label) {
            found.push(Inconsistency::LoadingState);
        }

        found
    }

    /// Heuristic: element is visually disabled when it occupies very little area
    /// or is classified as `SizeClass::Small` while being positioned centrally.
    fn looks_disabled_visually(visual: &VisualSignal) -> bool {
        visual.size_class == SizeClass::Small && visual.bounds.area() < 400.0
    }

    /// Heuristic: element is semantically enabled when the role is non-empty.
    fn looks_enabled_semantically(semantic: &SemanticSignal) -> bool {
        !semantic.role.is_empty() && semantic.role.starts_with("AX")
    }

    /// Check if the label contains common loading-state keywords.
    fn label_suggests_loading(label: &str) -> bool {
        let lower = label.to_lowercase();
        ["loading", "please wait", "spinner"]
            .iter()
            .any(|kw| lower.contains(kw))
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

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

    // ── Fixtures ──────────────────────────────────────────────────────────

    fn medium_button_bounds() -> Rect {
        Rect {
            x: 10.0,
            y: 20.0,
            width: 80.0,
            height: 30.0,
        }
    }

    fn visual_medium() -> VisualSignal {
        VisualSignal {
            bounds: medium_button_bounds(),
            relative_position: Position::Center,
            size_class: SizeClass::Medium,
        }
    }

    fn semantic_button(label: &str) -> SemanticSignal {
        SemanticSignal {
            role: "AXButton".into(),
            label: label.into(),
            value: None,
        }
    }

    fn structural_leaf() -> StructuralSignal {
        StructuralSignal {
            depth: 3,
            parent_role: "AXGroup".into(),
            sibling_index: 0,
            child_count: 0,
        }
    }

    // ── Rect ──────────────────────────────────────────────────────────────

    #[test]
    fn rect_center_computes_midpoint() {
        // GIVEN: Rect at (10, 20) with size 80×30
        let r = Rect {
            x: 10.0,
            y: 20.0,
            width: 80.0,
            height: 30.0,
        };
        // WHEN: Computing center
        let (cx, cy) = r.center();
        // THEN: Midpoint is correct
        assert_eq!(cx, 50.0);
        assert_eq!(cy, 35.0);
    }

    #[test]
    fn rect_area_is_width_times_height() {
        let r = Rect {
            x: 0.0,
            y: 0.0,
            width: 50.0,
            height: 40.0,
        };
        assert_eq!(r.area(), 2_000.0);
    }

    // ── SizeClass ─────────────────────────────────────────────────────────

    #[test]
    fn size_class_from_rect_classifies_small_correctly() {
        // GIVEN: 30×30 button (area 900 < 1000)
        let r = Rect {
            x: 0.0,
            y: 0.0,
            width: 30.0,
            height: 30.0,
        };
        assert_eq!(SizeClass::from_rect(&r), SizeClass::Small);
    }

    #[test]
    fn size_class_from_rect_classifies_full_width_correctly() {
        // GIVEN: 1920×1080 screen
        let r = Rect {
            x: 0.0,
            y: 0.0,
            width: 1920.0,
            height: 1080.0,
        };
        assert_eq!(SizeClass::from_rect(&r), SizeClass::FullWidth);
    }

    #[test]
    fn size_class_from_rect_classifies_medium_correctly() {
        // GIVEN: 80×30 button (area 2400)
        let r = Rect {
            x: 0.0,
            y: 0.0,
            width: 80.0,
            height: 30.0,
        };
        assert_eq!(SizeClass::from_rect(&r), SizeClass::Medium);
    }

    // ── VisualSignal confidence ────────────────────────────────────────────

    #[test]
    fn visual_confidence_is_in_unit_range() {
        // GIVEN: Any visual signal
        let v = visual_medium();
        let c = v.confidence();
        // THEN: Confidence in [0, 1]
        assert!((0.0..=1.0).contains(&c));
    }

    #[test]
    fn visual_full_width_has_higher_confidence_than_small() {
        let full = VisualSignal {
            bounds: Rect {
                x: 0.0,
                y: 0.0,
                width: 1920.0,
                height: 1080.0,
            },
            relative_position: Position::Center,
            size_class: SizeClass::FullWidth,
        };
        let small = VisualSignal {
            bounds: Rect {
                x: 0.0,
                y: 0.0,
                width: 10.0,
                height: 10.0,
            },
            relative_position: Position::TopLeft,
            size_class: SizeClass::Small,
        };
        assert!(full.confidence() > small.confidence());
    }

    // ── SemanticSignal confidence ──────────────────────────────────────────

    #[test]
    fn semantic_empty_role_and_label_has_zero_confidence() {
        let s = SemanticSignal {
            role: String::new(),
            label: String::new(),
            value: None,
        };
        assert_eq!(s.confidence(), 0.0);
    }

    #[test]
    fn semantic_with_role_and_label_has_non_zero_confidence() {
        let s = semantic_button("Submit");
        assert!(s.confidence() > 0.0);
    }

    #[test]
    fn semantic_value_bonus_increases_confidence() {
        let without = semantic_button("Submit");
        let with_val = SemanticSignal {
            role: "AXTextField".into(),
            label: "Email".into(),
            value: Some("user@example.com".into()),
        };
        assert!(with_val.confidence() > without.confidence() - 0.15);
    }

    // ── StructuralSignal confidence ────────────────────────────────────────

    #[test]
    fn structural_leaf_at_depth_3_has_reasonable_confidence() {
        let s = structural_leaf();
        let c = s.confidence();
        assert!((0.0..=1.0).contains(&c));
        assert!(c > 0.5); // leaf + moderate depth + known parent
    }

    #[test]
    fn structural_root_has_lower_confidence_than_leaf() {
        let root = StructuralSignal {
            depth: 0,
            parent_role: String::new(),
            sibling_index: 0,
            child_count: 5,
        };
        assert!(structural_leaf().confidence() > root.confidence());
    }

    // ── TripleUnderstanding combined confidence ────────────────────────────

    #[test]
    fn combined_confidence_matches_weighted_average() {
        // GIVEN: Known signals
        let v = visual_medium();
        let s = semantic_button("Submit");
        let st = structural_leaf();

        let expected = VISUAL_WEIGHT * v.confidence()
            + SEMANTIC_WEIGHT * s.confidence()
            + STRUCTURAL_WEIGHT * st.confidence();

        let understanding = TripleUnderstanding::build(v, s, st);

        // THEN: Combined confidence matches formula
        let diff = (understanding.combined_confidence - expected).abs();
        assert!(diff < 1e-10, "diff={diff}");
    }

    #[test]
    fn combined_confidence_is_in_unit_range() {
        let understanding =
            TripleUnderstanding::build(visual_medium(), semantic_button("OK"), structural_leaf());
        assert!((0.0..=1.0).contains(&understanding.combined_confidence));
    }

    // ── Inconsistency detection ────────────────────────────────────────────

    #[test]
    fn no_inconsistencies_for_normal_button() {
        // GIVEN: Normal medium button
        let u = TripleUnderstanding::build(
            visual_medium(),
            semantic_button("Submit"),
            structural_leaf(),
        );
        // THEN: No inconsistencies
        assert!(u.inconsistencies.is_empty());
    }

    #[test]
    fn detects_loading_state_inconsistency() {
        // GIVEN: Button whose label says "Loading…"
        let u = TripleUnderstanding::build(
            visual_medium(),
            SemanticSignal {
                role: "AXButton".into(),
                label: "Loading...".into(),
                value: None,
            },
            structural_leaf(),
        );
        // THEN: Loading-state inconsistency detected
        assert!(u.inconsistencies.contains(&Inconsistency::LoadingState));
    }

    #[test]
    fn detects_not_in_a11y_tree_when_role_empty_but_has_area() {
        // GIVEN: Visible element with no accessibility role
        let u = TripleUnderstanding::build(
            VisualSignal {
                bounds: Rect {
                    x: 0.0,
                    y: 0.0,
                    width: 200.0,
                    height: 50.0,
                },
                relative_position: Position::Center,
                size_class: SizeClass::Medium,
            },
            SemanticSignal {
                role: String::new(),
                label: String::new(),
                value: None,
            },
            structural_leaf(),
        );
        // THEN: NotInA11yTree detected
        assert!(u.inconsistencies.contains(&Inconsistency::NotInA11yTree));
    }

    #[test]
    fn detects_visually_disabled_but_a11y_enabled() {
        // GIVEN: Tiny element (visually collapsed) with valid AX role
        let u = TripleUnderstanding::build(
            VisualSignal {
                bounds: Rect {
                    x: 0.0,
                    y: 0.0,
                    width: 15.0,
                    height: 15.0,
                },
                relative_position: Position::TopLeft,
                size_class: SizeClass::Small,
            },
            SemanticSignal {
                role: "AXButton".into(),
                label: "hidden".into(),
                value: None,
            },
            structural_leaf(),
        );
        // THEN: Visual/a11y disabled mismatch detected
        assert!(u
            .inconsistencies
            .contains(&Inconsistency::VisuallyDisabledButA11yEnabled));
    }
}