ljos 0.35.5

Memory, a work tracker and a shell-command gate for coding agents (Claude Code, Codex, Grok Build, agy, opencode) over MCP and hooks.
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
//! Processes above this one, each named by its pid and its start time, so
//! a pid the kernel has since handed to another process is not taken for
//! the one that was recorded. Read from `/proc` on Linux and `libproc` and
//! `sysctl` on macOS; elsewhere every list is empty and nothing is alive.

use std::path::{Path, PathBuf};

/// One process: its pid, when it started (clock ticks after boot), and its
/// name at the time it was read.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Proc {
    pub pid: u32,
    pub start: u64,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub comm: String,
}

impl Proc {
    /// The same process: the name may change at exec, the start does not.
    #[must_use]
    pub fn same(&self, other: &Self) -> bool {
        self.pid == other.pid && self.start == other.start
    }
}

/// How far up a chain is read.
const DEPTH: usize = 32;

#[derive(Clone)]
struct Stat {
    comm: String,
    dead: bool,
    ppid: u32,
    start: u64,
}

/// One process's stat. Inside a hook, the processes above this one are
/// read once: a hook walks the tree from several places and is gone in
/// well under a second. A server that lives for hours watches its parent
/// through this, so outside a hook every read is fresh, and a child this
/// process reaps reads as gone everywhere.
fn stat(pid: u32) -> Option<Stat> {
    if let Some(found) = ancestor_stats()
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .get(&pid)
    {
        return found.clone();
    }
    stat_read(pid)
}

type AncestorStats = std::sync::Mutex<std::collections::HashMap<u32, Option<Stat>>>;

/// The stats of the processes above this one, filled by the first walk
/// up from this process ([`above`] on this pid).
fn ancestor_stats() -> &'static AncestorStats {
    static STATS: std::sync::OnceLock<AncestorStats> = std::sync::OnceLock::new();
    STATS.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()))
}

#[cfg(target_os = "linux")]
fn stat_read(pid: u32) -> Option<Stat> {
    let raw = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
    let open = raw.find('(')?;
    let close = raw.rfind(')')?;
    let comm = raw.get(open + 1..close)?.to_string();
    // After the name: state, ppid, ... and starttime, field 22 of stat(5).
    let rest: Vec<&str> = raw.get(close + 1..)?.split_whitespace().collect();
    Some(Stat {
        comm,
        dead: matches!(*rest.first()?, "Z" | "X" | "x"),
        ppid: rest.get(1)?.parse().ok()?,
        start: rest.get(19)?.parse().ok()?,
    })
}

#[cfg(target_os = "macos")]
fn stat_read(pid: u32) -> Option<Stat> {
    let mut info: libc::proc_bsdinfo = unsafe { std::mem::zeroed() };
    let size = libc::c_int::try_from(std::mem::size_of::<libc::proc_bsdinfo>()).ok()?;
    // SAFETY: the buffer is a zeroed proc_bsdinfo of the size passed.
    let n = unsafe {
        libc::proc_pidinfo(
            libc::c_int::try_from(pid).ok()?,
            libc::PROC_PIDTBSDINFO,
            0,
            std::ptr::addr_of_mut!(info).cast(),
            size,
        )
    };
    if n != size {
        // The full record is the owner's or root's to read. A process
        // another user owns (launchd, sshd, a login shell's parent) still
        // answers the short record, so the walk does not stop below it.
        return short_stat(pid);
    }
    let comm: Vec<u8> = info
        .pbi_comm
        .iter()
        .take_while(|c| **c != 0)
        .map(|c| c.to_ne_bytes()[0])
        .collect();
    let start = info
        .pbi_start_tvsec
        .saturating_mul(1_000_000)
        .saturating_add(info.pbi_start_tvusec);
    Some(Stat {
        comm: String::from_utf8_lossy(&comm).into_owned(),
        dead: info.pbi_status == libc::SZOMB,
        ppid: info.pbi_ppid,
        start,
    })
}

/// `pid`'s parent, name and state from the short BSD record, which any
/// user may read, and its start time from `kern.proc.pid`.
#[cfg(target_os = "macos")]
fn short_stat(pid: u32) -> Option<Stat> {
    let mut info: libc::proc_bsdshortinfo = unsafe { std::mem::zeroed() };
    let size = libc::c_int::try_from(std::mem::size_of::<libc::proc_bsdshortinfo>()).ok()?;
    // SAFETY: the buffer is a zeroed proc_bsdshortinfo of the size passed.
    let n = unsafe {
        libc::proc_pidinfo(
            libc::c_int::try_from(pid).ok()?,
            libc::PROC_PIDT_SHORTBSDINFO,
            0,
            std::ptr::addr_of_mut!(info).cast(),
            size,
        )
    };
    if n != size {
        return None;
    }
    let comm: Vec<u8> = info
        .pbsi_comm
        .iter()
        .take_while(|c| **c != 0)
        .map(|c| c.to_ne_bytes()[0])
        .collect();
    Some(Stat {
        comm: String::from_utf8_lossy(&comm).into_owned(),
        dead: info.pbsi_status == libc::SZOMB,
        ppid: info.pbsi_ppid,
        start: kern_proc_start(pid)?,
    })
}

/// The start time `kern.proc.pid` gives for `pid`, in microseconds. A
/// `struct kinfo_proc` opens with `kp_proc.p_un`, whose `p_starttime` is a
/// `struct timeval`: seconds as an `i64`, then microseconds as an `i32`.
#[cfg(target_os = "macos")]
fn kern_proc_start(pid: u32) -> Option<u64> {
    let mut mib = [
        libc::CTL_KERN,
        libc::KERN_PROC,
        libc::KERN_PROC_PID,
        libc::c_int::try_from(pid).ok()?,
    ];
    let mut buf = [0u8; 1024];
    let mut len: libc::size_t = buf.len();
    // SAFETY: the buffer and its length are passed together; sysctl writes
    // at most `len` bytes and stores how many it wrote.
    let rc = unsafe {
        libc::sysctl(
            mib.as_mut_ptr(),
            4,
            buf.as_mut_ptr().cast(),
            &mut len,
            std::ptr::null_mut(),
            0,
        )
    };
    if rc != 0 || len < 12 {
        return None;
    }
    let sec = i64::from_ne_bytes(buf[0..8].try_into().ok()?);
    let usec = i32::from_ne_bytes(buf[8..12].try_into().ok()?);
    let sec = u64::try_from(sec).ok()?;
    let usec = u64::try_from(usec).ok()?;
    Some(sec.saturating_mul(1_000_000).saturating_add(usec))
}

#[cfg(not(any(target_os = "linux", target_os = "macos")))]
fn stat_read(_pid: u32) -> Option<Stat> {
    None
}

/// The process `pid` names now.
#[must_use]
pub fn of(pid: u32) -> Option<Proc> {
    stat(pid).map(|s| Proc {
        pid,
        start: s.start,
        comm: s.comm,
    })
}

/// The processes above `pid`, nearest first, up to and including pid 1:
/// in a container that may be the harness itself.
#[must_use]
pub fn above(pid: u32) -> Vec<Proc> {
    let own = pid == std::process::id();
    let mut out = Vec::new();
    let mut next = stat(pid).map(|s| s.ppid);
    while let Some(p) = next.filter(|&p| p > 0 && out.len() < DEPTH) {
        let Some(s) = stat(p) else {
            break;
        };
        if own && std::env::var_os("LJOS_IN_HOOK").is_some() {
            ancestor_stats()
                .lock()
                .unwrap_or_else(std::sync::PoisonError::into_inner)
                .entry(p)
                .or_insert_with(|| Some(s.clone()));
        }
        next = Some(s.ppid);
        out.push(Proc {
            pid: p,
            start: s.start,
            comm: s.comm,
        });
    }
    out
}

/// The processes above this one, nearest first. Walked once: a process
/// does not move in the tree, and a hook asks for its ancestors from
/// several places in one call.
#[must_use]
pub fn ancestors() -> Vec<Proc> {
    static WALKED: std::sync::OnceLock<Vec<Proc>> = std::sync::OnceLock::new();
    WALKED.get_or_init(|| above(std::process::id())).clone()
}

/// `pid`'s parent and its own name.
fn parent_and_name(pid: u32) -> Option<(u32, String)> {
    stat(pid).map(|s| (s.ppid, s.comm))
}

fn split_environ(raw: &[u8]) -> Vec<(String, String)> {
    raw.split(|b| *b == 0)
        .filter_map(|kv| {
            let kv = String::from_utf8_lossy(kv);
            let (k, v) = kv.split_once('=')?;
            Some((k.to_string(), v.to_string()))
        })
        .collect()
}

/// The environment `pid` was started with. A program it runs can set its
/// own variables, but cannot change what its parent was started with.
#[cfg(target_os = "linux")]
#[must_use]
pub fn environ(pid: u32) -> Option<Vec<(String, String)>> {
    std::fs::read(format!("/proc/{pid}/environ"))
        .ok()
        .map(|raw| split_environ(&raw))
}

#[cfg(target_os = "macos")]
fn procargs2_buf(pid: u32) -> Option<Vec<u8>> {
    let mut mib = [
        libc::CTL_KERN,
        libc::KERN_PROCARGS2,
        libc::c_int::try_from(pid).ok()?,
    ];
    let mut size: libc::size_t = 0;
    // SAFETY: a null buffer asks sysctl for the size alone.
    let asked = unsafe {
        libc::sysctl(
            mib.as_mut_ptr(),
            3,
            std::ptr::null_mut(),
            &mut size,
            std::ptr::null_mut(),
            0,
        )
    };
    if asked != 0 || size < 4 {
        return None;
    }
    let mut buf = vec![0u8; size];
    // SAFETY: buf holds the size sysctl reported.
    let read = unsafe {
        libc::sysctl(
            mib.as_mut_ptr(),
            3,
            buf.as_mut_ptr().cast(),
            &mut size,
            std::ptr::null_mut(),
            0,
        )
    };
    if read != 0 {
        return None;
    }
    buf.truncate(size);
    Some(buf)
}

#[cfg(target_os = "macos")]
#[must_use]
pub fn environ(pid: u32) -> Option<Vec<(String, String)>> {
    let buf = procargs2_buf(pid)?;
    // argc, the executable path and its padding, argc words, then the
    // environment up to an empty string.
    let argc = usize::try_from(i32::from_ne_bytes(buf.get(..4)?.try_into().ok()?)).ok()?;
    let mut words = buf[4..]
        .split(|b| *b == 0)
        .skip(1)
        .skip_while(|w| w.is_empty());
    for _ in 0..argc {
        words.next()?;
    }
    let env: Vec<u8> = words
        .take_while(|w| !w.is_empty())
        .flat_map(|w| w.iter().copied().chain([0]))
        .collect();
    Some(split_environ(&env))
}

#[cfg(not(any(target_os = "linux", target_os = "macos")))]
#[must_use]
pub fn environ(_pid: u32) -> Option<Vec<(String, String)>> {
    None
}

/// The command-line words of `pid`.
#[cfg(target_os = "linux")]
#[must_use]
pub fn argv(pid: u32) -> Option<Vec<String>> {
    let raw = std::fs::read(format!("/proc/{pid}/cmdline")).ok()?;
    let words: Vec<String> = raw
        .split(|b| *b == 0)
        .filter(|w| !w.is_empty())
        .map(|w| String::from_utf8_lossy(w).into_owned())
        .collect();
    (!words.is_empty()).then_some(words)
}

#[cfg(target_os = "macos")]
#[must_use]
pub fn argv(pid: u32) -> Option<Vec<String>> {
    let buf = procargs2_buf(pid)?;
    let argc = usize::try_from(i32::from_ne_bytes(buf.get(..4)?.try_into().ok()?)).ok()?;
    if argc == 0 {
        return None;
    }
    let words: Vec<String> = buf[4..]
        .split(|b| *b == 0)
        .skip(1)
        .skip_while(|w| w.is_empty())
        .take(argc)
        .filter(|w| !w.is_empty())
        .map(|w| String::from_utf8_lossy(w).into_owned())
        .collect();
    (!words.is_empty()).then_some(words)
}

#[cfg(not(any(target_os = "linux", target_os = "macos")))]
#[must_use]
pub fn argv(_pid: u32) -> Option<Vec<String>> {
    None
}

/// The executable path of `pid`.
#[cfg(target_os = "linux")]
#[must_use]
pub fn exe(pid: u32) -> Option<PathBuf> {
    std::fs::read_link(format!("/proc/{pid}/exe")).ok()
}

#[cfg(target_os = "macos")]
#[must_use]
pub fn exe(pid: u32) -> Option<PathBuf> {
    use std::os::unix::ffi::OsStrExt as _;
    let mut buf = [0u8; 4096];
    // SAFETY: proc_pidpath writes at most `buf.len()` bytes into `buf`.
    let len = unsafe {
        libc::proc_pidpath(
            libc::c_int::try_from(pid).ok()?,
            buf.as_mut_ptr().cast(),
            u32::try_from(buf.len()).ok()?,
        )
    };
    let len = usize::try_from(len)
        .ok()
        .filter(|&n| n > 0 && n <= buf.len())?;
    Some(PathBuf::from(std::ffi::OsStr::from_bytes(&buf[..len])))
}

#[cfg(not(any(target_os = "linux", target_os = "macos")))]
#[must_use]
pub fn exe(_pid: u32) -> Option<PathBuf> {
    None
}

/// The working directory of `pid`.
#[cfg(target_os = "linux")]
#[must_use]
pub fn cwd(pid: u32) -> Option<PathBuf> {
    std::fs::read_link(format!("/proc/{pid}/cwd")).ok()
}

#[cfg(target_os = "macos")]
#[must_use]
pub fn cwd(pid: u32) -> Option<PathBuf> {
    use std::os::unix::ffi::OsStrExt as _;
    let mut info: libc::proc_vnodepathinfo = unsafe { std::mem::zeroed() };
    let size = libc::c_int::try_from(std::mem::size_of::<libc::proc_vnodepathinfo>()).ok()?;
    // SAFETY: the buffer is a zeroed proc_vnodepathinfo of the size passed.
    let n = unsafe {
        libc::proc_pidinfo(
            libc::c_int::try_from(pid).ok()?,
            libc::PROC_PIDVNODEPATHINFO,
            0,
            std::ptr::addr_of_mut!(info).cast(),
            size,
        )
    };
    if n != size {
        return None;
    }
    let bytes: Vec<u8> = info
        .pvi_cdir
        .vip_path
        .iter()
        .flatten()
        .take_while(|c| **c != 0)
        .map(|c| c.to_ne_bytes()[0])
        .collect();
    (!bytes.is_empty()).then(|| PathBuf::from(std::ffi::OsStr::from_bytes(&bytes)))
}

#[cfg(not(any(target_os = "linux", target_os = "macos")))]
#[must_use]
pub fn cwd(_pid: u32) -> Option<PathBuf> {
    None
}

/// The process the nearest runner on this process's chain started: the
/// shell it opened for a tool call, or this process when the runner ran
/// it directly. `None` when the chain reaches the person's session or the
/// top without a runner.
#[must_use]
pub fn started_by_runner() -> Option<u32> {
    let mut child = std::process::id();
    for _ in 0..DEPTH {
        let (ppid, _) = parent_and_name(child)?;
        if ppid == 0 {
            return None;
        }
        let (_, comm) = parent_and_name(ppid)?;
        if crate::is_harness_process(ppid, &comm) {
            return Some(child);
        }
        if crate::is_session(&comm) || ppid == 1 {
            return None;
        }
        child = ppid;
    }
    None
}

/// Whether `p` still runs: the same pid with the same start, and not a
/// zombie waiting to be reaped.
#[must_use]
pub fn alive(p: &Proc) -> bool {
    stat(p.pid).is_some_and(|s| s.start == p.start && !s.dead)
}

/// This boot, so a process recorded before a reboot or on another machine
/// never matches one here.
#[must_use]
pub fn boot() -> &'static str {
    static BOOT: std::sync::OnceLock<String> = std::sync::OnceLock::new();
    BOOT.get_or_init(|| {
        raw_boot_id()
            .map(|s| {
                s.trim()
                    .chars()
                    .filter(char::is_ascii_hexdigit)
                    .take(12)
                    .collect()
            })
            .filter(|s: &String| !s.is_empty())
            .unwrap_or_else(|| "-".into())
    })
}

#[cfg(target_os = "linux")]
fn raw_boot_id() -> Option<String> {
    std::fs::read_to_string("/proc/sys/kernel/random/boot_id").ok()
}

#[cfg(target_os = "macos")]
fn raw_boot_id() -> Option<String> {
    let mut buf = [0u8; 64];
    let mut size = buf.len();
    // SAFETY: buf holds `size` bytes, and sysctlbyname writes at most `size`.
    let rc = unsafe {
        libc::sysctlbyname(
            c"kern.bootsessionuuid".as_ptr(),
            buf.as_mut_ptr().cast(),
            &mut size,
            std::ptr::null_mut(),
            0,
        )
    };
    if rc != 0 || size == 0 {
        return None;
    }
    let end = buf[..size].iter().position(|&b| b == 0).unwrap_or(size);
    String::from_utf8(buf[..end].to_vec()).ok()
}

#[cfg(not(any(target_os = "linux", target_os = "macos")))]
fn raw_boot_id() -> Option<String> {
    None
}

/// `p` as one word that names it on this machine and boot.
#[must_use]
pub fn token(p: &Proc) -> String {
    format!("{}:{}:{}", boot(), p.pid, p.start)
}

/// Whether the process a [`token`] names still runs here.
#[must_use]
pub fn token_alive(token: &str) -> bool {
    let mut parts = token.splitn(3, ':');
    let (Some(at), Some(pid), Some(start)) = (parts.next(), parts.next(), parts.next()) else {
        return false;
    };
    let (Ok(pid), Ok(start)) = (pid.parse(), start.parse()) else {
        return false;
    };
    at == boot()
        && alive(&Proc {
            pid,
            start,
            comm: String::new(),
        })
}

const SHELLS: &[&str] = &[
    "sh", "bash", "dash", "zsh", "ksh", "mksh", "ash", "yash", "fish", "tcsh", "csh", "busybox",
];

/// Programs that run a command and stand between it and the shell that
/// asked for it.
const WRAPPERS: &[&str] = &[
    "env", "nice", "nohup", "timeout", "stdbuf", "setsid", "ionice", "chrt", "taskset", "time",
    "flock", "sudo", "doas", "xargs",
];

fn is_shell(p: &Proc) -> bool {
    SHELLS.contains(&p.comm.as_str())
}

fn is_wrapper(p: &Proc) -> bool {
    WRAPPERS.contains(&p.comm.as_str())
}

fn is_harness(p: &Proc) -> bool {
    crate::is_harness_process(p.pid, &p.comm)
}

/// The shell that ran the process whose ancestors are `chain`: past any
/// wrappers, the outermost of the shells nested directly above it, so a
/// script that starts a fresh `sh -c` per line is still one shell. `None`
/// when a program other than a shell ran it.
#[must_use]
pub fn calling_shell(chain: &[Proc]) -> Option<&Proc> {
    let mut rest = chain.iter().skip_while(|p| is_wrapper(p));
    let mut top = rest.next().filter(|p| is_shell(p))?;
    for p in rest {
        if is_shell(p) {
            top = p;
        } else if !is_wrapper(p) {
            break;
        }
    }
    Some(top)
}

fn exe_path_key(path: &Path) -> std::ffi::OsString {
    let text = path.as_os_str().to_string_lossy();
    match text.strip_suffix(" (deleted)") {
        Some(plain) => std::ffi::OsString::from(plain),
        None => path.as_os_str().to_os_string(),
    }
}

fn same_resolved_exe(pid: u32, mine: &Path) -> bool {
    exe(pid).is_some_and(|theirs| exe_path_key(&theirs) == exe_path_key(mine))
}

/// Whether `path` is the `ljos` executable. The resolved file name stays
/// `ljos` when argv0 is a link or another name.
#[must_use]
pub fn is_ljos_exe(path: &Path) -> bool {
    let key = exe_path_key(path);
    Path::new(&key)
        .file_name()
        .is_some_and(|name| name == "ljos")
}

fn is_python(p: &Proc) -> bool {
    p.comm.starts_with("python")
}

/// The shell a cast binds to. Ancestors whose resolved executable is
/// `mine` are this program, whatever argv0 said, and they do not end the
/// walk. A Python process that launched it does not end the walk either.
/// The outermost nested shell is then the one [`calling_shell`] would take.
/// `None` when some other program, an agent runner or the session is the
/// first program above this process.
#[must_use]
pub fn cast_shell<'a>(chain: &'a [Proc], mine: Option<&Path>) -> Option<&'a Proc> {
    let transparent =
        |p: &Proc| is_wrapper(p) || mine.is_some_and(|mine| same_resolved_exe(p.pid, mine));
    let mut i = 0;
    while i < chain.len() {
        let p = &chain[i];
        if transparent(p) || is_python(p) {
            i += 1;
            continue;
        }
        break;
    }
    let mut top = chain.get(i).filter(|p| is_shell(p))?;
    i += 1;
    while i < chain.len() {
        let p = &chain[i];
        if is_shell(p) {
            top = p;
        } else if !transparent(p) {
            break;
        }
        i += 1;
    }
    Some(top)
}

/// Where a chain stops being the hook's own: the person's session, a
/// terminal or the init system ([`crate::is_session`]), or pid 1 unless
/// it is a harness. Every sitting in that session shares it, and it
/// outlives each of them.
fn ends_the_walk(p: &Proc) -> bool {
    crate::is_session(&p.comm) || (p.pid == 1 && !is_harness(p))
}

/// The program that ran the process whose ancestors are `chain`, read up
/// to the session ([`ends_the_walk`]), which is never the program: the
/// nearest harness ([`crate::is_harness_process`]), so a `uv`, `npx` or
/// `node` that only started the hook and exits with it does not outrank
/// the harness above it; else the nearest one that is neither a shell
/// nor a wrapper, which keeps a harness that runs as plain `node`; else
/// the outermost of the shells and wrappers below the session. `None`
/// when the session ran the process itself.
#[must_use]
pub fn runner(chain: &[Proc]) -> Option<&Proc> {
    let own = chain.iter().take_while(|p| !ends_the_walk(p));
    own.clone()
        .find(|p| is_harness(p))
        .or_else(|| own.clone().find(|p| !is_shell(p) && !is_wrapper(p)))
        .or_else(|| own.last())
}

/// The runners that spawn `ljos hook`, by the name of the program they
/// are: `claude-code` is Claude Code's npm package.
const HOOK_RUNNERS: &[(&str, &str)] = &[
    ("claude", "claude"),
    ("claude-code", "claude"),
    ("codex", "codex"),
    ("cursor-agent", "cursor-agent"),
    ("cursor", "cursor"),
    ("grok", "grok"),
    ("opencode", "opencode"),
    ("gemini", "gemini"),
    ("agy", "agy"),
    ("antigravity", "agy"),
];

/// Runtimes a runner may ship as: the program is the directory or script
/// above them.
const RUNTIMES: &[&str] = &["node", "nodejs", "bun", "deno"];

/// The stem of a path component, so `cli.js` is the entry `cli`.
fn component_stem(component: &str) -> &str {
    component
        .strip_suffix(".js")
        .or_else(|| component.strip_suffix(".mjs"))
        .or_else(|| component.strip_suffix(".cjs"))
        .unwrap_or(component)
}

/// A path component that names where a runner is packed, not the runner.
fn layout_component(component: &str) -> bool {
    let name = component_stem(component);
    crate::version_like(name)
        || crate::PLACES.contains(&name)
        || crate::ENTRY_STEMS.contains(&name)
        || RUNTIMES.contains(&name)
        || matches!(name, "vendor" | "share")
        || name.starts_with('@')
        || name.contains("unknown-linux")
        || matches!(name, "x86_64" | "aarch64" | "arm64")
        || name.starts_with("armv")
}

/// The runner a component names, after an architecture suffix is dropped.
fn hook_name(component: &str) -> Option<&'static str> {
    let name = component_stem(component);
    let name = name.split_once("-x86_64").map_or(name, |(head, _)| head);
    let name = name.split_once("-aarch64").map_or(name, |(head, _)| head);
    HOOK_RUNNERS
        .iter()
        .find(|(n, _)| *n == name)
        .map(|(_, runner)| *runner)
}

/// The home this user's passwd entry names. A tool call sets `HOME` for
/// whatever it starts, but cannot change this.
#[must_use]
pub fn own_home() -> Option<std::path::PathBuf> {
    use std::os::unix::ffi::OsStrExt as _;
    let mut buf = vec![0u8; 1024];
    loop {
        // SAFETY: passwd is plain data, so all zeroes is a valid value.
        let mut entry: libc::passwd = unsafe { std::mem::zeroed() };
        let mut found: *mut libc::passwd = std::ptr::null_mut();
        // SAFETY: getpwuid_r writes at most buf.len() bytes into buf and
        // points entry's fields into it; buf outlives every read below.
        let rc = unsafe {
            libc::getpwuid_r(
                libc::getuid(),
                &mut entry,
                buf.as_mut_ptr().cast(),
                buf.len(),
                &mut found,
            )
        };
        if rc == libc::ERANGE && buf.len() < 1 << 20 {
            buf.resize(buf.len() * 2, 0);
            continue;
        }
        if rc != 0 || found.is_null() || entry.pw_dir.is_null() {
            return None;
        }
        // SAFETY: pw_dir is a NUL-terminated string inside buf.
        let dir = unsafe { std::ffi::CStr::from_ptr(entry.pw_dir) };
        let home = std::path::PathBuf::from(std::ffi::OsStr::from_bytes(dir.to_bytes()));
        return home.is_absolute().then_some(home);
    }
}

/// Where a runner is installed under the person's home ([`own_home`]):
/// a user `bin`, and the prefix npm's own guide gives a user for global
/// packages. These are trusted because the person owns them, which
/// also lets any process of the person's uid, a tool call among them,
/// replace what they hold: the check keeps out other users and copies
/// placed elsewhere, not the person's own account.
const HOME_ROOTS: &[&str] = &[".local/bin", ".cargo/bin", ".npm-global"];

/// Where a runner is installed for every user, and where npm keeps a
/// global package.
const SYSTEM_ROOTS: &[&str] = &[
    "/usr/bin",
    "/bin",
    "/usr/local/bin",
    "/opt/homebrew/bin",
    "/usr/lib/node_modules",
    "/usr/local/lib/node_modules",
    "/opt/homebrew/lib/node_modules",
];

/// The directories a runner is installed below, for a person whose
/// passwd home is `home`: the roots above, and an app directory of a
/// runner's name under `~/.local/share` or `/usr/share`, where a native
/// installer keeps the versions `~/.local/bin` links to.
fn install_roots(home: Option<&Path>) -> Vec<PathBuf> {
    let mut roots: Vec<PathBuf> = SYSTEM_ROOTS.iter().map(PathBuf::from).collect();
    let mut shares = vec![PathBuf::from("/usr/share")];
    if let Some(home) = home {
        roots.extend(HOME_ROOTS.iter().map(|root| home.join(root)));
        shares.push(home.join(".local/share"));
    }
    for share in shares {
        roots.extend(HOOK_RUNNERS.iter().map(|(name, _)| share.join(name)));
    }
    roots
}

/// Where Nix keeps what it builds.
const NIX_STORE: &str = "/nix/store";

/// The `STORE/HASH-NAME` entry `path` sits in, STORE being Nix's store
/// ([`NIX_STORE`]) and HASH 32 characters of Nix's base 32.
fn nix_entry(path: &Path, store: &Path) -> Option<PathBuf> {
    let name = path.strip_prefix(store).ok()?.iter().next()?.to_str()?;
    let (hash, rest) = name.split_at_checked(32)?;
    let hashed = hash
        .chars()
        .all(|c| "0123456789abcdfghijklmnpqrsvwxyz".contains(c));
    (hashed && rest.len() > 1 && rest.starts_with('-')).then(|| store.join(name))
}

/// The runner `path` names when it sits below a root ([`root_below`]),
/// and that root: the nearest component that is not packing layout
/// ([`layout_component`]), read from the file up to the root's own name,
/// so `share/claude/versions/2.1.3` is Claude Code.
fn runner_below(path: &Path, roots: &[PathBuf], store: &Path) -> Option<(&'static str, PathBuf)> {
    let root = root_below(path, roots, store)?;
    let parts = root
        .file_name()
        .into_iter()
        .chain(path.strip_prefix(&root).ok()?.iter())
        .map(std::ffi::OsStr::to_str)
        .collect::<Option<Vec<_>>>()?;
    let name = parts.iter().rev().find(|part| !layout_component(part))?;
    Some((hook_name(name)?, root))
}

/// The one of `roots`, or the entry of the Nix store `store`, that
/// `path` sits strictly below. The path must be absolute and plain,
/// since a `..` after the root would leave it. A path the kernel marks
/// ` (deleted)` is not the file that was installed.
fn root_below(path: &Path, roots: &[PathBuf], store: &Path) -> Option<PathBuf> {
    let plain = path.is_absolute()
        && path.components().all(|c| {
            matches!(
                c,
                std::path::Component::RootDir | std::path::Component::Normal(_)
            )
        });
    if !plain || path.to_str()?.contains(" (deleted)") {
        return None;
    }
    roots
        .iter()
        .cloned()
        .chain(nix_entry(path, store))
        .find(|root| path != root.as_path() && path.starts_with(root))
}

/// A group as the group database lists it.
struct GroupEntry {
    name: std::ffi::OsString,
    members: Vec<std::ffi::OsString>,
}

/// The account lookups [`group_is_private`] makes. `None` is a lookup
/// that failed or that cannot be shown to be complete, which is never
/// read as an empty answer.
trait Accounts {
    fn user_name(&self, uid: u32) -> Option<std::ffi::OsString>;
    fn group(&self, gid: u32) -> Option<GroupEntry>;
    /// The uid of every passwd entry whose primary group is `gid`.
    fn primary_members(&self, gid: u32) -> Option<Vec<u32>>;
}

/// The passwd and group databases: a user's name through the C
/// library, and a group and the accounts in it from `/etc/group` and
/// `/etc/passwd` themselves ([`group_in_files`], [`primary_in_files`]),
/// since a lookup by gid returns only the first line and enumerating
/// NSS can stop short.
struct SystemAccounts;

/// Runs a `get*_r` lookup with a buffer that grows while it is too small.
fn with_buf<T>(mut lookup: impl FnMut(&mut [u8]) -> Result<Option<T>, i32>) -> Option<T> {
    let mut buf = vec![0u8; 1024];
    loop {
        match lookup(&mut buf) {
            Err(libc::ERANGE) if buf.len() < 1 << 20 => buf.resize(buf.len() * 2, 0),
            Ok(found) => return found,
            Err(_) => return None,
        }
    }
}

/// # Safety
/// `ptr` is a NUL-terminated string.
unsafe fn os_string(ptr: *const libc::c_char) -> std::ffi::OsString {
    use std::os::unix::ffi::OsStrExt as _;
    // SAFETY: the caller's contract.
    let bytes = unsafe { std::ffi::CStr::from_ptr(ptr) }.to_bytes();
    std::ffi::OsStr::from_bytes(bytes).to_os_string()
}

impl Accounts for SystemAccounts {
    fn user_name(&self, uid: u32) -> Option<std::ffi::OsString> {
        with_buf(|buf| {
            // SAFETY: passwd is plain data, so all zeroes is a valid value.
            let mut entry: libc::passwd = unsafe { std::mem::zeroed() };
            let mut found: *mut libc::passwd = std::ptr::null_mut();
            // SAFETY: getpwuid_r writes at most buf.len() bytes into buf
            // and points entry's fields into it.
            let rc = unsafe {
                libc::getpwuid_r(
                    uid,
                    &mut entry,
                    buf.as_mut_ptr().cast(),
                    buf.len(),
                    &mut found,
                )
            };
            if rc != 0 {
                return Err(rc);
            }
            // SAFETY: a found entry's pw_name is a string inside buf.
            Ok((!found.is_null() && !entry.pw_name.is_null())
                .then(|| unsafe { os_string(entry.pw_name) }))
        })
    }

    fn group(&self, gid: u32) -> Option<GroupEntry> {
        group_in_files(Path::new(ETC), gid)
    }

    fn primary_members(&self, gid: u32) -> Option<Vec<u32>> {
        primary_in_files(Path::new(ETC), gid)
    }
}

/// Where the account files and `nsswitch.conf` are.
const ETC: &str = "/etc";

/// Whether `etc/nsswitch.conf` sends database `db` to `files` and
/// nothing else, so the file under `etc` is all of it. A missing
/// file, a missing or repeated line, or any other source, such as
/// `systemd`, `sss`, `ldap` or `compat`, may add accounts that file
/// does not list.
fn files_only(etc: &Path, db: &str) -> bool {
    let Ok(conf) = std::fs::read_to_string(etc.join("nsswitch.conf")) else {
        return false;
    };
    let mut lines = conf
        .lines()
        .map(|line| line.split('#').next().unwrap_or_default())
        .filter_map(|line| line.split_once(':'))
        .filter(|(name, _)| name.trim() == db);
    let (Some((_, sources)), None) = (lines.next(), lines.next()) else {
        return false;
    };
    sources.split_whitespace().eq(["files"])
}

/// The one line of `etc/group` for `gid`, read only when group is
/// that file alone ([`files_only`]). `None` when no line or more than
/// one has that gid, since a lookup returns only the first and the
/// members of the others still hold the group, and when the file
/// cannot be read whole, as for `passwd` ([`primary_in_files`]).
fn group_in_files(etc: &Path, gid: u32) -> Option<GroupEntry> {
    if !files_only(etc, "group") {
        return None;
    }
    let text = std::fs::read_to_string(etc.join("group")).ok()?;
    let mut found = None;
    for line in text.lines() {
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        if line.starts_with(['+', '-']) {
            return None;
        }
        let fields: Vec<&str> = line.split(':').collect();
        let [name, _, id, members] = fields[..] else {
            return None;
        };
        if id.parse::<u32>().ok()? != gid {
            continue;
        }
        if found.is_some() {
            return None;
        }
        found = Some(GroupEntry {
            name: name.into(),
            members: members
                .split(',')
                .filter(|m| !m.is_empty())
                .map(Into::into)
                .collect(),
        });
    }
    found
}

/// The uid of every line of `etc/passwd` whose primary group is `gid`,
/// read only when passwd is that file alone ([`files_only`]). `None`
/// when the file cannot be read whole: a line that is not seven fields
/// with numeric ids, or a `+` or `-` line, which names accounts kept
/// elsewhere.
fn primary_in_files(etc: &Path, gid: u32) -> Option<Vec<u32>> {
    if !files_only(etc, "passwd") {
        return None;
    }
    let text = std::fs::read_to_string(etc.join("passwd")).ok()?;
    let mut uids = Vec::new();
    for line in text.lines() {
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        if line.starts_with(['+', '-']) {
            return None;
        }
        let fields: Vec<&str> = line.split(':').collect();
        let [_, _, uid, primary, _, _, _] = fields[..] else {
            return None;
        };
        let (uid, primary) = (uid.parse::<u32>().ok()?, primary.parse::<u32>().ok()?);
        if primary == gid {
            uids.push(uid);
        }
    }
    Some(uids)
}

/// Whether group `gid` holds no one but user `uid`: it bears the user's
/// name, lists no other member, and is no other account's primary group.
fn group_is_private(accounts: &dyn Accounts, uid: u32, gid: u32) -> bool {
    let (Some(user), Some(group), Some(primary)) = (
        accounts.user_name(uid),
        accounts.group(gid),
        accounts.primary_members(gid),
    ) else {
        return false;
    };
    group.name == user
        && group.members.iter().all(|member| *member == user)
        && primary.iter().all(|other| *other == uid)
}

/// Who [`person_keeps`] judges a file for: this process's user,
/// primary group and supplementary groups (`None` when they could not
/// be read), and whether the primary group is the user's alone, asked
/// only when a file is group-writable.
struct Person<'a> {
    uid: u32,
    gid: u32,
    groups: Option<Vec<u32>>,
    accounts: &'a dyn Accounts,
    private_group: std::cell::OnceCell<bool>,
}

impl<'a> Person<'a> {
    fn new(accounts: &'a dyn Accounts) -> Self {
        // SAFETY: getuid and getgid take no arguments and only read the
        // process identity.
        let (uid, gid) = unsafe { (libc::getuid(), libc::getgid()) };
        Person {
            uid,
            gid,
            groups: supplementary_groups(),
            accounts,
            private_group: std::cell::OnceCell::new(),
        }
    }

    /// Whether the person writes what group `gid` may write. Groups that
    /// could not be read count as every group.
    fn in_group(&self, gid: u32) -> bool {
        gid == self.gid
            || self
                .groups
                .as_ref()
                .is_none_or(|groups| groups.contains(&gid))
    }

    fn private_group(&self) -> bool {
        *self
            .private_group
            .get_or_init(|| group_is_private(self.accounts, self.uid, self.gid))
    }
}

/// This process's supplementary groups.
fn supplementary_groups() -> Option<Vec<u32>> {
    // SAFETY: a size of zero asks only for the count and writes nothing.
    let count = unsafe { libc::getgroups(0, std::ptr::null_mut()) };
    let mut groups = vec![0; usize::try_from(count).ok()?];
    // SAFETY: getgroups writes at most `count` ids into groups.
    let got = unsafe { libc::getgroups(count, groups.as_mut_ptr()) };
    groups.truncate(usize::try_from(got).ok()?);
    Some(groups)
}

/// A file's owner, group and mode.
#[derive(Clone, Copy)]
struct Owner {
    uid: u32,
    gid: u32,
    mode: u32,
}

impl From<&std::fs::Metadata> for Owner {
    fn from(meta: &std::fs::Metadata) -> Self {
        use std::os::unix::fs::MetadataExt as _;
        Owner {
            uid: meta.uid(),
            gid: meta.gid(),
            mode: meta.mode(),
        }
    }
}

/// The owner of `/` and of each directory below it down to `file`, and
/// of `file`, each read from a descriptor opened beneath the one before
/// without following a link, so a directory swapped for a link after
/// `file` was resolved is not walked through. One swapped for another
/// directory leads to another file than `expect`, the (device, inode)
/// the caller holds for `file`. `None` unless every component above
/// `file` is a directory and the file the walk ends on is a regular
/// file that is `expect`.
fn pinned_walk(file: &Path, expect: (u64, u64)) -> Option<Vec<Owner>> {
    use std::os::fd::{AsRawFd as _, FromRawFd as _};
    use std::os::unix::ffi::OsStrExt as _;
    use std::os::unix::fs::MetadataExt as _;
    #[cfg(target_os = "linux")]
    let flags = libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC;
    #[cfg(not(target_os = "linux"))]
    let flags = libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_CLOEXEC;
    let open = |dir: libc::c_int, name: &std::ffi::CStr| {
        // SAFETY: name is NUL-terminated, and openat only reads it.
        let fd = unsafe { libc::openat(dir, name.as_ptr(), flags) };
        // SAFETY: a descriptor openat returned is open and owned here.
        (fd >= 0).then(|| std::fs::File::from(unsafe { std::os::fd::OwnedFd::from_raw_fd(fd) }))
    };
    let mut parts = file.components();
    if parts.next() != Some(std::path::Component::RootDir) {
        return None;
    }
    let mut at = open(libc::AT_FDCWD, c"/")?;
    let mut meta = at.metadata().ok()?;
    let mut owners = vec![Owner::from(&meta)];
    for part in parts {
        let std::path::Component::Normal(name) = part else {
            return None;
        };
        if !meta.is_dir() {
            return None;
        }
        at = open(
            at.as_raw_fd(),
            &std::ffi::CString::new(name.as_bytes()).ok()?,
        )?;
        meta = at.metadata().ok()?;
        owners.push(Owner::from(&meta));
    }
    (meta.is_file() && expect == (meta.dev(), meta.ino())).then_some(owners)
}

/// Whether a Nix store and an entry in it are as Nix leaves them, so
/// that only Nix can change what the entry holds. The store is root's,
/// the person cannot write it, and it is sticky if its group or anyone
/// may write it; the entry is then root's, as the daemon builds it. On
/// a single-user install the store is the person's and no one else may
/// write it, and the entry is the person's or root's. Such a store, like
/// a home root ([`HOME_ROOTS`]), is writable by a tool call of the
/// person's uid, and is trusted only because the person owns it.
fn store_keeps(store: Owner, entry: Owner, person: &Person) -> bool {
    let group = store.mode & 0o020 != 0;
    let anyone = store.mode & 0o002 != 0;
    if store.uid == 0 {
        let person_writes = anyone
            || (group && person.in_group(store.gid))
            || (person.uid == 0 && store.mode & 0o200 != 0);
        !person_writes && (!group || store.mode & 0o1000 != 0) && entry.uid == 0
    } else {
        store.uid == person.uid && !group && !anyone && (entry.uid == 0 || entry.uid == person.uid)
    }
}

/// Whether root or `person` owns a file, and no one else can write it
/// but `person`'s primary group when that group is theirs alone.
fn person_keeps(file: Owner, person: &Person) -> bool {
    (file.uid == 0 || file.uid == person.uid)
        && file.mode & 0o002 == 0
        && (file.mode & 0o020 == 0 || (file.gid == person.gid && person.private_group()))
}

/// The runner a program file is, when the file is an installed copy for
/// the person whose passwd home is `home` ([`runner_below`]).
/// `~/.local/share/claude/versions/2.1.3` is Claude Code, and so is
/// `/usr/lib/node_modules/@anthropic-ai/claude-code/cli.js`. A bundled
/// runtime (`cursor-agent/versions/V/node`) is the runner it ships in.
/// The file and the roots are compared as the kernel resolves them, so a
/// link from `~/.local/bin` into `/tmp` is read in `/tmp`. A copy whose
/// name is the runner, in a temp directory, a project tree or a `.local`
/// of its own making, is not: the name alone is what a tool call can
/// choose. Nor is a file that someone other than the person could have
/// written, or swapped through a directory between it and its root, or
/// an entry of a Nix store `store` that Nix does not keep
/// ([`store_keeps`]). The directories and the file are judged as they
/// were opened ([`pinned_walk`]) from `path` resolved once, and the
/// file the walk ends on must be `expect`, the (device, inode) the
/// caller holds for the file it means.
fn runner_of_file(
    path: &Path,
    home: Option<&Path>,
    store: &Path,
    person: &Person,
    expect: (u64, u64),
) -> Option<&'static str> {
    runner_at(
        &std::fs::canonicalize(path).ok()?,
        home,
        store,
        person,
        expect,
    )
}

/// [`runner_of_file`] for `file`, a path already resolved.
fn runner_at(
    file: &Path,
    home: Option<&Path>,
    store: &Path,
    person: &Person,
    expect: (u64, u64),
) -> Option<&'static str> {
    let (roots, store) = resolved_roots(home, store);
    let (runner, root) = runner_below(file, &roots, &store)?;
    kept_below(file, &root, &store, person, expect).then_some(runner)
}

/// Whether `path` is a runtime ([`RUNTIMES`]) by its exact name, and
/// an installed copy kept as a runner file is ([`runner_of_file`]):
/// below an install root, left to the person, and the file `expect`.
fn runtime_of_file(
    path: &Path,
    home: Option<&Path>,
    store: &Path,
    person: &Person,
    expect: (u64, u64),
) -> bool {
    let Ok(file) = std::fs::canonicalize(path) else {
        return false;
    };
    let named = file
        .file_name()
        .and_then(std::ffi::OsStr::to_str)
        .is_some_and(|name| RUNTIMES.contains(&name));
    let (roots, store) = resolved_roots(home, store);
    named
        && root_below(&file, &roots, &store)
            .is_some_and(|root| kept_below(&file, &root, &store, person, expect))
}

/// The install roots for `home` ([`install_roots`]) and the Nix store
/// `store`, resolved.
fn resolved_roots(home: Option<&Path>, store: &Path) -> (Vec<PathBuf>, PathBuf) {
    // Resolved once per process for each home and store: the walk asks
    // for them once per ancestor, and each resolve reads every link on
    // the way to every root.
    type Roots = (Vec<PathBuf>, PathBuf);
    type Resolved = (Option<PathBuf>, PathBuf, Roots);
    static RESOLVED: std::sync::LazyLock<std::sync::Mutex<Vec<Resolved>>> =
        std::sync::LazyLock::new(|| std::sync::Mutex::new(Vec::new()));
    let key_home = home.map(Path::to_path_buf);
    if let Some((_, _, roots)) = RESOLVED
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .iter()
        .find(|(h, s, _)| *h == key_home && s == store)
    {
        return roots.clone();
    }
    let roots: Vec<PathBuf> = install_roots(home)
        .iter()
        .filter_map(|root| std::fs::canonicalize(root).ok())
        .collect();
    let resolved_store = std::fs::canonicalize(store).unwrap_or_else(|_| store.to_path_buf());
    let out = (roots, resolved_store);
    RESOLVED
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .push((key_home, store.to_path_buf(), out.clone()));
    out
}

/// Whether `file`, a resolved path below install root `root`, is the
/// file `expect` and left to the person ([`walk_kept`]) as the walk
/// reads it ([`pinned_walk`]). A file in a temp directory never is.
fn kept_below(file: &Path, root: &Path, store: &Path, person: &Person, expect: (u64, u64)) -> bool {
    if crate::bookkeep::resolved_path_is_temp(file) {
        return false;
    }
    let (Some(owners), Some(at)) = (
        pinned_walk(file, expect),
        root.components().count().checked_sub(1),
    ) else {
        return false;
    };
    walk_kept(&owners, at, root.parent() == Some(store), person)
}

/// Whether the owners [`pinned_walk`] read leave a file to the person,
/// its install root being at `at`. The directory holding the root, the
/// root, and all below it are kept by the person ([`person_keeps`]),
/// since whoever may write the root's directory may rename the root.
/// For an entry of a Nix store, the store and the entry are as Nix keeps
/// them ([`store_keeps`]) instead.
fn walk_kept(owners: &[Owner], at: usize, in_store: bool, person: &Person) -> bool {
    let (Some(&above), Some(&root)) = (
        at.checked_sub(1).and_then(|above| owners.get(above)),
        owners.get(at),
    ) else {
        return false;
    };
    let top = if in_store {
        store_keeps(above, root, person)
    } else {
        person_keeps(above, person)
    };
    top && owners[at..].iter().all(|dir| person_keeps(*dir, person))
}

#[cfg(target_os = "linux")]
fn running_exe(pid: u32) -> Option<(PathBuf, Option<(u64, u64)>)> {
    use std::os::unix::fs::MetadataExt as _;
    let path = format!("/proc/{pid}/exe");
    let exe = std::fs::read_link(&path).ok()?;
    let running = std::fs::metadata(&path)
        .ok()
        .map(|meta| (meta.dev(), meta.ino()));
    Some((exe, running))
}

#[cfg(not(target_os = "linux"))]
fn running_exe(pid: u32) -> Option<(PathBuf, Option<(u64, u64)>)> {
    use std::os::unix::fs::MetadataExt as _;
    let exe = exe(pid)?;
    let running = std::fs::metadata(&exe)
        .ok()
        .map(|meta| (meta.dev(), meta.ino()));
    Some((exe, running))
}

/// The runner `pid` is, from the file the kernel runs it from, never
/// from the name it gives itself. An installed runtime such as `node`
/// ([`runtime_of_file`]) is the runner whose script it runs, that
/// script's path resolved on disk and judged as a runner file is. The
/// script's path comes from the process's own arguments, so only a
/// runtime the person installed is believed about it.
#[must_use]
pub fn exe_runner(pid: u32) -> Option<&'static str> {
    let (exe, running) = running_exe(pid)?;
    let script = || {
        let words = argv(pid)?;
        let script = words
            .into_iter()
            .skip(1)
            .find(|a| !a.is_empty() && !a.starts_with('-'))?;
        let cwd = cwd(pid)?;
        Some(cwd.join(script))
    };
    let home = own_home();
    let person = Person::new(&SystemAccounts);
    runner_from(
        &exe,
        running,
        script,
        home.as_deref(),
        Path::new(NIX_STORE),
        &person,
    )
}

/// [`exe_runner`] for a process run from `exe`, whose (device, inode)
/// the kernel reports as `running`, and that names `script` as the
/// script a runtime there runs. `None` when `running` could not be
/// read, since the path alone may name another file than the one the
/// process runs.
fn runner_from(
    exe: &Path,
    running: Option<(u64, u64)>,
    script: impl FnOnce() -> Option<PathBuf>,
    home: Option<&Path>,
    store: &Path,
    person: &Person,
) -> Option<&'static str> {
    use std::os::unix::fs::MetadataExt as _;
    let running = running?;
    if let Some(r) = runner_of_file(exe, home, store, person, running) {
        return Some(r);
    }
    if !runtime_of_file(exe, home, store, person, running) {
        return None;
    }
    let script = std::fs::canonicalize(script()?).ok()?;
    let meta = std::fs::metadata(&script).ok()?;
    runner_of_file(&script, home, store, person, (meta.dev(), meta.ino()))
}

/// Editors and agents. A server whose chain still holds one of these is
/// not an orphan. Matched on the file name, without regard to case.
const EDITORS: &[&str] = &[
    "claude",
    "claude-code",
    "codex",
    "cursor",
    "cursor-agent",
    "opencode",
    "opencode-ai",
    "agy",
    "antigravity",
    "grok",
    "gemini",
    "copilot",
    "qwen",
    "droid",
    "crush",
    "kiro",
    "kiro-cli",
    "hermes",
    "omp",
    "cline",
    "aider",
    "code",
    "code-oss",
    "codium",
    "vscodium",
    "zed",
    "zed-editor",
    "windsurf",
    "goland",
    "idea",
    "pycharm",
    "webstorm",
    "rustrover",
    "sublime_text",
    "emacs",
    "nvim",
    "vim",
    "gvim",
    "helix",
    "lapce",
    "kate",
    "gedit",
    "cursor helper",
];

/// Whether `name` is an editor or an agent. A path uses its file name.
#[must_use]
pub fn is_editor_name(name: &str) -> bool {
    let base = name.rsplit(['/', '\\']).next().unwrap_or(name).trim();
    EDITORS.iter().any(|item| base.eq_ignore_ascii_case(item))
}

#[cfg(target_os = "linux")]
fn command_base(pid: u32) -> Option<String> {
    let raw = std::fs::read(format!("/proc/{pid}/cmdline")).ok()?;
    let first = raw.split(|b| *b == 0).find(|word| !word.is_empty())?;
    let text = String::from_utf8_lossy(first);
    Some(text.rsplit(['/', '\\']).next().unwrap_or(&text).to_string())
}

#[cfg(target_os = "macos")]
fn command_base(pid: u32) -> Option<String> {
    let mut mib = [
        libc::CTL_KERN,
        libc::KERN_PROCARGS2,
        libc::c_int::try_from(pid).ok()?,
    ];
    let mut size: libc::size_t = 0;
    // SAFETY: a null buffer asks sysctl for the size alone.
    let asked = unsafe {
        libc::sysctl(
            mib.as_mut_ptr(),
            3,
            std::ptr::null_mut(),
            &mut size,
            std::ptr::null_mut(),
            0,
        )
    };
    if asked != 0 || size < 4 {
        return None;
    }
    let mut buf = vec![0u8; size];
    // SAFETY: buf holds the size sysctl reported.
    let read = unsafe {
        libc::sysctl(
            mib.as_mut_ptr(),
            3,
            buf.as_mut_ptr().cast(),
            &mut size,
            std::ptr::null_mut(),
            0,
        )
    };
    if read != 0 {
        return None;
    }
    buf.truncate(size);
    let argc = usize::try_from(i32::from_ne_bytes(buf.get(..4)?.try_into().ok()?)).ok()?;
    if argc == 0 {
        return None;
    }
    let word = buf[4..]
        .split(|b| *b == 0)
        .skip(1)
        .find(|word| !word.is_empty())?;
    let text = String::from_utf8_lossy(word);
    Some(text.rsplit(['/', '\\']).next().unwrap_or(&text).to_string())
}

/// Whether an editor or an agent is still above this process. Linux also
/// accepts the runner named by the file the process is running, so a
/// `node` that is only hosting an editor still counts.
#[cfg(target_os = "linux")]
#[must_use]
pub fn editor_above() -> bool {
    ancestors().into_iter().any(|proc| {
        is_editor_name(&proc.comm)
            || command_base(proc.pid).is_some_and(|name| is_editor_name(&name))
            || exe_runner(proc.pid).is_some_and(is_editor_name)
    })
}

#[cfg(target_os = "macos")]
#[must_use]
pub fn editor_above() -> bool {
    // SAFETY: getppid has no preconditions.
    let mut pid = unsafe { libc::getppid() } as u32;
    for _ in 0..DEPTH {
        if pid <= 1 {
            return false;
        }
        let Some((ppid, comm)) = parent_and_name(pid) else {
            return false;
        };
        if is_editor_name(&comm) || command_base(pid).is_some_and(|name| is_editor_name(&name)) {
            return true;
        }
        if ppid == pid {
            return false;
        }
        pid = ppid;
    }
    false
}

#[cfg(not(any(target_os = "linux", target_os = "macos")))]
#[must_use]
pub fn editor_above() -> bool {
    false
}

/// Whether `cmd`, a shell's `-c` line, runs `ljos hook` and nothing else:
/// the program (`ljos`, a path to it, or the plugin launcher with `ljos`),
/// `hook`, and flags. `${NAME}` and double quotes are the runner's own
/// spelling of the launcher; a redirection, pipe or second command,
/// which a tool call needs to hand the hook a payload, is not.
fn bare_hook_command(cmd: &str) -> bool {
    let mut plain = String::new();
    let mut rest = cmd;
    while let Some(at) = rest.find("${") {
        plain.push_str(&rest[..at]);
        let Some(close) = rest[at..].find('}') else {
            return false;
        };
        let name = &rest[at + 2..at + close];
        if name.is_empty() || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
            return false;
        }
        plain.push_str("VAR");
        rest = &rest[at + close + 1..];
    }
    plain.push_str(rest);
    let plain = plain.replace('"', "");
    if plain.contains(|c: char| "<>|;&$`(){}\\'\n\r*?[]~#!".contains(c)) {
        return false;
    }
    let words: Vec<&str> = plain.split_whitespace().collect();
    let base = |w: &str| w.rsplit('/').next().unwrap_or(w).to_string();
    let at = match words.first().map(|w| base(w)).as_deref() {
        Some("ljos-plugin") if words.get(1) == Some(&"ljos") => 2,
        Some("ljos") => 1,
        _ => return false,
    };
    words.get(at) == Some(&"hook")
        && words[at + 1..].iter().all(|w| {
            w.starts_with("--")
                || w.chars()
                    .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
        })
}

/// Whether `pid` is the shell a runner opens to run its configured hook
/// command: a shell by the file it runs from, started as `SHELL -c CMD`
/// with [`bare_hook_command`] for CMD. `dash` forks that command rather
/// than replacing itself with it.
fn hook_shell(pid: u32) -> bool {
    let Some(exe) = exe(pid) else {
        return false;
    };
    let shell = exe
        .file_name()
        .and_then(|f| f.to_str())
        .is_some_and(|f| SHELLS.contains(&f));
    let words = argv(pid).unwrap_or_default();
    shell && matches!(words.as_slice(), [_, c, cmd] if c == "-c" && bare_hook_command(cmd))
}

/// The nearest process above this one that is a runner by the file the
/// kernel runs it from ([`exe_runner`]), and which runner it is.
#[must_use]
pub fn runner_above() -> Option<(Proc, &'static str)> {
    ancestors()
        .into_iter()
        .find_map(|p| exe_runner(p.pid).map(|r| (p, r)))
}

/// Variables a runner gives the shell of a tool call. A runner started
/// with one runs inside another runner's tool call.
fn tool_call_stamp(env: &[(String, String)]) -> Option<&str> {
    env.iter()
        .find(|(k, v)| {
            matches!(
                k.as_str(),
                "CLAUDECODE" | "CURSOR_AGENT" | "CODEX_THREAD_ID"
            ) || (crate::runner_session_var(k, v) && !k.starts_with("LJOS_"))
        })
        .map(|(k, _)| k.as_str())
}

/// One tool call the guard's `PreToolUse` saw: the session and cgroup it
/// could not shed, the start time of that hook (a later process is part
/// of the call), and the runner that spawned the hook.
struct ToolMark {
    sid: u32,
    at: u64,
    runner_pid: u32,
    runner_start: u64,
    shell_pid: u32,
    shell_start: u64,
    cgroup: String,
}

/// The session and cgroup of this process. A child inherits both until
/// it calls `setsid` or migrates cgroup.
struct Here {
    sid: u32,
    cgroup: String,
}

fn marks_path() -> std::path::PathBuf {
    crate::runtime_dir().join("tool-calls")
}

fn broken_path() -> std::path::PathBuf {
    crate::runtime_dir().join("tool-calls.broken")
}

/// The calling process's session id.
fn current_sid() -> Result<u32, String> {
    // SAFETY: getsid(0) reads the calling process's session id and writes
    // nothing the caller owns.
    let sid = unsafe { libc::getsid(0) };
    if sid < 0 {
        return Err(
            "the session id cannot be read, so a tool call cannot be told from the runner".into(),
        );
    }
    u32::try_from(sid).map_err(|_| "the session id does not fit".into())
}

fn here_evidence() -> Result<Here, String> {
    let sid = current_sid()?;
    #[cfg(target_os = "linux")]
    let cgroup = std::fs::read_to_string("/proc/self/cgroup").map_err(|_| {
        "the cgroup cannot be read, so a tool call cannot be told from the runner".to_string()
    })?;
    #[cfg(not(target_os = "linux"))]
    let cgroup = format!("sid:{sid}");
    if cgroup.is_empty() {
        return Err("the cgroup is empty, so a tool call cannot be told from the runner".into());
    }
    Ok(Here { sid, cgroup })
}

fn self_start() -> Result<u64, String> {
    stat(std::process::id())
        .map(|row| row.start)
        .ok_or_else(|| "this process's start time cannot be read".into())
}

/// Remember that a tool-call record could not be written. A later read
/// then fails closed: a missing record means no tool call, and a failed
/// write must not look like that.
/// A tool call may have happened and its evidence could not be taken.
/// Later reads fail closed instead of looking like a quiet runtime.
pub fn seal_unreadable_tool_call() {
    mark_broken();
}

fn mark_broken() {
    let dir = crate::runtime_dir();
    let _ = std::fs::create_dir_all(&dir);
    let mut options = std::fs::OpenOptions::new();
    options.create(true).write(true).truncate(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt as _;
        options.mode(0o600);
    }
    let _ = options.open(broken_path());
}

fn tool_marks() -> Result<Vec<ToolMark>, String> {
    if broken_path().exists() {
        return Err(
            "a tool-call record could not be written, so nothing is kept as the person's".into(),
        );
    }
    let text = match std::fs::read_to_string(marks_path()) {
        Ok(text) => text,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(_) => {
            return Err(
                "the tool-call record cannot be read, so nothing is kept as the person's".into(),
            );
        }
    };
    let mut marks = Vec::new();
    for line in text.lines() {
        let fields: Vec<&str> = line.split('\t').collect();
        if fields.len() != 8 || fields[0] != "1" {
            return Err(
                "the tool-call record is corrupt, so nothing is kept as the person's".into(),
            );
        }
        let number = |index: usize, label: &str| -> Result<u64, String> {
            fields[index].parse().map_err(|_| {
                format!(
                    "the tool-call record has a bad {label}, so nothing is kept as the person's"
                )
            })
        };
        let cgroup = hex::decode(fields[7])
            .ok()
            .and_then(|bytes| String::from_utf8(bytes).ok())
            .ok_or("the tool-call record has a bad cgroup, so nothing is kept as the person's")?;
        let narrow = |value: u64, label: &str| -> Result<u32, String> {
            u32::try_from(value).map_err(|_| {
                format!(
                    "the tool-call record has a bad {label}, so nothing is kept as the person's"
                )
            })
        };
        marks.push(ToolMark {
            sid: narrow(number(1, "session")?, "session")?,
            at: number(2, "start")?,
            runner_pid: narrow(number(3, "runner")?, "runner")?,
            runner_start: number(4, "runner start")?,
            shell_pid: narrow(number(5, "shell")?, "shell")?,
            shell_start: number(6, "shell start")?,
            cgroup,
        });
    }
    Ok(marks)
}

/// Record the tool call whose guard hook this is. The runner is `runner`,
/// the process that spawned the hook. The hook's own start time is the
/// watermark: a process started later, in this session or cgroup, is the
/// tool call even after it detaches.
///
/// # Errors
///
/// The session, cgroup or start time cannot be read, or the record cannot
/// be written. A failed write leaves a sentinel so later reads fail closed.
pub fn note_tool_call(runner: &Proc) -> Result<(), String> {
    // A tool call whose session, cgroup or start time cannot be read must
    // not look like a runtime that has seen no tool call.
    let here = match here_evidence() {
        Ok(here) => here,
        Err(why) => {
            mark_broken();
            return Err(why);
        }
    };
    let at = match self_start() {
        Ok(at) => at,
        Err(why) => {
            mark_broken();
            return Err(why);
        }
    };
    let dir = crate::runtime_dir();
    let mut builder = std::fs::DirBuilder::new();
    builder.recursive(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::DirBuilderExt as _;
        builder.mode(0o700);
    }
    if builder.create(&dir).is_err() {
        mark_broken();
        return Err("the tool-call record directory cannot be created".into());
    }
    // sid, watermark, runner pid and start, tool shell pid and start
    // (unset when the shell does not exist yet), cgroup text as hex.
    // One line stays under PIPE_BUF so the append is one write.
    let line = format!(
        "1\t{}\t{at}\t{}\t{}\t0\t0\t{}\n",
        here.sid,
        runner.pid,
        runner.start,
        hex::encode(here.cgroup.as_bytes())
    );
    if line.len() > 4096 {
        mark_broken();
        return Err("the tool-call record does not fit one write".into());
    }
    let mut options = std::fs::OpenOptions::new();
    options.create(true).append(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt as _;
        options.mode(0o600);
    }
    let opened = options.open(marks_path());
    let mut file = match opened {
        Ok(file) => file,
        Err(_) => {
            mark_broken();
            return Err("the tool-call record cannot be written".into());
        }
    };
    use std::io::Write as _;
    if file.write_all(line.as_bytes()).is_err() {
        mark_broken();
        return Err("the tool-call record cannot be written".into());
    }
    Ok(())
}

/// Whether `runner` is the runner a person started, rather than a process
/// a recorded tool call still owns. The same runner process that recorded
/// a mark is that opener. Any other process that shares the mark's cgroup
/// or session and is not older than the mark is the tool call. No marks
/// means the person has not made a tool call in this runtime yet.
fn confirm_runner(runner: &Proc) -> Result<(), String> {
    let here = here_evidence()?;
    let marks = tool_marks()?;
    let chain = ancestors();
    for mark in &marks {
        if mark.runner_pid == runner.pid && mark.runner_start == runner.start {
            continue;
        }
        if mark.shell_pid > 0
            && chain
                .iter()
                .any(|proc| proc.pid == mark.shell_pid && proc.start == mark.shell_start)
        {
            return Err(format!(
                "{} (pid {}) descends from a recorded tool call",
                runner.comm, runner.pid
            ));
        }
        let same_place = mark.sid == here.sid || mark.cgroup == here.cgroup;
        if same_place && runner.start >= mark.at {
            return Err(format!(
                "{} (pid {}) shares a recorded tool call's cgroup or session and is not older than that tool call",
                runner.comm, runner.pid
            ));
        }
    }
    Ok(())
}

/// The installed runner above this process, checked against the tool-call
/// record ([`confirm_runner`]). Shells and wrappers are stepped over. The
/// first other program that is not an installed runner ends the walk, so
/// a copy named like a runner cannot hide behind a real one further up.
///
/// # Errors
///
/// No installed runner is above this process, or the one that is still
/// belongs to a recorded tool call.
pub fn placed_runner() -> Result<(), String> {
    for proc in ancestors() {
        if is_shell(&proc) || is_wrapper(&proc) {
            continue;
        }
        if ends_the_walk(&proc) {
            break;
        }
        if exe_runner(proc.pid).is_some() {
            return confirm_runner(&proc);
        }
        return Err(format!(
            "{} (pid {}) is not an installed runner, so this is not the person's runner",
            proc.comm, proc.pid
        ));
    }
    Err("no installed runner is above this process, so this is not the person's runner".into())
}

/// The runner that spawned this `ljos hook` itself, or why none did: the
/// parent must be an installed runner ([`exe_runner`]), with no shell or
/// interpreter between them but the `sh -c` the runner runs its hook
/// command in ([`hook_shell`]). That runner must not run inside a tool
/// call, which a runner above it, a tool call's variables in the
/// environment it was started with, or the guard's tool-call record
/// ([`confirm_runner`]) would show. Only such a hook's prompt is the
/// person's. An environment that cannot be read hides the stamp, so it
/// is refused.
///
/// # Errors
///
/// Why the parent is not a runner the person started.
pub fn hook_runner() -> Result<(Proc, &'static str), String> {
    let mut chain = ancestors();
    let parent = chain.first().ok_or("it has no parent process")?;
    if exe_runner(parent.pid).is_none() && chain.len() > 1 && hook_shell(parent.pid) {
        chain.remove(0);
    }
    let parent = &chain[0];
    let Some(runner) = exe_runner(parent.pid) else {
        return Err(format!(
            "its parent, {} (pid {}), is not a runner's own program: a shell, an interpreter or ssh ran it, so a tool call may have",
            parent.comm, parent.pid
        ));
    };
    let env = environ(parent.pid).ok_or_else(|| {
        format!(
            "the environment {} (pid {}) was started with cannot be read, so a tool call's stamp would be hidden",
            parent.comm, parent.pid
        )
    })?;
    if let Some(key) = tool_call_stamp(&env) {
        return Err(format!(
            "{runner} (pid {}) was started with {key} set, inside another runner's tool call",
            parent.pid
        ));
    }
    // The Cursor app also hosts the person's own terminals; its agent's
    // shells carry `CURSOR_AGENT`, which the stamp above reads.
    let own = chain[1..].iter().take_while(|p| !ends_the_walk(p));
    if let Some((p, other)) = own
        .filter_map(|p| exe_runner(p.pid).map(|r| (p, r)))
        .find(|(_, r)| *r != "cursor")
    {
        return Err(format!(
            "{runner} (pid {}) runs under {other} (pid {}), inside a tool call",
            parent.pid, p.pid
        ));
    }
    confirm_runner(parent)?;
    Ok((parent.clone(), runner))
}

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

    /// [`runner_of_file`] for the file `path` names now.
    #[cfg(target_os = "linux")]
    fn runner_here(
        path: &Path,
        home: Option<&Path>,
        store: &Path,
        person: &Person,
    ) -> Option<&'static str> {
        use std::os::unix::fs::MetadataExt as _;
        let meta = std::fs::metadata(path).ok()?;
        runner_of_file(path, home, store, person, (meta.dev(), meta.ino()))
    }

    #[test]
    fn an_editor_name_matches_the_file_and_not_a_shell() {
        assert!(is_editor_name("Cursor"));
        assert!(is_editor_name("/Applications/Cursor Helper"));
        assert!(is_editor_name("cursor-agent"));
        assert!(!is_editor_name("bash"));
        assert!(!is_editor_name("python3"));
    }

    #[test]
    fn a_runner_is_read_from_the_file_it_runs_from() {
        let roots = install_roots(Some(Path::new("/home/u")));
        for (path, want) in [
            ("/home/u/.local/share/claude/versions/2.1.3", Some("claude")),
            ("/home/u/.local/bin/claude", Some("claude")),
            (
                "/usr/lib/node_modules/@anthropic-ai/claude-code/cli.js",
                Some("claude"),
            ),
            (
                "/usr/lib/node_modules/@openai/codex/vendor/x86_64-unknown-linux-musl/codex/codex",
                Some("codex"),
            ),
            (
                "/home/u/.local/share/cursor-agent/versions/2025.10.2-abc/node",
                Some("cursor-agent"),
            ),
            ("/usr/share/cursor/cursor", Some("cursor")),
            ("/usr/local/bin/codex", Some("codex")),
            ("/usr/bin/claude", Some("claude")),
            ("/bin/grok", Some("grok")),
            ("/home/u/.cargo/bin/codex", Some("codex")),
            (
                "/home/u/.npm-global/lib/node_modules/@anthropic-ai/claude-code/cli.js",
                Some("claude"),
            ),
            (
                "/nix/store/0c9yapqd0b8y4mj5xj7mrpmhy3l5ykh8-claude-code-2.0.1/bin/claude",
                Some("claude"),
            ),
            ("/usr/bin/node", None),
            ("/usr/bin/bash", None),
            ("/usr/bin/python3", None),
            ("/usr/bin/ssh", None),
            ("/home/u/.cargo/bin/ljos", None),
            ("/tmp/claude", None),
            ("/tmp/claude/versions/2.1.3", None),
            ("/home/u/runners/claude", None),
            ("/home/u/plant/grok", None),
            ("/home/u/plant/bin/claude", None),
            ("/home/u/.local/bin/claude (deleted)", None),
            ("/home/u/plant/.local/bin/claude", None),
            ("/tmp/.local/bin/claude", None),
            ("/tmp/project/node_modules/.bin/claude", None),
            ("/home/u/../other/.local/bin/claude", None),
            ("/home/uu/.local/bin/claude", None),
            ("/home/other/.local/bin/claude", None),
            ("/home/u/.local/binx/claude", None),
            ("/home/u/.local/bin/../../plant/claude", None),
            ("/home/u/.local/share/plant/claude", None),
            ("/home/u/.local/share/claude-plant/claude", None),
            ("/home/u/src/app/node_modules/.bin/claude", None),
            ("/usr/binx/claude", None),
            ("/usr/share/plant/claude", None),
            ("/usr/lib/node_modules/../../../tmp/claude", None),
            ("/opt/plant/claude", None),
            ("/var/tmp/.local/bin/claude", None),
            ("/dev/shm/node_modules/.bin/claude", None),
            ("/nix/store/claude/bin/claude", None),
            (
                "/nix/store/0c9yapqd0b8y4mj5xj7mrpmhy3l5ykh8/bin/claude",
                None,
            ),
            (
                "/nix/store/0c9yapqd0b8y4mj5xj7mrpmhy3l5ykhe-claude-code-2.0.1/bin/claude",
                None,
            ),
        ] {
            let got = runner_below(Path::new(path), &roots, Path::new(NIX_STORE))
                .map(|(runner, _)| runner);
            assert_eq!(got, want, "{path}");
        }
    }

    /// A runner is read where the kernel resolves it. A link from the
    /// person's own `~/.local/bin` into `/tmp`, a path that climbs out of
    /// that home into another, and a file anyone may rewrite or reach
    /// through a directory anyone may write are not installed copies; the
    /// same file kept by the person is.
    #[cfg(target_os = "linux")]
    #[test]
    fn an_install_root_holds_only_what_resolves_inside_it() {
        use std::os::unix::fs::PermissionsExt as _;
        let base = tempfile::Builder::new()
            .prefix(".ljos-roots-")
            .tempdir_in(own_home().expect("this user's passwd entry names a home"))
            .unwrap();
        let home = base.path().join("u");
        let person = Person::new(&SystemAccounts);
        let store = PathBuf::from(NIX_STORE);
        let program = |dir: &Path, name: &str| {
            std::fs::create_dir_all(dir).unwrap();
            let path = dir.join(name);
            std::fs::write(&path, "").unwrap();
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
            path
        };
        let bin = home.join(".local/bin");
        let claude = program(&bin, "claude");
        assert_eq!(
            runner_here(&claude, Some(&home), &store, &person),
            Some("claude")
        );

        let away = tempfile::tempdir().unwrap();
        std::os::unix::fs::symlink(program(away.path(), "codex"), bin.join("codex")).unwrap();
        assert_eq!(
            runner_here(&bin.join("codex"), Some(&home), &store, &person),
            None
        );

        program(&base.path().join("other/.local/bin"), "claude");
        let climbed = home.join("../other/.local/bin/claude");
        assert_eq!(runner_here(&climbed, Some(&home), &store, &person), None);

        std::fs::set_permissions(&claude, std::fs::Permissions::from_mode(0o757)).unwrap();
        assert_eq!(runner_here(&claude, Some(&home), &store, &person), None);

        let open = bin.join("open");
        let grok = program(&open, "grok");
        assert_eq!(
            runner_here(&grok, Some(&home), &store, &person),
            Some("grok")
        );
        std::fs::set_permissions(&open, std::fs::Permissions::from_mode(0o777)).unwrap();
        assert_eq!(runner_here(&grok, Some(&home), &store, &person), None);
    }

    /// Whoever may write the directory an install root sits in may swap
    /// the root, so that directory is judged as the root is: each root
    /// under the person's home is refused once its own directory is
    /// writable by anyone or by a group the person shares.
    #[cfg(target_os = "linux")]
    #[test]
    fn a_root_in_a_directory_others_may_write_is_refused() {
        use std::os::unix::fs::PermissionsExt as _;
        let base = tempfile::Builder::new()
            .prefix(".ljos-above-")
            .tempdir_in(own_home().expect("this user's passwd entry names a home"))
            .unwrap();
        let home = base.path().join("u");
        let store = PathBuf::from(NIX_STORE);
        let person = Person::new(&SystemAccounts);
        let staff = FakeAccounts {
            user: Some("u"),
            group: Some("staff"),
            members: &["u", "v"],
            primary: Some(vec![person.uid]),
        };
        let sharing = Person::new(&staff);
        let mut files: Vec<PathBuf> = vec![
            home.join(".local/bin/claude"),
            home.join(".cargo/bin/codex"),
            home.join(".npm-global/lib/node_modules/@anthropic-ai/claude-code/cli.js"),
        ];
        files.extend(
            HOOK_RUNNERS
                .iter()
                .map(|(name, _)| home.join(".local/share").join(name).join(name)),
        );
        for file in &files {
            std::fs::create_dir_all(file.parent().unwrap()).unwrap();
            std::fs::write(file, "").unwrap();
        }
        let set = |dir: &Path, mode| {
            std::fs::set_permissions(dir, std::fs::Permissions::from_mode(mode)).unwrap();
        };
        for root in install_roots(Some(&home))
            .iter()
            .filter(|r| r.starts_with(&home))
        {
            let file = files.iter().find(|f| f.starts_with(root)).unwrap();
            let above = root.parent().unwrap();
            let runner = |who| runner_here(file, Some(&home), &store, who);
            assert!(runner(&person).is_some(), "{}", root.display());
            set(above, 0o757);
            assert_eq!(runner(&person), None, "{}", root.display());
            set(above, 0o775);
            assert_eq!(runner(&sharing), None, "{}", root.display());
            set(above, 0o755);
        }

        let uid = person.uid;
        let owner = |uid, mode| Owner {
            uid,
            gid: person.gid,
            mode,
        };
        let walk = |above| [owner(0, 0o755), above, owner(uid, 0o755), owner(uid, 0o755)];
        assert!(walk_kept(&walk(owner(uid, 0o755)), 2, false, &person));
        assert!(walk_kept(&walk(owner(0, 0o755)), 2, false, &person));
        assert!(!walk_kept(&walk(owner(uid + 1, 0o755)), 2, false, &person));
        assert!(!walk_kept(&walk(owner(uid, 0o757)), 2, false, &person));
        assert!(!walk_kept(&walk(owner(uid, 0o775)), 2, false, &sharing));
    }

    /// The file judged is the one opened. A directory swapped after the
    /// path resolved, for a link or for another directory holding a file
    /// of the same name, is not walked through, and a file that is not
    /// the one the process runs is not its runner.
    #[cfg(target_os = "linux")]
    #[test]
    fn a_parent_swapped_after_the_path_resolved_is_refused() {
        use std::os::unix::fs::MetadataExt as _;
        let base = tempfile::Builder::new()
            .prefix(".ljos-swap-")
            .tempdir_in(own_home().expect("this user's passwd entry names a home"))
            .unwrap();
        let home = std::fs::canonicalize(base.path()).unwrap().join("u");
        let person = Person::new(&SystemAccounts);
        let store = PathBuf::from(NIX_STORE);
        let versions = home.join(".local/share/claude/versions");
        let other = home.join("other");
        for dir in [&versions, &other] {
            std::fs::create_dir_all(dir).unwrap();
            std::fs::write(dir.join("2.1.3"), "").unwrap();
        }
        let id = |path: &Path| {
            let meta = std::fs::metadata(path).unwrap();
            (meta.dev(), meta.ino())
        };
        let file = versions.join("2.1.3");
        let (running, planted) = (id(&file), id(&other.join("2.1.3")));
        let runner = |expect| runner_at(&file, Some(&home), &store, &person, expect);
        assert_eq!(runner(running), Some("claude"));

        std::fs::rename(&versions, home.join("held")).unwrap();
        std::os::unix::fs::symlink(&other, &versions).unwrap();
        assert_eq!(runner(running), None);
        assert_eq!(runner(planted), None);

        std::fs::remove_file(&versions).unwrap();
        std::fs::rename(&other, &versions).unwrap();
        assert_eq!(runner(running), None);
    }

    /// A process is its runner only through the (device, inode) the
    /// kernel reports for its executable. When that cannot be read, the
    /// path the link names is not trusted in its place.
    #[cfg(target_os = "linux")]
    #[test]
    fn an_executable_that_cannot_be_read_is_no_runner() {
        use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};
        let base = tempfile::Builder::new()
            .prefix(".ljos-exe-")
            .tempdir_in(own_home().expect("this user's passwd entry names a home"))
            .unwrap();
        let home = base.path().join("u");
        let bin = home.join(".local/bin");
        std::fs::create_dir_all(&bin).unwrap();
        let claude = bin.join("claude");
        std::fs::write(&claude, "").unwrap();
        std::fs::set_permissions(&claude, std::fs::Permissions::from_mode(0o755)).unwrap();
        let meta = std::fs::metadata(&claude).unwrap();
        let person = Person::new(&SystemAccounts);
        let store = PathBuf::from(NIX_STORE);
        let runner = |running| runner_from(&claude, running, || None, Some(&home), &store, &person);
        assert_eq!(runner(Some((meta.dev(), meta.ino()))), Some("claude"));
        assert_eq!(runner(None), None);
    }

    /// A runtime's script names the runner only when the runtime is an
    /// installed copy of its exact name, kept as a runner file is and the
    /// file the process runs. A `node` of a tool call's own making, or a
    /// program whose name merely starts like one, may name any script.
    #[cfg(target_os = "linux")]
    #[test]
    fn a_script_names_the_runner_only_for_an_installed_runtime() {
        use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};
        let base = tempfile::Builder::new()
            .prefix(".ljos-runtime-")
            .tempdir_in(own_home().expect("this user's passwd entry names a home"))
            .unwrap();
        let home = base.path().join("u");
        let away = tempfile::tempdir().unwrap();
        let program = |dir: &Path, name: &str| {
            std::fs::create_dir_all(dir).unwrap();
            let path = dir.join(name);
            std::fs::write(&path, "").unwrap();
            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
            path
        };
        let id = |path: &Path| {
            let meta = std::fs::metadata(path).unwrap();
            (meta.dev(), meta.ino())
        };
        let cli = program(
            &home.join(".npm-global/lib/node_modules/@anthropic-ai/claude-code"),
            "cli.js",
        );
        let bin = home.join(".local/bin");
        let node = program(&bin, "node");
        let person = Person::new(&SystemAccounts);
        let store = PathBuf::from(NIX_STORE);
        let runner = |exe: &Path, running| {
            runner_from(
                exe,
                Some(running),
                || Some(cli.clone()),
                Some(&home),
                &store,
                &person,
            )
        };
        assert_eq!(runner(&node, id(&node)), Some("claude"));
        assert_eq!(runner(&node, id(&cli)), None);
        for planted in [
            program(&bin, "node-v20"),
            program(&bin, "nodejs_modules"),
            program(away.path(), "node"),
        ] {
            assert_eq!(
                runner(&planted, id(&planted)),
                None,
                "{}",
                planted.display()
            );
        }
        std::fs::set_permissions(&node, std::fs::Permissions::from_mode(0o757)).unwrap();
        assert_eq!(runner(&node, id(&node)), None);
    }

    /// A Nix store entry is a runner only while Nix alone keeps it. A
    /// store the person owns counts as a single-user install only while
    /// no one else may write it; a root's store must be closed to the
    /// person, sticky when its group may write it, and hold root's
    /// entries.
    #[cfg(target_os = "linux")]
    #[test]
    fn a_nix_entry_is_a_runner_only_in_a_store_nix_keeps() {
        use std::os::unix::fs::PermissionsExt as _;
        let base = tempfile::Builder::new()
            .prefix(".ljos-store-")
            .tempdir_in(own_home().expect("this user's passwd entry names a home"))
            .unwrap();
        let store = base.path().join("store");
        let bin = store.join("0c9yapqd0b8y4mj5xj7mrpmhy3l5ykh8-claude-code-2.0.1/bin");
        std::fs::create_dir_all(&bin).unwrap();
        let claude = bin.join("claude");
        std::fs::write(&claude, "").unwrap();
        std::fs::set_permissions(&claude, std::fs::Permissions::from_mode(0o755)).unwrap();
        let person = Person::new(&SystemAccounts);
        let set = |mode| {
            std::fs::set_permissions(&store, std::fs::Permissions::from_mode(mode)).unwrap();
        };
        let runner = || runner_here(&claude, None, &store, &person);

        set(0o755);
        assert_eq!(runner(), Some("claude"));
        for mode in [0o775, 0o757, 0o777, 0o1775, 0o1777] {
            set(mode);
            assert_eq!(runner(), None, "{mode:o}");
        }
        set(0o755);

        let uid = person.uid;
        let nixbld = person.gid + 1;
        let owner = |uid, gid, mode| Owner { uid, gid, mode };
        let outsider = Person {
            groups: Some(vec![]),
            ..Person::new(&SystemAccounts)
        };
        let builder = Person {
            groups: Some(vec![nixbld]),
            ..Person::new(&SystemAccounts)
        };
        let unread = Person {
            groups: None,
            ..Person::new(&SystemAccounts)
        };
        let root_entry = owner(0, 0, 0o555);
        let own_entry = owner(uid, uid, 0o555);
        for (store, entry, who, want) in [
            (owner(0, nixbld, 0o1775), root_entry, &outsider, true),
            (owner(0, 0, 0o755), root_entry, &outsider, true),
            (owner(0, nixbld, 0o1775), own_entry, &outsider, false),
            (owner(0, nixbld, 0o775), root_entry, &outsider, false),
            (owner(0, nixbld, 0o1775), root_entry, &builder, false),
            (owner(0, nixbld, 0o1775), root_entry, &unread, false),
            (owner(0, 0, 0o1777), root_entry, &outsider, false),
            (owner(uid, uid, 0o755), own_entry, &outsider, true),
            (owner(uid, uid, 0o755), root_entry, &outsider, true),
            (owner(uid, uid, 0o775), own_entry, &outsider, false),
            (owner(uid, uid, 0o1777), own_entry, &outsider, false),
            (
                owner(uid, uid, 0o755),
                owner(uid + 1, 0, 0o555),
                &outsider,
                false,
            ),
            (owner(uid + 1, 0, 0o755), own_entry, &outsider, false),
        ] {
            assert_eq!(
                store_keeps(store, entry, who),
                want,
                "{}:{} {:o}",
                store.uid,
                store.gid,
                store.mode
            );
        }
    }

    /// One user `u`, the name and members of whatever group is asked
    /// for, and the uids whose primary group it is.
    #[cfg(target_os = "linux")]
    struct FakeAccounts {
        user: Option<&'static str>,
        group: Option<&'static str>,
        members: &'static [&'static str],
        primary: Option<Vec<u32>>,
    }

    #[cfg(target_os = "linux")]
    impl Accounts for FakeAccounts {
        fn user_name(&self, _uid: u32) -> Option<std::ffi::OsString> {
            self.user.map(Into::into)
        }

        fn group(&self, _gid: u32) -> Option<GroupEntry> {
            self.group.map(|name| GroupEntry {
                name: name.into(),
                members: self.members.iter().map(Into::into).collect(),
            })
        }

        fn primary_members(&self, _gid: u32) -> Option<Vec<u32>> {
            self.primary.clone()
        }
    }

    /// A runner file the person's primary group may write is theirs only
    /// when that group is: named for them, listing no one else, and no
    /// other account's primary group. An account lookup that fails is
    /// not such a group.
    #[cfg(target_os = "linux")]
    #[test]
    fn a_group_write_counts_only_from_a_group_the_person_has_alone() {
        use std::os::unix::fs::PermissionsExt as _;
        // SAFETY: getuid takes no arguments and only reads the process
        // identity.
        let uid = unsafe { libc::getuid() };
        let alone = |members, primary| FakeAccounts {
            user: Some("u"),
            group: Some("u"),
            members,
            primary: Some(primary),
        };
        let shared = [
            FakeAccounts {
                group: Some("staff"),
                ..alone(&[], vec![uid])
            },
            FakeAccounts {
                group: None,
                ..alone(&[], vec![uid])
            },
            alone(&["u", "v"], vec![uid]),
            alone(&["v"], vec![uid]),
            alone(&[], vec![uid, uid + 1]),
            FakeAccounts {
                user: None,
                ..alone(&[], vec![uid])
            },
            FakeAccounts {
                primary: None,
                ..alone(&[], vec![uid])
            },
        ];

        let base = tempfile::Builder::new()
            .prefix(".ljos-group-")
            .tempdir_in(own_home().expect("this user's passwd entry names a home"))
            .unwrap();
        let home = base.path().join("u");
        let bin = home.join(".local/bin");
        std::fs::create_dir_all(&bin).unwrap();
        let claude = bin.join("claude");
        std::fs::write(&claude, "").unwrap();
        std::fs::set_permissions(&claude, std::fs::Permissions::from_mode(0o775)).unwrap();
        let store = PathBuf::from(NIX_STORE);

        for accounts in [alone(&[], vec![uid]), alone(&["u"], vec![uid, uid])] {
            assert!(group_is_private(&accounts, uid, 0));
            let person = Person::new(&accounts);
            assert_eq!(
                runner_here(&claude, Some(&home), &store, &person),
                Some("claude")
            );
        }
        for accounts in &shared {
            assert!(!group_is_private(accounts, uid, 0));
            let person = Person::new(accounts);
            assert_eq!(runner_here(&claude, Some(&home), &store, &person), None);
        }
    }

    /// The accounts in a group are read from `passwd` only when
    /// `nsswitch.conf` names that file alone, and a file that cannot be
    /// read whole lists no one rather than fewer.
    #[test]
    fn a_primary_group_is_listed_only_from_a_passwd_file_read_whole() {
        let etc = tempfile::tempdir().unwrap();
        let write = |name: &str, text: &str| std::fs::write(etc.path().join(name), text).unwrap();
        let passwd = "root:x:0:0::/root:/bin/sh\nu:x:1000:1000::/home/u:/bin/sh\n";
        write("passwd", passwd);
        assert_eq!(primary_in_files(etc.path(), 1000), None, "no nsswitch.conf");
        for conf in [
            "passwd: files systemd\n",
            "passwd: sss files\n",
            "passwd: compat\n",
            "passwd: files [NOTFOUND=return] ldap\n",
            "passwd: files\npasswd: files ldap\n",
            "group: files\n",
        ] {
            write("nsswitch.conf", conf);
            assert_eq!(primary_in_files(etc.path(), 1000), None, "{conf}");
        }
        write(
            "nsswitch.conf",
            "# local\npasswd:   files # only\ngroup: files\n",
        );
        assert_eq!(primary_in_files(etc.path(), 1000), Some(vec![1000]));
        assert_eq!(primary_in_files(etc.path(), 7), Some(vec![]));
        for extra in [
            "+@admins\n",
            "-v\n",
            "v:x:1001\n",
            "v:x:one:1000::/home/v:/bin/sh\n",
        ] {
            write("passwd", &format!("{passwd}{extra}"));
            assert_eq!(primary_in_files(etc.path(), 1000), None, "{extra}");
        }
        write(
            "passwd",
            &format!("{passwd}\n# kept\nv:x:1001:1000::/home/v:/bin/sh\n"),
        );
        assert_eq!(primary_in_files(etc.path(), 1000), Some(vec![1000, 1001]));
        std::fs::remove_file(etc.path().join("passwd")).unwrap();
        assert_eq!(primary_in_files(etc.path(), 1000), None);
    }

    /// A group is read from `group` only when `nsswitch.conf` names that
    /// file alone, and only when one line has its gid: a second line's
    /// members hold the group as well, though a lookup returns the first.
    #[test]
    fn a_group_is_read_only_from_one_line_of_a_group_file_read_whole() {
        let etc = tempfile::tempdir().unwrap();
        let write = |name: &str, text: &str| std::fs::write(etc.path().join(name), text).unwrap();
        let group = "root:x:0:\nu:x:1000:\nstaff:x:50:u,v\n";
        write("group", group);
        let read = |gid| {
            group_in_files(etc.path(), gid).map(|g| {
                let members: Vec<String> = g
                    .members
                    .iter()
                    .map(|m| m.to_string_lossy().into_owned())
                    .collect();
                (g.name.to_string_lossy().into_owned(), members)
            })
        };
        assert_eq!(read(1000), None, "no nsswitch.conf");
        for conf in ["group: files systemd\n", "group: sss\n", "passwd: files\n"] {
            write("nsswitch.conf", conf);
            assert_eq!(read(1000), None, "{conf}");
        }
        write("nsswitch.conf", "passwd: files\ngroup: files\n");
        assert_eq!(read(1000), Some(("u".into(), vec![])));
        assert_eq!(
            read(50),
            Some(("staff".into(), vec!["u".into(), "v".into()]))
        );
        assert_eq!(read(7), None);
        for extra in ["shadow:x:1000:v\n", "+:::\n", "w:x:1000\n", "w:x:ten:\n"] {
            write("group", &format!("{group}{extra}"));
            assert_eq!(read(1000), None, "{extra}");
        }
    }

    /// A process younger than a recorded tool call, in that call's cgroup
    /// or session, is still the tool call. The runner that recorded the
    /// mark is not. A missing record is not a tool call; a corrupt one
    /// refuses everything.
    #[test]
    fn a_young_runner_in_a_recorded_tool_call_is_refused() {
        let _guard = crate::test_env_lock();
        let opener = Proc {
            pid: 1,
            start: 1,
            comm: "claude".into(),
        };
        let young = Proc {
            pid: 999_999,
            start: u64::MAX,
            comm: "claude".into(),
        };
        let old = Proc {
            pid: 42,
            start: 0,
            comm: "claude".into(),
        };
        assert!(confirm_runner(&young).is_ok(), "no record yet");
        note_tool_call(&opener).unwrap();
        let why = confirm_runner(&young).unwrap_err();
        assert!(why.contains("tool call"), "{why}");
        assert!(confirm_runner(&opener).is_ok(), "the opener recorded it");
        assert!(confirm_runner(&old).is_ok(), "older than the record");
        std::fs::write(marks_path(), "nope\n").unwrap();
        let why = confirm_runner(&old).unwrap_err();
        assert!(why.contains("corrupt"), "{why}");
    }

    #[test]
    fn a_tool_calls_variables_mark_a_runner_started_inside_one() {
        let env = |k: &str, v: &str| vec![(k.to_string(), v.to_string())];
        assert_eq!(tool_call_stamp(&env("CLAUDECODE", "1")), Some("CLAUDECODE"));
        assert_eq!(
            tool_call_stamp(&env("CURSOR_AGENT", "1")),
            Some("CURSOR_AGENT")
        );
        assert!(tool_call_stamp(&env("CURSOR_CONVERSATION_ID", "0199a1b2-c3d4")).is_some());
        assert_eq!(tool_call_stamp(&env("LJOS_SESSION_ID", "mine-0001")), None);
        assert_eq!(tool_call_stamp(&env("HOME", "/home/u")), None);
    }

    #[test]
    fn only_a_bare_hook_command_is_the_runners_hook_shell() {
        for cmd in [
            "ljos hook",
            "/home/u/.cargo/bin/ljos hook --runner codex",
            "ljos hook --event SessionStart",
            "\"${CLAUDE_PLUGIN_ROOT}/bin/ljos-plugin\" ljos hook",
            "\"${CURSOR_PLUGIN_ROOT}/bin/ljos-plugin\" ljos hook",
        ] {
            assert!(bare_hook_command(cmd), "{cmd}");
        }
        for cmd in [
            "ljos hook < plant.json",
            "cat plant.json | ljos hook",
            "ljos hook <<'EOF'\n{}\nEOF",
            "ljos status; ljos hook",
            "ljos hook $(cat p)",
            "python3 plant.py",
            "ljos remember a b c d",
            "ljos-plugin hook",
            "bash -c 'ljos hook'",
        ] {
            assert!(!bare_hook_command(cmd), "{cmd}");
        }
    }

    /// The test runner is no runner's program, so a hook it spawned is
    /// not the person's.
    #[test]
    fn a_hook_this_test_runs_has_no_runner() {
        let why = hook_runner().unwrap_err();
        assert!(why.contains("not a runner's own program"), "{why}");
    }

    fn named(pid: u32, comm: &str) -> Proc {
        Proc {
            pid,
            start: u64::from(pid) * 10,
            comm: comm.into(),
        }
    }

    #[test]
    fn this_process_has_live_ancestors_and_a_dead_pid_does_not_match() {
        let chain = ancestors();
        assert!(!chain.is_empty(), "the test runner is above this process");
        assert!(chain.iter().all(alive));
        let parent = &chain[0];
        assert!(token_alive(&token(parent)));
        let reused = Proc {
            start: parent.start + 1,
            ..parent.clone()
        };
        assert!(!alive(&reused));
        assert!(!token_alive(&format!(
            "other-boot:{}:{}",
            parent.pid, parent.start
        )));
    }

    #[test]
    fn a_reaped_child_is_not_alive() {
        let mut child = std::process::Command::new("sleep")
            .arg("30")
            .spawn()
            .unwrap();
        let pid = child.id();
        let p = of(pid).unwrap();
        assert!(alive(&p));
        assert_eq!(above(pid).first().map(|q| q.pid), Some(std::process::id()));
        child.kill().unwrap();
        child.wait().unwrap();
        assert!(!alive(&p));
    }

    #[test]
    fn a_child_is_read_with_the_environment_it_was_started_with() {
        let mut child = std::process::Command::new("sleep")
            .arg("30")
            .env("LJOS_PROC_TREE_PROBE", "started-with")
            .spawn()
            .unwrap();
        // Until the child has exec'd, its environment is the fork's.
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        let env = loop {
            let env = environ(child.id()).unwrap_or_default();
            if env.iter().any(|(k, _)| k == "LJOS_PROC_TREE_PROBE")
                || std::time::Instant::now() > deadline
            {
                break env;
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        };
        child.kill().unwrap();
        child.wait().unwrap();
        assert!(
            env.iter()
                .any(|(k, v)| k == "LJOS_PROC_TREE_PROBE" && v == "started-with"),
            "{env:?}"
        );
    }

    #[test]
    fn the_calling_shell_is_the_outermost_of_a_nested_run() {
        let harness = named(10, "claude");
        let chain = [
            named(3, "timeout"),
            named(4, "sh"),
            named(5, "bash"),
            harness.clone(),
        ];
        assert_eq!(calling_shell(&chain), Some(&chain[2]));
        let chain = [
            named(4, "sh"),
            named(6, "env"),
            named(5, "bash"),
            named(7, "node"),
            named(8, "bash"),
        ];
        assert_eq!(calling_shell(&chain), Some(&chain[2]));
        assert_eq!(calling_shell(&[harness.clone(), named(5, "bash")]), None);
        assert_eq!(calling_shell(&[named(3, "env"), harness.clone()]), None);
        assert_eq!(calling_shell(&[]), None);
        let launched = [named(3, "python3"), named(4, "sh"), named(5, "bash")];
        assert_eq!(calling_shell(&launched), None);
        assert_eq!(cast_shell(&launched, None), Some(&launched[2]));
        assert_eq!(cast_shell(&[harness, named(5, "bash")], None), None);
        assert_eq!(
            cast_shell(&[named(9, "cargo"), named(5, "bash")], None),
            None
        );
        assert_eq!(cast_shell(&[], None), None);
    }

    #[test]
    fn the_runner_is_above_the_shells_and_wrappers_it_started() {
        let chain = [
            named(4, "sh"),
            named(3, "timeout"),
            named(5, "bash"),
            named(10, "claude"),
            named(2, "tmux"),
        ];
        assert_eq!(runner(&chain).map(|p| p.pid), Some(10));
        assert_eq!(runner(&chain[3..]).map(|p| p.pid), Some(10));
        let shells = [named(4, "sh"), named(5, "bash")];
        assert_eq!(runner(&shells).map(|p| p.pid), Some(5));
        assert_eq!(runner(&[]), None);
    }

    #[test]
    fn a_session_above_the_hook_is_never_its_runner() {
        for session in ["tmux", "tmux: server", "gnome-terminal-", "systemd", "sshd"] {
            let chain = [named(4, "sh"), named(5, "bash"), named(2, session)];
            assert_eq!(runner(&chain).map(|p| p.pid), Some(5), "{session}");
            let chain = [named(4, "sh"), named(2, session), named(10, "claude")];
            assert_eq!(runner(&chain).map(|p| p.pid), Some(4), "{session}");
            assert_eq!(runner(&[named(2, session), named(10, "claude")]), None);
        }
        let chain = [named(4, "sh"), named(7, "git"), named(2, "kitty")];
        assert_eq!(runner(&chain).map(|p| p.pid), Some(7));
    }

    /// A process no kernel runs, so no `/proc` entry names it: pids stop
    /// below 2^22.
    fn fake(n: u32, comm: &str) -> Proc {
        named((1 << 22) + n, comm)
    }

    #[test]
    fn a_harness_outranks_a_runtime_that_only_started_the_hook() {
        let chain = [
            fake(1, "sh"),
            fake(2, "uv"),
            fake(3, "uv"),
            fake(4, "claude"),
        ];
        assert_eq!(runner(&chain), Some(&chain[3]));
        let chain = [fake(1, "sh"), fake(2, "node"), fake(3, "claude")];
        assert_eq!(runner(&chain), Some(&chain[2]));
        let chain = [
            fake(1, "sh"),
            fake(2, "npx"),
            fake(3, "bash"),
            fake(4, "cursor-agent"),
            fake(5, "tmux"),
        ];
        assert_eq!(runner(&chain), Some(&chain[3]));
        let chain = [
            fake(1, "sh"),
            fake(2, "uv"),
            fake(3, "codex"),
            fake(4, "agy"),
        ];
        assert_eq!(runner(&chain), Some(&chain[2]), "the nearest harness");
    }

    #[test]
    fn a_node_harness_with_no_known_harness_above_is_the_runner() {
        let chain = [
            fake(1, "sh"),
            fake(2, "node"),
            fake(3, "bash"),
            fake(4, "tmux"),
        ];
        assert_eq!(runner(&chain), Some(&chain[1]));
        assert_eq!(runner(&chain[..2]), Some(&chain[1]));
        // The walk stops at the session: a harness above it is not read.
        let chain = [
            fake(1, "sh"),
            fake(2, "node"),
            fake(3, "tmux"),
            fake(4, "claude"),
        ];
        assert_eq!(runner(&chain), Some(&chain[1]));
    }

    #[test]
    fn pid_1_is_the_runner_only_as_a_harness() {
        let chain = [fake(1, "sh"), fake(2, "uv"), named(1, "claude")];
        assert_eq!(runner(&chain), Some(&chain[2]), "a container's harness");
        let chain = [fake(1, "sh"), fake(2, "bash"), named(1, "tini")];
        assert_eq!(runner(&chain), Some(&chain[1]), "an init is no runner");
        let chain = [fake(1, "sh"), fake(2, "node"), named(1, "dumb-init")];
        assert_eq!(runner(&chain), Some(&chain[1]));
        assert_eq!(runner(&[named(1, "tini")]), None);
    }

    #[test]
    fn the_walk_reads_up_to_a_process_with_no_parent() {
        let chain = ancestors();
        let top = chain.last().expect("the test runner is above this process");
        let top = stat(top.pid).expect("the top process was just read");
        // A parent the kernel will not name ends the walk. macOS answers
        // that way for a process this user cannot inspect. pid 0 is the
        // same stop when the parent can be read.
        let hidden_parent = top.ppid != 0 && stat(top.ppid).is_none();
        assert!(
            chain.len() == DEPTH || top.ppid == 0 || hidden_parent,
            "{chain:?}"
        );
    }
}