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
//! System Context Materialization
//!
//! This module implements the filesystem-as-context principle by materializing
//! system state as structured, queryable context that AI systems can reason about.
//!
//! The context provides a snapshot of the entire system state that can be:
//! - Serialized to JSON for LLM context windows
//! - Queried via JSONPath or structured queries
//! - Diffed against previous states for change detection
//! - Filtered by capabilities for permission-aware access

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::{SystemTime, UNIX_EPOCH};

/// Complete system context - materialized state for AI reasoning
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemContext {
    /// Context generation timestamp
    pub timestamp: u64,
    /// Context schema version
    pub schema_version: String,
    /// System identification
    pub system: SystemIdentity,
    /// Hardware inventory
    pub hardware: HardwareContext,
    /// Software/OS context
    pub software: SoftwareContext,
    /// Current metrics snapshot
    pub metrics: MetricsContext,
    /// Active alerts and events
    pub alerts: Vec<AlertContext>,
    /// Metadata about this context
    pub meta: ContextMeta,
}

impl SystemContext {
    /// Create a new context builder
    pub fn builder() -> SystemContextBuilder {
        SystemContextBuilder::new()
    }

    /// Get context as pretty-printed JSON
    pub fn to_json_pretty(&self) -> String {
        serde_json::to_string_pretty(self).unwrap_or_default()
    }

    /// Get context as compact JSON
    pub fn to_json(&self) -> String {
        serde_json::to_string(self).unwrap_or_default()
    }

    /// Get estimated token count (rough estimate: 4 chars per token)
    pub fn estimated_tokens(&self) -> usize {
        self.to_json().len() / 4
    }

    /// Create a minimal context with just essential info
    pub fn minimal(&self) -> MinimalContext {
        MinimalContext {
            timestamp: self.timestamp,
            hostname: self.system.hostname.clone(),
            os: self.system.os_name.clone(),
            // `cpu_count` has always been the logical count, which `thread_count`
            // holds. It is left logical rather than changed to the physical count.
            cpu_count: self.hardware.cpu.as_ref().map(|c| c.thread_count),
            gpu_count: self.hardware.gpus.len(),
            memory_total_gb: self.hardware.memory.as_ref().map(|m| m.total_gb),
            alert_count: self.alerts.len(),
        }
    }
}

/// Minimal context for constrained environments
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MinimalContext {
    pub timestamp: u64,
    /// `None` when the hostname was not read
    pub hostname: Option<String>,
    /// `None` where the OS name was not read.
    pub os: Option<String>,
    /// `None` where the CPU was not read: a zero would say the machine has none.
    pub cpu_count: Option<usize>,
    pub gpu_count: usize,
    /// `None` where memory was not read.
    pub memory_total_gb: Option<f64>,
    pub alert_count: usize,
}

/// System identification information
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SystemIdentity {
    /// Hostname; `None` when it was not read
    pub hostname: Option<String>,
    /// Operating system name; `None` when it was not read
    pub os_name: Option<String>,
    /// OS version; `None` when it was not read
    pub os_version: Option<String>,
    /// Kernel version; `None` when it was not read
    pub kernel_version: Option<String>,
    /// Architecture (x86_64, aarch64, etc.); `None` when it was not read
    pub architecture: Option<String>,
    /// Machine ID (unique system identifier)
    pub machine_id: Option<String>,
    /// Boot time
    pub boot_time: Option<u64>,
    /// Uptime in seconds
    pub uptime_seconds: Option<u64>,
}

/// Hardware inventory context
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct HardwareContext {
    /// CPU information
    pub cpu: Option<CpuContext>,
    /// GPU inventory
    pub gpus: Vec<GpuContext>,
    /// Memory information
    pub memory: Option<MemoryContext>,
    /// Disk inventory
    pub disks: Vec<DiskContext>,
    /// Network interface inventory
    pub network_interfaces: Vec<NetworkInterfaceContext>,
    /// Motherboard information
    pub motherboard: Option<MotherboardContext>,
    /// Power supply information
    pub power_supply: Option<PowerSupplyContext>,
    /// Fans
    pub fans: Vec<FanContext>,
    /// Temperature sensors
    pub temperature_sensors: Vec<TemperatureSensorContext>,
}

/// CPU context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CpuContext {
    /// CPU model name, or `None` where the platform reported none. This used to
    /// be an empty string, which read as a name.
    pub model: Option<String>,
    /// CPU vendor string as CPUID reports it (e.g. "GenuineIntel", "AuthenticAMD"),
    /// or `None` where it was not read. Not parsed from the model name, which
    /// used to fill this field with an empty string.
    pub vendor: Option<String>,
    /// Number of physical cores, or `None` where no count was read. This was the
    /// logical count, which `thread_count` already holds.
    pub core_count: Option<usize>,
    /// Number of logical processors (with hyperthreading)
    pub thread_count: usize,
    /// Base (nominal) frequency in MHz, or `None` where it was not read. This is
    /// never the current clock.
    pub base_frequency_mhz: Option<u32>,
    /// Max boost frequency in MHz, as reported for CPU core 0 (the first core
    /// enumerated). Cores are not guaranteed to share a limit on hybrid CPUs.
    pub max_frequency_mhz: Option<u32>,
    /// L1 cache size
    pub l1_cache_kb: Option<u32>,
    /// L2 cache size
    pub l2_cache_kb: Option<u32>,
    /// L3 cache size
    pub l3_cache_kb: Option<u32>,
    /// CPU feature flags, or `None`: no feature list is read here. This used to
    /// be an empty list, which read as "this CPU has no features".
    pub features: Option<Vec<String>>,
}

/// GPU context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GpuContext {
    /// GPU index
    pub index: usize,
    /// GPU name/model
    pub name: String,
    /// Vendor (NVIDIA, AMD, Intel, Apple)
    pub vendor: String,
    /// Total VRAM in MB
    /// Video memory in MB, or `None` where the driver reported no capacity.
    pub vram_mb: Option<u64>,
    /// Driver version
    pub driver_version: Option<String>,
    /// CUDA/ROCm/Metal version
    pub compute_version: Option<String>,
    /// PCIe information
    pub pcie: Option<PcieContext>,
    /// Supported capabilities, or `None`: none are read here. This used to be an
    /// empty list, which read as "this GPU has no capabilities".
    pub capabilities: Option<Vec<String>>,
}

/// PCIe context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PcieContext {
    /// PCIe generation (1-6), or `None` where the link was not read. This used
    /// to be a literal `0`, which is not a generation.
    pub generation: Option<u8>,
    /// Link width in lanes, or `None` where the link was not read. This used
    /// to be a literal `0`, which is not a width.
    pub width: Option<u8>,
    /// Bus ID
    pub bus_id: Option<String>,
}

/// Memory context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryContext {
    /// Total RAM in GB
    pub total_gb: f64,
    /// Memory type (DDR4, DDR5, etc.)
    pub memory_type: Option<String>,
    /// Memory speed in MHz
    pub speed_mhz: Option<u32>,
    /// Number of DIMMs
    pub dimm_count: Option<u32>,
    /// Swap/page file size in GB
    /// Swap total in GB, or `None` where the pagefile was not read.
    pub swap_total_gb: Option<f64>,
}

/// Disk context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiskContext {
    /// Disk device path or name
    pub device: String,
    /// Disk model
    pub model: Option<String>,
    /// Disk type (SSD, HDD, NVMe)
    pub disk_type: String,
    /// Total size in GB, or `None` where the capacity was not read.
    pub size_gb: Option<f64>,
    /// Mount point (if mounted). `None` when the disk has none, or when its
    /// filesystems could not be read; `filesystem_error` says which.
    pub mount_point: Option<String>,
    /// Filesystem type
    pub filesystem: Option<String>,
    /// Why the filesystem list could not be read, or `None` when it was read
    /// (an empty list is a reading too). Without this, a disk whose filesystem
    /// query failed looked like one with no mount.
    pub filesystem_error: Option<String>,
    /// Serial number (if available)
    pub serial: Option<String>,
}

/// Network interface context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkInterfaceContext {
    /// Interface name
    pub name: String,
    /// Interface type (ethernet, wifi, loopback), or `None` where the platform
    /// did not report it. Previously guessed from name prefixes such as "wl".
    pub interface_type: Option<String>,
    /// MAC address
    pub mac_address: Option<String>,
    /// IPv4 addresses, or `None` where the platform did not enumerate them.
    /// `Some(empty)` is enumerated and none present.
    pub ipv4_addresses: Option<Vec<String>>,
    /// IPv6 addresses, or `None` where the platform did not enumerate them.
    /// Windows reads neither family yet, and used to publish `[]` for it.
    pub ipv6_addresses: Option<Vec<String>>,
    /// Link speed in Mbps
    pub speed_mbps: Option<u32>,
    /// MTU
    pub mtu: Option<u32>,
    /// Whether interface is up, or `None` where the state was not read
    pub is_up: Option<bool>,
}

/// Motherboard context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MotherboardContext {
    /// Manufacturer, or `None` where the platform reported none. This used to be
    /// an empty string.
    pub manufacturer: Option<String>,
    /// Product name, or `None` where the platform reported none. This used to be
    /// an empty string.
    pub product: Option<String>,
    /// BIOS vendor
    pub bios_vendor: Option<String>,
    /// BIOS version
    pub bios_version: Option<String>,
    /// BIOS date
    pub bios_date: Option<String>,
    /// Chassis type
    pub chassis_type: Option<String>,
}

/// Power supply context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PowerSupplyContext {
    /// Power supply status
    pub status: String,
    /// Whether on AC power. `None` when the platform did not report it --
    /// which used to be indistinguishable from `false`, "on battery".
    pub on_ac_power: Option<bool>,
    /// Battery percentage (if applicable)
    pub battery_percent: Option<f32>,
    /// Battery status (charging, discharging, full)
    pub battery_status: Option<String>,
    /// Estimated time remaining (minutes)
    pub time_remaining_minutes: Option<u32>,
}

/// Fan context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FanContext {
    /// Fan name/label
    pub name: String,
    /// Current speed in RPM
    pub speed_rpm: Option<u32>,
    /// Speed percentage (0-100)
    pub speed_percent: Option<u8>,
    /// Minimum RPM
    pub min_rpm: Option<u32>,
    /// Maximum RPM
    pub max_rpm: Option<u32>,
}

/// Temperature sensor context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemperatureSensorContext {
    /// Sensor name/label
    pub name: String,
    /// Current temperature in Celsius, or `None` where the sensor exists and
    /// could not be read. Serialises as `null`, matching the thresholds beside
    /// it, which were always optional.
    pub temperature_c: Option<f32>,
    /// High threshold
    pub high_threshold_c: Option<f32>,
    /// Critical threshold
    pub critical_threshold_c: Option<f32>,
    /// Sensor location (CPU, GPU, Chassis, etc.)
    pub location: Option<String>,
}

/// Software/OS context
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SoftwareContext {
    /// Running processes count
    pub process_count: usize,
    /// Running services
    /// Running services. `None` because service enumeration is not implemented on
    /// any platform; an empty list would say the machine has no services.
    pub services: Option<Vec<ServiceContext>>,
    /// Installed drivers
    pub drivers: Vec<DriverContext>,
    /// Boot configuration
    pub boot_config: Option<BootConfigContext>,
}

/// Service context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceContext {
    /// Service name
    pub name: String,
    /// Display name
    pub display_name: Option<String>,
    /// Status (running, stopped, etc.)
    pub status: String,
    /// Start type (auto, manual, disabled)
    pub start_type: Option<String>,
    /// PID if running
    pub pid: Option<u32>,
}

/// Driver context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DriverContext {
    /// Driver name
    pub name: String,
    /// Version
    pub version: Option<String>,
    /// Provider
    pub provider: Option<String>,
    /// Date
    pub date: Option<String>,
}

/// Boot configuration context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BootConfigContext {
    /// Boot mode (UEFI, Legacy), or `None` where the firmware type was not
    /// determined. This was the string "Unknown" in that case.
    pub boot_mode: Option<String>,
    /// Secure boot enabled
    pub secure_boot: Option<bool>,
    /// Boot entries. `None` because they are not enumerated; an empty list would
    /// say the machine has no boot entries.
    pub boot_entries: Option<Vec<String>>,
}

/// Current metrics snapshot
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct MetricsContext {
    /// CPU metrics
    pub cpu: Option<CpuMetrics>,
    /// GPU metrics (per GPU)
    pub gpus: Vec<GpuMetrics>,
    /// Memory metrics
    pub memory: Option<MemoryMetrics>,
    /// Disk metrics (per disk)
    pub disks: Vec<DiskMetrics>,
    /// Network metrics (per interface)
    pub network: Vec<NetworkMetrics>,
    /// Top processes
    pub top_processes: Vec<ProcessMetrics>,
    /// System load
    pub system_load: Option<SystemLoadMetrics>,
}

/// CPU metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CpuMetrics {
    /// Overall CPU utilization (0-100)
    pub utilization_percent: f32,
    /// Per-core utilization
    /// Per-core utilization, `None` for a core whose idle time was not read.
    ///
    /// A core that reported nothing used to arrive here as `100.0 - 100.0`, a
    /// measured 0% busy. See `agent::state::CpuState::per_core_usage`.
    pub per_core_utilization: Vec<Option<f32>>,
    /// Current clock in MHz of CPU core 0 (the first core enumerated), not of the
    /// package or of every core. Per-core clocks are not in this struct.
    pub frequency_mhz: Option<u32>,
    /// Temperature in Celsius
    pub temperature_c: Option<f32>,
}

/// GPU metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GpuMetrics {
    /// GPU index
    pub index: usize,
    /// GPU utilization (0-100)
    /// Utilization percentage, or `None` where the device reports no counter.
    pub utilization_percent: Option<f32>,
    /// Memory used in MB
    /// GPU memory used in MB, or `None` where unreported.
    pub memory_used_mb: Option<u64>,
    /// Memory total in MB
    /// GPU memory total in MB, or `None` where unreported.
    pub memory_total_mb: Option<u64>,
    /// Temperature in Celsius
    pub temperature_c: Option<f32>,
    /// Power draw in watts
    pub power_watts: Option<f32>,
    /// Fan speed percentage
    pub fan_speed_percent: Option<u8>,
    /// Clock speeds
    pub clocks: Option<GpuClocks>,
}

/// GPU clock speeds
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GpuClocks {
    /// Graphics clock in MHz
    pub graphics_mhz: Option<u32>,
    /// Memory clock in MHz
    pub memory_mhz: Option<u32>,
    /// SM/shader clock in MHz
    pub sm_mhz: Option<u32>,
}

/// Memory metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryMetrics {
    /// Used memory in MB
    pub used_mb: u64,
    /// Free memory in MB, or `None` where it was not read.
    pub free_mb: Option<u64>,
    /// Total memory in MB
    pub total_mb: u64,
    /// Cached memory in MB
    pub cached_mb: Option<u64>,
    /// Buffers in MB
    pub buffers_mb: Option<u64>,
    /// Swap used in MB
    /// Swap in use in MB, or `None` where the pagefile was not read.
    pub swap_used_mb: Option<u64>,
    /// Swap total in MB
    /// Swap total in MB, or `None` where the pagefile was not read.
    pub swap_total_mb: Option<u64>,
}

/// Disk metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiskMetrics {
    /// Device name
    pub device: String,
    /// Used space in GB, or `None` where the filesystem did not report it.
    ///
    /// **Bare beside four `Option` throughput fields**, and reached by the
    /// compiler from `FilesystemInfo` rather than by the scan that had already
    /// flagged it -- these three were being filled from figures that WMI
    /// reports as nullable and that were flattened to `0` on the way here.
    pub used_gb: Option<f64>,
    /// Free space in GB, or `None` where not reported.
    pub free_gb: Option<f64>,
    /// Total space in GB, or `None` where not reported.
    pub total_gb: Option<f64>,
    /// Read bytes per second
    pub read_bps: Option<u64>,
    /// Write bytes per second
    pub write_bps: Option<u64>,
    /// IOPS read
    pub iops_read: Option<u64>,
    /// IOPS write
    pub iops_write: Option<u64>,
    /// Why this disk's filesystem could not be read, or `None` when it was. A disk
    /// whose filesystem query failed used to produce no row at all.
    pub error: Option<String>,
}

/// Network metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkMetrics {
    /// Interface name
    pub interface: String,
    /// Received bytes per second, or `None` until a second sample.
    ///
    /// A rate is a difference between two readings; the first reading has
    /// nothing to difference against. This was a bare `f64` reporting `0.0`,
    /// which states the link is idle.
    pub rx_bps: Option<f64>,
    /// Transmitted bytes per second. See [`Self::rx_bps`].
    pub tx_bps: Option<f64>,
    /// Total received bytes
    pub rx_bytes_total: u64,
    /// Total transmitted bytes
    pub tx_bytes_total: u64,
    /// Packets received
    pub rx_packets: u64,
    /// Packets transmitted
    pub tx_packets: u64,
    /// Errors
    pub errors: u64,
    /// Dropped packets, where every interface counts drops in both
    /// directions; macOS counts no transmit drops.
    pub dropped: Option<u64>,
}

/// Process metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProcessMetrics {
    /// Process ID
    pub pid: u32,
    /// Process name
    pub name: String,
    /// CPU usage percentage, `None` when not yet known (see
    /// [`crate::process_monitor::ProcessMonitorInfo::cpu_percent`])
    pub cpu_percent: Option<f32>,
    /// Memory usage in MB
    pub memory_mb: u64,
    /// GPU memory in MB (if using GPU)
    pub gpu_memory_mb: Option<u64>,
    /// Thread count
    pub threads: u32,
    /// User
    pub user: Option<String>,
    /// Command line
    pub command: Option<String>,
}

/// System load metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemLoadMetrics {
    /// 1-minute load average, or `None` where the platform has no such figure.
    ///
    /// Load average is a Unix quantity: a decaying average of the number of
    /// tasks runnable or in uninterruptible sleep. Windows has no equivalent
    /// and publishes nothing that can be converted into one.
    ///
    /// It said `f64`, and the Windows arm filled all three from instantaneous
    /// CPU utilisation -- `(usage / 100) * cores`, assigned to the 1, 5 and 15
    /// minute figures alike. That is not a load average by any reading. It
    /// cannot exceed the core count, so the queue depth that makes the metric
    /// worth having is exactly what it cannot express; it has no history, so
    /// the three windows that distinguish a spike from a trend were identical;
    /// and it counts busy CPUs rather than waiting tasks, so a machine wedged
    /// on I/O -- the case load average exists to expose -- read as idle.
    pub load_1: Option<f64>,
    /// 5-minute load average. See [`Self::load_1`].
    pub load_5: Option<f64>,
    /// 15-minute load average. See [`Self::load_1`].
    pub load_15: Option<f64>,
    /// Processes in the running state, or `None` where unreported.
    pub running_processes: Option<u32>,
    /// Total processes, or `None` where unreported.
    pub total_processes: Option<u32>,
}

/// Alert context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AlertContext {
    /// Alert ID
    pub id: String,
    /// Alert severity (info, warning, critical)
    pub severity: String,
    /// Alert message
    pub message: String,
    /// Alert source (cpu, gpu, memory, etc.)
    pub source: String,
    /// When the alert was triggered
    pub timestamp: u64,
    /// Additional context/metadata
    pub metadata: HashMap<String, String>,
}

/// Metadata about the context
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ContextMeta {
    /// Time to generate context in milliseconds
    pub generation_time_ms: u64,
    /// Context size in bytes
    pub size_bytes: usize,
    /// Which capabilities were included
    pub included_capabilities: Vec<String>,
    /// Which capabilities were not included. Either filtered out by permissions,
    /// or permitted but not collected, in which case the entry says why.
    pub excluded_capabilities: Vec<String>,
}

/// Builder for creating system context
pub struct SystemContextBuilder {
    context: SystemContext,
    start_time: std::time::Instant,
}

impl SystemContextBuilder {
    pub fn new() -> Self {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);

        Self {
            context: SystemContext {
                timestamp,
                schema_version: "1.0.0".to_string(),
                system: SystemIdentity::default(),
                hardware: HardwareContext::default(),
                software: SoftwareContext::default(),
                metrics: MetricsContext::default(),
                alerts: Vec::new(),
                meta: ContextMeta::default(),
            },
            start_time: std::time::Instant::now(),
        }
    }

    pub fn system(mut self, system: SystemIdentity) -> Self {
        self.context.system = system;
        self
    }

    pub fn hardware(mut self, hardware: HardwareContext) -> Self {
        self.context.hardware = hardware;
        self
    }

    pub fn software(mut self, software: SoftwareContext) -> Self {
        self.context.software = software;
        self
    }

    pub fn metrics(mut self, metrics: MetricsContext) -> Self {
        self.context.metrics = metrics;
        self
    }

    pub fn alerts(mut self, alerts: Vec<AlertContext>) -> Self {
        self.context.alerts = alerts;
        self
    }

    pub fn build(mut self) -> SystemContext {
        let generation_time = self.start_time.elapsed().as_millis() as u64;
        let json = serde_json::to_string(&self.context).unwrap_or_default();

        self.context.meta.generation_time_ms = generation_time;
        self.context.meta.size_bytes = json.len();

        self.context
    }
}

impl Default for SystemContextBuilder {
    fn default() -> Self {
        Self::new()
    }
}