Skip to main content

vibe/
hid.rs

1//! Inbound event record ABI for HID/sensors (T41).
2//!
3//! Defines the structured event record that inbound HID/sensor data
4//! flows through. Depth maps, EEG raw, hand skeletons must never
5//! become `List<f64>` — they need a typed record with a fat-buffer
6//! AssetRef.
7//!
8//! ## Design
9//!
10//! - [`InboundEvent`] is the top-level event record.
11//! - [`EventKind`] classifies the event (pointer, keyboard, touch,
12//!   biosignal, depth, skeleton, etc.).
13//! - [`EventPayload`] carries the event data — either inline (small)
14//!   or via an AssetRef (fat buffers like depth maps, EEG raw).
15//! - The timestamp is `u64` nanoseconds (monotonic or Unix, depending
16//!   on source).
17//!
18//! ## ABI rules
19//!
20//! - Small payloads (pointer position, key code, touch point) are
21//!   inline in the record.
22//! - Fat payloads (depth map, EEG raw, hand skeleton) are an AssetRef
23//!   — the host holds the actual data, VibeScript sees the handle.
24//! - Every event has a timestamp_ns and a source ID.
25//! - Biosignal events are capability-leased and DP-filtered (T44).
26//!
27//! Reference: `docs/vibescript-full-impl-PLAN.md` §8.9 T41.
28
29use crate::span::Span;
30use crate::value::{AssetRef, Value};
31use std::collections::BTreeMap;
32
33/// The kind of inbound event.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum EventKind {
36    /// Pointer move/button (mouse, trackpad, stylus).
37    Pointer,
38    /// Keyboard key press/release.
39    Keyboard,
40    /// Touch contact (start, move, end).
41    Touch,
42    /// Biosignal (EEG, EMG, ECG, GSR).
43    Biosignal,
44    /// Depth map (camera depth buffer).
45    Depth,
46    /// Hand/body skeleton (joint positions).
47    Skeleton,
48    /// IMU (accelerometer, gyroscope, magnetometer).
49    Imu,
50    /// Audio (raw audio samples).
51    Audio,
52    /// Generic sensor (temperature, humidity, pressure, etc.).
53    Sensor,
54    /// Assistive input (sip-and-puff, switch, Braille chord).
55    Assistive,
56    /// Gamepad / game controller buttons, thumbsticks, and triggers.
57    Gamepad,
58    /// 6-DoF Spatial Head pose (position + orientation quaternion).
59    SpatialHead,
60    /// 26-joint articulated Spatial Hand skeleton and gesture confidence.
61    SpatialHand,
62    /// Eye gaze ray, pupilometry, and vergence tracking.
63    SpatialGaze,
64    /// MIDI controller event (note on/off, control change, pitch bend).
65    Midi,
66    /// Outbound/Inbound haptic actuation and vibrotactile feedback.
67    Haptic,
68}
69
70impl EventKind {
71    /// Get the string name of this event kind.
72    pub fn as_str(&self) -> &'static str {
73        match self {
74            Self::Pointer => "pointer",
75            Self::Keyboard => "keyboard",
76            Self::Touch => "touch",
77            Self::Biosignal => "biosignal",
78            Self::Depth => "depth",
79            Self::Skeleton => "skeleton",
80            Self::Imu => "imu",
81            Self::Audio => "audio",
82            Self::Sensor => "sensor",
83            Self::Assistive => "assistive",
84            Self::Gamepad => "gamepad",
85            Self::SpatialHead => "spatial_head",
86            Self::SpatialHand => "spatial_hand",
87            Self::SpatialGaze => "spatial_gaze",
88            Self::Midi => "midi",
89            Self::Haptic => "haptic",
90        }
91    }
92
93    /// Parse from a string.
94    pub fn from_str(s: &str) -> Option<Self> {
95        match s {
96            "pointer" => Some(Self::Pointer),
97            "keyboard" => Some(Self::Keyboard),
98            "touch" => Some(Self::Touch),
99            "biosignal" => Some(Self::Biosignal),
100            "depth" => Some(Self::Depth),
101            "skeleton" => Some(Self::Skeleton),
102            "imu" => Some(Self::Imu),
103            "audio" => Some(Self::Audio),
104            "sensor" => Some(Self::Sensor),
105            "assistive" => Some(Self::Assistive),
106            "gamepad" => Some(Self::Gamepad),
107            "spatial_head" => Some(Self::SpatialHead),
108            "spatial_hand" => Some(Self::SpatialHand),
109            "spatial_gaze" => Some(Self::SpatialGaze),
110            "midi" => Some(Self::Midi),
111            "haptic" => Some(Self::Haptic),
112            _ => None,
113        }
114    }
115}
116
117/// The payload of an inbound event — either inline data or a fat
118/// buffer reference.
119#[derive(Debug, Clone)]
120pub enum EventPayload {
121    /// Empty payload (e.g. a key release with no additional data).
122    Empty,
123    /// Inline scalar values (pointer x/y, key code, touch point).
124    Inline(BTreeMap<String, Value>),
125    /// Fat buffer reference (depth map, EEG raw, skeleton data).
126    /// The host holds the actual data; VibeScript sees the AssetRef.
127    FatBuffer(AssetRef),
128}
129
130impl EventPayload {
131    /// Create an inline payload with a single key-value pair.
132    pub fn inline_kv(key: &str, val: Value) -> Self {
133        let mut m = BTreeMap::new();
134        m.insert(key.to_string(), val);
135        Self::Inline(m)
136    }
137
138    /// Create an inline payload from a slice of key-value pairs.
139    pub fn inline_pairs(pairs: &[(&str, Value)]) -> Self {
140        let mut m = BTreeMap::new();
141        for (k, v) in pairs {
142            m.insert(k.to_string(), v.clone());
143        }
144        Self::Inline(m)
145    }
146
147    /// Create a fat buffer payload.
148    pub fn fat_buffer(iri: &str, hash: u64) -> Self {
149        Self::FatBuffer(AssetRef {
150            iri: iri.to_string(),
151            hash,
152        })
153    }
154
155    /// Is this payload empty?
156    pub fn is_empty(&self) -> bool {
157        matches!(self, Self::Empty)
158    }
159
160    /// Is this payload inline?
161    pub fn is_inline(&self) -> bool {
162        matches!(self, Self::Inline(_))
163    }
164
165    /// Is this payload a fat buffer?
166    pub fn is_fat_buffer(&self) -> bool {
167        matches!(self, Self::FatBuffer(_))
168    }
169}
170
171/// An inbound event record — the structured ABI for HID/sensor data.
172///
173/// Every inbound event has:
174/// - A timestamp (nanoseconds, monotonic or Unix).
175/// - A source ID (which device/sensor produced this event).
176/// - An event kind (pointer, keyboard, touch, etc.).
177/// - A payload (inline data or fat buffer reference).
178/// - An optional capability lease ID (for biosignals and other
179///   capability-leased sources).
180#[derive(Debug, Clone)]
181pub struct InboundEvent {
182    /// Timestamp in nanoseconds (monotonic or Unix, depending on source).
183    pub timestamp_ns: u64,
184    /// Source device/sensor ID (e.g. "mouse:0", "keyboard:0", "eeg:0").
185    pub source_id: String,
186    /// The kind of event.
187    pub kind: EventKind,
188    /// The event payload (inline or fat buffer).
189    pub payload: EventPayload,
190    /// Optional capability lease ID (for biosignals and other leased sources).
191    pub capability_lease: Option<u64>,
192    /// The span where this event was triggered (if from VibeScript).
193    pub span: Span,
194}
195
196impl InboundEvent {
197    /// Create a new inbound event.
198    pub fn new(timestamp_ns: u64, source_id: &str, kind: EventKind, payload: EventPayload) -> Self {
199        Self {
200            timestamp_ns,
201            source_id: source_id.to_string(),
202            kind,
203            payload,
204            capability_lease: None,
205            span: Span::point(0),
206        }
207    }
208
209    /// Set the capability lease ID.
210    pub fn with_lease(mut self, lease_id: u64) -> Self {
211        self.capability_lease = Some(lease_id);
212        self
213    }
214
215    /// Set the span.
216    pub fn with_span(mut self, span: Span) -> Self {
217        self.span = span;
218        self
219    }
220
221    /// Convert to a VibeScript Record value.
222    pub fn to_value(&self) -> Value {
223        let mut rec = BTreeMap::new();
224        rec.insert("timestamp_ns".into(), Value::U64(self.timestamp_ns));
225        rec.insert("source_id".into(), Value::String(self.source_id.clone()));
226        rec.insert("kind".into(), Value::String(self.kind.as_str().to_string()));
227        rec.insert(
228            "payload".into(),
229            match &self.payload {
230                EventPayload::Empty => Value::Null,
231                EventPayload::Inline(m) => Value::Record(m.clone()),
232                EventPayload::FatBuffer(ar) => Value::AssetRef(ar.clone()),
233            },
234        );
235        if let Some(lease) = self.capability_lease {
236            rec.insert("capability_lease".into(), Value::U64(lease));
237        }
238        Value::Record(rec)
239    }
240
241    /// Create a pointer move event.
242    pub fn pointer_move(timestamp_ns: u64, source_id: &str, x: f64, y: f64) -> Self {
243        Self::new(
244            timestamp_ns,
245            source_id,
246            EventKind::Pointer,
247            EventPayload::inline_pairs(&[
248                ("x", Value::F64(x)),
249                ("y", Value::F64(y)),
250                ("button", Value::I64(0)), // no button
251                ("state", Value::String("move".into())),
252            ]),
253        )
254    }
255
256    /// Create a pointer button event.
257    pub fn pointer_button(
258        timestamp_ns: u64,
259        source_id: &str,
260        x: f64,
261        y: f64,
262        button: i64,
263        pressed: bool,
264    ) -> Self {
265        Self::new(
266            timestamp_ns,
267            source_id,
268            EventKind::Pointer,
269            EventPayload::inline_pairs(&[
270                ("x", Value::F64(x)),
271                ("y", Value::F64(y)),
272                ("button", Value::I64(button)),
273                (
274                    "state",
275                    Value::String(if pressed { "down" } else { "up" }.into()),
276                ),
277            ]),
278        )
279    }
280
281    /// Create a keyboard event.
282    pub fn keyboard(timestamp_ns: u64, source_id: &str, key_code: i64, pressed: bool) -> Self {
283        Self::new(
284            timestamp_ns,
285            source_id,
286            EventKind::Keyboard,
287            EventPayload::inline_pairs(&[
288                ("key_code", Value::I64(key_code)),
289                (
290                    "state",
291                    Value::String(if pressed { "down" } else { "up" }.into()),
292                ),
293            ]),
294        )
295    }
296
297    /// Create a touch event.
298    pub fn touch(
299        timestamp_ns: u64,
300        source_id: &str,
301        touch_id: i64,
302        x: f64,
303        y: f64,
304        phase: &str,
305    ) -> Self {
306        Self::new(
307            timestamp_ns,
308            source_id,
309            EventKind::Touch,
310            EventPayload::inline_pairs(&[
311                ("touch_id", Value::I64(touch_id)),
312                ("x", Value::F64(x)),
313                ("y", Value::F64(y)),
314                ("phase", Value::String(phase.into())),
315            ]),
316        )
317    }
318
319    /// Create a biosignal event (with capability lease).
320    pub fn biosignal(
321        timestamp_ns: u64,
322        source_id: &str,
323        iri: &str,
324        hash: u64,
325        lease_id: u64,
326    ) -> Self {
327        Self::new(
328            timestamp_ns,
329            source_id,
330            EventKind::Biosignal,
331            EventPayload::fat_buffer(iri, hash),
332        )
333        .with_lease(lease_id)
334    }
335
336    /// Create a depth map event (fat buffer).
337    pub fn depth(timestamp_ns: u64, source_id: &str, iri: &str, hash: u64) -> Self {
338        Self::new(
339            timestamp_ns,
340            source_id,
341            EventKind::Depth,
342            EventPayload::fat_buffer(iri, hash),
343        )
344    }
345
346    // ── T43: Assistive I/O constructors ──────────────────────────────
347
348    /// Create a sip-and-puff event (assistive input).
349    /// `strength` is 0.0–1.0 (no puff → hard puff).
350    /// `duration_ms` is the duration of the sip/puff in milliseconds.
351    pub fn sip_and_puff(
352        timestamp_ns: u64,
353        source_id: &str,
354        strength: f64,
355        duration_ms: u64,
356    ) -> Self {
357        Self::new(
358            timestamp_ns,
359            source_id,
360            EventKind::Assistive,
361            EventPayload::inline_pairs(&[
362                ("device", Value::String("sip_puff".into())),
363                ("strength", Value::F64(strength.clamp(0.0, 1.0))),
364                ("duration_ms", Value::U64(duration_ms)),
365            ]),
366        )
367    }
368
369    /// Create a switch event (assistive input — single switch, binary).
370    pub fn switch_event(timestamp_ns: u64, source_id: &str, switch_id: i64, pressed: bool) -> Self {
371        Self::new(
372            timestamp_ns,
373            source_id,
374            EventKind::Assistive,
375            EventPayload::inline_pairs(&[
376                ("device", Value::String("switch".into())),
377                ("switch_id", Value::I64(switch_id)),
378                (
379                    "state",
380                    Value::String(if pressed { "down" } else { "up" }.into()),
381                ),
382            ]),
383        )
384    }
385
386    /// Create a Braille chord event (assistive input).
387    /// `dots` is a bitmask of the 8 Braille dots (bits 0–7).
388    pub fn braille_chord(timestamp_ns: u64, source_id: &str, dots: u8) -> Self {
389        Self::new(
390            timestamp_ns,
391            source_id,
392            EventKind::Assistive,
393            EventPayload::inline_pairs(&[
394                ("device", Value::String("braille".into())),
395                ("dots", Value::I64(dots as i64)),
396            ]),
397        )
398    }
399
400    /// Create an eye-gaze event (assistive input — eye tracking).
401    pub fn eye_gaze(timestamp_ns: u64, source_id: &str, x: f64, y: f64, fixation_ms: u64) -> Self {
402        Self::new(
403            timestamp_ns,
404            source_id,
405            EventKind::Assistive,
406            EventPayload::inline_pairs(&[
407                ("device", Value::String("eye_gaze".into())),
408                ("x", Value::F64(x)),
409                ("y", Value::F64(y)),
410                ("fixation_ms", Value::U64(fixation_ms)),
411            ]),
412        )
413    }
414
415    /// Create a Gamepad event (buttons + axes).
416    pub fn gamepad(timestamp_ns: u64, source_id: &str, buttons: u32, axes: &[f64]) -> Self {
417        let axis_values: Vec<Value> = axes.iter().map(|&a| Value::F64(a)).collect();
418        Self::new(
419            timestamp_ns,
420            source_id,
421            EventKind::Gamepad,
422            EventPayload::inline_pairs(&[
423                ("buttons", Value::U64(buttons as u64)),
424                ("axes", Value::List(axis_values)),
425            ]),
426        )
427    }
428
429    /// Create a 6-DoF Spatial Head pose event.
430    pub fn spatial_head(timestamp_ns: u64, source_id: &str, pos: [f64; 3], ori: [f64; 4]) -> Self {
431        Self::new(
432            timestamp_ns,
433            source_id,
434            EventKind::SpatialHead,
435            EventPayload::inline_pairs(&[
436                ("x", Value::F64(pos[0])),
437                ("y", Value::F64(pos[1])),
438                ("z", Value::F64(pos[2])),
439                ("qx", Value::F64(ori[0])),
440                ("qy", Value::F64(ori[1])),
441                ("qz", Value::F64(ori[2])),
442                ("qw", Value::F64(ori[3])),
443            ]),
444        )
445    }
446
447    /// Create a 26-joint Spatial Hand skeleton tracking event.
448    pub fn spatial_hand(
449        timestamp_ns: u64,
450        source_id: &str,
451        is_left: bool,
452        joint_asset_iri: &str,
453        joint_asset_hash: u64,
454        pinch_confidence: f64,
455    ) -> Self {
456        let mut e = Self::new(
457            timestamp_ns,
458            source_id,
459            EventKind::SpatialHand,
460            EventPayload::fat_buffer(joint_asset_iri, joint_asset_hash),
461        );
462        if let EventPayload::Inline(ref mut m) = e.payload {
463            m.insert("is_left".into(), Value::Bool(is_left));
464            m.insert("pinch_confidence".into(), Value::F64(pinch_confidence));
465        }
466        e
467    }
468
469    /// Create a Spatial Gaze tracking ray event.
470    pub fn spatial_gaze(
471        timestamp_ns: u64,
472        source_id: &str,
473        origin: [f64; 3],
474        direction: [f64; 3],
475        pupil_dia_mm: f64,
476    ) -> Self {
477        Self::new(
478            timestamp_ns,
479            source_id,
480            EventKind::SpatialGaze,
481            EventPayload::inline_pairs(&[
482                ("ox", Value::F64(origin[0])),
483                ("oy", Value::F64(origin[1])),
484                ("oz", Value::F64(origin[2])),
485                ("dx", Value::F64(direction[0])),
486                ("dy", Value::F64(direction[1])),
487                ("dz", Value::F64(direction[2])),
488                ("pupil_diameter_mm", Value::F64(pupil_dia_mm)),
489            ]),
490        )
491    }
492
493    /// Create a MIDI controller message event.
494    pub fn midi(timestamp_ns: u64, source_id: &str, status: u8, data1: u8, data2: u8) -> Self {
495        Self::new(
496            timestamp_ns,
497            source_id,
498            EventKind::Midi,
499            EventPayload::inline_pairs(&[
500                ("status", Value::U64(status as u64)),
501                ("data1", Value::U64(data1 as u64)),
502                ("data2", Value::U64(data2 as u64)),
503            ]),
504        )
505    }
506
507    /// Create a Haptic actuation event.
508    pub fn haptic(
509        timestamp_ns: u64,
510        source_id: &str,
511        pattern: &str,
512        intensity: f64,
513        duration_ms: f64,
514    ) -> Self {
515        Self::new(
516            timestamp_ns,
517            source_id,
518            EventKind::Haptic,
519            EventPayload::inline_pairs(&[
520                ("pattern", Value::String(pattern.into())),
521                ("intensity", Value::F64(intensity.clamp(0.0, 1.0))),
522                ("duration_ms", Value::F64(duration_ms)),
523            ]),
524        )
525    }
526}
527
528/// Outbound cue kinds for assistive output (T43/T45).
529#[derive(Debug, Clone, Copy, PartialEq, Eq)]
530pub enum CueKind {
531    /// Haptic feedback (vibration, force feedback).
532    Haptic,
533    /// Audio cue (tone, earcon, speech).
534    Audio,
535    /// Visual cue (flash, border highlight).
536    Visual,
537    /// Accessibility cue (screen reader announcement, Braille output).
538    Accessibility,
539}
540
541impl CueKind {
542    /// `str` form.
543    pub fn as_str(&self) -> &'static str {
544        match self {
545            Self::Haptic => "Haptic",
546            Self::Audio => "Audio",
547            Self::Visual => "Visual",
548            Self::Accessibility => "Accessibility",
549        }
550    }
551
552    /// Constructs from str.
553    pub fn from_str(s: &str) -> Option<Self> {
554        match s {
555            "Haptic" => Some(Self::Haptic),
556            "Audio" => Some(Self::Audio),
557            "Visual" => Some(Self::Visual),
558            "Accessibility" => Some(Self::Accessibility),
559            _ => None,
560        }
561    }
562}
563
564/// An outbound cue — haptic, audio, visual, or accessibility output.
565#[derive(Debug, Clone)]
566pub struct OutboundCue {
567    /// The cue kind.
568    pub kind: CueKind,
569    /// The cue name (e.g. "Haptic.buzz", "Audio.earcon.success",
570    /// "Accessibility.announce", "Visual.flash").
571    pub name: String,
572    /// The cue payload (inline parameters).
573    pub payload: BTreeMap<String, Value>,
574}
575
576impl OutboundCue {
577    /// Create a haptic buzz cue.
578    pub fn haptic_buzz(duration_ms: u64, strength: f64) -> Self {
579        let mut payload = BTreeMap::new();
580        payload.insert("duration_ms".into(), Value::U64(duration_ms));
581        payload.insert("strength".into(), Value::F64(strength.clamp(0.0, 1.0)));
582        Self {
583            kind: CueKind::Haptic,
584            name: "Haptic.buzz".into(),
585            payload,
586        }
587    }
588
589    /// Create an audio earcon cue.
590    pub fn audio_earcon(earcon_id: &str) -> Self {
591        let mut payload = BTreeMap::new();
592        payload.insert("earcon_id".into(), Value::String(earcon_id.into()));
593        Self {
594            kind: CueKind::Audio,
595            name: "Audio.earcon".into(),
596            payload,
597        }
598    }
599
600    /// Create a screen reader announcement cue.
601    pub fn accessibility_announce(message: &str) -> Self {
602        let mut payload = BTreeMap::new();
603        payload.insert("message".into(), Value::String(message.into()));
604        Self {
605            kind: CueKind::Accessibility,
606            name: "Accessibility.announce".into(),
607            payload,
608        }
609    }
610
611    /// Create a visual flash cue.
612    pub fn visual_flash(color: &str, duration_ms: u64) -> Self {
613        let mut payload = BTreeMap::new();
614        payload.insert("color".into(), Value::String(color.into()));
615        payload.insert("duration_ms".into(), Value::U64(duration_ms));
616        Self {
617            kind: CueKind::Visual,
618            name: "Visual.flash".into(),
619            payload,
620        }
621    }
622
623    /// Convert to a VibeScript cue.post argument value.
624    pub fn to_value(&self) -> Value {
625        let mut rec = BTreeMap::new();
626        rec.insert("kind".into(), Value::String(self.kind.as_str().into()));
627        rec.insert("name".into(), Value::String(self.name.clone()));
628        rec.insert("payload".into(), Value::Record(self.payload.clone()));
629        Value::Record(rec)
630    }
631
632    /// Get the cue ID string for cue.post (e.g. "Haptic.buzz").
633    pub fn cue_id(&self) -> &str {
634        &self.name
635    }
636}
637
638#[cfg(test)]
639mod tests {
640    use super::*;
641
642    #[test]
643    fn event_kind_as_str() {
644        assert_eq!(EventKind::Pointer.as_str(), "pointer");
645        assert_eq!(EventKind::Keyboard.as_str(), "keyboard");
646        assert_eq!(EventKind::Touch.as_str(), "touch");
647        assert_eq!(EventKind::Biosignal.as_str(), "biosignal");
648        assert_eq!(EventKind::Depth.as_str(), "depth");
649    }
650
651    #[test]
652    fn event_kind_from_str() {
653        assert_eq!(EventKind::from_str("pointer"), Some(EventKind::Pointer));
654        assert_eq!(EventKind::from_str("keyboard"), Some(EventKind::Keyboard));
655        assert_eq!(EventKind::from_str("touch"), Some(EventKind::Touch));
656        assert_eq!(EventKind::from_str("biosignal"), Some(EventKind::Biosignal));
657        assert_eq!(EventKind::from_str("depth"), Some(EventKind::Depth));
658        assert_eq!(EventKind::from_str("unknown"), None);
659    }
660
661    #[test]
662    fn event_kind_round_trip() {
663        for kind in [
664            EventKind::Pointer,
665            EventKind::Keyboard,
666            EventKind::Touch,
667            EventKind::Biosignal,
668            EventKind::Depth,
669            EventKind::Skeleton,
670            EventKind::Imu,
671            EventKind::Audio,
672            EventKind::Sensor,
673            EventKind::Assistive,
674            EventKind::Gamepad,
675            EventKind::SpatialHead,
676            EventKind::SpatialHand,
677            EventKind::SpatialGaze,
678            EventKind::Midi,
679            EventKind::Haptic,
680        ] {
681            let s = kind.as_str();
682            assert_eq!(EventKind::from_str(s), Some(kind));
683        }
684    }
685
686    #[test]
687    fn inbound_event_gamepad_and_spatial() {
688        let g = InboundEvent::gamepad(1000, "gamepad:0", 0b0011, &[0.5, -0.5]);
689        assert_eq!(g.kind, EventKind::Gamepad);
690        assert!(g.payload.is_inline());
691
692        let h = InboundEvent::spatial_head(2000, "xr:head", [0.0, 1.7, -0.5], [0.0, 0.0, 0.0, 1.0]);
693        assert_eq!(h.kind, EventKind::SpatialHead);
694
695        let gaze =
696            InboundEvent::spatial_gaze(3000, "xr:eye", [0.0, 1.6, 0.0], [0.0, 0.0, -1.0], 3.5);
697        assert_eq!(gaze.kind, EventKind::SpatialGaze);
698
699        let m = InboundEvent::midi(4000, "midi:0", 0x90, 60, 127);
700        assert_eq!(m.kind, EventKind::Midi);
701
702        let hap = InboundEvent::haptic(5000, "haptic:0", "buzz", 0.8, 150.0);
703        assert_eq!(hap.kind, EventKind::Haptic);
704    }
705
706    #[test]
707    fn payload_empty() {
708        let p = EventPayload::Empty;
709        assert!(p.is_empty());
710        assert!(!p.is_inline());
711        assert!(!p.is_fat_buffer());
712    }
713
714    #[test]
715    fn payload_inline() {
716        let p = EventPayload::inline_kv("x", Value::F64(1.0));
717        assert!(p.is_inline());
718        assert!(!p.is_empty());
719        assert!(!p.is_fat_buffer());
720    }
721
722    #[test]
723    fn payload_fat_buffer() {
724        let p = EventPayload::fat_buffer("asset:eeg:0", 123);
725        assert!(p.is_fat_buffer());
726        assert!(!p.is_empty());
727        assert!(!p.is_inline());
728    }
729
730    #[test]
731    fn inbound_event_pointer_move() {
732        let e = InboundEvent::pointer_move(1000, "mouse:0", 10.5, 20.5);
733        assert_eq!(e.timestamp_ns, 1000);
734        assert_eq!(e.source_id, "mouse:0");
735        assert_eq!(e.kind, EventKind::Pointer);
736        assert!(e.payload.is_inline());
737        assert!(e.capability_lease.is_none());
738    }
739
740    #[test]
741    fn inbound_event_pointer_button() {
742        let e = InboundEvent::pointer_button(2000, "mouse:0", 10.0, 20.0, 1, true);
743        assert_eq!(e.kind, EventKind::Pointer);
744        assert!(e.payload.is_inline());
745    }
746
747    #[test]
748    fn inbound_event_keyboard() {
749        let e = InboundEvent::keyboard(3000, "keyboard:0", 65, true);
750        assert_eq!(e.kind, EventKind::Keyboard);
751        assert_eq!(e.source_id, "keyboard:0");
752        assert!(e.payload.is_inline());
753    }
754
755    #[test]
756    fn inbound_event_touch() {
757        let e = InboundEvent::touch(4000, "touch:0", 0, 100.0, 200.0, "start");
758        assert_eq!(e.kind, EventKind::Touch);
759        assert!(e.payload.is_inline());
760    }
761
762    #[test]
763    fn inbound_event_biosignal_has_lease() {
764        let e = InboundEvent::biosignal(5000, "eeg:0", "asset:eeg:raw", 999, 42);
765        assert_eq!(e.kind, EventKind::Biosignal);
766        assert!(e.payload.is_fat_buffer());
767        assert_eq!(e.capability_lease, Some(42));
768    }
769
770    #[test]
771    fn inbound_event_depth_is_fat_buffer() {
772        let e = InboundEvent::depth(6000, "depth:0", "asset:depth:0", 777);
773        assert_eq!(e.kind, EventKind::Depth);
774        assert!(e.payload.is_fat_buffer());
775        assert!(e.capability_lease.is_none());
776    }
777
778    #[test]
779    fn inbound_event_to_value() {
780        let e = InboundEvent::pointer_move(1000, "mouse:0", 10.5, 20.5);
781        let v = e.to_value();
782        let rec = match &v {
783            Value::Record(r) => r,
784            _ => panic!("expected Record"),
785        };
786        assert_eq!(
787            match rec.get("timestamp_ns").unwrap() {
788                Value::U64(n) => *n,
789                _ => panic!("expected U64"),
790            },
791            1000
792        );
793        assert_eq!(
794            match rec.get("source_id").unwrap() {
795                Value::String(s) => s.as_str(),
796                _ => panic!("expected String"),
797            },
798            "mouse:0"
799        );
800        assert_eq!(
801            match rec.get("kind").unwrap() {
802                Value::String(s) => s.as_str(),
803                _ => panic!("expected String"),
804            },
805            "pointer"
806        );
807    }
808
809    #[test]
810    fn inbound_event_to_value_with_lease() {
811        let e = InboundEvent::biosignal(5000, "eeg:0", "asset:eeg:raw", 999, 42);
812        let v = e.to_value();
813        let rec = match &v {
814            Value::Record(r) => r,
815            _ => panic!("expected Record"),
816        };
817        assert_eq!(
818            match rec.get("capability_lease").unwrap() {
819                Value::U64(n) => *n,
820                _ => panic!("expected U64"),
821            },
822            42
823        );
824    }
825
826    #[test]
827    fn inbound_event_to_value_fat_buffer() {
828        let e = InboundEvent::depth(6000, "depth:0", "asset:depth:0", 777);
829        let v = e.to_value();
830        let rec = match &v {
831            Value::Record(r) => r,
832            _ => panic!("expected Record"),
833        };
834        let payload = rec.get("payload").unwrap();
835        assert!(payload.as_asset_ref().is_some());
836    }
837
838    #[test]
839    fn inbound_event_with_lease_builder() {
840        let e = InboundEvent::keyboard(1000, "kb:0", 65, true).with_lease(99);
841        assert_eq!(e.capability_lease, Some(99));
842    }
843
844    #[test]
845    fn inbound_event_with_span_builder() {
846        let e = InboundEvent::keyboard(1000, "kb:0", 65, true).with_span(Span::new(10, 20));
847        assert_eq!(e.span.start, 10);
848        assert_eq!(e.span.end, 20);
849    }
850
851    #[test]
852    fn payload_inline_pairs() {
853        let p = EventPayload::inline_pairs(&[
854            ("a", Value::I64(1)),
855            ("b", Value::F64(2.0)),
856            ("c", Value::String("hi".into())),
857        ]);
858        assert!(p.is_inline());
859        if let EventPayload::Inline(m) = p {
860            assert_eq!(m.len(), 3);
861        }
862    }
863
864    // ── T43: Assistive I/O tests ─────────────────────────────────────
865
866    #[test]
867    fn t43_sip_and_puff_event() {
868        let e = InboundEvent::sip_and_puff(1000, "sip_puff:0", 0.7, 200);
869        assert_eq!(e.kind, EventKind::Assistive);
870        assert!(e.payload.is_inline());
871        if let EventPayload::Inline(m) = &e.payload {
872            assert_eq!(
873                match m.get("device").unwrap() {
874                    Value::String(s) => s.as_str(),
875                    _ => panic!("expected String"),
876                },
877                "sip_puff"
878            );
879            assert_eq!(
880                match m.get("strength").unwrap() {
881                    Value::F64(f) => *f,
882                    _ => panic!("expected F64"),
883                },
884                0.7
885            );
886        }
887    }
888
889    #[test]
890    fn t43_sip_and_puff_clamps_strength() {
891        let e = InboundEvent::sip_and_puff(1000, "sip_puff:0", 1.5, 100);
892        if let EventPayload::Inline(m) = &e.payload {
893            assert_eq!(
894                match m.get("strength").unwrap() {
895                    Value::F64(f) => *f,
896                    _ => panic!("expected F64"),
897                },
898                1.0
899            ); // clamped
900        }
901    }
902
903    #[test]
904    fn t43_switch_event() {
905        let e = InboundEvent::switch_event(2000, "switch:0", 1, true);
906        assert_eq!(e.kind, EventKind::Assistive);
907        if let EventPayload::Inline(m) = &e.payload {
908            assert_eq!(
909                match m.get("switch_id").unwrap() {
910                    Value::I64(n) => *n,
911                    _ => panic!("expected I64"),
912                },
913                1
914            );
915            assert_eq!(
916                match m.get("state").unwrap() {
917                    Value::String(s) => s.as_str(),
918                    _ => panic!("expected String"),
919                },
920                "down"
921            );
922        }
923    }
924
925    #[test]
926    fn t43_braille_chord_event() {
927        let e = InboundEvent::braille_chord(3000, "braille:0", 0b00010111);
928        assert_eq!(e.kind, EventKind::Assistive);
929        if let EventPayload::Inline(m) = &e.payload {
930            assert_eq!(
931                match m.get("dots").unwrap() {
932                    Value::I64(n) => *n,
933                    _ => panic!("expected I64"),
934                },
935                0b00010111
936            );
937        }
938    }
939
940    #[test]
941    fn t43_eye_gaze_event() {
942        let e = InboundEvent::eye_gaze(4000, "eye:0", 150.0, 200.0, 500);
943        assert_eq!(e.kind, EventKind::Assistive);
944        if let EventPayload::Inline(m) = &e.payload {
945            assert_eq!(
946                match m.get("device").unwrap() {
947                    Value::String(s) => s.as_str(),
948                    _ => panic!("expected String"),
949                },
950                "eye_gaze"
951            );
952            assert_eq!(
953                match m.get("fixation_ms").unwrap() {
954                    Value::U64(n) => *n,
955                    _ => panic!("expected U64"),
956                },
957                500
958            );
959        }
960    }
961
962    #[test]
963    fn t43_cue_kind_round_trip() {
964        for kind in [
965            CueKind::Haptic,
966            CueKind::Audio,
967            CueKind::Visual,
968            CueKind::Accessibility,
969        ] {
970            let s = kind.as_str();
971            assert_eq!(CueKind::from_str(s), Some(kind));
972        }
973    }
974
975    #[test]
976    fn t43_haptic_buzz_cue() {
977        let cue = OutboundCue::haptic_buzz(100, 0.5);
978        assert_eq!(cue.kind, CueKind::Haptic);
979        assert_eq!(cue.cue_id(), "Haptic.buzz");
980        assert_eq!(cue.payload.len(), 2);
981    }
982
983    #[test]
984    fn t43_audio_earcon_cue() {
985        let cue = OutboundCue::audio_earcon("success");
986        assert_eq!(cue.kind, CueKind::Audio);
987        assert_eq!(cue.cue_id(), "Audio.earcon");
988    }
989
990    #[test]
991    fn t43_accessibility_announce_cue() {
992        let cue = OutboundCue::accessibility_announce("Form submitted");
993        assert_eq!(cue.kind, CueKind::Accessibility);
994        assert_eq!(cue.cue_id(), "Accessibility.announce");
995        if let Value::String(s) = cue.payload.get("message").unwrap() {
996            assert_eq!(s, "Form submitted");
997        }
998    }
999
1000    #[test]
1001    fn t43_visual_flash_cue() {
1002        let cue = OutboundCue::visual_flash("red", 200);
1003        assert_eq!(cue.kind, CueKind::Visual);
1004        assert_eq!(cue.cue_id(), "Visual.flash");
1005    }
1006
1007    #[test]
1008    fn t43_cue_to_value() {
1009        let cue = OutboundCue::haptic_buzz(100, 0.5);
1010        let v = cue.to_value();
1011        let rec = match &v {
1012            Value::Record(r) => r,
1013            _ => panic!("expected Record"),
1014        };
1015        assert_eq!(
1016            match rec.get("kind").unwrap() {
1017                Value::String(s) => s.as_str(),
1018                _ => panic!("expected String"),
1019            },
1020            "Haptic"
1021        );
1022        assert_eq!(
1023            match rec.get("name").unwrap() {
1024                Value::String(s) => s.as_str(),
1025                _ => panic!("expected String"),
1026            },
1027            "Haptic.buzz"
1028        );
1029    }
1030
1031    #[test]
1032    fn t43_haptic_buzz_clamps_strength() {
1033        let cue = OutboundCue::haptic_buzz(100, 2.0);
1034        if let Value::F64(f) = cue.payload.get("strength").unwrap() {
1035            assert_eq!(*f, 1.0); // clamped
1036        }
1037    }
1038}