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
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
//! Unified monitoring backend for CLI, TUI, and GUI modes
//!
//! This module provides a single, consistent interface for accessing all hardware
//! monitoring data and the AI agent system. All frontends (CLI, TUI, GUI) should
//! use this backend to ensure consistent behavior.

use std::collections::VecDeque;
use std::time::{Duration, Instant};

use serde::{Deserialize, Serialize};

use crate::agent::{Agent, AgentConfig, AgentResponse, ModelSize};
use crate::connections::{ConnectionInfo, ConnectionMonitor, ConnectionState, Protocol};
use crate::core::cpu::CpuStats;
use crate::core::memory::MemoryStats;
use crate::disk::{self, DiskDevice};
use crate::error::{IronError, Result};
use crate::gpu::{GpuCollection, GpuDynamicInfo, GpuStaticInfo};
use crate::motherboard::{self, DriverInfo, MotherboardDevice, SystemInfo as MBSystemInfo};
use crate::network_monitor::NetworkMonitor;
use crate::process_monitor::{ProcessMonitor, ProcessMonitorInfo};
use crate::system_stats::SystemStats;
use crate::UnifiedMonitor;

/// Default history buffer size for time-series data
pub const DEFAULT_HISTORY_SIZE: usize = 60;

/// Default update interval
pub const DEFAULT_UPDATE_INTERVAL: Duration = Duration::from_secs(1);

// ============================================================================
// UNIFIED SYSTEM STATE FOR AI AGENT
// ============================================================================

/// Complete system state snapshot for AI agent context
/// This extends the GPU-only SystemState to include all hardware
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FullSystemState {
    /// CPU state
    pub cpu: Option<CpuState>,

    /// Memory state
    pub memory: Option<MemoryState>,

    /// GPU/Accelerator states
    pub accelerators: Vec<AcceleratorState>,

    /// Disk states, or `None` where enumeration failed. `Some(vec![])` is a
    /// machine with no disks. Was a `Vec` filled by `unwrap_or_default()`, so a
    /// failed enumeration read as "no disks".
    pub disks: Option<Vec<DiskState>>,

    /// Network interface states
    pub network: Vec<NetworkState>,

    /// Top processes by resource usage, or `None` where the process list was
    /// not read. Was a `Vec`, so an unread list read as "no processes".
    pub top_processes: Option<Vec<ProcessState>>,

    /// System information
    pub system: Option<SystemInfoState>,

    /// Timestamp of state capture
    pub timestamp: u64,
}

/// CPU state for AI context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CpuState {
    /// CPU model name, or `None` where it was not read.
    pub name: Option<String>,

    /// Physical cores, or `None` where the platform reported no count
    /// distinct from the logical one.
    ///
    /// **The sixth surface of a defect the other five were fixed for.** This
    /// was `cpu.cores.len()` -- one entry per *logical* processor -- beside
    /// `threads` taking the same value under a `// Simplified` comment. So the
    /// AI context read "AMD Ryzen 9 9900X 12-Core Processor (24 cores)", the
    /// name and the figure contradicting each other one space apart. HANDOFF,
    /// "A 12-core CPU that read 24", records the fix to the TUI and four other
    /// surfaces; this one was not among them. It now reads the same source as
    /// the TUI, `CpuMicroarchMonitor`'s physical count.
    pub cores: Option<usize>,

    /// Logical processors (hardware threads).
    pub threads: usize,

    /// Overall utilization (0-100%)
    pub utilization: f32,

    /// Temperature (Celsius)
    pub temperature: Option<f32>,

    /// Current frequency (MHz)
    pub frequency_mhz: Option<u64>,

    /// Per-core utilization
    /// Per-core utilization, `None` for a core whose idle time was not read.
    ///
    /// Was `Vec<f32>`, filled with `100.0 - c.idle.unwrap_or(100.0)` -- so an
    /// unread core arrived as a measured 0% busy. The type could not say
    /// "not read", which is the fault the queued section of the handoff is
    /// about, and it had eight copies.
    pub per_core_usage: Vec<Option<f32>>,
}

/// Memory state for AI context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MemoryState {
    /// Total RAM (bytes)
    pub total_bytes: u64,

    /// Used RAM (bytes)
    pub used_bytes: u64,

    /// Available RAM (bytes)
    pub available_bytes: u64,

    /// Usage percentage, or `None` where no RAM total was read.
    pub usage_percent: Option<f32>,

    /// Total swap (bytes)
    /// Swap total in bytes, or `None` where the platform reported none.
    ///
    /// Filled with `total_or_zero()` until 6.0.0, so a machine whose pagefile
    /// could not be read was published as having no swap.
    pub swap_total_bytes: Option<u64>,

    /// Used swap (bytes)
    /// Swap in use in bytes, or `None`. See [`Self::swap_total_bytes`].
    pub swap_used_bytes: Option<u64>,

    /// Swap usage percentage
    /// Swap usage percentage, or `None` when there was nothing to derive it
    /// from. This was computed against a total that could be zero and answered
    /// `0.0` in that case.
    pub swap_usage_percent: Option<f32>,
}

/// Accelerator state (GPU/NPU/FPGA/etc.) for AI context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AcceleratorState {
    /// Accelerator index
    pub index: usize,

    /// Accelerator type
    pub accel_type: String,

    /// Device name
    pub name: String,

    /// Vendor name
    pub vendor: String,

    /// Utilization (0-100%)
    /// Utilization percentage, or `None` where the device reports no counter.
    pub utilization: Option<f32>,

    /// Memory used in bytes, or `None` where the device reported none.
    pub memory_used_bytes: Option<u64>,

    /// Memory total in bytes, or `None` where the device reported none.
    pub memory_total_bytes: Option<u64>,

    /// Memory usage percentage, or `None` when there was nothing to derive it
    /// from. This was computed here against a total that could be zero, and
    /// answered `0.0` in that case.
    pub memory_usage_percent: Option<f32>,

    /// Temperature (Celsius)
    pub temperature: Option<f32>,

    /// Power usage (Watts)
    pub power_watts: Option<f32>,

    /// Power limit (Watts)
    pub power_limit_watts: Option<f32>,

    /// Core clock (MHz)
    pub clock_mhz: Option<u32>,

    /// Memory clock (MHz)
    pub memory_clock_mhz: Option<u32>,

    /// Number of processes using this accelerator, or `None` when its process
    /// list could not be read. Was `dynamic_info.processes.len()`, but no dynamic
    /// sample carries a process list (every adapter leaves it empty and reports
    /// processes through its own `processes()` call), so it read `0` for every
    /// device, a measured-looking count of nothing.
    pub process_count: Option<usize>,
}

/// Disk state for AI context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiskState {
    /// Disk name/model
    pub name: String,

    /// Mount point
    pub mount_point: String,

    /// Filesystem type
    pub filesystem: String,

    /// Total space (bytes), or `None` where the capacity was not read.
    pub total_bytes: Option<u64>,

    /// Used space (bytes), or `None` where no filesystem reported one.
    ///
    /// The `(String::new(), String::new(), 0)` fallback below set this to `0`
    /// for a disk with no readable filesystem -- a mounted volume using none
    /// of itself.
    pub used_bytes: Option<u64>,

    /// Usage percentage, or `None` where the capacity was not read.
    pub usage_percent: Option<f32>,
}

/// Network interface state for AI context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkState {
    /// Interface name
    pub name: String,

    /// Is interface up, or `None` where the state was not read
    pub is_up: Option<bool>,

    /// Bytes received
    pub rx_bytes: u64,

    /// Bytes transmitted
    pub tx_bytes: u64,

    /// Receive rate in bytes/sec, or `None` until a second sample.
    ///
    /// A rate is a difference between two readings, and the first read of an
    /// interface has nothing to difference against.
    pub rx_rate: Option<f64>,

    /// Transmit rate in bytes/sec. See [`Self::rx_rate`].
    pub tx_rate: Option<f64>,
}

/// Process state for AI context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProcessState {
    /// 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 (bytes)
    pub memory_bytes: u64,

    /// GPU memory usage (bytes)
    /// GPU memory in bytes, or `None` where no device reported one. NVML does
    /// not expose this under WDDM.
    pub gpu_memory_bytes: Option<u64>,

    /// GPU indices used, or `None` when GPU attribution did not run. Empty
    /// means it ran and found none.
    pub gpu_indices: Option<Vec<usize>>,
}

/// System information state for AI context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SystemInfoState {
    /// Hostname
    pub hostname: String,

    /// Operating system
    pub os: String,

    /// Kernel version
    pub kernel: String,

    /// System uptime (seconds) as the OS reports it, or `None` when it was not
    /// read. This was the monitor's own age (`start_time.elapsed()`), which
    /// the AI context then presented as how long the machine had been up.
    pub uptime_secs: Option<u64>,
}

impl FullSystemState {
    /// Create an empty system state
    pub fn empty() -> Self {
        Self {
            cpu: None,
            memory: None,
            accelerators: Vec::new(),
            disks: None,
            network: Vec::new(),
            top_processes: None,
            system: None,
            timestamp: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs(),
        }
    }

    /// Format state as natural language text for AI agent context
    pub fn to_context_string(&self) -> String {
        let mut ctx = String::new();
        ctx.push_str("=== Current System State ===\n\n");

        // System info
        if let Some(ref sys) = self.system {
            // An empty string is a field that was not read; it is named as such.
            let or_unknown = |s: &str| if s.is_empty() { "unknown" } else { s }.to_string();
            let uptime = sys.uptime_secs.map_or_else(
                || "unknown".to_string(),
                |secs| format!("{}h {}m", secs / 3600, (secs % 3600) / 60),
            );
            ctx.push_str(&format!(
                "Host: {} | OS: {} | Kernel: {} | Uptime: {}\n\n",
                or_unknown(&sys.hostname),
                or_unknown(&sys.os),
                or_unknown(&sys.kernel),
                uptime
            ));
        }

        // CPU
        if let Some(ref cpu) = self.cpu {
            ctx.push_str(&format!(
                "CPU: {} ({})\n  Utilization: {:.1}%",
                cpu.name.as_deref().unwrap_or("unknown"),
                // Physical and logical named separately, and the physical count
                // left out rather than guessed when the platform gave none.
                match cpu.cores {
                    Some(cores) => format!("{cores} cores, {} threads", cpu.threads),
                    None => format!("{} threads", cpu.threads),
                },
                cpu.utilization
            ));
            if let Some(temp) = cpu.temperature {
                ctx.push_str(&format!(" | Temp: {:.0}°C", temp));
            }
            if let Some(freq) = cpu.frequency_mhz {
                ctx.push_str(&format!(" | Freq: {} MHz", freq));
            }
            ctx.push_str("\n\n");
        }

        // Memory
        if let Some(ref mem) = self.memory {
            let used_gb = mem.used_bytes as f64 / 1024.0 / 1024.0 / 1024.0;
            let total_gb = mem.total_bytes as f64 / 1024.0 / 1024.0 / 1024.0;
            let pct = mem
                .usage_percent
                .map_or_else(|| "not read".to_string(), |p| format!("{:.1}%", p));
            ctx.push_str(&format!(
                "Memory: {:.1}GB / {:.1}GB ({})\n",
                used_gb, total_gb, pct
            ));
            // Written out only where the pagefile was read. The `> 0` test
            // could not tell an unread pagefile from an absent one, so a
            // machine whose swap query failed silently lost the line.
            if let (Some(used), Some(total), Some(pct)) = (
                mem.swap_used_bytes,
                mem.swap_total_bytes,
                mem.swap_usage_percent,
            ) {
                ctx.push_str(&format!(
                    "Swap: {:.1}GB / {:.1}GB ({:.1}%)\n",
                    used as f64 / 1024.0 / 1024.0 / 1024.0,
                    total as f64 / 1024.0 / 1024.0 / 1024.0,
                    pct
                ));
            }
            ctx.push('\n');
        }

        // Accelerators
        if !self.accelerators.is_empty() {
            ctx.push_str("Accelerators:\n");
            for accel in &self.accelerators {
                ctx.push_str(&format!(
                    "  {} {}: {} ({})\n",
                    accel.accel_type, accel.index, accel.name, accel.vendor
                ));
                match accel.utilization {
                    Some(u) => ctx.push_str(&format!("    Utilization: {u:.0}%")),
                    None => ctx.push_str("    Utilization: not reported"),
                }
                if let Some(temp) = accel.temperature {
                    ctx.push_str(&format!(" | Temp: {:.0}°C", temp));
                }
                if let Some(power) = accel.power_watts {
                    ctx.push_str(&format!(" | Power: {:.0}W", power));
                    if let Some(limit) = accel.power_limit_watts {
                        ctx.push_str(&format!("/{:.0}W", limit));
                    }
                }
                ctx.push('\n');
                // Written out only where there is something to write. A
                // model shown "0.0GB / 0.0GB (0.0%)" will reason about an idle
                // card; shown nothing, it reasons about the rest.
                const GB: f64 = 1024.0 * 1024.0 * 1024.0;
                match (
                    accel.memory_used_bytes,
                    accel.memory_total_bytes,
                    accel.memory_usage_percent,
                ) {
                    (Some(used), Some(total), Some(pct)) => ctx.push_str(&format!(
                        "    Memory: {:.1}GB / {:.1}GB ({:.1}%)\n",
                        used as f64 / GB,
                        total as f64 / GB,
                        pct
                    )),
                    (Some(used), None, _) => ctx.push_str(&format!(
                        "    Memory: {:.1}GB used, capacity not reported\n",
                        used as f64 / GB
                    )),
                    _ => ctx.push_str("    Memory: not reported\n"),
                }
            }
            ctx.push('\n');
        }

        // Disks
        match &self.disks {
            None => ctx.push_str("Disks: not read\n\n"),
            Some(disks) if disks.is_empty() => ctx.push_str("Disks: none enumerated\n\n"),
            Some(disks) => {
                ctx.push_str("Disks:\n");
                for disk in disks {
                    const GIB: f64 = 1024.0 * 1024.0 * 1024.0;
                    // Shown only where it is a measurement. This was
                    // `disk.used_bytes as f64 / GIB` over a fabricated zero.
                    let used_gb = disk.used_bytes.map_or("unknown".to_string(), |b| {
                        format!("{:.1}GB", b as f64 / GIB)
                    });
                    match (disk.total_bytes, disk.usage_percent) {
                        (Some(total), Some(pct)) => ctx.push_str(&format!(
                            "  {}: {} / {:.1}GB ({:.1}%) at {}\n",
                            disk.name,
                            used_gb,
                            total as f64 / GIB,
                            pct,
                            disk.mount_point
                        )),
                        // Capacity unread: the used figure is still a measurement
                        // and is shown; the total is named unknown rather than
                        // rendered as 0.0GB at 0.0%.
                        _ => ctx.push_str(&format!(
                            "  {}: {} / capacity unknown at {}\n",
                            disk.name, used_gb, disk.mount_point
                        )),
                    }
                }
                ctx.push('\n');
            }
        }

        // Top processes
        match &self.top_processes {
            None => ctx.push_str("Top Processes: not read\n\n"),
            Some(procs) if procs.is_empty() => {}
            Some(procs) => {
                ctx.push_str("Top Processes (by CPU):\n");
                for proc in procs.iter().take(5) {
                    ctx.push_str(&format!(
                        "  {} (PID {}): CPU {}, Memory {:.0}MB",
                        proc.name,
                        proc.pid,
                        proc.cpu_percent
                            .map_or_else(|| "not yet known".to_string(), |c| format!("{c:.1}%")),
                        proc.memory_bytes as f64 / 1024.0 / 1024.0
                    ));
                    if let Some(bytes) = proc.gpu_memory_bytes.filter(|b| *b > 0) {
                        ctx.push_str(&format!(
                            ", GPU Mem {:.0}MB",
                            bytes as f64 / 1024.0 / 1024.0
                        ));
                    }
                    ctx.push('\n');
                }
            }
        }

        ctx
    }
}

// ============================================================================
// HISTORY BUFFER FOR TIME-SERIES DATA
// ============================================================================

/// Generic history buffer for time-series data
#[derive(Debug, Clone)]
pub struct HistoryBuffer<T: Clone> {
    data: VecDeque<T>,
    capacity: usize,
}

impl<T: Clone> HistoryBuffer<T> {
    /// Create a new history buffer with given capacity
    pub fn new(capacity: usize) -> Self {
        Self {
            data: VecDeque::with_capacity(capacity),
            capacity,
        }
    }

    /// Push a new value, removing oldest if at capacity
    pub fn push(&mut self, value: T) {
        if self.data.len() >= self.capacity {
            self.data.pop_front();
        }
        self.data.push_back(value);
    }

    /// Get all values as a slice
    pub fn values(&self) -> impl Iterator<Item = &T> {
        self.data.iter()
    }

    /// Get the most recent value
    pub fn latest(&self) -> Option<&T> {
        self.data.back()
    }

    /// Get the previous value (second to last)
    pub fn previous(&self) -> Option<&T> {
        self.data.iter().rev().nth(1)
    }

    /// Clear all history
    pub fn clear(&mut self) {
        self.data.clear();
    }

    /// Check if buffer is empty
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// Get number of values in buffer
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Convert to Vec
    pub fn to_vec(&self) -> Vec<T> {
        self.data.iter().cloned().collect()
    }
}

impl<T: Clone + Into<u64>> HistoryBuffer<T> {
    /// Convert values to u64 for sparkline rendering
    pub fn as_u64_vec(&self) -> Vec<u64> {
        self.data.iter().cloned().map(Into::into).collect()
    }
}

impl<T: Clone + Into<f32>> HistoryBuffer<T> {
    /// Convert values to f32 for chart rendering
    pub fn as_f32_vec(&self) -> Vec<f32> {
        self.data.iter().cloned().map(Into::into).collect()
    }
}

// ============================================================================
// UNIFIED MONITORING BACKEND
// ============================================================================

/// Unified monitoring backend providing consistent data access for CLI, TUI, and GUI
pub struct MonitoringBackend {
    // === Hardware monitors ===
    /// GPU/Accelerator collection
    gpu_collection: Option<GpuCollection>,

    /// Process monitor (with GPU attribution)
    process_monitor: Option<ProcessMonitor>,

    /// Network monitor
    network_monitor: Option<NetworkMonitor>,

    /// Connection monitor (netstat-like)
    connection_monitor: Option<ConnectionMonitor>,

    /// Disk devices, or `None` where enumeration failed. Every list field in
    /// this struct is `None` when it was not read, and `Some(vec![])` only when
    /// the read succeeded and found nothing.
    disks: Option<Vec<Box<dyn DiskDevice>>>,

    /// Motherboard sensors, or `None` where enumeration failed.
    motherboard_sensors: Option<Vec<Box<dyn MotherboardDevice>>>,

    // === Cached data ===
    /// Cached CPU stats
    cpu_stats: Option<CpuStats>,

    /// Cached memory stats
    memory_stats: Option<MemoryStats>,

    /// Cached GPU static info, one slot per enumerated device in collection
    /// order. A slot is `None` where that device's static query failed; the
    /// other slots keep their positions.
    gpu_static_info: Vec<Option<GpuStaticInfo>>,

    /// Cached GPU dynamic info, one slot per enumerated device, with the same
    /// positions as `gpu_static_info`. `None` where that device's sample failed.
    gpu_dynamic_info: Vec<Option<GpuDynamicInfo>>,

    /// Cached process list, or `None` where it was not read.
    processes: Option<Vec<ProcessMonitorInfo>>,

    /// Cached connection list, or `None` where it was not read.
    connections: Option<Vec<ConnectionInfo>>,

    /// System info
    system_info: Option<MBSystemInfo>,

    /// System stats (load avg, vmstat, etc.)
    system_stats: Option<SystemStats>,

    /// Driver inventory, enumerated on first request.
    ///
    /// `motherboard::get_driver_versions` queries `Win32_PnPSignedDriver`, which
    /// measured 7.1s on this host — more than half the cost of constructing a backend,
    /// paid by every `ironmon cli` invocation for a getter no caller in the tree ever
    /// invokes.
    driver_info: std::cell::OnceCell<Option<Vec<DriverInfo>>>,

    // === History buffers ===
    /// CPU utilization history
    cpu_history: HistoryBuffer<f32>,

    /// Memory utilization history
    memory_history: HistoryBuffer<f32>,

    /// Per-accelerator utilization history
    accelerator_histories: Vec<HistoryBuffer<f32>>,

    /// Per-accelerator memory history
    accelerator_memory_histories: Vec<HistoryBuffer<f32>>,

    /// Per-accelerator temperature history
    accelerator_temp_histories: Vec<HistoryBuffer<f32>>,

    /// Network RX rate history
    network_rx_history: HistoryBuffer<f32>,

    /// Network TX rate history
    network_tx_history: HistoryBuffer<f32>,

    // === AI Agent ===
    /// AI agent, detected on first request.
    ///
    /// Detection probes five local ports and cost 1.2s at construction — again on
    /// every invocation — for an agent the CLI frontends never ask anything.
    agent: std::cell::OnceCell<Option<Agent>>,

    /// Whether an agent may be built at all, from `BackendConfig::enable_agent`.
    agent_enabled: bool,

    /// Agent request timeout, held for the deferred construction.
    agent_timeout_secs: u64,

    /// UnifiedMonitor for agent context
    unified_monitor: Option<UnifiedMonitor>,

    /// Agent response history
    agent_history: VecDeque<AgentResponse>,

    // === Timing ===
    /// Last update time
    last_update: Instant,

    /// Update interval
    update_interval: Duration,

    /// Start time for uptime calculation
    start_time: Instant,

    // === System identification ===
    /// Hostname
    hostname: String,

    /// OS info string
    os_info: String,
}

impl MonitoringBackend {
    /// Create a new monitoring backend with all available monitors
    pub fn new() -> Result<Self> {
        Self::with_config(BackendConfig::default())
    }

    /// Create a new monitoring backend with custom configuration
    pub fn with_config(config: BackendConfig) -> Result<Self> {
        // Initialize GPU collection
        let gpu_collection = GpuCollection::auto_detect().ok();

        // Initialize GPU static info
        let (gpu_static_info, gpu_dynamic_info) = if let Some(ref gpus) = gpu_collection {
            // Static descriptors come from the static query alone. `snapshot_all`
            // also needs every device's dynamic sample, and Apple silicon's comes
            // from `powermetrics`, which needs root, so a non-root run listed no GPU.
            // One slot per device. A device whose static query failed keeps its
            // slot as `None`; the readable devices are not dropped with it.
            let static_info: Vec<Option<GpuStaticInfo>> = gpus
                .gpus()
                .iter()
                .map(|gpu| gpu.static_info().ok())
                .collect();
            let dynamic_info = Self::dynamic_slots(gpus, static_info.len());
            (static_info, dynamic_info)
        } else {
            (Vec::new(), Vec::new())
        };

        let gpu_count = gpu_static_info.len();

        // Initialize process monitor (standalone, will update GPU info later)
        let process_monitor = ProcessMonitor::new().ok();

        // Initialize network monitor
        let network_monitor = NetworkMonitor::new().ok();

        // Initialize connection monitor
        let connection_monitor = ConnectionMonitor::new().ok();

        // Initialize disk devices
        // A failed enumeration is `None` ("not read"), not an empty list ("none exist").
        let disks = disk::enumerate_disks().ok();

        // Initialize motherboard sensors
        let motherboard_sensors = motherboard::enumerate_sensors().ok();

        // Get system info
        let system_info = motherboard::get_system_info().ok();

        // Driver inventory is deferred; see the field.
        let driver_info = std::cell::OnceCell::new();

        // Get system stats
        let system_stats = SystemStats::new().ok();

        // Get hostname and OS info
        // Empty when unread, which callers render as unknown. This was the
        // literal "unknown", indistinguishable from a machine so named.
        #[cfg(any(feature = "cli", feature = "gui"))]
        let hostname = hostname::get()
            .map(|h| h.to_string_lossy().to_string())
            .unwrap_or_default();
        #[cfg(not(any(feature = "cli", feature = "gui")))]
        let hostname = String::new();

        let os_info = std::env::consts::OS.to_string();

        // Agent detection is deferred; see the field.
        let agent = std::cell::OnceCell::new();

        // Built on first use by `ask_agent`, not here.
        //
        // The comment this replaces claimed it shared the GPU collection above; it
        // does not. `UnifiedMonitor::new` runs its own `GpuCollection::auto_detect`,
        // so constructing a backend enumerated every GPU twice — measured at 260ms on
        // an idle three-GPU host and seconds on a busy one — to serve an agent query
        // that most invocations never make. `ironmon cli gpu` paid it in full.
        let unified_monitor = None;

        let mut backend = Self {
            agent_enabled: config.enable_agent,
            agent_timeout_secs: config.agent_timeout_secs,
            gpu_collection,
            process_monitor,
            network_monitor,
            connection_monitor,
            disks,
            motherboard_sensors,
            cpu_stats: None,
            memory_stats: None,
            gpu_static_info,
            gpu_dynamic_info,
            processes: None,
            connections: None,
            system_info,
            system_stats,
            driver_info,
            cpu_history: HistoryBuffer::new(config.history_size),
            memory_history: HistoryBuffer::new(config.history_size),
            accelerator_histories: (0..gpu_count)
                .map(|_| HistoryBuffer::new(config.history_size))
                .collect(),
            accelerator_memory_histories: (0..gpu_count)
                .map(|_| HistoryBuffer::new(config.history_size))
                .collect(),
            accelerator_temp_histories: (0..gpu_count)
                .map(|_| HistoryBuffer::new(config.history_size))
                .collect(),
            network_rx_history: HistoryBuffer::new(config.history_size),
            network_tx_history: HistoryBuffer::new(config.history_size),
            agent,
            unified_monitor,
            agent_history: VecDeque::with_capacity(config.agent_history_size),
            last_update: Instant::now(),
            update_interval: config.update_interval,
            start_time: Instant::now(),
            hostname,
            os_info,
        };

        // Perform initial update
        backend.update()?;

        Ok(backend)
    }

    /// Update all monitored data
    pub fn update(&mut self) -> Result<()> {
        self.update_cpu()?;
        self.update_memory()?;
        self.update_gpus()?;
        self.update_processes()?;
        self.update_network()?;
        self.update_connections()?;
        self.update_disks()?;
        self.update_system_stats()?;

        self.last_update = Instant::now();
        Ok(())
    }

    /// Check if update is needed based on interval
    pub fn should_update(&self) -> bool {
        self.last_update.elapsed() >= self.update_interval
    }

    /// Update if interval has elapsed
    pub fn update_if_needed(&mut self) -> Result<bool> {
        if self.should_update() {
            self.update()?;
            Ok(true)
        } else {
            Ok(false)
        }
    }

    // === CPU ===

    fn update_cpu(&mut self) -> Result<()> {
        // Cleared before the read, not after it. The previous sample used to survive
        // a failed read, so `get_full_system_state` reported an old sample as the
        // current one. A failed read now leaves `None`, which renders as unknown.
        self.cpu_stats = None;

        #[cfg(target_os = "windows")]
        {
            if let Ok(stats) = crate::platform::windows::read_cpu_stats() {
                self.cpu_stats = Some(stats.clone());
                let utilization = 100.0 - stats.total.idle;
                self.cpu_history.push(utilization);
            }
        }

        #[cfg(target_os = "linux")]
        {
            if let Ok(stats) = crate::platform::linux::read_cpu_stats() {
                self.cpu_stats = Some(stats.clone());
                let utilization = 100.0 - stats.total.idle;
                self.cpu_history.push(utilization);
            }
        }

        #[cfg(target_os = "macos")]
        {
            // Was hand-rolled from `sysctl` and the load average, and every
            // per-core field it produced was invented: the system-wide figure
            // repeated across all cores, a fixed 60/40 user/system split, a
            // `governor` of "performance" on a platform with no governors, a
            // minimum frequency of max/2, and `"Apple CPU"` when the brand
            // string was missing. A failed load-average parse fell to 0.0, which
            // published 100% idle -- the same shape as the zero-constructor
            // defects 6.0.0 removed, where no threshold could ever be crossed.
            //
            // `platform::macos::read_cpu_stats` has existed since 5.2.0 and reads
            // real per-core ticks from `host_processor_info`. It was wired into
            // the ontology resolver and not into this backend, so `ironmon` and the
            // ontology reported different CPU figures on the same Mac. This is
            // now the same call Windows and Linux make above.
            if let Ok(stats) = crate::platform::macos::read_cpu_stats() {
                self.cpu_stats = Some(stats.clone());
                let utilization = 100.0 - stats.total.idle;
                self.cpu_history.push(utilization);
            }
        }

        Ok(())
    }

    pub fn cpu_stats(&self) -> Option<&CpuStats> {
        self.cpu_stats.as_ref()
    }

    /// Overall CPU utilisation, or `None` before a sample has been taken.
    ///
    /// Returned `0.0` when no stats had been read -- an idle machine, reported
    /// for one that was never sampled. `pipeline::Snapshot::cpu_utilization`,
    /// the method of the same name on the other snapshot type, already returned
    /// `Option`; the two now answer "not sampled" the same way.
    pub fn cpu_utilization(&self) -> Option<f32> {
        self.cpu_stats.as_ref().map(|s| 100.0 - s.total.idle)
    }

    pub fn cpu_history(&self) -> &HistoryBuffer<f32> {
        &self.cpu_history
    }

    // === Memory ===

    fn update_memory(&mut self) -> Result<()> {
        #[cfg(target_os = "windows")]
        {
            if let Ok(stats) = crate::platform::windows::read_memory_stats() {
                self.memory_stats = Some(stats.clone());
                // No sample where no RAM total was read.
                if let Some(usage) = stats.ram_usage_percent() {
                    self.memory_history.push(usage);
                }
            }
        }

        #[cfg(target_os = "linux")]
        {
            if let Ok(stats) = crate::platform::linux::read_memory_stats() {
                self.memory_stats = Some(stats.clone());
                // No sample where no RAM total was read.
                if let Some(usage) = stats.ram_usage_percent() {
                    self.memory_history.push(usage);
                }
            }
        }

        // There was no macOS arm here at all, so `memory_stats` stayed `None` on
        // a Mac and every caller saw memory as simply absent. That is quieter
        // than the CPU path's invented figures and wrong in the same way: the
        // reader has existed since 5.2.0 and was wired only into the ontology, so
        // `ironmon` reported no memory on a machine the ontology could read.
        #[cfg(target_os = "macos")]
        {
            if let Ok(stats) = crate::platform::macos::read_memory_stats() {
                self.memory_stats = Some(stats.clone());
                // No sample where no RAM total was read.
                if let Some(usage) = stats.ram_usage_percent() {
                    self.memory_history.push(usage);
                }
            }
        }

        Ok(())
    }

    pub fn memory_stats(&self) -> Option<&MemoryStats> {
        self.memory_stats.as_ref()
    }

    /// RAM utilisation, or `None` before a sample has been taken. See
    /// [`Self::cpu_utilization`].
    pub fn memory_utilization(&self) -> Option<f32> {
        self.memory_stats
            .as_ref()
            .and_then(|s| s.ram_usage_percent())
    }

    pub fn memory_history(&self) -> &HistoryBuffer<f32> {
        &self.memory_history
    }

    // === GPUs/Accelerators ===

    /// One dynamic sample per static descriptor, in collection order. A device
    /// whose sample failed keeps its slot with every field unknown, rather than
    /// blanking every other device or shifting their indices.
    fn dynamic_slots(gpus: &GpuCollection, len: usize) -> Vec<Option<GpuDynamicInfo>> {
        let mut samples = gpus.snapshot_all_partial().into_iter();
        (0..len)
            .map(|_| {
                samples
                    .next()
                    .and_then(|sample| sample.ok())
                    .map(|info| info.dynamic_info)
            })
            .collect()
    }

    fn update_gpus(&mut self) -> Result<()> {
        if let Some(ref gpus) = self.gpu_collection {
            {
                self.gpu_dynamic_info = Self::dynamic_slots(gpus, self.gpu_static_info.len());

                // Update histories
                for (i, slot) in self.gpu_dynamic_info.iter().enumerate() {
                    // A failed sample contributes nothing to the series.
                    let Some(info) = slot else { continue };
                    if i < self.accelerator_histories.len() {
                        if let Some(util) = info.utilization {
                            self.accelerator_histories[i].push(util as f32);
                        }
                        // A device that reported no memory contributes no
                        // sample, so the series does not advance -- a flat
                        // segment, not a drop to zero. The GPU histories in the
                        // pipeline take the same line for the same reason.
                        if let Some(mem_util) = info.memory.utilization {
                            self.accelerator_memory_histories[i].push(mem_util as f32);
                        }
                        if let Some(temp) = info.thermal.temperature {
                            self.accelerator_temp_histories[i].push(temp as f32);
                        }
                    }
                }
            }
        }
        Ok(())
    }

    pub fn gpu_collection(&self) -> Option<&GpuCollection> {
        self.gpu_collection.as_ref()
    }

    /// Static info per enumerated device. A `None` slot is a device whose
    /// static query failed; its position is still its index.
    pub fn gpu_static_info(&self) -> &[Option<GpuStaticInfo>] {
        &self.gpu_static_info
    }

    /// Dynamic sample per enumerated device, positions matching
    /// [`Self::gpu_static_info`]. A `None` slot is a failed sample.
    pub fn gpu_dynamic_info(&self) -> &[Option<GpuDynamicInfo>] {
        &self.gpu_dynamic_info
    }

    pub fn gpu_count(&self) -> usize {
        self.gpu_static_info.len()
    }

    pub fn accelerator_history(&self, index: usize) -> Option<&HistoryBuffer<f32>> {
        self.accelerator_histories.get(index)
    }

    pub fn accelerator_memory_history(&self, index: usize) -> Option<&HistoryBuffer<f32>> {
        self.accelerator_memory_histories.get(index)
    }

    pub fn accelerator_temp_history(&self, index: usize) -> Option<&HistoryBuffer<f32>> {
        self.accelerator_temp_histories.get(index)
    }

    // === Processes ===

    fn update_processes(&mut self) -> Result<()> {
        if let Some(ref mut monitor) = self.process_monitor {
            // A failed enumeration leaves the list unread rather than empty.
            self.processes = monitor.processes().ok();
        }
        Ok(())
    }

    /// The process list, or `None` where it was not read.
    pub fn processes(&self) -> Option<&[ProcessMonitorInfo]> {
        self.processes.as_deref()
    }

    /// Processes by CPU, or `None` where the list was not read.
    pub fn processes_by_cpu(&self) -> Option<Vec<&ProcessMonitorInfo>> {
        let mut procs: Vec<_> = self.processes.as_ref()?.iter().collect();
        procs.sort_by(|a, b| {
            b.cpu_percent
                .partial_cmp(&a.cpu_percent)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        Some(procs)
    }

    /// Processes by memory, or `None` where the list was not read.
    pub fn processes_by_memory(&self) -> Option<Vec<&ProcessMonitorInfo>> {
        let mut procs: Vec<_> = self.processes.as_ref()?.iter().collect();
        procs.sort_by_key(|p| std::cmp::Reverse(p.memory_bytes));
        Some(procs)
    }

    /// Processes using the given GPU, or `None` where the list was not read.
    pub fn processes_by_gpu(&self, gpu_index: usize) -> Option<Vec<&ProcessMonitorInfo>> {
        let mut procs: Vec<_> = self
            .processes
            .as_ref()?
            .iter()
            .filter(|p| {
                p.gpu_indices
                    .as_ref()
                    .is_some_and(|gpus| gpus.contains(&gpu_index))
            })
            .collect();
        procs.sort_by(|a, b| {
            let a_mem = a.gpu_memory_per_device.get(&gpu_index).unwrap_or(&0);
            let b_mem = b.gpu_memory_per_device.get(&gpu_index).unwrap_or(&0);
            b_mem.cmp(a_mem)
        });
        Some(procs)
    }

    // === Network ===

    fn update_network(&mut self) -> Result<()> {
        // Network monitoring - rates are handled internally by NetworkMonitor
        Ok(())
    }

    pub fn network_monitor(&self) -> Option<&NetworkMonitor> {
        self.network_monitor.as_ref()
    }

    pub fn network_monitor_mut(&mut self) -> Option<&mut NetworkMonitor> {
        self.network_monitor.as_mut()
    }

    // === Connections ===

    fn update_connections(&mut self) -> Result<()> {
        if let Some(ref mut monitor) = self.connection_monitor {
            // A failed enumeration leaves the list unread rather than empty.
            self.connections = monitor.all_connections().ok();
        }
        Ok(())
    }

    /// The connection list, or `None` where it was not read.
    pub fn connections(&self) -> Option<&[ConnectionInfo]> {
        self.connections.as_deref()
    }

    /// Filtered connections, or `None` where the list was not read.
    pub fn connections_filtered(
        &self,
        protocol: Option<Protocol>,
        state: Option<ConnectionState>,
    ) -> Option<Vec<&ConnectionInfo>> {
        Some(
            self.connections
                .as_ref()?
                .iter()
                .filter(|c| protocol.is_none_or(|p| c.protocol == p))
                .filter(|c| state.is_none_or(|s| c.state == s))
                .collect(),
        )
    }

    // === Disks ===

    /// Intentionally does nothing.
    ///
    /// Disk topology changes rarely and enumeration is comparatively expensive, so it
    /// is not part of the per-tick update. Call [`MonitoringBackend::refresh_disks`]
    /// when a refresh is actually wanted.
    fn update_disks(&mut self) -> Result<()> {
        Ok(())
    }

    /// Disk devices, or `None` where enumeration failed.
    pub fn disks(&self) -> Option<&[Box<dyn DiskDevice>]> {
        self.disks.as_deref()
    }

    pub fn refresh_disks(&mut self) {
        self.disks = disk::enumerate_disks().ok();
    }

    // === System Stats ===

    fn update_system_stats(&mut self) -> Result<()> {
        // This previously did nothing, on the claim that stats were "refreshed during
        // read operations". They are not — `system_stats()` returns a cached value,
        // so the figures stayed frozen at whatever construction captured.
        //
        // The collection is cheap (measured well under a millisecond), so there is no
        // reason to skip it.
        if let Ok(stats) = SystemStats::new() {
            self.system_stats = Some(stats);
        }
        Ok(())
    }

    pub fn system_stats(&self) -> Option<&SystemStats> {
        self.system_stats.as_ref()
    }

    pub fn system_info(&self) -> Option<&MBSystemInfo> {
        self.system_info.as_ref()
    }

    /// Driver inventory. Enumerated on the first call, then cached.
    /// Driver inventory, or `None` where it could not be read.
    pub fn driver_info(&self) -> Option<&[DriverInfo]> {
        self.driver_info
            .get_or_init(|| motherboard::get_driver_versions().ok())
            .as_deref()
    }

    /// Motherboard sensors, or `None` where enumeration failed.
    pub fn motherboard_sensors(&self) -> Option<&[Box<dyn MotherboardDevice>]> {
        self.motherboard_sensors.as_deref()
    }

    // === System Identification ===

    pub fn hostname(&self) -> &str {
        &self.hostname
    }

    pub fn os_info(&self) -> &str {
        &self.os_info
    }

    /// How long this monitor has been running. This is not how long the machine
    /// has been up; for that see [`Self::system_uptime`].
    pub fn uptime(&self) -> Duration {
        self.start_time.elapsed()
    }

    /// Time since the operating system booted, or `None` where it was not read.
    pub fn system_uptime() -> Option<Duration> {
        crate::stats::uptime().ok()
    }

    // === AI Agent ===

    /// Detect and construct the agent on first use.
    ///
    /// Deferred rather than done at construction: the probes take over a second and
    /// every `ironmon cli` invocation paid for them, whether or not it asked anything.
    fn agent_slot(&self) -> &Option<Agent> {
        self.agent.get_or_init(|| {
            if !self.agent_enabled {
                return None;
            }
            AgentConfig::auto_detect()
                .ok()
                .map(|agent_cfg| {
                    agent_cfg
                        .with_caching(true)
                        .with_cache_size(50)
                        .with_timeout(Duration::from_secs(self.agent_timeout_secs))
                })
                .and_then(|agent_cfg| Agent::new(agent_cfg).ok())
        })
    }

    /// Check if AI agent is available.
    ///
    /// The first call runs backend detection, which takes about a second.
    pub fn has_agent(&self) -> bool {
        self.agent_slot().is_some()
    }

    /// Get reference to the AI agent
    pub fn agent(&self) -> Option<&Agent> {
        self.agent_slot().as_ref()
    }

    /// Get mutable reference to the AI agent
    pub fn agent_mut(&mut self) -> Option<&mut Agent> {
        // Force detection, then hand out the mutable borrow.
        let _ = self.agent_slot();
        self.agent.get_mut().and_then(|slot| slot.as_mut())
    }

    /// Query the AI agent with a natural language question
    pub fn ask_agent(&mut self, question: &str) -> Result<AgentResponse> {
        // Enumerate on first use, then reuse the handles.
        if self.unified_monitor.is_none() {
            self.unified_monitor = Some(UnifiedMonitor::new()?);
        }

        // Force detection before borrowing mutably.
        let _ = self.agent_slot();
        let agent = self
            .agent
            .get_mut()
            .and_then(|slot| slot.as_mut())
            .ok_or_else(|| IronError::Other("AI agent not available".to_string()))?;

        let monitor = self
            .unified_monitor
            .as_ref()
            .ok_or_else(|| IronError::Other("Silicon monitor not available".to_string()))?;

        // Get response using the agent's ask method
        let response = agent.ask(question, monitor)?;

        // Store in history
        self.agent_history.push_front(response.clone());
        if self.agent_history.len() > 50 {
            self.agent_history.pop_back();
        }

        Ok(response)
    }

    /// Get agent response history
    pub fn agent_history(&self) -> &VecDeque<AgentResponse> {
        &self.agent_history
    }

    /// Clear agent history
    pub fn clear_agent_history(&mut self) {
        self.agent_history.clear();
    }

    // === Full System State ===

    /// Get complete system state snapshot for AI context or export
    /// Collect everything the backend can see.
    ///
    /// `state.network` was declared, exported, serialised by
    /// `ironmon cli all --format json`, and **never populated** -- it came back
    /// `[]` on a host with twenty interfaces, while every other section of the
    /// same document was filled. `NetworkState` was therefore a public type no
    /// code constructed, which is why its rate fields still held the bare `f64`
    /// that the rest of the crate had moved away from.
    pub fn get_full_system_state(&self) -> FullSystemState {
        let mut state = FullSystemState::empty();

        // Network state.
        //
        // A fresh monitor rather than `self.network_monitor`: keeping rate
        // baselines needs `&mut` and this method takes `&self`. The rates are
        // therefore `None` here by construction, which is the honest answer for
        // a one-shot dump and is why they are `Option` -- a caller wanting real
        // throughput holds a monitor and samples it twice.
        if let Ok(mut monitor) = crate::network_monitor::NetworkMonitor::new() {
            if let Ok(interfaces) = monitor.interfaces() {
                state.network = interfaces
                    .iter()
                    .map(|iface| {
                        let rate = monitor.bandwidth_rate(&iface.name, iface);
                        NetworkState {
                            name: iface.name.clone(),
                            is_up: iface.is_up,
                            rx_bytes: iface.rx_bytes,
                            tx_bytes: iface.tx_bytes,
                            rx_rate: rate.map(|(rx, _)| rx),
                            tx_rate: rate.map(|(_, tx)| tx),
                        }
                    })
                    .collect();
            }
        }

        // CPU state
        if let Some(ref cpu) = self.cpu_stats {
            state.cpu = Some(CpuState {
                // `None` when the model string was not read. This was the
                // literal "CPU", a name no processor has, and later an empty string.
                name: cpu.cores.first().and_then(|c| c.model.clone()),
                cores: crate::cpu_microarch::physical_cores(),
                threads: cpu.cores.len(),
                utilization: 100.0 - cpu.total.idle,
                temperature: None, // Would need thermal zone access
                frequency_mhz: cpu
                    .cores
                    .first()
                    .and_then(|c| c.frequency.as_ref().and_then(|f| f.current))
                    .map(u64::from),
                per_core_usage: cpu
                    .cores
                    .iter()
                    .map(|c| c.idle.map(|i| 100.0 - i))
                    .collect(),
            });
        }

        // Memory state
        if let Some(ref mem) = self.memory_stats {
            let ram_usage = mem.ram_usage_percent();
            state.memory = Some(MemoryState {
                total_bytes: mem.ram.total * 1024,
                used_bytes: mem.ram.used * 1024,
                // `total - used`, not `free`: the twin of the agent's
                // `MemoryState::available_mb`, which read `free` the same way.
                // Linux computes `used` as `MemTotal - MemAvailable` and
                // Windows as `ullTotalPhys - ullAvailPhys`, so this recovers
                // each platform's own available figure; `free` on Linux
                // excludes reclaimable cache and understates it.
                available_bytes: mem.ram.total.saturating_sub(mem.ram.used) * 1024,
                usage_percent: ram_usage,
                swap_total_bytes: mem.swap.total.map(|v| v * 1024),
                swap_used_bytes: mem.swap.used.map(|v| v * 1024),
                // `swap_usage_percent()` is already `Option` and already
                // handles the zero-total case; it was being recomputed here
                // from `*_or_zero()` and answering `0.0` for an unread
                // pagefile.
                swap_usage_percent: mem.swap_usage_percent(),
            });
        }

        // Accelerator states
        // Slots are walked by position, so a device whose static query failed
        // leaves a gap at its own index and the others keep theirs. It has no
        // name or vendor to report, so it is not given a summary entry here;
        // `ironmon gpu` lists it through the slot.
        for (i, static_slot) in self.gpu_static_info.iter().enumerate() {
            let Some(static_info) = static_slot else {
                continue;
            };
            // A failed dynamic sample leaves every reading unknown, not zero.
            let dynamic = self.gpu_dynamic_info.get(i).and_then(|slot| slot.as_ref());
            // Slot `i` is the `i`th device of the collection, so the process list is
            // asked of that device directly.
            let process_count = self
                .gpu_collection
                .as_ref()
                .and_then(|collection| collection.gpus().get(i))
                .and_then(|gpu| gpu.processes().ok())
                .map(|procs| procs.len());
            state.accelerators.push(AcceleratorState {
                index: i,
                accel_type: "GPU".to_string(), // Could be extended for NPU/FPGA
                name: static_info.name.clone(),
                vendor: format!("{:?}", static_info.vendor),
                utilization: dynamic.and_then(|d| d.utilization).map(f32::from),
                memory_used_bytes: dynamic.and_then(|d| d.memory.used),
                memory_total_bytes: dynamic.and_then(|d| d.memory.total),
                // Derived once, on `GpuMemory`, rather than recomputed here
                // against a total that might be zero.
                memory_usage_percent: dynamic.and_then(|d| d.memory.utilization).map(|u| u as f32),
                temperature: dynamic
                    .and_then(|d| d.thermal.temperature)
                    .map(|t| t as f32),
                power_watts: dynamic
                    .and_then(|d| d.power.draw)
                    .map(|p| p as f32 / 1000.0),
                power_limit_watts: dynamic
                    .and_then(|d| d.power.limit)
                    .map(|p| p as f32 / 1000.0),
                clock_mhz: dynamic.and_then(|d| d.clocks.graphics),
                memory_clock_mhz: dynamic.and_then(|d| d.clocks.memory),
                process_count,
            });
        }

        // Disk states
        // `None` when enumeration failed; `Some(vec![])` only for a machine with
        // no disks. A disk whose info query fails stays in the list with its
        // capacity unread; it used to be dropped, so an enumerated disk that
        // could not be read looked like one that was never there.
        state.disks = self.disks.as_ref().map(|disks| {
            disks
                .iter()
                .map(|disk| {
                    let capacity = disk.info().ok().and_then(|info| info.capacity);
                    // Try to get filesystem info for mount point
                    let (mount_point, fs_type, used) = if let Ok(fs_info) = disk.filesystem_info() {
                        if let Some(first_fs) = fs_info.first() {
                            (
                                first_fs.mount_point.to_string_lossy().to_string(),
                                first_fs.fs_type.clone(),
                                first_fs.used_size,
                            )
                        } else {
                            (String::new(), String::new(), None)
                        }
                    } else {
                        (String::new(), String::new(), None)
                    };

                    // `capacity > 0` was a sentinel for "not read", and the `0.0`
                    // it produced was a usage percentage of a disk nobody measured.
                    // Both sides must be readings for there to be a percentage.
                    let usage = match (used, capacity.filter(|c| *c > 0)) {
                        (Some(used), Some(capacity)) => {
                            Some((used as f32 / capacity as f32) * 100.0)
                        }
                        _ => None,
                    };

                    DiskState {
                        name: disk.name().to_string(),
                        mount_point,
                        filesystem: fs_type,
                        total_bytes: capacity,
                        used_bytes: used,
                        usage_percent: usage,
                    }
                })
                .collect()
        });

        // Top processes, or `None` where the list was not read.
        state.top_processes = self.processes_by_cpu().map(|procs| {
            procs
                .iter()
                .take(10)
                .map(|proc| ProcessState {
                    pid: proc.pid,
                    name: proc.name.clone(),
                    cpu_percent: proc.cpu_percent,
                    memory_bytes: proc.memory_bytes,
                    gpu_memory_bytes: proc.total_gpu_memory_bytes,
                    gpu_indices: proc.gpu_indices.clone(),
                })
                .collect()
        });

        // System info
        if let Some(ref sys) = self.system_info {
            state.system = Some(SystemInfoState {
                hostname: self.hostname.clone(),
                // Empty when unread. The compile-target family (`os_info`) is a
                // different fact from the OS version, so it is not substituted.
                os: sys.os_version.clone().unwrap_or_default(),
                kernel: sys.kernel_version.clone().unwrap_or_default(),
                // The OS's own boot clock, not the monitor's age.
                uptime_secs: Self::system_uptime().map(|d| d.as_secs()),
            });
        }

        state.timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();

        state
    }

    /// Reset all history buffers
    pub fn reset_history(&mut self) {
        self.cpu_history.clear();
        self.memory_history.clear();
        for hist in &mut self.accelerator_histories {
            hist.clear();
        }
        for hist in &mut self.accelerator_memory_histories {
            hist.clear();
        }
        for hist in &mut self.accelerator_temp_histories {
            hist.clear();
        }
        self.network_rx_history.clear();
        self.network_tx_history.clear();
    }
}

// ============================================================================
// BACKEND CONFIGURATION
// ============================================================================

/// Configuration for the monitoring backend
#[derive(Debug, Clone)]
pub struct BackendConfig {
    /// Enable AI agent
    pub enable_agent: bool,

    /// AI agent model size
    pub agent_model_size: ModelSize,

    /// AI agent timeout (seconds)
    pub agent_timeout_secs: u64,

    /// History buffer size
    pub history_size: usize,

    /// Agent history size
    pub agent_history_size: usize,

    /// Update interval
    pub update_interval: Duration,
}

impl Default for BackendConfig {
    fn default() -> Self {
        Self {
            enable_agent: true,
            agent_model_size: ModelSize::Medium,
            agent_timeout_secs: 10,
            history_size: DEFAULT_HISTORY_SIZE,
            agent_history_size: 50,
            update_interval: DEFAULT_UPDATE_INTERVAL,
        }
    }
}

impl BackendConfig {
    /// Create config with agent disabled (for faster startup)
    pub fn without_agent() -> Self {
        Self {
            enable_agent: false,
            ..Default::default()
        }
    }

    /// Create config with custom history size
    pub fn with_history_size(mut self, size: usize) -> Self {
        self.history_size = size;
        self
    }

    /// Create config with custom update interval
    pub fn with_update_interval(mut self, interval: Duration) -> Self {
        self.update_interval = interval;
        self
    }
}

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

    // === HistoryBuffer tests ===

    #[test]
    fn test_history_buffer_new() {
        let buf: HistoryBuffer<f32> = HistoryBuffer::new(10);
        assert!(buf.is_empty());
        assert_eq!(buf.len(), 0);
        assert!(buf.latest().is_none());
    }

    #[test]
    fn test_history_buffer_push_and_latest() {
        let mut buf = HistoryBuffer::new(5);
        buf.push(1.0f32);
        assert_eq!(buf.len(), 1);
        assert!(!buf.is_empty());
        assert_eq!(*buf.latest().unwrap(), 1.0);
    }

    #[test]
    fn test_history_buffer_previous() {
        let mut buf = HistoryBuffer::new(10);
        buf.push(10.0f32);
        assert!(buf.previous().is_none());
        buf.push(20.0);
        assert_eq!(*buf.previous().unwrap(), 10.0);
        assert_eq!(*buf.latest().unwrap(), 20.0);
    }

    #[test]
    fn test_history_buffer_capacity_eviction() {
        let mut buf = HistoryBuffer::new(3);
        buf.push(1u64);
        buf.push(2);
        buf.push(3);
        assert_eq!(buf.len(), 3);
        buf.push(4);
        assert_eq!(buf.len(), 3);
        let v = buf.to_vec();
        assert_eq!(v, vec![2, 3, 4]);
    }

    #[test]
    fn test_history_buffer_values_iterator() {
        let mut buf = HistoryBuffer::new(10);
        buf.push(10u64);
        buf.push(20);
        buf.push(30);
        let values: Vec<&u64> = buf.values().collect();
        assert_eq!(values, vec![&10, &20, &30]);
    }

    #[test]
    fn test_history_buffer_clear() {
        let mut buf = HistoryBuffer::new(10);
        buf.push(1.0f32);
        buf.push(2.0);
        buf.clear();
        assert!(buf.is_empty());
        assert_eq!(buf.len(), 0);
        assert!(buf.latest().is_none());
    }

    #[test]
    fn test_history_buffer_to_vec() {
        let mut buf = HistoryBuffer::new(5);
        buf.push(1.0f32);
        buf.push(2.0);
        buf.push(3.0);
        assert_eq!(buf.to_vec(), vec![1.0, 2.0, 3.0]);
    }

    #[test]
    fn test_history_buffer_as_u64_vec() {
        let mut buf: HistoryBuffer<u64> = HistoryBuffer::new(5);
        buf.push(100);
        buf.push(200);
        buf.push(300);
        assert_eq!(buf.as_u64_vec(), vec![100, 200, 300]);
    }

    #[test]
    fn test_history_buffer_as_f32_vec() {
        let mut buf: HistoryBuffer<f32> = HistoryBuffer::new(5);
        buf.push(1.5);
        buf.push(2.5);
        assert_eq!(buf.as_f32_vec(), vec![1.5, 2.5]);
    }

    #[test]
    fn test_history_buffer_large_capacity() {
        let mut buf = HistoryBuffer::new(1000);
        for i in 0..1000 {
            buf.push(i as f32);
        }
        assert_eq!(buf.len(), 1000);
        assert_eq!(*buf.latest().unwrap(), 999.0);
        buf.push(1000.0);
        assert_eq!(buf.len(), 1000);
        assert_eq!(*buf.values().next().unwrap(), 1.0);
    }

    #[test]
    fn test_history_buffer_single_capacity() {
        let mut buf = HistoryBuffer::new(1);
        buf.push(10u64);
        assert_eq!(buf.len(), 1);
        buf.push(20);
        assert_eq!(buf.len(), 1);
        assert_eq!(*buf.latest().unwrap(), 20);
    }

    // === FullSystemState tests ===

    #[test]
    fn test_full_system_state_empty() {
        let state = FullSystemState::empty();
        assert!(state.cpu.is_none());
        assert!(state.memory.is_none());
        assert!(state.accelerators.is_empty());
        assert!(state.disks.is_none());
        assert!(state.network.is_empty());
        assert!(state.top_processes.is_none());
        assert!(state.system.is_none());
        assert!(state.timestamp > 0);
    }

    #[test]
    fn test_full_system_state_to_context_string() {
        let state = FullSystemState::empty();
        let ctx = state.to_context_string();
        assert!(ctx.contains("Current System State"));
    }

    fn system_state(uptime_secs: Option<u64>) -> SystemInfoState {
        SystemInfoState {
            hostname: "host".into(),
            os: String::new(),
            kernel: String::new(),
            uptime_secs,
        }
    }

    /// Uptime is the OS's boot clock. An unread one is named as unknown rather
    /// than shown as the monitor's age, and an empty OS or kernel string is
    /// named as unknown rather than printed as a blank.
    #[test]
    fn the_context_reports_system_uptime_or_unknown() {
        let mut state = FullSystemState::empty();
        state.system = Some(system_state(Some(2 * 3600 + 5 * 60)));
        let ctx = state.to_context_string();
        assert!(ctx.contains("Uptime: 2h 5m"), "{ctx}");
        assert!(ctx.contains("OS: unknown"), "{ctx}");

        state.system = Some(system_state(None));
        let ctx = state.to_context_string();
        assert!(ctx.contains("Uptime: unknown"), "{ctx}");
        assert!(!ctx.contains("Uptime: 0h 0m"), "{ctx}");
    }

    /// A list that was not read is not the same as an empty one.
    #[test]
    fn the_context_separates_unread_disks_and_processes_from_none() {
        let mut state = FullSystemState::empty();
        let ctx = state.to_context_string();
        assert!(ctx.contains("Disks: not read"), "{ctx}");
        assert!(ctx.contains("Top Processes: not read"), "{ctx}");

        state.disks = Some(Vec::new());
        state.top_processes = Some(Vec::new());
        let ctx = state.to_context_string();
        assert!(ctx.contains("Disks: none enumerated"), "{ctx}");
        assert!(!ctx.contains("Top Processes"), "{ctx}");
    }

    /// The context handed to the model must not call logical processors cores.
    ///
    /// It read "AMD Ryzen 9 9900X 12-Core Processor (24 cores)" -- the name and
    /// the figure contradicting each other one space apart -- because `cores`
    /// was the logical count. With a physical count, both are named; without
    /// one, only threads are, rather than relabelling them.
    #[test]
    fn the_ai_context_names_physical_and_logical_cores_separately() {
        let cpu = |cores| CpuState {
            name: Some("AMD Ryzen 9 9900X 12-Core Processor".into()),
            cores,
            threads: 24,
            utilization: 10.0,
            temperature: None,
            frequency_mhz: None,
            per_core_usage: Vec::new(),
        };

        let mut state = FullSystemState::empty();
        state.cpu = Some(cpu(Some(12)));
        let ctx = state.to_context_string();
        assert!(ctx.contains("12 cores, 24 threads"), "{ctx}");
        assert!(
            !ctx.contains("24 cores"),
            "logical count labelled as cores: {ctx}"
        );

        state.cpu = Some(cpu(None));
        let ctx = state.to_context_string();
        assert!(ctx.contains("(24 threads)"), "{ctx}");
        assert!(
            !ctx.contains("cores"),
            "with no physical count, no core count may be stated: {ctx}"
        );
    }

    // === BackendConfig tests ===

    #[test]
    fn test_backend_config_minimal() {
        let config = BackendConfig::without_agent();
        assert!(!config.enable_agent);
    }

    #[test]
    fn test_backend_config_with_history_size() {
        let config = BackendConfig::without_agent().with_history_size(120);
        assert_eq!(config.history_size, 120);
    }

    #[test]
    fn test_backend_config_with_update_interval() {
        let config = BackendConfig::without_agent().with_update_interval(Duration::from_secs(5));
        assert_eq!(config.update_interval, Duration::from_secs(5));
    }
}