oomtop-core 0.2.2

oomtop core: pure data model, units, attribution, headroom, forecast, throttle, query and ranking logic (no I/O)
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
//! Attribution (SPEC §7): group every process under the agent session, app, sandbox, model server, build
//! daemon or system component that owns it. Pure: works over a [`Snapshot`], compiled rules and lineage data.
//!
//! ## Signals, in the order they are tried for each process
//! 0. **oomtop itself** — its own process tree forms the `oomtop` group, except that an `oomtop mcp` child
//!    stays inside the agent session that launched it (and is excluded from that session's reclaim gain).
//! 1. **Adapter truth** — pids that adapters already mapped (`Snapshot::model_servers[].pids`,
//!    `Snapshot::sandboxes[].host_pids`) when attribution runs after an adapter probe.
//! 2. **cgroup path** (Linux) — container / VM scopes (docker, podman, containerd, CRI-O, kubepods, LXC,
//!    libvirt/QEMU machines) form sandbox groups.
//! 3. **Rule roots** — an identity match (`match.exe|name|script|cmdline|cwd|bundle|cgroup`, OR'd) makes the
//!    process a group root, keyed by rule and root pid (`agent:<rule-id>:<pid>`). A root merges into a
//!    same-rule parent (`ollama serve` → `ollama runner`, a `claude -p` started by a Claude Code session).
//!    The id never depends on which descendants happen to be running: a root with `session_key` learns its
//!    (hashed) session id from its marker-carrying descendants, but that id is only an *alias*
//!    (`agent:<hash12>`) used to find the session — by markers below, and by journals written before ids
//!    were pid-keyed.
//! 4. **Session markers** — a process carrying an allowlisted marker (`CLAUDECODE`, hashed
//!    `CLAUDE_CODE_SESSION_ID`) joins the live session with that id, even after being re-parented. The id
//!    is read from the rule's own `session_key` (an agent started inside another agent carries both ids);
//!    when several sessions match, the one the parent already belongs to wins, else the innermost (the
//!    one with the youngest root).
//! 5. **Responsible pid** (macOS) — XPC services / helpers join the app that is responsible for them (the
//!    `com.apple.Virtualization.VirtualMachine` XPC → Claude.app). Ignored when the responsible process is a
//!    terminal or the process was launched from a shell (macOS makes the terminal "responsible" for every
//!    command typed into it).
//! 6. **Ancestry** — the ppid chain. Terminals, interactive shells and `sudo`-style launchers are
//!    *boundaries*: a command typed into a shell becomes its own root unless the shell itself belongs to a
//!    rule-defined group (e.g. an agent session), so the terminal app does not swallow everything run in it;
//!    terminal plumbing (`login`, interactive shells, `tmux`, `sudo`) stays in the terminal's group.
//!    `launchd` / `systemd` / `init` are subreapers, never owners.
//! 7. **Lineage journal** — a re-parented process (recorded ppid > 1, now 1 / a subreaper / a reused pid)
//!    rejoins its recorded group while that group is alive; otherwise it becomes an **orphan root** whose
//!    `owner_group` names the group that spawned it.
//! 8. **Dead-session markers** — like 7 for marker carriers whose session root has exited.
//! 9. **systemd unit / app scope** (Linux) — top-level processes of the same `.service` / `app-*.scope` share
//!    a group.
//! 10. **Heuristic** — the process is a top-level root: apps are keyed by bundle name (`app:google-chrome`),
//!     system daemons by name, everything else by name + pid.
//!
//! Every process lands in exactly one group; groups are sorted by footprint desc; group ids are stable
//! across samples for the same root. Identity is always `(pid, start_time)`: a parent whose start time is
//! after its child's is a reused pid and is not treated as the parent.
//!
//! ## Rule semantics
//! `[[group]]` in `rules.d/*.toml` (SPEC §15): within `match`, **fields are OR'd** (any identity field
//! matching makes the process a group root) and values within a field are OR'd. `match.env` is not an
//! identity match: it groups processes carrying those marker keys into the session (by `session_key`) of the
//! rule's root. `exclude` vetoes a match. Higher `priority` wins; ties → first rule. Globs are case-sensitive;
//! `match.exe` is tried against the executable path, its basename and argv[0] (self-updating CLIs such as
//! Claude Code run from a versioned file, so argv[0] is the stable name).

use crate::actions::{is_protected_process, ProtectContext};
use crate::fingerprint;
use crate::measured::{sum_bytes, sum_f64};
use crate::model::{
    AttributionSignal, Confidence, Group, GroupKind, GroupTotals, Member, ModelServerKind, ProcId, Process,
    SandboxKind, Snapshot,
};
use globset::{Glob, GlobBuilder, GlobSet, GlobSetBuilder};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, HashMap, HashSet};
use thiserror::Error;

/// Group id of oomtop's own processes.
pub const SELF_GROUP_ID: &str = "oomtop";
/// Ancestry walks stop after this many hops (cycle / pathological-depth guard).
const MAX_DEPTH: usize = 256;

// ---------------------------------------------------------------------------------------------------------
// Rules
// ---------------------------------------------------------------------------------------------------------

/// Identity match fields of a rule.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
pub struct MatchSpec {
    /// Globs against the executable path, its basename and argv[0] (e.g. "claude", "**/bin/sd-server").
    pub exe: Vec<String>,
    /// Globs against the short process name (comm).
    pub name: Vec<String>,
    /// Globs against any argv element after argv[0] (node/python scripts, java main classes).
    pub script: Vec<String>,
    /// Regexes against the space-joined command line.
    pub cmdline: Vec<String>,
    /// Marker keys (must be in the allowlist); groups carriers into the rule's session. Not an identity match.
    pub env: Vec<String>,
    /// Globs against cwd.
    pub cwd: Vec<String>,
    /// Globs against the macOS bundle id.
    pub bundle: Vec<String>,
    /// Globs against the Linux cgroup path.
    pub cgroup: Vec<String>,
}

impl MatchSpec {
    fn has_identity(&self) -> bool {
        !(self.exe.is_empty()
            && self.name.is_empty()
            && self.script.is_empty()
            && self.cmdline.is_empty()
            && self.cwd.is_empty()
            && self.bundle.is_empty()
            && self.cgroup.is_empty())
    }
}

/// One detection rule (TOML `[[group]]`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Rule {
    /// Optional stable id ("builtin:claude-code"); defaults to the label slug.
    pub id: Option<String>,
    pub kind: GroupKind,
    pub label: String,
    #[serde(rename = "match")]
    pub matcher: MatchSpec,
    pub exclude: Option<MatchSpec>,
    /// "env:KEY" → one group per distinct (hashed) marker value.
    pub session_key: Option<String>,
    pub priority: i32,
    /// Matching processes are protected (never offered for actions).
    pub protected: bool,
}

impl Default for Rule {
    fn default() -> Self {
        Rule {
            id: None,
            kind: GroupKind::Other,
            label: String::new(),
            matcher: MatchSpec::default(),
            exclude: None,
            session_key: None,
            priority: 0,
            protected: false,
        }
    }
}

impl Rule {
    pub fn rule_id(&self) -> String {
        self.id.clone().unwrap_or_else(|| slug(&self.label))
    }

    /// The marker key named by `session_key = "env:KEY"`.
    pub fn session_env_key(&self) -> Option<&str> {
        self.session_key
            .as_deref()
            .and_then(|k| k.strip_prefix("env:"))
            .map(str::trim)
            .filter(|k| !k.is_empty())
    }
}

/// An ordered rule set (built-in rules first, then user rules; user rules usually carry higher priority).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default, deny_unknown_fields)]
pub struct RuleSet {
    #[serde(rename = "group")]
    pub rules: Vec<Rule>,
}

#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum RuleError {
    #[error("rule {rule:?}: bad glob {pattern:?}: {msg}")]
    Glob {
        rule: String,
        pattern: String,
        msg: String,
    },
    #[error("rule {rule:?}: bad regex {pattern:?}: {msg}")]
    Regex {
        rule: String,
        pattern: String,
        msg: String,
    },
    #[error("rule {rule:?}: empty label")]
    EmptyLabel { rule: String },
    #[error("rule {rule:?}: session_key {key:?} must look like \"env:KEY\"")]
    SessionKey { rule: String, key: String },
}

#[derive(Debug, Clone)]
struct CompiledSpec {
    exe: GlobSet,
    name: GlobSet,
    script: GlobSet,
    cmdline: Vec<Regex>,
    cwd: GlobSet,
    bundle: GlobSet,
    cgroup: GlobSet,
    env: Vec<String>,
    has_identity: bool,
}

#[derive(Debug, Clone)]
struct CompiledRule {
    rule: Rule,
    id: String,
    spec: CompiledSpec,
    exclude: Option<CompiledSpec>,
}

/// All rules' globs for one field in a single [`GlobSet`] (glob index → rule index), so a process is
/// matched once per field instead of once per rule.
#[derive(Debug, Clone, Default)]
struct GlobIndex {
    set: GlobSet,
    owner: Vec<usize>,
}

impl GlobIndex {
    fn build(set: &RuleSet, pick: impl Fn(&MatchSpec) -> &Vec<String>) -> Result<Self, RuleError> {
        let mut b = GlobSetBuilder::new();
        let mut owner = Vec::new();
        for (i, r) in set.rules.iter().enumerate() {
            for pat in pick(&r.matcher) {
                let g = GlobBuilder::new(pat)
                    .case_insensitive(false)
                    .literal_separator(false)
                    .build()
                    .map_err(|e| RuleError::Glob {
                        rule: r.rule_id(),
                        pattern: pat.clone(),
                        msg: e.to_string(),
                    })?;
                b.add(g);
                owner.push(i);
            }
        }
        let set = b.build().map_err(|e| RuleError::Glob {
            rule: "(all rules)".into(),
            pattern: String::new(),
            msg: e.to_string(),
        })?;
        Ok(GlobIndex { set, owner })
    }

    fn is_empty(&self) -> bool {
        self.owner.is_empty()
    }

    fn hits(&self, value: &str, buf: &mut Vec<usize>, cand: &mut [bool]) {
        if self.is_empty() || value.is_empty() {
            return;
        }
        self.set.matches_into(value, buf);
        for &g in buf.iter() {
            cand[self.owner[g]] = true;
        }
    }
}

#[derive(Debug, Clone)]
struct RegexIndex {
    set: regex::RegexSet,
    owner: Vec<usize>,
}

impl Default for RegexIndex {
    fn default() -> Self {
        RegexIndex {
            set: regex::RegexSet::empty(),
            owner: Vec::new(),
        }
    }
}

/// Most memo entries kept before the memo is reset (a long session sees many short-lived processes).
const MEMO_CAP: usize = 16_384;

/// Signature of the identity fields that rule matching and fingerprinting read (exe, name, argv, cwd,
/// bundle id, cgroup). Equal signatures give equal results, so results are memoized by it.
fn identity_sig(p: &Process) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut h = std::collections::hash_map::DefaultHasher::new();
    p.exe.hash(&mut h);
    p.name.hash(&mut h);
    p.cmdline.hash(&mut h);
    p.cwd.hash(&mut h);
    p.bundle_id.hash(&mut h);
    p.cgroup.hash(&mut h);
    h.finish()
}

/// Memo of pure per-process results — the root rule match and the group fingerprint — keyed by
/// [`identity_sig`]. A process's identity rarely changes between samples, so re-matching ~700 processes
/// against every glob and regex each refresh is wasted work (SPEC §14 CPU budget). Interior mutability
/// keeps `match_root(&self)` unchanged; a poisoned lock just disables the memo.
#[derive(Debug, Default)]
struct Memo {
    roots: HashMap<u64, Option<usize>>,
    fingerprints: HashMap<(u64, GroupKind), String>,
    /// [`heuristic_kind_label`] also reads the uid and pid.
    heuristics: HashMap<(u64, Option<u32>, u32), (GroupKind, String)>,
}

#[derive(Debug, Default)]
struct MemoCell(std::sync::Mutex<Memo>);

impl Clone for MemoCell {
    fn clone(&self) -> Self {
        MemoCell::default()
    }
}

/// Rules compiled for matching.
#[derive(Debug, Clone, Default)]
pub struct CompiledRules {
    memo: MemoCell,
    rules: Vec<CompiledRule>,
    exe: GlobIndex,
    name: GlobIndex,
    script: GlobIndex,
    cwd: GlobIndex,
    bundle: GlobIndex,
    cgroup: GlobIndex,
    cmdline: RegexIndex,
}

fn glob_set(rule: &str, pats: &[String]) -> Result<GlobSet, RuleError> {
    let mut b = GlobSetBuilder::new();
    for p in pats {
        let g: Glob = GlobBuilder::new(p)
            .case_insensitive(false)
            .literal_separator(false)
            .build()
            .map_err(|e| RuleError::Glob {
                rule: rule.to_string(),
                pattern: p.clone(),
                msg: e.to_string(),
            })?;
        b.add(g);
    }
    b.build().map_err(|e| RuleError::Glob {
        rule: rule.to_string(),
        pattern: String::new(),
        msg: e.to_string(),
    })
}

fn compile_spec(rule: &str, s: &MatchSpec) -> Result<CompiledSpec, RuleError> {
    let cmdline = s
        .cmdline
        .iter()
        .map(|p| {
            Regex::new(p).map_err(|e| RuleError::Regex {
                rule: rule.to_string(),
                pattern: p.clone(),
                msg: e.to_string(),
            })
        })
        .collect::<Result<Vec<_>, _>>()?;
    Ok(CompiledSpec {
        exe: glob_set(rule, &s.exe)?,
        name: glob_set(rule, &s.name)?,
        script: glob_set(rule, &s.script)?,
        cmdline,
        cwd: glob_set(rule, &s.cwd)?,
        bundle: glob_set(rule, &s.bundle)?,
        cgroup: glob_set(rule, &s.cgroup)?,
        env: s.env.clone(),
        has_identity: s.has_identity(),
    })
}

fn basename(path: &str) -> &str {
    let p = path.trim_end_matches('/');
    p.rsplit('/').next().unwrap_or(p)
}

/// Per-process strings computed once for matching against every rule.
struct ProcView<'a> {
    p: &'a Process,
    exe_base: &'a str,
    argv0: Option<&'a str>,
    joined: String,
}

impl<'a> ProcView<'a> {
    fn new(p: &'a Process) -> Self {
        ProcView {
            p,
            exe_base: basename(&p.exe),
            argv0: p.cmdline.first().map(String::as_str).filter(|a| !a.is_empty()),
            joined: p.cmdline.join(" "),
        }
    }
}

impl CompiledSpec {
    fn identity_match(&self, v: &ProcView<'_>) -> bool {
        if !self.has_identity {
            return false;
        }
        let p = v.p;
        if !self.exe.is_empty() {
            if !p.exe.is_empty() && (self.exe.is_match(&p.exe) || self.exe.is_match(v.exe_base)) {
                return true;
            }
            if let Some(a0) = v.argv0 {
                if self.exe.is_match(a0) || self.exe.is_match(basename(a0)) {
                    return true;
                }
            }
        }
        if !p.name.is_empty() && self.name.is_match(&p.name) {
            return true;
        }
        if !self.script.is_empty() && p.cmdline.iter().skip(1).any(|a| self.script.is_match(a)) {
            return true;
        }
        if !self.cmdline.is_empty() && self.cmdline.iter().any(|r| r.is_match(&v.joined)) {
            return true;
        }
        if let Some(cwd) = &p.cwd {
            if self.cwd.is_match(cwd) {
                return true;
            }
        }
        if let Some(b) = &p.bundle_id {
            if self.bundle.is_match(b) {
                return true;
            }
        }
        if let Some(cg) = &p.cgroup {
            if self.cgroup.is_match(cg) {
                return true;
            }
        }
        false
    }

    fn env_match(&self, p: &Process) -> bool {
        !self.env.is_empty() && self.env.iter().any(|k| p.markers.keys.iter().any(|m| m == k))
    }
}

/// A rule match for one process.
#[derive(Debug, Clone, PartialEq)]
pub struct RuleMatch<'a> {
    pub index: usize,
    pub rule: &'a Rule,
}

impl CompiledRules {
    pub fn compile(set: &RuleSet) -> Result<CompiledRules, RuleError> {
        let mut rules = Vec::with_capacity(set.rules.len());
        for r in &set.rules {
            let id = r.rule_id();
            if r.label.trim().is_empty() {
                return Err(RuleError::EmptyLabel { rule: id });
            }
            if let Some(k) = &r.session_key {
                if r.session_env_key().is_none() {
                    return Err(RuleError::SessionKey {
                        rule: id,
                        key: k.clone(),
                    });
                }
            }
            let spec = compile_spec(&id, &r.matcher)?;
            let exclude = r.exclude.as_ref().map(|e| compile_spec(&id, e)).transpose()?;
            rules.push(CompiledRule {
                rule: r.clone(),
                id,
                spec,
                exclude,
            });
        }
        let mut pats = Vec::new();
        let mut owner = Vec::new();
        for (i, r) in set.rules.iter().enumerate() {
            for p in &r.matcher.cmdline {
                pats.push(p.clone());
                owner.push(i);
            }
        }
        let cmdline = RegexIndex {
            set: regex::RegexSet::new(&pats).map_err(|e| RuleError::Regex {
                rule: "(all rules)".into(),
                pattern: String::new(),
                msg: e.to_string(),
            })?,
            owner,
        };
        Ok(CompiledRules {
            memo: MemoCell::default(),
            rules,
            exe: GlobIndex::build(set, |m| &m.exe)?,
            name: GlobIndex::build(set, |m| &m.name)?,
            script: GlobIndex::build(set, |m| &m.script)?,
            cwd: GlobIndex::build(set, |m| &m.cwd)?,
            bundle: GlobIndex::build(set, |m| &m.bundle)?,
            cgroup: GlobIndex::build(set, |m| &m.cgroup)?,
            cmdline,
        })
    }

    /// Rules whose identity fields match (same semantics as matching each rule's spec in turn).
    fn identity_candidates(&self, v: &ProcView<'_>) -> Vec<bool> {
        let mut cand = vec![false; self.rules.len()];
        let mut buf = Vec::new();
        let p = v.p;
        if !p.exe.is_empty() {
            self.exe.hits(&p.exe, &mut buf, &mut cand);
            self.exe.hits(v.exe_base, &mut buf, &mut cand);
        }
        if let Some(a0) = v.argv0 {
            self.exe.hits(a0, &mut buf, &mut cand);
            self.exe.hits(basename(a0), &mut buf, &mut cand);
        }
        self.name.hits(&p.name, &mut buf, &mut cand);
        if !self.script.is_empty() {
            for a in p.cmdline.iter().skip(1) {
                self.script.hits(a, &mut buf, &mut cand);
            }
        }
        if !self.cmdline.owner.is_empty() {
            for i in self.cmdline.set.matches(&v.joined).iter() {
                cand[self.cmdline.owner[i]] = true;
            }
        }
        if let Some(c) = &p.cwd {
            self.cwd.hits(c, &mut buf, &mut cand);
        }
        if let Some(b) = &p.bundle_id {
            self.bundle.hits(b, &mut buf, &mut cand);
        }
        if let Some(c) = &p.cgroup {
            self.cgroup.hits(c, &mut buf, &mut cand);
        }
        cand
    }

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

    pub fn is_empty(&self) -> bool {
        self.rules.is_empty()
    }

    /// The rule at `index` (as returned in [`RuleMatch::index`]).
    pub fn rule(&self, index: usize) -> Option<&Rule> {
        self.rules.get(index).map(|r| &r.rule)
    }

    fn best<'a>(
        &'a self,
        v: &ProcView<'_>,
        f: impl Fn(&CompiledSpec, &ProcView<'_>) -> bool,
        precomputed: Option<&[bool]>,
    ) -> Option<RuleMatch<'a>> {
        let mut best: Option<RuleMatch<'a>> = None;
        for (i, r) in self.rules.iter().enumerate() {
            let hit = match precomputed {
                Some(c) => c[i] && r.spec.has_identity,
                None => f(&r.spec, v),
            };
            if !hit {
                continue;
            }
            if r.exclude.as_ref().map(|e| e.identity_match(v)).unwrap_or(false) {
                continue;
            }
            if best
                .as_ref()
                .map(|b| r.rule.priority > b.rule.priority)
                .unwrap_or(true)
            {
                best = Some(RuleMatch {
                    index: i,
                    rule: &r.rule,
                });
            }
        }
        best
    }

    /// Best identity match (process becomes a group root). Memoized by the process's identity fields.
    pub fn match_root(&self, p: &Process) -> Option<RuleMatch<'_>> {
        let sig = identity_sig(p);
        if let Ok(m) = self.memo.0.lock() {
            if let Some(hit) = m.roots.get(&sig) {
                return hit.map(|index| RuleMatch {
                    index,
                    rule: &self.rules[index].rule,
                });
            }
        }
        let found = self.match_root_uncached(p);
        if let Ok(mut m) = self.memo.0.lock() {
            if m.roots.len() >= MEMO_CAP {
                m.roots.clear();
            }
            m.roots.insert(sig, found.as_ref().map(|r| r.index));
        }
        found
    }

    fn match_root_uncached(&self, p: &Process) -> Option<RuleMatch<'_>> {
        let v = ProcView::new(p);
        let cand = self.identity_candidates(&v);
        self.best(&v, |_, _| false, Some(&cand))
    }

    /// [`heuristic_kind_label`], memoized by the process's identity fields, uid and pid.
    fn heuristic_kind_label(&self, p: &Process) -> (GroupKind, String) {
        let key = (identity_sig(p), p.uid, p.id.pid);
        if let Ok(m) = self.memo.0.lock() {
            if let Some(v) = m.heuristics.get(&key) {
                return v.clone();
            }
        }
        let v = heuristic_kind_label(p);
        if let Ok(mut m) = self.memo.0.lock() {
            if m.heuristics.len() >= MEMO_CAP {
                m.heuristics.clear();
            }
            m.heuristics.insert(key, v.clone());
        }
        v
    }

    /// [`fingerprint::group_fingerprint`], memoized by kind + the root's identity fields.
    fn group_fingerprint(&self, kind: GroupKind, root: &Process) -> String {
        let key = (identity_sig(root), kind);
        if let Ok(m) = self.memo.0.lock() {
            if let Some(fp) = m.fingerprints.get(&key) {
                return fp.clone();
            }
        }
        let fp = fingerprint::group_fingerprint(kind, root);
        if let Ok(mut m) = self.memo.0.lock() {
            if m.fingerprints.len() >= MEMO_CAP {
                m.fingerprints.clear();
            }
            m.fingerprints.insert(key, fp.clone());
        }
        fp
    }

    /// Reference implementation of [`Self::match_root`] (one rule at a time), kept for equivalence tests.
    #[cfg(test)]
    fn match_root_naive(&self, p: &Process) -> Option<RuleMatch<'_>> {
        self.best(&ProcView::new(p), |s, v| s.identity_match(v), None)
    }

    /// Best marker (env) match (process joins a session of the rule).
    pub fn match_marker(&self, p: &Process) -> Option<RuleMatch<'_>> {
        if p.markers.keys.is_empty() {
            return None;
        }
        self.best(&ProcView::new(p), |s, v| s.env_match(v.p), None)
    }

    /// Every marker (env) match, best first (priority desc, then rule order).
    fn match_markers(&self, p: &Process) -> Vec<usize> {
        if p.markers.keys.is_empty() {
            return Vec::new();
        }
        let v = ProcView::new(p);
        let mut hits: Vec<usize> = self
            .rules
            .iter()
            .enumerate()
            .filter(|(_, r)| {
                r.spec.env_match(p) && !r.exclude.as_ref().map(|e| e.identity_match(&v)).unwrap_or(false)
            })
            .map(|(i, _)| i)
            .collect();
        hits.sort_by_key(|&i| (std::cmp::Reverse(self.rules[i].rule.priority), i));
        hits
    }

    fn is_protected_rule(&self, id: &str) -> bool {
        self.rules.iter().any(|r| r.id == id && r.rule.protected)
    }
}

// ---------------------------------------------------------------------------------------------------------
// Lineage, context
// ---------------------------------------------------------------------------------------------------------

/// Lineage journal entry (SPEC §6.2), stored by `oomtop-state`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct LineageEntry {
    pub id: ProcId,
    pub ppid: Option<u32>,
    pub group_id: String,
    pub group_kind: GroupKind,
    pub group_label: String,
    pub group_fingerprint: String,
    /// Hashed session id.
    pub session_id: Option<String>,
    /// true if spawned (directly or transitively) by an agent session or tool.
    pub spawned_by_agent: bool,
    pub first_seen_ms: u64,
    pub last_seen_ms: u64,
    pub last_active_ms: u64,
}

/// Inputs besides the snapshot.
#[derive(Debug, Clone, Copy)]
pub struct AttributionContext<'a> {
    pub rules: &'a CompiledRules,
    pub lineage: &'a BTreeMap<ProcId, LineageEntry>,
    pub protect: &'a ProtectContext,
}

/// Lower-case, dash-separated slug.
pub fn slug(s: &str) -> String {
    let mut out = String::new();
    let mut dash = false;
    for c in s.chars() {
        if c.is_ascii_alphanumeric() {
            out.push(c.to_ascii_lowercase());
            dash = false;
        } else if !dash && !out.is_empty() {
            out.push('-');
            dash = true;
        }
    }
    while out.ends_with('-') {
        out.pop();
    }
    out
}

// ---------------------------------------------------------------------------------------------------------
// Process classification (terminals, shells, subreapers, app bundles)
// ---------------------------------------------------------------------------------------------------------

const SHELLS: &[&str] = &[
    "sh", "bash", "zsh", "fish", "dash", "ksh", "mksh", "oksh", "loksh", "tcsh", "csh", "ash", "yash", "nu",
    "elvish", "xonsh", "pwsh",
];

/// Terminal emulators, multiplexers and remote-login daemons (process / executable names).
const TERMINALS: &[&str] = &[
    "Terminal",
    "iTerm2",
    "iTerm",
    "ghostty",
    "Ghostty",
    "kitty",
    "alacritty",
    "Alacritty",
    "wezterm",
    "wezterm-gui",
    "wezterm-mux-server",
    "WezTerm",
    "Hyper",
    "Tabby",
    "rio",
    "gnome-terminal-server",
    "gnome-terminal-",
    "gnome-terminal",
    "kgx",
    "ptyxis",
    "ptyxis-agent",
    "konsole",
    "xterm",
    "uxterm",
    "urxvt",
    "rxvt",
    "foot",
    "footclient",
    "tilix",
    "terminator",
    "xfce4-terminal",
    "lxterminal",
    "mate-terminal",
    "qterminal",
    "st",
    "contour",
    "tmux",
    "tmux: server",
    "screen",
    "SCREEN",
    "zellij",
    "dtach",
    "abduco",
    "sshd",
    "sshd-session",
    "login",
    "mosh-server",
];

/// macOS terminal app bundle names (the part before `.app/`).
const TERMINAL_APPS: &[&str] = &[
    "Terminal",
    "iTerm",
    "iTerm2",
    "Ghostty",
    "kitty",
    "Alacritty",
    "WezTerm",
    "Warp",
    "Hyper",
    "Tabby",
    "Rio",
];

/// Launchers that exec a command and stay around as its parent.
const TRANSPARENT: &[&str] = &[
    "sudo",
    "doas",
    "su",
    "caffeinate",
    "script",
    "nohup",
    "timeout",
    "nice",
    "ionice",
    "taskpolicy",
];

/// Process reapers: their children are top-level processes, never their members.
const SUBREAPERS: &[&str] = &["launchd", "systemd", "init"];

fn names_of(p: &Process) -> [&str; 3] {
    [
        p.name.trim_start_matches('-'),
        basename(&p.exe),
        p.cmdline
            .first()
            .map(|a| basename(a).trim_start_matches('-'))
            .unwrap_or(""),
    ]
}

fn name_in(p: &Process, list: &[&str]) -> bool {
    names_of(p).iter().any(|n| !n.is_empty() && list.contains(n))
}

/// Bundle markers in an executable path. Chrome's updater runs the app from a temporary
/// `…/code_sign_clone/…/Google Chrome.app.bundle/Contents/MacOS/Google Chrome` copy.
const BUNDLE_MARKERS: [&str; 2] = [".app/", ".app.bundle/"];

fn bundle_in(path: &str) -> Option<&str> {
    let i = BUNDLE_MARKERS.iter().filter_map(|m| path.find(m)).min()?;
    let name = basename(&path[..i]);
    (!name.is_empty()).then_some(name)
}

/// The outermost `.app` bundle name of the executable (`Google Chrome` for a Chrome helper). Falls back
/// to `argv[0]` when the executable runs from a non-bundle copy.
pub fn app_bundle_name(p: &Process) -> Option<&str> {
    bundle_in(&p.exe).or_else(|| p.cmdline.first().and_then(|a| bundle_in(a)))
}

/// True for the main executable of an app bundle (`X.app/Contents/MacOS/X`), not a nested helper.
fn is_app_main(p: &Process) -> bool {
    let n: usize = BUNDLE_MARKERS.iter().map(|m| p.exe.matches(m).count()).sum();
    n == 1
        && BUNDLE_MARKERS
            .iter()
            .any(|m| p.exe.contains(&format!("{m}Contents/MacOS/")))
}

/// Terminal emulators, multiplexers, sshd / login.
pub fn is_terminal(p: &Process) -> bool {
    name_in(p, TERMINALS)
        || (is_app_main(p)
            && app_bundle_name(p)
                .map(|a| TERMINAL_APPS.contains(&a))
                .unwrap_or(false))
}

/// Any shell process (interactive or not).
pub fn is_shell(p: &Process) -> bool {
    name_in(p, SHELLS)
}

/// A shell waiting for user commands: no `-c`, no script argument (only flags such as `-l`, `-i`).
pub fn is_interactive_shell(p: &Process) -> bool {
    if !is_shell(p) {
        return false;
    }
    p.cmdline.iter().skip(1).all(|a| {
        if a == "-c" || a == "-s" || !a.starts_with('-') {
            return false;
        }
        // short flag clusters such as `-lc`
        !(a.len() > 1 && !a.starts_with("--") && a[1..].contains('c'))
    })
}

fn is_subreaper(p: &Process) -> bool {
    p.id.pid <= 1 || name_in(p, SUBREAPERS)
}

/// A process whose children start their own groups (unless it sits in a rule-defined group).
pub fn is_boundary(p: &Process) -> bool {
    is_terminal(p) || is_interactive_shell(p) || name_in(p, TRANSPARENT)
}

/// Virtualization.framework guest processes: host footprint under-counts them (SPEC §5).
pub fn is_vm_lower_bound(p: &Process) -> bool {
    p.name.contains("com.apple.Virtualization.VirtualMachine")
        || p.exe.contains("com.apple.Virtualization.VirtualMachine")
}

/// Heuristic kind + label for a top-level process with no rule.
pub fn heuristic_kind_label(p: &Process) -> (GroupKind, String) {
    if let Some(app) = app_bundle_name(p) {
        return (GroupKind::App, app.to_string());
    }
    let exe = p.exe.as_str();
    let system_prefixes = [
        "/System/",
        "/usr/libexec/",
        "/usr/sbin/",
        "/sbin/",
        "/usr/lib/systemd/",
        "/lib/systemd/",
    ];
    let short = if p.name.is_empty() {
        basename(exe).to_string()
    } else {
        p.name.clone()
    };
    // Terminals are user apps even when installed under /usr/libexec (gnome-terminal-server): commands
    // typed into them need a non-system owner.
    let system_path = system_prefixes.iter().any(|pre| exe.starts_with(pre)) && !is_terminal(p);
    if system_path || p.uid == Some(0) || p.id.pid <= 1 {
        return (GroupKind::System, short);
    }
    // Interpreted programs are named after what they run ("studio.py", "@scope/pkg", "GradleDaemon").
    let head = fingerprint::template_head(p);
    let label = if head.is_empty() || head.starts_with('<') || head.contains(" -c") {
        short
    } else {
        head
    };
    (
        GroupKind::Other,
        if label.is_empty() {
            format!("pid {}", p.id.pid)
        } else {
            label
        },
    )
}

// ---------------------------------------------------------------------------------------------------------
// cgroups (Linux)
// ---------------------------------------------------------------------------------------------------------

/// What a Linux cgroup v2 path says about a process's owner.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum CgroupScope {
    /// Container runtime scope (docker, podman, containerd, cri-o, kubepods, lxc, nspawn). `id` ≤ 12 chars.
    Container { runtime: String, id: String },
    /// libvirt / QEMU machine scope.
    Vm { name: String },
    /// A systemd service unit; `system` = under `system.slice`.
    Service { unit: String, system: bool },
    /// A desktop app scope (`app-gnome-firefox-1234.scope`, `snap.firefox.firefox-….scope`).
    App { app: String },
}

fn unescape_systemd(s: &str) -> String {
    s.replace("\\x2d", "-").replace("\\x20", " ")
}

fn is_hex_id(s: &str) -> bool {
    s.len() >= 12 && s.bytes().all(|b| b.is_ascii_hexdigit())
}

fn short_id(s: &str) -> String {
    s.chars().take(12).collect()
}

fn strip_instance_suffix(s: &str) -> &str {
    // trailing "-<pid>" / "-<uuid>" / "-<hex>"
    let mut cur = s;
    loop {
        let Some((head, tail)) = cur.rsplit_once('-') else {
            return cur;
        };
        let instance = !tail.is_empty()
            && tail.bytes().all(|b| b.is_ascii_hexdigit())
            && (tail.bytes().any(|b| b.is_ascii_digit()));
        if instance && !head.is_empty() {
            cur = head;
        } else {
            return cur;
        }
    }
}

/// Parses a cgroup v2 path (as read from `/proc/<pid>/cgroup`, `0::` prefix optional).
pub fn parse_cgroup(path: &str) -> Option<CgroupScope> {
    let path = path.trim().trim_start_matches("0::");
    let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
    // Containers and VMs anywhere in the path.
    for (i, seg) in segs.iter().enumerate() {
        let seg = *seg;
        let scope = seg.strip_suffix(".scope");
        if let Some(s) = scope {
            for (prefix, runtime) in [
                ("docker-", "docker"),
                ("libpod-conmon-", "podman"),
                ("libpod-", "podman"),
                ("cri-containerd-", "containerd"),
                ("crio-conmon-", "cri-o"),
                ("crio-", "cri-o"),
                ("containerd-", "containerd"),
            ] {
                if let Some(id) = s.strip_prefix(prefix) {
                    if is_hex_id(id) {
                        return Some(CgroupScope::Container {
                            runtime: runtime.into(),
                            id: short_id(id),
                        });
                    }
                }
            }
            if let Some(m) = s.strip_prefix("machine-") {
                let m = unescape_systemd(m);
                if let Some(rest) = m.strip_prefix("qemu-") {
                    // "qemu-<n>-<name>"
                    let name = rest.split_once('-').map(|(_, n)| n).unwrap_or(rest);
                    return Some(CgroupScope::Vm {
                        name: name.to_string(),
                    });
                }
                return Some(CgroupScope::Container {
                    runtime: "nspawn".into(),
                    id: m,
                });
            }
        }
        if let Some(name) = seg.strip_prefix("lxc.payload.") {
            return Some(CgroupScope::Container {
                runtime: "lxc".into(),
                id: name.to_string(),
            });
        }
        if (seg == "docker" || seg.starts_with("kubepods") || seg.starts_with("pod")) && i + 1 < segs.len() {
            let next = segs[i + 1];
            if is_hex_id(next) {
                let runtime = if seg == "docker" { "docker" } else { "kubernetes" };
                return Some(CgroupScope::Container {
                    runtime: runtime.into(),
                    id: short_id(next),
                });
            }
        }
    }
    let last = *segs.last()?;
    if last.ends_with("-spawn")
        || last.starts_with("vte-spawn-")
        || last.starts_with("tmux-spawn-")
        || last.starts_with("session-")
        || last == "init.scope"
    {
        return None;
    }
    if let Some(unit) = last.strip_suffix(".service") {
        if unit.starts_with("user@") || unit.is_empty() {
            return None;
        }
        let system = segs.first() == Some(&"system.slice");
        let unit = unescape_systemd(unit);
        let unit = unit.split('@').next().unwrap_or(&unit).to_string();
        return Some(CgroupScope::Service { unit, system });
    }
    let scope = last.strip_suffix(".scope")?;
    let raw = if let Some(rest) = scope.strip_prefix("app-") {
        let rest = unescape_systemd(rest);
        let rest = strip_instance_suffix(&rest).to_string();
        let rest = [
            "gnome-",
            "kde-",
            "xfce-",
            "flatpak-",
            "glib-",
            "dbus-:1.",
            "systemd-",
            "niri-",
            "sway-",
            "hyprland-",
        ]
        .iter()
        .find_map(|pre| rest.strip_prefix(pre).map(str::to_string))
        .unwrap_or(rest);
        rest
    } else {
        let rest = scope.strip_prefix("snap.")?;
        rest.split('.').next().unwrap_or(rest).to_string()
    };
    // reverse-DNS app ids → last component ("org.mozilla.firefox" → "firefox")
    let app = if raw.contains('.') && !raw.ends_with('.') {
        raw.rsplit('.').next().unwrap_or(&raw).to_string()
    } else {
        raw
    };
    if app.is_empty()
        || TERMINALS.contains(&app.as_str())
        || TERMINAL_APPS.contains(&app.as_str())
        || app.eq_ignore_ascii_case("terminal")
    {
        return None;
    }
    Some(CgroupScope::App { app })
}

/// Kubernetes QoS class, as encoded in the kubelet's cgroup layout (and `status.qosClass`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum QosClass {
    /// Pod cgroup directly under `kubepods` (requests = limits for every container).
    Guaranteed,
    #[default]
    Burstable,
    BestEffort,
}

impl QosClass {
    pub fn as_str(self) -> &'static str {
        match self {
            QosClass::Guaranteed => "Guaranteed",
            QosClass::Burstable => "Burstable",
            QosClass::BestEffort => "BestEffort",
        }
    }

    /// `status.qosClass` spelling ("Guaranteed", "Burstable", "BestEffort"), case-insensitive.
    pub fn parse(s: &str) -> Option<QosClass> {
        match s.to_ascii_lowercase().as_str() {
            "guaranteed" => Some(QosClass::Guaranteed),
            "burstable" => Some(QosClass::Burstable),
            "besteffort" => Some(QosClass::BestEffort),
            _ => None,
        }
    }
}

/// What a kubelet-managed cgroup path says (SPEC §11 "Local Kubernetes"): QoS class, pod UID and the
/// **full** container id, from the path alone. [`parse_cgroup`] keeps only a 12-character id for grouping;
/// this keeps everything the cluster tree needs.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct KubeCgroup {
    pub qos: QosClass,
    /// Pod UID with dashes (`systemd` driver paths spell them `_`).
    pub pod_uid: String,
    /// Full container id (64 hex for containerd / CRI-O / docker), `None` for the pod-level cgroup.
    pub container_id: Option<String>,
    /// `containerd` | `cri-o` | `docker` from the scope prefix; `None` for cgroupfs-driver paths (bare id).
    pub runtime: Option<String>,
    /// CRI-O's `crio-conmon-<id>.scope` (the monitor, not the container itself).
    pub conmon: bool,
    /// Path of the pod cgroup (`…/kubepods-burstable-pod<uid>.slice` or `…/pod<uid>`).
    pub pod_cgroup: String,
    /// Path of the container cgroup, when the path goes below the pod.
    pub container_cgroup: Option<String>,
    /// Everything before the `kubepods` segment: empty on a node that is this host; a container scope
    /// (`/system.slice/docker-<id>.scope/kubelet.slice`) for kind / k3d / minikube nodes seen from the host.
    pub node_prefix: String,
}

fn is_uid_like(s: &str) -> bool {
    (32..=40).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_hexdigit() || b == b'-' || b == b'_')
}

/// `pod<uid>` / `kubepods[-<qos>]-pod<uid>.slice` / `kubelet-kubepods-<qos>-pod<uid>.slice` → uid.
fn pod_uid_of(seg: &str) -> Option<String> {
    let s = seg.strip_suffix(".slice").unwrap_or(seg);
    let idx = s.rfind("pod")?;
    let head = &s[..idx];
    if !(head.is_empty() || head.ends_with('-')) {
        return None;
    }
    let uid = &s[idx + 3..];
    is_uid_like(uid).then(|| uid.replace('_', "-"))
}

/// QoS from a `kubepods…` segment: `burstable` / `besteffort` anywhere in it.
fn qos_of(seg: &str) -> Option<QosClass> {
    let s = seg.to_ascii_lowercase();
    if s.contains("besteffort") {
        Some(QosClass::BestEffort)
    } else if s.contains("burstable") {
        Some(QosClass::Burstable)
    } else {
        None
    }
}

/// Container scope below a pod: `cri-containerd-<id>.scope`, `crio-<id>.scope`, `crio-conmon-<id>.scope`,
/// `docker-<id>.scope`, or a bare 64-hex id (cgroupfs driver). → (id, runtime, conmon)
fn container_of(seg: &str) -> Option<(String, Option<String>, bool)> {
    if let Some(s) = seg.strip_suffix(".scope") {
        for (prefix, runtime, conmon) in [
            ("cri-containerd-", "containerd", false),
            ("crio-conmon-", "cri-o", true),
            ("crio-", "cri-o", false),
            ("docker-", "docker", false),
            ("containerd-", "containerd", false),
        ] {
            if let Some(id) = s.strip_prefix(prefix) {
                return is_hex_id(id).then(|| (id.to_string(), Some(runtime.to_string()), conmon));
            }
        }
        return None;
    }
    // cgroupfs driver: the bare id; CRI-O cgroupfs writes "crio-<id>" without ".scope".
    if let Some(id) = seg.strip_prefix("crio-conmon-") {
        return is_hex_id(id).then(|| (id.to_string(), Some("cri-o".into()), true));
    }
    if let Some(id) = seg.strip_prefix("crio-") {
        return is_hex_id(id).then(|| (id.to_string(), Some("cri-o".into()), false));
    }
    is_hex_id(seg).then(|| (seg.to_string(), None, false))
}

/// Parses a kubelet-managed cgroup v2 path (cgroupfs and systemd drivers; containerd, CRI-O and
/// cri-dockerd scopes; nodes nested in a container such as kind / k3d / minikube). `None` when the path
/// is not below a `kubepods` cgroup with a pod segment.
pub fn parse_kube_cgroup(path: &str) -> Option<KubeCgroup> {
    let path = path.trim().trim_start_matches("0::");
    let segs: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
    // The first segment naming kubepods (`kubepods`, `kubepods.slice`, `kubelet-kubepods.slice`).
    let start = segs.iter().position(|s| {
        let s = s.strip_suffix(".slice").unwrap_or(s);
        s == "kubepods" || s.ends_with("-kubepods") || s.starts_with("kubepods")
    })?;
    let mut qos = QosClass::Guaranteed;
    let mut i = start;
    let mut pod: Option<(usize, String)> = None;
    while i < segs.len() {
        let seg = segs[i];
        if let Some(uid) = pod_uid_of(seg) {
            if let Some(q) = qos_of(seg) {
                qos = q;
            }
            pod = Some((i, uid));
            break;
        }
        if let Some(q) = qos_of(seg) {
            qos = q;
        } else if i > start && !seg.contains("kubepods") {
            return None;
        }
        i += 1;
    }
    let (pi, pod_uid) = pod?;
    let join = |n: usize| format!("/{}", segs[..n].join("/"));
    let node_prefix = if start == 0 { String::new() } else { join(start) };
    let mut out = KubeCgroup {
        qos,
        pod_uid,
        pod_cgroup: join(pi + 1),
        node_prefix,
        ..Default::default()
    };
    if let Some(seg) = segs.get(pi + 1) {
        let (id, runtime, conmon) = container_of(seg)?;
        out.container_id = Some(id);
        out.runtime = runtime;
        out.conmon = conmon;
        out.container_cgroup = Some(join(pi + 2));
    }
    Some(out)
}

// ---------------------------------------------------------------------------------------------------------
// Builder
// ---------------------------------------------------------------------------------------------------------

#[derive(Debug, Clone, Copy)]
struct Slot {
    group: usize,
    via: AttributionSignal,
    confidence: Confidence,
}

#[derive(Debug, Clone, Default)]
struct Meta {
    /// Rule/adapter/cgroup/self groups keep shell-launched descendants.
    sticky: bool,
    /// Root is a terminal: never a responsible-pid owner.
    launcher_root: bool,
}

#[derive(Debug, Clone)]
struct AdapterHint {
    key: String,
    kind: GroupKind,
    label: String,
    matched_by: String,
}

fn model_server_label(k: ModelServerKind) -> &'static str {
    match k {
        ModelServerKind::Ollama => "Ollama",
        ModelServerKind::LlamaCpp => "llama.cpp server",
        ModelServerKind::SdCpp => "sd-server",
        ModelServerKind::Vllm => "vLLM",
        ModelServerKind::LmStudio => "LM Studio",
        ModelServerKind::Mlx => "MLX-LM server",
        ModelServerKind::Generic => "model server",
    }
}

/// Alias of a session: `<alias>:<first 12 hex of the hashed session id>`. It names the session in marker
/// lookups, in `owner_group` of orphans whose session is gone, and in journals written before session
/// groups were keyed by root pid; a live session's group id is `agent:<rule-id>:<root pid>`. A session id that is not
/// hash-shaped (e.g. from an old journal or a hand-made fixture) is hashed first, so a raw id never becomes
/// part of an exported id and slicing never splits a multi-byte character.
fn session_group_key(kind: GroupKind, sid: &str) -> String {
    let hashed = sid.len() >= 12 && sid.bytes().all(|b| b.is_ascii_hexdigit());
    let h: String = if hashed {
        sid.chars().take(12).collect()
    } else {
        crate::redact::hash_marker(sid).chars().take(12).collect()
    };
    format!("{}:{h}", kind.alias())
}

struct Builder<'a> {
    snap: &'a Snapshot,
    rules: &'a CompiledRules,
    lineage: &'a BTreeMap<ProcId, LineageEntry>,
    by_pid: HashMap<u32, usize>,
    by_id: HashMap<ProcId, usize>,
    groups: Vec<Group>,
    meta: Vec<Meta>,
    key_to_group: HashMap<String, usize>,
    assigned: Vec<Option<Slot>>,
    visiting: Vec<bool>,
    root_rule: Vec<Option<usize>>,
    /// Session id of each session-keyed rule root.
    root_sid: Vec<Option<String>>,
    adapter: Vec<Option<AdapterHint>>,
    /// Session aliases ([`session_group_key`]) → index of the live rule root of that session.
    live_sessions: HashMap<String, usize>,
    /// oomtop's own uid: label-keyed app groups of other (non-root) users get a `@u<uid>` suffix, so
    /// another logged-in user's Chrome never merges with ours (fast user switching).
    self_uid: Option<u32>,
}

impl<'a> Builder<'a> {
    /// `""`, or `@u<uid>` for a process of another non-root user.
    fn user_suffix(&self, p: &Process) -> String {
        match (p.uid, self.self_uid) {
            (Some(u), Some(me)) if u != me && u != 0 => format!("@u{u}"),
            _ => String::new(),
        }
    }

    fn proc(&self, i: usize) -> &'a Process {
        &self.snap.processes[i]
    }

    fn proc_by_id(&self, id: ProcId) -> Option<&'a Process> {
        self.by_id.get(&id).map(|&i| &self.snap.processes[i])
    }

    fn ensure_group(&mut self, key: &str, kind: GroupKind, label: &str, root: Option<ProcId>) -> usize {
        if let Some(&i) = self.key_to_group.get(key) {
            if self.groups[i].root.is_none() {
                self.groups[i].root = root;
            }
            return i;
        }
        let i = self.groups.len();
        self.groups.push(Group {
            id: key.to_string(),
            kind,
            label: label.to_string(),
            root,
            ..Default::default()
        });
        self.meta.push(Meta::default());
        self.key_to_group.insert(key.to_string(), i);
        i
    }

    fn set_root_meta(&mut self, g: usize) {
        let root = self.groups[g].root.and_then(|r| self.proc_by_id(r));
        self.meta[g].launcher_root = root.map(is_terminal).unwrap_or(false);
    }

    /// Index of the live parent (not a subreaper, not a reused pid).
    fn parent_index(&self, i: usize) -> Option<usize> {
        let p = self.proc(i);
        let pp = p.ppid.filter(|&pp| pp > 1 && pp != p.id.pid)?;
        let pi = *self.by_pid.get(&pp)?;
        let parent = self.proc(pi);
        if pi == i || is_subreaper(parent) {
            return None;
        }
        if parent.id.start_time > 0 && p.id.start_time > 0 && parent.id.start_time > p.id.start_time {
            return None; // pid reused after our real parent exited
        }
        Some(pi)
    }

    fn resolve(&mut self, i: usize, depth: usize) -> Option<usize> {
        if let Some(s) = self.assigned[i] {
            return Some(s.group);
        }
        if self.visiting[i] || depth > MAX_DEPTH {
            return None;
        }
        self.visiting[i] = true;
        let slot = self.decide(i, depth);
        self.visiting[i] = false;
        self.assigned[i] = Some(slot);
        Some(slot.group)
    }

    /// Session aliases the process's markers name, best rule first: `(alias, rule index)` for every
    /// marker-matching rule with a `session_key` whose own id the process carries.
    fn marker_sessions(&self, i: usize) -> Vec<(String, usize)> {
        let p = self.proc(i);
        if p.markers.session_id.is_none() {
            return Vec::new();
        }
        self.rules
            .match_markers(p)
            .into_iter()
            .filter_map(|ri| {
                let rule = &self.rules.rules[ri].rule;
                let sid = crate::redact::session_id_for_key(&p.markers, rule.session_env_key()?)?;
                Some((session_group_key(rule.kind, sid), ri))
            })
            .collect()
    }

    /// The group of the live session with this alias, if its root is in the snapshot.
    fn session_group(&mut self, alias: &str, depth: usize) -> Option<usize> {
        let root = *self.live_sessions.get(alias)?;
        self.resolve(root, depth + 1)
    }

    fn decide(&mut self, i: usize, depth: usize) -> Slot {
        let p = self.proc(i);

        // 0. oomtop itself
        if Some(p.id.pid) == self.snap.self_pid {
            if let Some(pg) = self.parent_index(i).and_then(|pi| self.resolve(pi, depth + 1)) {
                if self.groups[pg].kind == GroupKind::AgentSession {
                    return Slot {
                        group: pg,
                        via: AttributionSignal::Ancestry,
                        confidence: Confidence::High,
                    };
                }
            }
            let g = self.ensure_group(SELF_GROUP_ID, GroupKind::Other, "oomtop", Some(p.id));
            self.groups[g].matched_by = Some("self".into());
            self.meta[g].sticky = true;
            return Slot {
                group: g,
                via: AttributionSignal::Rule,
                confidence: Confidence::High,
            };
        }

        // 1. adapter truth (rule roots keep their rule key so ids stay stable with/without adapter data)
        if self.root_rule[i].is_none() {
            if let Some(h) = self.adapter[i].clone() {
                let g = self.ensure_group(&h.key, h.kind, &h.label, Some(p.id));
                self.groups[g].matched_by.get_or_insert(h.matched_by);
                self.meta[g].sticky = true;
                return Slot {
                    group: g,
                    via: AttributionSignal::Adapter,
                    confidence: Confidence::High,
                };
            }
        }

        // 2. container / VM cgroup
        if let Some(scope) = p.cgroup.as_deref().and_then(parse_cgroup) {
            let hit = match scope {
                CgroupScope::Container { runtime, id } => Some((
                    format!("sandbox:{runtime}-{}", slug(&id)),
                    format!("{runtime} {id}"),
                    format!("cgroup:{runtime}"),
                )),
                CgroupScope::Vm { name } => Some((
                    format!("sandbox:vm-{}", slug(&name)),
                    format!("VM {name}"),
                    "cgroup:machine".to_string(),
                )),
                _ => None,
            };
            if let Some((key, label, by)) = hit {
                let g = self.ensure_group(&key, GroupKind::Sandbox, &label, Some(p.id));
                self.groups[g].matched_by.get_or_insert(by);
                self.meta[g].sticky = true;
                return Slot {
                    group: g,
                    via: AttributionSignal::Cgroup,
                    confidence: Confidence::High,
                };
            }
        }

        // 3. rule root
        if let Some(r) = self.root_rule[i] {
            return self.rule_root(i, r, depth);
        }

        // 4. live session marker — unless the parent belongs to a different rule/adapter-defined group (a
        //    Gradle worker under its daemon, a model server's workers): those inherit the agent's env but
        //    are owned, and freed, by their own root.
        //    A process inside a nested agent carries the outer agent's id too: the session its parent
        //    already belongs to wins,
        let markers = self.marker_sessions(i);
        let mut marker: Option<String> = markers.first().map(|(k, _)| k.clone());
        if marker.is_some() {
            let parent = self.parent_index(i).and_then(|pi| self.resolve(pi, depth + 1));
            // …otherwise the innermost one: a nested session's root is younger than the outer one's.
            let mut session = None;
            let mut best_age = None;
            for (k, _) in &markers {
                let Some(root) = self.live_sessions.get(k).copied() else {
                    continue;
                };
                let Some(g) = self.session_group(k, depth) else {
                    continue;
                };
                let rp = self.proc(root);
                let age = (Some(g) == parent, rp.id.start_time, rp.id.pid);
                if best_age.is_none_or(|b| age > b) {
                    best_age = Some(age);
                    session = Some(g);
                    marker = Some(k.clone());
                }
            }
            let parent_group = parent.filter(|&pg| {
                let g = &self.groups[pg];
                self.meta[pg].sticky
                    && Some(pg) != session
                    && g.id != SELF_GROUP_ID
                    && g.kind != GroupKind::AgentSession
                    && g.kind != GroupKind::System
            });
            if let Some(pg) = parent_group {
                return Slot {
                    group: pg,
                    via: AttributionSignal::Ancestry,
                    confidence: Confidence::High,
                };
            }
            if let Some(g) = session {
                return Slot {
                    group: g,
                    via: AttributionSignal::Marker,
                    confidence: Confidence::High,
                };
            }
        }

        // 5. responsible pid (macOS)
        if let Some(g) = self.responsible_group(i, depth) {
            return Slot {
                group: g,
                via: AttributionSignal::Responsible,
                confidence: Confidence::High,
            };
        }

        // 6. ancestry
        if let Some(pi) = self.parent_index(i) {
            if let Some(pg) = self.resolve(pi, depth + 1) {
                let parent = self.proc(pi);
                // A command typed into a shell/terminal is its own root; terminal plumbing (login, shells,
                // tmux, sudo) stays with the terminal.
                if is_boundary(parent) && !self.meta[pg].sticky && !is_boundary(p) {
                    let owner =
                        (self.groups[pg].kind != GroupKind::System).then(|| self.groups[pg].id.clone());
                    return self.heuristic_root(i, owner);
                }
                let parent_high = self.assigned[pi]
                    .map(|s| s.confidence == Confidence::High)
                    .unwrap_or(false);
                return Slot {
                    group: pg,
                    via: AttributionSignal::Ancestry,
                    confidence: if parent_high {
                        Confidence::High
                    } else {
                        Confidence::Medium
                    },
                };
            }
        }

        // --- top-level from here on (parent exited, is a subreaper, or unknown) ---

        // 7. lineage journal
        if let Some(le) = self.lineage.get(&p.id).filter(|le| !le.group_id.is_empty()) {
            if reparented(p, le, self.snap, &self.by_pid) {
                // Once an orphan is its own root the journal records *that* group; its owner is then the
                // recorded session (or the marker's), never itself.
                let recorded_self = le.group_id == orphan_identity(p).2;
                let target = if recorded_self {
                    le.session_id
                        .as_deref()
                        .map(|sid| session_group_key(GroupKind::AgentSession, sid))
                        .or_else(|| marker.clone())
                } else {
                    Some(le.group_id.clone())
                };
                let agent = le.spawned_by_agent || p.markers.session_id.is_some();
                if let Some(t) = target {
                    // A session alias (old journals, `recorded_self`) resolves to the live session's group.
                    // A recorded group is alive only if its root predates this process (group keys contain
                    // pids; a younger root is a reused pid, not the group that spawned it).
                    // The recorded root may not have been resolved yet (`<alias>:<rule>:<pid>` names it).
                    let recorded_root = t
                        .rsplit_once(':')
                        .and_then(|(_, pid)| pid.parse::<u32>().ok())
                        .and_then(|pid| self.by_pid.get(&pid).copied())
                        .filter(|&k| k != i && self.root_rule[k].is_some());
                    if let Some(k) = recorded_root {
                        self.resolve(k, depth + 1);
                    }
                    let live = self.session_group(&t, depth).or_else(|| {
                        self.key_to_group.get(&t).copied().filter(|&g| {
                            self.groups[g]
                                .root
                                .and_then(|r| self.proc_by_id(r))
                                .map(|r| r.id.start_time <= p.id.start_time)
                                .unwrap_or(false)
                        })
                    });
                    if let Some(g) = live {
                        return Slot {
                            group: g,
                            via: AttributionSignal::Lineage,
                            confidence: Confidence::Medium,
                        };
                    }
                    return self.orphan_root(i, Some(t), AttributionSignal::Lineage, agent);
                }
                if agent {
                    return self.orphan_root(i, None, AttributionSignal::Lineage, true);
                }
            }
        }

        // 8. marker of a session whose root has exited
        if let Some(key) = marker {
            return self.orphan_root(i, Some(key), AttributionSignal::Marker, true);
        }

        // 9. systemd unit / desktop app scope
        if let Some(scope) = p.cgroup.as_deref().and_then(parse_cgroup) {
            let hit = match scope {
                CgroupScope::Service { unit, system } => {
                    let kind = if system || p.uid == Some(0) {
                        GroupKind::System
                    } else {
                        GroupKind::Other
                    };
                    Some((format!("{}:{}", kind.alias(), slug(&unit)), kind, unit))
                }
                CgroupScope::App { app } => Some((format!("app:{}", slug(&app)), GroupKind::App, app)),
                _ => None,
            };
            if let Some((key, kind, label)) = hit {
                let g = self.ensure_group(&key, kind, &label, Some(p.id));
                self.groups[g]
                    .matched_by
                    .get_or_insert_with(|| "cgroup:unit".into());
                self.set_root_meta(g);
                return Slot {
                    group: g,
                    via: AttributionSignal::Cgroup,
                    confidence: Confidence::Medium,
                };
            }
        }

        // 10. heuristic top-level root
        self.heuristic_root(i, None)
    }

    fn rule_root(&mut self, i: usize, r: usize, depth: usize) -> Slot {
        let p = self.proc(i);
        let cr = &self.rules.rules[r];
        let (kind, label, rid) = (cr.rule.kind, cr.rule.label.clone(), cr.id.clone());
        // The key never depends on the session id: a session is `agent:<rule>:<pid>` whether or not a
        // marker-carrying descendant is running right now (its id is stable for the life of the root).
        let key = match kind {
            // apps and system components are one group per label (all Firefox processes are "Firefox")
            GroupKind::App => format!("app:{}{}", slug(&label), self.user_suffix(p)),
            GroupKind::System => format!("{}:{}", kind.alias(), slug(&label)),
            _ => format!("{}:{}:{}", kind.alias(), rid, p.id.pid),
        };
        let via = if self.adapter[i].is_some() {
            AttributionSignal::Adapter
        } else {
            AttributionSignal::Rule
        };
        let pi = self.parent_index(i);
        let pg = pi.and_then(|pi| self.resolve(pi, depth + 1));
        if let Some(pg) = pg {
            let g = &self.groups[pg];
            // A same-rule root under a group of that rule is part of it (`ollama serve` → runner), unless
            // it is known to be a session of its own: a nested agent CLI whose children carry another id.
            let sid = self.root_sid[i].as_ref();
            let parent_sid = g
                .root
                .and_then(|r| self.by_id.get(&r))
                .and_then(|&ri| self.root_sid[ri].as_ref());
            if g.matched_by.as_deref() == Some(rid.as_str())
                && g.kind == kind
                && (sid.is_none() || sid == parent_sid)
            {
                return Slot {
                    group: pg,
                    via: AttributionSignal::Ancestry,
                    confidence: Confidence::High,
                };
            }
        }
        // A root that carries the id of a live session rooted elsewhere (an agent CLI the session started
        // and that was re-parented to launchd) is part of that session, like any other marker carrier.
        if let Some(sid) = &self.root_sid[i] {
            let alias = session_group_key(kind, sid);
            if self.live_sessions.get(&alias).is_some_and(|&j| j != i) {
                if let Some(sg) = self.session_group(&alias, depth) {
                    return Slot {
                        group: sg,
                        via: AttributionSignal::Marker,
                        confidence: Confidence::High,
                    };
                }
            }
        }
        let g = self.ensure_group(&key, kind, &label, Some(p.id));
        {
            let grp = &mut self.groups[g];
            grp.kind = kind;
            grp.label = label;
            grp.matched_by = Some(rid);
            if grp.root.is_none() {
                grp.root = Some(p.id);
            }
        }
        self.meta[g].sticky = true;
        self.set_root_meta(g);
        if self.groups[g].owner_group.is_none() {
            // the group it was launched from (a terminal, an IDE, another session) — never a system component
            let parent_owner = match pg {
                Some(pg) if pg != g && self.groups[pg].kind != GroupKind::System => {
                    Some(self.groups[pg].id.clone())
                }
                _ => None,
            };
            // the session whose marker it carries: the live session's group, else the (dead) session alias
            let marker_owner = match self.marker_sessions(i).into_iter().next() {
                Some((alias, _)) => match self.live_sessions.get(&alias).copied() {
                    Some(r) if r == i => None,
                    Some(_) => self
                        .session_group(&alias, depth)
                        .filter(|&og| og != g)
                        .map(|og| self.groups[og].id.clone()),
                    None => Some(alias),
                },
                None => None,
            };
            let owner = parent_owner.or(marker_owner).or_else(|| {
                self.lineage
                    .get(&p.id)
                    .map(|le| le.group_id.clone())
                    .filter(|id| !id.is_empty() && *id != key)
            });
            self.groups[g].owner_group = owner;
        }
        Slot {
            group: g,
            via,
            confidence: Confidence::High,
        }
    }

    fn responsible_group(&mut self, i: usize, depth: usize) -> Option<usize> {
        let p = self.proc(i);
        let rp = p.responsible_pid.filter(|&rp| rp != p.id.pid && rp > 1)?;
        let ri = *self.by_pid.get(&rp)?;
        let resp = self.proc(ri);
        if ri == i || is_terminal(resp) || is_shell(resp) || is_subreaper(resp) {
            return None;
        }
        // Launched from a shell or terminal before reaching the responsible app? Then ancestry decides.
        let mut cur = self.parent_index(i);
        let mut hops = 0;
        while let Some(ci) = cur {
            if ci == ri {
                break;
            }
            if is_boundary(self.proc(ci)) || hops > 64 {
                return None;
            }
            hops += 1;
            cur = self.parent_index(ci);
        }
        let g = self.resolve(ri, depth + 1)?;
        (!self.meta[g].launcher_root).then_some(g)
    }

    /// A top-level root for process `i` (apps merge by bundle name, system daemons by name).
    fn heuristic_root(&mut self, i: usize, owner: Option<String>) -> Slot {
        let p = self.proc(i);
        let (kind, base) = self.rules.heuristic_kind_label(p);
        let suffix = self.user_suffix(p);
        let label = if kind == GroupKind::App && !suffix.is_empty() {
            // Another user's copy of an app: say so. By uid, like the `@u<uid>` suffix of the id: it is always
            // known and ASCII (the name, when the OS gave one, is `Process.user` and is exported as it is).
            format!("{base} (uid {})", p.uid.unwrap_or_default())
        } else {
            base.clone()
        };
        let key = match kind {
            GroupKind::App => format!("app:{}{suffix}", slug(&base)),
            GroupKind::System => format!("system:{}", slug(&label)),
            _ => format!("{}:{}:{}", kind.alias(), slug(&label), p.id.pid),
        };
        let g = self.ensure_group(&key, kind, &label, Some(p.id));
        // Prefer the app's main executable as the root (actions quit the app, never a helper).
        if kind == GroupKind::App && is_app_main(p) {
            let cur = self.groups[g].root.and_then(|r| self.proc_by_id(r));
            if cur.map(|c| !is_app_main(c)).unwrap_or(true) {
                self.groups[g].root = Some(p.id);
            }
        }
        if self.groups[g].owner_group.is_none() {
            self.groups[g].owner_group = owner;
        }
        self.set_root_meta(g);
        Slot {
            group: g,
            via: AttributionSignal::Heuristic,
            confidence: Confidence::Low,
        }
    }

    /// Orphan roots are their own groups (never merged into an app by name) owned by the exited group.
    /// `agent_spawned` sets the preliminary `orphan` flag (the age rule is applied by [`crate::idle`]).
    fn orphan_root(
        &mut self,
        i: usize,
        owner: Option<String>,
        via: AttributionSignal,
        agent_spawned: bool,
    ) -> Slot {
        let p = self.proc(i);
        let (kind, label, key) = orphan_identity(p);
        let g = self.ensure_group(&key, kind, &label, Some(p.id));
        self.groups[g].owner_group = owner.filter(|o| *o != key);
        self.groups[g].orphan = agent_spawned;
        self.meta[g].sticky = true;
        self.set_root_meta(g);
        Slot {
            group: g,
            via,
            confidence: Confidence::Medium,
        }
    }
}

/// Kind, label and group key of a process that is (or would be) an orphan root: its own group, keyed by pid
/// (orphans are never merged into an app group by name).
fn orphan_identity(p: &Process) -> (GroupKind, String, String) {
    let (kind, label) = heuristic_kind_label(p);
    let kind = if kind == GroupKind::System {
        GroupKind::Other
    } else {
        kind
    };
    let key = format!("{}:{}:{}", kind.alias(), slug(&label), p.id.pid);
    (kind, label, key)
}

/// True if a process was re-parented since the journal recorded it: its recorded parent (> 1) is gone
/// (the ppid changed to 1 / a subreaper, or the recorded pid now belongs to a younger process).
fn reparented(p: &Process, le: &LineageEntry, s: &Snapshot, by_pid: &HashMap<u32, usize>) -> bool {
    let Some(orig) = le.ppid.filter(|&pp| pp > 1) else {
        return false;
    };
    let parent = |pid: u32| by_pid.get(&pid).map(|&i| &s.processes[i]);
    let orig_alive = parent(orig)
        .map(|pp| pp.id.start_time <= p.id.start_time)
        .unwrap_or(false);
    if p.ppid == Some(orig) {
        return !orig_alive;
    }
    match p.ppid {
        None | Some(0) | Some(1) => true,
        Some(now) => parent(now).map(is_subreaper).unwrap_or(true),
    }
}

/// Session ids for session-keyed rule roots: from the earliest marker-carrying descendant whose nearest
/// rule-root ancestor is this root, else the root's own marker when no ancestor runs the same rule (a
/// nested agent inherits its parent's marker, which is not its own session).
fn session_ids(
    s: &Snapshot,
    rules: &CompiledRules,
    root_rule: &[Option<usize>],
    by_pid: &HashMap<u32, usize>,
) -> Vec<Option<String>> {
    let n = s.processes.len();
    let mut best: Vec<Option<(u64, u32, String)>> = vec![None; n];
    let parent_of = |i: usize| -> Option<usize> {
        let p = &s.processes[i];
        let pp = p.ppid.filter(|&pp| pp > 1 && pp != p.id.pid)?;
        let pi = *by_pid.get(&pp)?;
        (pi != i && !is_subreaper(&s.processes[pi])).then_some(pi)
    };
    for (ci, c) in s.processes.iter().enumerate() {
        if c.markers.session_id.is_none() {
            continue;
        }
        let mut cur = parent_of(ci);
        let mut hops = 0;
        while let Some(k) = cur {
            if hops > 64 {
                break;
            }
            if let Some(r) = root_rule[k] {
                // the id of the rule's own key: a nested agent's children also carry the outer agent's id
                let sid = rules.rules[r]
                    .rule
                    .session_env_key()
                    .and_then(|key| crate::redact::session_id_for_key(&c.markers, key));
                {
                    if let Some(sid) = sid {
                        let cand = (c.id.start_time, c.id.pid, sid.to_string());
                        if best[k]
                            .as_ref()
                            .map(|b| (cand.0, cand.1) < (b.0, b.1))
                            .unwrap_or(true)
                        {
                            best[k] = Some(cand);
                        }
                    }
                }
                break;
            }
            hops += 1;
            cur = parent_of(k);
        }
    }
    (0..n)
        .map(|i| {
            let r = root_rule[i]?;
            let rule = &rules.rules[r].rule;
            let key = rule.session_env_key()?;
            if let Some((_, _, sid)) = &best[i] {
                return Some(sid.clone());
            }
            let p = &s.processes[i];
            let own = crate::redact::session_id_for_key(&p.markers, key)?.to_string();
            // nested under the same rule → the marker is the parent session's
            let mut cur = parent_of(i);
            let mut hops = 0;
            while let Some(k) = cur {
                if hops > 64 {
                    break;
                }
                if root_rule[k] == Some(r) {
                    return None;
                }
                hops += 1;
                cur = parent_of(k);
            }
            Some(own)
        })
        .collect()
}

fn adapter_hints(s: &Snapshot) -> HashMap<ProcId, AdapterHint> {
    let mut out = HashMap::new();
    for ms in &s.model_servers {
        let label = model_server_label(ms.kind);
        let id = if ms.id.is_empty() {
            slug(label)
        } else {
            slug(&ms.id)
        };
        for pid in &ms.pids {
            out.entry(*pid).or_insert_with(|| AdapterHint {
                key: format!("model:{id}"),
                kind: GroupKind::ModelServer,
                label: label.to_string(),
                matched_by: format!("adapter:{}", ms.id),
            });
        }
    }
    for sb in &s.sandboxes {
        // App-owned VMs (Claude desktop, Docker Desktop) belong to their app via the responsible pid.
        if sb.kind == SandboxKind::Vm && sb.runtime.to_ascii_lowercase().contains("virtualization") {
            continue;
        }
        let label = if sb.label.is_empty() {
            sb.runtime.clone()
        } else {
            sb.label.clone()
        };
        for pid in &sb.host_pids {
            out.entry(*pid).or_insert_with(|| AdapterHint {
                key: format!("sandbox:{}", slug(&sb.id)),
                kind: GroupKind::Sandbox,
                label: label.clone(),
                matched_by: format!("adapter:{}", sb.runtime),
            });
        }
    }
    out
}

/// oomtop's own pid plus all its descendants.
fn self_tree(s: &Snapshot) -> HashSet<ProcId> {
    let mut out = HashSet::new();
    let Some(me) = s.self_pid.and_then(|pid| s.process_by_pid(pid)) else {
        return out;
    };
    let mut children: HashMap<u32, Vec<&Process>> = HashMap::new();
    for p in &s.processes {
        if let Some(pp) = p.ppid {
            children.entry(pp).or_default().push(p);
        }
    }
    let mut stack = vec![me];
    while let Some(p) = stack.pop() {
        if !out.insert(p.id) || out.len() > 4096 {
            continue;
        }
        if let Some(kids) = children.get(&p.id.pid) {
            stack.extend(
                kids.iter()
                    .filter(|k| k.id.start_time >= p.id.start_time)
                    .copied(),
            );
        }
    }
    out
}

/// Groups all processes of the snapshot. Totals, reclaim gain, fingerprint, protection, `lower_bound` and
/// `owner_group` are filled; `orphan` is a preliminary flag (agent-spawned root whose spawning group is gone)
/// that [`crate::idle::IdleTracker::apply`] re-decides with the age rule, together with `idle` / `idle_for_s`.
pub fn attribute(snapshot: &Snapshot, ctx: &AttributionContext<'_>) -> Vec<Group> {
    let n = snapshot.processes.len();
    // pid → index of the newest process with that pid (pid reuse inside one listing keeps both entries).
    let mut by_pid: HashMap<u32, usize> = HashMap::with_capacity(n);
    for (i, p) in snapshot.processes.iter().enumerate() {
        match by_pid.get(&p.id.pid) {
            Some(&j) if snapshot.processes[j].id.start_time >= p.id.start_time => {}
            _ => {
                by_pid.insert(p.id.pid, i);
            }
        }
    }
    let by_id: HashMap<ProcId, usize> = snapshot
        .processes
        .iter()
        .enumerate()
        .map(|(i, p)| (p.id, i))
        .collect();
    let root_rule: Vec<Option<usize>> = snapshot
        .processes
        .iter()
        .map(|p| ctx.rules.match_root(p).map(|m| m.index))
        .collect();
    let root_sid = session_ids(snapshot, ctx.rules, &root_rule, &by_pid);
    // Session alias → its root. When several roots share a session id (a nested same-rule root whose
    // children carry the id), the oldest one is the session.
    let mut live_sessions: HashMap<String, usize> = HashMap::new();
    for (i, (r, sid)) in root_rule.iter().zip(&root_sid).enumerate() {
        let (Some(r), Some(sid)) = (r, sid) else { continue };
        let alias = session_group_key(ctx.rules.rules[*r].rule.kind, sid);
        let age = |k: usize| (snapshot.processes[k].id.start_time, snapshot.processes[k].id.pid);
        match live_sessions.get(&alias) {
            Some(&j) if age(j) <= age(i) => {}
            _ => {
                live_sessions.insert(alias, i);
            }
        }
    }
    let hints = adapter_hints(snapshot);
    let adapter = snapshot
        .processes
        .iter()
        .map(|p| hints.get(&p.id).cloned())
        .collect();
    let mut b = Builder {
        snap: snapshot,
        rules: ctx.rules,
        lineage: ctx.lineage,
        by_pid,
        by_id: by_id.clone(),
        groups: Vec::new(),
        meta: Vec::new(),
        key_to_group: HashMap::new(),
        assigned: vec![None; n],
        visiting: vec![false; n],
        root_rule,
        root_sid,
        adapter,
        live_sessions,
        self_uid: ctx.protect.self_uid,
    };
    // Resolve in (start_time, pid) order so parents and group roots usually resolve first.
    let mut order: Vec<usize> = (0..n).collect();
    order.sort_by_key(|&i| (snapshot.processes[i].id.start_time, snapshot.processes[i].id.pid));
    for &i in &order {
        if b.resolve(i, 0).is_none() {
            // Unreachable in practice (resolve only fails inside a cycle); never leave a process out.
            let slot = b.heuristic_root(i, None);
            b.assigned[i] = Some(slot);
        }
    }
    let Builder {
        mut groups, assigned, ..
    } = b;
    for &i in &order {
        if let Some(s) = assigned[i] {
            groups[s.group].members.push(Member {
                id: snapshot.processes[i].id,
                confidence: s.confidence,
                via: s.via,
            });
        }
    }
    groups.retain(|g| !g.members.is_empty());
    let self_ids = self_tree(snapshot);
    for g in &mut groups {
        if g.root
            .map(|r| !g.members.iter().any(|m| m.id == r))
            .unwrap_or(true)
        {
            g.root = g.members.first().map(|m| m.id);
        }
        finish_group(g, snapshot, ctx, &self_ids, &by_id);
    }
    link_by_project(&mut groups, snapshot, &by_id);
    groups.sort_by(|a, b| {
        b.totals
            .footprint
            .value
            .unwrap_or(0)
            .cmp(&a.totals.footprint.value.unwrap_or(0))
            .then_with(|| a.id.cmp(&b.id))
    });
    groups
}

/// The per-sample numbers of a group — totals, swap gain, reclaim gain — from its member processes.
fn group_numbers<'a>(
    g: &mut Group,
    members: &[&Process],
    self_ids: &HashSet<ProcId>,
    reclaim_model: &crate::headroom::ReclaimModel,
    lookup: impl Fn(ProcId) -> Option<&'a Process> + Copy,
) {
    let mut footprint = sum_bytes(
        members.iter().map(|p| &p.mem.footprint_or_pss),
        "Σ footprint_or_pss",
    );
    if g.lower_bound && footprint.value.is_some() {
        footprint = footprint.into_estimate();
        footprint.source = "Σ footprint_or_pss (lower bound: VM memory under-counted)".into();
    }
    g.totals = GroupTotals {
        footprint,
        resident: sum_bytes(members.iter().map(|p| &p.mem.resident), "Σ resident"),
        gpu: sum_bytes(members.iter().map(|p| &p.mem.gpu), "Σ gpu"),
        swapped: sum_bytes(members.iter().map(|p| &p.mem.swapped), "Σ swapped"),
        cpu_pct: sum_f64(members.iter().map(|p| &p.cpu_pct), "Σ cpu"),
        process_count: members.len() as u32,
    };
    g.swap_gain = g.totals.swapped.clone().into_estimate();
    // An `oomtop mcp` child inside an agent session is not part of what stopping that session frees.
    if !g.is_self && g.members.iter().any(|m| self_ids.contains(&m.id)) {
        let mut others = g.clone();
        others.members.retain(|m| !self_ids.contains(&m.id));
        g.reclaim_gain = crate::headroom::group_reclaim_gain_by(&others, reclaim_model, lookup);
    } else {
        g.reclaim_gain = crate::headroom::group_reclaim_gain_by(g, reclaim_model, lookup);
    }
}

/// Signature of every input group **membership** depends on: each process's identity fields, parent,
/// responsible pid, uid and markers, the adapter truth (model servers, sandboxes), the lineage entries of
/// the listed processes (without their timestamps) and the protection context. Two samples with the same
/// signature attribute to the same groups; only the per-sample numbers differ (see [`refresh_numbers`]).
/// On a quiet machine the process set is unchanged between most refreshes, so a frontend can skip the
/// whole attribution (SPEC §14 CPU budget).
pub fn membership_signature(snapshot: &Snapshot, ctx: &AttributionContext<'_>) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut h = std::collections::hash_map::DefaultHasher::new();
    snapshot.host.os.hash(&mut h);
    snapshot.self_pid.hash(&mut h);
    snapshot.processes.len().hash(&mut h);
    for p in &snapshot.processes {
        p.id.hash(&mut h);
        p.ppid.hash(&mut h);
        p.responsible_pid.hash(&mut h);
        p.uid.hash(&mut h);
        identity_sig(p).hash(&mut h);
        p.markers.session_id.hash(&mut h);
        p.markers.agent.hash(&mut h);
        p.markers.keys.hash(&mut h);
        if let Some(le) = ctx.lineage.get(&p.id) {
            le.ppid.hash(&mut h);
            le.group_id.hash(&mut h);
            le.group_kind.hash(&mut h);
            le.group_label.hash(&mut h);
            le.group_fingerprint.hash(&mut h);
            le.session_id.hash(&mut h);
            le.spawned_by_agent.hash(&mut h);
        } else {
            0u8.hash(&mut h);
        }
    }
    for m in &snapshot.model_servers {
        m.id.hash(&mut h);
        m.kind.hash(&mut h);
        m.pids.hash(&mut h);
    }
    for b in &snapshot.sandboxes {
        b.id.hash(&mut h);
        b.kind.hash(&mut h);
        b.runtime.hash(&mut h);
        b.label.hash(&mut h);
        b.host_pids.hash(&mut h);
        b.footprint_lower_bound.hash(&mut h);
        b.configured_mem.value.hash(&mut h);
    }
    let pc = ctx.protect;
    pc.self_pid.hash(&mut h);
    pc.self_uid.hash(&mut h);
    pc.ancestor_pids.hash(&mut h);
    pc.protected_names.hash(&mut h);
    pc.caller_group.hash(&mut h);
    h.finish()
}

/// Recomputes the per-sample numbers (totals, swap gain, reclaim gain) of `groups` — the result of an
/// earlier [`attribute`] with the same [`membership_signature`] — from `snapshot`, and re-sorts them by
/// footprint like [`attribute`] does. Membership, ids, labels, fingerprints and flags are kept.
pub fn refresh_numbers(groups: &mut [Group], snapshot: &Snapshot) {
    let by_id: HashMap<ProcId, usize> = snapshot
        .processes
        .iter()
        .enumerate()
        .map(|(i, p)| (p.id, i))
        .collect();
    let lookup = |id: ProcId| by_id.get(&id).map(|&i| &snapshot.processes[i]);
    let self_ids = self_tree(snapshot);
    let model = crate::headroom::ReclaimModel::from_snapshot(snapshot);
    for g in groups.iter_mut() {
        let members: Vec<&Process> = g.members.iter().filter_map(|m| lookup(m.id)).collect();
        group_numbers(g, &members, &self_ids, &model, lookup);
    }
    groups.sort_by(|a, b| {
        b.totals
            .footprint
            .value
            .unwrap_or(0)
            .cmp(&a.totals.footprint.value.unwrap_or(0))
            .then_with(|| a.id.cmp(&b.id))
    });
}

fn finish_group(
    g: &mut Group,
    snapshot: &Snapshot,
    ctx: &AttributionContext<'_>,
    self_ids: &HashSet<ProcId>,
    by_id: &HashMap<ProcId, usize>,
) {
    let lookup = |id: ProcId| by_id.get(&id).map(|&i| &snapshot.processes[i]);
    // root first, then by start time (members were pushed in (start_time, pid) order)
    if let Some(r) = g.root {
        if let Some(pos) = g.members.iter().position(|m| m.id == r) {
            let m = g.members.remove(pos);
            g.members.insert(0, m);
        }
    }
    let members: Vec<&Process> = g.members.iter().filter_map(|m| lookup(m.id)).collect();
    let root = g.root.and_then(lookup);
    let reclaim_model = crate::headroom::ReclaimModel::from_snapshot(snapshot);

    // lower bound: Virtualization.framework guests, or an adapter-reported under-count
    let sandbox = snapshot
        .sandboxes
        .iter()
        .find(|sb| sb.footprint_lower_bound && g.members.iter().any(|m| sb.host_pids.contains(&m.id)));
    g.lower_bound = g.lower_bound || members.iter().any(|p| is_vm_lower_bound(p)) || sandbox.is_some();
    if g.configured_mem.is_none() {
        g.configured_mem = sandbox.and_then(|sb| sb.configured_mem.value);
    }

    g.is_self = g.id == SELF_GROUP_ID;
    group_numbers(g, &members, self_ids, &reclaim_model, lookup);

    // Group confidence = how sure we are about the root's identity.
    let root_member = g.root.and_then(|r| g.members.iter().find(|m| m.id == r));
    g.confidence = match root_member.map(|m| (m.via, m.confidence)) {
        Some((AttributionSignal::Heuristic, _)) if g.kind == GroupKind::App => Confidence::Medium,
        Some((_, c)) => c,
        None => g.members.iter().map(|m| m.confidence).max().unwrap_or_default(),
    };
    if g.matched_by.is_some()
        && g.confidence < Confidence::High
        && g.matched_by.as_deref() != Some("cgroup:unit")
    {
        g.confidence = Confidence::High;
    }

    if let Some(r) = root {
        if g.fingerprint.is_empty() {
            g.fingerprint = ctx.rules.group_fingerprint(g.kind, r);
        }
    }
    let rule_protected = g
        .matched_by
        .as_deref()
        .map(|id| ctx.rules.is_protected_rule(id))
        .unwrap_or(false);
    g.protected = g.protected
        || rule_protected
        || g.is_self
        || g.kind == GroupKind::System
        || ctx.protect.caller_group.as_deref() == Some(g.id.as_str())
        || root
            .map(|r| is_protected_process(r, snapshot, ctx.protect))
            .unwrap_or(false);
}

/// Rules & heuristics, lowest priority (SPEC §7): a user-launched root whose cwd is inside exactly one live
/// agent session's project is linked to it via `owner_group` (membership is not changed; an owner that is
/// merely the terminal it was typed into is replaced).
fn link_by_project(groups: &mut [Group], s: &Snapshot, by_id: &HashMap<ProcId, usize>) {
    let lookup = |id: ProcId| by_id.get(&id).map(|&i| &s.processes[i]);
    let sessions: Vec<(String, String)> = groups
        .iter()
        .filter(|g| g.kind == GroupKind::AgentSession)
        .filter_map(|g| {
            let root = lookup(g.root?)?;
            let cwd = fingerprint::project_root(root)?;
            Some((cwd.to_string(), g.id.clone()))
        })
        .collect();
    if sessions.is_empty() {
        return;
    }
    // groups rooted in a terminal / multiplexer: "launched from iTerm" is less informative than the project
    let launchers: HashSet<String> = groups
        .iter()
        .filter(|g| g.root.and_then(lookup).map(is_terminal).unwrap_or(false))
        .map(|g| g.id.clone())
        .collect();
    for g in groups.iter_mut() {
        let replaceable = g
            .owner_group
            .as_ref()
            .map(|o| launchers.contains(o))
            .unwrap_or(true);
        if g.kind != GroupKind::Other || !replaceable || g.matched_by.is_some() || g.orphan {
            continue;
        }
        let Some(cwd) = g.root.and_then(lookup).and_then(fingerprint::project_root) else {
            continue;
        };
        let mut hits: Vec<&(String, String)> = sessions
            .iter()
            .filter(|(root, _)| {
                cwd == root
                    || cwd
                        .strip_prefix(root.as_str())
                        .map(|r| r.starts_with('/'))
                        .unwrap_or(false)
            })
            .collect();
        hits.sort_by_key(|(root, _)| std::cmp::Reverse(root.len()));
        match hits.as_slice() {
            [only] => g.owner_group = Some(only.1.clone()),
            [a, b, ..] if a.0.len() > b.0.len() => g.owner_group = Some(a.1.clone()),
            _ => {}
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{Markers, Measured};

    pub(crate) fn proc(pid: u32, ppid: u32, name: &str, exe: &str, fp: u64) -> Process {
        Process {
            id: ProcId::new(pid, 1000 + pid as u64),
            ppid: Some(ppid),
            name: name.into(),
            exe: exe.into(),
            cmdline: vec![exe.into()],
            uid: Some(501),
            mem: crate::model::MemBreakdown {
                footprint_or_pss: Measured::exact(fp, "t"),
                resident: Measured::exact(fp / 2, "t"),
                ..Default::default()
            },
            ..Default::default()
        }
    }

    fn rules() -> CompiledRules {
        let set: RuleSet = RuleSet {
            rules: vec![
                Rule {
                    kind: GroupKind::AgentSession,
                    label: "Claude Code".into(),
                    matcher: MatchSpec {
                        exe: vec!["claude".into()],
                        env: vec!["CLAUDECODE".into()],
                        ..Default::default()
                    },
                    session_key: Some("env:CLAUDE_CODE_SESSION_ID".into()),
                    ..Default::default()
                },
                Rule {
                    kind: GroupKind::BuildDaemon,
                    label: "GradleDaemon".into(),
                    matcher: MatchSpec {
                        script: vec!["org.gradle.launcher.daemon.*".into()],
                        ..Default::default()
                    },
                    ..Default::default()
                },
            ],
        };
        CompiledRules::compile(&set).unwrap()
    }

    fn run(s: &Snapshot, lineage: &BTreeMap<ProcId, LineageEntry>) -> Vec<Group> {
        let r = rules();
        let protect = ProtectContext::default();
        attribute(
            s,
            &AttributionContext {
                rules: &r,
                lineage,
                protect: &protect,
            },
        )
    }

    fn sess(sid: &str) -> Markers {
        Markers {
            session_id: Some(sid.into()),
            agent: Some("claude-code".into()),
            keys: vec!["CLAUDECODE".into(), "CLAUDE_CODE_SESSION_ID".into()],
        }
    }

    #[test]
    fn sessions_ancestry_and_markers() {
        let mut s = Snapshot::default();
        // The agent CLI itself carries no marker; only its children do.
        let claude = proc(100, 50, "claude", "/opt/bin/claude", 400);
        let desktop = proc(
            300,
            1,
            "Claude",
            "/Applications/Claude.app/Contents/MacOS/Claude",
            50,
        );
        let zsh = proc(50, 1, "zsh", "/bin/zsh", 10);
        let mut child = proc(101, 100, "node", "/usr/bin/node", 100);
        child.markers = sess("abcdef0123456789");
        // re-parented to launchd but still carries the marker
        let mut orphan = proc(102, 1, "chrome", "/x/chrome", 1000);
        orphan.markers = sess("abcdef0123456789");
        let mut gradle = proc(200, 1, "java", "/usr/bin/java", 3000);
        gradle.cmdline = vec![
            "java".into(),
            "org.gradle.launcher.daemon.bootstrap.GradleDaemon".into(),
        ];
        gradle.markers = sess("abcdef0123456789");
        s.processes = vec![zsh, claude, child, orphan, gradle, desktop];
        let groups = run(&s, &BTreeMap::new());
        let agent = groups.iter().find(|g| g.kind == GroupKind::AgentSession).unwrap();
        assert_eq!(agent.members.len(), 3, "{groups:#?}");
        assert_eq!(agent.totals.footprint.value, Some(1500));
        // keyed by rule and root pid, not by the session id its children happen to carry
        assert_eq!(agent.id, "agent:claude-code:100");
        assert_eq!(agent.root.map(|r| r.pid), Some(100));
        let daemon = groups.iter().find(|g| g.kind == GroupKind::BuildDaemon).unwrap();
        assert_eq!(daemon.members.len(), 1);
        assert_eq!(daemon.owner_group.as_deref(), Some("agent:claude-code:100"));
        assert!(!daemon.fingerprint.is_empty());
        let app = groups.iter().find(|g| g.label == "Claude").unwrap();
        assert_eq!(
            app.kind,
            GroupKind::App,
            "desktop app is not Claude Code (case-sensitive exe)"
        );
        let zsh_group = groups.iter().find(|g| g.label == "zsh").unwrap();
        assert_eq!(zsh_group.members.len(), 1);
        // largest first
        assert_eq!(groups[0].kind, GroupKind::BuildDaemon);
    }

    #[test]
    fn lineage_rejoins_live_group_and_orphans_dead_one() {
        let mut s = Snapshot::default();
        let orphan = proc(500, 1, "chrome", "/x/chrome", 100);
        let stale = proc(
            600,
            1,
            "Claude",
            "/Applications/Claude.app/Contents/MacOS/Claude",
            100,
        );
        s.processes = vec![orphan.clone(), stale.clone()];
        let mut lineage = BTreeMap::new();
        let le = |id: ProcId, ppid: u32| LineageEntry {
            id,
            ppid: Some(ppid),
            group_id: "agent:abc".into(),
            group_kind: GroupKind::AgentSession,
            group_label: "Claude Code".into(),
            spawned_by_agent: true,
            ..Default::default()
        };
        lineage.insert(orphan.id, le(orphan.id, 77));
        lineage.insert(stale.id, le(stale.id, 1));
        let groups = run(&s, &lineage);
        // the session is gone → the re-parented process is its own (orphan) root owned by the session
        let g = groups.iter().find(|g| g.root == Some(orphan.id)).unwrap();
        assert_eq!(g.members[0].via, AttributionSignal::Lineage);
        assert_eq!(g.owner_group.as_deref(), Some("agent:abc"));
        assert_eq!(g.members.len(), 1);
        // ppid was already 1 when recorded → not re-parented → heuristic app
        assert!(groups
            .iter()
            .any(|g| g.label == "Claude" && g.kind == GroupKind::App));
    }

    #[test]
    fn orphan_identity_is_stable_across_samples() {
        // sample 1: session gone, marker carrier → orphan root owned by the dead session
        let mut s = Snapshot::default();
        let mut o = proc(700, 1, "node", "/usr/bin/node", 100);
        o.markers = sess("feedfacefeedface");
        s.processes = vec![o.clone()];
        let g1 = run(&s, &BTreeMap::new());
        assert_eq!(g1[0].owner_group.as_deref(), Some("agent:feedfacefeed"));
        assert!(g1[0].orphan);
        // sample 2: the engine journaled the orphan's *own* group id (+ original ppid and session id)
        let mut lineage = BTreeMap::new();
        lineage.insert(
            o.id,
            LineageEntry {
                id: o.id,
                ppid: Some(650),
                group_id: g1[0].id.clone(),
                group_kind: g1[0].kind,
                session_id: Some("feedfacefeedface".into()),
                spawned_by_agent: true,
                ..Default::default()
            },
        );
        let g2 = run(&s, &lineage);
        assert_eq!(g2[0].id, g1[0].id);
        assert_eq!(
            g2[0].owner_group.as_deref(),
            Some("agent:feedfacefeed"),
            "never its own owner"
        );
        assert!(g2[0].orphan);
        // …and without the marker the journal alone still knows the session
        s.processes[0].markers = Markers::default();
        let g3 = run(&s, &lineage);
        assert_eq!(g3[0].id, g1[0].id);
        assert_eq!(g3[0].owner_group.as_deref(), Some("agent:feedfacefeed"));
        assert_eq!(g3[0].members[0].via, AttributionSignal::Lineage);
    }

    /// Audit finding 2: the group id of a session must not depend on which marker-carrying descendants are
    /// alive in the sample (it used to flip between `agent:<rule>:<pid>` and `agent:<hash12>`).
    #[test]
    fn session_id_is_stable_while_marker_children_come_and_go() {
        let claude = proc(100, 50, "claude", "/opt/bin/claude", 400);
        let mut tool = proc(101, 100, "node", "/usr/bin/node", 50);
        tool.markers = sess("abcdef0123456789");
        let mut s = Snapshot {
            processes: vec![claude.clone()],
            ..Default::default()
        };
        let idle = run(&s, &BTreeMap::new());
        s.processes = vec![claude.clone(), tool.clone()];
        let busy = run(&s, &BTreeMap::new());
        s.processes = vec![claude];
        let idle_again = run(&s, &BTreeMap::new());
        let id = |g: &[Group]| {
            g.iter()
                .find(|g| g.kind == GroupKind::AgentSession)
                .map(|g| g.id.clone())
                .unwrap()
        };
        assert_eq!(id(&idle), "agent:claude-code:100");
        assert_eq!(id(&busy), id(&idle));
        assert_eq!(id(&idle_again), id(&idle));
    }

    /// A journal entry names the session either by its group id or (journals written before ids were
    /// pid-keyed, and orphans that recorded themselves) by the hashed session id: both find the live group,
    /// whatever the order of the process table.
    #[test]
    fn lineage_finds_the_live_session_by_id_or_alias() {
        let claude = proc(900, 50, "claude", "/opt/bin/claude", 400);
        let mut tool = proc(901, 900, "node", "/usr/bin/node", 50);
        tool.markers = sess("abcdef0123456789");
        // spawned by the session with a scrubbed environment, re-parented to launchd; listed *before* the
        // session root, so the root is not resolved yet when the journal is consulted
        let mut watcher = proc(300, 1, "fswatch", "/usr/bin/fswatch", 20);
        watcher.id.start_time = claude.id.start_time + 1;
        let s = Snapshot {
            processes: vec![watcher.clone(), claude, tool],
            ..Default::default()
        };
        for recorded in ["agent:claude-code:900", "agent:abcdef012345"] {
            let mut lineage = BTreeMap::new();
            lineage.insert(
                watcher.id,
                LineageEntry {
                    id: watcher.id,
                    ppid: Some(901),
                    group_id: recorded.into(),
                    group_kind: GroupKind::AgentSession,
                    group_label: "Claude Code".into(),
                    spawned_by_agent: true,
                    ..Default::default()
                },
            );
            let groups = run(&s, &lineage);
            let a = groups.iter().find(|g| g.kind == GroupKind::AgentSession).unwrap();
            assert_eq!(a.id, "agent:claude-code:900", "{recorded}");
            let m = a.members.iter().find(|m| m.id.pid == 300);
            assert_eq!(
                m.map(|m| m.via),
                Some(AttributionSignal::Lineage),
                "{recorded}: {groups:#?}"
            );
        }
    }

    /// Audit finding 5: a session id belongs to the marker key it came from. Codex started inside a Claude
    /// Code session inherits `CLAUDE_CODE_SESSION_ID`; its children must not be keyed (or labelled) by it.
    #[test]
    fn nested_agents_read_the_session_id_of_their_own_key() {
        let set = RuleSet {
            rules: vec![
                Rule {
                    kind: GroupKind::AgentSession,
                    label: "Claude Code".into(),
                    matcher: MatchSpec {
                        exe: vec!["claude".into()],
                        env: vec!["CLAUDECODE".into()],
                        ..Default::default()
                    },
                    session_key: Some("env:CLAUDE_CODE_SESSION_ID".into()),
                    ..Default::default()
                },
                Rule {
                    kind: GroupKind::AgentSession,
                    label: "Codex".into(),
                    matcher: MatchSpec {
                        exe: vec!["codex".into()],
                        env: vec!["CODEX_SESSION_ID".into()],
                        ..Default::default()
                    },
                    session_key: Some("env:CODEX_SESSION_ID".into()),
                    ..Default::default()
                },
            ],
        };
        let rules = CompiledRules::compile(&set).unwrap();
        let allow: Vec<String> = ["CLAUDECODE", "CLAUDE_CODE_SESSION_ID", "CODEX_SESSION_ID"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        let claude_env = [("CLAUDECODE", "1"), ("CLAUDE_CODE_SESSION_ID", "outer-claude")];
        let both_env = [
            ("CLAUDECODE", "1"),
            ("CLAUDE_CODE_SESSION_ID", "outer-claude"),
            ("CODEX_SESSION_ID", "inner-codex"),
        ];
        let claude = proc(100, 50, "claude", "/opt/bin/claude", 400);
        let mut sh = proc(101, 100, "zsh", "/bin/zsh", 5);
        sh.markers = crate::redact::markers_from_env(claude_env, &allow);
        let mut codex = proc(110, 101, "codex", "/opt/bin/codex", 300);
        codex.markers = crate::redact::markers_from_env(claude_env, &allow);
        let mut tool = proc(111, 110, "node", "/usr/bin/node", 50);
        tool.markers = crate::redact::markers_from_env(both_env, &allow);
        // a Codex tool process re-parented to launchd: it carries both ids and belongs to Codex
        let mut orphan = proc(112, 1, "python3", "/usr/bin/python3", 70);
        orphan.markers = crate::redact::markers_from_env(both_env, &allow);
        // …and one of Claude's own, with only Claude's id
        let mut claude_orphan = proc(102, 1, "python3", "/usr/bin/python3", 70);
        claude_orphan.markers = crate::redact::markers_from_env(claude_env, &allow);
        let s = Snapshot {
            processes: vec![claude, sh, codex, tool, orphan, claude_orphan],
            ..Default::default()
        };
        let protect = ProtectContext::default();
        let groups = attribute(
            &s,
            &AttributionContext {
                rules: &rules,
                lineage: &BTreeMap::new(),
                protect: &protect,
            },
        );
        let pids = |label: &str| -> Vec<u32> {
            let g = groups.iter().find(|g| g.label == label).unwrap();
            let mut v: Vec<u32> = g.members.iter().map(|m| m.id.pid).collect();
            v.sort();
            v
        };
        assert_eq!(pids("Claude Code"), vec![100, 101, 102], "{groups:#?}");
        assert_eq!(pids("Codex"), vec![110, 111, 112], "{groups:#?}");
        let cx = groups.iter().find(|g| g.label == "Codex").unwrap();
        assert_eq!(cx.owner_group.as_deref(), Some("agent:claude-code:100"));
        assert_eq!(
            groups
                .iter()
                .filter(|g| g.kind == GroupKind::AgentSession)
                .count(),
            2
        );
    }

    #[test]
    fn workers_of_a_rule_root_stay_with_it_despite_markers() {
        // `./gradlew build` in a session → daemon (ppid 1) → worker; both inherit the session env
        let mut s = Snapshot::default();
        let claude = proc(100, 50, "claude", "/opt/bin/claude", 400);
        let mut mcp = proc(101, 100, "node", "/usr/bin/node", 50);
        mcp.markers = sess("abcdef0123456789");
        let mut daemon = proc(200, 1, "java", "/usr/bin/java", 3000);
        daemon.cmdline = vec![
            "java".into(),
            "org.gradle.launcher.daemon.bootstrap.GradleDaemon".into(),
        ];
        daemon.markers = sess("abcdef0123456789");
        let mut worker = proc(201, 200, "java", "/usr/bin/java", 500);
        worker.markers = sess("abcdef0123456789");
        s.processes = vec![claude, mcp, daemon, worker];
        let groups = run(&s, &BTreeMap::new());
        let d = groups.iter().find(|g| g.kind == GroupKind::BuildDaemon).unwrap();
        let pids: Vec<u32> = d.members.iter().map(|m| m.id.pid).collect();
        assert_eq!(pids, vec![200, 201], "{groups:#?}");
        assert_eq!(d.members[1].via, AttributionSignal::Ancestry);
        assert_eq!(d.owner_group.as_deref(), Some("agent:claude-code:100"));
        let a = groups.iter().find(|g| g.kind == GroupKind::AgentSession).unwrap();
        assert_eq!(a.members.len(), 2);
    }

    #[test]
    fn raw_or_non_ascii_session_ids_never_panic_or_leak() {
        let mut s = Snapshot::default();
        let claude = proc(100, 50, "claude", "/opt/bin/claude", 400);
        let mut child = proc(101, 100, "node", "/usr/bin/node", 50);
        // byte 12 falls inside 'ä' (a byte-index slice would panic)
        child.markers = sess("aääääääääää-raw");
        s.processes = vec![claude, child];
        let groups = run(&s, &BTreeMap::new());
        let a = groups.iter().find(|g| g.kind == GroupKind::AgentSession).unwrap();
        assert!(a.id.is_ascii() && !a.id.contains("raw"), "{}", a.id);
        assert_eq!(a.members.len(), 2);
        // …and the alias of a dead session (an orphan's owner) is a hash, never the raw id
        s.processes.remove(0);
        s.processes[0].ppid = Some(1);
        let groups = run(&s, &BTreeMap::new());
        let owner = groups[0].owner_group.clone().unwrap();
        assert!(owner.is_ascii() && !owner.contains("raw"), "{owner}");
        assert_eq!(owner.len(), "agent:".len() + 12);
        // a hashed id keeps its prefix (ids stay stable with the existing journal)
        assert_eq!(
            session_group_key(GroupKind::AgentSession, "abcdef0123456789"),
            "agent:abcdef012345"
        );
    }

    #[test]
    fn lineage_never_rejoins_a_pid_reused_group() {
        // journal: pid 900 (started at 1900) was spawned by group "other:start-sh:800"; pid 800 now belongs
        // to a *younger* process with the same label → not the group that spawned it
        let mut s = Snapshot::default();
        let mut reused = proc(800, 1, "start.sh", "/bin/start.sh", 10);
        reused.id.start_time = 5000;
        let child = proc(900, 1, "node", "/usr/bin/node", 100);
        // an older XPC-style process that names the reused pid as responsible makes it resolve first
        let mut early = proc(850, 1, "helper", "/opt/helper", 1);
        early.responsible_pid = Some(800);
        s.processes = vec![reused.clone(), child.clone(), early];
        let groups = run(&s, &BTreeMap::new());
        let key = groups
            .iter()
            .find(|g| g.root == Some(reused.id))
            .unwrap()
            .id
            .clone();
        let mut lineage = BTreeMap::new();
        lineage.insert(
            child.id,
            LineageEntry {
                id: child.id,
                ppid: Some(800),
                group_id: key.clone(),
                group_kind: GroupKind::Other,
                group_label: "start.sh".into(),
                ..Default::default()
            },
        );
        let groups = run(&s, &lineage);
        let g = groups
            .iter()
            .find(|g| g.members.iter().any(|m| m.id == child.id))
            .unwrap();
        assert_ne!(g.id, key, "{groups:#?}");
        assert_eq!(g.root, Some(child.id));
        assert_eq!(g.owner_group.as_deref(), Some(key.as_str()));
    }

    #[test]
    fn libexec_terminal_is_not_a_system_component() {
        let t = proc(
            600,
            400,
            "gnome-terminal-",
            "/usr/libexec/gnome-terminal-server",
            60,
        );
        assert_eq!(heuristic_kind_label(&t).0, GroupKind::Other);
        let d = proc(601, 1, "polkitd", "/usr/libexec/polkitd", 6);
        assert_eq!(heuristic_kind_label(&d).0, GroupKind::System);
    }

    #[test]
    fn bad_rules_are_errors() {
        let set = RuleSet {
            rules: vec![Rule {
                label: "x".into(),
                matcher: MatchSpec {
                    cmdline: vec!["(".into()],
                    ..Default::default()
                },
                ..Default::default()
            }],
        };
        assert!(matches!(
            CompiledRules::compile(&set),
            Err(RuleError::Regex { .. })
        ));
        let set = RuleSet {
            rules: vec![Rule::default()],
        };
        assert!(matches!(
            CompiledRules::compile(&set),
            Err(RuleError::EmptyLabel { .. })
        ));
        let set = RuleSet {
            rules: vec![Rule {
                label: "x".into(),
                session_key: Some("CLAUDE_CODE_SESSION_ID".into()),
                ..Default::default()
            }],
        };
        assert!(matches!(
            CompiledRules::compile(&set),
            Err(RuleError::SessionKey { .. })
        ));
    }

    /// Audit finding 9: a misspelled top-level table (`[[groups]]`, `[[rule]]`) is an error, not an
    /// empty rule set.
    #[test]
    fn unknown_top_level_keys_in_a_rule_set_are_errors() {
        let ok: RuleSet = serde_json::from_str(r#"{"group":[{"label":"x","match":{"exe":["x"]}}]}"#).unwrap();
        assert_eq!(ok.rules.len(), 1);
        assert_eq!(serde_json::from_str::<RuleSet>("{}").unwrap().rules.len(), 0);
        for bad in [
            r#"{"groups":[{"label":"x","match":{"exe":["x"]}}]}"#,
            r#"{"rule":[{"label":"x"}]}"#,
            r#"{"group":[],"version":2}"#,
        ] {
            let e = serde_json::from_str::<RuleSet>(bad).unwrap_err().to_string();
            assert!(e.contains("unknown field"), "{bad}: {e}");
        }
    }

    #[test]
    fn slugs() {
        assert_eq!(slug("Claude Code"), "claude-code");
        assert_eq!(slug("  sd-server · qwen "), "sd-server-qwen");
    }

    #[test]
    fn cgroups() {
        let c = |p: &str| parse_cgroup(p);
        assert_eq!(
            c("0::/system.slice/docker-3f2a9c01e2b4aabbccddeeff00112233445566778899aabbccddeeff00112233.scope"),
            Some(CgroupScope::Container {
                runtime: "docker".into(),
                id: "3f2a9c01e2b4".into()
            })
        );
        assert_eq!(
            c("/user.slice/user-1000.slice/user@1000.service/user.slice/libpod-0123456789abcdef0123.scope/container"),
            Some(CgroupScope::Container {
                runtime: "podman".into(),
                id: "0123456789ab".into()
            })
        );
        assert_eq!(
            c("/kubepods/burstable/pod1234-5678/0123456789abcdef0123456789abcdef"),
            Some(CgroupScope::Container {
                runtime: "kubernetes".into(),
                id: "0123456789ab".into()
            })
        );
        assert_eq!(
            c("/machine.slice/machine-qemu\\x2d1\\x2dubuntu.scope/libvirt/emulator"),
            Some(CgroupScope::Vm {
                name: "ubuntu".into()
            })
        );
        assert_eq!(
            c("/system.slice/ollama.service"),
            Some(CgroupScope::Service {
                unit: "ollama".into(),
                system: true
            })
        );
        assert_eq!(
            c("/user.slice/user-1000.slice/user@1000.service/app.slice/app-gnome-firefox-4242.scope"),
            Some(CgroupScope::App {
                app: "firefox".into()
            })
        );
        assert_eq!(
            c("/user.slice/user-1000.slice/user@1000.service/app.slice/app-flatpak-org.mozilla.firefox-4242.scope"),
            Some(CgroupScope::App { app: "firefox".into() })
        );
        assert_eq!(c("/user.slice/user-1000.slice/user@1000.service/app.slice/app-org.gnome.Terminal.slice/vte-spawn-1a2b.scope"), None);
        assert_eq!(
            c("/user.slice/user-1000.slice/user@1000.service/app.slice/app-kitty-4242.scope"),
            None
        );
        assert_eq!(c("/user.slice/user-1000.slice/session-2.scope"), None);
        assert_eq!(
            c("/user.slice/user-1000.slice/user@1000.service/init.scope"),
            None
        );
    }

    /// Real-world kubelet cgroup layouts: cgroupfs and systemd drivers, every QoS class, containerd /
    /// CRI-O / cri-dockerd scopes, pod-level paths, nodes nested in kind / k3d containers, rootless k3s.
    #[test]
    fn kube_cgroups() {
        let cid = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
        let uid = "8f6c1c3e-3b5a-4b8e-9d55-0a1b2c3d4e5f";
        let uid_ = uid.replace('-', "_");
        let k = |p: &str| parse_kube_cgroup(p);
        // cgroupfs driver (containerd/k3s/microk8s default), burstable.
        let c = k(&format!("0::/kubepods/burstable/pod{uid}/{cid}")).unwrap();
        assert_eq!(c.qos, QosClass::Burstable);
        assert_eq!(c.pod_uid, uid);
        assert_eq!(c.container_id.as_deref(), Some(cid));
        assert_eq!(c.runtime, None);
        assert_eq!(c.pod_cgroup, format!("/kubepods/burstable/pod{uid}"));
        assert_eq!(
            c.container_cgroup,
            Some(format!("/kubepods/burstable/pod{uid}/{cid}"))
        );
        assert_eq!(c.node_prefix, "");
        // cgroupfs guaranteed (pod directly under kubepods) and besteffort.
        assert_eq!(
            k(&format!("/kubepods/pod{uid}/{cid}")).unwrap().qos,
            QosClass::Guaranteed
        );
        assert_eq!(
            k(&format!("/kubepods/besteffort/pod{uid}/{cid}")).unwrap().qos,
            QosClass::BestEffort
        );
        // systemd driver, containerd.
        let c = k(&format!(
            "/kubepods.slice/kubepods-burstable.slice/kubepods-burstable-pod{uid_}.slice/cri-containerd-{cid}.scope"
        ))
        .unwrap();
        assert_eq!((c.qos, c.pod_uid.as_str()), (QosClass::Burstable, uid));
        assert_eq!(c.runtime.as_deref(), Some("containerd"));
        assert_eq!(c.container_id.as_deref(), Some(cid));
        assert!(c
            .pod_cgroup
            .ends_with(&format!("kubepods-burstable-pod{uid_}.slice")));
        // systemd driver guaranteed + CRI-O, and its conmon scope.
        let c = k(&format!(
            "/kubepods.slice/kubepods-pod{uid_}.slice/crio-{cid}.scope"
        ))
        .unwrap();
        assert_eq!(
            (c.qos, c.runtime.as_deref(), c.conmon),
            (QosClass::Guaranteed, Some("cri-o"), false)
        );
        let c = k(&format!(
            "/kubepods.slice/kubepods-pod{uid_}.slice/crio-conmon-{cid}.scope"
        ))
        .unwrap();
        assert!(c.conmon);
        // cri-dockerd (Docker Desktop / minikube docker runtime).
        let c = k(&format!(
            "/kubepods.slice/kubepods-besteffort.slice/kubepods-besteffort-pod{uid_}.slice/docker-{cid}.scope"
        ))
        .unwrap();
        assert_eq!(
            (c.qos, c.runtime.as_deref()),
            (QosClass::BestEffort, Some("docker"))
        );
        // Pod-level cgroup: no container.
        let c = k(&format!("/kubepods/burstable/pod{uid}")).unwrap();
        assert_eq!((c.container_id, c.container_cgroup), (None, None));
        // kind node (kubelet cgroup root /kubelet) seen from the host, inside the node's docker scope.
        let node = format!("/system.slice/docker-{cid}.scope");
        let c = k(&format!(
            "{node}/kubelet.slice/kubelet-kubepods.slice/kubelet-kubepods-burstable.slice/kubelet-kubepods-burstable-pod{uid_}.slice/cri-containerd-{cid}.scope"
        ))
        .unwrap();
        assert_eq!(c.node_prefix, format!("{node}/kubelet.slice"));
        assert_eq!((c.qos, c.pod_uid.as_str()), (QosClass::Burstable, uid));
        // k3d node (cgroupfs inside a docker container), rootless k3s under a user service.
        let c = k(&format!(
            "/system.slice/docker-{cid}.scope/kubepods/besteffort/pod{uid}/{cid}"
        ))
        .unwrap();
        assert_eq!(c.node_prefix, format!("/system.slice/docker-{cid}.scope"));
        let c = k(&format!(
            "/user.slice/user-1000.slice/user@1000.service/k3s-rootless.service/kubepods/burstable/pod{uid}/{cid}"
        ))
        .unwrap();
        assert_eq!(c.qos, QosClass::Burstable);
        // Not kubelet paths.
        for p in [
            "/system.slice/kubelet.service",
            "/kubepods.slice",
            "/kubepods/burstable",
            &format!("/system.slice/docker-{cid}.scope"),
            &format!("/kubepods/burstable/podnot-a-uid/{cid}"),
            &format!("/kubepods/burstable/pod{uid}/not-an-id"),
            &format!("/kubepods/burstable/extra/pod{uid}/{cid}"),
        ] {
            assert_eq!(k(p), None, "{p}");
        }
        // The grouping parser still keeps its 12-character id for the same paths.
        assert_eq!(
            parse_cgroup(&format!("/kubepods/burstable/pod{uid}/{cid}")),
            Some(CgroupScope::Container {
                runtime: "kubernetes".into(),
                id: cid[..12].into()
            })
        );
        assert_eq!(QosClass::parse("BestEffort"), Some(QosClass::BestEffort));
    }

    #[test]
    fn indexed_matching_equals_rule_by_rule() {
        let set: RuleSet = serde_json::from_str(
            r#"{ "group": [
              { "id": "a", "kind": "agent_session", "label": "A", "match": { "exe": ["claude", "**/versions/*"], "name": ["claude"], "script": ["**/@anthropic-ai/claude-code/**"], "env": ["CLAUDECODE"] }, "session_key": "env:CLAUDE_CODE_SESSION_ID" },
              { "id": "b", "kind": "model_server", "label": "B", "match": { "cmdline": ["vllm\\s+serve", "mlx_lm[._]server"] } },
              { "id": "c", "kind": "app", "label": "C", "match": { "exe": ["firefox"] }, "exclude": { "exe": ["**/*.app/**"] } },
              { "id": "d", "kind": "other", "label": "D", "match": { "cwd": ["/srv/**"], "bundle": ["com.example.*"], "cgroup": ["/system.slice/x*.service"] } },
              { "id": "e", "kind": "build_daemon", "label": "E", "priority": 5, "match": { "script": ["*.js"] } },
              { "id": "f", "kind": "other", "label": "F only env", "match": { "env": ["CODEX_SANDBOX"] } }
            ] }"#,
        )
        .unwrap();
        let r = CompiledRules::compile(&set).unwrap();
        let mk = |exe: &str, argv: &[&str]| Process {
            exe: exe.into(),
            name: basename(exe).into(),
            cmdline: argv.iter().map(|s| s.to_string()).collect(),
            ..Default::default()
        };
        let mut cases = vec![
            mk("/opt/bin/claude", &["claude"]),
            mk("/u/.local/share/claude/versions/2.1.3", &["claude"]),
            mk("", &["claude", "-p", "x"]),
            mk(
                "/usr/bin/node",
                &["node", "/l/node_modules/@anthropic-ai/claude-code/cli.js"],
            ),
            mk("/usr/bin/python3", &["python3", "-m", "vllm", "serve", "m"]),
            mk("/usr/bin/python3", &["python", "-m", "mlx_lm.server"]),
            mk("/usr/lib/firefox/firefox", &["firefox"]),
            mk("/Applications/Firefox.app/Contents/MacOS/firefox", &["firefox"]),
            mk("/usr/bin/node", &["node", "server.js"]),
            mk("/bin/zsh", &["-zsh"]),
            mk("/x/tool", &[]),
        ];
        let mut d = mk("/x/y", &["y"]);
        d.cwd = Some("/srv/app".into());
        cases.push(d.clone());
        d.cwd = None;
        d.bundle_id = Some("com.example.tool".into());
        cases.push(d.clone());
        d.bundle_id = None;
        d.cgroup = Some("/system.slice/xyz.service".into());
        cases.push(d);
        for p in &cases {
            let a = r.match_root(p).map(|m| m.index);
            let b = r.match_root_naive(p).map(|m| m.index);
            assert_eq!(a, b, "{:?}", p.cmdline);
        }
        assert_eq!(
            r.match_root(&cases[3]).map(|m| m.index),
            Some(4),
            "priority 5 script rule wins"
        );
        assert_eq!(r.match_root(&cases[7]), None, "excluded .app");
        assert_eq!(r.match_root(&cases[11]).map(|m| m.rule.label.as_str()), Some("D"));
    }

    #[test]
    fn shells_and_terminals() {
        let mut p = proc(1, 0, "zsh", "/bin/zsh", 0);
        assert!(is_interactive_shell(&p));
        p.cmdline = vec!["-zsh".into()];
        p.name = "-zsh".into();
        assert!(is_interactive_shell(&p));
        p.cmdline = vec!["/bin/zsh".into(), "-c".into(), "ls".into()];
        assert!(!is_interactive_shell(&p));
        p.cmdline = vec!["bash".into(), "-lc".into(), "ls".into()];
        assert!(!is_interactive_shell(&p));
        p.cmdline = vec!["bash".into(), "start.sh".into()];
        assert!(!is_interactive_shell(&p));
        let t = proc(2, 1, "iTerm2", "/Applications/iTerm.app/Contents/MacOS/iTerm2", 0);
        assert!(is_terminal(&t));
        let w = proc(3, 1, "stable", "/Applications/Warp.app/Contents/MacOS/stable", 0);
        assert!(is_terminal(&w));
        let c = proc(
            4,
            1,
            "Google Chrome",
            "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
            0,
        );
        assert!(!is_terminal(&c));
    }

    #[test]
    fn another_users_app_is_its_own_group() {
        // Fast user switching: a second logged-in user runs Chrome too (seen on the M5 Air).
        let exe = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
        let mine = proc(10, 1, "Google Chrome", exe, 100);
        let mut theirs = proc(20, 1, "Google Chrome", exe, 100);
        theirs.uid = Some(502);
        let s = Snapshot {
            processes: vec![mine, theirs],
            ..Default::default()
        };
        let r = rules();
        let protect = ProtectContext {
            self_uid: Some(501),
            ..Default::default()
        };
        let groups = attribute(
            &s,
            &AttributionContext {
                rules: &r,
                lineage: &BTreeMap::new(),
                protect: &protect,
            },
        );
        let ids: Vec<&str> = groups.iter().map(|g| g.id.as_str()).collect();
        assert!(ids.contains(&"app:google-chrome"), "{ids:?}");
        assert!(ids.contains(&"app:google-chrome@u502"), "{ids:?}");
        let mine = groups.iter().find(|g| g.id == "app:google-chrome").unwrap();
        assert!(!mine.protected, "our own Chrome stays actionable");
        // Without a known self uid (pure tests, fixtures) keys are unchanged.
        let groups = run(&s, &BTreeMap::new());
        assert_eq!(groups.len(), 1);
    }

    #[test]
    fn chrome_code_sign_clone_is_still_the_app() {
        // Chrome's updater runs the browser from a temporary `.app.bundle` copy (seen on the M5 Air).
        let mut c = proc(
            5,
            1,
            "Google Chrome",
            "/private/var/folders/xx/X/com.google.Chrome.code_sign_clone/code_sign_clone.AbCd/Google Chrome.app.bundle/Contents/MacOS/Google Chrome",
            0,
        );
        assert_eq!(app_bundle_name(&c), Some("Google Chrome"));
        assert!(is_app_main(&c));
        assert_eq!(heuristic_kind_label(&c).0, GroupKind::App);
        // Unknown exe, argv[0] still names the bundle.
        c.exe = String::new();
        c.cmdline = vec!["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome".into()];
        assert_eq!(app_bundle_name(&c), Some("Google Chrome"));
    }
}