reovim-kernel 0.14.3

Core kernel mechanisms for reovim (Linux kernel/ equivalent)
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
use super::*;

/// Verify Module trait is object-safe (can be used as `dyn Module`).
/// This is critical for dynamic module loading via libloading.
#[test]
#[cfg_attr(coverage_nightly, coverage(off))]
fn test_module_trait_object_safety() {
    // These function signatures compile = trait is object safe
    fn _accepts_module_ref(_: &dyn Module) {}
    fn _accepts_boxed_module(_: Box<dyn Module>) {}

    // Trait is object safe if this compiles
}

#[test]
#[cfg_attr(coverage_nightly, coverage(off))]
fn test_module_deferred_probing() {
    // Test module that uses deferred probing pattern
    struct DeferredModule {
        ready: bool,
    }

    impl Module for DeferredModule {
        fn id(&self) -> ModuleId {
            ModuleId::new("deferred")
        }
        fn name(&self) -> &'static str {
            "Deferred Module"
        }
        fn version(&self) -> Version {
            Version::new(1, 0, 0)
        }
        fn init(&mut self, _ctx: &ModuleContext) -> ProbeResult {
            if self.ready {
                ProbeResult::Success
            } else {
                ProbeResult::Defer("waiting for dependency".into())
            }
        }
        fn exit(&mut self) -> Result<(), ModuleError> {
            Ok(())
        }
    }

    // Verify module implements the trait correctly with both states
    let ready_module = DeferredModule { ready: true };
    assert_eq!(ready_module.id(), ModuleId::new("deferred"));
    assert_eq!(ready_module.name(), "Deferred Module");

    let not_ready = DeferredModule { ready: false };
    assert_eq!(not_ready.id(), ModuleId::new("deferred"));
    // Both ready and not-ready modules have the same identity
}

// ========== Module default impls ==========

#[test]
#[cfg_attr(coverage_nightly, coverage(off))]
fn test_module_default_impls() {
    struct MinimalModule;

    impl Module for MinimalModule {
        fn id(&self) -> ModuleId {
            ModuleId::new("minimal")
        }
        fn name(&self) -> &'static str {
            "Minimal"
        }
        fn version(&self) -> Version {
            Version::new(0, 1, 0)
        }
        fn init(&mut self, _ctx: &ModuleContext) -> ProbeResult {
            ProbeResult::Success
        }
        fn exit(&mut self) -> Result<(), ModuleError> {
            Ok(())
        }
    }

    let mut m = MinimalModule;

    // Test all default impls
    assert!(m.dependencies().is_empty());
    assert!(m.optional_dependencies().is_empty());
    assert!(m.extension_kinds().is_empty());
    assert!(m.commands().is_empty());
    assert!(m.keybindings().is_empty());
    assert!(m.event_handlers().is_empty());
    assert!(!m.supports_hot_reload());
    assert!(m.save_state().is_none());

    // restore_state default returns error
    let result = m.restore_state(&[1, 2, 3]);
    assert!(result.is_err());

    // on_unload default returns Ok
    assert!(m.on_unload().is_ok());

    // api_version returns current API version
    assert_eq!(m.api_version(), API_VERSION);
}

// ========== Lifecycle hooks via trait object ==========

#[test]
#[cfg_attr(coverage_nightly, coverage(off))]
fn test_module_lifecycle_hooks_via_dyn() {
    use std::sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    };

    struct HookModule {
        all_loaded: Arc<AtomicBool>,
        buffer_focus: Arc<AtomicBool>,
        on_unload: Arc<AtomicBool>,
    }

    impl Module for HookModule {
        fn id(&self) -> ModuleId {
            ModuleId::new("hook-test")
        }
        fn name(&self) -> &'static str {
            "Hook Test"
        }
        fn version(&self) -> Version {
            Version::new(1, 0, 0)
        }
        fn init(&mut self, _ctx: &ModuleContext) -> ProbeResult {
            ProbeResult::Success
        }
        fn exit(&mut self) -> Result<(), ModuleError> {
            Ok(())
        }
        fn on_all_loaded(&mut self, _ctx: &ModuleContext) {
            self.all_loaded.store(true, Ordering::SeqCst);
        }
        fn on_buffer_focus(&mut self, _buffer_id: BufferId, _ctx: &ModuleContext) {
            self.buffer_focus.store(true, Ordering::SeqCst);
        }
        fn on_unload(&mut self) -> Result<(), ModuleError> {
            self.on_unload.store(true, Ordering::SeqCst);
            Ok(())
        }
    }

    let all_loaded = Arc::new(AtomicBool::new(false));
    let buffer_focus = Arc::new(AtomicBool::new(false));
    let unload = Arc::new(AtomicBool::new(false));

    let mut module: Box<dyn Module> = Box::new(HookModule {
        all_loaded: Arc::clone(&all_loaded),
        buffer_focus: Arc::clone(&buffer_focus),
        on_unload: Arc::clone(&unload),
    });

    // Call lifecycle hooks through trait object
    let ctx = ModuleContext::default();
    module.on_all_loaded(&ctx);
    assert!(all_loaded.load(Ordering::SeqCst));

    module.on_buffer_focus(BufferId::from_raw(1), &ctx);
    assert!(buffer_focus.load(Ordering::SeqCst));

    assert!(module.on_unload().is_ok());
    assert!(unload.load(Ordering::SeqCst));
}

#[test]
#[cfg_attr(coverage_nightly, coverage(off))]
fn test_module_default_lifecycle_hooks_via_dyn() {
    struct DefaultModule;

    impl Module for DefaultModule {
        fn id(&self) -> ModuleId {
            ModuleId::new("default-hooks")
        }
        fn name(&self) -> &'static str {
            "Default Hooks"
        }
        fn version(&self) -> Version {
            Version::new(0, 1, 0)
        }
        fn init(&mut self, _ctx: &ModuleContext) -> ProbeResult {
            ProbeResult::Success
        }
        fn exit(&mut self) -> Result<(), ModuleError> {
            Ok(())
        }
    }

    let mut module: Box<dyn Module> = Box::new(DefaultModule);
    let ctx = ModuleContext::default();

    // Default on_all_loaded is no-op (should not panic)
    module.on_all_loaded(&ctx);

    // Default on_buffer_focus is no-op (should not panic)
    module.on_buffer_focus(BufferId::from_raw(42), &ctx);

    // Default on_unload returns Ok
    assert!(module.on_unload().is_ok());

    // Test all registration methods via dyn
    assert!(module.commands().is_empty());
    assert!(module.keybindings().is_empty());
    assert!(module.event_handlers().is_empty());
    assert!(module.dependencies().is_empty());
    assert!(module.optional_dependencies().is_empty());
    assert!(!module.supports_hot_reload());
    assert!(module.save_state().is_none());
    assert!(module.restore_state(&[1, 2]).is_err());
}

#[test]
#[cfg_attr(coverage_nightly, coverage(off))]
fn test_module_init_exit_via_dyn() {
    struct InitExitModule {
        initialized: bool,
    }

    impl Module for InitExitModule {
        fn id(&self) -> ModuleId {
            ModuleId::new("init-exit")
        }
        fn name(&self) -> &'static str {
            "Init Exit"
        }
        fn version(&self) -> Version {
            Version::new(1, 0, 0)
        }
        fn init(&mut self, _ctx: &ModuleContext) -> ProbeResult {
            self.initialized = true;
            ProbeResult::Success
        }
        fn exit(&mut self) -> Result<(), ModuleError> {
            self.initialized = false;
            Ok(())
        }
    }

    let mut module: Box<dyn Module> = Box::new(InitExitModule { initialized: false });
    let ctx = ModuleContext::default();

    // Test init
    let result = module.init(&ctx);
    assert!(matches!(result, ProbeResult::Success));

    // Test exit
    assert!(module.exit().is_ok());

    // Test identity via dyn
    assert_eq!(module.id(), ModuleId::new("init-exit"));
    assert_eq!(module.name(), "Init Exit");
    assert_eq!(module.version(), Version::new(1, 0, 0));
    assert_eq!(module.api_version(), API_VERSION);
}

#[test]
#[cfg_attr(coverage_nightly, coverage(off))]
fn test_module_hot_reload_via_dyn() {
    struct HotReloadModule {
        state: u32,
    }

    impl Module for HotReloadModule {
        fn id(&self) -> ModuleId {
            ModuleId::new("hot-reload")
        }
        fn name(&self) -> &'static str {
            "Hot Reload"
        }
        fn version(&self) -> Version {
            Version::new(1, 0, 0)
        }
        fn init(&mut self, _ctx: &ModuleContext) -> ProbeResult {
            ProbeResult::Success
        }
        fn exit(&mut self) -> Result<(), ModuleError> {
            Ok(())
        }
        fn supports_hot_reload(&self) -> bool {
            true
        }
        fn save_state(&self) -> Option<Box<[u8]>> {
            let bytes = self.state.to_le_bytes();
            Some(bytes.to_vec().into_boxed_slice())
        }
        fn restore_state(&mut self, state: &[u8]) -> Result<(), ModuleError> {
            if state.len() < 4 {
                return Err(ModuleError::InitFailed("state too short".into()));
            }
            let bytes: [u8; 4] = state[..4]
                .try_into()
                .map_err(|_| ModuleError::InitFailed("invalid state".into()))?;
            self.state = u32::from_le_bytes(bytes);
            Ok(())
        }
    }

    let mut module: Box<dyn Module> = Box::new(HotReloadModule { state: 42 });

    assert!(module.supports_hot_reload());

    // Save state via dyn
    let saved = module.save_state().unwrap();
    assert_eq!(saved.len(), 4);

    // Restore state via dyn
    assert!(module.restore_state(&saved).is_ok());

    // Restore with bad state
    assert!(module.restore_state(&[1]).is_err());
}

#[test]
#[cfg_attr(coverage_nightly, coverage(off))]
fn test_module_with_dependencies_via_dyn() {
    struct DepModule;

    impl Module for DepModule {
        fn id(&self) -> ModuleId {
            ModuleId::new("dep-module")
        }
        fn name(&self) -> &'static str {
            "Dep Module"
        }
        fn version(&self) -> Version {
            Version::new(1, 0, 0)
        }
        fn init(&mut self, _ctx: &ModuleContext) -> ProbeResult {
            ProbeResult::Success
        }
        fn exit(&mut self) -> Result<(), ModuleError> {
            Ok(())
        }
        fn dependencies(&self) -> Vec<ModuleId> {
            vec![ModuleId::new("core-module")]
        }
        fn optional_dependencies(&self) -> Vec<ModuleId> {
            vec![ModuleId::new("feat-lsp")]
        }
    }

    let mut module: Box<dyn Module> = Box::new(DepModule);
    let deps = module.dependencies();
    assert_eq!(deps.len(), 1);
    assert_eq!(deps[0], ModuleId::new("core-module"));

    let opt_deps = module.optional_dependencies();
    assert_eq!(opt_deps.len(), 1);
    assert_eq!(opt_deps[0], ModuleId::new("feat-lsp"));

    // Exercise init/exit on DepModule
    let ctx = ModuleContext::default();
    let result = module.init(&ctx);
    assert!(matches!(result, ProbeResult::Success));
    assert!(module.exit().is_ok());
}

// ========================================================================
// Additional coverage tests
// ========================================================================

#[test]
#[cfg_attr(coverage_nightly, coverage(off))]
fn test_deferred_module_init_both_paths() {
    struct DeferredModule {
        ready: bool,
    }

    impl Module for DeferredModule {
        fn id(&self) -> ModuleId {
            ModuleId::new("deferred")
        }
        fn name(&self) -> &'static str {
            "Deferred Module"
        }
        fn version(&self) -> Version {
            Version::new(1, 0, 0)
        }
        fn init(&mut self, _ctx: &ModuleContext) -> ProbeResult {
            if self.ready {
                ProbeResult::Success
            } else {
                ProbeResult::Defer("waiting for dependency".into())
            }
        }
        fn exit(&mut self) -> Result<(), ModuleError> {
            Ok(())
        }
    }

    let ctx = ModuleContext::default();

    // Not ready path - should defer
    let mut not_ready = DeferredModule { ready: false };
    assert_eq!(not_ready.id(), ModuleId::new("deferred"));
    assert_eq!(not_ready.name(), "Deferred Module");
    assert_eq!(not_ready.version(), Version::new(1, 0, 0));
    let result = not_ready.init(&ctx);
    assert!(matches!(result, ProbeResult::Defer(_)));
    assert!(not_ready.exit().is_ok());

    // Ready path - should succeed
    let mut ready = DeferredModule { ready: true };
    let result = ready.init(&ctx);
    assert!(matches!(result, ProbeResult::Success));
    assert!(ready.exit().is_ok());
}

#[test]
#[cfg_attr(coverage_nightly, coverage(off))]
fn test_minimal_module_full_lifecycle() {
    struct MinimalModule;

    impl Module for MinimalModule {
        fn id(&self) -> ModuleId {
            ModuleId::new("minimal")
        }
        fn name(&self) -> &'static str {
            "Minimal"
        }
        fn version(&self) -> Version {
            Version::new(0, 1, 0)
        }
        fn init(&mut self, _ctx: &ModuleContext) -> ProbeResult {
            ProbeResult::Success
        }
        fn exit(&mut self) -> Result<(), ModuleError> {
            Ok(())
        }
    }

    let mut m = MinimalModule;
    let ctx = ModuleContext::default();

    // Exercise identity methods
    assert_eq!(m.id(), ModuleId::new("minimal"));
    assert_eq!(m.name(), "Minimal");
    assert_eq!(m.version(), Version::new(0, 1, 0));
    assert_eq!(m.api_version(), API_VERSION);

    // Exercise lifecycle
    let result = m.init(&ctx);
    assert!(matches!(result, ProbeResult::Success));

    m.on_all_loaded(&ctx);
    m.on_buffer_focus(BufferId::from_raw(1), &ctx);

    assert!(m.on_unload().is_ok());
    assert!(m.exit().is_ok());

    // Exercise registration defaults
    assert!(m.dependencies().is_empty());
    assert!(m.optional_dependencies().is_empty());
    assert!(m.commands().is_empty());
    assert!(m.keybindings().is_empty());
    assert!(m.event_handlers().is_empty());

    // Exercise hot reload defaults
    assert!(!m.supports_hot_reload());
    assert!(m.save_state().is_none());
    assert!(m.restore_state(&[1, 2, 3]).is_err());
}

#[test]
#[cfg_attr(coverage_nightly, coverage(off))]
fn test_hook_module_init_exit_exercised() {
    use std::sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    };

    struct HookModule {
        all_loaded: Arc<AtomicBool>,
        buffer_focus: Arc<AtomicBool>,
        on_unload: Arc<AtomicBool>,
    }

    impl Module for HookModule {
        fn id(&self) -> ModuleId {
            ModuleId::new("hook-test")
        }
        fn name(&self) -> &'static str {
            "Hook Test"
        }
        fn version(&self) -> Version {
            Version::new(1, 0, 0)
        }
        fn init(&mut self, _ctx: &ModuleContext) -> ProbeResult {
            ProbeResult::Success
        }
        fn exit(&mut self) -> Result<(), ModuleError> {
            Ok(())
        }
        fn on_all_loaded(&mut self, _ctx: &ModuleContext) {
            self.all_loaded.store(true, Ordering::SeqCst);
        }
        fn on_buffer_focus(&mut self, _buffer_id: BufferId, _ctx: &ModuleContext) {
            self.buffer_focus.store(true, Ordering::SeqCst);
        }
        fn on_unload(&mut self) -> Result<(), ModuleError> {
            self.on_unload.store(true, Ordering::SeqCst);
            Ok(())
        }
    }

    let all_loaded = Arc::new(AtomicBool::new(false));
    let buffer_focus = Arc::new(AtomicBool::new(false));
    let unload = Arc::new(AtomicBool::new(false));

    let mut module: Box<dyn Module> = Box::new(HookModule {
        all_loaded: Arc::clone(&all_loaded),
        buffer_focus: Arc::clone(&buffer_focus),
        on_unload: Arc::clone(&unload),
    });

    // Exercise identity
    assert_eq!(module.id(), ModuleId::new("hook-test"));
    assert_eq!(module.name(), "Hook Test");
    assert_eq!(module.version(), Version::new(1, 0, 0));

    // Exercise init/exit
    let ctx = ModuleContext::default();
    let result = module.init(&ctx);
    assert!(matches!(result, ProbeResult::Success));

    module.on_all_loaded(&ctx);
    assert!(all_loaded.load(Ordering::SeqCst));

    module.on_buffer_focus(BufferId::from_raw(1), &ctx);
    assert!(buffer_focus.load(Ordering::SeqCst));

    assert!(module.on_unload().is_ok());
    assert!(unload.load(Ordering::SeqCst));

    assert!(module.exit().is_ok());
}

#[test]
#[cfg_attr(coverage_nightly, coverage(off))]
fn test_default_module_full_exercise() {
    struct DefaultModule;

    impl Module for DefaultModule {
        fn id(&self) -> ModuleId {
            ModuleId::new("default-hooks")
        }
        fn name(&self) -> &'static str {
            "Default Hooks"
        }
        fn version(&self) -> Version {
            Version::new(0, 1, 0)
        }
        fn init(&mut self, _ctx: &ModuleContext) -> ProbeResult {
            ProbeResult::Success
        }
        fn exit(&mut self) -> Result<(), ModuleError> {
            Ok(())
        }
    }

    let mut module: Box<dyn Module> = Box::new(DefaultModule);
    let ctx = ModuleContext::default();

    // Identity
    assert_eq!(module.id(), ModuleId::new("default-hooks"));
    assert_eq!(module.name(), "Default Hooks");
    assert_eq!(module.version(), Version::new(0, 1, 0));
    assert_eq!(module.api_version(), API_VERSION);

    // Full lifecycle
    let result = module.init(&ctx);
    assert!(matches!(result, ProbeResult::Success));

    module.on_all_loaded(&ctx);
    module.on_buffer_focus(BufferId::from_raw(42), &ctx);
    assert!(module.on_unload().is_ok());
    assert!(module.exit().is_ok());

    // Registration defaults
    assert!(module.commands().is_empty());
    assert!(module.keybindings().is_empty());
    assert!(module.event_handlers().is_empty());
    assert!(module.dependencies().is_empty());
    assert!(module.optional_dependencies().is_empty());

    // Hot reload defaults
    assert!(!module.supports_hot_reload());
    assert!(module.save_state().is_none());
    assert!(module.restore_state(&[1, 2]).is_err());
}

#[test]
#[cfg_attr(coverage_nightly, coverage(off))]
fn test_hot_reload_module_full_exercise() {
    struct HotReloadModule {
        state: u32,
    }

    impl Module for HotReloadModule {
        fn id(&self) -> ModuleId {
            ModuleId::new("hot-reload")
        }
        fn name(&self) -> &'static str {
            "Hot Reload"
        }
        fn version(&self) -> Version {
            Version::new(1, 0, 0)
        }
        fn init(&mut self, _ctx: &ModuleContext) -> ProbeResult {
            ProbeResult::Success
        }
        fn exit(&mut self) -> Result<(), ModuleError> {
            Ok(())
        }
        fn supports_hot_reload(&self) -> bool {
            true
        }
        fn save_state(&self) -> Option<Box<[u8]>> {
            let bytes = self.state.to_le_bytes();
            Some(bytes.to_vec().into_boxed_slice())
        }
        fn restore_state(&mut self, state: &[u8]) -> Result<(), ModuleError> {
            if state.len() < 4 {
                return Err(ModuleError::InitFailed("state too short".into()));
            }
            let bytes: [u8; 4] = state[..4]
                .try_into()
                .map_err(|_| ModuleError::InitFailed("invalid state".into()))?;
            self.state = u32::from_le_bytes(bytes);
            Ok(())
        }
    }

    let mut module: Box<dyn Module> = Box::new(HotReloadModule { state: 42 });
    let ctx = ModuleContext::default();

    // Identity
    assert_eq!(module.id(), ModuleId::new("hot-reload"));
    assert_eq!(module.name(), "Hot Reload");
    assert_eq!(module.version(), Version::new(1, 0, 0));

    // Lifecycle
    let result = module.init(&ctx);
    assert!(matches!(result, ProbeResult::Success));

    // Hot reload
    assert!(module.supports_hot_reload());
    let saved = module.save_state().unwrap();
    assert_eq!(saved.len(), 4);
    assert!(module.restore_state(&saved).is_ok());

    // Restore with too-short state
    let short_result = module.restore_state(&[1]);
    assert!(short_result.is_err());

    // Restore with empty state
    let empty_result = module.restore_state(&[]);
    assert!(empty_result.is_err());

    // Restore with exactly 4 bytes
    assert!(module.restore_state(&[0, 0, 0, 0]).is_ok());

    assert!(module.exit().is_ok());
}

#[test]
#[cfg_attr(coverage_nightly, coverage(off))]
fn test_module_failed_init() {
    struct FailingModule;

    impl Module for FailingModule {
        fn id(&self) -> ModuleId {
            ModuleId::new("failing")
        }
        fn name(&self) -> &'static str {
            "Failing Module"
        }
        fn version(&self) -> Version {
            Version::new(0, 1, 0)
        }
        fn init(&mut self, _ctx: &ModuleContext) -> ProbeResult {
            ProbeResult::Failed(ModuleError::InitFailed("config missing".into()))
        }
        fn exit(&mut self) -> Result<(), ModuleError> {
            Err(ModuleError::InitFailed("never initialized".into()))
        }
    }

    let mut module = FailingModule;
    let ctx = ModuleContext::default();

    assert_eq!(module.id(), ModuleId::new("failing"));
    assert_eq!(module.name(), "Failing Module");
    assert_eq!(module.version(), Version::new(0, 1, 0));

    let result = module.init(&ctx);
    assert!(matches!(result, ProbeResult::Failed(_)));

    let exit_result = module.exit();
    assert!(exit_result.is_err());
}

#[test]
#[cfg_attr(coverage_nightly, coverage(off))]
fn test_module_on_unload_error() {
    struct UnloadFailModule;

    impl Module for UnloadFailModule {
        fn id(&self) -> ModuleId {
            ModuleId::new("unload-fail")
        }
        fn name(&self) -> &'static str {
            "Unload Fail"
        }
        fn version(&self) -> Version {
            Version::new(1, 0, 0)
        }
        fn init(&mut self, _ctx: &ModuleContext) -> ProbeResult {
            ProbeResult::Success
        }
        fn exit(&mut self) -> Result<(), ModuleError> {
            Ok(())
        }
        fn on_unload(&mut self) -> Result<(), ModuleError> {
            Err(ModuleError::InitFailed("resource leak".into()))
        }
    }

    let mut module = UnloadFailModule;
    let ctx = ModuleContext::default();

    assert_eq!(module.id(), ModuleId::new("unload-fail"));
    assert_eq!(module.name(), "Unload Fail");
    assert_eq!(module.version(), Version::new(1, 0, 0));

    let result = module.init(&ctx);
    assert!(matches!(result, ProbeResult::Success));

    let unload_result = module.on_unload();
    assert!(unload_result.is_err());

    assert!(module.exit().is_ok());
}

#[test]
#[cfg_attr(coverage_nightly, coverage(off))]
fn test_module_with_custom_api_version() {
    struct CustomApiModule;

    impl Module for CustomApiModule {
        fn id(&self) -> ModuleId {
            ModuleId::new("custom-api")
        }
        fn name(&self) -> &'static str {
            "Custom API"
        }
        fn version(&self) -> Version {
            Version::new(1, 0, 0)
        }
        fn api_version(&self) -> Version {
            Version::new(0, 1, 0)
        }
        fn init(&mut self, _ctx: &ModuleContext) -> ProbeResult {
            ProbeResult::Success
        }
        fn exit(&mut self) -> Result<(), ModuleError> {
            Ok(())
        }
    }

    let mut module = CustomApiModule;
    let ctx = ModuleContext::default();

    assert_eq!(module.api_version(), Version::new(0, 1, 0));
    assert_ne!(module.api_version(), API_VERSION);

    let result = module.init(&ctx);
    assert!(matches!(result, ProbeResult::Success));
    assert!(module.exit().is_ok());
}

#[test]
#[cfg_attr(coverage_nightly, coverage(off))]
fn test_module_with_registrations() {
    struct RegistrationModule;

    impl Module for RegistrationModule {
        fn id(&self) -> ModuleId {
            ModuleId::new("reg-module")
        }
        fn name(&self) -> &'static str {
            "Registration Module"
        }
        fn version(&self) -> Version {
            Version::new(1, 0, 0)
        }
        fn init(&mut self, _ctx: &ModuleContext) -> ProbeResult {
            ProbeResult::Success
        }
        fn exit(&mut self) -> Result<(), ModuleError> {
            Ok(())
        }
        fn commands(&self) -> Vec<CommandRegistration> {
            vec![CommandRegistration::new("test-cmd").with_name("Test Command")]
        }
        fn keybindings(&self) -> Vec<KeybindingRegistration> {
            use crate::core::CommandId;
            let cmd_id = CommandId::new(ModuleId::new("reg-module"), "test-cmd");
            vec![KeybindingRegistration::new("t", cmd_id).with_modes(&["normal"])]
        }
        fn event_handlers(&self) -> Vec<EventHandlerRegistration> {
            vec![EventHandlerRegistration::new("BufferChanged").with_priority(50)]
        }
    }

    let mut module: Box<dyn Module> = Box::new(RegistrationModule);
    let ctx = ModuleContext::default();

    // Identity
    assert_eq!(module.id(), ModuleId::new("reg-module"));
    assert_eq!(module.name(), "Registration Module");
    assert_eq!(module.version(), Version::new(1, 0, 0));

    // Lifecycle
    let result = module.init(&ctx);
    assert!(matches!(result, ProbeResult::Success));

    // Registrations
    let cmds = module.commands();
    assert_eq!(cmds.len(), 1);
    assert_eq!(cmds[0].id, "test-cmd");
    assert_eq!(cmds[0].name, "Test Command");

    let keys = module.keybindings();
    assert_eq!(keys.len(), 1);
    assert_eq!(keys[0].keys, "t");

    let events = module.event_handlers();
    assert_eq!(events.len(), 1);
    assert_eq!(events[0].event_type, "BufferChanged");
    assert_eq!(events[0].priority, 50);

    assert!(module.exit().is_ok());
}

#[test]
#[cfg_attr(coverage_nightly, coverage(off))]
fn test_module_restore_state_default_error_message() {
    struct NoHotReload;

    impl Module for NoHotReload {
        fn id(&self) -> ModuleId {
            ModuleId::new("no-hot-reload")
        }
        fn name(&self) -> &'static str {
            "No Hot Reload"
        }
        fn version(&self) -> Version {
            Version::new(0, 1, 0)
        }
        fn init(&mut self, _ctx: &ModuleContext) -> ProbeResult {
            ProbeResult::Success
        }
        fn exit(&mut self) -> Result<(), ModuleError> {
            Ok(())
        }
    }

    let mut module = NoHotReload;
    let result = module.restore_state(&[1, 2, 3, 4]);
    assert!(result.is_err());
    if let Err(ModuleError::InitFailed(msg)) = result {
        assert!(msg.contains("hot reload not supported"));
    } else {
        panic!("expected InitFailed error");
    }
}

#[test]
#[cfg_attr(coverage_nightly, coverage(off))]
fn test_module_multiple_buffer_focus_calls() {
    struct CountingModule {
        focus_count: u32,
    }

    impl Module for CountingModule {
        fn id(&self) -> ModuleId {
            ModuleId::new("counting")
        }
        fn name(&self) -> &'static str {
            "Counting"
        }
        fn version(&self) -> Version {
            Version::new(1, 0, 0)
        }
        fn init(&mut self, _ctx: &ModuleContext) -> ProbeResult {
            ProbeResult::Success
        }
        fn exit(&mut self) -> Result<(), ModuleError> {
            Ok(())
        }
        fn on_buffer_focus(&mut self, _buffer_id: BufferId, _ctx: &ModuleContext) {
            self.focus_count += 1;
        }
    }

    let mut module = CountingModule { focus_count: 0 };
    let ctx = ModuleContext::default();

    let result = module.init(&ctx);
    assert!(matches!(result, ProbeResult::Success));

    module.on_buffer_focus(BufferId::from_raw(1), &ctx);
    module.on_buffer_focus(BufferId::from_raw(2), &ctx);
    module.on_buffer_focus(BufferId::from_raw(3), &ctx);
    assert_eq!(module.focus_count, 3);

    assert!(module.exit().is_ok());
}