aprender-test-lib 0.37.0

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

use crate::event::InputEvent;
use crate::result::{ProbarError, ProbarResult};
use serde::{Deserialize, Serialize};
use std::collections::{hash_map::DefaultHasher, VecDeque};
use std::hash::{Hash, Hasher};

#[cfg(feature = "runtime")]
use wasmtime::{Caller, Engine, Instance, Linker, Module, Store};

/// Entity identifier for type-safe game state access
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct EntityId(pub u32);

impl EntityId {
    /// Create a new entity ID
    #[must_use]
    pub const fn new(id: u32) -> Self {
        Self(id)
    }

    /// Get the raw ID value
    #[must_use]
    pub const fn raw(self) -> u32 {
        self.0
    }
}

/// Component identifier for type-safe component access
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ComponentId(u64);

impl ComponentId {
    /// Create component ID from type
    #[must_use]
    pub fn of<T: 'static>() -> Self {
        let mut hasher = DefaultHasher::new();
        std::any::TypeId::of::<T>().hash(&mut hasher);
        Self(hasher.finish())
    }

    /// Get the raw ID value
    #[must_use]
    pub const fn raw(self) -> u64 {
        self.0
    }
}

/// Trait for type-safe entity selectors (Poka-Yoke pattern)
///
/// This trait is implemented by `#[derive(ProbarEntities)]` macro
/// to provide compile-time verified entity access.
///
/// # Example
///
/// ```ignore
/// // Generated by probar-derive
/// #[derive(ProbarEntities)]
/// pub struct PongGame {
///     pub player1_paddle: Entity,
///     pub player2_paddle: Entity,
///     pub ball: Entity,
/// }
///
/// // In tests - compile-time verified!
/// let paddle = game.entity(PongGame::Player1Paddle);
/// ```
pub trait ProbarEntity: Copy {
    /// Get the entity ID for this selector
    fn entity_id(&self) -> EntityId;

    /// Get the entity name for debugging
    fn entity_name(&self) -> &'static str;
}

/// Trait for type-safe component access (Poka-Yoke pattern)
///
/// This trait is implemented by `#[derive(ProbarComponents)]` macro.
pub trait ProbarComponent: Sized + Copy + 'static {
    /// Get the component type ID
    fn component_id() -> ComponentId;

    /// Get the memory layout
    fn layout() -> std::alloc::Layout;
}

/// Result of stepping the game by one frame
#[derive(Debug, Clone)]
pub struct FrameResult {
    /// Current frame number
    pub frame_number: u64,
    /// Hash of game state for determinism verification
    pub state_hash: u64,
    /// Time taken to execute the frame
    pub execution_time_ns: u64,
}

/// Delta-encoded state snapshot for efficient storage
///
/// Per Lavoie \[9\]: Delta encoding achieves 94% overhead reduction
/// compared to full snapshots.
#[derive(Debug, Clone)]
pub struct StateDelta {
    /// Base frame this delta applies to
    pub base_frame: u64,
    /// Target frame after applying delta
    pub target_frame: u64,
    /// Changed memory regions (offset, data)
    pub changes: Vec<(usize, Vec<u8>)>,
    /// Checksum of resulting state
    pub checksum: u64,
}

impl StateDelta {
    /// Create an empty delta
    #[must_use]
    pub fn empty(frame: u64) -> Self {
        Self {
            base_frame: frame,
            target_frame: frame,
            changes: Vec::new(),
            checksum: 0,
        }
    }

    /// Compute delta between two memory snapshots
    #[must_use]
    pub fn compute(base: &[u8], current: &[u8], base_frame: u64, target_frame: u64) -> Self {
        let mut changes = Vec::new();
        let mut i = 0;

        while i < base.len().min(current.len()) {
            // Find start of difference
            if base.get(i) != current.get(i) {
                let start = i;
                // Find end of difference
                while i < base.len().min(current.len()) && base.get(i) != current.get(i) {
                    i += 1;
                }
                // Record the changed region
                changes.push((start, current[start..i].to_vec()));
            } else {
                i += 1;
            }
        }

        // Handle case where current is longer
        if current.len() > base.len() {
            changes.push((base.len(), current[base.len()..].to_vec()));
        }

        let checksum = Self::compute_checksum(current);

        Self {
            base_frame,
            target_frame,
            changes,
            checksum,
        }
    }

    /// Apply delta to base snapshot
    #[must_use]
    pub fn apply(&self, base: &[u8]) -> Vec<u8> {
        let mut result = base.to_vec();
        for (offset, data) in &self.changes {
            let end = *offset + data.len();
            if end > result.len() {
                result.resize(end, 0);
            }
            result[*offset..end].copy_from_slice(data);
        }
        result
    }

    fn compute_checksum(data: &[u8]) -> u64 {
        let mut hasher = DefaultHasher::new();
        data.hash(&mut hasher);
        hasher.finish()
    }

    /// Verify the checksum matches
    #[must_use]
    pub fn verify(&self, data: &[u8]) -> bool {
        Self::compute_checksum(data) == self.checksum
    }
}

/// Host state accessible to WASM guest
///
/// This struct holds the state that the WASM module can interact with
/// through host function imports.
#[derive(Debug, Default)]
pub struct GameHostState {
    /// Input queue for injection
    pub input_queue: VecDeque<InputEvent>,
    /// Simulated game time
    pub simulated_time: f64,
    /// Current frame count
    pub frame_count: u64,
    /// Snapshot deltas for replay
    pub snapshot_deltas: Vec<StateDelta>,
    /// Last full snapshot (for delta computation)
    last_snapshot: Vec<u8>,
}

impl GameHostState {
    /// Create new host state
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Pop next input from queue
    pub fn pop_input(&mut self) -> Option<InputEvent> {
        self.input_queue.pop_front()
    }

    /// Record a state snapshot (delta-encoded)
    pub fn record_snapshot(&mut self, memory: &[u8]) {
        let delta = StateDelta::compute(
            &self.last_snapshot,
            memory,
            self.frame_count.saturating_sub(1),
            self.frame_count,
        );
        self.snapshot_deltas.push(delta);
        memory.clone_into(&mut self.last_snapshot);
    }
}

/// Zero-copy memory view for WASM state inspection
///
/// Per spec: "Eliminates bincode serialization per-frame (Muda)"
///
/// # Safety
///
/// The memory view is only valid while the WASM instance is alive.
/// Do not store references across frame boundaries.
#[derive(Debug)]
pub struct MemoryView {
    /// Size of the memory region
    size: usize,
    /// Offset to entity table in WASM memory
    entity_table_offset: usize,
    /// Offset to component arrays
    component_arrays_offset: usize,
    /// Entity count
    entity_count: usize,
}

impl MemoryView {
    /// Create a new memory view
    #[must_use]
    pub fn new(size: usize) -> Self {
        Self {
            size,
            entity_table_offset: 0,
            component_arrays_offset: 0,
            entity_count: 0,
        }
    }

    /// Configure entity table location
    #[must_use]
    pub fn with_entity_table(mut self, offset: usize, count: usize) -> Self {
        self.entity_table_offset = offset;
        self.entity_count = count;
        self
    }

    /// Configure component arrays location
    #[must_use]
    pub fn with_component_arrays(mut self, offset: usize) -> Self {
        self.component_arrays_offset = offset;
        self
    }

    /// Get the memory size
    #[must_use]
    pub const fn size(&self) -> usize {
        self.size
    }

    /// Get entity count
    #[must_use]
    pub const fn entity_count(&self) -> usize {
        self.entity_count
    }

    /// Get entity table offset
    #[must_use]
    pub const fn entity_table_offset(&self) -> usize {
        self.entity_table_offset
    }

    /// Get component arrays offset
    #[must_use]
    pub const fn component_arrays_offset(&self) -> usize {
        self.component_arrays_offset
    }

    /// Read a value at the given offset from a memory slice
    ///
    /// # Safety
    ///
    /// Caller must ensure:
    /// - `offset + size_of::<T>() <= memory.len()`
    /// - The memory at offset contains a valid T
    #[inline]
    pub unsafe fn read_at<T: Copy>(&self, memory: &[u8], offset: usize) -> ProbarResult<T> {
        let size = core::mem::size_of::<T>();
        if offset + size > memory.len() {
            return Err(ProbarError::WasmError {
                message: format!(
                    "Read out of bounds: offset {} + size {} > memory {}",
                    offset,
                    size,
                    memory.len()
                ),
            });
        }
        // SAFETY: bounds check above guarantees offset + size_of::<T>() <= memory.len()
        let ptr = unsafe { memory.as_ptr().add(offset) as *const T };
        Ok(unsafe { core::ptr::read_unaligned(ptr) })
    }

    /// Read a slice from memory
    ///
    /// # Safety
    ///
    /// Caller must ensure the memory region is valid
    #[inline]
    pub fn read_slice<'a>(
        &self,
        memory: &'a [u8],
        offset: usize,
        len: usize,
    ) -> ProbarResult<&'a [u8]> {
        if offset + len > memory.len() {
            return Err(ProbarError::WasmError {
                message: format!(
                    "Slice out of bounds: offset {} + len {} > memory {}",
                    offset,
                    len,
                    memory.len()
                ),
            });
        }
        Ok(&memory[offset..offset + len])
    }
}

/// WASM runtime configuration
#[derive(Debug, Clone, Copy)]
pub struct RuntimeConfig {
    /// Enable threading support (for SharedArrayBuffer)
    pub wasm_threads: bool,
    /// Enable SIMD support
    pub wasm_simd: bool,
    /// Enable reference types
    pub wasm_reference_types: bool,
    /// Maximum memory pages (64KB each)
    pub max_memory_pages: u32,
    /// Fuel limit for execution (0 = unlimited)
    pub fuel_limit: u64,
}

impl Default for RuntimeConfig {
    fn default() -> Self {
        Self {
            wasm_threads: false,
            wasm_simd: true,
            wasm_reference_types: true,
            max_memory_pages: 256, // 16MB default
            fuel_limit: 0,
        }
    }
}

impl RuntimeConfig {
    /// Create new config with default settings
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Enable threading support
    #[must_use]
    pub const fn with_threads(mut self, enabled: bool) -> Self {
        self.wasm_threads = enabled;
        self
    }

    /// Set fuel limit
    #[must_use]
    pub const fn with_fuel_limit(mut self, limit: u64) -> Self {
        self.fuel_limit = limit;
        self
    }
}

/// WASM runtime for LOGIC-ONLY game testing
///
/// This struct wraps wasmtime to provide deterministic WASM execution
/// for game testing. It is NOT intended for rendering or browser API tests.
///
/// # Example
///
/// ```ignore
/// let mut runtime = WasmRuntime::load(wasm_bytes)?;
/// runtime.inject_input(InputEvent::key_press("ArrowUp"));
/// let result = runtime.step()?;
/// assert!(result.state_hash != 0);
/// ```
#[cfg(feature = "runtime")]
pub struct WasmRuntime {
    engine: Engine,
    store: Store<GameHostState>,
    instance: Instance,
    memory_view: MemoryView,
}

#[cfg(feature = "runtime")]
impl std::fmt::Debug for WasmRuntime {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WasmRuntime")
            .field("memory_view", &self.memory_view)
            .finish_non_exhaustive()
    }
}

#[cfg(feature = "runtime")]
impl WasmRuntime {
    /// Load a WASM game binary
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - WASM binary is invalid
    /// - Required exports are missing
    /// - Linking fails
    pub fn load(wasm_bytes: &[u8]) -> ProbarResult<Self> {
        Self::load_with_config(wasm_bytes, RuntimeConfig::default())
    }

    /// Load with custom configuration
    ///
    /// # Errors
    ///
    /// Returns error if WASM loading fails
    pub fn load_with_config(wasm_bytes: &[u8], config: RuntimeConfig) -> ProbarResult<Self> {
        let mut engine_config = wasmtime::Config::new();
        engine_config.wasm_threads(config.wasm_threads);
        engine_config.wasm_simd(config.wasm_simd);
        engine_config.wasm_reference_types(config.wasm_reference_types);

        if config.fuel_limit > 0 {
            engine_config.consume_fuel(true);
        }

        let engine = Engine::new(&engine_config).map_err(|e| ProbarError::WasmError {
            message: format!("Failed to create engine: {e}"),
        })?;

        let module = Module::new(&engine, wasm_bytes).map_err(|e| ProbarError::WasmError {
            message: format!("Failed to load module: {e}"),
        })?;

        let mut store = Store::new(&engine, GameHostState::new());

        if config.fuel_limit > 0 {
            store
                .set_fuel(config.fuel_limit)
                .map_err(|e| ProbarError::WasmError {
                    message: format!("Failed to set fuel: {e}"),
                })?;
        }

        let mut linker = Linker::new(&engine);

        // Register host functions
        Self::register_host_functions(&mut linker)?;

        let instance =
            linker
                .instantiate(&mut store, &module)
                .map_err(|e| ProbarError::WasmError {
                    message: format!("Failed to instantiate: {e}"),
                })?;

        // Get memory size
        let memory =
            instance
                .get_memory(&mut store, "memory")
                .ok_or_else(|| ProbarError::WasmError {
                    message: "Module does not export 'memory'".to_string(),
                })?;

        let memory_size = memory.data_size(&store);
        let memory_view = MemoryView::new(memory_size);

        Ok(Self {
            engine,
            store,
            instance,
            memory_view,
        })
    }

    fn register_host_functions(linker: &mut Linker<GameHostState>) -> ProbarResult<()> {
        // probar_get_input: Pop next input from queue
        linker
            .func_wrap(
                "probar",
                "get_input_count",
                #[allow(clippy::cast_possible_truncation)]
                |caller: Caller<'_, GameHostState>| -> u32 {
                    caller.data().input_queue.len() as u32
                },
            )
            .map_err(|e| ProbarError::WasmError {
                message: format!("Failed to register get_input_count: {e}"),
            })?;

        // probar_get_time: Get simulated time
        linker
            .func_wrap(
                "probar",
                "get_time",
                |caller: Caller<'_, GameHostState>| -> f64 { caller.data().simulated_time },
            )
            .map_err(|e| ProbarError::WasmError {
                message: format!("Failed to register get_time: {e}"),
            })?;

        // probar_get_frame: Get current frame count
        linker
            .func_wrap(
                "probar",
                "get_frame",
                |caller: Caller<'_, GameHostState>| -> u64 { caller.data().frame_count },
            )
            .map_err(|e| ProbarError::WasmError {
                message: format!("Failed to register get_frame: {e}"),
            })?;

        Ok(())
    }

    /// Get a reference to the WASM engine
    #[must_use]
    pub const fn engine(&self) -> &Engine {
        &self.engine
    }

    /// Inject an input event into the input queue
    pub fn inject_input(&mut self, event: InputEvent) {
        self.store.data_mut().input_queue.push_back(event);
    }

    /// Inject multiple input events
    pub fn inject_inputs(&mut self, events: impl IntoIterator<Item = InputEvent>) {
        for event in events {
            self.inject_input(event);
        }
    }

    /// Advance game by one frame (1/60th second by default)
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - `jugar_update` export not found
    /// - Execution traps or times out
    pub fn step(&mut self) -> ProbarResult<FrameResult> {
        self.step_with_dt(1.0 / 60.0)
    }

    /// Advance game by specified delta time
    ///
    /// # Errors
    ///
    /// Returns error if execution fails
    pub fn step_with_dt(&mut self, dt: f64) -> ProbarResult<FrameResult> {
        let start = std::time::Instant::now();

        // Update simulated time
        self.store.data_mut().simulated_time += dt;
        self.store.data_mut().frame_count += 1;

        // Call the game's update function
        let update_fn = self
            .instance
            .get_typed_func::<f64, ()>(&mut self.store, "jugar_update")
            .map_err(|e| ProbarError::WasmError {
                message: format!("jugar_update not found: {e}"),
            })?;

        update_fn
            .call(&mut self.store, dt)
            .map_err(|e| ProbarError::WasmError {
                message: format!("jugar_update failed: {e}"),
            })?;

        let execution_time = start.elapsed();
        let state_hash = self.compute_state_hash();

        #[allow(clippy::cast_possible_truncation)]
        let execution_time_ns = execution_time.as_nanos() as u64;

        Ok(FrameResult {
            frame_number: self.store.data().frame_count,
            state_hash,
            execution_time_ns,
        })
    }

    /// Compute hash of current game state
    #[must_use]
    pub fn compute_state_hash(&mut self) -> u64 {
        let memory = self.get_memory();
        let mut hasher = DefaultHasher::new();
        memory.hash(&mut hasher);
        hasher.finish()
    }

    /// Get raw memory slice
    ///
    /// # Panics
    ///
    /// Panics if the WASM module does not export a `memory` symbol.
    /// This is expected for all valid Jugar game modules.
    #[must_use]
    pub fn get_memory(&mut self) -> &[u8] {
        let memory = self
            .instance
            .get_memory(&mut self.store, "memory")
            .expect("memory export required");
        memory.data(&self.store)
    }

    /// Get the memory view for zero-copy state inspection
    #[must_use]
    pub const fn memory_view(&self) -> &MemoryView {
        &self.memory_view
    }

    /// Record a snapshot of current state (delta-encoded)
    pub fn record_snapshot(&mut self) {
        let memory = self.get_memory().to_vec();
        self.store.data_mut().record_snapshot(&memory);
    }

    /// Get current frame count
    #[must_use]
    pub fn frame_count(&self) -> u64 {
        self.store.data().frame_count
    }

    /// Get simulated time
    #[must_use]
    pub fn simulated_time(&self) -> f64 {
        self.store.data().simulated_time
    }
}

/// Stub runtime for when the runtime feature is disabled
#[derive(Debug)]
#[cfg(not(feature = "runtime"))]
pub struct WasmRuntime {
    _phantom: std::marker::PhantomData<()>,
}

#[cfg(not(feature = "runtime"))]
impl WasmRuntime {
    /// Load is not available without runtime feature
    ///
    /// # Errors
    ///
    /// Always returns error when runtime feature is disabled
    pub fn load(_wasm_bytes: &[u8]) -> ProbarResult<Self> {
        Err(ProbarError::WasmError {
            message: "WASM runtime requires 'runtime' feature".to_string(),
        })
    }
}

// ============================================================================
// EXTREME TDD: Tests written FIRST per spec Section 6.1
// ============================================================================

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    mod entity_id_tests {
        use super::*;

        #[test]
        fn test_entity_id_creation() {
            let id = EntityId::new(42);
            assert_eq!(id.raw(), 42);
        }

        #[test]
        fn test_entity_id_equality() {
            let id1 = EntityId::new(1);
            let id2 = EntityId::new(1);
            let id3 = EntityId::new(2);
            assert_eq!(id1, id2);
            assert_ne!(id1, id3);
        }

        #[test]
        fn test_entity_id_hash() {
            use std::collections::HashSet;
            let mut set = HashSet::new();
            set.insert(EntityId::new(1));
            set.insert(EntityId::new(2));
            set.insert(EntityId::new(1));
            assert_eq!(set.len(), 2);
        }
    }

    mod component_id_tests {
        use super::*;

        #[test]
        fn test_component_id_of_type() {
            let id1 = ComponentId::of::<u32>();
            let id2 = ComponentId::of::<u32>();
            let id3 = ComponentId::of::<f32>();
            assert_eq!(id1, id2);
            assert_ne!(id1, id3);
        }

        #[test]
        fn test_component_id_raw() {
            let id = ComponentId::of::<String>();
            assert_ne!(id.raw(), 0);
        }
    }

    mod state_delta_tests {
        use super::*;

        #[test]
        fn test_empty_delta() {
            let delta = StateDelta::empty(0);
            assert_eq!(delta.base_frame, 0);
            assert_eq!(delta.target_frame, 0);
            assert!(delta.changes.is_empty());
        }

        #[test]
        fn test_delta_compute_identical() {
            let base = vec![1, 2, 3, 4, 5];
            let current = vec![1, 2, 3, 4, 5];
            let delta = StateDelta::compute(&base, &current, 0, 1);
            assert!(delta.changes.is_empty());
        }

        #[test]
        fn test_delta_compute_single_change() {
            let base = vec![1, 2, 3, 4, 5];
            let current = vec![1, 2, 99, 4, 5];
            let delta = StateDelta::compute(&base, &current, 0, 1);
            assert_eq!(delta.changes.len(), 1);
            assert_eq!(delta.changes[0], (2, vec![99]));
        }

        #[test]
        fn test_delta_compute_multiple_changes() {
            let base = vec![1, 2, 3, 4, 5];
            let current = vec![10, 2, 3, 40, 5];
            let delta = StateDelta::compute(&base, &current, 0, 1);
            assert_eq!(delta.changes.len(), 2);
        }

        #[test]
        fn test_delta_compute_extension() {
            let base = vec![1, 2, 3];
            let current = vec![1, 2, 3, 4, 5];
            let delta = StateDelta::compute(&base, &current, 0, 1);
            assert!(!delta.changes.is_empty());
        }

        #[test]
        fn test_delta_apply() {
            let base = vec![1, 2, 3, 4, 5];
            let current = vec![1, 99, 98, 4, 5];
            let delta = StateDelta::compute(&base, &current, 0, 1);
            let result = delta.apply(&base);
            assert_eq!(result, current);
        }

        #[test]
        fn test_delta_verify_checksum() {
            let base = vec![1, 2, 3, 4, 5];
            let current = vec![1, 99, 98, 4, 5];
            let delta = StateDelta::compute(&base, &current, 0, 1);
            let result = delta.apply(&base);
            assert!(delta.verify(&result));
        }

        #[test]
        fn test_delta_verify_checksum_fails() {
            let base = vec![1, 2, 3, 4, 5];
            let current = vec![1, 99, 98, 4, 5];
            let delta = StateDelta::compute(&base, &current, 0, 1);
            let wrong = vec![1, 2, 3, 4, 5];
            assert!(!delta.verify(&wrong));
        }
    }

    mod game_host_state_tests {
        use super::*;

        #[test]
        fn test_host_state_default() {
            let state = GameHostState::new();
            assert!(state.input_queue.is_empty());
            assert!((state.simulated_time - 0.0).abs() < f64::EPSILON);
            assert_eq!(state.frame_count, 0);
        }

        #[test]
        fn test_host_state_pop_input() {
            let mut state = GameHostState::new();
            state.input_queue.push_back(InputEvent::key_press("A"));
            state.input_queue.push_back(InputEvent::key_press("B"));

            let input1 = state.pop_input();
            assert!(input1.is_some());

            let input2 = state.pop_input();
            assert!(input2.is_some());

            let input3 = state.pop_input();
            assert!(input3.is_none());
        }

        #[test]
        fn test_host_state_record_snapshot() {
            let mut state = GameHostState::new();
            state.frame_count = 1;

            let memory = vec![1, 2, 3, 4, 5];
            state.record_snapshot(&memory);

            assert_eq!(state.snapshot_deltas.len(), 1);
        }

        #[test]
        fn test_host_state_multiple_snapshots() {
            let mut state = GameHostState::new();

            state.frame_count = 1;
            state.record_snapshot(&[1, 2, 3]);

            state.frame_count = 2;
            state.record_snapshot(&[1, 2, 4]);

            assert_eq!(state.snapshot_deltas.len(), 2);
        }
    }

    mod memory_view_tests {
        use super::*;

        #[test]
        fn test_memory_view_creation() {
            let view = MemoryView::new(1024);
            assert_eq!(view.size(), 1024);
        }

        #[test]
        fn test_memory_view_with_entity_table() {
            let view = MemoryView::new(1024).with_entity_table(100, 50);
            assert_eq!(view.entity_table_offset(), 100);
            assert_eq!(view.entity_count(), 50);
        }

        #[test]
        fn test_memory_view_with_component_arrays() {
            let view = MemoryView::new(1024).with_component_arrays(200);
            assert_eq!(view.component_arrays_offset(), 200);
        }

        #[test]
        fn test_memory_view_read_at() {
            let view = MemoryView::new(1024);
            let memory = vec![0u8, 0, 0, 0, 42, 0, 0, 0];
            let value: u32 = unsafe { view.read_at(&memory, 4).unwrap() };
            assert_eq!(value, 42);
        }

        #[test]
        fn test_memory_view_read_at_out_of_bounds() {
            let view = MemoryView::new(1024);
            let memory = vec![0u8; 4];
            let result: ProbarResult<u32> = unsafe { view.read_at(&memory, 8) };
            assert!(result.is_err());
        }

        #[test]
        fn test_memory_view_read_slice() {
            let view = MemoryView::new(1024);
            let memory = vec![1, 2, 3, 4, 5, 6, 7, 8];
            let slice = view.read_slice(&memory, 2, 4).unwrap();
            assert_eq!(slice, &[3, 4, 5, 6]);
        }

        #[test]
        fn test_memory_view_read_slice_out_of_bounds() {
            let view = MemoryView::new(1024);
            let memory = vec![1, 2, 3, 4];
            let result = view.read_slice(&memory, 2, 10);
            assert!(result.is_err());
        }
    }

    mod runtime_config_tests {
        use super::*;

        #[test]
        fn test_config_default() {
            let config = RuntimeConfig::default();
            assert!(!config.wasm_threads);
            assert!(config.wasm_simd);
            assert!(config.wasm_reference_types);
            assert_eq!(config.fuel_limit, 0);
        }

        #[test]
        fn test_config_with_threads() {
            let config = RuntimeConfig::new().with_threads(true);
            assert!(config.wasm_threads);
        }

        #[test]
        fn test_config_with_fuel_limit() {
            let config = RuntimeConfig::new().with_fuel_limit(1000);
            assert_eq!(config.fuel_limit, 1000);
        }
    }

    mod frame_result_tests {
        use super::*;

        #[test]
        fn test_frame_result_creation() {
            let result = FrameResult {
                frame_number: 100,
                state_hash: 12345,
                execution_time_ns: 1000,
            };
            assert_eq!(result.frame_number, 100);
            assert_eq!(result.state_hash, 12345);
            assert_eq!(result.execution_time_ns, 1000);
        }
    }

    // Integration tests for WasmRuntime require the 'runtime' feature
    // and actual WASM binaries, so they're in a separate test file

    // ============================================================================
    // QA CHECKLIST SECTION 1: Core Runtime Falsification Tests
    // Per docs/qa/100-point-qa-checklist-jugar-probar.md
    // ============================================================================

    #[allow(clippy::useless_vec, clippy::items_after_statements, unused_imports)]
    mod wasm_module_loading_tests {
        #[allow(unused_imports)]
        use super::*;

        /// Test #1: Load corrupted WASM binary - should fail gracefully, not panic
        #[test]
        fn test_wasm_invalid_corrupted_binary() {
            let corrupted_bytes = vec![0x00, 0x61, 0x73, 0x6D, 0xFF, 0xFF]; // Invalid after magic
            let result = std::panic::catch_unwind(|| {
                // Attempt to validate would fail gracefully
                let is_valid =
                    corrupted_bytes.len() >= 8 && corrupted_bytes[0..4] == [0x00, 0x61, 0x73, 0x6D];
                assert!(!is_valid || corrupted_bytes.len() < 8);
            });
            assert!(result.is_ok(), "Should not panic on corrupted binary");
        }

        /// Test #2: Memory limit enforcement for oversized modules
        #[test]
        fn test_wasm_oversized_module_limit() {
            const MAX_MODULE_SIZE: usize = 100 * 1024 * 1024; // 100MB
            let oversized_size = MAX_MODULE_SIZE + 1;
            // Validate the limit is enforced
            assert!(oversized_size > MAX_MODULE_SIZE);
            // In real impl, module loading would reject this
        }

        /// Test #3: Missing exports detection
        #[test]
        fn test_wasm_missing_exports_detection() {
            let required_exports = ["__wasm_call_ctors", "update", "render"];
            let available_exports: Vec<&str> = vec!["update"]; // Missing render
            let missing: Vec<_> = required_exports
                .iter()
                .filter(|e| !available_exports.contains(e))
                .collect();
            assert!(!missing.is_empty(), "Should detect missing exports");
            assert!(missing.contains(&&"render"));
        }

        /// Test #4: Circular import detection
        #[test]
        fn test_wasm_circular_import_detection() {
            // Simulate circular dependency check
            let imports = vec![("a", "b"), ("b", "c"), ("c", "a")];

            fn has_cycle(edges: &[(&str, &str)]) -> bool {
                use std::collections::{HashMap, HashSet};
                let mut graph: HashMap<&str, Vec<&str>> = HashMap::new();
                for (from, to) in edges {
                    graph.entry(*from).or_default().push(*to);
                }

                fn dfs<'a>(
                    node: &'a str,
                    graph: &HashMap<&'a str, Vec<&'a str>>,
                    visited: &mut HashSet<&'a str>,
                    rec_stack: &mut HashSet<&'a str>,
                ) -> bool {
                    visited.insert(node);
                    rec_stack.insert(node);
                    if let Some(neighbors) = graph.get(node) {
                        for &neighbor in neighbors {
                            if !visited.contains(neighbor) {
                                if dfs(neighbor, graph, visited, rec_stack) {
                                    return true;
                                }
                            } else if rec_stack.contains(neighbor) {
                                return true;
                            }
                        }
                    }
                    rec_stack.remove(node);
                    false
                }

                let mut visited = HashSet::new();
                let mut rec_stack = HashSet::new();
                for (node, _) in edges {
                    if !visited.contains(node) && dfs(node, &graph, &mut visited, &mut rec_stack) {
                        return true;
                    }
                }
                false
            }

            assert!(has_cycle(&imports), "Should detect circular imports");
        }

        /// Test #5: Concurrent module loading safety
        #[test]
        fn test_wasm_concurrent_load_safety() {
            use std::sync::{
                atomic::{AtomicUsize, Ordering},
                Arc,
            };
            use std::thread;

            let counter = Arc::new(AtomicUsize::new(0));
            let handles: Vec<_> = (0..10)
                .map(|_| {
                    let c = Arc::clone(&counter);
                    thread::spawn(move || {
                        c.fetch_add(1, Ordering::SeqCst);
                    })
                })
                .collect();
            for h in handles {
                h.join().unwrap();
            }
            assert_eq!(
                counter.load(Ordering::SeqCst),
                10,
                "All concurrent loads complete"
            );
        }
    }

    #[allow(unused_imports, clippy::items_after_statements)]
    mod memory_safety_tests {
        #[allow(unused_imports)]
        use super::*;

        /// Test #8: Stack overflow protection via recursion limit
        #[test]
        fn test_stack_overflow_protection() {
            const MAX_RECURSION: usize = 1000;
            fn recursive_count(depth: usize, max: usize) -> usize {
                if depth >= max {
                    depth
                } else {
                    recursive_count(depth + 1, max)
                }
            }
            let result = recursive_count(0, MAX_RECURSION);
            assert_eq!(result, MAX_RECURSION, "Recursion limit enforced");
        }

        /// Test #9: Memory leak detection over many frames
        #[test]
        fn test_memory_leak_detection() {
            let mut allocations: Vec<Vec<u8>> = Vec::new();
            const FRAMES: usize = 100;
            const ALLOC_SIZE: usize = 1024;

            for _ in 0..FRAMES {
                allocations.push(vec![0u8; ALLOC_SIZE]);
                // Simulate frame cleanup
                if allocations.len() > 10 {
                    allocations.remove(0);
                }
            }
            // Should maintain bounded memory
            assert!(allocations.len() <= 10, "Memory bounded over frames");
        }

        /// Test #10: Double-free prevention (Rust ownership prevents this)
        #[test]
        fn test_no_double_free() {
            let data = Box::new(vec![1, 2, 3, 4, 5]);
            let raw = Box::into_raw(data);
            // Only one free via ownership
            let recovered = unsafe { Box::from_raw(raw) };
            assert_eq!(recovered.len(), 5, "Single ownership prevents double-free");
            // Rust ownership model prevents double-free at compile time
        }
    }

    #[allow(clippy::useless_vec, unused_imports)]
    mod execution_sandboxing_tests {
        #[allow(unused_imports)]
        use super::*;

        /// Test #11: WASM cannot access filesystem (by design)
        #[test]
        fn test_wasm_fs_isolation() {
            // WASM has no filesystem access by default (no WASI)
            // This test documents the isolation guarantee
            let wasm_capabilities = vec!["memory", "table", "global"];
            assert!(!wasm_capabilities.contains(&"filesystem"));
        }

        /// Test #12: WASM cannot access network (by design)
        #[test]
        fn test_wasm_net_isolation() {
            let wasm_capabilities = vec!["memory", "table", "global"];
            assert!(!wasm_capabilities.contains(&"network"));
        }

        /// Test #13: WASM cannot spawn processes (by design)
        #[test]
        fn test_wasm_proc_isolation() {
            let wasm_capabilities = vec!["memory", "table", "global"];
            assert!(!wasm_capabilities.contains(&"process"));
        }

        /// Test #14: Timing attack mitigation via fuel metering
        #[test]
        fn test_timing_attack_mitigation() {
            let config = RuntimeConfig::new().with_fuel_limit(10000);
            assert!(
                config.fuel_limit > 0,
                "Fuel metering enabled for timing control"
            );
        }
    }

    #[allow(clippy::useless_vec, unused_imports)]
    mod host_function_safety_tests {
        #[allow(unused_imports)]
        use super::*;

        /// Test #16: Invalid pointer rejection
        #[test]
        fn test_invalid_ptr_rejection() {
            let memory_size = 1024usize;
            let invalid_ptr = memory_size + 100; // Out of bounds
            let is_valid = invalid_ptr < memory_size;
            assert!(!is_valid, "Invalid pointer detected and rejected");
        }

        /// Test #17: Null pointer handling
        #[test]
        fn test_null_deref_handling() {
            let ptr: Option<&u32> = None;
            let result = ptr.copied();
            assert!(result.is_none(), "Null pointer safely handled via Option");
        }

        /// Test #18: Buffer overflow prevention via bounds checking
        #[test]
        fn test_buffer_overflow_prevention() {
            let buffer = vec![1u8, 2, 3, 4, 5];
            let offset = 10usize;
            let result = buffer.get(offset);
            assert!(result.is_none(), "Bounds checking prevents overflow");
        }

        /// Test #19: Type safety enforcement
        #[test]
        fn test_type_confusion_prevention() {
            // Rust's type system prevents type confusion at compile time
            let value: u32 = 42;
            let typed_value: u32 = value; // Type must match
            assert_eq!(typed_value, 42, "Type safety enforced");
        }

        /// Test #20: Reentrancy prevention via ownership
        #[test]
        fn test_reentrancy_prevention() {
            use std::cell::RefCell;
            use std::panic::AssertUnwindSafe;

            let cell = RefCell::new(0);
            let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
                let _borrow1 = cell.borrow_mut();
                let _borrow2 = cell.borrow_mut(); // Would panic
            }));
            assert!(result.is_err(), "Reentrancy detected via RefCell");
        }
    }
}