fyi-core 0.1.0

Core types and traits for fyi
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
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::time::Duration;
use thiserror::Error;

use crate::EventType;

#[derive(Error, Debug)]
pub enum ConfigError {
    #[error("failed to read config file: {0}")]
    ReadError(#[from] std::io::Error),
    #[error("failed to parse config file: {0}")]
    ParseError(#[from] toml::de::Error),
    #[error("failed to determine home directory")]
    NoHomeDir,
}

/// Error parsing a TTL string
#[derive(Error, Debug, PartialEq, Eq)]
pub enum TtlParseError {
    #[error("invalid TTL format: {0}")]
    InvalidFormat(String),
    #[error("invalid TTL number: {0}")]
    InvalidNumber(String),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    /// Explicit database path. If None, uses default (~/.fyi/events.db).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub db_path: Option<String>,

    /// Explicit machine identifier. If None, uses hostname.
    /// Resolution order: FYI_MACHINE_ID env var > config > hostname > "unknown"
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub machine_id: Option<String>,

    #[serde(default)]
    pub hooks: HooksConfig,

    /// Data retention period for all events. Default: 365 days.
    /// Supports suffixes: 'd' (days), 'h' (hours), 'm' (minutes), 's' (seconds), or raw seconds.
    #[serde(default = "default_retention")]
    pub retention: String,

    /// Where the config was loaded from (not serialized)
    #[serde(skip)]
    source: ConfigSource,
}

/// Macro to define HooksConfig with automatic snake_case to PascalCase mapping.
///
/// This macro generates the struct, Default impl, and enabled_hooks() method
/// from a single definition, ensuring the field names and EventType variants
/// are always in sync.
macro_rules! define_hooks_config {
    ($($field:ident => $variant:ident),* $(,)?) => {
        #[derive(Debug, Clone, Serialize, Deserialize)]
        #[serde(rename_all = "PascalCase")]
        pub struct HooksConfig {
            $(
                #[serde(default = "default_true")]
                pub $field: bool,
            )*
        }

        impl Default for HooksConfig {
            fn default() -> Self {
                Self {
                    $($field: true,)*
                }
            }
        }

        impl HooksConfig {
            /// Returns enabled hooks as EventType values for type-safe handling.
            pub fn enabled_hooks(&self) -> Vec<EventType> {
                let mut hooks = Vec::new();
                $(
                    if self.$field {
                        hooks.push(EventType::$variant);
                    }
                )*
                hooks
            }
        }
    };
}

define_hooks_config! {
    session_start => SessionStart,
    session_end => SessionEnd,
    user_prompt_submit => UserPromptSubmit,
    stop => Stop,
    subagent_stop => SubagentStop,
    notification => Notification,
    permission_request => PermissionRequest,
    pre_compact => PreCompact,
    pre_tool_use => PreToolUse,
    post_tool_use => PostToolUse,
}

fn default_true() -> bool {
    true
}

/// Default retention period: 365 days
pub const DEFAULT_RETENTION: Duration = Duration::from_secs(365 * 24 * 60 * 60);

fn default_retention() -> String {
    "365d".to_string()
}

/// Parse a retention/TTL string like "7d", "30d", "1h" into a Duration.
///
/// Supports suffixes:
/// - 'd' for days (e.g., "7d" = 7 days)
/// - 'h' for hours (e.g., "24h" = 24 hours)
/// - 'm' for minutes (e.g., "30m" = 30 minutes)
/// - 's' for seconds (e.g., "3600s" = 1 hour)
/// - Raw seconds if no suffix (e.g., "86400" = 1 day)
pub fn parse_retention(s: &str) -> Result<Duration, TtlParseError> {
    let s = s.trim();
    if let Some(stripped) = s.strip_suffix('d') {
        let days: u64 = stripped
            .parse()
            .map_err(|_| TtlParseError::InvalidNumber(s.to_string()))?;
        Ok(Duration::from_secs(days * 24 * 60 * 60))
    } else if let Some(stripped) = s.strip_suffix('h') {
        let hours: u64 = stripped
            .parse()
            .map_err(|_| TtlParseError::InvalidNumber(s.to_string()))?;
        Ok(Duration::from_secs(hours * 60 * 60))
    } else if let Some(stripped) = s.strip_suffix('m') {
        let minutes: u64 = stripped
            .parse()
            .map_err(|_| TtlParseError::InvalidNumber(s.to_string()))?;
        Ok(Duration::from_secs(minutes * 60))
    } else if let Some(stripped) = s.strip_suffix('s') {
        let secs: u64 = stripped
            .parse()
            .map_err(|_| TtlParseError::InvalidNumber(s.to_string()))?;
        Ok(Duration::from_secs(secs))
    } else {
        // Assume seconds (raw number)
        let secs: u64 = s
            .parse()
            .map_err(|_| TtlParseError::InvalidFormat(s.to_string()))?;
        Ok(Duration::from_secs(secs))
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            db_path: None,
            machine_id: None,
            hooks: HooksConfig::default(),
            retention: default_retention(),
            source: ConfigSource::Default,
        }
    }
}

/// Where the config was loaded from
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ConfigSource {
    /// Environment variable (FYI_CONFIG)
    EnvVar,
    /// User global ~/.fyi/config.toml
    UserGlobal,
    /// No config file found, using defaults
    #[default]
    Default,
}

impl Config {
    /// Load config with source information.
    ///
    /// Config resolution order:
    /// 1. `FYI_CONFIG` env var (if set and file exists)
    /// 2. `~/.fyi/config.toml` (user global)
    /// 3. Built-in defaults
    ///
    /// For per-project database paths, use the `FYI_DB_PATH` env var.
    pub fn load_with_source() -> Result<(Self, ConfigSource), ConfigError> {
        // 1. Check environment variable
        if let Ok(path) = std::env::var("FYI_CONFIG") {
            let path = PathBuf::from(path);
            if path.exists() {
                let contents = std::fs::read_to_string(&path)?;
                let mut config: Config = toml::from_str(&contents)?;
                config.source = ConfigSource::EnvVar;
                return Ok((config, ConfigSource::EnvVar));
            }
        }

        // 2. Check user global ~/.fyi/config.toml
        if let Some(home) = dirs::home_dir() {
            let global_config = home.join(".fyi/config.toml");
            if global_config.exists() {
                let contents = std::fs::read_to_string(&global_config)?;
                let mut config: Config = toml::from_str(&contents)?;
                config.source = ConfigSource::UserGlobal;
                return Ok((config, ConfigSource::UserGlobal));
            }
        }

        // 3. Use defaults
        Ok((Config::default(), ConfigSource::Default))
    }

    /// Load config (convenience method that discards source)
    pub fn load() -> Result<Self, ConfigError> {
        Ok(Self::load_with_source()?.0)
    }

    /// Get the database path.
    ///
    /// Resolution order:
    /// 1. `FYI_DB_PATH` env var (if set)
    /// 2. `db_path` from config file (if set)
    /// 3. Default: `~/.fyi/events.db`
    pub fn db_path(&self) -> Result<PathBuf, ConfigError> {
        // Environment variable always takes precedence
        if let Ok(path) = std::env::var("FYI_DB_PATH") {
            return Ok(PathBuf::from(path));
        }

        // If db_path is explicitly set in config, use it
        if let Some(ref db_path) = self.db_path {
            return Self::expand_path(db_path);
        }

        // Default to global database location
        let home = dirs::home_dir().ok_or(ConfigError::NoHomeDir)?;
        Ok(home.join(".fyi/events.db"))
    }

    /// Get the source from which this config was loaded.
    pub fn source(&self) -> ConfigSource {
        self.source
    }

    /// Expand a path, handling ~ for home directory
    fn expand_path(path: &str) -> Result<PathBuf, ConfigError> {
        if let Some(stripped) = path.strip_prefix("~/") {
            let home = dirs::home_dir().ok_or(ConfigError::NoHomeDir)?;
            Ok(home.join(stripped))
        } else {
            Ok(PathBuf::from(path))
        }
    }

    /// Get the user global config directory
    pub fn user_global_dir() -> Result<PathBuf, ConfigError> {
        let home = dirs::home_dir().ok_or(ConfigError::NoHomeDir)?;
        Ok(home.join(".fyi"))
    }

    /// Get the machine ID.
    ///
    /// Resolution order:
    /// 1. `FYI_MACHINE_ID` env var (if set)
    /// 2. `machine_id` from config file (if set)
    /// 3. Hostname (current behavior)
    /// 4. "unknown" fallback
    pub fn machine_id(&self) -> String {
        // 1. Environment variable takes precedence
        if let Ok(id) = std::env::var("FYI_MACHINE_ID")
            && !id.is_empty()
        {
            return id;
        }

        // 2. Config file setting
        if let Some(ref id) = self.machine_id
            && !id.is_empty()
        {
            return id.clone();
        }

        // 3. Hostname
        if let Some(hostname) = hostname::get().ok().and_then(|h| h.into_string().ok())
            && !hostname.is_empty()
        {
            return hostname;
        }

        // 4. Fallback
        "unknown".to_string()
    }

    /// Get the retention period as a Duration.
    ///
    /// Falls back to default if the retention string is invalid.
    pub fn retention_duration(&self) -> Duration {
        match parse_retention(&self.retention) {
            Ok(duration) => duration,
            Err(e) => {
                eprintln!(
                    "fyi: warning: failed to parse retention '{}': {}. Using default.",
                    self.retention, e
                );
                DEFAULT_RETENTION
            }
        }
    }
}

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

    #[test]
    fn test_parse_retention() {
        // Days
        assert_eq!(
            parse_retention("7d"),
            Ok(Duration::from_secs(7 * 24 * 60 * 60))
        );
        assert_eq!(
            parse_retention("30d"),
            Ok(Duration::from_secs(30 * 24 * 60 * 60))
        );

        // Hours
        assert_eq!(parse_retention("1h"), Ok(Duration::from_secs(60 * 60)));
        assert_eq!(
            parse_retention("24h"),
            Ok(Duration::from_secs(24 * 60 * 60))
        );

        // Minutes
        assert_eq!(parse_retention("30m"), Ok(Duration::from_secs(30 * 60)));
        assert_eq!(parse_retention("60m"), Ok(Duration::from_secs(60 * 60)));

        // Seconds (raw number)
        assert_eq!(parse_retention("1000"), Ok(Duration::from_secs(1000)));

        // Explicit seconds suffix
        assert_eq!(parse_retention("3600s"), Ok(Duration::from_secs(3600)));

        // Invalid
        assert_eq!(
            parse_retention("abc"),
            Err(TtlParseError::InvalidFormat("abc".to_string()))
        );
        assert_eq!(
            parse_retention("d"),
            Err(TtlParseError::InvalidNumber("d".to_string()))
        );
    }

    #[test]
    fn test_config_default_retention() {
        let config = Config::default();
        assert_eq!(config.retention, "365d");
        assert_eq!(config.retention_duration(), DEFAULT_RETENTION);
    }

    #[test]
    fn test_config_custom_retention() -> Result<(), String> {
        let toml_str = r#"
            retention = "30d"
        "#;

        let config: Config = toml::from_str(toml_str).map_err(|e| e.to_string())?;
        assert_eq!(config.retention, "30d");
        assert_eq!(
            config.retention_duration(),
            std::time::Duration::from_secs(30 * 24 * 60 * 60)
        );
        Ok(())
    }

    #[test]
    fn test_config_retention_fallback_on_invalid() {
        let config = Config {
            retention: "invalid".to_string(),
            ..Default::default()
        };
        // Should fall back to DEFAULT_RETENTION
        assert_eq!(config.retention_duration(), DEFAULT_RETENTION);
    }

    #[test]
    fn test_config_default_source() {
        let config = Config::default();
        assert_eq!(config.source(), ConfigSource::Default);
    }

    #[test]
    fn test_config_source_cached_from_load() -> Result<(), String> {
        // When loading config, the source should be cached in the struct
        let (config, source) = Config::load_with_source().map_err(|e| e.to_string())?;
        assert_eq!(config.source(), source);
        Ok(())
    }

    #[test]
    fn test_db_path_consistent() -> Result<(), String> {
        // Calling db_path() multiple times should return consistent results
        let config = Config::default();
        let path1 = config.db_path().map_err(|e| e.to_string())?;
        let path2 = config.db_path().map_err(|e| e.to_string())?;
        assert_eq!(path1, path2);
        Ok(())
    }

    #[test]
    fn test_config_source_default_is_default() {
        // Verify ConfigSource::Default is the default variant
        assert_eq!(ConfigSource::default(), ConfigSource::Default);
    }

    #[test]
    fn test_enabled_hooks_returns_all_event_types() {
        let config = HooksConfig::default();
        let hooks = config.enabled_hooks();

        // Verify all expected hooks are present as EventType variants
        assert!(hooks.contains(&EventType::SessionStart));
        assert!(hooks.contains(&EventType::SessionEnd));
        assert!(hooks.contains(&EventType::UserPromptSubmit));
        assert!(hooks.contains(&EventType::Stop));
        assert!(hooks.contains(&EventType::SubagentStop));
        assert!(hooks.contains(&EventType::Notification));
        assert!(hooks.contains(&EventType::PermissionRequest));
        assert!(hooks.contains(&EventType::PreCompact));
        assert!(hooks.contains(&EventType::PreToolUse));
        assert!(hooks.contains(&EventType::PostToolUse));

        // Verify we have exactly 10 hooks
        assert_eq!(hooks.len(), 10);
    }

    #[test]
    fn test_enabled_hooks_respects_disabled_hooks() {
        let config = HooksConfig {
            session_start: false,
            pre_tool_use: false,
            ..Default::default()
        };

        let hooks = config.enabled_hooks();
        assert_eq!(hooks.len(), 8);
        assert!(!hooks.contains(&EventType::SessionStart));
        assert!(!hooks.contains(&EventType::PreToolUse));
        assert!(hooks.contains(&EventType::SessionEnd));
    }

    #[test]
    fn test_machine_id_returns_nonempty() {
        // machine_id() should always return a non-empty string
        let config = Config::default();
        let machine_id = config.machine_id();
        // Should be non-empty (env var, config, hostname, or "unknown")
        assert!(!machine_id.is_empty());
    }

    #[test]
    fn test_config_machine_id_from_toml() -> Result<(), String> {
        let toml_str = r#"
            machine_id = "test-machine"
        "#;

        let config: Config = toml::from_str(toml_str).map_err(|e| e.to_string())?;
        assert_eq!(config.machine_id, Some("test-machine".to_string()));
        Ok(())
    }

    #[test]
    fn test_config_machine_id_optional_in_toml() -> Result<(), String> {
        // machine_id should be optional in TOML
        let toml_str = r#"
            retention = "30d"
        "#;

        let config: Config = toml::from_str(toml_str).map_err(|e| e.to_string())?;
        assert_eq!(config.machine_id, None);
        Ok(())
    }

    #[test]
    fn test_machine_id_default_is_none() {
        // Default config should have machine_id as None
        let config = Config::default();
        assert!(config.machine_id.is_none());
    }
}