ironmonitor 7.1.0

IronMonitor: hardware monitoring for CPUs, GPUs, NPUs, memory, I/O and network silicon on Linux, Windows and macOS, which reports what it cannot read as well as what it can
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
//! User Consent Management
//!
//! # IronMonitor collects nothing and transmits nothing
//!
//! Read this before anything else in the module, because the rest of it
//! describes machinery that does not currently drive anything.
//!
//! No code in this crate reports anything about a user's machine to the people
//! who wrote it. **There is no endpoint.** No vendor receives telemetry,
//! analytics, hardware inventory or diagnostics from this program, and there is
//! nowhere for such a thing to go. [`ConsentScope::is_collected`] returns
//! `false` for every scope, and it is the single place that changes if that ever
//! stops being true.
//!
//! The only outbound HTTP in the crate goes to LLM backends the user configures
//! and points at themselves.
//!
//! **"Collects nothing" means nothing leaves for us, not that nothing is ever
//! written down.** This paragraph used to say "no code in this crate collects,
//! aggregates or transmits telemetry", which was broader than the guarantee
//! beneath it and was already untrue of the program as shipped: [`crate::tsdb`]
//! records metrics to a local file, [`crate::prometheus`] publishes them for a
//! scraper the operator runs, and the optional `fleet-store` feature appends
//! them to an Apache Iceberg table the operator configures. Every one of those
//! is storage the *user* asked for and controls the destination of, which is the
//! opposite of telemetry, and none of them existed to serve anyone but them.
//!
//! The line is **who chose the destination**. If the answer is the person
//! running the program, it is their data going where they told it to. If the
//! answer were us, it would be telemetry, and this crate would have to say so
//! here, on the three `ironmon privacy` screens, and in
//! [`ConsentScope::is_collected`] — in the same change.
//!
//! What this module provides is the consent *record* — a persisted preference,
//! with a timestamp, that a future collector would have to honour. Presenting
//! it as a live privacy control would tell the user they had switched
//! something off that was never on, which is the same defect as reporting a
//! measurement that was never taken.
//!
//! # Principles
//!
//! - **Denied until asked**: a scope with no consent record is not granted.
//!   This module previously defaulted to granted while describing itself as
//!   opt-in; the two cannot both be true, and the safe reading is the one that
//!   does not assume permission nobody gave.
//! - **Easy opt-out**: `ironmon privacy opt-out` records a denial for every scope
//! - **Transparency**: the disclosure says what *would* be collected, and says
//!   plainly that none of it is
//! - **Auditability**: every consent decision is stored with the time it was made
//!
//! No claim is made here about compliance with any particular privacy
//! regulation. That is a question about a deployment and its operator, not
//! about a library, and this module is not in a position to answer it.
//!
//! # Example
//!
//! ```no_run
//! use ironmonitor::consent::{ConsentManager, ConsentScope};
//!
//! let mut manager = ConsentManager::load()?;
//!
//! // Check if user has consented to basic telemetry
//! if !manager.has_consent(ConsentScope::BasicTelemetry) {
//!     // Prompt user for consent
//!     manager.request_consent(ConsentScope::BasicTelemetry)?;
//! }
//!
//! // Only collect data if user explicitly consented
//! if manager.has_consent(ConsentScope::BasicTelemetry) {
//!     // Safe to collect anonymized usage data
//! }
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use crate::error::{IronError, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};

/// Check if telemetry is disabled for this session via CLI flags.
///
/// Returns `true` if the `--no-telemetry` or `--offline` CLI flag was used.
/// This check is fast and can be used early in code paths to skip telemetry logic entirely.
///
/// # Example
///
/// ```no_run
/// use ironmonitor::consent::is_telemetry_disabled;
///
/// if is_telemetry_disabled() {
///     // Skip any telemetry code paths
///     return;
/// }
/// ```
pub fn is_telemetry_disabled() -> bool {
    std::env::var("IRONMON_NO_TELEMETRY").is_ok() || std::env::var("IRONMON_OFFLINE").is_ok()
}

/// Check if running in offline mode (all network features disabled).
///
/// Returns `true` if the `--offline` CLI flag was used.
///
/// # Example
///
/// ```no_run
/// use ironmonitor::consent::is_offline_mode;
///
/// if is_offline_mode() {
///     // Skip any network-dependent features
///     return;
/// }
/// ```
pub fn is_offline_mode() -> bool {
    std::env::var("IRONMON_OFFLINE").is_ok()
}

/// Consent scopes - each represents a specific type of data collection
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConsentScope {
    /// Basic anonymized usage telemetry (feature usage, crash reports)
    BasicTelemetry,

    /// Hardware information (GPU model, CPU type - anonymized)
    HardwareInfo,

    /// Performance metrics (aggregated, anonymized)
    PerformanceMetrics,

    /// Detailed diagnostics (for troubleshooting, includes system info)
    DetailedDiagnostics,

    /// Anonymous analytics (usage patterns, feature popularity)
    Analytics,
}

impl ConsentScope {
    /// Get human-readable name
    pub fn name(&self) -> &'static str {
        match self {
            Self::BasicTelemetry => "Basic Telemetry",
            Self::HardwareInfo => "Hardware Information",
            Self::PerformanceMetrics => "Performance Metrics",
            Self::DetailedDiagnostics => "Detailed Diagnostics",
            Self::Analytics => "Anonymous Analytics",
        }
    }

    /// Get detailed description of what's collected
    pub fn description(&self) -> &'static str {
        match self {
            Self::BasicTelemetry =>
                "Basic usage statistics and crash reports. Helps improve stability and reliability. \
                 No personally identifiable information is collected.",
            Self::HardwareInfo =>
                "Anonymized hardware information (GPU models, CPU types, RAM size). \
                 Helps prioritize hardware support. Serial numbers and MAC addresses are never collected.",
            Self::PerformanceMetrics =>
                "Aggregated performance metrics (frame rates, GPU utilization averages). \
                 Helps optimize performance. All data is anonymized and aggregated.",
            Self::DetailedDiagnostics =>
                "Detailed system information for troubleshooting (driver versions, kernel info). \
                 Only collected when explicitly requested for bug reports.",
            Self::Analytics =>
                "Anonymous analytics about feature usage patterns. \
                 Helps understand which features are most valuable. No tracking or profiling.",
        }
    }

    /// Whether any code in this crate actually collects or transmits data
    /// under this scope.
    ///
    /// Every arm is `false`, and that is the point. The five scopes, their
    /// descriptions and their itemised data points were written for a
    /// collector that was never built, and `ironmon privacy` displayed them as
    /// though the collection were happening and merely switched off.
    ///
    /// **If you add a collector, flip its scope here in the same change.**
    /// [`ConsentManager::should_collect_data`] consults this, so a scope that
    /// nothing implements cannot report that it should collect, however the
    /// user answered. `granting_every_scope_still_collects_nothing` in this
    /// module fails the moment an arm becomes `true`, which is the moment the
    /// disclosure and the CLI text need revisiting.
    pub fn is_collected(&self) -> bool {
        match self {
            Self::BasicTelemetry
            | Self::HardwareInfo
            | Self::PerformanceMetrics
            | Self::DetailedDiagnostics
            | Self::Analytics => false,
        }
    }

    /// The data points that *would* be collected under this scope if it were
    /// implemented. Nothing here is gathered today — see [`Self::is_collected`].
    pub fn data_points(&self) -> Vec<&'static str> {
        match self {
            Self::BasicTelemetry => vec![
                "Application version",
                "Operating system type (Linux/Windows/macOS)",
                "Crash stack traces (anonymized)",
                "Error frequency (aggregated)",
            ],
            Self::HardwareInfo => vec![
                "GPU vendor (NVIDIA/AMD/Intel)",
                "GPU generation (e.g., RTX 30-series, not exact model)",
                "CPU architecture (x86_64/ARM)",
                "Approximate RAM size (e.g., 16GB range)",
            ],
            Self::PerformanceMetrics => vec![
                "Average GPU utilization",
                "Average memory usage",
                "Frame time distributions",
                "Application startup time",
            ],
            Self::DetailedDiagnostics => vec![
                "Exact GPU model and driver version",
                "Kernel version",
                "System configuration",
                "Running processes (names only, no PIDs or paths)",
            ],
            Self::Analytics => vec![
                "Feature usage frequency",
                "Tab/view navigation patterns",
                "Configuration changes (types, not values)",
                "Session duration",
            ],
        }
    }
}

/// Consent decision record
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConsentRecord {
    /// The scope this consent applies to
    pub scope: ConsentScope,

    /// Whether user granted consent
    pub granted: bool,

    /// When the consent was recorded
    pub timestamp: u64,

    /// Version of the consent prompt shown
    pub prompt_version: u32,

    /// Always `None`. No IP address is recorded, hashed or otherwise; the
    /// field exists only because it was declared, and `record_consent` has
    /// never populated it. Queued for removal, which is breaking.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ip_hash: Option<String>,
}

/// Consent management configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConsentConfig {
    /// All consent records
    pub records: HashMap<ConsentScope, ConsentRecord>,

    /// When the user was first prompted
    pub first_prompt_timestamp: Option<u64>,

    /// Last time consent was reviewed
    pub last_review_timestamp: Option<u64>,

    /// User can set a reminder to review consent
    pub review_reminder_days: Option<u32>,

    /// Version of consent system (for tracking changes)
    pub consent_version: u32,
}

impl Default for ConsentConfig {
    fn default() -> Self {
        Self {
            records: HashMap::new(),
            first_prompt_timestamp: None,
            last_review_timestamp: None,
            review_reminder_days: Some(90), // Remind every 90 days by default
            consent_version: 1,
        }
    }
}

/// Consent manager - handles all consent-related operations
pub struct ConsentManager {
    config: ConsentConfig,
    config_path: PathBuf,
}

impl ConsentManager {
    /// Current version of the consent prompt/policy
    const CURRENT_PROMPT_VERSION: u32 = 1;

    /// Get default config path
    pub fn default_path() -> Result<PathBuf> {
        let config_dir = if cfg!(windows) {
            std::env::var("APPDATA")
                .map(PathBuf::from)
                .map_err(|_| IronError::Configuration("APPDATA not set".into()))?
        } else {
            std::env::var("HOME")
                .map(|h| PathBuf::from(h).join(".config"))
                .map_err(|_| IronError::Configuration("HOME not set".into()))?
        };

        Ok(config_dir.join("ironmon").join("consent.toml"))
    }

    /// A consent record left at the pre-rename path, when this install has none.
    ///
    /// **Deliberately not adopted.** `config.toml` and the profile audit log are
    /// copied forward by [`crate::legacy_paths::adopt`]; consent is not. Copying
    /// it would silently restore a privilege grant a user made to a program
    /// under a different name, and this crate's standing rule is that absent
    /// consent is asked for rather than assumed — the failure stays in the safe
    /// direction. What a caller can honestly do is *tell* the user the old file
    /// is there, which is what this reports.
    pub fn legacy_record() -> Option<std::path::PathBuf> {
        let current = Self::default_path().ok()?;
        crate::legacy_paths::legacy_consent_exists(&current)
    }

    /// Load consent configuration from default path
    pub fn load() -> Result<Self> {
        let path = Self::default_path()?;
        Self::load_from(&path)
    }

    /// Load consent configuration from specific path
    pub fn load_from(path: &PathBuf) -> Result<Self> {
        let config = if path.exists() {
            let contents = fs::read_to_string(path).map_err(|e| {
                IronError::Configuration(format!("Failed to read consent config: {}", e))
            })?;

            toml::from_str(&contents).map_err(|e| {
                IronError::Configuration(format!("Failed to parse consent config: {}", e))
            })?
        } else {
            ConsentConfig::default()
        };

        Ok(Self {
            config,
            config_path: path.clone(),
        })
    }

    /// Save consent configuration
    pub fn save(&self) -> Result<()> {
        // Create parent directory if it doesn't exist
        if let Some(parent) = self.config_path.parent() {
            fs::create_dir_all(parent).map_err(|e| {
                IronError::Configuration(format!("Failed to create config directory: {}", e))
            })?;
        }

        let contents = toml::to_string_pretty(&self.config).map_err(|e| {
            IronError::Configuration(format!("Failed to serialize consent config: {}", e))
        })?;

        fs::write(&self.config_path, contents).map_err(|e| {
            IronError::Configuration(format!("Failed to write consent config: {}", e))
        })?;

        Ok(())
    }

    /// Check if user has granted consent for a specific scope
    ///
    /// # Sandbox Protection
    ///
    /// Returns `false` if running in a sandboxed environment, regardless of
    /// stored consent. This ensures no data is collected during analysis or testing.
    ///
    /// # Runtime Opt-Out
    ///
    /// Also returns `false` if the IRONMON_NO_TELEMETRY or IRONMON_OFFLINE environment
    /// variables are set (via --no-telemetry or --offline CLI flags).
    pub fn has_consent(&self, scope: ConsentScope) -> bool {
        // CRITICAL: Check runtime opt-out flags first (set by CLI --no-telemetry or --offline)
        if std::env::var("IRONMON_NO_TELEMETRY").is_ok() || std::env::var("IRONMON_OFFLINE").is_ok()
        {
            return false;
        }

        // CRITICAL: Never collect data in sandboxed environments
        let sandbox_detector = crate::sandbox::SandboxDetector::new();
        if sandbox_detector.is_sandboxed() {
            return false;
        }

        // A scope with no record has not been consented to. This defaulted to
        // `true` under a comment reading "opt-in by default", which is a
        // contradiction: a default of granted is opt-out. Nothing consumed the
        // answer, so the wrong default was inert, but it would have started
        // granting consent nobody gave on the day a collector landed.
        self.config
            .records
            .get(&scope)
            .map(|r| r.granted)
            .unwrap_or(false)
    }

    /// Whether data may be collected under `scope` right now.
    ///
    /// Combines consent, sandbox detection, the runtime opt-out flags, and
    /// whether a collector for the scope exists at all. It returns `false` for
    /// every scope today, because none is implemented — see
    /// [`ConsentScope::is_collected`].
    pub fn should_collect_data(&self, scope: ConsentScope) -> bool {
        // Nothing collects under this scope, so consent to it cannot make
        // collection appropriate. Checked first: it is the reason the answer
        // is false regardless of everything below.
        if !scope.is_collected() {
            return false;
        }

        // Check runtime opt-out flags first (fastest check, set by CLI)
        if std::env::var("IRONMON_NO_TELEMETRY").is_ok() || std::env::var("IRONMON_OFFLINE").is_ok()
        {
            return false;
        }

        // Check sandbox second (fast check)
        let sandbox_detector = crate::sandbox::SandboxDetector::new();
        if sandbox_detector.is_sandboxed() {
            return false;
        }

        // Then check consent
        self.has_consent(scope)
    }

    /// Check if any consent prompt is needed (first run or consent expired)
    pub fn needs_consent_prompt(&self) -> bool {
        // First run - never prompted before
        if self.config.first_prompt_timestamp.is_none() {
            return true;
        }

        // Check if review reminder is due
        if let (Some(last_review), Some(reminder_days)) = (
            self.config.last_review_timestamp,
            self.config.review_reminder_days,
        ) {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs();

            let days_since_review = (now - last_review) / 86400;
            if days_since_review >= reminder_days as u64 {
                return true;
            }
        }

        false
    }

    /// Record consent decision for a scope
    pub fn record_consent(&mut self, scope: ConsentScope, granted: bool) -> Result<()> {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        // Update first prompt timestamp if this is the first time
        if self.config.first_prompt_timestamp.is_none() {
            self.config.first_prompt_timestamp = Some(timestamp);
        }

        // Update last review timestamp
        self.config.last_review_timestamp = Some(timestamp);

        // Create consent record
        let record = ConsentRecord {
            scope,
            granted,
            timestamp,
            prompt_version: Self::CURRENT_PROMPT_VERSION,
            ip_hash: None, // We don't collect IP addresses for consent
        };

        self.config.records.insert(scope, record);
        self.save()?;

        Ok(())
    }

    /// Revoke consent for a specific scope
    pub fn revoke_consent(&mut self, scope: ConsentScope) -> Result<()> {
        self.record_consent(scope, false)?;
        Ok(())
    }

    /// Revoke all consents
    pub fn revoke_all(&mut self) -> Result<()> {
        for scope in [
            ConsentScope::BasicTelemetry,
            ConsentScope::HardwareInfo,
            ConsentScope::PerformanceMetrics,
            ConsentScope::DetailedDiagnostics,
            ConsentScope::Analytics,
        ] {
            self.revoke_consent(scope)?;
        }
        Ok(())
    }

    /// Get all consent records
    pub fn get_all_consents(&self) -> &HashMap<ConsentScope, ConsentRecord> {
        &self.config.records
    }

    /// Export consent status as human-readable string
    pub fn export_consent_status(&self) -> String {
        let mut output = String::from("=== IronMonitor - Consent Status ===\n\n");

        if let Some(first_prompt) = self.config.first_prompt_timestamp {
            output.push_str(&format!(
                "First prompted: {}\n",
                format_timestamp(first_prompt)
            ));
        }

        if let Some(last_review) = self.config.last_review_timestamp {
            output.push_str(&format!(
                "Last reviewed: {}\n",
                format_timestamp(last_review)
            ));
        }

        output.push_str(&format!(
            "\nConsent version: {}\n\n",
            self.config.consent_version
        ));

        output.push_str("Current consents:\n");
        output.push_str("─────────────────────────────────────────\n");

        for scope in [
            ConsentScope::BasicTelemetry,
            ConsentScope::HardwareInfo,
            ConsentScope::PerformanceMetrics,
            ConsentScope::DetailedDiagnostics,
            ConsentScope::Analytics,
        ] {
            let status = if self.has_consent(scope) {
                "[+] GRANTED"
            } else {
                "[-] DENIED"
            };
            output.push_str(&format!("{:<30} {}\n", scope.name(), status));

            if let Some(record) = self.config.records.get(&scope) {
                output.push_str(&format!(
                    "  Recorded: {}\n",
                    format_timestamp(record.timestamp)
                ));
            }
        }

        output.push_str("\n=== End of Consent Status ===\n");
        output
    }

    /// Request consent interactively (CLI mode)
    pub fn request_consent(&mut self, scope: ConsentScope) -> Result<bool> {
        println!("\n╔════════════════════════════════════════════════════════════════╗");
        println!("║           IronMonitor - Data Collection Consent           ║");
        println!("╚════════════════════════════════════════════════════════════════╝\n");

        println!("Scope: {}\n", scope.name());
        println!("Description:\n{}\n", scope.description());
        println!("Data collected:");
        for point in scope.data_points() {
            println!("  * {}", point);
        }
        println!();
        println!("You can review and change your consent at any time by:");
        println!("  - Running: ironmon --consent-status");
        println!("  - Running: ironmon --revoke-consent");
        println!();

        loop {
            println!("Do you consent to this data collection? [y/N]: ");
            let mut input = String::new();
            let bytes = std::io::stdin()
                .read_line(&mut input)
                .map_err(|e| IronError::Configuration(format!("Failed to read input: {}", e)))?;

            // End of input is not an answer. It used to fall through to the
            // `""` arm below, which recorded a timestamped denial nobody gave,
            // and which also moved the review date forward and suppressed the
            // reminder. Leave the scope unrecorded instead.
            if bytes == 0 {
                return Err(IronError::Configuration(format!(
                    "no answer for {} on standard input; consent was not recorded",
                    scope.name()
                )));
            }

            let input = input.trim().to_lowercase();
            match input.as_str() {
                "y" | "yes" => {
                    self.record_consent(scope, true)?;
                    println!("[+] Consent granted for {}\n", scope.name());
                    return Ok(true);
                }
                "n" | "no" | "" => {
                    self.record_consent(scope, false)?;
                    println!("[-] Consent denied for {}\n", scope.name());
                    return Ok(false);
                }
                _ => {
                    println!("Invalid input. Please enter 'y' for yes or 'n' for no.");
                }
            }
        }
    }

    /// Request multiple consents interactively
    pub fn request_all_consents(&mut self) -> Result<()> {
        println!("\n╔════════════════════════════════════════════════════════════════╗");
        println!("║           Welcome to IronMonitor!                         ║");
        println!("╚════════════════════════════════════════════════════════════════╝\n");
        println!("This is your first time running IronMonitor.");
        println!("We respect your privacy and will only collect data you explicitly consent to.\n");
        println!("You'll be asked about several types of optional data collection.");
        println!("You can say 'no' to all of them - the tool works perfectly without any data collection.\n");

        println!("Press Enter to continue...");
        let mut input = String::new();
        std::io::stdin().read_line(&mut input).ok();

        for scope in [
            ConsentScope::BasicTelemetry,
            ConsentScope::HardwareInfo,
            ConsentScope::PerformanceMetrics,
            ConsentScope::Analytics,
        ] {
            self.request_consent(scope)?;
        }

        println!("╔════════════════════════════════════════════════════════════════╗");
        println!("║           Consent Setup Complete                              ║");
        println!("╚════════════════════════════════════════════════════════════════╝\n");
        println!("You can review or change these settings at any time:");
        println!("  ironmon --consent-status      # View current consent status");
        println!("  ironmon --revoke-consent      # Revoke all consents");
        println!("  ironmon --consent-review      # Review and change specific consents\n");

        Ok(())
    }
}

/// Format timestamp as human-readable string
fn format_timestamp(timestamp: u64) -> String {
    // An unrepresentable timestamp used to fall back to the Unix epoch, which
    // displayed as 1970-01-01 and read like a real date. Say it is unknown.
    match chrono::DateTime::from_timestamp(timestamp as i64, 0) {
        Some(datetime) => datetime.format("%Y-%m-%d %H:%M:%S UTC").to_string(),
        None => "unknown time".to_string(),
    }
}

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

    #[test]
    fn test_default_consent() {
        let manager = ConsentManager {
            config: ConsentConfig::default(),
            config_path: PathBuf::from("/tmp/test_consent.toml"),
        };

        // Test that default config has no explicit consent records
        assert!(manager.config.records.is_empty());
    }

    #[test]
    fn test_consent_recording() {
        let mut manager = ConsentManager {
            config: ConsentConfig::default(),
            config_path: PathBuf::from("/tmp/test_consent.toml"),
        };

        // Record consent
        manager
            .record_consent(ConsentScope::BasicTelemetry, true)
            .unwrap();

        // Check the record directly to bypass sandbox detection in has_consent
        // (sandbox detection may interfere with tests in CI/VMs)
        let record = manager.config.records.get(&ConsentScope::BasicTelemetry);
        assert!(record.is_some());
        assert!(record.unwrap().granted);

        // Revoke consent
        manager
            .revoke_consent(ConsentScope::BasicTelemetry)
            .unwrap();

        // Verify revocation by checking record directly
        let record = manager.config.records.get(&ConsentScope::BasicTelemetry);
        assert!(record.is_some());
        assert!(!record.unwrap().granted);
    }

    #[test]
    fn test_consent_scope_descriptions() {
        let scope = ConsentScope::BasicTelemetry;
        assert!(!scope.name().is_empty());
        assert!(!scope.description().is_empty());
        assert!(!scope.data_points().is_empty());
    }

    const EVERY_SCOPE: [ConsentScope; 5] = [
        ConsentScope::BasicTelemetry,
        ConsentScope::HardwareInfo,
        ConsentScope::PerformanceMetrics,
        ConsentScope::DetailedDiagnostics,
        ConsentScope::Analytics,
    ];

    /// The disclosure in this module, and everything `ironmon privacy` prints,
    /// says that nothing is collected. This is what makes that a checked claim
    /// rather than a comment.
    ///
    /// It fails the moment a scope is marked implemented, which is exactly when
    /// the module docs, `ironmon privacy status`, `ironmon privacy info` and
    /// `ironmon privacy opt-in` all stop being true and need rewriting. Deleting
    /// this test to make a new collector pass would remove the only thing
    /// keeping those four in step.
    #[test]
    fn granting_every_scope_still_collects_nothing() {
        let mut manager = ConsentManager {
            config: ConsentConfig::default(),
            config_path: PathBuf::from("unused-in-this-test.toml"),
        };

        for scope in EVERY_SCOPE {
            manager.config.records.insert(
                scope,
                ConsentRecord {
                    scope,
                    granted: true,
                    timestamp: 1,
                    prompt_version: 1,
                    ip_hash: None,
                },
            );
        }

        for scope in EVERY_SCOPE {
            assert!(
                !scope.is_collected(),
                concat!(
                    "{} claims to be collected. If that is now true, update the ",
                    "module docs and the three `ironmon privacy` screens, which ",
                    "all state that IronMonitor collects and transmits nothing."
                ),
                scope.name()
            );
            assert!(
                !manager.should_collect_data(scope),
                concat!(
                    "{} was granted and reported that it should collect, but ",
                    "no collector for it exists"
                ),
                scope.name()
            );
        }
    }

    /// A scope nobody has answered for is not a scope anyone agreed to.
    #[test]
    fn a_scope_with_no_record_is_not_granted() {
        let manager = ConsentManager {
            config: ConsentConfig::default(),
            config_path: PathBuf::from("unused-in-this-test.toml"),
        };

        assert!(
            manager.config.records.is_empty(),
            "the default config records no answers"
        );

        // `has_consent` consults the environment and the sandbox detector
        // first, either of which would return false for reasons unrelated to
        // the default. Read the default directly so the assertion is about
        // the default.
        let answered = manager
            .config
            .records
            .get(&ConsentScope::Analytics)
            .map(|r| r.granted)
            .unwrap_or(false);
        assert!(
            !answered,
            "an unanswered scope defaults to denied, not granted"
        );
    }
}