forgewright 0.2.0

Standalone UI automation — CDP for browsers, UIA for Windows desktop apps
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
//! Visual Gate Report orchestrator — capture → compress → input → assess → JSON.
//!
//! This is the main entry point for the `visual-gate` CLI action.
//! Sequences burst capture, VisionBridge compression, input state reading,
//! and pass/fail assessment into a structured GateReport JSON.

use std::error::Error;
use std::path::Path;

use serde::{Deserialize, Serialize};

use crate::bridge::VisionBridge;
use crate::burst::{self, BurstConfig, BurstFormat};
use crate::input::{self, InputState};

// ═══ TYPES ═══════════════════════════════════════════════════════════════════

/// Configuration for a visual gate run.
pub struct GateConfig {
    pub burst: BurstConfig,
    pub tile_size: u32,
    /// Optional: expected state for pass/fail assessment.
    pub expectations: Option<GateExpectations>,
}

/// What the agent expects to see (for automated pass/fail).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GateExpectations {
    /// Maximum allowed changed tiles (e.g., 0 for "screen should be static").
    pub max_changed_tiles: Option<u32>,
    /// Expected mouse position region.
    pub mouse_region: Option<Rect>,
    /// Gamepad must be connected.
    pub gamepad_required: bool,
}

/// A rectangle for mouse region containment checks.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Rect {
    pub x: i32,
    pub y: i32,
    pub width: i32,
    pub height: i32,
}

impl Rect {
    /// Check if a point (px, py) is inside this rectangle.
    /// Uses half-open interval: x <= px < x+width, y <= py < y+height.
    pub fn contains(&self, px: i32, py: i32) -> bool {
        px >= self.x
            && px < self.x + self.width
            && py >= self.y
            && py < self.y + self.height
    }
}

/// The structured JSON report output by the visual gate.
#[derive(Debug, Serialize)]
pub struct GateReport {
    pub status: String,
    pub timestamp: String,
    pub screenshot_path: String,
    pub capture_backend: String,
    pub resolution: (u32, u32),
    pub compressed_frame: CompressedFrameJson,
    pub input_state: InputState,
    pub assessment: Assessment,
    /// For burst captures: per-frame compressed data.
    pub burst_frames: Option<Vec<CompressedFrameJson>>,
    pub gif_path: Option<String>,
}

/// JSON-friendly compressed frame representation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompressedFrameJson {
    pub total_tiles: u32,
    pub changed_tiles: u32,
    pub change_ratio: f32,
    pub tiles: Vec<TileJson>,
}

/// JSON-friendly tile descriptor.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TileJson {
    pub col: u16,
    pub row: u16,
    pub mean_color: [u8; 4],
    pub edge_density: f32,
    pub likely_text: bool,
}

/// Pass/fail assessment with reasons.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Assessment {
    pub pass: bool,
    pub reasons: Vec<String>,
}

// ═══ VIRTUAL RESOLUTION MAPPING ══════════════════════════════════════════════

/// Virtual resolution width.
pub const VIRTUAL_WIDTH: i32 = 640;
/// Virtual resolution height.
pub const VIRTUAL_HEIGHT: i32 = 480;

/// Map mouse coordinates from window-space to virtual resolution (640×480).
///
/// `virtual_x = mouse_x * 640 / window_width`
/// `virtual_y = mouse_y * 480 / window_height`
///
/// Returns (0, 0) if window dimensions are zero (avoids division by zero).
pub fn map_to_virtual(
    mouse_x: i32,
    mouse_y: i32,
    window_width: i32,
    window_height: i32,
) -> (i32, i32) {
    if window_width <= 0 || window_height <= 0 {
        return (0, 0);
    }
    let vx = mouse_x * VIRTUAL_WIDTH / window_width;
    let vy = mouse_y * VIRTUAL_HEIGHT / window_height;
    (vx, vy)
}

// ═══ ASSESSMENT LOGIC ════════════════════════════════════════════════════════

/// Assess a gate result against optional expectations.
///
/// - No expectations → informational mode (pass = true, descriptive reasons).
/// - max_changed_tiles: pass &= changed_tiles <= threshold.
/// - mouse_region: pass &= region.contains(mouse_x, mouse_y).
/// - gamepad_required: pass &= gamepad.is_some().
pub fn assess(
    compressed: &CompressedFrameJson,
    input_state: &InputState,
    expectations: &Option<GateExpectations>,
) -> Assessment {
    match expectations {
        None => {
            // Informational mode
            let mut reasons = Vec::new();
            reasons.push(format!(
                "{} changed tiles out of {} total (ratio: {:.4})",
                compressed.changed_tiles, compressed.total_tiles, compressed.change_ratio
            ));
            reasons.push(format!(
                "mouse at ({}, {})",
                input_state.mouse.x, input_state.mouse.y
            ));
            if let Some(ref gp) = input_state.gamepad {
                reasons.push(format!("gamepad connected (buttons: {})", gp.buttons));
            } else {
                reasons.push("no gamepad connected".to_string());
            }
            Assessment {
                pass: true,
                reasons,
            }
        }
        Some(exp) => {
            let mut pass = true;
            let mut reasons = Vec::new();

            // Check max_changed_tiles threshold
            if let Some(threshold) = exp.max_changed_tiles {
                let tile_pass = compressed.changed_tiles <= threshold;
                if !tile_pass {
                    pass = false;
                    reasons.push(format!(
                        "FAIL: {} changed tiles exceeds threshold {}",
                        compressed.changed_tiles, threshold
                    ));
                } else {
                    reasons.push(format!(
                        "{} changed tiles within threshold {}",
                        compressed.changed_tiles, threshold
                    ));
                }
            }

            // Check mouse region containment
            if let Some(ref region) = exp.mouse_region {
                let mouse_in = region.contains(input_state.mouse.x, input_state.mouse.y);
                if !mouse_in {
                    pass = false;
                    reasons.push(format!(
                        "FAIL: mouse ({}, {}) outside region ({}, {}, {}x{})",
                        input_state.mouse.x,
                        input_state.mouse.y,
                        region.x,
                        region.y,
                        region.width,
                        region.height
                    ));
                } else {
                    reasons.push("mouse in expected region".to_string());
                }
            }

            // Check gamepad requirement
            if exp.gamepad_required {
                let gp_ok = input_state.gamepad.is_some();
                if !gp_ok {
                    pass = false;
                    reasons.push("FAIL: gamepad required but not connected".to_string());
                } else {
                    reasons.push("gamepad connected".to_string());
                }
            }

            Assessment { pass, reasons }
        }
    }
}

// ═══ CONVERSION HELPERS ══════════════════════════════════════════════════════

/// Convert an inlined CompressedFrame into our JSON-friendly representation.
fn compressed_to_json(cf: &crate::inlined_types::CompressedFrame) -> CompressedFrameJson {
    let total = cf.total_tiles;
    let changed = cf.changed_tiles;
    let change_ratio = if total > 0 {
        changed as f32 / total as f32
    } else {
        0.0
    };
    let tiles = cf
        .tiles
        .iter()
        .map(|t: &crate::inlined_types::TileDescriptor| TileJson {
            col: t.col,
            row: t.row,
            mean_color: t.mean_color,
            edge_density: t.edge_density,
            likely_text: t.likely_text,
        })
        .collect();
    CompressedFrameJson {
        total_tiles: total,
        changed_tiles: changed,
        change_ratio,
        tiles,
    }
}

// ═══ RUN GATE ════════════════════════════════════════════════════════════════

/// Run the visual gate and produce a structured report.
///
/// Orchestrates: burst capture → compress each frame via VisionBridge →
/// read input state → assess against expectations → produce GateReport JSON.
///
/// The VisionBridge maintains delta state across iterative capture loop runs
/// when the same bridge instance is reused.
pub fn run_gate(config: GateConfig) -> Result<GateReport, Box<dyn Error>> {
    run_gate_with_bridge(config, &mut None)
}

/// Run the visual gate with an optional pre-existing VisionBridge for delta tracking.
///
/// Pass `bridge_state = &mut Some(bridge)` to maintain delta state across runs.
/// Pass `bridge_state = &mut None` to create a fresh bridge.
pub fn run_gate_with_bridge(
    config: GateConfig,
    bridge_state: &mut Option<VisionBridge>,
) -> Result<GateReport, Box<dyn Error>> {
    // Step 1: Burst capture
    let burst_result = burst::capture_burst(&config.burst)?;

    // Ensure we have at least one frame
    if burst_result.frame_paths.is_empty() {
        return Err("gate: no frames captured".into());
    }

    // Step 2: Initialize or reuse VisionBridge
    let bridge = bridge_state.get_or_insert_with(|| VisionBridge::new(config.tile_size));

    // Step 3: Compress each frame via VisionBridge
    let mut compressed_frames: Vec<CompressedFrameJson> = Vec::new();
    for frame_path in &burst_result.frame_paths {
        let cf = bridge.compress_bmp(frame_path)?;
        compressed_frames.push(compressed_to_json(&cf));
    }

    // Primary compressed frame is the last one (most recent state)
    let primary_frame = compressed_frames.last().cloned().unwrap();

    // Step 4: Read input state
    let input_state = input::read_input_state();

    // Step 5: Verify screenshot_path exists on disk
    let screenshot_path = burst_result
        .frame_paths
        .last()
        .map(|p| p.to_string_lossy().to_string())
        .unwrap_or_default();

    if !screenshot_path.is_empty() && !Path::new(&screenshot_path).exists() {
        return Err(format!("gate: screenshot_path does not exist: {}", screenshot_path).into());
    }

    // Step 6: Determine capture backend
    let capture_backend = "dxgi".to_string(); // DXGI preferred, GDI fallback handled in burst

    // Step 7: Determine resolution (from tile grid or default virtual resolution)
    let resolution = (VIRTUAL_WIDTH as u32, VIRTUAL_HEIGHT as u32);

    // Step 8: Assess against expectations
    let assessment = assess(&primary_frame, &input_state, &config.expectations);

    // Step 9: Build burst_frames and gif_path
    let (burst_frames, gif_path) = if burst_result.frame_count > 1 {
        let gif = if config.burst.output_format == BurstFormat::Gif {
            let gif_candidate = burst_result.output_path.to_string_lossy().to_string();
            if gif_candidate.ends_with(".gif") && Path::new(&gif_candidate).exists() {
                Some(gif_candidate)
            } else {
                None
            }
        } else {
            None
        };
        (Some(compressed_frames), gif)
    } else {
        (None, None)
    };

    Ok(GateReport {
        status: "ok".to_string(),
        timestamp: burst_result.timestamp,
        screenshot_path,
        capture_backend,
        resolution,
        compressed_frame: primary_frame,
        input_state,
        assessment,
        burst_frames,
        gif_path,
    })
}

// ═══ TESTABLE GATE (for property tests without real capture) ═════════════════

/// Build a GateReport from pre-built data (no actual capture).
/// Used for property testing the assessment and structural logic.
pub fn build_gate_report(
    compressed_frame: CompressedFrameJson,
    input_state: InputState,
    expectations: &Option<GateExpectations>,
    burst_frames: Option<Vec<CompressedFrameJson>>,
    gif_path: Option<String>,
) -> GateReport {
    let assessment = assess(&compressed_frame, &input_state, expectations);
    GateReport {
        status: "ok".to_string(),
        timestamp: "20260426_143022".to_string(),
        screenshot_path: "test_screenshot.bmp".to_string(),
        capture_backend: "test".to_string(),
        resolution: (VIRTUAL_WIDTH as u32, VIRTUAL_HEIGHT as u32),
        compressed_frame,
        input_state,
        assessment,
        burst_frames,
        gif_path,
    }
}

// ═══ TESTS ═══════════════════════════════════════════════════════════════════

#[cfg(test)]
mod tests {
    use super::*;
    use crate::input::{GamepadState, MouseState};
    use proptest::prelude::*;

    // ── Helpers ──────────────────────────────────────────────────────────

    /// Create a synthetic CompressedFrameJson for testing.
    fn make_compressed(total_tiles: u32, changed_tiles: u32) -> CompressedFrameJson {
        let change_ratio = if total_tiles > 0 {
            changed_tiles as f32 / total_tiles as f32
        } else {
            0.0
        };
        let tiles: Vec<TileJson> = (0..changed_tiles)
            .map(|i| TileJson {
                col: i as u16,
                row: 0,
                mean_color: [128, 128, 128, 255],
                edge_density: 0.1,
                likely_text: true,
            })
            .collect();
        CompressedFrameJson {
            total_tiles,
            changed_tiles,
            change_ratio,
            tiles,
        }
    }

    /// Create a synthetic InputState for testing.
    fn make_input(mx: i32, my: i32, has_gamepad: bool) -> InputState {
        InputState {
            mouse: MouseState {
                x: mx,
                y: my,
                screen_width: 1920,
                screen_height: 1080,
            },
            gamepad: if has_gamepad {
                Some(GamepadState {
                    connected: true,
                    left_stick: (0.0, 0.0),
                    right_stick: (0.0, 0.0),
                    left_trigger: 0.0,
                    right_trigger: 0.0,
                    buttons: 0,
                })
            } else {
                None
            },
        }
    }

    // ── Unit tests ──────────────────────────────────────────────────────

    #[test]
    fn rect_contains_inside() {
        let r = Rect { x: 10, y: 20, width: 100, height: 50 };
        assert!(r.contains(10, 20));
        assert!(r.contains(50, 40));
        assert!(r.contains(109, 69));
    }

    #[test]
    fn rect_contains_outside() {
        let r = Rect { x: 10, y: 20, width: 100, height: 50 };
        assert!(!r.contains(9, 20));
        assert!(!r.contains(10, 19));
        assert!(!r.contains(110, 20));
        assert!(!r.contains(10, 70));
    }

    #[test]
    fn assess_no_expectations_is_informational() {
        let cf = make_compressed(100, 5);
        let input = make_input(100, 200, false);
        let a = assess(&cf, &input, &None);
        assert!(a.pass);
        assert!(!a.reasons.is_empty());
    }

    #[test]
    fn assess_threshold_pass() {
        let cf = make_compressed(100, 5);
        let input = make_input(100, 200, false);
        let exp = Some(GateExpectations {
            max_changed_tiles: Some(10),
            mouse_region: None,
            gamepad_required: false,
        });
        let a = assess(&cf, &input, &exp);
        assert!(a.pass);
    }

    #[test]
    fn assess_threshold_fail() {
        let cf = make_compressed(100, 15);
        let input = make_input(100, 200, false);
        let exp = Some(GateExpectations {
            max_changed_tiles: Some(10),
            mouse_region: None,
            gamepad_required: false,
        });
        let a = assess(&cf, &input, &exp);
        assert!(!a.pass);
    }

    #[test]
    fn assess_mouse_region_pass() {
        let cf = make_compressed(100, 0);
        let input = make_input(50, 50, false);
        let exp = Some(GateExpectations {
            max_changed_tiles: None,
            mouse_region: Some(Rect { x: 0, y: 0, width: 100, height: 100 }),
            gamepad_required: false,
        });
        let a = assess(&cf, &input, &exp);
        assert!(a.pass);
    }

    #[test]
    fn assess_mouse_region_fail() {
        let cf = make_compressed(100, 0);
        let input = make_input(150, 50, false);
        let exp = Some(GateExpectations {
            max_changed_tiles: None,
            mouse_region: Some(Rect { x: 0, y: 0, width: 100, height: 100 }),
            gamepad_required: false,
        });
        let a = assess(&cf, &input, &exp);
        assert!(!a.pass);
    }

    #[test]
    fn assess_gamepad_required_fail() {
        let cf = make_compressed(100, 0);
        let input = make_input(50, 50, false);
        let exp = Some(GateExpectations {
            max_changed_tiles: None,
            mouse_region: None,
            gamepad_required: true,
        });
        let a = assess(&cf, &input, &exp);
        assert!(!a.pass);
    }

    #[test]
    fn assess_gamepad_required_pass() {
        let cf = make_compressed(100, 0);
        let input = make_input(50, 50, true);
        let exp = Some(GateExpectations {
            max_changed_tiles: None,
            mouse_region: None,
            gamepad_required: true,
        });
        let a = assess(&cf, &input, &exp);
        assert!(a.pass);
    }

    #[test]
    fn virtual_mapping_basic() {
        let (vx, vy) = map_to_virtual(960, 540, 1920, 1080);
        assert_eq!(vx, 320);
        assert_eq!(vy, 240);
    }

    #[test]
    fn virtual_mapping_zero_window() {
        let (vx, vy) = map_to_virtual(100, 100, 0, 0);
        assert_eq!(vx, 0);
        assert_eq!(vy, 0);
    }

    #[test]
    fn build_gate_report_structural() {
        let cf = make_compressed(100, 5);
        let input = make_input(100, 200, true);
        let report = build_gate_report(cf, input, &None, None, None);
        assert_eq!(report.status, "ok");
        assert!(!report.timestamp.is_empty());
        assert!(!report.screenshot_path.is_empty());
        assert!(!report.capture_backend.is_empty());
        assert!(report.resolution.0 > 0);
        assert!(report.resolution.1 > 0);
        assert!(report.compressed_frame.total_tiles > 0);
        assert!(report.assessment.pass);
    }

    // ── Property 16: Assessment threshold logic ─────────────────────────

    /// **Property 16: Assessment threshold logic**
    ///
    /// For any max_changed_tiles = T and changed_tiles = C,
    /// verify `assessment.pass == (C <= T)`.
    ///
    /// **Validates: Requirement 7.4**
    mod prop_threshold {
        use super::*;

        proptest! {
            #[test]
            fn assessment_threshold_logic(
                threshold in 0u32..=1000,
                changed in 0u32..=1000,
                total in 1u32..=10000,
            ) {
                // Ensure total >= changed for a valid frame
                let total = total.max(changed);
                let cf = make_compressed(total, changed);
                let input = make_input(0, 0, false);
                let exp = Some(GateExpectations {
                    max_changed_tiles: Some(threshold),
                    mouse_region: None,
                    gamepad_required: false,
                });
                let a = assess(&cf, &input, &exp);
                prop_assert_eq!(
                    a.pass,
                    changed <= threshold,
                    "changed={}, threshold={}, pass={}",
                    changed, threshold, a.pass
                );
            }
        }
    }

    // ── Property 17: Assessment mouse region logic ──────────────────────

    /// **Property 17: Assessment mouse region logic**
    ///
    /// For any mouse_region R and position (x, y),
    /// verify `assessment.pass == R.contains(x, y)`.
    ///
    /// **Validates: Requirement 7.5**
    mod prop_mouse_region {
        use super::*;

        proptest! {
            #[test]
            fn assessment_mouse_region_logic(
                rx in -500i32..=500,
                ry in -500i32..=500,
                rw in 1i32..=1000,
                rh in 1i32..=1000,
                mx in -1000i32..=1000,
                my in -1000i32..=1000,
            ) {
                let region = Rect { x: rx, y: ry, width: rw, height: rh };
                let cf = make_compressed(100, 0);
                let input = make_input(mx, my, false);
                let exp = Some(GateExpectations {
                    max_changed_tiles: None,
                    mouse_region: Some(region.clone()),
                    gamepad_required: false,
                });
                let a = assess(&cf, &input, &exp);
                let expected = region.contains(mx, my);
                prop_assert_eq!(
                    a.pass,
                    expected,
                    "region=({},{},{}x{}), mouse=({},{}), contains={}, pass={}",
                    rx, ry, rw, rh, mx, my, expected, a.pass
                );
            }
        }
    }

    // ── Property 18: GateReport structural completeness ─────────────────

    /// **Property 18: GateReport structural completeness**
    ///
    /// For any successful gate run, verify GateReport contains non-empty status,
    /// timestamp, screenshot_path, capture_backend, resolution with two positive
    /// values, compressed_frame with total_tiles > 0, and valid mouse coordinates.
    ///
    /// **Validates: Requirement 7.2**
    mod prop_structural {
        use super::*;

        proptest! {
            #[test]
            fn gate_report_structural_completeness(
                total_tiles in 1u32..=10000,
                changed_tiles in 0u32..=1000,
                mx in -2000i32..=2000,
                my in -2000i32..=2000,
                has_gamepad in proptest::bool::ANY,
            ) {
                let changed = changed_tiles.min(total_tiles);
                let cf = make_compressed(total_tiles, changed);
                let input = make_input(mx, my, has_gamepad);
                let report = build_gate_report(cf, input, &None, None, None);

                prop_assert!(!report.status.is_empty(), "status should be non-empty");
                prop_assert!(!report.timestamp.is_empty(), "timestamp should be non-empty");
                prop_assert!(!report.screenshot_path.is_empty(), "screenshot_path should be non-empty");
                prop_assert!(!report.capture_backend.is_empty(), "capture_backend should be non-empty");
                prop_assert!(report.resolution.0 > 0, "resolution width should be positive");
                prop_assert!(report.resolution.1 > 0, "resolution height should be positive");
                prop_assert!(
                    report.compressed_frame.total_tiles > 0,
                    "compressed_frame.total_tiles should be > 0"
                );
                // Mouse coordinates are valid (any i32 is valid for mouse position)
                // Just verify the struct is populated
                let _ = report.input_state.mouse.x;
                let _ = report.input_state.mouse.y;
            }
        }
    }

    // ── Property 19: Burst GateReport frame count ───────────────────────

    /// **Property 19: Burst GateReport frame count**
    ///
    /// For any burst gate run with N frames, verify burst_frames array
    /// has exactly N entries.
    ///
    /// **Validates: Requirement 7.9**
    mod prop_burst_count {
        use super::*;

        proptest! {
            #[test]
            fn burst_gate_report_frame_count(
                n_frames in 2u32..=20,
                total_tiles in 1u32..=1000,
            ) {
                let frames: Vec<CompressedFrameJson> = (0..n_frames)
                    .map(|i| make_compressed(total_tiles, i.min(total_tiles)))
                    .collect();
                let primary = frames.last().cloned().unwrap();
                let input = make_input(100, 200, false);
                let report = build_gate_report(
                    primary,
                    input,
                    &None,
                    Some(frames.clone()),
                    None,
                );

                let burst = report.burst_frames.expect("burst_frames should be Some");
                prop_assert_eq!(
                    burst.len() as u32,
                    n_frames,
                    "burst_frames should have exactly {} entries, got {}",
                    n_frames,
                    burst.len()
                );
            }
        }
    }

    // ── Property 27: Virtual coordinate mapping ─────────────────────────

    /// **Property 27: Virtual coordinate mapping**
    ///
    /// For any positive mouse_x, mouse_y, window_width, window_height,
    /// verify `virtual_x = mouse_x * 640 / window_width` and
    /// `virtual_y = mouse_y * 480 / window_height`.
    ///
    /// **Validates: Requirement 10.2**
    mod prop_virtual_coords {
        use super::*;

        proptest! {
            #[test]
            fn virtual_coordinate_mapping(
                mouse_x in 1i32..=10000,
                mouse_y in 1i32..=10000,
                window_width in 1i32..=10000,
                window_height in 1i32..=10000,
            ) {
                let (vx, vy) = map_to_virtual(mouse_x, mouse_y, window_width, window_height);
                let expected_vx = mouse_x * 640 / window_width;
                let expected_vy = mouse_y * 480 / window_height;
                prop_assert_eq!(
                    vx, expected_vx,
                    "virtual_x: mouse_x={}, window_width={}, got={}, expected={}",
                    mouse_x, window_width, vx, expected_vx
                );
                prop_assert_eq!(
                    vy, expected_vy,
                    "virtual_y: mouse_y={}, window_height={}, got={}, expected={}",
                    mouse_y, window_height, vy, expected_vy
                );
            }
        }
    }
}