repon 0.30.5

A terminal UI for the outer loop: seeing many git repos at once and acting on many in one gesture
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
//! The detail pane: entity identity and path, one line per value with its provenance spelled
//! out in words plus its age, recent commits, any in-progress git operation, and a section for
//! the last Action's own outcome. [layout-and-provenance.md](../../../../docs/spec/layout-and-provenance.md)'s
//! "The detail pane" fixes what this shows; [ADR 0019](../../../../docs/adr/0019-a-detached-head-is-a-shape-of-head-not-a-worktree-state.md)
//! fixes the in-progress operation's home here and nowhere else: not a state, not a gutter
//! mark, and never a gate refusing an Action the user typed.
//!
//! A step's own captured output is parsed from raw ANSI bytes into styled spans here, in
//! this crate, and nowhere in `repon-core`: `docs/spec/actions.md`'s "The run on screen"
//! puts the parse "in the consumer, never in repon-core", since the parser produces ratatui
//! types the core's own dependency allowlist cannot carry. The mark standing in for what a
//! bounded capture dropped is chosen here for the same reason: the core reports the drop as
//! a `CaptureElision`'s two counts and never names a glyph. Those spans take the child's own
//! literal colour, never a theme [`Role`], because that output is a quotation of another
//! program's screen; [`ContentLine::Raw`] is the one place in this module a real
//! [`ratatui::style::Style`] reaches the buffer instead of a role resolved against the
//! live theme. The elision row is the one row inside that region Repon writes itself, and it
//! takes no role and no child colour but a default style, `docs/spec/actions.md`'s own rule
//! for it.

use ansi_to_tui::IntoText;
use ratatui::{
    Frame,
    buffer::Buffer,
    layout::Rect,
    style::Style,
    widgets::{Scrollbar, ScrollbarOrientation, ScrollbarState, StatefulWidget},
};
use repon_core::{
    ActionReceipt, CaptureElision, DefaultBranch, DefaultBranchStopped, Diagnostics, DirtyCounts,
    EntityState, Head, InProgressOperation, Kind, OwnWork, RunningStep, Settled, StepOutcome,
    StepResult, SyncState, Timestamp, Unknown,
};

use super::list::{
    base_meaning, dirty_meaning, name_cell_meaning, spinner_frame, state_meaning,
    worktree_state_word, write_cell_runs,
};
use crate::{
    elapsed::format_seconds_elapsed,
    glyphs::{BorderScratch, FULL_SPINNER_INTERVAL, GlyphSet},
    keys::Action,
    scroll::scroll_after,
    theme::{Meaning, Role, Theme},
};

/// Columns eaten by the pane's own border, subtracted from an area's width to get the
/// interior [`ratatui::widgets::Block::inner`] draws into: one column of `│` on each side.
const BORDER_WIDTH: u16 = 2;

/// The pane's own scroll position. Owns no content of its own: [`content_lines`] derives it
/// fresh from the entity on every call, the same shape [`crate::help::HelpOverlay`] takes.
#[derive(Default)]
pub struct Detail {
    scroll: u16,
}

impl Detail {
    /// Folds one of the pane's own scroll actions into its offset, clamped to `content_len`.
    pub fn apply(&mut self, action: Action, content_len: usize, viewport_height: u16) {
        self.scroll = scroll_after(self.scroll, action, content_len, viewport_height);
    }

    /// How many lines [`content_lines`] would produce for `entity` at `area_width` (the same
    /// outer area [`Detail::draw`] is given, border included), without building any of them:
    /// the scroll clamp only ever needs the count. Takes the width and the glyph set because
    /// a captured Action step's output wraps to the pane's own interior and a still-running
    /// step's own line carries a glyph set's own spinner character, so either changing
    /// changes how many screen rows, or which characters, the same content fills.
    pub fn content_len(entity: &EntityState, area_width: u16, glyphs: &'static GlyphSet) -> usize {
        content_lines(entity, interior_width(area_width), glyphs).len()
    }

    /// Draws the pane's border and content into `area`. `focused` picks the border role,
    /// [theming.md](../../../../docs/spec/theming.md)'s "focus communicated by border colour":
    /// this is the one place two panels can be on screen together, so `List` reads the same
    /// real focus flag through [`crate::components::Component::draw`] rather than either
    /// panel always painting itself focused. `theme` is the live, loaded theme, not the
    /// compiled default:
    /// a theme file's own colours must reach this pane the same as the palettes and the
    /// status bar already do. The top title names `entity`, following the superfile research's
    /// own "the panel title, path, mode, and cursor position in the border itself" import; the
    /// close hint moves to a right-aligned `title_bottom`, sharing `warnings.rs`'s own
    /// [`crate::warnings::CLOSE_HINT`] rather than a second copy of the same words.
    pub fn draw(
        &self,
        frame: &mut Frame,
        area: Rect,
        entity: &EntityState,
        glyphs: &'static GlyphSet,
        focused: bool,
        theme: &Theme,
    ) {
        let role = if focused {
            Role::BorderFocused
        } else {
            Role::Border
        };
        let mut scratch = BorderScratch::new();
        let block = glyphs
            .bordered_block(&mut scratch)
            .border_style(theme.style_for(role))
            .title(format!(" {} ", entity.name))
            .title_bottom(ratatui::text::Line::from(crate::warnings::CLOSE_HINT).right_aligned());
        let interior = block.inner(area);
        frame.render_widget(block, area);

        let lines = styled_content_lines(entity, interior.width, glyphs);
        let buf = frame.buffer_mut();
        draw_lines(buf, interior, &lines, self.scroll, theme);
        draw_scrollbar(
            buf,
            area,
            interior,
            lines.len(),
            self.scroll,
            glyphs,
            theme.style_for(role),
        );
    }
}

/// `area_width` (the outer, bordered area) minus the one-column border on each side, the
/// same subtraction [`ratatui::widgets::Block::inner`] performs; kept as its own function so
/// [`Detail::content_len`]'s clamp and [`Detail::draw`]'s own `block.inner(area)` can never
/// disagree about how wide the interior actually is.
fn interior_width(area_width: u16) -> u16 {
    area_width.saturating_sub(BORDER_WIDTH)
}

/// One piece of a content line's text paired with the theme role it paints in:
/// [theming.md](../../../../docs/spec/theming.md)'s "the detail pane's labels are `dim` and
/// its values take whichever role their meaning already has."
type Span = (String, Role);

/// A whole content line as the styled pieces [`draw_lines`] paints left to right, in the
/// same run-based shape `list.rs`'s `sync` column already paints its own two-meaning cell
/// with. [`content_lines`] flattens the same lines to plain text for every caller that only
/// wants the words.
type StyledLine = Vec<Span>;

/// One row [`draw_lines`] paints: almost every row takes its colour from a theme [`Role`]
/// ([`Styled`](ContentLine::Styled)), while every row inside a captured step's own quoted
/// region is a [`Raw`](ContentLine::Raw) carrying a real [`Style`], per this module's own
/// top-level doc comment. Two kinds of row live there: the child's own output, which carries
/// the child's literal [`Style`], and [`elision_row`], Repon's own text about the quotation,
/// which carries [`Style::default`]. [`content_lines`] flattens either shape to plain text.
#[derive(Debug)]
enum ContentLine {
    Styled(StyledLine),
    Raw(Vec<(String, Style)>),
}

impl ContentLine {
    /// The spans of a `Styled` line. Every call site in this module's own test suite that
    /// indexes a line by position built it as `Styled` itself, so a `Raw` line here is a
    /// test bug, not a shape this needs to render around.
    #[cfg(test)]
    fn spans(&self) -> &StyledLine {
        match self {
            ContentLine::Styled(spans) => spans,
            ContentLine::Raw(_) => panic!("expected a Styled content line, got {self:?}"),
        }
    }

    /// The first run's own text, regardless of which shape this line is: what a test scanning
    /// for a line by its opening word needs, without caring whether that line is `Styled` or
    /// `Raw`.
    #[cfg(test)]
    fn first_text(&self) -> Option<&str> {
        match self {
            ContentLine::Styled(spans) => spans.first().map(|(text, _)| text.as_str()),
            ContentLine::Raw(runs) => runs.first().map(|(text, _)| text.as_str()),
        }
    }
}

/// A line with no styled distinction of its own: theming.md names no meaning for it, so it
/// takes `text`, the map's own default for a value named nowhere else.
fn plain(text: String) -> StyledLine {
    vec![(text, Role::Text)]
}

/// A label (always `dim`) followed by a value's own styled spans.
fn labelled(label: &str, value: StyledLine) -> StyledLine {
    let mut line = vec![(label.to_string(), Role::Dim)];
    line.extend(value);
    line
}

/// Draws as many of `lines` as fit `area`, starting from `scroll`, one per row, each line's
/// spans painted left to right sharing one width budget the way [`super::list::write_cell_runs`]
/// already paints the list's own multi-role `sync` cell, rather than a second answer for the
/// same "more than one role in one string" shape.
fn draw_lines(buf: &mut Buffer, area: Rect, lines: &[ContentLine], scroll: u16, theme: &Theme) {
    for (row, line) in lines
        .iter()
        .skip(scroll as usize)
        .take(area.height as usize)
        .enumerate()
    {
        let runs: Vec<(String, Style)> = match line {
            ContentLine::Styled(spans) => spans
                .iter()
                .map(|(text, role)| (text.clone(), theme.style_for(*role)))
                .collect(),
            ContentLine::Raw(runs) => runs.clone(),
        };
        write_cell_runs(buf, area, area.x, area.y + row as u16, area.width, &runs);
    }
}

/// Draws the pane's own scrollbar over its right border, or nothing at all when every line
/// already fits the interior: a pane showing all it has looks exactly as it did before this
/// existed. `style` is the border's own resolved style, so the bar reads as part of the frame
/// it is painted over and carries the same focus colour, and its two characters come from the
/// live glyph table for the reason the frame's own do.
///
/// [`ScrollbarState`]'s `content_length` is given the number of scroll positions rather than
/// the line count: ratatui sizes and places the thumb against `content_length - 1 + viewport`,
/// so the line count would leave the thumb short of the bottom on a pane scrolled to its last
/// line, which is the one reading this bar exists to make certain.
fn draw_scrollbar(
    buf: &mut Buffer,
    area: Rect,
    interior: Rect,
    content_len: usize,
    scroll: u16,
    glyphs: &'static GlyphSet,
    style: Style,
) {
    let viewport = interior.height as usize;
    if viewport == 0 || area.width < BORDER_WIDTH || content_len <= viewport {
        return;
    }

    let mut track = [0u8; 4];
    let mut thumb = [0u8; 4];
    let bar = Scrollbar::new(ScrollbarOrientation::VerticalRight)
        .track_symbol(Some(glyphs.scrollbar_track.encode_utf8(&mut track)))
        .thumb_symbol(glyphs.scrollbar_thumb.encode_utf8(&mut thumb))
        .begin_symbol(None)
        .end_symbol(None)
        .track_style(style)
        .thumb_style(style);
    let mut state = ScrollbarState::new(content_len - viewport + 1).position(scroll as usize);
    bar.render(
        Rect::new(area.right() - 1, interior.y, 1, interior.height),
        buf,
        &mut state,
    );
}

/// Every line the pane shows, in order: identity and path, one line per Cell's provenance in
/// words plus age, any row-level failure the gutter's single `!` cannot itself distinguish, any
/// in-progress operation, recent commits, and the last Action's own outcome. Every caller that
/// only wants the words reads [`content_lines`]; [`Detail::draw`] reads this directly so the
/// label and each value keep the role theming.md's per-surface assignment gives them.
///
/// Destructures `EntityState` exhaustively rather than naming six cells by hand: a Cell or
/// fact added to the struct later fails to compile here instead of quietly never reaching the
/// pane, the project's own recurring defect this ticket was asked to watch for.
///
/// `interior_width` is the pane's own interior column count and `glyphs` the resolved glyph
/// set, the two things a captured Action step's own section needs and every other line here
/// ignores: `interior_width` is what a long captured line wraps to rather than truncating,
/// and `glyphs` names the spinner a still-running step's own line carries
/// (`docs/spec/actions.md`'s "The run on screen").
fn styled_content_lines(
    entity: &EntityState,
    interior_width: u16,
    glyphs: &'static GlyphSet,
) -> Vec<ContentLine> {
    let EntityState {
        key,
        name,
        common_dir: _,
        kind,
        branch,
        sync,
        base,
        dirty,
        state,
        default_branch,
        diagnostics,
        last_action,
        presence: _,
        excluded: _,
        in_progress_operation,
        recent_commits,
    } = entity;

    // Folded into the one fixed row `freshness_row` builds below, in place of the per-cell
    // suffix `describe_cell_spans` used to carry.
    let freshness = freshness_row(&[
        cell_freshness("branch", branch.settled(), branch.is_in_flight()),
        cell_freshness("sync", sync.settled(), sync.is_in_flight()),
        cell_freshness("base", base.settled(), base.is_in_flight()),
        cell_freshness("dirty", dirty.settled(), dirty.is_in_flight()),
        cell_freshness("state", state.settled(), state.is_in_flight()),
        cell_freshness(
            "default branch",
            default_branch.settled(),
            default_branch.is_in_flight(),
        ),
    ]);

    let mut lines: Vec<ContentLine> = Vec::new();
    lines.push(ContentLine::Styled(vec![
        (name.to_string(), name_cell_meaning(*kind).role()),
        (format!("  {}", kind_word(*kind)), Role::Dim),
    ]));
    lines.push(ContentLine::Styled(plain(key.path().display().to_string())));
    lines.push(ContentLine::Styled(plain(String::new())));

    lines.push(ContentLine::Styled(labelled(
        "branch          ",
        describe_cell_spans(branch.settled(), head_word, |_| Meaning::FreshValue),
    )));
    lines.push(ContentLine::Styled(labelled(
        "sync            ",
        describe_cell_spans(sync.settled(), sync_word, sync_meaning),
    )));
    lines.push(ContentLine::Styled(labelled(
        "base            ",
        describe_cell_spans(base.settled(), base_word, base_meaning),
    )));
    lines.push(ContentLine::Styled(labelled(
        "dirty           ",
        describe_cell_spans(dirty.settled(), dirty_word, dirty_meaning),
    )));
    lines.push(ContentLine::Styled(labelled(
        "state           ",
        describe_cell_spans(
            state.settled(),
            |value| worktree_state_word(value).to_string(),
            state_meaning,
        ),
    )));
    lines.push(ContentLine::Styled(labelled(
        "default branch  ",
        describe_cell_spans(default_branch.settled(), default_branch_word, |_| {
            Meaning::FreshValue
        }),
    )));
    for diagnostic_line in default_branch_diagnostics_lines(diagnostics) {
        lines.push(ContentLine::Styled(plain(format!(
            "                {diagnostic_line}"
        ))));
    }
    if let Some(freshness) = freshness {
        let (label, values, role) = match freshness {
            FreshnessRow::Loading(value) => {
                ("loading", vec![value], Meaning::LoadingSpinner.role())
            }
            FreshnessRow::Refreshed(values) => ("refreshed", values, Meaning::Age.role()),
        };
        // One `ContentLine` per breakdown entry so `draw_lines` paints each on its own screen
        // row; only the first carries the label, later entries indent under it.
        for (index, value) in values.into_iter().enumerate() {
            let label_text = if index == 0 {
                format!("{label:<16}")
            } else {
                " ".repeat(16)
            };
            lines.push(ContentLine::Styled(labelled(
                &label_text,
                vec![(value, role)],
            )));
        }
    }

    if let Some(reason) = row_level_failure(diagnostics, last_action) {
        lines.push(ContentLine::Styled(plain(String::new())));
        lines.push(ContentLine::Styled(vec![(
            reason,
            Meaning::FailedProvenance.role(),
        )]));
    }

    if let Some(operation) = in_progress_operation {
        lines.push(ContentLine::Styled(plain(String::new())));
        lines.push(ContentLine::Styled(plain(format!(
            "in progress: {}",
            in_progress_word(*operation)
        ))));
    }

    lines.push(ContentLine::Styled(plain(String::new())));
    lines.push(ContentLine::Styled(vec![(
        "recent".to_string(),
        Meaning::ColumnHeader.role(),
    )]));
    if recent_commits.is_empty() {
        lines.push(ContentLine::Styled(plain(
            "  no commits read yet".to_string(),
        )));
    } else {
        for commit in recent_commits {
            lines.push(ContentLine::Styled(plain(format!(
                "  {}  {}",
                commit.short_id, commit.summary
            ))));
        }
    }

    lines.push(ContentLine::Styled(plain(String::new())));
    lines.push(ContentLine::Styled(labelled(
        "last action   ",
        last_action_spans(last_action),
    )));
    if let Some(receipt) = last_action {
        lines.extend(action_run_lines(receipt, interior_width, glyphs));
    }

    lines
}

/// [`styled_content_lines`] flattened to plain text: every caller that only cares about the
/// words, including this pane's own scroll-length count and its own test suite.
fn content_lines(
    entity: &EntityState,
    interior_width: u16,
    glyphs: &'static GlyphSet,
) -> Vec<String> {
    styled_content_lines(entity, interior_width, glyphs)
        .into_iter()
        .map(|line| match line {
            ContentLine::Styled(spans) => spans.into_iter().map(|(text, _)| text).collect(),
            ContentLine::Raw(runs) => runs.into_iter().map(|(text, _)| text).collect(),
        })
        .collect()
}

/// The last Action's own outcome, in the role theming.md's map already gives that state: a
/// succeeded step is `ok`, a failed one `danger`, and a receipt that never ran or was
/// cancelled (there being none yet reads the same as one that was) is `dim`, the same role a
/// column header or a Merged Worktree takes. Delegates to [`ActionReceipt::failed`], the
/// classification chokepoint, rather than a wildcard arm of its own, so this can never
/// quietly disagree with what the gutter's row summary already calls a failure.
fn last_action_spans(last_action: &Option<ActionReceipt>) -> StyledLine {
    match last_action {
        Some(receipt) if receipt.failed() => {
            vec![("failed".to_string(), Meaning::FailedActionStep.role())]
        }
        Some(receipt) if receipt.refused() => vec![(
            "refused".to_string(),
            Meaning::ActionStepNotRunOrCancelled.role(),
        )],
        Some(_) => vec![("ok".to_string(), Meaning::SucceededActionStep.role())],
        None => vec![(
            "none yet".to_string(),
            Meaning::ActionStepNotRunOrCancelled.role(),
        )],
    }
}

/// Every line the last Action's own run adds beyond the one-word summary
/// [`last_action_spans`] already gives: each finished step's own header line and (if it
/// wrote any) its captured output, then the step now executing, if the run has not yet
/// finished (`docs/spec/actions.md`'s "The run on screen"). Nothing here for a step that
/// produced no output: `rm -rf node_modules` succeeding has nothing further to show, and a
/// `NotRun` step's own output is always empty, so this needs no separate case for either.
fn action_run_lines(
    receipt: &ActionReceipt,
    interior_width: u16,
    glyphs: &'static GlyphSet,
) -> Vec<ContentLine> {
    let mut lines = Vec::new();
    for (index, step) in receipt.steps.iter().enumerate() {
        lines.push(finished_step_line(index, step));
        lines.extend(captured_output_lines(
            &step.output,
            step.elision,
            interior_width,
            glyphs,
        ));
    }
    if let Some(running) = &receipt.running {
        lines.push(running_step_line(receipt.steps.len(), running, glyphs));
    }
    lines
}

/// A finished step's own outcome word, or, for a step Repon performed itself, Repon's own
/// sentence about it. Exhaustive over [`StepOutcome`]'s closed five, the same discipline
/// [`sync_word`] and [`stopped_word`] hold over their own closed sets, so a sixth variant
/// fails to compile here rather than falling through a default word.
fn step_outcome_word(outcome: &StepOutcome) -> String {
    match outcome {
        StepOutcome::Ok => "ok".to_string(),
        StepOutcome::Failed(code) => format!("failed exit {code}"),
        StepOutcome::NotRun => "not run".to_string(),
        StepOutcome::Cancelled => "cancelled".to_string(),
        StepOutcome::OwnWork(work) => work.said().to_string(),
    }
}

/// [`step_outcome_word`]'s own role: the same three meanings [`last_action_spans`] already
/// gives an Action's overall outcome, over the same closed five `StepOutcome` variants. A
/// refusal takes `dim` beside a cancelled step rather than `danger`, because nothing went
/// wrong (`docs/spec/actions.md`'s own role column for `OwnWork`).
fn step_outcome_meaning(outcome: &StepOutcome) -> Meaning {
    match outcome {
        StepOutcome::Ok | StepOutcome::OwnWork(OwnWork::Did(_)) => Meaning::SucceededActionStep,
        StepOutcome::Failed(_) | StepOutcome::OwnWork(OwnWork::CouldNotAct(_)) => {
            Meaning::FailedActionStep
        }
        StepOutcome::NotRun
        | StepOutcome::Cancelled
        | StepOutcome::OwnWork(OwnWork::Refused(_)) => Meaning::ActionStepNotRunOrCancelled,
    }
}

/// One finished step's own header line, in whichever of the two shapes its outcome earns.
/// Exhaustive rather than a default, so a sixth `StepOutcome` has to say which shape it draws
/// in rather than inheriting one.
fn finished_step_line(index: usize, step: &StepResult) -> ContentLine {
    match &step.outcome {
        StepOutcome::Ok | StepOutcome::Failed(_) | StepOutcome::NotRun | StepOutcome::Cancelled => {
            child_step_line(index, step)
        }
        StepOutcome::OwnWork(_) => own_work_line(step),
    }
}

/// `step.shell`'s own mark on the label, present only when it is `true`: a config step
/// defaults to argv and stays unmarked, so this only draws attention to the case worth
/// noticing, an ad hoc command's own default
/// ([`docs/spec/actions.md`](https://github.com/paulchiu/repon/blob/main/docs/spec/actions.md)'s
/// "The Selection and the gate"). `interactive` sharpens the tag to `[shell -ic]` rather than
/// a second, separate mark, since it only ever means anything alongside `shell`. One
/// rendering path for both origins, since `StepResult` carries no field saying which one
/// produced it.
fn shell_tag(shell: bool, interactive: bool) -> &'static str {
    match (shell, interactive) {
        (true, true) => "[shell -ic] ",
        (true, false) => "[shell] ",
        (false, _) => "",
    }
}

/// A child process step's own header line: its number, its outcome, its label (marked
/// [`shell_tag`] when it ran through a shell) and its elapsed time.
fn child_step_line(index: usize, step: &StepResult) -> ContentLine {
    ContentLine::Styled(vec![
        (format!("  step {}  ", index + 1), Role::Dim),
        (
            step_outcome_word(&step.outcome),
            step_outcome_meaning(&step.outcome).role(),
        ),
        (
            format!(
                "   {}{}   {}",
                shell_tag(step.shell, step.interactive),
                step.label,
                format_seconds_elapsed(step.elapsed)
            ),
            Role::Dim,
        ),
    ])
}

/// A step Repon performed itself: the operation, then Repon's own sentence about what it did
/// or would not do, then how long it took. No step number, because such an operation is one
/// act rather than a position in an ordered list, and the sentence leads rather than trails
/// because it is the answer this row exists to give
/// (`docs/spec/repo-management.md`'s "Receipts").
fn own_work_line(step: &StepResult) -> ContentLine {
    ContentLine::Styled(vec![
        (format!("  {}   ", step.label), Role::Dim),
        (
            step_outcome_word(&step.outcome),
            step_outcome_meaning(&step.outcome).role(),
        ),
        (
            format!("   {}", format_seconds_elapsed(step.elapsed)),
            Role::Dim,
        ),
    ])
}

/// The step executing right now's own header line: a spinner glyph in the position a
/// finished step's own outcome word occupies
/// (`docs/spec/actions.md`'s "a running step carries the spinner in the same position the
/// step number's outcome will occupy"), its label and its live elapsed time. Both the
/// spinner's own frame and the elapsed text are computed fresh from `running.started_at` on
/// every draw, so nothing here goes stale between two draws without this function running
/// again.
fn running_step_line(
    index: usize,
    running: &RunningStep,
    glyphs: &'static GlyphSet,
) -> ContentLine {
    let elapsed = running.started_at.elapsed();
    let frame = spinner_frame(glyphs.loading, FULL_SPINNER_INTERVAL, elapsed);
    ContentLine::Styled(vec![
        (
            format!("{frame} step {}  ", index + 1),
            Meaning::LoadingSpinner.role(),
        ),
        ("running".to_string(), Meaning::LoadingSpinner.role()),
        (
            format!(
                "   {}{}   {}",
                shell_tag(running.shell, running.interactive),
                running.label,
                format_seconds_elapsed(elapsed)
            ),
            Role::Dim,
        ),
    ])
}

/// Indentation a step's own captured output sits under its header line at, plain text with
/// no styling of its own.
const CAPTURED_OUTPUT_INDENT: &str = "    ";

/// The row standing in for what the capture bound dropped, drawn with the live glyph set's
/// own `capture_elision`, so `glyphs = "ascii"` renders `...` where `full` renders `···`.
/// The wording is `docs/spec/actions.md`'s own detail-pane mock.
///
/// The mark is picked here rather than in `repon-core` for [ADR 0015](../../../../docs/adr/0015-the-core-owns-the-table.md)'s
/// reason ("the consumer owns ... every glyph"), which is why the core hands over a
/// [`CaptureElision`] and not a formatted line.
fn elision_row(elision: CaptureElision, glyphs: &'static GlyphSet) -> String {
    // Destructured exhaustively rather than read field by field, so a third count added to
    // `CaptureElision` is a compile error here instead of a silently ignored field.
    let CaptureElision {
        dropped_lines,
        kept_head_lines: _,
    } = elision;
    let mark = glyphs.capture_elision;
    format!("{mark} {dropped_lines} lines elided {mark}")
}

/// Parses `output`'s raw ANSI SGR bytes into wrapped, styled lines at `interior_width`
/// columns, indented under the step header they belong to, with [`elision_row`] inserted
/// after `elision`'s own kept head if the capture was bounded. `output.into_text()` fails
/// only on invalid UTF-8, never observed from a real step's own capture; that fallback
/// reads the bytes lossily as plain, unstyled text instead, so a parse failure loses no
/// content, only its colour.
///
/// The elision row joins the parsed lines before wrapping rather than being spliced into
/// `output`'s bytes, so it is never mistaken for the child's own output and the child's own
/// output is never mistaken for it.
fn captured_output_lines(
    output: &[u8],
    elision: Option<CaptureElision>,
    interior_width: u16,
    glyphs: &'static GlyphSet,
) -> Vec<ContentLine> {
    if output.is_empty() {
        return Vec::new();
    }
    let wrap_width = (interior_width as usize).saturating_sub(CAPTURED_OUTPUT_INDENT.len());
    let mut parsed = parse_output_lines(output);
    if let Some(elision) = elision {
        // Exhaustive for the reason `elision_row` states.
        let CaptureElision {
            dropped_lines: _,
            kept_head_lines,
        } = elision;
        let at = kept_head_lines.min(parsed.len());
        parsed.insert(at, ratatui::text::Line::raw(elision_row(elision, glyphs)));
    }
    let mut lines = Vec::new();
    for line in parsed {
        let expanded = expand_tabs(&line);
        for row in wrap_output_line(&expanded, wrap_width) {
            let mut runs = vec![(CAPTURED_OUTPUT_INDENT.to_string(), Style::default())];
            runs.extend(row);
            lines.push(ContentLine::Raw(runs));
        }
    }
    lines
}

/// A terminal's own fixed tab-stop width, matching the columnar `ls` output
/// [issue #177](https://github.com/paulchiu/repon/issues/177) was raised against: a tab
/// advances to the next multiple of 8 columns, never a fixed number of characters.
const TAB_STOP: usize = 8;

/// Expands every tab in `line` to the spaces reaching its next [`TAB_STOP`]-column stop,
/// measured from column 0 of `line` itself, before wrapping and before
/// [`CAPTURED_OUTPUT_INDENT`] is prepended: the child that wrote the tab knows nothing of
/// either, so measuring against the wrapped, indented screen row would misalign every stop
/// by the indent's own width and reset the count at an arbitrary wrap boundary the child
/// never saw. Each inserted space keeps the style of the run the tab came from, so a tab
/// inside a coloured span still colours the space it becomes (ADR 0018, "Captured colours
/// are rendered rather than stripped").
///
/// Walks each span's own graphemes with [`unicode_segmentation`] directly rather than
/// [`ratatui::text::Line::styled_graphemes`]: that method's own `Span::styled_graphemes`
/// filters every control character out of the stream it yields
/// (`ratatui_core`'s `span.rs`, `.filter(|g| !g.contains(char::is_control))`), which drops a
/// raw tab before this function would ever see it, silently, with no line or symbol left
/// behind to expand. Each span's own resolved style is `line.style` patched with that
/// span's own style, the same two-step patch `styled_graphemes` itself performs.
fn expand_tabs(line: &ratatui::text::Line<'static>) -> ratatui::text::Line<'static> {
    use unicode_segmentation::UnicodeSegmentation;

    let mut runs: Vec<(String, Style)> = Vec::new();
    let mut column = 0usize;
    for span in &line.spans {
        let style = Style::default().patch(line.style).patch(span.style);
        for grapheme in span.content.as_ref().graphemes(true) {
            if grapheme == "\t" {
                let width = TAB_STOP - (column % TAB_STOP);
                column += width;
                push_run(&mut runs, &" ".repeat(width), style);
            } else {
                column += ratatui::text::Span::raw(grapheme).width();
                push_run(&mut runs, grapheme, style);
            }
        }
    }
    ratatui::text::Line::from(
        runs.into_iter()
            .map(|(text, style)| ratatui::text::Span::styled(text, style))
            .collect::<Vec<_>>(),
    )
}

/// Appends `text` onto `runs`' last run when it already carries `style`, splitting into a
/// new run only where the style actually changes: the one merge rule [`expand_tabs`] and
/// [`wrap_output_line`] both need, kept in one place so they cannot drift apart.
fn push_run(runs: &mut Vec<(String, Style)>, text: &str, style: Style) {
    match runs.last_mut() {
        Some((existing_text, existing_style)) if *existing_style == style => {
            existing_text.push_str(text)
        }
        _ => runs.push((text.to_string(), style)),
    }
}

/// `output` parsed into ratatui lines carrying the child's own real colour
/// ([ADR 0018](../../../../docs/adr/0018-an-action-is-a-fanout-of-pty-backed-steps.md)'s
/// "Captured colours are rendered rather than stripped"). Falls back to one unstyled line
/// per `\n`-separated line of a lossy decode on the one input `ansi_to_tui` rejects, invalid
/// UTF-8, so a step's own output is never silently dropped.
fn parse_output_lines(output: &[u8]) -> Vec<ratatui::text::Line<'static>> {
    match output.into_text() {
        Ok(text) => text.lines,
        Err(_) => String::from_utf8_lossy(output)
            .lines()
            .map(|line| ratatui::text::Line::raw(line.to_string()))
            .collect(),
    }
}

/// Wraps one already-styled `line` to `width` columns, splitting on grapheme boundaries
/// (never a raw byte offset, so a multi-byte character is never cut in half) and carrying
/// each grapheme's own style into whichever wrapped row it lands on. A row only ever starts
/// fresh once it already holds something: a single grapheme wider than `width` still lands
/// on its own row rather than looping forever trying to make it fit.
fn wrap_output_line(
    line: &ratatui::text::Line<'static>,
    width: usize,
) -> Vec<Vec<(String, Style)>> {
    let mut rows: Vec<Vec<(String, Style)>> = vec![Vec::new()];
    let mut row_width = 0usize;
    for grapheme in line.styled_graphemes(Style::default()) {
        let symbol_width = ratatui::text::Span::raw(grapheme.symbol).width();
        if row_width > 0 && row_width + symbol_width > width {
            rows.push(Vec::new());
            row_width = 0;
        }
        let style = strip_colour_if_disabled(grapheme.style);
        let row = rows.last_mut().expect("rows always holds at least one row");
        push_run(row, grapheme.symbol, style);
        row_width += symbol_width;
    }
    rows
}

/// Strips a captured span's own colour when colour is disabled for this run, leaving every
/// other attribute (bold, italic, underline, ...) untouched: `NO_COLOR` is a statement about
/// colour specifically (`docs/spec/actions.md`'s "that setting is a statement about the
/// whole screen"), not about styling in general. Consults crossterm's own memoised answer
/// (`crossterm::style::Colored::ansi_color_disabled_memoized`) rather than reading the
/// variable a second time: a second implementation of the check would risk disagreeing with
/// crossterm's own, the class of defect [theming.md](../../../../docs/spec/theming.md)'s
/// "Colour is never the only carrier" rule exists to keep out. This is the one place in the
/// pane that needs the answer at all: every other line takes its colour from a theme `Role`,
/// and crossterm strips those the same way at the point it actually writes them, with no
/// code of this crate's own involved.
fn strip_colour_if_disabled(style: Style) -> Style {
    if crossterm::style::Colored::ansi_color_disabled_memoized() {
        Style {
            fg: None,
            bg: None,
            underline_color: None,
            ..style
        }
    } else {
        style
    }
}

fn kind_word(kind: Kind) -> &'static str {
    match kind {
        Kind::Repo => "repo",
        Kind::Worktree => "worktree",
        Kind::Submodule => "submodule",
    }
}

/// `sync`'s own role in this pane: unlike the list's cell, which paints an ahead run and a
/// behind run side by side, this pane spells both counts into one sentence, so there is only
/// one role to give the whole value. A diverged value (both counts nonzero) takes the ahead
/// count's role; the words themselves, not the colour, are what tells the two counts apart
/// here, the same division of labour `describe_cell_spans`'s own age suffix already holds
/// with its value.
fn sync_meaning(value: &SyncState) -> Meaning {
    match value {
        SyncState::Tracking(counts) if counts.ahead > 0 => Meaning::AheadCount,
        SyncState::Tracking(counts) if counts.behind > 0 => Meaning::BehindCount,
        SyncState::Tracking(_) => Meaning::KnownZero,
        SyncState::NoUpstream | SyncState::NoRemote => Meaning::FreshValue,
    }
}

/// One Cell's whole provenance, spelled out in words: a Known value's own words, "unknown:
/// timed out", or a Failed cell's own probe message, which already reads as words
/// (`ProbeError`'s `Display`). Exhaustive over `Option<&Settled<T>>` with no wildcard arm, the
/// same discipline `list.rs`'s `render_cell` holds, so a `Settled` shape added later fails to
/// compile here instead of falling through some default reading. [`styled_content_lines`] now
/// reads [`describe_cell_spans`] directly; this stays as the plain-text oracle this module's
/// own words-only tests check the formatting against, independent of colour.
#[allow(dead_code)] // read only from `#[cfg(test)]` call sites
fn describe_cell<T>(
    settled: Option<&Settled<T>>,
    format_value: impl FnOnce(&T) -> String,
) -> String {
    describe_cell_spans(settled, format_value, |_| Meaning::FreshValue)
        .into_iter()
        .map(|(text, _)| text)
        .collect()
}

/// [`describe_cell`]'s styled counterpart: the value takes `meaning_for_value`'s own role and
/// the Unknown, Failed, NotApplicable and Loading words take the role theming.md's map already
/// gives that state, matching `list.rs`'s `cell_role` rather than inventing a second answer for
/// the same `Settled` shape. Never carries an age: a Known cell's own freshness is reported once
/// for the whole row, by [`freshness_row`], not repeated on each cell's own line.
fn describe_cell_spans<T>(
    settled: Option<&Settled<T>>,
    format_value: impl FnOnce(&T) -> String,
    meaning_for_value: impl FnOnce(&T) -> Meaning,
) -> StyledLine {
    match settled {
        Some(Settled::Known {
            value,
            at: _,
            stale: _,
        }) => {
            vec![(format_value(value), meaning_for_value(value).role())]
        }
        Some(Settled::Unknown(reason)) => vec![(
            format!("unknown: {}", describe_unknown(*reason)),
            Meaning::StaleOrUnknownGutterMark.role(),
        )],
        Some(Settled::Failed(error)) => {
            vec![(error.to_string(), Meaning::FailedProvenance.role())]
        }
        Some(Settled::NotApplicable) => vec![("not applicable".to_string(), Role::Text)],
        None => vec![("loading".to_string(), Meaning::LoadingSpinner.role())],
    }
}

/// A Known cell's freshness in words: the reading word, "refreshed" once settled or "stale"
/// once past the age threshold, describes when Repon last looked rather than the value itself,
/// followed by [`format_age`]'s own elapsed text. Read only by this module's own tests now:
/// [`freshness_text`] is what a real render computes, and never says "refreshed" itself, since
/// the fixed freshness row's own label already carries that word when every cell agrees.
#[allow(dead_code)] // read only from #[cfg(test)] call sites
fn age_annotation(at: Timestamp, stale: bool) -> String {
    let word = if stale { "stale" } else { "refreshed" };
    format!("{word} {}", format_age(at))
}

/// A Known cell's freshness for the fixed freshness row [`freshness_row`] builds: just
/// [`format_age`]'s own elapsed text, with a `stale ` prefix once the reading has passed the
/// staleness threshold. Never "refreshed": that word lives on the row's own label, not
/// repeated into every cell's value.
fn freshness_text(at: Timestamp, stale: bool) -> String {
    if stale {
        format!("stale {}", format_age(at))
    } else {
        format_age(at)
    }
}

/// One of the six Cells' own freshness fact, named by this row's label, for [`freshness_row`]
/// to fold into the one fixed row [`styled_content_lines`] shows in their place. `age` is
/// `None` for every `Settled` shape but `Known`: `Unknown`, `Failed`, `NotApplicable` and a
/// still-loading cell carry no age. `in_flight` is read independently of `settled`, since a
/// re-probe leaves a Known cell's previous value in place rather than blanking it.
struct CellFreshness {
    label: &'static str,
    age: Option<String>,
    in_flight: bool,
}

/// Builds one [`CellFreshness`] from a Cell's own `settled` and `is_in_flight` reads, the two
/// facts [`styled_content_lines`] already has on hand for each of the six named Cells.
fn cell_freshness<T>(
    label: &'static str,
    settled: Option<&Settled<T>>,
    in_flight: bool,
) -> CellFreshness {
    CellFreshness {
        label,
        age: match settled {
            Some(Settled::Known {
                value: _,
                at,
                stale,
            }) => Some(freshness_text(*at, *stale)),
            _ => None,
        },
        in_flight,
    }
}

/// The fixed freshness row [`styled_content_lines`] shows in the place the six per-cell
/// suffixes `describe_cell_spans` used to carry.
enum FreshnessRow {
    /// A re-probe is running against at least one of the six cells: the value names only
    /// those cells' own labels, outranking a stale or disagreeing age the way a Cell's own
    /// `is_in_flight` already outranks its settled state elsewhere.
    Loading(String),
    /// Every currently-in-flight cell is quiet: one line, the shared age, when every Known
    /// cell agrees, or one `label, age` line per cell that disagrees with the majority, when
    /// they do not. Each `String` is its own screen row, never a value with `\n` inside it:
    /// [`draw_lines`] paints one `ContentLine` per row and neither it nor ratatui's own
    /// `Buffer::set_stringn` splits on an embedded newline, so a caller collapsing this back
    /// into one row would silently squash every entry after the first onto the row above it.
    Refreshed(Vec<String>),
}

/// Folds the six cells' own freshness facts into the one row [`docs/spec/layout-and-provenance.md`'s
/// "The detail pane"] fixes in this slot, or `None` while nothing is Known yet. A Refresh
/// settles a row's cells together, so on the overwhelmingly common path every Known cell's age
/// agrees to the second; comparing the already-formatted text rather than the raw `Timestamp`
/// is deliberate, since a `stale` cell reads different text from a fresh neighbour even at the
/// same instant, and either kind of real difference already fails this comparison without a
/// separate flag for it. The majority must be strict (more than half of the Known cells): short
/// of that, no group can claim to be the baseline the rest disagree with, so every cell's own
/// reading is named rather than picking whichever group the tally reaches first.
fn freshness_row(cells: &[CellFreshness; 6]) -> Option<FreshnessRow> {
    let in_flight_labels: Vec<&str> = cells
        .iter()
        .filter(|cell| cell.in_flight)
        .map(|cell| cell.label)
        .collect();
    if !in_flight_labels.is_empty() {
        return Some(FreshnessRow::Loading(in_flight_labels.join(", ")));
    }

    let known: Vec<&CellFreshness> = cells.iter().filter(|cell| cell.age.is_some()).collect();
    let mut tally: Vec<(&str, usize)> = Vec::new();
    for cell in &known {
        let age = cell.age.as_deref().expect("filtered to Known above");
        match tally.iter_mut().find(|(text, _)| *text == age) {
            Some(entry) => entry.1 += 1,
            None => tally.push((age, 1)),
        }
    }
    let majority_count = tally.iter().map(|(_, count)| *count).max()?;
    if majority_count == known.len() {
        return Some(FreshnessRow::Refreshed(vec![
            known[0].age.clone().expect("filtered to Known above"),
        ]));
    }

    let majority_age = (majority_count * 2 > known.len()).then(|| {
        tally
            .iter()
            .find(|(_, count)| *count == majority_count)
            .expect("the tallied max came from this same tally")
            .0
    });
    let breakdown = known
        .iter()
        .filter(|cell| majority_age.is_none() || cell.age.as_deref() != majority_age)
        .map(|cell| {
            format!(
                "{}, {}",
                cell.label,
                cell.age.as_deref().expect("filtered to Known above")
            )
        })
        .collect();
    Some(FreshnessRow::Refreshed(breakdown))
}

/// The two closed [`Unknown`] reasons, distinguished by name even though both share the
/// gutter's one `?` mark: the pane is the only place that tells them apart.
fn describe_unknown(reason: Unknown) -> &'static str {
    match reason {
        Unknown::TimedOut => "timed out",
        Unknown::NoDefaultBranch => "no default branch found",
        Unknown::SubmoduleUninitialized => "not yet initialised",
    }
}

/// A value's age against the settled timestamp, computed by [`Timestamp::elapsed`] rather than
/// against a fixed epoch: a backward clock jump therefore reads "just now" because `elapsed`
/// itself reads zero for a future timestamp, with no extra clamp layered on here. Below a
/// minute the text is quantised to 10-second steps so a poll shorter than that cannot retext
/// it on every frame.
fn format_age(at: Timestamp) -> String {
    let elapsed = at.elapsed();
    let secs = elapsed.as_secs();
    if secs < 10 {
        "just now".to_string()
    } else if secs < 60 {
        format!("{}s ago", secs / 10 * 10)
    } else if secs < 3_600 {
        format!("{}m ago", secs / 60)
    } else if secs < 86_400 {
        format!("{}h ago", secs / 3_600)
    } else {
        format!("{}d ago", secs / 86_400)
    }
}

/// The list's branch cell shows a fixed nine-character abbreviation of a detached
/// HEAD's object id; this pane shows the full id instead, since nothing here needs a
/// column to stay unragged and the pane is the one place that can disambiguate an id
/// from a branch name of the same shape (ADR 0019's accepted cost: an object id is
/// itself a legal branch name).
fn head_word(value: &Head) -> String {
    match value {
        Head::Branch { name, .. } => name.to_string(),
        Head::Unborn(name) => format!("{name} (no commits yet)"),
        Head::Detached(oid) => format!("detached at {oid}"),
    }
}

/// Exhaustive over [`SyncState`], the same discipline [`stopped_word`] holds over
/// [`DefaultBranchStopped`]: a variant added there later fails to compile here rather than
/// silently falling through a wildcard arm.
fn sync_word(value: &SyncState) -> String {
    match value {
        SyncState::Tracking(counts) => format!("{} ahead, {} behind", counts.ahead, counts.behind),
        SyncState::NoUpstream => "no upstream configured".to_string(),
        SyncState::NoRemote => "no remote configured".to_string(),
    }
}

fn base_word(value: &u32) -> String {
    if *value == 0 {
        "level with the default branch".to_string()
    } else {
        format!("{value} behind the default branch")
    }
}

/// The same total [`format_dirty`](super::list) shows in the list column, in words: the
/// breakdown between modified, untracked and deleted stays out of both surfaces, per
/// [layout-and-provenance.md](../../../../docs/spec/layout-and-provenance.md)'s mock.
fn dirty_word(value: &DirtyCounts) -> String {
    let total = value.total();
    if total == 0 {
        "clean".to_string()
    } else {
        format!("{total} changed")
    }
}

fn default_branch_word(value: &DefaultBranch) -> String {
    value.name().to_string()
}

/// The word for one of the ten in-progress git operations gix's own `state::InProgress`
/// names, per [ADR 0019](../../../../docs/adr/0019-a-detached-head-is-a-shape-of-head-not-a-worktree-state.md).
fn in_progress_word(operation: InProgressOperation) -> &'static str {
    match operation {
        InProgressOperation::ApplyMailbox => "applying a mailbox",
        InProgressOperation::ApplyMailboxRebase => "rebasing while applying a mailbox",
        InProgressOperation::Bisect => "bisecting",
        InProgressOperation::CherryPick => "cherry-picking",
        InProgressOperation::CherryPickSequence => "cherry-picking a sequence",
        InProgressOperation::Merge => "merging",
        InProgressOperation::Rebase => "rebasing",
        InProgressOperation::RebaseInteractive => "rebasing interactively",
        InProgressOperation::Revert => "reverting",
        InProgressOperation::RevertSequence => "reverting a sequence",
    }
}

/// The two distinct facts that can each drive a row's gutter to the Failed mark even when no
/// per-cell line above reads Failed: an unparseable `.gitmodules` and a failed last Action
/// ([`repon_core`]'s own row summary fold applies exactly these two widenings). Named in
/// distinct words from each other, and from a per-cell probe's own Failed message above, since
/// the gutter's one `!` cannot itself tell any of the three apart and the pane is where that
/// happens.
/// The default branch cell's own diagnostics, beside it rather than in it, per
/// `default-branch.md`: which rung answered (only rung 3, the name list, is called
/// out by name), whether rung 2's `origin/HEAD` disagreed with rung 3, and why
/// resolution stopped when it did not settle. None has its own Cell, so none of
/// this reaches `list.rs`, which never imports [`Diagnostics`] at all.
fn default_branch_diagnostics_lines(diagnostics: &Diagnostics) -> Vec<String> {
    let mut lines = Vec::new();
    if diagnostics.default_branch_rung == Some(3) {
        lines.push("resolved by the name list, not origin/HEAD".to_string());
    }
    if diagnostics.default_branch_rung_disagreement {
        lines.push(
            "origin/HEAD and the name list disagree; origin/HEAD's answer is used".to_string(),
        );
    }
    if diagnostics.default_branch_rung_two_stale {
        lines.push("origin/HEAD named a target that no longer resolves".to_string());
    }
    if let Some(stopped) = diagnostics.default_branch_stopped {
        lines.push(format!("no default branch: {}", stopped_word(stopped)));
    }
    lines
}

/// Why the chain reached rung 4 with nothing settled, in words. Exhaustive over the three
/// [`DefaultBranchStopped`] reasons with no wildcard arm, the same discipline `describe_unknown`
/// holds over the two [`Unknown`] reasons.
fn stopped_word(stopped: DefaultBranchStopped) -> &'static str {
    match stopped {
        DefaultBranchStopped::NoRemote => "no remote is configured",
        DefaultBranchStopped::AmbiguousRemote => "two or more remotes and none named origin",
        DefaultBranchStopped::NameListExhausted => "origin/HEAD and the name list found no match",
    }
}

fn row_level_failure(
    diagnostics: &Diagnostics,
    last_action: &Option<ActionReceipt>,
) -> Option<String> {
    if let Some(reason) = &diagnostics.gitmodules_failed {
        return Some(format!("failed to read .gitmodules: {reason}"));
    }
    if last_action.as_ref().is_some_and(ActionReceipt::failed) {
        return Some("the last Action failed".to_string());
    }
    None
}

#[cfg(test)]
mod tests {
    use std::{path::Path, process::Command, sync::Arc, time::Duration};

    use repon_core::{
        CaptureElision, Cell, Core, CoreSpec, EntityKey, ProbeError, RecentCommit, SetSpec,
        StepOutcome, StepResult, WorktreeState, liveness::wait_for,
    };

    use super::*;
    use crate::theme;

    fn entity(name: &str) -> EntityState {
        EntityState::new(
            EntityKey::new(Arc::from(Path::new(name))),
            Arc::from(name),
            Arc::from(Path::new(name)),
            Kind::Worktree,
        )
    }

    /// A generous interior width for every test that is not itself exercising wrapping:
    /// the full frame's own 104-column interior (`docs/spec/actions.md`'s "The run on
    /// screen"), wide enough that nothing this module's own fixtures write wraps by
    /// accident.
    const WIDE: u16 = 104;

    /// The full glyph set, for every test that does not care which one is in force: the
    /// same fallback [`crate::components::list::List::glyphs`] gives an unconfigured
    /// component.
    fn full_glyphs() -> &'static GlyphSet {
        GlyphSet::for_config(crate::config::document::Glyphs::default())
    }

    /// A receipt with one step, whose outcome is `Ok` or `Failed`: this module only ever
    /// needs to distinguish the two words the pane shows, never a step's own label or output.
    fn receipt(outcome: StepOutcome) -> ActionReceipt {
        ActionReceipt {
            label: Arc::from("action"),
            steps: Arc::from(vec![StepResult {
                label: Arc::from("step"),
                outcome,
                output: Arc::from(&b""[..]),
                elapsed: Duration::from_millis(1),
                elision: None,
                shell: false,
                interactive: false,
            }]),
            skip: None,
            finished_at: Timestamp::now(),
            running: None,
        }
    }

    fn step_result(
        label: &str,
        outcome: StepOutcome,
        output: &[u8],
        elapsed: Duration,
    ) -> StepResult {
        StepResult {
            label: Arc::from(label),
            outcome,
            output: Arc::from(output),
            elapsed,
            elision: None,
            shell: false,
            interactive: false,
        }
    }

    fn action_receipt(
        label: &str,
        steps: Vec<StepResult>,
        running: Option<RunningStep>,
    ) -> ActionReceipt {
        ActionReceipt {
            label: Arc::from(label),
            steps: Arc::from(steps),
            skip: None,
            finished_at: Timestamp::now(),
            running,
        }
    }

    /// Serialises every test in this module that touches crossterm's own process-global
    /// colour capability flag (`crossterm::style::force_color_output`) or asserts a captured
    /// Action step's own colour reaches the buffer: `cargo test`'s default parallelism runs
    /// this module's tests concurrently, and that flag is shared by the whole test binary.
    static COLOUR_CAPABILITY_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// Criterion 2's "never written to disk" claim, the one absence a source scan is the
    /// honest form of: no file in either crate that mentions an Action receipt also performs
    /// a disk write. `ActionReceipt` and `StepResult` are defined in `repon-core`, where the
    /// executor will land, so a scan of this crate's own `src` alone is blind to half the
    /// claim's subject; `repon-core/src` is walked too, the same `manifest_dir.join("../repon-core/src")`
    /// precedent `main.rs`'s workspace-wide scan uses. Neither half exists yet (there is no
    /// `[[action]]` executor and no session persistence path), so this is a regression guard
    /// against the two being wired together silently, not a claim about code that runs today.
    #[test]
    fn no_source_file_writes_an_action_receipt_to_disk() {
        let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
        let core_src = manifest_dir.join("../repon-core/src");
        let repon_src = manifest_dir.join("src");
        let receipt_markers = ["ActionReceipt", "StepResult", "last_action"];
        let disk_write_markers = [
            "fs::write",
            "File::create",
            "toml::to_string",
            "OpenOptions::new",
            "serde_json::to",
        ];

        let mut offending = Vec::new();
        for path in crate::test_support::rust_source_files(&core_src)
            .into_iter()
            .chain(crate::test_support::rust_source_files(&repon_src))
        {
            let production = crate::test_support::production_source_at(&path);
            let mentions_receipt = receipt_markers
                .iter()
                .any(|marker| production.contains(marker));
            let writes_to_disk = disk_write_markers
                .iter()
                .any(|marker| production.contains(marker));
            if mentions_receipt && writes_to_disk {
                offending.push(path);
            }
        }

        assert!(
            offending.is_empty(),
            "found a file whose production source both mentions an Action receipt and \
             writes to disk: {offending:?}"
        );
    }

    // --- age_annotation: freshness in words, computed from the settled timestamp ---
    //
    // `describe_cell` no longer carries a Known cell's age at all (that moved to the one
    // fixed freshness row below), so these test `age_annotation` and `format_age` directly
    // rather than through it.

    #[test]
    fn a_known_refreshed_value_reads_its_word_and_age_in_words() {
        let text = age_annotation(Timestamp::now(), false);

        assert!(text.starts_with("refreshed"), "got {text:?}");
        assert!(
            text.contains("ago") || text.contains("just now"),
            "got {text:?}"
        );
    }

    #[test]
    fn a_known_stale_value_reads_stale_rather_than_refreshed() {
        let text = age_annotation(Timestamp::now(), true);

        assert!(text.starts_with("stale"), "got {text:?}");
        assert!(!text.contains("refreshed"), "got {text:?}");
    }

    #[test]
    fn age_is_computed_from_the_settled_timestamp_not_a_fixed_epoch() {
        let recent = Timestamp::at(std::time::SystemTime::now() - Duration::from_secs(45));
        let old = Timestamp::at(std::time::SystemTime::now() - Duration::from_secs(7_200));

        assert!(
            age_annotation(recent, false).ends_with("40s ago"),
            "got {:?}",
            age_annotation(recent, false)
        );
        assert!(
            age_annotation(old, false).ends_with("2h ago"),
            "got {:?}",
            age_annotation(old, false)
        );
    }

    #[test]
    fn a_settled_timestamp_in_the_future_reads_as_just_now_with_no_clamp_defence() {
        let backward_clock_jump =
            Timestamp::at(std::time::SystemTime::now() + Duration::from_secs(3_600));

        assert!(
            age_annotation(backward_clock_jump, false).ends_with("just now"),
            "got {:?}",
            age_annotation(backward_clock_jump, false)
        );
    }

    #[test]
    fn elapsed_under_ten_seconds_reads_just_now() {
        for secs in [0, 1, 5, 9] {
            let at = Timestamp::at(std::time::SystemTime::now() - Duration::from_secs(secs));

            assert_eq!(format_age(at), "just now", "elapsed {secs}s");
        }
    }

    #[test]
    fn between_ten_seconds_and_a_minute_rounds_down_to_the_nearest_ten() {
        let cases = [
            (19, "10s ago"),
            (59, "50s ago"),
            (10, "10s ago"),
            (20, "20s ago"),
        ];
        for (secs, expected) in cases {
            let at = Timestamp::at(std::time::SystemTime::now() - Duration::from_secs(secs));

            assert_eq!(format_age(at), expected, "elapsed {secs}s");
        }
    }

    #[test]
    fn a_minute_or_more_keeps_the_existing_minute_hour_and_day_rungs() {
        let cases = [
            (60, "1m ago"),
            (3_599, "59m ago"),
            (3_600, "1h ago"),
            (86_399, "23h ago"),
            (86_400, "1d ago"),
        ];
        for (secs, expected) in cases {
            let at = Timestamp::at(std::time::SystemTime::now() - Duration::from_secs(secs));

            assert_eq!(format_age(at), expected, "elapsed {secs}s");
        }
    }

    /// The property that makes the 2s-poll flicker impossible rather than merely
    /// unlikely: any two elapsed times sharing a 10-second bucket must render the same
    /// text, checked over several bucket boundaries and several offsets within each
    /// rather than one hand-picked pair.
    #[test]
    fn two_elapsed_values_in_the_same_ten_second_bucket_render_identically() {
        for bucket_start in [0, 10, 20, 30, 40, 50] {
            for (offset_a, offset_b) in [(0, 9), (1, 8), (3, 6)] {
                let a = Timestamp::at(
                    std::time::SystemTime::now() - Duration::from_secs(bucket_start + offset_a),
                );
                let b = Timestamp::at(
                    std::time::SystemTime::now() - Duration::from_secs(bucket_start + offset_b),
                );

                assert_eq!(
                    format_age(a),
                    format_age(b),
                    "bucket starting at {bucket_start}s: offsets {offset_a}s and {offset_b}s diverged"
                );
            }
        }
    }

    #[test]
    fn a_never_probed_cell_reads_loading() {
        let settled: Option<&Settled<u32>> = None;

        assert_eq!(describe_cell(settled, |value| value.to_string()), "loading");
    }

    #[test]
    fn a_not_applicable_cell_reads_not_applicable_in_words() {
        let settled: Settled<u32> = Settled::NotApplicable;

        assert_eq!(
            describe_cell(Some(&settled), |value| value.to_string()),
            "not applicable"
        );
    }

    #[test]
    fn a_failed_cells_probe_message_reads_as_words_not_a_debug_dump() {
        let settled: Settled<u32> = Settled::Failed(ProbeError::Read(Arc::from("boom")));

        let text = describe_cell(Some(&settled), |value| value.to_string());

        assert!(!text.contains("ProbeError"), "got {text:?}");
        assert!(text.contains("failed to read HEAD"), "got {text:?}");
    }

    // --- the three Unknown reasons, distinguished by name ---

    #[test]
    fn the_three_unknown_reasons_read_as_distinct_words() {
        let reasons = [
            Unknown::TimedOut,
            Unknown::NoDefaultBranch,
            Unknown::SubmoduleUninitialized,
        ];
        for (index, a) in reasons.iter().enumerate() {
            for b in &reasons[index + 1..] {
                assert_ne!(describe_unknown(*a), describe_unknown(*b));
            }
        }
        assert_eq!(describe_unknown(Unknown::TimedOut), "timed out");
        assert_eq!(
            describe_unknown(Unknown::NoDefaultBranch),
            "no default branch found"
        );
        assert_eq!(
            describe_unknown(Unknown::SubmoduleUninitialized),
            "not yet initialised"
        );
    }

    // --- the two meanings the Failed gutter mark can carry ---

    #[test]
    fn a_gitmodules_parse_failure_and_a_failed_last_action_read_as_distinct_words() {
        let mut gitmodules_row = entity("a");
        gitmodules_row.diagnostics.gitmodules_failed = Some(Arc::from("bad syntax"));

        let mut action_row = entity("b");
        action_row.last_action = Some(receipt(StepOutcome::Failed(1)));

        let gitmodules_reason =
            row_level_failure(&gitmodules_row.diagnostics, &gitmodules_row.last_action)
                .expect("expected a row-level failure reason");
        let action_reason = row_level_failure(&action_row.diagnostics, &action_row.last_action)
            .expect("expected a row-level failure reason");

        assert_ne!(gitmodules_reason, action_reason);
        assert!(gitmodules_reason.contains(".gitmodules"));
        assert!(action_reason.contains("Action"));
    }

    #[test]
    fn a_row_with_neither_failure_cause_has_no_row_level_failure_reason() {
        let clean_row = entity("c");

        assert_eq!(
            row_level_failure(&clean_row.diagnostics, &clean_row.last_action),
            None
        );
    }

    // --- default_branch_diagnostics_lines: the three per-entity facts beside the cell ---

    /// Criterion 3's marked case: rung 3 (the name list) answering rather than `origin/HEAD`
    /// is the one case `default-branch.md` requires called out by name, "marked in the detail
    /// pane and nowhere in the list".
    #[test]
    fn a_rung_three_default_branch_is_marked_resolved_by_the_name_list() {
        let mut rung_three = entity("a");
        rung_three.diagnostics.default_branch_rung = Some(3);

        let lines = default_branch_diagnostics_lines(&rung_three.diagnostics).join("\n");

        assert!(lines.contains("name list"), "got {lines:?}");
    }

    /// The other half: rung 2 (or rung 1) answering is the ordinary path and carries no mark,
    /// or every entity whose `origin/HEAD` resolves cleanly would read as remarkable.
    #[test]
    fn a_rung_two_default_branch_carries_no_name_list_mark() {
        let mut rung_two = entity("a");
        rung_two.diagnostics.default_branch_rung = Some(2);

        let lines = default_branch_diagnostics_lines(&rung_two.diagnostics);

        assert!(lines.is_empty(), "got {lines:?}");
    }

    /// The disagreement is recorded even though `origin/HEAD` still wins: the pane must say
    /// both, not merely that a disagreement happened, or a reader could not tell which answer
    /// is live.
    #[test]
    fn a_recorded_disagreement_says_origin_head_still_wins() {
        let mut disagreeing = entity("a");
        disagreeing.diagnostics.default_branch_rung_disagreement = true;

        let lines = default_branch_diagnostics_lines(&disagreeing.diagnostics).join("\n");

        assert!(lines.contains("disagree"), "got {lines:?}");
        assert!(lines.contains("origin/HEAD"), "got {lines:?}");
    }

    #[test]
    fn no_disagreement_recorded_carries_no_disagreement_line() {
        let agreeing = entity("a");

        let lines = default_branch_diagnostics_lines(&agreeing.diagnostics);

        assert!(lines.is_empty(), "got {lines:?}");
    }

    #[test]
    fn a_stale_origin_head_target_is_named() {
        let mut stale = entity("a");
        stale.diagnostics.default_branch_rung_two_stale = true;

        let lines = default_branch_diagnostics_lines(&stale.diagnostics).join("\n");

        assert!(lines.contains("no longer resolves"), "got {lines:?}");
    }

    #[test]
    fn a_resolvable_origin_head_target_carries_no_stale_line() {
        let resolvable = entity("a");

        let lines = default_branch_diagnostics_lines(&resolvable.diagnostics);

        assert!(lines.is_empty(), "got {lines:?}");
    }

    /// Absence claim: the three [`DefaultBranchStopped`] reasons are the whole set. This match
    /// has no wildcard arm, so a fourth variant added later fails to compile here rather than
    /// silently falling through an `_`, the same discipline `worktree_state_is_exactly_four...`
    /// holds for `WorktreeState` in `repon-core`.
    #[test]
    fn every_stopped_reason_reads_as_its_own_distinct_words() {
        let words = [
            stopped_word(DefaultBranchStopped::NoRemote),
            stopped_word(DefaultBranchStopped::AmbiguousRemote),
            stopped_word(DefaultBranchStopped::NameListExhausted),
        ];

        for (index, word) in words.iter().enumerate() {
            for (other_index, other) in words.iter().enumerate() {
                if index != other_index {
                    assert_ne!(word, other, "got duplicate stopped words: {words:?}");
                }
            }
        }
    }

    #[test]
    fn a_stopped_reason_is_named_only_once_recorded() {
        let mut exhausted = entity("a");
        exhausted.diagnostics.default_branch_stopped =
            Some(DefaultBranchStopped::NameListExhausted);

        let lines = default_branch_diagnostics_lines(&exhausted.diagnostics).join("\n");

        assert!(lines.contains(stopped_word(DefaultBranchStopped::NameListExhausted)));
    }

    #[test]
    fn a_rung_that_answered_carries_no_stopped_reason_line() {
        let answered = entity("a");

        let lines = default_branch_diagnostics_lines(&answered.diagnostics);

        assert!(lines.is_empty(), "got {lines:?}");
    }

    // --- criterion 3's absence half: the list never reads these facts ---

    /// The harder half of criterion 3: `default-branch.md` requires these four facts marked
    /// "in the detail pane and nowhere in the list". A behavioural test of `list.rs`'s own
    /// output cannot prove that; `list.rs` does not even import [`Diagnostics`], so nothing
    /// stops a future column from reading one of these fields directly off `EntityState`. A
    /// source scan is the honest form of an absence claim, the same pattern this crate already
    /// holds for `no_path_from_escape_to_quit_exists_anywhere_in_this_crates_production_source`
    /// in `app.rs`: this file is the one place allowed to read any of the four field names, so
    /// every other file's production source must read none of them.
    #[test]
    fn the_default_branchs_diagnostics_fields_are_read_nowhere_outside_this_file() {
        let needles = ["default_branch_rung", "default_branch_stopped"];
        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let mut offending_locations = Vec::new();
        for path in crate::test_support::rust_source_files(&manifest_dir.join("src")) {
            if path.file_name().is_some_and(|name| name == "detail.rs") {
                continue;
            }
            let production = crate::test_support::production_source_at(&path);
            for (number, line) in production.lines().enumerate() {
                if line.trim_start().starts_with("//") {
                    continue;
                }
                if needles.iter().any(|needle| line.contains(needle)) {
                    offending_locations.push(format!("{}:{}", path.display(), number + 1));
                }
            }
        }
        assert!(
            offending_locations.is_empty(),
            "a default branch diagnostics field was read outside detail.rs, the one place \
             `default-branch.md` allows it, at: {offending_locations:?}"
        );
    }

    // --- head_word: the pane's own words for HEAD's three shapes ---

    /// Criterion 2's other half, proven through a real, settled detached row rather than a
    /// hand-built `gix::ObjectId` (this crate does not depend on `gix` directly): the list
    /// abbreviates a detached HEAD's object id to a fixed nine characters, but the detail
    /// pane carries the full forty-character sha1 one, distinct from the list's own
    /// abbreviation so a mutation that truncated this pane to the list's width would fail
    /// this assertion rather than pass by coincidence.
    #[test]
    fn head_word_carries_a_detached_heads_full_object_id_not_the_lists_abbreviation() {
        use repon_core::{Core, CoreSpec, SetSpec};

        let dir = tempfile::tempdir().expect("temp dir");
        let root = dir.path().canonicalize().expect("canonicalize temp dir");
        let status = Command::new("git")
            .arg("init")
            .args(["--quiet", "--initial-branch", "main"])
            .arg(&root)
            .status()
            .expect("run git init");
        assert!(status.success());
        git(&root, &["commit", "--allow-empty", "-m", "first"]);
        let sha_output = Command::new("git")
            .arg("-C")
            .arg(&root)
            .args(["rev-parse", "HEAD"])
            .output()
            .expect("run git rev-parse");
        assert!(sha_output.status.success());
        let full_id = String::from_utf8(sha_output.stdout)
            .expect("utf8 sha")
            .trim()
            .to_string();
        assert_eq!(full_id.len(), 40, "expected a full sha1 hex id");
        let status = Command::new("git")
            .arg("-C")
            .arg(&root)
            .args(["checkout", "--quiet", "--detach", &full_id])
            .status()
            .expect("run git checkout --detach");
        assert!(status.success());

        let core = Core::start_discovered(CoreSpec {
            set: SetSpec {
                name: "test".to_string(),
                roots: vec![root],
                include: Vec::new(),
                exclude: Vec::new(),
            },
            overrides: Vec::new(),
            poll_interval: Duration::from_secs(3600),
            status_stale_after: Duration::from_secs(3600),
            generation_deadline: Duration::from_secs(3600),
            show_submodules: false,
            fetch: repon_core::FetchSpec {
                enabled: false,
                interval: std::time::Duration::from_secs(3600),
                concurrency: 4,
            },
            auto_update: repon_core::AutoUpdateSpec { enabled: false },
        });
        let keys: Vec<_> = core
            .snapshot()
            .entities
            .iter()
            .map(|entity| entity.key.clone())
            .collect();
        core.refresh(&keys);
        let settled = core.settle();

        let lines = content_lines(&settled.entities[0], WIDE, full_glyphs());
        let branch_line = line_labelled(&lines, "branch");

        assert!(
            branch_line.contains(&full_id),
            "expected the full forty-character id in the pane, got {branch_line:?}"
        );
    }

    // --- content_lines: assembly ---

    #[test]
    fn content_lines_opens_with_the_entitys_name_kind_and_path() {
        let lines = content_lines(&entity("acquiring-gateway"), WIDE, full_glyphs());

        assert!(lines[0].contains("acquiring-gateway"));
        assert!(lines[0].contains("worktree"));
        assert_eq!(lines[1], "acquiring-gateway");
    }

    #[test]
    fn content_lines_carries_one_line_per_cell_even_before_any_probe() {
        let lines = content_lines(&entity("a"), WIDE, full_glyphs()).join("\n");

        for label in ["branch", "sync", "base", "dirty", "state", "default branch"] {
            assert!(
                lines.contains(label),
                "expected a {label} line, got {lines:?}"
            );
        }
    }

    // --- the fixed freshness row: never a per-cell suffix, always the same line index ---

    /// A `Known` cell settled at an explicit instant, so two cells can be given the same `at`
    /// (or a deliberately different one) without racing separate `Timestamp::now()` calls
    /// against each other.
    fn settled_known_at<T>(value: T, at: Timestamp, stale: bool) -> Cell<T> {
        Cell::already_settled(Settled::Known { value, at, stale })
    }

    #[test]
    fn a_known_cells_value_line_never_carries_its_own_inline_age() {
        let at = Timestamp::now();
        let two_hours_ago =
            Timestamp::at(std::time::SystemTime::now() - Duration::from_secs(7_200));
        let mut row = entity("a");
        row.branch = settled_known_at(Head::Unborn(Arc::from("main")), at, false);
        row.dirty = settled_known_at(DirtyCounts::default(), at, true);
        row.sync = settled_known_at(SyncState::NoUpstream, two_hours_ago, false);

        let lines = content_lines(&row, WIDE, full_glyphs());

        for label in ["branch", "sync", "base", "dirty", "state", "default branch"] {
            let line = line_labelled(&lines, label);
            assert!(
                !line.contains("ago")
                    && !line.contains("just now")
                    && !line.contains("refreshed")
                    && !line.contains("stale"),
                "expected no inline age on the {label} row, got {line:?}"
            );
        }
    }

    #[test]
    fn a_rows_agreeing_known_cells_print_one_refreshed_line_with_their_shared_age() {
        let at = Timestamp::now();
        let mut row = entity("a");
        row.branch = settled_known_at(Head::Unborn(Arc::from("main")), at, false);
        row.sync = settled_known_at(SyncState::NoUpstream, at, false);
        row.dirty = settled_known_at(DirtyCounts::default(), at, false);
        row.default_branch =
            settled_known_at(DefaultBranch::new(Arc::from("origin/main")), at, false);

        let lines = content_lines(&row, WIDE, full_glyphs());

        let freshness_line = line_labelled(&lines, "refreshed");
        assert_eq!(
            freshness_line, "refreshed       just now",
            "got {freshness_line:?}"
        );
        assert_eq!(
            lines
                .iter()
                .filter(|line| line.starts_with("refreshed"))
                .count(),
            1,
            "expected exactly one refreshed line, got {lines:?}"
        );
    }

    #[test]
    fn a_rows_disagreeing_known_cells_print_one_refreshed_line_with_one_label_and_age_per_line() {
        let now = Timestamp::now();
        let ten_seconds_ago = Timestamp::at(std::time::SystemTime::now() - Duration::from_secs(12));
        let twenty_seconds_ago =
            Timestamp::at(std::time::SystemTime::now() - Duration::from_secs(25));
        let mut row = entity("a");
        row.branch = settled_known_at(Head::Unborn(Arc::from("main")), now, false);
        row.base = settled_known_at(0u32, now, false);
        row.default_branch =
            settled_known_at(DefaultBranch::new(Arc::from("origin/main")), now, false);
        row.sync = settled_known_at(SyncState::NoUpstream, ten_seconds_ago, false);
        row.dirty = settled_known_at(DirtyCounts::default(), twenty_seconds_ago, false);

        let lines = content_lines(&row, WIDE, full_glyphs());

        let freshness_index = lines
            .iter()
            .position(|line| line.starts_with("refreshed"))
            .expect("expected a refreshed line");
        assert_eq!(
            lines[freshness_index], "refreshed       sync, 10s ago",
            "got {lines:?}"
        );
        assert_eq!(
            lines[freshness_index + 1],
            "                dirty, 20s ago",
            "expected the second breakdown entry on its own line, indented under the label, \
             got {lines:?}"
        );
        assert_eq!(
            lines
                .iter()
                .filter(|line| line.starts_with("refreshed"))
                .count(),
            1,
            "expected exactly one line to start with the refreshed label, got {lines:?}"
        );
    }

    /// `content_lines` flattens every `ContentLine` to plain text, so a breakdown squashed
    /// into one `ContentLine` with an embedded `\n` reads identically to one split across
    /// several `ContentLine`s there. Drawing through the real `Buffer` is the only way to
    /// tell them apart: `Buffer::set_stringn` treats `\n` as a control character and drops
    /// it, so a squashed breakdown paints both entries onto one screen row with no
    /// separator between them instead of two rows.
    #[test]
    fn a_disagreement_breakdown_draws_each_label_age_line_as_its_own_screen_row() {
        use ratatui::{Terminal, backend::TestBackend};

        let now = Timestamp::now();
        let ten_seconds_ago = Timestamp::at(std::time::SystemTime::now() - Duration::from_secs(12));
        let twenty_seconds_ago =
            Timestamp::at(std::time::SystemTime::now() - Duration::from_secs(25));
        let mut row = entity("a");
        row.branch = settled_known_at(Head::Unborn(Arc::from("main")), now, false);
        row.base = settled_known_at(0u32, now, false);
        row.default_branch =
            settled_known_at(DefaultBranch::new(Arc::from("origin/main")), now, false);
        row.sync = settled_known_at(SyncState::NoUpstream, ten_seconds_ago, false);
        row.dirty = settled_known_at(DirtyCounts::default(), twenty_seconds_ago, false);

        let glyphs = full_glyphs();
        let detail = Detail::default();
        let backend = TestBackend::new(60, 20);
        let mut terminal = Terminal::new(backend).expect("create test terminal");

        terminal
            .draw(|frame| {
                detail.draw(frame, frame.area(), &row, glyphs, true, &theme::DEFAULT);
            })
            .expect("draw the frame");

        let buf = terminal.backend().buffer();
        let rows: Vec<String> = (1..buf.area.height.saturating_sub(1))
            .map(|y| {
                (1..buf.area.width.saturating_sub(1))
                    .map(|x| buf[(x, y)].symbol())
                    .collect::<String>()
                    .trim_end()
                    .to_string()
            })
            .collect();

        let refreshed_row = rows
            .iter()
            .position(|line| line.starts_with("refreshed"))
            .unwrap_or_else(|| panic!("no refreshed row drawn, got {rows:?}"));
        assert!(
            rows[refreshed_row].contains("sync, 10s ago") && !rows[refreshed_row].contains("dirty"),
            "expected only the first breakdown entry on the refreshed row, got {:?}",
            rows[refreshed_row]
        );
        assert!(
            rows[refreshed_row + 1].contains("dirty, 20s ago")
                && !rows[refreshed_row + 1].contains("refreshed"),
            "expected the second breakdown entry on its own row below, got {:?}",
            rows[refreshed_row + 1]
        );
    }

    /// With no group ahead of the rest, `freshness_row` used to report whichever group its
    /// tally happened to reach first as "the majority" and hide those cells from the
    /// breakdown entirely, so half a genuine 3-3 split vanished instead of reading as a
    /// disagreement. Short of a strict majority, every cell's own reading is named.
    #[test]
    fn a_three_three_split_names_every_cell_rather_than_hide_half_behind_an_arbitrary_majority() {
        let group_a = Timestamp::now();
        let group_b = Timestamp::at(std::time::SystemTime::now() - Duration::from_secs(15));
        let mut row = entity("a");
        row.branch = settled_known_at(Head::Unborn(Arc::from("main")), group_a, false);
        row.sync = settled_known_at(SyncState::NoUpstream, group_a, false);
        row.base = settled_known_at(0u32, group_a, false);
        row.dirty = settled_known_at(DirtyCounts::default(), group_b, false);
        row.state = settled_known_at(WorktreeState::Active, group_b, false);
        row.default_branch =
            settled_known_at(DefaultBranch::new(Arc::from("origin/main")), group_b, false);

        let lines = content_lines(&row, WIDE, full_glyphs());
        let freshness_index = lines
            .iter()
            .position(|line| line.starts_with("refreshed"))
            .expect("expected a refreshed line");
        let breakdown = &lines[freshness_index..freshness_index + 6];

        for label in ["branch", "sync", "base", "dirty", "state", "default branch"] {
            assert!(
                breakdown.iter().any(|line| line.contains(label)),
                "expected {label} named in a 3-3 split with no majority, got {breakdown:?}"
            );
        }
    }

    #[test]
    fn a_stale_cell_beside_a_fresh_one_still_counts_as_a_disagreement_and_gets_its_own_breakdown_line()
     {
        let at = Timestamp::now();
        let mut row = entity("a");
        row.branch = settled_known_at(Head::Unborn(Arc::from("main")), at, false);
        row.base = settled_known_at(0u32, at, false);
        row.default_branch =
            settled_known_at(DefaultBranch::new(Arc::from("origin/main")), at, false);
        row.dirty = settled_known_at(DirtyCounts::default(), at, true);

        let lines = content_lines(&row, WIDE, full_glyphs());

        let freshness_line = line_labelled(&lines, "refreshed");
        assert_eq!(
            freshness_line, "refreshed       dirty, stale just now",
            "a stale cell beside fresh, same-instant neighbours must still disagree, got \
             {freshness_line:?}"
        );
        assert_eq!(
            lines
                .iter()
                .filter(|line| line.starts_with("refreshed"))
                .count(),
            1,
            "expected exactly one refreshed line, got {lines:?}"
        );
    }

    /// A `Known` cell with a re-probe running against it right now: the shape a cell keeps
    /// while its previous value stays on screen and a new one is being fetched.
    fn settled_known_and_in_flight<T>(value: T, at: Timestamp, stale: bool) -> Cell<T> {
        Cell::already_settled_and_in_flight(Settled::Known { value, at, stale })
    }

    #[test]
    fn a_cell_being_reprobed_reads_loading_and_names_only_the_in_flight_labels() {
        let at = Timestamp::now();
        let mut row = entity("a");
        row.branch = settled_known_at(Head::Unborn(Arc::from("main")), at, false);
        row.sync = settled_known_at(SyncState::NoUpstream, at, false);
        row.base = settled_known_at(0u32, at, false);
        row.default_branch =
            settled_known_at(DefaultBranch::new(Arc::from("origin/main")), at, false);
        row.dirty = settled_known_and_in_flight(DirtyCounts::default(), at, false);
        row.state = settled_known_and_in_flight(WorktreeState::Active, at, false);

        let lines = content_lines(&row, WIDE, full_glyphs());

        let freshness_line = line_labelled(&lines, "loading");
        assert_eq!(
            freshness_line, "loading         dirty, state",
            "got {freshness_line:?}"
        );
        assert!(
            !lines.iter().any(|line| line.starts_with("refreshed")),
            "a cell being reprobed must never also show a refreshed line, got {lines:?}"
        );
    }

    #[test]
    fn the_refreshed_lines_position_is_the_same_line_index_whether_loading_or_settled() {
        let at = Timestamp::now();

        let mut settled = entity("a");
        settled.branch = settled_known_at(Head::Unborn(Arc::from("main")), at, false);

        let mut loading = entity("a");
        loading.branch = settled_known_and_in_flight(Head::Unborn(Arc::from("main")), at, false);

        let settled_lines = content_lines(&settled, WIDE, full_glyphs());
        let loading_lines = content_lines(&loading, WIDE, full_glyphs());

        let default_branch_index = settled_lines
            .iter()
            .position(|line| line.starts_with("default branch"))
            .expect("a default branch line");
        let settled_freshness_index = settled_lines
            .iter()
            .position(|line| line.starts_with("refreshed"))
            .expect("settled Known cells print a refreshed line");
        let loading_freshness_index = loading_lines
            .iter()
            .position(|line| line.starts_with("loading"))
            .expect("an in-flight cell prints a loading line");

        assert_eq!(
            settled_freshness_index,
            default_branch_index + 1,
            "got {settled_lines:?}"
        );
        assert_eq!(
            loading_freshness_index,
            default_branch_index + 1,
            "got {loading_lines:?}"
        );
    }

    #[test]
    fn a_row_with_no_known_cell_yet_prints_no_refreshed_line_at_all() {
        let row = entity("a");

        let lines = content_lines(&row, WIDE, full_glyphs());

        assert!(
            !lines
                .iter()
                .any(|line| line.starts_with("refreshed") || line.starts_with("loading")),
            "a row with nothing Known yet has nothing to report, got {lines:?}"
        );
    }

    #[test]
    fn a_single_known_cell_still_gets_its_own_refreshed_line_rather_than_no_line_at_all() {
        let mut row = entity("a");
        row.dirty = settled_known_at(DirtyCounts::default(), Timestamp::now(), false);

        let lines = content_lines(&row, WIDE, full_glyphs());

        let freshness_line = line_labelled(&lines, "refreshed");
        assert!(
            freshness_line.contains("just now"),
            "got {freshness_line:?}"
        );
        assert_eq!(
            lines
                .iter()
                .filter(|line| line.starts_with("refreshed"))
                .count(),
            1,
            "one Known cell has nothing to disagree with, so it still gets the row, got \
             {lines:?}"
        );
    }

    /// The wiring half of criterion 3: `default_branch_diagnostics_lines` above proves the
    /// words are right, but nothing yet proves `content_lines` actually calls it. Without this,
    /// a diagnostics fact computed correctly could still sit unread and never reach the pane.
    #[test]
    fn content_lines_carries_the_default_branchs_own_diagnostics_lines() {
        let mut disagreeing_at_rung_three = entity("a");
        disagreeing_at_rung_three.diagnostics.default_branch_rung = Some(3);
        disagreeing_at_rung_three
            .diagnostics
            .default_branch_rung_disagreement = true;

        let lines = content_lines(&disagreeing_at_rung_three, WIDE, full_glyphs()).join("\n");

        assert!(lines.contains("name list"), "got {lines:?}");
        assert!(lines.contains("disagree"), "got {lines:?}");
    }

    #[test]
    fn content_lines_shows_the_in_progress_operation_only_when_one_is_set() {
        let mut idle = entity("a");
        idle.in_progress_operation = None;
        let idle_lines = content_lines(&idle, WIDE, full_glyphs()).join("\n");
        assert!(!idle_lines.contains("in progress"));

        let mut rebasing = entity("b");
        rebasing.in_progress_operation = Some(InProgressOperation::Rebase);
        let rebasing_lines = content_lines(&rebasing, WIDE, full_glyphs()).join("\n");
        assert!(rebasing_lines.contains("in progress: rebasing"));
    }

    #[test]
    fn content_lines_lists_recent_commits_most_recent_first() {
        let mut with_commits = entity("a");
        with_commits.recent_commits = vec![
            RecentCommit {
                short_id: Arc::from("abc1234"),
                summary: Arc::from("second commit"),
            },
            RecentCommit {
                short_id: Arc::from("def5678"),
                summary: Arc::from("first commit"),
            },
        ];

        let lines = content_lines(&with_commits, WIDE, full_glyphs());
        let second_index = lines
            .iter()
            .position(|line| line.contains("second commit"))
            .expect("second commit line");
        let first_index = lines
            .iter()
            .position(|line| line.contains("first commit"))
            .expect("first commit line");

        assert!(second_index < first_index);
    }

    #[test]
    fn content_lines_shows_the_last_actions_own_outcome() {
        let mut ok_run = entity("a");
        ok_run.last_action = Some(receipt(StepOutcome::Ok));
        assert!(
            content_lines(&ok_run, WIDE, full_glyphs())
                .join("\n")
                .contains("last action   ok")
        );

        let mut failed_run = entity("b");
        failed_run.last_action = Some(receipt(StepOutcome::Failed(1)));
        assert!(
            content_lines(&failed_run, WIDE, full_glyphs())
                .join("\n")
                .contains("last action   failed")
        );

        let mut no_run = entity("c");
        no_run.last_action = None;
        assert!(
            content_lines(&no_run, WIDE, full_glyphs())
                .join("\n")
                .contains("last action   none yet")
        );
    }

    // --- content_lines: each label line reads its own cell, never a neighbour's ---

    /// A git call against `path` with a fixed identity, so a commit never depends on the
    /// machine's own global git config.
    fn git(path: &Path, args: &[&str]) {
        let status = Command::new("git")
            .arg("-C")
            .arg(path)
            .args(["-c", "user.email=test@example.com", "-c", "user.name=Test"])
            .args(args)
            .status()
            .expect("run git");
        assert!(status.success(), "git {args:?} failed");
    }

    /// A real disposable repository at `path`, on `branch`, with one commit and a fabricated
    /// `origin/main` remote-tracking ref plus a symbolic `origin/HEAD`: `default_branch`
    /// resolves to a real Known value at rung 2 without a real remote, the same hermetic
    /// fixture `repon-core`'s own default-branch tests use.
    fn init_repo_with_a_resolvable_default_branch(path: &Path, branch: &str) {
        std::fs::create_dir_all(path).expect("create repo dir");
        let status = Command::new("git")
            .arg("init")
            .args(["--quiet", "--initial-branch", branch])
            .arg(path)
            .status()
            .expect("run git init");
        assert!(status.success());
        git(path, &["commit", "--allow-empty", "-m", "first"]);
        git(
            path,
            &[
                "remote",
                "add",
                "origin",
                "https://example.invalid/repo.git",
            ],
        );
        let sha_output = Command::new("git")
            .arg("-C")
            .arg(path)
            .args(["rev-parse", "HEAD"])
            .output()
            .expect("run git rev-parse");
        assert!(sha_output.status.success());
        let sha = String::from_utf8(sha_output.stdout)
            .expect("utf8 sha")
            .trim()
            .to_string();
        git(path, &["update-ref", "refs/remotes/origin/main", &sha]);
        let remote_refs_dir = path
            .join(".git")
            .join("refs")
            .join("remotes")
            .join("origin");
        std::fs::create_dir_all(&remote_refs_dir).expect("create refs/remotes/origin dir");
        std::fs::write(
            remote_refs_dir.join("HEAD"),
            "ref: refs/remotes/origin/main\n",
        )
        .expect("write refs/remotes/origin/HEAD");
    }

    /// The line whose label starts `lines`' entry, panicking with the whole pane's content if
    /// none does: every assertion below reads the pane by label, never by position, so a
    /// reordering of [`content_lines`]'s own pushes could not make this pass by accident.
    fn line_labelled<'a>(lines: &'a [String], label: &str) -> &'a str {
        lines
            .iter()
            .find(|line| line.starts_with(label))
            .unwrap_or_else(|| panic!("no {label:?} line in {lines:?}"))
    }

    /// The defining behaviour of criterion 2: every one of the six per-Cell lines reads its
    /// own cell's value, never a neighbour's. The submodule's own branch, sync, dirty and
    /// default branch settle in the same refresh and so share one age, which
    /// `row_freshness_agreement` collapses onto its own line rather than repeating per cell;
    /// this test checks that collapsed line exists once, rather than the age inside each
    /// per-cell line, for that reason. `base` (`Cell<u32>`) and
    /// `dirty` (`Cell<DirtyCounts>`) now carry distinct types, so a wiring bug that read one
    /// from the other could not compile; this test still proves it at the value level rather
    /// than resting on that alone, since a future change could narrow both back to the same
    /// shape. A `Kind::Submodule` entity is built from a real disposable repository nested
    /// under a `.gitmodules` boundary, whose own working tree this crate probes and finds
    /// clean, with its own `default_branch` genuinely resolvable; construction alone still
    /// settles `state` and `base` to `Unknown` regardless, per
    /// [ADR 0017](https://github.com/paulchiu/repon/blob/main/docs/adr/0017-discovery-stops-at-the-repo-boundary.md)
    /// as amended, which is what gives `base` and `dirty` distinct, non-equal text
    /// ("unknown: no default branch found" against "clean") without a way to reach into a
    /// private `Cell` from this crate.
    #[test]
    fn content_lines_never_reads_one_cells_line_from_a_different_cell() {
        let dir = tempfile::tempdir().expect("temp dir");
        let root = dir.path().canonicalize().expect("canonicalize temp dir");
        let outer = root.join("outer");
        let submodule_path = outer.join("vendor").join("lib");

        std::fs::create_dir_all(&outer).expect("create outer dir");
        let status = Command::new("git")
            .arg("init")
            .args(["--quiet", "--initial-branch", "outer-main"])
            .arg(&outer)
            .status()
            .expect("run git init");
        assert!(status.success());
        git(&outer, &["commit", "--allow-empty", "-m", "first"]);
        std::fs::write(
            outer.join(".gitmodules"),
            "[submodule \"lib\"]\n\tpath = vendor/lib\n\turl = https://example.invalid/lib.git\n",
        )
        .expect("write .gitmodules");
        init_repo_with_a_resolvable_default_branch(&submodule_path, "feature-distinct-branch");

        let core = Core::start_discovered(CoreSpec {
            set: SetSpec {
                name: "test".to_string(),
                roots: vec![root],
                include: Vec::new(),
                exclude: Vec::new(),
            },
            overrides: Vec::new(),
            poll_interval: Duration::from_secs(3600),
            status_stale_after: Duration::from_secs(3600),
            generation_deadline: Duration::from_secs(3600),
            // Shown, so `refresh` below actually dispatches a probe against it: this test is
            // about per-cell content, not about `show_submodules`'s own dispatch gate.
            show_submodules: true,
            fetch: repon_core::FetchSpec {
                enabled: false,
                interval: std::time::Duration::from_secs(3600),
                concurrency: 4,
            },
            auto_update: repon_core::AutoUpdateSpec { enabled: false },
        });
        let keys: Vec<_> = core
            .snapshot()
            .entities
            .iter()
            .map(|entity| entity.key.clone())
            .collect();
        core.refresh(&keys);
        let settled = core.settle();
        let submodule = settled
            .entities
            .iter()
            .find(|entity| matches!(entity.kind, Kind::Submodule))
            .expect("submodule entity present");

        let lines = content_lines(submodule, WIDE, full_glyphs());

        let branch_line = line_labelled(&lines, "branch");
        let sync_line = line_labelled(&lines, "sync");
        let base_line = line_labelled(&lines, "base");
        let dirty_line = line_labelled(&lines, "dirty");
        let state_line = line_labelled(&lines, "state");
        let default_branch_line = line_labelled(&lines, "default branch");

        assert!(
            branch_line.contains("feature-distinct-branch") && !branch_line.contains("refreshed"),
            "got {branch_line:?}"
        );
        assert!(
            default_branch_line.contains("origin/main")
                && !default_branch_line.contains("refreshed"),
            "got {default_branch_line:?}"
        );
        assert!(
            sync_line.contains("no upstream configured") && !sync_line.contains("refreshed"),
            "the submodule's own branch has a remote but no upstream configured for it, got \
             {sync_line:?}"
        );
        assert!(
            dirty_line.contains("clean") && !dirty_line.contains("refreshed"),
            "the submodule's own working tree is freshly committed and clean, got \
             {dirty_line:?}"
        );
        assert!(
            base_line.ends_with("unknown: no default branch found"),
            "got {base_line:?}"
        );
        assert!(
            state_line.ends_with("unknown: no default branch found"),
            "got {state_line:?}"
        );
        assert!(
            lines.iter().any(|line| line.contains("refreshed")
                && (line.contains("ago") || line.contains("just now"))),
            "expected the four agreeing Known cells' shared age on its own line, got {lines:?}"
        );

        // Defence in depth beyond the type-level guard `DirtyCounts` now gives `dirty` over
        // `base`'s plain `u32`: a wiring bug that read one cell's line from the other would
        // still show up here as a value that reads alike.
        assert_ne!(
            base_line, dirty_line,
            "base and dirty must never read alike: {base_line:?} vs {dirty_line:?}"
        );
    }

    // --- Criterion 3: "the detail pane's labels are dim and its values take
    // whichever role their meaning already has" ---

    #[test]
    fn describe_cell_spans_gives_a_known_values_own_meaning_its_role_and_no_other_span() {
        let settled = Settled::Known {
            value: 5u32,
            at: Timestamp::now(),
            stale: false,
        };

        let spans = describe_cell_spans(
            Some(&settled),
            |value| value.to_string(),
            |_| Meaning::Dirty,
        );

        assert_eq!(
            spans,
            vec![("5".to_string(), Meaning::Dirty.role())],
            "a Known value carries no age span of its own, got {spans:?}"
        );
    }

    #[test]
    fn describe_cell_spans_colours_unknown_dim_failed_danger_not_applicable_text_and_loading_accent()
     {
        let unknown: Settled<u32> = Settled::Unknown(Unknown::TimedOut);
        let failed: Settled<u32> = Settled::Failed(ProbeError::Read(Arc::from("boom")));
        let not_applicable: Settled<u32> = Settled::NotApplicable;

        assert_eq!(
            describe_cell_spans(Some(&unknown), |v: &u32| v.to_string(), |_| Meaning::Dirty)[0].1,
            Meaning::StaleOrUnknownGutterMark.role()
        );
        assert_eq!(
            describe_cell_spans(Some(&failed), |v: &u32| v.to_string(), |_| Meaning::Dirty)[0].1,
            Meaning::FailedProvenance.role()
        );
        assert_eq!(
            describe_cell_spans(
                Some(&not_applicable),
                |v: &u32| v.to_string(),
                |_| { Meaning::Dirty }
            )[0]
            .1,
            Role::Text
        );
        assert_eq!(
            describe_cell_spans(
                None::<&Settled<u32>>,
                |v: &u32| v.to_string(),
                |_| Meaning::Dirty
            )[0]
            .1,
            Meaning::LoadingSpinner.role()
        );
    }

    // --- Own work: the receipt a Management operation leaves, docs/spec/repo-management.md ---

    /// A receipt whose one step Repon performed itself, built the way
    /// [`repon_core::Core::record_own_work`] builds one: the operation labels both the receipt
    /// and its single step, and nothing was captured.
    fn own_work_receipt(operation: &str, work: OwnWork) -> ActionReceipt {
        ActionReceipt {
            label: Arc::from(operation),
            steps: Arc::from(vec![StepResult {
                label: Arc::from(operation),
                outcome: StepOutcome::OwnWork(work),
                output: Arc::from(&b""[..]),
                elapsed: Duration::from_millis(3),
                elision: None,
                shell: false,
                interactive: false,
            }]),
            skip: None,
            finished_at: Timestamp::now(),
            running: None,
        }
    }

    /// The pane names the operation and what Repon did, in Repon's own words. This is the
    /// Done-when's "naming per Repo what was done" reaching the surface that has to show it.
    #[test]
    fn the_pane_names_the_operation_and_what_repon_did() {
        let mut row = entity("repo-a");
        row.last_action = Some(own_work_receipt(
            "delete",
            OwnWork::Did(Arc::from("working tree removed, `[[repo]]` entry removed")),
        ));

        let lines = content_lines(&row, WIDE, full_glyphs()).join("\n");

        assert!(lines.contains("delete"), "got {lines:?}");
        assert!(
            lines.contains("working tree removed, `[[repo]]` entry removed"),
            "got {lines:?}"
        );
    }

    /// The refusal half: the pane names why the row was not acted on, and the summary word
    /// above it says refused rather than ok, since neither a success nor a failure happened.
    #[test]
    fn the_pane_names_why_a_row_was_refused_and_calls_the_run_refused_rather_than_ok() {
        let mut row = entity("sidecar");
        row.last_action = Some(own_work_receipt(
            "delete",
            OwnWork::Refused(Arc::from(
                "refused, removing a linked Worktree is `git worktree remove`'s job",
            )),
        ));

        let lines = content_lines(&row, WIDE, full_glyphs()).join("\n");

        assert!(
            lines.contains("refused, removing a linked Worktree"),
            "got {lines:?}"
        );
        assert_eq!(
            last_action_spans(&row.last_action)[0].0,
            "refused",
            "a refusal is neither ok nor failed"
        );
        assert_eq!(
            last_action_spans(&row.last_action)[0].1,
            Meaning::ActionStepNotRunOrCancelled.role(),
            "and takes the dim role rather than danger, since nothing went wrong"
        );
    }

    /// No row of a management receipt reads as something a child process did: no step number,
    /// since the operation is one act rather than a position in an ordered list, and no exit
    /// code, since nothing exited.
    #[test]
    fn an_own_work_row_carries_no_step_number_and_no_exit_code() {
        for work in [
            OwnWork::Did(Arc::from("ignored")),
            OwnWork::Refused(Arc::from("refused, already ignored")),
            OwnWork::CouldNotAct(Arc::from("failed, permission denied")),
        ] {
            let mut row = entity("repo-a");
            row.last_action = Some(own_work_receipt("ignore", work));

            let lines = content_lines(&row, WIDE, full_glyphs()).join("\n");

            assert!(!lines.contains("step 1"), "got {lines:?}");
            assert!(!lines.contains("exit"), "got {lines:?}");
            assert!(!lines.contains("not run"), "got {lines:?}");
            assert!(!lines.contains("cancelled"), "got {lines:?}");
        }
    }

    /// Each grade takes the role theming.md already gives that state, and a refusal takes the
    /// dim one rather than danger: a Repo Repon declined to act on must not read as a Repo
    /// whose command blew up.
    #[test]
    fn each_grade_of_own_work_takes_its_own_role_and_only_could_not_act_reads_as_a_failure() {
        let did = StepOutcome::OwnWork(OwnWork::Did(Arc::from("ignored")));
        let refused = StepOutcome::OwnWork(OwnWork::Refused(Arc::from("already ignored")));
        let could_not = StepOutcome::OwnWork(OwnWork::CouldNotAct(Arc::from("boom")));

        assert_eq!(step_outcome_meaning(&did), Meaning::SucceededActionStep);
        assert_eq!(
            step_outcome_meaning(&refused),
            Meaning::ActionStepNotRunOrCancelled
        );
        assert_eq!(step_outcome_meaning(&could_not), Meaning::FailedActionStep);

        assert_eq!(step_outcome_word(&did), "ignored");
        assert_eq!(step_outcome_word(&refused), "already ignored");
        assert_eq!(step_outcome_word(&could_not), "boom");

        let mut refused_row = entity("a");
        refused_row.last_action = Some(own_work_receipt(
            "ignore",
            OwnWork::Refused(Arc::from("already ignored")),
        ));
        assert_eq!(
            row_level_failure(&refused_row.diagnostics, &refused_row.last_action),
            None,
            "a refusal must not widen the row summary fold"
        );

        let mut could_not_row = entity("b");
        could_not_row.last_action = Some(own_work_receipt(
            "delete",
            OwnWork::CouldNotAct(Arc::from("boom")),
        ));
        assert!(
            row_level_failure(&could_not_row.diagnostics, &could_not_row.last_action).is_some(),
            "work Repon could not finish is a failure and does widen it"
        );
    }

    #[test]
    fn sync_meaning_gives_an_ahead_a_behind_a_known_zero_and_a_settled_absence_their_own_role() {
        assert_eq!(
            sync_meaning(&SyncState::Tracking(repon_core::AheadBehind {
                ahead: 2,
                behind: 0
            })),
            Meaning::AheadCount
        );
        assert_eq!(
            sync_meaning(&SyncState::Tracking(repon_core::AheadBehind {
                ahead: 0,
                behind: 3
            })),
            Meaning::BehindCount
        );
        assert_eq!(
            sync_meaning(&SyncState::Tracking(repon_core::AheadBehind {
                ahead: 0,
                behind: 0
            })),
            Meaning::KnownZero
        );
        assert_eq!(sync_meaning(&SyncState::NoUpstream), Meaning::FreshValue);
        assert_eq!(sync_meaning(&SyncState::NoRemote), Meaning::FreshValue);
    }

    #[test]
    fn last_action_spans_names_ok_failed_and_none_yet_through_their_own_role() {
        assert_eq!(
            last_action_spans(&Some(receipt(StepOutcome::Ok)))[0].1,
            Meaning::SucceededActionStep.role()
        );
        assert_eq!(
            last_action_spans(&Some(receipt(StepOutcome::Failed(1))))[0].1,
            Meaning::FailedActionStep.role()
        );
        assert_eq!(
            last_action_spans(&None)[0].1,
            Meaning::ActionStepNotRunOrCancelled.role()
        );
    }

    #[test]
    fn styled_content_lines_gives_every_labels_own_span_the_dim_role() {
        let lines = styled_content_lines(&entity("a"), WIDE, full_glyphs());

        // Every per-cell line pushed through `labelled` opens with a `(label, Role::Dim)`
        // span; the header, path and blank lines are not labelled and are excluded by their
        // own shape (more than one word before any padding, or empty).
        let labelled_lines = [3, 4, 5, 6, 7, 8];
        for index in labelled_lines {
            assert_eq!(
                lines[index].spans()[0].1,
                Role::Dim,
                "line {index} {:?} must open with a dim label",
                lines[index]
            );
        }
    }

    #[test]
    fn styled_content_lines_gives_the_header_name_its_kind_cell_meaning_and_the_kind_word_dim() {
        let repo = EntityState::new(
            EntityKey::new(Arc::from(Path::new("r"))),
            Arc::from("r"),
            Arc::from(Path::new("r")),
            Kind::Repo,
        );
        let worktree = entity("wt");

        let repo_header = &styled_content_lines(&repo, WIDE, full_glyphs())[0];
        let worktree_header = &styled_content_lines(&worktree, WIDE, full_glyphs())[0];

        assert_eq!(repo_header.spans()[0].1, Meaning::FreshValue.role());
        assert_eq!(worktree_header.spans()[0].1, Meaning::WorktreeName.role());
        assert_eq!(
            worktree_header.spans()[1].1,
            Role::Dim,
            "the kind word is dim"
        );
    }

    #[test]
    fn styled_content_lines_colours_the_recent_header_as_a_column_header_and_a_row_level_failure_danger()
     {
        let lines = styled_content_lines(&entity("a"), WIDE, full_glyphs());
        let recent_line = lines
            .iter()
            .find(|line| line.first_text() == Some("recent"))
            .expect("expected a 'recent' section header line");
        assert_eq!(recent_line.spans()[0].1, Meaning::ColumnHeader.role());

        let mut failing = entity("b");
        failing.diagnostics.gitmodules_failed = Some(Arc::from("bad syntax"));
        let failing_lines = styled_content_lines(&failing, WIDE, full_glyphs());
        let failure_line = failing_lines
            .iter()
            .find(|line| {
                line.first_text()
                    .is_some_and(|text| text.contains(".gitmodules"))
            })
            .expect("expected the row-level failure line");
        assert_eq!(failure_line.spans()[0].1, Meaning::FailedProvenance.role());
    }

    /// Defect 2 (the detail half): the top title names the Entity `draw` was handed, not a
    /// fixed word, so a caller cycling through rows sees which one it is looking at without
    /// opening a second surface.
    #[test]
    fn draw_titles_the_top_border_with_the_entitys_own_name() {
        use ratatui::{Terminal, backend::TestBackend};

        let glyphs = full_glyphs();
        let detail = Detail::default();
        let backend = TestBackend::new(60, 10);
        let mut terminal = Terminal::new(backend).expect("create test terminal");

        terminal
            .draw(|frame| {
                detail.draw(
                    frame,
                    frame.area(),
                    &entity("distinctive-repo-name"),
                    glyphs,
                    true,
                    &theme::DEFAULT,
                );
            })
            .expect("draw the frame");

        let top_row: String = (0..60)
            .map(|x| terminal.backend().buffer()[(x, 0)].symbol())
            .collect();
        assert!(
            top_row.contains("distinctive-repo-name"),
            "expected the entity's own name in the top border, got: {top_row:?}"
        );
    }

    /// The border must take its role from the live theme handed to `draw`, not the compiled
    /// default: before this ticket `draw` always painted through `theme::DEFAULT`, which
    /// meant a theme file's own colours never reached this pane. A colour with no compiled
    /// role reuses it (`Rgb(9, 8, 7)`, the same fixture `launcher_palette.rs`'s own version
    /// of this test uses), so passing the compiled default through by mistake cannot pass by
    /// coincidence.
    #[test]
    fn draw_paints_the_border_from_the_live_theme_not_the_compiled_default() {
        use ratatui::{Terminal, backend::TestBackend};

        let live_theme = Theme {
            border_focused: ratatui::style::Color::Rgb(9, 8, 7),
            ..theme::DEFAULT
        };
        let glyphs = GlyphSet::for_config(crate::config::document::Glyphs::default());
        let detail = Detail::default();
        let backend = TestBackend::new(40, 10);
        let mut terminal = Terminal::new(backend).expect("create test terminal");

        terminal
            .draw(|frame| {
                detail.draw(frame, frame.area(), &entity("a"), glyphs, true, &live_theme);
            })
            .expect("draw the frame");

        let buf = terminal.backend().buffer();
        assert_eq!(
            buf[(0, 0)].fg,
            ratatui::style::Color::Rgb(9, 8, 7),
            "expected the focused border painted in the live theme's own colour"
        );
    }

    /// theming.md's "panel border" row: the pane frames itself with the active table's own
    /// characters and degrades with it under `glyphs = "ascii"`, the same set every other
    /// framed surface reads. Both tables in the one test, so a hardcoded copy of either
    /// satisfies neither.
    #[test]
    fn draw_frames_the_pane_with_the_active_glyph_tables_own_border() {
        use ratatui::{Terminal, backend::TestBackend};

        // Tall enough that this fixture's own content fits: the assertion below reads the
        // whole right border, which a scrollable pane draws its own scrollbar over.
        for glyphs in [&crate::glyphs::FULL, &crate::glyphs::ASCII] {
            let detail = Detail::default();
            let backend = TestBackend::new(40, 30);
            let mut terminal = Terminal::new(backend).expect("create test terminal");

            terminal
                .draw(|frame| {
                    detail.draw(
                        frame,
                        frame.area(),
                        &entity("a"),
                        glyphs,
                        true,
                        &theme::DEFAULT,
                    );
                })
                .expect("draw the frame");

            // Not `assert_frame_drawn_with`: the bottom border now carries the close hint
            // rather than a plain dash run, the same reason `warnings.rs`'s own frame test
            // reads the top and the bottom separately.
            crate::test_support::assert_bordered_frame_and_top_title_drawn_with(
                terminal.backend().buffer(),
                Rect::new(0, 0, 40, 30),
                glyphs.border,
                " a ",
                "the detail pane's frame",
            );
            let bottom_row: String = (0..40)
                .map(|x| terminal.backend().buffer()[(x, 29)].symbol())
                .collect();
            let expected_tail = format!(
                "{}{}",
                crate::warnings::CLOSE_HINT,
                glyphs.border.bottom_right
            );
            assert!(
                bottom_row.ends_with(&expected_tail),
                "expected the close hint right-aligned against the bottom-right corner, got \
                 {bottom_row:?}"
            );
        }
    }

    // --- the scrollbar: whether the pane scrolls, where in the content it is, how much is left ---

    /// The pane's own right border between its two corners, top to bottom: the cells the
    /// scrollbar is drawn over, and the only cells it may touch.
    fn right_border_interior(buf: &Buffer, area: Rect) -> String {
        ((area.y + 1)..(area.bottom() - 1))
            .map(|y| buf[(area.right() - 1, y)].symbol())
            .collect()
    }

    /// An Entity whose recent commits are the only thing making the pane long: one line each,
    /// and nothing else the pane shows changes with their number.
    fn entity_with_commits(count: usize) -> EntityState {
        let mut entity = entity("a");
        entity.recent_commits = (0..count)
            .map(|index| RecentCommit {
                short_id: Arc::from(format!("{index:07}")),
                summary: Arc::from("a commit summary"),
            })
            .collect();
        entity
    }

    /// Draws `entity` into a `width` by `height` pane at `scroll`, and returns the buffer's
    /// own right border between the corners.
    fn drawn_scrollbar(
        entity: &EntityState,
        glyphs: &'static GlyphSet,
        theme: &Theme,
        focused: bool,
        scroll: u16,
        width: u16,
        height: u16,
    ) -> (String, ratatui::buffer::Buffer) {
        use ratatui::{Terminal, backend::TestBackend};

        let area = Rect::new(0, 0, width, height);
        let detail = Detail { scroll };
        let backend = TestBackend::new(width, height);
        let mut terminal = Terminal::new(backend).expect("create test terminal");
        terminal
            .draw(|frame| detail.draw(frame, frame.area(), entity, glyphs, focused, theme))
            .expect("draw the frame");
        let buf = terminal.backend().buffer().clone();
        (right_border_interior(&buf, area), buf)
    }

    /// A pane showing everything it has is drawn exactly as it was before the bar existed:
    /// the frame's own vertical rule, all the way down, and no thumb anywhere.
    #[test]
    fn draw_leaves_the_right_border_bare_when_the_content_fits_the_pane() {
        let glyphs = full_glyphs();
        let (bar, _) = drawn_scrollbar(&entity("a"), glyphs, &theme::DEFAULT, true, 0, 40, 40);

        assert_eq!(
            bar,
            glyphs
                .border
                .vertical
                .to_string()
                .repeat(bar.chars().count()),
            "expected an unscrollable pane's right border untouched, got {bar:?}"
        );
    }

    /// The pane at its first line reports it: the thumb sits against the top of the track,
    /// and the rest of the track is still bare border.
    #[test]
    fn draw_marks_the_top_of_the_right_border_when_a_scrollable_pane_shows_its_first_line() {
        let glyphs = full_glyphs();
        let (bar, _) = drawn_scrollbar(
            &entity_with_commits(30),
            glyphs,
            &theme::DEFAULT,
            true,
            0,
            40,
            10,
        );

        assert!(
            bar.starts_with(glyphs.scrollbar_thumb),
            "expected the thumb against the top of the track, got {bar:?}"
        );
        assert!(
            bar.ends_with(glyphs.scrollbar_track),
            "expected track below the thumb at the first line, got {bar:?}"
        );
    }

    /// The reading the pane could not give before: a pane showing its last line is told apart
    /// from one showing its first, because the thumb reaches the bottom of the track. The
    /// corners and the bottom border's own close hint are outside the bar's own cells.
    #[test]
    fn draw_marks_the_bottom_of_the_right_border_when_a_scrollable_pane_shows_its_last_line() {
        let glyphs = full_glyphs();
        let entity = entity_with_commits(30);
        let mut detail = Detail::default();
        detail.apply(Action::Bottom, Detail::content_len(&entity, 40, glyphs), 8);

        let (bar, buf) = drawn_scrollbar(
            &entity,
            glyphs,
            &theme::DEFAULT,
            true,
            detail.scroll,
            40,
            10,
        );

        assert!(
            bar.ends_with(glyphs.scrollbar_thumb),
            "expected the thumb against the bottom of the track at the last line, got {bar:?}"
        );
        assert!(
            bar.starts_with(glyphs.scrollbar_track),
            "expected track above the thumb at the last line, got {bar:?}"
        );
        assert_eq!(
            buf[(39, 0)].symbol(),
            glyphs.border.top_right.to_string(),
            "the bar must not reach the pane's own top-right corner"
        );
        assert_eq!(
            buf[(39, 9)].symbol(),
            glyphs.border.bottom_right.to_string(),
            "the bar must not reach the pane's own bottom-right corner"
        );
    }

    /// The bar degrades with the frame it is drawn over: both characters come from the
    /// active table, so `glyphs = "ascii"` leaves nothing on the border that `TERM=linux`
    /// cannot draw. Both tables in the one test, so a hardcoded copy of either satisfies
    /// neither.
    #[test]
    fn draw_takes_the_scrollbars_characters_from_the_active_glyph_table() {
        for glyphs in [&crate::glyphs::FULL, &crate::glyphs::ASCII] {
            let (bar, _) = drawn_scrollbar(
                &entity_with_commits(30),
                glyphs,
                &theme::DEFAULT,
                true,
                0,
                40,
                10,
            );

            assert!(
                bar.contains(glyphs.scrollbar_thumb),
                "expected the active table's own thumb on the border, got {bar:?}"
            );
            assert!(
                bar.contains(glyphs.scrollbar_track),
                "expected the active table's own track on the border, got {bar:?}"
            );
        }
    }

    /// The bar takes the border's own role rather than one of its own, so it carries the
    /// pane's focus the same way the frame around it does. Colours with no compiled role
    /// reuse them, so passing the wrong one through cannot pass by coincidence.
    #[test]
    fn draw_paints_the_scrollbar_in_the_role_of_the_border_it_sits_in() {
        let live_theme = Theme {
            border: ratatui::style::Color::Rgb(1, 2, 3),
            border_focused: ratatui::style::Color::Rgb(9, 8, 7),
            ..theme::DEFAULT
        };
        let glyphs = full_glyphs();

        for (focused, expected) in [
            (true, ratatui::style::Color::Rgb(9, 8, 7)),
            (false, ratatui::style::Color::Rgb(1, 2, 3)),
        ] {
            let (_, buf) = drawn_scrollbar(
                &entity_with_commits(30),
                glyphs,
                &live_theme,
                focused,
                0,
                40,
                10,
            );

            assert_eq!(
                buf[(39, 1)].fg,
                expected,
                "expected the thumb painted in the same role as the border, focused: {focused}"
            );
        }
    }

    /// The rendering half of the criterion above: proves `draw` actually reads
    /// `styled_content_lines` (dim label, meaning-coloured value) rather than the plain,
    /// uncoloured `content_lines` this ticket's predecessor painted with `Style::new()`.
    #[test]
    fn draw_paints_the_header_lines_name_in_its_own_meaning_role() {
        use ratatui::{Terminal, backend::TestBackend};

        let glyphs = GlyphSet::for_config(crate::config::document::Glyphs::default());
        let detail = Detail::default();
        let backend = TestBackend::new(40, 10);
        let mut terminal = Terminal::new(backend).expect("create test terminal");
        let worktree = entity("wt");

        terminal
            .draw(|frame| {
                detail.draw(
                    frame,
                    frame.area(),
                    &worktree,
                    glyphs,
                    true,
                    &theme::DEFAULT,
                );
            })
            .expect("draw the frame");

        let buf = terminal.backend().buffer();
        // The interior starts one cell in from the border on both axes.
        assert_eq!(
            buf[(1, 1)].fg,
            theme::DEFAULT.role_color(Meaning::WorktreeName.role()),
            "expected the Worktree name painted in its own meaning's role, not left uncoloured"
        );
    }

    // --- Criterion 1: labelled per-step output survives the run, with elapsed time ---

    /// The first claim, separated from the other four the ticket's own risk analysis names:
    /// a finished step's own label and its captured output are both still there after the
    /// whole run has ended, read straight off the receipt with no run in flight at all.
    #[test]
    fn a_finished_steps_own_label_and_output_survive_the_run() {
        let mut row = entity("a");
        row.last_action = Some(action_receipt(
            "reinstall",
            vec![
                step_result(
                    "rm -rf node_modules",
                    StepOutcome::Ok,
                    b"",
                    Duration::from_millis(300),
                ),
                step_result(
                    "pnpm install",
                    StepOutcome::Ok,
                    b"added 42 packages\n",
                    Duration::from_secs(9),
                ),
            ],
            None,
        ));

        let lines = content_lines(&row, WIDE, full_glyphs()).join("\n");

        assert!(
            lines.contains("rm -rf node_modules"),
            "expected the first step's own label, got: {lines}"
        );
        assert!(
            lines.contains("pnpm install"),
            "expected the second step's own label, got: {lines}"
        );
        assert!(
            lines.contains("added 42 packages"),
            "expected the second step's own captured output, still present after the run, \
             got: {lines}"
        );
    }

    /// The third claim: per-step elapsed time, distinct from the step's own label or output.
    #[test]
    fn each_finished_steps_own_elapsed_time_is_shown() {
        let mut row = entity("a");
        row.last_action = Some(action_receipt(
            "reinstall",
            vec![
                step_result(
                    "rm -rf node_modules",
                    StepOutcome::Ok,
                    b"",
                    Duration::from_millis(300),
                ),
                step_result("pnpm test", StepOutcome::Ok, b"", Duration::from_secs(75)),
            ],
            None,
        ));

        let lines = content_lines(&row, WIDE, full_glyphs()).join("\n");

        assert!(
            lines.contains("0.3s"),
            "expected the first step's own elapsed time, got: {lines}"
        );
        assert!(
            lines.contains("1m15s"),
            "expected the second step's own elapsed time past a minute, got: {lines}"
        );
    }

    /// The fourth claim: a spinner in the outcome position for the step now running, and
    /// only that step; a finished step's own line never carries one.
    #[test]
    fn a_running_step_carries_the_spinner_in_the_outcome_position_and_a_finished_step_never_does() {
        let glyphs = full_glyphs();
        let mut row = entity("a");
        row.last_action = Some(action_receipt(
            "reinstall",
            vec![step_result(
                "rm -rf node_modules",
                StepOutcome::Ok,
                b"",
                Duration::from_millis(300),
            )],
            Some(RunningStep {
                label: Arc::from("pnpm install"),
                started_at: Timestamp::now(),
                shell: false,
                interactive: false,
            }),
        ));

        let lines = styled_content_lines(&row, WIDE, glyphs);
        let finished_line = lines
            .iter()
            .find(|line| {
                line.first_text()
                    .is_some_and(|text| text.contains("step 1"))
            })
            .expect("expected the finished step's own line");
        let running_line = lines
            .iter()
            .find(|line| {
                line.first_text()
                    .is_some_and(|text| text.contains("step 2"))
            })
            .expect("expected the running step's own line");

        assert_eq!(
            finished_line.spans()[0].1,
            Role::Dim,
            "a finished step's own leading span must never carry the spinner's role"
        );
        assert_eq!(
            running_line.spans()[0].1,
            Meaning::LoadingSpinner.role(),
            "the running step's own leading span must carry the spinner's role"
        );
        let running_text = running_line.first_text().expect("running line has text");
        assert!(
            glyphs
                .loading
                .iter()
                .any(|frame| running_text.starts_with(*frame)),
            "expected the running line to open with one of the glyph set's own spinner \
             frames, got: {running_text:?}"
        );
    }

    // --- A step's own shell mode reaches the pane (#351) ---

    /// [`StepResult::shell`] marks a finished step's own label with [`shell_tag`] when it ran
    /// through a shell, and leaves an argv step unmarked: the reader sees which one produced
    /// the output above it without opening the receipt's own fields.
    #[test]
    fn a_finished_step_that_ran_through_a_shell_is_marked_and_an_argv_step_is_not() {
        let mut row = entity("a");
        row.last_action = Some(action_receipt(
            "deploy",
            vec![
                step_result(
                    "rm -rf node_modules",
                    StepOutcome::Ok,
                    b"",
                    Duration::from_millis(1),
                ),
                StepResult {
                    shell: true,
                    ..step_result(
                        "echo $(pwd)",
                        StepOutcome::Ok,
                        b"",
                        Duration::from_millis(1),
                    )
                },
            ],
            None,
        ));

        let lines = content_lines(&row, WIDE, full_glyphs()).join("\n");

        let argv_line = lines
            .lines()
            .find(|line| line.contains("rm -rf node_modules"))
            .expect("expected the argv step's own line");
        let shell_line = lines
            .lines()
            .find(|line| line.contains("echo $(pwd)"))
            .expect("expected the shell step's own line");
        assert!(
            !argv_line.contains("[shell]"),
            "an argv step must carry no shell mark, got: {argv_line:?}"
        );
        assert!(
            shell_line.contains("[shell]"),
            "a step that ran through a shell must carry its mark, got: {shell_line:?}"
        );
    }

    /// [`StepResult::interactive`] sharpens the mark to `[shell -ic]` rather than adding a
    /// second, separate one.
    #[test]
    fn a_finished_step_that_ran_interactively_is_marked_shell_ic() {
        let mut row = entity("a");
        row.last_action = Some(action_receipt(
            "deploy",
            vec![StepResult {
                shell: true,
                interactive: true,
                ..step_result("gff", StepOutcome::Ok, b"", Duration::from_millis(1))
            }],
            None,
        ));

        let lines = content_lines(&row, WIDE, full_glyphs()).join("\n");

        let line = lines
            .lines()
            .find(|line| line.contains("gff"))
            .expect("expected the interactive step's own line");
        assert!(
            line.contains("[shell -ic]"),
            "an interactive step must carry the -ic mark, got: {line:?}"
        );
    }

    /// The same mark on a step still running, read off [`RunningStep::shell`] rather than
    /// waiting for the step to finish.
    #[test]
    fn a_running_step_that_is_shelling_out_is_marked_before_it_finishes() {
        let mut row = entity("a");
        row.last_action = Some(action_receipt(
            "deploy",
            Vec::new(),
            Some(RunningStep {
                label: Arc::from("echo $(pwd)"),
                started_at: Timestamp::now(),
                shell: true,
                interactive: false,
            }),
        ));

        let lines = content_lines(&row, WIDE, full_glyphs()).join("\n");

        let running_line = lines
            .lines()
            .find(|line| line.contains("echo $(pwd)"))
            .expect("expected the running step's own line");
        assert!(
            running_line.contains("[shell]"),
            "a running shell step must carry its mark before it finishes, got: {running_line:?}"
        );
    }

    // --- The capture elision mark is the consumer's, chosen from the live glyph set ---

    /// A finished step whose capture was bounded: `kept_head` head lines, then `kept_tail`
    /// tail lines, with the drop reported beside them, which is the shape
    /// `bound_head_and_tail` hands over once the mark stopped being written into the bytes.
    /// The two runs are numbered so a row's position can be read off the text, not merely
    /// its presence.
    fn elided_step(dropped_lines: usize, kept_head: usize, kept_tail: usize) -> StepResult {
        let mut output = String::new();
        for n in 0..kept_head {
            output.push_str(&format!("head {n}\n"));
        }
        for n in 0..kept_tail {
            output.push_str(&format!("tail {n}\n"));
        }
        StepResult {
            label: Arc::from("pnpm install"),
            outcome: StepOutcome::Ok,
            output: Arc::from(output.as_bytes()),
            elapsed: Duration::from_millis(1),
            elision: Some(CaptureElision {
                dropped_lines,
                kept_head_lines: kept_head,
            }),
            shell: false,
            interactive: false,
        }
    }

    /// The pane's own content lines for a row whose last Action elided output, under `set`.
    fn elided_step_content_lines(
        set: &'static GlyphSet,
        dropped_lines: usize,
        kept_head: usize,
        kept_tail: usize,
    ) -> Vec<String> {
        let mut row = entity("a");
        row.last_action = Some(action_receipt(
            "reinstall",
            vec![elided_step(dropped_lines, kept_head, kept_tail)],
            None,
        ));
        content_lines(&row, WIDE, set)
    }

    /// The one line of a bounded step's rendering that stands in for the drop.
    fn rendered_elision_row(lines: &[String], label: &str) -> String {
        lines[rendered_elision_index(lines, label)]
            .trim()
            .to_string()
    }

    /// Where that line sits among `lines`, which is the half of the claim
    /// [`rendered_elision_row`] throws away.
    fn rendered_elision_index(lines: &[String], label: &str) -> usize {
        let matches: Vec<usize> = lines
            .iter()
            .enumerate()
            .filter(|(_, line)| line.contains("lines elided"))
            .map(|(index, _)| index)
            .collect();
        let [index] = matches.as_slice() else {
            panic!("expected exactly one elision row under {label}, got {matches:?}");
        };
        *index
    }

    /// The head half of the capture bound, read out of `docs/spec/actions.md` at test time
    /// rather than restated here, so a fixture standing in for a real capture carries the
    /// number the core actually reports.
    fn spec_capture_head_lines() -> usize {
        let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
        let spec = std::fs::read_to_string(manifest_dir.join("../../docs/spec/actions.md"))
            .expect("read the actions specification");
        spec.split("Capture is bounded to the head ")
            .nth(1)
            .expect("actions.md states the capture bound")
            .split(' ')
            .next()
            .expect("a head line count")
            .parse()
            .expect("actions.md's head bound is a whole number of lines")
    }

    /// The `capture elision` row of `docs/spec/theming.md`'s own two-set glyph table, read
    /// at test time: `(full, ascii)`. The design of record names the marks; restating them
    /// here would let the code and the spec drift apart with both tests still green.
    fn spec_capture_elision_marks() -> (String, String) {
        let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
        let spec = std::fs::read_to_string(manifest_dir.join("../../docs/spec/theming.md"))
            .expect("read the theming specification");
        let rows: Vec<Vec<String>> = spec
            .lines()
            .map(str::trim)
            .filter(|line| line.starts_with('|'))
            .map(|line| {
                line.trim_matches('|')
                    .split('|')
                    .map(|cell| cell.trim().trim_matches('`').to_string())
                    .collect()
            })
            .filter(|cells: &Vec<String>| {
                cells
                    .first()
                    .is_some_and(|first| first == "capture elision")
            })
            .collect();
        let [row] = rows.as_slice() else {
            panic!(
                "expected exactly one `capture elision` row in theming.md's glyph table, got {rows:?}"
            );
        };
        let [_, full, ascii] = row.as_slice() else {
            panic!("theming.md's `capture elision` row does not have exactly three cells: {row:?}");
        };
        (full.clone(), ascii.clone())
    }

    /// The criterion itself, both halves of it: the mark on screen travels from the live
    /// glyph set through [`content_lines`], the pane's own path, and it is the mark
    /// `docs/spec/theming.md`'s glyph table names for that set, so `glyphs = "ascii"`
    /// renders `...` and not merely something different from `full`'s.
    #[test]
    fn an_elided_steps_mark_is_the_one_theming_mds_glyph_table_names_for_the_live_set() {
        let (spec_full, spec_ascii) = spec_capture_elision_marks();
        assert_ne!(
            spec_full, spec_ascii,
            "theming.md's two sets must name different capture elision marks, or this test \
             cannot tell them apart"
        );

        for (label, set, mark) in [
            ("full", &crate::glyphs::FULL, &spec_full),
            ("ascii", &crate::glyphs::ASCII, &spec_ascii),
        ] {
            assert_eq!(
                rendered_elision_row(&elided_step_content_lines(set, 212, 3, 2), label),
                format!("{mark} 212 lines elided {mark}"),
                "the {label} set's elision row must be drawn with the mark theming.md's own \
                 glyph table gives it"
            );
        }
    }

    /// Where the mark sits: after exactly `kept_head_lines` of the kept output and directly
    /// before the kept tail, which is the only thing that can place it now that no line in
    /// the captured bytes says so. Built at the real capture's own scale, the head count
    /// `docs/spec/actions.md` fixes, because a fixture with one kept head line cannot tell
    /// the field apart from the literal `1`. The tail run is deliberately a different
    /// length: with equal runs, counting from the end lands on the same index as counting
    /// from the start, so a head-for-tail confusion would pass.
    #[test]
    fn an_elided_steps_mark_sits_after_exactly_the_kept_head_lines_it_names() {
        let kept_head = spec_capture_head_lines();
        let kept_tail = kept_head / 4 + 1;
        assert_ne!(
            kept_head, kept_tail,
            "the two kept runs must differ, or this test cannot tell an index counted from \
             the head apart from one counted from the tail"
        );
        let lines = elided_step_content_lines(&crate::glyphs::FULL, 100, kept_head, kept_tail);
        let position = |needle: &str| {
            lines
                .iter()
                .position(|line| line.trim() == needle)
                .unwrap_or_else(|| panic!("expected a line reading {needle:?}: {lines:?}"))
        };

        let elided = rendered_elision_index(&lines, "full");

        assert_eq!(
            elided,
            position("head 0") + kept_head,
            "the mark must sit {kept_head} kept lines after the first, not merely somewhere \
             between the head and the tail"
        );
        assert_eq!(lines[elided - 1].trim(), format!("head {}", kept_head - 1));
        assert_eq!(lines[elided + 1].trim(), "tail 0");
    }

    /// A bounded step whose kept lines carry the child's own bold, so the elision row's own
    /// styling is distinguishable from its neighbours'. Bold rather than a colour because
    /// `strip_colour_if_disabled` drops colour under `NO_COLOR` and leaves every other
    /// attribute alone, which a machine with that variable set would otherwise turn into a
    /// failure with nothing wrong.
    fn bold_elided_step(dropped_lines: usize, kept_head: usize, kept_tail: usize) -> StepResult {
        let mut output = String::new();
        for n in 0..kept_head {
            output.push_str(&format!("\u{1b}[1mhead {n}\u{1b}[0m\n"));
        }
        for n in 0..kept_tail {
            output.push_str(&format!("\u{1b}[1mtail {n}\u{1b}[0m\n"));
        }
        StepResult {
            label: Arc::from("pnpm install"),
            outcome: StepOutcome::Ok,
            output: Arc::from(output.as_bytes()),
            elapsed: Duration::from_millis(1),
            elision: Some(CaptureElision {
                dropped_lines,
                kept_head_lines: kept_head,
            }),
            shell: false,
            interactive: false,
        }
    }

    /// The pane's own rendered rows, styles and all, for a row whose last Action elided
    /// output written by a child that styled it: what [`elided_step_content_lines`]'s plain
    /// text throws away.
    fn bold_elided_step_rendered_rows(set: &'static GlyphSet) -> Vec<Vec<(String, Style)>> {
        let mut row = entity("a");
        row.last_action = Some(action_receipt(
            "reinstall",
            vec![bold_elided_step(212, 3, 2)],
            None,
        ));
        styled_content_lines(&row, WIDE, set)
            .into_iter()
            .filter_map(|line| match line {
                ContentLine::Styled(_) => None,
                ContentLine::Raw(runs) => Some(runs),
            })
            .collect()
    }

    /// `docs/spec/actions.md`'s "It renders unstyled": the row belongs to neither voice, so
    /// it takes no theme role and none of the child's own SGR either. The child's own rows
    /// are asserted bold in the same pass, so a rendering that styled nothing at all could
    /// not pass this by accident.
    #[test]
    fn an_elided_steps_mark_renders_unstyled_between_the_childs_own_styled_rows() {
        for (label, set) in [
            ("full", &crate::glyphs::FULL),
            ("ascii", &crate::glyphs::ASCII),
        ] {
            let rows = bold_elided_step_rendered_rows(set);
            let (elided, child): (Vec<_>, Vec<_>) = rows
                .iter()
                .partition(|runs| runs.iter().any(|(text, _)| text.contains("lines elided")));
            let [elided] = elided.as_slice() else {
                panic!("expected exactly one elision row under {label}, got {elided:?}");
            };

            for (text, style) in elided.iter() {
                assert_eq!(
                    *style,
                    Style::default(),
                    "the {label} set's elision row must render unstyled, but {text:?} carries \
                     {style:?}"
                );
            }
            assert!(
                child.iter().flat_map(|runs| runs.iter()).any(|(_, style)| {
                    style.add_modifier.contains(ratatui::style::Modifier::BOLD)
                }),
                "the child's own rows must reach the pane styled under {label}, or this test \
                 cannot tell an unstyled elision row from an unstyled pane"
            );
        }
    }

    /// A step whose own output prints the elision text must not be read as an elision: the
    /// receipt says whether output was dropped, and matching on the captured bytes is the
    /// hack this split exists to prevent.
    #[test]
    fn a_step_whose_own_output_prints_the_elision_text_is_not_treated_as_elided() {
        let mut row = entity("a");
        row.last_action = Some(action_receipt(
            "reinstall",
            vec![step_result(
                "echo",
                StepOutcome::Ok,
                "\u{b7}\u{b7}\u{b7} 212 lines elided \u{b7}\u{b7}\u{b7}\n".as_bytes(),
                Duration::from_millis(1),
            )],
            None,
        ));

        let lines = content_lines(&row, WIDE, &crate::glyphs::ASCII);

        let row = rendered_elision_row(&lines, "ascii");
        assert_eq!(
            row, "\u{b7}\u{b7}\u{b7} 212 lines elided \u{b7}\u{b7}\u{b7}",
            "a step's own output is a quotation of another program's screen and must reach \
             the pane unrewritten, even under the ascii table"
        );
    }

    /// The wording is `docs/spec/actions.md`'s, read at test time from the pane mock that
    /// fixes it rather than restated here, so a change to the mock's phrasing fails this
    /// test instead of leaving the code and the design of record quietly apart.
    #[test]
    fn the_full_tables_elision_row_matches_actions_mds_own_detail_pane_mock() {
        let manifest_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
        let spec = std::fs::read_to_string(manifest_dir.join("../../docs/spec/actions.md"))
            .expect("read the actions specification");
        let mock: Vec<String> = spec
            .lines()
            .filter(|line| line.contains("lines elided"))
            .map(|line| line.trim_matches(['│', ' ']).to_string())
            .collect();
        let [mock] = mock.as_slice() else {
            panic!("expected exactly one elision line in actions.md's own mocks, got {mock:?}");
        };

        let dropped: usize = mock
            .split_whitespace()
            .nth(1)
            .expect("the mock's dropped count")
            .parse()
            .expect("the mock's dropped count is a number");

        assert_eq!(
            rendered_elision_row(
                &elided_step_content_lines(&crate::glyphs::FULL, dropped, 3, 2),
                "full"
            ),
            *mock
        );
    }

    /// Every way a Rust source line can spell U+00B7: the literal character, and the
    /// `\u{...}` escape, whose grammar allows one to six hex digits in either case. The
    /// spellings are generated from that grammar rather than listed, because a scan that
    /// lists two of them stops checking under the third.
    fn elision_glyph_spellings() -> Vec<String> {
        let mut spellings = vec!["\u{b7}".to_string()];
        for leading_zeros in 0..=4 {
            let zeros = "0".repeat(leading_zeros);
            // Only `b` has a case; `7` and the zeros do not.
            for hex in ["b7", "B7"] {
                spellings.push(format!("u{{{zeros}{hex}}}"));
            }
        }
        spellings
    }

    /// The boundary claim, which is an absence and so a source scan is the honest form of:
    /// nothing in `repon-core` names the mark it used to hardcode, in any spelling
    /// [`elision_glyph_spellings`] enumerates. Comment lines are excluded by the shared
    /// helper, so a doc comment explaining the split is free to name the character.
    #[test]
    fn repon_core_names_no_elision_glyph() {
        let core_src = Path::new(env!("CARGO_MANIFEST_DIR")).join("../repon-core/src");
        for needle in elision_glyph_spellings() {
            let offending = crate::test_support::production_lines_under_containing(
                std::slice::from_ref(&core_src),
                &needle,
            );
            assert!(
                offending.is_empty(),
                "repon-core names {needle:?}, the mark the consumer's glyph set owns, at: \
                 {offending:?}"
            );
        }
    }

    /// The fifth claim: a captured line longer than the pane wraps rather than truncating,
    /// with no character lost. 300 characters against a 40-column area (36-column wrap width
    /// once the 4-column indent is subtracted) forces several wrapped rows, not a boundary
    /// that happens to land on a separator.
    #[test]
    fn captured_output_wraps_a_line_longer_than_the_pane_without_losing_any_character() {
        let long_line: String = (0..300)
            .map(|index| char::from(b'a' + (index % 26) as u8))
            .collect();
        let output = format!("{long_line}\n").into_bytes();
        let area_width = 40u16;
        let wrap_width = (interior_width(area_width) as usize) - CAPTURED_OUTPUT_INDENT.len();

        let wrapped =
            captured_output_lines(&output, None, interior_width(area_width), full_glyphs());

        assert!(
            wrapped.len() > 1,
            "a 300-character line at a {wrap_width}-column wrap width must wrap into more \
             than one row"
        );
        let mut reconstructed = String::new();
        for line in &wrapped {
            let ContentLine::Raw(runs) = line else {
                panic!("expected every captured-output row to be Raw, got {line:?}");
            };
            assert_eq!(
                runs[0].0, CAPTURED_OUTPUT_INDENT,
                "expected every row to open with the captured-output indent"
            );
            let row_text: String = runs[1..].iter().map(|(text, _)| text.as_str()).collect();
            assert!(
                row_text.chars().count() <= wrap_width,
                "expected row {row_text:?} to fit the {wrap_width}-column wrap width"
            );
            reconstructed.push_str(&row_text);
        }
        assert_eq!(
            reconstructed, long_line,
            "expected every character of the original line preserved across the wrap"
        );
    }

    // --- Criterion 6 (issue #177): a tab advances to the next 8-column stop, not a fixed
    // width, measured from the output line's own start ---

    /// The ticket's own risk analysis: a single tab looks the same under a correct
    /// implementation and a fixed-width one, since the first stop is the same either way.
    /// Two tabs at different starting columns, with the middle field long enough to cross a
    /// stop on its own, are needed to tell them apart: `"ab"` (column 2) takes 6 spaces to
    /// reach column 8, and `"cdefghijkl"` (10 characters, crossing the column-16 stop) takes
    /// 6 more to reach column 24, not the same width either time and not a multiple of the
    /// field's own length.
    #[test]
    fn a_tab_advances_to_the_next_eight_column_stop_not_a_fixed_width() {
        let output = b"ab\tcdefghijkl\tmn\n".to_vec();

        let lines = captured_output_lines(&output, None, interior_width(104), full_glyphs());

        assert_eq!(
            lines.len(),
            1,
            "expected the one output line to stay one rendered row"
        );
        let ContentLine::Raw(runs) = &lines[0] else {
            panic!("expected a Raw content line, got {:?}", lines[0]);
        };
        let text: String = runs.iter().map(|(text, _)| text.as_str()).collect();
        assert_eq!(
            text,
            format!("{CAPTURED_OUTPUT_INDENT}ab      cdefghijkl      mn"),
            "expected each tab to reach the next 8-column stop counted from the line's own \
             start, got {text:?}"
        );
    }

    /// Inserted tab spaces keep the style of the run the tab itself came from, not the run
    /// before or after it: colour brackets only the tab here (`a` and `b` are both default
    /// style, the tab alone is red), so a wrong implementation that copied a neighbouring
    /// run's style rather than the tab's own would still pass a test that coloured the whole
    /// line one colour.
    #[test]
    fn a_tabs_inserted_spaces_keep_the_style_of_the_run_the_tab_came_from() {
        use ratatui::style::Color;

        // `wrap_output_line`'s own colour stripping reads the same process-global flag the
        // colour-capability tests toggle; without this lock this test's own `Color::Red`
        // assertion below races them.
        let _guard = COLOUR_CAPABILITY_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        crossterm::style::force_color_output(true);

        let output = b"a\x1b[31m\t\x1b[0mb\n".to_vec();

        let lines = captured_output_lines(&output, None, interior_width(104), full_glyphs());

        let ContentLine::Raw(runs) = &lines[0] else {
            panic!("expected a Raw content line, got {:?}", lines[0]);
        };
        let (tab_run_text, tab_run_style) = runs[1..]
            .iter()
            .find(|(text, _)| text.chars().all(|ch| ch == ' ') && !text.is_empty())
            .expect("expected a run of spaces from the expanded tab");
        assert_eq!(
            tab_run_text.len(),
            7,
            "expected the tab (starting at column 1, after 'a') to reach column 8 with 7 \
             spaces, got {tab_run_text:?}"
        );
        assert_eq!(
            tab_run_style.fg,
            Some(Color::Red),
            "expected the tab's own inserted spaces to carry the tab's own colour"
        );
        for (text, style) in runs {
            if text == "a" || text == "b" {
                assert_ne!(
                    style.fg,
                    Some(Color::Red),
                    "expected the untouched letters either side of the tab to keep their own \
                     default style, not the tab's"
                );
            }
        }
    }

    /// Real pty bytes, captured once and committed here rather than typed by hand, per the
    /// ticket's own warning that a hand-written expected string risks writing exactly what
    /// the implementation under test produces: `ls` run under a pty sized 120x40 (the same
    /// width `repon-core`'s own `executor.rs` opens every step's pty at, `PTY_WIDTH`), over a
    /// fresh directory holding exactly the five files named below. Names were chosen so real
    /// `ls` crosses several tab stops at different starting columns, per the ticket's risk
    /// analysis that two short adjacent names alone would look aligned under both a correct
    /// and a fixed-width implementation. Captured with:
    ///
    /// ```text
    /// python3 -c "
    /// import pty, os, fcntl, termios, struct, tempfile
    /// d = tempfile.mkdtemp()
    /// for n in ['ab', 'abcdefghij', 'longlonglonglongname', 'mid1234', 'x']:
    ///     open(os.path.join(d, n), 'w').close()
    /// master, slave = pty.openpty()
    /// fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack('HHHH', 40, 120, 0, 0))
    /// pid = os.fork()
    /// if pid == 0:
    ///     os.setsid(); os.dup2(slave, 0); os.dup2(slave, 1); os.dup2(slave, 2)
    ///     os.chdir(d); os.execvp('ls', ['ls'])
    /// else:
    ///     os.close(slave)
    ///     data = b''
    ///     while True:
    ///         chunk = os.read(master, 4096)
    ///         if not chunk: break
    ///         data += chunk
    ///     os.waitpid(pid, 0)
    ///     print(repr(data))
    /// "
    /// ```
    ///
    /// run against macOS's own `/bin/ls`, `\r\n` line ending included exactly as captured.
    const REAL_LS_PTY_CAPTURE: &[u8] =
        b"ab\t\t\tabcdefghij\t\tlonglonglonglongname\tmid1234\t\t\tx\r\n";

    /// The ticket's other named criterion: real `ls` output under a pty renders with its
    /// columns aligned, checked by comparing where each name actually lands on screen rather
    /// than by string equality against a blob this test authored. A fixed number of spaces
    /// per tab (the ticket's own named wrong fix) cannot reproduce these positions: `"ab"`
    /// needs 22 spaces of padding to reach the next stop, `"abcdefghij"` needs 14,
    /// `"longlonglonglongname"` needs 4 and `"mid1234"` needs 17, so no single per-tab
    /// constant reaches column 24, 48, 72 and 96 all at once, though real `ls` happened to
    /// pick a uniform 24-column field width here, which is why the gap between each pair of
    /// names comes out equal even though the padding behind each one does not.
    #[test]
    fn real_ls_output_under_a_pty_keeps_its_columns_tab_stop_aligned() {
        use ratatui::{Terminal, backend::TestBackend};

        let mut row = entity("a");
        row.last_action = Some(action_receipt(
            "list",
            vec![step_result(
                "ls",
                StepOutcome::Ok,
                REAL_LS_PTY_CAPTURE,
                Duration::from_millis(1),
            )],
            None,
        ));
        let glyphs = full_glyphs();
        let detail = Detail::default();
        let backend = TestBackend::new(150, 20);
        let mut terminal = Terminal::new(backend).expect("create test terminal");

        terminal
            .draw(|frame| {
                detail.draw(frame, frame.area(), &row, glyphs, true, &theme::DEFAULT);
            })
            .expect("draw the frame");

        let buf = terminal.backend().buffer();
        let names = ["ab", "abcdefghij", "longlonglonglongname", "mid1234", "x"];
        let mut positions = Vec::new();
        let mut row_y = None;
        for name in names {
            let (x, y) = find_text(buf, buf.area, name).unwrap_or_else(|| {
                panic!("expected to find {name:?} rendered somewhere in the pane")
            });
            match row_y {
                Some(expected_y) => assert_eq!(
                    y, expected_y,
                    "expected every name on the same rendered row, {name:?} landed on a \
                     different one"
                ),
                None => row_y = Some(y),
            }
            positions.push(x);
        }
        let gaps: Vec<u16> = positions.windows(2).map(|pair| pair[1] - pair[0]).collect();
        assert_eq!(
            gaps,
            vec![24, 24, 24, 24],
            "expected each name's start column to match real tab-stop arithmetic, got \
             positions {positions:?}"
        );

        // No stray CR artifact from the pty's own carriage-return-plus-newline line ending:
        // nothing but blank cells follows "x" up to the pane's own right border, excluding
        // the border column itself.
        let last_x = positions.last().expect("at least one position") + 1;
        let border_x = buf.area.width - 1;
        let trailing: String = (last_x..border_x)
            .map(|x| buf[(x, row_y.expect("a row was found"))].symbol())
            .collect();
        assert_eq!(
            trailing.trim(),
            "",
            "expected nothing but blank cells after the last name, got {trailing:?}"
        );
    }

    // --- Criterion 7 (issue #177): a step whose output is elided says so on screen ---

    /// Whether the elision line actually reaches this pane at all, proven by really
    /// overrunning `repon-core`'s own head-plus-tail capture bound through a real Action
    /// rather than typing the words `docs/spec/actions.md`'s own mock shows: a step that
    /// echoes 3,000 lines is bound to exceed that bound however many lines it actually keeps,
    /// so this needs no restated number of its own to compare against. The rendered pane is
    /// dumped and searched by text, not by constructing the exact bytes
    /// `repon_core::executor`'s own (private) `elision_line` would produce, since restating
    /// that wording here is exactly the single-source-of-truth risk this project's own
    /// defect history warns about.
    #[test]
    fn a_step_whose_output_is_elided_says_so_on_screen() {
        use ratatui::{Terminal, backend::TestBackend};
        use repon_core::{ActionSpec, Core, CoreSpec, FetchSpec, SetSpec, Step};

        let dir = tempfile::tempdir().expect("temp dir");
        let root = dir.path().canonicalize().expect("canonicalize temp dir");
        let status = Command::new("git")
            .arg("init")
            .args(["--quiet", "--initial-branch", "main"])
            .arg(&root)
            .status()
            .expect("run git init");
        assert!(status.success());
        git(&root, &["commit", "--allow-empty", "-m", "first"]);

        let core = Core::start_discovered(CoreSpec {
            set: SetSpec {
                name: "test".to_string(),
                roots: vec![root.clone()],
                include: Vec::new(),
                exclude: Vec::new(),
            },
            overrides: Vec::new(),
            poll_interval: Duration::from_secs(3600),
            status_stale_after: Duration::from_secs(3600),
            generation_deadline: Duration::from_secs(3600),
            show_submodules: false,
            fetch: FetchSpec {
                enabled: false,
                interval: Duration::from_secs(3600),
                concurrency: 4,
            },
            auto_update: repon_core::AutoUpdateSpec { enabled: false },
        });
        let key = core.snapshot().entities[0].key.clone();

        let steps = vec![Step {
            argv: vec![
                "sh".to_string(),
                "-c".to_string(),
                "i=1; while [ \"$i\" -le 3000 ]; do echo \"line $i\"; i=$((i+1)); done".to_string(),
            ],
            shell: false,
            interactive: false,
            env: Vec::new(),
        }];
        let started = core.run_action(
            ActionSpec {
                label: Arc::from("flood"),
                name: None,
                steps,
                concurrency: 1,
                when: None,
            },
            std::slice::from_ref(&key),
        );
        assert!(started, "expected the flooding Action to start");
        wait_for("the flooding step to finish", || !core.action_running());

        let entity = core.snapshot().entities[0].clone();
        let glyphs = full_glyphs();
        let detail = Detail::default();
        let backend = TestBackend::new(120, 450);
        let mut terminal = Terminal::new(backend).expect("create test terminal");
        terminal
            .draw(|frame| {
                detail.draw(frame, frame.area(), &entity, glyphs, true, &theme::DEFAULT);
            })
            .expect("draw the frame");

        let buf = terminal.backend().buffer();
        let screen = dump_screen(buf, buf.area);
        let elision_line = screen
            .lines()
            .find(|line| line.contains("lines elided"))
            .unwrap_or_else(|| {
                panic!("expected an elision line somewhere on screen, got:\n{screen}")
            });
        let dropped_count: usize = elision_line
            .split_whitespace()
            .find_map(|word| word.parse::<usize>().ok())
            .unwrap_or_else(|| {
                panic!("expected a number naming the dropped count in {elision_line:?}")
            });
        assert!(
            dropped_count > 0 && dropped_count < 3_000,
            "expected a plausible dropped-line count between 0 and 3,000, got {dropped_count}"
        );
    }

    // --- Criterion 2: the child's own colour is parsed at render time, in this crate ---

    /// Captured colour reaches the rendered buffer as the child's own real colour: the raw
    /// bytes `\x1b[31mZEBRA\x1b[0m` render as an actual `Color::Red` cell, not the literal
    /// escape digits ratatui-core would otherwise leave on screen (ADR 0018's own measured
    /// defect, "`\x1b[1;31merror\x1b[0m[E0308]` renders as the literal `[1;31merror[0m[E0308]`").
    #[test]
    fn captured_output_colour_survives_into_the_rendered_buffer() {
        use ratatui::{Terminal, backend::TestBackend, style::Color};

        let _guard = COLOUR_CAPABILITY_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        crossterm::style::force_color_output(true);

        let mut row = entity("a");
        row.last_action = Some(action_receipt(
            "reinstall",
            vec![step_result(
                "pnpm install",
                StepOutcome::Ok,
                b"\x1b[31mZEBRA\x1b[0m",
                Duration::from_millis(1),
            )],
            None,
        ));
        let glyphs = full_glyphs();
        let detail = Detail::default();
        let backend = TestBackend::new(60, 20);
        let mut terminal = Terminal::new(backend).expect("create test terminal");

        terminal
            .draw(|frame| {
                detail.draw(frame, frame.area(), &row, glyphs, true, &theme::DEFAULT);
            })
            .expect("draw the frame");

        let buf = terminal.backend().buffer();
        let (x, y) = find_text(buf, buf.area, "ZEBRA")
            .expect("expected to find the captured word ZEBRA rendered somewhere in the pane");
        assert_eq!(
            buf[(x, y)].fg,
            Color::Red,
            "expected the captured word's own literal colour, not left uncoloured or lost"
        );
    }

    // --- Criterion 3: a global colour setting strips captured colour too ---

    /// The real test the ticket's own risk analysis demands, a pair rather than one
    /// monochrome render on its own: the very same captured bytes render with the child's
    /// own colour when colour is on, and with none when it is off, and the two renders show
    /// the identical text throughout, proving only the styling differs.
    #[test]
    fn captured_colour_renders_with_it_on_and_is_stripped_with_it_off_but_the_text_never_changes() {
        use ratatui::{Terminal, backend::TestBackend, style::Color};

        let _guard = COLOUR_CAPABILITY_LOCK
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);

        let mut row = entity("a");
        row.last_action = Some(action_receipt(
            "reinstall",
            vec![step_result(
                "pnpm install",
                StepOutcome::Ok,
                b"\x1b[31mZEBRA\x1b[0m plain",
                Duration::from_millis(1),
            )],
            None,
        ));
        let glyphs = full_glyphs();
        let detail = Detail::default();

        let render = || {
            let backend = TestBackend::new(60, 20);
            let mut terminal = Terminal::new(backend).expect("create test terminal");
            terminal
                .draw(|frame| {
                    detail.draw(frame, frame.area(), &row, glyphs, true, &theme::DEFAULT);
                })
                .expect("draw the frame");
            terminal.backend().buffer().clone()
        };

        crossterm::style::force_color_output(true);
        let coloured = render();
        crossterm::style::force_color_output(false);
        let monochrome = render();
        // Restored before any assertion can panic and skip past it: a later test in this
        // module must never inherit colour disabled from this one.
        crossterm::style::force_color_output(true);

        let area = coloured.area;
        assert_eq!(area, monochrome.area);
        for y in area.top()..area.bottom() {
            for x in area.left()..area.right() {
                assert_eq!(
                    coloured[(x, y)].symbol(),
                    monochrome[(x, y)].symbol(),
                    "expected identical text at ({x}, {y}) regardless of colour capability"
                );
            }
        }

        let (x, y) = find_text(&coloured, area, "ZEBRA")
            .expect("expected to find the captured word ZEBRA rendered somewhere in the pane");
        assert_eq!(
            coloured[(x, y)].fg,
            Color::Red,
            "expected the captured word's own colour with colour on"
        );
        assert_ne!(
            monochrome[(x, y)].fg,
            Color::Red,
            "expected the captured word's own colour stripped with colour off"
        );
    }

    /// Finds the top-left cell of the first occurrence of `text`, read left to right, top to
    /// bottom, over every position `area` covers: what a test that does not know (or does not
    /// want to hard-code) the exact row a line of dynamic content lands on needs instead.
    fn find_text(buf: &Buffer, area: Rect, text: &str) -> Option<(u16, u16)> {
        let needle: Vec<char> = text.chars().collect();
        for y in area.top()..area.bottom() {
            for x in area.left()..area.right() {
                if x + needle.len() as u16 > area.right() {
                    continue;
                }
                let found = needle
                    .iter()
                    .enumerate()
                    .all(|(offset, ch)| buf[(x + offset as u16, y)].symbol() == ch.to_string());
                if found {
                    return Some((x, y));
                }
            }
        }
        None
    }

    /// Renders `buf`'s own cells back to plain text, one line per row, trailing blanks
    /// trimmed: the actual evidence a test that only asserts never produces, kept separate
    /// from [`find_text`] so a caller wanting the whole rendered screen for a report does not
    /// have to reassemble it by hand.
    fn dump_screen(buf: &Buffer, area: Rect) -> String {
        let mut screen = String::new();
        for y in area.top()..area.bottom() {
            let mut row = String::new();
            for x in area.left()..area.right() {
                row.push_str(buf[(x, y)].symbol());
            }
            screen.push_str(row.trim_end());
            screen.push('\n');
        }
        screen
    }
}