ljos 0.32.1

Memory, a work tracker and a shell-command gate for coding agents (Claude Code, Codex, Grok Build, agy, opencode) over MCP and hooks.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
//! The seat keeps the book when the model never calls ljos.
//!
//! A harness hook files a claim on the first edit in a session and
//! repository, cites a deed when a git commit has landed, and finishes at
//! Stop or the end of the session. The finish writes one lesson from the
//! sitting. `ljos-mcp` does the same on the first write and on shutdown,
//! for a client that has no hooks. A failure is written to the runtime
//! log and never becomes a deny: the agent's tool call goes on.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};

use serde_json::Value;

/// How long one habitat command may run from a hook. A runner that waits
/// on PreToolUse treats a slow hook as a refusal, so the book stays inside
/// this and a warm call does not spawn anything.
const COMMAND_DEADLINE: Duration = Duration::from_secs(2);

/// Unix seconds of the last MCP tool call. Zero means the server has not
/// been touched, and the idle watcher does not finish a session it has
/// not seen.
static LAST_ACTIVITY: AtomicU64 = AtomicU64::new(0);

/// Events that keep the book. A subagent stop and a bare argv line do not:
/// the parent session is the one that claimed.
const BOOK_EVENTS: &[&str] = &[
    "SessionStart",
    "UserPromptSubmit",
    "PreToolUse",
    "PostToolUse",
    "PostToolUseFailure",
    "Stop",
    "SessionEnd",
];

/// File tools. The first one in a session files the claim. Names are matched
/// without regard to case, so `edit` and `Edit` are the same tool. agy 1.4.3
/// writes a new file with `write_file` (arguments `Path`, `Content`,
/// `Overwrite`) and changes one with `edit_file`.
const EDIT_TOOLS: &[&str] = &[
    "Edit",
    "Write",
    "MultiEdit",
    "apply_patch",
    "StrReplace",
    "ApplyPatch",
    "write_to_file",
    "write_file",
    "replace_file_content",
    "edit_file",
    "NotebookEdit",
];

/// MCP tools that write a habitat. The claim, the sitting and the finish
/// are the bookkeeping verbs themselves, and `ljos_file` opens its own issue.
/// Before one of these runs the server joins the issue this seat holds
/// ([`before_mcp_write`]); it never files one. Mail (`ljos_send`,
/// `ljos_reply`) and `ljos_note` are not on the list.
const MCP_WRITES: &[&str] = &[
    "ljos_remember",
    "ljos_prefer",
    "ljos_forget",
    "ljos_deed",
    "ljos_rule",
    "ljos_vote",
    "ljos_learn",
    "ljos_trust",
    "ljos_persona",
    "ljos_playbook",
    "ljos_graded",
    "ljos_consolidate",
    "ljos_calibrate",
    "ljos_habit",
];

/// One sitting's book: the prompt the title came from, and one row per
/// repository the sitting has touched. An MCP server spawned per call
/// keeps this under the seat, so the next process sees the open claim.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
struct Book {
    #[serde(default)]
    prompt: String,
    #[serde(default)]
    repos: BTreeMap<String, RepoBook>,
    /// Unix seconds of the last call for this sitting. Zero means the
    /// sitting has not been touched, and an idle check does not finish it.
    /// This is not a row's age: a commit in one repository refreshes it
    /// while another repository's row stays idle.
    #[serde(default)]
    last_unix: u64,
    /// Repository `prompt` was recorded for. A git-hook claim uses the
    /// prompt as its title only when the commit is in this checkout and
    /// the sitting is still open.
    #[serde(default)]
    prompt_repo: String,
    /// Unix seconds when `prompt` was recorded. Zero means it was not stamped.
    #[serde(default)]
    prompt_unix: u64,
    /// Pid of the runner that last wrote this book. A later session finishes
    /// the claim when that pid is gone, which is how a timeout (the runner
    /// exits 124 before Stop) still closes.
    #[serde(default)]
    owner_pid: u32,
    /// `cwd` as the hook named it, to the repository key. The warm path is
    /// a lookup, not another `git rev-parse`.
    #[serde(default)]
    cwd_repo: BTreeMap<String, String>,
    /// The last repository a git hook booked for this seat. An MCP claim
    /// with no `repo` argument files there instead of under the server's cwd.
    #[serde(default)]
    last_repo: String,
}

/// What this session has already recorded for one repository.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
struct RepoBook {
    #[serde(default)]
    issue: Option<String>,
    /// `ljos_start` claimed this row's issue. A hook in another sitting
    /// takes over only such a row: a row another hook filed is that
    /// session's own work.
    #[serde(default)]
    started: bool,
    /// A hook filed this row's issue for the sitting's first edit or
    /// commit: no one asked for that ticket by name. A commit naming another
    /// open issue before any deed lands here takes the row over, and this
    /// issue is cancelled.
    #[serde(default)]
    filed: bool,
    /// Commit shas already cited. The id is `deed-file-commit-<sha>`, so a
    /// second commit is a second deed, and the same sha is not cited twice.
    #[serde(default)]
    deeds: Vec<String>,
    /// Cited shas found in HEAD by a sweep. A sweep asks git once for a
    /// sha, not on every prompt.
    #[serde(default)]
    landed: Vec<String>,
    /// The HEAD those shas were found in.
    #[serde(default)]
    landed_head: Option<String>,
    /// Short notes from tool failures, for the lesson written at Stop.
    #[serde(default)]
    failures: Vec<String>,
    /// Short notes from guard asks, for the same lesson.
    #[serde(default)]
    asks: Vec<String>,
    /// The sitting's lesson was written. Stop and SessionEnd share one.
    #[serde(default)]
    lesson: bool,
    #[serde(default)]
    finished: bool,
    /// `vissue` failed once. Later edits stay on the warm path instead of
    /// asking again on every tool call.
    #[serde(default)]
    claim_failed: bool,
    #[serde(default)]
    recall: String,
    /// HEAD the first time this sitting saw the repository, before a commit
    /// ran. A deed is cited only when HEAD has moved past it.
    #[serde(default)]
    start_sha: Option<String>,
    /// The prompt this sitting is working from. agy sends no title of its
    /// own; the words come from the prompt payload.
    #[serde(default)]
    title: Option<String>,
    /// Unix seconds of the last hook call that touched this repository.
    /// Zero means the row has no clock of its own. The book's `last_unix`
    /// is the last touch of whichever repository the seat used, not this one.
    #[serde(default)]
    last_unix: u64,
    /// The issue is one a commit named, not one this sitting filed. The
    /// sweep hands it back with a release instead of closing it: the
    /// commit cited work on someone's open ticket, it did not accept it.
    #[serde(default)]
    named: bool,
    /// Other open issues this row's commits named while it held `issue`.
    /// The sweep releases each of them too.
    #[serde(default)]
    also: Vec<String>,
    /// Shas already cited on an issue in `also`, so they are not cited on
    /// `issue` as well.
    #[serde(default)]
    elsewhere: Vec<String>,
}

/// Whether the guard and the pack daemon should stay out of this process.
/// A temp sandbox and `LJOS_OFF` are not seats: rtrash's tests delete
/// branches in a temp repository, and a daemon must not write under a temp
/// `HOME`. The book is not suspended here. A hook in a scratch directory
/// still files its claim.
#[must_use]
pub fn guard_suspended() -> bool {
    ljos_off() || home_or_cwd_is_temp()
}

/// `LJOS_OFF` set to one of the on-switches.
fn ljos_off() -> bool {
    matches!(
        std::env::var("LJOS_OFF").ok().as_deref(),
        Some("1" | "true" | "TRUE" | "yes" | "YES" | "on" | "ON")
    )
}

fn home_or_cwd_is_temp() -> bool {
    let home = std::env::var_os("HOME").map(PathBuf::from);
    let cwd = std::env::current_dir().ok();
    path_is_temp(home.as_deref()) || path_is_temp(cwd.as_deref())
}

/// Whether `LJOS_OFF` is set to one of its on-switches.
#[must_use]
pub fn ljos_is_off() -> bool {
    ljos_off()
}

/// `HOME` when it is a temporary directory or sits inside one.
#[must_use]
pub fn temp_home() -> Option<PathBuf> {
    std::env::var_os("HOME")
        .map(PathBuf::from)
        .filter(|home| path_is_temp(Some(home.as_path())))
}

/// Why [`guard_suspended`] holds in this process, in words a person reads
/// in `ljos doctor`. `None` when the guard is on.
#[must_use]
pub fn guard_off_reason() -> Option<String> {
    if ljos_off() {
        return Some("off: LJOS_OFF is set".to_string());
    }
    if let Some(home) = temp_home() {
        return Some(format!(
            "off: HOME ({}) is a temporary directory, and ljos stays out of test sandboxes",
            home.display()
        ));
    }
    let cwd = std::env::current_dir().ok()?;
    path_is_temp(Some(cwd.as_path())).then(|| {
        format!(
            "off here: {} is a temporary directory, and ljos stays out of test sandboxes",
            cwd.display()
        )
    })
}

/// Whether `path` is a temporary directory or sits inside one.
/// A missing path is judged as written, so `/tmpfoo` is not `/tmp`.
#[must_use]
pub fn path_is_temp(path: Option<&Path>) -> bool {
    let Some(path) = path else {
        return false;
    };
    if path.as_os_str().is_empty() {
        return false;
    }
    let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
    temp_roots().iter().any(|root| path.starts_with(root))
}

fn temp_roots() -> Vec<PathBuf> {
    let mut roots = vec![
        std::env::temp_dir(),
        PathBuf::from("/tmp"),
        PathBuf::from("/var/tmp"),
        PathBuf::from("/private/tmp"),
        PathBuf::from("/dev/shm"),
    ];
    if let Some(tmp) = std::env::var_os("TMPDIR").filter(|t| !t.is_empty()) {
        roots.push(PathBuf::from(tmp));
    }
    roots
        .into_iter()
        .map(|root| std::fs::canonicalize(&root).unwrap_or(root))
        .collect()
}

/// Keep the book for this hook call. The string is recall to inject, and
/// only on session start and on a prompt. Empty when there is nothing to
/// say. Never an error: a habitat that did not answer is a line in the
/// book log.
#[must_use]
pub fn observe(raw: &str, call: &super::HookCall) -> (String, Vec<String>) {
    let raw = raw.to_string();
    let call = call.clone();
    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| observe_inner(&raw, &call))) {
        Ok(text) => (text, Vec::new()),
        Err(_) => {
            log_line("bookkeep panicked");
            (String::new(), Vec::new())
        }
    }
}

fn observe_inner(raw: &str, call: &super::HookCall) -> String {
    if !BOOK_EVENTS.contains(&call.event.as_str()) {
        return String::new();
    }
    let session = session_key(call);
    let value: Value = serde_json::from_str(raw.trim()).unwrap_or(Value::Null);
    let _held = super::hook_timed("book_lock", || {
        super::CommitLock::acquire(&super::runtime_dir().join("book.lock"))
    });
    // A runner killed before Stop leaves its claims open. The next session
    // finishes those whose pid is gone, and replaces a deed whose commit is
    // no longer in the checkout with the one that is.
    if matches!(call.event.as_str(), "SessionStart" | "UserPromptSubmit") {
        let deadline = std::time::Instant::now() + SWEEP_BUDGET;
        super::hook_timed("finish_orphans", || finish_orphans(&session, deadline));
        super::hook_timed("refresh_landed_deeds", || refresh_landed_deeds(deadline));
    }
    // A sitting that only commits never sees SessionStart. Close every row
    // that has been idle, including one in another repository, before this
    // call stamps the book again.
    let path = book_path(&session);
    let repo_hint = {
        let mut scout = load_book(&path);
        repo_key(&mut scout, &value)
    };
    let hint = (!repo_hint.is_empty()).then_some(repo_hint.as_str());
    close_idle_sittings(unix_secs(), Some(session.as_str()), hint);
    let mut book = load_book(&path);
    book.owner_pid = next_owner_pid(&call.event, book.owner_pid, hook_owner());
    let mut prompt_set = false;
    if call.event == "UserPromptSubmit" {
        let prompt = collapse(&call.cue);
        if !prompt.is_empty() {
            book.prompt = prompt.chars().take(4000).collect();
            prompt_set = true;
        }
    }
    // agy's first model call often runs before the transcript has the
    // turn. A later payload still names that file, or carries `prompt`.
    if book.prompt.trim().is_empty() {
        let prompt = collapse(&super::prompt_of(&value));
        if !prompt.is_empty() {
            book.prompt = prompt.chars().take(4000).collect();
            prompt_set = true;
        }
    }
    let repo = repo_key(&mut book, &value);
    // Stop and SessionEnd close what the sitting opened. In a checkout the
    // book has no row for, they open nothing: an MCP server that answered
    // only guard checks used to leave a row with no issue at its exit.
    let ending_elsewhere =
        matches!(call.event.as_str(), "Stop" | "SessionEnd") && !book.repos.contains_key(&repo);
    let now = unix_secs();
    if prompt_set {
        bind_prompt(&mut book, &repo, now);
    }
    // `ljos hook --git-commit` puts the commit subject in `prompt`. That
    // subject titles the claim when this record has no live prompt for
    // the checkout. A prompt from the current sitting in this repository
    // still wins, and is left on the book for that sitting.
    let git_hook = value
        .get("ljos_git_hook")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    let subject_title = git_hook && !prompt_live_for(&book, &repo, now);
    let offered = if subject_title {
        super::prompt_of(&value)
    } else {
        String::new()
    };
    if subject_title {
        // An issue already open in this checkout keeps the title it was
        // filed under. The subject is for the claim this commit opens.
        let open = book
            .repos
            .get(&repo)
            .is_some_and(|row| row.issue.is_some() && !row.finished);
        if !open {
            let subject = collapse(&offered);
            if !subject.is_empty() && !repo.is_empty() {
                book.repos.entry(repo.clone()).or_default().title =
                    Some(subject.chars().take(4000).collect());
            }
        }
    } else if !ending_elsewhere {
        remember_title(&mut book, &repo);
    }
    let commit = is_git_commit(&call.cue);
    // A clean PostToolUse is the commit that just ran. Record the starting
    // HEAD on every other call, including the ask that stopped the command,
    // so the after hook cannot cite the commit the sitting began on.
    // A missing exit code is unknown, never a failure: Claude omits it on
    // a commit that landed, and Codex leaves it in the transcript. Read
    // the baseline before this call can record one.
    let exit = if call.event == "PostToolUse" {
        command_exit(&value)
    } else {
        CommandExit::Absent
    };
    let start = book.repos.get(&repo).and_then(|row| row.start_sha.clone());
    let landed = call.event == "PostToolUse"
        && commit
        && commit_landed(exit, &value, &repo, start.as_deref());
    // A commit that did not land must not become the baseline, and a
    // failed one must not finish the sitting or replace the start already
    // recorded. note_start writes the sha only when this row has none.
    if !landed && !ending_elsewhere {
        note_start(&mut book, &repo);
    }
    if call.event == "PostToolUseFailure"
        || (call.event == "PostToolUse" && command_failed(exit) && !commit)
    {
        note_failure(&mut book, &repo, &failure_text(&value, &call.cue));
    }
    if matches!(call.event.as_str(), "PreToolUse" | "PostToolUse") {
        // A write tool claims even for a new file. A shell redirect claims
        // when it writes a file inside this work tree, tracked or not.
        // A commit claims too, so a sitting that only commits still has a ticket.
        // A harness commit whose command names an open issue claims that
        // issue once it lands, through the git hook's path, not a new one.
        let names_open = commit && !git_hook && named_open_issue(&call.cue).is_some();
        if is_edit(&value, &call.cue)
            || (commit && !names_open)
            || writes_worktree(&repo, &call.cue)
        {
            let offered = subject_title.then_some(offered.as_str());
            let _ = ensure_claim(&mut book, &path, &repo, offered);
        }
        // The commit has not happened on the way in. Cite it on the way
        // out when the evidence says it landed, every new sha since the
        // recorded start. An explicit non-zero exit is the failure. A
        // missing exit, with nothing else that says the commit landed, is
        // not one.
        if landed {
            let named = if git_hook { None } else { named_head(&repo) };
            if let Some((issue, head)) = named {
                // An `ljos_start` row for this checkout comes back first, so
                // the named commit sees the issue the sitting holds.
                if book.repos.get(&repo).is_none_or(|row| row.issue.is_none()) {
                    let _ = take_started_row(&mut book, &path, &repo);
                }
                book_named_in(&mut book, &repo, &repo, &head, &issue);
            } else if names_open {
                // The command named an id the landed message does not: the
                // commit still gets the claim a commit files.
                let offered = subject_title.then_some(offered.as_str());
                let _ = ensure_claim(&mut book, &path, &repo, offered);
            }
            let _ = ensure_deed(&mut book, &repo);
        } else if call.event == "PostToolUse" && commit && command_failed(exit) {
            note_failure(&mut book, &repo, "git commit exited non-zero");
        }
    }
    if matches!(call.event.as_str(), "Stop" | "SessionEnd") {
        finish_open(&mut book);
        drop_unclaimed_rows(&mut book);
    }
    let held = if matches!(call.event.as_str(), "SessionStart" | "UserPromptSubmit") {
        book.repos.get(&repo).map(|row| {
            (
                row.issue.clone().filter(|_| !row.finished),
                row.recall.clone(),
            )
        })
    } else {
        None
    };
    if landed && !repo.is_empty() {
        book.last_repo.clone_from(&repo);
    }
    stamp_touch(&mut book, &repo, unix_secs());
    store_book(&path, &book);
    // The book is stored; the pack read below must not hold other hooks
    // on the lock.
    drop(_held);
    match held {
        Some((Some(issue), cached)) => claimed_recall(&issue, &cached),
        Some((None, cached)) => cached,
        None => String::new(),
    }
}

/// The recall a SessionStart or prompt hook hands the model for the issue
/// this checkout holds: the title line and [`super::recall_memories`], the
/// same memories `ljos recall` lists, read now rather than at the claim. A
/// seat with no pack keeps the line stored at the claim.
fn claimed_recall(issue: &str, cached: &str) -> String {
    if super::pack().is_err() {
        return cached.to_string();
    }
    format!("{}{}", recall_line(issue), super::recall_memories(issue))
}

/// Whether this MCP tool writes a habitat, so the server joins the held issue first.
#[must_use]
pub fn mcp_tool_writes(name: &str) -> bool {
    MCP_WRITES.contains(&name)
}

/// Attach a write tool's call to the issue this seat holds, before it runs.
/// A write tool (`ljos_remember`, `ljos_prefer`, ...) never files or claims
/// an issue: its text titled the claims it used to file. With an issue held
/// in the checkout, by this book or another book of this seat (a hook's
/// edit, `ljos_start`), the call joins that sitting. With none, it runs
/// unattached.
pub fn before_mcp_write(name: &str, args: Option<&serde_json::Map<String, Value>>) {
    if !mcp_tool_writes(name) {
        return;
    }
    let session = sitting_key();
    let explicit = args.and_then(|map| map.get("repo")).and_then(Value::as_str);
    let Some(place) = place_for_claim(explicit) else {
        log_line(&format!("{name}: no checkout here; ran unattached"));
        return;
    };
    {
        let _held = super::CommitLock::acquire(&super::runtime_dir().join("book.lock"));
        let path = book_path(&session);
        let mut book = load_book(&path);
        let open = book
            .repos
            .get(&place)
            .is_some_and(|row| row.issue.is_some() && !row.finished);
        if open || take_held_issue(&mut book, &path, &place) {
            store_book(&path, &book);
        } else {
            log_line(&format!("{name}: nothing held in {place}; ran unattached"));
        }
    }
    stamp_sitting(&session, unix_secs());
}

/// Finish every claim this MCP process opened. Called when the server exits.
pub fn mcp_shutdown() {
    let session = sitting_key();
    let cwd = std::env::current_dir()
        .ok()
        .map(|p| p.display().to_string())
        .unwrap_or_default();
    let raw = serde_json::json!({
        "cwd": cwd,
        "session_id": session,
        "hook_event_name": "SessionEnd",
    })
    .to_string();
    let call = super::HookCall {
        event: "SessionEnd".into(),
        cue: String::new(),
        session: Some(session),
        shape: super::HookShape::Asks,
    };
    let _ = observe(&raw, &call);
    match super::sync::sync_repo_in_passing(false, true) {
        Ok(line) if !line.trim().is_empty() => log_line(line.trim()),
        Err(e) => log_line(&format!("sync: {e:#}")),
        Ok(_) => {}
    }
}

/// Note that a tool ran, so the idle watcher waits another window.
pub fn touch_activity() {
    LAST_ACTIVITY.store(unix_secs(), Ordering::Relaxed);
}

/// Tool calls this process has answered. A process that answered one call
/// and exited was spawned per call: finishing in `Drop` would close the
/// sitting before the next call. The book stays, and the next start
/// finishes it once the idle window has passed.
static MCP_CALLS: AtomicU64 = AtomicU64::new(0);

/// Count one tool call in this process, for [`ShutdownFinish`].
pub fn note_mcp_process_call() {
    MCP_CALLS.fetch_add(1, Ordering::Relaxed);
}

/// Finish the seat's open claims when the last call is older than the
/// idle window, then stamp this call. A per-call server has no thread
/// left alive to notice the idle; the next process does.
pub fn resume_seat() {
    resume_seat_at(unix_secs());
}

fn resume_seat_at(now: u64) {
    let key = sitting_key();
    if let Some(limit) = idle_limit() {
        let book = load_book(&book_path(&key));
        let open = book
            .repos
            .values()
            .any(|row| row.issue.is_some() && !row.finished);
        if open && idle_due(now, book.last_unix, limit) {
            mcp_shutdown();
        }
    }
    stamp_sitting(&key, now);
}

fn stamp_sitting(key: &str, now: u64) {
    let _held = super::CommitLock::acquire(&super::runtime_dir().join("book.lock"));
    let path = book_path(key);
    let mut book = load_book(&path);
    book.last_unix = now;
    store_book(&path, &book);
}

/// How long a silent MCP server sits before it finishes. Unset is thirty
/// minutes. `0` and `off` leave the session open until the process exits.
#[must_use]
pub fn idle_limit() -> Option<Duration> {
    idle_limit_from(std::env::var("LJOS_MCP_IDLE").ok().as_deref())
}

/// [`idle_limit`] from an already-read value. `None` is the default window.
#[must_use]
pub fn idle_limit_from(raw: Option<&str>) -> Option<Duration> {
    let Some(raw) = raw.map(str::trim).filter(|text| !text.is_empty()) else {
        return Some(Duration::from_secs(30 * 60));
    };
    let lowered = raw.to_ascii_lowercase();
    if matches!(lowered.as_str(), "0" | "off" | "false" | "no") {
        return None;
    }
    match super::reap::parse_idle(raw) {
        Ok(window) if window.is_zero() => None,
        Ok(window) => Some(window),
        Err(_) => Some(Duration::from_secs(30 * 60)),
    }
}

/// Whether `now` is at least `limit` past `last`. A `last` of zero has
/// never been touched, so it is not idle.
#[must_use]
pub fn idle_due(now: u64, last: u64, limit: Duration) -> bool {
    last > 0 && now.saturating_sub(last) >= limit.as_secs()
}

/// How long a sitting may go without a hook call before the next call
/// finishes it. Unset is two hours. `0` and `off` leave it open.
fn sitting_idle() -> Option<Duration> {
    sitting_idle_from(std::env::var("LJOS_SITTING_IDLE").ok().as_deref())
}

fn sitting_idle_from(raw: Option<&str>) -> Option<Duration> {
    let Some(raw) = raw.map(str::trim).filter(|text| !text.is_empty()) else {
        return Some(Duration::from_secs(2 * 60 * 60));
    };
    let lowered = raw.to_ascii_lowercase();
    if matches!(lowered.as_str(), "0" | "off" | "false" | "no") {
        return None;
    }
    match super::reap::parse_idle(raw) {
        Ok(window) if window.is_zero() => None,
        Ok(window) => Some(window),
        Err(_) => Some(Duration::from_secs(2 * 60 * 60)),
    }
}

/// Finish idle rows on the next hook call.
///
/// Each repository has its own clock. A fresh `last_unix` on the book,
/// from a commit in one checkout, does not keep another checkout's row
/// open. `session` and `current` name the book and repository this call
/// is in. A row that predates the per-repository clock is finished when
/// this call is in a different repository: the book's clock was refreshed
/// by that other checkout, not by the row.
pub(crate) fn sweep_idle_sittings(session: &str, current: &str) {
    let _held = super::CommitLock::acquire(&super::runtime_dir().join("book.lock"));
    let current = (!current.is_empty()).then_some(current);
    close_idle_sittings(unix_secs(), Some(session), current);
}

/// Finish rows idle longer than [`sitting_idle`], and drop the finished
/// ones so the next call in that repository files its own claim.
fn close_idle_sittings(now: u64, session: Option<&str>, current: Option<&str>) {
    let Some(limit) = sitting_idle() else {
        return;
    };
    let current_path = session.map(book_path);
    for path in book_files() {
        let mut book = load_book(&path);
        let here = current_path.as_ref().is_some_and(|want| want == &path);
        let hint = if here { current } else { None };
        let idle: Vec<String> = book
            .repos
            .iter()
            .filter(|(repo, row)| row_is_idle(now, &book, repo, row, limit, hint))
            .map(|(repo, _)| repo.clone())
            .collect();
        let unclaimed = book.repos.len();
        let touched = book.last_unix;
        book.repos.retain(|_, row| {
            !unclaimed_row(row) || !idle_due(now, row.last_unix.max(touched), limit)
        });
        let dropped = book.repos.len() != unclaimed;
        if idle.is_empty() {
            if dropped {
                book.cwd_repo
                    .retain(|_, repo| book.repos.contains_key(repo));
                store_book(&path, &book);
            }
            continue;
        }
        finish_rows(&mut book, &idle);
        book.repos.retain(|_, row| !row.finished);
        book.cwd_repo
            .retain(|_, repo| book.repos.contains_key(repo));
        release_spent_prompt(&mut book);
        store_book(&path, &book);
    }
}

fn unix_secs() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|elapsed| elapsed.as_secs())
        .unwrap_or(0)
}

/// Finish the open claims when no tool has run for [`idle_limit`]. One
/// thread for the process. A disabled window starts nothing.
pub fn spawn_idle_finish() {
    static ONCE: std::sync::Once = std::sync::Once::new();
    ONCE.call_once(|| {
        let Some(limit) = idle_limit() else {
            return;
        };
        touch_activity();
        let _ = std::thread::Builder::new()
            .name("ljos-mcp-idle".into())
            .spawn(move || {
                let tick = Duration::from_secs(30.min(limit.as_secs().max(1)));
                loop {
                    std::thread::sleep(tick);
                    let last = LAST_ACTIVITY.load(Ordering::Relaxed);
                    if idle_due(unix_secs(), last, limit) {
                        mcp_shutdown();
                        touch_activity();
                    }
                }
            });
    });
}

/// Words a model passes when it does not know the issue id.
#[must_use]
pub fn blank_issue(id: &str) -> bool {
    matches!(
        id.trim().to_ascii_lowercase().as_str(),
        "" | "none"
            | "null"
            | "nil"
            | "n/a"
            | "na"
            | "undefined"
            | "unknown"
            | "-"
            | "n.a."
            | "n.a"
    )
}

/// The issue `raw` names, or the one this session claimed when `raw` is
/// missing or a placeholder such as `none`.
#[must_use]
pub fn canonical_issue(raw: Option<&str>, session: Option<&str>) -> Option<String> {
    if let Some(id) = raw.map(str::trim).filter(|id| !blank_issue(id)) {
        return Some(id.to_string());
    }
    claimed_issue(session)
}

/// The unfinished issue this conversation's book holds. A new session does
/// not inherit another conversation's ticket.
#[must_use]
pub fn session_issue(session: Option<&str>) -> Option<String> {
    issue_in_sessions(session)
}

/// The issue to use when a tool did not name one: this session's claim,
/// the MCP sitting, or the newest unfinished claim in this directory.
#[must_use]
pub fn claimed_issue(session: Option<&str>) -> Option<String> {
    issue_in_sessions(session)
        .or_else(open_issue)
        .or_else(latest_cwd_issue)
}

fn issue_in_sessions(session: Option<&str>) -> Option<String> {
    let mut seen = std::collections::BTreeSet::new();
    let mut keys = Vec::new();
    let mut push = |raw: String| {
        let key = raw.trim().to_string();
        if key.is_empty() || !seen.insert(key.clone()) {
            return;
        }
        keys.push(key);
    };
    if let Some(session) = session {
        push(session.to_string());
    }
    if let Some(session) = crate::ballot_sig::call_session() {
        push(session);
    }
    if let Ok(session) = std::env::var("LJOS_HARNESS_SESSION") {
        push(session);
    }
    if let Ok(session) = std::env::var("LJOS_SESSION_ID") {
        push(session);
    }
    if let Some((id, _)) = super::session_actor() {
        push(id);
    }
    for key in &keys {
        if let Some(issue) = open_in_book(&load_book(&book_path(key))) {
            return Some(issue);
        }
    }
    None
}

fn open_in_book(book: &Book) -> Option<String> {
    let cwd = std::env::current_dir()
        .ok()
        .map(|path| path.display().to_string())
        .unwrap_or_default();
    if let Some(key) = book.cwd_repo.get(&cwd) {
        if let Some(issue) = unfinished(book, key) {
            return Some(issue);
        }
    }
    let mut found = None;
    for key in book.repos.keys() {
        if let Some(issue) = unfinished(book, key) {
            if found.is_some() {
                return None;
            }
            found = Some(issue);
        }
    }
    found
}

/// The newest unfinished claim whose book names this working directory.
fn latest_cwd_issue() -> Option<String> {
    let cwd = std::env::current_dir().ok()?;
    let dir = super::runtime_dir();
    let mut hits = Vec::new();
    for entry in std::fs::read_dir(dir).ok()?.flatten() {
        let name = entry.file_name();
        let name = name.to_string_lossy();
        if !name.starts_with("book-") || !name.ends_with(".json") {
            continue;
        }
        let book = load_book(&entry.path());
        let Some(issue) = issue_for_cwd(&book, &cwd) else {
            continue;
        };
        let when = entry
            .metadata()
            .and_then(|meta| meta.modified())
            .unwrap_or(std::time::SystemTime::UNIX_EPOCH);
        hits.push((when, issue));
    }
    hits.sort_by_key(|hit| hit.0);
    hits.pop().map(|hit| hit.1)
}

fn issue_for_cwd(book: &Book, cwd: &Path) -> Option<String> {
    let cwd_s = cwd.display().to_string();
    if let Some(key) = book.cwd_repo.get(&cwd_s) {
        if let Some(issue) = unfinished(book, key) {
            return Some(issue);
        }
    }
    for (dir, key) in &book.cwd_repo {
        if paths_match(dir, cwd) {
            if let Some(issue) = unfinished(book, key) {
                return Some(issue);
            }
        }
    }
    for key in book.repos.keys() {
        if paths_match(key, cwd) {
            if let Some(issue) = unfinished(book, key) {
                return Some(issue);
            }
        }
    }
    None
}

fn paths_match(raw: &str, cwd: &Path) -> bool {
    let path = Path::new(raw);
    if path == cwd {
        return true;
    }
    match (
        std::fs::canonicalize(path).ok(),
        std::fs::canonicalize(cwd).ok(),
    ) {
        (Some(left), Some(right)) => left == right,
        _ => false,
    }
}

/// The issue this MCP sitting still holds, for a finish that did not name one.
#[must_use]
pub fn open_issue() -> Option<String> {
    let book = load_book(&book_path(&sitting_key()));
    let cwd = std::env::current_dir()
        .ok()
        .map(|path| path.display().to_string())
        .unwrap_or_default();
    if let Some(key) = book.cwd_repo.get(&cwd) {
        if let Some(issue) = unfinished(&book, key) {
            return Some(issue);
        }
    }
    book.repos
        .iter()
        .find_map(|(key, _)| unfinished(&book, key))
}

fn unfinished(book: &Book, key: &str) -> Option<String> {
    let row = book.repos.get(key)?;
    if row.finished {
        return None;
    }
    row.issue.clone()
}

/// The explicit finish closed `issue`. Shutdown then has nothing left to close.
pub fn note_finished(issue: &str) {
    let _held = super::CommitLock::acquire(&super::runtime_dir().join("book.lock"));
    let path = book_path(&sitting_key());
    let mut book = load_book(&path);
    let mut changed = false;
    for row in book.repos.values_mut() {
        if row.issue.as_deref() == Some(issue) && !row.finished {
            row.finished = true;
            changed = true;
        }
    }
    if changed {
        store_book(&path, &book);
    }
}

/// Recall and claim before repo work. `issue` claims that ticket. Without
/// it, `task` is filed under `repo` (or the working directory) and claimed.
/// The issue is the one shutdown and an issue-less finish close.
///
/// # Errors
///
/// `task` is empty, or the tracker did not file or claim.
pub fn start_work(issue: Option<&str>, repo: Option<&str>, task: &str) -> Result<String, String> {
    let task = collapse(task);
    if task.is_empty() {
        return Err("ljos_start: pass the task in one sentence".into());
    }
    let cwd = std::env::current_dir()
        .ok()
        .map(|path| path.display().to_string())
        .unwrap_or_default();
    let named = repo.map(str::trim).filter(|path| !path.is_empty());
    let Some(place) = place_for_claim(named) else {
        return Err(if named.is_some() {
            "ljos_start: repo is not a git checkout".into()
        } else {
            "ljos_start: pass repo, a git checkout".into()
        });
    };
    let asked = issue.map(str::trim).filter(|id| !blank_issue(id));
    if asked.is_none() {
        if let Some(said) = start_on_held(&place, &task, &cwd) {
            return Ok(said);
        }
    }
    let issue_id = match asked {
        Some(id) => {
            claim_existing(id)?;
            id.to_string()
        }
        None => file_and_claim(&project_for(&place), &task)?,
    };
    let persisted = super::persist_tracker(&issue_id, "claimed");
    if persisted.contains("could not") || persisted.contains("refused") {
        log_line(persisted.trim());
    }
    let recall = format!(
        "{}{}",
        recall_line(&issue_id),
        super::recall_memories(&issue_id)
    );
    let _held = super::CommitLock::acquire(&super::runtime_dir().join("book.lock"));
    let path = book_path(&sitting_key());
    let mut book = load_book(&path);
    let now = unix_secs();
    book.last_unix = now;
    if book.prompt.trim().is_empty() {
        book.prompt = task.chars().take(4000).collect();
        bind_prompt(&mut book, &place, now);
    }
    let row = book.repos.entry(place.clone()).or_default();
    row.last_unix = now;
    row.issue = Some(issue_id.clone());
    row.finished = false;
    row.started = true;
    row.claim_failed = false;
    row.recall.clone_from(&recall);
    if !cwd.is_empty() {
        book.cwd_repo.insert(cwd, place);
    }
    store_book(&path, &book);
    drop(_held);
    Ok(format!("claimed {issue_id}\n{recall}"))
}

fn claim_existing(issue: &str) -> Result<(), String> {
    let assignee = super::resolve_assignee(None);
    if which::which("claimdag").is_ok() && super::claim(issue, &assignee).is_ok() {
        return Ok(());
    }
    let first = run_timed(
        "vissue",
        &["claim", issue],
        &[("VISSUE_AGENT", assignee.as_str())],
    );
    match first {
        Ok(_) => Ok(()),
        // The same seat under another name (the hook's tag, the server's
        // bare seat) holds it: this conversation takes its own claim back.
        Err(e)
            if e.to_string().contains("pass --force")
                && tracker_holder(issue)
                    .is_some_and(|by| super::same_seat_here(&by, &assignee)) =>
        {
            run_timed(
                "vissue",
                &["claim", issue, "--force"],
                &[("VISSUE_AGENT", assignee.as_str())],
            )
            .map(|_| ())
            .map_err(|e| e.to_string())
        }
        Err(e) => Err(e.to_string()),
    }
}

/// Finishes the MCP session's claims when the server process returns.
/// Bind it to a name. `let _ = ShutdownFinish` drops it at that statement.
pub struct ShutdownFinish;

impl Drop for ShutdownFinish {
    fn drop(&mut self) {
        // One call, then the process is gone: this was spawned per call.
        // The sitting stays on disk under the seat. The next start finishes
        // it once the idle window has passed. A server that answered more
        // than one call is the long-lived process, and its exit closes.
        if MCP_CALLS.load(Ordering::Relaxed) > 1 {
            mcp_shutdown();
        }
    }
}

/// The book key. An MCP call is keyed by the seat, so a server spawned
/// once per tool call keeps the claim and the idle clock. A hook, and an
/// MCP process with no seat yet, stay on the session id.
fn sitting_key() -> String {
    let named = super::hook_actor().or_else(|| {
        std::env::var("LJOS_SEAT")
            .ok()
            .map(|raw| raw.trim().to_string())
            .filter(|raw| !raw.is_empty())
    });
    if let Some(name) = named {
        let slug = super::seat_slug(&name);
        if slug != "runner" && !super::omitted_actor_name(&slug) {
            return format!("seat:{slug}");
        }
    }
    mcp_session()
}

fn mcp_session() -> String {
    std::env::var("LJOS_SESSION_ID")
        .ok()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .unwrap_or_else(|| format!("mcp-{}", std::process::id()))
}

fn session_key(call: &super::HookCall) -> String {
    call.session
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_string)
        .or_else(|| {
            std::env::var("LJOS_SESSION_ID")
                .ok()
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
        })
        .unwrap_or_else(|| std::process::id().to_string())
}

fn book_path(session: &str) -> PathBuf {
    super::runtime_dir().join(format!("book-{}.json", super::session_tag(session)))
}

fn load_book(path: &Path) -> Book {
    std::fs::read_to_string(path)
        .ok()
        .and_then(|text| serde_json::from_str(&text).ok())
        .unwrap_or_default()
}

fn store_book(path: &Path, book: &Book) {
    let Ok(text) = serde_json::to_string(book) else {
        return;
    };
    if std::fs::read_to_string(path).is_ok_and(|prev| prev == text) {
        return;
    }
    if let Some(dir) = path.parent() {
        let _ = std::fs::create_dir_all(dir);
    }
    if let Err(e) = std::fs::write(path, text) {
        log_line(&format!("book: {e}"));
    }
}

/// Append one line to the seat's `book.log` under the runtime directory.
pub fn log_line(line: &str) {
    let dir = super::runtime_dir();
    let _ = std::fs::create_dir_all(&dir);
    let Ok(mut file) = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(dir.join("book.log"))
    else {
        return;
    };
    use std::io::Write;
    let _ = writeln!(file, "{line}");
}

fn collapse(text: &str) -> String {
    text.split_whitespace().collect::<Vec<_>>().join(" ")
}

/// The repository this call is about: `git rev-parse` once per cwd, then
/// the canonical directory when this cwd is not a checkout.
fn repo_key(book: &mut Book, raw: &Value) -> String {
    let cwd = raw["cwd"]
        .as_str()
        .or_else(|| raw["workspacePaths"][0].as_str())
        .map(str::to_string)
        .filter(|s| !s.is_empty())
        .or_else(|| {
            std::env::current_dir()
                .ok()
                .map(|p| p.display().to_string())
        })
        .unwrap_or_default();
    if let Some(hit) = book.cwd_repo.get(&cwd) {
        return hit.clone();
    }
    let key = git_toplevel(Path::new(&cwd)).unwrap_or_else(|| {
        let path = PathBuf::from(&cwd);
        std::fs::canonicalize(&path)
            .unwrap_or(path)
            .display()
            .to_string()
    });
    if !cwd.is_empty() {
        book.cwd_repo.insert(cwd, key.clone());
    }
    key
}

/// Where a new claim is filed. An explicit path is used only when it is a
/// checkout: it does not fall back to the working directory. With no path,
/// the last repository this seat's git hook booked, then the working
/// directory when that is a checkout.
fn place_for_claim(explicit: Option<&str>) -> Option<String> {
    place_for_claim_in(
        explicit,
        last_booked_repo().as_deref(),
        std::env::current_dir().ok().as_deref(),
    )
}

fn place_for_claim_in(
    explicit: Option<&str>,
    last: Option<&str>,
    cwd: Option<&Path>,
) -> Option<String> {
    if let Some(path) = explicit.map(str::trim).filter(|path| !path.is_empty()) {
        return git_toplevel(Path::new(path));
    }
    if let Some(path) = last.map(str::trim).filter(|path| !path.is_empty()) {
        if let Some(top) = git_toplevel(Path::new(path)) {
            return Some(top);
        }
    }
    cwd.and_then(git_toplevel)
}

/// The checkout the git hook last booked for this seat.
fn last_booked_repo() -> Option<String> {
    let book = load_book(&book_path(&sitting_key()));
    let repo = book.last_repo.trim();
    if repo.is_empty() {
        None
    } else {
        Some(repo.to_string())
    }
}

/// The book key for this seat, shared by the git hook and the MCP server.
#[must_use]
pub fn seat_session() -> String {
    sitting_key()
}

fn git_toplevel(cwd: &Path) -> Option<String> {
    if cwd.as_os_str().is_empty() {
        return None;
    }
    let said = run_timed(
        "git",
        &[
            "-C",
            &cwd.display().to_string(),
            "rev-parse",
            "--show-toplevel",
        ],
        &[],
    )
    .ok()?;
    let top = said.stdout.trim();
    (!top.is_empty()).then(|| top.to_string())
}

fn ensure_claim(
    book: &mut Book,
    own: &Path,
    repo: &str,
    offered: Option<&str>,
) -> Result<(), String> {
    let row = book.repos.entry(repo.to_string()).or_default();
    if row.claim_failed {
        return Ok(());
    }
    if let Some(issue) = row.issue.clone() {
        if row.recall.is_empty() {
            row.recall = recall_line(&issue);
        }
        return Ok(());
    }
    // The seat may already hold an issue in this checkout under another
    // book: `ljos_start` in the MCP server keys its book by the seat, the
    // harness hook by the harness session. That issue is this sitting's.
    if take_held_issue(book, own, repo) {
        return Ok(());
    }
    // A hold from another repository is a different ticket. This sitting
    // files its own claim for the repository the tool just wrote.
    // A git hook passes the commit subject when the saved prompt is not
    // this sitting's.
    let title = match offered.map(str::trim).filter(|text| !text.is_empty()) {
        Some(subject) => title_from(subject, repo),
        None => title_from(&book.prompt, repo),
    };
    let project = project_for(repo);
    match file_and_claim(&project, &title) {
        Ok(issue) => {
            let line = super::persist_tracker(&issue, "claimed");
            if line.contains("could not") || line.contains("refused") {
                log_line(line.trim());
            }
            let row = book.repos.entry(repo.to_string()).or_default();
            row.issue = Some(issue.clone());
            row.filed = true;
            row.recall = recall_line(&issue);
            Ok(())
        }
        Err(e) => {
            log_line(&format!("claim: {e}"));
            book.repos.entry(repo.to_string()).or_default().claim_failed = true;
            Ok(())
        }
    }
}

/// `ljos_start` with no issue, when this seat already holds one in the
/// checkout `place`: a hook claimed it for an edit, or an earlier start
/// did. That row moves to the server's book, marked as started, so an
/// issue-less finish closes it and the next hook call takes it back. The
/// task goes on the issue as a note when it differs from the title the
/// hook filed it under. `None` when nothing is held there.
fn start_on_held(place: &str, task: &str, cwd: &str) -> Option<String> {
    let held = super::CommitLock::acquire(&super::runtime_dir().join("book.lock"));
    let own = book_path(&sitting_key());
    let mut found: Option<((u64, u128), PathBuf, String, String)> = None;
    for path in book_files() {
        let other = load_book(&path);
        let rank = row_rank(&path, &other);
        for (key, row) in &other.repos {
            let Some(issue) = row.issue.as_deref() else {
                continue;
            };
            if row.finished || !same_checkout(key, place) {
                continue;
            }
            if found.as_ref().is_some_and(|(when, ..)| *when > rank) {
                continue;
            }
            if held_by_this_seat(issue) {
                found = Some((rank, path.clone(), key.clone(), issue.to_string()));
            }
        }
    }
    let (_, path, key, issue) = found?;
    let mut book = load_book(&own);
    let moved = if path == own {
        book.repos.remove(&key).unwrap_or_default()
    } else {
        let mut other = load_book(&path);
        let moved = other.repos.remove(&key).unwrap_or_default();
        store_book(&path, &other);
        moved
    };
    let filed = moved.filed;
    let now = unix_secs();
    book.last_unix = now;
    if book.prompt.trim().is_empty() {
        book.prompt = task.chars().take(4000).collect();
        bind_prompt(&mut book, place, now);
    }
    adopt_row(&mut book, place, &issue, moved);
    let row = book.repos.entry(place.to_string()).or_default();
    row.started = true;
    row.last_unix = now;
    if !cwd.is_empty() {
        book.cwd_repo.insert(cwd.to_string(), place.to_string());
    }
    store_book(&own, &book);
    drop(held);
    log_line(&format!("start: kept {issue}, already held in {place}"));
    if filed && !same_words(task, &issue_title(&issue)) {
        let note = format!("ljos_start task: {task}");
        match run_timed("vissue", &["note", &issue, &note], &[]) {
            Ok(_) => {
                let line = super::persist_tracker(&issue, "noted");
                if line.contains("could not") || line.contains("refused") {
                    log_line(line.trim());
                }
            }
            Err(e) => log_line(&format!("start: note on {issue}: {e}")),
        }
    }
    let recall = format!("{}{}", recall_line(&issue), super::recall_memories(&issue));
    Some(format!("claimed {issue}\n{recall}"))
}

/// The title the tracker holds for `issue`, or nothing.
fn issue_title(issue: &str) -> String {
    super::issue_record(issue)
        .ok()
        .and_then(|v| v["title"].as_str().map(str::to_string))
        .unwrap_or_default()
}

/// Whether two titles say the same words, case and punctuation aside.
fn same_words(a: &str, b: &str) -> bool {
    let words = |text: &str| -> Vec<String> {
        text.split(|c: char| !c.is_alphanumeric() && c != '_')
            .filter(|w| !w.is_empty())
            .map(str::to_lowercase)
            .collect()
    };
    words(a) == words(b)
}

/// Put the issue this seat already holds in `repo` on this book's row, and
/// say whether there was one. A row another book keeps for the checkout
/// (`ljos_start`, a named commit) moves here whole, so one book finishes
/// it and the other does not finish it a second time without its deeds.
/// Else a claim the seat's hold record names in this checkout's project
/// (`ljos claim`) is taken as the row's issue. Either issue has to be
/// STARTED in the tracker under this holder, in either form: the bare
/// seat or `SEAT@TAG`.
fn take_held_issue(book: &mut Book, own: &Path, repo: &str) -> bool {
    if take_started_row(book, own, repo) {
        return true;
    }
    let project = project_for(repo);
    let Some(issue) = super::held_issue().filter(|id| {
        id.rsplit_once('-').is_some_and(|(p, _)| p == project) && held_by_this_seat(id)
    }) else {
        return false;
    };
    // A hold record is shared by the runner. An automatic claim in a
    // different hook conversation belongs to that conversation; only a
    // started sitting can transfer through take_started_row.
    let claimed_elsewhere = book_files().into_iter().any(|path| {
        path != own
            && load_book(&path).repos.values().any(|row| {
                row.filed
                    && !row.started
                    && !row.finished
                    && row.issue.as_deref() == Some(issue.as_str())
            })
    });
    if claimed_elsewhere {
        return false;
    }
    adopt_row(book, repo, &issue, RepoBook::default());
    log_line(&format!("claim: kept {issue}, held by this seat"));
    true
}

/// The book scan of [`take_held_issue`]: an `ljos_start` row another book
/// keeps for the checkout moves to `book`.
fn take_started_row(book: &mut Book, own: &Path, repo: &str) -> bool {
    let mut found: Option<((u64, u128), PathBuf, String, String)> = None;
    for path in book_files() {
        if path == own {
            continue;
        }
        let other = load_book(&path);
        let rank = row_rank(&path, &other);
        for (key, row) in &other.repos {
            let Some(issue) = row.issue.as_deref() else {
                continue;
            };
            if row.finished || !row.started || !same_checkout(key, repo) {
                continue;
            }
            if found.as_ref().is_some_and(|(when, ..)| *when > rank) {
                continue;
            }
            if held_by_this_seat(issue) {
                found = Some((rank, path.clone(), key.clone(), issue.to_string()));
            }
        }
    }
    if let Some((_, path, key, issue)) = found {
        let mut other = load_book(&path);
        let moved = other.repos.remove(&key).unwrap_or_default();
        store_book(&path, &other);
        adopt_row(book, repo, &issue, moved);
        log_line(&format!("claim: kept {issue}, already held in {repo}"));
        return true;
    }
    false
}

/// Whether the tracker has `issue` STARTED and claimed by this seat. The
/// callers look at one checkout, so a holder of this seat under another
/// tag is this conversation: the git hook books `SEAT@TAG` (`SEAT-TAG`
/// before 0.32) and `ljos_start` books the bare seat ([`super::same_seat`]).
/// A tracker that records no holder answers by the state alone.
fn held_by_this_seat(issue: &str) -> bool {
    let Ok(v) = super::issue_record(issue) else {
        return false;
    };
    if v["id"].as_str() != Some(issue) || v["state"].as_str() != Some("STARTED") {
        return false;
    }
    match v["claimed_by"].as_str().map(str::trim) {
        Some(by) if !by.is_empty() => super::same_seat_here(by, &super::holder_name()),
        _ => true,
    }
}

/// The tracker's holder of `issue`, when the record names one.
fn tracker_holder(issue: &str) -> Option<String> {
    super::issue_record(issue).ok().and_then(|v| {
        v["claimed_by"]
            .as_str()
            .map(str::trim)
            .filter(|by| !by.is_empty())
            .map(str::to_string)
    })
}

/// Fold `moved`, another book's row for the checkout, into this book's
/// row, which then holds `issue`.
fn adopt_row(book: &mut Book, repo: &str, issue: &str, moved: RepoBook) {
    let row = book.repos.entry(repo.to_string()).or_default();
    row.issue = Some(issue.to_string());
    row.finished = false;
    row.claim_failed = false;
    row.recall = if moved.recall.is_empty() {
        recall_line(issue)
    } else {
        moved.recall
    };
    if moved.start_sha.is_some() {
        row.start_sha = moved.start_sha;
    }
    if row.title.is_none() {
        row.title = moved.title;
    }
    for sha in moved.deeds {
        if !row.deeds.contains(&sha) {
            row.deeds.push(sha);
        }
    }
    for sha in moved.landed {
        if !row.landed.contains(&sha) {
            row.landed.push(sha);
        }
    }
    row.failures.extend(moved.failures);
    row.asks.extend(moved.asks);
    row.named |= moved.named;
    row.filed = moved.filed;
    for other in moved.also {
        if !row.also.contains(&other) {
            row.also.push(other);
        }
    }
    for sha in moved.elsewhere {
        if !row.elsewhere.contains(&sha) {
            row.elsewhere.push(sha);
        }
    }
}

fn file_and_claim(project: &str, title: &str) -> Result<String, String> {
    let assignee = super::resolve_assignee(None);
    let said = run_timed(
        "vissue",
        &["create", "-p", project, title, "-q"],
        &[("VISSUE_AGENT", assignee.as_str())],
    )
    .map_err(|e| e.to_string())?;
    let issue = parse_issue_id(&said.stdout)
        .ok_or_else(|| format!("vissue create printed no issue id: {}", said.stdout.trim()))?;
    if which::which("claimdag").is_ok() {
        if let Err(e) = super::claim(&issue, &assignee) {
            log_line(&format!("claim graph: {e:#}"));
            run_timed(
                "vissue",
                &["claim", &issue],
                &[("VISSUE_AGENT", assignee.as_str())],
            )
            .map_err(|e| e.to_string())?;
        }
    } else {
        run_timed(
            "vissue",
            &["claim", &issue],
            &[("VISSUE_AGENT", assignee.as_str())],
        )
        .map_err(|e| e.to_string())?;
    }
    Ok(issue)
}

fn ensure_deed(book: &mut Book, repo: &str) -> Result<(), String> {
    cite_row(book, repo, repo)
}

/// Cite every commit that landed after the row's baseline. A compound
/// command can write more than one. No baseline means this post is the
/// first time the sitting saw the repository, so the sha is the one git wrote.
fn cite_row(book: &mut Book, row_key: &str, git_repo: &str) -> Result<(), String> {
    let head = match head_sha(git_repo) {
        Ok(sha) => sha,
        Err(e) => {
            log_line(&format!("deed: {e}"));
            return Ok(());
        }
    };
    let start = book
        .repos
        .get(row_key)
        .and_then(|row| row.start_sha.clone());
    let Some(issue) = book.repos.get(row_key).and_then(|row| row.issue.clone()) else {
        return Ok(());
    };
    for sha in commits_since(git_repo, start.as_deref(), &head) {
        if book.repos.get(row_key).is_some_and(|row| {
            row.deeds
                .iter()
                .chain(&row.elsewhere)
                .any(|seen| seen == &sha)
        }) {
            continue;
        }
        match cite_deed(&issue, &sha) {
            Ok(()) => {
                book.repos
                    .entry(row_key.to_string())
                    .or_default()
                    .deeds
                    .push(sha);
            }
            Err(e) => {
                log_line(&format!("deed: {e}"));
                return Ok(());
            }
        }
    }
    Ok(())
}

/// Commits strictly after `start`, oldest first. Without a baseline, the
/// current HEAD is the commit this post is about.
fn commits_since(repo: &str, start: Option<&str>, head: &str) -> Vec<String> {
    let Some(start) = start.map(str::trim).filter(|sha| !sha.is_empty()) else {
        return vec![head.to_string()];
    };
    if start == head {
        return Vec::new();
    }
    let range = format!("{start}..{head}");
    let shas = run_timed("git", &["-C", repo, "rev-list", "--reverse", &range], &[])
        .ok()
        .map(|said| {
            said.stdout
                .lines()
                .map(str::trim)
                .filter(|sha| sha.len() >= 7 && sha.chars().all(|c| c.is_ascii_hexdigit()))
                .map(str::to_string)
                .collect::<Vec<_>>()
        });
    match shas {
        Some(shas) if !shas.is_empty() => shas,
        _ => vec![head.to_string()],
    }
}

/// Cite `repo`'s new commits on the open sitting that already holds it.
/// A git hook books here instead of opening a seat book whose start is the
/// commit that just landed. False when no sitting holds the checkout.
pub(crate) fn cite_into_open_sitting(repo: &str) -> bool {
    let _held = super::CommitLock::acquire(&super::runtime_dir().join("book.lock"));
    let Some((path, key)) = open_row_for_repo(repo) else {
        return false;
    };
    let mut book = load_book(&path);
    let open = book
        .repos
        .get(&key)
        .is_some_and(|row| !row.finished && row.issue.is_some());
    if !open {
        return false;
    }
    // The failure notes and the baseline stay. A retry cites the new sha
    // on this issue; it does not finish the row or replace its start.
    let _ = cite_row(&mut book, &key, repo);
    stamp_touch(&mut book, &key, unix_secs());
    store_book(&path, &book);
    true
}

fn open_row_for_repo(repo: &str) -> Option<(PathBuf, String)> {
    let mut best: Option<((u64, u128), PathBuf, String)> = None;
    for path in book_files() {
        let book = load_book(&path);
        let rank = row_rank(&path, &book);
        for (key, row) in &book.repos {
            if row.finished || row.issue.is_none() || !same_checkout(key, repo) {
                continue;
            }
            let take = best.as_ref().is_none_or(|(when, _, _)| rank >= *when);
            if take {
                best = Some((rank, path.clone(), key.clone()));
            }
        }
    }
    best.map(|(_, path, key)| (path, key))
}

fn row_rank(path: &Path, book: &Book) -> (u64, u128) {
    let modified = std::fs::metadata(path)
        .and_then(|meta| meta.modified())
        .ok()
        .and_then(|when| when.duration_since(std::time::UNIX_EPOCH).ok())
        .map(|elapsed| elapsed.as_nanos())
        .unwrap_or(0);
    (book.last_unix, modified)
}

fn same_checkout(left: &str, right: &str) -> bool {
    if left == right {
        return true;
    }
    match (std::fs::canonicalize(left), std::fs::canonicalize(right)) {
        (Ok(left), Ok(right)) => left == right,
        _ => false,
    }
}

/// A file deed's accession has to start with `deed-file-`. The sha keeps
/// each commit's id distinct; `deed-file-commit` alone is one frozen deed.
fn deed_id(sha: &str) -> String {
    format!("deed-file-commit-{sha}")
}

fn cite_deed(issue: &str, sha: &str) -> Result<(), String> {
    let dir = super::runtime_dir();
    let _ = std::fs::create_dir_all(&dir);
    let path = dir.join(format!("deed-{sha}.txt"));
    std::fs::write(&path, format!("{sha}\n")).map_err(|e| e.to_string())?;
    let seat = super::holder_name();
    let id = deed_id(sha);
    let said = run_timed(
        "deedar",
        &[
            "create",
            "file",
            "--id",
            &id,
            "--name",
            sha,
            "--path",
            &path.display().to_string(),
            "--agent",
            &seat,
        ],
        &[("VISSUE_AGENT", seat.as_str())],
    )
    .map_err(|e| e.to_string())?;
    let accession = parse_deed(&said.stdout)
        .ok_or_else(|| format!("deedar printed no accession: {}", said.stdout.trim()))?;
    run_timed(
        "vissue",
        &["deed", issue, "--add", &accession],
        &[("VISSUE_AGENT", seat.as_str())],
    )
    .map_err(|e| e.to_string())?;
    let line = super::persist_tracker(issue, "cited a deed");
    if line.contains("could not") || line.contains("refused") {
        return Err(line.trim().to_string());
    }
    Ok(())
}

/// A short-lived hook must not replace the runner that owns the sitting.
/// Session start and a new prompt are that runner. A pid of zero has never
/// been set, so the first call of any kind may set it.
fn next_owner_pid(event: &str, current: u32, incoming: u32) -> u32 {
    if current == 0 || matches!(event, "SessionStart" | "UserPromptSubmit") {
        incoming
    } else {
        current
    }
}

/// The runner that spawned this hook. When it is gone, the next session
/// finishes the claims this book still has open.
fn hook_owner() -> u32 {
    // SAFETY: getppid only reads the parent pid.
    unsafe { libc::getppid() as u32 }
}
/// How long the sweeps over past sittings may take in one hook call. They
/// walk every book the seat has kept, and the landed check runs git once per
/// cited commit, so the walk grows with the seat's history. Books the walk
/// does not reach are the next call's, most recently written first.
const SWEEP_BUDGET: std::time::Duration = std::time::Duration::from_millis(1000);

/// Finish every other sitting whose runner has exited. A sitting that
/// never claimed still counts when a tool failed or the guard asked and
/// the lesson has not been written.
fn finish_orphans(current: &str, deadline: std::time::Instant) {
    let keep = book_path(current);
    for path in book_files() {
        if path == keep {
            continue;
        }
        if std::time::Instant::now() >= deadline {
            break;
        }
        let mut book = load_book(&path);
        let open = book.repos.values().any(sitting_open);
        if !open || book.owner_pid == 0 || super::pid_alive(book.owner_pid) {
            continue;
        }
        finish_open(&mut book);
        store_book(&path, &book);
    }
}

/// Replace a cited commit that is not in HEAD with the commit that is, and
/// write the lesson again when it already named the one that did not land.
fn refresh_landed_deeds(deadline: std::time::Instant) {
    let mut heads = Heads::new();
    for path in book_files() {
        if std::time::Instant::now() >= deadline {
            break;
        }
        let mut book = load_book(&path);
        let repos: Vec<String> = book.repos.keys().cloned().collect();
        let mut changed = false;
        let mut cached = false;
        for repo in repos {
            changed |= reconcile_deeds(&mut book, &repo, deadline, &mut heads, &mut cached);
        }
        if !changed {
            if cached {
                store_book(&path, &book);
            }
            continue;
        }
        let repos: Vec<String> = book.repos.keys().cloned().collect();
        for repo in repos {
            let Some(row) = book.repos.get(&repo) else {
                continue;
            };
            if !row.finished || row.lesson {
                continue;
            }
            let Some(issue) = row.issue.clone() else {
                continue;
            };
            let heard = heard_title(&book, &repo, row);
            let title = title_from(&heard, &repo);
            let deeds = row.deeds.clone();
            let failures = row.failures.clone();
            let asks = row.asks.clone();
            match write_lesson(&issue, &title, &deeds, &failures, &asks) {
                Ok(()) => {
                    if let Some(row) = book.repos.get_mut(&repo) {
                        row.lesson = true;
                    }
                }
                Err(e) => log_line(&format!("lesson: {e}")),
            }
        }
        store_book(&path, &book);
    }
}

/// Unfinished claims already on disk, for a prompt that has not waited on
/// the pack. Empty when none are held, so a quiet seat does not say `none`.
#[must_use]
pub fn prompt_claims() -> String {
    let mut ids = Vec::new();
    for path in book_files() {
        let book = load_book(&path);
        for row in book.repos.values() {
            if row.finished {
                continue;
            }
            if let Some(issue) = row
                .issue
                .as_deref()
                .map(str::trim)
                .filter(|id| !id.is_empty())
            {
                ids.push(issue.to_string());
            }
        }
    }
    ids.sort();
    ids.dedup();
    if ids.is_empty() {
        String::new()
    } else {
        format!("claims: {}", ids.join(" "))
    }
}

/// The books, most recently written first: a sitting that ended a moment ago
/// is the one a sweep is likely to find work in.
fn book_files() -> Vec<PathBuf> {
    let Ok(entries) = std::fs::read_dir(super::runtime_dir()) else {
        return Vec::new();
    };
    let mut out = Vec::new();
    for entry in entries.flatten() {
        let name = entry.file_name();
        let name = name.to_string_lossy();
        if name.starts_with("book-") && name.ends_with(".json") {
            let written = entry
                .metadata()
                .and_then(|m| m.modified())
                .unwrap_or(std::time::UNIX_EPOCH);
            out.push((written, entry.path()));
        }
    }
    out.sort_by_key(|row| std::cmp::Reverse(row.0));
    out.into_iter().map(|(_, path)| path).collect()
}

/// HEAD of each checkout, asked once per sweep: the books of a seat share a
/// few checkouts, and a row's cached answer stands while its HEAD does.
type Heads = std::collections::HashMap<String, Option<String>>;

/// Drop deed shas that are not ancestors of HEAD, then cite HEAD when the
/// sitting had cited one that never landed. `false` when nothing changed,
/// or when git could not say. The shas found in HEAD are remembered with
/// the HEAD they were found in, so a later sweep asks git again only when
/// HEAD has moved (an amend, a rebase); `cached` says a row grew.
fn reconcile_deeds(
    book: &mut Book,
    repo: &str,
    deadline: std::time::Instant,
    heads: &mut Heads,
    cached: &mut bool,
) -> bool {
    let Some(row) = book.repos.get(repo) else {
        return false;
    };
    if row.deeds.is_empty() || row.issue.is_none() {
        return false;
    }
    let head = heads
        .entry(repo.to_string())
        .or_insert_with(|| head_sha(repo).ok())
        .clone();
    let same_head = head.is_some() && row.landed_head == head;
    let mut kept = Vec::new();
    for sha in &row.deeds {
        if same_head && row.landed.contains(sha) {
            kept.push(sha.clone());
            continue;
        }
        if std::time::Instant::now() >= deadline {
            return false;
        }
        match sha_landed(repo, sha) {
            Some(true) => kept.push(sha.clone()),
            Some(false) => {}
            None => return false,
        }
    }
    let all_landed = kept.len() == row.deeds.len();
    if head.is_some() && !(same_head && all_landed) {
        if let Some(row) = book.repos.get_mut(repo) {
            row.landed.clone_from(&kept);
            row.landed_head = head;
        }
        *cached = true;
    }
    if all_landed {
        return false;
    }
    if let Some(row) = book.repos.get_mut(repo) {
        row.deeds = kept;
        row.lesson = false;
    }
    let _ = ensure_deed(book, repo);
    true
}

/// `Some` when git could answer. `None` when this directory is not a
/// checkout, so a missing git does not wipe a deed.
fn sha_landed(repo: &str, sha: &str) -> Option<bool> {
    match run_timed(
        "git",
        &["-C", repo, "merge-base", "--is-ancestor", sha, "HEAD"],
        &[],
    ) {
        Ok(_) => Some(true),
        Err(e) => {
            let text = format!("{e:#}");
            if text.contains("not a git repository") || text.contains("not on PATH") {
                None
            } else {
                Some(false)
            }
        }
    }
}

/// Remember HEAD the first time this sitting sees the repository.
fn note_start(book: &mut Book, repo: &str) {
    if repo.is_empty() {
        return;
    }
    if book
        .repos
        .get(repo)
        .and_then(|row| row.start_sha.as_deref())
        .is_some()
    {
        return;
    }
    let Ok(sha) = head_sha(repo) else {
        return;
    };
    book.repos.entry(repo.to_string()).or_default().start_sha = Some(sha);
}

/// A claim still open, or failures and asks with no lesson yet. A sitting
/// that never claimed still has a lesson to write when a tool failed or
/// the guard asked.
fn sitting_open(row: &RepoBook) -> bool {
    let notes = !row.failures.is_empty() || !row.asks.is_empty();
    (row.issue.is_some() && !row.finished) || (notes && !row.lesson)
}

fn head_sha(repo: &str) -> Result<String, String> {
    let said =
        run_timed("git", &["-C", repo, "rev-parse", "HEAD"], &[]).map_err(|e| e.to_string())?;
    let sha = said.stdout.trim().to_string();
    if sha.len() < 7 || !sha.chars().all(|c| c.is_ascii_hexdigit()) {
        return Err(format!("HEAD is not a sha: {sha}"));
    }
    Ok(sha)
}

/// A row that never held an issue and has nothing to say: the prompt hook
/// opened it with a start sha and a title, and no edit or commit claimed.
/// A row with failures or asks stays, since its lesson and the failures it
/// booked are the sitting's record.
fn unclaimed_row(row: &RepoBook) -> bool {
    row.issue.is_none() && row.deeds.is_empty() && row.failures.is_empty() && row.asks.is_empty()
}

/// Drop the rows of a sitting that ended without a claim, so no book keeps
/// a row whose issue is null. The next prompt opens a fresh one.
fn drop_unclaimed_rows(book: &mut Book) {
    book.repos.retain(|_, row| !unclaimed_row(row));
    book.cwd_repo
        .retain(|_, repo| book.repos.contains_key(repo));
}

fn finish_open(book: &mut Book) {
    let repos: Vec<String> = book.repos.keys().cloned().collect();
    finish_rows(book, &repos);
    book.prompt.clear();
    book.prompt_repo.clear();
    book.prompt_unix = 0;
}

fn finish_rows(book: &mut Book, repos: &[String]) {
    for repo in repos {
        let mut cached = false;
        let in_a_minute = std::time::Instant::now() + std::time::Duration::from_secs(60);
        let _ = reconcile_deeds(book, repo, in_a_minute, &mut Heads::new(), &mut cached);
        let Some(row) = book.repos.get(repo) else {
            continue;
        };
        let issue = row.issue.clone();
        let notes = !row.failures.is_empty() || !row.asks.is_empty();
        let finished = row.finished;
        // A claim closes with a lesson. So does a sitting that only failed
        // or was asked: the next session otherwise has nothing to recall.
        if !row.lesson && (issue.is_some() || notes) {
            let heard = heard_title(book, repo, row);
            let title = title_from(&heard, repo);
            let deeds = row.deeds.clone();
            let failures = row.failures.clone();
            let asks = row.asks.clone();
            let label = issue.clone().unwrap_or_default();
            match write_lesson(&label, &title, &deeds, &failures, &asks) {
                Ok(()) => {
                    if let Some(row) = book.repos.get_mut(repo) {
                        row.lesson = true;
                    }
                }
                Err(e) => log_line(&format!("lesson: {e}")),
            }
        }
        let also = book
            .repos
            .get_mut(repo)
            .map(|row| std::mem::take(&mut row.also))
            .unwrap_or_default();
        for other in &also {
            if let Err(e) = hand_back(other) {
                log_line(&format!("finish: {e}"));
            }
        }
        let Some(issue) = issue else {
            continue;
        };
        if finished {
            continue;
        }
        let named = book.repos.get(repo).is_some_and(|row| row.named);
        let done = if named {
            hand_back(&issue)
        } else {
            close_issue(&issue)
        };
        match done {
            Ok(()) => {
                if let Some(row) = book.repos.get_mut(repo) {
                    row.finished = true;
                }
            }
            Err(e) => log_line(&format!("finish: {e}")),
        }
    }
}

/// The ticket is done, the claim is released, the tracker commit says
/// finished. The lesson was written just before this, from the sitting.
fn close_issue(issue: &str) -> Result<(), String> {
    run_timed("vissue", &["update", issue, "-s", "DONE"], &[]).map_err(|e| e.to_string())?;
    let assignee = super::resolve_assignee(None);
    if which::which("claimdag").is_ok() {
        if let Err(e) = super::release(issue, &assignee) {
            log_line(&format!("release: {e:#}"));
        }
    }
    let line = super::persist_tracker(issue, "finished");
    if line.contains("could not") || line.contains("refused") {
        return Err(line.trim().to_string());
    }
    Ok(())
}

/// Release a claim the git hook took on an issue a commit named. The
/// issue goes back to the state it had before the claim, as `ljos release`
/// leaves it, and stays open: naming a ticket in a commit is not accepting
/// the work on it.
fn hand_back(issue: &str) -> Result<(), String> {
    let assignee = super::resolve_assignee(None);
    if which::which("claimdag").is_ok() {
        if let Err(e) = super::release(issue, &assignee) {
            log_line(&format!("release: {e:#}"));
            if let Err(e) = super::unstamp_tracker(issue, &assignee, true) {
                log_line(&format!("release: {e:#}"));
            }
        }
    } else if let Err(e) = super::unstamp_tracker(issue, &assignee, true) {
        log_line(&format!("release: {e:#}"));
    }
    let line = super::persist_tracker(issue, "released");
    if line.contains("could not") || line.contains("refused") {
        return Err(line.trim().to_string());
    }
    Ok(())
}

/// The most ids a commit message is checked for. Each one is a tracker read.
const NAMED_IDS_MAX: usize = 8;

/// The first id in `message` that names an issue the tracker holds and
/// has not closed: `ljos-policyd-32fx: ...` in a subject, `Fixes ljos-xsor`
/// in a body. A word shaped like an id (`fix-hook`) that the tracker does
/// not know is not one, and a DONE or CANCELLED issue is not reopened.
#[must_use]
pub fn named_open_issue(message: &str) -> Option<String> {
    named_open_issue_with(message, |id| {
        super::issue_record(id).ok().and_then(|v| {
            (v["id"].as_str() == Some(id)).then(|| v["state"].as_str().unwrap_or("").to_string())
        })
    })
}

/// [`named_open_issue`] with the tracker read passed in: `state` gives the
/// issue's state, `None` when the tracker does not hold it.
fn named_open_issue_with(message: &str, state: impl Fn(&str) -> Option<String>) -> Option<String> {
    let mut seen: Vec<String> = Vec::new();
    for raw in message.split_whitespace() {
        let token = raw.trim_matches(|c: char| {
            matches!(
                c,
                ',' | '.'
                    | ':'
                    | ';'
                    | '!'
                    | '?'
                    | '"'
                    | '\''
                    | '`'
                    | '('
                    | ')'
                    | '['
                    | ']'
                    | '{'
                    | '}'
                    | '<'
                    | '>'
                    | '#'
            )
        });
        if !is_issue_id(token) || seen.iter().any(|s| s == token) {
            continue;
        }
        if seen.len() >= NAMED_IDS_MAX {
            break;
        }
        seen.push(token.to_string());
        if !matches!(state(token).as_deref(), Some("DONE" | "CANCELLED") | None) {
            return Some(token.to_string());
        }
    }
    None
}

/// Book the commit at `head` in `repo` on `issue`, an open issue its
/// message named, instead of filing a new one. The sitting that already
/// holds the checkout keeps its row; otherwise the seat's book does. The
/// claim is taken unless that row already holds the issue, and the deed is
/// cited on the issue. A row holding another issue keeps it, and the named
/// one is released with it at the end of the sitting.
pub(crate) fn book_named_commit(repo: &str, head: &str, issue: &str) {
    let _held = super::CommitLock::acquire(&super::runtime_dir().join("book.lock"));
    let (path, key) =
        open_row_for_repo(repo).unwrap_or_else(|| (book_path(&sitting_key()), repo.to_string()));
    let mut book = load_book(&path);
    book_named_in(&mut book, &key, repo, head, issue);
    store_book(&path, &book);
}

/// The commit `repo`'s HEAD message names an open issue: that id and the
/// sha. A harness hook reads it once the commit has landed.
fn named_head(repo: &str) -> Option<(String, String)> {
    let said = run_timed("git", &["-C", repo, "log", "-1", "--format=%H%n%B"], &[]).ok()?;
    let (sha, message) = said.stdout.split_once('\n')?;
    let sha = sha.trim();
    if sha.is_empty() {
        return None;
    }
    named_open_issue(message).map(|issue| (issue, sha.to_string()))
}

/// [`book_named_commit`] on a book already loaded under the book lock, at
/// row `key`. The git hook and a harness hook both book through this, so a
/// commit naming an open issue is claimed and cited the same way whichever
/// of them saw it.
fn book_named_in(book: &mut Book, key: &str, repo: &str, head: &str, issue: &str) {
    let key = key.to_string();
    let now = unix_secs();
    let row = book.repos.entry(key.clone()).or_default();
    let open = row.issue.clone().filter(|_| !row.finished);
    let holds = open.as_deref() == Some(issue);
    let held_also = row.also.iter().any(|other| other == issue);
    // The issue a hook filed for this sitting's first edit, with no deed
    // yet, was a placeholder: the commit says which ticket the work is on.
    // It is cancelled before the named one is claimed, so a claim graph
    // that holds one node per assignee takes the named one.
    let placeholder = open
        .clone()
        .filter(|held| held != issue && !held_also && empty_filed_row(row, held));
    if let Some(auto) = &placeholder {
        cancel_placeholder(auto, issue);
    }
    let open = if placeholder.is_some() { None } else { open };
    if !holds && !held_also {
        match claim_existing(issue) {
            Ok(()) => {
                let line = super::persist_tracker(issue, "claimed");
                if line.contains("could not") || line.contains("refused") {
                    log_line(line.trim());
                }
            }
            Err(e) => log_line(&format!("claim: {issue}: {e}")),
        }
    }
    let cited = cite_deed(issue, head);
    if let Err(e) = &cited {
        log_line(&format!("deed: {e}"));
    }
    let row = book.repos.entry(key.clone()).or_default();
    match open {
        Some(ref held) if held == issue => {
            if cited.is_ok() && !row.deeds.iter().any(|seen| seen == head) {
                row.deeds.push(head.to_string());
            }
        }
        Some(_) => {
            if !held_also {
                row.also.push(issue.to_string());
            }
            if !row.elsewhere.iter().any(|seen| seen == head) {
                row.elsewhere.push(head.to_string());
            }
        }
        None if placeholder.is_some() => {
            row.issue = Some(issue.to_string());
            row.named = true;
            row.filed = false;
            row.started = false;
            row.finished = false;
            row.lesson = false;
            row.recall = recall_line(issue);
            row.elsewhere.retain(|seen| seen != head);
            if cited.is_ok() && !row.deeds.iter().any(|seen| seen == head) {
                row.deeds.push(head.to_string());
            }
        }
        None => {
            *row = RepoBook {
                issue: Some(issue.to_string()),
                named: true,
                deeds: if cited.is_ok() {
                    vec![head.to_string()]
                } else {
                    Vec::new()
                },
                start_sha: Some(head.to_string()),
                recall: recall_line(issue),
                ..RepoBook::default()
            };
        }
    }
    book.last_unix = now;
    if !repo.is_empty() {
        book.last_repo = repo.to_string();
    }
    stamp_touch(book, &key, now);
}

/// Whether `row` holds `held` as a placeholder: a hook filed it, no commit
/// is booked on it here or in the tracker, and the tracker has it STARTED
/// under this holder. An issue someone else holds, or one with a deed, is
/// real work and stays.
fn empty_filed_row(row: &RepoBook, held: &str) -> bool {
    if !row.filed || row.named || row.started || !row.deeds.is_empty() {
        return false;
    }
    if !held_by_this_seat(held) {
        return false;
    }
    super::issue_record(held)
        .is_ok_and(|v| v["deeds"].as_array().is_none_or(|deeds| deeds.is_empty()))
}

/// Cancel `auto`, the placeholder a hook filed, now that a commit named
/// `named`. The claim is released first, and the tracker commit and the
/// log say why. A claim graph's release hands the issue back to TODO, so
/// the cancel takes STARTED or TODO and leaves any other state alone.
fn cancel_placeholder(auto: &str, named: &str) {
    let assignee = super::resolve_assignee(None);
    if which::which("claimdag").is_ok() {
        if let Err(e) = super::release(auto, &assignee) {
            log_line(&format!("release: {e:#}"));
        }
    }
    let state = super::issue_record(auto)
        .ok()
        .and_then(|v| v["state"].as_str().map(str::to_string))
        .unwrap_or_default();
    if !matches!(state.as_str(), "STARTED" | "TODO") {
        log_line(&format!(
            "claim: left {auto} {state}, not a placeholder now"
        ));
        return;
    }
    match run_timed(
        "vissue",
        &["update", auto, "-s", "CANCELLED", "--if-state", &state],
        &[],
    ) {
        Ok(_) => {
            let line = super::persist_tracker(auto, "cancelled");
            if line.contains("could not") || line.contains("refused") {
                log_line(line.trim());
            }
            log_line(&format!(
                "claim: cancelled {auto}, filed for this sitting with no deed; the commit named {named}"
            ));
        }
        Err(e) => log_line(&format!("claim: could not cancel {auto}: {e}")),
    }
}

/// Remember a guard ask on this repository. The book file is the only
/// write: a slow tracker must not sit on the path that is about to ask.
pub fn note_ask(raw: &str, call: &super::HookCall, reason: &str) {
    if !matches!(call.event.as_str(), "PreToolUse" | "argv") {
        return;
    }
    let reason = collapse(reason);
    if reason.is_empty() {
        return;
    }
    let value: Value = serde_json::from_str(raw.trim()).unwrap_or(Value::Null);
    let _held = super::CommitLock::acquire(&super::runtime_dir().join("book.lock"));
    let path = book_path(&session_key(call));
    let mut book = load_book(&path);
    let repo = repo_key(&mut book, &value);
    // The ask is the call that did not run. Remember HEAD now, because the
    // after hook is a later process and must not cite this commit.
    note_start(&mut book, &repo);
    let now = unix_secs();
    let row = book.repos.entry(repo).or_default();
    row.last_unix = now;
    let short: String = reason.chars().take(160).collect();
    if row.asks.len() < 4 && !row.asks.iter().any(|seen| seen == &short) {
        row.asks.push(short);
    }
    book.last_unix = now;
    store_book(&path, &book);
}

fn note_failure(book: &mut Book, repo: &str, text: &str) {
    let text = collapse(text);
    if text.is_empty() {
        return;
    }
    let short: String = text.chars().take(160).collect();
    let row = book.repos.entry(repo.to_string()).or_default();
    if row.failures.len() < 4 && !row.failures.iter().any(|seen| seen == &short) {
        row.failures.push(short);
    }
}

fn failure_text(raw: &Value, cue: &str) -> String {
    let err = raw
        .pointer("/tool_response/error")
        .and_then(Value::as_str)
        .or_else(|| raw.get("error").and_then(Value::as_str))
        .or_else(|| raw.get("error_message").and_then(Value::as_str))
        .unwrap_or("")
        .trim();
    if !err.is_empty() {
        return err.to_string();
    }
    if !cue.trim().is_empty() {
        return cue.trim().to_string();
    }
    "a tool failed".to_string()
}

/// One standing lesson, agent-derived, with the writer in the atom source.
/// Two short sentences: the ticket and its commits, then the failing
/// command and the guard's rule when the sitting had them. The full title,
/// rule and command also ride in `source`, which the prose gate does not
/// read. The issue id rides in the `issue` field, so a later lesson for
/// another issue does not close this one. A pack that is off is an error
/// here; the caller logs it and still closes the ticket.
fn write_lesson(
    issue: &str,
    title: &str,
    shas: &[String],
    failures: &[String],
    asks: &[String],
) -> Result<(), String> {
    let text = lesson_text(title, issue, shas, failures, asks);
    super::packset_write_agent_sourced(
        "Remember",
        &text,
        Some(false),
        title,
        &join_notes(asks),
        &join_notes(failures),
        issue,
    )
    .map(|_| ())
    .map_err(|e| noted_err(&e))
}

/// The sitting's notes, one per line, for an atom field the prose gate
/// does not read.
fn join_notes(notes: &[String]) -> String {
    notes
        .iter()
        .map(|line| line.trim())
        .filter(|line| !line.is_empty())
        .collect::<Vec<_>>()
        .join("\n")
}

/// The error and its causes, so a refused `POST /v1/atoms` keeps the HTTP
/// status and the body. `Display` on the context alone drops both.
fn noted_err(err: &anyhow::Error) -> String {
    let mut out = String::new();
    for cause in err.chain() {
        let text = cause.to_string();
        if text.is_empty() {
            continue;
        }
        if !out.is_empty() {
            out.push_str(": ");
        }
        out.push_str(&text);
    }
    if out.is_empty() {
        err.to_string()
    } else {
        out
    }
}

/// At most two short sentences. The pack refuses a third sentence, a
/// sentence of thirty words or more, and a readability grade past 14 once
/// the text has twelve words. The title keeps the words a later prompt can
/// match: stopwords and filler go first, and a word is shortened only when
/// the gate still refuses. The rule name and the failing command's verb
/// stay whole. A title that is only filler still leaves a word.
fn lesson_text(
    title: &str,
    issue: &str,
    shas: &[String],
    failures: &[String],
    asks: &[String],
) -> String {
    let issue = issue.trim();
    let shas: Vec<String> = shas
        .iter()
        .take(3)
        .map(|sha| sha.chars().take(7).collect::<String>())
        .filter(|sha| !sha.is_empty())
        .collect();
    let verb = failures.first().map(|text| command_verb(text));
    let rule = asks.iter().find_map(|ask| rule_name(ask));
    let second = second_sentence(verb.as_deref(), rule.as_deref());
    let mut words = title_words(title);
    let mut shortening = true;
    for _ in 0..256 {
        let text = lesson_sentence(&words, issue, &shas, &second);
        if lesson_prose_ok(&text) {
            return text;
        }
        if shortening && shorten_longest(&mut words) {
            continue;
        }
        shortening = false;
        if words.len() <= 1 {
            return text;
        }
        let drop_at = words
            .iter()
            .enumerate()
            .min_by_key(|(i, word)| (word.chars().count(), *i))
            .map(|(i, _)| i)
            .unwrap_or(0);
        words.remove(drop_at);
    }
    lesson_sentence(&words, issue, &shas, &second)
}

/// Runners whose next word is the command a failure should name.
const COMMAND_RUNNERS: &[&str] = &[
    "git", "cargo", "npm", "pnpm", "yarn", "bun", "npx", "pip", "uv", "go", "make", "python",
    "python3", "node",
];

/// Words that describe a failure and are not the command that failed.
fn status_word(word: &str) -> bool {
    matches!(
        word.to_ascii_lowercase().as_str(),
        "exited" | "failed" | "failure" | "error" | "nonzero" | "non-zero"
    )
}

/// The verb of a failing command: `git commit exited non-zero` is `commit`,
/// and `cargo test` is `test`. An error that is not a command names its
/// first distinctive word.
fn command_verb(text: &str) -> String {
    let words = super::shell_words(text);
    if let Some(verb) = runner_subcommand(&words) {
        return verb;
    }
    words
        .into_iter()
        .find(|word| !super::is_lesson_filler(word) && !status_word(word))
        .map(|word| word.to_ascii_lowercase())
        .unwrap_or_else(|| "tool".to_string())
}

/// The subcommand of `git`, `cargo`, `npm` and the other [`COMMAND_RUNNERS`].
fn runner_subcommand(words: &[String]) -> Option<String> {
    let mut i = 0usize;
    if words
        .first()
        .is_some_and(|word| word.eq_ignore_ascii_case("sudo"))
    {
        i += 1;
    }
    let bin = words.get(i)?.rsplit('/').next().unwrap_or("");
    let bin_name = bin.to_ascii_lowercase();
    if !COMMAND_RUNNERS.contains(&bin_name.as_str()) {
        return None;
    }
    i += 1;
    if bin_name == "git" {
        while i < words.len() {
            match words[i].as_str() {
                "-C" | "-c" | "--git-dir" | "--work-tree" => i += 2,
                flag if flag.starts_with("--git-dir=") || flag.starts_with("--work-tree=") => {
                    i += 1;
                }
                flag if flag.starts_with('-') => i += 1,
                other => return Some(other.to_ascii_lowercase()),
            }
        }
        return Some(bin_name);
    }
    Some(
        words
            .iter()
            .skip(i)
            .find(|word| !word.starts_with('-'))
            .map_or(bin_name, |word| word.to_ascii_lowercase()),
    )
}

/// Words of an ask that the sentence already says, so the rule name is the
/// rest: `the guard asked before a force push` names `force push`.
const ASK_BOILER: &[&str] = &["guard", "asked", "about", "tool", "failed", "failure"];

/// One rule token: letters, digits, hyphens, and not a filler word.
fn rule_token(token: &str) -> bool {
    !token.is_empty()
        && token
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
        && token.chars().any(|c| c.is_ascii_alphabetic())
        && !super::is_lesson_filler(token)
}

/// The guard's rule, as `git-force-push` from `git-force-push: a force push…`.
/// Without that token, the first distinctive words of the ask.
fn rule_name(ask: &str) -> Option<String> {
    let ask = ask.trim();
    if ask.is_empty() {
        return None;
    }
    if let Some((head, _)) = ask.split_once(':') {
        let head = head.trim();
        if rule_token(head) {
            return Some(head.to_string());
        }
    }
    for raw in ask.split_whitespace() {
        let token = raw.trim_matches(|c: char| !c.is_ascii_alphanumeric());
        if token.contains('-') && rule_token(token) {
            return Some(token.to_string());
        }
    }
    let named: Vec<String> = title_words(ask)
        .into_iter()
        .filter(|word| !ASK_BOILER.contains(&word.to_ascii_lowercase().as_str()))
        .take(2)
        .collect();
    if named.is_empty() {
        None
    } else {
        Some(named.join(" "))
    }
}

/// `Commit failed and the guard asked about git-force-push.` The rule token
/// and the verb are not shortened with the title.
fn second_sentence(verb: Option<&str>, rule: Option<&str>) -> String {
    match (verb, rule) {
        (Some(verb), Some(rule)) => {
            format!(
                "{} failed and the guard asked about {rule}.",
                capitalize_word(verb)
            )
        }
        (Some(verb), None) => format!("{} failed.", capitalize_word(verb)),
        (None, Some(rule)) => format!("The guard asked about {rule}."),
        (None, None) => String::new(),
    }
}

fn capitalize_word(word: &str) -> String {
    let mut chars = word.chars();
    match chars.next() {
        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
        None => String::new(),
    }
}

/// Distinctive words, in the order the prompt said them. When every word is
/// filler, the first few raw tokens, so the title cannot vanish.
fn title_words(title: &str) -> Vec<String> {
    let words: Vec<String> = title
        .split(|c: char| !c.is_alphanumeric())
        .filter(|word| !word.is_empty() && !super::is_lesson_filler(word))
        .map(str::to_string)
        .collect();
    if !words.is_empty() {
        return words;
    }
    title
        .split(|c: char| !c.is_alphanumeric())
        .filter(|word| !word.is_empty())
        .take(3)
        .map(str::to_string)
        .collect()
}

/// One character off the longest title word, and not below four characters.
/// The rule name and the command verb are not in this list.
fn shorten_longest(words: &mut [String]) -> bool {
    let Some(at) = words
        .iter()
        .enumerate()
        .filter(|(_, word)| word.chars().count() > 4)
        .max_by_key(|(i, word)| (word.chars().count(), *i))
        .map(|(i, _)| i)
    else {
        return false;
    };
    words[at].pop();
    true
}

fn lesson_sentence(words: &[String], issue: &str, shas: &[String], second: &str) -> String {
    let head = words.join(" ");
    let issue = issue.trim();
    let first = if issue.is_empty() {
        // No ticket was filed. The lesson is a sentence about the work,
        // then what went wrong.
        if shas.is_empty() {
            if head.is_empty() {
                String::new()
            } else {
                format!("The session worked on {head}.")
            }
        } else if head.is_empty() {
            format!("Committed {}.", shas.join(" "))
        } else {
            format!("{head} committed {}.", shas.join(" "))
        }
    } else if shas.is_empty() {
        if head.is_empty() {
            format!("Work {issue} closed.")
        } else {
            format!("{head} ({issue}) closed.")
        }
    } else if head.is_empty() {
        format!("Work {issue} committed {}.", shas.join(" "))
    } else {
        format!("{head} ({issue}) committed {}.", shas.join(" "))
    };
    if second.is_empty() {
        first
    } else if first.is_empty() {
        second.to_string()
    } else {
        format!("{first} {second}")
    }
}

/// The pack's prose gate for one atom. A lesson that fails it is not stored,
/// and the next session then has nothing to recall.
fn lesson_prose_ok(text: &str) -> bool {
    packset_core::prose_refuse(text, packset_core::ProseRole::Atom).is_ok()
}

/// Record that `prompt` belongs to `repo`. A later git hook in another
/// checkout can tell the words are not its title.
fn bind_prompt(book: &mut Book, repo: &str, now: u64) {
    if repo.is_empty() || book.prompt.trim().is_empty() {
        return;
    }
    book.prompt_repo = repo.to_string();
    book.prompt_unix = now;
}

/// The prompt the lesson and the claim use for `repo`. The book's prompt
/// is that text only when it was recorded for this checkout.
fn heard_title(book: &Book, repo: &str, row: &RepoBook) -> String {
    if prompt_belongs_to(book, repo) {
        let prompt = book.prompt.trim();
        if !prompt.is_empty() {
            return prompt.to_string();
        }
    }
    row.title.clone().unwrap_or_default()
}

/// Whether the saved prompt is the live one for `repo`. A git hook may
/// title a claim with it. Another repository's prompt, or one from a
/// sitting that has already gone idle, may not.
fn prompt_live_for(book: &Book, repo: &str, now: u64) -> bool {
    if !prompt_belongs_to(book, repo) {
        return false;
    }
    let Some(limit) = sitting_idle() else {
        return true;
    };
    let earlier = book.repos.iter().any(|(key, row)| {
        same_checkout(key, repo) && row_is_idle(now, book, key, row, limit, Some(repo))
    });
    if earlier {
        return false;
    }
    let open = book
        .repos
        .iter()
        .any(|(key, row)| same_checkout(key, repo) && !row.finished && sitting_open(row));
    if open {
        return true;
    }
    // The prompt was recorded for this checkout and no claim is open.
    // An old stamp is the previous sitting; a fresh one is this sitting,
    // still waiting for its first claim.
    let stamped = if book.prompt_unix > 0 {
        book.prompt_unix
    } else {
        book.last_unix
    };
    !idle_due(now, stamped, limit)
}

fn prompt_belongs_to(book: &Book, repo: &str) -> bool {
    let prompt = book.prompt.trim();
    if prompt.is_empty() || repo.is_empty() {
        return false;
    }
    let recorded = book.prompt_repo.trim();
    if !recorded.is_empty() {
        return same_checkout(recorded, repo);
    }
    book.repos.iter().any(|(key, row)| {
        !row.finished
            && same_checkout(key, repo)
            && row
                .title
                .as_deref()
                .is_some_and(|title| title.trim() == prompt)
    })
}

/// Drop the prompt once the repository it belongs to no longer has an open row.
fn release_spent_prompt(book: &mut Book) {
    if book.prompt.trim().is_empty() {
        return;
    }
    let recorded = book.prompt_repo.trim();
    let still = if !recorded.is_empty() {
        book.repos.keys().any(|repo| same_checkout(repo, recorded))
    } else {
        let prompt = book.prompt.trim();
        book.repos.values().any(|row| {
            !row.finished
                && row
                    .title
                    .as_deref()
                    .is_some_and(|title| title.trim() == prompt)
        })
    };
    if !still {
        book.prompt.clear();
        book.prompt_repo.clear();
        book.prompt_unix = 0;
    }
}

/// Whether `row` has been idle past `limit`. A row clock wins. A row with
/// no clock of its own follows the book when that clock is idle, and is
/// idle on a call in a different repository when the book clock is fresh:
/// that fresh clock is the other repository's touch.
fn row_is_idle(
    now: u64,
    book: &Book,
    repo: &str,
    row: &RepoBook,
    limit: Duration,
    current: Option<&str>,
) -> bool {
    if !sitting_open(row) {
        return false;
    }
    if row.last_unix > 0 {
        return idle_due(now, row.last_unix, limit);
    }
    if idle_due(now, book.last_unix, limit) {
        return true;
    }
    matches!(
        current,
        Some(cur) if !cur.is_empty() && book.last_unix > 0 && !same_checkout(cur, repo)
    )
}

fn stamp_touch(book: &mut Book, repo: &str, now: u64) {
    if !repo.is_empty() {
        if let Some(row) = book.repos.get_mut(repo) {
            row.last_unix = now;
        }
    }
    book.last_unix = now;
}

/// Keep the prompt on the repository row. The lesson and a later session
/// read it from there. An empty prompt leaves a title that was already stored.
fn remember_title(book: &mut Book, repo: &str) {
    let prompt: String = collapse(&book.prompt).chars().take(4000).collect();
    if prompt.is_empty() || repo.is_empty() {
        return;
    }
    book.repos.entry(repo.to_string()).or_default().title = Some(prompt);
}

fn title_from(prompt: &str, repo: &str) -> String {
    let forced = std::env::var("LJOS_PROJECT").ok();
    let tracker = std::env::var_os("VISSUE_ROOT").map(PathBuf::from);
    title_at(prompt, repo, forced.as_deref(), tracker.as_deref())
}

/// [`title_from`] with the project inputs passed in. With no prompt the
/// title names the project the issue files under, as [`project_for_at`]
/// picks it, so a clone in `bench-w18b-tfn7` is "Work in bench".
fn title_at(prompt: &str, repo: &str, forced: Option<&str>, tracker: Option<&Path>) -> String {
    let words: String = prompt
        .split_whitespace()
        .take(12)
        .collect::<Vec<_>>()
        .join(" ");
    let title: String = words.chars().take(80).collect();
    if !title.is_empty() {
        return title;
    }
    if repo.trim().is_empty() {
        return "agent work".to_string();
    }
    let project = project_for_at(repo, forced, tracker);
    if project.trim().is_empty() {
        "agent work".to_string()
    } else {
        format!("Work in {project}")
    }
}

fn project_for(repo: &str) -> String {
    let forced = std::env::var("LJOS_PROJECT").ok();
    let tracker = std::env::var_os("VISSUE_ROOT").map(PathBuf::from);
    project_for_at(repo, forced.as_deref(), tracker.as_deref())
}

fn project_for_at(repo: &str, forced: Option<&str>, tracker: Option<&Path>) -> String {
    if let Some(project) = forced.map(str::trim).filter(|project| !project.is_empty()) {
        return project.to_string();
    }
    let remote = git_remote_url(repo);
    if let Some(tracker) = tracker {
        if let Some(project) = match_remote_project(repo, tracker) {
            return project;
        }
    }
    // A clone in a folder of its own name (`bench-w18b-tfn7`) is still the
    // repository its origin names. The folder is the project only when the
    // checkout has no origin.
    if let Some(name) = remote.as_deref().and_then(remote_repo_name) {
        return name;
    }
    if let Some(tracker) = tracker {
        if let Some(project) = sole_project_in(tracker) {
            return project;
        }
    }
    Path::new(repo)
        .file_name()
        .and_then(|name| name.to_str())
        .filter(|name| !name.is_empty())
        .unwrap_or("agent")
        .to_string()
}

/// The project whose recorded remote is this checkout's, else the project
/// named like the repository in that URL. A checkout called `workspace`
/// then files on the existing project instead of a new basename.
fn match_remote_project(repo: &str, tracker: &Path) -> Option<String> {
    let url = git_remote_url(repo)?;
    let want = normalize_remote(&url);
    if want.is_empty() {
        return None;
    }
    let projects = projects_in(tracker);
    for (name, dir) in &projects {
        if project_records_remote(dir, &want) {
            return Some(name.clone());
        }
        if tracker_project_remote(tracker, name).is_some_and(|url| normalize_remote(&url) == want) {
            return Some(name.clone());
        }
    }
    let slug = remote_slug(&want);
    projects
        .into_iter()
        .find(|(name, _)| name.eq_ignore_ascii_case(&slug))
        .map(|(name, _)| name)
}

/// The repository name in an origin URL, as the forge spells it:
/// `https://github.com/leidarljos/bench.git` and `git@github.com:leidarljos/bench`
/// are `bench`. vissue names a project by its directory under the tracker,
/// and `vissue create -p` matches an existing one whatever its case.
/// A local path or `file:` origin names no forge repository, and the
/// folder stays the fallback there.
fn remote_repo_name(url: &str) -> Option<String> {
    let raw = url.trim().trim_end_matches('/');
    if raw.starts_with(['/', '.', '~']) || raw.starts_with("file:") {
        return None;
    }
    let raw = raw.strip_suffix(".git").unwrap_or(raw);
    let name = raw.rsplit(['/', ':']).next()?.trim();
    let ok = !name.is_empty()
        && name
            .chars()
            .next()
            .is_some_and(|c| c.is_ascii_alphanumeric())
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'));
    ok.then(|| name.to_string())
}

fn git_remote_url(repo: &str) -> Option<String> {
    if repo.is_empty() {
        return None;
    }
    let said = run_timed("git", &["-C", repo, "remote", "get-url", "origin"], &[]).ok()?;
    let url = said.stdout.trim();
    if url.is_empty() {
        None
    } else {
        Some(url.to_string())
    }
}

fn normalize_remote(raw: &str) -> String {
    let mut raw = raw.trim().trim_end_matches('/').to_string();
    if let Some(stripped) = raw.strip_suffix(".git") {
        raw = stripped.to_string();
    }
    for prefix in ["ssh://", "git://", "https://", "http://"] {
        if let Some(rest) = raw.strip_prefix(prefix) {
            raw = rest.to_string();
            break;
        }
    }
    // userinfo@host, including a token a credential helper wrote in front
    // of the host. The host and the path are the remote.
    if let Some((user, host)) = raw.split_once('@') {
        if !user.contains('/') {
            raw = host.to_string();
        }
    }
    if let Some((host, path)) = raw.split_once(':') {
        if !host.contains('/') {
            raw = format!("{host}/{}", path.trim_start_matches('/'));
        }
    }
    raw.to_ascii_lowercase()
}

fn remote_slug(normalized: &str) -> String {
    normalized
        .rsplit('/')
        .next()
        .unwrap_or(normalized)
        .to_string()
}

fn project_records_remote(dir: &Path, want: &str) -> bool {
    recorded_remotes(dir)
        .iter()
        .any(|url| normalize_remote(url) == want)
}

/// Remotes this project recorded on purpose. A `#+REMOTE:` header, a
/// one-url line in `remote.url` or `repo.url`, or a `remote` field in
/// `project.toml`. A URL in a note is not a record.
fn recorded_remotes(dir: &Path) -> Vec<String> {
    let mut out = Vec::new();
    if let Ok(text) = std::fs::read_to_string(dir.join("issues.org")) {
        for line in text.lines() {
            if let Some(url) = header_remote(line) {
                out.push(url);
            }
        }
    }
    for name in ["remote.url", "repo.url"] {
        let Ok(text) = std::fs::read_to_string(dir.join(name)) else {
            continue;
        };
        for line in text.lines() {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') || line.contains(char::is_whitespace) {
                continue;
            }
            out.push(line.to_string());
        }
    }
    out.extend(toml_remotes(&dir.join("project.toml")));
    out
}

/// `#+REMOTE: url` in an org file. The rest of the file is notes.
fn header_remote(line: &str) -> Option<String> {
    let rest = line.trim().strip_prefix("#+")?;
    let (key, value) = rest.split_once(':')?;
    if !key.eq_ignore_ascii_case("REMOTE") {
        return None;
    }
    let value = value.trim().trim_matches('"').trim();
    if value.is_empty() {
        None
    } else {
        Some(value.to_string())
    }
}

fn toml_remotes(path: &Path) -> Vec<String> {
    let Ok(text) = std::fs::read_to_string(path) else {
        return Vec::new();
    };
    let Ok(value) = toml::from_str::<toml::Value>(&text) else {
        return Vec::new();
    };
    let mut out = Vec::new();
    push_remote(&mut out, &value);
    if let Some(project) = value.get("project") {
        push_remote(&mut out, project);
    }
    out
}

fn push_remote(out: &mut Vec<String>, value: &toml::Value) {
    let Some(url) = value.get("remote").and_then(toml::Value::as_str) else {
        return;
    };
    let url = url.trim();
    if !url.is_empty() {
        out.push(url.to_string());
    }
}

/// `remote` under `[projects.<name>]` in the tracker's `vissue.toml`.
fn tracker_project_remote(tracker: &Path, project: &str) -> Option<String> {
    let text = std::fs::read_to_string(tracker.join("vissue.toml")).ok()?;
    let value: toml::Value = toml::from_str(&text).ok()?;
    let url = value
        .get("projects")?
        .get(project)?
        .get("remote")?
        .as_str()?
        .trim();
    if url.is_empty() {
        None
    } else {
        Some(url.to_string())
    }
}

fn projects_in(root: &Path) -> Vec<(String, PathBuf)> {
    let mut found = Vec::new();
    let mut consider = |dir: PathBuf| {
        if dir.join("issues.org").is_file() {
            if let Some(name) = dir.file_name().and_then(|name| name.to_str()) {
                found.push((name.to_string(), dir));
            }
        }
    };
    let Ok(entries) = std::fs::read_dir(root) else {
        return found;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if entry.file_name() == "Software" {
            if let Ok(children) = std::fs::read_dir(&path) {
                for child in children.flatten() {
                    consider(child.path());
                }
            }
        } else {
            consider(path);
        }
    }
    found
}

fn sole_project_in(root: &Path) -> Option<String> {
    let mut found: Vec<String> = projects_in(root)
        .into_iter()
        .map(|(name, _)| name)
        .collect();
    found.sort();
    found.dedup();
    (found.len() == 1).then(|| found.remove(0))
}

/// Recall for the claim this session filed. The pack is not searched:
/// that walk is what makes a cold prompt hook slow, and an issue with no
/// memories would then add nothing. The title is the working set the hook
/// can name without the pack.
fn recall_line(issue: &str) -> String {
    let head = format!("Recall for {issue} (`ljos recall {issue}` shows its full working set):");
    match super::tracker_show_json(issue) {
        Ok(card) => match card.get("title").and_then(Value::as_str) {
            Some(title) if !title.trim().is_empty() => format!("{head}\n{title}"),
            _ => head,
        },
        Err(_) => head,
    }
}

/// The SessionStart brief, once per conversation, on stderr. A second call
/// in the same conversation prints nothing. A temp sandbox and `LJOS_OFF`
/// print nothing. This does not wait on the pack when it is off.
pub fn print_brief_once() {
    if ljos_off() || home_or_cwd_is_temp() {
        return;
    }
    let path = brief_mark(&brief_key());
    if path.exists() {
        return;
    }
    if let Some(dir) = path.parent() {
        let _ = std::fs::create_dir_all(dir);
    }
    if std::fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&path)
        .is_err()
    {
        return;
    }
    let text = seat_brief();
    if text.is_empty() {
        return;
    }
    eprintln!("{text}");
    let _ = std::io::Write::flush(&mut std::io::stderr());
}

fn brief_key() -> String {
    let seat = std::env::var("LJOS_SEAT")
        .ok()
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty())
        .unwrap_or_else(|| "seat".into());
    let convo = std::env::var("CURSOR_CONVERSATION_ID")
        .ok()
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty())
        .or_else(|| {
            std::env::var("LJOS_SHELL_SESSION")
                .ok()
                .map(|value| value.trim().to_string())
                .filter(|value| !value.is_empty())
        })
        .unwrap_or_else(process_sid);
    format!("{seat}:{convo}")
}

fn process_sid() -> String {
    // SAFETY: getsid reads this process's session id.
    let sid = unsafe { libc::getsid(0) };
    if sid > 0 {
        sid.to_string()
    } else {
        std::process::id().to_string()
    }
}

fn brief_mark(key: &str) -> PathBuf {
    let safe: String = key
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
                c
            } else {
                '_'
            }
        })
        .collect();
    super::runtime_dir().join("brief").join(safe)
}

fn seat_brief() -> String {
    format!(
        "claims: {}\nrecall: {}\nmail: {}",
        held_claims_line(),
        brief_recall_line(),
        brief_mail_line()
    )
}

fn held_claims_line() -> String {
    let book = load_book(&book_path(&sitting_key()));
    let mut ids: Vec<String> = book
        .repos
        .values()
        .filter(|row| !row.finished)
        .filter_map(|row| row.issue.clone())
        .collect();
    ids.sort();
    ids.dedup();
    if ids.is_empty() {
        "none".into()
    } else {
        ids.join(" ")
    }
}

fn brief_recall_line() -> String {
    let book = load_book(&book_path(&sitting_key()));
    for row in book.repos.values() {
        if row.finished {
            continue;
        }
        if let Some(title) = row
            .title
            .as_deref()
            .map(str::trim)
            .filter(|t| !t.is_empty())
        {
            return one_line(title);
        }
        if !row.recall.trim().is_empty() {
            return one_line(&row.recall);
        }
    }
    "none".into()
}

fn brief_mail_line() -> String {
    let url = std::env::var("PACKSET_URL").unwrap_or_default();
    let url = url.trim();
    if url.is_empty() || url == "off" {
        return "none".into();
    }
    let (text, _) = super::mail::prompt_note();
    let line = one_line(&text);
    if line.is_empty() || line.contains("nothing unread") {
        "none".into()
    } else {
        line
    }
}

/// One line for the commit hook when the sitting's title bears on the
/// message. Empty when nothing filed matches.
#[must_use]
pub fn commit_recall_line(session: &str, repo: &str, subject: &str) -> Option<String> {
    let book = load_book(&book_path(session));
    let row = book.repos.get(repo).filter(|row| row.issue.is_some())?;
    let title = row
        .title
        .clone()
        .filter(|title| !title.trim().is_empty())
        .unwrap_or_else(|| subject.trim().to_string());
    let body = format!("{title}\n{}", row.recall);
    if !relevant(subject, &body) {
        return None;
    }
    let line = one_line(&title);
    if line.is_empty() {
        None
    } else {
        Some(format!("recall: {line}"))
    }
}

fn relevant(subject: &str, body: &str) -> bool {
    let subject = subject.trim();
    if subject.is_empty() {
        return false;
    }
    let body = body.to_ascii_lowercase();
    if body.contains(&subject.to_ascii_lowercase()) {
        return true;
    }
    subject
        .split(|c: char| !c.is_alphanumeric())
        .filter(|word| word.len() >= 4)
        .any(|word| body.contains(&word.to_ascii_lowercase()))
}

fn one_line(text: &str) -> String {
    text.split_whitespace().collect::<Vec<_>>().join(" ")
}

/// How a PostToolUse names the command's exit. Codex 0.163 sends the
/// output as a string and records `exit_code` in the transcript, under the
/// same `call_id` as the hook's `tool_use_id`.
#[derive(Clone, Copy)]
enum CommandExit {
    /// A code from the payload or the transcript.
    Code(i64),
    /// The output was text, and neither the payload nor the transcript
    /// named a code. Unknown is not a failure. Other evidence decides.
    Unknown,
    /// The runner sent an object, or omitted the output, and named no code.
    Absent,
}

/// A code the transcript or the payload named, and it was not zero.
fn command_failed(exit: CommandExit) -> bool {
    matches!(exit, CommandExit::Code(code) if code != 0)
}

/// Whether this commit landed. An explicit code wins, including a zero
/// beside an error string and a non-zero beside a banner. A missing code
/// is unknown: a git operation, a `[branch sha]` line, then HEAD moving
/// past the recorded start. A guard refusal or an interrupt blocks only
/// that missing-code path, so a command that never ran is not a deed.
fn commit_landed(exit: CommandExit, raw: &Value, repo: &str, start: Option<&str>) -> bool {
    match exit {
        CommandExit::Code(0) => return true,
        CommandExit::Code(_) => return false,
        CommandExit::Unknown | CommandExit::Absent => {}
    }
    if raw
        .pointer("/tool_response/interrupted")
        .and_then(Value::as_bool)
        == Some(true)
        || permission_block(raw)
    {
        return false;
    }
    git_operation_committed(raw) || stdout_has_commit_banner(raw) || head_moved(repo, start)
}

/// `gitOperation.commit` names a sha or a kind that means the commit was
/// written. Claude sends this beside the stdout, and omits the exit code.
fn git_operation_committed(raw: &Value) -> bool {
    [
        "/gitOperation",
        "/git_operation",
        "/tool_response/gitOperation",
        "/tool_response/git_operation",
        "/toolResponse/gitOperation",
    ]
    .iter()
    .any(|slot| raw.pointer(slot).is_some_and(commit_record_landed))
}

fn commit_record_landed(value: &Value) -> bool {
    if value.get("commit").is_some_and(commit_record_landed) {
        return true;
    }
    let sha = value
        .get("sha")
        .and_then(Value::as_str)
        .unwrap_or("")
        .trim();
    if sha_token(sha) {
        return true;
    }
    let kind = value
        .get("kind")
        .and_then(Value::as_str)
        .unwrap_or("")
        .trim();
    matches!(kind, "committed" | "amended" | "cherry-picked")
}

fn sha_token(text: &str) -> bool {
    (7..=40).contains(&text.len()) && text.chars().all(|c| c.is_ascii_hexdigit())
}

fn branch_token(text: &str) -> bool {
    !text.is_empty()
        && text
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '/' | '.' | '_' | '-'))
}

/// Git's `[branch sha]` line, including a root commit and a detached HEAD.
fn stdout_has_commit_banner(raw: &Value) -> bool {
    commit_output(raw)
        .iter()
        .any(|text| text.lines().any(line_has_commit_banner))
}

fn commit_output(raw: &Value) -> Vec<&str> {
    let mut out = Vec::new();
    for key in [
        "tool_response",
        "toolResponse",
        "stdout",
        "stderr",
        "output",
    ] {
        if let Some(text) = raw.get(key).and_then(Value::as_str) {
            out.push(text);
        }
    }
    for slot in [
        "/tool_response/stdout",
        "/tool_response/output",
        "/tool_response/stderr",
        "/toolResponse/stdout",
        "/toolResponse/output",
        "/toolResponse/stderr",
    ] {
        if let Some(text) = raw.pointer(slot).and_then(Value::as_str) {
            out.push(text);
        }
    }
    out
}

fn line_has_commit_banner(line: &str) -> bool {
    let mut from = 0;
    while let Some(rel) = line[from..].find('[') {
        let start = from + rel + 1;
        let Some(end_rel) = line[start..].find(']') else {
            break;
        };
        if banner_inside(&line[start..start + end_rel]) {
            return true;
        }
        from = start;
    }
    false
}

fn banner_inside(inside: &str) -> bool {
    let mut rest = inside.trim();
    if rest.is_empty() {
        return false;
    }
    if let Some(after) = rest.strip_prefix("detached HEAD") {
        rest = after.trim_start();
    } else {
        let Some((branch, after)) = rest.split_once(|c: char| c.is_whitespace()) else {
            return false;
        };
        if !branch_token(branch) {
            return false;
        }
        rest = after.trim_start();
    }
    if let Some(after) = rest.strip_prefix("(root-commit)") {
        rest = after.trim_start();
    }
    let Some((sha, tail)) = rest.split_once(|c: char| c.is_whitespace()) else {
        return sha_token(rest);
    };
    tail.trim().is_empty() && sha_token(sha)
}

/// HEAD is past the sha recorded before this commit. No baseline means
/// this post has not been shown an earlier commit, so movement is not
/// evidence by itself.
fn head_moved(repo: &str, start: Option<&str>) -> bool {
    let Some(start) = start.map(str::trim).filter(|sha| !sha.is_empty()) else {
        return false;
    };
    head_sha(repo).is_ok_and(|head| head != start)
}

/// The exit code for this call. The payload wins. Otherwise the Codex
/// transcript at `transcript_path` is read, time-bounded, and matched on
/// `tool_use_id`. A text `tool_response` with no code is [`CommandExit::Unknown`].
fn command_exit(raw: &Value) -> CommandExit {
    if let Some(code) = explicit_exit(raw) {
        return CommandExit::Code(code);
    }
    if let Some(code) = transcript_exit(raw) {
        return CommandExit::Code(code);
    }
    if response_is_text(raw) {
        return CommandExit::Unknown;
    }
    CommandExit::Absent
}

/// Codex sends the shell output as a string. Other runners send an object,
/// or omit the field, and a missing code there is still success.
fn response_is_text(raw: &Value) -> bool {
    raw.get("tool_response")
        .or_else(|| raw.get("toolResponse"))
        .is_some_and(Value::is_string)
}

fn tool_use_id(raw: &Value) -> Option<&str> {
    ["tool_use_id", "toolUseId", "tool_call_id", "toolCallId"]
        .iter()
        .find_map(|key| raw.get(*key).and_then(Value::as_str))
        .map(str::trim)
        .filter(|id| !id.is_empty())
}

/// `exit_code` for `tool_use_id` in the Codex transcript. Codex 0.163 puts
/// the code on a `CommandExecution` item whose `id` is the call, and only
/// as text (`Process exited with code N`) on the `function_call_output`
/// with that `call_id`. The read is the tail of the file and gives up at
/// [`TRANSCRIPT_DEADLINE`], so a stuck transcript cannot hold the hook.
fn transcript_exit(raw: &Value) -> Option<i64> {
    let path = raw
        .get("transcript_path")
        .and_then(Value::as_str)
        .or_else(|| raw.get("transcriptPath").and_then(Value::as_str))
        .map(str::trim)
        .filter(|path| !path.is_empty())?;
    let call_id = tool_use_id(raw)?;
    let text = read_transcript_tail(&super::expand(path))?;
    exit_for_call(&text, call_id)
}

/// How long a transcript read may take. The same budget as one habitat
/// command: a hook that waits longer is treated as a refusal by the runner.
const TRANSCRIPT_DEADLINE: Duration = COMMAND_DEADLINE;

/// Bytes read from the end of a transcript. The call that just finished is
/// the last one, and a command's output can be long.
const TRANSCRIPT_TAIL_BYTES: u64 = 1024 * 1024;

fn read_transcript_tail(path: &Path) -> Option<String> {
    read_bounded(path, TRANSCRIPT_TAIL_BYTES, true)
}

/// The transcript's tail, bounded in bytes like the exit lookup. Regular
/// files remain readable regardless of their size, so polling alone cannot
/// limit the work. A missing prompt in this window leaves the stored one in use.
pub(crate) fn read_text_bounded(path: &Path) -> Option<String> {
    read_transcript_tail(path)
}

/// Open `path` without blocking and read at most `max_bytes`. A regular
/// file is ready at once. A fifo with no writer reports hangup at once.
/// `tail` keeps the end of a regular file and drops the partial first line.
fn read_bounded(path: &Path, max_bytes: u64, tail: bool) -> Option<String> {
    use std::os::unix::fs::FileTypeExt;
    let mut file = open_nonblock(path)?;
    let kind = file.metadata().ok().map(|meta| meta.file_type());
    // A fifo with no writer reads as immediate EOF. Poll does not say so
    // on this kernel: POLLHUP shows up only after a writer has opened the
    // fifo, so waiting on POLLIN spends the whole deadline.
    if kind.as_ref().is_some_and(|ty| ty.is_fifo()) {
        return read_available(&mut file, max_bytes, Duration::ZERO);
    }
    if kind.as_ref().is_some_and(|ty| ty.is_file()) {
        if tail {
            return read_file_tail(&mut file, max_bytes);
        }
        return read_available(&mut file, max_bytes, TRANSCRIPT_DEADLINE);
    }
    read_available(&mut file, max_bytes, Duration::ZERO)
}

fn open_nonblock(path: &Path) -> Option<std::fs::File> {
    use std::os::unix::ffi::OsStrExt;
    use std::os::unix::io::FromRawFd;
    let bytes = path.as_os_str().as_bytes();
    let c_path = std::ffi::CString::new(bytes).ok()?;
    // SAFETY: `c_path` is NUL-terminated and lives until `open` returns.
    let fd = unsafe {
        libc::open(
            c_path.as_ptr(),
            libc::O_RDONLY | libc::O_NONBLOCK | libc::O_CLOEXEC,
        )
    };
    if fd < 0 {
        return None;
    }
    // SAFETY: `fd` is open and this function owns it.
    Some(unsafe { std::fs::File::from_raw_fd(fd) })
}

fn wait_readable(fd: i32, deadline: Duration) -> bool {
    use std::io::ErrorKind;
    let start = Instant::now();
    loop {
        let elapsed = start.elapsed();
        let left = deadline.saturating_sub(elapsed);
        let ms = i32::try_from(left.as_millis()).unwrap_or(i32::MAX);
        let mut polled = libc::pollfd {
            fd,
            events: libc::POLLIN,
            revents: 0,
        };
        // SAFETY: `polled` is one valid `pollfd` and lives until `poll` returns.
        let rc = unsafe { libc::poll(&mut polled, 1, ms) };
        if rc < 0 {
            let err = std::io::Error::last_os_error();
            if err.kind() == ErrorKind::Interrupted && start.elapsed() < deadline {
                continue;
            }
            return false;
        }
        if rc == 0 {
            return false;
        }
        let rev = polled.revents;
        if (rev & libc::POLLIN) != 0 {
            return true;
        }
        if (rev & (libc::POLLHUP | libc::POLLERR | libc::POLLNVAL)) != 0 {
            return false;
        }
        if start.elapsed() >= deadline {
            return false;
        }
    }
}

fn read_file_tail(file: &mut std::fs::File, max_bytes: u64) -> Option<String> {
    use std::io::{Read, Seek, SeekFrom};
    let len = file.metadata().ok()?.len();
    let start = len.saturating_sub(max_bytes);
    file.seek(SeekFrom::Start(start)).ok()?;
    let mut buf = Vec::new();
    file.take(max_bytes).read_to_end(&mut buf).ok()?;
    let mut text = String::from_utf8_lossy(&buf).into_owned();
    if start > 0 {
        if let Some(pos) = text.find('\n') {
            text.drain(..=pos);
        }
    }
    Some(text)
}

fn read_available(file: &mut std::fs::File, max_bytes: u64, deadline: Duration) -> Option<String> {
    use std::io::{ErrorKind, Read};
    use std::os::unix::io::AsRawFd;
    let start = Instant::now();
    let cap = usize::try_from(max_bytes).unwrap_or(usize::MAX);
    let mut buf = Vec::new();
    let mut tmp = [0u8; 8192];
    while buf.len() < cap {
        let room = cap - buf.len();
        let nread = room.min(tmp.len());
        match file.read(&mut tmp[..nread]) {
            Ok(0) => break,
            Ok(n) => {
                buf.extend_from_slice(&tmp[..n]);
                if !deadline.is_zero() && start.elapsed() >= deadline {
                    break;
                }
            }
            Err(err) if err.kind() == ErrorKind::Interrupted => {
                if !deadline.is_zero() && start.elapsed() >= deadline {
                    break;
                }
                continue;
            }
            Err(err) if err.kind() == ErrorKind::WouldBlock => {
                let left = deadline.saturating_sub(start.elapsed());
                if left.is_zero() || !wait_readable(file.as_raw_fd(), left) {
                    break;
                }
            }
            Err(_) => break,
        }
    }
    if buf.is_empty() {
        None
    } else {
        Some(String::from_utf8_lossy(&buf).into_owned())
    }
}

/// A code read from the transcript. The command item wins. The sentence in
/// the function output is only used when that item is absent.
struct TranscriptExit {
    item: Option<i64>,
    spoken: Option<i64>,
}

impl TranscriptExit {
    fn code(self) -> Option<i64> {
        self.item.or(self.spoken)
    }
}

/// The exit code for `call_id`. A later `CommandExecution` for the same id
/// replaces an earlier one. `Process exited with code N` does not replace
/// a code the item already named.
fn exit_for_call(text: &str, call_id: &str) -> Option<i64> {
    let mut found = TranscriptExit {
        item: None,
        spoken: None,
    };
    for line in text.lines() {
        note_line_exit(line, call_id, &mut found);
    }
    found.code()
}

fn note_line_exit(line: &str, call_id: &str, found: &mut TranscriptExit) {
    if !line.contains(call_id) {
        return;
    }
    if let Ok(value) = serde_json::from_str::<Value>(line) {
        walk_exit(&value, call_id, found);
    } else {
        exit_in_text(line, call_id, found);
    }
}

fn walk_exit(value: &Value, call_id: &str, found: &mut TranscriptExit) {
    match value {
        Value::Array(items) => {
            for item in items {
                walk_exit(item, call_id, found);
            }
        }
        Value::Object(map) => {
            if let Some(code) = command_execution_code(map, call_id) {
                found.item = Some(code);
            }
            if let Some(code) = function_output_code(map, call_id) {
                found.spoken = Some(code);
            }
            for child in map.values() {
                walk_exit(child, call_id, found);
            }
        }
        _ => {}
    }
}

/// `item.type == CommandExecution` and `item.id` is the hook's `tool_use_id`.
fn command_execution_code(map: &serde_json::Map<String, Value>, call_id: &str) -> Option<i64> {
    if map.get("type").and_then(Value::as_str) != Some("CommandExecution") {
        return None;
    }
    if map.get("id").and_then(Value::as_str) != Some(call_id) {
        return None;
    }
    ["exit_code", "exitCode"]
        .iter()
        .find_map(|key| map.get(*key).and_then(exit_number))
}

/// The matching `function_call_output`. The code is the first
/// `Process exited with code N` in its `output`, which is the harness
/// header rather than a line the command printed later.
fn function_output_code(map: &serde_json::Map<String, Value>, call_id: &str) -> Option<i64> {
    if map.get("type").and_then(Value::as_str) != Some("function_call_output") {
        return None;
    }
    let matched = map
        .get("call_id")
        .or_else(|| map.get("callId"))
        .and_then(Value::as_str)
        == Some(call_id);
    if !matched {
        return None;
    }
    map.get("output")
        .and_then(Value::as_str)
        .and_then(process_exit_code)
}

fn process_exit_code(text: &str) -> Option<i64> {
    let marker = "Process exited with code ";
    let rest = text.get(text.find(marker)? + marker.len()..)?;
    let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
    if digits.is_empty() {
        None
    } else {
        digits.parse().ok()
    }
}

fn exit_number(slot: &Value) -> Option<i64> {
    if let Some(code) = slot.as_i64() {
        return Some(code);
    }
    slot.as_str().and_then(|text| text.trim().parse().ok())
}

/// A tail that starts in the middle of a line is not valid JSON. The item
/// still names `CommandExecution`, its `id`, and `exit_code`. A cut-off
/// function output still says `Process exited with code N` after `call_id`.
fn exit_in_text(line: &str, call_id: &str, found: &mut TranscriptExit) {
    let mut from = 0;
    while let Some(rel) = line[from..].find("CommandExecution") {
        let start = from + rel;
        let rest = start + "CommandExecution".len();
        let end = line[rest..]
            .find("CommandExecution")
            .map(|rel| rest + rel)
            .unwrap_or(line.len());
        let window = &line[start..end];
        if find_key(window, "\"id\"", call_id).is_some() {
            if let Some(code) = exit_code_in(window) {
                found.item = Some(code);
            }
        }
        from = rest;
    }
    let mut from = 0;
    while let Some(start) = find_key(&line[from..], "\"call_id\"", call_id) {
        let start = from + start;
        let after = start + "\"call_id\"".len();
        let end = line[after..]
            .find("\"call_id\"")
            .map(|rel| after + rel)
            .unwrap_or(line.len());
        if let Some(code) = process_exit_code(&line[start..end]) {
            found.spoken = Some(code);
        }
        from = after;
    }
}

fn find_key(text: &str, key: &str, want: &str) -> Option<usize> {
    let mut from = 0;
    while from < text.len() {
        let Some(rel) = text[from..].find(key) else {
            break;
        };
        let at = from + rel;
        let after = at + key.len();
        if json_string_is(text.get(after..).unwrap_or(""), want) {
            return Some(at);
        }
        from = after;
    }
    None
}

fn json_string_is(text: &str, want: &str) -> bool {
    let rest = text.trim_start();
    let Some(rest) = rest.strip_prefix(':') else {
        return false;
    };
    let Some(rest) = rest.trim_start().strip_prefix('"') else {
        return false;
    };
    rest.strip_prefix(want)
        .is_some_and(|rest| rest.starts_with('"'))
}

fn exit_code_in(text: &str) -> Option<i64> {
    for key in ["\"exit_code\"", "\"exitCode\""] {
        let Some(at) = text.find(key) else {
            continue;
        };
        let rest = text[at + key.len()..].trim_start();
        let Some(rest) = rest.strip_prefix(':') else {
            continue;
        };
        if let Some(code) = parse_exit_token(rest.trim_start()) {
            return Some(code);
        }
    }
    None
}

fn parse_exit_token(rest: &str) -> Option<i64> {
    let digits = |text: &str| -> Option<i64> {
        let num: String = text
            .chars()
            .take_while(|c| c.is_ascii_digit() || *c == '-')
            .collect();
        if num.is_empty() {
            None
        } else {
            num.parse().ok()
        }
    };
    if let Some(rest) = rest.strip_prefix('"') {
        return digits(rest);
    }
    digits(rest)
}

fn explicit_exit(raw: &Value) -> Option<i64> {
    let slots = [
        raw.get("exit_code"),
        raw.get("exit"),
        raw.pointer("/tool_response/exit_code"),
        raw.pointer("/tool_response/exit"),
        raw.pointer("/tool_response/exitCode"),
        raw.pointer("/tool_output/exit_code"),
    ];
    for slot in slots.into_iter().flatten() {
        if let Some(code) = slot.as_i64() {
            return Some(code);
        }
        if let Some(code) = slot.as_str() {
            return code.trim().parse().ok();
        }
    }
    None
}

/// A guard that already refused this call. A missing exit is not one of
/// these. An error string is not a guard decision: a commit is judged from
/// its exit code, then from what git wrote.
fn permission_block(raw: &Value) -> bool {
    let decisions = [
        raw.get("permissionDecision"),
        raw.get("permission_decision"),
        raw.pointer("/hookSpecificOutput/permissionDecision"),
        raw.pointer("/tool_response/permissionDecision"),
        raw.get("decision"),
    ];
    decisions.into_iter().flatten().any(|slot| {
        slot.as_str()
            .is_some_and(|word| matches!(word.trim(), "deny" | "ask" | "block"))
    })
}

/// `>` and `>>` targets on the line, not `2>&1` and not a quoted sentence.
fn redirect_targets(line: &str) -> Vec<String> {
    let mut out = Vec::new();
    for seg in super::nested_lines(line, 0)
        .iter()
        .flat_map(|l| super::raw_segments(l))
    {
        let words = super::shell_words(&seg);
        let mut i = 0;
        while i < words.len() {
            let word = words[i].as_str();
            if word == ">" || word == ">>" {
                if let Some(target) = words.get(i + 1) {
                    if let Some(target) = redirect_path(target) {
                        out.push(target);
                    }
                }
                i += 2;
                continue;
            }
            if let Some(target) = glued_redirect(word) {
                out.push(target);
            }
            i += 1;
        }
    }
    out
}

fn redirect_path(word: &str) -> Option<String> {
    let word = word.trim_matches(|c| c == '"' || c == '\'');
    if word.is_empty() || word.starts_with('&') {
        return None;
    }
    Some(word.to_string())
}

fn glued_redirect(word: &str) -> Option<String> {
    let rest = word.trim_start_matches(|c: char| c.is_ascii_digit());
    let body = rest
        .strip_prefix(">>")
        .or_else(|| rest.strip_prefix("&>"))
        .or_else(|| rest.strip_prefix('>'))?;
    redirect_path(body)
}

/// Whether `line` redirects into a file inside `repo`. A new file is not
/// tracked yet; `git ls-files` used to wait for a later git command before
/// the sitting had a claim. A path outside the checkout, a home path, or
/// a glob is not this work tree.
fn writes_worktree(repo: &str, line: &str) -> bool {
    let repo = Path::new(repo);
    if repo.as_os_str().is_empty() {
        return false;
    }
    redirect_targets(line)
        .into_iter()
        .any(|target| path_in_worktree(repo, &target))
}

fn path_in_worktree(repo: &Path, target: &str) -> bool {
    if target.is_empty()
        || target.starts_with('~')
        || target.contains('$')
        || target.contains('*')
        || target.starts_with('&')
    {
        return false;
    }
    let target = Path::new(target);
    let joined = if target.is_absolute() {
        target.to_path_buf()
    } else {
        repo.join(target)
    };
    let repo = lexical_norm(repo);
    let joined = lexical_norm(&joined);
    joined.starts_with(&repo) && joined != repo
}

/// `..` and `.` collapsed, without asking the filesystem. A missing file
/// is still inside the work tree when its path says so.
fn lexical_norm(path: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for component in path.components() {
        match component {
            std::path::Component::CurDir => {}
            std::path::Component::ParentDir => {
                out.pop();
            }
            other => out.push(other.as_os_str()),
        }
    }
    out
}

fn is_edit(raw: &Value, cue: &str) -> bool {
    if edit_name(&tool_name(raw)) || edit_name(cue.split_whitespace().next().unwrap_or("")) {
        return true;
    }
    command_is_apply_patch(cue)
}

fn tool_name(raw: &Value) -> String {
    raw["tool_name"]
        .as_str()
        .or_else(|| raw["toolName"].as_str())
        .or_else(|| raw["toolCall"]["name"].as_str())
        .unwrap_or("")
        .to_string()
}

fn edit_name(name: &str) -> bool {
    let base = name.rsplit(['/', '\\']).next().unwrap_or(name);
    EDIT_TOOLS
        .iter()
        .any(|tool| tool.eq_ignore_ascii_case(base))
}

fn command_is_apply_patch(line: &str) -> bool {
    super::nested_lines(line, 0)
        .iter()
        .flat_map(|l| super::raw_segments(l))
        .any(|seg| {
            let words = super::shell_words(&seg);
            let (at, _) = super::prefix_end(&words);
            words.get(at).is_some_and(|word| {
                word.rsplit('/')
                    .next()
                    .unwrap_or(word)
                    .eq_ignore_ascii_case("apply_patch")
            })
        })
}

/// A git commit, not `commit-tree` and not a command that merely mentions
/// the word. Global options that change the repository are skipped; any
/// other flag means this is not the commit subcommand.
fn is_git_commit(line: &str) -> bool {
    super::nested_lines(line, 0)
        .iter()
        .flat_map(|l| super::raw_segments(l))
        .any(|seg| {
            let words = super::shell_words(&seg);
            let (at, _) = super::prefix_end(&words);
            git_commit_argv(&words[at..])
        })
}

fn git_commit_argv(words: &[String]) -> bool {
    let Some(bin) = words.first() else {
        return false;
    };
    if bin.rsplit('/').next().unwrap_or(bin) != "git" {
        return false;
    }
    let mut i = 1;
    while i < words.len() {
        match words[i].as_str() {
            "-C" | "-c" | "--git-dir" | "--work-tree" => i += 2,
            flag if flag.starts_with("--git-dir=") || flag.starts_with("--work-tree=") => i += 1,
            "commit" => return true,
            _ => return false,
        }
    }
    false
}

fn parse_issue_id(text: &str) -> Option<String> {
    let mut found = None;
    for raw in text.split_whitespace() {
        let token = raw.trim_matches(|c: char| matches!(c, ',' | '.' | ':' | '"' | '\''));
        if is_issue_id(token) {
            found = Some(token.to_string());
        }
    }
    found
}

/// A vissue id, as `vissue-core` reads one in `is_vissue_id`: `{project}-{suffix}`
/// with the suffix after the last hyphen. `generate_id` mints that suffix from
/// `ID_ALPHABET` (`0-9a-z`) at `issues.id_length`, which defaults to 4 and is
/// at least 2. The project is the rest, so it may contain hyphens and digits
/// (`ljos-policyd-c0jc`, `lgio-1792329616-q4uh`). A nested project may contain
/// `/` (`acme/cli-1a2b`).
fn is_issue_id(token: &str) -> bool {
    let Some((project, suffix)) = token.rsplit_once('-') else {
        return false;
    };
    issue_project(project) && issue_suffix(suffix)
}

fn issue_project(project: &str) -> bool {
    let mut chars = project.chars();
    matches!(chars.next(), Some(c) if c.is_ascii_alphabetic())
        && project
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '/'))
        && !project.ends_with('-')
        && !project.ends_with('/')
        && !project.contains("--")
}

fn issue_suffix(suffix: &str) -> bool {
    // Shorter than the default mint stays out. A longer configured
    // `id_length` is still the same id.
    suffix.len() >= 4
        && suffix
            .bytes()
            .all(|b| b.is_ascii_digit() || b.is_ascii_lowercase())
}

fn parse_deed(text: &str) -> Option<String> {
    for raw in text.split(|c: char| c.is_whitespace() || matches!(c, '=' | '"' | '\'' | ',')) {
        let Some(rest) = raw.strip_prefix("deed-") else {
            continue;
        };
        if !rest.is_empty()
            && rest
                .chars()
                .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
        {
            return Some(format!("deed-{rest}"));
        }
    }
    None
}

struct Said {
    stdout: String,
}

fn run_timed(bin: &str, args: &[&str], env: &[(&str, &str)]) -> anyhow::Result<Said> {
    use std::io::Read;
    use std::process::{Command, Stdio};
    let path = which::which(bin).map_err(|_| anyhow::anyhow!("{bin} not on PATH"))?;
    let mut cmd = Command::new(path);
    for (key, value) in env {
        cmd.env(key, value);
    }
    crate::git_hooks::hook_child_env(&mut cmd);
    let mut child = cmd
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|e| anyhow::anyhow!("{bin}: {e}"))?;
    let started = std::time::Instant::now();
    loop {
        match child.try_wait() {
            Ok(Some(status)) => {
                let mut stdout = String::new();
                let mut stderr = String::new();
                if let Some(mut out) = child.stdout.take() {
                    let _ = out.read_to_string(&mut stdout);
                }
                if let Some(mut err) = child.stderr.take() {
                    let _ = err.read_to_string(&mut stderr);
                }
                if !status.success() {
                    let why = if stderr.trim().is_empty() {
                        stdout.trim()
                    } else {
                        stderr.trim()
                    };
                    anyhow::bail!("{bin} exited {status}: {why}");
                }
                return Ok(Said { stdout });
            }
            Ok(None) if started.elapsed() > COMMAND_DEADLINE => {
                let _ = child.kill();
                let _ = child.wait();
                anyhow::bail!("{bin} exceeded 2s");
            }
            Ok(None) => std::thread::sleep(Duration::from_millis(10)),
            Err(e) => anyhow::bail!("{bin}: {e}"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Arc, Mutex};

    fn lock() -> crate::EnvLock {
        crate::test_env_lock()
    }

    /// willma-20261020f w4, w8 and w12: agy 1.4.3's `write_file` filed no
    /// claim, and the claim came later with `edit_file` or a shell command.
    /// Every agy file tool those cells sent is an edit; a read is not.
    #[test]
    fn every_agy_file_tool_is_an_edit() {
        for name in [
            "write_file",
            "edit_file",
            "write_to_file",
            "replace_file_content",
        ] {
            let raw =
                serde_json::json!({"toolCall": {"name": name, "args": {"Path": "/w/slug.py"}}});
            assert!(is_edit(&raw, name), "{name}");
        }
        let read = serde_json::json!({"toolCall": {"name": "view_file", "args": {}}});
        assert!(!is_edit(&read, "view_file"));
    }

    struct Restore {
        pairs: Vec<(String, Option<std::ffi::OsString>)>,
    }

    impl Restore {
        fn new(keys: &[&str]) -> Self {
            Self {
                pairs: keys
                    .iter()
                    .map(|k| ((*k).to_string(), std::env::var_os(k)))
                    .collect(),
            }
        }
    }

    impl Drop for Restore {
        fn drop(&mut self) {
            for (key, value) in &self.pairs {
                // SAFETY: the caller holds test_env_lock, dropped after this.
                unsafe {
                    match value {
                        Some(v) => std::env::set_var(key, v),
                        None => std::env::remove_var(key),
                    }
                }
            }
        }
    }

    #[test]
    fn a_commit_names_the_first_open_issue_the_tracker_holds() {
        let state = |id: &str| match id {
            "ljos-policyd-32fx" | "ljos-xsor" => Some("TODO".to_string()),
            "ljos-cjd8" => Some("STARTED".to_string()),
            "ljos-done" => Some("DONE".to_string()),
            _ => None,
        };
        let pick = |m: &str| named_open_issue_with(m, state);
        assert_eq!(
            pick("ljos-policyd-32fx: claim the named id").as_deref(),
            Some("ljos-policyd-32fx")
        );
        assert_eq!(
            pick("tidy the hook\n\nFixes ljos-xsor.").as_deref(),
            Some("ljos-xsor")
        );
        assert_eq!(pick("(ljos-cjd8) reopen").as_deref(), Some("ljos-cjd8"));
        assert_eq!(
            pick("fix-hook: ljos-done then ljos-xsor").as_deref(),
            Some("ljos-xsor")
        );
        assert!(pick("fix-hook: ljos-done and ljos-gone").is_none());
        assert!(pick("no id here").is_none());
    }

    #[test]
    fn a_hyphenated_project_id_is_a_vissue_id() {
        for id in [
            "ljos-policyd-c0jc",
            "lgio-1792329616-q4uh",
            "probe-0001",
            "acme/cli-1a2b",
        ] {
            assert_eq!(parse_issue_id(id).as_deref(), Some(id), "{id}");
        }
        assert_eq!(
            parse_issue_id("created ljos-policyd-c0jc.").as_deref(),
            Some("ljos-policyd-c0jc")
        );
        assert!(parse_issue_id("ljos-policyd-C0JC").is_none());
        assert!(parse_issue_id("not-an-id").is_none());
        assert!(parse_issue_id("well").is_none());
    }

    #[test]
    fn a_bookkeep_test_does_not_read_the_login_user_rules() {
        let home = Path::new("/home/someone");
        let got = super::super::resolve_config_base(None, Some(home)).expect("isolated base");
        assert_ne!(got, home.join(".config"));
        assert!(!got.starts_with(home), "{got:?}");
        let rules = super::super::user_rules::rules_path().expect("rules path");
        if std::env::var_os("XDG_CONFIG_HOME")
            .filter(|value| !value.is_empty())
            .is_none()
        {
            let login = std::env::var_os("HOME").map(PathBuf::from);
            if let Some(login) = login {
                assert!(!rules.starts_with(&login), "{rules:?} is the login config");
            }
        }
    }

    #[test]
    fn a_temp_path_is_the_directory_not_a_prefix() {
        assert!(path_is_temp(Some(Path::new("/tmp/scratch"))));
        assert!(!path_is_temp(Some(Path::new("/tmpfoo"))));
        assert!(!path_is_temp(Some(Path::new("/home/ubuntu"))));
        assert!(!path_is_temp(None));
    }

    #[test]
    fn ljos_off_and_a_temp_home_suspend_the_guard() {
        let _g = lock();
        let _saved = Restore::new(&["HOME", "LJOS_OFF"]);
        unsafe {
            std::env::remove_var("LJOS_OFF");
            std::env::set_var("HOME", "/home/ubuntu");
        }
        assert!(!guard_suspended(), "a normal home is a seat");
        unsafe { std::env::set_var("LJOS_OFF", "1") };
        assert!(guard_suspended());
        unsafe {
            std::env::set_var("LJOS_OFF", "yes");
        }
        assert!(guard_suspended());
        unsafe {
            std::env::remove_var("LJOS_OFF");
            std::env::set_var("HOME", "/tmp/ljos-not-a-seat");
        }
        assert!(guard_suspended(), "a temp HOME is not a seat");
        unsafe { std::env::set_var("HOME", "/tmpfoo") };
        assert!(!guard_suspended(), "/tmpfoo is a name, not /tmp");
    }

    #[test]
    fn a_commit_is_the_commit_subcommand() {
        assert!(is_git_commit("git commit -m \"readme\""));
        assert!(is_git_commit("git -C /src commit -m readme"));
        assert!(is_git_commit("FOO=1 git --git-dir=/src/.git commit"));
        assert!(!is_git_commit("git commit-tree HEAD"));
        assert!(!is_git_commit("git status"));
        assert!(!is_git_commit("echo git commit"));
        assert!(command_is_apply_patch("apply_patch <<'EOF'\n***\nEOF"));
        assert!(!command_is_apply_patch("git apply patch"));
    }

    #[test]
    fn a_prompt_field_does_not_hide_the_commit_command() {
        let raw = r#"{"hook_event_name":"PostToolUse","prompt":"please commit the readme","tool_input":{"command":"git commit -m readme"}}"#;
        let call = crate::hook_call(raw);
        assert!(
            is_git_commit(&call.cue),
            "the prompt hid the commit: {}",
            call.cue
        );
    }

    #[test]
    fn owner_pid_stays_put_on_a_tool_hook() {
        assert_eq!(next_owner_pid("SessionStart", 0, 10), 10);
        assert_eq!(next_owner_pid("UserPromptSubmit", 10, 42), 42);
        assert_eq!(next_owner_pid("PostToolUse", 10, 99), 10);
        assert_eq!(next_owner_pid("PreToolUse", 10, 99), 10);
        assert_eq!(next_owner_pid("Stop", 10, 99), 10);
        assert_eq!(next_owner_pid("PostToolUse", 0, 99), 99);
    }

    #[test]
    fn an_old_row_idles_while_the_book_clock_is_fresh() {
        let limit = Duration::from_secs(2 * 60 * 60);
        let now = 1_000_000_u64;
        let mut book = Book {
            last_unix: now,
            ..Book::default()
        };
        book.repos.insert(
            "/repo-a".into(),
            RepoBook {
                issue: Some("probe-aaaa".into()),
                last_unix: 10,
                ..RepoBook::default()
            },
        );
        book.repos.insert(
            "/repo-b".into(),
            RepoBook {
                issue: Some("probe-bbbb".into()),
                last_unix: now,
                ..RepoBook::default()
            },
        );
        let idle = row_is_idle(
            now,
            &book,
            "/repo-a",
            book.repos.get("/repo-a").unwrap(),
            limit,
            Some("/repo-b"),
        );
        let fresh = row_is_idle(
            now,
            &book,
            "/repo-b",
            book.repos.get("/repo-b").unwrap(),
            limit,
            Some("/repo-b"),
        );
        assert!(idle, "repo A was last touched at 10");
        assert!(!fresh, "repo B was touched with the book");

        let unclocked = RepoBook {
            issue: Some("probe-cccc".into()),
            ..RepoBook::default()
        };
        assert!(
            row_is_idle(now, &book, "/repo-c", &unclocked, limit, Some("/repo-b")),
            "a row with no clock is not the checkout that refreshed the book"
        );
        assert!(
            !row_is_idle(now, &book, "/repo-b", &unclocked, limit, Some("/repo-b")),
            "the current checkout keeps the fresh book clock"
        );
    }

    #[test]
    fn a_prompt_for_another_repo_is_not_a_live_title() {
        let _g = lock();
        let _saved = Restore::new(&["LJOS_SITTING_IDLE"]);
        unsafe { std::env::remove_var("LJOS_SITTING_IDLE") };
        let now = 1_000_000_u64;
        let mut book = Book {
            prompt: "notes: add a second line".into(),
            prompt_repo: "/other".into(),
            prompt_unix: now,
            last_unix: now,
            ..Book::default()
        };
        assert!(
            !prompt_live_for(&book, "/repo", now),
            "the prompt belongs to /other"
        );
        book.prompt_repo = "/repo".into();
        book.repos.insert(
            "/repo".into(),
            RepoBook {
                issue: Some("probe-aaaa".into()),
                title: Some(book.prompt.clone()),
                last_unix: now,
                ..RepoBook::default()
            },
        );
        assert!(
            prompt_live_for(&book, "/repo", now),
            "the current sitting in this checkout keeps its prompt"
        );
        book.repos.get_mut("/repo").unwrap().last_unix = 10;
        assert!(
            !prompt_live_for(&book, "/repo", now),
            "an earlier sitting's prompt does not title the next claim"
        );
    }

    #[test]
    fn a_commit_only_sitting_idles_after_two_hours() {
        assert_eq!(
            sitting_idle_from(None),
            Some(Duration::from_secs(2 * 60 * 60))
        );
        assert_eq!(
            sitting_idle_from(Some("")),
            Some(Duration::from_secs(2 * 60 * 60))
        );
        assert_eq!(sitting_idle_from(Some("0")), None);
        assert_eq!(sitting_idle_from(Some("off")), None);
        assert_eq!(
            sitting_idle_from(Some("30m")),
            Some(Duration::from_secs(1800))
        );
        assert!(idle_due(10_000, 10, Duration::from_secs(2 * 60 * 60)));
        assert!(!idle_due(100, 10, Duration::from_secs(2 * 60 * 60)));
        assert!(!idle_due(10_000, 0, Duration::from_secs(1)));
    }

    #[test]
    fn a_claim_uses_a_checkout_or_the_last_booked_repo() {
        // git_toplevel looks git up with which(), so this holds the same
        // lock as the other PATH readers.
        let _g = lock();
        let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/ljos-place-test");
        let _ = std::fs::remove_dir_all(&root);
        let repo = root.join("repo");
        let other = root.join("other");
        let plain = root.join("plain");
        std::fs::create_dir_all(&repo).unwrap();
        std::fs::create_dir_all(&other).unwrap();
        std::fs::create_dir_all(&plain).unwrap();
        // This tree sits inside the ljos checkout. An invalid gitfile stops
        // git from walking up and treating `plain` as that checkout.
        std::fs::write(plain.join(".git"), "gitdir: /dev/null\n").unwrap();
        git(&repo, &["init", "-q", "-b", "main"]);
        git(&other, &["init", "-q", "-b", "main"]);
        let top = git_toplevel(&repo).unwrap();
        let other_top = git_toplevel(&other).unwrap();
        assert_eq!(
            place_for_claim_in(Some(repo.to_str().unwrap()), None, Some(&plain)).as_deref(),
            Some(top.as_str())
        );
        assert_eq!(
            place_for_claim_in(Some(plain.to_str().unwrap()), Some(&other_top), Some(&repo)),
            None,
            "a named path that is not a checkout does not fall back"
        );
        assert_eq!(
            place_for_claim_in(None, Some(&other_top), Some(&plain)).as_deref(),
            Some(other_top.as_str())
        );
        assert_eq!(place_for_claim_in(None, None, Some(&plain)), None);
        assert_eq!(
            place_for_claim_in(None, None, Some(&repo)).as_deref(),
            Some(top.as_str())
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn project_for_matches_the_remote_before_the_basename() {
        // The remote lookup runs git through which(), so this holds the
        // same lock as the other PATH readers.
        let _g = lock();
        let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/ljos-project-test");
        let _ = std::fs::remove_dir_all(&root);
        let tracker = root.join("tracker");
        let repo = root.join("workspace");
        std::fs::create_dir_all(tracker.join("Software/ljos")).unwrap();
        std::fs::create_dir_all(tracker.join("Software/other")).unwrap();
        std::fs::write(
            tracker.join("Software/ljos/issues.org"),
            "#+REMOTE: https://github.com/acme/ljos.git\n",
        )
        .unwrap();
        std::fs::write(tracker.join("Software/other/issues.org"), "* TODO other\n").unwrap();
        std::fs::create_dir_all(&repo).unwrap();
        git(&repo, &["init", "-q", "-b", "main"]);
        git(
            &repo,
            &["remote", "add", "origin", "git@github.com:acme/ljos.git"],
        );
        assert_eq!(
            project_for_at(repo.to_str().unwrap(), None, Some(&tracker)),
            "ljos"
        );
        assert_eq!(
            project_for_at(repo.to_str().unwrap(), Some("probe"), Some(&tracker)),
            "probe"
        );
        let bare = root.join("bare");
        std::fs::create_dir_all(&bare).unwrap();
        git(&bare, &["init", "-q", "-b", "main"]);
        assert_eq!(
            project_for_at(bare.to_str().unwrap(), None, Some(&tracker)),
            "bare",
            "no remote and more than one project uses the basename"
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    /// A clone in a folder named for the job (`bench-w18b-tfn7`) files on
    /// the repository its origin names, even before the tracker holds a
    /// project of that name. The folder is the fallback only with no origin.
    #[test]
    fn a_clone_folder_is_not_the_project_when_origin_names_the_repo() {
        let _g = lock();
        let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/ljos-clone-folder");
        let _ = std::fs::remove_dir_all(&root);
        let tracker = root.join("tracker");
        std::fs::create_dir_all(tracker.join("Software/ljos")).unwrap();
        std::fs::write(tracker.join("Software/ljos/issues.org"), "* TODO ljos\n").unwrap();
        let repo = root.join("bench-w18b-tfn7");
        std::fs::create_dir_all(&repo).unwrap();
        git(&repo, &["init", "-q", "-b", "main"]);
        git(
            &repo,
            &[
                "remote",
                "add",
                "origin",
                "https://github.com/leidarljos/bench.git",
            ],
        );
        assert_eq!(
            project_for_at(repo.to_str().unwrap(), None, Some(&tracker)),
            "bench"
        );
        assert_eq!(
            title_at("", repo.to_str().unwrap(), None, Some(&tracker)),
            "Work in bench"
        );
        assert_eq!(title_at("  ", "", None, Some(&tracker)), "agent work");
        let mixed = root.join("orpc-clone");
        std::fs::create_dir_all(tracker.join("Software/OmniPotentRPC")).unwrap();
        std::fs::write(
            tracker.join("Software/OmniPotentRPC/issues.org"),
            "* TODO orpc\n",
        )
        .unwrap();
        std::fs::create_dir_all(&mixed).unwrap();
        git(&mixed, &["init", "-q", "-b", "main"]);
        git(
            &mixed,
            &[
                "remote",
                "add",
                "origin",
                "git@github.com:HaoZeke/omnipotentrpc.git",
            ],
        );
        assert_eq!(
            project_for_at(mixed.to_str().unwrap(), None, Some(&tracker)),
            "OmniPotentRPC",
            "an existing project matches whatever its case"
        );
        let bare = root.join("scratch-folder");
        std::fs::create_dir_all(&bare).unwrap();
        git(&bare, &["init", "-q", "-b", "main"]);
        assert_eq!(
            project_for_at(bare.to_str().unwrap(), None, Some(&tracker)),
            "scratch-folder"
        );
        for (url, name) in [
            ("https://github.com/leidarljos/bench.git", Some("bench")),
            (
                "git@github.com:leidarljos/ljos-policyd",
                Some("ljos-policyd"),
            ),
            (
                "https://github.com/HaoZeke/haozeke.github.io/",
                Some("haozeke.github.io"),
            ),
            ("/srv/git/bench.git", None),
            ("file:///srv/git/bench.git", None),
            ("", None),
        ] {
            assert_eq!(remote_repo_name(url).as_deref(), name, "{url}");
        }
        let _ = std::fs::remove_dir_all(&root);
    }

    /// A URL in a project's notes is not its remote. promo's board mentions
    /// the ljos repository; the commit still files on the slug, or on the
    /// project whose metadata records that remote.
    #[test]
    fn a_decoy_note_does_not_take_the_project() {
        // The remote lookup runs git through which(), so this holds the
        // same lock as the other PATH readers.
        let _g = lock();
        let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../target/ljos-decoy-remote");
        let _ = std::fs::remove_dir_all(&root);
        let tracker = root.join("tracker");
        let repo = root.join("workspace");
        std::fs::create_dir_all(tracker.join("Software/ljos")).unwrap();
        std::fs::create_dir_all(tracker.join("Software/promo")).unwrap();
        std::fs::write(tracker.join("Software/ljos/issues.org"), "* TODO ljos\n").unwrap();
        std::fs::write(
            tracker.join("Software/promo/issues.org"),
            "The notes mention https://github.com/leidarljos/ljos as the tool.\n* TODO promo\n",
        )
        .unwrap();
        std::fs::create_dir_all(&repo).unwrap();
        git(&repo, &["init", "-q", "-b", "main"]);
        git(
            &repo,
            &[
                "remote",
                "add",
                "origin",
                "git@github.com:leidarljos/ljos.git",
            ],
        );
        assert_eq!(
            project_for_at(repo.to_str().unwrap(), None, Some(&tracker)),
            "ljos",
            "a note that names the url took the project"
        );

        let atlas = tracker.join("Software/atlas");
        std::fs::create_dir_all(&atlas).unwrap();
        std::fs::write(atlas.join("issues.org"), "* TODO atlas\n").unwrap();
        std::fs::write(
            atlas.join("project.toml"),
            "remote = \"ssh://git@github.com/leidarljos/ljos.git\"\n",
        )
        .unwrap();
        std::fs::remove_dir_all(tracker.join("Software/ljos")).unwrap();
        assert_eq!(
            project_for_at(repo.to_str().unwrap(), None, Some(&tracker)),
            "atlas",
            "the recorded remote lost to a note"
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    fn git(dir: &Path, args: &[&str]) {
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(dir)
            .args(args)
            .env("PATH", std::env::var_os("PATH").unwrap_or_default())
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "git {args:?}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }

    fn habitat_bin(dir: &Path) {
        std::fs::create_dir_all(dir).unwrap();
        std::fs::write(
            dir.join("vissue"),
            r#"#!/usr/bin/env python3
import os, sys, pathlib, re
root = pathlib.Path(os.environ["VISSUE_ROOT"])
log = root / "vissue.log"
args = sys.argv[1:]
with log.open("a") as fh:
    fh.write(" ".join(args) + "\n")
cmd, rest = args[0], args[1:]

def files():
    return list(root.rglob("issues.org"))

def rewrite(iid, state):
    pat = re.compile(r"(\* )[A-Z]+( \[#[A-Z]\] [^\n]*\n:PROPERTIES:\n:ID:\s+" + re.escape(iid) + r"\n)")
    for f in files():
        text = f.read_text()
        new, n = pat.subn(r"\1" + state + r"\2", text, count=1)
        if n:
            f.write_text(new)
            return
    sys.exit("no heading for " + iid)

if cmd == "create":
    proj, title, i = "agent", "agent work", 0
    while i < len(rest):
        if rest[i] == "-p" and i + 1 < len(rest):
            proj = rest[i + 1]
            i += 2
            continue
        if rest[i] == "-q":
            i += 1
            continue
        title = rest[i]
        i += 1
    seq = root / ".seq"
    n = int(seq.read_text()) + 1 if seq.exists() else 1
    seq.write_text(str(n))
    iid = f"{proj}-{n:04x}"
    dest = root / "Software" / proj
    dest.mkdir(parents=True, exist_ok=True)
    with (dest / "issues.org").open("a") as fh:
        fh.write(f"* TODO [#C] {title}\n:PROPERTIES:\n:ID:         {iid}\n:END:\n")
    print(iid)
elif cmd == "claim":
    rewrite(rest[0], "STARTED")
elif cmd == "update":
    state = rest[rest.index("-s") + 1]
    rewrite(rest[0], state)
elif cmd == "deed":
    iid, acc = rest[0], rest[rest.index("--add") + 1]
    needle = f":ID:         {iid}\n:END:\n"
    for f in files():
        text = f.read_text()
        if needle in text:
            f.write_text(text.replace(needle, needle + f"cited {acc}\n", 1))
            sys.exit(0)
    sys.exit("no issue " + iid)
elif cmd == "claims":
    print("[]")
elif cmd == "show":
    print("{}")
else:
    sys.exit("unknown " + cmd)
"#,
        )
        .unwrap();
        std::fs::write(
            dir.join("deedar"),
            r#"#!/usr/bin/env python3
import os, pathlib, sys
root = pathlib.Path(os.environ["VISSUE_ROOT"])
args = sys.argv[1:]
(root / "deedar.log").open("a").write(" ".join(args) + "\n")
ident = None
i = 0
while i < len(args):
    if args[i] == "--id" and i + 1 < len(args):
        ident = args[i + 1]
    if args[i] == "--path" and i + 1 < len(args):
        (root / "deedar-body.log").open("a").write(pathlib.Path(args[i + 1]).read_text())
    i += 1
if not ident:
    seq = root / ".deedseq"
    n = int(seq.read_text()) + 1 if seq.exists() else 1
    seq.write_text(str(n))
    ident = f"deed-{n:04x}"
print(f"id={ident}")
"#,
        )
        .unwrap();
        use std::os::unix::fs::PermissionsExt;
        for name in ["vissue", "deedar"] {
            std::fs::set_permissions(dir.join(name), std::fs::Permissions::from_mode(0o755))
                .unwrap();
        }
    }

    fn scratch() -> (tempfile::TempDir, PathBuf, PathBuf) {
        let dir = tempfile::tempdir().unwrap();
        let tracker = dir.path().join("tracker");
        let repo = dir.path().join("repo");
        std::fs::create_dir_all(&tracker).unwrap();
        std::fs::create_dir_all(&repo).unwrap();
        for root in [&tracker, &repo] {
            git(root, &["init", "-q"]);
            git(root, &["config", "user.email", "seat@example.invalid"]);
            git(root, &["config", "user.name", "seat"]);
            git(root, &["config", "core.hooksPath", "/dev/null"]);
            // The host signs every commit, and that signer takes a lock the
            // whole machine shares. A transcript budget must not include it.
            git(root, &["config", "commit.gpgsign", "false"]);
            git(root, &["config", "core.fsmonitor", "false"]);
        }
        std::fs::write(repo.join("README.md"), "seed\n").unwrap();
        git(&repo, &["add", "README.md"]);
        git(&repo, &["commit", "-q", "-m", "seed"]);
        habitat_bin(&dir.path().join("bin"));
        (dir, tracker, repo)
    }

    fn arm(dir: &Path, tracker: &Path) -> crate::PathGuard {
        let bins = crate::prepend_path(&dir.join("bin"));
        unsafe {
            std::env::set_var("VISSUE_ROOT", tracker);
            std::env::set_var("VISSUE_NO_ROUTE", "1");
            std::env::set_var("LJOS_TRACKER_GIT", "commit");
            std::env::set_var("LJOS_PROJECT", "probe");
            std::env::set_var("XDG_RUNTIME_DIR", dir.join("run"));
            std::env::set_var("LJOS_IN_HOOK", "1");
            std::env::set_var("PACKSET_URL", "off");
            std::env::remove_var("ISSUE_ROOT");
            std::env::remove_var("LJOS_OFF");
            std::env::remove_var("LJOS_SESSION_ID");
        }
        bins
    }

    fn payload(event: &str, session: &str, cwd: &Path, extra: Value) -> (String, crate::HookCall) {
        let mut raw = serde_json::json!({
            "hook_event_name": event,
            "session_id": session,
            "cwd": cwd,
        });
        if let (Value::Object(dst), Value::Object(src)) = (&mut raw, extra) {
            for (k, v) in src {
                dst.insert(k, v);
            }
        }
        let text = raw.to_string();
        let call = crate::hook_call(&text);
        (text, call)
    }

    fn creates(tracker: &Path) -> usize {
        let log = std::fs::read_to_string(tracker.join("vissue.log")).unwrap_or_default();
        log.matches("\ncreate").count() + usize::from(log.starts_with("create"))
    }

    /// A redirect into this checkout claims on the call that writes it, for
    /// every harness shell shape, including a file git does not track yet.
    /// A redirect outside the checkout does not.
    fn assert_redirect_claims(repo: &Path, tracker: &Path) {
        let cwd = repo.display().to_string();
        let repo_s = cwd.clone();
        let claim = |session: &str, raw: Value, file: &str, want: bool| {
            let text = raw.to_string();
            let call = crate::hook_call(&text);
            assert!(
                matches!(call.event.as_str(), "PreToolUse" | "PostToolUse"),
                "{session}: {}",
                call.event
            );
            assert!(
                call.cue.contains(file),
                "{session} dropped the redirect: {}",
                call.cue
            );
            assert_eq!(
                writes_worktree(&repo_s, &call.cue),
                want,
                "{session} worktree {}",
                call.cue
            );
            let before = creates(tracker);
            let _ = observe(&text, &call);
            assert_eq!(
                creates(tracker) > before,
                want,
                "{session} claim {before} -> {}",
                creates(tracker)
            );
        };
        claim(
            "claude-pre",
            serde_json::json!({
                "hook_event_name": "PreToolUse",
                "session_id": "redir-claude-pre",
                "cwd": cwd,
                "tool_name": "Bash",
                "tool_input": {"command": "echo hi > kebab_claude.py"}
            }),
            "kebab_claude.py",
            true,
        );
        claim(
            "opencode-post",
            serde_json::json!({
                "hook_event_name": "PostToolUse",
                "session_id": "redir-opencode-post",
                "cwd": cwd,
                "tool_name": "Bash",
                "tool_input": {"command": "cat > fresh_opencode.txt"},
                "tool_response": {"exit_code": 0}
            }),
            "fresh_opencode.txt",
            true,
        );
        claim(
            "codex-pre",
            serde_json::json!({
                "hook_event_name": "PreToolUse",
                "session_id": "redir-codex-pre",
                "turn_id": "t-redir-pre",
                "cwd": cwd,
                "tool_name": "Bash",
                "tool_input": {"command": "echo hi > kebab_codex.py"}
            }),
            "kebab_codex.py",
            true,
        );
        claim(
            "codex-post",
            serde_json::json!({
                "hook_event_name": "PostToolUse",
                "session_id": "redir-codex-post",
                "turn_id": "t-redir-post",
                "cwd": cwd,
                "tool_name": "Bash",
                "tool_input": {"command": "cat > fresh_codex.txt"},
                "tool_response": {"exit_code": 0}
            }),
            "fresh_codex.txt",
            true,
        );
        claim(
            "agy-pre",
            serde_json::json!({
                "conversationId": "redir-agy-pre",
                "cwd": cwd,
                "toolCall": {"name": "run_command", "args": {"CommandLine": "echo hi > kebab_agy.py"}}
            }),
            "kebab_agy.py",
            true,
        );
        claim(
            "agy-post",
            serde_json::json!({
                "conversationId": "redir-agy-post",
                "cwd": cwd,
                "error": "",
                "toolCall": {"name": "run_command", "args": {"CommandLine": "cat > fresh_agy.txt"}}
            }),
            "fresh_agy.txt",
            true,
        );
        claim(
            "cursor-shell",
            serde_json::json!({
                "cursor_version": "3.2.0",
                "conversation_id": "redir-cursor-shell",
                "hook_event_name": "beforeShellExecution",
                "command": "echo hi > kebab_cursor.py",
                "cwd": cwd
            }),
            "kebab_cursor.py",
            true,
        );
        claim(
            "cursor-post",
            serde_json::json!({
                "cursor_version": "3.2.0",
                "conversation_id": "redir-cursor-post",
                "hook_event_name": "postToolUse",
                "cwd": cwd,
                "tool_name": "Shell",
                "tool_input": {"command": "cat > fresh_cursor.txt"}
            }),
            "fresh_cursor.txt",
            true,
        );
        claim(
            "grok-pre",
            serde_json::json!({
                "hookEventName": "preToolUse",
                "sessionId": "redir-grok-pre",
                "cwd": cwd,
                "toolName": "run_terminal_command",
                "toolInput": {"command": "echo hi > kebab_grok.py"}
            }),
            "kebab_grok.py",
            true,
        );
        claim(
            "grok-post",
            serde_json::json!({
                "hookEventName": "postToolUse",
                "sessionId": "redir-grok-post",
                "cwd": cwd,
                "toolInput": {"command": "cat > fresh_grok.txt"}
            }),
            "fresh_grok.txt",
            true,
        );
        claim(
            "gemini-pre",
            serde_json::json!({
                "hook_event_name": "pre_tool_call",
                "session_id": "redir-gem-pre",
                "cwd": cwd,
                "tool_name": "terminal",
                "tool_input": {"command": "echo hi>kebab_gem.py"}
            }),
            "kebab_gem.py",
            true,
        );
        claim(
            "gemini-post",
            serde_json::json!({
                "hook_event_name": "post_tool_call",
                "session_id": "redir-gem-post",
                "cwd": cwd,
                "tool_name": "terminal",
                "tool_input": {"command": "echo more >> fresh_gem.txt"}
            }),
            "fresh_gem.txt",
            true,
        );
        claim(
            "outside-tmp",
            serde_json::json!({
                "hook_event_name": "PreToolUse",
                "session_id": "redir-outside-tmp",
                "cwd": cwd,
                "tool_name": "Bash",
                "tool_input": {"command": "echo hi > /tmp/ljos-not-in-the-worktree.txt"}
            }),
            "/tmp/ljos-not-in-the-worktree.txt",
            false,
        );
        claim(
            "outside-parent",
            serde_json::json!({
                "hook_event_name": "PreToolUse",
                "session_id": "redir-outside-parent",
                "cwd": cwd,
                "tool_name": "Bash",
                "tool_input": {"command": "echo hi > ../outside.txt"}
            }),
            "../outside.txt",
            false,
        );
        claim(
            "outside-home",
            serde_json::json!({
                "hook_event_name": "PreToolUse",
                "session_id": "redir-outside-home",
                "cwd": cwd,
                "tool_name": "Bash",
                "tool_input": {"command": "echo hi > \"$HOME/.bashrc\""}
            }),
            "$HOME/.bashrc",
            false,
        );
        claim(
            "outside-tilde",
            serde_json::json!({
                "hook_event_name": "PreToolUse",
                "session_id": "redir-outside-tilde",
                "cwd": cwd,
                "tool_name": "Bash",
                "tool_input": {"command": "echo hi > ~/notes.txt"}
            }),
            "~/notes.txt",
            false,
        );
    }

    #[test]
    fn an_ending_sitting_opens_no_row_in_a_checkout_it_never_worked_in() {
        let _g = lock();
        let _saved = saved_env();
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        // The shape an MCP server leaves at exit after answering only
        // guard checks: SessionEnd on the seat's book, which holds no row.
        let session = "seat:probe-guard";
        for event in ["Stop", "SessionEnd"] {
            let (raw, call) = payload(event, session, &repo, Value::Null);
            let _ = observe(&raw, &call);
        }
        let book = load_book(&book_path(session));
        assert!(
            book.repos.is_empty(),
            "no row with a null issue: {:?}",
            book.repos.keys().collect::<Vec<_>>()
        );
        assert_eq!(creates(&tracker), 0);
    }

    #[test]
    fn a_shell_redirect_into_the_work_tree_claims_on_that_call() {
        let _g = lock();
        let _saved = saved_env();
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        assert_redirect_claims(&repo, &tracker);
    }

    #[test]
    fn a_session_files_a_claim_a_deed_and_a_finish_without_being_asked() {
        let _g = lock();
        let _saved = Restore::new(&[
            "PATH",
            "VISSUE_ROOT",
            "VISSUE_NO_ROUTE",
            "LJOS_TRACKER_GIT",
            "LJOS_PROJECT",
            "XDG_RUNTIME_DIR",
            "LJOS_IN_HOOK",
            "PACKSET_URL",
            "ISSUE_ROOT",
            "LJOS_OFF",
            "LJOS_SESSION_ID",
        ]);
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        let session = "book-session-1";
        let (prompt_raw, prompt_call) = payload(
            "UserPromptSubmit",
            session,
            &repo,
            serde_json::json!({"prompt": "Add a readme line"}),
        );
        assert!(
            !prompt_raw.contains("ljos"),
            "the prompt the test sends does not name the seat"
        );
        assert!(observe(&prompt_raw, &prompt_call).0.is_empty());

        let (edit_raw, edit_call) = payload(
            "PreToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Edit", "tool_input": {"file_path": "README.md"}}),
        );
        let _ = observe(&edit_raw, &edit_call);

        let (start_raw, start_call) = payload("SessionStart", session, &repo, Value::Null);
        let (recall, _) = observe(&start_raw, &start_call);
        assert!(recall.contains("Recall for probe-"), "{recall}");
        assert!(recall.contains("Add a readme line"), "{recall}");

        let (commit_raw, commit_call) = payload(
            "PreToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Bash", "tool_input": {"command": "git commit -m \"readme\""}}),
        );
        let _ = observe(&commit_raw, &commit_call);
        let deedar_before = std::fs::read_to_string(tracker.join("deedar.log")).unwrap_or_default();
        assert!(
            deedar_before.is_empty(),
            "the pre-hook does not cite a commit that has not run\n{deedar_before}"
        );
        // The commit runs between the hooks and moves HEAD past the sha this
        // sitting started on. The post cites that new sha.
        commit_file(&repo, "README.md", "hello from the session\n");
        // The same commit on the way out cites the sha once.
        let (post_raw, post_call) = payload(
            "PostToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Bash", "tool_input": {"command": "git commit -m \"readme\""}}),
        );
        let _ = observe(&post_raw, &post_call);
        let _ = observe(&post_raw, &post_call);

        let (stop_raw, stop_call) = payload("Stop", session, &repo, Value::Null);
        let _ = observe(&stop_raw, &stop_call);
        let log_before = git_log(&tracker);
        let _ = observe(&stop_raw, &stop_call);
        let (end_raw, end_call) = payload("SessionEnd", session, &repo, Value::Null);
        let _ = observe(&end_raw, &end_call);
        let log = git_log(&tracker);
        assert_eq!(log, log_before, "a second stop does not finish again");
        assert!(log.contains("claimed"), "{log}");
        assert!(log.contains("cited a deed"), "{log}");
        assert!(log.contains("finished"), "{log}");
        assert_eq!(log.matches("finished").count(), 1, "{log}");
        let org = std::fs::read_to_string(tracker.join("Software/probe/issues.org")).unwrap();
        assert!(org.contains("Add a readme line"), "{org}");
        let sha = String::from_utf8(
            std::process::Command::new("git")
                .arg("-C")
                .arg(&repo)
                .args(["rev-parse", "HEAD"])
                .output()
                .unwrap()
                .stdout,
        )
        .unwrap();
        let sha = sha.trim();
        assert!(org.contains(&format!("deed-file-commit-{sha}")), "{org}");
        let body = std::fs::read_to_string(tracker.join("deedar-body.log")).unwrap();
        assert!(body.contains(sha), "{body}");
        assert_eq!(
            std::fs::read_to_string(tracker.join("deedar.log"))
                .unwrap()
                .lines()
                .count(),
            1
        );

        let vissue_log = std::fs::read_to_string(tracker.join("vissue.log")).unwrap();
        let creates =
            vissue_log.matches("\ncreate").count() + usize::from(vissue_log.starts_with("create"));
        assert_eq!(creates, 1, "{vissue_log}");
        let started = std::time::Instant::now();
        let _ = observe(&edit_raw, &edit_call);
        assert!(
            started.elapsed() < Duration::from_millis(100),
            "warm edit took {:?}",
            started.elapsed()
        );
        let after = std::fs::read_to_string(tracker.join("vissue.log")).unwrap();
        assert_eq!(after, vissue_log, "a warm edit does not ask vissue");
    }

    #[test]
    fn a_missing_tracker_does_not_block_the_next_edit() {
        let _g = lock();
        let _saved = Restore::new(&[
            "PATH",
            "VISSUE_ROOT",
            "XDG_RUNTIME_DIR",
            "LJOS_IN_HOOK",
            "PACKSET_URL",
            "LJOS_OFF",
            "LJOS_PROJECT",
        ]);
        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path().join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        git(&repo, &["init", "-q"]);
        // Hide vissue, which lives outside the coreutils directories.
        // cat and sh stay on PATH.
        let _bins = crate::set_path(crate::path_without(&["vissue"]));
        unsafe {
            std::env::set_var("XDG_RUNTIME_DIR", dir.path().join("run"));
            std::env::set_var("LJOS_IN_HOOK", "1");
            std::env::set_var("PACKSET_URL", "off");
            std::env::remove_var("LJOS_OFF");
            std::env::set_var("VISSUE_ROOT", dir.path().join("tracker"));
            std::env::set_var("LJOS_PROJECT", "probe");
        }
        let (raw, call) = payload(
            "PreToolUse",
            "book-missing",
            &repo,
            serde_json::json!({"tool_name": "Write", "tool_input": {"file_path": "a.txt"}, "prompt": "Write the notes"}),
        );
        // The prompt is a separate event; the edit still has a title from it
        // when it was stored. Here the edit arrives with no prompt stored.
        let (text, _) = observe(&raw, &call);
        assert!(text.is_empty());
        let started = std::time::Instant::now();
        let (again, _) = observe(&raw, &call);
        assert!(again.is_empty());
        assert!(
            started.elapsed() < Duration::from_millis(100),
            "second edit took {:?}",
            started.elapsed()
        );
        let logged =
            std::fs::read_to_string(dir.path().join("run/ljos/book.log")).unwrap_or_default();
        assert_eq!(logged.matches("claim:").count(), 1, "{logged}");
    }

    /// A write tool files and claims nothing. With nothing held it runs
    /// unattached; after a hook's edit claimed an issue in the checkout,
    /// it joins that issue and still files nothing.
    #[test]
    fn a_write_tool_files_no_issue_and_joins_the_held_one() {
        let _g = lock();
        let _saved = Restore::new(&[
            "PATH",
            "VISSUE_ROOT",
            "VISSUE_NO_ROUTE",
            "LJOS_TRACKER_GIT",
            "LJOS_PROJECT",
            "XDG_RUNTIME_DIR",
            "LJOS_IN_HOOK",
            "PACKSET_URL",
            "LJOS_SESSION_ID",
            "LJOS_OFF",
        ]);
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        unsafe {
            std::env::set_var("LJOS_SESSION_ID", "mcp-session-9");
        }
        assert!(!mcp_tool_writes("ljos_claim"));
        assert!(!mcp_tool_writes("ljos_file"));
        assert!(!mcp_tool_writes("ljos_finish"));
        assert!(mcp_tool_writes("ljos_remember"));
        assert!(mcp_tool_writes("ljos_prefer"));
        let mut args = serde_json::Map::new();
        args.insert(
            "text".into(),
            Value::String("the readme stays short".into()),
        );
        args.insert("repo".into(), Value::String(repo.display().to_string()));
        for tool in MCP_WRITES {
            before_mcp_write(tool, Some(&args));
        }
        assert_eq!(creates(&tracker), 0, "a write tool filed an issue");
        let logged =
            std::fs::read_to_string(dir.path().join("run/ljos/book.log")).unwrap_or_default();
        assert!(logged.contains("ran unattached"), "{logged}");
        let session = "hook-edit-then-remember";
        let (raw, call) = payload(
            "PostToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Edit", "tool_input": {"file_path": "slug.py"}}),
        );
        let _ = observe(&raw, &call);
        assert_eq!(creates(&tracker), 1);
        args.insert("text".into(), Value::String("the notes stay dated".into()));
        before_mcp_write("ljos_remember", Some(&args));
        before_mcp_write("ljos_prefer", Some(&args));
        assert_eq!(creates(&tracker), 1, "a write tool filed a second issue");
    }

    #[test]
    fn mail_and_notes_from_the_server_file_no_claim() {
        let _g = lock();
        let _saved = Restore::new(&[
            "PATH",
            "VISSUE_ROOT",
            "VISSUE_NO_ROUTE",
            "LJOS_TRACKER_GIT",
            "LJOS_PROJECT",
            "XDG_RUNTIME_DIR",
            "LJOS_IN_HOOK",
            "PACKSET_URL",
            "LJOS_SESSION_ID",
            "LJOS_OFF",
        ]);
        let (dir, tracker, _repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        unsafe {
            std::env::set_var("LJOS_SESSION_ID", "mcp-mail-1");
        }
        assert!(!mcp_tool_writes("ljos_send"));
        assert!(!mcp_tool_writes("ljos_reply"));
        let mut args = serde_json::Map::new();
        args.insert("to".into(), Value::String("disk-saver".into()));
        args.insert(
            "text".into(),
            Value::String(
                "Hourly poke from Inky: pick up your outstanding queue now and make progress"
                    .into(),
            ),
        );
        before_mcp_write("ljos_send", Some(&args));
        before_mcp_write("ljos_reply", Some(&args));
        // A note names its issue; it never files one titled by its text
        // (willma-20261018e w4 work-d3pl, w11 work-0v1j).
        before_mcp_write("ljos_note", Some(&args));
        let log = std::fs::read_to_string(tracker.join("vissue.log")).unwrap_or_default();
        assert!(
            !log.contains("create"),
            "mail or a note filed an issue\n{log}"
        );
        let book = std::fs::read_to_string(book_path(&sitting_key())).unwrap_or_default();
        assert!(
            !book.contains("Hourly poke"),
            "mail text became the prompt\n{book}"
        );
    }

    #[test]
    fn idle_defaults_to_half_an_hour_and_zero_turns_it_off() {
        assert_eq!(idle_limit_from(None), Some(Duration::from_secs(1800)));
        assert_eq!(idle_limit_from(Some("")), Some(Duration::from_secs(1800)));
        assert_eq!(idle_limit_from(Some("0")), None);
        assert_eq!(idle_limit_from(Some("OFF")), None);
        assert_eq!(idle_limit_from(Some("15m")), Some(Duration::from_secs(900)));
        assert_eq!(
            idle_limit_from(Some("nope")),
            Some(Duration::from_secs(1800))
        );
        assert!(idle_due(2_000, 100, Duration::from_secs(1800)));
        assert!(!idle_due(1_000, 100, Duration::from_secs(1800)));
        assert!(!idle_due(5_000, 0, Duration::from_secs(1)));
    }

    #[test]
    fn an_empty_guard_is_refused() {
        let err = crate::guard_command(" ").unwrap_err().to_string();
        assert!(err.contains("pass the command"), "{err}");
        assert!(crate::command_refused("deny\tTCB required\n"));
        assert!(crate::command_refused("ask: wipe\n"));
        assert!(!crate::command_refused("echo hi\n"));
        assert!(!crate::command_refused("the person may ask later\n"));
    }

    #[test]
    fn a_call_seat_must_be_one_the_tracker_knows() {
        let _g = lock();
        let _saved = Restore::new(&["VISSUE_ROOT", "ISSUE_ROOT", "VISSUE_NO_ROUTE", "LJOS_SEAT"]);
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("vissue.toml"),
            "seats = [\"inky\", \"Disk Saver\", \"saddle\"]\n",
        )
        .unwrap();
        std::fs::create_dir_all(dir.path().join("Software/probe")).unwrap();
        std::fs::write(
            dir.path().join("Software/probe/issues.org"),
            "* STARTED [#C] held\n:PROPERTIES:\n:ID:         probe-abcd\n:CLAIMED_BY: eessi@box\n:END:\n",
        )
        .unwrap();
        unsafe {
            std::env::set_var("VISSUE_ROOT", dir.path());
            std::env::set_var("VISSUE_NO_ROUTE", "1");
            std::env::remove_var("ISSUE_ROOT");
            std::env::remove_var("LJOS_SEAT");
        }
        let err = crate::resolve_call_seat(None).unwrap_err().to_string();
        assert!(err.contains("LJOS_SEAT"), "{err}");
        unsafe {
            std::env::set_var("LJOS_SEAT", "inky");
        }
        assert_eq!(crate::resolve_call_seat(None).unwrap().seat, "inky");
        assert_eq!(
            crate::resolve_call_seat(Some("Disk Saver")).unwrap().seat,
            "disk-saver"
        );
        let err = crate::resolve_call_seat(Some("sadle"))
            .unwrap_err()
            .to_string();
        assert!(err.contains("Did you mean saddle"), "{err}");
        assert!(err.contains("inky"), "{err}");
        assert!(err.contains("disk-saver"), "{err}");
        assert!(err.contains("eessi"), "{err}");
    }

    /// Codex onboarded with `LJOS_SEAT=codex` on a tracker whose only
    /// codex claims were `codex-vax0` (the `SEAT-TAG` of ljos 0.31) and
    /// bare thread ids. Every call failed with "no seat named codex" and
    /// a list of thread ids. A harness id and a name from the environment
    /// are the seat; only a name the call made up is refused, briefly.
    #[test]
    fn a_harness_or_environment_seat_is_never_refused() {
        let _g = lock();
        let _saved = Restore::new(&[
            "HOME",
            "VISSUE_ROOT",
            "ISSUE_ROOT",
            "VISSUE_NO_ROUTE",
            "LJOS_SEAT",
            "VISSUE_AGENT",
            "XDG_RUNTIME_DIR",
        ]);
        let dir = tempfile::tempdir().unwrap();
        let run = dir.path().join("run");
        std::fs::create_dir_all(&run).unwrap();
        std::fs::write(
            dir.path().join("vissue.toml"),
            "seats = [\"inky\", \"free-claude\"]\n",
        )
        .unwrap();
        std::fs::create_dir_all(dir.path().join("Software/probe")).unwrap();
        std::fs::write(
            dir.path().join("Software/probe/issues.org"),
            "* STARTED [#C] one\n:PROPERTIES:\n:ID:         probe-abcd\n:CLAIMED_BY: codex-vax0\n:END:\n\
             * STARTED [#C] two\n:PROPERTIES:\n:ID:         probe-efgh\n\
             :CLAIMED_BY: 01a0dab3-895e-7533-93ca-c9807d5cb680\n:END:\n",
        )
        .unwrap();
        unsafe {
            std::env::set_var("HOME", dir.path().join("home"));
            std::env::set_var("VISSUE_ROOT", dir.path());
            std::env::set_var("VISSUE_NO_ROUTE", "1");
            std::env::set_var("XDG_RUNTIME_DIR", &run);
            std::env::remove_var("ISSUE_ROOT");
            std::env::remove_var("LJOS_SEAT");
            std::env::remove_var("VISSUE_AGENT");
        }
        let known = crate::tracker_known_seats();
        assert!(known.contains("codex"), "{known:?}");
        assert!(!known.contains("codex-vax0"), "{known:?}");
        assert!(!known.iter().any(|s| s.contains("01a0dab3")), "{known:?}");
        let seat = |name: &str| crate::resolve_call_seat(Some(name)).unwrap().seat;
        assert_eq!(seat("codex"), "codex", "a legacy holder names the seat");
        assert_eq!(seat("claude"), "free-claude", "the harness's one seat here");
        assert_eq!(seat("opencode"), "opencode", "a harness with no seat here");
        unsafe {
            std::env::set_var("LJOS_SEAT", "newbot");
        }
        assert_eq!(crate::resolve_call_seat(None).unwrap().seat, "newbot");
        assert_eq!(
            seat("codex"),
            "newbot",
            "LJOS_SEAT wins over the harness id"
        );
        unsafe {
            std::env::remove_var("LJOS_SEAT");
        }
        let err = crate::resolve_call_seat(Some("nobody"))
            .unwrap_err()
            .to_string();
        assert!(
            err.starts_with("no seat named nobody on this tracker."),
            "{err}"
        );
        assert!(err.contains("codex, free-claude, inky"), "{err}");
        assert!(err.contains("LJOS_SEAT"), "{err}");
        assert!(!err.contains("01a0dab3"), "{err}");
        assert!(!err.contains("codex-vax0"), "{err}");
    }

    #[test]
    fn the_mcp_seat_follows_the_hook_seat() {
        let _g = lock();
        let _saved = Restore::new(&[
            "HOME",
            "LJOS_SEAT",
            "VISSUE_AGENT",
            "VISSUE_ROOT",
            "ISSUE_ROOT",
            "VISSUE_NO_ROUTE",
            "XDG_RUNTIME_DIR",
        ]);
        let home = tempfile::tempdir().unwrap();
        let config = home.path().join(".config/ljos");
        std::fs::create_dir_all(&config).unwrap();
        std::fs::write(config.join("env"), "LJOS_SEAT=free-claude\n").unwrap();
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("vissue.toml"),
            "seats = [\"free-claude\", \"inky\"]\n",
        )
        .unwrap();
        unsafe {
            std::env::set_var("HOME", home.path());
            std::env::set_var("VISSUE_ROOT", dir.path());
            std::env::set_var("VISSUE_NO_ROUTE", "1");
            std::env::remove_var("ISSUE_ROOT");
            std::env::remove_var("LJOS_SEAT");
            std::env::remove_var("VISSUE_AGENT");
        }
        assert_eq!(
            crate::resolve_call_seat(Some("claude")).unwrap().seat,
            "free-claude",
            "a harness name does not replace the seat in the config"
        );
        assert_eq!(crate::resolve_call_seat(None).unwrap().seat, "free-claude");
        unsafe {
            std::env::set_var("LJOS_SEAT", "free-claude");
        }
        assert_eq!(crate::resolve_call_seat(Some("inky")).unwrap().seat, "inky");
        unsafe {
            std::env::set_var("LJOS_SEAT", "inky");
        }
        assert_eq!(
            crate::resolve_call_seat(Some("claude")).unwrap().seat,
            "inky",
            "LJOS_SEAT wins over the harness id"
        );
    }

    #[test]
    fn a_tracker_with_no_seats_registers_the_harness_seat() {
        let _g = lock();
        let _saved = Restore::new(&[
            "VISSUE_ROOT",
            "ISSUE_ROOT",
            "VISSUE_NO_ROUTE",
            "LJOS_SEAT",
            "VISSUE_AGENT",
            "XDG_RUNTIME_DIR",
            "HOME",
        ]);
        let dir = tempfile::tempdir().unwrap();
        let run = dir.path().join("run");
        std::fs::create_dir_all(&run).unwrap();
        std::fs::write(dir.path().join("vissue.toml"), "prefix = \"Software\"\n").unwrap();
        unsafe {
            std::env::set_var("VISSUE_ROOT", dir.path());
            std::env::set_var("VISSUE_NO_ROUTE", "1");
            std::env::set_var("XDG_RUNTIME_DIR", &run);
            std::env::remove_var("ISSUE_ROOT");
            std::env::remove_var("LJOS_SEAT");
            std::env::remove_var("VISSUE_AGENT");
            std::env::set_var("HOME", dir.path().join("home"));
        }
        let seat = crate::resolve_call_seat(Some("ljosbot")).unwrap();
        assert_eq!(seat.seat, "ljosbot");
        let text = std::fs::read_to_string(dir.path().join("vissue.toml")).unwrap();
        assert!(text.contains("ljosbot"), "{text}");
        assert!(text.contains("seats"), "{text}");
        assert!(text.contains("Software"), "{text}");
        let log = std::fs::read_to_string(run.join("ljos/book.log")).unwrap();
        assert!(log.contains("registered"), "{log}");
        assert!(log.contains("ljosbot"), "{log}");
    }

    #[test]
    fn an_issue_named_none_is_the_one_this_session_claimed() {
        let _g = lock();
        let _saved = Restore::new(&[
            "PATH",
            "VISSUE_ROOT",
            "VISSUE_NO_ROUTE",
            "LJOS_TRACKER_GIT",
            "LJOS_PROJECT",
            "XDG_RUNTIME_DIR",
            "LJOS_IN_HOOK",
            "PACKSET_URL",
            "ISSUE_ROOT",
            "LJOS_OFF",
            "LJOS_SESSION_ID",
            "LJOS_HARNESS_SESSION",
            "LJOS_SEAT",
        ]);
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        unsafe {
            std::env::remove_var("LJOS_SEAT");
            std::env::remove_var("LJOS_HARNESS_SESSION");
        }
        let session = "book-none";
        let (edit_raw, edit_call) = payload(
            "PreToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Write", "tool_input": {"file_path": "README.md"}}),
        );
        let _ = observe(&edit_raw, &edit_call);
        let issue = canonical_issue(Some("none"), Some(session)).expect("the claim");
        assert!(issue.starts_with("probe-"), "{issue}");
        assert_eq!(
            canonical_issue(Some("NONE"), Some(session)).as_deref(),
            Some(issue.as_str())
        );
        assert_eq!(
            canonical_issue(Some("null"), Some(session)).as_deref(),
            Some(issue.as_str())
        );
        assert_eq!(
            canonical_issue(Some("other-1"), Some(session)).as_deref(),
            Some("other-1")
        );
        let line = crate::session_start_for(Some(session));
        assert!(
            line.contains(&format!("This session's issue is {issue}.")),
            "{line}"
        );
    }

    #[test]
    fn ljos_start_claims_the_task() {
        let _g = lock();
        let _saved = Restore::new(&[
            "PATH",
            "VISSUE_ROOT",
            "VISSUE_NO_ROUTE",
            "LJOS_TRACKER_GIT",
            "LJOS_PROJECT",
            "XDG_RUNTIME_DIR",
            "LJOS_IN_HOOK",
            "PACKSET_URL",
            "ISSUE_ROOT",
            "LJOS_OFF",
            "LJOS_SESSION_ID",
        ]);
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        unsafe {
            std::env::set_var("LJOS_SESSION_ID", "mcp-start-1");
        }
        let err = start_work(None, None, "  ").unwrap_err();
        assert!(err.contains("one sentence"), "{err}");
        let said = start_work(None, Some(repo.to_str().unwrap()), "Add a readme line").unwrap();
        assert!(said.contains("claimed probe-"), "{said}");
        assert!(said.contains("Add a readme line"), "{said}");
        let org = std::fs::read_to_string(tracker.join("Software/probe/issues.org")).unwrap();
        assert!(org.contains("Add a readme line"), "{org}");
        let held = open_issue().expect("the start filed an issue");
        assert!(said.contains(&held), "{said}");
        mcp_shutdown();
        assert!(git_log(&tracker).contains("finished"));
        assert!(open_issue().is_none());
    }

    /// `ljos_start` in the MCP server books under the seat's key and the
    /// harness hook under the harness session. The first write after the
    /// start stays on the started issue instead of filing a second one,
    /// and the issue is finished once, by the book it moved to.
    #[test]
    fn a_write_after_ljos_start_keeps_the_started_issue() {
        let _g = lock();
        let _saved = Restore::new(&[
            "PATH",
            "VISSUE_ROOT",
            "VISSUE_NO_ROUTE",
            "LJOS_TRACKER_GIT",
            "LJOS_PROJECT",
            "XDG_RUNTIME_DIR",
            "LJOS_IN_HOOK",
            "PACKSET_URL",
            "ISSUE_ROOT",
            "LJOS_OFF",
            "LJOS_SESSION_ID",
            "LJOS_HARNESS_SESSION",
            "LJOS_SEAT",
        ]);
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        unsafe {
            std::env::remove_var("LJOS_SEAT");
            std::env::remove_var("LJOS_HARNESS_SESSION");
            std::env::set_var("LJOS_SESSION_ID", "mcp-start-held");
        }
        let said = start_work(
            None,
            Some(repo.to_str().unwrap()),
            "Add slugify and its test",
        )
        .unwrap();
        let started = said
            .lines()
            .next()
            .and_then(|line| line.strip_prefix("claimed "))
            .expect("the start claimed")
            .to_string();
        assert_eq!(creates(&tracker), 1);

        let session = "harness-after-start";
        let (raw, call) = payload(
            "PostToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Write", "tool_input": {"file_path": "slug.py"}}),
        );
        let _ = observe(&raw, &call);
        assert_eq!(creates(&tracker), 1, "the write filed a second issue");
        let book = load_book(&book_path(session));
        let held: Vec<_> = book
            .repos
            .values()
            .filter_map(|r| r.issue.clone())
            .collect();
        assert_eq!(held, vec![started.clone()]);
        assert!(
            load_book(&book_path(&sitting_key()))
                .repos
                .values()
                .all(|r| r.issue.is_none()),
            "the start's book still holds the issue"
        );

        // The server's shutdown has nothing left to finish.
        mcp_shutdown();
        assert!(
            !git_log(&tracker).contains("finished"),
            "{}",
            git_log(&tracker)
        );
        let (stop_raw, stop_call) = payload("Stop", session, &repo, serde_json::json!({}));
        let _ = observe(&stop_raw, &stop_call);
        let log = git_log(&tracker);
        assert_eq!(
            log.matches(&format!("{started} finished")).count(),
            1,
            "{log}"
        );
    }

    /// A STARTED row another holder keeps in the same checkout is that
    /// holder's ticket: the write files its own.
    #[test]
    fn a_write_does_not_take_another_holders_issue() {
        let _g = lock();
        let _saved = Restore::new(&[
            "PATH",
            "VISSUE_ROOT",
            "VISSUE_NO_ROUTE",
            "LJOS_TRACKER_GIT",
            "LJOS_PROJECT",
            "XDG_RUNTIME_DIR",
            "LJOS_IN_HOOK",
            "PACKSET_URL",
            "ISSUE_ROOT",
            "LJOS_OFF",
            "LJOS_SESSION_ID",
            "LJOS_HARNESS_SESSION",
            "LJOS_SEAT",
        ]);
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        unsafe {
            std::env::remove_var("LJOS_SEAT");
            std::env::remove_var("LJOS_HARNESS_SESSION");
            std::env::set_var("LJOS_SESSION_ID", "mcp-start-other");
        }
        let said = start_work(
            None,
            Some(repo.to_str().unwrap()),
            "Add slugify and its test",
        )
        .unwrap();
        let started = said
            .lines()
            .next()
            .and_then(|line| line.strip_prefix("claimed "))
            .expect("the start claimed")
            .to_string();
        let org_path = tracker.join("Software/probe/issues.org");
        let org = std::fs::read_to_string(&org_path).unwrap();
        let id_line = format!(":ID:         {started}\n");
        std::fs::write(
            &org_path,
            org.replace(
                &id_line,
                &format!("{id_line}:CLAIMED_BY: someone-else@zz9\n"),
            ),
        )
        .unwrap();

        let session = "harness-other-holder";
        let (raw, call) = payload(
            "PostToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Write", "tool_input": {"file_path": "slug.py"}}),
        );
        let _ = observe(&raw, &call);
        assert_eq!(
            creates(&tracker),
            2,
            "the write took another holder's issue"
        );
        let book = load_book(&book_path(session));
        assert!(book
            .repos
            .values()
            .all(|r| r.issue.as_deref() != Some(started.as_str())));
    }

    #[test]
    fn a_second_commit_is_a_second_deed_and_a_failed_one_is_not() {
        let _g = lock();
        let _saved = Restore::new(&[
            "PATH",
            "VISSUE_ROOT",
            "VISSUE_NO_ROUTE",
            "LJOS_TRACKER_GIT",
            "LJOS_PROJECT",
            "XDG_RUNTIME_DIR",
            "LJOS_IN_HOOK",
            "PACKSET_URL",
            "ISSUE_ROOT",
            "LJOS_OFF",
            "LJOS_SESSION_ID",
            "LJOS_HOLD",
            "LJOS_SEAT",
        ]);
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        unsafe {
            std::env::set_var("LJOS_SEAT", "probe-seat");
            std::env::set_var("LJOS_HOLD", "book-holder");
        }
        let run = dir.path().join("run/ljos");
        std::fs::create_dir_all(&run).unwrap();
        std::fs::write(
            run.join("hold-book-holder"),
            "book-holder\nprobe-seat\n999999\nbash\n2026-01-01T00:00:00Z\nother-9999\n-\n",
        )
        .unwrap();
        let session = "book-two-commits";
        let (prompt_raw, prompt_call) = payload(
            "UserPromptSubmit",
            session,
            &repo,
            serde_json::json!({"prompt": "Add a readme line"}),
        );
        let _ = observe(&prompt_raw, &prompt_call);
        let (edit_raw, edit_call) = payload(
            "PreToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Write", "tool_input": {"file_path": "README.md"}}),
        );
        let _ = observe(&edit_raw, &edit_call);
        let vissue = std::fs::read_to_string(tracker.join("vissue.log")).unwrap();
        assert!(!vissue.contains("other-9999"), "{vissue}");
        assert!(vissue.contains("create"), "{vissue}");
        fn commit(repo: &Path, name: &str) -> String {
            std::fs::write(repo.join(name), "x\n").unwrap();
            git(repo, &["add", name]);
            git(repo, &["commit", "-q", "-m", name]);
            let out = std::process::Command::new("git")
                .arg("-C")
                .arg(repo)
                .args(["rev-parse", "HEAD"])
                .output()
                .unwrap();
            String::from_utf8(out.stdout).unwrap().trim().to_string()
        }
        let first = commit(&repo, "one.txt");
        let (post, post_call) = payload(
            "PostToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Bash", "tool_input": {"command": "git commit -m one"}, "tool_response": {"exit_code": 0}}),
        );
        let _ = observe(&post, &post_call);
        let failed = payload(
            "PostToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Bash", "tool_input": {"command": "git commit -m boom"}, "tool_response": {"exit_code": 1}}),
        );
        let _ = observe(&failed.0, &failed.1);
        let second = commit(&repo, "two.txt");
        let (post2, post2_call) = payload(
            "PostToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Bash", "tool_input": {"command": "git commit -m two"}}),
        );
        let _ = observe(&post2, &post2_call);
        let org = std::fs::read_to_string(tracker.join("Software/probe/issues.org")).unwrap();
        assert!(org.contains(&format!("deed-file-commit-{first}")), "{org}");
        assert!(org.contains(&format!("deed-file-commit-{second}")), "{org}");
        assert!(!org.contains("other-9999"), "{org}");
        let deeds = std::fs::read_to_string(tracker.join("deedar.log")).unwrap();
        assert_eq!(deeds.lines().count(), 2, "{deeds}");
        let (redir, redir_call) = payload(
            "PreToolUse",
            "book-redirect",
            &repo,
            serde_json::json!({"tool_name": "Bash", "tool_input": {"command": "echo hi > README.md"}}),
        );
        let before = std::fs::read_to_string(tracker.join("vissue.log")).unwrap();
        let _ = observe(&redir, &redir_call);
        let after = std::fs::read_to_string(tracker.join("vissue.log")).unwrap();
        assert!(
            after.matches("create").count() > before.matches("create").count(),
            "a redirect onto a tracked file claims\n{after}"
        );
        let text = lesson_text(
            "Add a readme line",
            "probe-0001",
            &[first.clone(), second],
            &["git commit exited non-zero".into()],
            &["git-force-push: a force push rewrites history".into()],
        );
        let sentences: Vec<&str> = text.split(". ").collect();
        assert!(sentences.len() <= 2, "{text}");
        for sentence in text.split_inclusive('.') {
            let sentence = sentence.trim();
            if sentence.is_empty() {
                continue;
            }
            assert!(sentence.split_whitespace().count() < 30, "{sentence}");
        }
        assert!(text.contains("probe-0001"), "{text}");
        assert!(text.contains(&first[..7]), "{text}");
        assert!(text.contains("git-force-push"), "{text}");
        assert!(text.contains("Commit failed"), "{text}");
        assert_lesson(&text);
    }

    /// ljos-myow: a refused lesson names the HTTP status and the response
    /// body, and a lesson the pack will keep is one its prose gate accepts.
    #[test]
    fn lesson_post_names_status_and_passes_the_prose_gate() {
        let hard =
            "Implement asynchronous reconciliation of cryptographic attestations for the seat";
        let text = lesson_text(
            hard,
            "probe-0001",
            &["abcdef0123456789".into()],
            &["the writer said the sentence was far too long to store".into()],
            &["the guard asked before a force push".into()],
        );
        assert_lesson(&text);
        assert!(text.contains("probe-0001"), "{text}");
        assert!(text.contains("abcdef0"), "{text}");
        assert!(text.contains("Implement"), "{text}");
        assert!(text.contains("seat"), "the title does not vanish: {text}");
        assert!(text.contains("Writer failed"), "{text}");
        assert!(
            !text.contains(hard),
            "a title the gate would refuse is shortened: {text}"
        );
        let plain = lesson_text(
            "Add a readme line",
            "probe-0001",
            &[],
            &["readme test failed".into()],
            &["git push --force origin main".into()],
        );
        assert_lesson(&plain);
        assert!(
            plain.contains("readme") && plain.contains("line"),
            "the words the next prompt recalls stay: {plain}"
        );

        let _g = lock();
        let _saved = saved_env();
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        let refused = serve_pack(|_| {
            (
                400,
                r#"{"error":"readability grade 19.4 exceeds 14"}"#.into(),
            )
        });
        set_var("PACKSET_URL", &refused);
        set_var("PACKSET_TIMEOUT_MS", "2000");
        let session = "myow-refused";
        prompt_and_edit(&repo, session, hard);
        commit_file(&repo, "README.md", "hello from the lesson\n");
        let (post, post_call) = payload(
            "PostToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Bash", "tool_input": {"command": "git commit -m land"}, "tool_response": {"exit_code": 0}}),
        );
        let _ = observe(&post, &post_call);
        let (stop, stop_call) = payload("Stop", session, &repo, Value::Null);
        let _ = observe(&stop, &stop_call);
        let log = std::fs::read_to_string(dir.path().join("run/ljos/book.log")).unwrap();
        assert!(log.contains("Remember: POST /v1/atoms failed"), "{log}");
        assert!(log.contains("400:"), "{log}");
        assert!(log.contains("readability grade 19.4 exceeds 14"), "{log}");
        let refused_book = book_json(dir.path(), session);
        assert_eq!(
            refused_book["repos"]
                .as_object()
                .unwrap()
                .values()
                .next()
                .unwrap()["lesson"],
            false,
            "{refused_book}"
        );

        let texts = Arc::new(Mutex::new(Vec::<String>::new()));
        let kept = serve_pack({
            let texts = Arc::clone(&texts);
            move |req| keep_atom(req, &texts)
        });
        set_var("PACKSET_URL", &kept);
        let session = "myow-kept";
        prompt_and_edit(&repo, session, hard);
        let sha = commit_file(&repo, "NOTES.md", "hello from the kept lesson\n");
        let (post, post_call) = payload(
            "PostToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Bash", "tool_input": {"command": "git commit -m land"}, "tool_response": {"exit_code": 0}}),
        );
        let _ = observe(&post, &post_call);
        let (stop, stop_call) = payload("Stop", session, &repo, Value::Null);
        let _ = observe(&stop, &stop_call);
        let stored = texts.lock().unwrap().clone();
        let lesson = stored.last().expect("the lesson was posted");
        assert_lesson(lesson);
        assert!(lesson.contains(&sha[..7]), "{lesson}");
        assert!(!lesson.contains(hard), "{lesson}");
        let kept_book = book_json(dir.path(), session);
        assert_eq!(
            kept_book["repos"]
                .as_object()
                .unwrap()
                .values()
                .next()
                .unwrap()["lesson"],
            true,
            "{kept_book}"
        );
    }

    /// ljos-myow: the lesson is built from the words a later prompt can match.
    /// Stopwords go first, the rule keeps its name, and the next session's
    /// cold encoder still finds the lesson by those words.
    #[test]
    fn slugify_lesson_keeps_the_word_and_the_rule_for_the_next_session() {
        let title = "In this git repo add a function slugify";
        let ask = "git-force-push: a force push rewrites history";
        let asked = lesson_text(title, "probe-0001", &[], &[], &[ask.into()]);
        assert_lesson(&asked);
        assert!(
            asked.contains("The guard asked about git-force-push."),
            "{asked}"
        );
        assert!(
            asked.contains("function") && asked.contains("slugify"),
            "{asked}"
        );
        assert!(
            asked.split_whitespace().any(|word| word == "git"),
            "{asked}"
        );
        for gone in ["this", "repo", "add"] {
            assert!(
                !asked
                    .split(|c: char| !c.is_alphanumeric())
                    .any(|word| word.eq_ignore_ascii_case(gone)),
                "{gone} is filler and stays out: {asked}"
            );
        }
        let faded = lesson_text("In this repo", "probe-0001", &[], &[], &[ask.into()]);
        assert_lesson(&faded);
        assert!(
            faded.contains("repo"),
            "a filler title still leaves a word: {faded}"
        );
        assert!(!faded.starts_with("Work "), "{faded}");
        let crowded = lesson_text(
            "slugify cryptography reconciliation asynchronous attestation implementation verification",
            "probe-0001",
            &[],
            &[],
            &[ask.into()],
        );
        assert_lesson(&crowded);
        assert!(
            crowded.contains("slugify"),
            "a longer neighbour is shortened before the recall word: {crowded}"
        );

        let _g = lock();
        let _saved = saved_env();
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        let marker = dir.path().join("run/ljos/encoder-warming");
        std::fs::create_dir_all(marker.parent().unwrap()).unwrap();
        std::fs::write(&marker, "").unwrap();
        let atoms = Arc::new(Mutex::new(Vec::<Value>::new()));
        let pack = serve_pack({
            let atoms = Arc::clone(&atoms);
            move |req| {
                let path = req.lines().next().unwrap_or("");
                if path.contains("POST /v1/atoms") {
                    let body = req
                        .split_once("\r\n\r\n")
                        .map(|(_, body)| body)
                        .unwrap_or("");
                    if let Ok(atom) = serde_json::from_str::<Value>(body) {
                        atoms.lock().unwrap().push(atom);
                    }
                    return (
                        200,
                        r#"{"id":"atom-slugify","kind":"lesson","origin":"agent-derived"}"#.into(),
                    );
                }
                if path.contains("GET /v1/status") {
                    return (
                        200,
                        r#"{"embedder":{"available":true,"answering":null}}"#.into(),
                    );
                }
                if path.contains("GET /v1/atoms") {
                    let list = atoms.lock().unwrap().clone();
                    return (200, serde_json::json!({"atoms": list}).to_string());
                }
                (200, "{}".into())
            }
        });
        set_var("PACKSET_URL", &pack);
        set_var("PACKSET_TIMEOUT_MS", "2000");
        let session = "slugify-1";
        prompt_and_edit(&repo, session, title);
        let (failed, failed_call) = payload(
            "PostToolUse",
            session,
            &repo,
            serde_json::json!({
                "tool_name": "Bash",
                "tool_input": {"command": "git commit -m slug"},
                "tool_response": {"exit_code": 1}
            }),
        );
        let _ = observe(&failed, &failed_call);
        let (ask_raw, ask_call) = payload(
            "PreToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Bash", "tool_input": {"command": "git push --force origin main"}}),
        );
        note_ask(&ask_raw, &ask_call, ask);
        let (stop, stop_call) = payload("Stop", session, &repo, Value::Null);
        let _ = observe(&stop, &stop_call);
        let stored = atoms.lock().unwrap().clone();
        let lesson = stored.last().expect("the lesson was posted");
        let prose = lesson["text"].as_str().unwrap_or("");
        assert!(prose.contains("slugify"), "{prose}");
        assert!(prose.contains("function"), "{prose}");
        assert!(prose.contains("git-force-push"), "{prose}");
        assert!(prose.contains("Commit failed"), "{prose}");
        assert_eq!(lesson["source"]["title"], title);
        assert!(
            lesson["source"]["rule"]
                .as_str()
                .unwrap_or("")
                .contains("git-force-push"),
            "{lesson}"
        );
        assert!(
            lesson["source"]["command"]
                .as_str()
                .unwrap_or("")
                .contains("git commit exited non-zero"),
            "{lesson}"
        );
        assert!(
            lesson["entities"].to_string().contains("horizon:standing"),
            "{lesson}"
        );
        let start = crate::session_start_for(Some("slugify-2"));
        assert!(!start.contains("no memories here yet"), "{start}");
        let (_raw, call) = payload(
            "UserPromptSubmit",
            "slugify-2",
            &repo,
            serde_json::json!({"prompt": "add a function slugify to the helper"}),
        );
        let (note, _) = crate::hook_note(&call, 4);
        assert!(note.contains("Remembered, oldest first"), "{note}");
        assert!(note.contains("slugify"), "{note}");
        assert!(note.contains("git-force-push"), "{note}");
    }

    /// A lesson is already stored and the encoder has never answered. No
    /// warm-up marker stands yet. The first prompt of the next session
    /// ranks that lesson from the atoms and recalls it; the warming note
    /// is what a prompt with nothing to recall hears. The marker is
    /// written after the atoms are read, so the load does not sit in
    /// front of the listing.
    #[test]
    fn the_first_prompt_recalls_a_lesson_while_the_encoder_is_cold() {
        let _g = lock();
        let _saved = saved_env();
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        let marker = dir.path().join("run/ljos/encoder-warming");
        assert!(!marker.exists(), "a fresh home has not started warming");
        let atoms = Arc::new(Mutex::new(vec![
            serde_json::json!({
                "id": "atom-kebab",
                "kind": "lesson",
                "text": "The helper keeps kebab case.",
                "entities": ["horizon:standing"],
                "ts": "2026-10-17T00:00:00Z",
                "origin": "agent-derived",
                "source": {"title": "keep kebab case in the helper"}
            }),
            serde_json::json!({
                "id": "atom-deploy",
                "kind": "lesson",
                "text": "The deploy script restarts the service.",
                "entities": ["horizon:standing"],
                "ts": "2026-10-17T00:00:01Z",
                "origin": "agent-derived"
            }),
        ]));
        let pack = serve_pack({
            let atoms = Arc::clone(&atoms);
            move |req| {
                let path = req.lines().next().unwrap_or("");
                if path.contains("GET /v1/status") {
                    return (
                        200,
                        r#"{"embedder":{"available":true,"answering":null}}"#.into(),
                    );
                }
                if path.contains("GET /v1/atoms") {
                    let list = atoms.lock().unwrap().clone();
                    return (200, serde_json::json!({"atoms": list}).to_string());
                }
                (200, "{}".into())
            }
        });
        set_var("PACKSET_URL", &pack);
        set_var("PACKSET_TIMEOUT_MS", "2000");
        let (_raw, call) = payload(
            "UserPromptSubmit",
            "cold-session-2",
            &repo,
            serde_json::json!({"prompt": "Please update test_kebab.py and run pytest."}),
        );
        let (note, _) = crate::hook_note(&call, 4);
        assert!(
            note.contains("Remembered, oldest first"),
            "the first prompt recalled nothing: {note}"
        );
        assert!(note.contains("kebab"), "{note}");
        assert!(
            !note.contains(crate::ENCODER_WARMING_NOTE),
            "the warming note hid the lesson: {note}"
        );
        assert!(marker.exists(), "warming starts after the atoms are read");
        let (_raw, other) = payload(
            "UserPromptSubmit",
            "cold-unrelated",
            &repo,
            serde_json::json!({"prompt": "Deploy the payments service tonight."}),
        );
        let (other_note, _) = crate::hook_note(&other, 4);
        assert!(
            !other_note.contains("kebab"),
            "an unrelated prompt was handed the lesson: {other_note}"
        );
    }

    /// A session that only met a force-push ask writes a sentence about that
    /// ask. The prompt's words stay, and the lesson is not a keyword list.
    #[test]
    fn an_ask_only_session_lesson_is_a_sentence() {
        let prompt = "git function slugify slug lowercases";
        let ask = "git-force-push: it rewrites shared history, so the agent asks you first";
        let keyword = "git function slugify slug lowercases. The guard asked about git-force-push.";
        let text = lesson_text(prompt, "", &[], &[], &[ask.into()]);
        assert_lesson(&text);
        assert_ne!(text, keyword);
        assert!(text.contains("worked"), "{text}");
        assert!(text.contains("asked"), "{text}");
        assert!(text.contains("slugify"), "{text}");
        assert!(text.contains("lowercases"), "{text}");
        assert!(
            text.contains("The guard asked about git-force-push."),
            "{text}"
        );
        assert!(!text.contains("closed"), "{text}");

        let _g = lock();
        let _saved = saved_env();
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        let atoms = Arc::new(Mutex::new(Vec::<Value>::new()));
        let pack = serve_pack({
            let atoms = Arc::clone(&atoms);
            move |req| {
                let path = req.lines().next().unwrap_or("");
                if path.contains("POST /v1/atoms") {
                    let body = req
                        .split_once("\r\n\r\n")
                        .map(|(_, body)| body)
                        .unwrap_or("");
                    if let Ok(atom) = serde_json::from_str::<Value>(body) {
                        atoms.lock().unwrap().push(atom);
                    }
                    return (
                        200,
                        r#"{"id":"atom-ask","kind":"lesson","origin":"agent-derived"}"#.into(),
                    );
                }
                (200, "{}".into())
            }
        });
        set_var("PACKSET_URL", &pack);
        set_var("PACKSET_TIMEOUT_MS", "2000");
        let session = "ask-only-sentence";
        let (prompt_raw, prompt_call) = payload(
            "UserPromptSubmit",
            session,
            &repo,
            serde_json::json!({"prompt": prompt}),
        );
        let _ = observe(&prompt_raw, &prompt_call);
        let (ask_raw, ask_call) = payload(
            "PreToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Bash", "tool_input": {"command": "git push --force origin main"}}),
        );
        note_ask(&ask_raw, &ask_call, ask);
        let (stop, stop_call) = payload("Stop", session, &repo, Value::Null);
        let _ = observe(&stop, &stop_call);
        let stored = atoms.lock().unwrap().clone();
        let lesson = stored.last().expect("the lesson was posted");
        let prose = lesson["text"].as_str().unwrap_or("");
        assert_lesson(prose);
        assert_ne!(prose, keyword);
        assert!(prose.contains("worked"), "{prose}");
        assert!(prose.contains("slugify"), "{prose}");
        assert!(prose.contains("lowercases"), "{prose}");
        assert!(prose.contains("git-force-push"), "{prose}");
        assert!(!prose.contains("closed"), "{prose}");
    }

    /// A commit the guard only asked about never ran. The after hook still
    /// looks like a clean PostToolUse, and HEAD is the commit the sitting
    /// started on. That sha is not a deed. A later commit that moves HEAD is.
    #[test]
    fn an_unrun_commit_is_not_a_deed() {
        let _g = lock();
        let _saved = saved_env();
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        let session = "unrun-commit";
        prompt_and_edit(&repo, session, "Add a readme line");
        let seed = head_sha_of(&repo);
        let command = "git add README.md\ngit commit -m land\ngit push --force origin main";
        let (ask_raw, ask_call) = payload(
            "PreToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Bash", "tool_input": {"command": command}}),
        );
        note_ask(
            &ask_raw,
            &ask_call,
            "git-force-push: a force push rewrites history",
        );
        let cwd = repo.to_str().unwrap();
        let asked = serde_json::json!({
            "conversationId": session,
            "cwd": cwd,
            "toolCall": {"args": {"CommandLine": command}},
            "error": "",
        });
        let asked_text = asked.to_string();
        let asked_call = crate::hook_call(&asked_text);
        assert_eq!(asked_call.event, "PostToolUse");
        assert!(is_git_commit(&asked_call.cue), "{}", asked_call.cue);
        let _ = observe(&asked_text, &asked_call);
        assert_eq!(head_sha_of(&repo), seed);
        let deeds = std::fs::read_to_string(tracker.join("deedar.log")).unwrap_or_default();
        assert!(deeds.is_empty(), "{deeds}");
        let org = std::fs::read_to_string(tracker.join("Software/probe/issues.org")).unwrap();
        assert!(!org.contains("cited"), "{org}");
        assert!(
            !dir.path()
                .join(format!("run/ljos/deed-{seed}.txt"))
                .exists(),
            "the starting commit was cited"
        );
        let sha = commit_file(&repo, "README.md", "hello from the commit that ran\n");
        assert_ne!(sha, seed);
        let (post, post_call) = payload(
            "PostToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Bash", "tool_input": {"command": "git commit -m land"}, "tool_response": {"exit_code": 0}}),
        );
        let _ = observe(&post, &post_call);
        let org = std::fs::read_to_string(tracker.join("Software/probe/issues.org")).unwrap();
        assert!(org.contains(&format!("deed-file-commit-{sha}")), "{org}");
        assert!(!org.contains(&format!("deed-file-commit-{seed}")), "{org}");
        let book = book_json(dir.path(), session);
        assert_eq!(deeds_of(&book), vec![sha], "{book}");
    }

    /// Failed commands and a guard ask are a lesson even when the sitting
    /// never claimed. The next session can recall it.
    #[test]
    fn a_sitting_without_a_claim_still_writes_a_lesson() {
        let _g = lock();
        let _saved = saved_env();
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        let marker = dir.path().join("run/ljos/encoder-warming");
        std::fs::create_dir_all(marker.parent().unwrap()).unwrap();
        std::fs::write(&marker, "").unwrap();
        let atoms = Arc::new(Mutex::new(Vec::<Value>::new()));
        let pack = serve_pack({
            let atoms = Arc::clone(&atoms);
            move |req| {
                let path = req.lines().next().unwrap_or("");
                if path.contains("POST /v1/atoms") {
                    let body = req
                        .split_once("\r\n\r\n")
                        .map(|(_, body)| body)
                        .unwrap_or("");
                    if let Ok(atom) = serde_json::from_str::<Value>(body) {
                        atoms.lock().unwrap().push(atom);
                    }
                    return (
                        200,
                        r#"{"id":"atom-fail","kind":"lesson","origin":"agent-derived"}"#.into(),
                    );
                }
                if path.contains("GET /v1/status") {
                    return (
                        200,
                        r#"{"embedder":{"available":true,"answering":null}}"#.into(),
                    );
                }
                if path.contains("GET /v1/atoms") {
                    let list = atoms.lock().unwrap().clone();
                    return (200, serde_json::json!({"atoms": list}).to_string());
                }
                (200, "{}".into())
            }
        });
        set_var("PACKSET_URL", &pack);
        set_var("PACKSET_TIMEOUT_MS", "2000");

        let session = "failures-only";
        let (prompt, prompt_call) = payload(
            "UserPromptSubmit",
            session,
            &repo,
            serde_json::json!({"prompt": "Fix the slugify helper"}),
        );
        let _ = observe(&prompt, &prompt_call);
        for _ in 0..11 {
            let (failed, failed_call) = payload(
                "PostToolUseFailure",
                session,
                &repo,
                serde_json::json!({
                    "tool_name": "Bash",
                    "tool_input": {"command": "cargo test"},
                    "tool_response": {"error": "slugify helper failed"}
                }),
            );
            let _ = observe(&failed, &failed_call);
        }
        let (stop, stop_call) = payload("Stop", session, &repo, Value::Null);
        let _ = observe(&stop, &stop_call);

        let asked = "asks-only";
        let (prompt, prompt_call) = payload(
            "UserPromptSubmit",
            asked,
            &repo,
            serde_json::json!({"prompt": "Check the release script"}),
        );
        let _ = observe(&prompt, &prompt_call);
        let (ask_raw, ask_call) = payload(
            "PreToolUse",
            asked,
            &repo,
            serde_json::json!({"tool_name": "Bash", "tool_input": {"command": "git push --force origin main"}}),
        );
        note_ask(
            &ask_raw,
            &ask_call,
            "git-force-push: a force push rewrites history",
        );
        let (stop, stop_call) = payload("Stop", asked, &repo, Value::Null);
        let _ = observe(&stop, &stop_call);

        let vissue = std::fs::read_to_string(tracker.join("vissue.log")).unwrap_or_default();
        assert!(!vissue.contains("create"), "{vissue}");
        let stored = atoms.lock().unwrap().clone();
        assert_eq!(stored.len(), 2, "{stored:?}");
        let failed = stored[0]["text"].as_str().unwrap_or("");
        assert!(failed.contains("slugify"), "{failed}");
        assert!(!failed.contains("closed"), "{failed}");
        assert_lesson(failed);
        let guard = stored[1]["text"].as_str().unwrap_or("");
        assert!(guard.contains("git-force-push"), "{guard}");
        assert!(!guard.contains("closed"), "{guard}");
        assert_lesson(guard);
        let book = book_json(dir.path(), session);
        let row = book["repos"].as_object().unwrap().values().next().unwrap();
        assert!(row["issue"].is_null(), "{book}");
        assert_eq!(row["lesson"], true, "{book}");

        let start = crate::session_start_for(Some("failures-next"));
        assert!(!start.contains("no memories here yet"), "{start}");
        let (_raw, call) = payload(
            "UserPromptSubmit",
            "failures-next",
            &repo,
            serde_json::json!({"prompt": "repair the slugify helper"}),
        );
        let (note, _) = crate::hook_note(&call, 4);
        assert!(note.contains("Remembered, oldest first"), "{note}");
        assert!(note.contains("slugify"), "{note}");
    }

    /// Codex 0.163 names the call as `CommandExecution.id`. The matching
    /// `function_call_output` only spells the code in its text, and that
    /// sentence does not replace a code the item already named.
    #[test]
    fn a_codex_transcript_exit_matches_the_call_id() {
        let id = "exec_command_058e85yevw32";
        let other = "exec_command_q3kpac3wpztr";
        let text = format!(
            "{}\n{}\n{}\n{}\n{}\n{}",
            codex_event(other, None),
            codex_event(other, Some(127)),
            function_output_line(other, 127),
            codex_event(id, None),
            codex_event(id, Some(1)),
            function_output_line(id, 1),
        );
        assert_eq!(exit_for_call(&text, id), Some(1));
        assert_eq!(exit_for_call(&text, other), Some(127));
        assert_eq!(exit_for_call(&text, "exec_command_missing"), None);
        let item_wins = format!(
            "{}\n{}",
            codex_event(id, Some(1)),
            function_output_line(id, 127),
        );
        assert_eq!(exit_for_call(&item_wins, id), Some(1));
        assert_eq!(exit_for_call(&function_output_line(id, 1), id), Some(1));
        let torn_item = codex_event(id, Some(1));
        let torn_item = &torn_item[..torn_item.len() - 1];
        assert_eq!(exit_for_call(torn_item, id), Some(1));
        let torn_output = function_output_line(id, 255);
        let phrase = "Process exited with code 255";
        let end = torn_output.find(phrase).unwrap() + phrase.len();
        assert_eq!(exit_for_call(&torn_output[..end], id), Some(255));
    }

    /// A Codex 0.163 PostToolUse whose `tool_response` is text books the
    /// failure from the transcript the hook was given.
    #[test]
    fn a_real_codex_post_books_the_exit_failure() {
        let _g = lock();
        let _saved = saved_env();
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        let session = "01a14bc1-59ae-7d43-9a16-bc94c6a0ef56";
        let id = "exec_command_058e85yevw32";
        let other = "exec_command_q3kpac3wpztr";
        let transcript = dir.path().join("rollout.jsonl");
        std::fs::write(
            &transcript,
            format!(
                "{}\n{}\n{}\n{}\n{}\n",
                codex_event(other, None),
                codex_event(other, Some(127)),
                function_output_line(other, 127),
                codex_event(id, Some(1)),
                function_output_line(id, 1),
            ),
        )
        .unwrap();
        let command = "/usr/bin/python3 -c 'import slug; slug.kebab_case(\"Hello World\")'";
        let raw = serde_json::json!({
            "session_id": session,
            "turn_id": "01a14bc1-59d4-7390-a148-c38ad5e58020",
            "transcript_path": transcript,
            "cwd": repo,
            "hook_event_name": "PostToolUse",
            "tool_name": "Bash",
            "tool_input": {"command": command},
            "tool_response": "ModuleNotFoundError: No module named 'slug'\n",
            "tool_use_id": id,
        });
        let text = serde_json::to_string(&raw).unwrap();
        let call = crate::hook_call(&text);
        assert_eq!(call.event, "PostToolUse");
        assert!(call.cue.contains("python3"), "{}", call.cue);
        let _ = observe(&text, &call);
        let book = book_json(dir.path(), session);
        let row = book["repos"].as_object().unwrap().values().next().unwrap();
        let failures = row["failures"].as_array().unwrap();
        assert!(
            failures
                .iter()
                .any(|note| note.as_str().unwrap_or("").contains("python3")),
            "{book}"
        );
        assert!(
            failures
                .iter()
                .any(|note| note.as_str().unwrap_or("").contains("slug")),
            "{book}"
        );
    }

    /// A string `tool_response` plus a transcript exit of 127 is a failure,
    /// and the lesson keeps it.
    #[test]
    fn a_codex_string_response_with_exit_127_is_a_lesson_failure() {
        let _g = lock();
        let _saved = saved_env();
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        let atoms = arm_lessons(dir.path());
        let session = "codex-exit-127";
        let id = "exec_command_n38zthdamfmc";
        let transcript = dir.path().join("rollout.jsonl");
        std::fs::write(
            &transcript,
            format!(
                "{}\n{}\n{}\n",
                codex_event("exec_command_other", Some(0)),
                codex_event(id, None),
                codex_event(id, Some(127)),
            ),
        )
        .unwrap();
        let (prompt, prompt_call) = payload(
            "UserPromptSubmit",
            session,
            &repo,
            serde_json::json!({"prompt": "Fix the slugify helper"}),
        );
        let _ = observe(&prompt, &prompt_call);
        let (failed, failed_call) = codex_post(
            session,
            &repo,
            id,
            "python slugify",
            "/bin/bash: line 1: python: command not found\r\n",
            &transcript,
        );
        let _ = observe(&failed, &failed_call);
        let (stop, stop_call) = payload("Stop", session, &repo, Value::Null);
        let _ = observe(&stop, &stop_call);

        let book = book_json(dir.path(), session);
        let row = book["repos"].as_object().unwrap().values().next().unwrap();
        let failures = row["failures"].as_array().unwrap();
        assert!(
            failures
                .iter()
                .any(|note| note.as_str().unwrap_or("").contains("python")),
            "{book}"
        );
        let stored = atoms.lock().unwrap().clone();
        let lesson = stored.last().expect("the lesson was posted");
        let prose = lesson["text"].as_str().unwrap_or("");
        assert!(prose.contains("slugify"), "{prose}");
        assert!(prose.contains("failed"), "{prose}");
        assert!(
            lesson["source"]["command"]
                .as_str()
                .unwrap_or("")
                .contains("python"),
            "{lesson}"
        );
        assert_lesson(prose);
    }

    /// Commands that only fail, on a sitting that never claimed, still leave
    /// a lesson. Codex reports those failures as PostToolUse with a string body.
    #[test]
    fn an_unclaimed_codex_session_with_failures_writes_a_lesson() {
        let _g = lock();
        let _saved = saved_env();
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        let atoms = arm_lessons(dir.path());
        let session = "codex-failures-only";
        let transcript = dir.path().join("rollout.jsonl");
        let first = "exec_command_n38zthdamfmc";
        let second = "exec_command_modmissing";
        std::fs::write(
            &transcript,
            format!(
                "{}\n{}\n",
                codex_event(first, Some(127)),
                codex_event(second, Some(1)),
            ),
        )
        .unwrap();
        let (prompt, prompt_call) = payload(
            "UserPromptSubmit",
            session,
            &repo,
            serde_json::json!({"prompt": "Fix the slugify helper"}),
        );
        let _ = observe(&prompt, &prompt_call);
        let (failed, failed_call) = codex_post(
            session,
            &repo,
            first,
            "python slugify",
            "/bin/bash: line 1: python: command not found\r\n",
            &transcript,
        );
        let _ = observe(&failed, &failed_call);
        let (again, again_call) = codex_post(
            session,
            &repo,
            second,
            "python -m slugify",
            "ModuleNotFoundError: No module named 'slugify'\r\n",
            &transcript,
        );
        let _ = observe(&again, &again_call);
        let (stop, stop_call) = payload("Stop", session, &repo, Value::Null);
        let _ = observe(&stop, &stop_call);

        let vissue = std::fs::read_to_string(tracker.join("vissue.log")).unwrap_or_default();
        assert!(!vissue.contains("create"), "{vissue}");
        let stored = atoms.lock().unwrap().clone();
        assert_eq!(stored.len(), 1, "{stored:?}");
        let prose = stored[0]["text"].as_str().unwrap_or("");
        assert!(prose.contains("slugify"), "{prose}");
        assert!(prose.contains("failed"), "{prose}");
        assert!(!prose.contains("closed"), "{prose}");
        assert_lesson(prose);
        let book = book_json(dir.path(), session);
        let row = book["repos"].as_object().unwrap().values().next().unwrap();
        assert!(row["issue"].is_null(), "{book}");
        assert_eq!(row["lesson"], true, "{book}");
        assert!(row["failures"].as_array().unwrap().len() >= 2, "{book}");

        let start = crate::session_start_for(Some("codex-failures-next"));
        assert!(!start.contains("no memories here yet"), "{start}");
        let (_raw, call) = payload(
            "UserPromptSubmit",
            "codex-failures-next",
            &repo,
            serde_json::json!({"prompt": "repair the slugify helper"}),
        );
        let (note, _) = crate::hook_note(&call, 4);
        assert!(note.contains("Remembered, oldest first"), "{note}");
        assert!(note.contains("slugify"), "{note}");
    }

    /// A git commit whose payload has no exit field is not a success. The
    /// sitting's current HEAD is not a deed, including when this post is the
    /// first time the sitting saw the repository. A later commit whose
    /// transcript says 0, and whose HEAD moved, is cited.
    #[test]
    fn a_failed_codex_commit_with_no_exit_field_cites_no_deed() {
        let _g = lock();
        let _saved = saved_env();
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        let session = "codex-commit";
        let seed = head_sha_of(&repo);
        let transcript = dir.path().join("rollout.jsonl");
        // Another call exited 0. This commit's id is not in the file, and
        // the payload has no exit field, so the code stays unknown.
        std::fs::write(
            &transcript,
            format!("{}\n", codex_event("exec_command_other", Some(0))),
        )
        .unwrap();
        let (failed, failed_call) = codex_post(
            session,
            &repo,
            "exec_command_n38zthdamfmc",
            "git commit -m nope",
            "error: nothing to commit\r\n",
            &transcript,
        );
        assert_eq!(failed_call.event, "PostToolUse");
        assert!(is_git_commit(&failed_call.cue), "{}", failed_call.cue);
        assert!(explicit_exit(&serde_json::from_str(&failed).unwrap()).is_none());
        let _ = observe(&failed, &failed_call);
        assert_eq!(head_sha_of(&repo), seed);
        let deeds = std::fs::read_to_string(tracker.join("deedar.log")).unwrap_or_default();
        assert!(deeds.is_empty(), "{deeds}");
        let org = std::fs::read_to_string(tracker.join("Software/probe/issues.org")).unwrap();
        assert!(!org.contains("cited"), "{org}");
        assert!(
            !dir.path()
                .join(format!("run/ljos/deed-{seed}.txt"))
                .exists(),
            "the sitting's HEAD was cited"
        );
        let book = book_json(dir.path(), session);
        assert!(deeds_of(&book).is_empty(), "{book}");

        let sha = commit_file(&repo, "README.md", "hello from codex\n");
        assert_ne!(sha, seed);
        std::fs::write(
            &transcript,
            format!("{}\n", codex_event("exec_command_ok", Some(0))),
        )
        .unwrap();
        let (post, post_call) = codex_post(
            session,
            &repo,
            "exec_command_ok",
            "git commit -m land",
            "1 file changed\r\n",
            &transcript,
        );
        let _ = observe(&post, &post_call);
        let book = book_json(dir.path(), session);
        assert_eq!(deeds_of(&book), vec![sha], "{book}");
    }

    /// A transcript that does not answer inside the hook budget is not exit 0.
    #[test]
    fn a_stuck_codex_transcript_is_not_a_clean_commit() {
        let _g = lock();
        let _saved = saved_env();
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        let session = "codex-stuck";
        let seed = head_sha_of(&repo);
        let (prompt, prompt_call) = payload(
            "UserPromptSubmit",
            session,
            &repo,
            serde_json::json!({"prompt": "Commit the readme"}),
        );
        let _ = observe(&prompt, &prompt_call);
        let fifo = dir.path().join("stuck.jsonl");
        let c_path = std::ffi::CString::new(fifo.to_str().unwrap()).unwrap();
        // SAFETY: mkfifo takes a NUL-terminated path and a mode. The path
        // lives until the call returns, and the mode is a plain permission.
        let rc = unsafe { libc::mkfifo(c_path.as_ptr(), 0o600) };
        assert_eq!(rc, 0, "mkfifo");
        let (failed, failed_call) = codex_post(
            session,
            &repo,
            "exec_command_n38zthdamfmc",
            "git commit -m nope",
            "error: nothing to commit\r\n",
            &fifo,
        );
        let started = std::time::Instant::now();
        let _ = observe(&failed, &failed_call);
        assert!(
            started.elapsed() < TRANSCRIPT_DEADLINE + Duration::from_secs(2),
            "the transcript read held the hook for {:?}",
            started.elapsed()
        );
        assert!(deeds_of(&book_json(dir.path(), session)).is_empty());
        assert_eq!(head_sha_of(&repo), seed);
        let deeds = std::fs::read_to_string(tracker.join("deedar.log")).unwrap_or_default();
        assert!(deeds.is_empty(), "{deeds}");
    }

    /// A timed-out agy sitting never gets Stop. Its prompt arrives on the
    /// payload after the first model call, and the lesson keeps those words
    /// so the next prompt can recall them.
    #[test]
    fn a_timed_out_agy_prompt_is_recalled() {
        let _g = lock();
        let asked = serde_json::json!({
            "conversationId": "agy-prompt-event",
            "prompt": "Fix the slugify helper",
        });
        let asked_call = crate::hook_call_as(&asked.to_string(), Some("beforeSubmitPrompt"));
        assert_eq!(asked_call.event, "UserPromptSubmit");
        assert!(asked_call.cue.contains("slugify"), "{}", asked_call.cue);

        let _saved = saved_env();
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        let marker = dir.path().join("run/ljos/encoder-warming");
        std::fs::create_dir_all(marker.parent().unwrap()).unwrap();
        std::fs::write(&marker, "").unwrap();
        let atoms = Arc::new(Mutex::new(Vec::<Value>::new()));
        let pack = serve_pack({
            let atoms = Arc::clone(&atoms);
            move |req| {
                let path = req.lines().next().unwrap_or("");
                if path.contains("POST /v1/atoms") {
                    let body = req
                        .split_once("\r\n\r\n")
                        .map(|(_, body)| body)
                        .unwrap_or("");
                    if let Ok(atom) = serde_json::from_str::<Value>(body) {
                        atoms.lock().unwrap().push(atom);
                    }
                    return (
                        200,
                        r#"{"id":"atom-agy","kind":"lesson","origin":"agent-derived"}"#.into(),
                    );
                }
                if path.contains("GET /v1/status") {
                    return (
                        200,
                        r#"{"embedder":{"available":true,"answering":null}}"#.into(),
                    );
                }
                if path.contains("GET /v1/atoms") {
                    let list = atoms.lock().unwrap().clone();
                    return (200, serde_json::json!({"atoms": list}).to_string());
                }
                (200, "{}".into())
            }
        });
        set_var("PACKSET_URL", &pack);
        set_var("PACKSET_TIMEOUT_MS", "2000");

        let session = "agy-timeout";
        let cwd = repo.to_str().unwrap();
        let transcript = dir.path().join("transcript.jsonl");
        std::fs::write(
            &transcript,
            "{\"type\":\"PLANNER_RESPONSE\",\"text\":\"working\"}\n",
        )
        .unwrap();
        let early = serde_json::json!({
            "invocationNum": 0,
            "conversationId": session,
            "cwd": cwd,
            "workspacePaths": [cwd],
            "transcriptPath": transcript,
        });
        let early_text = early.to_string();
        let early_call = crate::hook_call(&early_text);
        assert_eq!(early_call.event, "UserPromptSubmit");
        assert!(early_call.cue.is_empty(), "{}", early_call.cue);
        let _ = observe(&early_text, &early_call);

        std::fs::write(
            &transcript,
            "{\"type\":\"USER_INPUT\",\"userInput\":{\"items\":[{\"text\":\"Fix the slugify helper\"}]}}\n",
        )
        .unwrap();
        let edit = serde_json::json!({
            "conversationId": session,
            "cwd": cwd,
            "workspacePaths": [cwd],
            "transcriptPath": transcript,
            "toolCall": {"name": "write_to_file", "args": {"TargetFile": "README.md", "CodeContent": "x"}},
        });
        let edit_text = edit.to_string();
        let edit_call = crate::hook_call(&edit_text);
        assert_eq!(edit_call.event, "PreToolUse");
        let _ = observe(&edit_text, &edit_call);
        set_owner(dir.path(), session, dead_pid());

        let (next, next_call) = payload(
            "UserPromptSubmit",
            "agy-next",
            &repo,
            serde_json::json!({"prompt": "repair the slugify helper"}),
        );
        let _ = observe(&next, &next_call);

        let book = book_json(dir.path(), session);
        let row = book["repos"].as_object().unwrap().values().next().unwrap();
        assert!(
            row["title"].as_str().unwrap_or("").contains("slugify"),
            "{book}"
        );
        assert_eq!(row["lesson"], true, "{book}");
        assert_eq!(row["finished"], true, "{book}");
        let stored = atoms.lock().unwrap().clone();
        let lesson = stored
            .last()
            .and_then(|atom| atom["text"].as_str())
            .unwrap_or("");
        assert!(lesson.contains("slugify"), "{lesson}");
        assert_lesson(lesson);

        let start = crate::session_start_for(Some("agy-next"));
        assert!(!start.contains("no memories here yet"), "{start}");
        let (note, _) = crate::hook_note(&next_call, 4);
        assert!(note.contains("Remembered, oldest first"), "{note}");
        assert!(note.contains("slugify"), "{note}");
    }

    /// ljos-6x14: agy sends no event name. Onboarding tells the after-command
    /// hook `--event PostToolUse`, and a payload that carries `error` is
    /// that same return when the flag is absent. Either way the commit is cited.
    #[test]
    fn agy_commit_without_an_event_name_is_cited() {
        let spec = crate::named_hook_spec("ljos");
        let command = spec["PostToolUse"][0]["hooks"][0]["command"]
            .as_str()
            .unwrap();
        assert!(command.contains("--event PostToolUse"), "{command}");
        let entering = r#"{"conversationId":"agy","toolCall":{"args":{"CommandLine":"git add README.md && git commit -m land"}}}"#;
        let before = crate::hook_call(entering);
        assert_eq!(before.event, "PreToolUse");
        assert_eq!(before.cue, "git add README.md && git commit -m land");
        let returning = r#"{"conversationId":"agy","toolCall":{"args":{"CommandLine":"git add README.md && git commit -m land"}},"error":""}"#;
        let after = crate::hook_call(returning);
        assert_eq!(after.event, "PostToolUse");
        assert_eq!(after.cue, before.cue);

        let _g = lock();
        let _saved = saved_env();
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        let session = "agy-deed";
        let cwd = repo.to_str().unwrap();
        let (prompt, prompt_call) = payload(
            "UserPromptSubmit",
            session,
            &repo,
            serde_json::json!({"prompt": "Add a readme line"}),
        );
        let _ = observe(&prompt, &prompt_call);
        let pre = serde_json::json!({
            "conversationId": session,
            "cwd": cwd,
            "toolCall": {"args": {"CommandLine": "git add README.md && git commit -m land"}},
        });
        let pre_text = pre.to_string();
        let pre_call = crate::hook_call(&pre_text);
        assert_eq!(pre_call.event, "PreToolUse");
        let _ = observe(&pre_text, &pre_call);
        assert!(
            std::fs::read_to_string(tracker.join("deedar.log"))
                .unwrap_or_default()
                .is_empty(),
            "the way in does not cite a commit that has not run"
        );
        let sha = commit_file(&repo, "README.md", "hello from agy\n");
        let post = serde_json::json!({
            "conversationId": session,
            "cwd": cwd,
            "toolCall": {"args": {"CommandLine": "git add README.md && git commit -m land"}},
            "error": "",
        });
        let post_text = post.to_string();
        let post_call = crate::hook_call(&post_text);
        assert_eq!(post_call.event, "PostToolUse");
        let _ = observe(&post_text, &post_call);
        let org = std::fs::read_to_string(tracker.join("Software/probe/issues.org")).unwrap();
        assert!(org.contains(&format!("deed-file-commit-{sha}")), "{org}");
        let book = book_json(dir.path(), session);
        let deeds = deeds_of(&book);
        assert_eq!(deeds, vec![sha], "{book}");
    }

    /// ljos-qpiw: git's own stderr on exit 0 is still a commit to cite.
    /// A non-zero exit is not. A missing exit whose HEAD moved is.
    #[test]
    fn successful_commit_with_stderr_text_is_cited() {
        let _g = lock();
        let _saved = saved_env();
        let (dir, _tracker, repo) = scratch();
        let _bins = arm(dir.path(), &_tracker);
        let session = "qpiw";
        prompt_and_edit(&repo, session, "Add a readme line");
        let sha = commit_file(&repo, "README.md", "hello from cloudflare\n");
        let (post, post_call) = payload(
            "PostToolUse",
            session,
            &repo,
            serde_json::json!({
                "tool_name": "bash",
                "tool_input": {"command": "git add README.md && git commit -m 'land a line'"},
                "tool_response": {
                    "output": "1 file changed, 1 insertion(+)",
                    "error": "1 file changed, 1 insertion(+)",
                    "exit_code": 0
                }
            }),
        );
        let _ = observe(&post, &post_call);
        let book = book_json(dir.path(), session);
        assert_eq!(deeds_of(&book), vec![sha.clone()], "{book}");
        git(
            &repo,
            &["commit", "--allow-empty", "-m", "a failed attempt"],
        );
        let missed = head_sha_of(&repo);
        let (failed, failed_call) = payload(
            "PostToolUse",
            session,
            &repo,
            serde_json::json!({
                "tool_name": "bash",
                "tool_input": {"command": "git commit --allow-empty -m 'a failed attempt'"},
                "tool_response": {"error": "nothing to commit", "exit_code": 1}
            }),
        );
        let _ = observe(&failed, &failed_call);
        let book = book_json(dir.path(), session);
        let deeds = deeds_of(&book);
        assert!(deeds.contains(&sha), "{book}");
        assert!(!deeds.contains(&missed), "{book}");
        let quiet = commit_file(&repo, "quiet.txt", "no exit field\n");
        let (stderr_only, stderr_call) = payload(
            "PostToolUse",
            session,
            &repo,
            serde_json::json!({
                "tool_name": "bash",
                "tool_input": {"command": "git commit -m quiet"},
                "tool_response": {"error": "1 file changed, 1 insertion(+)"}
            }),
        );
        let _ = observe(&stderr_only, &stderr_call);
        let book = book_json(dir.path(), session);
        assert!(
            deeds_of(&book).contains(&quiet),
            "HEAD moved and no exit code is a landed commit: {book}"
        );
    }

    /// ljos-tha1: a session killed before Stop leaves its claim open.
    /// The next session finishes a book whose runner pid is dead.
    #[test]
    fn dead_runner_claims_finish_at_the_next_session() {
        let _g = lock();
        let _saved = saved_env();
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        let gone = dead_pid();
        for session in ["dead-a", "dead-b"] {
            prompt_and_edit(&repo, session, "Add a readme line");
            set_owner(dir.path(), session, gone);
        }
        prompt_and_edit(&repo, "live-one", "still running");
        let (start, start_call) = payload(
            "UserPromptSubmit",
            "next-sitting",
            &repo,
            serde_json::json!({"prompt": "a later sitting"}),
        );
        let _ = observe(&start, &start_call);
        for session in ["dead-a", "dead-b"] {
            let book = book_json(dir.path(), session);
            let row = book["repos"].as_object().unwrap().values().next().unwrap();
            assert_eq!(row["finished"], true, "{session}: {book}");
        }
        let live = book_json(dir.path(), "live-one");
        let row = live["repos"].as_object().unwrap().values().next().unwrap();
        assert_eq!(row["finished"], false, "{live}");
        assert_eq!(
            git_log(&tracker).matches("finished").count(),
            2,
            "{}",
            git_log(&tracker)
        );
    }

    /// ljos-gfiz: a cited commit that never landed is replaced by the
    /// commit that did, and the lesson names that one.
    #[test]
    fn deed_follows_the_commit_that_landed() {
        let _g = lock();
        let _saved = saved_env();
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        let texts = Arc::new(Mutex::new(Vec::<String>::new()));
        let kept = serve_pack({
            let texts = Arc::clone(&texts);
            move |req| keep_atom(req, &texts)
        });
        set_var("PACKSET_URL", &kept);
        set_var("PACKSET_TIMEOUT_MS", "2000");
        let session = "gfiz";
        prompt_and_edit(&repo, session, "Add a readme line");
        let abandoned = commit_file(&repo, "README.md", "hello from the first sha\n");
        let (post, post_call) = payload(
            "PostToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Bash", "tool_input": {"command": "git commit -m 'land a line'"}, "tool_response": {"exit_code": 0}}),
        );
        let _ = observe(&post, &post_call);
        let (stop, stop_call) = payload("Stop", session, &repo, Value::Null);
        let _ = observe(&stop, &stop_call);
        git(&repo, &["commit", "--amend", "-m", "landed"]);
        let landed = head_sha_of(&repo);
        assert_ne!(abandoned, landed);
        let (next, next_call) = payload(
            "UserPromptSubmit",
            "gfiz-next",
            &repo,
            serde_json::json!({"prompt": "next sitting"}),
        );
        let _ = observe(&next, &next_call);
        let book = book_json(dir.path(), session);
        assert_eq!(deeds_of(&book), vec![landed.clone()], "{book}");
        let stored = texts.lock().unwrap().clone();
        let lesson = stored.last().expect("a lesson was posted");
        assert!(lesson.contains(&landed[..7]), "{lesson}");
        assert!(!lesson.contains(&abandoned[..7]), "{lesson}");
        let org = std::fs::read_to_string(tracker.join("Software/probe/issues.org")).unwrap();
        assert!(org.contains(&format!("deed-file-commit-{landed}")), "{org}");
    }

    /// A prompt answers inside the sweep budget however many past sittings
    /// the seat keeps, and the sweeps still reach every book: a sha found in
    /// HEAD is remembered, so a later pass does not ask git again.
    #[test]
    fn a_prompt_does_not_wait_on_the_seats_history() {
        let _g = lock();
        let _saved = saved_env();
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        let head = head_sha_of(&repo);
        let repo_key = repo.display().to_string();
        let sittings = 300;
        for n in 0..sittings {
            let mut book = Book::default();
            book.repos.insert(
                repo_key.clone(),
                RepoBook {
                    issue: Some("probe-aaaa".into()),
                    deeds: vec![head.clone()],
                    finished: true,
                    lesson: true,
                    ..RepoBook::default()
                },
            );
            let path = book_path(&format!("old-{n}"));
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            store_book(&path, &book);
        }
        let landed = || {
            (0..sittings)
                .filter(|n| {
                    let book = load_book(&book_path(&format!("old-{n}")));
                    book.repos.values().all(|row| !row.landed.is_empty())
                })
                .count()
        };
        assert_eq!(landed(), 0);
        let mut passes = 0;
        while landed() < sittings && passes < 60 {
            let (raw, call) = payload(
                "UserPromptSubmit",
                "now",
                &repo,
                serde_json::json!({"prompt": "summarize the failing build"}),
            );
            let started = std::time::Instant::now();
            let _ = observe(&raw, &call);
            let took = started.elapsed();
            assert!(
                took < std::time::Duration::from_millis(2500),
                "pass {passes} took {took:?}"
            );
            passes += 1;
        }
        assert_eq!(landed(), sittings, "the sweep reached every book");
    }

    fn saved_env() -> Restore {
        Restore::new(&[
            "PATH",
            "VISSUE_ROOT",
            "VISSUE_NO_ROUTE",
            "LJOS_TRACKER_GIT",
            "LJOS_PROJECT",
            "XDG_RUNTIME_DIR",
            "LJOS_IN_HOOK",
            "PACKSET_URL",
            "ISSUE_ROOT",
            "LJOS_OFF",
            "LJOS_SESSION_ID",
            "PACKSET_TIMEOUT_MS",
        ])
    }

    fn set_var(key: &str, value: &str) {
        unsafe { std::env::set_var(key, value) };
    }

    /// A Codex 0.163 transcript line, trimmed to the fields the exit lookup
    /// reads. `Some` is the completed `CommandExecution` item (`id`, not
    /// `call_id`). `None` is the `function_call`, which names the id and
    /// carries no code.
    fn codex_event(call_id: &str, exit_code: Option<i64>) -> String {
        match exit_code {
            Some(code) => serde_json::json!({
                "timestamp": "2026-10-17T21:25:30.203Z",
                "type": "event_msg",
                "payload": {
                    "type": "item_completed",
                    "item": {
                        "type": "CommandExecution",
                        "id": call_id,
                        "command": ["/bin/bash", "-lc", "true"],
                        "status": if code == 0 { "completed" } else { "failed" },
                        "exit_code": code,
                    }
                }
            })
            .to_string(),
            None => serde_json::json!({
                "timestamp": "2026-10-17T21:25:30.129Z",
                "type": "response_item",
                "payload": {
                    "type": "function_call",
                    "name": "exec_command",
                    "call_id": call_id,
                    "arguments": "{}",
                }
            })
            .to_string(),
        }
    }

    /// The `function_call_output` whose `call_id` matches. The code is only
    /// the harness sentence, as Codex 0.163 writes it.
    fn function_output_line(call_id: &str, code: i64) -> String {
        serde_json::json!({
            "timestamp": "2026-10-17T21:25:30.218Z",
            "type": "response_item",
            "payload": {
                "type": "function_call_output",
                "call_id": call_id,
                "output": format!(
                    "Chunk ID: 13ab48\nWall time: 0.0000 seconds\nProcess exited with code {code}\nOriginal token count: 46\nOutput:\nModuleNotFoundError: No module named 'slug'\n"
                ),
            }
        })
        .to_string()
    }

    fn codex_post(
        session: &str,
        repo: &Path,
        tool_use_id: &str,
        command: &str,
        response: &str,
        transcript: &Path,
    ) -> (String, crate::HookCall) {
        payload(
            "PostToolUse",
            session,
            repo,
            serde_json::json!({
                "tool_name": "Bash",
                "tool_use_id": tool_use_id,
                "tool_input": {"command": command},
                "tool_response": response,
                "transcript_path": transcript,
            }),
        )
    }

    fn arm_lessons(dir: &Path) -> Arc<Mutex<Vec<Value>>> {
        let marker = dir.join("run/ljos/encoder-warming");
        std::fs::create_dir_all(marker.parent().unwrap()).unwrap();
        std::fs::write(&marker, "").unwrap();
        let atoms = Arc::new(Mutex::new(Vec::<Value>::new()));
        let pack = serve_lessons(Arc::clone(&atoms));
        set_var("PACKSET_URL", &pack);
        set_var("PACKSET_TIMEOUT_MS", "2000");
        atoms
    }

    fn serve_lessons(atoms: Arc<Mutex<Vec<Value>>>) -> String {
        serve_pack(move |req| {
            let path = req.lines().next().unwrap_or("");
            if path.contains("POST /v1/atoms") {
                let body = req
                    .split_once("\r\n\r\n")
                    .map(|(_, body)| body)
                    .unwrap_or("");
                if let Ok(atom) = serde_json::from_str::<Value>(body) {
                    atoms.lock().unwrap().push(atom);
                }
                return (
                    200,
                    r#"{"id":"atom-codex","kind":"lesson","origin":"agent-derived"}"#.into(),
                );
            }
            if path.contains("GET /v1/status") {
                return (
                    200,
                    r#"{"embedder":{"available":true,"answering":null}}"#.into(),
                );
            }
            if path.contains("GET /v1/atoms") {
                let list = atoms.lock().unwrap().clone();
                return (200, serde_json::json!({"atoms": list}).to_string());
            }
            (200, "{}".into())
        })
    }

    fn head_sha_of(repo: &Path) -> String {
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(repo)
            .args(["rev-parse", "HEAD"])
            .output()
            .unwrap();
        String::from_utf8(out.stdout).unwrap().trim().to_string()
    }

    fn commit_file(repo: &Path, name: &str, body: &str) -> String {
        std::fs::write(repo.join(name), body).unwrap();
        git(repo, &["add", name]);
        git(repo, &["commit", "-q", "-m", name]);
        head_sha_of(repo)
    }

    fn prompt_and_edit(repo: &Path, session: &str, prompt: &str) {
        let (raw, call) = payload(
            "UserPromptSubmit",
            session,
            repo,
            serde_json::json!({"prompt": prompt}),
        );
        let _ = observe(&raw, &call);
        let (raw, call) = payload(
            "PreToolUse",
            session,
            repo,
            serde_json::json!({"tool_name": "Write", "tool_input": {"file_path": "README.md"}}),
        );
        let _ = observe(&raw, &call);
    }

    fn book_json(dir: &Path, session: &str) -> Value {
        let path = dir.join(format!(
            "run/ljos/book-{}.json",
            crate::session_tag(session)
        ));
        serde_json::from_str(
            &std::fs::read_to_string(&path)
                .unwrap_or_else(|_| panic!("no book for {session} at {}", path.display())),
        )
        .unwrap()
    }

    fn deeds_of(book: &Value) -> Vec<String> {
        book["repos"]
            .as_object()
            .unwrap()
            .values()
            .flat_map(|row| {
                row["deeds"]
                    .as_array()
                    .into_iter()
                    .flatten()
                    .filter_map(|v| v.as_str().map(str::to_string))
            })
            .collect()
    }

    fn set_owner(dir: &Path, session: &str, pid: u32) {
        let path = dir.join(format!(
            "run/ljos/book-{}.json",
            crate::session_tag(session)
        ));
        let mut book: Value =
            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        book["owner_pid"] = serde_json::json!(pid);
        std::fs::write(&path, serde_json::to_string(&book).unwrap()).unwrap();
    }

    fn dead_pid() -> u32 {
        let mut child = std::process::Command::new("true").spawn().unwrap();
        let pid = child.id();
        let _ = child.wait();
        assert!(!crate::pid_alive(pid), "pid {pid} is still alive");
        pid
    }

    fn assert_lesson(text: &str) {
        let mut atom = serde_json::json!({
            "kind": "lesson",
            "text": text,
            "workspace": "seat",
            "origin": "agent-derived",
        });
        let map = atom.as_object_mut().expect("atom");
        if let Err(e) = packset_core::record::validate(map) {
            panic!("{text}: {e}");
        }
    }

    fn serve_pack(on: impl Fn(&str) -> (u16, String) + Send + 'static) -> String {
        use std::io::{Read, Write};
        use std::net::TcpListener;
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        std::thread::spawn(move || {
            for stream in listener.incoming() {
                let Ok(mut stream) = stream else {
                    break;
                };
                let mut buf = Vec::new();
                let mut tmp = [0u8; 2048];
                while let Ok(n) = stream.read(&mut tmp) {
                    if n == 0 {
                        break;
                    }
                    buf.extend_from_slice(&tmp[..n]);
                    let Some(at) = buf.windows(4).position(|w| w == b"\r\n\r\n") else {
                        continue;
                    };
                    let mut need = 0usize;
                    for line in buf[..at].split(|b| *b == b'\n') {
                        let line = std::str::from_utf8(line).unwrap_or("").trim();
                        let Some((name, value)) = line.split_once(':') else {
                            continue;
                        };
                        if name.eq_ignore_ascii_case("content-length") {
                            need = value.trim().parse().unwrap_or(0);
                        }
                    }
                    if buf.len().saturating_sub(at + 4) >= need {
                        break;
                    }
                }
                let req = String::from_utf8_lossy(&buf).into_owned();
                let (code, body) = on(&req);
                let status = if code == 200 {
                    "200 OK"
                } else {
                    "400 Bad Request"
                };
                let resp = format!(
                    "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
                    body.len()
                );
                let _ = stream.write_all(resp.as_bytes());
            }
        });
        format!("http://{addr}")
    }

    fn keep_atom(req: &str, texts: &Mutex<Vec<String>>) -> (u16, String) {
        let path = req.lines().next().unwrap_or("");
        let body = req
            .split_once("\r\n\r\n")
            .map(|(_, body)| body)
            .unwrap_or("");
        if path.contains("POST /v1/atoms") {
            let atom: Value = serde_json::from_str(body).unwrap_or(Value::Null);
            if let Some(text) = atom["text"].as_str() {
                texts.lock().unwrap().push(text.to_string());
            }
            return (
                200,
                r#"{"id":"atom-1","kind":"lesson","origin":"agent-derived"}"#.into(),
            );
        }
        (200, "{}".into())
    }

    fn git_log(tracker: &Path) -> String {
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(tracker)
            .args(["log", "--format=%s"])
            .output()
            .unwrap();
        String::from_utf8_lossy(&out.stdout).into_owned()
    }

    /// File an issue in the stub tracker the way a person would, outside
    /// any sitting, and give its id.
    fn file_by_hand(title: &str) -> String {
        let out = std::process::Command::new("vissue")
            .args(["create", "-p", "probe", title, "-q"])
            .output()
            .unwrap();
        String::from_utf8(out.stdout).unwrap().trim().to_string()
    }

    fn land_commit(repo: &Path, file: &str, message: &str) -> String {
        std::fs::write(repo.join(file), "x\n").unwrap();
        git(repo, &["add", file]);
        git(repo, &["commit", "-q", "-m", message]);
        let out = std::process::Command::new("git")
            .arg("-C")
            .arg(repo)
            .args(["rev-parse", "HEAD"])
            .output()
            .unwrap();
        String::from_utf8(out.stdout).unwrap().trim().to_string()
    }

    fn issue_state(tracker: &Path, issue: &str) -> String {
        let org = std::fs::read_to_string(tracker.join("Software/probe/issues.org")).unwrap();
        let at = org.find(&format!(":ID:         {issue}\n")).unwrap();
        let head = org[..at].rfind("* ").unwrap();
        org[head + 2..]
            .split_whitespace()
            .next()
            .unwrap()
            .to_string()
    }

    fn hook_row(session: &str, repo: &Path) -> RepoBook {
        load_book(&book_path(session))
            .repos
            .get(repo.to_str().unwrap())
            .cloned()
            .unwrap_or_default()
    }

    /// The willma w1 shape: session 2's first edit files a placeholder,
    /// then the commit names the reopened session 1 issue. The row moves to
    /// the named issue with the sha in `deeds`, and the placeholder is
    /// cancelled.
    #[test]
    fn a_named_commit_takes_over_the_empty_issue_the_edit_filed() {
        let _g = lock();
        let _saved = saved_env();
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        let named = file_by_hand("Add slugify function and tests");
        let session = "harness-named-takeover";
        let (raw, call) = payload(
            "PostToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Edit", "tool_input": {"file_path": "slug.py"}}),
        );
        let _ = observe(&raw, &call);
        let auto = hook_row(session, &repo)
            .issue
            .expect("the edit filed a claim");
        assert_ne!(auto, named);
        let message = format!("{named}: add kebab_case");
        let sha = land_commit(&repo, "slug.py", &message);
        let (raw, call) = payload(
            "PostToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Bash",
                "tool_input": {"command": format!("git commit -m \"{message}\"")},
                "tool_response": {"exit_code": 0}}),
        );
        let _ = observe(&raw, &call);
        let row = hook_row(session, &repo);
        assert_eq!(row.issue.as_deref(), Some(named.as_str()));
        assert_eq!(row.deeds, vec![sha.clone()]);
        assert!(row.elsewhere.is_empty(), "{:?}", row.elsewhere);
        assert!(row.also.is_empty(), "{:?}", row.also);
        assert!(row.named && !row.filed);
        assert_eq!(issue_state(&tracker, &auto), "CANCELLED");
        let log =
            std::fs::read_to_string(crate::runtime_dir().join("book.log")).unwrap_or_default();
        assert!(log.contains(&format!("claim: cancelled {auto}")), "{log}");
        assert_eq!(creates(&tracker), 2, "the commit filed no third issue");
    }

    /// A placeholder that already has a deed is real work: the named
    /// commit is booked beside it, and it is not cancelled.
    #[test]
    fn a_named_commit_keeps_a_filed_issue_that_has_a_deed() {
        let _g = lock();
        let _saved = saved_env();
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        let named = file_by_hand("Add slugify function and tests");
        let session = "harness-named-keeps";
        let (raw, call) = payload(
            "PostToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Edit", "tool_input": {"file_path": "slug.py"}}),
        );
        let _ = observe(&raw, &call);
        let auto = hook_row(session, &repo).issue.unwrap();
        let first = land_commit(&repo, "one.txt", "add one");
        let (raw, call) = payload(
            "PostToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Bash",
                "tool_input": {"command": "git commit -m \"add one\""},
                "tool_response": {"exit_code": 0}}),
        );
        let _ = observe(&raw, &call);
        assert_eq!(hook_row(session, &repo).deeds, vec![first]);
        let message = format!("{named}: add kebab_case");
        let sha = land_commit(&repo, "two.txt", &message);
        let (raw, call) = payload(
            "PostToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Bash",
                "tool_input": {"command": format!("git commit -m \"{message}\"")},
                "tool_response": {"exit_code": 0}}),
        );
        let _ = observe(&raw, &call);
        let row = hook_row(session, &repo);
        assert_eq!(row.issue.as_deref(), Some(auto.as_str()));
        assert_eq!(row.also, vec![named]);
        assert!(row.elsewhere.contains(&sha));
        assert_eq!(issue_state(&tracker, &auto), "STARTED");
    }

    /// A placeholder another holder has on the tracker is theirs: the
    /// named commit leaves it alone.
    #[test]
    fn a_named_commit_leaves_a_filed_issue_another_holder_has() {
        let _g = lock();
        let _saved = saved_env();
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        let named = file_by_hand("Add slugify function and tests");
        let session = "harness-named-other";
        let (raw, call) = payload(
            "PostToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Edit", "tool_input": {"file_path": "slug.py"}}),
        );
        let _ = observe(&raw, &call);
        let auto = hook_row(session, &repo).issue.unwrap();
        let org_path = tracker.join("Software/probe/issues.org");
        let org = std::fs::read_to_string(&org_path).unwrap();
        let needle = format!(":ID:         {auto}\n");
        std::fs::write(
            &org_path,
            org.replace(&needle, &format!("{needle}:CLAIMED_BY: someone-else@zz9\n")),
        )
        .unwrap();
        let message = format!("{named}: add kebab_case");
        let _ = land_commit(&repo, "slug.py", &message);
        let (raw, call) = payload(
            "PostToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Bash",
                "tool_input": {"command": format!("git commit -m \"{message}\"")},
                "tool_response": {"exit_code": 0}}),
        );
        let _ = observe(&raw, &call);
        assert_eq!(
            hook_row(session, &repo).issue.as_deref(),
            Some(auto.as_str())
        );
        assert_eq!(issue_state(&tracker, &auto), "STARTED");
    }

    /// The willma w1 session 2 shape: the edit filed an issue, then
    /// `ljos_start` ran with a task of its own. The start keeps that issue,
    /// files nothing, and notes the task on it.
    #[test]
    fn ljos_start_keeps_the_issue_the_edit_already_filed() {
        let _g = lock();
        let _saved = Restore::new(&[
            "PATH",
            "VISSUE_ROOT",
            "VISSUE_NO_ROUTE",
            "LJOS_TRACKER_GIT",
            "LJOS_PROJECT",
            "XDG_RUNTIME_DIR",
            "LJOS_IN_HOOK",
            "PACKSET_URL",
            "ISSUE_ROOT",
            "LJOS_OFF",
            "LJOS_SESSION_ID",
            "LJOS_HARNESS_SESSION",
            "LJOS_SEAT",
        ]);
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        unsafe {
            std::env::remove_var("LJOS_SEAT");
            std::env::remove_var("LJOS_HARNESS_SESSION");
        }
        let session = "harness-edit-then-start";
        let (raw, call) = payload(
            "PostToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Edit", "tool_input": {"file_path": "slug.py"}}),
        );
        let _ = observe(&raw, &call);
        let auto = hook_row(session, &repo).issue.unwrap();
        assert_eq!(creates(&tracker), 1);
        unsafe { std::env::set_var("LJOS_SESSION_ID", "mcp-after-edit") };
        let said = start_work(
            None,
            Some(repo.to_str().unwrap()),
            "add kebab_case function and test",
        )
        .unwrap();
        assert_eq!(
            said.lines().next(),
            Some(format!("claimed {auto}").as_str())
        );
        assert_eq!(creates(&tracker), 1, "ljos_start filed a second issue");
        let vissue = std::fs::read_to_string(tracker.join("vissue.log")).unwrap();
        assert!(
            vissue.contains(&format!("note {auto} ljos_start task: add kebab_case")),
            "{vissue}"
        );
        assert!(hook_row(session, &repo).issue.is_none());
        let start = load_book(&book_path(&sitting_key()));
        let row = start.repos.get(repo.to_str().unwrap()).unwrap();
        assert_eq!(row.issue.as_deref(), Some(auto.as_str()));
        assert!(row.started && row.filed);

        // The next write takes it back, and nothing is filed.
        let (raw, call) = payload(
            "PostToolUse",
            session,
            &repo,
            serde_json::json!({"tool_name": "Write", "tool_input": {"file_path": "test_kebab.py"}}),
        );
        let _ = observe(&raw, &call);
        assert_eq!(
            hook_row(session, &repo).issue.as_deref(),
            Some(auto.as_str())
        );
        assert_eq!(creates(&tracker), 1);
    }

    /// The willma w5 shape: a prompt, then the session ends before any
    /// edit. No row with a null issue is left.
    #[test]
    fn a_sitting_that_never_claimed_leaves_no_row() {
        let _g = lock();
        let _saved = saved_env();
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        let session = "harness-never-claimed";
        let (raw, call) = payload(
            "UserPromptSubmit",
            session,
            &repo,
            serde_json::json!({"prompt": "In this git repo, add a function slugify(s) to slug.py"}),
        );
        let _ = observe(&raw, &call);
        assert!(load_book(&book_path(session))
            .repos
            .values()
            .all(|row| row.issue.is_none()));
        let (raw, call) = payload("SessionEnd", session, &repo, serde_json::json!({}));
        let _ = observe(&raw, &call);
        let book = load_book(&book_path(session));
        assert!(book.repos.is_empty(), "{:?}", book.repos);
        assert_eq!(creates(&tracker), 0);
    }

    #[test]
    fn prompt_reads_are_bounded_by_bytes_on_large_regular_files() {
        use std::io::{Seek, SeekFrom, Write};
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("long-chat.jsonl");
        let mut file = std::fs::File::create(&path).unwrap();
        file.seek(SeekFrom::Start(64 * 1024 * 1024)).unwrap();
        file.write_all(b"\n{\"type\":\"user_message\",\"message\":\"check the saddle\"}\n")
            .unwrap();
        drop(file);
        let tail = read_text_bounded(&path).unwrap();
        assert!(tail.len() <= TRANSCRIPT_TAIL_BYTES as usize);
        assert_eq!(super::super::last_user_text(&tail), "check the saddle");
    }

    /// The idle sweep drops a row that never claimed, once it is idle.
    #[test]
    fn the_idle_sweep_drops_a_row_that_never_claimed() {
        let _g = lock();
        let _saved = saved_env();
        let (dir, tracker, repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        let mut book = Book::default();
        book.repos.insert(
            repo.to_str().unwrap().to_string(),
            RepoBook {
                start_sha: Some("1bfeb804".into()),
                title: Some("slugify".into()),
                last_unix: 1_000,
                ..RepoBook::default()
            },
        );
        book.last_unix = 1_000;
        let path = book_path("harness-idle-null");
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        store_book(&path, &book);
        close_idle_sittings(1_000 + 10 * 24 * 3600, None, None);
        assert!(load_book(&path).repos.is_empty());
        assert_eq!(creates(&tracker), 0);
    }

    /// A claim graph's release hands the placeholder back to TODO before
    /// the cancel runs. The cancel takes it from TODO too, and leaves an
    /// issue that is DONE by then alone.
    #[test]
    fn a_placeholder_released_to_todo_is_still_cancelled() {
        let _g = lock();
        let _saved = saved_env();
        let (dir, tracker, _repo) = scratch();
        let _bins = arm(dir.path(), &tracker);
        let released = file_by_hand("Work in repo");
        assert_eq!(issue_state(&tracker, &released), "TODO");
        cancel_placeholder(&released, "probe-named");
        assert_eq!(issue_state(&tracker, &released), "CANCELLED");
        let done = file_by_hand("Work in repo again");
        let _ = std::process::Command::new("vissue")
            .args(["update", &done, "-s", "DONE"])
            .output()
            .unwrap();
        cancel_placeholder(&done, "probe-named");
        assert_eq!(issue_state(&tracker, &done), "DONE");
    }
}