synheart-sensor-agent 0.2.2

Privacy-first PC background sensor for behavioral research
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
//! Feature computation from event windows.
//!
//! This module extracts behavioral features from time windows of events.
//! All features are computed from timing and magnitude data only - never content.

use crate::collector::types::{
    KeyboardEvent, KeyboardEventType, MouseEvent, MouseEventType, ShortcutEvent,
};
use crate::core::windowing::EventWindow;
use serde::{Deserialize, Serialize};

/// Keyboard-derived behavioral features.
///
/// Note: Typing metrics (typing_rate, typing_tap_count, etc.) are computed from
/// typing keys ONLY. Navigation keys (arrows, page up/down, home/end) are tracked
/// separately via keyboard_scroll_rate to avoid inflating typing metrics during
/// navigation-heavy text editing sessions.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct KeyboardFeatures {
    /// Typing keys per second (excludes navigation keys)
    pub typing_rate: f64,
    /// Number of idle gaps (pauses) per window
    pub pause_count: u32,
    /// Average pause duration in milliseconds
    pub mean_pause_ms: f64,
    /// Standard deviation of inter-key intervals
    pub latency_variability: f64,
    /// Average key hold duration in milliseconds
    pub hold_time_mean: f64,
    /// Burstiness index (0-1, higher = more bursty)
    pub burst_index: f64,
    /// Ratio of active typing time to total window time
    pub session_continuity: f64,
    /// Total number of discrete typing tap events (excludes navigation keys)
    pub typing_tap_count: u32,
    /// Normalized rhythmic consistency score (0-1, higher = more regular timing)
    pub typing_cadence_stability: f64,
    /// Proportion of inter-tap intervals classified as gaps
    pub typing_gap_ratio: f64,
    /// Composite metric combining speed, cadence stability, and gap behavior (0-1)
    pub typing_interaction_intensity: f64,
    /// Navigation key events per second (arrow keys, page up/down, home/end)
    /// Tracked separately from typing to distinguish keyboard scrolling from mouse scrolling
    pub keyboard_scroll_rate: f64,
    /// Total navigation key events in the window
    pub navigation_key_count: u32,

    // Correction metrics
    /// Backspace key presses
    pub backspace_count: u32,
    /// Forward delete key presses
    pub delete_count: u32,
    /// (backspace + delete) / typing_tap_count (0-1+)
    pub correction_rate: f64,
    /// 1.0 - correction_rate, clamped to 0-1
    pub typing_efficiency: f64,

    // Special key counts
    /// Enter/Return key presses
    pub enter_count: u32,
    /// Tab key presses
    pub tab_count: u32,
    /// Escape key presses
    pub escape_count: u32,
    /// Modifier key events (Shift, Control, Option, Command)
    pub modifier_key_count: u32,
    /// Function key presses (F1-F12)
    pub function_key_count: u32,

    // Shortcut metrics
    /// Total shortcuts detected in the window
    pub shortcut_count: u32,
    /// Shortcuts per second
    pub shortcut_rate: f64,
}

/// Mouse-derived behavioral features.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MouseFeatures {
    /// Movement events per second
    pub mouse_activity_rate: f64,
    /// Average cursor speed (relative units)
    pub mean_velocity: f64,
    /// Standard deviation of velocity
    pub velocity_variability: f64,
    /// Count of sudden acceleration changes
    pub acceleration_spikes: u32,
    /// Clicks per window
    pub click_rate: f64,
    /// Scroll events per window
    pub scroll_rate: f64,
    /// Ratio of idle time to active time
    pub idle_ratio: f64,
    /// Ratio of small movements to total movements
    pub micro_adjustment_ratio: f64,
    /// Total idle time in milliseconds (periods with no mouse activity > 1 second)
    pub idle_time_ms: u64,
}

/// Derived behavioral signals combining keyboard and mouse data.
///
/// Metric Provenance:
/// - These signals are computed locally in the sensor agent
/// - Additional enriched signals (distraction_score, focus_hint) are computed in Flux
/// - Task switch metrics are NOT captured (requires app context, violates privacy policy)
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct BehavioralSignals {
    /// Overall interaction rhythm (regularity of input)
    pub interaction_rhythm: f64,
    /// Friction indicator (hesitation, corrections)
    pub friction: f64,
    /// Motor stability (consistency of movements)
    pub motor_stability: f64,
    /// Proxy for focus/attention continuity
    pub focus_continuity_proxy: f64,
    /// General burstiness of interactions (0-1, higher = more clustered activity)
    /// Combines keyboard burst_index and mouse activity patterns
    pub burstiness: f64,
    /// True if this window represents a deep focus block:
    /// - Continuous interaction with no idle gaps > 2 seconds
    /// - High session continuity (> 0.7)
    /// - Consistent activity throughout the window
    pub deep_focus_block: bool,
}

/// All computed features for a window.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct WindowFeatures {
    /// Keyboard-derived features (typing speed, pauses, etc.).
    pub keyboard: KeyboardFeatures,
    /// Mouse-derived features (click rate, movement speed, etc.).
    pub mouse: MouseFeatures,
    /// Cross-modal behavioural signals (burstiness, task switching, etc.).
    pub behavioral: BehavioralSignals,
}

/// Threshold for considering a gap as a "pause" (in milliseconds).
const PAUSE_THRESHOLD_MS: i64 = 500;

/// Threshold for micro-adjustments (in movement magnitude units).
const MICRO_ADJUSTMENT_THRESHOLD: f64 = 5.0;

/// Threshold for acceleration spikes (change in velocity).
const ACCELERATION_SPIKE_THRESHOLD: f64 = 50.0;

/// Compute all features from an event window.
pub fn compute_features(window: &EventWindow) -> WindowFeatures {
    let keyboard = compute_keyboard_features(
        &window.keyboard_events,
        &window.shortcut_events,
        window.duration_secs(),
    );
    let mouse = compute_mouse_features(&window.mouse_events, window.duration_secs());
    let behavioral = compute_behavioral_signals(&keyboard, &mouse);

    WindowFeatures {
        keyboard,
        mouse,
        behavioral,
    }
}

/// Compute keyboard features from a list of keyboard events and shortcut events.
///
/// Typing metrics are computed from typing key events ONLY (excludes navigation keys
/// and other special keys). Navigation keys, correction keys, and other special keys
/// are tracked separately.
fn compute_keyboard_features(
    events: &[KeyboardEvent],
    shortcuts: &[ShortcutEvent],
    window_duration: f64,
) -> KeyboardFeatures {
    if (events.is_empty() && shortcuts.is_empty()) || window_duration <= 0.0 {
        return KeyboardFeatures::default();
    }

    // Separate typing events from navigation events
    let typing_events: Vec<&KeyboardEvent> = events
        .iter()
        .filter(|e| e.event_type == KeyboardEventType::TypingTap)
        .collect();

    let navigation_events: Vec<&KeyboardEvent> = events
        .iter()
        .filter(|e| e.event_type == KeyboardEventType::NavigationKey)
        .collect();

    // Count navigation key presses (key down events only)
    let navigation_key_presses: Vec<&KeyboardEvent> = navigation_events
        .iter()
        .filter(|e| e.is_key_down)
        .copied()
        .collect();
    let navigation_key_count = navigation_key_presses.len() as u32;
    let keyboard_scroll_rate = navigation_key_count as f64 / window_duration;

    // Count special key presses (key down events only)
    let backspace_count = events
        .iter()
        .filter(|e| e.is_key_down && e.event_type == KeyboardEventType::Backspace)
        .count() as u32;
    let delete_count = events
        .iter()
        .filter(|e| e.is_key_down && e.event_type == KeyboardEventType::Delete)
        .count() as u32;
    let enter_count = events
        .iter()
        .filter(|e| e.is_key_down && e.event_type == KeyboardEventType::Enter)
        .count() as u32;
    let tab_count = events
        .iter()
        .filter(|e| e.is_key_down && e.event_type == KeyboardEventType::Tab)
        .count() as u32;
    let escape_count = events
        .iter()
        .filter(|e| e.is_key_down && e.event_type == KeyboardEventType::Escape)
        .count() as u32;
    let modifier_key_count = events
        .iter()
        .filter(|e| e.is_key_down && e.event_type == KeyboardEventType::ModifierKey)
        .count() as u32;
    let function_key_count = events
        .iter()
        .filter(|e| e.is_key_down && e.event_type == KeyboardEventType::FunctionKey)
        .count() as u32;

    // Count typing key presses (key down events only) - EXCLUDES navigation keys and special keys
    let typing_key_presses: Vec<&KeyboardEvent> = typing_events
        .iter()
        .filter(|e| e.is_key_down)
        .copied()
        .collect();
    let typing_tap_count = typing_key_presses.len() as u32;

    // Correction metrics
    let correction_rate = (backspace_count + delete_count) as f64 / typing_tap_count.max(1) as f64;
    let typing_efficiency = (1.0 - correction_rate).clamp(0.0, 1.0);

    // Shortcut metrics
    let shortcut_count = shortcuts.len() as u32;
    let shortcut_rate = shortcut_count as f64 / window_duration;

    // Typing rate (typing keys only)
    let typing_rate = typing_tap_count as f64 / window_duration;

    // Compute inter-key intervals for typing key presses only
    let intervals: Vec<i64> = typing_key_presses
        .windows(2)
        .map(|pair| (pair[1].timestamp - pair[0].timestamp).num_milliseconds())
        .collect();

    // Pause count and mean pause duration
    let pauses: Vec<i64> = intervals
        .iter()
        .filter(|&&i| i > PAUSE_THRESHOLD_MS)
        .copied()
        .collect();
    let pause_count = pauses.len() as u32;
    let mean_pause_ms = if pauses.is_empty() {
        0.0
    } else {
        pauses.iter().sum::<i64>() as f64 / pauses.len() as f64
    };

    // Latency variability (std dev of intervals)
    let latency_variability = std_dev(&intervals.iter().map(|&i| i as f64).collect::<Vec<_>>());

    // Hold time computation (requires matching key down/up pairs)
    // Only compute from typing events to avoid navigation key hold times
    let hold_times = compute_hold_times(&typing_events);
    let hold_time_mean = if hold_times.is_empty() {
        0.0
    } else {
        hold_times.iter().sum::<f64>() / hold_times.len() as f64
    };

    // Burst index: ratio of short intervals to all intervals
    // Short interval = less than 100ms (fast typing burst)
    let short_interval_count = intervals.iter().filter(|&&i| i < 100).count();
    let burst_index = if intervals.is_empty() {
        0.0
    } else {
        short_interval_count as f64 / intervals.len() as f64
    };

    // Session continuity: ratio of active time to total window time
    // Active time is sum of intervals (excluding long pauses)
    let active_intervals: Vec<i64> = intervals
        .iter()
        .filter(|&&i| i <= PAUSE_THRESHOLD_MS * 2) // Allow some breathing room
        .copied()
        .collect();
    let active_time_ms: i64 = active_intervals.iter().sum();
    let session_continuity = (active_time_ms as f64 / 1000.0) / window_duration;

    // Typing cadence stability: normalized rhythmic consistency (0-1, higher = more regular)
    // Inverse relationship with latency variability
    let typing_cadence_stability = 1.0 / (1.0 + latency_variability / 100.0);

    // Typing gap ratio: proportion of inter-tap intervals classified as gaps
    let typing_gap_ratio = if intervals.is_empty() {
        0.0
    } else {
        pause_count as f64 / intervals.len() as f64
    };

    // Typing interaction intensity: composite metric (0-1)
    // Combines normalized speed, cadence stability, and inverse gap ratio
    let normalized_speed = (typing_rate / 10.0).min(1.0); // Normalize to ~10 keys/sec max
    let typing_interaction_intensity =
        (normalized_speed * 0.4 + typing_cadence_stability * 0.3 + (1.0 - typing_gap_ratio) * 0.3)
            .clamp(0.0, 1.0);

    KeyboardFeatures {
        typing_rate,
        pause_count,
        mean_pause_ms,
        latency_variability,
        hold_time_mean,
        burst_index,
        session_continuity: session_continuity.min(1.0), // Cap at 1.0
        typing_tap_count,
        typing_cadence_stability,
        typing_gap_ratio,
        typing_interaction_intensity,
        keyboard_scroll_rate,
        navigation_key_count,
        backspace_count,
        delete_count,
        correction_rate,
        typing_efficiency,
        enter_count,
        tab_count,
        escape_count,
        modifier_key_count,
        function_key_count,
        shortcut_count,
        shortcut_rate,
    }
}

/// Estimate hold times from event sequence.
fn compute_hold_times(events: &[&KeyboardEvent]) -> Vec<f64> {
    let mut hold_times = Vec::new();
    let mut last_down: Option<&KeyboardEvent> = None;

    for event in events {
        if event.is_key_down {
            last_down = Some(event);
        } else if let Some(down) = last_down {
            let hold_ms = (event.timestamp - down.timestamp).num_milliseconds() as f64;
            // Filter out unreasonable hold times (< 20ms or > 2000ms)
            if (20.0..=2000.0).contains(&hold_ms) {
                hold_times.push(hold_ms);
            }
            last_down = None;
        }
    }

    hold_times
}

/// Compute mouse features from a list of mouse events.
fn compute_mouse_features(events: &[MouseEvent], window_duration: f64) -> MouseFeatures {
    if events.is_empty() || window_duration <= 0.0 {
        return MouseFeatures::default();
    }

    // Categorize events
    let move_events: Vec<&MouseEvent> = events
        .iter()
        .filter(|e| e.event_type == MouseEventType::Move)
        .collect();

    let click_events: Vec<&MouseEvent> = events
        .iter()
        .filter(|e| {
            e.event_type == MouseEventType::LeftClick || e.event_type == MouseEventType::RightClick
        })
        .collect();

    let scroll_events: Vec<&MouseEvent> = events
        .iter()
        .filter(|e| e.event_type == MouseEventType::Scroll)
        .collect();

    // Mouse activity rate (movements per second)
    let mouse_activity_rate = move_events.len() as f64 / window_duration;

    // Velocity statistics
    let velocities: Vec<f64> = move_events
        .iter()
        .filter_map(|e| e.delta_magnitude)
        .collect();

    let mean_velocity = if velocities.is_empty() {
        0.0
    } else {
        velocities.iter().sum::<f64>() / velocities.len() as f64
    };

    let velocity_variability = std_dev(&velocities);

    // Acceleration spikes (large changes in velocity)
    let acceleration_spikes = velocities
        .windows(2)
        .filter(|pair| (pair[1] - pair[0]).abs() > ACCELERATION_SPIKE_THRESHOLD)
        .count() as u32;

    // Click and scroll rates
    let click_rate = click_events.len() as f64 / window_duration;
    let scroll_rate = scroll_events.len() as f64 / window_duration;

    // Idle metrics: estimate based on gaps in movement events
    let (idle_ratio, idle_time_ms, _has_long_gap) =
        estimate_idle_metrics(&move_events, window_duration);

    // Micro-adjustment ratio: small movements vs all movements
    let micro_count = velocities
        .iter()
        .filter(|&&v| v < MICRO_ADJUSTMENT_THRESHOLD)
        .count();
    let micro_adjustment_ratio = if velocities.is_empty() {
        0.0
    } else {
        micro_count as f64 / velocities.len() as f64
    };

    MouseFeatures {
        mouse_activity_rate,
        mean_velocity,
        velocity_variability,
        acceleration_spikes,
        click_rate,
        scroll_rate,
        idle_ratio,
        micro_adjustment_ratio,
        idle_time_ms,
    }
}

/// Estimate idle metrics from movement event gaps.
/// Returns (idle_ratio, idle_time_ms, has_long_gap).
/// has_long_gap is true if any gap exceeds 2 seconds (used for deep focus detection).
fn estimate_idle_metrics(move_events: &[&MouseEvent], window_duration: f64) -> (f64, u64, bool) {
    if move_events.len() < 2 {
        // No movement = all idle
        let total_idle = (window_duration * 1000.0) as u64;
        return (1.0, total_idle, true);
    }

    // Consider gaps > 1 second as "idle"
    const IDLE_THRESHOLD_MS: i64 = 1000;
    // Consider gaps > 2 seconds as "long gaps" (breaks deep focus)
    const LONG_GAP_THRESHOLD_MS: i64 = 2000;

    let mut idle_time_ms: i64 = 0;
    let mut has_long_gap = false;

    for pair in move_events.windows(2) {
        let gap = (pair[1].timestamp - pair[0].timestamp).num_milliseconds();
        if gap > IDLE_THRESHOLD_MS {
            idle_time_ms += gap - IDLE_THRESHOLD_MS; // Count only the excess as idle
        }
        if gap > LONG_GAP_THRESHOLD_MS {
            has_long_gap = true;
        }
    }

    let idle_secs = idle_time_ms as f64 / 1000.0;
    let idle_ratio = (idle_secs / window_duration).min(1.0);

    (idle_ratio, idle_time_ms.max(0) as u64, has_long_gap)
}

/// Compute derived behavioral signals from keyboard and mouse features.
fn compute_behavioral_signals(
    keyboard: &KeyboardFeatures,
    mouse: &MouseFeatures,
) -> BehavioralSignals {
    // Interaction rhythm: combines typing regularity and mouse consistency
    // Lower variability = more rhythmic
    let typing_rhythm = 1.0 / (1.0 + keyboard.latency_variability / 100.0);
    let mouse_rhythm = 1.0 / (1.0 + mouse.velocity_variability / 50.0);
    let interaction_rhythm = (typing_rhythm + mouse_rhythm) / 2.0;

    // Friction: indicates hesitation, uncertainty
    // High pause rate, low burst index, many micro-adjustments, high correction rate
    let friction = (keyboard.pause_count as f64 * 0.1)
        + (1.0 - keyboard.burst_index) * 0.2
        + mouse.micro_adjustment_ratio * 0.2
        + keyboard.correction_rate.min(1.0) * 0.3;

    // Motor stability: consistency of physical movements
    // Low variability in both keyboard and mouse
    let motor_stability = 1.0
        - (keyboard.latency_variability / 200.0).min(0.5)
        - (mouse.velocity_variability / 100.0).min(0.5);

    // Focus continuity proxy: sustained activity patterns
    // High session continuity, low idle ratio
    let focus_continuity_proxy = keyboard.session_continuity * 0.5 + (1.0 - mouse.idle_ratio) * 0.5;

    // Burstiness: general measure of whether interactions occur in clusters or evenly
    // Combines keyboard burst_index with mouse activity patterns
    // High burstiness = interactions come in bursts with gaps between
    let keyboard_burstiness = keyboard.burst_index;
    // Mouse burstiness: high activity rate with high idle ratio indicates bursty behavior
    let mouse_burstiness = if mouse.mouse_activity_rate > 0.0 {
        // If there's activity but also significant idle time, it's bursty
        mouse.idle_ratio * (1.0 - mouse.micro_adjustment_ratio)
    } else {
        0.0
    };
    let burstiness = (keyboard_burstiness * 0.6 + mouse_burstiness * 0.4).clamp(0.0, 1.0);

    // Deep focus block detection:
    // - High session continuity (> 0.7) - sustained typing activity
    // - Low idle ratio (< 0.3) - minimal gaps in mouse activity
    // - Some minimum activity (typing or mouse) to confirm engagement
    let has_activity = keyboard.typing_tap_count > 0 || mouse.mouse_activity_rate > 0.5;
    let sustained_typing = keyboard.session_continuity > 0.7;
    let minimal_idle = mouse.idle_ratio < 0.3;
    let deep_focus_block = has_activity && sustained_typing && minimal_idle;

    BehavioralSignals {
        interaction_rhythm: interaction_rhythm.clamp(0.0, 1.0),
        friction: friction.clamp(0.0, 1.0),
        motor_stability: motor_stability.clamp(0.0, 1.0),
        focus_continuity_proxy: focus_continuity_proxy.clamp(0.0, 1.0),
        burstiness,
        deep_focus_block,
    }
}

/// Compute standard deviation of a slice of values.
fn std_dev(values: &[f64]) -> f64 {
    if values.len() < 2 {
        return 0.0;
    }

    let mean = values.iter().sum::<f64>() / values.len() as f64;
    let variance = values.iter().map(|&v| (v - mean).powi(2)).sum::<f64>() / values.len() as f64;
    variance.sqrt()
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::{Duration, Utc};

    fn make_keyboard_event(is_down: bool, offset_ms: i64) -> KeyboardEvent {
        KeyboardEvent {
            timestamp: Utc::now() + Duration::milliseconds(offset_ms),
            is_key_down: is_down,
            event_type: KeyboardEventType::TypingTap,
        }
    }

    fn make_navigation_event(is_down: bool, offset_ms: i64) -> KeyboardEvent {
        KeyboardEvent {
            timestamp: Utc::now() + Duration::milliseconds(offset_ms),
            is_key_down: is_down,
            event_type: KeyboardEventType::NavigationKey,
        }
    }

    #[test]
    fn test_keyboard_features_empty() {
        let features = compute_keyboard_features(&[], &[], 10.0);
        assert_eq!(features.typing_rate, 0.0);
    }

    #[test]
    fn test_keyboard_features_basic() {
        let events = vec![
            make_keyboard_event(true, 0),
            make_keyboard_event(false, 50),
            make_keyboard_event(true, 100),
            make_keyboard_event(false, 150),
            make_keyboard_event(true, 200),
            make_keyboard_event(false, 250),
        ];

        let features = compute_keyboard_features(&events, &[], 1.0);
        assert_eq!(features.typing_rate, 3.0); // 3 key presses in 1 second
    }

    #[test]
    fn test_std_dev() {
        let values = vec![2.0, 4.0, 4.0, 4.0, 5.0, 5.0, 7.0, 9.0];
        let sd = std_dev(&values);
        assert!((sd - 2.0).abs() < 0.1);
    }

    #[test]
    fn test_behavioral_signals_bounds() {
        let keyboard = KeyboardFeatures::default();
        let mouse = MouseFeatures::default();
        let signals = compute_behavioral_signals(&keyboard, &mouse);

        // All signals should be between 0 and 1
        assert!(signals.interaction_rhythm >= 0.0 && signals.interaction_rhythm <= 1.0);
        assert!(signals.friction >= 0.0 && signals.friction <= 1.0);
        assert!(signals.motor_stability >= 0.0 && signals.motor_stability <= 1.0);
        assert!(signals.focus_continuity_proxy >= 0.0 && signals.focus_continuity_proxy <= 1.0);
    }

    #[test]
    fn test_typing_tap_count() {
        let events = vec![
            make_keyboard_event(true, 0),
            make_keyboard_event(false, 50),
            make_keyboard_event(true, 100),
            make_keyboard_event(false, 150),
            make_keyboard_event(true, 200),
            make_keyboard_event(false, 250),
        ];

        let features = compute_keyboard_features(&events, &[], 1.0);
        assert_eq!(features.typing_tap_count, 3); // 3 key presses
    }

    #[test]
    fn test_typing_cadence_stability_bounds() {
        // Empty events should give default (which uses 0 variability)
        let features_empty = compute_keyboard_features(&[], &[], 10.0);
        assert!(
            features_empty.typing_cadence_stability >= 0.0
                && features_empty.typing_cadence_stability <= 1.0
        );

        // Regular typing should have high cadence stability
        let events = vec![
            make_keyboard_event(true, 0),
            make_keyboard_event(false, 50),
            make_keyboard_event(true, 100),
            make_keyboard_event(false, 150),
            make_keyboard_event(true, 200),
            make_keyboard_event(false, 250),
        ];
        let features = compute_keyboard_features(&events, &[], 1.0);
        assert!(
            features.typing_cadence_stability >= 0.0 && features.typing_cadence_stability <= 1.0
        );
        // Regular intervals should yield high stability
        assert!(features.typing_cadence_stability > 0.5);
    }

    #[test]
    fn test_typing_gap_ratio_bounds() {
        let features_empty = compute_keyboard_features(&[], &[], 10.0);
        assert_eq!(features_empty.typing_gap_ratio, 0.0);

        // Fast typing with no pauses
        let events = vec![
            make_keyboard_event(true, 0),
            make_keyboard_event(false, 50),
            make_keyboard_event(true, 100),
            make_keyboard_event(false, 150),
        ];
        let features = compute_keyboard_features(&events, &[], 1.0);
        assert!(features.typing_gap_ratio >= 0.0 && features.typing_gap_ratio <= 1.0);
        assert_eq!(features.typing_gap_ratio, 0.0); // No gaps in fast typing

        // Typing with pauses (>500ms gaps)
        let events_with_gaps = vec![
            make_keyboard_event(true, 0),
            make_keyboard_event(false, 50),
            make_keyboard_event(true, 600), // 600ms gap = pause
            make_keyboard_event(false, 650),
        ];
        let features_gaps = compute_keyboard_features(&events_with_gaps, &[], 1.0);
        assert!(features_gaps.typing_gap_ratio > 0.0); // Should have gaps
    }

    #[test]
    fn test_typing_interaction_intensity_bounds() {
        let features_empty = compute_keyboard_features(&[], &[], 10.0);
        assert!(
            features_empty.typing_interaction_intensity >= 0.0
                && features_empty.typing_interaction_intensity <= 1.0
        );

        // High intensity: fast, regular, no gaps
        let fast_events = vec![
            make_keyboard_event(true, 0),
            make_keyboard_event(false, 30),
            make_keyboard_event(true, 60),
            make_keyboard_event(false, 90),
            make_keyboard_event(true, 120),
            make_keyboard_event(false, 150),
            make_keyboard_event(true, 180),
            make_keyboard_event(false, 210),
            make_keyboard_event(true, 240),
            make_keyboard_event(false, 270),
        ];
        let features = compute_keyboard_features(&fast_events, &[], 1.0);
        assert!(
            features.typing_interaction_intensity >= 0.0
                && features.typing_interaction_intensity <= 1.0
        );
        // Fast regular typing should have moderate to high intensity
        assert!(features.typing_interaction_intensity > 0.3);
    }

    #[test]
    fn test_navigation_key_separation() {
        // Mix of typing and navigation events
        let events = vec![
            make_keyboard_event(true, 0),      // typing
            make_keyboard_event(false, 50),    // typing
            make_navigation_event(true, 100),  // navigation (arrow key)
            make_navigation_event(false, 150), // navigation
            make_keyboard_event(true, 200),    // typing
            make_keyboard_event(false, 250),   // typing
            make_navigation_event(true, 300),  // navigation
            make_navigation_event(false, 350), // navigation
        ];

        let features = compute_keyboard_features(&events, &[], 1.0);

        // Should only count typing key presses (2 typing events)
        assert_eq!(features.typing_tap_count, 2);
        assert_eq!(features.typing_rate, 2.0);

        // Should count navigation key presses separately (2 navigation events)
        assert_eq!(features.navigation_key_count, 2);
        assert_eq!(features.keyboard_scroll_rate, 2.0);
    }

    #[test]
    fn test_navigation_keys_dont_inflate_typing_metrics() {
        // Only navigation events - typing metrics should be zero/default
        let nav_only_events = vec![
            make_navigation_event(true, 0),
            make_navigation_event(false, 50),
            make_navigation_event(true, 100),
            make_navigation_event(false, 150),
            make_navigation_event(true, 200),
            make_navigation_event(false, 250),
        ];

        let features = compute_keyboard_features(&nav_only_events, &[], 1.0);

        // Typing metrics should be zero
        assert_eq!(features.typing_tap_count, 0);
        assert_eq!(features.typing_rate, 0.0);

        // Navigation metrics should be counted
        assert_eq!(features.navigation_key_count, 3);
        assert_eq!(features.keyboard_scroll_rate, 3.0);
    }

    #[test]
    fn test_keyboard_scroll_rate_bounds() {
        let features_empty = compute_keyboard_features(&[], &[], 10.0);
        assert_eq!(features_empty.keyboard_scroll_rate, 0.0);
        assert_eq!(features_empty.navigation_key_count, 0);

        // Navigation-heavy session
        let nav_events = vec![
            make_navigation_event(true, 0),
            make_navigation_event(false, 30),
            make_navigation_event(true, 60),
            make_navigation_event(false, 90),
            make_navigation_event(true, 120),
            make_navigation_event(false, 150),
        ];
        let features = compute_keyboard_features(&nav_events, &[], 1.0);
        assert_eq!(features.navigation_key_count, 3);
        assert!(features.keyboard_scroll_rate > 0.0);
    }

    #[test]
    fn test_burstiness_bounds() {
        let keyboard = KeyboardFeatures::default();
        let mouse = MouseFeatures::default();
        let signals = compute_behavioral_signals(&keyboard, &mouse);

        // Burstiness should be between 0 and 1
        assert!(signals.burstiness >= 0.0 && signals.burstiness <= 1.0);
    }

    #[test]
    fn test_burstiness_high_burst_index() {
        // High keyboard burst_index should increase burstiness
        let keyboard = KeyboardFeatures {
            burst_index: 0.9, // Very bursty typing
            ..Default::default()
        };

        let mouse = MouseFeatures::default();
        let signals = compute_behavioral_signals(&keyboard, &mouse);

        // Should have elevated burstiness
        assert!(signals.burstiness > 0.4);
        assert!(signals.burstiness <= 1.0);
    }

    #[test]
    fn test_deep_focus_block_detection() {
        // Default (empty) features should NOT be deep focus
        let keyboard = KeyboardFeatures::default();
        let mouse = MouseFeatures::default();
        let signals = compute_behavioral_signals(&keyboard, &mouse);
        assert!(!signals.deep_focus_block);

        // High continuity, low idle, some activity = deep focus
        let keyboard_active = KeyboardFeatures {
            session_continuity: 0.9, // High continuity
            typing_tap_count: 50,    // Some activity
            ..Default::default()
        };

        let mouse_active = MouseFeatures {
            idle_ratio: 0.1, // Low idle ratio
            mouse_activity_rate: 2.0,
            ..Default::default()
        };

        let signals_active = compute_behavioral_signals(&keyboard_active, &mouse_active);
        assert!(signals_active.deep_focus_block);
    }

    #[test]
    fn test_deep_focus_block_requires_low_idle() {
        // High continuity but high idle = NOT deep focus
        let keyboard = KeyboardFeatures {
            session_continuity: 0.9,
            typing_tap_count: 50,
            ..Default::default()
        };

        let mouse = MouseFeatures {
            idle_ratio: 0.5, // Too much idle time
            ..Default::default()
        };

        let signals = compute_behavioral_signals(&keyboard, &mouse);
        assert!(!signals.deep_focus_block);
    }

    #[test]
    fn test_idle_time_ms_computation() {
        use crate::collector::types::MouseEvent;

        // Test with mouse events that have gaps
        let base_time = chrono::Utc::now();
        let events = vec![
            MouseEvent {
                timestamp: base_time,
                event_type: MouseEventType::Move,
                delta_magnitude: Some(10.0),
                scroll_direction: None,
                scroll_magnitude: None,
            },
            MouseEvent {
                timestamp: base_time + chrono::Duration::milliseconds(500),
                event_type: MouseEventType::Move,
                delta_magnitude: Some(10.0),
                scroll_direction: None,
                scroll_magnitude: None,
            },
            MouseEvent {
                timestamp: base_time + chrono::Duration::milliseconds(2000), // 1500ms gap
                event_type: MouseEventType::Move,
                delta_magnitude: Some(10.0),
                scroll_direction: None,
                scroll_magnitude: None,
            },
        ];

        let features = compute_mouse_features(&events, 2.0);

        // Should have some idle time (gap of 1500ms, 500ms over threshold)
        assert!(features.idle_time_ms > 0);
        assert!(features.idle_ratio > 0.0);
    }

    #[test]
    fn test_behavioral_signals_new_fields_bounds() {
        // Test that all new behavioral signals are properly bounded
        let keyboard = KeyboardFeatures {
            burst_index: 0.5,
            session_continuity: 0.5,
            typing_tap_count: 10,
            ..Default::default()
        };

        let mouse = MouseFeatures {
            idle_ratio: 0.5,
            mouse_activity_rate: 1.0,
            ..Default::default()
        };

        let signals = compute_behavioral_signals(&keyboard, &mouse);

        // All signals should be bounded 0-1
        assert!(signals.interaction_rhythm >= 0.0 && signals.interaction_rhythm <= 1.0);
        assert!(signals.friction >= 0.0 && signals.friction <= 1.0);
        assert!(signals.motor_stability >= 0.0 && signals.motor_stability <= 1.0);
        assert!(signals.focus_continuity_proxy >= 0.0 && signals.focus_continuity_proxy <= 1.0);
        assert!(signals.burstiness >= 0.0 && signals.burstiness <= 1.0);
        // deep_focus_block is a boolean, no bounds check needed
    }

    fn make_special_key_event(
        event_type: KeyboardEventType,
        is_down: bool,
        offset_ms: i64,
    ) -> KeyboardEvent {
        KeyboardEvent {
            timestamp: Utc::now() + Duration::milliseconds(offset_ms),
            is_key_down: is_down,
            event_type,
        }
    }

    #[test]
    fn test_correction_rate_computation() {
        let events = vec![
            make_keyboard_event(true, 0),
            make_keyboard_event(false, 50),
            make_keyboard_event(true, 100),
            make_keyboard_event(false, 150),
            make_keyboard_event(true, 200),
            make_keyboard_event(false, 250),
            make_special_key_event(KeyboardEventType::Backspace, true, 300),
            make_special_key_event(KeyboardEventType::Backspace, false, 350),
        ];

        let features = compute_keyboard_features(&events, &[], 1.0);
        assert_eq!(features.typing_tap_count, 3);
        assert_eq!(features.backspace_count, 1);
        assert_eq!(features.delete_count, 0);
        // correction_rate = 1/3 ≈ 0.333
        assert!((features.correction_rate - 1.0 / 3.0).abs() < 0.01);
        assert!((features.typing_efficiency - (1.0 - 1.0 / 3.0)).abs() < 0.01);
    }

    #[test]
    fn test_correction_rate_zero_typing() {
        // Only backspace events, no typing taps
        let events = vec![
            make_special_key_event(KeyboardEventType::Backspace, true, 0),
            make_special_key_event(KeyboardEventType::Backspace, false, 50),
        ];

        let features = compute_keyboard_features(&events, &[], 1.0);
        assert_eq!(features.typing_tap_count, 0);
        assert_eq!(features.backspace_count, 1);
        // correction_rate = 1/1 (max(1) prevents division by zero) = 1.0
        assert!((features.correction_rate - 1.0).abs() < 0.01);
        assert_eq!(features.typing_efficiency, 0.0);
    }

    #[test]
    fn test_special_key_counts() {
        let events = vec![
            make_special_key_event(KeyboardEventType::Enter, true, 0),
            make_special_key_event(KeyboardEventType::Enter, false, 50),
            make_special_key_event(KeyboardEventType::Tab, true, 100),
            make_special_key_event(KeyboardEventType::Tab, false, 150),
            make_special_key_event(KeyboardEventType::Escape, true, 200),
            make_special_key_event(KeyboardEventType::Escape, false, 250),
            make_special_key_event(KeyboardEventType::ModifierKey, true, 300),
            make_special_key_event(KeyboardEventType::FunctionKey, true, 400),
            make_special_key_event(KeyboardEventType::FunctionKey, false, 450),
        ];

        let features = compute_keyboard_features(&events, &[], 1.0);
        assert_eq!(features.enter_count, 1);
        assert_eq!(features.tab_count, 1);
        assert_eq!(features.escape_count, 1);
        assert_eq!(features.modifier_key_count, 1);
        assert_eq!(features.function_key_count, 1);
        assert_eq!(features.typing_tap_count, 0); // None of these are typing taps
    }

    #[test]
    fn test_shortcut_metrics() {
        use crate::collector::types::{ShortcutEvent, ShortcutType};

        let shortcuts = vec![
            ShortcutEvent {
                timestamp: Utc::now(),
                shortcut_type: ShortcutType::Copy,
            },
            ShortcutEvent {
                timestamp: Utc::now() + Duration::milliseconds(500),
                shortcut_type: ShortcutType::Paste,
            },
        ];

        let features = compute_keyboard_features(&[], &shortcuts, 10.0);
        assert_eq!(features.shortcut_count, 2);
        assert!((features.shortcut_rate - 0.2).abs() < 0.01); // 2 shortcuts / 10s
    }

    #[test]
    fn test_friction_includes_correction_rate() {
        // With corrections, friction should be higher
        let keyboard_with_corrections = KeyboardFeatures {
            correction_rate: 0.5,
            burst_index: 0.5,
            ..Default::default()
        };

        let keyboard_without = KeyboardFeatures {
            correction_rate: 0.0,
            burst_index: 0.5,
            ..Default::default()
        };

        let mouse = MouseFeatures::default();

        let signals_with = compute_behavioral_signals(&keyboard_with_corrections, &mouse);
        let signals_without = compute_behavioral_signals(&keyboard_without, &mouse);

        assert!(signals_with.friction > signals_without.friction);
    }
}