omni-dev 0.46.0

AI-powered git commit rewriter, PR generator, and MCP server for Jira, Confluence, Datadog, Gmail, and Drive.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
//! `omni-dev sessions` — track the Claude Code, Codex and pi.dev sessions running
//! across every terminal and VS Code window, via the daemon's `sessions` service.
//!
//! The subcommands split by role:
//! - `list` is a **read** client (like `omni-dev worktrees list`): it asks the
//!   daemon's `sessions` service for the live set and renders it.
//! - `hook` is the **feed sink**: Claude Code (or Codex, with `--agent codex`)
//!   runs it per hook event; it reads
//!   the hook JSON on stdin, maps it to an `observe`/`end` op, and fire-and-forgets
//!   it to the daemon socket. It must **never** block or fail a Claude turn — a
//!   missing daemon, a bad payload, or any other error is swallowed and it always
//!   exits 0.
//! - `install-hooks` / `uninstall-hooks` idempotently merge (or remove) the hook
//!   block in `~/.claude/settings.json`, preserving any hooks already there. When
//!   pi.dev is installed they also write (or remove) the generated pi extension
//!   in `~/.pi/agent/extensions/`, which reports straight to the socket (#1901),
//!   and when Codex is installed the same hook block, tagged `--agent codex`, in
//!   `$CODEX_HOME/hooks.json` — position-stably, since Codex trusts a hook by
//!   its index (#1907).
//! - `install-wrapper` / `uninstall-wrapper` are the same idea for Feed 4: they
//!   write the shim that VS Code's Claude extension launches
//!   [`omni-dev claude-wrap`](crate::cli::claude_wrap) through, and point the
//!   extension's `claudeCode.claudeProcessWrapper` setting at it.
//!
//! The register/heartbeat feed from the companion VS Code extension talks to the
//! socket directly (like the worktrees companion), not through this CLI.

use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::Duration;

use anyhow::{anyhow, bail, Context, Result};
use chrono::Utc;
use clap::{Parser, Subcommand, ValueEnum};
use serde::Deserialize;
use serde_json::{json, Value};

use crate::cli::format::{sanitize_for_terminal, TableOrJson};
use crate::daemon::client::DaemonClient;
use crate::daemon::paths;
use crate::daemon::protocol::{DaemonEnvelope, DaemonReply};
use crate::daemon::server;
use crate::sessions::journal::{self, JournalRecord};
use crate::sessions::{Agent, EventStamp, NotificationKind, ObserveRequest, SessionEvent};

/// The `sessions` service routing key on the daemon control socket.
const SERVICE: &str = "sessions";

/// How long the fire-and-forget `hook` sink waits for the daemon before giving
/// up — short, so a slow or wedged daemon never stalls a Claude turn.
const HOOK_TIMEOUT: Duration = Duration::from_secs(2);

/// Sessions: see the Claude Code sessions running across every terminal and
/// VS Code window, kept live by the daemon.
#[derive(Parser)]
pub struct SessionsCommand {
    /// The sessions subcommand to execute.
    #[command(subcommand)]
    pub command: SessionsSubcommands,
}

/// Sessions subcommands.
#[derive(Subcommand)]
pub enum SessionsSubcommands {
    /// List the Claude Code, Codex and pi.dev sessions currently running across
    /// all windows.
    List(ListCommand),
    /// Claude Code / Codex hook sink: read a hook event on stdin and report it to
    /// the daemon (run by the agent, not by hand).
    Hook(HookCommand),
    /// Install the Claude Code hooks that feed the sessions tracker into
    /// `~/.claude/settings.json`, plus the pi.dev extension when pi is installed
    /// and the Codex hooks when Codex is (idempotent).
    InstallHooks(InstallHooksCommand),
    /// Remove the sessions-tracker hooks from `~/.claude/settings.json`, the
    /// pi.dev extension, and the Codex hooks.
    UninstallHooks(UninstallHooksCommand),
    /// Install the `claude-wrap` shim and point VS Code's Claude extension at it
    /// (idempotent).
    InstallWrapper(InstallWrapperCommand),
    /// Remove the `claude-wrap` shim and VS Code's wrapper setting.
    UninstallWrapper(UninstallWrapperCommand),
    /// Report a window's Claude tab/terminal counts (companion feed op).
    Window(WindowCommand),
    /// Remove a window's embedding report (companion feed op).
    WindowUnregister(WindowUnregisterCommand),
}

impl SessionsCommand {
    /// Executes the sessions command.
    pub async fn execute(self) -> Result<()> {
        match self.command {
            SessionsSubcommands::List(cmd) => cmd.execute().await,
            SessionsSubcommands::Hook(cmd) => cmd.execute().await,
            SessionsSubcommands::InstallHooks(cmd) => cmd.execute(),
            SessionsSubcommands::UninstallHooks(cmd) => cmd.execute(),
            SessionsSubcommands::InstallWrapper(cmd) => cmd.execute(),
            SessionsSubcommands::UninstallWrapper(cmd) => cmd.execute(),
            SessionsSubcommands::Window(cmd) => cmd.execute().await,
            SessionsSubcommands::WindowUnregister(cmd) => cmd.execute().await,
        }
    }
}

// --- list --------------------------------------------------------------------

/// Lists the live cross-window set of running Claude sessions.
#[derive(Parser)]
pub struct ListCommand {
    /// Control-socket path. Defaults to the per-user runtime location.
    #[arg(long, value_name = "PATH")]
    pub socket: Option<PathBuf>,
    /// Output format.
    #[arg(short = 'o', long, value_enum, default_value_t = TableOrJson::Table)]
    pub output: TableOrJson,
}

impl ListCommand {
    /// Executes the list command.
    pub async fn execute(self) -> Result<()> {
        let socket = server::resolve_socket(self.socket)?;
        let result = call(&socket, "list", Value::Null).await?;
        match self.output {
            TableOrJson::Json => println!("{}", serde_json::to_string_pretty(&result)?),
            TableOrJson::Table => println!("{}", render_sessions(&result)),
        }
        Ok(())
    }
}

// --- window feed -------------------------------------------------------------

/// Reports a window's Claude embedding counts (the companion `window` feed op).
///
/// Exposed as a typed command so scripted/headless reporters and integration
/// tests can drive the sessions registry the way the VS Code companion does.
/// Mirrors `WindowReport`.
#[derive(Parser)]
pub struct WindowCommand {
    /// Stable per-window identity (the companion generates a per-activate UUID).
    #[arg(long, value_name = "KEY")]
    pub key: String,
    /// A workspace-folder path (repeatable) — used to join sessions by `cwd`.
    #[arg(long = "folder", value_name = "PATH")]
    pub folders: Vec<PathBuf>,
    /// How many Claude editor tabs the window has.
    #[arg(long, value_name = "N", default_value_t = 0)]
    pub tabs: usize,
    /// How many Claude Code integrated terminals the window has.
    #[arg(long, value_name = "N", default_value_t = 0)]
    pub terminals: usize,
    /// Control-socket path. Defaults to the per-user runtime location.
    #[arg(long, value_name = "PATH")]
    pub socket: Option<PathBuf>,
}

impl WindowCommand {
    /// Executes the window command.
    pub async fn execute(self) -> Result<()> {
        let socket = server::resolve_socket(self.socket)?;
        let payload = json!({
            "key": self.key,
            "folders": self.folders,
            "tabs": self.tabs,
            "terminals": self.terminals,
        });
        call(&socket, "window", payload).await?;
        println!("Reported window {}", self.key);
        Ok(())
    }
}

/// Removes a window's embedding report — the companion `window-unregister` feed
/// op made typed. Prints whether an entry was actually removed.
#[derive(Parser)]
pub struct WindowUnregisterCommand {
    /// The window key to unregister.
    #[arg(long, value_name = "KEY")]
    pub key: String,
    /// Control-socket path. Defaults to the per-user runtime location.
    #[arg(long, value_name = "PATH")]
    pub socket: Option<PathBuf>,
}

impl WindowUnregisterCommand {
    /// Executes the window-unregister command.
    pub async fn execute(self) -> Result<()> {
        let socket = server::resolve_socket(self.socket)?;
        let reply = call(&socket, "window-unregister", json!({ "key": self.key })).await?;
        let removed = reply
            .get("removed")
            .and_then(Value::as_bool)
            .unwrap_or(false);
        println!("removed: {removed}");
        Ok(())
    }
}

// --- hook --------------------------------------------------------------------

/// The Claude Code / Codex hook sink: reads one hook event's JSON on stdin and
/// reports it to the daemon. Fire-and-forget and infallible-by-design.
#[derive(Parser)]
pub struct HookCommand {
    /// Control-socket path. Defaults to the per-user runtime location.
    #[arg(long, value_name = "PATH")]
    pub socket: Option<PathBuf>,

    /// Which agent runs this hook. The payloads share field names, so the agent
    /// cannot be inferred from them; it selects the event mapping and tags the
    /// session.
    #[arg(long, value_enum, default_value_t = HookAgent::Claude)]
    pub agent: HookAgent,
}

/// The agents whose hooks run [`HookCommand`]. pi.dev reports through its own
/// extension, so it has no hook variant.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum HookAgent {
    /// Claude Code (`~/.claude/settings.json`).
    Claude,
    /// OpenAI Codex (`$CODEX_HOME/hooks.json`).
    Codex,
}

impl HookAgent {
    /// The registry tag sessions reported by this agent's hooks carry.
    fn agent(self) -> Agent {
        match self {
            Self::Claude => Agent::Claude,
            Self::Codex => Agent::Codex,
        }
    }
}

impl HookCommand {
    /// Executes the hook sink. Always returns `Ok(())` (exit 0): a hook must
    /// never block or fail a Claude turn, so every error — no daemon, bad JSON,
    /// an unknown event — is swallowed after a best-effort report.
    pub async fn execute(self) -> Result<()> {
        // Read before stdin, while the agent that spawned this hook is surely
        // still alive to be our parent.
        let pid = agent_pid(std::os::unix::process::parent_id());
        if let Some(input) = self.read_input(std::io::stdin()) {
            self.report(&input, pid).await;
        }
        Ok(())
    }

    /// Reads the whole hook payload from `reader`, or `None` — after a debug
    /// line — when it cannot be read (an I/O error, or bytes that are not
    /// UTF-8). Split out so tests can feed it a reader that fails.
    fn read_input(&self, mut reader: impl Read) -> Option<String> {
        let mut input = String::new();
        if reader.read_to_string(&mut input).is_err() {
            tracing::debug!(agent = ?self.agent, outcome = "stdin_read_failed", "session_hook_skipped");
            return None;
        }
        Some(input)
    }

    /// Parses the hook JSON, maps it to an op, and best-effort sends it. Split
    /// out so tests can exercise the send path against a fake socket.
    async fn report(&self, input: &str, pid: Option<u32>) {
        let Ok(hook) = serde_json::from_str::<HookPayload>(input) else {
            tracing::debug!(agent = ?self.agent, outcome = "invalid_json", "session_hook_skipped");
            return;
        };
        let Some(hook_op) = hook.to_hook_op(self.agent, pid) else {
            return;
        };
        let Ok(socket) = server::resolve_socket(self.socket.clone()) else {
            // omni-dev: coverage ignore reason="resolve_socket fails only when the platform has no data directory to put the default socket in (no resolvable home), which a test cannot reproduce on macOS or Linux; the sink is fail-open by design, so this is the same silent return as every other skipped hook"
            tracing::debug!(agent = ?self.agent, outcome = "socket_resolution_failed", "session_hook_skipped");
            return;
            // omni-dev: coverage end
        };
        // Stamped once, so the journal record and the POST name the same event and
        // the daemon can drop whichever copy it sees second (#2108).
        let stamp = journal::new_stamp();
        self.journal(&socket, &hook_op, &stamp);
        let Some((op, payload)) = hook_op.wire(self.agent, Some(&stamp)) else {
            return; // omni-dev: coverage ignore-line reason="wire returns None only through the serialization failure ignored in wire() itself (a non-UTF-8 cwd, which a hook payload cannot carry), so this arm is unreachable for the same reason"
        };
        let env = DaemonEnvelope::service(SERVICE, op, payload);
        let outcome =
            match tokio::time::timeout(HOOK_TIMEOUT, DaemonClient::new(&socket).request(env)).await
            {
                Err(_) => "timeout",
                Ok(Err(_)) => "transport_failed",
                Ok(Ok(reply)) if !reply.ok => "daemon_rejected",
                Ok(Ok(_)) => "delivered",
            };
        tracing::debug!(agent = ?self.agent, session_id = ?hook.session_id, ?pid, op, outcome, "session_hook_report");
    }

    /// Appends the event to its session's journal beside the socket, so the
    /// daemon can recover it if the POST is lost (#2108). Fail-open exactly like
    /// the POST: an error is logged — never with the payload — and swallowed, so
    /// a journal that cannot be written costs one event's durability, never a
    /// turn. Written *before* the POST, so a daemon that dies mid-delivery still
    /// finds the event on disk.
    fn journal(&self, socket: &Path, op: &HookOp, stamp: &EventStamp) {
        let dir = paths::sessions_journal_dir_for_socket(socket);
        match journal::append(&dir, &op.record(stamp)) {
            Ok(()) => {
                tracing::debug!(agent = ?self.agent, outcome = "journaled", "session_hook_journal");
            }
            Err(error) => {
                tracing::debug!(agent = ?self.agent, outcome = "journal_failed", %error, "session_hook_journal");
            }
        }
    }
}

/// The pid of the agent process that ran this hook, from the sink's parent pid.
///
/// The agent runs the installed hook command directly (a simple command, so no
/// per-hook shell sits in between), making the parent the `claude` / `codex`
/// process itself. The pid tells a resumed session's new process from the old
/// one it replaced (#1948). Pid 1 means the hook was orphaned — its agent already
/// exited and init/launchd adopted it — so it identifies nothing.
fn agent_pid(parent: u32) -> Option<u32> {
    (parent > 1).then_some(parent)
}

/// The subset of a Claude Code hook payload the sink reads. Every field is
/// optional and defaulted, so an unexpected or future payload shape never fails
/// to parse (the sink then simply produces no op). See the hooks docs.
#[derive(Debug, Clone, Default, Deserialize)]
struct HookPayload {
    /// Subagent hooks share the parent session id.
    #[serde(default)]
    agent_id: Option<String>,
    #[serde(default)]
    session_id: Option<String>,
    #[serde(default)]
    transcript_path: Option<PathBuf>,
    #[serde(default)]
    cwd: Option<PathBuf>,
    #[serde(default)]
    hook_event_name: Option<String>,
    /// Present on `Notification` events — the message classified into a
    /// [`NotificationKind`] when `notification_type` is absent or unrecognised.
    #[serde(default)]
    message: Option<String>,
    /// Present on `Notification` events — Claude Code's own classification
    /// (`permission_prompt`, `idle_prompt`, …), preferred over `message`.
    #[serde(default)]
    notification_type: Option<String>,
    /// Present on `SessionEnd` — why the session ended.
    #[serde(default)]
    reason: Option<String>,
    /// Present on `SessionStart` — why it fired (`startup`, `resume`, `clear`,
    /// `compact`). A `compact` start is not a new session.
    #[serde(default)]
    source: Option<String>,
    /// Present on tool events. Codex's clarifying-question UI is the
    /// `request_user_input` tool, so its `PreToolUse` is a wait for input.
    #[serde(default)]
    tool_name: Option<String>,
    /// Best-effort model id, when a payload carries one.
    #[serde(default)]
    model: Option<String>,
}

/// What the sink reports for one hook event: the typed value the socket POST and
/// the journal record are both made from, so the two cannot drift (#2108).
#[derive(Debug, Clone)]
enum HookOp {
    /// An `observe` sighting.
    Observe(ObserveRequest),
    /// A `SessionEnd`, which the daemon's `end` op takes without an agent; the
    /// agent rides only into the journal record, to name its directory.
    End {
        agent: Agent,
        session_id: String,
        reason: Option<String>,
        pid: Option<u32>,
    },
}

impl HookOp {
    /// The journal record for this event.
    fn record(&self, stamp: &EventStamp) -> JournalRecord {
        match self {
            Self::Observe(req) => JournalRecord::observe(req, stamp),
            Self::End {
                agent,
                session_id,
                reason,
                pid,
            } => JournalRecord::end(*agent, session_id, reason.as_deref(), *pid, stamp),
        }
    }

    /// The `(op, payload)` for the daemon, carrying `stamp` as an additive
    /// top-level `stamp` object when there is one (an older daemon ignores it).
    fn wire(&self, agent: HookAgent, stamp: Option<&EventStamp>) -> Option<(&'static str, Value)> {
        let (op, mut payload) = match self {
            Self::Observe(request) => {
                let Ok(payload) = serde_json::to_value(request) else {
                    // omni-dev: coverage ignore reason="to_value on an ObserveRequest fails only for a non-UTF-8 cwd, and the hook payload's cwd is deserialized from a JSON string, so it is always UTF-8; the arm exists so a future non-string field cannot silently drop the report"
                    tracing::debug!(
                        ?agent,
                        outcome = "serialization_failed",
                        "session_hook_skipped"
                    );
                    return None;
                    // omni-dev: coverage end
                };
                ("observe", payload)
            }
            Self::End {
                session_id,
                reason,
                pid,
                ..
            } => {
                let mut payload = json!({ "session_id": session_id });
                if let Some(reason) = reason {
                    payload["reason"] = Value::String(reason.clone());
                }
                if let Some(pid) = pid {
                    payload["pid"] = Value::from(*pid);
                }
                ("end", payload)
            }
        };
        if let Some(stamp) = stamp {
            payload["stamp"] = json!({ "ts": stamp.ts, "seq": stamp.seq });
        }
        Some((op, payload))
    }
}

impl HookPayload {
    /// Maps this hook payload to the [`HookOp`] to report, or `None` when it
    /// carries no `session_id` or names an event the tracker ignores. `pid` (the
    /// [`agent_pid`]) rides along on both ops when known — it is also the seed
    /// for pid-based liveness (#1916), whose identity-token reading is entirely
    /// the daemon's own [`pid_watcher`](crate::sessions::pid_watcher) work, never
    /// this sink's.
    fn to_hook_op(&self, agent: HookAgent, pid: Option<u32>) -> Option<HookOp> {
        let Some(session_id) = self.session_id.clone().filter(|s| !s.trim().is_empty()) else {
            tracing::debug!(
                ?agent,
                outcome = "missing_session_id",
                "session_hook_skipped"
            );
            return None;
        };
        let Some(event_name) = self.hook_event_name.as_deref() else {
            tracing::debug!(?agent, outcome = "missing_event", "session_hook_skipped");
            return None;
        };
        if event_name == "SessionEnd" {
            return Some(HookOp::End {
                agent: agent.agent(),
                session_id,
                reason: self.reason.clone().or_else(|| self.message.clone()),
                pid,
            });
        }
        let mapped = match agent {
            HookAgent::Claude => session_event_for(
                event_name,
                self.source.as_deref(),
                self.notification_type.as_deref(),
                self.message.as_deref(),
            ),
            HookAgent::Codex => codex_session_event_for(
                event_name,
                self.source.as_deref(),
                self.tool_name.as_deref(),
            ),
        };
        let Some(mut event) = mapped else {
            tracing::debug!(?agent, outcome = "unmapped_event", "session_hook_skipped");
            return None;
        };
        let agent_id = (agent == HookAgent::Claude)
            .then(|| self.agent_id.clone())
            .flatten()
            .filter(|id| !id.trim().is_empty());
        if agent_id.is_some() && event_name == "SubagentStop" {
            event = SessionEvent::PostToolUse;
        }
        Some(HookOp::Observe(ObserveRequest {
            agent_id,
            agent: agent.agent(),
            session_id,
            cwd: self.cwd.clone(),
            transcript_path: self.transcript_path.clone(),
            event,
            repo: None,
            model: self.model.clone(),
            pid,
        }))
    }

    /// The unstamped `(op, payload)` for the daemon — [`to_hook_op`] and
    /// [`HookOp::wire`] together, as the sink sent it before the journal.
    ///
    /// [`to_hook_op`]: Self::to_hook_op
    #[cfg(test)]
    fn to_op(&self, agent: HookAgent, pid: Option<u32>) -> Option<(&'static str, Value)> {
        self.to_hook_op(agent, pid)?.wire(agent, None)
    }
}

/// Maps a Claude Code hook event name to the [`SessionEvent`] it implies, or
/// `None` for an event the tracker does not act on. `SessionEnd` is handled
/// separately (it maps to the `end` op, not `observe`).
///
/// Everything lands on the **existing** events, so the engine's state machine
/// handles parent hooks as before (the Codex precedent, ADR-0087). Subagent
/// identity travels separately so the registry can preserve parent activity
/// and release only the wait belonging to a completing subagent (#1926):
///
/// - `PermissionRequest` is the dedicated "a prompt is about to be shown"
///   event, so it sets the permission wait without matching `Notification`
///   text. The sink must never answer it — a `PermissionRequest` hook that
///   prints a decision approves or denies on the user's behalf — and it cannot:
///   [`HookCommand`] writes nothing to stdout;
/// - `Elicitation` (an MCP server asking the user a question) is a wait for
///   input, released by its `ElicitationResult`;
/// - `PostToolUseFailure` and `PermissionDenied` (auto mode refused a call and
///   the turn goes on) are post-tool signals: `working`;
/// - `StopFailure` ends a turn on an API error, which fires no `Stop`;
/// - `SubagentStart` means a subagent is being spawned inside a turn: `working`;
/// - `SubagentStop`, `PreCompact` and `PostCompact` can all fire while the
///   session is idle — a background subagent finishing after the turn's `Stop`,
///   a manual `/compact` — and nothing after them would release a `working`, so
///   they are the state-preserving
///   [`TranscriptDiscovered`](SessionEvent::TranscriptDiscovered) sighting,
///   which refreshes liveness alone;
/// - `SessionStart` with `source: "compact"` follows a compaction, which can run
///   mid-turn, and is not a new session. Since growth no longer moves a
///   `starting` session (#1946), mapping it to `SessionStart` would hold a
///   working session at `starting` until its next tool hook, so it is the same
///   state-preserving sighting. Every other source (`startup`, `resume`,
///   `clear`) is a real start.
///
/// `PostToolBatch` is deliberately not installed: every tool in a batch has
/// already reported its own `PostToolUse` / `PostToolUseFailure`, so it would be
/// a process spawn per batch carrying no new state.
///
/// No event fires when the user answers a permission prompt, either way; the
/// wait is released by whatever hook comes next.
fn session_event_for(
    event_name: &str,
    source: Option<&str>,
    notification_type: Option<&str>,
    message: Option<&str>,
) -> Option<SessionEvent> {
    Some(match event_name {
        "SessionStart" if source == Some("compact") => SessionEvent::TranscriptDiscovered,
        "SessionStart" => SessionEvent::SessionStart,
        "UserPromptSubmit" => SessionEvent::UserPromptSubmit,
        "PreToolUse" => SessionEvent::PreToolUse,
        "PostToolUse" | "PostToolUseFailure" | "PermissionDenied" | "ElicitationResult"
        | "SubagentStart" => SessionEvent::PostToolUse,
        "SubagentStop" | "PreCompact" | "PostCompact" => SessionEvent::TranscriptDiscovered,
        "Stop" | "StopFailure" => SessionEvent::Stop,
        "PermissionRequest" => SessionEvent::Notification(NotificationKind::PermissionPrompt),
        "Elicitation" => SessionEvent::Notification(NotificationKind::AgentNeedsInput),
        "Notification" => {
            let kind = classify_notification(notification_type, message);
            let has_notification_type = notification_type.is_some();
            let has_message = message.is_some();
            tracing::debug!(
                ?kind,
                has_notification_type,
                has_message,
                "session_notification_classified"
            );
            SessionEvent::Notification(kind)
        }
        _ => return None,
    })
}

/// Maps a Codex hook event name to the [`SessionEvent`] it implies, or `None` for
/// an event the tracker does not act on (ADR-0087). Codex's payload uses Claude
/// Code's field names, but adds events Claude lacks, and all of them land on the
/// **existing** events so the engine's state machine is unchanged:
///
/// - `PermissionRequest` is Codex's dedicated "waiting on an approval" event, so
///   it is the reliable permission signal (its resolution is inferred from the
///   next `PostToolUse`, or from the turn ending);
/// - `PreToolUse` of the `request_user_input` tool is the clarifying-question UI,
///   a wait for input until its `PostToolUse`;
/// - `Interrupt` (Esc / Ctrl-C mid-turn, or a declined approval in the TUI) ends
///   the turn without a `Stop`, so it is one;
/// - `SubagentStart` carries the parent session's id and is caused by the
///   parent's spawn tool call, so it can only occur inside a turn: `working`;
/// - `SubagentStop`, `PreCompact` and `PostCompact` can fire while the session
///   is idle — `/compact` is captured as `Stop · PreCompact · PostCompact`, and
///   a subagent that is not joined can finish after the turn's `Stop` — and
///   nothing after them would release a `working`, so, as for Claude (#1925),
///   they are the state-preserving
///   [`TranscriptDiscovered`](SessionEvent::TranscriptDiscovered) sighting.
///   Liveness needs no heartbeat here: Codex's thread lock keeps an idle
///   session alive (#1909);
/// - a `SessionStart` with `source: "compact"` is not a new session, so, as for
///   Claude, it preserves the state rather than resetting it to `starting`
///   (#1946).
///
/// `SessionEnd` is handled by the caller, as for Claude.
fn codex_session_event_for(
    event_name: &str,
    source: Option<&str>,
    tool_name: Option<&str>,
) -> Option<SessionEvent> {
    Some(match event_name {
        "SessionStart" if source == Some("compact") => SessionEvent::TranscriptDiscovered,
        "SessionStart" => SessionEvent::SessionStart,
        "UserPromptSubmit" => SessionEvent::UserPromptSubmit,
        "PreToolUse" if tool_name == Some("request_user_input") => {
            SessionEvent::Notification(NotificationKind::AgentNeedsInput)
        }
        "PreToolUse" => SessionEvent::PreToolUse,
        "PostToolUse" | "SubagentStart" => SessionEvent::PostToolUse,
        "SubagentStop" | "PreCompact" | "PostCompact" => SessionEvent::TranscriptDiscovered,
        "PermissionRequest" => SessionEvent::Notification(NotificationKind::PermissionPrompt),
        "Stop" | "Interrupt" => SessionEvent::Stop,
        _ => return None,
    })
}

/// Classifies a `Notification` into a [`NotificationKind`]. A version that sends
/// Claude Code's own `notification_type` is classified by it alone — a type we
/// do not map (`auth_success`, …) is [`NotificationKind::Other`] rather than a
/// guess at its message, which could mention "allow" or "permission" without
/// asking for anything. Only an older version that sends no type falls back to
/// best-effort substring matching on the version-unstable message text, where an
/// unrecognised message is likewise [`NotificationKind::Other`] (which carries no
/// state signal and leaves the session's state unchanged).
fn classify_notification(
    notification_type: Option<&str>,
    message: Option<&str>,
) -> NotificationKind {
    match notification_type {
        Some("permission_prompt") => return NotificationKind::PermissionPrompt,
        Some("idle_prompt") => return NotificationKind::IdlePrompt,
        Some("elicitation_dialog") => return NotificationKind::AgentNeedsInput,
        Some(_) => return NotificationKind::Other,
        None => {}
    }
    let Some(message) = message else {
        return NotificationKind::Other;
    };
    let lower = message.to_lowercase();
    if lower.contains("permission") || lower.contains("approve") || lower.contains("allow") {
        NotificationKind::PermissionPrompt
    } else if lower.contains("waiting for your input")
        || lower.contains("idle")
        || lower.contains("needs your input")
    {
        NotificationKind::IdlePrompt
    } else {
        NotificationKind::Other
    }
}

// --- install-hooks / uninstall-hooks ----------------------------------------

/// Installs the sessions-tracker hooks into `~/.claude/settings.json`, plus the
/// pi.dev extension when pi is installed and the Codex hooks when Codex is.
#[derive(Parser)]
pub struct InstallHooksCommand {
    /// Path to the Claude settings file. Defaults to `~/.claude/settings.json`
    /// (respecting `$CLAUDE_CONFIG_DIR`).
    #[arg(long, value_name = "PATH")]
    pub settings: Option<PathBuf>,

    /// pi.dev's agent directory. Defaults to `$PI_CODING_AGENT_DIR`, else
    /// `~/.pi/agent`. Passing it installs the pi extension even when pi is not
    /// detected.
    #[arg(long, value_name = "PATH")]
    pub pi_agent_dir: Option<PathBuf>,

    /// Codex's home directory, holding `hooks.json`. Defaults to `$CODEX_HOME`,
    /// else `~/.codex`. Passing it installs the Codex hooks even when Codex is
    /// not detected.
    #[arg(long, value_name = "PATH")]
    pub codex_home: Option<PathBuf>,
}

impl InstallHooksCommand {
    /// Executes the install: rewrites any stale sink left by a moved binary,
    /// merges the hook block idempotently (preserving any other hooks already
    /// present), then writes the pi extension if pi is present and the Codex
    /// hooks if Codex is.
    pub fn execute(self) -> Result<()> {
        let path = settings_path(self.settings)?;
        let mut settings = read_settings(&path)?;
        let command = hook_command();
        let sync = sync_claude_hooks(&mut settings, &command);
        if sync.is_noop() {
            println!(
                "sessions hooks already installed in {} (no change)",
                path.display()
            );
        } else {
            write_settings(&path, &settings)?;
            if sync.replaced > 0 {
                println!(
                    "rewrote {} stale `sessions hook` entry(ies) in {} in place",
                    sync.replaced,
                    path.display()
                );
            }
            if sync.deduped > 0 {
                println!(
                    "removed {} duplicate `sessions hook` entry(ies) from {}",
                    sync.deduped,
                    path.display()
                );
            }
            if sync.added > 0 {
                println!(
                    "installed {} sessions hook event(s) into {}",
                    sync.added,
                    path.display()
                );
            }
            println!("command: {command}");
        }
        if sync.customised > 0 {
            println!("{}", customised_note(sync.customised));
        }
        install_pi_extension(self.pi_agent_dir)?;
        install_codex_hooks(self.codex_home)
    }
}

/// Removes the sessions-tracker hooks from `~/.claude/settings.json`, the pi.dev
/// extension, and the Codex hooks.
#[derive(Parser)]
pub struct UninstallHooksCommand {
    /// Path to the Claude settings file. Defaults to `~/.claude/settings.json`
    /// (respecting `$CLAUDE_CONFIG_DIR`).
    #[arg(long, value_name = "PATH")]
    pub settings: Option<PathBuf>,

    /// pi.dev's agent directory. Defaults to `$PI_CODING_AGENT_DIR`, else
    /// `~/.pi/agent`.
    #[arg(long, value_name = "PATH")]
    pub pi_agent_dir: Option<PathBuf>,

    /// Codex's home directory, holding `hooks.json`. Defaults to `$CODEX_HOME`,
    /// else `~/.codex`.
    #[arg(long, value_name = "PATH")]
    pub codex_home: Option<PathBuf>,
}

impl UninstallHooksCommand {
    /// Executes the uninstall: removes any hook entries whose command is ours
    /// (including a stale sink from another path), leaving every other hook
    /// untouched, then removes our pi extension and Codex hooks.
    pub fn execute(self) -> Result<()> {
        let path = settings_path(self.settings)?;
        if path.exists() {
            let mut settings = read_settings(&path)?;
            let current = hook_command();
            let removed = remove_hooks(&mut settings, |c| c == current || is_stale_claude_sink(c));
            write_settings(&path, &settings)?;
            println!(
                "removed {removed} sessions hook entry(ies) from {}",
                path.display()
            );
            let customised = count_customised_sinks(&settings, &current);
            if customised > 0 {
                println!("{}", customised_note(customised));
            }
        } else {
            println!("no settings file at {} (nothing to remove)", path.display());
        }
        uninstall_pi_extension(self.pi_agent_dir)?;
        uninstall_codex_hooks(self.codex_home)
    }
}

// --- pi.dev extension ---------------------------------------------------------

/// Filename of the generated extension inside pi's global extensions directory.
const PI_EXTENSION_NAME: &str = "omni-dev-sessions.ts";

/// The generated extension's source, with [`PI_SOCKET_PLACEHOLDER`] still in it.
const PI_EXTENSION_TEMPLATE: &str = include_str!("../templates/pi-sessions-extension.ts");

/// Stands in for the socket path (a JSON string literal) in the template.
const PI_SOCKET_PLACEHOLDER: &str = "__OMNI_DEV_SOCKET__";

/// The template's first line. A file that does not start with it is not ours, so
/// install refuses to overwrite it and uninstall leaves it alone.
fn pi_extension_marker() -> &'static str {
    PI_EXTENSION_TEMPLATE.lines().next().unwrap_or_default()
}

/// The extension source with the daemon socket baked in, as `install-hooks`
/// bakes in the absolute exe path: pi's Node process has no other way to find
/// the socket, and resolving it there would duplicate `dirs::data_dir()`.
fn render_pi_extension(socket: &Path) -> String {
    let literal =
        serde_json::to_string(&socket.display().to_string()).unwrap_or_else(|_| "\"\"".to_string());
    PI_EXTENSION_TEMPLATE.replace(PI_SOCKET_PLACEHOLDER, &literal)
}

/// pi's default agent directory: `$PI_CODING_AGENT_DIR`, else `~/.pi/agent`.
fn default_pi_agent_dir() -> Result<PathBuf> {
    if let Some(dir) = std::env::var_os("PI_CODING_AGENT_DIR").filter(|d| !d.is_empty()) {
        return Ok(PathBuf::from(dir));
    }
    let home = dirs::home_dir().context("could not resolve the home directory")?;
    Ok(home.join(".pi").join("agent"))
}

/// Whether pi.dev is installed: its agent directory exists (pi has run), or a
/// `pi` executable is on `path` (installed but never run).
fn pi_is_present(agent_dir: &Path, path: Option<&std::ffi::OsStr>) -> bool {
    agent_dir.is_dir()
        || path.is_some_and(|path| {
            std::env::split_paths(path).any(|dir| is_executable(&dir.join("pi")))
        })
}

/// Whether `path` is a file with an execute bit set.
fn is_executable(path: &Path) -> bool {
    use std::os::unix::fs::PermissionsExt;

    std::fs::metadata(path)
        .is_ok_and(|meta| meta.is_file() && meta.permissions().mode() & 0o111 != 0)
}

/// What [`write_pi_extension`] did.
#[derive(Debug, PartialEq, Eq)]
enum PiInstall {
    /// Wrote a new or updated extension.
    Written,
    /// The file already had exactly this content.
    Unchanged,
}

/// Writes `contents` to `<agent_dir>/extensions/omni-dev-sessions.ts`, creating
/// the directory. Refuses to replace a file of that name that is not ours.
fn write_pi_extension(agent_dir: &Path, contents: &str) -> Result<(PathBuf, PiInstall)> {
    let dir = agent_dir.join("extensions");
    let file = dir.join(PI_EXTENSION_NAME);
    if file.exists() {
        let existing = std::fs::read_to_string(&file)
            .with_context(|| format!("failed to read {}", file.display()))?;
        if existing == contents {
            return Ok((file, PiInstall::Unchanged));
        }
        if !existing.starts_with(pi_extension_marker()) {
            bail!(
                "{} exists and was not written by omni-dev; refusing to overwrite it",
                file.display()
            );
        }
    }
    std::fs::create_dir_all(&dir).with_context(|| format!("failed to create {}", dir.display()))?;
    std::fs::write(&file, contents)
        .with_context(|| format!("failed to write {}", file.display()))?;
    Ok((file, PiInstall::Written))
}

/// Removes our extension from `<agent_dir>/extensions/`, returning its path when
/// it removed it. A file of that name that is not ours is left alone.
fn remove_pi_extension(agent_dir: &Path) -> Result<Option<PathBuf>> {
    let file = agent_dir.join("extensions").join(PI_EXTENSION_NAME);
    let Ok(existing) = std::fs::read_to_string(&file) else {
        return Ok(None);
    };
    if !existing.starts_with(pi_extension_marker()) {
        return Ok(None);
    }
    std::fs::remove_file(&file).with_context(|| format!("failed to remove {}", file.display()))?;
    Ok(Some(file))
}

/// The pi half of `install-hooks`. Without `--pi-agent-dir` it installs only when
/// pi is present, so a machine without pi gets nothing under `~/.pi`.
fn install_pi_extension(explicit: Option<PathBuf>) -> Result<()> {
    let agent_dir = if let Some(dir) = explicit {
        dir
    } else {
        let dir = default_pi_agent_dir()?;
        if !pi_is_present(&dir, std::env::var_os("PATH").as_deref()) {
            println!(
                "pi.dev not found (no {} and no `pi` on PATH); skipped its extension",
                dir.display()
            );
            return Ok(());
        }
        dir
    };
    let socket = server::resolve_socket(None)?;
    let (file, outcome) = write_pi_extension(&agent_dir, &render_pi_extension(&socket))?;
    match outcome {
        PiInstall::Unchanged => println!(
            "pi.dev extension already installed at {} (no change)",
            file.display()
        ),
        PiInstall::Written => {
            println!(
                "installed the pi.dev sessions extension at {}",
                file.display()
            );
            println!("pi sessions started after this report their state");
        }
    }
    Ok(())
}

/// The pi half of `uninstall-hooks`. Runs whether or not pi is present, so an
/// uninstalled pi does not strand the file.
fn uninstall_pi_extension(explicit: Option<PathBuf>) -> Result<()> {
    let agent_dir = match explicit {
        Some(dir) => dir,
        None => default_pi_agent_dir()?,
    };
    if let Some(file) = remove_pi_extension(&agent_dir)? {
        println!("removed {}", file.display());
    }
    Ok(())
}

// --- install-wrapper / uninstall-wrapper -------------------------------------

/// The VS Code setting the Claude Code extension reads to decide what to launch
/// Claude through. Machine-scoped, so it belongs in the *user* settings file.
const WRAPPER_SETTING_KEY: &str = "claudeCode.claudeProcessWrapper";

/// Filename of the shim written into omni-dev's runtime directory.
const SHIM_NAME: &str = "claude-wrap";

/// Installs the `claude-wrap` shim and points VS Code's Claude extension at it.
#[derive(Parser)]
pub struct InstallWrapperCommand {
    /// Path to the VS Code user settings file. Defaults to the platform's
    /// `Code/User/settings.json`.
    #[arg(long, value_name = "PATH")]
    pub settings: Option<PathBuf>,

    /// Path to write the shim to. Defaults to `<data-dir>/omni-dev/claude-wrap`.
    #[arg(long, value_name = "PATH")]
    pub shim: Option<PathBuf>,
}

impl InstallWrapperCommand {
    /// Executes the install: writes the shim, then idempotently sets the
    /// extension's wrapper setting to point at it.
    pub fn execute(self) -> Result<()> {
        let shim = shim_path(self.shim)?;
        write_shim(&shim)?;
        let path = vscode_settings_path(self.settings)?;
        let target = shim.display().to_string();

        let mut settings =
            read_settings(&path).map_err(|error| manual_setup_hint(&error, &target))?;
        let changed = set_wrapper(&mut settings, &target);
        write_settings(&path, &settings)?;

        println!("wrapper shim: {target}");
        if changed {
            println!("set {WRAPPER_SETTING_KEY} in {}", path.display());
            println!("reload VS Code; Claude tabs opened after that report their exact state");
        } else {
            println!(
                "{WRAPPER_SETTING_KEY} already points there in {} (no change)",
                path.display()
            );
        }
        Ok(())
    }
}

/// Removes the wrapper setting and the shim it points at.
#[derive(Parser)]
pub struct UninstallWrapperCommand {
    /// Path to the VS Code user settings file. Defaults to the platform's
    /// `Code/User/settings.json`.
    #[arg(long, value_name = "PATH")]
    pub settings: Option<PathBuf>,

    /// Path the shim was written to. Defaults to
    /// `<data-dir>/omni-dev/claude-wrap`.
    #[arg(long, value_name = "PATH")]
    pub shim: Option<PathBuf>,
}

impl UninstallWrapperCommand {
    /// Executes the uninstall: clears the setting when (and only when) it still
    /// points at our shim, then removes the shim file.
    pub fn execute(self) -> Result<()> {
        let shim = shim_path(self.shim)?;
        let target = shim.display().to_string();
        let path = vscode_settings_path(self.settings)?;

        if path.exists() {
            let mut settings =
                read_settings(&path).map_err(|error| manual_setup_hint(&error, &target))?;
            if clear_wrapper(&mut settings, &target) {
                write_settings(&path, &settings)?;
                println!("cleared {WRAPPER_SETTING_KEY} in {}", path.display());
            } else {
                println!(
                    "{WRAPPER_SETTING_KEY} in {} does not point at our shim; left alone",
                    path.display()
                );
            }
        } else {
            println!("no settings file at {} (nothing to clear)", path.display());
        }

        if shim.exists() {
            std::fs::remove_file(&shim)
                .with_context(|| format!("failed to remove {}", shim.display()))?;
            println!("removed {target}");
        }
        Ok(())
    }
}

/// The shim's path: an explicit `--shim`, else `claude-wrap` in omni-dev's
/// runtime directory (beside the daemon socket).
fn shim_path(explicit: Option<PathBuf>) -> Result<PathBuf> {
    match explicit {
        Some(path) => Ok(path),
        None => Ok(paths::runtime_dir()?.join(SHIM_NAME)),
    }
}

/// The VS Code **user** settings path: an explicit `--settings`, else
/// `<config-dir>/Code/User/settings.json` — `~/Library/Application Support/…` on
/// macOS and `~/.config/…` on Linux, which is where a machine-scoped setting has
/// to live. (The runtime directory is `data_dir()`; this one is deliberately
/// `config_dir()`.)
fn vscode_settings_path(explicit: Option<PathBuf>) -> Result<PathBuf> {
    if let Some(path) = explicit {
        return Ok(path);
    }
    let base = dirs::config_dir().context("could not determine the user config directory")?;
    Ok(base.join("Code").join("User").join("settings.json"))
}

/// The shim script's contents.
///
/// The extension spawns the configured wrapper directly — no shell, no argument
/// splitting — so the setting has to name a single executable file. This is that
/// file: a one-line `exec` into `omni-dev claude-wrap`, using the absolute path
/// of the running binary so it does not depend on VS Code's `PATH`.
fn shim_contents() -> String {
    let exe = std::env::current_exe()
        .map_or_else(|_| "omni-dev".to_string(), |exe| exe.display().to_string());
    format!("#!/bin/sh\nexec \"{exe}\" claude-wrap -- \"$@\"\n")
}

/// Writes the shim, creating its directory and marking it owner-executable.
fn write_shim(path: &Path) -> Result<()> {
    use std::os::unix::fs::PermissionsExt;

    if let Some(parent) = path.parent() {
        paths::ensure_dir_0700(parent)?;
    }
    std::fs::write(path, shim_contents())
        .with_context(|| format!("failed to write {}", path.display()))?;
    std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))
        .with_context(|| format!("failed to make {} executable", path.display()))
}

/// Points the wrapper setting at `shim`, returning whether anything changed.
fn set_wrapper(settings: &mut Value, shim: &str) -> bool {
    let Some(root) = settings.as_object_mut() else {
        return false;
    };
    if root.get(WRAPPER_SETTING_KEY).and_then(Value::as_str) == Some(shim) {
        return false;
    }
    root.insert(WRAPPER_SETTING_KEY.to_string(), json!(shim));
    true
}

/// Clears the wrapper setting when it points at `shim`, returning whether it
/// did. A setting pointing somewhere else is someone else's and is left alone.
fn clear_wrapper(settings: &mut Value, shim: &str) -> bool {
    let Some(root) = settings.as_object_mut() else {
        return false;
    };
    if root.get(WRAPPER_SETTING_KEY).and_then(Value::as_str) != Some(shim) {
        return false;
    }
    root.remove(WRAPPER_SETTING_KEY);
    true
}

/// Turns an unparseable-settings error into one that tells the user what to do.
///
/// VS Code settings files are JSON**C** — comments and trailing commas are
/// legal there and common in practice, and [`read_settings`] rightly refuses to
/// rewrite what it cannot parse. The shim is already in place by then, so the
/// only thing left is one line to paste.
fn manual_setup_hint(error: &anyhow::Error, shim: &str) -> anyhow::Error {
    anyhow!(
        "{error:#}\n\n\
         VS Code settings files may contain comments or trailing commas, which cannot be \
         rewritten safely. The shim is installed, so add this line by hand instead:\n\n    \
         \"{WRAPPER_SETTING_KEY}\": \"{shim}\""
    )
}

/// One hook event the tracker installs.
#[derive(Debug, Clone, Copy)]
struct HookSpec {
    /// The event name, as the settings file keys it.
    event: &'static str,
    /// Whether the event's group gets the `*` tool `matcher` (the tool events —
    /// `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`,
    /// `PermissionDenied` — match on tool name; the rest are left unmatched,
    /// which matches every occurrence).
    matcher: bool,
    /// A per-hook `timeout` in seconds, where the agent caps the event below
    /// its default.
    timeout: Option<u64>,
}

impl HookSpec {
    const fn new(event: &'static str) -> Self {
        Self {
            event,
            matcher: false,
            timeout: None,
        }
    }

    const fn matched(event: &'static str) -> Self {
        Self {
            matcher: true,
            ..Self::new(event)
        }
    }

    const fn capped(event: &'static str, secs: u64) -> Self {
        Self {
            timeout: Some(secs),
            ..Self::new(event)
        }
    }
}

/// The Claude Code hook events the tracker installs. `SessionEnd` is included —
/// it maps to the `end` op in the sink. The events after `SessionEnd` narrow
/// the hooks-only state gaps (#1915). Claude Code 2.1.280 drops a hook event it
/// does not know with a warning rather than rejecting the settings file; how
/// older versions treat one is unverified (docs/sessions-service.md).
const HOOK_EVENTS: &[HookSpec] = &[
    HookSpec::new("SessionStart"),
    HookSpec::new("UserPromptSubmit"),
    HookSpec::matched("PreToolUse"),
    HookSpec::matched("PostToolUse"),
    HookSpec::new("Notification"),
    HookSpec::new("Stop"),
    HookSpec::new("SessionEnd"),
    HookSpec::matched("PermissionRequest"),
    HookSpec::matched("PermissionDenied"),
    HookSpec::matched("PostToolUseFailure"),
    HookSpec::new("StopFailure"),
    HookSpec::new("Elicitation"),
    HookSpec::new("ElicitationResult"),
    HookSpec::new("SubagentStart"),
    HookSpec::new("SubagentStop"),
    HookSpec::new("PreCompact"),
    HookSpec::new("PostCompact"),
];

/// The Codex hook events the tracker installs into `$CODEX_HOME/hooks.json`:
/// Claude's set minus `Notification` (Codex has none), plus Codex's
/// `PermissionRequest` and `Interrupt` and the compaction and subagent events
/// (ADR-0087). Codex caps `SessionEnd` and `Interrupt` hooks at 3 s.
const CODEX_HOOK_EVENTS: &[HookSpec] = &[
    HookSpec::new("SessionStart"),
    HookSpec::new("UserPromptSubmit"),
    HookSpec::matched("PreToolUse"),
    HookSpec::matched("PostToolUse"),
    HookSpec::new("PermissionRequest"),
    HookSpec::new("Stop"),
    HookSpec::capped("Interrupt", 3),
    HookSpec::capped("SessionEnd", 3),
    HookSpec::new("PreCompact"),
    HookSpec::new("PostCompact"),
    HookSpec::new("SubagentStart"),
    HookSpec::new("SubagentStop"),
];

/// The hook command string written into settings.json: the absolute path of the
/// running binary plus `sessions hook`, so Claude Code invokes *this* omni-dev
/// regardless of its hook `PATH`. Falls back to the bare `omni-dev sessions hook`
/// when the executable path cannot be resolved (documented as the portable form).
fn hook_command() -> String {
    match std::env::current_exe() {
        Ok(exe) => format!("{} sessions hook", exe.display()),
        Err(_) => "omni-dev sessions hook".to_string(),
    }
}

/// The Claude settings file path: an explicit `--settings`, else
/// `$CLAUDE_CONFIG_DIR/settings.json`, else `~/.claude/settings.json`.
fn settings_path(explicit: Option<PathBuf>) -> Result<PathBuf> {
    if let Some(path) = explicit {
        return Ok(path);
    }
    if let Some(dir) = std::env::var_os("CLAUDE_CONFIG_DIR") {
        return Ok(PathBuf::from(dir).join("settings.json"));
    }
    let home = dirs::home_dir().context("could not resolve the home directory")?;
    Ok(home.join(".claude").join("settings.json"))
}

/// Reads and parses `path` into a JSON object, treating a missing file as an
/// empty object. Errors (rather than clobbering) when the file exists but is not
/// valid JSON, or is valid JSON that is not an object.
fn read_settings(path: &Path) -> Result<Value> {
    if !path.exists() {
        return Ok(json!({}));
    }
    let text = std::fs::read_to_string(path)
        .with_context(|| format!("failed to read {}", path.display()))?;
    if text.trim().is_empty() {
        return Ok(json!({}));
    }
    let value: Value = serde_json::from_str(&text).with_context(|| {
        format!(
            "{} is not valid JSON; refusing to overwrite it",
            path.display()
        )
    })?;
    if !value.is_object() {
        bail!(
            "{} is not a JSON object; refusing to overwrite it",
            path.display()
        );
    }
    Ok(value)
}

/// Serializes `settings` back to `path`, pretty-printed with a trailing newline,
/// creating the parent directory if needed.
fn write_settings(path: &Path, settings: &Value) -> Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("failed to create {}", parent.display()))?;
    }
    let mut text = serde_json::to_string_pretty(settings)?;
    text.push('\n');
    std::fs::write(path, text).with_context(|| format!("failed to write {}", path.display()))?;
    Ok(())
}

/// Merges the sessions-tracker hook `command` into a settings object under each
/// event in `specs`, returning how many events were newly added. Idempotent (an
/// event that already has a group running `command` is skipped) and additive (it
/// never touches other hooks, and appending moves no existing group). Creates
/// `hooks` and any per-event array as needed.
fn merge_hooks(settings: &mut Value, command: &str, specs: &[HookSpec]) -> usize {
    // `read_settings` guarantees an object, but degrade gracefully rather than
    // panic if a caller passes something else.
    let Some(root) = settings.as_object_mut() else {
        return 0;
    };
    let hooks = root
        .entry("hooks")
        .or_insert_with(|| json!({}))
        .as_object_mut();
    let Some(hooks) = hooks else {
        // `hooks` exists but is not an object; leave the file alone rather than
        // clobber a user's unexpected shape.
        return 0;
    };
    let mut added = 0;
    for spec in specs {
        let groups = hooks
            .entry(spec.event.to_string())
            .or_insert_with(|| json!([]));
        let Some(groups) = groups.as_array_mut() else {
            continue;
        };
        if groups.iter().any(|g| group_has_command(g, command)) {
            continue; // already installed for this event
        }
        groups.push(hook_group(command, spec));
        added += 1;
    }
    added
}

/// Removes every hook entry whose command `is_ours` matches from a settings
/// object, pruning any group and per-event array left empty, and returning how
/// many hook entries were removed. Leaves all other hooks in place.
fn remove_hooks(settings: &mut Value, is_ours: impl Fn(&str) -> bool) -> usize {
    let Some(root) = settings.as_object_mut() else {
        return 0;
    };
    let Some(hooks) = root.get_mut("hooks").and_then(Value::as_object_mut) else {
        return 0;
    };
    let mut removed = 0;
    let mut empty_events = Vec::new();
    for (event, groups) in hooks.iter_mut() {
        let Some(groups) = groups.as_array_mut() else {
            continue;
        };
        for group in groups.iter_mut() {
            if let Some(inner) = group.get_mut("hooks").and_then(Value::as_array_mut) {
                let before = inner.len();
                inner.retain(|h| {
                    !h.get("command")
                        .and_then(Value::as_str)
                        .is_some_and(&is_ours)
                });
                removed += before - inner.len();
            }
        }
        // Drop groups whose hook list is now empty, then the event if no groups
        // remain, so an uninstall leaves no empty scaffolding behind.
        groups.retain(|g| {
            g.get("hooks")
                .and_then(Value::as_array)
                .is_none_or(|h| !h.is_empty())
        });
        if groups.is_empty() {
            empty_events.push(event.clone());
        }
    }
    for event in empty_events {
        hooks.remove(&event);
    }
    removed
}

/// One hook group as written into an event array: `{ "hooks": [{ "type":
/// "command", "command": … }] }`, with a `"matcher": "*"` when the event matches
/// on tool name and a `timeout` where the spec caps one.
fn hook_group(command: &str, spec: &HookSpec) -> Value {
    let mut group = json!({ "hooks": [hook_entry(command, spec)] });
    if spec.matcher {
        group["matcher"] = Value::String("*".to_string());
    }
    group
}

/// One hook entry: `{ "type": "command", "command": … }`, plus a `timeout`
/// where the spec caps one.
fn hook_entry(command: &str, spec: &HookSpec) -> Value {
    let mut hook = json!({ "type": "command", "command": command });
    if let Some(secs) = spec.timeout {
        hook["timeout"] = json!(secs);
    }
    hook
}

/// Whether a hook `group` already contains a hook running `command`.
fn group_has_command(group: &Value, command: &str) -> bool {
    group
        .get("hooks")
        .and_then(Value::as_array)
        .is_some_and(|hooks| hooks.iter().any(|h| hook_has_command(h, command)))
}

/// Whether a single hook entry runs `command`.
fn hook_has_command(hook: &Value, command: &str) -> bool {
    hook.get("command").and_then(Value::as_str) == Some(command)
}

// --- Claude stale-sink handling (#1927) ---------------------------------------

/// What [`sync_claude_hooks`] changed in a Claude settings object.
#[derive(Debug, Default, PartialEq, Eq)]
struct ClaudeSync {
    /// Stale sink entries rewritten to the current command in place.
    replaced: usize,
    /// Duplicate entries of the current command removed.
    deduped: usize,
    /// Events that gained a group.
    added: usize,
    /// Customised sinks (extra arguments) left untouched.
    customised: usize,
}

impl ClaudeSync {
    /// Whether the settings object was left unchanged.
    fn is_noop(&self) -> bool {
        self.replaced == 0 && self.deduped == 0 && self.added == 0
    }
}

/// Whether `command` is a stale **un-customised** Claude sink: an `omni-dev
/// sessions hook` from any path whose arguments are empty or only the Claude tag
/// (`--agent claude`), the two shapes `install-hooks` has written for Claude.
/// Unlike Codex's [`is_sessions_sink`], a sink with any other argument (a
/// `--socket`, an `--agent codex`) is a deliberate choice and is **not** stale:
/// rewriting it to the canonical command would silently discard that choice.
fn is_stale_claude_sink(command: &str) -> bool {
    // A launcher with whitespace in it is a wrapper (`FOO=1 …`, `nice -n 10 …`,
    // `cd /x && …`), which is as customised as an extra argument.
    let Some((launcher, rest)) = split_sink(command) else {
        return false;
    };
    let args: Vec<&str> = rest.split_whitespace().collect();
    !launcher.contains(char::is_whitespace)
        && matches!(
            args.as_slice(),
            [] | ["--agent", "claude"] | ["--agent=claude"]
        )
}

/// Whether `command`, which is not `current`, is a sink install and uninstall
/// leave alone: an `omni-dev sessions hook` that is not [`is_stale_claude_sink`].
fn is_customised_sink(command: &str, current: &str) -> bool {
    command != current && is_sessions_sink(command) && !is_stale_claude_sink(command)
}

/// Counts the `omni-dev sessions hook` entries in `settings` that are neither
/// `current` nor stale-and-rewritable: the customised ones install and uninstall
/// leave alone.
fn count_customised_sinks(settings: &Value, current: &str) -> usize {
    settings
        .get("hooks")
        .and_then(Value::as_object)
        .into_iter()
        .flat_map(|hooks| hooks.values())
        .filter_map(Value::as_array)
        .flatten()
        .filter_map(|g| g.get("hooks").and_then(Value::as_array))
        .flatten()
        .filter_map(|h| h.get("command").and_then(Value::as_str))
        .filter(|c| is_customised_sink(c, current))
        .count()
}

/// The note printed when customised sinks were left in place.
fn customised_note(count: usize) -> String {
    format!(
        "left {count} customised `sessions hook` entry(ies) (extra arguments such as \
         `--socket`) untouched: edit or remove them by hand if they point at a moved binary"
    )
}

/// Removes the second and later occurrences of exactly `command` under each
/// event, pruning any group this empties, and returns how many it removed. The
/// first copy under each matcher is always kept, so an event never empties. Settings left by the pre-#1927 bug hold the old and new sink side by
/// side; once [`replace_stale_sinks`] rewrites the old one they would be two
/// identical entries, each spawning a sink per event. Claude identifies a hook by
/// content rather than position, so removing one shifts nothing that matters.
fn dedupe_command(settings: &mut Value, command: &str) -> usize {
    let Some(hooks) = settings.get_mut("hooks").and_then(Value::as_object_mut) else {
        return 0;
    };
    let mut removed = 0;
    for groups in hooks.values_mut() {
        let Some(groups) = groups.as_array_mut() else {
            continue;
        };
        // Keyed by matcher: a copy under `Bash` does not cover a copy under `*`.
        let mut seen: Vec<Option<String>> = Vec::new();
        let mut dropped_here = 0;
        for group in groups.iter_mut() {
            let matcher = group
                .get("matcher")
                .and_then(Value::as_str)
                .map(str::to_string);
            let Some(inner) = group.get_mut("hooks").and_then(Value::as_array_mut) else {
                continue;
            };
            let before = inner.len();
            inner.retain(|h| {
                if !hook_has_command(h, command) {
                    return true;
                }
                if seen.contains(&matcher) {
                    return false;
                }
                seen.push(matcher.clone());
                true
            });
            let dropped = before - inner.len();
            if dropped > 0 && inner.is_empty() {
                *group = Value::Null; // emptied by us: pruned below
            }
            dropped_here += dropped;
        }
        if dropped_here == 0 {
            continue; // never touch an event we removed nothing from
        }
        removed += dropped_here;
        groups.retain(|g| !g.is_null());
    }
    removed
}

/// The Claude half of `install-hooks` as a pure transform: rewrite stale
/// un-customised sinks to `command` in place, drop the duplicates that leaves (or
/// that an earlier buggy install left), then add whichever events lack a sink.
/// Customised sinks are counted but never touched.
fn sync_claude_hooks(settings: &mut Value, command: &str) -> ClaudeSync {
    let replaced = replace_stale_sinks(settings, command, HOOK_EVENTS, is_stale_claude_sink);
    let deduped = dedupe_command(settings, command);
    let added = merge_hooks(settings, command, HOOK_EVENTS);
    ClaudeSync {
        replaced,
        deduped,
        added,
        customised: count_customised_sinks(settings, command),
    }
}

// --- Codex hooks.json ----------------------------------------------------------

/// The one-time trust step every Codex install needs. Codex skips an untrusted
/// hook without any message, and trusts a hook by its position *and* content, so
/// a changed command string needs trusting again.
const CODEX_TRUST_STEP: &str =
    "Codex skips untrusted hooks silently: open the Codex CLI, run `/hooks`, \
and trust the omni-dev entries (once, and again after the command changes). \
One approval covers the VS Code extension and Codex Desktop.";

/// The Codex hook command: [`hook_command`] tagged `--agent codex`.
fn codex_hook_command() -> String {
    format!("{} --agent codex", hook_command())
}

/// Codex's home directory: `$CODEX_HOME`, else `~/.codex`.
fn default_codex_home() -> Result<PathBuf> {
    if let Some(dir) = std::env::var_os("CODEX_HOME").filter(|d| !d.is_empty()) {
        return Ok(PathBuf::from(dir));
    }
    let home = dirs::home_dir().context("could not resolve the home directory")?;
    Ok(home.join(".codex"))
}

/// Whether Codex is installed: its home directory exists (Codex has run), or a
/// `codex` executable is on `path`.
fn codex_is_present(codex_home: &Path, path: Option<&std::ffi::OsStr>) -> bool {
    codex_home.is_dir()
        || path.is_some_and(|path| {
            std::env::split_paths(path).any(|dir| is_executable(&dir.join("codex")))
        })
}

/// Whether `command` runs the `omni-dev sessions hook` sink, from any path to an
/// `omni-dev` binary and with any arguments. In Codex's `hooks.json` every such
/// entry other than the current [`codex_hook_command`] is stale: an untagged or
/// `--agent claude` one (a user who wired Codex by hand) reports Codex sessions
/// as Claude's, and a tagged one from another path is left by an upgrade that
/// moved the binary.
fn is_sessions_sink(command: &str) -> bool {
    split_sink(command).is_some()
}

/// Splits a sink `command` into the text before `sessions hook` (the launcher
/// path, plus anything a wrapper put in front of it) and the arguments after it,
/// or `None` when it is not an `omni-dev sessions hook` at all. The one place the
/// command is tokenised, so [`is_sessions_sink`] and [`is_stale_claude_sink`]
/// cannot disagree about what a sink is.
fn split_sink(command: &str) -> Option<(&str, &str)> {
    let command = command.trim();
    let at = command.find(" sessions hook")?;
    let rest = &command[at + " sessions hook".len()..];
    let launcher = command[..at].trim();
    ((rest.is_empty() || rest.starts_with(char::is_whitespace))
        && Path::new(launcher)
            .file_name()
            .is_some_and(|name| name == "omni-dev"))
    .then_some((launcher, rest))
}

/// Rewrites every stale sink entry (one `is_stale` matches, other than `command`
/// itself) in `settings` to `command` **where it sits**, returning how many it
/// rewrote. Codex passes [`is_sessions_sink`]; Claude the narrower
/// [`is_stale_claude_sink`]. (Claude identifies a hook by content, so in-place
/// matters there only for keeping a user's ordering; the trust argument below is
/// Codex's.) Left beside the
/// tagged entry, an untagged one would race it to be a session's first sighting
/// and could fix the session's tag as `claude` for good; replacing it in place
/// moves no other hook, so nothing else loses its Codex trust (ADR-0087). The
/// replaced entry takes the spec's `timeout` for its event. Extra arguments on
/// the old entry (a `--socket`, say) are not carried over: the canonical command
/// is what makes a second install recognise it.
fn replace_stale_sinks(
    settings: &mut Value,
    command: &str,
    specs: &[HookSpec],
    is_stale: impl Fn(&str) -> bool,
) -> usize {
    let Some(hooks) = settings.get_mut("hooks").and_then(Value::as_object_mut) else {
        return 0;
    };
    let mut replaced = 0;
    for (event, groups) in hooks.iter_mut() {
        let spec = specs.iter().find(|s| s.event == event);
        let Some(groups) = groups.as_array_mut() else {
            continue;
        };
        for hook in groups
            .iter_mut()
            .filter_map(|g| g.get_mut("hooks").and_then(Value::as_array_mut))
            .flatten()
        {
            let stale = hook
                .get("command")
                .and_then(Value::as_str)
                .is_some_and(|c| c != command && is_stale(c));
            if !stale {
                continue;
            }
            hook["command"] = Value::String(command.to_string());
            if let Some(secs) = spec.and_then(|s| s.timeout) {
                hook["timeout"] = json!(secs);
            }
            replaced += 1;
        }
    }
    replaced
}

/// What [`remove_hooks_stable`] did.
#[derive(Debug, Default, PartialEq, Eq)]
struct Removal {
    /// How many hook entries were removed.
    removed: usize,
    /// Whether a surviving hook moved to a lower index **within its group** — the
    /// one shift a group placeholder cannot prevent, since a hook list has no
    /// empty-entry form. That hook needs trusting again.
    shifted: bool,
}

/// Removes every hook entry `is_ours` matches, **without shifting any surviving
/// group** — the position-stable counterpart of [`remove_hooks`] for Codex, which
/// trusts a hook by its `<event>:<group>:<hook>` index. A group this empties keeps
/// its slot as an inert `{ "hooks": [] }` placeholder unless no group follows it,
/// so a later group never moves into its index and silently loses its trust;
/// trailing empty groups (and then an empty event) are dropped, since nothing
/// can shift into them.
fn remove_hooks_stable(settings: &mut Value, is_ours: impl Fn(&str) -> bool) -> Removal {
    let mut outcome = Removal::default();
    let Some(hooks) = settings.get_mut("hooks").and_then(Value::as_object_mut) else {
        return outcome;
    };
    let mut empty_events = Vec::new();
    for (event, groups) in hooks.iter_mut() {
        let Some(groups) = groups.as_array_mut() else {
            continue;
        };
        for group in groups.iter_mut() {
            let Some(inner) = group.get_mut("hooks").and_then(Value::as_array_mut) else {
                continue;
            };
            let mut removed_before = false;
            inner.retain(|h| {
                let ours = h
                    .get("command")
                    .and_then(Value::as_str)
                    .is_some_and(&is_ours);
                if ours {
                    removed_before = true;
                    outcome.removed += 1;
                } else if removed_before {
                    outcome.shifted = true;
                }
                !ours
            });
            if removed_before && inner.is_empty() {
                *group = json!({ "hooks": [] });
            }
        }
        while groups.last().is_some_and(is_empty_group) {
            groups.pop();
        }
        if groups.is_empty() {
            empty_events.push(event.clone());
        }
    }
    for event in empty_events {
        hooks.remove(&event);
    }
    outcome
}

/// Whether `group` is a group with an empty `hooks` list.
fn is_empty_group(group: &Value) -> bool {
    group
        .get("hooks")
        .and_then(Value::as_array)
        .is_some_and(Vec::is_empty)
}

/// The Codex half of `install-hooks`. Without `--codex-home` it installs only
/// when Codex is present, so a machine without Codex gets nothing under
/// `~/.codex`.
fn install_codex_hooks(explicit: Option<PathBuf>) -> Result<()> {
    let codex_home = if let Some(dir) = explicit {
        dir
    } else {
        let dir = default_codex_home()?;
        if !codex_is_present(&dir, std::env::var_os("PATH").as_deref()) {
            println!(
                "Codex not found (no {} and no `codex` on PATH); skipped its hooks",
                dir.display()
            );
            return Ok(());
        }
        dir
    };
    let path = codex_home.join("hooks.json");
    let mut hooks = read_settings(&path)?;
    let command = codex_hook_command();
    let replaced = replace_stale_sinks(&mut hooks, &command, CODEX_HOOK_EVENTS, is_sessions_sink);
    let added = merge_hooks(&mut hooks, &command, CODEX_HOOK_EVENTS);
    if replaced == 0 && added == 0 {
        println!(
            "Codex sessions hooks already installed in {} (no change)",
            path.display()
        );
        return Ok(());
    }
    write_settings(&path, &hooks)?;
    if replaced > 0 {
        println!(
            "rewrote {replaced} existing `sessions hook` entry(ies) in {} in place",
            path.display()
        );
    }
    if added > 0 {
        println!(
            "installed {added} Codex sessions hook event(s) into {}",
            path.display()
        );
    }
    println!("command: {command}\n{CODEX_TRUST_STEP}");
    Ok(())
}

/// The Codex half of `uninstall-hooks`. Runs whether or not Codex is present, so
/// an uninstalled Codex does not strand the entries. Removes every sink entry,
/// tagged or not and from any path (install would have rewritten it),
/// position-stably.
fn uninstall_codex_hooks(explicit: Option<PathBuf>) -> Result<()> {
    let codex_home = match explicit {
        Some(dir) => dir,
        None => default_codex_home()?,
    };
    let path = codex_home.join("hooks.json");
    if !path.exists() {
        return Ok(());
    }
    let mut hooks = read_settings(&path)?;
    // The exact current command too, in case this binary is not named `omni-dev`.
    let current = codex_hook_command();
    let Removal { removed, shifted } =
        remove_hooks_stable(&mut hooks, |c| c == current || is_sessions_sink(c));
    if removed == 0 {
        return Ok(());
    }
    write_settings(&path, &hooks)?;
    println!(
        "removed {removed} Codex sessions hook entry(ies) from {}",
        path.display()
    );
    if shifted {
        println!(
            "a hook that shared a group with ours moved up within it, so Codex no \
             longer trusts it: run `/hooks` in the Codex CLI to trust it again"
        );
    } else {
        println!("no other Codex hook moved, so their `/hooks` trust stands");
    }
    Ok(())
}

// --- shared socket + rendering ----------------------------------------------

/// Sends one `sessions` service op over the control socket, returning its
/// payload or turning an `ok: false` reply into an error.
async fn call(socket: &Path, op: &str, payload: Value) -> Result<Value> {
    let reply = DaemonClient::new(socket)
        .request(DaemonEnvelope::service(SERVICE, op, payload))
        .await?;
    reply_payload(reply)
}

/// Unwraps a daemon reply into its payload, turning an `ok: false` reply into an
/// error. Pure (no socket), so both mappings are unit-testable.
fn reply_payload(reply: DaemonReply) -> Result<Value> {
    if reply.ok {
        Ok(reply.payload)
    } else {
        bail!(
            "daemon returned an error: {}",
            reply.error.as_deref().unwrap_or("unknown error")
        )
    }
}

/// Renders a `list` reply as a human-readable table: a header and one row per
/// live session (state, source, repo, working directory, and age). Returns a
/// placeholder line when nothing is running.
fn render_sessions(result: &Value) -> String {
    let sessions = result
        .get("sessions")
        .and_then(Value::as_array)
        .map(Vec::as_slice)
        .unwrap_or_default();
    if sessions.is_empty() {
        return "No active agent sessions.".to_string();
    }
    // CWD is last so a long path never misaligns the columns after it.
    let mut out = format!(
        "{:<13} {:<6} {:<8} {:<20} {:>5}  {}",
        "STATE", "AGENT", "SOURCE", "REPO", "AGE", "CWD"
    );
    for session in sessions {
        let state = state_display(session.get("state").and_then(Value::as_str).unwrap_or("-"));
        let agent = agent_label(session);
        let source = source_label(session);
        let repo = sanitize(session.get("repo").and_then(Value::as_str).unwrap_or("-"));
        let cwd = sanitize(session.get("cwd").and_then(Value::as_str).unwrap_or("-"));
        let age = age_secs(session.get("last_seen").and_then(Value::as_str));
        out.push_str(&format!(
            "\n{state:<13} {agent:<6} {source:<8} {repo:<20} {age:>4}s  {cwd}"
        ));
    }
    out
}

/// A compact, fixed-width-friendly label for a session state, so the wide
/// `waiting_for_permission` does not overflow the STATE column. Falls through to
/// the raw (sanitized) string for any unexpected value.
fn state_display(state: &str) -> String {
    match state {
        "waiting_for_permission" => "waiting-perm".to_string(),
        "waiting_for_input" => "waiting-input".to_string(),
        other => sanitize(other),
    }
}

/// The agent label for a session: `pi` for pi.dev, `codex` for Codex, else
/// `claude` (a daemon that predates the `agent` field only ever reports Claude
/// Code sessions).
fn agent_label(session: &Value) -> &'static str {
    match session.get("agent").and_then(Value::as_str) {
        Some("pi") => "pi",
        Some("codex") => "codex",
        _ => "claude",
    }
}

/// The short source label for a session: `vscode` when embedded in a VS Code
/// window, else `terminal`.
fn source_label(session: &Value) -> &'static str {
    match session.pointer("/source/kind").and_then(Value::as_str) {
        Some("vs_code") => "vscode",
        _ => "terminal",
    }
}

/// Strips control characters from an untrusted registry string so a crafted
/// payload cannot inject terminal escape sequences into the rendered table
/// (#1137). The `--json` path stays verbatim.
fn sanitize(s: &str) -> String {
    sanitize_for_terminal(s)
}

/// Seconds elapsed since an RFC 3339 timestamp (0 if absent/unparseable).
fn age_secs(ts: Option<&str>) -> i64 {
    ts.and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
        .map_or(0, |t| {
            (Utc::now() - t.with_timezone(&Utc)).num_seconds().max(0)
        })
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    #[tokio::test]
    async fn hook_diagnostics_identify_gates_without_logging_payload_content() {
        let dir = tempfile::tempdir().unwrap();
        let command = HookCommand {
            socket: Some(dir.path().join("missing.sock")),
            agent: HookAgent::Claude,
        };
        let ((), logs) = crate::test_support::capture_future_at(tracing::Level::DEBUG, async {
            for input in ["not json HOOK_CONTENT_SECRET", "{}",
                r#"{"session_id":"test"}"#,
                r#"{"session_id":"test","hook_event_name":"future-event"}"#,
                r#"{"session_id":"test","hook_event_name":"Notification","message":"HOOK_CONTENT_SECRET"}"#] {
                command.report(input, None).await;
            }
        }).await;
        for reason in [
            "invalid_json",
            "missing_session_id",
            "missing_event",
            "unmapped_event",
            "transport_failed",
        ] {
            assert!(logs.contains(reason), "missing {reason}: {logs}");
        }
        assert!(logs.contains("session_notification_classified"));
        assert!(!logs.contains("HOOK_CONTENT_SECRET"));
    }

    const JOURNAL_ID: &str = "0b7e6c1a-2f4d-4a8e-9c3b-5d1e7f9a2b4c";

    fn journal_hook(event: &str) -> String {
        format!(
            r#"{{"session_id":"{JOURNAL_ID}","cwd":"/work/repo","hook_event_name":"{event}","prompt":"PROMPT_CONTENT_SECRET","tool_input":{{"command":"TOOL_CONTENT_SECRET"}}}}"#
        )
    }

    fn read_journal(dir: &Path, agent: &str) -> Vec<JournalRecord> {
        let path = dir
            .join("sessions")
            .join(agent)
            .join(format!("{JOURNAL_ID}.jsonl"));
        let text = std::fs::read_to_string(path).unwrap();
        assert!(!text.contains("CONTENT_SECRET"), "{text}");
        text.lines()
            .map(|line| JournalRecord::parse(line).unwrap())
            .collect()
    }

    #[tokio::test]
    async fn a_hook_is_journaled_even_when_the_daemon_is_unreachable() {
        let dir = tempfile::tempdir().unwrap();
        let command = HookCommand {
            socket: Some(dir.path().join("missing.sock")),
            agent: HookAgent::Claude,
        };
        command
            .report(&journal_hook("UserPromptSubmit"), Some(77))
            .await;
        command.report(&journal_hook("Stop"), Some(77)).await;
        command.report(&journal_hook("SessionEnd"), Some(77)).await;

        let records = read_journal(dir.path(), "claude");
        assert_eq!(records.len(), 3);
        assert!(records
            .iter()
            .all(|r| r.agent == Agent::Claude && r.pid() == Some(77)));
        assert!(matches!(
            &records[0].body,
            journal::JournalBody::Observe { event: SessionEvent::UserPromptSubmit, cwd: Some(cwd), .. }
                if cwd == Path::new("/work/repo")
        ));
        assert!(matches!(
            &records[1].body,
            journal::JournalBody::Observe {
                event: SessionEvent::Stop,
                ..
            }
        ));
        assert!(matches!(&records[2].body, journal::JournalBody::End { .. }));
        // Each event has its own stamp.
        let seqs: std::collections::HashSet<_> = records.iter().map(|r| r.seq.clone()).collect();
        assert_eq!(seqs.len(), 3);
    }

    #[tokio::test]
    async fn a_codex_hook_is_journaled_under_its_own_agent() {
        let dir = tempfile::tempdir().unwrap();
        let command = HookCommand {
            socket: Some(dir.path().join("missing.sock")),
            agent: HookAgent::Codex,
        };
        command
            .report(&journal_hook("PermissionRequest"), None)
            .await;
        let records = read_journal(dir.path(), "codex");
        assert_eq!(records.len(), 1);
        assert_eq!(records[0].agent, Agent::Codex);
        assert!(!dir.path().join("sessions/claude").exists());
    }

    #[tokio::test]
    async fn events_the_tracker_ignores_and_ids_no_journal_is_named_for_leave_no_journal() {
        let dir = tempfile::tempdir().unwrap();
        let command = HookCommand {
            socket: Some(dir.path().join("missing.sock")),
            agent: HookAgent::Claude,
        };
        command.report(&journal_hook("FutureEvent"), None).await;
        command
            .report(
                r#"{"session_id":"../../escape","hook_event_name":"Stop"}"#,
                None,
            )
            .await;
        assert!(!dir.path().join("sessions").exists());
        assert!(!dir.path().join("escape").exists());
    }

    #[tokio::test]
    async fn a_journal_write_failure_is_swallowed_and_never_logs_content() {
        let dir = tempfile::tempdir().unwrap();
        // The journal root is a file, so no journal can be made.
        std::fs::write(dir.path().join("sessions"), "").unwrap();
        let command = HookCommand {
            socket: Some(dir.path().join("missing.sock")),
            agent: HookAgent::Claude,
        };
        let ((), logs) = crate::test_support::capture_future_at(tracing::Level::DEBUG, async {
            command.report(&journal_hook("Stop"), None).await;
        })
        .await;
        assert!(logs.contains("journal_failed"), "{logs}");
        // It went on to report, which is what the fail-open sink is for.
        assert!(logs.contains("transport_failed"), "{logs}");
        assert!(!logs.contains("CONTENT_SECRET"), "{logs}");
    }

    #[test]
    fn the_wire_payload_carries_the_stamp_only_when_given_one() {
        let stamp = journal::new_stamp();
        let hook = |event: &str| serde_json::from_str::<HookPayload>(&journal_hook(event)).unwrap();
        for (event, op) in [("Stop", "observe"), ("SessionEnd", "end")] {
            let hook_op = hook(event).to_hook_op(HookAgent::Claude, Some(5)).unwrap();
            let (name, bare) = hook_op.wire(HookAgent::Claude, None).unwrap();
            assert_eq!(name, op);
            assert!(bare.get("stamp").is_none(), "{event}");
            let (_, stamped) = hook_op.wire(HookAgent::Claude, Some(&stamp)).unwrap();
            assert_eq!(stamped["stamp"]["seq"], stamp.seq.as_str());
            assert_eq!(
                serde_json::from_value::<EventStamp>(stamped["stamp"].clone()).unwrap(),
                stamp
            );
            // The stamp is the only difference from the unstamped payload.
            let mut without = stamped.clone();
            without.as_object_mut().unwrap().remove("stamp");
            assert_eq!(without, bare);
            // The journal record is made from the same value.
            let record = hook_op.record(&stamp);
            assert_eq!(record.stamp(), stamp);
            assert_eq!(record.session_id, JOURNAL_ID);
        }
    }

    use super::*;
    use crate::sessions::SessionState;

    /// Mirrors the `omni-dev sessions` argv surface for parse tests.
    #[derive(Parser)]
    struct Wrapper {
        #[command(subcommand)]
        cmd: SessionsSubcommands,
    }

    fn parse(args: &[&str]) -> SessionsSubcommands {
        let mut full = vec!["omni-dev"];
        full.extend_from_slice(args);
        Wrapper::try_parse_from(full).unwrap().cmd
    }

    #[test]
    fn subcommands_parse() {
        assert!(matches!(parse(&["list"]), SessionsSubcommands::List(_)));
        assert!(matches!(parse(&["hook"]), SessionsSubcommands::Hook(_)));
        assert!(matches!(
            parse(&["install-hooks"]),
            SessionsSubcommands::InstallHooks(_)
        ));
        assert!(matches!(
            parse(&["uninstall-hooks"]),
            SessionsSubcommands::UninstallHooks(_)
        ));
        assert!(matches!(
            parse(&["install-wrapper"]),
            SessionsSubcommands::InstallWrapper(_)
        ));
        assert!(matches!(
            parse(&["uninstall-wrapper"]),
            SessionsSubcommands::UninstallWrapper(_)
        ));
    }

    #[test]
    fn list_parses_flags() {
        let cmd =
            ListCommand::try_parse_from(["list", "-o", "json", "--socket", "/tmp/d.sock"]).unwrap();
        assert_eq!(cmd.output, TableOrJson::Json);
        assert_eq!(cmd.socket.as_deref(), Some(Path::new("/tmp/d.sock")));
    }

    // --- hook mapping --------------------------------------------------------

    fn hook_op(json_str: &str) -> Option<(&'static str, Value)> {
        serde_json::from_str::<HookPayload>(json_str)
            .unwrap()
            .to_op(HookAgent::Claude, None)
    }

    #[test]
    fn hook_maps_lifecycle_events_to_observe() {
        let (op, payload) = hook_op(
            r#"{"session_id":"s1","cwd":"/p","transcript_path":"/t.jsonl","hook_event_name":"PreToolUse"}"#,
        )
        .unwrap();
        assert_eq!(op, "observe");
        assert_eq!(payload["session_id"], "s1");
        assert_eq!(payload["cwd"], "/p");
        assert_eq!(payload["event"], "pre_tool_use");
    }

    #[test]
    fn hook_maps_session_start_and_stop() {
        assert_eq!(
            hook_op(r#"{"session_id":"s1","hook_event_name":"SessionStart"}"#)
                .unwrap()
                .1["event"],
            "session_start"
        );
        assert_eq!(
            hook_op(r#"{"session_id":"s1","hook_event_name":"Stop"}"#)
                .unwrap()
                .1["event"],
            "stop"
        );
    }

    #[test]
    fn hook_maps_session_end_to_end_op() {
        let (op, payload) =
            hook_op(r#"{"session_id":"s1","hook_event_name":"SessionEnd","message":"exit"}"#)
                .unwrap();
        assert_eq!(op, "end");
        assert_eq!(payload["session_id"], "s1");
        assert_eq!(payload["reason"], "exit");
    }

    #[test]
    fn hook_sends_the_agent_pid_on_both_ops_when_known() {
        let hook = |json_str: &str, pid| {
            serde_json::from_str::<HookPayload>(json_str)
                .unwrap()
                .to_op(HookAgent::Claude, pid)
                .unwrap()
        };
        let start = r#"{"session_id":"s1","hook_event_name":"SessionStart"}"#;
        let end = r#"{"session_id":"s1","hook_event_name":"SessionEnd"}"#;
        assert_eq!(hook(start, Some(42)).1["pid"], 42);
        assert_eq!(hook(end, Some(42)).1["pid"], 42);
        // Unknown: omitted from the wire, exactly as before #1948.
        assert!(hook(start, None).1.get("pid").is_none());
        assert!(hook(end, None).1.get("pid").is_none());
    }

    #[test]
    fn agent_pid_treats_an_orphaned_hook_as_unknown() {
        assert_eq!(agent_pid(4242), Some(4242));
        assert_eq!(agent_pid(1), None);
        assert_eq!(agent_pid(0), None);
    }

    #[test]
    fn hook_classifies_notifications() {
        let permission = hook_op(
            r#"{"session_id":"s1","hook_event_name":"Notification","message":"Claude needs your permission to use Bash"}"#,
        )
        .unwrap();
        assert_eq!(permission.1["event"]["notification"], "permission_prompt");

        let idle = hook_op(
            r#"{"session_id":"s1","hook_event_name":"Notification","message":"Claude is waiting for your input"}"#,
        )
        .unwrap();
        assert_eq!(idle.1["event"]["notification"], "idle_prompt");

        let other = hook_op(
            r#"{"session_id":"s1","hook_event_name":"Notification","message":"something else"}"#,
        )
        .unwrap();
        assert_eq!(other.1["event"]["notification"], "other");
    }

    #[test]
    fn hook_ignores_unknown_events_and_missing_session_id() {
        // No session_id → no op.
        assert!(hook_op(r#"{"hook_event_name":"Stop"}"#).is_none());
        // Blank session_id → no op.
        assert!(hook_op(r#"{"session_id":"  ","hook_event_name":"Stop"}"#).is_none());
        // Unknown event → no op.
        assert!(hook_op(r#"{"session_id":"s1","hook_event_name":"CwdChanged"}"#).is_none());
        // Garbage that still parses as an (empty) payload → no op.
        assert!(hook_op("{}").is_none());
    }

    fn codex_op(json_str: &str) -> Option<(&'static str, Value)> {
        serde_json::from_str::<HookPayload>(json_str)
            .unwrap()
            .to_op(HookAgent::Codex, None)
    }

    fn codex_event(event: &str, tool: Option<&str>) -> Value {
        let mut hook = json!({ "session_id": "c1", "hook_event_name": event });
        if let Some(tool) = tool {
            hook["tool_name"] = json!(tool);
        }
        codex_op(&hook.to_string()).unwrap().1["event"].clone()
    }

    #[test]
    fn codex_hooks_are_tagged_from_the_first_event() {
        let (op, payload) = codex_op(
            r#"{"session_id":"c1","cwd":"/p","model":"gpt-5.5","hook_event_name":"SessionStart","source":"startup"}"#,
        )
        .unwrap();
        assert_eq!(op, "observe");
        assert_eq!(payload["agent"], "codex");
        assert_eq!(payload["model"], "gpt-5.5");
        assert_eq!(payload["event"], "session_start");
        // The Claude sink stays untagged on the wire.
        let claude = hook_op(r#"{"session_id":"s1","hook_event_name":"Stop"}"#).unwrap();
        assert!(claude.1.get("agent").is_none());
    }

    #[test]
    fn codex_events_map_onto_the_existing_session_events() {
        assert_eq!(codex_event("UserPromptSubmit", None), "user_prompt_submit");
        assert_eq!(codex_event("PreToolUse", Some("Bash")), "pre_tool_use");
        assert_eq!(codex_event("PostToolUse", Some("Bash")), "post_tool_use");
        assert_eq!(codex_event("Stop", None), "stop");
        let compact =
            json!({ "session_id": "c1", "hook_event_name": "SessionStart", "source": "compact" });
        assert_eq!(
            codex_op(&compact.to_string()).unwrap().1["event"],
            "transcript_discovered",
            "a compaction start is not a new session (#1946)"
        );
        assert_eq!(
            codex_event("PermissionRequest", Some("Bash"))["notification"],
            "permission_prompt"
        );
        assert_eq!(
            codex_event("PreToolUse", Some("request_user_input"))["notification"],
            "agent_needs_input"
        );
        // Its resolution is an ordinary PostToolUse.
        assert_eq!(
            codex_event("PostToolUse", Some("request_user_input")),
            "post_tool_use"
        );
        assert_eq!(codex_event("Interrupt", None), "stop");
        assert_eq!(codex_event("SubagentStart", None), "post_tool_use");
        // Each of these can fire on an idle session, so none may turn it working.
        for preserving in ["SubagentStop", "PreCompact", "PostCompact"] {
            assert_eq!(
                codex_event(preserving, None),
                "transcript_discovered",
                "{preserving}"
            );
        }
        // Codex has no Notification event; an unknown one is ignored.
        assert!(codex_op(r#"{"session_id":"c1","hook_event_name":"Notification"}"#).is_none());
    }

    #[test]
    fn codex_session_end_is_the_end_op_with_its_reason() {
        let (op, payload) =
            codex_op(r#"{"session_id":"c1","hook_event_name":"SessionEnd","reason":"other"}"#)
                .unwrap();
        assert_eq!(op, "end");
        assert_eq!(payload["reason"], "other");
    }

    #[test]
    fn the_claude_sink_ignores_codex_only_events() {
        // Codex's `Interrupt` and its `request_user_input` tool have no Claude
        // equivalent, so the untagged sink keeps its own mapping for both.
        assert!(hook_op(r#"{"session_id":"s1","hook_event_name":"Interrupt"}"#).is_none());
        assert_eq!(
            hook_op(r#"{"session_id":"s1","hook_event_name":"PreToolUse","tool_name":"request_user_input"}"#)
                .unwrap()
                .1["event"],
            "pre_tool_use"
        );
    }

    fn claude_event(event: &str) -> Value {
        let hook = json!({ "session_id": "s1", "hook_event_name": event });
        hook_op(&hook.to_string()).unwrap().1["event"].clone()
    }

    #[test]
    fn claude_newer_events_map_onto_the_existing_session_events() {
        assert_eq!(
            claude_event("PermissionRequest")["notification"],
            "permission_prompt"
        );
        assert_eq!(
            claude_event("Elicitation")["notification"],
            "agent_needs_input"
        );
        for working in [
            "PostToolUseFailure",
            "PermissionDenied",
            "ElicitationResult",
            "SubagentStart",
        ] {
            assert_eq!(claude_event(working), "post_tool_use", "{working}");
        }
        assert_eq!(claude_event("StopFailure"), "stop");
        // Liveness-only sightings: each can fire while the session is idle (a
        // background subagent, a manual /compact) and must not turn it working.
        for preserving in ["SubagentStop", "PreCompact", "PostCompact"] {
            assert_eq!(
                claude_event(preserving),
                "transcript_discovered",
                "{preserving}"
            );
        }
    }

    #[test]
    fn every_installed_claude_event_is_mapped_by_the_sink() {
        // An installed event the sink ignores would spawn a process per event
        // for nothing.
        for HookSpec { event, .. } in HOOK_EVENTS {
            let hook = json!({ "session_id": "s1", "hook_event_name": event });
            assert!(hook_op(&hook.to_string()).is_some(), "{event} is unmapped");
        }
    }

    #[test]
    fn a_finished_subagent_or_compaction_leaves_an_idle_session_idle() {
        for preserving in ["SubagentStop", "PreCompact", "PostCompact"] {
            let hook = json!({ "session_id": "s1", "hook_event_name": preserving });
            let (_, payload) = hook_op(&hook.to_string()).unwrap();
            let event: SessionEvent = serde_json::from_value(payload["event"].clone()).unwrap();
            assert_eq!(
                SessionState::for_event(&event, Some(SessionState::Idle)),
                SessionState::Idle,
                "{preserving}"
            );
            assert_eq!(
                SessionState::for_event(&event, Some(SessionState::WaitingForPermission)),
                SessionState::WaitingForPermission,
                "{preserving}"
            );
        }
    }

    fn observe_claude_hook(reg: &crate::sessions::SessionsRegistry, event: &str, id: Option<&str>) {
        let hook = json!({"session_id": "s1", "hook_event_name": event, "agent_id": id});
        let (_, payload) = hook_op(&hook.to_string()).unwrap();
        reg.observe(serde_json::from_value(payload).unwrap());
    }

    #[test]
    fn background_subagent_tools_preserve_parent_state_and_refresh_liveness() {
        use crate::sessions::SessionsRegistry;
        for (parent, expected) in [
            ("Stop", SessionState::Idle),
            ("UserPromptSubmit", SessionState::Working),
        ] {
            let reg = SessionsRegistry::new();
            observe_claude_hook(&reg, parent, None);
            for event in [
                "PreToolUse",
                "PostToolUse",
                "PostToolUseFailure",
                "PermissionDenied",
                "SubagentStop",
            ] {
                let before = reg.list()[0].last_seen;
                observe_claude_hook(&reg, event, Some("child"));
                assert_eq!(reg.list()[0].state, expected, "{parent}: {event}");
                assert!(reg.list()[0].last_seen >= before);
            }
        }
    }

    #[test]
    fn subagent_completion_releases_only_its_own_wait_to_parent_state() {
        use crate::sessions::SessionsRegistry;
        for (parent, expected) in [
            ("Stop", SessionState::Idle),
            ("UserPromptSubmit", SessionState::Working),
        ] {
            for (wait, waiting, completions) in [
                (
                    "PermissionRequest",
                    SessionState::WaitingForPermission,
                    vec![
                        "PostToolUse",
                        "PostToolUseFailure",
                        "PermissionDenied",
                        "SubagentStop",
                    ],
                ),
                (
                    "Elicitation",
                    SessionState::WaitingForInput,
                    vec!["ElicitationResult", "SubagentStop"],
                ),
            ] {
                for completion in completions {
                    let reg = SessionsRegistry::new();
                    observe_claude_hook(&reg, parent, None);
                    observe_claude_hook(&reg, wait, Some("a"));
                    observe_claude_hook(&reg, "PostToolUse", Some("b"));
                    observe_claude_hook(&reg, "PreToolUse", Some("a"));
                    observe_claude_hook(&reg, "Notification", Some("a"));
                    assert_eq!(reg.list()[0].state, waiting);
                    observe_claude_hook(&reg, completion, Some("a"));
                    assert_eq!(
                        reg.list()[0].state,
                        expected,
                        "{parent}: {wait}/{completion}"
                    );
                }
            }
        }
    }

    #[test]
    fn overlapping_subagent_waits_resolve_independently() {
        let reg = crate::sessions::SessionsRegistry::new();
        observe_claude_hook(&reg, "Stop", None);
        observe_claude_hook(&reg, "PermissionRequest", Some("a"));
        observe_claude_hook(&reg, "Elicitation", Some("b"));
        assert_eq!(reg.list()[0].state, SessionState::WaitingForPermission);
        observe_claude_hook(&reg, "PostToolUse", Some("a"));
        assert_eq!(reg.list()[0].state, SessionState::WaitingForInput);
        observe_claude_hook(&reg, "ElicitationResult", Some("b"));
        assert_eq!(reg.list()[0].state, SessionState::Idle);
    }

    #[test]
    fn first_subagent_wait_and_parent_wait_release_remain_supported() {
        let reg = crate::sessions::SessionsRegistry::new();
        observe_claude_hook(&reg, "PermissionRequest", Some("a"));
        assert_eq!(reg.list()[0].state, SessionState::WaitingForPermission);
        observe_claude_hook(&reg, "PostToolUse", None);
        assert_eq!(reg.list()[0].state, SessionState::Working);
        observe_claude_hook(&reg, "Stop", None);
        observe_claude_hook(&reg, "PostToolUse", Some("a"));
        assert_eq!(reg.list()[0].state, SessionState::Idle);
        observe_claude_hook(&reg, "PermissionRequest", None);
        observe_claude_hook(&reg, "PostToolUse", Some("b"));
        assert_eq!(reg.list()[0].state, SessionState::WaitingForPermission);
    }

    #[test]
    fn subagent_notifications_survive_passive_evidence_and_end_ignores_late_tools() {
        let reg = crate::sessions::SessionsRegistry::new();
        observe_claude_hook(&reg, "Stop", None);
        let hook = json!({"session_id":"s1", "hook_event_name":"Notification", "agent_id":"a", "notification_type":"permission_prompt"});
        let (_, payload) = hook_op(&hook.to_string()).unwrap();
        reg.observe(serde_json::from_value(payload).unwrap());
        for event in [
            SessionEvent::TranscriptDiscovered,
            SessionEvent::TranscriptGrew,
        ] {
            let req: ObserveRequest =
                serde_json::from_value(json!({"session_id":"s1", "event":event})).unwrap();
            reg.observe(req);
            assert_eq!(reg.list()[0].state, SessionState::WaitingForPermission);
        }
        observe_claude_hook(&reg, "PostToolUse", Some("a"));
        assert_eq!(reg.list()[0].state, SessionState::Idle);
        reg.end("s1", None, None);
        let before = reg.list()[0].last_seen;
        observe_claude_hook(&reg, "PostToolUse", Some("a"));
        assert_eq!(reg.list()[0].state, SessionState::Ended);
        assert_eq!(reg.list()[0].last_seen, before);
    }

    #[test]
    fn subagent_identity_is_optional_and_claude_only() {
        for id in [None, Some(""), Some("  ")] {
            let hook = json!({"session_id":"s1", "hook_event_name":"PostToolUse", "agent_id":id});
            let payload = hook_op(&hook.to_string()).unwrap().1;
            assert!(payload.get("agent_id").is_none());
            let request: ObserveRequest = serde_json::from_value(payload).unwrap();
            assert!(request.agent_id.is_none());
        }
        let hook = json!({"session_id":"c1", "hook_event_name":"PostToolUse", "agent_id":"child"});
        assert!(codex_op(&hook.to_string())
            .unwrap()
            .1
            .get("agent_id")
            .is_none());
    }

    #[test]
    fn a_codex_subagent_stop_or_compaction_leaves_an_idle_session_idle() {
        for preserving in ["SubagentStop", "PreCompact", "PostCompact"] {
            let hook = json!({ "session_id": "c1", "hook_event_name": preserving });
            let (_, payload) = codex_op(&hook.to_string()).unwrap();
            let event: SessionEvent = serde_json::from_value(payload["event"].clone()).unwrap();
            assert_eq!(
                SessionState::for_event(&event, Some(SessionState::Idle)),
                SessionState::Idle,
                "{preserving}"
            );
            assert_eq!(
                SessionState::for_event(&event, Some(SessionState::WaitingForPermission)),
                SessionState::WaitingForPermission,
                "{preserving}"
            );
        }
    }

    #[test]
    fn a_compaction_session_start_preserves_state() {
        let event_for = |source: Option<&str>| {
            let mut hook = json!({ "session_id": "s1", "hook_event_name": "SessionStart" });
            if let Some(source) = source {
                hook["source"] = json!(source);
            }
            let (_, payload) = hook_op(&hook.to_string()).unwrap();
            serde_json::from_value::<SessionEvent>(payload["event"].clone()).unwrap()
        };
        // Claude fires it after a compaction, possibly mid-turn: a working
        // session must stay working, an idle one idle (#1946).
        let compact = event_for(Some("compact"));
        assert_eq!(compact, SessionEvent::TranscriptDiscovered);
        for current in [SessionState::Working, SessionState::Idle] {
            assert_eq!(SessionState::for_event(&compact, Some(current)), current);
        }
        for start in [Some("startup"), Some("resume"), Some("clear"), None] {
            assert_eq!(event_for(start), SessionEvent::SessionStart, "{start:?}");
        }
    }

    #[test]
    fn hook_classifies_notifications_by_type_before_message() {
        let typed = |ty: &str, msg: &str| {
            let hook = json!({
                "session_id": "s1",
                "hook_event_name": "Notification",
                "notification_type": ty,
                "message": msg,
            });
            hook_op(&hook.to_string()).unwrap().1["event"]["notification"].clone()
        };
        // The type wins over a message the substring match would misread.
        assert_eq!(
            typed("permission_prompt", "something else"),
            "permission_prompt"
        );
        assert_eq!(typed("idle_prompt", "Please approve"), "idle_prompt");
        assert_eq!(typed("elicitation_dialog", "x"), "agent_needs_input");
        // A type we do not map is `other`, never a guess at its message.
        assert_eq!(typed("auth_success", "You can now allow access"), "other");
        // With no type at all (an older version), the message is classified.
        let untyped = hook_op(
            r#"{"session_id":"s1","hook_event_name":"Notification","message":"Claude needs your permission"}"#,
        )
        .unwrap();
        assert_eq!(untyped.1["event"]["notification"], "permission_prompt");
    }

    #[test]
    fn hook_parses_the_agent_flag() {
        match parse(&["hook", "--agent", "codex"]) {
            SessionsSubcommands::Hook(cmd) => assert_eq!(cmd.agent, HookAgent::Codex),
            _ => panic!("expected hook"),
        }
        match parse(&["hook"]) {
            SessionsSubcommands::Hook(cmd) => assert_eq!(cmd.agent, HookAgent::Claude),
            _ => panic!("expected hook"),
        }
        match parse(&["install-hooks", "--codex-home", "/x/codex"]) {
            SessionsSubcommands::InstallHooks(cmd) => {
                assert_eq!(cmd.codex_home, Some(PathBuf::from("/x/codex")));
            }
            _ => panic!("expected install-hooks"),
        }
    }

    // --- Codex hooks.json ---------------------------------------------------

    const TAGGED: &str = "/bin/omni-dev sessions hook --agent codex";

    /// The `(group index, commands)` layout of one event, for position checks.
    fn layout(hooks: &Value, event: &str) -> Vec<Vec<String>> {
        hooks["hooks"][event]
            .as_array()
            .map(|groups| {
                groups
                    .iter()
                    .map(|g| {
                        g["hooks"]
                            .as_array()
                            .unwrap()
                            .iter()
                            .map(|h| h["command"].as_str().unwrap().to_string())
                            .collect()
                    })
                    .collect()
            })
            .unwrap_or_default()
    }

    #[test]
    fn is_sessions_sink_matches_any_omni_dev_sink_and_nothing_else() {
        assert!(is_sessions_sink(
            "/Users/me/.cargo/bin/omni-dev sessions hook"
        ));
        assert!(is_sessions_sink("omni-dev sessions hook"));
        assert!(is_sessions_sink(TAGGED));
        assert!(is_sessions_sink("omni-dev sessions hook --socket /x"));
        assert!(is_sessions_sink(
            "/old/omni-dev sessions hook --agent codex"
        ));
        assert!(!is_sessions_sink("/bin/other sessions hook"));
        assert!(!is_sessions_sink("omni-dev sessions list"));
        assert!(!is_sessions_sink("omni-dev sessions hooks"));
        assert!(!is_sessions_sink("my-omni-dev sessions hook"));
    }

    #[test]
    fn codex_install_rewrites_a_moved_binarys_tagged_entry_in_place() {
        let mut hooks = json!({ "hooks": { "Stop": [
            { "hooks": [{ "type": "command", "command": "/old/omni-dev sessions hook --agent codex" }] },
            { "hooks": [{ "type": "command", "command": "omni-dev sessions hook --socket /x" }] },
            { "hooks": [{ "type": "command", "command": "mine" }] }
        ] } });
        assert_eq!(
            replace_stale_sinks(&mut hooks, TAGGED, CODEX_HOOK_EVENTS, is_sessions_sink),
            2
        );
        assert_eq!(
            layout(&hooks, "Stop"),
            vec![vec![TAGGED], vec![TAGGED], vec!["mine"]]
        );
        // Already tagged by the current binary: nothing added under Stop.
        merge_hooks(&mut hooks, TAGGED, CODEX_HOOK_EVENTS);
        assert_eq!(layout(&hooks, "Stop").len(), 3);
    }

    #[test]
    fn codex_install_replaces_untagged_sinks_in_place_and_never_reorders() {
        let mut hooks = json!({ "hooks": {
            "PreToolUse": [
                { "matcher": "Bash", "hooks": [{ "type": "command", "command": "guard" }] },
                { "matcher": "*", "hooks": [{ "type": "command", "command": "/old/omni-dev sessions hook" }] },
                { "hooks": [{ "type": "command", "command": "audit" }] }
            ],
            "SessionEnd": [
                { "hooks": [{ "type": "command", "command": "omni-dev sessions hook" }] }
            ]
        }});
        let replaced = replace_stale_sinks(&mut hooks, TAGGED, CODEX_HOOK_EVENTS, is_sessions_sink);
        assert_eq!(replaced, 2);
        let added = merge_hooks(&mut hooks, TAGGED, CODEX_HOOK_EVENTS);
        // Only the events without a (now tagged) sink got a new group.
        assert_eq!(added, CODEX_HOOK_EVENTS.len() - 2);
        // The untagged sink became the tagged one where it sat; nothing moved.
        assert_eq!(
            layout(&hooks, "PreToolUse"),
            vec![vec!["guard"], vec![TAGGED], vec!["audit"]]
        );
        assert_eq!(hooks["hooks"]["PreToolUse"][1]["matcher"], "*");
        // The capped event picked up its timeout in place.
        assert_eq!(hooks["hooks"]["SessionEnd"][0]["hooks"][0]["timeout"], 3);
        // Appended groups carry the matcher and timeout their event needs.
        assert_eq!(hooks["hooks"]["PostToolUse"][0]["matcher"], "*");
        assert_eq!(hooks["hooks"]["Interrupt"][0]["hooks"][0]["timeout"], 3);
        assert!(hooks["hooks"]["Stop"][0]["hooks"][0]
            .get("timeout")
            .is_none());
        assert!(hooks["hooks"].get("Notification").is_none());
        // Idempotent.
        assert_eq!(
            replace_stale_sinks(&mut hooks, TAGGED, CODEX_HOOK_EVENTS, is_sessions_sink),
            0
        );
        assert_eq!(merge_hooks(&mut hooks, TAGGED, CODEX_HOOK_EVENTS), 0);
    }

    #[test]
    fn codex_uninstall_never_shifts_a_surviving_group() {
        let mut hooks = json!({ "hooks": {
            "Stop": [
                { "hooks": [{ "type": "command", "command": TAGGED }] },
                { "hooks": [{ "type": "command", "command": "user-a" }] },
                { "hooks": [{ "type": "command", "command": "omni-dev sessions hook" }] },
                { "hooks": [{ "type": "command", "command": "user-b" }] },
                { "hooks": [{ "type": "command", "command": TAGGED }] }
            ],
            "PreToolUse": [
                { "hooks": [
                    { "type": "command", "command": TAGGED },
                    { "type": "command", "command": "shared" }
                ] }
            ],
            "Interrupt": [
                { "hooks": [] },
                { "hooks": [{ "type": "command", "command": TAGGED }] }
            ],
            "PostToolUse": [
                { "hooks": [{ "type": "command", "command": "keep" }] }
            ]
        }});
        let removal = remove_hooks_stable(&mut hooks, is_sessions_sink);
        assert_eq!(removal.removed, 5);
        // `shared` moved from hook index 1 to 0 within its group.
        assert!(removal.shifted);
        // Emptied non-trailing groups stay as placeholders, so user-a and user-b
        // keep their indices (1 and 3); the trailing emptied group is dropped.
        let stop = hooks["hooks"]["Stop"].as_array().unwrap();
        assert_eq!(stop.len(), 4);
        assert_eq!(stop[0], json!({ "hooks": [] }));
        assert_eq!(layout(&hooks, "Stop")[1], vec!["user-a"]);
        assert_eq!(stop[2], json!({ "hooks": [] }));
        assert_eq!(layout(&hooks, "Stop")[3], vec!["user-b"]);
        // A group with other hooks keeps them.
        assert_eq!(layout(&hooks, "PreToolUse"), vec![vec!["shared"]]);
        // Trailing placeholders, then the empty event, are dropped.
        assert!(hooks["hooks"].get("Interrupt").is_none());
        assert_eq!(layout(&hooks, "PostToolUse"), vec![vec!["keep"]]);
        // A second pass removes nothing.
        assert_eq!(
            remove_hooks_stable(&mut hooks, is_sessions_sink),
            Removal::default()
        );
    }

    #[test]
    fn remove_hooks_stable_does_not_report_a_shift_for_a_trailing_hook() {
        let mut hooks = json!({ "hooks": { "Stop": [ { "hooks": [
            { "type": "command", "command": "shared" },
            { "type": "command", "command": TAGGED }
        ] } ] } });
        let removal = remove_hooks_stable(&mut hooks, is_sessions_sink);
        assert_eq!(
            removal,
            Removal {
                removed: 1,
                shifted: false
            }
        );
        assert_eq!(layout(&hooks, "Stop"), vec![vec!["shared"]]);
    }

    #[test]
    fn remove_hooks_stable_tolerates_malformed_shapes() {
        let none = Removal::default();
        assert_eq!(remove_hooks_stable(&mut json!([]), |_| true), none);
        assert_eq!(remove_hooks_stable(&mut json!({}), |_| true), none);
        let mut odd = json!({ "hooks": { "Stop": 5, "Start": [ { "matcher": "x" } ] } });
        assert_eq!(remove_hooks_stable(&mut odd, |_| true), none);
        assert_eq!(odd["hooks"]["Stop"], 5);
        assert_eq!(
            replace_stale_sinks(&mut json!({}), TAGGED, CODEX_HOOK_EVENTS, is_sessions_sink),
            0
        );
        assert_eq!(
            replace_stale_sinks(
                &mut json!({ "hooks": { "Stop": 5 } }),
                TAGGED,
                CODEX_HOOK_EVENTS,
                is_sessions_sink
            ),
            0
        );
    }

    #[test]
    fn codex_is_present_via_its_home_or_a_codex_executable_on_path() {
        use std::os::unix::fs::PermissionsExt;

        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().join("codex-home");
        let bin = tmp.path().join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        let path = std::env::join_paths([&bin]).unwrap();
        assert!(!codex_is_present(&home, Some(&path)));
        assert!(!codex_is_present(&home, None));
        let exe = bin.join("codex");
        std::fs::write(&exe, "#!/bin/sh\n").unwrap();
        std::fs::set_permissions(&exe, std::fs::Permissions::from_mode(0o755)).unwrap();
        assert!(codex_is_present(&home, Some(&path)));
        std::fs::create_dir_all(&home).unwrap();
        assert!(codex_is_present(&home, None));
    }

    #[test]
    fn codex_hook_command_is_the_sink_tagged_codex() {
        assert_eq!(
            codex_hook_command(),
            format!("{} --agent codex", hook_command())
        );
        assert!(codex_hook_command().ends_with(" sessions hook --agent codex"));
    }

    #[test]
    fn codex_install_and_uninstall_round_trip_through_the_file() {
        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().join("codex-home");
        std::fs::create_dir_all(&home).unwrap();
        let file = home.join("hooks.json");
        std::fs::write(
            &file,
            json!({ "hooks": { "Stop": [
                { "hooks": [{ "type": "command", "command": "omni-dev sessions hook" }] },
                { "hooks": [{ "type": "command", "command": "mine" }] }
            ] } })
            .to_string(),
        )
        .unwrap();
        install_codex_hooks(Some(home.clone())).unwrap();
        let tagged = codex_hook_command();
        let installed = read_settings(&file).unwrap();
        assert_eq!(
            layout(&installed, "Stop"),
            vec![vec![tagged.clone()], vec!["mine".to_string()]]
        );
        assert_eq!(layout(&installed, "Interrupt"), vec![vec![tagged]]);
        // A second install is the no-change branch and leaves the file as is.
        install_codex_hooks(Some(home.clone())).unwrap();
        assert_eq!(read_settings(&file).unwrap(), installed);

        uninstall_codex_hooks(Some(home.clone())).unwrap();
        let removed = read_settings(&file).unwrap();
        assert_eq!(
            removed,
            json!({ "hooks": { "Stop": [ { "hooks": [] }, { "hooks": [{ "type": "command", "command": "mine" }] } ] } })
        );
        // Nothing left to remove, and a missing home is a no-op.
        uninstall_codex_hooks(Some(home)).unwrap();
        uninstall_codex_hooks(Some(tmp.path().join("absent"))).unwrap();
    }

    #[test]
    fn install_codex_hooks_via_the_default_home_skips_absent_and_writes_present() {
        let _guard = PI_ENV_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let saved = ["CODEX_HOME", "PATH", "HOME"].map(|k| (k, std::env::var_os(k)));

        let tmp = tempfile::tempdir().unwrap();
        let home = tmp.path().join("codex-home");
        let empty_bin = tmp.path().join("bin");
        std::fs::create_dir_all(&empty_bin).unwrap();
        std::env::set_var("CODEX_HOME", &home);
        std::env::set_var("PATH", std::env::join_paths([&empty_bin]).unwrap());

        assert_eq!(default_codex_home().unwrap(), home);
        install_codex_hooks(None).unwrap();
        assert!(
            !home.exists(),
            "install must not create an absent Codex home"
        );
        uninstall_codex_hooks(None).unwrap();

        std::fs::create_dir_all(&home).unwrap();
        install_codex_hooks(None).unwrap();
        assert!(home.join("hooks.json").exists());
        uninstall_codex_hooks(None).unwrap();
        assert_eq!(
            read_settings(&home.join("hooks.json")).unwrap(),
            json!({ "hooks": {} })
        );

        // An empty CODEX_HOME falls back to `$HOME/.codex`.
        std::env::set_var("CODEX_HOME", "");
        std::env::set_var("HOME", "/home/tester");
        assert_eq!(
            default_codex_home().unwrap(),
            PathBuf::from("/home/tester/.codex")
        );

        for (k, v) in saved {
            match v {
                Some(val) => std::env::set_var(k, val),
                None => std::env::remove_var(k),
            }
        }
    }

    #[test]
    fn classify_notification_covers_cases() {
        assert_eq!(
            classify_notification(None, Some("Please approve this")),
            NotificationKind::PermissionPrompt
        );
        assert_eq!(
            classify_notification(None, Some("Claude is idle")),
            NotificationKind::IdlePrompt
        );
        assert_eq!(classify_notification(None, None), NotificationKind::Other);
        assert_eq!(
            classify_notification(Some("idle_prompt"), None),
            NotificationKind::IdlePrompt
        );
    }

    // --- install / uninstall hooks ------------------------------------------

    #[test]
    fn merge_hooks_is_idempotent_and_additive() {
        // A pre-existing unrelated hook must survive the merge.
        let mut settings = json!({
            "hooks": {
                "PreToolUse": [
                    { "matcher": "Bash", "hooks": [{ "type": "command", "command": "other-tool" }] }
                ]
            },
            "model": "sonnet"
        });
        let cmd = "/usr/bin/omni-dev sessions hook";
        let added = merge_hooks(&mut settings, cmd, HOOK_EVENTS);
        assert_eq!(added, HOOK_EVENTS.len());

        // Our command landed under every event, and the unrelated hook stands.
        for HookSpec { event, .. } in HOOK_EVENTS {
            let groups = settings["hooks"][event].as_array().unwrap();
            assert!(
                groups.iter().any(|g| group_has_command(g, cmd)),
                "missing under {event}"
            );
        }
        let pre = settings["hooks"]["PreToolUse"].as_array().unwrap();
        assert!(pre.iter().any(|g| group_has_command(g, "other-tool")));
        assert_eq!(settings["model"], "sonnet");

        // A second merge is a no-op.
        assert_eq!(merge_hooks(&mut settings, cmd, HOOK_EVENTS), 0);
    }

    #[test]
    fn reinstalling_over_the_original_seven_events_adds_only_the_new_ones() {
        // An install from before #1915 carries only the first seven events.
        let cmd = "/usr/bin/omni-dev sessions hook";
        let original = &HOOK_EVENTS[..7];
        assert_eq!(original.last().unwrap().event, "SessionEnd");
        let mut settings = json!({});
        merge_hooks(&mut settings, cmd, original);
        let before = settings.clone();

        let added = merge_hooks(&mut settings, cmd, HOOK_EVENTS);
        assert_eq!(added, HOOK_EVENTS.len() - 7);
        // The existing groups are untouched: one group each, as before.
        for HookSpec { event, .. } in original {
            assert_eq!(settings["hooks"][event], before["hooks"][event], "{event}");
        }
        // Tool events get the `*` matcher; the others none.
        assert_eq!(settings["hooks"]["PermissionRequest"][0]["matcher"], "*");
        assert!(settings["hooks"]["StopFailure"][0].get("matcher").is_none());

        // Uninstall removes every event, old and new.
        assert_eq!(remove_hooks(&mut settings, |c| c == cmd), HOOK_EVENTS.len());
        assert!(settings["hooks"].as_object().unwrap().is_empty());
    }

    #[test]
    fn merge_then_remove_round_trips_and_preserves_others() {
        let mut settings = json!({
            "hooks": {
                "PreToolUse": [
                    { "matcher": "Bash", "hooks": [{ "type": "command", "command": "keep-me" }] }
                ]
            }
        });
        let cmd = "/usr/bin/omni-dev sessions hook";
        merge_hooks(&mut settings, cmd, HOOK_EVENTS);
        let removed = remove_hooks(&mut settings, |c| c == cmd);
        assert_eq!(removed, HOOK_EVENTS.len());

        // Every one of our entries is gone...
        for HookSpec { event, .. } in HOOK_EVENTS {
            let empty = settings["hooks"]
                .get(event)
                .and_then(Value::as_array)
                .is_none_or(|g| g.iter().all(|g| !group_has_command(g, cmd)));
            assert!(empty, "our hook survived under {event}");
        }
        // ...but the unrelated PreToolUse hook remains.
        let pre = settings["hooks"]["PreToolUse"].as_array().unwrap();
        assert!(pre.iter().any(|g| group_has_command(g, "keep-me")));
    }

    // --- stale Claude sinks (#1927) -----------------------------------------

    const OLD: &str = "/old/bin/omni-dev sessions hook";
    const NEW: &str = "/new/bin/omni-dev sessions hook";

    fn sinks_under(settings: &Value, event: &str) -> Vec<String> {
        settings["hooks"][event]
            .as_array()
            .into_iter()
            .flatten()
            .filter_map(|g| g["hooks"].as_array())
            .flatten()
            .filter_map(|h| h["command"].as_str().map(str::to_string))
            .collect()
    }

    #[test]
    fn is_stale_claude_sink_matches_only_uncustomised_sinks() {
        assert!(is_stale_claude_sink(OLD));
        assert!(is_stale_claude_sink("omni-dev sessions hook"));
        assert!(is_stale_claude_sink(
            "/x/omni-dev sessions hook --agent claude"
        ));
        assert!(is_stale_claude_sink(
            "/x/omni-dev sessions hook --agent=claude"
        ));
        // Customised: a deliberate choice, never rewritten.
        assert!(!is_stale_claude_sink(
            "/x/omni-dev sessions hook --socket /s"
        ));
        assert!(!is_stale_claude_sink(
            "/x/omni-dev sessions hook --agent codex"
        ));
        assert!(!is_stale_claude_sink(
            "/x/omni-dev sessions hook --agent claude --socket /s"
        ));
        // Not a sink at all.
        assert!(!is_stale_claude_sink("/x/other sessions hook"));
        assert!(!is_stale_claude_sink("/x/omni-dev sessions list"));
    }

    #[test]
    fn install_after_the_binary_moves_rewrites_the_old_sink_in_place() {
        let mut settings = json!({ "model": "sonnet" });
        merge_hooks(&mut settings, OLD, HOOK_EVENTS);
        // An unrelated hook sharing an event must survive, in its slot.
        settings["hooks"]["Stop"].as_array_mut().unwrap().insert(
            0,
            json!({ "hooks": [{ "type": "command", "command": "other" }] }),
        );

        let sync = sync_claude_hooks(&mut settings, NEW);
        assert_eq!(
            sync,
            ClaudeSync {
                replaced: HOOK_EVENTS.len(),
                ..ClaudeSync::default()
            }
        );
        for HookSpec { event, .. } in HOOK_EVENTS {
            assert!(
                sinks_under(&settings, event).contains(&NEW.to_string()),
                "{event}"
            );
            assert!(
                !sinks_under(&settings, event).contains(&OLD.to_string()),
                "{event}"
            );
        }
        assert_eq!(sinks_under(&settings, "Stop"), ["other", NEW]);
        assert_eq!(settings["model"], "sonnet");

        // A second install is a no-op.
        assert!(sync_claude_hooks(&mut settings, NEW).is_noop());
    }

    #[test]
    fn install_heals_settings_that_already_hold_both_sinks() {
        // What the pre-#1927 bug left behind: old and new side by side.
        let mut settings = json!({});
        merge_hooks(&mut settings, OLD, HOOK_EVENTS);
        merge_hooks(&mut settings, NEW, HOOK_EVENTS);

        let sync = sync_claude_hooks(&mut settings, NEW);
        assert_eq!(sync.replaced, HOOK_EVENTS.len());
        assert_eq!(sync.deduped, HOOK_EVENTS.len());
        assert_eq!(sync.added, 0);
        for HookSpec { event, .. } in HOOK_EVENTS {
            assert_eq!(sinks_under(&settings, event), [NEW], "{event}");
        }
        assert!(sync_claude_hooks(&mut settings, NEW).is_noop());
    }

    #[test]
    fn install_adds_new_events_while_rewriting_an_old_seven_event_install() {
        let mut settings = json!({});
        merge_hooks(&mut settings, OLD, &HOOK_EVENTS[..7]);
        let sync = sync_claude_hooks(&mut settings, NEW);
        assert_eq!(sync.replaced, 7);
        assert_eq!(sync.added, HOOK_EVENTS.len() - 7);
        for HookSpec { event, .. } in HOOK_EVENTS {
            assert_eq!(sinks_under(&settings, event), [NEW], "{event}");
        }
    }

    #[test]
    fn install_and_uninstall_preserve_a_customised_sink() {
        let custom = "/old/bin/omni-dev sessions hook --socket /my/d.sock";
        let mut settings = json!({
            "hooks": { "Stop": [{ "hooks": [{ "type": "command", "command": custom }] }] }
        });
        let sync = sync_claude_hooks(&mut settings, NEW);
        assert_eq!(sync.replaced, 0);
        assert_eq!(sync.customised, 1);
        assert_eq!(sinks_under(&settings, "Stop"), [custom, NEW]);

        let removed = remove_hooks(&mut settings, |c| c == NEW || is_stale_claude_sink(c));
        assert_eq!(removed, HOOK_EVENTS.len());
        assert_eq!(sinks_under(&settings, "Stop"), [custom]);
        assert_eq!(count_customised_sinks(&settings, NEW), 1);
        assert!(customised_note(1).contains("customised"));
    }

    #[test]
    fn uninstall_from_a_new_path_removes_the_old_path_sink() {
        let mut settings = json!({});
        merge_hooks(&mut settings, OLD, HOOK_EVENTS);
        merge_hooks(&mut settings, NEW, HOOK_EVENTS);
        let removed = remove_hooks(&mut settings, |c| c == NEW || is_stale_claude_sink(c));
        assert_eq!(removed, 2 * HOOK_EVENTS.len());
        assert!(settings["hooks"].as_object().unwrap().is_empty());
    }

    #[test]
    fn is_stale_claude_sink_rejects_wrapped_launchers() {
        // Only a wrapper whose last word is a path to `omni-dev` is recognised as a
        // sink at all; the rest (`nice -n 10 omni-dev …`) never match, so are
        // never touched either.
        for wrapped in [
            "FOO=1 /x/omni-dev sessions hook",
            "sudo -u me /usr/bin/omni-dev sessions hook",
            "cd /repo && /x/omni-dev sessions hook",
        ] {
            assert!(is_sessions_sink(wrapped), "{wrapped}");
            assert!(!is_stale_claude_sink(wrapped), "{wrapped}");
            assert!(is_customised_sink(wrapped, NEW), "{wrapped}");
        }
        assert!(!is_sessions_sink("nice -n 10 omni-dev sessions hook"));
        assert!(!is_customised_sink(NEW, NEW));
        assert!(!is_customised_sink(OLD, NEW));
    }

    #[test]
    fn dedupe_command_keys_on_the_matcher_and_leaves_untouched_events_alone() {
        let mut settings = json!({
            "hooks": {
                "PreToolUse": [
                    { "matcher": "Bash", "hooks": [{ "type": "command", "command": NEW }] },
                    { "matcher": "*", "hooks": [{ "type": "command", "command": NEW }] },
                    { "matcher": "*", "hooks": [{ "type": "command", "command": NEW }] }
                ],
                "Stop": [],
                "Notification": [{ "hooks": [] }]
            }
        });
        // Only the second `*` copy is redundant: `Bash` does not cover `*`.
        assert_eq!(dedupe_command(&mut settings, NEW), 1);
        assert_eq!(sinks_under(&settings, "PreToolUse"), [NEW, NEW]);
        assert_eq!(settings["hooks"]["PreToolUse"][1]["matcher"], "*");
        // Pre-existing empty scaffolding in events it removed nothing from stays.
        assert_eq!(settings["hooks"]["Stop"], json!([]));
        assert_eq!(settings["hooks"]["Notification"], json!([{ "hooks": [] }]));
    }

    #[test]
    fn install_command_execute_rewrites_an_old_sink_and_a_rerun_changes_nothing() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("settings.json");
        let mut old = json!({});
        merge_hooks(&mut old, OLD, HOOK_EVENTS);
        merge_hooks(
            &mut old,
            "/x/omni-dev sessions hook --socket /s",
            &HOOK_EVENTS[..1],
        );
        write_settings(&path, &old).unwrap();
        let install = || {
            InstallHooksCommand {
                settings: Some(path.clone()),
                pi_agent_dir: Some(tmp.path().join("pi-agent")),
                codex_home: Some(tmp.path().join("codex-home")),
            }
            .execute()
            .unwrap();
        };

        install();
        let current = hook_command();
        let settings = read_settings(&path).unwrap();
        for HookSpec { event, .. } in HOOK_EVENTS {
            let sinks = sinks_under(&settings, event);
            assert!(sinks.contains(&current), "{event}: {sinks:?}");
            assert!(!sinks.contains(&OLD.to_string()), "{event}: {sinks:?}");
        }
        // The customised sink survives beside the canonical one.
        assert_eq!(count_customised_sinks(&settings, &current), 1);

        let after_first = std::fs::read_to_string(&path).unwrap();
        install();
        assert_eq!(std::fs::read_to_string(&path).unwrap(), after_first);

        // Uninstalling from "a new path" also clears anything old left behind.
        let mut stale = read_settings(&path).unwrap();
        merge_hooks(&mut stale, OLD, HOOK_EVENTS);
        write_settings(&path, &stale).unwrap();
        UninstallHooksCommand {
            settings: Some(path.clone()),
            pi_agent_dir: Some(tmp.path().join("pi-agent")),
            codex_home: Some(tmp.path().join("codex-home")),
        }
        .execute()
        .unwrap();
        let settings = read_settings(&path).unwrap();
        assert_eq!(
            sinks_under(&settings, HOOK_EVENTS[0].event),
            ["/x/omni-dev sessions hook --socket /s"]
        );
        assert_eq!(count_customised_sinks(&settings, &current), 1);
    }

    #[test]
    fn install_command_execute_reports_and_removes_a_duplicate_sink() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("settings.json");
        // What the pre-#1927 bug left behind: the old and current sinks side by side.
        let mut both = json!({});
        merge_hooks(&mut both, OLD, HOOK_EVENTS);
        merge_hooks(&mut both, &hook_command(), HOOK_EVENTS);
        write_settings(&path, &both).unwrap();

        InstallHooksCommand {
            settings: Some(path.clone()),
            pi_agent_dir: Some(tmp.path().join("pi-agent")),
            codex_home: Some(tmp.path().join("codex-home")),
        }
        .execute()
        .unwrap();

        let settings = read_settings(&path).unwrap();
        for HookSpec { event, .. } in HOOK_EVENTS {
            assert_eq!(sinks_under(&settings, event), [hook_command()], "{event}");
        }
    }

    #[test]
    fn dedupe_command_keeps_the_first_and_tolerates_odd_shapes() {
        let mut settings = json!({
            "hooks": {
                "Stop": [
                    { "hooks": [{ "type": "command", "command": NEW }] },
                    { "matcher": "Bash" },
                    { "hooks": [{ "type": "command", "command": "other" },
                                { "type": "command", "command": NEW }] }
                ],
                "Notification": 5
            }
        });
        assert_eq!(dedupe_command(&mut settings, NEW), 1);
        assert_eq!(sinks_under(&settings, "Stop"), [NEW, "other"]);
        // A group with no `hooks` array is left as it was.
        assert_eq!(settings["hooks"]["Stop"][1], json!({ "matcher": "Bash" }));
        assert_eq!(settings["hooks"]["Notification"], 5);
        assert_eq!(dedupe_command(&mut json!({}), NEW), 0);
    }

    #[test]
    fn remove_hooks_prunes_empty_events_entirely() {
        let mut settings = json!({});
        let cmd = "cmd sessions hook";
        merge_hooks(&mut settings, cmd, HOOK_EVENTS);
        remove_hooks(&mut settings, |c| c == cmd);
        // With no other hooks, every event array empties and is pruned.
        let hooks = settings["hooks"].as_object().unwrap();
        assert!(hooks.is_empty(), "expected all events pruned: {hooks:?}");
    }

    #[test]
    fn install_uninstall_via_files_round_trips() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("settings.json");
        // Install into a missing file, then uninstall.
        let mut settings = read_settings(&path).unwrap();
        merge_hooks(&mut settings, "cmd sessions hook", HOOK_EVENTS);
        write_settings(&path, &settings).unwrap();
        assert!(path.exists());

        let reloaded = read_settings(&path).unwrap();
        assert!(reloaded["hooks"]["Stop"].is_array());

        let mut settings = read_settings(&path).unwrap();
        remove_hooks(&mut settings, |c| c == "cmd sessions hook");
        write_settings(&path, &settings).unwrap();
        let reloaded = read_settings(&path).unwrap();
        assert!(reloaded["hooks"].as_object().unwrap().is_empty());
    }

    #[test]
    fn read_settings_rejects_non_json() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("settings.json");
        std::fs::write(&path, "not json {").unwrap();
        let err = read_settings(&path).unwrap_err();
        assert!(err.to_string().contains("not valid JSON"), "{err}");
    }

    #[test]
    fn read_settings_handles_empty_and_non_object() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("settings.json");
        // An empty (or whitespace-only) file reads as an empty object.
        std::fs::write(&path, "   \n").unwrap();
        assert_eq!(read_settings(&path).unwrap(), json!({}));
        // Valid JSON that is not an object is refused rather than clobbered.
        std::fs::write(&path, "[1, 2, 3]").unwrap();
        let err = read_settings(&path).unwrap_err();
        assert!(err.to_string().contains("not a JSON object"), "{err}");
    }

    #[test]
    fn hook_command_targets_sessions_hook() {
        assert!(hook_command().ends_with("sessions hook"));
    }

    // --- rendering -----------------------------------------------------------

    #[test]
    fn render_sessions_handles_empty() {
        assert_eq!(
            render_sessions(&json!({ "sessions": [] })),
            "No active agent sessions."
        );
        assert_eq!(render_sessions(&json!({})), "No active agent sessions.");
    }

    #[test]
    fn render_sessions_renders_rows_and_source() {
        let result = json!({ "sessions": [{
            "session_id": "s1",
            "state": "working",
            "source": { "kind": "vs_code", "window_key": "w1" },
            "repo": "omni-dev",
            "cwd": "/home/me/omni-dev",
            "last_seen": "2000-01-01T00:00:00Z",
        }]});
        let table = render_sessions(&result);
        assert!(table.contains("working"), "{table}");
        assert!(table.contains("vscode"), "{table}");
        assert!(table.contains("omni-dev"), "{table}");
        assert!(table.contains("claude"), "{table}");
        // Header plus one data row.
        assert_eq!(table.lines().count(), 2, "{table}");
    }

    #[test]
    fn render_sessions_strips_control_bytes() {
        let result = json!({ "sessions": [{
            "session_id": "s1",
            "state": "wor\x1b[31mking",
            "source": { "kind": "terminal" },
            "repo": "ev\x07il",
            "cwd": "/tmp/a\rb",
            "last_seen": "2000-01-01T00:00:00Z",
        }]});
        let table = render_sessions(&result);
        assert!(
            !table.contains(|c: char| c.is_control() && c != '\n'),
            "{table:?}"
        );
        // Embedded CR cannot forge a row: header plus one data row.
        assert_eq!(table.lines().count(), 2, "{table:?}");
    }

    #[test]
    fn source_label_maps_kinds() {
        assert_eq!(
            source_label(&json!({ "source": { "kind": "vs_code", "window_key": "w" } })),
            "vscode"
        );
        assert_eq!(
            source_label(&json!({ "source": { "kind": "terminal" } })),
            "terminal"
        );
        assert_eq!(source_label(&json!({})), "terminal");
    }

    #[test]
    fn reply_payload_unwraps_ok_and_maps_errors() {
        assert_eq!(
            reply_payload(DaemonReply::ok(json!({ "a": 1 }))).unwrap(),
            json!({ "a": 1 })
        );
        let err = reply_payload(DaemonReply::err("boom")).unwrap_err();
        assert!(err.to_string().contains("boom"), "{err}");
    }

    // --- pi.dev extension ----------------------------------------------------

    #[test]
    fn render_pi_extension_bakes_in_the_socket_as_a_json_string() {
        let rendered = render_pi_extension(Path::new("/tmp/we \"ird\"/daemon.sock"));
        assert!(
            !rendered.contains(PI_SOCKET_PLACEHOLDER),
            "placeholder left behind"
        );
        assert!(
            rendered.contains(r#"const SOCKET: string = "/tmp/we \"ird\"/daemon.sock";"#),
            "socket not escaped as a JSON string"
        );
        assert!(rendered.starts_with(pi_extension_marker()));
    }

    #[test]
    fn the_template_reports_only_state_and_tags_the_agent() {
        // Each state the mapping can produce, the agent tag, and the `end` op.
        for needle in [
            r#""working""#,
            r#""idle""#,
            r#""waiting_for_input""#,
            r#"agent: "pi""#,
            "stream_state: next",
            r#"send("end""#,
            r#""agent_settled""#,
            r#""ui_prompt_start""#,
            r#""session_shutdown""#,
        ] {
            assert!(
                PI_EXTENSION_TEMPLATE.contains(needle),
                "template lacks {needle}"
            );
        }
        // pi has no permission prompt, so the template must never claim one.
        assert!(!PI_EXTENSION_TEMPLATE.contains("waiting_for_permission"));
        // pi's chat input is already live at `session_start`, so the template
        // must report `idle` there, never the hook-only `starting` state, which
        // means "launched, chat surface not up yet" (reporting it once left every
        // pi session showing as busy from launch until the first prompt, #1905).
        assert!(!PI_EXTENSION_TEMPLATE.contains("\"starting\""));
        assert_eq!(
            PI_EXTENSION_TEMPLATE.matches(PI_SOCKET_PLACEHOLDER).count(),
            1
        );
    }

    #[test]
    fn pi_is_present_via_its_agent_dir_or_a_pi_executable_on_path() {
        use std::os::unix::fs::PermissionsExt;

        let tmp = tempfile::tempdir().unwrap();
        let agent = tmp.path().join("agent");
        let bin = tmp.path().join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        let path = std::env::join_paths([bin.clone()]).unwrap();

        // Neither: absent.
        assert!(!pi_is_present(&agent, Some(&path)));
        assert!(!pi_is_present(&agent, None));

        // A non-executable `pi` does not count.
        let pi = bin.join("pi");
        std::fs::write(&pi, "#!/bin/sh\n").unwrap();
        std::fs::set_permissions(&pi, std::fs::Permissions::from_mode(0o600)).unwrap();
        assert!(!pi_is_present(&agent, Some(&path)));

        // An executable one does.
        std::fs::set_permissions(&pi, std::fs::Permissions::from_mode(0o755)).unwrap();
        assert!(pi_is_present(&agent, Some(&path)));

        // So does the agent directory alone.
        std::fs::create_dir_all(&agent).unwrap();
        assert!(pi_is_present(&agent, None));
    }

    #[test]
    fn write_pi_extension_is_idempotent_and_updates_its_own_file() {
        let tmp = tempfile::tempdir().unwrap();
        let v1 = render_pi_extension(Path::new("/a.sock"));
        let (file, outcome) = write_pi_extension(tmp.path(), &v1).unwrap();
        assert_eq!(outcome, PiInstall::Written);
        assert_eq!(file, tmp.path().join("extensions").join(PI_EXTENSION_NAME));
        assert_eq!(std::fs::read_to_string(&file).unwrap(), v1);

        assert_eq!(
            write_pi_extension(tmp.path(), &v1).unwrap().1,
            PiInstall::Unchanged
        );

        // A new socket path (or a newer template) replaces our own file.
        let v2 = render_pi_extension(Path::new("/b.sock"));
        assert_eq!(
            write_pi_extension(tmp.path(), &v2).unwrap().1,
            PiInstall::Written
        );
        assert_eq!(std::fs::read_to_string(&file).unwrap(), v2);
    }

    #[test]
    fn pi_extension_install_and_remove_leave_foreign_files_alone() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("extensions");
        std::fs::create_dir_all(&dir).unwrap();
        let other = dir.join("someone-elses.ts");
        std::fs::write(&other, "export default () => {};\n").unwrap();

        // A same-named file that is not ours is neither overwritten nor removed.
        let ours = dir.join(PI_EXTENSION_NAME);
        std::fs::write(&ours, "// hand-written\n").unwrap();
        let err = write_pi_extension(tmp.path(), &render_pi_extension(Path::new("/s")))
            .unwrap_err()
            .to_string();
        assert!(err.contains("not written by omni-dev"), "{err}");
        assert_eq!(remove_pi_extension(tmp.path()).unwrap(), None);
        assert_eq!(std::fs::read_to_string(&ours).unwrap(), "// hand-written\n");

        // Ours is removed; the neighbour survives.
        std::fs::remove_file(&ours).unwrap();
        write_pi_extension(tmp.path(), &render_pi_extension(Path::new("/s"))).unwrap();
        assert_eq!(remove_pi_extension(tmp.path()).unwrap(), Some(ours.clone()));
        assert!(!ours.exists());
        assert!(other.exists());

        // Removing again, or from a directory that never existed, is a no-op.
        assert_eq!(remove_pi_extension(tmp.path()).unwrap(), None);
        assert_eq!(remove_pi_extension(&tmp.path().join("nope")).unwrap(), None);
    }

    #[test]
    fn hook_commands_parse_the_pi_agent_dir_flag() {
        match parse(&["install-hooks", "--pi-agent-dir", "/x/agent"]) {
            SessionsSubcommands::InstallHooks(cmd) => {
                assert_eq!(cmd.pi_agent_dir, Some(PathBuf::from("/x/agent")));
            }
            _ => panic!("expected install-hooks"), // omni-dev: coverage ignore-line reason="the arm above always matches: parse() above always parses an install-hooks argv into SessionsSubcommands::InstallHooks"
        }
        match parse(&["uninstall-hooks"]) {
            SessionsSubcommands::UninstallHooks(cmd) => assert_eq!(cmd.pi_agent_dir, None),
            _ => panic!("expected uninstall-hooks"), // omni-dev: coverage ignore-line reason="the arm above always matches: parse() above always parses an uninstall-hooks argv into SessionsSubcommands::UninstallHooks"
        }
    }

    /// Env-isolation lock for tests that mutate `PI_CODING_AGENT_DIR`, `PATH`,
    /// or `HOME` to exercise [`default_pi_agent_dir`]'s and
    /// [`install_pi_extension`]'s env-driven branches. Aliases the crate-wide
    /// [`crate::test_support::HOME_ENV_MUTEX`] per its own doc comment
    /// (issue #1465), rather than a module-local `Mutex<()>`.
    static PI_ENV_LOCK: &std::sync::Mutex<()> = &crate::test_support::HOME_ENV_MUTEX;

    fn snapshot_pi_env() -> [(&'static str, Option<std::ffi::OsString>); 3] {
        ["PI_CODING_AGENT_DIR", "PATH", "HOME"].map(|k| (k, std::env::var_os(k)))
    }

    fn restore_pi_env(snap: [(&'static str, Option<std::ffi::OsString>); 3]) {
        for (k, v) in snap {
            match v {
                Some(val) => std::env::set_var(k, val),
                None => std::env::remove_var(k),
            }
        }
    }

    #[test]
    fn default_pi_agent_dir_honors_the_env_var_and_falls_back_to_home() {
        let _guard = PI_ENV_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let snap = snapshot_pi_env();

        // An explicit, non-empty env var wins.
        std::env::set_var("PI_CODING_AGENT_DIR", "/explicit/agent");
        assert_eq!(
            default_pi_agent_dir().unwrap(),
            PathBuf::from("/explicit/agent")
        );

        // An empty env var is treated as unset, falling back to `$HOME/.pi/agent`.
        std::env::set_var("PI_CODING_AGENT_DIR", "");
        std::env::set_var("HOME", "/home/tester");
        assert_eq!(
            default_pi_agent_dir().unwrap(),
            PathBuf::from("/home/tester/.pi/agent")
        );

        // A wholly unset env var falls back the same way.
        std::env::remove_var("PI_CODING_AGENT_DIR");
        assert_eq!(
            default_pi_agent_dir().unwrap(),
            PathBuf::from("/home/tester/.pi/agent")
        );

        restore_pi_env(snap);
    }

    #[test]
    fn install_pi_extension_via_the_default_dir_skips_absent_and_writes_present() {
        let _guard = PI_ENV_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let snap = snapshot_pi_env();

        let tmp = tempfile::tempdir().unwrap();
        let agent_dir = tmp.path().join("nonexistent-agent");
        let empty_bin = tmp.path().join("bin");
        std::fs::create_dir_all(&empty_bin).unwrap();

        std::env::set_var("PI_CODING_AGENT_DIR", &agent_dir);
        std::env::set_var("PATH", std::env::join_paths([&empty_bin]).unwrap());

        // Neither the agent dir exists nor is `pi` on PATH: install skips,
        // via default_pi_agent_dir()'s env-var branch.
        install_pi_extension(None).unwrap();
        assert!(
            !agent_dir.exists(),
            "install must not create the agent dir when pi is absent"
        );

        // Uninstall with no explicit dir also resolves via default_pi_agent_dir()
        // and is a no-op since nothing was ever installed there.
        uninstall_pi_extension(None).unwrap();

        // Once the agent dir exists, pi counts as present: install falls
        // through to actually write the extension, still via the env-resolved
        // default dir (no explicit `--pi-agent-dir`).
        std::fs::create_dir_all(&agent_dir).unwrap();
        install_pi_extension(None).unwrap();
        let extension = agent_dir.join("extensions").join(PI_EXTENSION_NAME);
        assert!(extension.exists());

        // Uninstall with no explicit dir removes what install just wrote.
        uninstall_pi_extension(None).unwrap();
        assert!(!extension.exists());

        restore_pi_env(snap);
    }

    #[test]
    fn agent_label_defaults_to_claude() {
        assert_eq!(agent_label(&json!({ "agent": "pi" })), "pi");
        assert_eq!(agent_label(&json!({ "agent": "codex" })), "codex");
        assert_eq!(agent_label(&json!({ "agent": "claude" })), "claude");
        assert_eq!(agent_label(&json!({})), "claude");
    }

    // --- command execute() paths -------------------------------------------

    #[test]
    fn install_then_uninstall_command_execute_round_trips() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("settings.json");
        // Install into a missing file: the hook block lands.
        InstallHooksCommand {
            settings: Some(path.clone()),
            pi_agent_dir: Some(tmp.path().join("pi-agent")),
            codex_home: Some(tmp.path().join("codex-home")),
        }
        .execute()
        .unwrap();
        assert!(read_settings(&path).unwrap()["hooks"]["Stop"].is_array());
        let extension = tmp
            .path()
            .join("pi-agent/extensions")
            .join(PI_EXTENSION_NAME);
        assert!(extension.exists());
        // A second install is the idempotent "no change" branch.
        InstallHooksCommand {
            settings: Some(path.clone()),
            pi_agent_dir: Some(tmp.path().join("pi-agent")),
            codex_home: Some(tmp.path().join("codex-home")),
        }
        .execute()
        .unwrap();
        // Uninstall removes our block, leaving an empty hooks object.
        UninstallHooksCommand {
            settings: Some(path.clone()),
            pi_agent_dir: Some(tmp.path().join("pi-agent")),
            codex_home: Some(tmp.path().join("codex-home")),
        }
        .execute()
        .unwrap();
        assert!(read_settings(&path).unwrap()["hooks"]
            .as_object()
            .unwrap()
            .is_empty());
        assert!(!extension.exists());
    }

    // --- install-wrapper / uninstall-wrapper --------------------------------

    /// An install/uninstall pair pointed entirely inside `tmp`, so nothing
    /// touches the developer's real data or config directories.
    fn wrapper_commands(tmp: &Path) -> (InstallWrapperCommand, UninstallWrapperCommand) {
        let settings = tmp.join("settings.json");
        let shim = tmp.join("bin").join("claude-wrap");
        (
            InstallWrapperCommand {
                settings: Some(settings.clone()),
                shim: Some(shim.clone()),
            },
            UninstallWrapperCommand {
                settings: Some(settings),
                shim: Some(shim),
            },
        )
    }

    #[test]
    fn install_wrapper_writes_an_executable_shim_and_sets_the_setting() {
        use std::os::unix::fs::PermissionsExt;

        let tmp = tempfile::tempdir().unwrap();
        let (install, _) = wrapper_commands(tmp.path());
        let shim = install.shim.clone().unwrap();
        let settings = install.settings.clone().unwrap();
        install.execute().unwrap();

        // The shim is a one-line exec into `claude-wrap`, owner-executable, and
        // names an absolute binary so it does not depend on VS Code's PATH.
        let script = std::fs::read_to_string(&shim).unwrap();
        assert!(script.starts_with("#!/bin/sh\nexec \"/"), "{script}");
        assert!(script.contains(" claude-wrap -- \"$@\""), "{script}");
        let mode = std::fs::metadata(&shim).unwrap().permissions().mode();
        assert_eq!(mode & 0o777, 0o700);

        assert_eq!(
            read_settings(&settings).unwrap()[WRAPPER_SETTING_KEY],
            json!(shim.display().to_string())
        );
    }

    #[test]
    fn install_wrapper_is_idempotent_and_preserves_other_settings() {
        let tmp = tempfile::tempdir().unwrap();
        let (install, _) = wrapper_commands(tmp.path());
        let settings_path = install.settings.clone().unwrap();
        write_settings(&settings_path, &json!({ "editor.fontSize": 13 })).unwrap();

        install.execute().unwrap();
        let (again, _) = wrapper_commands(tmp.path());
        again.execute().unwrap();

        let settings = read_settings(&settings_path).unwrap();
        assert_eq!(settings["editor.fontSize"], json!(13));
        assert!(settings[WRAPPER_SETTING_KEY].is_string());
    }

    #[test]
    fn uninstall_wrapper_clears_only_our_own_setting() {
        let tmp = tempfile::tempdir().unwrap();
        let (install, uninstall) = wrapper_commands(tmp.path());
        let settings_path = install.settings.clone().unwrap();
        let shim = install.shim.clone().unwrap();
        install.execute().unwrap();
        uninstall.execute().unwrap();

        assert!(read_settings(&settings_path).unwrap()[WRAPPER_SETTING_KEY].is_null());
        assert!(!shim.exists());

        // A setting someone else owns survives, and so does their file.
        write_settings(
            &settings_path,
            &json!({ WRAPPER_SETTING_KEY: "/opt/someone-elses-wrapper" }),
        )
        .unwrap();
        let (_, uninstall) = wrapper_commands(tmp.path());
        uninstall.execute().unwrap();
        assert_eq!(
            read_settings(&settings_path).unwrap()[WRAPPER_SETTING_KEY],
            json!("/opt/someone-elses-wrapper")
        );
    }

    #[test]
    fn uninstall_wrapper_on_a_missing_settings_file_is_a_noop() {
        let tmp = tempfile::tempdir().unwrap();
        let (_, uninstall) = wrapper_commands(tmp.path());
        let settings = uninstall.settings.clone().unwrap();
        uninstall.execute().unwrap();
        assert!(!settings.exists());
    }

    #[test]
    fn install_wrapper_on_a_jsonc_settings_file_explains_the_manual_step() {
        let tmp = tempfile::tempdir().unwrap();
        let (install, _) = wrapper_commands(tmp.path());
        let settings = install.settings.clone().unwrap();
        let shim = install.shim.clone().unwrap();
        // Comments are legal in VS Code settings and cannot be rewritten safely.
        std::fs::write(
            &settings,
            "{\n  // a comment\n  \"editor.fontSize\": 13\n}\n",
        )
        .unwrap();

        let error = format!("{:#}", install.execute().unwrap_err());
        assert!(error.contains("not valid JSON"), "{error}");
        assert!(error.contains(WRAPPER_SETTING_KEY), "{error}");
        // The shim is written first, so the printed line is ready to paste.
        assert!(error.contains(&shim.display().to_string()), "{error}");
        assert!(shim.exists());
    }

    #[test]
    fn install_wrapper_fails_when_the_shim_directory_cannot_be_made() {
        let tmp = tempfile::tempdir().unwrap();
        // A regular file where the shim's parent directory would have to go, so
        // creating it cannot succeed — a mistyped `--shim` in practice.
        let blocker = tmp.path().join("not-a-dir");
        std::fs::write(&blocker, b"").unwrap();
        let error = InstallWrapperCommand {
            settings: Some(tmp.path().join("settings.json")),
            shim: Some(blocker.join("claude-wrap")),
        }
        .execute()
        .unwrap_err();
        assert!(format!("{error:#}").contains("not-a-dir"), "{error:#}");
        // The settings file is left untouched when the shim cannot be written.
        assert!(!tmp.path().join("settings.json").exists());
    }

    #[test]
    fn set_and_clear_wrapper_tolerate_a_non_object_settings_value() {
        // `read_settings` guarantees an object, but these degrade rather than
        // panic if a caller hands them anything else (the `merge_hooks` rule).
        let mut scalar = json!("not an object");
        assert!(!set_wrapper(&mut scalar, "/shim"));
        assert!(!clear_wrapper(&mut scalar, "/shim"));
        assert_eq!(scalar, json!("not an object"));
    }

    #[test]
    fn the_wrapper_paths_default_outside_the_claude_config_dir() {
        // The shim lives beside the daemon socket; the setting lives in VS Code's
        // *config* directory, which is a different base on every platform.
        let shim = shim_path(None).unwrap();
        assert_eq!(shim.file_name().unwrap(), SHIM_NAME);
        assert_eq!(shim.parent().unwrap(), paths::runtime_dir().unwrap());
        let settings = vscode_settings_path(None).unwrap();
        assert!(
            settings.ends_with("Code/User/settings.json"),
            "{settings:?}"
        );
    }

    #[test]
    fn uninstall_command_on_a_missing_file_is_a_noop() {
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("does-not-exist.json");
        // The no-file branch: nothing to remove, still Ok, and no file created.
        UninstallHooksCommand {
            settings: Some(path.clone()),
            pi_agent_dir: Some(tmp.path().join("pi-agent")),
            codex_home: Some(tmp.path().join("codex-home")),
        }
        .execute()
        .unwrap();
        assert!(!path.exists());
    }

    #[tokio::test]
    async fn sessions_command_dispatches_to_subcommands() {
        // Cover the outer dispatch for the two file-backed arms (no socket/stdin).
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("settings.json");
        SessionsCommand {
            command: SessionsSubcommands::InstallHooks(InstallHooksCommand {
                settings: Some(path.clone()),
                pi_agent_dir: Some(tmp.path().join("pi-agent")),
                codex_home: Some(tmp.path().join("codex-home")),
            }),
        }
        .execute()
        .await
        .unwrap();
        SessionsCommand {
            command: SessionsSubcommands::UninstallHooks(UninstallHooksCommand {
                settings: Some(path.clone()),
                pi_agent_dir: Some(tmp.path().join("pi-agent")),
                codex_home: Some(tmp.path().join("codex-home")),
            }),
        }
        .execute()
        .await
        .unwrap();
        let (install, uninstall) = wrapper_commands(tmp.path());
        SessionsCommand {
            command: SessionsSubcommands::InstallWrapper(install),
        }
        .execute()
        .await
        .unwrap();
        SessionsCommand {
            command: SessionsSubcommands::UninstallWrapper(uninstall),
        }
        .execute()
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn hook_report_is_silent_when_the_daemon_is_down() {
        // A valid hook event but no daemon at the socket: the send fails and is
        // swallowed (never panics, never errors).
        let tmp = tempfile::tempdir_in("/tmp").unwrap();
        let sock = tmp.path().join("nope.sock");
        let cmd = HookCommand {
            socket: Some(sock),
            agent: HookAgent::Claude,
        };
        cmd.report(r#"{"session_id":"s1","hook_event_name":"Stop"}"#, None)
            .await;
        // Unmappable input returns before any socket work.
        cmd.report("not json", None).await;
        cmd.report(r#"{"hook_event_name":"Stop"}"#, None).await; // no session_id → no op
    }

    #[test]
    fn hook_input_that_cannot_be_read_is_skipped_with_a_debug_line() {
        /// A reader whose every read fails, like a stdin closed under the sink.
        struct Broken;
        impl Read for Broken {
            fn read(&mut self, _: &mut [u8]) -> std::io::Result<usize> {
                Err(std::io::Error::other("stdin went away"))
            }
        }
        let cmd = HookCommand {
            socket: None,
            agent: HookAgent::Claude,
        };
        let logs = crate::test_support::capture_at(tracing::Level::DEBUG, || {
            // Bytes that are not UTF-8 fail `read_to_string`, as does an I/O error.
            assert_eq!(cmd.read_input(&b"\xff\xfe"[..]), None);
            assert_eq!(cmd.read_input(Broken), None);
        });
        assert_eq!(logs.matches("stdin_read_failed").count(), 2, "{logs}");
        assert_eq!(
            cmd.read_input(&b"{\"session_id\":\"s1\"}"[..]).as_deref(),
            Some("{\"session_id\":\"s1\"}")
        );
    }

    #[tokio::test]
    async fn hook_report_logs_a_daemon_rejection_without_its_content() {
        let (_dir, sock, server) = fake_daemon(json!({"ok": false, "error": "HOOK_REPLY_SECRET"}));
        let cmd = HookCommand {
            socket: Some(sock),
            agent: HookAgent::Claude,
        };
        let ((), logs) = crate::test_support::capture_future_at(
            tracing::Level::DEBUG,
            cmd.report(r#"{"session_id":"s1","hook_event_name":"Stop"}"#, None),
        )
        .await;
        server.await.unwrap();
        assert!(logs.contains("daemon_rejected"), "{logs}");
        assert!(!logs.contains("HOOK_REPLY_SECRET"), "{logs}");
    }

    #[tokio::test(start_paused = true)]
    async fn hook_report_gives_up_on_a_wedged_daemon() {
        let dir = tempfile::tempdir_in("/tmp").unwrap();
        let sock = dir.path().join("d.sock");
        // Bound but never accepted: the connect lands in the backlog and the
        // request in the socket buffer, so only the hook timeout can end the
        // exchange. With the clock paused, that two-second wait costs no wall time.
        let _wedged = tokio::net::UnixListener::bind(&sock).unwrap();
        let cmd = HookCommand {
            socket: Some(sock),
            agent: HookAgent::Claude,
        };
        let ((), logs) = crate::test_support::capture_future_at(
            tracing::Level::DEBUG,
            cmd.report(r#"{"session_id":"s1","hook_event_name":"Stop"}"#, None),
        )
        .await;
        assert!(logs.contains("timeout"), "{logs}");
    }

    #[tokio::test]
    async fn hook_report_logs_a_delivered_event() {
        let (_dir, sock, server) = fake_daemon(json!({"ok": true, "payload": {}}));
        let cmd = HookCommand {
            socket: Some(sock),
            agent: HookAgent::Claude,
        };
        let ((), logs) = crate::test_support::capture_future_at(
            tracing::Level::DEBUG,
            cmd.report(r#"{"session_id":"s1","hook_event_name":"Stop"}"#, None),
        )
        .await;
        server.await.unwrap();
        assert!(logs.contains("delivered"), "{logs}");
    }

    /// Spawns a minimal fake daemon on a short-path Unix socket that answers one
    /// request with `reply`. Returns the temp dir (kept alive), the socket path,
    /// and the server task.
    fn fake_daemon(reply: Value) -> (tempfile::TempDir, PathBuf, tokio::task::JoinHandle<()>) {
        use futures::{SinkExt, StreamExt};
        use tokio::net::UnixListener;
        use tokio_util::codec::{Framed, LinesCodec};

        let dir = tempfile::tempdir_in("/tmp").unwrap();
        let sock = dir.path().join("d.sock");
        let listener = UnixListener::bind(&sock).unwrap();
        let server = tokio::spawn(async move {
            let (stream, _) = listener.accept().await.unwrap();
            let mut framed = Framed::new(stream, LinesCodec::new());
            let _req = framed.next().await.unwrap().unwrap();
            framed
                .send(serde_json::to_string(&reply).unwrap())
                .await
                .unwrap();
        });
        (dir, sock, server)
    }

    /// Like [`fake_daemon`] but **returns the request envelope it received** so a
    /// test can assert the exact op/payload wire shape the client sent.
    fn fake_daemon_capture(
        reply: Value,
    ) -> (tempfile::TempDir, PathBuf, tokio::task::JoinHandle<Value>) {
        use futures::{SinkExt, StreamExt};
        use tokio::net::UnixListener;
        use tokio_util::codec::{Framed, LinesCodec};

        let dir = tempfile::tempdir_in("/tmp").unwrap();
        let sock = dir.path().join("d.sock");
        let listener = UnixListener::bind(&sock).unwrap();
        let server = tokio::spawn(async move {
            let (stream, _) = listener.accept().await.unwrap();
            let mut framed = Framed::new(stream, LinesCodec::new());
            let req = framed.next().await.unwrap().unwrap();
            framed
                .send(serde_json::to_string(&reply).unwrap())
                .await
                .unwrap();
            serde_json::from_str::<Value>(&req).unwrap()
        });
        (dir, sock, server)
    }

    #[tokio::test]
    async fn list_command_execute_renders_from_a_socket() {
        let payload = json!({
            "ok": true,
            "payload": { "sessions": [{
                "session_id": "s1", "state": "working",
                "source": { "kind": "terminal" }, "repo": "omni-dev",
                "cwd": "/home/me/omni-dev", "last_seen": "2000-01-01T00:00:00Z"
            }]}
        });
        // Table output, dispatched through the outer `SessionsCommand` so the
        // `List` arm of the dispatch is covered too.
        let (_dir, sock, server) = fake_daemon(payload.clone());
        SessionsCommand {
            command: SessionsSubcommands::List(ListCommand {
                socket: Some(sock),
                output: TableOrJson::Table,
            }),
        }
        .execute()
        .await
        .unwrap();
        server.await.unwrap();

        // JSON output goes through the other branch of the renderer.
        let (_dir, sock, server) = fake_daemon(payload);
        ListCommand {
            socket: Some(sock),
            output: TableOrJson::Json,
        }
        .execute()
        .await
        .unwrap();
        server.await.unwrap();
    }

    #[test]
    fn merge_and_remove_hooks_tolerate_malformed_shapes() {
        let cmd = "cmd sessions hook";
        // Non-object settings: both are no-ops rather than panics.
        assert_eq!(merge_hooks(&mut json!([]), cmd, HOOK_EVENTS), 0);
        assert_eq!(remove_hooks(&mut json!([]), |c| c == cmd), 0);
        // `hooks` present but not an object → merge leaves it alone.
        assert_eq!(merge_hooks(&mut json!({ "hooks": 5 }), cmd, HOOK_EVENTS), 0);
        // No `hooks` key → remove has nothing to do.
        assert_eq!(remove_hooks(&mut json!({}), |c| c == cmd), 0);
        // A per-event value that is not an array is skipped, not indexed.
        assert_eq!(
            merge_hooks(&mut json!({ "hooks": { "Stop": 5 } }), cmd, HOOK_EVENTS),
            HOOK_EVENTS.len() - 1
        );
        assert_eq!(
            remove_hooks(&mut json!({ "hooks": { "Stop": 5 } }), |c| c == cmd),
            0
        );
    }

    // --- #1361 typed window feed commands -----------------------------------

    #[test]
    fn window_subcommands_route_and_require_key() {
        assert!(matches!(
            parse(&["window", "--key", "w1"]),
            SessionsSubcommands::Window(_)
        ));
        assert!(matches!(
            parse(&["window-unregister", "--key", "w1"]),
            SessionsSubcommands::WindowUnregister(_)
        ));
        // `--key` is required for both.
        assert!(WindowCommand::try_parse_from(["window"]).is_err());
        assert!(WindowUnregisterCommand::try_parse_from(["window-unregister"]).is_err());
    }

    #[test]
    fn window_parses_counts_and_folders() {
        let cmd = WindowCommand::try_parse_from([
            "window",
            "--key",
            "w1",
            "--folder",
            "/a",
            "--folder",
            "/b",
            "--tabs",
            "2",
            "--terminals",
            "3",
        ])
        .unwrap();
        assert_eq!(cmd.key, "w1");
        assert_eq!(cmd.folders, vec![PathBuf::from("/a"), PathBuf::from("/b")]);
        assert_eq!(cmd.tabs, 2);
        assert_eq!(cmd.terminals, 3);
        // Counts default to zero.
        let cmd = WindowCommand::try_parse_from(["window", "--key", "w1"]).unwrap();
        assert_eq!(cmd.tabs, 0);
        assert_eq!(cmd.terminals, 0);
    }

    #[tokio::test]
    async fn window_and_window_unregister_send_their_ops() {
        let (_dir, sock, server) =
            fake_daemon_capture(json!({ "ok": true, "payload": { "ok": true } }));
        // Routed through the outer `SessionsCommand::execute` so the `Window`
        // dispatch arm is covered too.
        SessionsCommand {
            command: SessionsSubcommands::Window(WindowCommand {
                key: "w1".to_string(),
                folders: vec![PathBuf::from("/a")],
                tabs: 1,
                terminals: 0,
                socket: Some(sock),
            }),
        }
        .execute()
        .await
        .unwrap();
        // The WindowReport wire shape: op + every field the daemon reads.
        let req = server.await.unwrap();
        assert_eq!(req["op"], "window");
        assert_eq!(req["payload"]["key"], json!("w1"));
        assert_eq!(req["payload"]["folders"], json!(["/a"]));
        assert_eq!(req["payload"]["tabs"], json!(1));
        assert_eq!(req["payload"]["terminals"], json!(0));

        // `window-unregister` replies `{removed}` (not `{ok}`); the client reads it.
        // Also routed through the wrapper to cover the `WindowUnregister` arm.
        let (_dir, sock, server) =
            fake_daemon_capture(json!({ "ok": true, "payload": { "removed": true } }));
        SessionsCommand {
            command: SessionsSubcommands::WindowUnregister(WindowUnregisterCommand {
                key: "w1".to_string(),
                socket: Some(sock),
            }),
        }
        .execute()
        .await
        .unwrap();
        let req = server.await.unwrap();
        assert_eq!(req["op"], "window-unregister");
        assert_eq!(req["payload"]["key"], json!("w1"));
    }
}