ironmonitor 7.0.2

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
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
//! Resolving ontology ids to live values.
//!
//! [`super::Ontology`] names what ironmon *can* report; this module answers what it
//! *does* report, right now, on this machine. Without it the ontology is a glossary:
//! an agent can learn that `gpu.0.thermal.temperature` exists but has no way to read
//! it.
//!
//! ## Declared vs. observed provenance
//!
//! An [`super::Entity`] declares the provenance a value is *supposed* to have. A
//! [`Reading`] carries the provenance it *actually* had when taken. These differ
//! routinely and the difference is the useful part: `gpu.0.thermal.temperature` is
//! declared `measured`, but on a machine whose driver exposes no sensor the reading
//! comes back `unavailable` with a note saying so.
//!
//! The rule this module exists to enforce is that a failed read is never dressed as
//! a successful one. There is no path here that substitutes zero, a previous sample,
//! or a plausible constant for a value that could not be obtained — every such
//! substitution this repository has shipped was indistinguishable from a real
//! reading at the point of consumption, which is precisely what a consuming agent
//! cannot afford.

use serde::{Deserialize, Serialize};

use super::{Entity, Ontology, Provenance, Unit};

/// One resolved value, with the provenance it actually had.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Reading {
    /// Concrete id — `gpu.0.name`, never the `gpu.{n}.name` template.
    pub id: String,
    /// `None` whenever `provenance` is [`Provenance::Unavailable`]. A consumer must
    /// render this as unknown; it is never a zero.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<serde_json::Value>,
    /// What this reading actually is — not what the entity declares it should be.
    pub provenance: Provenance,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unit: Option<Unit>,
    /// Why a value is missing, or what qualifies it. Present whenever the observed
    /// provenance differs from the declared one, so the difference is never silent.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
}

impl Reading {
    fn measured(id: impl Into<String>, value: serde_json::Value, unit: Option<Unit>) -> Self {
        Self {
            id: id.into(),
            value: Some(value),
            provenance: Provenance::Measured,
            unit,
            note: None,
        }
    }

    fn derived(id: impl Into<String>, value: serde_json::Value, unit: Option<Unit>) -> Self {
        Self {
            id: id.into(),
            value: Some(value),
            provenance: Provenance::Derived,
            unit,
            note: None,
        }
    }

    /// A value the hardware or firmware declares about itself rather than one
    /// ironmon sampled. A DIMM part number and a CPU base clock are both this: a
    /// consumer may rely on them to be stable, and may not treat them as
    /// evidence of the machine's state right now.
    fn spec(id: impl Into<String>, value: serde_json::Value, unit: Option<Unit>) -> Self {
        Self {
            id: id.into(),
            value: Some(value),
            provenance: Provenance::Specification,
            unit,
            note: None,
        }
    }

    /// A value that could not be obtained. The reason is mandatory: "unavailable"
    /// without a cause is the same dead end as a fabricated number.
    fn unavailable(id: impl Into<String>, unit: Option<Unit>, why: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            value: None,
            provenance: Provenance::Unavailable,
            unit,
            note: Some(why.into()),
        }
    }

    /// Whether this reading may be treated as a live observation of the hardware.
    pub fn is_observation(&self) -> bool {
        self.provenance.is_observation() && self.value.is_some()
    }
}

/// Everything IronMonitor can currently resolve, in id order.
///
/// Entities with no resolver bound are reported as [`Provenance::Unavailable`] with
/// a note saying so, rather than omitted. An agent comparing this against
/// [`Ontology::build`] can therefore tell "this machine has no such device" apart
/// from "IronMonitor cannot read this yet" — two very different facts that an omission
/// would collapse into one.
pub fn snapshot() -> Vec<Reading> {
    let ontology = Ontology::build();
    let mut out = Vec::new();

    resolve_cpu(&mut out);
    resolve_memory(&mut out);
    resolve_system(&mut out);
    resolve_board(&mut out);
    resolve_gpu(&mut out);
    resolve_disk(&mut out);
    resolve_network(&mut out);
    resolve_process(&mut out);
    resolve_thermal(&mut out);
    resolve_power(&mut out);
    resolve_rapl(&mut out);
    resolve_sensors(&mut out);
    resolve_displays(&mut out);
    resolve_virtualization(&mut out);
    resolve_numa(&mut out);
    resolve_ecc(&mut out);
    resolve_pci(&mut out);
    resolve_usb(&mut out);
    resolve_memory_bandwidth(&mut out);
    resolve_microarch(&mut out);
    resolve_crypto(&mut out);
    resolve_input(&mut out);
    resolve_audio(&mut out);
    resolve_cameras(&mut out);
    resolve_printers(&mut out);
    resolve_services(&mut out);
    resolve_kernel_params(&mut out);
    resolve_secure_boot(&mut out);
    resolve_boot_duration(&mut out);
    resolve_bluetooth(&mut out);
    resolve_storage_controllers(&mut out);
    resolve_power_profiles(&mut out);
    resolve_codecs(&mut out);
    resolve_settings(&mut out);

    // Anything the ontology names but nothing above produced.
    //
    // Most of these have no resolver. Some do, and it returned early after a
    // `<prefix>.<none>` diagnostic saying why -- the processor could not be
    // identified, the service manager could not be reached. Those entities
    // used to get the note below too, "no resolver bound", which is false for
    // them: the resolver ran and gave its reason. They inherit the reason of
    // the nearest enclosing diagnostic instead.
    let declined: Vec<(String, String)> = out
        .iter()
        .filter_map(|r| {
            let prefix = r.id.strip_suffix(".<none>")?;
            Some((format!("{prefix}."), r.note.clone()?))
        })
        .collect();
    let produced: std::collections::HashSet<&str> = out.iter().map(|r| r.id.as_str()).collect();
    let mut unbound: Vec<Reading> = ontology
        .entities
        .values()
        .filter(|e| {
            // Diagnostics are claims about the reading process, and a resolver emits
            // one only when its condition actually holds. Sweeping them in here
            // asserted the opposite of the truth: `network.<none>` appeared saying
            // "no resolver bound" in a snapshot where the network resolver had just
            // enumerated forty-five readings.
            e.kind != super::EntityKind::Diagnostic
                && !Ontology::is_template(&e.id)
                && !produced.contains(e.id.as_str())
        })
        .map(|e| {
            let inherited = declined
                .iter()
                .filter(|(prefix, _)| e.id.starts_with(prefix.as_str()))
                .max_by_key(|(prefix, _)| prefix.len());
            match inherited {
                Some((_, why)) => Reading::unavailable(e.id.clone(), e.unit, why.clone()),
                None => Reading::unavailable(
                    e.id.clone(),
                    e.unit,
                    "no resolver bound on this build — the entity is defined but ironmon \
                     does not yet read it here",
                ),
            }
        })
        .collect();
    out.append(&mut unbound);

    // Templated entities need the same treatment, and used to be skipped entirely on
    // the grounds that an unexpanded `disk.{n}.model` is not a fact about a machine.
    // That reasoning was wrong in a way this module exists to prevent: a domain whose
    // entities are *all* templates simply vanished from the snapshot, so an agent
    // could not tell "this machine has no disks" from "IronMonitor does not read disks".
    // Silence is the one answer a resolver must never give. A domain that produced
    // nothing gets one row saying so, keyed on the template so the id stays traceable
    // back to the schema.
    let mut missing_domains: Vec<Reading> = Vec::new();
    for domain in super::Domain::ALL {
        let prefix = format!("{}.", domain.as_str());
        if out.iter().any(|r| r.id.starts_with(&prefix)) {
            continue;
        }
        let declares_any = ontology.entities.values().any(|e| e.domain == *domain);
        if declares_any {
            missing_domains.push(Reading::unavailable(
                format!("{}.<none>", domain.as_str()),
                None,
                "no instance of this domain was found and no resolver reported why; \
                 the ontology declares entities here but nothing was enumerated",
            ));
        }
    }
    out.append(&mut missing_domains);

    // Last gate: a resolver must not hand an agent a number its own schema calls
    // impossible. Anything outside the declared range becomes unavailable, with the
    // offending value quoted in the note — surfaced, not swallowed, and never
    // clamped. Clamping would turn a 103% core into a plausible 100% and destroy the
    // evidence that the sampling was wrong.
    //
    // This exists because the derivation above got it wrong under load and shipped
    // an impossible percentage. The specific bug is fixed; the gate means the next
    // one degrades to "unknown, and here is why" instead of to a confident lie.
    for reading in out.iter_mut() {
        let Some(value) = reading.value.as_ref().and_then(|v| v.as_f64()) else {
            continue;
        };
        let Some(entity) = lookup_template(&ontology, &reading.id) else {
            continue;
        };
        if let Some(problem) = entity.validate_range(value) {
            reading.value = None;
            reading.provenance = Provenance::Unavailable;
            reading.note = Some(format!(
                "reader produced a value the ontology rejects, so it is withheld \
                 rather than reported: {problem}"
            ));
        }
    }

    // Same shape of gate, for absences dressed as text. A reader that returns
    // "unknown" or "n/a" has told you it does not know, and passing that through
    // as `measured` hands an agent a reading that looks like an answer.
    //
    // This is a final pass rather than only a guard in the push helpers because
    // guarding the helpers did not work. `push_text` and `push_id` were fixed
    // first, on the stated reasoning that they were the only route a text value
    // could take. `push_opt` was a third route, and `pci.*.link.speed` came
    // through it as "unknown" on the next CI run. Four instances of this class
    // have now been found in four different places, which is the argument for
    // catching it where every reading is guaranteed to pass rather than where it
    // happens to be produced.
    for reading in out.iter_mut() {
        if reading.provenance == Provenance::Unavailable {
            continue;
        }
        let Some(text) = reading.value.as_ref().and_then(|v| v.as_str()) else {
            continue;
        };
        if !names_an_absence(text) {
            continue;
        }
        let quoted = text.trim().to_string();
        reading.value = None;
        reading.provenance = Provenance::Unavailable;
        reading.note = Some(format!(
            "reader returned {quoted:?}, which names an absence rather than a value, so it is reported as unavailable rather than as a reading"
        ));
    }

    out.sort_by(|a, b| a.id.cmp(&b.id));
    out
}

/// Resolve one id. Templates are rejected: `gpu.{n}.name` is not a question that has
/// an answer, `gpu.0.name` is.
pub fn get(id: &str) -> Option<Reading> {
    if Ontology::is_template(id) {
        return None;
    }
    snapshot().into_iter().find(|r| r.id == id)
}

/// Entities the ontology declares that this build can actually resolve.
///
/// Coverage is a fact about ironmon, not about the machine, so it is worth being able
/// to ask for directly rather than inferring from a snapshot full of nulls.
pub fn coverage() -> Coverage {
    coverage_of(&snapshot())
}

/// Why no current per-core clock is reported.
///
/// Named per platform because the causes differ, and a caller deciding whether to
/// look elsewhere needs to know which one it hit. On Windows this is not a
/// missing reader: `CallNtPowerInformation` answers, and its answer is the
/// nominal clock rather than the current one — see `get_cpu_frequency`.
#[cfg(target_os = "windows")]
const FREQUENCY_ABSENT: &str = concat!(
    "Windows reports the nominal clock through CallNtPowerInformation, not the ",
    "current one — it returned the maximum unchanged for every core, so there is ",
    "no per-core reading here to report. The real figure needs the ",
    "'% Processor Performance' counter, which IronMonitor does not read yet",
);

#[cfg(not(target_os = "windows"))]
const FREQUENCY_ABSENT: &str = "no per-core clock reported";

/// Coverage of an existing snapshot.
///
/// Split out because a caller wanting both the readings and their tally must not
/// take two snapshots to get them: instance counts move between calls on a live
/// machine — a USB device is unplugged, a process exits — so two snapshots
/// legitimately differ in length. A test asserting they match was passing only
/// while the box was quiet, and failed the moment the suite got busier.
pub fn coverage_of(readings: &[Reading]) -> Coverage {
    let bound = readings.iter().filter(|r| r.value.is_some()).count();
    Coverage {
        total: readings.len(),
        resolved: bound,
        unavailable: readings.len() - bound,
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Coverage {
    pub total: usize,
    pub resolved: usize,
    pub unavailable: usize,
}

// ── Per-domain resolvers ─────────────────────────────────────────────────────
//
// Each pushes what it can read and an `unavailable` with a cause for what it
// cannot. None of them invent a value on failure.

fn resolve_cpu(out: &mut Vec<Reading>) {
    // Cache topology is independent of the sampling below and must still resolve
    // when the CPU reader fails, so it runs before the early return.
    resolve_cpu_cache(out);

    let stats = read_cpu_stats();

    let stats = match stats {
        Ok(s) => s,
        Err(why) => {
            out.push(Reading::unavailable(
                "cpu.total.utilization",
                Some(Unit::Percent),
                format!("the platform CPU reader failed: {why}"),
            ));
            return;
        }
    };

    out.push(Reading::derived(
        "cpu.total.utilization",
        serde_json::json!(100.0 - stats.total.idle),
        Some(Unit::Percent),
    ));
    out.push(Reading::measured(
        "cpu.total.idle",
        serde_json::json!(stats.total.idle),
        Some(Unit::Percent),
    ));
    out.push(Reading::measured(
        "cpu.cores.logical",
        serde_json::json!(stats.cores.len()),
        Some(Unit::Count),
    ));

    // Declared since the ontology was written and never resolved — the CPU stats
    // reader counts logical processors only, so nothing filled it and the entity
    // fell through to the unbound sweep. Found by
    // `tests/ontology_conformance.rs::non_nullable_entities_are_never_null`, which
    // is the whole argument for deriving tests from the schema: a declared,
    // non-nullable id that no resolver touched is invisible to a hand-written suite.
    match crate::cpu_microarch::CpuMicroarchMonitor::new() {
        Ok(m) if m.report().physical_cores > 0 => out.push(Reading::measured(
            "cpu.cores.physical",
            serde_json::json!(m.report().physical_cores),
            Some(Unit::Count),
        )),
        Ok(_) => out.push(Reading::unavailable(
            "cpu.cores.physical",
            Some(Unit::Count),
            "the platform reported no physical core count distinct from the \
             logical one",
        )),
        Err(e) => out.push(Reading::unavailable(
            "cpu.cores.physical",
            Some(Unit::Count),
            format!("microarchitecture reader unavailable: {e}"),
        )),
    }

    match stats.cores.first().map(|c| c.model.as_str()) {
        // An empty model string is a failed read, not a CPU without a name.
        Some(model) if !model.trim().is_empty() => push_text(out, "cpu.model", model),
        _ => out.push(Reading::unavailable(
            "cpu.model",
            Some(Unit::Text),
            "no core reported a model string",
        )),
    }

    for core in &stats.cores {
        let base = format!("cpu.core.{}", core.id);
        // Derived as `100 - idle`, matching how `cpu.total.utilization` is computed.
        // Summing user and system instead let sampling jitter push the result past
        // 100 — the per-core deltas are taken across a boundary and need not add up
        // — which produced an impossible percentage under heavy load. Deriving from
        // idle is bounded by the same value the total already trusts.
        match core.idle {
            Some(idle) => {
                // The measured input is published beside the figure derived from
                // it. It was read either way and discarding it left the
                // derivation naming an input no consumer could fetch.
                out.push(Reading::measured(
                    format!("{base}.idle"),
                    serde_json::json!(idle),
                    Some(Unit::Percent),
                ));
                out.push(Reading::derived(
                    format!("{base}.utilization"),
                    serde_json::json!(100.0 - idle),
                    Some(Unit::Percent),
                ));
            }
            // The platform exposes no per-processor times. Reporting the system
            // average here would look per-core and be one number repeated.
            _ => {
                for suffix in ["idle", "utilization"] {
                    out.push(Reading::unavailable(
                        format!("{base}.{suffix}"),
                        Some(Unit::Percent),
                        "platform exposes no per-processor times; the system-wide \
                         average is not a per-core reading",
                    ));
                }
            }
        }
        // `current` is an `Option` now; the `> 0` guard stays because a reader
        // could still produce a zero and it would mean the same thing.
        match &core.frequency {
            // Windows has no unprivileged API that reports a current clock, so
            // it multiplies the nominal maximum by the kernel's delivered
            // performance figure. That product is per-core and real, and it is
            // not a direct reading -- publishing it as `Measured` would put a
            // specification behind a measurement's provenance, which is the
            // thing the reader below it was rewritten to stop doing.
            Some(f) if f.current.is_some_and(|c| c > 0) && f.current_is_derived => {
                out.push(Reading::derived(
                    format!("{base}.frequency"),
                    serde_json::json!(f.current),
                    Some(Unit::Megahertz),
                ))
            }
            Some(f) if f.current.is_some_and(|c| c > 0) => out.push(Reading::measured(
                format!("{base}.frequency"),
                serde_json::json!(f.current),
                Some(Unit::Megahertz),
            )),
            _ => out.push(Reading::unavailable(
                format!("{base}.frequency"),
                Some(Unit::Megahertz),
                FREQUENCY_ABSENT,
            )),
        }
        // The rated maximum, which the Windows reader multiplies by delivered
        // performance to get the figure above -- so it is published rather than
        // discarded, and `cpu.core.{n}.frequency` names it as its input.
        //
        // `push_spec_opt`, not `push_opt`: this is a rated figure the firmware
        // states, not one ironmon measured. It was published as `measured` on
        // every row while the entity beside it declared `Specification` -- the
        // only entity in the ontology whose rows over-claimed their own
        // declaration.
        push_spec_opt(
            out,
            format!("{base}.frequency.max"),
            core.frequency
                .as_ref()
                .and_then(|f| f.max)
                .map(|v| serde_json::json!(v)),
            Some(Unit::Megahertz),
            "platform reports no rated maximum for this core",
        );
        // Deliberately not derived from the maximum: a minimum is a distinct
        // property, and dividing the maximum by four produced a plausible number
        // that was not one.
        out.push(Reading::unavailable(
            format!("{base}.frequency.min"),
            Some(Unit::Megahertz),
            "platform exposes no minimum core frequency; it is not inferable from \
             the maximum",
        ));
    }
}

fn resolve_memory(out: &mut Vec<Reading>) {
    // Slot topology is read from SMBIOS and is independent of the usage figures
    // below, so it runs first and still resolves if those fail.
    resolve_memory_dimms(out);

    let stats = match read_memory_stats() {
        Ok(s) => s,
        Err(why) => {
            for (id, unit) in [
                ("memory.total", Unit::Bytes),
                ("memory.used", Unit::Bytes),
                ("memory.utilization", Unit::Percent),
            ] {
                out.push(Reading::unavailable(
                    id,
                    Some(unit),
                    format!("the platform memory reader failed: {why}"),
                ));
            }
            return;
        }
    };

    // Core readers work in KB; the ontology declares bytes.
    let total = stats.ram.total.saturating_mul(1024);
    let used = stats.ram.used.saturating_mul(1024);
    out.push(Reading::measured(
        "memory.total",
        serde_json::json!(total),
        Some(Unit::Bytes),
    ));
    out.push(Reading::measured(
        "memory.used",
        serde_json::json!(used),
        Some(Unit::Bytes),
    ));
    match total {
        0 => out.push(Reading::unavailable(
            "memory.utilization",
            Some(Unit::Percent),
            "total memory reported as zero, so a percentage has no denominator",
        )),
        t => out.push(Reading::derived(
            "memory.utilization",
            serde_json::json!((used as f64 / t as f64) * 100.0),
            Some(Unit::Percent),
        )),
    }

    // Three outcomes, and until 6.0.0 the type could only express two.
    //
    // A platform that did not report swap and a machine with no swap both
    // arrived here as `0`, and both were published as the definite statement
    // "no swap or pagefile configured". Now `None` says the first and `Some(0)`
    // the second, which is the same distinction this module makes everywhere
    // else and could not make for its own swap rows.
    match stats.swap.total {
        None => {
            for id in ["memory.swap.total", "memory.swap.used"] {
                out.push(Reading::unavailable(
                    id,
                    Some(Unit::Bytes),
                    "the platform did not report swap, so whether this machine has any is unknown",
                ));
            }
        }
        Some(0) => {
            for id in ["memory.swap.total", "memory.swap.used"] {
                out.push(Reading::unavailable(
                    id,
                    Some(Unit::Bytes),
                    "no swap or pagefile configured",
                ));
            }
        }
        Some(total_kb) => {
            out.push(Reading::measured(
                "memory.swap.total",
                serde_json::json!(total_kb.saturating_mul(1024)),
                Some(Unit::Bytes),
            ));
            match stats.swap.used {
                Some(used_kb) => out.push(Reading::measured(
                    "memory.swap.used",
                    serde_json::json!(used_kb.saturating_mul(1024)),
                    Some(Unit::Bytes),
                )),
                None => out.push(Reading::unavailable(
                    "memory.swap.used",
                    Some(Unit::Bytes),
                    "the platform reported a swap total and no used figure",
                )),
            }
        }
    }
}

fn resolve_system(out: &mut Vec<Reading>) {
    match crate::os_info::OsInfoMonitor::new() {
        Ok(monitor) => {
            let info = monitor.info();
            push_text(out, "system.os.name", &info.os_name);
            push_id(out, "system.os.build", &info.os_build);
            // Read by `os_info` since long before the ontology named them.
            push_text(out, "system.hostname", &info.hostname);
            push_text(out, "system.os.version", &info.os_version);
            push_text(out, "system.kernel.version", &info.kernel_version);
            push_id(out, "system.architecture", &info.architecture);
            if info.uptime_seconds > 0 {
                out.push(Reading::measured(
                    "system.uptime",
                    serde_json::json!(info.uptime_seconds),
                    Some(Unit::Seconds),
                ));
            } else {
                out.push(Reading::unavailable(
                    "system.uptime",
                    Some(Unit::Seconds),
                    "uptime read as zero, which would mean the machine booted this \
                     instant",
                ));
            }
        }
        Err(e) => {
            for (id, unit) in [
                ("system.os.name", Unit::Text),
                ("system.os.build", Unit::Identifier),
                ("system.uptime", Unit::Seconds),
            ] {
                out.push(Reading::unavailable(
                    id,
                    Some(unit),
                    format!("OS info reader failed: {e}"),
                ));
            }
        }
    }
}

fn resolve_board(out: &mut Vec<Reading>) {
    match detect_board() {
        Some(board) => {
            push_text(out, "board.model", &board.hardware.model);
            match &board.hardware.module {
                Some(m) => push_text(out, "board.manufacturer", m),
                None => out.push(Reading::unavailable(
                    "board.manufacturer",
                    Some(Unit::Text),
                    "SMBIOS reported no baseboard manufacturer",
                )),
            }
        }
        None => {
            for id in ["board.model", "board.manufacturer"] {
                out.push(Reading::unavailable(
                    id,
                    Some(Unit::Text),
                    "no board detection on this platform",
                ));
            }
        }
    }

    resolve_firmware(out);
    resolve_tpm(out);
}

fn resolve_firmware(out: &mut Vec<Reading>) {
    const IDS: [&str; 3] = [
        "board.firmware.vendor",
        "board.firmware.product",
        "board.firmware.boot_mode",
    ];

    let inventory = match crate::firmware::FirmwareInventory::new() {
        Ok(i) => i,
        Err(e) => {
            for id in IDS {
                out.push(Reading::unavailable(
                    id,
                    Some(Unit::Text),
                    format!("firmware inventory unavailable: {e}"),
                ));
            }
            return;
        }
    };

    push_text(out, "board.firmware.vendor", inventory.system_vendor());
    push_text(out, "board.firmware.product", inventory.system_product());
    push_id(
        out,
        "board.firmware.boot_mode",
        &format!("{:?}", inventory.boot_mode()).to_lowercase(),
    );

    for (i, entry) in inventory.items().iter().enumerate() {
        push_id(
            out,
            format!("board.firmware.{i}.component"),
            &format!("{:?}", entry.component).to_lowercase(),
        );
        push_text(out, format!("board.firmware.{i}.version"), &entry.version);
    }
}

fn resolve_tpm(out: &mut Vec<Reading>) {
    const DETAIL_IDS: [&str; 4] = [
        "board.tpm.version",
        "board.tpm.manufacturer",
        "board.tpm.status",
        "board.tpm.measured_boot",
    ];

    let monitor = match crate::tpm::TpmMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            // Not knowing whether a TPM exists is different from knowing there is
            // none, so `present` goes unavailable here rather than false.
            out.push(Reading::unavailable(
                "board.tpm.present",
                None,
                format!("TPM enumeration failed: {e}"),
            ));
            for id in DETAIL_IDS {
                out.push(Reading::unavailable(
                    id,
                    None,
                    format!("TPM enumeration failed: {e}"),
                ));
            }
            return;
        }
    };

    // A successful enumeration that found nothing is a reading: this machine has
    // no TPM. That is exactly the case `present` exists to state.
    out.push(Reading::measured(
        "board.tpm.present",
        serde_json::json!(monitor.has_tpm()),
        None,
    ));

    let Some(tpm) = monitor.tpm() else {
        for id in DETAIL_IDS {
            out.push(Reading::unavailable(
                id,
                None,
                "no TPM present on this machine",
            ));
        }
        return;
    };

    // `Unknown` on either of these is the reader having failed to determine the
    // value, not the device reporting "unknown". Passing it through as a measured
    // identifier would let an agent conclude a TPM's state had been established
    // when it had not — and for a security property that is the wrong way to be
    // wrong. Presence is separately reported above and stays true either way.
    use crate::tpm::{TpmStatus, TpmVersion};
    match tpm.version {
        TpmVersion::Unknown => out.push(Reading::unavailable(
            "board.tpm.version",
            Some(Unit::Identifier),
            "a TPM is present but its specification version could not be determined",
        )),
        v => push_id(out, "board.tpm.version", &format!("{v:?}").to_lowercase()),
    }
    // An empty manufacturer here is a privilege boundary, not a silent device,
    // and `push_text` would have said "reader returned an empty string" -- a
    // reason that names the reader's disappointment rather than the cause.
    //
    // The chip vendor is published by `Win32_Tpm.ManufacturerIdTxt`, which
    // answers "Access denied" on an ordinary account. The device node beside it
    // *does* carry a `Manufacturer`, and on this machine it reads "(Standard)":
    // the driver provider, not the silicon vendor. Publishing that would be the
    // same category error as reporting a root hub's PCI ids as USB ones.
    if tpm.manufacturer.trim().is_empty() {
        out.push(Reading::unavailable(
            "board.tpm.manufacturer",
            Some(Unit::Identifier),
            "the TPM's manufacturer is published only by `Win32_Tpm`, which requires elevation; the security device node carries a driver provider rather than the chip vendor",
        ));
    } else {
        push_text(out, "board.tpm.manufacturer", &tpm.manufacturer);
    }
    match tpm.status {
        TpmStatus::Unknown => out.push(Reading::unavailable(
            "board.tpm.status",
            Some(Unit::Identifier),
            "a TPM is present but whether it is enabled could not be determined",
        )),
        s => push_id(out, "board.tpm.status", &format!("{s:?}").to_lowercase()),
    }
    // `None` here is not `false`. On Windows the positive comes from a Measured
    // Boot log and the negative cannot be evidenced at all; on macOS nothing is
    // consulted. Publishing a measured `false` would tell a security check that
    // integrity measurement is off, which is a claim this crate cannot make.
    push_opt(
        out,
        "board.tpm.measured_boot".to_string(),
        tpm.measured_boot.map(|b| serde_json::json!(b)),
        None,
        concat!(
            "a TPM is present but whether platform integrity measurements ",
            "are active could not be established"
        ),
    );
}

fn resolve_virtualization(out: &mut Vec<Reading>) {
    const IDS: [&str; 4] = [
        "system.virtualization.platform",
        "system.virtualization.hypervisor",
        "system.virtualization.detection_method",
        "system.virtualization.hardware_support",
    ];

    let monitor = match crate::virtualization::VirtMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            for id in IDS {
                out.push(Reading::unavailable(
                    id,
                    None,
                    format!("virtualization detection unavailable: {e}"),
                ));
            }
            return;
        }
    };

    let hypervisor = monitor.hypervisor();

    // Hyper-V used to be the one case IronMonitor could not call: with
    // virtualization-based security on — the Windows 11 default — the host OS
    // runs as the Hyper-V *root partition*, so CPUID reports "Microsoft Hv" on a
    // bare-metal workstation exactly as it does inside a guest. 3.7.0 reported
    // this entity as unavailable rather than guess, because it is the entity an
    // agent consults before trusting every other reading.
    //
    // 3.10.0 reads the partition privilege mask from CPUID leaf 0x40000003, which
    // answers it: only a root partition holds CreatePartitions and CpuManagement.
    // The special case below is now just the ordinary determination.
    let is_hyperv = matches!(
        hypervisor.as_ref().map(|h| &h.hypervisor),
        Some(crate::virtualization::Hypervisor::HyperV)
    );

    // Bare metal is a determination, not a failure to detect one.
    let platform = if monitor.is_container() {
        "container"
    } else if monitor.is_virtual_machine() {
        "virtual_machine"
    } else {
        "bare_metal"
    };
    push_id(out, "system.virtualization.platform", platform);

    match hypervisor {
        Some(h) => {
            push_id(
                out,
                "system.virtualization.hypervisor",
                &format!("{:?}", h.hypervisor).to_lowercase(),
            );
            push_text(
                out,
                "system.virtualization.detection_method",
                &h.detection_method,
            );
        }
        None => {
            out.push(Reading::unavailable(
                "system.virtualization.hypervisor",
                Some(Unit::Identifier),
                "no hypervisor detected; this machine appears to be bare metal",
            ));
            out.push(Reading::unavailable(
                "system.virtualization.detection_method",
                Some(Unit::Text),
                "no hypervisor was detected, so no detection method applied",
            ));
        }
    }

    // A running hypervisor masks the virtualization bits from CPUID, so a `false`
    // here under one means "not visible", not "not supported" — reporting it would
    // tell an agent this CPU cannot virtualize while it is actively virtualizing.
    match monitor.cpu_capabilities() {
        Some(c) if !is_hyperv => out.push(Reading::measured(
            "system.virtualization.hardware_support",
            serde_json::json!(c.hardware_virt),
            None,
        )),
        Some(_) => out.push(Reading::unavailable(
            "system.virtualization.hardware_support",
            None,
            "a hypervisor is masking the CPU virtualization bits from CPUID; \
             absence here would not mean the hardware lacks them",
        )),
        None => out.push(Reading::unavailable(
            "system.virtualization.hardware_support",
            None,
            "the platform did not report CPU virtualization capabilities",
        )),
    }
}

fn resolve_numa(out: &mut Vec<Reading>) {
    let monitor = match crate::numa::NumaMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            for id in ["memory.numa.nodes", "memory.numa.is_numa"] {
                out.push(Reading::unavailable(
                    id,
                    None,
                    format!("NUMA topology unavailable: {e}"),
                ));
            }
            return;
        }
    };

    let summary = monitor.summary();
    out.push(Reading::measured(
        "memory.numa.nodes",
        serde_json::json!(summary.node_count),
        Some(Unit::Count),
    ));
    out.push(Reading::measured(
        "memory.numa.is_numa",
        serde_json::json!(summary.is_numa),
        None,
    ));

    for node in monitor.nodes() {
        let base = format!("memory.numa.{}", node.id);
        out.push(Reading::measured(
            format!("{base}.cpus"),
            serde_json::json!(node.cpus.len()),
            Some(Unit::Count),
        ));
        push_opt(
            out,
            format!("{base}.memory"),
            // `> 0` was standing in for "was it read", which the type now
            // answers directly; a node genuinely reporting 0 bytes is a
            // reading and is published as one.
            node.memory_total_bytes.map(|b| serde_json::json!(b)),
            Some(Unit::Bytes),
            "the platform reported no memory total for this node",
        );
    }
}

fn resolve_ecc(out: &mut Vec<Reading>) {
    const IDS: [&str; 3] = [
        "memory.ecc.active",
        "memory.ecc.correctable_errors",
        "memory.ecc.uncorrectable_errors",
    ];

    let monitor = match crate::edac::EdacMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            // On Windows and macOS there is no EDAC equivalent IronMonitor reads, so
            // this is the common path. The note says so rather than implying the
            // machine has no ECC — which would be a claim about the hardware
            // rather than about the reader.
            for id in IDS {
                out.push(Reading::unavailable(
                    id,
                    None,
                    format!("no ECC error reporting interface available here: {e}"),
                ));
            }
            return;
        }
    };

    let overview = monitor.overview();
    if overview.total_controllers == 0 {
        for id in IDS {
            out.push(Reading::unavailable(
                id,
                None,
                "no memory controller exposed ECC reporting; the platform interface \
                 exists but enumerated nothing",
            ));
        }
        return;
    }

    out.push(Reading::measured(
        "memory.ecc.active",
        serde_json::json!(overview.ecc_active),
        None,
    ));
    // `measured` only when there is something measured.
    //
    // **The compiler cannot catch this one.** `serde_json::json!` accepts an
    // `Option` and renders `None` as `null`, so writing the totals straight
    // through would produce a reading with `provenance: measured` and a null
    // value — a claimed observation of nothing, through the very field that
    // exists to keep claims honest. The totals are `None` whenever any
    // controller's counter could not be read.
    match overview.total_ce {
        Some(count) => out.push(Reading::measured(
            "memory.ecc.correctable_errors",
            serde_json::json!(count),
            Some(Unit::Count),
        )),
        None => out.push(Reading::unavailable(
            "memory.ecc.correctable_errors",
            Some(Unit::Count),
            "a memory controller's correctable-error counter could not be read;              a total over partly-unknown inputs would understate it",
        )),
    }
    match overview.total_ue {
        Some(count) => out.push(Reading::measured(
            "memory.ecc.uncorrectable_errors",
            serde_json::json!(count),
            Some(Unit::Count),
        )),
        None => out.push(Reading::unavailable(
            "memory.ecc.uncorrectable_errors",
            Some(Unit::Count),
            "a memory controller's uncorrectable-error counter could not be read;              a total over partly-unknown inputs would understate it",
        )),
    }
}

fn resolve_pci(out: &mut Vec<Reading>) {
    let monitor = match crate::pci_devices::PciDeviceMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            out.push(Reading::unavailable(
                "pci.<none>",
                None,
                format!("PCI enumeration failed: {e}"),
            ));
            return;
        }
    };
    if monitor.devices().is_empty() {
        out.push(Reading::unavailable(
            "pci.<none>",
            None,
            "no PCI devices enumerated on this machine",
        ));
        return;
    }

    for dev in monitor.devices() {
        let base = format!("pci.{}", id_segment(&dev.address));
        push_text(out, format!("{base}.vendor"), &dev.vendor_name);
        push_text(out, format!("{base}.device"), &dev.device_name);
        push_id(
            out,
            format!("{base}.class"),
            &format!("{:?}", dev.class).to_lowercase(),
        );
        push_opt(
            out,
            format!("{base}.driver"),
            (!dev.driver.trim().is_empty()).then(|| serde_json::json!(dev.driver)),
            Some(Unit::Text),
            "no driver is bound to this device",
        );

        match &dev.link_info {
            Some(link) => {
                for (suffix, value) in [
                    ("link.width", &link.width),
                    ("link.max_width", &link.max_width),
                    ("link.speed", &link.speed),
                    ("link.max_speed", &link.max_speed),
                ] {
                    push_opt(
                        out,
                        format!("{base}.{suffix}"),
                        (!value.trim().is_empty()).then(|| serde_json::json!(value)),
                        Some(Unit::Identifier),
                        "the device did not report this link property",
                    );
                }
            }
            None => {
                for suffix in [
                    "link.width",
                    "link.max_width",
                    "link.speed",
                    "link.max_speed",
                ] {
                    out.push(Reading::unavailable(
                        format!("{base}.{suffix}"),
                        Some(Unit::Identifier),
                        "Windows populates the PCIe link properties on the device \
                         node for endpoints only. Bridges, switch ports and host \
                         bridges carry none, and neither do devices that are not \
                         PCIe at all; this is one of those. Measured on a 64-device \
                         host: 23 carry the properties, and IronMonitor reports all 23",
                    ));
                }
            }
        }

        // The reader uses -1 for "no affinity". Passing that through would give an
        // agent a node number that does not exist.
        push_opt(
            out,
            format!("{base}.numa_node"),
            (dev.numa_node >= 0).then(|| serde_json::json!(dev.numa_node)),
            Some(Unit::Count),
            "the platform reports no NUMA affinity for this device",
        );
    }
}

fn resolve_usb(out: &mut Vec<Reading>) {
    let monitor = match crate::usb::UsbMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            out.push(Reading::unavailable(
                "usb.<none>",
                None,
                format!("USB enumeration failed: {e}"),
            ));
            return;
        }
    };
    if monitor.devices().is_empty() {
        out.push(Reading::unavailable(
            "usb.<none>",
            None,
            "no USB devices enumerated on this machine",
        ));
        return;
    }

    for dev in monitor.devices() {
        // The device's own path, not enumeration order and not bus-and-port.
        //
        // This used to be `{bus_number}_{port_number}` with a comment arguing
        // that an index would repoint every id when an unrelated device was
        // unplugged -- and the Windows reader filled those two fields with `0`
        // and the index. Bus and port cannot fix it either: of this machine's
        // 41 USB nodes only 14 have a hub and port Windows reports, and the
        // composite-device interfaces share their parent's location, so the
        // ids would have been stable and collided. `UsbDevice::address` is the
        // platform's own device path, which is unique and moves only with the
        // device.
        let base = format!("usb.{}", id_segment(&dev.address));
        push_opt(
            out,
            format!("{base}.product"),
            dev.product
                .as_ref()
                .or(dev.description.as_ref())
                .map(|p| serde_json::json!(p)),
            Some(Unit::Text),
            "the device publishes no product string",
        );
        push_opt(
            out,
            format!("{base}.manufacturer"),
            dev.manufacturer.as_ref().map(|m| serde_json::json!(m)),
            Some(Unit::Text),
            "the device publishes no manufacturer string",
        );
        // A root hub's PnP id carries no VID_ or PID_ at all, so these were
        // published as the identifier "0000" — a value indistinguishable from a
        // device that reports it.
        push_opt(
            out,
            format!("{base}.vendor_id"),
            dev.vendor_id.map(|v| serde_json::json!(format!("{v:04x}"))),
            Some(Unit::Identifier),
            "this entry carries no USB vendor id; root hubs and virtual devices have none",
        );
        push_opt(
            out,
            format!("{base}.product_id"),
            dev.product_id
                .map(|p| serde_json::json!(format!("{p:04x}"))),
            Some(Unit::Identifier),
            "this entry carries no USB product id; root hubs and virtual devices have none",
        );
        // `Unknown` on either of these is the descriptor not having been read, not
        // a device that identifies itself as unknown. Third occurrence of this
        // shape in one sweep, which is why it is called out in the handoff.
        use crate::usb::{UsbDeviceClass, UsbSpeed};
        match dev.class {
            UsbDeviceClass::Unknown => out.push(Reading::unavailable(
                format!("{base}.class"),
                Some(Unit::Identifier),
                concat!(
                    "no class was recorded for this node: no device-descriptor ",
                    "class, no interface class, and no hub identifier, in ",
                    "either its hardware or its compatible ids. The usual cases ",
                    "are a composite parent, which declares class 00 to say the ",
                    "class is defined per interface and leaves its interfaces to ",
                    "answer, and a node enumerated on another bus -- a USBSTOR ",
                    "disk or a USB4 router -- which has no USB device descriptor ",
                    "to declare one from"
                ),
            )),
            c => push_id(
                out,
                format!("{base}.class"),
                &format!("{c:?}").to_lowercase(),
            ),
        }
        match dev.speed {
            UsbSpeed::Unknown => out.push(Reading::unavailable(
                format!("{base}.speed"),
                Some(Unit::Identifier),
                concat!(
                    "no hub reported a negotiated speed for this device. The ",
                    "speed is a property of a link, so a node that sits on no ",
                    "upstream hub port has none to report -- a root hub is the ",
                    "usual case, and reporting one for it would be describing a ",
                    "link that does not exist. A device on a bus this reader ",
                    "does not walk reaches the same answer by a different route"
                ),
            )),
            s => push_id(
                out,
                format!("{base}.speed"),
                &format!("{s:?}").to_lowercase(),
            ),
        }
    }
}

fn resolve_memory_dimms(out: &mut Vec<Reading>) {
    const PER_SLOT: [&str; 10] = [
        "capacity",
        "speed",
        "configured_speed",
        "type",
        "manufacturer",
        "part_number",
        "ecc",
        "data_width",
        "total_width",
        "voltage",
    ];

    let monitor = match crate::memory_topology::MemoryTopologyMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            out.push(Reading::unavailable(
                "memory.dimm.0.locator",
                Some(Unit::Text),
                format!("memory topology unavailable: {e}"),
            ));
            return;
        }
    };

    for (i, dimm) in monitor.topology().dimms.iter().enumerate() {
        let base = format!("memory.dimm.{i}");
        push_spec_text(out, format!("{base}.locator"), &dimm.locator);
        // Firmware-declared like the rest of the cluster: the board says the
        // slot is filled, and ironmon did not look inside the case.
        push_spec_opt(
            out,
            format!("{base}.populated"),
            dimm.populated.map(|p| serde_json::json!(p)),
            None,
            concat!(
                "nothing the platform reported establishes whether this slot holds a ",
                "module: no size could be read, and no status or part number says"
            ),
        );

        // An empty slot is a real slot with nothing in it. Reporting zeros for its
        // capacity and speed would describe a module of no size running at no
        // speed, which is not what the board is telling us.
        if dimm.populated == Some(false) {
            for suffix in PER_SLOT {
                out.push(Reading::unavailable(
                    format!("{base}.{suffix}"),
                    None,
                    "this slot is empty",
                ));
            }
            continue;
        }

        push_spec_opt(
            out,
            format!("{base}.capacity"),
            dimm.capacity_bytes.map(|b| serde_json::json!(b)),
            Some(Unit::Bytes),
            "no module size was read for this slot",
        );
        push_spec_opt(
            out,
            format!("{base}.speed"),
            dimm.speed_mts.map(|v| serde_json::json!(v)),
            Some(Unit::MegatransfersPerSecond),
            "SMBIOS reported no rated speed",
        );
        push_spec_opt(
            out,
            format!("{base}.configured_speed"),
            // `> 0` passed the substituted rated speed straight through, since
            // it was non-zero. The reader no longer substitutes, so the type
            // now carries the absence the guard could not see.
            dimm.configured_speed_mts.map(|v| serde_json::json!(v)),
            Some(Unit::MegatransfersPerSecond),
            "SMBIOS reported no configured speed",
        );
        push_spec_id(
            out,
            format!("{base}.type"),
            &format!("{:?}", dimm.memory_type).to_lowercase(),
        );
        push_spec_text(out, format!("{base}.manufacturer"), &dimm.manufacturer);
        push_spec_text(out, format!("{base}.part_number"), &dimm.part_number);
        push_spec_opt(
            out,
            format!("{base}.data_width"),
            dimm.data_width_bits
                .filter(|w| *w > 0)
                .map(|w| serde_json::json!(w)),
            Some(Unit::Count),
            "SMBIOS reported no data width",
        );
        push_spec_opt(
            out,
            format!("{base}.total_width"),
            dimm.total_width_bits
                .filter(|w| *w > 0)
                .map(|w| serde_json::json!(w)),
            Some(Unit::Count),
            "SMBIOS reported no total width",
        );
        // ECC is the widths differing, so it can only be stated when both are
        // known. Two zeros are equal, and would otherwise report "no ECC".
        //
        // That guard was right about the danger and wrong about the sentinel:
        // the readers defaulted `data_width` to **64** and `total_width` to
        // whatever `data_width` became, so both passed `> 0` and this published
        // `ecc: false` as `derived` for any DIMM whose widths were not read.
        // A `> 0` guard only defends against a zero; a plausible default walks
        // through it. The fields are `Option` now and the question is asked
        // directly.
        if let Some(ecc) = dimm.is_ecc() {
            out.push(Reading::derived(
                format!("{base}.ecc"),
                serde_json::json!(ecc),
                None,
            ));
        } else {
            out.push(Reading::unavailable(
                format!("{base}.ecc"),
                None,
                "ECC is inferred from the data and total widths, and one is unknown",
            ));
        }
        push_spec_opt(
            out,
            format!("{base}.voltage"),
            dimm.voltage.map(|v| serde_json::json!(v)),
            Some(Unit::Volts),
            "SMBIOS reported no operating voltage",
        );
    }
}

fn resolve_cpu_cache(out: &mut Vec<Reading>) {
    const TOTALS: [&str; 4] = [
        "cpu.cache.l1d",
        "cpu.cache.l1i",
        "cpu.cache.l2",
        "cpu.cache.l3",
    ];

    let monitor = match crate::cpu_cache::CpuCacheMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            for id in TOTALS {
                out.push(Reading::unavailable(
                    id,
                    Some(Unit::Bytes),
                    format!("cache topology unavailable: {e}"),
                ));
            }
            return;
        }
    };

    let topology = monitor.topology();
    // The platform sources state these in KiB. Converting here keeps every
    // capacity in the ontology in bytes, so an agent never has to ask which unit a
    // particular size field happens to use.
    let kib = |v: u64| (v > 0).then(|| serde_json::json!(v * 1024));
    for (id, value) in TOTALS.iter().zip([
        topology.total_l1d_kb,
        topology.total_l1i_kb,
        topology.total_l2_kb,
        topology.total_l3_kb,
    ]) {
        push_opt(
            out,
            *id,
            kib(value),
            Some(Unit::Bytes),
            "no aggregate was reported for this level; some platforms publish a \
             combined L1 rather than separate data and instruction figures, in \
             which case the per-instance entities below carry the sizes",
        );
    }

    for (i, cache) in monitor.caches().iter().enumerate() {
        let base = format!("cpu.cache.{i}");
        push_id(
            out,
            format!("{base}.level"),
            &format!("{:?}", cache.level).to_lowercase(),
        );
        push_opt(
            out,
            format!("{base}.size"),
            kib(cache.size_kb),
            Some(Unit::Bytes),
            "the platform reported no size for this cache",
        );
        push_opt(
            out,
            format!("{base}.line_size"),
            cache.line_size.map(|b| serde_json::json!(b)),
            Some(Unit::Bytes),
            "the platform reported no line size for this cache",
        );
        push_opt(
            out,
            format!("{base}.shared_cpus"),
            (!cache.shared_cpu_list.trim().is_empty())
                .then(|| serde_json::json!(cache.shared_cpu_list)),
            Some(Unit::Text),
            "the platform does not publish which processors share this cache",
        );
    }
}

fn resolve_gpu(out: &mut Vec<Reading>) {
    // All three failure paths report against `gpu.<none>`, the declared
    // diagnostic for a domain that enumerated nothing — not against `gpu.0.name`.
    //
    // Reporting them as an unavailable `gpu.0.name` asserted that adapter zero
    // exists and could not be read, when the truth is that no adapter is known
    // to exist at all. It also broke the schema's own promise: `gpu.{n}.name` is
    // declared non-nullable, meaning a GPU always has a name, so an unavailable
    // one is by definition a reader bug. On a headless CI runner that is exactly
    // what it was, and `non_nullable_entities_are_never_null` said so — on Linux,
    // where there is no GPU. Every machine that had one passed.
    let Ok(monitor) = crate::UnifiedMonitor::new() else {
        out.push(Reading::unavailable(
            "gpu.<none>",
            None,
            "GPU enumeration failed",
        ));
        return;
    };
    // Per adapter, not all-or-nothing. This took `snapshot_gpus()`, which fails
    // as a whole when any one adapter's query fails, and answered that with
    // `gpu.<none>` -- the row declared to mean "this domain enumerated nothing".
    // A machine with two GPUs and one flaky driver was reported as having no
    // GPU, and the adapter that read fine was dropped with it. The partial
    // snapshot is index-aligned, so a failure keeps its adapter's number.
    let gpus = monitor.gpus().snapshot_all_partial();
    if gpus.is_empty() {
        // Absent hardware is a fact, not a failure — and not a zero-valued GPU.
        out.push(Reading::unavailable(
            "gpu.<none>",
            None,
            "no GPU detected on this machine",
        ));
        return;
    }

    // Six of these entities used to name the driver or the vendor as the party
    // that reported nothing -- "driver reports no power telemetry", "vendor
    // publishes no thermal limit for this adapter". On this machine's AMD
    // integrated GPU all six were false in the same way: the Windows AMD
    // backend sets `clocks` and `power` to `None` without consulting anything,
    // and the Intel one says so in a comment ("nothing is read on this
    // platform, so nothing is reported"). AMD's ADL libraries are installed
    // here -- `atiadlxx.dll` and `amdadlx64.dll` are both in System32 -- so the
    // driver does publish this and IronMonitor has no binding to ask it.
    //
    // The reasons now say what was read rather than what a vendor supposedly
    // withholds. They stay true for an NVIDIA card, where NVML *was* asked and
    // declined.
    const NO_ADAPTER_TEMPERATURE: &str = concat!(
        "no temperature was read for this adapter. NVML answers for NVIDIA ",
        "cards; on Windows an AMD or Intel adapter has no source in ironmon but ",
        "an OpenHardwareMonitor or LibreHardwareMonitor WMI namespace, which ",
        "exists only where one of those tools is installed. An adapter with no ",
        "sensor and a ironmon with no binding to the vendor SDK are ",
        "indistinguishable from here"
    );
    const NO_ADAPTER_THERMAL_LIMIT: &str = concat!(
        "no thermal limit was read for this adapter. NVML publishes one for ",
        "NVIDIA cards; the Windows AMD and Intel backends fill this field with ",
        "nothing, without asking the driver whether it has one"
    );
    const NO_ADAPTER_SHUTDOWN_THRESHOLD: &str = concat!(
        "no shutdown threshold was read for this adapter. NVML publishes one ",
        "for NVIDIA cards; the Windows AMD and Intel backends fill this field ",
        "with nothing, without asking the driver whether it has one"
    );
    const NO_ADAPTER_POWER_DRAW: &str = concat!(
        "no power draw was read for this adapter. NVML reports it for NVIDIA ",
        "cards; the Windows AMD and Intel backends set this field to nothing ",
        "without consulting the driver, and both vendors expose it through a ",
        "library IronMonitor does not bind"
    );
    const NO_ADAPTER_POWER_CAP: &str = concat!(
        "no enforced power cap was read for this adapter. See the power draw ",
        "beside it: on Windows the AMD and Intel backends consult nothing for ",
        "either figure"
    );
    const NO_ADAPTER_CLOCK: &str = concat!(
        "no graphics clock was read for this adapter. NVML reports it for ",
        "NVIDIA cards, the Linux sysfs readers report it for AMD and Intel, ",
        "and the Windows AMD and Intel backends consult nothing -- there is no ",
        "clock in the Windows GPU performance counters, and the vendor ",
        "libraries that do carry one are not bound"
    );
    const NO_ADAPTER_CLOCK_CEILING: &str = concat!(
        "no graphics clock ceiling was read for this adapter. See the clock ",
        "beside it"
    );

    const NO_ADAPTER_UTILIZATION: &str = concat!(
        "no utilization counter was read for this adapter; the backend that ",
        "queried it reports none, which is not the same as an idle engine"
    );

    for (i, gpu) in gpus.iter().enumerate() {
        let gpu = match gpu {
            Ok(gpu) => gpu,
            Err(e) => {
                out.push(Reading::unavailable(
                    format!("gpu.{i}.<unreadable>"),
                    None,
                    format!("this adapter was enumerated but its query failed: {e}"),
                ));
                continue;
            }
        };
        let base = format!("gpu.{i}");
        push_text(out, format!("{base}.name"), &gpu.static_info.name);
        out.push(Reading::measured(
            format!("{base}.vendor"),
            serde_json::json!(format!("{:?}", gpu.static_info.vendor).to_lowercase()),
            Some(Unit::Identifier),
        ));

        let dynamic = &gpu.dynamic_info;
        // This comment used to say utilization was not an Option, because the
        // collection layer flattened an absent counter to zero. The field became
        // `Option<u8>` and this call stayed `Reading::measured`, so an adapter
        // with no counter was published as a *measured* reading whose value was
        // null -- neither a number nor an absence with a reason.
        push_opt(
            out,
            format!("{base}.utilization"),
            dynamic.utilization.map(|u| serde_json::json!(u)),
            Some(Unit::Percent),
            NO_ADAPTER_UTILIZATION,
        );
        push_opt(
            out,
            format!("{base}.thermal.temperature"),
            dynamic.thermal.temperature.map(|t| serde_json::json!(t)),
            Some(Unit::Celsius),
            NO_ADAPTER_TEMPERATURE,
        );
        push_opt(
            out,
            format!("{base}.thermal.max_temperature"),
            dynamic
                .thermal
                .max_temperature
                .map(|t| serde_json::json!(t)),
            Some(Unit::Celsius),
            NO_ADAPTER_THERMAL_LIMIT,
        );
        push_opt(
            out,
            format!("{base}.thermal.critical_temperature"),
            dynamic
                .thermal
                .critical_temperature
                .map(|t| serde_json::json!(t)),
            Some(Unit::Celsius),
            NO_ADAPTER_SHUTDOWN_THRESHOLD,
        );
        push_opt(
            out,
            format!("{base}.power.draw"),
            dynamic.power.draw.map(|p| serde_json::json!(p)),
            Some(Unit::Milliwatts),
            NO_ADAPTER_POWER_DRAW,
        );
        push_opt(
            out,
            format!("{base}.power.limit"),
            dynamic.power.limit.map(|p| serde_json::json!(p)),
            Some(Unit::Milliwatts),
            NO_ADAPTER_POWER_CAP,
        );
        push_opt(
            out,
            format!("{base}.clocks.graphics"),
            dynamic.clocks.graphics.map(|c| serde_json::json!(c)),
            Some(Unit::Megahertz),
            NO_ADAPTER_CLOCK,
        );
        push_opt(
            out,
            format!("{base}.clocks.graphics.max"),
            dynamic.clocks.graphics_max.map(|c| serde_json::json!(c)),
            Some(Unit::Megahertz),
            NO_ADAPTER_CLOCK_CEILING,
        );

        // Each figure stands on its own now. The old gate was `total > 0`,
        // which published *both* as unavailable whenever the total was missing
        // -- including the case where the used bytes were read perfectly well
        // and only the adapter's capacity was unknown, which is what the WMI
        // readers hit. It also had to infer absence from a zero, because the
        // zero was all the type could carry.
        let mem = &dynamic.memory;
        for (suffix, value) in [("total", mem.total), ("used", mem.used)] {
            match value {
                Some(bytes) => out.push(Reading::measured(
                    format!("{base}.memory.{suffix}"),
                    serde_json::json!(bytes),
                    Some(Unit::Bytes),
                )),
                None => out.push(Reading::unavailable(
                    format!("{base}.memory.{suffix}"),
                    Some(Unit::Bytes),
                    "the driver reported no figure for it. Unified-memory parts \
                     have no discrete video memory to report, and some adapters \
                     publish usage without publishing a capacity",
                )),
            }
        }
    }
}

// ── Helpers ──────────────────────────────────────────────────────────────────

/// Make a device name safe to use as one segment of a dotted id.
///
/// Device names are chosen by vendors and drivers, not by ironmon: Windows hands back
/// "Bluetooth Network Connection", and VLAN interfaces carry dots. Both break the id
/// contract — a dot creates a spurious path segment, and whitespace makes the id
/// impossible to pass to `ironmon get` without quoting. Substitution is lossy but
/// total, which matters more here than being reversible: an id an agent cannot type
/// is not an id.
pub(crate) fn id_segment(raw: &str) -> String {
    let cleaned: String = raw
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
                c
            } else {
                '_'
            }
        })
        .collect();
    // Collapse runs so "Bluetooth Network Connection" does not become a thicket of
    // underscores, and trim the edges.
    let mut out = String::with_capacity(cleaned.len());
    let mut last_underscore = false;
    for c in cleaned.chars() {
        if c == '_' {
            if !last_underscore {
                out.push(c);
            }
            last_underscore = true;
        } else {
            out.push(c);
            last_underscore = false;
        }
    }
    let trimmed = out.trim_matches('_').to_string();
    if trimmed.is_empty() {
        "unnamed".to_string()
    } else {
        trimmed
    }
}

/// Strings that name an absence rather than state a value.
///
/// DMI is the reason this exists: firmware tables routinely carry "n/a" or
/// "unknown" where a board vendor left a field unfilled, and passing those
/// through as `measured` hands an agent a reading that says nothing while
/// looking exactly like one that says something. `board.firmware.{n}.version`
/// did that on Linux CI runners, whose virtualised firmware fills two entries
/// with "n/a".
///
/// The list matches `unknown_is_never_dressed_as_a_measurement` in
/// `tests/ontology_conformance.rs`, which forbids these values in readings. It
/// is enforced here, at the one place every text reading passes through, rather
/// than in each reader — the conformance test has caught this class three times
/// now, always in a different reader.
const ABSENCE_WORDS: [&str; 5] = ["unknown", "unspecified", "undetermined", "n/a", "none"];

/// Public because the agent tool surface needs the *same* predicate, not a
/// second copy of the list. `ai_api::call_tool` applies it to every value it
/// returns; before that it had no guard at all, and `get_usb_devices` handed an
/// agent `"speed": "Unknown"` seventy times on one machine while the ontology
/// was rejecting that exact string.
pub fn names_an_absence(value: &str) -> bool {
    let v = value.trim().to_ascii_lowercase();
    ABSENCE_WORDS.contains(&v.as_str())
}

fn push_text(out: &mut Vec<Reading>, id: impl Into<String>, value: &str) {
    push_str_as(out, id, value, Unit::Text, Provenance::Measured);
}

/// `push_text` for a firmware-declared string. The absence handling is
/// identical; only the provenance differs, and it differs because a DIMM's
/// manufacturer was not measured off the module -- the SMBIOS table said so.
fn push_spec_text(out: &mut Vec<Reading>, id: impl Into<String>, value: &str) {
    push_str_as(out, id, value, Unit::Text, Provenance::Specification);
}

fn push_id(out: &mut Vec<Reading>, id: impl Into<String>, value: &str) {
    push_str_as(out, id, value, Unit::Identifier, Provenance::Measured);
}

/// `push_id` for a firmware-declared identifier.
fn push_spec_id(out: &mut Vec<Reading>, id: impl Into<String>, value: &str) {
    push_str_as(out, id, value, Unit::Identifier, Provenance::Specification);
}

/// The one place a string reading becomes a `Reading`.
///
/// Both guards below were added after the fact, each because a reader had
/// already tripped it. An empty string is an absence, and a string that spells
/// an absence -- an enum's `Unknown` variant lowercased, most often -- is also
/// an absence however confidently it arrives. Keeping this in one function is
/// why the second guard only had to be written once: the conformance test has
/// caught this class three times, in three different readers.
fn push_str_as(
    out: &mut Vec<Reading>,
    id: impl Into<String>,
    value: &str,
    unit: Unit,
    provenance: Provenance,
) {
    let id = id.into();
    if value.trim().is_empty() {
        out.push(Reading::unavailable(
            id,
            Some(unit),
            "reader returned an empty string",
        ));
        return;
    }
    if names_an_absence(value) {
        out.push(Reading::unavailable(
            id,
            Some(unit),
            format!(
                "reader returned {:?}, which names an absence rather than a value",
                value.trim()
            ),
        ));
        return;
    }
    let json = serde_json::json!(value);
    out.push(match provenance {
        Provenance::Specification => Reading::spec(id, json, Some(unit)),
        Provenance::Derived => Reading::derived(id, json, Some(unit)),
        _ => Reading::measured(id, json, Some(unit)),
    });
}

fn push_opt(
    out: &mut Vec<Reading>,
    id: impl Into<String>,
    value: Option<serde_json::Value>,
    unit: Option<Unit>,
    why_absent: &str,
) {
    match value {
        // A string that names an absence is an absence, however it arrived.
        // `push_text` and `push_id` were guarded first on the reasoning that
        // they were the only route a text reading could take; they were not.
        // `pci.*.link.speed` came through here as "unknown" with measured
        // provenance, on Linux, where PCIe link training is readable and some
        // devices report exactly that word.
        Some(v) if v.as_str().is_some_and(names_an_absence) => {
            out.push(Reading::unavailable(
                id,
                unit,
                format!(
                    "reader returned {}, which names an absence rather than a value",
                    v
                ),
            ));
        }
        Some(v) => out.push(Reading::measured(id, v, unit)),
        None => out.push(Reading::unavailable(id, unit, why_absent)),
    }
}

/// The platform CPU reader, keeping the error text.
///
/// `.ok()` threw it away, so every failure surfaced as the same sentence — "the
/// platform CPU reader returned an error" — with no way to tell a permission
/// problem from a parse failure from an unimplemented platform. There is a test
/// called `every_absence_carries_a_usable_reason`; a constant string satisfies
/// it and tells a reader nothing.
fn read_cpu_stats() -> Result<crate::core::cpu::CpuStats, String> {
    #[cfg(windows)]
    {
        crate::platform::windows::read_cpu_stats().map_err(|e| e.to_string())
    }
    #[cfg(target_os = "linux")]
    {
        crate::platform::linux::read_cpu_stats().map_err(|e| e.to_string())
    }
    #[cfg(target_os = "macos")]
    {
        crate::platform::macos::read_cpu_stats().map_err(|e| e.to_string())
    }
    #[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
    {
        Err("no CPU reader is implemented for this platform".to_string())
    }
}

/// The platform memory reader, keeping the error text. See [`read_cpu_stats`].
fn read_memory_stats() -> Result<crate::core::memory::MemoryStats, String> {
    #[cfg(windows)]
    {
        crate::platform::windows::read_memory_stats().map_err(|e| e.to_string())
    }
    #[cfg(target_os = "linux")]
    {
        crate::platform::linux::read_memory_stats().map_err(|e| e.to_string())
    }
    #[cfg(target_os = "macos")]
    {
        crate::platform::macos::read_memory_stats().map_err(|e| e.to_string())
    }
    #[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
    {
        Err("no memory reader is implemented for this platform".to_string())
    }
}

fn detect_board() -> Option<crate::core::platform_info::BoardInfo> {
    #[cfg(windows)]
    {
        crate::platform::windows::detect_platform().ok()
    }
    #[cfg(not(windows))]
    {
        None
    }
}

/// Check a snapshot against the ontology's declared ranges.
///
/// Returns one message per reading that is physically impossible. An empty result
/// is the assertion this repository's plausibility tier makes, available to any
/// consumer rather than only to the test suite.
pub fn validate(readings: &[Reading]) -> Vec<String> {
    let ontology = Ontology::build();
    let mut problems = Vec::new();
    for r in readings {
        let Some(value) = r.value.as_ref().and_then(|v| v.as_f64()) else {
            continue;
        };
        if let Some(entity) = lookup_template(&ontology, &r.id) {
            if let Some(problem) = entity.validate_range(value) {
                problems.push(problem);
            }
        }
    }
    problems
}

/// Find the entity for a concrete id, matching `gpu.0.name` against `gpu.{n}.name`.
fn lookup_template<'a>(ontology: &'a Ontology, concrete: &str) -> Option<&'a Entity> {
    ontology.template_for(concrete)
}

/// Number of processes reported. Enumerating every process would make a snapshot
/// dominated by transient noise, so the list is capped — and the cap is announced as
/// a reading rather than applied silently, because a truncated list that looks
/// complete is its own kind of wrong answer.
const PROCESS_LIMIT: usize = 10;

/// The interval `process.{pid}.cpu` is measured over. Long enough that a
/// scheduler tick is a small fraction of it, short enough not to dominate a
/// snapshot.
const PROCESS_CPU_INTERVAL_MS: u64 = 250;

fn resolve_disk(out: &mut Vec<Reading>) {
    let disks = match crate::disk::enumerate_disks() {
        Ok(d) => d,
        Err(e) => {
            out.push(Reading::unavailable(
                "disk.<none>",
                None,
                format!("disk enumeration failed: {e}"),
            ));
            return;
        }
    };
    if disks.is_empty() {
        out.push(Reading::unavailable(
            "disk.<none>",
            None,
            "no block devices enumerated on this machine",
        ));
        return;
    }

    for (i, disk) in disks.iter().enumerate() {
        let base = format!("disk.{i}");
        match disk.info() {
            Ok(info) => {
                push_text(out, format!("{base}.model"), &info.model);
                // `capacity > 0` was this resolver compensating for a field
                // that could not say "not read". It can now, and the two cases
                // are finally distinguishable: a device that genuinely reports
                // zero is a different answer from one nobody asked.
                match info.capacity {
                    Some(bytes) if bytes > 0 => out.push(Reading::measured(
                        format!("{base}.capacity"),
                        serde_json::json!(bytes),
                        Some(Unit::Bytes),
                    )),
                    Some(_) => out.push(Reading::unavailable(
                        format!("{base}.capacity"),
                        Some(Unit::Bytes),
                        "device reported zero capacity",
                    )),
                    // Newly expressible: the reader never obtained a capacity,
                    // which the old sentinel could not distinguish from a
                    // device answering zero.
                    None => out.push(Reading::unavailable(
                        format!("{base}.capacity"),
                        Some(Unit::Bytes),
                        "capacity was not read from this device",
                    )),
                }
            }
            Err(e) => {
                for suffix in ["model", "capacity"] {
                    out.push(Reading::unavailable(
                        format!("{base}.{suffix}"),
                        None,
                        format!("device info read failed: {e}"),
                    ));
                }
            }
        }

        // Throughput is documented as calculated from recent samples. One sample is
        // not two, so a single-shot query legitimately has none.
        match disk.io_stats() {
            Ok(io) => {
                push_opt(
                    out,
                    format!("{base}.read_rate"),
                    io.read_throughput.map(|v| serde_json::json!(v)),
                    Some(Unit::BytesPerSecond),
                    "a throughput needs two samples; this query took one",
                );
                push_opt(
                    out,
                    format!("{base}.write_rate"),
                    io.write_throughput.map(|v| serde_json::json!(v)),
                    Some(Unit::BytesPerSecond),
                    "a throughput needs two samples; this query took one",
                );
            }
            Err(e) => {
                for suffix in ["read_rate", "write_rate"] {
                    out.push(Reading::unavailable(
                        format!("{base}.{suffix}"),
                        Some(Unit::BytesPerSecond),
                        format!("I/O statistics read failed: {e}"),
                    ));
                }
            }
        }

        resolve_disk_health(out, &base, disk.as_ref());
    }
}

/// Health, SMART and NVMe entities for one drive.
///
/// Split out because the three readers fail independently and each has its own
/// reason to have nothing to say — a SATA drive has no NVMe log page, an NVMe
/// drive has no sector reallocation concept, and a USB bridge may tunnel neither.
/// An agent needs those told apart, so each absence carries the reason rather than
/// the row being omitted.
fn resolve_disk_health(out: &mut Vec<Reading>, base: &str, disk: &dyn crate::disk::DiskDevice) {
    // Spelled out rather than derived from `{:?}`, which lowercases `NvmeSsd` to
    // `nvmessd` — a token no reader would guess and no id elsewhere resembles.
    use crate::disk::DiskType;
    let kind = match disk.disk_type() {
        DiskType::NvmeSsd => Some("nvme_ssd"),
        DiskType::SataSsd => Some("sata_ssd"),
        DiskType::SataHdd => Some("sata_hdd"),
        DiskType::Scsi => Some("scsi"),
        DiskType::Usb => Some("usb"),
        DiskType::Virtual => Some("virtual"),
        DiskType::Unknown => None,
    };
    push_opt(
        out,
        format!("{base}.kind"),
        kind.map(|k| serde_json::json!(k)),
        Some(Unit::Text),
        "the platform did not classify this device's transport or medium",
    );

    match disk.info() {
        Ok(info) => push_opt(
            out,
            format!("{base}.serial"),
            info.serial.as_ref().map(|s| serde_json::json!(s)),
            Some(Unit::Text),
            "the platform did not disclose a serial number for this device",
        ),
        Err(e) => out.push(Reading::unavailable(
            format!("{base}.serial"),
            Some(Unit::Text),
            format!("device info read failed: {e}"),
        )),
    }

    // `Unknown` is the absence of a verdict, not a verdict of "unknown". Passing it
    // through as a measured string would let an agent record a health check it
    // never actually got — the same shape as reporting an access error as 0 °C.
    use crate::disk::DiskHealth;
    match disk.health() {
        Ok(DiskHealth::Unknown) => out.push(Reading::unavailable(
            format!("{base}.health"),
            Some(Unit::Text),
            "no counter this device exposes yielded a health verdict",
        )),
        Ok(h) => push_text(
            out,
            format!("{base}.health"),
            &format!("{h:?}").to_lowercase(),
        ),
        Err(e) => out.push(Reading::unavailable(
            format!("{base}.health"),
            Some(Unit::Text),
            format!("health read failed: {e}"),
        )),
    }

    const SMART_FIELDS: [&str; 7] = [
        "temperature",
        "smart.passed",
        "smart.power_on_hours",
        "smart.power_cycles",
        "smart.reallocated_sectors",
        "smart.pending_sectors",
        "smart.uncorrectable_sectors",
    ];

    match disk.smart_info() {
        Ok(s) => {
            // Each absence below is explained by *which source answered*, which
            // `SmartInfo` now carries. Before it, every one of these was a claim
            // about the drive -- "the drive did not report a power cycle count",
            // "this device exposes no thermal sensor" -- made without knowing
            // whether the drive had been asked. On this machine's USB drive none
            // of them had: its counters come from
            // `Get-StorageReliabilityCounter`, which fails unelevated for every
            // disk here, so four absences blamed a device that was never
            // consulted.
            use crate::disk::SmartSource;
            let from_the_drive = matches!(
                s.source,
                SmartSource::NvmeLogPage | SmartSource::AtaAttributes
            );
            let counter_absent = |what: &str| -> String {
                if from_the_drive {
                    format!("the drive did not report a {what}")
                } else {
                    format!(
                        "no {what} was read: this drive's counters come from the \
                         operating system's storage stack rather than from the \
                         drive -- `Get-StorageReliabilityCounter` on Windows, which \
                         needs Administrator -- and it returned nothing here. The \
                         drive was not asked"
                    )
                }
            };

            push_opt(
                out,
                format!("{base}.temperature"),
                s.temperature.map(|t| serde_json::json!(t)),
                Some(Unit::Celsius),
                if from_the_drive {
                    "this device exposes no thermal sensor"
                } else {
                    "no temperature was read: it would come from the storage \
                     stack's reliability counters, which returned nothing here. \
                     Whether the device has a sensor is not established either way"
                },
            );
            push_opt(
                out,
                format!("{base}.smart.passed"),
                s.passed.map(|v| serde_json::json!(v)),
                None,
                concat!(
                    "the drive's own verdict was not obtained: neither the NVMe ",
                    "critical warning bits nor the ATA failure prediction was ",
                    "readable, and this field is not a judgement computed from ",
                    "the counters"
                ),
            );
            push_opt(
                out,
                format!("{base}.smart.power_on_hours"),
                s.power_on_hours.map(|v| serde_json::json!(v)),
                Some(Unit::Hours),
                &counter_absent("power-on hour count"),
            );
            push_opt(
                out,
                format!("{base}.smart.power_cycles"),
                s.power_cycle_count.map(|v| serde_json::json!(v)),
                Some(Unit::Count),
                &counter_absent("power cycle count"),
            );
            // NVMe has no sector reallocation concept. Reporting 0 here would
            // assert a clean count that was never measured, which is exactly the
            // substitution this module exists to refuse.
            //
            // The reason said "not an NVMe concept; on ATA, the drive did not
            // report attribute 5" for every drive -- a disjunction that names two
            // situations and says which applies to neither. The source says.
            let sector_absent = |attribute: u8, what: &str| -> String {
                match s.source {
                    SmartSource::NvmeLogPage => format!(
                        "not an NVMe concept: this drive answered from its NVMe \
                         SMART/Health log page, which has no {what} -- attribute \
                         {attribute} is an ATA notion and does not exist here"
                    ),
                    SmartSource::AtaAttributes => format!(
                        "the drive returned an ATA attribute table of {} attributes \
                         and none of them is {attribute} ({what})",
                        s.attributes.len()
                    ),
                    SmartSource::StorageStack => format!(
                        "no {what} was read: no ATA attribute table was obtained \
                         from this drive at all, so attribute {attribute} was \
                         neither present nor absent -- it was never looked for"
                    ),
                }
            };
            push_opt(
                out,
                format!("{base}.smart.reallocated_sectors"),
                s.reallocated_sectors.map(|v| serde_json::json!(v)),
                Some(Unit::Count),
                &sector_absent(5, "reallocated sector count"),
            );
            push_opt(
                out,
                format!("{base}.smart.pending_sectors"),
                s.pending_sectors.map(|v| serde_json::json!(v)),
                Some(Unit::Count),
                &sector_absent(197, "pending sector count"),
            );
            push_opt(
                out,
                format!("{base}.smart.uncorrectable_sectors"),
                s.uncorrectable_sectors.map(|v| serde_json::json!(v)),
                Some(Unit::Count),
                &counter_absent("uncorrectable sector count"),
            );
        }
        Err(e) => {
            // On Windows this is the unelevated case for devices that reach the
            // WMI fallback, and the error says so. Naming the reason is the whole
            // point: a caller can tell "needs elevation" from "no such sensor".
            for suffix in SMART_FIELDS {
                out.push(Reading::unavailable(
                    format!("{base}.{suffix}"),
                    None,
                    format!("SMART read failed: {e}"),
                ));
            }
        }
    }

    const NVME_FIELDS: [&str; 6] = [
        "nvme.version",
        "nvme.percentage_used",
        "nvme.data_units_written",
        "nvme.data_units_read",
        "nvme.power_state",
        "nvme.critical_warnings",
    ];

    match disk.nvme_info() {
        Ok(n) => {
            push_opt(
                out,
                format!("{base}.nvme.version"),
                n.nvme_version.as_ref().map(|v| serde_json::json!(v)),
                Some(Unit::Text),
                "the controller did not report a specification version",
            );
            push_opt(
                out,
                format!("{base}.nvme.percentage_used"),
                n.percentage_used.map(|v| serde_json::json!(v)),
                Some(Unit::Percent),
                "the controller did not report a wear figure",
            );
            push_opt(
                out,
                format!("{base}.nvme.data_units_written"),
                n.data_units_written.map(|v| serde_json::json!(v)),
                Some(Unit::Count),
                "the controller did not report a written data unit count",
            );
            push_opt(
                out,
                format!("{base}.nvme.data_units_read"),
                n.data_units_read.map(|v| serde_json::json!(v)),
                Some(Unit::Count),
                "the controller did not report a read data unit count",
            );
            push_opt(
                out,
                format!("{base}.nvme.power_state"),
                n.power_state.map(|v| serde_json::json!(v)),
                Some(Unit::Count),
                "the controller does not implement Get Features for power management",
            );
            push_opt(
                out,
                format!("{base}.nvme.critical_warnings"),
                n.critical_warnings.map(|v| serde_json::json!(v)),
                Some(Unit::Count),
                "the controller did not serve the SMART/Health log page",
            );
        }
        Err(e) => {
            // `NotSupported` here is the device declining the NVMe protocol, which
            // is how a SATA or USB device answers. That is a fact about the device,
            // not a failure of the query, and the note says which.
            for suffix in NVME_FIELDS {
                out.push(Reading::unavailable(
                    format!("{base}.{suffix}"),
                    None,
                    format!("no NVMe controller data: {e}"),
                ));
            }
        }
    }
}

fn resolve_network(out: &mut Vec<Reading>) {
    let mut monitor = match crate::network_monitor::NetworkMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            out.push(Reading::unavailable(
                "network.<none>",
                None,
                format!("network monitor unavailable: {e}"),
            ));
            return;
        }
    };
    let interfaces = match monitor.interfaces() {
        Ok(i) => i,
        Err(e) => {
            out.push(Reading::unavailable(
                "network.<none>",
                None,
                format!("interface enumeration failed: {e}"),
            ));
            return;
        }
    };
    if interfaces.is_empty() {
        out.push(Reading::unavailable(
            "network.<none>",
            None,
            "no network interfaces enumerated",
        ));
        return;
    }

    for iface in &interfaces {
        let base = format!("network.{}", id_segment(&iface.name));

        out.push(Reading::measured(
            format!("{base}.rx_bytes"),
            serde_json::json!(iface.rx_bytes),
            Some(Unit::Bytes),
        ));
        out.push(Reading::measured(
            format!("{base}.tx_bytes"),
            serde_json::json!(iface.tx_bytes),
            Some(Unit::Bytes),
        ));

        // The counters above are cumulative. Reporting them as a rate would be the
        // same category of error as calling a spec constant a measurement.
        for dir in ["rx", "tx"] {
            out.push(Reading::unavailable(
                format!("{base}.{dir}_rate"),
                Some(Unit::BytesPerSecond),
                "a rate needs two samples; this query took one — differentiate \
                 rx_bytes/tx_bytes across two snapshots",
            ));
        }

        push_opt(
            out,
            format!("{base}.link_speed"),
            iface.speed_mbps.map(|s| serde_json::json!(s)),
            Some(Unit::Count),
            "driver reports no negotiated link rate for this interface",
        );
    }
}

fn resolve_process(out: &mut Vec<Reading>) {
    let mut monitor = match crate::process_monitor::ProcessMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            out.push(Reading::unavailable(
                "process.<none>",
                None,
                format!("process monitor unavailable: {e}"),
            ));
            return;
        }
    };
    // Two samples, so `cpu` is what its entity says: the share over an
    // interval. One sample from a fresh monitor gave each process's lifetime
    // average instead -- CPU time since it started, over how long it has run --
    // published as a measurement of now. A process started days ago and busy
    // for the last minute read as idle.
    if let Err(e) = monitor.sample_cpu_times() {
        out.push(Reading::unavailable(
            "process.<none>",
            None,
            format!("process enumeration failed: {e}"),
        ));
        return;
    }
    std::thread::sleep(std::time::Duration::from_millis(PROCESS_CPU_INTERVAL_MS));
    let procs = match monitor.processes_by_memory() {
        Ok(p) => p,
        Err(e) => {
            out.push(Reading::unavailable(
                "process.<none>",
                None,
                format!("process enumeration failed: {e}"),
            ));
            return;
        }
    };
    if procs.is_empty() {
        out.push(Reading::unavailable(
            "process.<none>",
            None,
            "no processes enumerated",
        ));
        return;
    }

    let total = procs.len();
    for p in procs.iter().take(PROCESS_LIMIT) {
        let base = format!("process.{}", p.pid);
        push_text(out, format!("{base}.name"), &p.name);
        out.push(Reading::measured(
            format!("{base}.cpu"),
            serde_json::json!(p.cpu_percent),
            Some(Unit::Percent),
        ));
        out.push(Reading::measured(
            format!("{base}.memory"),
            serde_json::json!(p.memory_bytes),
            Some(Unit::Bytes),
        ));
    }

    // Announce the truncation. A capped list presented as complete would let an agent
    // conclude a process is absent when it was merely ranked eleventh.
    if total > PROCESS_LIMIT {
        out.push(Reading::unavailable(
            "process.<truncated>",
            Some(Unit::Count),
            format!(
                "{total} processes exist; this snapshot reports the {PROCESS_LIMIT} \
                 largest by memory. Absence from this list is not absence from the \
                 machine — use `ironmon cli processes` for the full table"
            ),
        ));
    }
}

fn resolve_thermal(out: &mut Vec<Reading>) {
    let temps = match crate::motherboard::get_system_temperatures() {
        Ok(t) => t,
        Err(e) => {
            out.push(Reading::unavailable(
                "thermal.<none>",
                Some(Unit::Celsius),
                format!("temperature read failed: {e}"),
            ));
            return;
        }
    };

    for (name, value) in [
        ("cpu", temps.cpu),
        ("gpu", temps.gpu),
        ("motherboard", temps.motherboard),
    ] {
        match value {
            Some(v) => out.push(Reading::measured(
                format!("thermal.{name}.temperature"),
                serde_json::json!(v),
                Some(Unit::Celsius),
            )),
            None => out.push(Reading::unavailable(
                format!("thermal.{name}.temperature"),
                Some(Unit::Celsius),
                "no sensor exposed for this component — on Windows most board \
                 sensors require a signed kernel driver, and a virtual machine \
                 usually exposes none at all",
            )),
        }
    }

    for (device, value) in temps.storage.iter().chain(temps.network.iter()) {
        out.push(Reading::measured(
            format!("thermal.{}.temperature", id_segment(device)),
            serde_json::json!(value),
            Some(Unit::Celsius),
        ));
    }

    // There is deliberately no `thermal.<none>` row when every sensor comes back
    // empty. `<none>` means the domain enumerated nothing, and this resolver always
    // enumerates cpu, gpu and motherboard — it emits an `unavailable` row for each,
    // which states the same fact per component and more precisely. Emitting both
    // produced a snapshot that said "the domain enumerated nothing" beside three
    // thermal rows. It only showed up on a machine where no sensor reads at all,
    // which is why the first macOS CI run found it and no Windows run ever did.
    //
    // The read-failure path above still emits `<none>`, and correctly: it returns
    // before pushing anything, so nothing contradicts it.
}

/// Attached displays.
fn resolve_displays(out: &mut Vec<Reading>) {
    let monitor = match crate::display::DisplayMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            out.push(Reading::unavailable(
                "board.display.<none>",
                None,
                format!("display enumeration failed: {e}"),
            ));
            return;
        }
    };

    let displays = monitor.displays();
    if displays.is_empty() {
        out.push(Reading::unavailable(
            "board.display.<none>",
            None,
            concat!(
                "no display is attached, or none is visible to this session — a ",
                "headless server and a locked-down service account both look like this",
            ),
        ));
        return;
    }

    for (i, d) in displays.iter().enumerate() {
        let base = format!("board.display.{i}");
        push_opt(
            out,
            format!("{base}.name"),
            d.name.as_ref().map(|n| serde_json::json!(n)),
            Some(Unit::Text),
            "this display publishes no name",
        );
        push_id(
            out,
            format!("{base}.connection"),
            &format!("{:?}", d.connection).to_lowercase(),
        );
        // A display is not zero pixels wide. This used to filter `> 0` because
        // the reader wrote zeros for a monitor whose mode it could not read;
        // the fields are `Option` now, so the absence arrives here intact
        // instead of being reconstructed from a sentinel. The zero guard stays
        // because a reader could still produce one, and it would mean the same
        // thing.
        const NOT_A_MODE: &str = "the display is attached and its current mode was not readable; zero is not a resolution";
        push_opt(
            out,
            format!("{base}.width"),
            d.width.filter(|w| *w > 0).map(|w| serde_json::json!(w)),
            Some(Unit::Count),
            NOT_A_MODE,
        );
        push_opt(
            out,
            format!("{base}.height"),
            d.height.filter(|h| *h > 0).map(|h| serde_json::json!(h)),
            Some(Unit::Count),
            NOT_A_MODE,
        );
        push_opt(
            out,
            format!("{base}.refresh_rate"),
            d.refresh_rate
                .filter(|r| *r > 0.0)
                .map(|r| serde_json::json!(r)),
            Some(Unit::Hertz),
            NOT_A_MODE,
        );
        out.push(Reading::measured(
            format!("{base}.primary"),
            serde_json::json!(d.is_primary),
            None,
        ));
    }
}

/// Platform sensor devices — ambient light, accelerometer, orientation.
///
/// Not the board temperature sensors, which resolve under `thermal`. A desktop
/// reporting none is the common case and a true reading, so the diagnostic
/// distinguishes that from a query that could not be made at all.
fn resolve_sensors(out: &mut Vec<Reading>) {
    let monitor = match crate::sensors::SensorMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            out.push(Reading::unavailable(
                "board.sensor.<none>",
                None,
                format!("sensor enumeration failed: {e}"),
            ));
            return;
        }
    };

    let items = monitor.sensors();
    if items.is_empty() {
        out.push(Reading::unavailable(
            "board.sensor.<none>",
            None,
            match monitor.note() {
                Some(why) => why.to_string(),
                // No note and no items: the enumeration ran and this machine has
                // none, which is the ordinary case on a desktop.
                None => "the platform enumerated no sensors on this machine".to_string(),
            },
        ));
        return;
    }

    for (i, sensor) in items.iter().enumerate() {
        let base = format!("board.sensor.{i}");
        push_text(out, format!("{base}.name"), &sensor.name);
        push_id(
            out,
            format!("{base}.type"),
            &format!("{:?}", sensor.sensor_type).to_lowercase(),
        );
        out.push(Reading::measured(
            format!("{base}.active"),
            serde_json::json!(sensor.active),
            None,
        ));
    }
}

/// Whether a string is a PCI address in either of the two forms that appear.
///
/// Domain-qualified `0000:03:00.0` and the bare `03:00.0` are both accepted;
/// anything else -- a Windows device instance path, a SCSI target triple, an
/// empty string -- is not. The check is deliberately shallow: it exists to stop
/// a value being published under a name that promises a PCI bus when it names
/// something else, not to validate that the address points at a real device.
fn looks_like_pci_address(value: &str) -> bool {
    let value = value.trim();
    let (bus_dev, function) = match value.rsplit_once('.') {
        Some(parts) => parts,
        None => return false,
    };
    if function.is_empty() || !function.chars().all(|c| c.is_ascii_hexdigit()) {
        return false;
    }
    let fields: Vec<&str> = bus_dev.split(':').collect();
    if !matches!(fields.len(), 2 | 3) {
        return false;
    }
    fields
        .iter()
        .all(|f| !f.is_empty() && f.chars().all(|c| c.is_ascii_hexdigit()))
}

/// The controllers the disks are attached to.
fn resolve_storage_controllers(out: &mut Vec<Reading>) {
    let monitor = match crate::storage_controller::StorageControllerMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            out.push(Reading::unavailable(
                "disk.controller.<none>",
                None,
                format!("storage controllers could not be enumerated here: {e}"),
            ));
            return;
        }
    };

    let controllers = monitor.controllers();
    if controllers.is_empty() {
        out.push(Reading::unavailable(
            "disk.controller.<none>",
            None,
            "controller enumeration succeeded and found none, which on a machine with \
             disks means the enumeration is incomplete rather than that the disks are \
             attached to nothing",
        ));
        return;
    }

    for (i, c) in controllers.iter().enumerate() {
        let base = format!("disk.controller.{i}");
        push_text(out, format!("{base}.name"), &c.name);
        push_text(out, format!("{base}.vendor"), &c.vendor);
        push_text(out, format!("{base}.model"), &c.model);
        push_id(out, format!("{base}.driver"), &c.driver);
        push_id(
            out,
            format!("{base}.interface"),
            &format!("{:?}", c.interface),
        );
        // Windows fills this field with a device instance path --
        // `ROOT\\SPACEPORT\\0000` for a Storage Spaces controller -- which is
        // not a PCI address and cannot be joined against `pci.*`. Publishing it
        // under a name that says PCI would send a consumer looking for a link
        // width to a bus the device is not on. Only a value that looks like one
        // is published as one, and the rest arrive as an absence naming what
        // was actually found.
        push_opt(
            out,
            format!("{base}.pci_address"),
            looks_like_pci_address(&c.pci_address).then(|| serde_json::json!(c.pci_address)),
            Some(Unit::Identifier),
            if c.pci_address.trim().is_empty() {
                "this controller reports no bus address".to_string()
            } else {
                format!(
                    "the platform reports `{}` for this controller, which is not a PCI \
                     address and cannot be joined against `pci.*`",
                    c.pci_address.trim()
                )
            }
            .as_str(),
        );
        push_opt(
            out,
            format!("{base}.ports"),
            (c.ports > 0).then(|| serde_json::json!(c.ports)),
            Some(Unit::Count),
            "this controller reports no port count",
        );
    }
}

/// The current value of every setting this build can write.
///
/// `EntityKind::Setting` entities are generated from the apply-handler registry,
/// and nothing read them: `cpu.setting.active_scheme_guid` was published as "no
/// resolver bound on this build — the entity is defined but IronMonitor does not yet
/// read it here" **while `ironmon profile explain active_scheme_guid` printed the
/// GUID from `profile::cpu` in the same binary**. Two surfaces over one machine,
/// disagreeing about whether the machine could be read at all.
///
/// `read_current` is the same call `ApplyHandler` uses to record what a write
/// overwrote, through the same retry that keeps a transient failure from being
/// mistaken for an unreadable setting. A handler that does not implement it is
/// one-way by construction — it can change the machine and cannot say what the
/// machine currently says — and that is what the absence reports.
fn resolve_settings(out: &mut Vec<Reading>) {
    for handler in crate::profile::apply::builtin_handlers() {
        let id = format!(
            "{}.setting.{}",
            super::setting_domain(handler.subsystem()).as_str(),
            handler.setting_id()
        );
        match crate::profile::apply::read_current_with_retry(handler.as_ref()) {
            // `Unreadable` carries its own reason and is not a value: rendering
            // it would publish the string "<unreadable: ...>" as the setting.
            Some(crate::profile::SettingValue::Unreadable(why)) => out.push(Reading::unavailable(
                id,
                Some(Unit::Identifier),
                format!("the handler for this setting reported it unreadable: {why}"),
            )),
            Some(value) => {
                // Every setting entity is declared `Unit::Identifier`, because a
                // setting's value space is its own -- a governor name, a GUID, a
                // frequency. The rendering here is exact for each variant;
                // `Display` is not used, because it decorates a `Uint` with its
                // hex form, and "3 (0x3)" is a label rather than a value.
                use crate::profile::SettingValue as V;
                let text = match &value {
                    V::Bool(b) => b.to_string(),
                    V::Int(i) => i.to_string(),
                    V::Uint(u) => u.to_string(),
                    V::Float(x) => x.to_string(),
                    V::Text(s) | V::Hex(s) => s.clone(),
                    V::Unreadable(_) => unreachable!("handled above"),
                };
                push_id(out, id, &text);
            }
            None => out.push(Reading::unavailable(
                id,
                Some(Unit::Identifier),
                concat!(
                    "this setting has a write handler and no reader: the handler ",
                    "implements no `read_current`, so IronMonitor can change it and ",
                    "cannot say what it currently holds. That also makes the ",
                    "write one-way -- `revert_setting` refuses rather than ",
                    "writing a default it never read"
                ),
            )),
        }
    }
}

/// Operating system power plans, and which one is in force.
fn resolve_power_profiles(out: &mut Vec<Reading>) {
    let monitor = match crate::power_profile::PowerProfileMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            out.push(Reading::unavailable(
                "power.profile.<none>",
                None,
                format!("power plans could not be enumerated here: {e}"),
            ));
            return;
        }
    };

    let plans = monitor.power_plans();
    if plans.is_empty() {
        out.push(Reading::unavailable(
            "power.profile.<none>",
            None,
            "no power plan was enumerated; this platform may manage power without \
             presenting named plans",
        ));
        return;
    }

    for (i, p) in plans.iter().enumerate() {
        let base = format!("power.profile.{i}");
        push_text(out, format!("{base}.name"), &p.name);
        out.push(Reading::measured(
            format!("{base}.active"),
            serde_json::json!(p.active),
            None,
        ));
    }
}

/// Hardware video encode and decode, each row carrying how it was learned.
///
/// The reader distinguishes a capability it asked the driver about from one it
/// concluded from the GPU model, and that distinction survives into the
/// provenance of every reading below. It is the one place in this module where
/// the provenance is chosen per row rather than per entity, and it is the
/// clearest illustration of why the field exists: an inferred AV1 encode
/// capability and a queried one look identical until you ask where each came
/// from, and only one of them will still be true after a driver update.
fn resolve_codecs(out: &mut Vec<Reading>) {
    use crate::codec::{BitDepth, CapabilitySource, MaxResolution};

    let monitor = match crate::codec::CodecMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            out.push(Reading::unavailable(
                "gpu.codec.<none>",
                None,
                format!("hardware codec support could not be determined here: {e}"),
            ));
            return;
        }
    };

    let caps = monitor.capabilities();
    if caps.is_empty() {
        out.push(Reading::unavailable(
            "gpu.codec.<none>",
            None,
            "no hardware codec capability was found; the GPU may have no media engine",
        ));
        return;
    }

    for (i, c) in caps.iter().enumerate() {
        let base = format!("gpu.codec.{i}");
        let queried = c.source == CapabilitySource::DirectQuery;

        // Every identity field on this row is exactly as good as the row's
        // source. Pushing them all as measured would have hidden that behind a
        // `confidence` number a consumer has to remember to read.
        let push_str = |out: &mut Vec<Reading>, id: String, v: &str| {
            if queried {
                push_id(out, id, v);
            } else {
                push_spec_id(out, id, v);
            }
        };

        if queried {
            push_text(out, format!("{base}.device"), &c.device);
        } else {
            push_spec_text(out, format!("{base}.device"), &c.device);
        }
        push_str(out, format!("{base}.codec"), &format!("{:?}", c.codec));
        push_str(
            out,
            format!("{base}.direction"),
            &format!("{:?}", c.direction),
        );
        push_str(out, format!("{base}.engine"), &c.engine);
        push_str(
            out,
            format!("{base}.max_resolution"),
            &format!("{:?}", c.max_resolution),
        );

        // Pixel dimensions for the frame class. A table, and declared as one:
        // the class is what the reader knows, and these two are what a consumer
        // sizing a buffer actually needs.
        let pixels = match c.max_resolution {
            MaxResolution::SD => Some((720, 480)),
            MaxResolution::HD => Some((1280, 720)),
            MaxResolution::FullHD => Some((1920, 1080)),
            MaxResolution::QHD => Some((2560, 1440)),
            MaxResolution::UHD4K => Some((3840, 2160)),
            MaxResolution::UHD8K => Some((7680, 4320)),
            MaxResolution::Unknown => None,
        };
        match pixels {
            Some((w, h)) => {
                out.push(Reading::derived(
                    format!("{base}.max_width"),
                    serde_json::json!(w),
                    Some(Unit::Count),
                ));
                out.push(Reading::derived(
                    format!("{base}.max_height"),
                    serde_json::json!(h),
                    Some(Unit::Count),
                ));
            }
            None => {
                for suffix in ["max_width", "max_height"] {
                    out.push(Reading::unavailable(
                        format!("{base}.{suffix}"),
                        Some(Unit::Count),
                        "the engine reports no frame class, so no dimensions follow from it",
                    ));
                }
            }
        }

        let depth = match c.max_bit_depth {
            BitDepth::Bit8 => Some(8),
            BitDepth::Bit10 => Some(10),
            BitDepth::Bit12 => Some(12),
            BitDepth::Unknown => None,
        };
        match depth {
            Some(d) if queried => out.push(Reading::measured(
                format!("{base}.max_bit_depth"),
                serde_json::json!(d),
                Some(Unit::Count),
            )),
            Some(d) => out.push(Reading::spec(
                format!("{base}.max_bit_depth"),
                serde_json::json!(d),
                Some(Unit::Count),
            )),
            None => out.push(Reading::unavailable(
                format!("{base}.max_bit_depth"),
                Some(Unit::Count),
                "the engine reports no bit depth",
            )),
        }

        // The comment that used to sit here said this figure was "arithmetic
        // over the engine generation". There was no arithmetic: `max_fps` was
        // the literal 60 at every construction site, so the `0 =>` arm that
        // guarded it was unreachable and the entity's declared derivation from
        // `codec` and `max_resolution` described a computation that did not
        // exist. Nothing fills the field now, and the entity is declared
        // `Unavailable` to match; a reader that learns a real frame rate has to
        // re-declare it, with the inputs it actually consumes.
        push_opt(
            out,
            format!("{base}.max_fps"),
            c.max_fps.map(|fps| serde_json::json!(fps)),
            Some(Unit::Count),
            "no driver reports a frame rate and this crate does not estimate one",
        );
        // The reader's confidence is a 0.0-1.0 fraction and the entity declares
        // a percentage, so it is scaled here rather than at the consumer, where
        // a 1.0 would read as one percent.
        out.push(Reading::derived(
            format!("{base}.confidence"),
            serde_json::json!(c.confidence * 100.0),
            Some(Unit::Percent),
        ));
    }
}

/// Keyboards, pointing devices and controllers, as attached right now.
fn resolve_input(out: &mut Vec<Reading>) {
    let monitor = match crate::input::InputMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            out.push(Reading::unavailable(
                "board.input.<none>",
                None,
                format!("input devices could not be enumerated here: {e}"),
            ));
            return;
        }
    };

    let devices = monitor.devices();
    if devices.is_empty() {
        out.push(Reading::unavailable(
            "board.input.<none>",
            None,
            "input enumeration succeeded and found no device, which is ordinary on a \
             headless machine",
        ));
        return;
    }

    for (i, d) in devices.iter().enumerate() {
        let base = format!("board.input.{i}");
        push_text(out, format!("{base}.name"), &d.name);
        push_id(out, format!("{base}.type"), &format!("{:?}", d.device_type));
        push_id(
            out,
            format!("{base}.interface"),
            &format!("{:?}", d.interface),
        );
        push_text(out, format!("{base}.vendor"), &d.vendor);
        push_text(out, format!("{base}.product"), &d.product);
        push_opt(
            out,
            format!("{base}.active"),
            d.is_active.map(|a| serde_json::json!(a)),
            None,
            "the platform did not report whether this device is connected and usable",
        );
    }
}

/// Audio endpoints, in whichever direction they carry sound.
fn resolve_audio(out: &mut Vec<Reading>) {
    let monitor = match crate::audio::AudioMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            out.push(Reading::unavailable(
                "board.audio.<none>",
                None,
                format!("audio endpoints could not be enumerated here: {e}"),
            ));
            return;
        }
    };

    let devices = monitor.devices();
    if devices.is_empty() {
        out.push(Reading::unavailable(
            "board.audio.<none>",
            None,
            "audio enumeration succeeded and found no endpoint",
        ));
        return;
    }

    for (i, d) in devices.iter().enumerate() {
        let base = format!("board.audio.{i}");
        push_text(out, format!("{base}.name"), &d.name);
        push_id(
            out,
            format!("{base}.direction"),
            &format!("{:?}", d.device_type),
        );
        push_opt(
            out,
            format!("{base}.state"),
            d.state
                .map(|s| serde_json::json!(format!("{s:?}").to_lowercase())),
            Some(Unit::Identifier),
            "the platform did not report an endpoint state for this device",
        );
        push_opt(
            out,
            format!("{base}.default"),
            d.is_default.map(|v| serde_json::json!(v)),
            None,
            concat!(
                "which endpoint the system routes to by default is a COM call ",
                "this crate does not make; it was previously whichever row the ",
                "enumeration returned first"
            ),
        );
        // Neither of these is read on any platform yet. The volume row already
        // said so; the mute row published a constant `false` as `measured`,
        // and the conformance suite caught it the moment the field could
        // express an absence.
        const NO_MIXER: &str =
            "IronMonitor has no mixer binding on this platform, so no level is read from this endpoint";
        push_opt(
            out,
            format!("{base}.volume"),
            d.volume.map(|v| serde_json::json!(v)),
            Some(Unit::Percent),
            NO_MIXER,
        );
        push_opt(
            out,
            format!("{base}.muted"),
            d.muted.map(|m| serde_json::json!(m)),
            None,
            NO_MIXER,
        );
    }
}

/// Cameras, and whether any of them is streaming.
fn resolve_cameras(out: &mut Vec<Reading>) {
    let monitor = match crate::camera::CameraMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            out.push(Reading::unavailable(
                "board.camera.<none>",
                None,
                format!("cameras could not be enumerated here: {e}"),
            ));
            return;
        }
    };

    let cameras = monitor.cameras();
    if cameras.is_empty() {
        out.push(Reading::unavailable(
            "board.camera.<none>",
            None,
            "camera enumeration succeeded and found no device",
        ));
        return;
    }

    for (i, c) in cameras.iter().enumerate() {
        let base = format!("board.camera.{i}");
        push_text(out, format!("{base}.name"), &c.name);
        push_id(
            out,
            format!("{base}.connection"),
            &format!("{:?}", c.connection),
        );
        push_id(out, format!("{base}.driver"), &c.driver);
        // Zero pixels is not a frame size, so it is reported absent -- but the
        // reason used to say "this camera reports no supported mode list",
        // which is a claim about the device, and no reader on any platform has
        // ever asked it. The Linux path carries the comment "would need v4l2
        // ioctl", Windows and macOS fill zero without comment, and the
        // ontology attributed all three silences to the camera.
        const NO_MODE_LIST: &str = concat!(
            "no reader asks this camera for its mode list on any platform: the ",
            "Linux path would need the VIDIOC_ENUM_FRAMESIZES ioctl and the ",
            "Windows path the Media Foundation frame-size attribute, and ",
            "neither is implemented. This is ironmon not looking, not a camera ",
            "that answered with nothing"
        );
        push_opt(
            out,
            format!("{base}.max_width"),
            (c.max_width > 0).then(|| serde_json::json!(c.max_width)),
            Some(Unit::Count),
            NO_MODE_LIST,
        );
        push_opt(
            out,
            format!("{base}.max_height"),
            (c.max_height > 0).then(|| serde_json::json!(c.max_height)),
            Some(Unit::Count),
            NO_MODE_LIST,
        );
        push_opt(
            out,
            format!("{base}.active"),
            c.is_active.map(|a| serde_json::json!(a)),
            None,
            concat!(
                "whether this camera is streaming was not established: only ",
                "Linux probes the device node, and the Windows consent store ",
                "attributes use to an application rather than to a device"
            ),
        );
    }
}

/// How long the machine took to boot, when the platform measured it.
///
/// Bound late: the entity was declared and nothing resolved it, so it read "no
/// resolver bound on this build" — which was the wrong absence. The entity is
/// supported on Windows; what stops it here is privilege, and saying so is a
/// different fact than saying IronMonitor has not implemented it.
///
/// `BootMonitor` leaves `total` at `Duration::ZERO` when nothing was measured,
/// so zero is the sentinel and must not be published as a boot that took no
/// time. The reason given for the absence is platform-specific because the
/// reasons genuinely differ: Windows keeps the only real measurement in a log
/// that needs Administrator, while elsewhere it comes from `systemd-analyze`,
/// which is simply absent on a machine without systemd.
fn resolve_boot_duration(out: &mut Vec<Reading>) {
    // Only the timing: a full `BootMonitor` also enumerates the boot
    // configuration and startup items, none of which this entity uses.
    let boot_time = match crate::boot_config::BootMonitor::read_boot_time() {
        Ok(t) => t,
        Err(e) => {
            out.push(Reading::unavailable(
                "system.boot.duration",
                Some(Unit::Seconds),
                format!("the boot timing could not be read: {e}"),
            ));
            return;
        }
    };

    let secs = boot_time.total.as_secs_f64();
    if secs > 0.0 {
        out.push(Reading::measured(
            "system.boot.duration",
            serde_json::json!(secs),
            Some(Unit::Seconds),
        ));
        return;
    }

    #[cfg(target_os = "windows")]
    let reason = concat!(
        "Windows records a boot duration only in ",
        "Microsoft-Windows-Diagnostics-Performance/Operational event 100, which ",
        "is not readable without Administrator — this is a privilege ",
        "boundary, not a missing reader",
    );
    #[cfg(target_os = "linux")]
    let reason = concat!(
        "`systemd-analyze` reported no total, which is what a machine without ",
        "systemd or with an incomplete boot transaction looks like",
    );
    #[cfg(not(any(target_os = "windows", target_os = "linux")))]
    let reason = "this platform publishes no boot duration IronMonitor knows how to read";

    out.push(Reading::unavailable(
        "system.boot.duration",
        Some(Unit::Seconds),
        reason,
    ));
}

/// Whether Secure Boot is enforcing, from the firmware flag.
///
/// The entity has been declared since the boot cluster was written and nothing
/// resolved it, so it fell to the unbound-id sweep and reported "no resolver
/// bound on this build" — on a machine where the flag is perfectly readable.
///
/// Two readers hold this and only one is honest. `boot_config` keeps it in a
/// `bool` and collapses a failed query with `unwrap_or(false)`, which reports
/// Secure Boot as *disabled* when it could not be read. `firmware` models it as
/// `SecureBootStatus`, which separates `Disabled` from `NotSupported` from
/// `Unknown`. That distinction is the whole reading, so `boot_config` is not
/// used here: off, unsupported and unread are three different answers and only
/// one of them is `false`.
fn resolve_secure_boot(out: &mut Vec<Reading>) {
    // Windows first, and unelevated. `firmware` asks `Confirm-SecureBootUEFI`,
    // which needs Administrator and so returns `Unknown` in normal use — this
    // machine reported "the firmware flag was not readable here" while the flag
    // sat in the registry the whole time. `SecureBoot\State\UEFISecureBootEnabled`
    // is readable without elevation and `secure_boot_enabled` already returns an
    // `Option`, so the absence survives.
    //
    // Same shape as the NVMe and ATA capabilities: both were scoped as needing
    // Administrator on a second reading and turned out not to. Check for an
    // unelevated source before accepting that a reading needs privilege.
    #[cfg(target_os = "windows")]
    {
        match crate::platform::windows::secure_boot_enabled() {
            Some(on) => {
                out.push(Reading::measured(
                    "system.boot.secure_boot",
                    serde_json::json!(on),
                    None,
                ));
            }
            None => {
                out.push(Reading::unavailable(
                    "system.boot.secure_boot",
                    None,
                    "the SecureBoot state key is absent, which is what a BIOS/CSM \
                     machine looks like — it is not the same as Secure Boot being \
                     turned off",
                ));
            }
        }
    }

    #[cfg(not(target_os = "windows"))]
    {
        resolve_secure_boot_from_firmware(out);
    }
}

/// The non-Windows arm, split out so the `cfg` above stays readable.
#[cfg(not(target_os = "windows"))]
fn resolve_secure_boot_from_firmware(out: &mut Vec<Reading>) {
    use crate::firmware::SecureBootStatus;

    // Only the flag: the full inventory also runs `fwupdmgr`, which cost this
    // entity 25 s on a machine without a reachable fwupd daemon.
    let status = match crate::firmware::FirmwareInventory::read_secure_boot() {
        Ok(s) => s,
        Err(e) => {
            out.push(Reading::unavailable(
                "system.boot.secure_boot",
                None,
                format!("the firmware inventory could not be read: {e}"),
            ));
            return;
        }
    };

    match status {
        SecureBootStatus::Enabled => out.push(Reading::measured(
            "system.boot.secure_boot",
            serde_json::json!(true),
            None,
        )),
        SecureBootStatus::Disabled => out.push(Reading::measured(
            "system.boot.secure_boot",
            serde_json::json!(false),
            None,
        )),
        // Not the same as `false`. A firmware without Secure Boot cannot have it
        // turned off, and an agent auditing posture needs to tell "off" from
        // "unavailable on this hardware" before recommending anything.
        SecureBootStatus::NotSupported => out.push(Reading::unavailable(
            "system.boot.secure_boot",
            None,
            "this firmware does not implement Secure Boot, which is not the same \
             as having it disabled",
        )),
        SecureBootStatus::Unknown => out.push(Reading::unavailable(
            "system.boot.secure_boot",
            None,
            "the firmware flag was not readable here",
        )),
    }
}

/// Kernel parameters: what the platform reported, and none of what this crate
/// thinks about it.
///
/// The reader also computes `is_recommended`, `recommended`, `security_score`,
/// `network_score` and a list of free-text recommendations. Those are opinions
/// about what a value ought to be, and `ironmon tune`'s standing rule is that a
/// proposed value comes from what the system declared and never from this crate.
/// A score published beside a measured value borrows its authority, so the split
/// is here rather than a subset of the fields being passed through.
fn resolve_kernel_params(out: &mut Vec<Reading>) {
    let monitor = match crate::kernel_params::KernelParamsMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            out.push(Reading::unavailable(
                "system.kernel_param.<none>",
                None,
                format!("kernel parameters could not be read here: {e}"),
            ));
            return;
        }
    };

    let params = &monitor.report().params;
    if params.is_empty() {
        out.push(Reading::unavailable(
            "system.kernel_param.<none>",
            None,
            "no kernel parameter was readable here; on Windows the reader knows \
             one setting and reports nothing when the query returns empty",
        ));
        return;
    }

    for (i, p) in params.iter().enumerate() {
        let base = format!("system.kernel_param.{i}");
        push_id(out, format!("{base}.name"), &p.name);
        push_id(out, format!("{base}.value"), &p.value);
        push_id(
            out,
            format!("{base}.category"),
            &format!("{:?}", p.category),
        );
    }
}

/// Services, as counts plus the names of the broken ones.
///
/// Deliberately not one entity per service. This machine runs 311, and
/// enumerating them would more than double every snapshot to carry a list no
/// consumer reads in full. The question being answered is "is anything broken,
/// and what" — so failures are named and the rest are counted.
fn resolve_services(out: &mut Vec<Reading>) {
    let monitor = match crate::services::ServiceMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            out.push(Reading::unavailable(
                "system.service.<none>",
                None,
                format!("the service manager could not be reached: {e}"),
            ));
            return;
        }
    };

    let services = monitor.services();
    if services.is_empty() {
        out.push(Reading::unavailable(
            "system.service.<none>",
            None,
            "the service manager was reached and reported no services, which on \
             a running machine means the enumeration is incomplete rather than \
             that nothing is installed",
        ));
        return;
    }

    let running = services.iter().filter(|s| s.is_active()).count();
    let failed: Vec<&str> = services
        .iter()
        .filter(|s| s.is_failed())
        .map(|s| s.name.as_str())
        .collect();

    for (id, n) in [
        ("system.service.count.total", services.len()),
        ("system.service.count.running", running),
        ("system.service.count.failed", failed.len()),
    ] {
        out.push(Reading::measured(
            id,
            serde_json::json!(n),
            Some(Unit::Count),
        ));
    }

    // Nothing is pushed when nothing has failed. The count above already says
    // zero, and a `<none>` here would claim the enumeration failed.
    for (i, name) in failed.iter().enumerate() {
        push_id(out, format!("system.service.failed.{i}"), name);
    }
}

/// Print queues the spooler knows about.
fn resolve_printers(out: &mut Vec<Reading>) {
    let monitor = match crate::printer::PrinterMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            out.push(Reading::unavailable(
                "system.printer.<none>",
                None,
                format!("printers could not be enumerated here: {e}"),
            ));
            return;
        }
    };

    let printers = monitor.printers();
    if printers.is_empty() {
        out.push(Reading::unavailable(
            "system.printer.<none>",
            None,
            "the spooler was reachable and holds no queue",
        ));
        return;
    }

    for (i, p) in printers.iter().enumerate() {
        let base = format!("system.printer.{i}");
        push_text(out, format!("{base}.name"), &p.name);
        push_text(out, format!("{base}.description"), &p.description);
        push_id(
            out,
            format!("{base}.connection"),
            &format!("{:?}", p.connection),
        );
        // `PrinterStatus::Unknown` renders as "unknown", which `push_id` turns
        // into an absence with a reason. That is the right outcome and it is
        // why the status goes through the guarded helper rather than being
        // pushed directly.
        push_id(out, format!("{base}.status"), &format!("{:?}", p.status));
        out.push(Reading::measured(
            format!("{base}.default"),
            serde_json::json!(p.is_default),
            None,
        ));
        push_opt(
            out,
            format!("{base}.accepting_jobs"),
            p.accepting_jobs.map(|a| serde_json::json!(a)),
            None,
            concat!(
                "whether the queue takes new work is reported by CUPS and has ",
                "no equivalent in Win32_Printer; deriving it from the printer ",
                "status is the one thing this field exists not to do"
            ),
        );
        push_opt(
            out,
            format!("{base}.color"),
            p.color.map(|c| serde_json::json!(c)),
            None,
            concat!(
                "the spooler listed no capabilities for this printer, so whether ",
                "it prints in colour was not reported",
            ),
        );
    }
}

/// Bluetooth adapters. Deliberately not the devices they can see.
fn resolve_bluetooth(out: &mut Vec<Reading>) {
    let monitor = match crate::bluetooth::BluetoothMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            out.push(Reading::unavailable(
                "network.bluetooth.<none>",
                None,
                format!("Bluetooth adapters could not be enumerated here: {e}"),
            ));
            return;
        }
    };

    let adapters = monitor.adapters();
    if adapters.is_empty() {
        out.push(Reading::unavailable(
            "network.bluetooth.<none>",
            None,
            "Bluetooth enumeration succeeded and found no adapter",
        ));
        return;
    }

    for (i, a) in adapters.iter().enumerate() {
        let base = format!("network.bluetooth.{i}");
        push_text(out, format!("{base}.name"), &a.name);
        push_opt(
            out,
            format!("{base}.powered"),
            a.powered.map(|p| serde_json::json!(p)),
            None,
            "the platform's adapter record carries no radio power state",
        );
    }
}

/// What the processor says about itself, and which instructions it implements.
///
/// The reader's inferred performance scores are read and discarded here. They
/// are a table lookup keyed on the microarchitecture name, and publishing one
/// through an interface whose whole promise is that a value carries its own
/// provenance would be the clearest possible violation of that promise: there
/// is no provenance to give it. `Derived` would be a lie about the inputs and
/// `Measured` a lie about the method.
fn resolve_microarch(out: &mut Vec<Reading>) {
    let monitor = match crate::cpu_microarch::CpuMicroarchMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            out.push(Reading::unavailable(
                "cpu.microarch.<none>",
                None,
                format!("the processor could not be identified here: {e}"),
            ));
            return;
        }
    };

    push_microarch(out, monitor.report());
}

/// The microarchitecture readings for one report, separate from reading it so
/// a report with unread fields can be tested.
fn push_microarch(out: &mut Vec<Reading>, report: &crate::cpu_microarch::CpuMicroarchReport) {
    let uarch = &report.microarch;

    // Field by field. An earlier version pushed `{:?}` of the whole struct,
    // which put a Rust debug rendering -- braces, quotes, `None` -- into a
    // reading declared as an identifier. It parsed as a value and was one only
    // in the sense that a screenshot of a table is a table.
    push_spec_id(out, "cpu.microarch.name", &uarch.name);
    push_spec_id(out, "cpu.microarch.codename", &uarch.codename);
    push_spec_id(out, "cpu.microarch.vendor", &format!("{:?}", uarch.vendor));
    push_spec_id(out, "cpu.microarch.isa", &uarch.arch);
    push_spec_opt(
        out,
        "cpu.microarch.process",
        (uarch.process_nm > 0).then(|| serde_json::json!(uarch.process_nm)),
        Some(Unit::Count),
        "IronMonitor holds no process node for this microarchitecture",
    );
    push_spec_opt(
        out,
        "cpu.microarch.year",
        (uarch.year > 0).then(|| serde_json::json!(uarch.year)),
        Some(Unit::Count),
        "IronMonitor holds no introduction date for this microarchitecture",
    );
    out.push(Reading::spec(
        "cpu.microarch.hybrid",
        serde_json::json!(uarch.hybrid),
        None,
    ));

    // Family zero identifies no x86 part that has ever shipped, so it means the
    // CPUID triple was not read rather than that this is family 0. When it is
    // missing the model and stepping beside it are missing too -- they are
    // decoded from the same leaf -- and stepping 0 is a legitimate value, so
    // publishing it while family is absent would present a default as a
    // reading. All three go together or none of them do.
    // `family > 0` was the proxy for "the triple was read", because the reader
    // returned zeros when it was not. The fields are `Option` now, so the
    // question is asked directly.
    let cpuid_read = report.family.is_some();
    for (suffix, value) in [
        ("family", report.family),
        ("model", report.model),
        ("stepping", report.stepping),
    ] {
        push_spec_opt(
            out,
            format!("cpu.microarch.{suffix}"),
            cpuid_read
                .then_some(value)
                .flatten()
                .map(|v| serde_json::json!(v)),
            Some(Unit::Count),
            "the CPUID family/model/stepping triple was not read on this platform",
        );
    }
    // The readers fill these with `.unwrap_or(0)`, and ARM Linux kernels
    // commonly omit the `cpu cores` line from /proc/cpuinfo. Published as-is,
    // an unread count was a specification of **zero cores**, and
    // `smt_enabled` -- computed as `threads > cores && cores > 0` -- a
    // measurement that SMT was off. A processor has at least one of each, so
    // zero is the reader's "not read".
    for (suffix, value) in [
        ("physical_cores", report.physical_cores),
        ("logical_cores", report.logical_cores),
    ] {
        push_spec_opt(
            out,
            format!("cpu.microarch.{suffix}"),
            (value > 0).then(|| serde_json::json!(value)),
            Some(Unit::Count),
            "the platform's processor description did not include this count",
        );
    }
    push_opt(
        out,
        "cpu.microarch.smt_enabled",
        (report.physical_cores > 0 && report.logical_cores > 0)
            .then(|| serde_json::json!(report.smt_enabled)),
        None,
        "SMT is judged by comparing logical to physical cores, and one of the two was not read",
    );

    // Supported only. An extension the processor does not implement is not a
    // property of this machine, and listing it with a false flag invites a
    // consumer that forgets to read the flag to conclude the opposite.
    let supported: Vec<_> = report.extensions.iter().filter(|x| x.supported).collect();
    if supported.is_empty() {
        out.push(Reading::unavailable(
            "cpu.microarch.extension.<none>",
            None,
            "the processor was identified and reported no instruction set extensions, \
             which means the extension probe failed rather than that the CPU has none",
        ));
        return;
    }
    for (i, x) in supported.iter().enumerate() {
        let base = format!("cpu.microarch.extension.{i}");
        push_spec_id(out, format!("{base}.name"), &x.name);
        push_spec_id(
            out,
            format!("{base}.category"),
            &format!("{:?}", x.category),
        );
        push_spec_text(out, format!("{base}.description"), &x.description);
    }
}

/// Hardware cryptographic acceleration and random sources.
///
/// Both lists are filtered to what is actually present, and both carry their own
/// `<none>` row. A machine with no hardware RNG is a real state an agent may
/// need to act on -- it changes how a key should be generated -- and it must not
/// be reachable by the same silence as a reader that failed.
fn resolve_crypto(out: &mut Vec<Reading>) {
    let monitor = match crate::crypto_accel::CryptoAccelMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            out.push(Reading::unavailable(
                "cpu.crypto.<none>",
                None,
                format!("hardware crypto support could not be determined here: {e}"),
            ));
            return;
        }
    };

    let report = monitor.report();

    let accelerated: Vec<_> = report
        .features
        .iter()
        .filter(|f| f.hardware_accelerated)
        .collect();
    if accelerated.is_empty() {
        out.push(Reading::unavailable(
            "cpu.crypto.<none>",
            None,
            "the processor reports no hardware-accelerated cryptographic primitive",
        ));
    }
    for (i, f) in accelerated.iter().enumerate() {
        let base = format!("cpu.crypto.feature.{i}");
        push_spec_id(out, format!("{base}.name"), &f.name);
        push_spec_id(out, format!("{base}.flag"), &f.cpu_flag);
        push_spec_id(
            out,
            format!("{base}.category"),
            &format!("{:?}", f.category),
        );
        // GB/s to bytes per second. Decimal, matching how the constants were
        // written down; and `Derived`, because a constant is not a measurement
        // however plausible the number looks.
        match f.estimated_throughput_gbs {
            Some(gbs) => out.push(Reading::derived(
                format!("{base}.throughput"),
                serde_json::json!(gbs * 1_000_000_000.0),
                Some(Unit::BytesPerSecond),
            )),
            None => out.push(Reading::unavailable(
                format!("{base}.throughput"),
                Some(Unit::BytesPerSecond),
                "IronMonitor holds no throughput estimate for this primitive",
            )),
        }
    }

    let sources: Vec<_> = report.rng_sources.iter().filter(|r| r.available).collect();
    if sources.is_empty() {
        // Two very different situations reach here, and saying "this machine
        // has no hardware RNG" would be wrong in one of them. On Windows the
        // feature list above routinely carries RDRAND and RDSEED while
        // `rng_sources` comes back empty, because the two are filled by
        // different probes and only one of them is implemented there. Asserting
        // the machine has no random source while IronMonitor has just reported the
        // instruction that provides one is a contradiction an agent would be
        // right to act on and wrong to believe.
        let instruction_present = accelerated.iter().any(|f| {
            matches!(
                f.category,
                crate::crypto_accel::CryptoCategory::RandomNumberGen
            )
        });
        out.push(Reading::unavailable(
            "cpu.crypto.rng.<none>",
            None,
            if instruction_present {
                "the hardware random source probe enumerated nothing, but the feature \
                 list above reports a random number instruction - this is a gap in the \
                 probe on this platform rather than a machine without an RNG"
            } else {
                "no hardware random source was found, and no random number instruction \
                 was reported either"
            },
        ));
        return;
    }
    for (i, r) in sources.iter().enumerate() {
        let base = format!("cpu.crypto.rng.{i}");
        push_spec_id(out, format!("{base}.name"), &r.name);
        push_spec_id(
            out,
            format!("{base}.source"),
            &format!("{:?}", r.source_type),
        );
        push_spec_opt(
            out,
            format!("{base}.quality"),
            r.quality.map(|q| serde_json::json!(q)),
            Some(Unit::Count),
            "this source declares no entropy figure, and assuming one would be worse \
             than saying nothing",
        );
    }
}

/// Memory bandwidth, every figure of which is arithmetic.
///
/// The estimate is worth publishing and worth labelling. `Derived` is not a
/// weaker `Measured`; it is a different claim, and the difference is the whole
/// reason an agent can use these numbers safely. Nothing here was benchmarked.
fn resolve_memory_bandwidth(out: &mut Vec<Reading>) {
    let monitor = match crate::memory_bandwidth::MemoryBandwidthMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            // The cluster's entities inherit this reason in `snapshot`'s
            // catch-all, rather than being told no resolver is bound.
            out.push(Reading::unavailable(
                "memory.bandwidth.<none>",
                None,
                format!(
                    "the memory configuration needed for an estimate is not readable here: {e}"
                ),
            ));
            return;
        }
    };

    let est = monitor.estimate();

    push_spec_id(
        out,
        "memory.bandwidth.generation",
        &format!("{:?}", est.generation),
    );

    // Everything below rests on the generation, and an unidentified generation
    // does not stop the estimator producing numbers -- it falls back to 3200
    // MT/s, a 64-bit bus and a 0.75 efficiency factor, none of which is a fact
    // about this machine. A VM's SMBIOS routinely names no generation, so on
    // those the whole chain was publishing defaults as `Specification` and
    // `Derived` readings with nothing to distinguish them from figures that had
    // been read. Withholding the chain is the only honest answer: the inputs
    // were not read, so the outputs are not estimates of anything.
    let unidentified = est.generation == crate::memory_bandwidth::MemoryGeneration::Unknown;
    const NO_GENERATION: &str = "the memory generation was not identified, so the transfer \
                                 rate and every bandwidth figure below it would be a built-in \
                                 default rather than a property of this machine";

    if unidentified {
        for id in [
            "memory.bandwidth.speed",
            "memory.bandwidth.peak",
            "memory.bandwidth.achievable",
            "memory.bandwidth.stream_triad",
        ] {
            let unit = if id == "memory.bandwidth.speed" {
                Unit::Count
            } else {
                Unit::BytesPerSecond
            };
            out.push(Reading::unavailable(id, Some(unit), NO_GENERATION));
        }
        out.push(Reading::spec(
            "memory.bandwidth.channels",
            serde_json::json!(est.channels.active_channels),
            Some(Unit::Count),
        ));
        out.push(Reading::spec(
            "memory.bandwidth.max_channels",
            serde_json::json!(est.channels.max_channels),
            Some(Unit::Count),
        ));
        return;
    }

    // The generation is known but the speed may not be. That case used to be
    // filled from a per-generation lookup table and published here as a
    // `specification` of this machine -- the guard above covered an unknown
    // generation and not an unknown speed, which fell back to the same kind of
    // default. Everything derived from the speed is withheld with it.
    let (Some(speed), Some(peak), Some(achievable), Some(triad)) = (
        est.speed_mts,
        est.peak_bandwidth_gbs,
        est.achievable_bandwidth_gbs,
        est.stream_triad_estimate_gbs,
    ) else {
        const NO_SPEED: &str = concat!(
            "no DIMM reported a transfer rate, so the speed and every bandwidth ",
            "figure derived from it would be a built-in default"
        );
        out.push(Reading::unavailable(
            "memory.bandwidth.speed",
            Some(Unit::Count),
            NO_SPEED,
        ));
        for id in [
            "memory.bandwidth.peak",
            "memory.bandwidth.achievable",
            "memory.bandwidth.stream_triad",
        ] {
            out.push(Reading::unavailable(
                id,
                Some(Unit::BytesPerSecond),
                NO_SPEED,
            ));
        }
        out.push(Reading::spec(
            "memory.bandwidth.channels",
            serde_json::json!(est.channels.active_channels),
            Some(Unit::Count),
        ));
        out.push(Reading::spec(
            "memory.bandwidth.max_channels",
            serde_json::json!(est.channels.max_channels),
            Some(Unit::Count),
        ));
        return;
    };

    out.push(Reading::spec(
        "memory.bandwidth.speed",
        serde_json::json!(speed),
        Some(Unit::Count),
    ));
    out.push(Reading::spec(
        "memory.bandwidth.channels",
        serde_json::json!(est.channels.active_channels),
        Some(Unit::Count),
    ));
    out.push(Reading::spec(
        "memory.bandwidth.max_channels",
        serde_json::json!(est.channels.max_channels),
        Some(Unit::Count),
    ));

    // GB/s to bytes per second, which is the unit the entities declare. Decimal
    // gigabytes, not gibibytes: memory bandwidth is quoted in the same decimal
    // units as the transfer rate it is computed from, and converting with 1024
    // would inflate every figure by 7%.
    const GB: f64 = 1_000_000_000.0;
    out.push(Reading::derived(
        "memory.bandwidth.peak",
        serde_json::json!(peak * GB),
        Some(Unit::BytesPerSecond),
    ));
    out.push(Reading::derived(
        "memory.bandwidth.achievable",
        serde_json::json!(achievable * GB),
        Some(Unit::BytesPerSecond),
    ));
    out.push(Reading::derived(
        "memory.bandwidth.stream_triad",
        serde_json::json!(triad * GB),
        Some(Unit::BytesPerSecond),
    ));
}

/// `push_opt` for firmware-declared values: same absence handling, but the
/// present case carries `Specification` rather than `Measured`. Without this a
/// DIMM's part number would claim to have been measured off the module.
fn push_spec_opt(
    out: &mut Vec<Reading>,
    id: impl Into<String>,
    value: Option<serde_json::Value>,
    unit: Option<Unit>,
    why_absent: &str,
) {
    match value {
        Some(v) if v.as_str().is_some_and(names_an_absence) => {
            out.push(Reading::unavailable(
                id,
                unit,
                format!("reader returned {v}, which names an absence rather than a value"),
            ));
        }
        Some(v) => out.push(Reading::spec(id, v, unit)),
        None => out.push(Reading::unavailable(id, unit, why_absent)),
    }
}

/// Package energy domains, where the platform exposes them.
///
/// The absence path is written first and deliberately: on Windows and macOS
/// there is no unprivileged RAPL interface at all, and the failure has to arrive
/// as a stated reason rather than as an empty list. The reader returned
/// `Ok(vec![])` on both until this was wired, which is indistinguishable from a
/// Linux box whose zones are all disabled.
fn resolve_rapl(out: &mut Vec<Reading>) {
    let mut monitor = match crate::rapl::RaplMonitor::new() {
        Ok(m) => m,
        Err(e) => {
            out.push(Reading::unavailable(
                "power.rapl.<none>",
                None,
                format!("RAPL is not readable here: {e}"),
            ));
            return;
        }
    };

    if let Err(e) = monitor.refresh() {
        out.push(Reading::unavailable(
            "power.rapl.<none>",
            None,
            format!("RAPL is not readable here: {e}"),
        ));
        return;
    }

    let readings = monitor.readings();

    if readings.is_empty() {
        // Reached only where the interface exists and enumerated nothing, which
        // is a different fact from the platform not having one.
        out.push(Reading::unavailable(
            "power.rapl.<none>",
            None,
            "the RAPL interface is present and enumerated no energy domains",
        ));
        return;
    }

    for (i, r) in readings.iter().enumerate() {
        let base = format!("power.rapl.{i}");
        push_text(out, format!("{base}.name"), &r.name);
        out.push(Reading::measured(
            format!("{base}.energy"),
            serde_json::json!(r.energy_uj),
            Some(Unit::Count),
        ));
        // `push_opt`, not `Reading::measured`: the range was `u64::MAX` when
        // unread and was published here as a measurement of it.
        push_opt(
            out,
            format!("{base}.max_energy_range"),
            r.max_energy_range_uj.map(|v| serde_json::json!(v)),
            Some(Unit::Count),
            "the domain's max_energy_range_uj attribute could not be read",
        );
        push_opt(
            out,
            format!("{base}.power_limit"),
            // Microwatts to watts, which is the unit the entity declares.
            r.power_limit_uw
                .map(|uw| serde_json::json!(uw as f64 / 1_000_000.0)),
            Some(Unit::Watts),
            "this RAPL domain publishes no power constraint",
        );
        out.push(Reading::measured(
            format!("{base}.enabled"),
            serde_json::json!(r.enabled),
            None,
        ));
    }
}

fn resolve_power(out: &mut Vec<Reading>) {
    match crate::battery::BatteryMonitor::new() {
        Ok(monitor) => {
            let batteries = monitor.batteries();
            if batteries.is_empty() {
                out.push(Reading::unavailable(
                    "power.battery.percentage",
                    Some(Unit::Percent),
                    "no battery present (desktop or always-AC machine)",
                ));
            } else {
                push_opt(
                    out,
                    "power.battery.percentage".to_string(),
                    batteries[0].charge_percent.map(|p| serde_json::json!(p)),
                    Some(Unit::Percent),
                    "a battery is present but its charge gauge could not be read",
                );
            }
        }
        Err(e) => out.push(Reading::unavailable(
            "power.battery.percentage",
            Some(Unit::Percent),
            format!("battery monitor unavailable: {e}"),
        )),
    }
}

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

    /// The invariant the whole module exists for: a missing value is never a zero,
    /// and never silent about why.
    /// Zero is how the microarch readers say a core count was not read, and
    /// it was published as a specification of zero cores -- with SMT
    /// "measured" off, since that is computed from the two counts.
    #[test]
    fn unread_core_counts_are_not_zero_cores_and_do_not_decide_smt() {
        use crate::cpu_microarch::{CpuMicroarchMonitor, CpuVendor};
        let mut report = CpuMicroarchMonitor::default().report().clone();
        report.microarch.vendor = CpuVendor::Unknown;
        report.physical_cores = 0;
        report.logical_cores = 16;
        report.smt_enabled = false;

        let mut out = Vec::new();
        push_microarch(&mut out, &report);
        let get = |id: &str| out.iter().find(|r| r.id == id).cloned().expect(id);

        let physical = get("cpu.microarch.physical_cores");
        assert_eq!(physical.provenance, Provenance::Unavailable);
        assert!(physical.value.is_none());
        let logical = get("cpu.microarch.logical_cores");
        assert_eq!(logical.value, Some(serde_json::json!(16)));
        let smt = get("cpu.microarch.smt_enabled");
        assert_eq!(
            smt.provenance,
            Provenance::Unavailable,
            "SMT was decided from an unread count"
        );
    }

    #[test]
    fn unavailable_readings_carry_no_value_and_state_a_reason() {
        for r in snapshot() {
            if r.provenance == Provenance::Unavailable {
                assert!(
                    r.value.is_none(),
                    "{} is unavailable but carries a value: {:?}",
                    r.id,
                    r.value
                );
                assert!(
                    r.note.as_ref().is_some_and(|n| !n.trim().is_empty()),
                    "{} is unavailable with no reason given",
                    r.id
                );
            } else {
                assert!(
                    r.value.is_some(),
                    "{} claims provenance {:?} but has no value",
                    r.id,
                    r.provenance
                );
            }
        }
    }

    #[test]
    fn only_measured_readings_count_as_observations() {
        for r in snapshot() {
            let expected = r.provenance == Provenance::Measured && r.value.is_some();
            assert_eq!(r.is_observation(), expected, "{}", r.id);
        }
    }

    /// Every resolved id must be one the ontology names — otherwise the schema an
    /// agent fetched does not describe what it receives.
    #[test]
    fn every_reading_maps_to_a_declared_entity() {
        let ontology = Ontology::build();
        for r in snapshot() {
            assert!(
                lookup_template(&ontology, &r.id).is_some(),
                "{} was resolved but is not declared in the ontology",
                r.id
            );
            assert!(
                !Ontology::is_template(&r.id),
                "{} is a template, not a concrete reading",
                r.id
            );
        }
    }

    /// Live values must satisfy the ranges the ontology declares.
    ///
    /// This held at rest and failed under the load of the full test suite, when a
    /// per-core utilization derived as `user + system` drifted past 100 percent.
    /// Two things changed: the derivation now uses `100 - idle`, and `snapshot`
    /// withholds anything the ontology rejects. The assertion is therefore now
    /// structural rather than a matter of timing.
    #[test]
    fn live_readings_are_physically_possible() {
        let problems = validate(&snapshot());
        assert!(problems.is_empty(), "impossible readings: {problems:#?}");
    }

    /// The gate must withhold rather than clamp. A clamped value looks like a
    /// reading and is not one, which is the failure mode this module exists to
    /// prevent — and it would destroy the evidence that sampling went wrong.
    #[test]
    fn out_of_range_values_are_withheld_with_the_offending_value_named() {
        use crate::ontology::{Domain, EntityKind};

        let ontology = Ontology::build();
        let entity = ontology.get("cpu.total.utilization").unwrap();
        assert_eq!(entity.domain, Domain::Cpu);
        assert_eq!(entity.kind, EntityKind::Measurement);

        // The range check the gate relies on, exercised directly: an impossible
        // percentage must be reported as a problem, not silently corrected.
        let problem = entity
            .validate_range(103.0)
            .expect("103 percent should be rejected");
        assert!(
            problem.contains("103"),
            "the rejection must name the offending value so it can be diagnosed, \
             got: {problem}"
        );
        assert!(entity.validate_range(99.9).is_none());
    }

    /// An id an agent cannot type is not an id.
    ///
    /// Device names come from vendors, not from ironmon: the first version of the
    /// network resolver emitted `network.Bluetooth Network Connection.rx_bytes`,
    /// which cannot be passed to `ironmon get` without quoting and whose spaces make
    /// the dotted structure ambiguous. Segments are sanitised at construction; this
    /// asserts the whole snapshot honours it.
    #[test]
    fn every_id_is_shell_safe_and_well_structured() {
        for r in snapshot() {
            assert!(
                !r.id.contains(char::is_whitespace),
                "{} contains whitespace, so it cannot be passed as a bare argument",
                r.id
            );
            assert!(
                !r.id.contains("..") && !r.id.starts_with('.') && !r.id.ends_with('.'),
                "malformed id: {}",
                r.id
            );
            for segment in r.id.split('.') {
                assert!(!segment.is_empty(), "{} has an empty path segment", r.id);
            }
        }
    }

    #[test]
    fn id_segments_are_sanitised_without_collapsing_distinct_names() {
        assert_eq!(
            id_segment("Bluetooth Network Connection"),
            "Bluetooth_Network_Connection"
        );
        assert_eq!(id_segment("eth0.100"), "eth0_100");
        assert_eq!(id_segment("  spaced  "), "spaced");
        // A name made entirely of separators still has to yield a usable segment.
        assert_eq!(id_segment("///"), "unnamed");
        // Distinct names must not collide into one id.
        assert_ne!(id_segment("eth0"), id_segment("eth1"));
    }

    /// A diagnostic must only appear when its condition holds. `disk.<none>` in a
    /// snapshot that also lists eight disk readings is a contradiction, and one that
    /// would teach an agent to distrust the diagnostics generally.
    #[test]
    fn diagnostics_do_not_contradict_the_readings_beside_them() {
        let readings = snapshot();
        for domain in crate::ontology::Domain::ALL {
            let none_id = format!("{}.<none>", domain.as_str());
            let has_none = readings.iter().any(|r| r.id == none_id);
            if !has_none {
                continue;
            }
            // Only rows carrying an actual observation can contradict the
            // diagnostic. An unavailable row asserts nothing about the hardware:
            // `gpu.setting.perf_level` reported as "no resolver bound on this
            // build" sits perfectly happily beside `gpu.<none>`, because neither
            // claims a GPU is present. Counting those made the test fire on a
            // Linux runner with no GPU, where three writable GPU settings are
            // declared from their registered apply handlers and read by nothing.
            //
            // The doc above always said "eight disk readings" — readings, values.
            // The predicate simply did not say it.
            let real_rows: Vec<&str> = readings
                .iter()
                .filter(|r| {
                    r.id.starts_with(&format!("{}.", domain.as_str()))
                        && !r.id.contains('<')
                        && r.is_observation()
                })
                .map(|r| r.id.as_str())
                .collect();
            // The ids, not just how many. A count says a contradiction exists and
            // leaves you to guess which resolver caused it; on a platform you
            // cannot reproduce locally that guess is the whole cost of the fix.
            assert!(
                real_rows.is_empty(),
                "{none_id} claims the domain enumerated nothing, but these {} rows are present alongside it: {real_rows:?}",
                real_rows.len(),
            );
        }
    }

    /// Every domain the ontology declares must appear in a snapshot, even when the
    /// machine has no such device. Silence would leave an agent unable to tell "no
    /// disks here" from "IronMonitor does not read disks".
    #[test]
    fn no_declared_domain_is_silently_absent() {
        let readings = snapshot();
        for domain in crate::ontology::Domain::ALL {
            let prefix = format!("{}.", domain.as_str());
            assert!(
                readings.iter().any(|r| r.id.starts_with(&prefix)),
                "domain {} produced no rows at all — an agent cannot distinguish an \
                 absent device from an unimplemented reader",
                domain.as_str()
            );
        }
    }

    #[test]
    fn ids_are_unique_within_a_snapshot() {
        let readings = snapshot();
        let mut seen = std::collections::HashSet::new();
        for r in &readings {
            assert!(seen.insert(r.id.clone()), "duplicate reading id: {}", r.id);
        }
    }

    #[test]
    fn get_rejects_templates_and_finds_concrete_ids() {
        assert!(
            get("gpu.{n}.name").is_none(),
            "a template is not a question with an answer"
        );
        // memory.total resolves on every supported platform; on an unsupported one
        // it is still present, as an unavailable reading.
        assert!(get("memory.total").is_some());
        assert!(get("no.such.entity").is_none());
    }

    #[test]
    fn coverage_accounts_for_every_reading() {
        // One snapshot, tallied. The previous version compared `coverage()`
        // against a second, independent `snapshot()` and asserted equal lengths —
        // which is a race on a live machine, since a USB device or a process can
        // come and go between the two calls. It passed for as long as the suite
        // was quiet enough, then failed under parallel load for no reason
        // connected to what it was testing.
        let readings = snapshot();
        let c = coverage_of(&readings);
        assert_eq!(c.total, c.resolved + c.unavailable);
        assert_eq!(c.total, readings.len());
    }
}