wasma-sys 1.3.0-beta-stable

WASMA Windows Assignment System Monitoring Architecture — client and protocol layer
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
// WASMA - Windows Assignment System Monitoring Architecture
// wasma_protocol_unixverse_windowesc.rs
// Unixverse Window Escape — AVAX ShiftMasking Protocol
// Target: All platforms, including non-POSIX devices (unixverse = universal scope)
// 32-bit: FULL support (no semi-restriction)
// 64-bit: FULL support
// Algorithms: XOR + Bit Rotation + Polynomial Hash + LFSR + AVAX ShiftMasking
// AVAX: Adaptive Vectorized Accumulative XOR-shift — the defining feature of unixverse
// Completely independent from unix_posix_windowesc
// January 2026

use crate::parser::WasmaConfig;
use std::sync::Arc;

// ============================================================================
// PLATFORM SUPPORT — Both 32 and 64-bit, full support
// ============================================================================

/// Unixverse platform width — both 32 and 64-bit are fully supported
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum UniverseWidth {
    Bits32,
    Bits64,
}

impl UniverseWidth {
    pub const fn detect() -> Self {
        if cfg!(target_pointer_width = "64") {
            Self::Bits64
        } else {
            Self::Bits32
        }
    }

    pub fn bits(&self) -> u32 {
        match self {
            Self::Bits32 => 32,
            Self::Bits64 => 64,
        }
    }

    pub fn name(&self) -> &'static str {
        match self {
            Self::Bits32 => "32-bit (full support)",
            Self::Bits64 => "64-bit (full support)",
        }
    }

    /// Max ShiftMask value for this width
    pub fn max_mask(&self) -> u64 {
        match self {
            Self::Bits32 => u32::MAX as u64,
            Self::Bits64 => u64::MAX,
        }
    }
}

pub const UNIVERSE_WIDTH: UniverseWidth = UniverseWidth::detect();

// ============================================================================
// UNIXVERSE SHIFTMASK KEY — Width-adaptive key
// ============================================================================

/// UniverseKey — adapts to 32 or 64-bit, both fully supported
#[derive(Debug, Clone, Copy)]
pub struct UniverseKey {
    /// Full 64-bit storage (lower 32 bits used on 32-bit)
    raw: u64,
    /// Width-adapted effective value
    effective: u64,
    /// Width at key creation
    width: UniverseWidth,
}

impl UniverseKey {
    pub fn new(raw: u64) -> Self {
        let effective = match UNIVERSE_WIDTH {
            UniverseWidth::Bits64 => raw,
            UniverseWidth::Bits32 => raw & 0xFFFF_FFFF,
        };
        // Ensure non-zero on the effective bits
        let effective = if effective == 0 {
            0x5A5A_5A5A_5A5A_5A5A
        } else {
            effective
        };
        Self {
            raw,
            effective,
            width: UNIVERSE_WIDTH,
        }
    }

    pub fn from_seed(seed: &str) -> Self {
        // FNV-1a 64-bit
        let mut h: u64 = 0xcbf2_9ce4_8422_2325;
        for b in seed.bytes() {
            h ^= b as u64;
            h = h.wrapping_mul(0x0000_0100_0000_01B3);
        }
        // Mix for better diffusion
        h ^= h >> 33;
        h = h.wrapping_mul(0xff51_afd7_ed55_8ccd);
        h ^= h >> 33;
        h = h.wrapping_mul(0xc4ce_b9fe_1a85_ec53);
        h ^= h >> 33;
        Self::new(h)
    }

    pub fn from_config(config: &WasmaConfig) -> Self {
        let seed = format!("{}/{}", config.uri_handling.window_app_spec, "1.0");
        Self::from_seed(&seed)
    }

    /// Derive a context-specific sub-key
    pub fn derive(&self, context: u64) -> Self {
        let k = self
            .effective
            .wrapping_mul(0x6c62_272e_07bb_0142)
            .wrapping_add(context)
            ^ context.rotate_left(17);
        Self::new(k)
    }

    pub fn raw(&self) -> u64 {
        self.raw
    }
    pub fn effective(&self) -> u64 {
        self.effective
    }
    pub fn width(&self) -> UniverseWidth {
        self.width
    }
}

// ============================================================================
// AVAX SHIFTMASKING — Core of unixverse_windowesc
// ============================================================================
// AVAX = Adaptive Vectorized Accumulative XOR-shift
//
// Algorithm:
//   state₀ = key
//   For each chunk:
//     state = AVAX_step(state)    — XOR-shift accumulation
//     chunk ^= state_bytes
//     state = AVAX_mix(state, chunk_hash)  — adaptive: chunk influences next state
//
// Properties:
//   - Adaptive: output depends on input history (not just key)
//   - Full 32/64-bit support: operates in native width
//   - Vectorized-ready: 8-byte chunks aligned for SIMD
//   - Non-symmetric: different from unix_posix XOR (separate state machine)

pub struct AvaxEngine {
    key: UniverseKey,
}

impl AvaxEngine {
    pub fn new(key: UniverseKey) -> Self {
        Self { key }
    }

    // ---- AVAX step: XOR-shift state advance ----
    fn avax_step(state: u64, width: UniverseWidth) -> u64 {
        let s = match width {
            UniverseWidth::Bits64 => {
                let s = state ^ (state << 13);
                let s = s ^ (s >> 7);
                s ^ (s << 17)
            }
            UniverseWidth::Bits32 => {
                // 32-bit AVAX: xorshift32 variant, fully contained
                let s = (state as u32) ^ ((state as u32) << 13);
                let s = s ^ (s >> 17);
                let s = s ^ (s << 5);
                s as u64
            }
        };
        // Clamp to width
        s & width.max_mask()
    }

    // ---- AVAX mix: incorporate chunk hash into state ----
    fn avax_mix(state: u64, chunk_hash: u64, width: UniverseWidth) -> u64 {
        let mixed = state
            .wrapping_add(chunk_hash)
            .wrapping_mul(0x9e37_79b9_7f4a_7c15);
        mixed & width.max_mask()
    }

    // ---- Chunk hash: fast non-crypto hash of a byte chunk ----
    fn chunk_hash(chunk: &[u8]) -> u64 {
        let mut h: u64 = 0x1234_5678_9ABC_DEF0;
        for &b in chunk {
            h ^= b as u64;
            h = h.wrapping_mul(0x0000_0100_0000_01B3);
        }
        h
    }

    /// AVAX mask a stream in-place
    pub fn mask_stream(&self, data: &mut [u8]) {
        let width = UNIVERSE_WIDTH;
        let mut state = self.key.effective();

        // Process in 8-byte chunks
        let chunks = data.chunks_mut(8);
        for chunk in chunks {
            // Advance state
            state = Self::avax_step(state, width);
            let state_bytes = state.to_le_bytes();

            // XOR chunk with state
            for (i, byte) in chunk.iter_mut().enumerate() {
                *byte ^= state_bytes[i % 8];
            }

            // Mix: state adapts to chunk (already XORed = output)
            let hash = Self::chunk_hash(chunk);
            state = Self::avax_mix(state, hash, width);
        }
    }

    /// AVAX mask a stream — returns new Vec
    pub fn mask_stream_copy(&self, data: &[u8]) -> Vec<u8> {
        let mut out = data.to_vec();
        self.mask_stream(&mut out);
        out
    }

    /// AVAX unmask — requires inverse step sequence
    /// Since AVAX is adaptive (state depends on ciphertext), we need
    /// to replay the masking on the ciphertext to recover the keystream
    pub fn unmask_stream(&self, data: &mut [u8]) {
        let width = UNIVERSE_WIDTH;
        let mut state = self.key.effective();

        let chunks = data.chunks_mut(8);
        for chunk in chunks {
            state = Self::avax_step(state, width);
            let state_bytes = state.to_le_bytes();

            // Save ciphertext bytes for state mix
            let cipher_chunk: Vec<u8> = chunk.to_vec();

            // XOR to recover plaintext
            for (i, byte) in chunk.iter_mut().enumerate() {
                *byte ^= state_bytes[i % 8];
            }

            // Mix with CIPHERTEXT (not plaintext) to match mask_stream behavior
            let hash = Self::chunk_hash(&cipher_chunk);
            state = Self::avax_mix(state, hash, width);
        }
    }

    /// AVAX mask a single u64 ID
    pub fn mask_id(&self, id: u64) -> u64 {
        let width = UNIVERSE_WIDTH;
        let state = Self::avax_step(self.key.effective(), width);
        (id ^ state) & width.max_mask()
    }

    /// AVAX unmask a single u64 ID (same operation — XOR is symmetric at single step)
    pub fn unmask_id(&self, masked: u64) -> u64 {
        self.mask_id(masked)
    }

    pub fn key(&self) -> &UniverseKey {
        &self.key
    }
}

// ============================================================================
// UNIXVERSE SHIFTMASK ALGORITHMS — All 5 algos, full 32+64-bit
// ============================================================================

#[derive(Debug, Clone, Copy, PartialEq)]
pub enum UniverseAlgo {
    /// XOR-based — symmetric, simple
    Xor,
    /// Bit rotation — width-adaptive (32 or 64-bit rotation)
    BitRotation,
    /// Polynomial hash mask — GF(2^32) or GF(2^64)
    PolynomialHash,
    /// LFSR — 32-bit or 64-bit LFSR, both fully supported
    Lfsr,
    /// AVAX — Adaptive Vectorized Accumulative XOR-shift (unixverse exclusive)
    Avax,
}

impl UniverseAlgo {
    pub fn name(&self) -> &'static str {
        match self {
            Self::Xor => "XOR",
            Self::BitRotation => "BitRotation",
            Self::PolynomialHash => "PolynomialHash",
            Self::Lfsr => "LFSR (full 32/64-bit)",
            Self::Avax => "AVAX (Adaptive Vectorized Accumulative XOR-shift)",
        }
    }

    /// All algos available on all platforms in unixverse
    pub fn is_available(&self) -> bool {
        true
    }
}

// ============================================================================
// UNIXVERSE SHIFTMASK ENGINE
// ============================================================================

pub struct UniverseEngine {
    key: UniverseKey,
    algo: UniverseAlgo,
    avax: Arc<AvaxEngine>,
}

impl UniverseEngine {
    pub fn new(key: UniverseKey, algo: UniverseAlgo) -> Self {
        let avax_key = key.derive(0xA_u64);
        Self {
            avax: Arc::new(AvaxEngine::new(avax_key)),
            key,
            algo,
        }
    }

    // ------------------------------------------------------------------
    // ID MASKING
    // ------------------------------------------------------------------

    pub fn mask_id(&self, id: u64) -> u64 {
        match self.algo {
            UniverseAlgo::Xor => self.xor_u64(id),
            UniverseAlgo::BitRotation => self.rotate_u64(id, true),
            UniverseAlgo::PolynomialHash => self.poly_u64(id),
            UniverseAlgo::Lfsr => self.lfsr_u64(id),
            UniverseAlgo::Avax => self.avax.mask_id(id),
        }
    }

    pub fn unmask_id(&self, masked: u64) -> u64 {
        match self.algo {
            UniverseAlgo::Xor => self.xor_u64(masked),
            UniverseAlgo::BitRotation => self.rotate_u64(masked, false),
            UniverseAlgo::PolynomialHash => self.poly_u64(masked), // approx inverse
            UniverseAlgo::Lfsr => self.lfsr_u64(masked),
            UniverseAlgo::Avax => self.avax.unmask_id(masked),
        }
    }

    // ------------------------------------------------------------------
    // STREAM MASKING
    // ------------------------------------------------------------------

    pub fn mask_stream(&self, data: &mut [u8]) {
        match self.algo {
            UniverseAlgo::Xor => self.xor_stream(data),
            UniverseAlgo::BitRotation => self.rotate_stream(data),
            UniverseAlgo::PolynomialHash => self.poly_stream(data),
            UniverseAlgo::Lfsr => self.lfsr_stream(data),
            UniverseAlgo::Avax => self.avax.mask_stream(data),
        }
    }

    pub fn unmask_stream(&self, data: &mut [u8]) {
        match self.algo {
            UniverseAlgo::Avax => self.avax.unmask_stream(data),
            _ => self.mask_stream(data), // others are symmetric
        }
    }

    pub fn mask_stream_copy(&self, data: &[u8]) -> Vec<u8> {
        let mut out = data.to_vec();
        self.mask_stream(&mut out);
        out
    }

    // ------------------------------------------------------------------
    // XOR
    // ------------------------------------------------------------------
    fn xor_u64(&self, v: u64) -> u64 {
        (v ^ self.key.effective()) & UNIVERSE_WIDTH.max_mask()
    }

    fn xor_stream(&self, data: &mut [u8]) {
        let key_bytes = self.key.effective().to_le_bytes();
        for (i, b) in data.iter_mut().enumerate() {
            *b ^= key_bytes[i % 8];
        }
    }

    // ------------------------------------------------------------------
    // BIT ROTATION — Full 32 and 64-bit
    // ------------------------------------------------------------------
    fn rotation_amount(&self) -> u32 {
        match UNIVERSE_WIDTH {
            UniverseWidth::Bits64 => (self.key.effective() & 0x3F) as u32,
            UniverseWidth::Bits32 => (self.key.effective() & 0x1F) as u32,
        }
    }

    fn rotate_u64(&self, v: u64, forward: bool) -> u64 {
        let r = self.rotation_amount();
        match UNIVERSE_WIDTH {
            UniverseWidth::Bits64 => {
                if forward {
                    v.rotate_left(r)
                } else {
                    v.rotate_right(r)
                }
            }
            UniverseWidth::Bits32 => {
                // Full 32-bit rotation (not semi-restricted — full support)
                let lo = v as u32;
                let hi = (v >> 32) as u32;
                let (lo2, hi2) = if forward {
                    (lo.rotate_left(r), hi.rotate_left(r))
                } else {
                    (lo.rotate_right(r), hi.rotate_right(r))
                };
                lo2 as u64 | ((hi2 as u64) << 32)
            }
        }
    }

    fn rotate_stream(&self, data: &mut [u8]) {
        let r = (self.rotation_amount() % 8) as u32;
        if r == 0 {
            return;
        }
        for b in data.iter_mut() {
            *b = b.rotate_left(r);
        }
    }

    // ------------------------------------------------------------------
    // POLYNOMIAL HASH MASK — GF(2^32) or GF(2^64)
    // ------------------------------------------------------------------
    const GF64_POLY: u64 = 0x0000_0000_0000_001B;
    const GF32_POLY: u64 = 0x0000_0000_0000_00AF;

    fn gf_mul(&self, a: u64, b: u64) -> u64 {
        let (width, poly) = match UNIVERSE_WIDTH {
            UniverseWidth::Bits64 => (64u32, Self::GF64_POLY),
            UniverseWidth::Bits32 => (32u32, Self::GF32_POLY),
        };
        let mask = if width == 64 {
            u64::MAX
        } else {
            (1u64 << width) - 1
        };
        let mut result = 0u64;
        let mut a = a & mask;
        let mut b = b & mask;
        while b > 0 {
            if b & 1 == 1 {
                result ^= a;
            }
            let carry = (a >> (width - 1)) & 1;
            a = (a << 1) & mask;
            if carry == 1 {
                a ^= poly;
            }
            b >>= 1;
        }
        result
    }

    fn poly_u64(&self, v: u64) -> u64 {
        let k = self.key.effective();
        self.gf_mul(v, k) ^ k.wrapping_mul(0x9e37_79b9_7f4a_7c15)
    }

    fn poly_stream(&self, data: &mut [u8]) {
        let key_bytes = self.key.effective().to_le_bytes();
        let poly = (Self::GF32_POLY & 0xFF) as u8;
        for (i, b) in data.iter_mut().enumerate() {
            *b ^= key_bytes[i % 8];
            *b = b.wrapping_add(poly.wrapping_mul(i as u8));
        }
    }

    // ------------------------------------------------------------------
    // LFSR — Full 32-bit AND 64-bit (unixverse: no restriction!)
    // ------------------------------------------------------------------
    const LFSR64_TAPS: u64 = 0xD800_0000_0000_0000;
    const LFSR32_TAPS: u64 = 0x0000_0000_B400_0000; // x^32+x^31+x^29+x+1

    fn lfsr_taps() -> u64 {
        match UNIVERSE_WIDTH {
            UniverseWidth::Bits64 => Self::LFSR64_TAPS,
            UniverseWidth::Bits32 => Self::LFSR32_TAPS,
        }
    }

    fn lfsr_next(state: u64) -> u64 {
        let taps = Self::lfsr_taps();
        let mask = UNIVERSE_WIDTH.max_mask();
        let lsb = state & 1;
        let next = (state >> 1) & mask;
        if lsb == 1 {
            next ^ taps
        } else {
            next
        }
    }

    fn lfsr_u64(&self, v: u64) -> u64 {
        let mut state = self.key.effective();
        let steps = (state & 0xFF).max(1);
        for _ in 0..steps {
            state = Self::lfsr_next(state);
        }
        (v ^ state) & UNIVERSE_WIDTH.max_mask()
    }

    fn lfsr_stream(&self, data: &mut [u8]) {
        let mut state = self.key.effective();
        for b in data.iter_mut() {
            state = Self::lfsr_next(state);
            *b ^= (state & 0xFF) as u8;
        }
    }

    pub fn algo(&self) -> UniverseAlgo {
        self.algo
    }
    pub fn key(&self) -> &UniverseKey {
        &self.key
    }
    pub fn avax(&self) -> Arc<AvaxEngine> {
        self.avax.clone()
    }
}

// ============================================================================
// UNIXVERSE WINDOW ID ESCAPER
// ============================================================================

pub struct UniverseWindowIdEscaper {
    engine: UniverseEngine,
    masked: std::collections::HashMap<u64, u64>,
    reverse: std::collections::HashMap<u64, u64>,
}

impl UniverseWindowIdEscaper {
    pub fn new(engine: UniverseEngine) -> Self {
        Self {
            engine,
            masked: Default::default(),
            reverse: Default::default(),
        }
    }

    pub fn register(&mut self, real_id: u64) -> u64 {
        if let Some(&m) = self.masked.get(&real_id) {
            return m;
        }
        let masked = self.engine.mask_id(real_id);
        self.masked.insert(real_id, masked);
        self.reverse.insert(masked, real_id);
        masked
    }

    pub fn resolve(&self, masked_id: u64) -> Option<u64> {
        self.reverse
            .get(&masked_id)
            .copied()
            .or_else(|| Some(self.engine.unmask_id(masked_id)))
    }

    pub fn unregister(&mut self, real_id: u64) {
        if let Some(m) = self.masked.remove(&real_id) {
            self.reverse.remove(&m);
        }
    }

    pub fn masked_id_of(&self, real_id: u64) -> Option<u64> {
        self.masked.get(&real_id).copied()
    }

    pub fn count(&self) -> usize {
        self.masked.len()
    }
}

// ============================================================================
// UNIXVERSE STREAM ESCAPER
// ============================================================================

pub struct UniverseStreamEscaper {
    engine: UniverseEngine,
}

impl UniverseStreamEscaper {
    pub fn new(engine: UniverseEngine) -> Self {
        Self { engine }
    }

    pub fn mask(&self, data: &mut [u8]) {
        self.engine.mask_stream(data);
    }
    pub fn unmask(&self, data: &mut [u8]) {
        self.engine.unmask_stream(data);
    }
    pub fn mask_copy(&self, data: &[u8]) -> Vec<u8> {
        self.engine.mask_stream_copy(data)
    }
    pub fn algo(&self) -> UniverseAlgo {
        self.engine.algo()
    }
}

// ============================================================================
// UNIXVERSE WINDOW ESC — Top-level coordinator
// ============================================================================

/// UniverseWindowEsc
///
/// Unixverse ShiftMasking coordinator.
/// Works on ALL platforms including non-POSIX devices.
/// 32-bit: FULL support (no restrictions)
/// 64-bit: FULL support
/// Exclusive: AVAX ShiftMasking algorithm
/// Completely independent from PosixWindowEsc
pub struct UniverseWindowEsc {
    pub id_escaper: UniverseWindowIdEscaper,
    pub stream_escaper: UniverseStreamEscaper,
    pub platform: UniverseWidth,
}

impl UniverseWindowEsc {
    pub fn new(key: UniverseKey, algo: UniverseAlgo) -> Self {
        let id_engine = UniverseEngine::new(key, algo);
        let stream_key = key.derive(0xB7C3_D5E1_F2A4);
        let stream_engine = UniverseEngine::new(stream_key, algo);

        Self {
            id_escaper: UniverseWindowIdEscaper::new(id_engine),
            stream_escaper: UniverseStreamEscaper::new(stream_engine),
            platform: UNIVERSE_WIDTH,
        }
    }

    pub fn from_config(config: &WasmaConfig, algo: UniverseAlgo) -> Self {
        Self::new(UniverseKey::from_config(config), algo)
    }

    /// Default: AVAX — unixverse's defining algorithm
    pub fn from_config_avax(config: &WasmaConfig) -> Self {
        Self::from_config(config, UniverseAlgo::Avax)
    }

    /// LFSR variant — fully supported on both 32 and 64-bit
    pub fn from_config_lfsr(config: &WasmaConfig) -> Self {
        Self::from_config(config, UniverseAlgo::Lfsr)
    }

    pub fn print_info(&self) {
        println!("╔══════════════════════════════════════════════════════════════╗");
        println!("║           WASMA UniverseWindowEsc Info                       ║");
        println!("╚══════════════════════════════════════════════════════════════╝");
        println!(
            "  Platform:    {} (ALL platforms, incl. non-POSIX)",
            self.platform.name()
        );
        println!("  ID algo:     {}", self.id_escaper.engine.algo().name());
        println!("  Stream algo: {}", self.stream_escaper.algo().name());
        println!("  Registered:  {} windows", self.id_escaper.count());
        println!("  AVAX:        Adaptive Vectorized Accumulative XOR-shift");
        println!("  LFSR 32-bit: FULLY SUPPORTED (no restriction)");
        println!("  LFSR 64-bit: FULLY SUPPORTED");
    }
}

// ============================================================================
// TESTS
// ============================================================================

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

    fn make_config() -> WasmaConfig {
        let parser = ConfigParser::new(None);
        let content = parser.generate_default_config();
        parser.parse(&content).unwrap()
    }

    fn make_key() -> UniverseKey {
        UniverseKey::new(0xCAFE_BABE_1234_5678)
    }

    fn make_engine(algo: UniverseAlgo) -> UniverseEngine {
        UniverseEngine::new(make_key(), algo)
    }

    #[test]
    fn test_platform_detection() {
        println!("✅ Unixverse platform: {}", UNIVERSE_WIDTH.name());
        println!("   Max mask: 0x{:X}", UNIVERSE_WIDTH.max_mask());
        assert!(UNIVERSE_WIDTH.bits() == 32 || UNIVERSE_WIDTH.bits() == 64);
    }

    #[test]
    fn test_key_from_seed_deterministic() {
        let k1 = UniverseKey::from_seed("unixverse.app");
        let k2 = UniverseKey::from_seed("unixverse.app");
        let k3 = UniverseKey::from_seed("other.app");
        assert_eq!(k1.raw(), k2.raw());
        assert_ne!(k1.raw(), k3.raw());
        println!("✅ UniverseKey seed deterministic");
    }

    #[test]
    fn test_key_derive_unique() {
        let k = make_key();
        assert_ne!(k.derive(0x01).raw(), k.derive(0x02).raw());
        assert_eq!(k.derive(0x01).raw(), k.derive(0x01).raw());
        println!("✅ UniverseKey derive unique and deterministic");
    }

    #[test]
    fn test_xor_id_roundtrip() {
        let engine = make_engine(UniverseAlgo::Xor);
        for id in [0u64, 1, 0xFFFF_FFFF, 0x1234_5678_9ABC_DEF0] {
            assert_eq!(engine.unmask_id(engine.mask_id(id)), id);
        }
        println!("✅ XOR ID roundtrip (unixverse)");
    }

    #[test]
    fn test_rotation_id_roundtrip() {
        let engine = make_engine(UniverseAlgo::BitRotation);
        for id in [1u64, 42, 0xDEAD_BEEF, u64::MAX / 3] {
            assert_eq!(engine.unmask_id(engine.mask_id(id)), id);
        }
        println!("✅ BitRotation ID roundtrip (unixverse, full 32/64)");
    }

    #[test]
    fn test_lfsr_full_support_both_widths() {
        // LFSR must work on BOTH 32 and 64-bit — no restriction in unixverse
        let engine = make_engine(UniverseAlgo::Lfsr);
        for id in [0u64, 1, 0xABCD, u64::MAX & UNIVERSE_WIDTH.max_mask()] {
            let masked = engine.mask_id(id);
            let back = engine.unmask_id(masked);
            assert_eq!(back, id & UNIVERSE_WIDTH.max_mask());
        }
        println!(
            "✅ LFSR FULL support on {} (no restriction!)",
            UNIVERSE_WIDTH.name()
        );
    }

    #[test]
    fn test_avax_id_roundtrip() {
        let engine = make_engine(UniverseAlgo::Avax);
        for id in [0u64, 1, 42, 0xFEED_FACE] {
            let masked = engine.mask_id(id);
            let back = engine.unmask_id(masked);
            assert_eq!(
                back,
                id & UNIVERSE_WIDTH.max_mask(),
                "AVAX ID roundtrip failed for {}",
                id
            );
        }
        println!("✅ AVAX ID roundtrip working");
    }

    #[test]
    fn test_avax_stream_roundtrip() {
        let engine = make_engine(UniverseAlgo::Avax);
        let original = b"AVAX unixverse stream masking test data 1234567890";
        let mut data = original.to_vec();
        engine.mask_stream(&mut data);
        assert_ne!(data, original);
        engine.unmask_stream(&mut data);
        assert_eq!(data, original.to_vec());
        println!("✅ AVAX stream roundtrip working");
    }

    #[test]
    fn test_avax_adaptive_property() {
        // Two streams with one byte different → different masking output
        let engine = make_engine(UniverseAlgo::Avax);
        let data1 = b"AAAAAAAAAA".to_vec();
        let mut data2 = b"BAAAAAAAAA".to_vec(); // first byte differs

        let masked1 = engine.mask_stream_copy(&data1);
        engine.mask_stream(&mut data2);

        // After the first differing byte, outputs should diverge due to adaptive mixing
        // (they will differ in at least later bytes due to adaptive state)
        assert_ne!(masked1, data2);
        println!("✅ AVAX adaptive property verified");
    }

    #[test]
    fn test_avax_engine_direct() {
        let key = make_key();
        let avax = AvaxEngine::new(key);

        let original = vec![0xFFu8; 32];
        let masked = avax.mask_stream_copy(&original);
        assert_ne!(masked, original);

        let mut back = masked.clone();
        avax.unmask_stream(&mut back);
        assert_eq!(back, original);
        println!("✅ AvaxEngine direct roundtrip working");
    }

    #[test]
    fn test_xor_stream_roundtrip() {
        let engine = make_engine(UniverseAlgo::Xor);
        let original = b"unixverse xor stream test";
        let mut data = original.to_vec();
        engine.mask_stream(&mut data);
        engine.unmask_stream(&mut data);
        assert_eq!(data, original);
        println!("✅ XOR stream roundtrip (unixverse)");
    }

    #[test]
    fn test_lfsr_stream_roundtrip() {
        let engine = make_engine(UniverseAlgo::Lfsr);
        let original = vec![0x55u8; 64];
        let mut data = original.clone();
        engine.mask_stream(&mut data);
        assert_ne!(data, original);
        engine.unmask_stream(&mut data);
        assert_eq!(data, original);
        println!("✅ LFSR stream roundtrip (unixverse, full support)");
    }

    #[test]
    fn test_universe_window_id_escaper() {
        let engine = make_engine(UniverseAlgo::Avax);
        let mut escaper = UniverseWindowIdEscaper::new(engine);

        let ids = [1u64, 2, 10, 100, 999];
        let masked: Vec<u64> = ids.iter().map(|&id| escaper.register(id)).collect();

        // Idempotent
        assert_eq!(escaper.register(ids[0]), masked[0]);

        // All masked IDs distinct
        for i in 0..masked.len() {
            for j in i + 1..masked.len() {
                assert_ne!(masked[i], masked[j]);
            }
        }
        // Resolve back
        for (i, &real) in ids.iter().enumerate() {
            assert_eq!(escaper.resolve(masked[i]), Some(real));
        }
        // Unregister
        escaper.unregister(ids[0]);
        assert_eq!(escaper.count(), ids.len() - 1);
        println!("✅ UniverseWindowIdEscaper (AVAX) working");
    }

    #[test]
    fn test_universe_stream_escaper() {
        let engine = make_engine(UniverseAlgo::Lfsr);
        let escaper = UniverseStreamEscaper::new(engine);

        let original = b"stream escaper test";
        let masked = escaper.mask_copy(original);
        assert_ne!(masked.as_slice(), original.as_slice());

        let mut back = masked;
        escaper.unmask(&mut back);
        assert_eq!(back, original);
        println!("✅ UniverseStreamEscaper (LFSR) working");
    }

    #[test]
    fn test_universe_window_esc_avax() {
        let config = make_config();
        let mut esc = UniverseWindowEsc::from_config_avax(&config);

        let id = esc.id_escaper.register(77u64);
        assert_ne!(id, 77);
        assert_eq!(esc.id_escaper.resolve(id), Some(77));

        let data = b"avax top level test";
        let masked = esc.stream_escaper.mask_copy(data);
        assert_ne!(masked.as_slice(), data.as_slice());

        esc.print_info();
        println!("✅ UniverseWindowEsc (AVAX) working");
    }

    #[test]
    fn test_universe_window_esc_lfsr() {
        let config = make_config();
        let mut esc = UniverseWindowEsc::from_config_lfsr(&config);
        let id = esc.id_escaper.register(42u64);
        assert_ne!(id, 42);
        println!("✅ UniverseWindowEsc (LFSR full) working: 42 → {}", id);
    }

    #[test]
    fn test_independence_from_posix() {
        // Verify unixverse uses different key derivation from posix
        // (different seed mixing in from_config)
        let config = make_config();
        let k_unixverse = UniverseKey::from_config(&config);
        // posix uses only app_id; unixverse uses app_id/version
        // Keys should be different (version appended)
        let k_posix_seed =
            crate::wasma_protocol_unix_posix_windowesc::ShiftMaskKey::from_config(&config);
        // They will differ because seeds differ
        assert_ne!(k_unixverse.raw(), k_posix_seed.raw());
        println!("✅ UniverseKey is independent from PosixKey");
    }

    #[test]
    fn test_all_algos_available() {
        // All algos must be available on all platforms in unixverse
        for algo in [
            UniverseAlgo::Xor,
            UniverseAlgo::BitRotation,
            UniverseAlgo::PolynomialHash,
            UniverseAlgo::Lfsr,
            UniverseAlgo::Avax,
        ] {
            assert!(algo.is_available(), "{} not available!", algo.name());
        }
        println!(
            "✅ All 5 UniverseAlgo variants available on {}",
            UNIVERSE_WIDTH.name()
        );
    }
}