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
// spooler.rs — Input Spooler shared memory ring buffer
//
// ForgeWright writes compiled AgentInputFrame sequences into a shared memory
// ring buffer. The game drains exactly one frame per logical tick.
//
// Layout: 64-byte SpoolerHeader + 256 × 32-byte AgentInputFrame = 8256 bytes.
// SpoolerState operates on a raw byte slice for testability (no Windows APIs).
// InputSpooler wraps SpoolerState with actual Windows shared memory mapping.

use std::sync::atomic::{AtomicBool, AtomicU32};

// ─── Constants ───────────────────────────────────────────────────────────────

/// Ring buffer capacity (power of 2 for mask trick).
pub const SPOOLER_CAPACITY: u32 = 256;

/// Bitmask for wrapping indices: index & SPOOLER_MASK = slot.
pub const SPOOLER_MASK: u32 = 255;

/// Total shared memory size: 64-byte header + 256 × 32-byte frames.
pub const SPOOLER_TOTAL_SIZE: usize = 8256;

/// MilliUnit virtual width (640 × 1000).
pub const MILLIUNIT_WIDTH: i32 = 640_000;

/// MilliUnit virtual height (480 × 1000).
pub const MILLIUNIT_HEIGHT: i32 = 480_000;

// ─── Header (64 bytes, cache-line aligned) ───────────────────────────────────

/// Shared memory header at offset 0. 64 bytes, cache-line aligned.
///
/// Atomic ordering contract:
/// - `is_agent_active`: SeqCst (both sides need immediate visibility)
/// - `head_index`: Release on write (writer), Acquire on read (reader)
/// - `tail_index`: Release on write (reader), Acquire on read (writer)
/// - `current_macro_id`: Relaxed (informational only)
#[repr(C, align(64))]
pub struct SpoolerHeader {
    pub is_agent_active: AtomicBool,
    pub _pad0: [u8; 3],
    pub current_macro_id: AtomicU32,
    pub head_index: AtomicU32,
    pub tail_index: AtomicU32,
    pub _reserved: [u8; 48],
}

// ─── AgentInputFrame (32 bytes, Pod + Zeroable) ─────────────────────────────

/// Exact hardware input state for one logical game tick.
/// 32 bytes, no pointers, safe to copy across process boundaries.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct AgentInputFrame {
    pub buttons: u16,
    pub _pad: u16,
    pub left_stick_x: f32,
    pub left_stick_y: f32,
    pub right_stick_x: f32,
    pub right_stick_y: f32,
    pub left_trigger: f32,
    pub right_trigger: f32,
    /// Pad to exactly 32 bytes (28 bytes of data + 4 bytes padding).
    pub _pad_end: u32,
}

impl Default for AgentInputFrame {
    fn default() -> Self {
        Self {
            buttons: 0,
            _pad: 0,
            left_stick_x: 0.0,
            left_stick_y: 0.0,
            right_stick_x: 0.0,
            right_stick_y: 0.0,
            left_trigger: 0.0,
            right_trigger: 0.0,
            _pad_end: 0,
        }
    }
}

// ─── ActuationReport ─────────────────────────────────────────────────────────

/// Game-side report produced when a macro finishes execution.
#[derive(Debug, Clone)]
pub struct ActuationReport {
    pub macro_id: u32,
    pub ticks_executed: u32,
    pub buffer_overflow: bool,
    pub user_override: bool,
    pub override_tick: Option<u32>,
    /// Final position in MilliUnit virtual space (640000×480000).
    pub final_position: (i32, i32),
    pub final_frame: AgentInputFrame,
}

// ─── SpoolerState (testable, operates on raw byte slice) ─────────────────────

/// Testable ring buffer logic operating on a raw byte slice.
/// No Windows shared memory APIs — just pointer arithmetic on a buffer.
pub struct SpoolerState<'a> {
    buf: &'a mut [u8],
}

impl<'a> SpoolerState<'a> {
    /// Wrap a mutable byte slice of exactly SPOOLER_TOTAL_SIZE bytes.
    pub fn new(buf: &'a mut [u8]) -> Self {
        assert_eq!(buf.len(), SPOOLER_TOTAL_SIZE);
        Self { buf }
    }

    /// Zero-initialize the entire buffer.
    pub fn zero_init(&mut self) {
        self.buf.fill(0);
    }

    // ── Header accessors (byte-level reads/writes, no alignment requirement) ──
    //
    // Header layout (64 bytes):
    //   offset 0:  is_agent_active (1 byte, bool)
    //   offset 1:  _pad0 (3 bytes)
    //   offset 4:  current_macro_id (4 bytes, u32 LE)
    //   offset 8:  head_index (4 bytes, u32 LE)
    //   offset 12: tail_index (4 bytes, u32 LE)
    //   offset 16: _reserved (48 bytes)

    fn read_u32_le(&self, offset: usize) -> u32 {
        let bytes: [u8; 4] = self.buf[offset..offset + 4].try_into().unwrap();
        u32::from_le_bytes(bytes)
    }

    fn write_u32_le(&mut self, offset: usize, val: u32) {
        self.buf[offset..offset + 4].copy_from_slice(&val.to_le_bytes());
    }

    pub fn is_agent_active(&self) -> bool {
        self.buf[0] != 0
    }

    pub fn set_agent_active(&mut self, active: bool) {
        self.buf[0] = if active { 1 } else { 0 };
    }

    pub fn current_macro_id(&self) -> u32 {
        self.read_u32_le(4)
    }

    pub fn set_macro_id(&mut self, id: u32) {
        self.write_u32_le(4, id);
    }

    pub fn head_index(&self) -> u32 {
        self.read_u32_le(8)
    }

    pub fn tail_index(&self) -> u32 {
        self.read_u32_le(12)
    }

    fn set_head_index(&mut self, val: u32) {
        self.write_u32_le(8, val);
    }

    fn set_tail_index(&mut self, val: u32) {
        self.write_u32_le(12, val);
    }

    // ── Frame slot access ──

    /// Byte offset of frame slot `index & SPOOLER_MASK` in the buffer.
    fn frame_offset(index: u32) -> usize {
        64 + ((index & SPOOLER_MASK) as usize) * 32
    }

    /// Write a single AgentInputFrame into the slot at `index`.
    fn write_frame_at(&mut self, index: u32, frame: &AgentInputFrame) {
        let off = Self::frame_offset(index);
        let src = unsafe {
            std::slice::from_raw_parts(frame as *const AgentInputFrame as *const u8, 32)
        };
        self.buf[off..off + 32].copy_from_slice(src);
    }

    /// Read a single AgentInputFrame from the slot at `index`.
    fn read_frame_at(&self, index: u32) -> AgentInputFrame {
        let off = Self::frame_offset(index);
        let mut frame = AgentInputFrame::default();
        let dst = unsafe {
            std::slice::from_raw_parts_mut(&mut frame as *mut AgentInputFrame as *mut u8, 32)
        };
        dst.copy_from_slice(&self.buf[off..off + 32]);
        frame
    }

    // ── Writer API (ForgeWright side) ──

    /// Write a compiled macro (sequence of AgentInputFrames) into the ring buffer.
    ///
    /// Atomic batch write: head_index is updated only after all frames are written.
    /// Returns Err if the write would overflow the buffer.
    pub fn write_macro(&mut self, macro_id: u32, frames: &[AgentInputFrame]) -> Result<(), SpoolerError> {
        let head = self.head_index();
        let tail = self.tail_index();

        // Overflow check: would writing these frames exceed capacity?
        let pending = head.wrapping_sub(tail);
        if pending.wrapping_add(frames.len() as u32) > SPOOLER_CAPACITY {
            return Err(SpoolerError::BufferOverflow {
                head,
                tail,
                attempted: frames.len() as u32,
            });
        }

        // Write all frames first (batch write)
        for (i, frame) in frames.iter().enumerate() {
            self.write_frame_at(head.wrapping_add(i as u32), frame);
        }

        // Set macro metadata
        self.set_macro_id(macro_id);
        self.set_agent_active(true);

        // Release fence: update head_index only after all frames are written
        self.set_head_index(head.wrapping_add(frames.len() as u32));

        Ok(())
    }

    // ── Reader API (game side) ──

    /// Drain exactly one AgentInputFrame per logical tick.
    ///
    /// Returns `None` when:
    /// - `is_agent_active` is false (XInput passthrough, zero overhead)
    /// - Buffer is empty (tail_index == head_index)
    ///
    /// `xinput_buttons`: current XInput button bitmask for user override detection.
    /// `tick`: current logical tick number.
    /// `report_builder`: mutable reference to track actuation state.
    pub fn drain_one(
        &mut self,
        xinput_buttons: u16,
        tick: u32,
        report: &mut DrainState,
    ) -> Option<AgentInputFrame> {
        // Fast path: agent not active → XInput passthrough
        if !self.is_agent_active() {
            return None;
        }

        let head = self.head_index();
        let tail = self.tail_index();

        // Check overflow condition
        if head.wrapping_sub(tail) > SPOOLER_CAPACITY {
            report.buffer_overflow = true;
        }

        // User override detection: non-zero XInput while agent is active
        if xinput_buttons != 0 && !report.user_override {
            report.user_override = true;
            report.override_tick = Some(tick);
        }

        // Buffer empty check
        if tail == head {
            return None;
        }

        // Pop one frame
        let frame = self.read_frame_at(tail);
        report.ticks_executed += 1;
        report.last_frame = frame;

        // Advance tail (release ordering for writer visibility)
        self.set_tail_index(tail.wrapping_add(1));

        Some(frame)
    }

    /// Produce an ActuationReport when the macro finishes (buffer drained to empty).
    pub fn finish_macro(&self, state: &DrainState, position: (i32, i32)) -> ActuationReport {
        // Clamp position to MilliUnit bounds
        let clamped_x = position.0.clamp(0, MILLIUNIT_WIDTH);
        let clamped_y = position.1.clamp(0, MILLIUNIT_HEIGHT);

        ActuationReport {
            macro_id: self.current_macro_id(),
            ticks_executed: state.ticks_executed,
            buffer_overflow: state.buffer_overflow,
            user_override: state.user_override,
            override_tick: state.override_tick,
            final_position: (clamped_x, clamped_y),
            final_frame: state.last_frame,
        }
    }
}

/// Mutable state accumulated during drain operations for a single macro.
#[derive(Debug, Clone)]
pub struct DrainState {
    pub ticks_executed: u32,
    pub buffer_overflow: bool,
    pub user_override: bool,
    pub override_tick: Option<u32>,
    pub last_frame: AgentInputFrame,
}

impl Default for DrainState {
    fn default() -> Self {
        Self {
            ticks_executed: 0,
            buffer_overflow: false,
            user_override: false,
            override_tick: None,
            last_frame: AgentInputFrame::default(),
        }
    }
}

/// Errors from spooler operations.
#[derive(Debug)]
pub enum SpoolerError {
    BufferOverflow {
        head: u32,
        tail: u32,
        attempted: u32,
    },
    #[cfg(target_os = "windows")]
    WindowsError(String),
}

impl std::fmt::Display for SpoolerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SpoolerError::BufferOverflow { head, tail, attempted } => {
                write!(
                    f,
                    "spooler overflow: head={}, tail={}, pending={}, attempted={}",
                    head,
                    tail,
                    head.wrapping_sub(*tail),
                    attempted
                )
            }
            #[cfg(target_os = "windows")]
            SpoolerError::WindowsError(msg) => write!(f, "windows error: {}", msg),
        }
    }
}

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

// ─── InputSpooler (Windows shared memory wrapper) ────────────────────────────

#[cfg(target_os = "windows")]
pub mod shared_mem {
    use super::*;
    use windows::core::PCWSTR;
    use windows::Win32::Foundation::{CloseHandle, HANDLE};
    use windows::Win32::System::Memory::{
        CreateFileMappingW, MapViewOfFile, OpenFileMappingW, UnmapViewOfFile,
        FILE_MAP_ALL_ACCESS, FILE_MAP_READ, PAGE_READWRITE,
    };

    const SPOOLER_NAME: &str = "Local\\ForgeSpooler";

    fn wide_name() -> Vec<u16> {
        SPOOLER_NAME.encode_utf16().chain(std::iter::once(0)).collect()
    }

    /// Writer-side spooler: creates the shared memory region.
    pub struct InputSpooler {
        handle: HANDLE,
        ptr: *mut u8,
    }

    // SAFETY: The shared memory region is process-local mapping.
    // Access is synchronized via atomics in SpoolerHeader.
    unsafe impl Send for InputSpooler {}

    impl InputSpooler {
        /// Create the shared memory region (writer side).
        pub fn create() -> Result<Self, SpoolerError> {
            let name = wide_name();
            unsafe {
                let handle = CreateFileMappingW(
                    HANDLE(-1isize as _), // INVALID_HANDLE_VALUE → page file backed
                    None,
                    PAGE_READWRITE,
                    0,
                    SPOOLER_TOTAL_SIZE as u32,
                    PCWSTR(name.as_ptr()),
                )
                .map_err(|e| SpoolerError::WindowsError(format!("CreateFileMappingW: {}", e)))?;

                let ptr = MapViewOfFile(handle, FILE_MAP_ALL_ACCESS, 0, 0, SPOOLER_TOTAL_SIZE)
                    .Value as *mut u8;

                if ptr.is_null() {
                    CloseHandle(handle).ok();
                    return Err(SpoolerError::WindowsError(
                        "MapViewOfFile returned null".into(),
                    ));
                }

                // Zero-init the region
                std::ptr::write_bytes(ptr, 0, SPOOLER_TOTAL_SIZE);

                Ok(Self { handle, ptr })
            }
        }

        /// Open existing shared memory region (game side).
        pub fn open() -> Result<Self, SpoolerError> {
            let name = wide_name();
            unsafe {
                let handle = OpenFileMappingW(FILE_MAP_READ.0 | FILE_MAP_ALL_ACCESS.0, false, PCWSTR(name.as_ptr()))
                    .map_err(|e| SpoolerError::WindowsError(format!("OpenFileMappingW: {}", e)))?;

                let ptr = MapViewOfFile(handle, FILE_MAP_ALL_ACCESS, 0, 0, SPOOLER_TOTAL_SIZE)
                    .Value as *mut u8;

                if ptr.is_null() {
                    CloseHandle(handle).ok();
                    return Err(SpoolerError::WindowsError(
                        "MapViewOfFile returned null".into(),
                    ));
                }

                Ok(Self { handle, ptr })
            }
        }

        /// Get a SpoolerState view over the shared memory.
        pub fn state(&mut self) -> SpoolerState<'_> {
            let slice = unsafe { std::slice::from_raw_parts_mut(self.ptr, SPOOLER_TOTAL_SIZE) };
            SpoolerState::new(slice)
        }
    }

    impl Drop for InputSpooler {
        fn drop(&mut self) {
            unsafe {
                let view = windows::Win32::System::Memory::MEMORY_MAPPED_VIEW_ADDRESS {
                    Value: self.ptr as *mut _,
                };
                UnmapViewOfFile(view).ok();
                CloseHandle(self.handle).ok();
            }
        }
    }
}

// ─── Compile-time assertions ─────────────────────────────────────────────────

const _: () = {
    assert!(std::mem::size_of::<SpoolerHeader>() == 64);
    assert!(std::mem::align_of::<SpoolerHeader>() == 64);
    assert!(std::mem::size_of::<AgentInputFrame>() == 32);
    assert!(SPOOLER_TOTAL_SIZE == 64 + (SPOOLER_CAPACITY as usize) * 32);
};

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

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

    /// Helper: create a zeroed buffer and SpoolerState for testing.
    fn test_spooler() -> Vec<u8> {
        vec![0u8; SPOOLER_TOTAL_SIZE]
    }

    /// Strategy for generating arbitrary AgentInputFrames.
    fn arb_agent_frame() -> impl Strategy<Value = AgentInputFrame> {
        (
            any::<u16>(),                    // buttons
            -1.0f32..=1.0f32,               // left_stick_x
            -1.0f32..=1.0f32,               // left_stick_y
            -1.0f32..=1.0f32,               // right_stick_x
            -1.0f32..=1.0f32,               // right_stick_y
            0.0f32..=1.0f32,                // left_trigger
            0.0f32..=1.0f32,                // right_trigger
        )
            .prop_map(|(buttons, lsx, lsy, rsx, rsy, lt, rt)| AgentInputFrame {
                buttons,
                _pad: 0,
                left_stick_x: lsx,
                left_stick_y: lsy,
                right_stick_x: rsx,
                right_stick_y: rsy,
                left_trigger: lt,
                right_trigger: rt,
                _pad_end: 0,
            })
    }

    // ── Property 20: Tick-drain determinism ──
    // **Validates: Requirement 8.2**
    //
    // Write N AgentInputFrames, drain exactly N times, verify N valid frames
    // returned and (N+1)th drain returns None.
    proptest! {
        #[test]
        fn prop20_tick_drain_determinism(
            frames in proptest::collection::vec(arb_agent_frame(), 1..=256)
        ) {
            let mut buf = test_spooler();
            let mut spooler = SpoolerState::new(&mut buf);
            spooler.zero_init();

            let n = frames.len();

            // Write all frames as a macro
            spooler.write_macro(42, &frames).unwrap();

            // Drain exactly N times — each should return Some
            let mut drain_state = DrainState::default();
            let mut drained = Vec::new();
            for tick in 0..n as u32 {
                let frame = spooler.drain_one(0, tick, &mut drain_state);
                prop_assert!(frame.is_some(), "drain {} of {} returned None", tick, n);
                drained.push(frame.unwrap());
            }

            // Verify we got exactly N frames
            prop_assert_eq!(drained.len(), n);

            // Verify frame content matches what was written
            for (i, (got, expected)) in drained.iter().zip(frames.iter()).enumerate() {
                prop_assert_eq!(got, expected, "frame {} mismatch", i);
            }

            // (N+1)th drain should return None (buffer empty)
            let extra = spooler.drain_one(0, n as u32, &mut drain_state);
            prop_assert!(extra.is_none(), "(N+1)th drain should be None");
        }
    }

    // ── Property 21: Agent inactive passthrough ──
    // **Validates: Requirement 8.3**
    //
    // Set is_agent_active = false, verify drain_spooler returns None
    // regardless of ring buffer contents.
    proptest! {
        #[test]
        fn prop21_agent_inactive_passthrough(
            frames in proptest::collection::vec(arb_agent_frame(), 1..=128)
        ) {
            let mut buf = test_spooler();
            let mut spooler = SpoolerState::new(&mut buf);
            spooler.zero_init();

            // Write frames into the buffer (this sets is_agent_active = true)
            spooler.write_macro(1, &frames).unwrap();

            // Now deactivate the agent
            spooler.set_agent_active(false);

            // Drain should return None even though buffer has data
            let mut drain_state = DrainState::default();
            for tick in 0..frames.len() as u32 {
                let result = spooler.drain_one(0, tick, &mut drain_state);
                prop_assert!(result.is_none(),
                    "drain at tick {} should be None when agent inactive", tick);
            }
        }
    }

    // ── Property 22: Buffer overflow detection ──
    // **Validates: Requirement 8.5**
    //
    // Set head_index - tail_index > SPOOLER_CAPACITY, verify overflow
    // is detected and reported.
    proptest! {
        #[test]
        fn prop22_buffer_overflow_detection(
            overflow_amount in 1u32..=100u32
        ) {
            let mut buf = test_spooler();
            let mut spooler = SpoolerState::new(&mut buf);
            spooler.zero_init();

            // Manually set head far ahead of tail to simulate overflow
            let tail = 10u32;
            let head = tail + SPOOLER_CAPACITY + overflow_amount;
            spooler.set_tail_index(tail);
            spooler.set_head_index(head);
            spooler.set_agent_active(true);

            // Drain should detect overflow
            let mut drain_state = DrainState::default();
            let _ = spooler.drain_one(0, 0, &mut drain_state);

            prop_assert!(drain_state.buffer_overflow,
                "overflow not detected: head={}, tail={}, diff={}",
                head, tail, head.wrapping_sub(tail));
        }
    }

    // ── Property 23: User override detection ──
    // **Validates: Requirement 8.6**
    //
    // Simulate non-zero XInput button bitmask while is_agent_active = true,
    // verify ActuationReport sets user_override = true with correct override_tick.
    proptest! {
        #[test]
        fn prop23_user_override_detection(
            frames in proptest::collection::vec(arb_agent_frame(), 1..=64),
            override_tick in 0u32..64u32,
            xinput_buttons in 1u16..=u16::MAX,
        ) {
            let mut buf = test_spooler();
            let mut spooler = SpoolerState::new(&mut buf);
            spooler.zero_init();

            let n = frames.len() as u32;
            // Clamp override_tick to valid range
            let override_tick = override_tick % n;

            spooler.write_macro(99, &frames).unwrap();

            let mut drain_state = DrainState::default();
            for tick in 0..n {
                let buttons = if tick == override_tick { xinput_buttons } else { 0 };
                let _ = spooler.drain_one(buttons, tick, &mut drain_state);
            }

            prop_assert!(drain_state.user_override,
                "user override not detected at tick {}", override_tick);
            prop_assert_eq!(drain_state.override_tick, Some(override_tick),
                "override_tick mismatch");
        }
    }

    // ── Property 28: MilliUnit position bounds ──
    // **Validates: Requirement 10.4**
    //
    // For any ActuationReport final_position, verify
    // 0 <= x <= 640000 and 0 <= y <= 480000.
    proptest! {
        #[test]
        fn prop28_milliunit_position_bounds(
            x in proptest::num::i32::ANY,
            y in proptest::num::i32::ANY,
        ) {
            let mut buf = test_spooler();
            let mut spooler = SpoolerState::new(&mut buf);
            spooler.zero_init();

            // Write a single frame so we have a valid macro
            let frame = AgentInputFrame::default();
            spooler.write_macro(1, &[frame]).unwrap();

            let drain_state = DrainState::default();
            let report = spooler.finish_macro(&drain_state, (x, y));

            let (rx, ry) = report.final_position;
            prop_assert!(rx >= 0 && rx <= MILLIUNIT_WIDTH,
                "x={} out of bounds [0, {}]", rx, MILLIUNIT_WIDTH);
            prop_assert!(ry >= 0 && ry <= MILLIUNIT_HEIGHT,
                "y={} out of bounds [0, {}]", ry, MILLIUNIT_HEIGHT);
        }
    }
}