Skip to main content

fyi_core/
event.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Deserializer, Serialize, Serializer};
3use std::fmt;
4use std::str::FromStr;
5
6/// Event types for Claude Code hooks and API requests.
7///
8/// Known event types are represented as enum variants for type safety.
9/// Unknown event types (from future Claude Code versions) are captured
10/// as `Custom(String)` to ensure forward compatibility.
11#[derive(Debug, Clone, PartialEq, Eq, Hash)]
12pub enum EventType {
13    /// Session begins
14    SessionStart,
15    /// Session ends
16    SessionEnd,
17    /// Before tool execution
18    PreToolUse,
19    /// After tool execution
20    PostToolUse,
21    /// User permission requested
22    PermissionRequest,
23    /// Before context compaction
24    PreCompact,
25    /// Execution stopped
26    Stop,
27    /// Subagent stopped
28    SubagentStop,
29    /// System notification
30    Notification,
31    /// User submitted prompt
32    UserPromptSubmit,
33    /// API request (from OpenTelemetry)
34    ApiRequest,
35    /// Unknown/future event type (forward compatibility)
36    Custom(String),
37}
38
39impl EventType {
40    /// Returns the canonical string representation of the event type.
41    pub fn as_str(&self) -> &str {
42        match self {
43            EventType::SessionStart => "SessionStart",
44            EventType::SessionEnd => "SessionEnd",
45            EventType::PreToolUse => "PreToolUse",
46            EventType::PostToolUse => "PostToolUse",
47            EventType::PermissionRequest => "PermissionRequest",
48            EventType::PreCompact => "PreCompact",
49            EventType::Stop => "Stop",
50            EventType::SubagentStop => "SubagentStop",
51            EventType::Notification => "Notification",
52            EventType::UserPromptSubmit => "UserPromptSubmit",
53            EventType::ApiRequest => "ApiRequest",
54            EventType::Custom(s) => s.as_str(),
55        }
56    }
57
58    /// Returns true if this is a known (non-custom) event type.
59    pub fn is_known(&self) -> bool {
60        !matches!(self, EventType::Custom(_))
61    }
62}
63
64impl fmt::Display for EventType {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        write!(f, "{}", self.as_str())
67    }
68}
69
70impl FromStr for EventType {
71    type Err = std::convert::Infallible;
72
73    /// Parse an event type string (case-insensitive for known types).
74    /// Unknown strings become `Custom(String)`.
75    fn from_str(s: &str) -> Result<Self, Self::Err> {
76        // Trim whitespace and use case-insensitive matching for known types
77        let trimmed = s.trim();
78        Ok(match trimmed.to_ascii_lowercase().as_str() {
79            "sessionstart" => EventType::SessionStart,
80            "sessionend" => EventType::SessionEnd,
81            "pretooluse" => EventType::PreToolUse,
82            "posttooluse" => EventType::PostToolUse,
83            "permissionrequest" => EventType::PermissionRequest,
84            "precompact" => EventType::PreCompact,
85            "stop" => EventType::Stop,
86            "subagentstop" => EventType::SubagentStop,
87            "notification" => EventType::Notification,
88            "userpromptsubmit" => EventType::UserPromptSubmit,
89            "apirequest" => EventType::ApiRequest,
90            _ => EventType::Custom(trimmed.to_string()),
91        })
92    }
93}
94
95impl Serialize for EventType {
96    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
97    where
98        S: Serializer,
99    {
100        serializer.serialize_str(self.as_str())
101    }
102}
103
104impl<'de> Deserialize<'de> for EventType {
105    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
106    where
107        D: Deserializer<'de>,
108    {
109        let s = String::deserialize(deserializer)?;
110        // FromStr is infallible, so this always succeeds
111        Ok(s.parse().unwrap())
112    }
113}
114
115/// A hook event captured from Claude Code
116#[derive(Debug, Clone, Serialize, Deserialize)]
117pub struct Event {
118    /// Database ID (None for new events)
119    #[serde(skip_serializing_if = "Option::is_none")]
120    pub id: Option<i64>,
121
122    /// Machine identifier for multi-machine sync
123    pub machine_id: String,
124
125    /// Event timestamp
126    #[serde(with = "timestamp_millis")]
127    pub timestamp: DateTime<Utc>,
128
129    /// Event type (SessionStart, PreToolUse, etc.)
130    pub event_type: EventType,
131
132    /// Session ID from Claude Code
133    pub session_id: String,
134
135    /// Source framework (claude, cursor, gemini, etc.)
136    #[serde(skip_serializing_if = "Option::is_none")]
137    pub framework: Option<String>,
138
139    /// Tool use ID for correlating PreToolUse/PostToolUse
140    #[serde(skip_serializing_if = "Option::is_none")]
141    pub tool_use_id: Option<String>,
142
143    /// Child agent ID from PostToolUse for Task tool (links parent → child sessions)
144    #[serde(skip_serializing_if = "Option::is_none")]
145    pub spawned_agent_id: Option<String>,
146
147    /// Tool name (Bash, Read, Write, Edit, Task, etc.)
148    #[serde(skip_serializing_if = "Option::is_none")]
149    pub tool_name: Option<String>,
150
151    /// Subagent type for Task tool (Explore, Plan, claude-code-guide, etc.)
152    #[serde(skip_serializing_if = "Option::is_none")]
153    pub subagent_type: Option<String>,
154
155    /// Permission mode (default, plan, acceptEdits, bypassPermissions)
156    #[serde(skip_serializing_if = "Option::is_none")]
157    pub permission_mode: Option<String>,
158
159    /// Path to the session transcript JSONL file
160    #[serde(skip_serializing_if = "Option::is_none")]
161    pub transcript_path: Option<String>,
162
163    /// Parent process ID
164    #[serde(skip_serializing_if = "Option::is_none")]
165    pub pid: Option<i32>,
166
167    /// Working directory
168    #[serde(skip_serializing_if = "Option::is_none")]
169    pub cwd: Option<String>,
170
171    // API request fields (NULL for hook events, populated for ApiRequest events)
172    /// Model used for API request (e.g., "claude-3-opus")
173    #[serde(skip_serializing_if = "Option::is_none")]
174    pub model: Option<String>,
175
176    /// Input tokens used
177    #[serde(skip_serializing_if = "Option::is_none")]
178    pub tokens_input: Option<i64>,
179
180    /// Output tokens generated
181    #[serde(skip_serializing_if = "Option::is_none")]
182    pub tokens_output: Option<i64>,
183
184    /// Tokens read from cache
185    #[serde(skip_serializing_if = "Option::is_none")]
186    pub tokens_cache_read: Option<i64>,
187
188    /// Tokens written to cache
189    #[serde(skip_serializing_if = "Option::is_none")]
190    pub tokens_cache_creation: Option<i64>,
191
192    /// Cost in USD
193    #[serde(skip_serializing_if = "Option::is_none")]
194    pub cost_usd: Option<f64>,
195
196    /// API call duration in milliseconds
197    #[serde(skip_serializing_if = "Option::is_none")]
198    pub duration_ms: Option<i64>,
199
200    /// JSON payload with all hook data
201    #[serde(skip_serializing_if = "Option::is_none")]
202    pub payload: Option<String>,
203
204    /// Extensible JSON metadata for future fields
205    #[serde(skip_serializing_if = "Option::is_none")]
206    pub metadata: Option<String>,
207}
208
209impl Event {
210    /// Create a new event with current timestamp
211    pub fn new(machine_id: String, event_type: EventType, session_id: String) -> Self {
212        Self {
213            id: None,
214            machine_id,
215            timestamp: Utc::now(),
216            event_type,
217            session_id,
218            framework: None,
219            tool_use_id: None,
220            spawned_agent_id: None,
221            tool_name: None,
222            subagent_type: None,
223            permission_mode: None,
224            transcript_path: None,
225            pid: None,
226            cwd: None,
227            model: None,
228            tokens_input: None,
229            tokens_output: None,
230            tokens_cache_read: None,
231            tokens_cache_creation: None,
232            cost_usd: None,
233            duration_ms: None,
234            payload: None,
235            metadata: None,
236        }
237    }
238
239    /// Check if this event is an API request (has token data)
240    pub fn is_api_request(&self) -> bool {
241        self.tokens_input.is_some() || self.tokens_output.is_some()
242    }
243
244    /// Total tokens (input + output) for API requests
245    pub fn total_tokens(&self) -> i64 {
246        self.tokens_input.unwrap_or(0) + self.tokens_output.unwrap_or(0)
247    }
248
249    pub fn with_framework(mut self, framework: Option<String>) -> Self {
250        self.framework = framework;
251        self
252    }
253
254    pub fn with_tool_use_id(mut self, tool_use_id: Option<String>) -> Self {
255        self.tool_use_id = tool_use_id;
256        self
257    }
258
259    pub fn with_spawned_agent_id(mut self, spawned_agent_id: Option<String>) -> Self {
260        self.spawned_agent_id = spawned_agent_id;
261        self
262    }
263
264    pub fn with_tool_name(mut self, tool_name: Option<String>) -> Self {
265        self.tool_name = tool_name;
266        self
267    }
268
269    pub fn with_subagent_type(mut self, subagent_type: Option<String>) -> Self {
270        self.subagent_type = subagent_type;
271        self
272    }
273
274    pub fn with_permission_mode(mut self, permission_mode: Option<String>) -> Self {
275        self.permission_mode = permission_mode;
276        self
277    }
278
279    pub fn with_transcript_path(mut self, transcript_path: Option<String>) -> Self {
280        self.transcript_path = transcript_path;
281        self
282    }
283
284    pub fn with_pid(mut self, pid: Option<i32>) -> Self {
285        self.pid = pid;
286        self
287    }
288
289    pub fn with_cwd(mut self, cwd: Option<String>) -> Self {
290        self.cwd = cwd;
291        self
292    }
293
294    pub fn with_model(mut self, model: Option<String>) -> Self {
295        self.model = model;
296        self
297    }
298
299    pub fn with_tokens_input(mut self, tokens_input: Option<i64>) -> Self {
300        self.tokens_input = tokens_input;
301        self
302    }
303
304    pub fn with_tokens_output(mut self, tokens_output: Option<i64>) -> Self {
305        self.tokens_output = tokens_output;
306        self
307    }
308
309    pub fn with_tokens_cache_read(mut self, tokens_cache_read: Option<i64>) -> Self {
310        self.tokens_cache_read = tokens_cache_read;
311        self
312    }
313
314    pub fn with_tokens_cache_creation(mut self, tokens_cache_creation: Option<i64>) -> Self {
315        self.tokens_cache_creation = tokens_cache_creation;
316        self
317    }
318
319    pub fn with_cost_usd(mut self, cost_usd: Option<f64>) -> Self {
320        self.cost_usd = cost_usd;
321        self
322    }
323
324    pub fn with_duration_ms(mut self, duration_ms: Option<i64>) -> Self {
325        self.duration_ms = duration_ms;
326        self
327    }
328
329    pub fn with_payload(mut self, payload: Option<String>) -> Self {
330        self.payload = payload;
331        self
332    }
333
334    pub fn with_metadata(mut self, metadata: Option<String>) -> Self {
335        self.metadata = metadata;
336        self
337    }
338
339    /// Set the timestamp (useful for testing)
340    pub fn with_timestamp(mut self, timestamp: DateTime<Utc>) -> Self {
341        self.timestamp = timestamp;
342        self
343    }
344}
345
346/// Builder for creating Event instances with an ergonomic API.
347///
348/// Provides helper methods that group related fields together and accept
349/// non-Option values directly, reducing verbosity compared to chained `with_*` calls.
350///
351/// # Method variants
352///
353/// - **Regular setters** (e.g., `framework()`, `model()`) accept values directly and always
354///   set the field.
355/// - **Optional setters** (e.g., `framework_opt()`, `model_opt()`) accept `Option<T>` and
356///   only set the field if `Some` is passed; `None` preserves any previously set value.
357/// - **Grouped helpers** (e.g., `tokens()`, `cache_tokens()`, `tool()`) set multiple related
358///   fields at once for common patterns.
359///
360/// # Example
361///
362/// ```
363/// use fyi_core::{EventBuilder, EventType};
364///
365/// // Building an API request event
366/// let event = EventBuilder::new("machine-1", EventType::ApiRequest, "session-123")
367///     .framework("claude")
368///     .tokens(1000, 500)
369///     .cache_tokens(200, 0)
370///     .cost(0.05)
371///     .model("claude-3-opus")
372///     .build();
373///
374/// // Building a hook event
375/// let event = EventBuilder::new("machine-1", EventType::PreToolUse, "session-123")
376///     .framework("claude")
377///     .tool("toolu_123", "Bash")
378///     .payload(r#"{"command": "ls"}"#)
379///     .build();
380///
381/// // Using _opt methods to conditionally set fields
382/// let maybe_model: Option<String> = Some("claude-3-opus".to_string());
383/// let event = EventBuilder::new("machine-1", EventType::ApiRequest, "session-123")
384///     .model_opt(maybe_model)  // Sets model to "claude-3-opus"
385///     .model_opt(None)         // Does nothing, preserves "claude-3-opus"
386///     .build();
387/// ```
388#[derive(Debug, Clone)]
389pub struct EventBuilder {
390    event: Event,
391}
392
393impl EventBuilder {
394    /// Create a new EventBuilder with required fields.
395    ///
396    /// The timestamp is set to the current time; use `timestamp()` to override.
397    pub fn new(
398        machine_id: impl Into<String>,
399        event_type: EventType,
400        session_id: impl Into<String>,
401    ) -> Self {
402        Self {
403            event: Event::new(machine_id.into(), event_type, session_id.into()),
404        }
405    }
406
407    /// Build the final Event.
408    pub fn build(self) -> Event {
409        self.event
410    }
411
412    // --- Grouped helper methods ---
413
414    /// Set input and output tokens together.
415    pub fn tokens(mut self, input: i64, output: i64) -> Self {
416        self.event.tokens_input = Some(input);
417        self.event.tokens_output = Some(output);
418        self
419    }
420
421    /// Set cache read and cache creation tokens together.
422    pub fn cache_tokens(mut self, read: i64, creation: i64) -> Self {
423        self.event.tokens_cache_read = Some(read);
424        self.event.tokens_cache_creation = Some(creation);
425        self
426    }
427
428    /// Set tool_use_id and tool_name together (common for tool events).
429    pub fn tool(mut self, tool_use_id: impl Into<String>, tool_name: impl Into<String>) -> Self {
430        self.event.tool_use_id = Some(tool_use_id.into());
431        self.event.tool_name = Some(tool_name.into());
432        self
433    }
434
435    // --- Individual field setters (non-Option convenience) ---
436
437    /// Set the framework.
438    pub fn framework(mut self, framework: impl Into<String>) -> Self {
439        self.event.framework = Some(framework.into());
440        self
441    }
442
443    /// Set the model.
444    pub fn model(mut self, model: impl Into<String>) -> Self {
445        self.event.model = Some(model.into());
446        self
447    }
448
449    /// Set the cost in USD.
450    pub fn cost(mut self, cost_usd: f64) -> Self {
451        self.event.cost_usd = Some(cost_usd);
452        self
453    }
454
455    /// Set the duration in milliseconds.
456    pub fn duration_ms(mut self, duration: i64) -> Self {
457        self.event.duration_ms = Some(duration);
458        self
459    }
460
461    /// Set the timestamp.
462    pub fn timestamp(mut self, timestamp: DateTime<Utc>) -> Self {
463        self.event.timestamp = timestamp;
464        self
465    }
466
467    /// Set the payload JSON string.
468    pub fn payload(mut self, payload: impl Into<String>) -> Self {
469        self.event.payload = Some(payload.into());
470        self
471    }
472
473    /// Set the metadata JSON string.
474    pub fn metadata(mut self, metadata: impl Into<String>) -> Self {
475        self.event.metadata = Some(metadata.into());
476        self
477    }
478
479    /// Set the tool_use_id.
480    pub fn tool_use_id(mut self, tool_use_id: impl Into<String>) -> Self {
481        self.event.tool_use_id = Some(tool_use_id.into());
482        self
483    }
484
485    /// Set the tool_name.
486    pub fn tool_name(mut self, tool_name: impl Into<String>) -> Self {
487        self.event.tool_name = Some(tool_name.into());
488        self
489    }
490
491    /// Set the spawned_agent_id.
492    pub fn spawned_agent_id(mut self, spawned_agent_id: impl Into<String>) -> Self {
493        self.event.spawned_agent_id = Some(spawned_agent_id.into());
494        self
495    }
496
497    /// Set the subagent_type.
498    pub fn subagent_type(mut self, subagent_type: impl Into<String>) -> Self {
499        self.event.subagent_type = Some(subagent_type.into());
500        self
501    }
502
503    /// Set the permission_mode.
504    pub fn permission_mode(mut self, permission_mode: impl Into<String>) -> Self {
505        self.event.permission_mode = Some(permission_mode.into());
506        self
507    }
508
509    /// Set the transcript_path.
510    pub fn transcript_path(mut self, transcript_path: impl Into<String>) -> Self {
511        self.event.transcript_path = Some(transcript_path.into());
512        self
513    }
514
515    /// Set the cwd.
516    pub fn cwd(mut self, cwd: impl Into<String>) -> Self {
517        self.event.cwd = Some(cwd.into());
518        self
519    }
520
521    /// Set the pid.
522    pub fn pid(mut self, pid: i32) -> Self {
523        self.event.pid = Some(pid);
524        self
525    }
526
527    // --- Optional field setters (for passing through Option values) ---
528
529    /// Set the framework if Some.
530    pub fn framework_opt(mut self, framework: Option<String>) -> Self {
531        if let Some(f) = framework {
532            self.event.framework = Some(f);
533        }
534        self
535    }
536
537    /// Set the timestamp if Some.
538    pub fn timestamp_opt(mut self, timestamp: Option<DateTime<Utc>>) -> Self {
539        if let Some(ts) = timestamp {
540            self.event.timestamp = ts;
541        }
542        self
543    }
544
545    /// Set the tool_use_id if Some.
546    pub fn tool_use_id_opt(mut self, tool_use_id: Option<String>) -> Self {
547        if let Some(id) = tool_use_id {
548            self.event.tool_use_id = Some(id);
549        }
550        self
551    }
552
553    /// Set the tool_name if Some.
554    pub fn tool_name_opt(mut self, tool_name: Option<String>) -> Self {
555        if let Some(name) = tool_name {
556            self.event.tool_name = Some(name);
557        }
558        self
559    }
560
561    /// Set the spawned_agent_id if Some.
562    pub fn spawned_agent_id_opt(mut self, spawned_agent_id: Option<String>) -> Self {
563        if let Some(id) = spawned_agent_id {
564            self.event.spawned_agent_id = Some(id);
565        }
566        self
567    }
568
569    /// Set the subagent_type if Some.
570    pub fn subagent_type_opt(mut self, subagent_type: Option<String>) -> Self {
571        if let Some(t) = subagent_type {
572            self.event.subagent_type = Some(t);
573        }
574        self
575    }
576
577    /// Set the permission_mode if Some.
578    pub fn permission_mode_opt(mut self, permission_mode: Option<String>) -> Self {
579        if let Some(m) = permission_mode {
580            self.event.permission_mode = Some(m);
581        }
582        self
583    }
584
585    /// Set the transcript_path if Some.
586    pub fn transcript_path_opt(mut self, transcript_path: Option<String>) -> Self {
587        if let Some(p) = transcript_path {
588            self.event.transcript_path = Some(p);
589        }
590        self
591    }
592
593    /// Set the cwd if Some.
594    pub fn cwd_opt(mut self, cwd: Option<String>) -> Self {
595        if let Some(c) = cwd {
596            self.event.cwd = Some(c);
597        }
598        self
599    }
600
601    /// Set the pid if Some.
602    pub fn pid_opt(mut self, pid: Option<i32>) -> Self {
603        if let Some(p) = pid {
604            self.event.pid = Some(p);
605        }
606        self
607    }
608
609    /// Set the model if Some.
610    pub fn model_opt(mut self, model: Option<String>) -> Self {
611        if let Some(m) = model {
612            self.event.model = Some(m);
613        }
614        self
615    }
616
617    /// Set the tokens_cache_read if Some.
618    pub fn tokens_cache_read_opt(mut self, tokens: Option<i64>) -> Self {
619        if let Some(t) = tokens {
620            self.event.tokens_cache_read = Some(t);
621        }
622        self
623    }
624
625    /// Set the tokens_cache_creation if Some.
626    pub fn tokens_cache_creation_opt(mut self, tokens: Option<i64>) -> Self {
627        if let Some(t) = tokens {
628            self.event.tokens_cache_creation = Some(t);
629        }
630        self
631    }
632
633    /// Set the cost_usd if Some.
634    pub fn cost_opt(mut self, cost: Option<f64>) -> Self {
635        if let Some(c) = cost {
636            self.event.cost_usd = Some(c);
637        }
638        self
639    }
640
641    /// Set the duration_ms if Some.
642    pub fn duration_ms_opt(mut self, duration: Option<i64>) -> Self {
643        if let Some(d) = duration {
644            self.event.duration_ms = Some(d);
645        }
646        self
647    }
648
649    /// Set the metadata if Some.
650    pub fn metadata_opt(mut self, metadata: Option<String>) -> Self {
651        if let Some(m) = metadata {
652            self.event.metadata = Some(m);
653        }
654        self
655    }
656
657    /// Set the payload if Some.
658    pub fn payload_opt(mut self, payload: Option<String>) -> Self {
659        if let Some(p) = payload {
660            self.event.payload = Some(p);
661        }
662        self
663    }
664}
665
666/// Aggregated statistics for API requests in a session
667#[derive(Debug, Clone, Default)]
668pub struct ApiStats {
669    /// Session ID
670    pub session_id: String,
671    /// Total API requests
672    pub request_count: i64,
673    /// Total input tokens
674    pub tokens_input: i64,
675    /// Total output tokens
676    pub tokens_output: i64,
677    /// Total cache read tokens
678    pub tokens_cache_read: i64,
679    /// Total cache creation tokens
680    pub tokens_cache_creation: i64,
681    /// Total cost in USD
682    pub cost_usd: f64,
683    /// First request timestamp
684    pub first_request_ts: Option<DateTime<Utc>>,
685    /// Last request timestamp
686    pub last_request_ts: Option<DateTime<Utc>>,
687    /// Context size of most recent request (input + cache_read + cache_creation)
688    pub context_latest: i64,
689    /// Maximum context size across all requests
690    pub context_peak: i64,
691}
692
693impl ApiStats {
694    /// Total tokens across all categories
695    pub fn total_tokens(&self) -> i64 {
696        self.tokens_input + self.tokens_output + self.tokens_cache_read + self.tokens_cache_creation
697    }
698
699    /// Duration from first to last request
700    pub fn duration(&self) -> Option<chrono::Duration> {
701        match (self.first_request_ts, self.last_request_ts) {
702            (Some(first), Some(last)) => Some(last - first),
703            _ => None,
704        }
705    }
706}
707
708/// Serde module for serializing `DateTime<Utc>` as Unix milliseconds
709pub mod timestamp_millis {
710    use chrono::{DateTime, TimeZone, Utc};
711    use serde::{self, Deserialize, Deserializer, Serializer};
712
713    pub fn serialize<S>(date: &DateTime<Utc>, serializer: S) -> Result<S::Ok, S::Error>
714    where
715        S: Serializer,
716    {
717        serializer.serialize_i64(date.timestamp_millis())
718    }
719
720    pub fn deserialize<'de, D>(deserializer: D) -> Result<DateTime<Utc>, D::Error>
721    where
722        D: Deserializer<'de>,
723    {
724        let millis = i64::deserialize(deserializer)?;
725        Utc.timestamp_millis_opt(millis)
726            .single()
727            .ok_or_else(|| serde::de::Error::custom("invalid timestamp"))
728    }
729}
730
731#[cfg(test)]
732mod tests {
733    use super::*;
734    use chrono::TimeZone;
735
736    /// Helper to parse EventType - infallible since unknown strings become Custom
737    fn parse_event_type(s: &str) -> EventType {
738        // EventType::from_str is infallible (Err type is Infallible)
739        s.parse::<EventType>()
740            .unwrap_or_else(|e: std::convert::Infallible| match e {})
741    }
742
743    #[test]
744    fn test_event_type_parse_known_types() {
745        assert_eq!(parse_event_type("SessionStart"), EventType::SessionStart);
746        assert_eq!(parse_event_type("SessionEnd"), EventType::SessionEnd);
747        assert_eq!(parse_event_type("PreToolUse"), EventType::PreToolUse);
748        assert_eq!(parse_event_type("PostToolUse"), EventType::PostToolUse);
749        assert_eq!(
750            parse_event_type("PermissionRequest"),
751            EventType::PermissionRequest
752        );
753        assert_eq!(parse_event_type("PreCompact"), EventType::PreCompact);
754        assert_eq!(parse_event_type("Stop"), EventType::Stop);
755        assert_eq!(parse_event_type("SubagentStop"), EventType::SubagentStop);
756        assert_eq!(parse_event_type("Notification"), EventType::Notification);
757        assert_eq!(
758            parse_event_type("UserPromptSubmit"),
759            EventType::UserPromptSubmit
760        );
761    }
762
763    #[test]
764    fn test_event_type_parse_case_insensitive() {
765        assert_eq!(parse_event_type("sessionstart"), EventType::SessionStart);
766        assert_eq!(parse_event_type("SESSIONSTART"), EventType::SessionStart);
767        assert_eq!(parse_event_type("SessionSTART"), EventType::SessionStart);
768        assert_eq!(parse_event_type("pretooluse"), EventType::PreToolUse);
769        assert_eq!(
770            parse_event_type("USERPROMPTSUBMIT"),
771            EventType::UserPromptSubmit
772        );
773    }
774
775    #[test]
776    fn test_event_type_parse_unknown_becomes_custom() {
777        let unknown = parse_event_type("FutureEventType");
778        assert_eq!(unknown, EventType::Custom("FutureEventType".to_string()));
779
780        let custom = parse_event_type("MyCustomEvent");
781        assert_eq!(custom, EventType::Custom("MyCustomEvent".to_string()));
782    }
783
784    #[test]
785    fn test_event_type_parse_trims_whitespace() {
786        // Leading/trailing whitespace should be trimmed for known types
787        assert_eq!(parse_event_type(" SessionStart "), EventType::SessionStart);
788        assert_eq!(parse_event_type("\tPreToolUse\n"), EventType::PreToolUse);
789        // Custom types also get trimmed
790        assert_eq!(
791            parse_event_type("  CustomEvent  "),
792            EventType::Custom("CustomEvent".to_string())
793        );
794    }
795
796    #[test]
797    fn test_event_type_display() {
798        assert_eq!(EventType::SessionStart.to_string(), "SessionStart");
799        assert_eq!(EventType::PreToolUse.to_string(), "PreToolUse");
800        assert_eq!(
801            EventType::Custom("MyEvent".to_string()).to_string(),
802            "MyEvent"
803        );
804    }
805
806    #[test]
807    fn test_event_type_as_str() {
808        assert_eq!(EventType::SessionStart.as_str(), "SessionStart");
809        assert_eq!(EventType::Custom("Test".to_string()).as_str(), "Test");
810    }
811
812    #[test]
813    fn test_event_type_is_known() {
814        assert!(EventType::SessionStart.is_known());
815        assert!(EventType::PreToolUse.is_known());
816        assert!(!EventType::Custom("Unknown".to_string()).is_known());
817    }
818
819    #[test]
820    fn test_event_type_serialize() -> Result<(), String> {
821        let session_start =
822            serde_json::to_string(&EventType::SessionStart).map_err(|e| e.to_string())?;
823        assert_eq!(session_start, r#""SessionStart""#);
824
825        let custom = serde_json::to_string(&EventType::Custom("MyEvent".to_string()))
826            .map_err(|e| e.to_string())?;
827        assert_eq!(custom, r#""MyEvent""#);
828        Ok(())
829    }
830
831    #[test]
832    fn test_event_type_deserialize() -> Result<(), String> {
833        let session_start: EventType =
834            serde_json::from_str(r#""SessionStart""#).map_err(|e| e.to_string())?;
835        assert_eq!(session_start, EventType::SessionStart);
836
837        let unknown: EventType =
838            serde_json::from_str(r#""FutureEvent""#).map_err(|e| e.to_string())?;
839        assert_eq!(unknown, EventType::Custom("FutureEvent".to_string()));
840        Ok(())
841    }
842
843    #[test]
844    fn test_event_type_roundtrip() -> Result<(), String> {
845        let original = EventType::PreToolUse;
846        let json = serde_json::to_string(&original).map_err(|e| e.to_string())?;
847        let parsed: EventType = serde_json::from_str(&json).map_err(|e| e.to_string())?;
848        assert_eq!(original, parsed);
849
850        let custom = EventType::Custom("SpecialEvent".to_string());
851        let json = serde_json::to_string(&custom).map_err(|e| e.to_string())?;
852        let parsed: EventType = serde_json::from_str(&json).map_err(|e| e.to_string())?;
853        assert_eq!(custom, parsed);
854        Ok(())
855    }
856
857    // --- EventBuilder tests ---
858
859    #[test]
860    fn test_event_builder_basic() {
861        let event = EventBuilder::new("machine-1", EventType::SessionStart, "session-123").build();
862
863        assert_eq!(event.machine_id, "machine-1");
864        assert_eq!(event.event_type, EventType::SessionStart);
865        assert_eq!(event.session_id, "session-123");
866        assert!(event.id.is_none());
867    }
868
869    #[test]
870    fn test_event_builder_impl_into_string() {
871        // Test that impl Into<String> works with &str
872        let event = EventBuilder::new("machine", EventType::ApiRequest, "session")
873            .framework("claude")
874            .model("claude-3-opus")
875            .build();
876
877        assert_eq!(event.framework, Some("claude".to_string()));
878        assert_eq!(event.model, Some("claude-3-opus".to_string()));
879    }
880
881    #[test]
882    fn test_event_builder_tokens() {
883        let event = EventBuilder::new("machine", EventType::ApiRequest, "session")
884            .tokens(1000, 500)
885            .build();
886
887        assert_eq!(event.tokens_input, Some(1000));
888        assert_eq!(event.tokens_output, Some(500));
889    }
890
891    #[test]
892    fn test_event_builder_cache_tokens() {
893        let event = EventBuilder::new("machine", EventType::ApiRequest, "session")
894            .cache_tokens(200, 100)
895            .build();
896
897        assert_eq!(event.tokens_cache_read, Some(200));
898        assert_eq!(event.tokens_cache_creation, Some(100));
899    }
900
901    #[test]
902    fn test_event_builder_tool() {
903        let event = EventBuilder::new("machine", EventType::PreToolUse, "session")
904            .tool("toolu_123", "Bash")
905            .build();
906
907        assert_eq!(event.tool_use_id, Some("toolu_123".to_string()));
908        assert_eq!(event.tool_name, Some("Bash".to_string()));
909    }
910
911    #[test]
912    fn test_event_builder_all_fields() {
913        let ts = Utc::now();
914        let event = EventBuilder::new("machine", EventType::ApiRequest, "session")
915            .framework("claude")
916            .model("claude-3-opus")
917            .tokens(1000, 500)
918            .cache_tokens(200, 100)
919            .cost(0.05)
920            .duration_ms(1234)
921            .timestamp(ts)
922            .payload(r#"{"key": "value"}"#)
923            .metadata(r#"{"extra": "data"}"#)
924            .build();
925
926        assert_eq!(event.framework, Some("claude".to_string()));
927        assert_eq!(event.model, Some("claude-3-opus".to_string()));
928        assert_eq!(event.tokens_input, Some(1000));
929        assert_eq!(event.tokens_output, Some(500));
930        assert_eq!(event.tokens_cache_read, Some(200));
931        assert_eq!(event.tokens_cache_creation, Some(100));
932        assert_eq!(event.cost_usd, Some(0.05));
933        assert_eq!(event.duration_ms, Some(1234));
934        assert_eq!(event.timestamp, ts);
935        assert_eq!(event.payload, Some(r#"{"key": "value"}"#.to_string()));
936        assert_eq!(event.metadata, Some(r#"{"extra": "data"}"#.to_string()));
937    }
938
939    #[test]
940    fn test_event_builder_opt_methods_with_some() {
941        let event = EventBuilder::new("machine", EventType::PreToolUse, "session")
942            .tool_use_id_opt(Some("toolu_123".to_string()))
943            .tool_name_opt(Some("Bash".to_string()))
944            .spawned_agent_id_opt(Some("agent-456".to_string()))
945            .subagent_type_opt(Some("Explore".to_string()))
946            .permission_mode_opt(Some("default".to_string()))
947            .transcript_path_opt(Some("/path/to/transcript".to_string()))
948            .cwd_opt(Some("/home/user".to_string()))
949            .pid_opt(Some(12345))
950            .build();
951
952        assert_eq!(event.tool_use_id, Some("toolu_123".to_string()));
953        assert_eq!(event.tool_name, Some("Bash".to_string()));
954        assert_eq!(event.spawned_agent_id, Some("agent-456".to_string()));
955        assert_eq!(event.subagent_type, Some("Explore".to_string()));
956        assert_eq!(event.permission_mode, Some("default".to_string()));
957        assert_eq!(
958            event.transcript_path,
959            Some("/path/to/transcript".to_string())
960        );
961        assert_eq!(event.cwd, Some("/home/user".to_string()));
962        assert_eq!(event.pid, Some(12345));
963    }
964
965    #[test]
966    fn test_event_builder_opt_methods_with_none() {
967        let event = EventBuilder::new("machine", EventType::PreToolUse, "session")
968            .tool_use_id_opt(None)
969            .tool_name_opt(None)
970            .spawned_agent_id_opt(None)
971            .subagent_type_opt(None)
972            .permission_mode_opt(None)
973            .transcript_path_opt(None)
974            .cwd_opt(None)
975            .pid_opt(None)
976            .build();
977
978        assert!(event.tool_use_id.is_none());
979        assert!(event.tool_name.is_none());
980        assert!(event.spawned_agent_id.is_none());
981        assert!(event.subagent_type.is_none());
982        assert!(event.permission_mode.is_none());
983        assert!(event.transcript_path.is_none());
984        assert!(event.cwd.is_none());
985        assert!(event.pid.is_none());
986    }
987
988    #[test]
989    fn test_event_builder_timestamp_opt_none_keeps_current() {
990        let event = EventBuilder::new("machine", EventType::SessionStart, "session")
991            .timestamp_opt(None)
992            .build();
993
994        // timestamp_opt(None) should keep the timestamp set during new()
995        // Just verify timestamp is set (it will be close to now)
996        assert!(event.timestamp.timestamp() > 0);
997    }
998
999    #[test]
1000    fn test_event_builder_timestamp_opt_some() {
1001        let ts = Utc.with_ymd_and_hms(2025, 1, 15, 12, 0, 0).unwrap();
1002        let event = EventBuilder::new("machine", EventType::SessionStart, "session")
1003            .timestamp_opt(Some(ts))
1004            .build();
1005
1006        assert_eq!(event.timestamp, ts);
1007    }
1008
1009    #[test]
1010    fn test_event_builder_api_request_opt_fields() {
1011        let event = EventBuilder::new("machine", EventType::ApiRequest, "session")
1012            .tokens_cache_read_opt(Some(500))
1013            .tokens_cache_creation_opt(Some(100))
1014            .cost_opt(Some(0.03))
1015            .duration_ms_opt(Some(2000))
1016            .model_opt(Some("claude-3-sonnet".to_string()))
1017            .metadata_opt(Some(r#"{"foo": "bar"}"#.to_string()))
1018            .payload_opt(Some(r#"{"input": "test"}"#.to_string()))
1019            .build();
1020
1021        assert_eq!(event.tokens_cache_read, Some(500));
1022        assert_eq!(event.tokens_cache_creation, Some(100));
1023        assert_eq!(event.cost_usd, Some(0.03));
1024        assert_eq!(event.duration_ms, Some(2000));
1025        assert_eq!(event.model, Some("claude-3-sonnet".to_string()));
1026        assert_eq!(event.metadata, Some(r#"{"foo": "bar"}"#.to_string()));
1027        assert_eq!(event.payload, Some(r#"{"input": "test"}"#.to_string()));
1028    }
1029
1030    #[test]
1031    fn test_event_builder_payload_opt_preserves_value() {
1032        let event = EventBuilder::new("machine", EventType::PreToolUse, "session")
1033            .payload(r#"{"original": true}"#)
1034            .payload_opt(None) // Should preserve original value
1035            .build();
1036
1037        assert_eq!(event.payload, Some(r#"{"original": true}"#.to_string()));
1038    }
1039
1040    #[test]
1041    fn test_event_builder_individual_setters() {
1042        let event = EventBuilder::new("machine", EventType::PreToolUse, "session")
1043            .tool_use_id("toolu_abc")
1044            .tool_name("Read")
1045            .spawned_agent_id("agent-xyz")
1046            .subagent_type("Plan")
1047            .permission_mode("acceptEdits")
1048            .transcript_path("/tmp/transcript.jsonl")
1049            .cwd("/workspace")
1050            .pid(9999)
1051            .build();
1052
1053        assert_eq!(event.tool_use_id, Some("toolu_abc".to_string()));
1054        assert_eq!(event.tool_name, Some("Read".to_string()));
1055        assert_eq!(event.spawned_agent_id, Some("agent-xyz".to_string()));
1056        assert_eq!(event.subagent_type, Some("Plan".to_string()));
1057        assert_eq!(event.permission_mode, Some("acceptEdits".to_string()));
1058        assert_eq!(
1059            event.transcript_path,
1060            Some("/tmp/transcript.jsonl".to_string())
1061        );
1062        assert_eq!(event.cwd, Some("/workspace".to_string()));
1063        assert_eq!(event.pid, Some(9999));
1064    }
1065}