codewhale-tui 0.9.8

Terminal UI for open-source and open-weight coding models
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
use std::collections::HashSet;
use std::fmt::Write as _;
use std::path::{Component, Path};
use std::time::Instant;

use ratatui::layout::Rect;

use crate::settings::InlineDiffMode;
use crate::tools::canonical_action::canonical_action_alias;
use crate::tools::subagent::{AgentWorkerStatus, SubAgentResult, SubAgentStatus};
use crate::tui::app::{AgentCurrentActivityStatus, AgentProgressMeta, App, SidebarRowAction};
use crate::tui::history::{
    FileActivityKind, FileActivitySummary, FileMutationReceipt, HistoryCell, ToolCell,
};
use crate::tui::menu_style::{StatusKind, status_mark};
use crate::work_graph::{
    AcceptanceRequirement, EdgeKind, EvidenceKind, EvidenceKindTag, NodeKind, NodeState,
    OperationBinding, OwnerState, Provenance, WorkGraphSnapshot, WorkNode,
};

/// Persisted Ocean work-surface placement. Bottom is deliberately absent: the
/// composer and phase footer own the shell's lower edge. `Off` hides the rail
/// outright (rail unification, 0.9.4).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum WorkSurfacePlacement {
    #[default]
    Top,
    Left,
    Right,
    Off,
}

/// Which panel the rail shows. Orthogonal to placement: the user picks
/// *where* the rail sits and *what* it shows (rail unification, 0.9.4).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum RailPanel {
    /// Tasks / to-do / workers — the live work projection rendered through
    /// the row/hitbox machinery in `render.rs`.
    #[default]
    Tasks,
    /// Sub-agents, ported from the legacy sidebar's Agents panel.
    Agents,
    /// Workspace / token / cost context, ported from the Context panel.
    Context,
    /// Pinned work summary (goal + checklist), ported from the Pinned panel.
    Pinned,
}

impl RailPanel {
    #[must_use]
    pub fn parse(value: &str) -> Self {
        match value.trim().to_ascii_lowercase().as_str() {
            "agents" => Self::Agents,
            "context" => Self::Context,
            "pinned" => Self::Pinned,
            _ => Self::Tasks,
        }
    }

    #[must_use]
    pub const fn as_setting(self) -> &'static str {
        match self {
            Self::Tasks => "tasks",
            Self::Agents => "agents",
            Self::Context => "context",
            Self::Pinned => "pinned",
        }
    }

    #[must_use]
    pub const fn title(self) -> &'static str {
        match self {
            Self::Tasks => "Tasks",
            Self::Agents => "Agents",
            Self::Context => "Context",
            Self::Pinned => "Pinned",
        }
    }
}

impl WorkSurfacePlacement {
    #[must_use]
    pub fn parse(value: &str) -> Self {
        match value.trim().to_ascii_lowercase().as_str() {
            "left" => Self::Left,
            "right" => Self::Right,
            "off" => Self::Off,
            _ => Self::Top,
        }
    }

    #[must_use]
    pub const fn as_setting(self) -> &'static str {
        match self {
            Self::Top => "top",
            Self::Left => "left",
            Self::Right => "right",
            Self::Off => "off",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct WorkRowId(pub String);

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum WorkTone {
    Heading,
    Live,
    Attention,
    Success,
    Muted,
}

#[derive(Debug, Clone)]
pub(super) struct WorkRow {
    pub id: WorkRowId,
    pub mark: &'static str,
    pub label: String,
    pub detail: String,
    pub tone: WorkTone,
    pub selectable: bool,
    pub primary_action: Option<SidebarRowAction>,
    /// Present only on sub-agent rows. Carries the fields the fleet row paints
    /// beyond `label`, so the renderer can drop them one at a time as the
    /// surface narrows instead of truncating one pre-joined string.
    pub agent: Option<AgentRowFacts>,
}

/// The parts of a sub-agent row that are laid out as their own columns.
///
/// `label` already carries the preferred identity column (nesting indent,
/// nickname when the agent has one, `(+N)` child count). This carries the
/// rest: the role-only spelling of that same column, what the agent is doing,
/// and the right-aligned receipt.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(super) struct AgentRowFacts {
    /// The identity column spelled with the fleet role instead of the
    /// nickname. Equal to `label` when the agent has no nickname. The
    /// renderer falls back to this when a nickname is too wide for the
    /// identity column — a name is shown whole or not at all.
    pub role_label: String,
    /// The status word (`running`, `completed`, `failed`, …) painted as its
    /// own column. The glyph carries the same fact for scanning; the word is
    /// what makes the row legible without memorizing glyph vocabulary
    /// (owner regression report, 2026-08-04).
    pub status: String,
    /// What the agent was sent to do.
    pub objective: String,
    /// Wall-clock seconds, frozen once the agent is observed terminal so a
    /// finished agent stops ticking. `None` when no duration is known.
    pub elapsed_secs: Option<u64>,
    /// Model from the child's frozen spawn route or a later effective-route
    /// usage envelope; never inferred from the parent session's model.
    pub model: Option<String>,
    /// Tokens used by the child. `None` means *genuinely unknown* —
    /// the row then renders no token figure rather than claiming zero.
    pub tokens: Option<u64>,
    /// Unsettled items on this child's to-do list. `None` when no list has
    /// been published; `Some(0)` means the list exists and is fully settled
    /// (the strip still hides a zero chip — see `agent_receipt`).
    pub todos_remaining: Option<u32>,
}

#[derive(Debug, Clone)]
pub(super) struct WorkHitbox {
    pub id: WorkRowId,
    pub row_y: u16,
}

#[derive(Debug, Clone)]
enum WorkSourceState {
    Error(String),
    Disconnected,
}

impl WorkSourceState {
    const fn label(&self) -> &'static str {
        match self {
            Self::Error(_) => "error",
            Self::Disconnected => "disconnected",
        }
    }

    fn detail(&self) -> &str {
        match self {
            Self::Error(error) => error,
            Self::Disconnected => "Work Graph runtime is not attached",
        }
    }
}

/// Live Work summary recent-only presentation lifetime (#4688).
pub(super) const RECENT_ONLY_TTL_MS: u64 = 4_000;
/// Settled file/search/write receipt lifetime in the live strip (#4690).
pub(super) const ACTIVITY_RECEIPT_TTL_MS: u64 = 3_000;
pub(super) const TOP_HEIGHT_MIN: u16 = 2;
pub(super) const TOP_HEIGHT_MAX: u16 = 16;
pub(super) const SIDE_WIDTH_MIN: u16 = 26;
pub(super) const SIDE_WIDTH_MAX: u16 = 80;

/// Which restored work rows belong to a prior session instance (#4416).
///
/// Decided once per session id and cached: this instance's own later
/// autosaves restamp the persisted record, and re-probing after that would
/// re-badge restored rows as live work.
#[derive(Debug, Clone)]
pub(crate) struct SessionInstanceScope {
    pub(super) session_id: String,
    pub(super) from_prior_instance: bool,
    /// Node ids present in the graph supplied at session restore time: the
    /// restored persisted rows, as opposed to work this instance creates
    /// afterwards.
    pub(super) restored_nodes: HashSet<String>,
}

#[derive(Debug, Clone)]
pub struct WorkSurfaceState {
    pub placement: WorkSurfacePlacement,
    pub(super) effective_placement: WorkSurfacePlacement,
    /// Panel selection — orthogonal to placement.
    pub panel: RailPanel,
    pub top_height: u16,
    pub side_width: u16,
    pub(super) resizing: bool,
    pub(super) divider_hovered: bool,
    pub(super) resize_anchor_column: u16,
    pub(super) resize_anchor_row: u16,
    pub(super) resize_anchor_size: u16,
    /// Focus owner axis — distinct from selection and detail-open.
    pub focused: bool,
    /// Keyboard/mouse selection highlight.
    pub selected: Option<WorkRowId>,
    /// Which row currently owns an open detail (pager / agent card).
    pub opened: Option<WorkRowId>,
    pub scroll_offset: usize,
    pub last_area: Option<Rect>,
    pub visible_rows: usize,
    pub total_rows: usize,
    pub(super) hovered: Option<WorkRowId>,
    pub(super) hitboxes: Vec<WorkHitbox>,
    pub(super) cached_graph: Option<WorkGraphSnapshot>,
    pub(super) latest_rows: Vec<WorkRow>,
    /// Full ranked catalog retained for inspector/history after live chrome expires.
    pub(super) catalog_rows: Vec<WorkRow>,
    /// Monotonic origin for presentation lifetimes (not wall-clock epoch).
    presentation_origin: Instant,
    /// Optional injected clock (ms since origin) for deterministic tests.
    presentation_now_ms: Option<u64>,
    /// When the projection last became recent-only (ms since origin).
    recent_only_since_ms: Option<u64>,
    /// Fingerprint of the recent-only set so a new completion can re-surface once.
    recent_only_fingerprint: u64,
    /// After TTL or user-turn, keep the live summary collapsed until new actionable work.
    recent_only_suppressed: bool,
    /// When the current activity receipt fingerprint first became live.
    activity_since_ms: Option<u64>,
    activity_fingerprint: u64,
    activity_suppressed: bool,
    /// Bumped on accepted user turns / newly started operations.
    user_turn_epoch: u64,
    last_handled_user_turn_epoch: u64,
    /// Elapsed wall-clock, in ms, captured the first frame each sub-agent was
    /// observed in a terminal state. The manager's `duration_ms` is
    /// `started_at.elapsed()` recomputed per snapshot, so it keeps growing
    /// after an agent finishes; latching the first terminal reading is what
    /// makes a completed row stop ticking.
    pub(super) frozen_agent_elapsed_ms: std::collections::HashMap<String, u64>,
    /// Session-instance ownership of the restored session record (#4416).
    pub(crate) session_instance: Option<SessionInstanceScope>,
    /// Test override for the sessions directory the ownership probe reads;
    /// production resolves the default location lazily.
    pub(crate) session_owner_probe_dir: Option<std::path::PathBuf>,
}

impl Default for WorkSurfaceState {
    fn default() -> Self {
        Self::with_placement(WorkSurfacePlacement::Top)
    }
}

impl WorkSurfaceState {
    #[must_use]
    pub(crate) fn is_resizing(&self) -> bool {
        self.resizing
    }

    /// The placement actually rendered this frame (after the narrow-terminal
    /// fallback), for truthful status readouts.
    #[must_use]
    pub fn effective_placement(&self) -> WorkSurfacePlacement {
        self.effective_placement
    }

    #[must_use]
    pub fn with_placement(placement: WorkSurfacePlacement) -> Self {
        Self::with_layout(placement, 3, 30)
    }

    #[must_use]
    pub fn with_layout(placement: WorkSurfacePlacement, top_height: u16, side_width: u16) -> Self {
        Self {
            placement,
            effective_placement: placement,
            panel: RailPanel::default(),
            top_height: top_height.clamp(TOP_HEIGHT_MIN, TOP_HEIGHT_MAX),
            side_width: side_width.clamp(SIDE_WIDTH_MIN, SIDE_WIDTH_MAX),
            resizing: false,
            divider_hovered: false,
            resize_anchor_column: 0,
            resize_anchor_row: 0,
            resize_anchor_size: 0,
            focused: false,
            selected: None,
            opened: None,
            scroll_offset: 0,
            last_area: None,
            visible_rows: 0,
            total_rows: 0,
            hovered: None,
            hitboxes: Vec::new(),
            cached_graph: None,
            latest_rows: Vec::new(),
            catalog_rows: Vec::new(),
            presentation_origin: Instant::now(),
            presentation_now_ms: None,
            recent_only_since_ms: None,
            recent_only_fingerprint: 0,
            recent_only_suppressed: false,
            activity_since_ms: None,
            activity_fingerprint: 0,
            activity_suppressed: false,
            user_turn_epoch: 0,
            last_handled_user_turn_epoch: 0,
            frozen_agent_elapsed_ms: std::collections::HashMap::new(),
            session_instance: None,
            session_owner_probe_dir: None,
        }
    }

    /// Inject a monotonic clock for presentation-lifetime tests.
    #[cfg(test)]
    pub(super) fn set_presentation_now_ms(&mut self, now_ms: u64) {
        self.presentation_now_ms = Some(now_ms);
    }

    /// Signal that the user accepted a turn or a new operation started.
    /// Recent-only live chrome collapses immediately (#4688).
    pub fn note_user_turn_or_new_operation(&mut self) {
        self.user_turn_epoch = self.user_turn_epoch.wrapping_add(1);
    }

    /// Record the exact graph restored from persisted session state. This
    /// must happen at the restore boundary: the first later runtime capture
    /// may already contain work created by this process.
    pub(crate) fn record_restored_session(
        &mut self,
        session_id: &str,
        graph: Option<&WorkGraphSnapshot>,
    ) {
        let from_prior_instance = session_record_from_prior_instance(self, session_id);
        let restored_nodes = if from_prior_instance {
            graph
                .into_iter()
                .flat_map(|graph| graph.nodes.iter())
                .map(|node| node.id.as_str().to_string())
                .collect()
        } else {
            HashSet::new()
        };
        self.session_instance = Some(SessionInstanceScope {
            session_id: session_id.to_string(),
            from_prior_instance,
            restored_nodes,
        });
    }

    /// A restored graph row owned by a prior session instance whose terminal
    /// failure or staleness must not render as this session's live work
    /// (#4416). Plan steps stay: the resumed to-do list is the point of
    /// restoring; failed/stale operations and blockers are the leak.
    pub(super) fn is_prior_instance_residue(&self, node: &WorkNode) -> bool {
        let Some(scope) = self.session_instance.as_ref() else {
            return false;
        };
        scope.from_prior_instance
            && scope.restored_nodes.contains(node.id.as_str())
            && node.kind != NodeKind::PlanStep
            && matches!(node.state, NodeState::Failed | NodeState::Stale)
    }

    fn now_ms(&self) -> u64 {
        self.presentation_now_ms.unwrap_or_else(|| {
            u64::try_from(self.presentation_origin.elapsed().as_millis()).unwrap_or(u64::MAX)
        })
    }

    pub(super) fn selected_index(&self, rows: &[WorkRow]) -> Option<usize> {
        self.selected
            .as_ref()
            .and_then(|selected| rows.iter().position(|row| &row.id == selected))
    }

    /// Keep row identity and the viewport offset valid without moving the
    /// viewport to the remembered keyboard selection. Mouse-wheel scrolling
    /// is allowed to leave that selection off-screen until keyboard
    /// navigation resumes.
    pub(super) fn clamp_viewport(&mut self, rows: &[WorkRow]) {
        let selectable = rows.iter().filter(|row| row.selectable).collect::<Vec<_>>();
        if selectable.is_empty() {
            self.selected = None;
            self.focused = false;
            self.scroll_offset = 0;
            return;
        }
        let established_selection = selectable
            .iter()
            .any(|row| Some(&row.id) == self.selected.as_ref());
        if !established_selection {
            let preferred = selectable
                .iter()
                .find(|row| row.tone == WorkTone::Attention)
                .or_else(|| selectable.iter().find(|row| row.tone == WorkTone::Live))
                .copied()
                .unwrap_or(selectable[0]);
            self.selected = Some(preferred.id.clone());
            // Establishing a new selection should reveal the current or
            // needs-input item without reordering the canonical list. Later
            // redraws keep mouse-wheel ownership and do not chase selection.
            if let Some(selected) = rows.iter().position(|row| row.id == preferred.id) {
                if selected < self.scroll_offset {
                    self.scroll_offset = selected;
                } else if self.visible_rows > 0
                    && selected >= self.scroll_offset.saturating_add(self.visible_rows)
                {
                    self.scroll_offset = selected.saturating_add(1) - self.visible_rows;
                }
            }
        }
        self.scroll_offset = self
            .scroll_offset
            .min(rows.len().saturating_sub(self.visible_rows.max(1)));
    }

    /// Reveal the remembered selection after keyboard navigation. Rendering
    /// alone must use `clamp_viewport`; otherwise every redraw undoes a mouse
    /// wheel offset when the selection is above the viewport.
    pub(super) fn clamp_selection(&mut self, rows: &[WorkRow]) {
        self.clamp_viewport(rows);
        let Some(selected) = self.selected_index(rows) else {
            return;
        };
        if selected < self.scroll_offset {
            self.scroll_offset = selected;
        } else if self.visible_rows > 0
            && selected >= self.scroll_offset.saturating_add(self.visible_rows)
        {
            self.scroll_offset = selected.saturating_add(1).saturating_sub(self.visible_rows);
        }
        self.scroll_offset = self
            .scroll_offset
            .min(rows.len().saturating_sub(self.visible_rows.max(1)));
    }
}

pub(super) fn project(app: &mut App) -> Vec<WorkRow> {
    let active_session = app.current_session_id.is_some();
    freeze_terminal_agent_elapsed(app);
    let agents = agent_rows(app);
    let coordination = coordination_row(app);
    let activity = settled_file_activity(app);
    let capture = app.runtime_services.work.as_ref().map(|work| {
        work.try_capture(app.current_session_id.as_deref())
            .map(|snapshot| snapshot.map(|snapshot| snapshot.graph))
    });

    let (graph, source_state) = match capture {
        Some(Ok(Some(graph))) => {
            app.work_surface.cached_graph = Some(graph.clone());
            (Some(graph), None)
        }
        Some(Ok(None)) => {
            app.work_surface.cached_graph = None;
            (None, None)
        }
        Some(Err(error)) => (
            app.work_surface.cached_graph.clone(),
            active_session.then_some(WorkSourceState::Error(error)),
        ),
        None => (
            app.work_surface.cached_graph.clone(),
            active_session.then_some(WorkSourceState::Disconnected),
        ),
    };

    update_session_instance_scope(app);

    let rows = match graph {
        Some(graph) => graph_rows(
            &mut app.work_surface,
            &graph,
            source_state.as_ref(),
            agents,
            coordination,
            activity,
        ),
        None if !agents.is_empty() || coordination.is_some() || !activity.is_empty() => {
            ordered_rows(
                &mut app.work_surface,
                None,
                source_state.as_ref(),
                agents,
                coordination,
                activity,
            )
        }
        None => source_state.map_or_else(Vec::new, |state| {
            vec![section_heading(
                "work",
                &format!("Work · {}", state.label()),
                state.detail(),
            )]
        }),
    };
    app.work_surface.latest_rows = rows.clone();
    if let Some(opened) = app.work_surface.opened.as_ref()
        && !rows.iter().any(|row| &row.id == opened)
        && !app
            .work_surface
            .catalog_rows
            .iter()
            .any(|row| &row.id == opened)
    {
        app.work_surface.opened = None;
    }
    rows
}

/// Projection used by the live surface. The full Work catalog remains intact
/// for explicit inspectors, while persistent chrome stays literal: current
/// sub-agents, then plan-step to-dos. Tool operations, coordination receipts,
/// file activity, and generic graph headings never enter this list.
///
/// On Top, the strip is actionable work only: running / queued / needs-input
/// agents, plus plan-step to-dos. Quietly completed or cancelled workers
/// collapse out of the strip into the group header count (e.g.
/// `▾ Subagents 2 running · Archived 6`) so fan-outs do not permanently eat
/// the transcript. Settled agents stay reachable through the Agents panel and
/// the work catalog — never deleted. Failed / interrupted workers stay in the
/// strip because they still need attention.
///
/// **The sub-agent group outranks the to-do list for strip rows.** The strip
/// is a fixed-height viewport over this list (`top_height`, 2..=16 rows) and
/// paints from the top, so whatever is ordered last is what falls off the
/// bottom behind `↓ N more`. Putting the to-dos first meant a session that
/// already had a checklist spent every row it had on to-dos and a running
/// sub-agent never appeared in the top bar at all — the 2026-08-04 owner
/// report, pinned by `tests/work_bar_subagents_pty.rs`. The workers are the
/// side that must not fall off: the to-do list keeps a pinned receipt
/// (`To-do · 3/8 · 5 left`) that survives its rows scrolling away, and a
/// sub-agent row has no such summary — it is the only place a running worker
/// is inspectable from the bar. Sub-agent rows are also the bounded set
/// (`max_concurrent` plus a capped terminal-card retention) while a to-do
/// list is unbounded, so seating the bounded set first is what keeps both
/// visible in the common case.
pub(super) fn project_visible(app: &mut App) -> Vec<WorkRow> {
    let rows = project(app);
    if app.work_surface.effective_placement != WorkSurfacePlacement::Top {
        return rows;
    }

    let todo_ids = plan_step_row_ids(app);
    let mut todos = Vec::new();
    let mut live_agents = Vec::new();
    let mut settled_agents = 0usize;
    for row in rows {
        if todo_ids.contains(&row.id.0) {
            todos.push(row);
        } else if row.id.0.starts_with("worker:") {
            if agent_row_is_strip_settled(&row) {
                settled_agents += 1;
            } else {
                live_agents.push(row);
            }
        }
    }

    let mut out = Vec::with_capacity(todos.len() + live_agents.len() + 1);
    if !live_agents.is_empty() || settled_agents > 0 {
        // Honest live/settled split — failed/interrupted stay as strip rows
        // (needs attention) and are never counted as "running".
        let attention = live_agents
            .iter()
            .filter(|row| agent_row_needs_attention(row))
            .count();
        let running = live_agents.len().saturating_sub(attention);
        let header = match (running, attention, settled_agents) {
            (0, 0, settled) => format!("Subagents · Archived {settled}"),
            (live, 0, 0) => format!("Subagents {live}"),
            (live, 0, settled) => format!("Subagents {live} running · Archived {settled}"),
            (0, blocked, 0) => format!("Subagents {blocked} needs input"),
            (0, blocked, settled) => {
                format!("Subagents {blocked} needs input · Archived {settled}")
            }
            (live, blocked, 0) => format!("Subagents {live} running · {blocked} needs input"),
            (live, blocked, settled) => {
                format!("Subagents {live} running · {blocked} needs input · Archived {settled}")
            }
        };
        out.push(agents_section_heading(&header));
        out.extend(live_agents);
    }
    out.extend(todos);
    app.work_surface.latest_rows = out.clone();
    out
}

/// Completed/cancelled workers leave the Top strip; failed/interrupted stay
/// because they still need attention. Paths to receipts remain via Agents.
fn agent_row_is_strip_settled(row: &WorkRow) -> bool {
    row.agent
        .as_ref()
        .is_some_and(|facts| matches!(facts.status.as_str(), "completed" | "cancelled"))
}

fn agent_row_needs_attention(row: &WorkRow) -> bool {
    row.agent.as_ref().is_some_and(|facts| {
        matches!(
            facts.status.as_str(),
            "failed" | "interrupted" | "needs_input" | "blocked"
        )
    })
}

/// Row ids of the plan-step (to-do) nodes in the cached graph.
fn plan_step_row_ids(app: &App) -> HashSet<String> {
    app.work_surface
        .cached_graph
        .as_ref()
        .map(|snapshot| {
            snapshot
                .nodes
                .iter()
                .filter(|node| node.kind == NodeKind::PlanStep)
                .map(|node| format!("graph:{}", node.id.as_str()))
                .collect::<HashSet<_>>()
        })
        .unwrap_or_default()
}

/// Rows for the selected rail panel, routed through the same row/hitbox
/// machinery regardless of panel: every work row a user can see is a door
/// (`crates/tui/AGENTS.md`, "rows are objects"), whichever panel it appears
/// in.
///
/// - `Tasks` — the full live projection ([`project_visible`]).
/// - `Agents` — the full sub-agent register under the `▾ Subagents N` header,
///   followed by the durable to-do checklist: opening the register never hides
///   the list.
/// - `Pinned` — the goal, the sub-agent group, then the plan-step to-dos.
/// - `Context` — empty: session facts are a line list, not work rows, and
///   render outside the row machinery.
///
/// **No panel choice may hide a running sub-agent.** `Pinned` used to filter
/// the projection down to plan steps, which meant the owner's own
/// `rail_panel = "pinned"` made a live worker unreachable: with no to-dos and
/// no goal the projection was empty, the strip collapsed to zero rows, and
/// the top bar was header chrome only — the 2026-08-04 "I spawned a sub agent
/// and the top bar showed nothing" report, pinned by
/// `tests/work_bar_subagents_pty.rs`. There is no header chip or phase-strip
/// fallback for sub-agents, so this strip is the *only* persistent surface
/// they have; a panel preference about which durable work to foreground is
/// not consent to lose the running fleet. Sub-agent rows are durable in the
/// same sense the panel's name means (they survive completion — see the row
/// lifetime rule in the module docs), so they belong here on their own terms.
pub(super) fn visible_rows_for_panel(app: &mut App) -> Vec<WorkRow> {
    match app.work_surface.panel {
        RailPanel::Tasks => project_visible(app),
        RailPanel::Agents => {
            let rows = project(app);
            let todo_ids = plan_step_row_ids(app);
            let mut agents = Vec::new();
            let mut todos = Vec::new();
            for row in rows {
                if row.id.0.starts_with("worker:") {
                    agents.push(row);
                } else if todo_ids.contains(&row.id.0) {
                    todos.push(row);
                }
            }
            let mut out = Vec::with_capacity(agents.len() + todos.len() + 2);
            if !agents.is_empty() {
                out.push(agents_section_heading(&format!(
                    "Subagents {}",
                    agents.len()
                )));
                out.extend(agents);
            }
            if !todos.is_empty() {
                out.push(section_heading("tasks", "Tasks", "Durable to-do checklist"));
                out.extend(todos);
            }
            app.work_surface.latest_rows = out.clone();
            out
        }
        RailPanel::Pinned => {
            let rows = project(app);
            let todo_ids = plan_step_row_ids(app);
            let mut todos = Vec::new();
            let mut agents = Vec::new();
            for row in rows {
                if todo_ids.contains(&row.id.0) {
                    todos.push(row);
                } else if row.id.0.starts_with("worker:") {
                    agents.push(row);
                }
            }
            let mut out = Vec::with_capacity(todos.len() + agents.len() + 2);
            // On Top the goal is already the strip title; a side column
            // repeats it as its first row so the durable goal home survives
            // in every placement.
            if app.work_surface.effective_placement != WorkSurfacePlacement::Top
                && let Some((objective, paused)) =
                    crate::tui::footer_ui::active_goal_chip_state(app)
            {
                let flat = objective.trim().replace(['\n', '\r'], " ");
                if !flat.is_empty() {
                    let label = if paused {
                        format!("Goal (paused): {flat}")
                    } else {
                        format!("Goal: {flat}")
                    };
                    out.push(section_heading("goal", &label, ""));
                }
            }
            // Same priority rule as Tasks: the bounded, summary-less set is
            // seated before the unbounded to-do list that keeps a pinned
            // receipt. See [`project_visible`].
            if !agents.is_empty() {
                out.push(agents_section_heading(&format!(
                    "Subagents {}",
                    agents.len()
                )));
                out.extend(agents);
            }
            out.extend(todos);
            app.work_surface.latest_rows = out.clone();
            out
        }
        RailPanel::Context => Vec::new(),
    }
}

/// Classify the current session against this process's session-instance
/// boot id (#4416), mirroring the `SubAgentManager` prior-session pattern
/// (#405). The probe runs once per session id. Persisted row identity is
/// recorded separately at the actual session restore boundary.
fn update_session_instance_scope(app: &mut App) {
    let Some(session_id) = app.current_session_id.clone() else {
        app.work_surface.session_instance = None;
        return;
    };
    let classified = app
        .work_surface
        .session_instance
        .as_ref()
        .is_some_and(|scope| scope.session_id == session_id);
    if !classified {
        let from_prior_instance =
            session_record_from_prior_instance(&app.work_surface, &session_id);
        app.work_surface.session_instance = Some(SessionInstanceScope {
            session_id,
            from_prior_instance,
            restored_nodes: HashSet::new(),
        });
    }
}

fn session_record_from_prior_instance(surface: &WorkSurfaceState, session_id: &str) -> bool {
    let manager = match surface.session_owner_probe_dir.as_ref() {
        Some(dir) => crate::session_manager::SessionManager::new(dir.clone()),
        None => crate::session_manager::SessionManager::default_location(),
    };
    manager.is_ok_and(|manager| manager.session_from_prior_instance(session_id))
}

fn graph_rows(
    surface: &mut WorkSurfaceState,
    snapshot: &WorkGraphSnapshot,
    source_state: Option<&WorkSourceState>,
    agents: Vec<RankedWorkRow>,
    coordination: Option<RankedWorkRow>,
    activity: SettledFileActivity,
) -> Vec<WorkRow> {
    ordered_rows(
        surface,
        Some(snapshot),
        source_state,
        agents,
        coordination,
        activity,
    )
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum WorkBucket {
    Active,
    Attention,
    Ready,
    Recent,
}

impl WorkBucket {
    /// Presentation priority: needs-input outranks running work (#4689).
    const fn rank(self) -> u8 {
        match self {
            Self::Attention => 0,
            Self::Active => 1,
            Self::Ready => 2,
            Self::Recent => 3,
        }
    }

    const fn is_actionable(self) -> bool {
        !matches!(self, Self::Recent)
    }
}

#[derive(Clone)]
struct RankedWorkRow {
    bucket: WorkBucket,
    order: usize,
    is_plan_step: bool,
    row: WorkRow,
}

#[derive(Default, Clone)]
struct SettledFileActivity {
    summary: FileActivitySummary,
    read: Vec<String>,
    list: Vec<String>,
    search: Vec<String>,
    write: Vec<String>,
    mutations: Vec<FileMutationReceipt>,
    inline_diff_mode: InlineDiffMode,
}

impl SettledFileActivity {
    fn is_empty(&self) -> bool {
        self.summary.is_empty()
    }
}

fn ordered_rows(
    surface: &mut WorkSurfaceState,
    snapshot: Option<&WorkGraphSnapshot>,
    source_state: Option<&WorkSourceState>,
    mut ranked: Vec<RankedWorkRow>,
    coordination: Option<RankedWorkRow>,
    activity: SettledFileActivity,
) -> Vec<WorkRow> {
    ranked.extend(coordination);
    if let Some(snapshot) = snapshot {
        ranked.extend(
            snapshot
                .nodes
                .iter()
                .filter(|node| {
                    matches!(
                        node.kind,
                        NodeKind::PlanStep | NodeKind::Operation | NodeKind::Blocker
                    )
                })
                .filter(|node| !is_settled_transient_operation(node))
                .filter(|node| !surface.is_prior_instance_residue(node))
                .enumerate()
                .map(|(order, node)| RankedWorkRow {
                    bucket: node_bucket(node),
                    order: 10_000usize.saturating_add(order),
                    is_plan_step: node.kind == NodeKind::PlanStep,
                    row: graph_node_row(snapshot, node),
                }),
        );
    }

    // Activity is projected separately so we can apply a single aggregated
    // transient receipt instead of one live row per tool kind (#4690).
    let activity_row = aggregate_activity_row(&activity);
    if let Some(row) = activity_row.clone() {
        ranked.push(row);
    }

    ranked.sort_by(|a, b| match (a.is_plan_step, b.is_plan_step) {
        // To-do (plan step) rows keep canonical order: a completed step must
        // not sink below a later pending step and lose its identity. Agent and
        // operation rows still sort by status bucket (#4689).
        (true, true) => a.order.cmp(&b.order),
        (true, false) => std::cmp::Ordering::Less,
        (false, true) => std::cmp::Ordering::Greater,
        (false, false) => a
            .bucket
            .rank()
            .cmp(&b.bucket.rank())
            .then_with(|| a.order.cmp(&b.order)),
    });

    let active = ranked
        .iter()
        .filter(|item| item.bucket == WorkBucket::Active)
        .count();
    let attention = ranked
        .iter()
        .filter(|item| item.bucket == WorkBucket::Attention)
        .count();
    let ready = ranked
        .iter()
        .filter(|item| item.bucket == WorkBucket::Ready)
        .count();
    let recent = ranked
        .iter()
        .filter(|item| item.bucket == WorkBucket::Recent)
        .count();
    let actionable = attention + active + ready;
    let source = source_state
        .map(|state| format!(" · {}", state.label()))
        .unwrap_or_default();
    let detail = match (snapshot, source_state) {
        (Some(snapshot), Some(state)) => {
            format!("graph revision {} · {}", snapshot.revision, state.detail())
        }
        (Some(snapshot), None) => format!("graph revision {}", snapshot.revision),
        (None, Some(state)) => state.detail().to_string(),
        (None, None) => "Current session activity".to_string(),
    };

    let now = surface.now_ms();
    let user_turn_force_hide = surface.user_turn_epoch != surface.last_handled_user_turn_epoch;
    if user_turn_force_hide {
        surface.last_handled_user_turn_epoch = surface.user_turn_epoch;
        if actionable == 0 {
            surface.recent_only_suppressed = true;
        }
        surface.activity_suppressed = true;
    }

    // Recent-only lifecycle (#4688): show a brief completion, then collapse.
    let recent_fp = fingerprint_rows(
        ranked
            .iter()
            .filter(|item| item.bucket == WorkBucket::Recent)
            .map(|item| item.row.id.0.as_str()),
    );
    if actionable > 0 {
        surface.recent_only_since_ms = None;
        surface.recent_only_suppressed = false;
        surface.recent_only_fingerprint = recent_fp;
    } else if recent > 0 {
        if surface.recent_only_fingerprint != recent_fp {
            // A new completion after expiry may surface once.
            surface.recent_only_fingerprint = recent_fp;
            surface.recent_only_since_ms = Some(now);
            surface.recent_only_suppressed = false;
        } else if surface.recent_only_since_ms.is_none() && !surface.recent_only_suppressed {
            surface.recent_only_since_ms = Some(now);
        }
        if let Some(since) = surface.recent_only_since_ms
            && now.saturating_sub(since) >= RECENT_ONLY_TTL_MS
        {
            surface.recent_only_suppressed = true;
        }
    } else {
        surface.recent_only_since_ms = None;
        surface.recent_only_suppressed = false;
        surface.recent_only_fingerprint = 0;
    }

    // Activity receipt lifetime (#4690): one aggregated row, 3s, no raw payloads.
    let activity_fp = activity_row
        .as_ref()
        .map(|row| fingerprint_rows(std::iter::once(row.row.label.as_str())))
        .unwrap_or(0);
    let show_activity = if activity_row.is_none() {
        surface.activity_since_ms = None;
        surface.activity_fingerprint = 0;
        surface.activity_suppressed = false;
        false
    } else {
        if surface.activity_fingerprint != activity_fp {
            surface.activity_fingerprint = activity_fp;
            surface.activity_since_ms = Some(now);
            surface.activity_suppressed = false;
        } else if surface.activity_since_ms.is_none() && !surface.activity_suppressed {
            surface.activity_since_ms = Some(now);
        }
        if let Some(since) = surface.activity_since_ms
            && now.saturating_sub(since) >= ACTIVITY_RECEIPT_TTL_MS
        {
            surface.activity_suppressed = true;
        }
        !surface.activity_suppressed
    };

    let subject = ranked
        .iter()
        .find(|item| item.bucket.is_actionable())
        .map(|item| (item.bucket, sanitize_summary_title(&item.row.label)));
    let heading_label = match (actionable > 0, subject.as_ref()) {
        (true, Some((WorkBucket::Attention, title))) => {
            format!("Work · Needs input: {title} · {attention} blocked{source}")
        }
        (true, Some((WorkBucket::Active, title))) => {
            format!("Work · Running: {title} · {active} active{source}")
        }
        (true, Some((WorkBucket::Ready, title))) => {
            format!("Work · Ready: {title} · {ready} ready{source}")
        }
        (true, _) => format!(
            "Work · {active} active · {attention} needs input · {ready} ready · {recent} recent{source}"
        ),
        (false, _) => format!(
            "Work · {active} active · {attention} needs input · {ready} ready · {recent} recent{source}"
        ),
    };

    // Full catalog for inspector/history even when live chrome collapses.
    let mut catalog = vec![section_heading("work", &heading_label, &detail)];
    catalog.extend(ranked.iter().map(|item| item.row.clone()));
    // Prior-instance terminal residue stays reachable through the explicit
    // catalog, labeled historical, but never as this session's live work
    // (#4416).
    if let Some(snapshot) = snapshot {
        catalog.extend(
            snapshot
                .nodes
                .iter()
                .filter(|node| surface.is_prior_instance_residue(node))
                .map(|node| {
                    let mut row = graph_node_row(snapshot, node);
                    row.detail = format!("prior session · {}", row.detail);
                    row.tone = WorkTone::Muted;
                    row
                }),
        );
    }
    surface.catalog_rows = catalog.clone();

    // Live chrome policy (Tasks/side projections — Top uses `project_visible`):
    // - actionable: heading + (optional) single activity receipt
    // - recent-only: transient receipts collapse after the TTL / next user
    //   turn (#4688); settled to-dos stay as durable rows. Settled sub-agents
    //   on Top collapse into the Subagents header (see `project_visible`) and
    //   remain reachable via the Agents panel / catalog.
    // - empty: no heading
    let is_durable =
        |item: &RankedWorkRow| item.is_plan_step || item.row.id.0.starts_with("worker:");
    let has_durable = ranked.iter().any(is_durable);
    if ranked.is_empty() && source_state.is_none() {
        return Vec::new();
    }
    if actionable == 0 && recent == 0 {
        // Source-only error/disconnected heading is still useful.
        return if source_state.is_some() {
            vec![section_heading("work", &heading_label, &detail)]
        } else {
            Vec::new()
        };
    }
    let suppress_transient_recent = actionable == 0 && surface.recent_only_suppressed;
    if suppress_transient_recent && !has_durable {
        return Vec::new();
    }

    // The live heading must count the rows the live list actually shows.
    // Once transient recent rows are suppressed, quoting the unfiltered
    // `recent` total would claim receipts the reader cannot see — the
    // catalog heading keeps the full count because the catalog keeps the
    // full rows.
    let live_heading = if suppress_transient_recent {
        let live_recent = ranked
            .iter()
            .filter(|item| item.bucket == WorkBucket::Recent && is_durable(item))
            .count();
        format!(
            "Work · {active} active · {attention} needs input · {ready} ready · {live_recent} recent{source}"
        )
    } else {
        heading_label.clone()
    };

    // Full ordered children remain in the projection for side rails, inspector
    // selection, and durable recent visibility. Live Top height is capped in
    // render (#4690). Recent-only *summary* lifetime is handled above (#4688).
    let mut live = vec![section_heading("work", &live_heading, &detail)];
    for item in ranked {
        if item.row.id.0 == "activity:aggregate" && !show_activity {
            continue;
        }
        if suppress_transient_recent && !is_durable(&item) {
            continue;
        }
        live.push(item.row);
    }
    live
}

fn fingerprint_rows<'a>(ids: impl Iterator<Item = &'a str>) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    for id in ids {
        id.hash(&mut hasher);
    }
    hasher.finish()
}

fn sanitize_summary_title(raw: &str) -> String {
    let single_line = raw
        .chars()
        .map(|ch| {
            if ch.is_control() || ch == '\n' || ch == '\r' || ch == '\t' {
                ' '
            } else {
                ch
            }
        })
        .collect::<String>();
    let collapsed = single_line.split_whitespace().collect::<Vec<_>>().join(" ");
    let trimmed = collapsed.trim();
    if trimmed.is_empty() {
        return "work item".to_string();
    }
    let mut chars = trimmed.chars();
    let prefix = chars.by_ref().take(72).collect::<String>();
    if chars.next().is_some() {
        format!("{prefix}")
    } else {
        prefix
    }
}

fn coordination_row(app: &App) -> Option<RankedWorkRow> {
    let projection = app.coordination_detail.as_ref()?;
    let has_context_receipt = projection.context_projections.iter().any(|receipt| {
        !receipt.decision_ids.is_empty()
            || receipt.projected_bytes > 0
            || receipt.deduplicated > 0
            || receipt.omitted > 0
    });
    let has_metrics = !projection.metrics.hottest_paths.is_empty()
        || projection.metrics.package_or_module_growth.is_some()
        || projection.metrics.route_or_cost.is_some();
    if projection.decisions.is_empty()
        && projection.write_claims.is_empty()
        && projection.reconciliations.is_empty()
        && projection.contentions.is_empty()
        && !has_context_receipt
        && !has_metrics
    {
        return None;
    }
    let attention = crate::tui::coordination_detail::needs_attention(projection);
    let bucket = if attention {
        WorkBucket::Attention
    } else {
        WorkBucket::Recent
    };
    let title = app
        .tr(crate::localization::MessageId::CoordinationWorkTitle)
        .into_owned();
    Some(RankedWorkRow {
        bucket,
        // Coordination is a session-wide receipt, before individual workers
        // within the same bucket but after live/attention priority sorting.
        order: 100,
        is_plan_step: false,
        row: WorkRow {
            id: WorkRowId("coordination".to_string()),
            mark: if attention {
                crate::tui::glyphs::ATTENTION
            } else {
                crate::tui::glyphs::DONE
            },
            label: title.clone(),
            detail: crate::tui::coordination_detail::summary(app.ui_locale, projection),
            tone: bucket_tone(bucket),
            selectable: true,
            primary_action: Some(SidebarRowAction::InspectWork {
                title,
                body: crate::tui::coordination_detail::format(app.ui_locale, projection),
                stop_action: None,
            }),
            agent: None,
        },
    })
}

fn node_bucket(node: &WorkNode) -> WorkBucket {
    match node.state {
        NodeState::Initializing | NodeState::Active => WorkBucket::Active,
        NodeState::Failed if is_transient_failed_operation(node) => WorkBucket::Recent,
        NodeState::Waiting | NodeState::Blocked | NodeState::Stale | NodeState::Failed => {
            WorkBucket::Attention
        }
        NodeState::Completed if !node.acceptance.is_empty() => WorkBucket::Attention,
        NodeState::Ready => WorkBucket::Ready,
        NodeState::Completed
        | NodeState::Verified
        | NodeState::Superseded
        | NodeState::Cancelled => WorkBucket::Recent,
    }
}

fn is_transient_failed_operation(node: &WorkNode) -> bool {
    node.kind == NodeKind::Operation
        && node
            .binding
            .as_ref()
            .is_some_and(|binding| !binding.durable)
        && node.acceptance.is_empty()
        && node.state == NodeState::Failed
}

/// One worker row before display ordering: the rendered row plus the parent
/// link and fleet identity the strip uses to number, order, and indent
/// nested spawns (#36).
struct AgentRowSeed {
    agent_id: String,
    parent_run_id: Option<String>,
    role: String,
    /// A real nickname or stable label, never the raw agent id (#36).
    name: Option<String>,
    ranked: RankedWorkRow,
}

/// Indent marker for a nested spawn: nothing at the top level (no permanent
/// chrome for the common flat fan-out), `↳` once nesting is actually
/// present, with two extra spaces per additional level (#36).
fn agent_nesting_indent(depth: usize) -> String {
    match depth {
        0 => String::new(),
        level => format!("{}", "  ".repeat(level.saturating_sub(1))),
    }
}

/// Compose the sub-agent identity column: nesting indent, who the agent is,
/// and `(+N)` when that agent has spawned children of its own.
///
/// `who` is the agent's nickname when it has one and its fleet role when it
/// does not. A nickname is identity that CodeWhale actually has, so it leads;
/// the role is the honest fallback. The raw agent-id hash is never a name and
/// is never rendered (#36).
fn agent_strip_label(indent: &str, who: &str, children: usize) -> String {
    if children == 0 {
        format!("{indent}{who}")
    } else {
        format!("{indent}{who} (+{children})")
    }
}

/// Order worker rows so nested spawns sit directly under their parent, then
/// stamp each label with its display depth and a sequential number. Rows
/// whose parent is not visible (e.g. the parent finished and left the cache)
/// stay at the top level — honest flat rendering beats a dangling indent.
fn order_agent_seeds(seeds: Vec<AgentRowSeed>) -> Vec<RankedWorkRow> {
    let known_ids: HashSet<&str> = seeds.iter().map(|seed| seed.agent_id.as_str()).collect();
    let mut children: std::collections::HashMap<&str, Vec<usize>> =
        std::collections::HashMap::new();
    let mut roots = Vec::new();
    for (idx, seed) in seeds.iter().enumerate() {
        if let Some(parent) = seed.parent_run_id.as_deref()
            && known_ids.contains(parent)
        {
            children.entry(parent).or_default().push(idx);
            continue;
        }
        roots.push(idx);
    }

    fn push_tree(
        idx: usize,
        depth: usize,
        seeds: &[AgentRowSeed],
        children: &std::collections::HashMap<&str, Vec<usize>>,
        seen: &mut HashSet<usize>,
        order: &mut Vec<(usize, usize)>,
    ) {
        if !seen.insert(idx) {
            return;
        }
        order.push((idx, depth));
        if let Some(child_indices) = children.get(seeds[idx].agent_id.as_str()) {
            for child_idx in child_indices {
                push_tree(*child_idx, depth + 1, seeds, children, seen, order);
            }
        }
    }

    let mut order = Vec::with_capacity(seeds.len());
    let mut seen = HashSet::new();
    for idx in roots {
        push_tree(idx, 0, &seeds, &children, &mut seen, &mut order);
    }
    // Cycle/orphan backstop: emit anything the walk missed at the top level.
    for idx in 0..seeds.len() {
        push_tree(idx, 0, &seeds, &children, &mut seen, &mut order);
    }

    // `(+N)` counts children that are actually on this surface: the same map
    // the tree walk used, so the badge can never promise a child the list does
    // not show. Snapshot it before `seeds` is consumed — `children` borrows it.
    let child_counts: Vec<usize> = seeds
        .iter()
        .map(|seed| {
            children
                .get(seed.agent_id.as_str())
                .map_or(0, |indices| indices.len())
        })
        .collect();

    let mut slots: Vec<Option<AgentRowSeed>> = seeds.into_iter().map(Some).collect();
    order
        .into_iter()
        .enumerate()
        .map(|(position, (idx, depth))| {
            let seed = slots[idx].take().expect("each row emitted exactly once");
            let mut ranked = seed.ranked;
            let indent = agent_nesting_indent(depth.min(3));
            let role_label = agent_strip_label(&indent, &seed.role, child_counts[idx]);
            ranked.row.label = match seed.name.as_deref() {
                Some(name) => agent_strip_label(&indent, name, child_counts[idx]),
                None => role_label.clone(),
            };
            if let Some(facts) = ranked.row.agent.as_mut() {
                facts.role_label = role_label;
            }
            // `ordered_rows` re-sorts within status buckets by `order`; stamp
            // the tree position so a child sorts directly under its parent
            // whenever they share a bucket.
            ranked.order = position;
            ranked
        })
        .collect()
}

fn agent_rows(app: &App) -> Vec<RankedWorkRow> {
    let cached_ids = app
        .subagent_cache
        .iter()
        .filter(|agent| !agent.from_prior_session)
        .map(|agent| agent.agent_id.as_str())
        .collect::<HashSet<_>>();
    let mut seeds = app
        .subagent_cache
        .iter()
        .filter(|agent| !agent.from_prior_session)
        .enumerate()
        .map(|(order, agent)| {
            let meta = app.agent_progress_meta.get(&agent.agent_id);
            let current_activity = meta.and_then(|meta| meta.current_activity.as_ref());
            let status = current_activity
                .map(|activity| current_activity_status_label(activity.status))
                .or_else(|| agent.worker_status.map(worker_status_label))
                .unwrap_or_else(|| subagent_status_label(&agent.status));
            let bucket = current_activity
                .map(|activity| current_activity_status_bucket(activity.status))
                .or_else(|| agent.worker_status.map(worker_status_bucket))
                .unwrap_or_else(|| subagent_status_bucket(&agent.status));
            let role = agent
                .assignment
                .role
                .as_deref()
                .filter(|role| !role.trim().is_empty())
                .unwrap_or_else(|| agent.agent_type.as_str())
                .to_string();
            // The dispatch name leads (#5287); a nickname or stable label
            // names the agents dispatched without one. Never the bare agent
            // id (#36) — absent rather than fabricated, so the identity
            // column falls back to the role.
            let name = crate::tui::sidebar::dispatched_agent_name(agent)
                .map(str::to_string)
                .or_else(|| {
                    agent
                        .nickname
                        .clone()
                        .filter(|name| !name.trim().is_empty() && name != &agent.agent_id)
                })
                .or_else(|| app.agent_label_map.get(&agent.agent_id).cloned());
            let terminal = agent_is_terminal(agent, meta);
            let objective = summarize_assignment(&agent.assignment.objective);
            let mut facts = vec![status.to_string(), objective.clone()];
            // Quiet completion (#36): a finished agent keeps its one-line
            // status and objective; in-flight metadata (current tool, step
            // counters, file tallies) is working state, not a receipt, and
            // must not linger as a spawn-metadata dump after the run ends.
            if !terminal {
                if let Some(detail) =
                    current_activity.and_then(|activity| activity.detail.as_deref())
                {
                    facts.push(detail.to_string());
                }
                if let Some(tool) =
                    current_activity.and_then(|activity| activity.current_tool.as_deref())
                {
                    facts.push(format!("using {tool}"));
                }
                if let Some(step) = current_activity.and_then(|activity| activity.step) {
                    facts.push(format!("step {step}"));
                }
                if let Some(files) = meta
                    .map(|meta| meta.files_touched)
                    .filter(|count| *count > 0)
                {
                    facts.push(format!("{files} files changed"));
                }
            }
            AgentRowSeed {
                agent_id: agent.agent_id.clone(),
                parent_run_id: agent.parent_run_id.clone(),
                role,
                name,
                ranked: RankedWorkRow {
                    bucket,
                    order,
                    is_plan_step: false,
                    row: WorkRow {
                        id: WorkRowId(format!("worker:{}", agent.agent_id)),
                        mark: agent_mark(bucket),
                        // Stamped by `order_agent_seeds` once the display
                        // depth (and therefore the indent) is known.
                        label: String::new(),
                        detail: facts.join(" · "),
                        tone: bucket_tone(bucket),
                        selectable: true,
                        // One agent, one destination (v0.9.7): activation
                        // opens the agent's transcript directly; Agent
                        // Details is the secondary action from there.
                        primary_action: Some(SidebarRowAction::OpenAgentTranscript {
                            agent_id: agent.agent_id.clone(),
                        }),
                        agent: Some(AgentRowFacts {
                            // Stamped by `order_agent_seeds`, which is where
                            // the indent and child count become known.
                            role_label: String::new(),
                            status: status.to_string(),
                            objective,
                            elapsed_secs: Some(agent_elapsed_ms(app, agent) / 1_000),
                            model: meta.and_then(|meta| meta.resolved_model.clone()),
                            tokens: meta.and_then(|meta| meta.received_tokens),
                            todos_remaining: meta.and_then(|meta| meta.todos_remaining),
                        }),
                    },
                },
            }
        })
        .collect::<Vec<_>>();

    let mut progress_only = app
        .agent_progress
        .iter()
        .filter(|(id, _)| !cached_ids.contains(id.as_str()))
        .collect::<Vec<_>>();
    progress_only.sort_by_key(|(id, _)| (*id).clone());
    seeds.extend(
        progress_only
            .into_iter()
            .enumerate()
            .map(|(order, (id, _progress))| {
                let meta = app.agent_progress_meta.get(id);
                let current_activity = meta.and_then(|meta| meta.current_activity.as_ref());
                let status = current_activity
                    .map(|activity| current_activity_status_label(activity.status))
                    .unwrap_or("running");
                let bucket = current_activity
                    .map(|activity| current_activity_status_bucket(activity.status))
                    .unwrap_or(WorkBucket::Active);
                let name = app.agent_label_map.get(id).cloned();
                let mut facts = vec![status.to_string()];
                if let Some(detail) =
                    current_activity.and_then(|activity| activity.detail.as_deref())
                {
                    facts.push(detail.to_string());
                }
                if let Some(tool) =
                    current_activity.and_then(|activity| activity.current_tool.as_deref())
                {
                    facts.push(format!("using {tool}"));
                }
                if let Some(step) = current_activity.and_then(|activity| activity.step) {
                    facts.push(format!("step {step}"));
                }
                if let Some(files) = meta
                    .map(|meta| meta.files_touched)
                    .filter(|count| *count > 0)
                {
                    facts.push(format!("{files} files changed"));
                }
                AgentRowSeed {
                    agent_id: id.clone(),
                    parent_run_id: meta.and_then(|meta| meta.parent_run_id.clone()),
                    // Role is unknown until the manager snapshot arrives;
                    // "agent" is the honest fallback, not a fabrication.
                    role: "agent".to_string(),
                    name,
                    ranked: RankedWorkRow {
                        bucket,
                        order: 5_000usize.saturating_add(order),
                        is_plan_step: false,
                        row: WorkRow {
                            id: WorkRowId(format!("worker:{id}")),
                            mark: agent_mark(bucket),
                            label: String::new(),
                            detail: facts.join(" · "),
                            tone: bucket_tone(bucket),
                            selectable: true,
                            // Same destination as the cached-seed rows above.
                            primary_action: Some(SidebarRowAction::OpenAgentTranscript {
                                agent_id: id.clone(),
                            }),
                            agent: Some(AgentRowFacts {
                                role_label: String::new(),
                                status: status.to_string(),
                                // No manager snapshot yet, so there is no
                                // assignment to quote: the live activity line
                                // is the honest answer to "what is it doing".
                                // The status word itself is the status
                                // column's job, so it is not repeated here.
                                objective: facts[1..].join(" · "),
                                // Neither a duration nor a usage envelope has
                                // been seen for this id. Both render as
                                // nothing rather than as `0s` / `0 tokens`.
                                elapsed_secs: None,
                                model: meta.and_then(|meta| meta.resolved_model.clone()),
                                tokens: meta.and_then(|meta| meta.received_tokens),
                                todos_remaining: meta.and_then(|meta| meta.todos_remaining),
                            }),
                        },
                    },
                }
            }),
    );
    order_agent_seeds(seeds)
}

fn summarize_assignment(value: &str) -> String {
    // Flatten newlines the way the goal-title path does: a multi-line
    // objective must not break the one-line work-bar row (2026-08-04 review).
    let summary = crate::tui::history::summarize_tool_output(value);
    if summary.contains(['\n', '\r']) {
        summary.replace(['\n', '\r'], " ")
    } else {
        summary
    }
}

/// Has this agent stopped working? Typed live activity wins over the worker
/// status, which in turn wins over the coarse manager status — the same
/// precedence the row's status label and bucket already use.
fn agent_is_terminal(agent: &SubAgentResult, meta: Option<&AgentProgressMeta>) -> bool {
    meta.and_then(|meta| meta.current_activity.as_ref())
        .map(|activity| {
            matches!(
                activity.status,
                AgentCurrentActivityStatus::Done
                    | AgentCurrentActivityStatus::Canceled
                    | AgentCurrentActivityStatus::Failed
                    | AgentCurrentActivityStatus::Interrupted
            )
        })
        .or_else(|| {
            agent.worker_status.map(|worker_status| {
                matches!(
                    worker_status,
                    AgentWorkerStatus::Completed
                        | AgentWorkerStatus::Cancelled
                        | AgentWorkerStatus::Failed
                        | AgentWorkerStatus::Interrupted
                )
            })
        })
        .unwrap_or(matches!(
            agent.status,
            SubAgentStatus::Completed
                | SubAgentStatus::Cancelled
                | SubAgentStatus::Failed(_)
                | SubAgentStatus::Interrupted(_)
                | SubAgentStatus::BudgetExhausted
        ))
}

/// Latch each finished agent's elapsed time the first frame it is observed
/// terminal, and forget agents that have left the cache.
///
/// The manager recomputes `SubAgentResult::duration_ms` as
/// `started_at.elapsed()` on every snapshot, so a completed agent's duration
/// keeps growing for as long as it stays listed. Without this pass a finished
/// row would tick forever, which is exactly the thing a receipt must not do.
fn freeze_terminal_agent_elapsed(app: &mut App) {
    let live: HashSet<&str> = app
        .subagent_cache
        .iter()
        .map(|agent| agent.agent_id.as_str())
        .collect();
    app.work_surface
        .frozen_agent_elapsed_ms
        .retain(|id, _| live.contains(id.as_str()));

    for agent in &app.subagent_cache {
        if !agent_is_terminal(agent, app.agent_progress_meta.get(&agent.agent_id)) {
            continue;
        }
        app.work_surface
            .frozen_agent_elapsed_ms
            .entry(agent.agent_id.clone())
            .or_insert(agent.duration_ms);
    }
}

/// Frozen elapsed for a finished agent, live elapsed for a running one.
fn agent_elapsed_ms(app: &App, agent: &crate::tools::subagent::SubAgentResult) -> u64 {
    // Live ticking (4b): derive from start timestamp at render when running,
    // otherwise use frozen snapshot. The redraw already happens; stale cached
    // duration is the bug.
    if matches!(
        agent.status,
        crate::tools::subagent::SubAgentStatus::Running
    ) && let Some(started_at) = agent.started_at
    {
        return u64::try_from(started_at.elapsed().as_millis()).unwrap_or(agent.duration_ms);
    }
    app.work_surface
        .frozen_agent_elapsed_ms
        .get(&agent.agent_id)
        .copied()
        .unwrap_or(agent.duration_ms)
}

fn current_activity_status_bucket(status: AgentCurrentActivityStatus) -> WorkBucket {
    match status {
        AgentCurrentActivityStatus::Waiting
        | AgentCurrentActivityStatus::Interrupted
        | AgentCurrentActivityStatus::Failed => WorkBucket::Attention,
        AgentCurrentActivityStatus::Queued => WorkBucket::Ready,
        AgentCurrentActivityStatus::Done | AgentCurrentActivityStatus::Canceled => {
            WorkBucket::Recent
        }
        AgentCurrentActivityStatus::Starting
        | AgentCurrentActivityStatus::Running
        | AgentCurrentActivityStatus::ModelWait
        | AgentCurrentActivityStatus::RunningTool => WorkBucket::Active,
    }
}

fn current_activity_status_label(status: AgentCurrentActivityStatus) -> &'static str {
    match status {
        AgentCurrentActivityStatus::Queued => "queued",
        AgentCurrentActivityStatus::Starting => "starting",
        AgentCurrentActivityStatus::Running => "running",
        AgentCurrentActivityStatus::ModelWait => "waiting for model",
        AgentCurrentActivityStatus::RunningTool => "running tool",
        AgentCurrentActivityStatus::Waiting => "waiting for input",
        AgentCurrentActivityStatus::Done => "completed",
        AgentCurrentActivityStatus::Failed => "failed",
        AgentCurrentActivityStatus::Canceled => "cancelled",
        AgentCurrentActivityStatus::Interrupted => "interrupted",
    }
}

fn worker_status_bucket(status: AgentWorkerStatus) -> WorkBucket {
    match status {
        AgentWorkerStatus::WaitingForUser
        | AgentWorkerStatus::Interrupted
        | AgentWorkerStatus::Failed => WorkBucket::Attention,
        AgentWorkerStatus::Queued => WorkBucket::Ready,
        AgentWorkerStatus::Completed | AgentWorkerStatus::Cancelled => WorkBucket::Recent,
        AgentWorkerStatus::Starting
        | AgentWorkerStatus::Running
        | AgentWorkerStatus::ModelWait
        | AgentWorkerStatus::RunningTool => WorkBucket::Active,
    }
}

fn worker_status_label(status: AgentWorkerStatus) -> &'static str {
    match status {
        AgentWorkerStatus::Queued => "queued",
        AgentWorkerStatus::Starting => "starting",
        AgentWorkerStatus::Running => "running",
        AgentWorkerStatus::WaitingForUser => "waiting for input",
        AgentWorkerStatus::ModelWait => "waiting for model",
        AgentWorkerStatus::RunningTool => "running tool",
        AgentWorkerStatus::Completed => "completed",
        AgentWorkerStatus::Failed => "failed",
        AgentWorkerStatus::Cancelled => "cancelled",
        AgentWorkerStatus::Interrupted => "interrupted",
    }
}

fn subagent_status_bucket(status: &SubAgentStatus) -> WorkBucket {
    match status {
        SubAgentStatus::Running => WorkBucket::Active,
        SubAgentStatus::Interrupted(_)
        | SubAgentStatus::Failed(_)
        | SubAgentStatus::BudgetExhausted => WorkBucket::Attention,
        SubAgentStatus::Completed | SubAgentStatus::Cancelled => WorkBucket::Recent,
    }
}

fn subagent_status_label(status: &SubAgentStatus) -> &'static str {
    match status {
        SubAgentStatus::Running => "running",
        SubAgentStatus::Completed => "completed",
        SubAgentStatus::Interrupted(_) => "interrupted",
        SubAgentStatus::Failed(_) => "failed",
        SubAgentStatus::Cancelled => "cancelled",
        SubAgentStatus::BudgetExhausted => "budget exhausted",
    }
}

const fn bucket_tone(bucket: WorkBucket) -> WorkTone {
    match bucket {
        WorkBucket::Active => WorkTone::Live,
        WorkBucket::Attention => WorkTone::Attention,
        WorkBucket::Ready => WorkTone::Muted,
        WorkBucket::Recent => WorkTone::Success,
    }
}

const fn agent_mark(bucket: WorkBucket) -> &'static str {
    match bucket {
        WorkBucket::Active => crate::tui::glyphs::SELECTION,
        WorkBucket::Attention => crate::tui::glyphs::ATTENTION,
        WorkBucket::Ready => crate::tui::glyphs::READY,
        WorkBucket::Recent => crate::tui::glyphs::DONE,
    }
}

fn settled_file_activity(app: &App) -> SettledFileActivity {
    let mut activity = SettledFileActivity {
        inline_diff_mode: app.inline_diff_mode,
        ..SettledFileActivity::default()
    };
    let mut seen = HashSet::new();
    for index in 0..app.virtual_cell_count() {
        let Some(HistoryCell::Tool(cell)) = app.cell_at_virtual_index(index) else {
            continue;
        };
        if !cell.is_success() {
            continue;
        }
        let Some(detail) = app.tool_detail_record_for_cell(index) else {
            continue;
        };
        let activity_tool_name = canonical_action_alias(&detail.tool_name, &detail.input);
        let kind = if matches!(cell, ToolCell::PatchSummary(_)) {
            Some(FileActivityKind::Write)
        } else {
            FileActivitySummary::from_tool_name(activity_tool_name)
        };
        let Some(kind) = kind else {
            continue;
        };
        if !seen.insert(detail.tool_id.as_str()) {
            continue;
        }
        activity.summary.record(kind);
        if kind == FileActivityKind::Write
            && let ToolCell::PatchSummary(mutation) = cell
            && let Some(receipt) = mutation.receipt.as_ref()
        {
            let additional_files =
                u32::try_from(receipt.files.len().saturating_sub(1)).unwrap_or(u32::MAX);
            activity.summary.files_written = activity
                .summary
                .files_written
                .saturating_add(additional_files);
            activity.mutations.push(receipt.clone());
        }
        let target = activity_target(&app.workspace, activity_tool_name, &detail.input, kind);
        let details = match kind {
            FileActivityKind::Read => &mut activity.read,
            FileActivityKind::List => &mut activity.list,
            FileActivityKind::Search => &mut activity.search,
            FileActivityKind::Write => &mut activity.write,
        };
        if let Some(target) = target
            && details.len() < 12
            && !details.contains(&target)
        {
            details.push(target);
        }
    }
    activity
}

fn aggregate_activity_row(activity: &SettledFileActivity) -> Option<RankedWorkRow> {
    if activity.is_empty() {
        return None;
    }
    let summaries = activity.summary.compact_display();
    if summaries.is_empty() {
        return None;
    }
    // Single aggregated live receipt; never inline raw patterns/commands (#4690).
    let label = if summaries.len() == 1 {
        summaries[0].clone()
    } else {
        summaries.join(" · ")
    };
    let mutation_detail = activity.mutations.last().map(|receipt| {
        if activity.inline_diff_mode == InlineDiffMode::Off {
            receipt.outcome_label()
        } else {
            receipt.semantic_summary()
        }
    });
    let mutation_body = settled_mutation_body(&activity.mutations, activity.inline_diff_mode);
    let mut body_parts = Vec::new();
    if !mutation_body.is_empty() {
        body_parts.push(mutation_body);
    }
    for (kind, details) in [
        ("Read", &activity.read),
        ("List", &activity.list),
        ("Search", &activity.search),
        ("Write", &activity.write),
    ] {
        if details.is_empty() {
            continue;
        }
        body_parts.push(format!("{kind}:\n{}", details.join("\n")));
    }
    if body_parts.is_empty() {
        body_parts.push("No safe target detail retained".to_string());
    }
    let detail = mutation_detail
        .or_else(|| {
            activity
                .write
                .first()
                .cloned()
                .or_else(|| activity.read.first().cloned())
                .or_else(|| activity.search.first().map(|_| "patterns".to_string()))
                .or_else(|| activity.list.first().cloned())
        })
        .unwrap_or_else(|| "settled".to_string());
    let detail = sanitize_summary_title(&detail);
    Some(RankedWorkRow {
        bucket: WorkBucket::Recent,
        order: 20_000,
        is_plan_step: false,
        row: WorkRow {
            id: WorkRowId("activity:aggregate".to_string()),
            mark: crate::tui::glyphs::DONE,
            label,
            detail,
            tone: WorkTone::Success,
            selectable: true,
            primary_action: Some(SidebarRowAction::InspectWork {
                title: "Work · file activity".to_string(),
                body: body_parts.join("\n\n"),
                stop_action: None,
            }),
            agent: None,
        },
    })
}

#[cfg(test)]
fn activity_rows(activity: SettledFileActivity) -> Vec<RankedWorkRow> {
    aggregate_activity_row(&activity).into_iter().collect()
}

fn settled_mutation_body(receipts: &[FileMutationReceipt], mode: InlineDiffMode) -> String {
    let Some(receipt) = receipts.last() else {
        return String::new();
    };
    let details = crate::tui::key_shortcuts::tool_details_shortcut_action_hint(
        "exact change evidence on the matching File receipt",
    );
    let hint = format!("Select the matching File receipt; {details}.");
    match mode {
        InlineDiffMode::Off => format!("{}\n\n{hint}", receipt.outcome_label()),
        InlineDiffMode::Summary => format!("{}\n\n{hint}", receipt.semantic_summary()),
        InlineDiffMode::Full => {
            let diff = receipt
                .display_diff
                .lines()
                .take(40)
                .collect::<Vec<_>>()
                .join("\n");
            if diff.trim().is_empty() {
                format!("{}\n\n{hint}", receipt.semantic_summary())
            } else {
                format!("{}\n\n{diff}\n\n{hint}", receipt.semantic_summary())
            }
        }
    }
}

fn activity_target(
    workspace: &Path,
    tool_name: &str,
    input: &serde_json::Value,
    kind: FileActivityKind,
) -> Option<String> {
    if tool_name == "apply_patch"
        && let Ok(preflight) = crate::tools::apply_patch::preflight_apply_patch(input)
    {
        let targets = preflight
            .touched_files
            .iter()
            .filter_map(|path| privacy_safe_path(workspace, path))
            .take(4)
            .collect::<Vec<_>>();
        if !targets.is_empty() {
            return Some(targets.join(", "));
        }
    }
    let keys: &[&str] = match kind {
        FileActivityKind::Search => &["pattern", "query", "path"],
        _ => &["path", "file_path"],
    };
    keys.iter().find_map(|key| {
        let value = input.get(*key)?.as_str()?.trim();
        if value.is_empty() {
            return None;
        }
        if kind == FileActivityKind::Search && *key != "path" {
            return Some(safe_pattern(value));
        }
        privacy_safe_path(workspace, value)
    })
}

fn privacy_safe_path(workspace: &Path, raw: &str) -> Option<String> {
    let path = Path::new(raw);
    let normalized_raw = raw.replace('\\', "/");
    let normalized_workspace = workspace.to_string_lossy().replace('\\', "/");
    let relative = if path.is_absolute() || normalized_raw.starts_with('/') {
        let workspace_prefix = normalized_workspace.trim_end_matches('/');
        if normalized_raw == workspace_prefix {
            ""
        } else {
            normalized_raw.strip_prefix(&format!("{workspace_prefix}/"))?
        }
    } else {
        normalized_raw.as_str()
    };
    let relative = Path::new(relative);
    if relative.components().any(|component| {
        matches!(
            component,
            Component::ParentDir | Component::RootDir | Component::Prefix(_)
        )
    }) {
        return None;
    }
    let display = relative.to_string_lossy().replace('\\', "/");
    (!display.is_empty()).then_some(display)
}

fn safe_pattern(raw: &str) -> String {
    let single_line = raw.replace(['\n', '\r', '\t'], " ");
    let mut chars = single_line.chars();
    let prefix = chars.by_ref().take(80).collect::<String>();
    if chars.next().is_some() {
        format!("{prefix}")
    } else {
        prefix
    }
}

fn is_settled_transient_operation(node: &WorkNode) -> bool {
    node.kind == NodeKind::Operation
        && node
            .binding
            .as_ref()
            .is_some_and(|binding| !binding.durable)
        && match node.state {
            NodeState::Completed => node.acceptance.is_empty(),
            NodeState::Verified | NodeState::Superseded | NodeState::Cancelled => true,
            _ => false,
        }
}

fn section_heading(id: &str, label: &str, detail: &str) -> WorkRow {
    WorkRow {
        id: WorkRowId(format!("section:{id}")),
        mark: "",
        label: label.to_string(),
        detail: detail.to_string(),
        tone: WorkTone::Heading,
        selectable: false,
        primary_action: None,
        agent: None,
    }
}

/// The sub-agent heading is a real group door: selecting it reveals the full
/// Agents panel, including settled workers whose exact transcripts remain
/// available after the compact strip archives them.
fn agents_section_heading(label: &str) -> WorkRow {
    WorkRow {
        id: WorkRowId("section:agents".to_string()),
        mark: "",
        label: label.to_string(),
        detail: "Open the full subagent register".to_string(),
        tone: WorkTone::Heading,
        selectable: true,
        primary_action: Some(SidebarRowAction::ShowSubagentsPanel),
        agent: None,
    }
}

fn graph_node_row(snapshot: &WorkGraphSnapshot, node: &WorkNode) -> WorkRow {
    let (mark, tone) = match node.state {
        NodeState::Ready => (crate::tui::glyphs::READY, WorkTone::Muted),
        NodeState::Initializing => (crate::tui::glyphs::SELECTION, WorkTone::Live),
        NodeState::Active => (crate::tui::glyphs::SELECTION, WorkTone::Live),
        NodeState::Waiting => (crate::tui::glyphs::ATTENTION, WorkTone::Attention),
        NodeState::Blocked => (
            status_mark(StatusKind::Attention).glyph,
            WorkTone::Attention,
        ),
        NodeState::Completed if node.acceptance.is_empty() => {
            (status_mark(StatusKind::Done).glyph, WorkTone::Success)
        }
        NodeState::Completed => (
            status_mark(StatusKind::Attention).glyph,
            WorkTone::Attention,
        ),
        NodeState::Verified => (status_mark(StatusKind::Done).glyph, WorkTone::Success),
        NodeState::Stale => ("?", WorkTone::Attention),
        NodeState::Superseded | NodeState::Cancelled => ("", WorkTone::Muted),
        NodeState::Failed => (crate::tui::glyphs::FAILED, WorkTone::Attention),
    };
    let state = state_label(node);
    let kind = kind_label(node.kind);
    // A to-do row always carries its status word in the detail column, using
    // the same vocabulary as `/task digest` (pending / in progress /
    // completed / cancelled). Only the redundant `· plan step` KIND suffix is
    // dropped — the strip's checkbox marks already say the row is a plan
    // step, but they do not say its state in words, and dropping the state
    // itself was the 0.9.4 regression (a pending to-do rendered no label at
    // all). Non-step nodes keep the state · kind pair.
    let detail = if node.kind == NodeKind::PlanStep {
        todo_state_label(node).to_string()
    } else {
        format!("{state} · {kind}")
    };
    let stop_action = node
        .state
        .is_live()
        .then(|| stop_action(node.binding.as_ref()))
        .flatten();
    WorkRow {
        id: WorkRowId(format!("graph:{}", node.id.as_str())),
        mark,
        label: node.title.clone(),
        detail,
        tone,
        selectable: true,
        primary_action: Some(SidebarRowAction::InspectWork {
            title: format!("Work · {}", node.title),
            body: inspector_text(snapshot, node),
            stop_action: stop_action.map(Box::new),
        }),
        agent: None,
    }
}

/// Status word for a plan-step (to-do) row, aligned with the four-state
/// To-do vocabulary the `/task digest` text surface uses. Graph-only states
/// keep their graph names.
fn todo_state_label(node: &WorkNode) -> &'static str {
    match node.state {
        NodeState::Ready => "pending",
        NodeState::Initializing | NodeState::Active => "in progress",
        _ => state_label(node),
    }
}

fn state_label(node: &WorkNode) -> &'static str {
    match node.state {
        NodeState::Ready => "ready",
        NodeState::Initializing => "initializing",
        NodeState::Active => "running",
        NodeState::Waiting => "waiting",
        NodeState::Blocked => "blocked",
        NodeState::Completed if node.acceptance.is_empty() => "completed",
        NodeState::Completed => "completed · evidence pending",
        NodeState::Verified => "verified",
        NodeState::Stale => "stale",
        NodeState::Superseded => "superseded",
        NodeState::Cancelled => "cancelled",
        NodeState::Failed => "failed",
    }
}

const fn kind_label(kind: NodeKind) -> &'static str {
    match kind {
        NodeKind::Objective => "objective",
        NodeKind::PlanStep => "plan step",
        NodeKind::Operation => "operation",
        NodeKind::Evidence => "evidence",
        NodeKind::Blocker => "blocker",
        NodeKind::Approval => "approval",
        NodeKind::RuntimeRef => "runtime",
        NodeKind::LaneRef => "lane",
    }
}

fn stop_action(binding: Option<&OperationBinding>) -> Option<SidebarRowAction> {
    let binding = binding?;
    if let Some(id) = binding.external.strip_prefix("task:") {
        Some(SidebarRowAction::Command(format!("/task cancel {id}")))
    } else if let Some(id) = binding.external.strip_prefix("shell:") {
        Some(SidebarRowAction::Command(format!("/jobs cancel {id}")))
    } else if let Some(id) = binding.external.strip_prefix("worker:") {
        Some(SidebarRowAction::CancelAgent {
            agent_id: id.to_string(),
        })
    } else {
        binding
            .external
            .strip_prefix("workflow:")
            .map(|id| SidebarRowAction::Command(format!("/workflow cancel {id}")))
    }
}

fn inspector_text(snapshot: &WorkGraphSnapshot, node: &WorkNode) -> String {
    let mut out = String::new();
    section_text(
        &mut out,
        "Objective",
        objective_for(snapshot, node)
            .as_deref()
            .unwrap_or("Not connected"),
    );
    section_list(
        &mut out,
        "Prerequisites",
        related_nodes(snapshot, node, EdgeKind::DependsOn, true),
    );
    section_text(
        &mut out,
        "Current",
        &format!("{} · {}", state_label(node), kind_label(node.kind)),
    );
    section_list(
        &mut out,
        "Downstream impact",
        related_nodes(snapshot, node, EdgeKind::DependsOn, false),
    );
    section_text(&mut out, "Binding + lifecycle owner", &binding_text(node));
    section_text(
        &mut out,
        "Evidence vs acceptance",
        &evidence_text(snapshot, node),
    );
    section_text(
        &mut out,
        "Blockers / approvals",
        &blockers_approvals_text(snapshot, node),
    );
    section_text(&mut out, "Why next", &why_next(snapshot, node));
    section_text(
        &mut out,
        "Provenance + last reconcile",
        &provenance_text(node),
    );
    if node.state == NodeState::Stale {
        section_text(
            &mut out,
            "Last bounded output",
            last_output_ref(snapshot, node)
                .as_deref()
                .unwrap_or("No output receipt"),
        );
    }
    out.trim_end().to_string()
}

fn objective_for(snapshot: &WorkGraphSnapshot, node: &WorkNode) -> Option<String> {
    if node.kind == NodeKind::Objective {
        return Some(node.title.clone());
    }
    let mut current = node.id.clone();
    let mut seen = HashSet::new();
    while seen.insert(current.clone()) {
        let Some(parent) = snapshot.edges.iter().find_map(|edge| {
            (edge.kind == EdgeKind::Contains && edge.to == current).then(|| edge.from.clone())
        }) else {
            break;
        };
        let Some(parent_node) = snapshot.node(&parent) else {
            break;
        };
        if parent_node.kind == NodeKind::Objective {
            return Some(parent_node.title.clone());
        }
        current = parent;
    }
    snapshot.compat.plan.objective.clone()
}

fn related_nodes(
    snapshot: &WorkGraphSnapshot,
    node: &WorkNode,
    kind: EdgeKind,
    outgoing: bool,
) -> Vec<String> {
    snapshot
        .edges
        .iter()
        .filter(|edge| edge.kind == kind)
        .filter_map(|edge| {
            let related = if outgoing && edge.from == node.id {
                Some(&edge.to)
            } else if !outgoing && edge.to == node.id {
                Some(&edge.from)
            } else {
                None
            }?;
            snapshot
                .node(related)
                .map(|related| format!("{} · {}", related.title, state_label(related)))
        })
        .collect()
}

fn binding_text(node: &WorkNode) -> String {
    let Some(binding) = node.binding.as_ref() else {
        return "Not bound".to_string();
    };
    let mut text = format!(
        "Owner: {}\nDurable: {}",
        binding.external,
        if binding.durable { "yes" } else { "no" }
    );
    if let Some(observation) = binding.last_observation.as_ref() {
        let owner_state = match observation.owner_state {
            OwnerState::Initializing => "initializing",
            OwnerState::Running => "running",
            OwnerState::Waiting => "waiting",
            OwnerState::Completed => "completed",
            OwnerState::Failed => "failed",
            OwnerState::Cancelled => "cancelled",
        };
        let _ = write!(
            text,
            "\nLast owner state: {owner_state}\nLast reconcile: {} ms UTC · sequence {}",
            observation.observed_at, observation.seq
        );
    } else {
        text.push_str("\nLast reconcile: never");
    }
    text
}

fn evidence_text(snapshot: &WorkGraphSnapshot, node: &WorkNode) -> String {
    let acceptance = if node.acceptance.is_empty() {
        vec!["- No evidence requirement".to_string()]
    } else {
        node.acceptance
            .iter()
            .map(|requirement| format!("- {}", acceptance_label(requirement)))
            .collect()
    };
    let evidence = evidence_for(snapshot, node);
    let evidence = if evidence.is_empty() {
        vec!["- None attached".to_string()]
    } else {
        evidence
            .into_iter()
            .map(|evidence| {
                let reference = evidence
                    .evidence
                    .as_ref()
                    .map(|item| item.reference())
                    .unwrap_or("invalid evidence node");
                format!("- {reference} · {}", state_label(evidence))
            })
            .collect()
    };
    format!(
        "Acceptance:\n{}\nEvidence:\n{}",
        acceptance.join("\n"),
        evidence.join("\n")
    )
}

fn acceptance_label(requirement: &AcceptanceRequirement) -> String {
    match requirement {
        AcceptanceRequirement::EvidenceOfKind { kind } => {
            let kind = match kind {
                EvidenceKindTag::ToolRun => "tool run",
                EvidenceKindTag::Artifact => "artifact",
                EvidenceKindTag::TestSummary => "test summary",
                EvidenceKindTag::Receipt => "receipt",
                EvidenceKindTag::Approval => "approval",
                EvidenceKindTag::Route => "route",
                EvidenceKindTag::WebCitation => "web citation",
            };
            format!("evidence of kind {kind}")
        }
    }
}

fn evidence_for<'a>(snapshot: &'a WorkGraphSnapshot, node: &WorkNode) -> Vec<&'a WorkNode> {
    snapshot
        .edges
        .iter()
        .filter(|edge| edge.kind == EdgeKind::Verifies && edge.to == node.id)
        .filter_map(|edge| snapshot.node(&edge.from))
        .collect()
}

fn blockers_approvals_text(snapshot: &WorkGraphSnapshot, node: &WorkNode) -> String {
    let mut lines = Vec::new();
    lines.extend(
        related_nodes(snapshot, node, EdgeKind::Blocks, false)
            .into_iter()
            .map(|item| format!("- Blocked by {item}")),
    );
    lines.extend(
        related_nodes(snapshot, node, EdgeKind::RequiresApproval, true)
            .into_iter()
            .map(|item| format!("- Approval {item}")),
    );
    if node.kind == NodeKind::PlanStep {
        lines.extend(
            snapshot
                .nodes
                .iter()
                .filter(|candidate| candidate.kind == NodeKind::Approval)
                .map(|approval| format!("- {} · {}", approval.title, state_label(approval))),
        );
    }
    if lines.is_empty() {
        "None".to_string()
    } else {
        lines.join("\n")
    }
}

fn why_next(snapshot: &WorkGraphSnapshot, node: &WorkNode) -> String {
    match node.state {
        NodeState::Ready => {
            let pending = related_nodes(snapshot, node, EdgeKind::DependsOn, true);
            if pending.is_empty() {
                "Ready with no recorded prerequisite".to_string()
            } else {
                format!("Ready after: {}", pending.join(", "))
            }
        }
        NodeState::Initializing => "Spawn intent is registered; awaiting owner handle".to_string(),
        NodeState::Active => "Lifecycle owner reports active work".to_string(),
        NodeState::Waiting => "Waiting on an owner or approval".to_string(),
        NodeState::Blocked => "Blocked; resolve the causes above".to_string(),
        NodeState::Completed if !node.acceptance.is_empty() => {
            "Execution ended, but acceptance evidence is still missing".to_string()
        }
        NodeState::Stale => "Owner cannot confirm liveness after reconciliation".to_string(),
        NodeState::Verified => "Acceptance evidence is satisfied".to_string(),
        NodeState::Completed => "Completed with no evidence requirement".to_string(),
        NodeState::Superseded => "A replacement node owns this work".to_string(),
        NodeState::Cancelled => "Cancelled by lifecycle owner".to_string(),
        NodeState::Failed => "Failed; inspect owner output before retrying".to_string(),
    }
}

fn provenance_text(node: &WorkNode) -> String {
    let provenance = match &node.provenance {
        Provenance::Import { ordinal, .. } => ordinal
            .map(|ordinal| format!("legacy import · ordinal {ordinal}"))
            .unwrap_or_else(|| "legacy import".to_string()),
        Provenance::ToolUpdate { tool, call_id } => {
            format!("tool {tool} · call {call_id}")
        }
        Provenance::RuntimeReconcile {
            source,
            observed_at,
        } => format!("runtime {source} · {observed_at} ms UTC"),
        Provenance::UserEdit { proposal_id } => format!("user-approved diff {proposal_id}"),
    };
    let reconcile = node
        .binding
        .as_ref()
        .and_then(|binding| binding.last_observation.as_ref())
        .map(|observation| format!("{} ms UTC", observation.observed_at))
        .unwrap_or_else(|| "never".to_string());
    format!("Source: {provenance}\nLast reconcile: {reconcile}")
}

fn last_output_ref(snapshot: &WorkGraphSnapshot, node: &WorkNode) -> Option<String> {
    node.binding
        .as_ref()
        .and_then(|binding| binding.last_observation.as_ref())
        .and_then(|observation| observation.output.as_ref())
        .map(format_evidence_ref)
        .or_else(|| {
            evidence_for(snapshot, node)
                .into_iter()
                .max_by_key(|evidence| evidence.updated_at)
                .and_then(|evidence| evidence.evidence.as_ref())
                .map(format_evidence_ref)
        })
}

fn format_evidence_ref(evidence: &crate::work_graph::EvidenceRef) -> String {
    let kind = match evidence.kind() {
        EvidenceKind::ToolRun => "tool run".to_string(),
        EvidenceKind::Artifact { .. } => "artifact".to_string(),
        EvidenceKind::TestSummary => "test summary".to_string(),
        EvidenceKind::Receipt { .. } => "receipt".to_string(),
        EvidenceKind::Approval => "approval".to_string(),
        EvidenceKind::Route => "route".to_string(),
        EvidenceKind::WebCitation {
            url, retrieved_at, ..
        } => format!("web citation · {url} · retrieved {retrieved_at}"),
    };
    let bytes = evidence
        .raw_bytes()
        .map(|bytes| format!(" · {bytes} raw bytes"))
        .unwrap_or_default();
    let truncation = if evidence.truncated() {
        " · truncated"
    } else {
        ""
    };
    format!("{} · {kind}{bytes}{truncation}", evidence.reference())
}

fn section_text(out: &mut String, title: &str, body: &str) {
    let _ = writeln!(out, "{title}\n{body}\n");
}

fn section_list(out: &mut String, title: &str, items: Vec<String>) {
    if items.is_empty() {
        section_text(out, title, "None");
    } else {
        section_text(
            out,
            title,
            &items
                .into_iter()
                .map(|item| format!("- {item}"))
                .collect::<Vec<_>>()
                .join("\n"),
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Config;
    use crate::tools::spec::ToolResult;
    use crate::tui::app::TuiOptions;
    use crate::tui::tool_routing::{handle_tool_call_complete, handle_tool_call_started};
    use crate::work_graph::{CompatTodoBinding, OperationBinding, WorkNodeId};

    fn test_app() -> App {
        App::new(
            TuiOptions {
                model: "deepseek-v4-flash".to_string(),
                start_in_agent_mode: true,
                ..crate::test_support::test_tui_options(std::path::PathBuf::from(
                    "/workspace/project",
                ))
            },
            &Config::default(),
        )
    }

    fn surface() -> WorkSurfaceState {
        WorkSurfaceState::default()
    }

    fn operation(state: NodeState, suffix: &str) -> WorkNode {
        WorkNode {
            id: WorkNodeId::derive("work-surface-test", suffix),
            kind: NodeKind::Operation,
            title: format!("operation {suffix}"),
            state,
            acceptance: Vec::new(),
            binding: Some(OperationBinding {
                external: format!("shell:{suffix}"),
                durable: false,
                last_observation: None,
            }),
            evidence: None,
            provenance: Provenance::ToolUpdate {
                tool: "test".to_string(),
                call_id: suffix.to_string(),
            },
            created_at: 1,
            updated_at: 1,
        }
    }

    fn running_agent(agent_id: &str) -> SubAgentResult {
        SubAgentResult {
            name: agent_id.to_string(),
            agent_id: agent_id.to_string(),
            context_mode: "fresh".to_string(),
            fork_context: false,
            workspace: None,
            git_branch: None,
            agent_type: crate::tools::subagent::FleetRole::Worker,
            assignment: crate::tools::subagent::SubAgentAssignment {
                objective: "sweep the lane".to_string(),
                role: Some("builder".to_string()),
            },
            model: "test-model".to_string(),
            nickname: Some("Blue Whale".to_string()),
            status: SubAgentStatus::Running,
            worker_status: None,
            runtime_permissions: None,
            parent_run_id: None,
            spawn_depth: 0,
            child_route: None,
            result: None,
            steps_taken: 1,
            checkpoint: None,
            needs_input: None,
            duration_ms: 100,
            started_at: None,
            from_prior_session: false,
        }
    }

    /// #5287: the identity column leads with the name the lane was dispatched
    /// under; the whale only names an agent that was dispatched without one.
    #[test]
    fn agent_identity_column_leads_with_the_dispatch_name() {
        let mut app = test_app();
        let mut named = running_agent("agent_named_lane");
        named.name = "branch-triage".to_string();
        app.subagent_cache.push(named);
        app.subagent_cache.push(running_agent("agent_plain_lane"));

        let rows = agent_rows(&app);
        let label = |id: &str| {
            rows.iter()
                .find(|ranked| ranked.row.id.0 == format!("worker:{id}"))
                .unwrap_or_else(|| panic!("row for {id}"))
                .row
                .label
                .clone()
        };
        assert_eq!(label("agent_named_lane"), "branch-triage");
        assert_eq!(label("agent_plain_lane"), "Blue Whale");
    }

    /// After the recent-only TTL suppresses transient receipts, the live
    /// heading must count only the recent rows the live list still shows —
    /// quoting the unfiltered total would claim receipts the reader cannot
    /// see (2026-08-04 adversarial review of the durable-row exemption).
    #[test]
    fn suppressed_transients_leave_the_live_heading_count_honest() {
        let mut plan_step = operation(NodeState::Completed, "shipped-step");
        plan_step.kind = NodeKind::PlanStep;
        plan_step.binding = None;
        let mut transient = operation(NodeState::Completed, "settled-op");
        transient.binding.as_mut().expect("binding").durable = true;
        let mut snapshot = WorkGraphSnapshot::new();
        snapshot.nodes = vec![plan_step, transient];

        let mut surface = surface();
        surface.set_presentation_now_ms(0);
        let _ = graph_rows(
            &mut surface,
            &snapshot,
            None,
            Vec::new(),
            None,
            SettledFileActivity::default(),
        );
        surface.set_presentation_now_ms(RECENT_ONLY_TTL_MS + 1);
        let rows = graph_rows(
            &mut surface,
            &snapshot,
            None,
            Vec::new(),
            None,
            SettledFileActivity::default(),
        );
        let heading = &rows[0];
        assert!(
            heading.label.contains("1 recent"),
            "live heading counts only the surviving durable row: {}",
            heading.label
        );
        assert!(
            rows.iter().any(|row| row.label.contains("shipped-step")),
            "durable to-do row survives: {rows:?}"
        );
        assert!(
            !rows.iter().any(|row| row.label.contains("settled-op")),
            "transient receipt is suppressed: {rows:?}"
        );
        // The catalog keeps the full rows, so it keeps the full count.
        assert!(
            surface
                .catalog_rows
                .first()
                .is_some_and(|row| row.label.contains("2 recent")),
            "catalog heading keeps the unfiltered count: {:?}",
            surface.catalog_rows.first()
        );
    }

    #[test]
    fn heading_counts_initializing_and_active_operations_as_running() {
        let mut snapshot = WorkGraphSnapshot::new();
        snapshot.nodes = vec![
            operation(NodeState::Initializing, "initializing"),
            operation(NodeState::Active, "active"),
            operation(NodeState::Ready, "ready"),
        ];

        let rows = graph_rows(
            &mut surface(),
            &snapshot,
            None,
            Vec::new(),
            None,
            SettledFileActivity::default(),
        );

        assert_eq!(
            rows.first().map(|row| row.label.as_str()),
            Some("Work · Running: operation initializing · 2 active")
        );
    }

    #[test]
    fn live_projection_hides_clean_transient_receipts_without_duplicate_todo_group() {
        let todo_id = WorkNodeId::derive("work-surface-test", "todo:1");
        let todo = WorkNode {
            id: todo_id.clone(),
            kind: NodeKind::PlanStep,
            title: "Keep the durable checklist visible".to_string(),
            state: NodeState::Ready,
            acceptance: Vec::new(),
            binding: None,
            evidence: None,
            provenance: Provenance::ToolUpdate {
                tool: "work_update".to_string(),
                call_id: "todo-1".to_string(),
            },
            created_at: 1,
            updated_at: 1,
        };
        let mut snapshot = WorkGraphSnapshot::new();
        snapshot.nodes = vec![
            operation(NodeState::Completed, "settled"),
            operation(NodeState::Active, "running"),
            todo,
        ];
        snapshot.compat.todos.push(CompatTodoBinding {
            legacy_id: 1,
            node: todo_id,
            plan_index: None,
        });

        let rows = graph_rows(
            &mut surface(),
            &snapshot,
            None,
            Vec::new(),
            None,
            SettledFileActivity::default(),
        );
        let labels = rows
            .iter()
            .map(|row| row.label.as_str())
            .collect::<Vec<_>>();

        assert!(labels.contains(&"operation running"), "{labels:?}");
        assert!(!labels.contains(&"operation settled"), "{labels:?}");
        assert_eq!(
            labels
                .iter()
                .filter(|label| **label == "Keep the durable checklist visible")
                .count(),
            1,
            "one plan node must produce one Work row: {labels:?}"
        );
        assert!(
            !labels.iter().any(|label| label.starts_with("To-do")),
            "the ordered Work projection must not add a duplicate To-do heading: {labels:?}"
        );
        assert!(
            labels.contains(&"Keep the durable checklist visible"),
            "{labels:?}"
        );
        assert!(
            snapshot
                .nodes
                .iter()
                .any(|node| node.title == "operation settled"),
            "projection filtering must retain the historical graph receipt"
        );
    }

    #[test]
    fn projection_keeps_durable_and_evidence_gated_terminal_operations() {
        let mut durable = operation(NodeState::Completed, "durable");
        durable.binding.as_mut().expect("binding").durable = true;
        let mut failed = operation(NodeState::Failed, "failed");
        failed.binding.as_mut().expect("binding").durable = true;
        let mut evidence_pending = operation(NodeState::Completed, "evidence-pending");
        evidence_pending.acceptance = vec![AcceptanceRequirement::EvidenceOfKind {
            kind: EvidenceKindTag::ToolRun,
        }];
        let mut snapshot = WorkGraphSnapshot::new();
        snapshot.nodes = vec![durable, failed, evidence_pending];

        let rows = graph_rows(
            &mut surface(),
            &snapshot,
            None,
            Vec::new(),
            None,
            SettledFileActivity::default(),
        );
        let labels = rows
            .iter()
            .map(|row| row.label.as_str())
            .collect::<Vec<_>>();

        for expected in [
            "operation durable",
            "operation failed",
            "operation evidence-pending",
        ] {
            assert!(labels.contains(&expected), "missing {expected}: {labels:?}");
        }
    }

    #[test]
    fn transient_failed_operation_is_recent_while_durable_failure_needs_input() {
        let transient = operation(NodeState::Failed, "shell transient");
        let mut durable = operation(NodeState::Failed, "durable");
        durable.binding.as_mut().expect("binding").durable = true;

        assert_eq!(node_bucket(&transient), WorkBucket::Recent);
        assert_eq!(node_bucket(&durable), WorkBucket::Attention);
    }

    #[test]
    fn projection_orders_attention_before_ready_and_recent() {
        let mut recent = operation(NodeState::Completed, "recent");
        recent.binding.as_mut().expect("binding").durable = true;
        let mut snapshot = WorkGraphSnapshot::new();
        snapshot.nodes = vec![
            recent,
            operation(NodeState::Ready, "ready"),
            operation(NodeState::Blocked, "blocked"),
            operation(NodeState::Active, "active"),
        ];

        let labels = graph_rows(
            &mut surface(),
            &snapshot,
            None,
            Vec::new(),
            None,
            SettledFileActivity::default(),
        )
        .into_iter()
        .map(|row| row.label)
        .collect::<Vec<_>>();

        assert_eq!(
            labels,
            [
                "Work · Needs input: operation blocked · 1 blocked",
                "operation blocked",
                "operation active",
                "operation ready",
                "operation recent",
            ]
        );
    }

    #[test]
    fn activity_targets_keep_workspace_relative_paths_and_hide_external_paths() {
        let workspace = Path::new("/workspace/project");
        assert_eq!(
            privacy_safe_path(workspace, "/workspace/project/src/lib.rs").as_deref(),
            Some("src/lib.rs")
        );
        assert_eq!(
            privacy_safe_path(workspace, "/Users/alice/private.txt"),
            None
        );
        assert_eq!(privacy_safe_path(workspace, "../private.txt"), None);
        assert_eq!(safe_pattern("needle\nsecret"), "needle secret");
    }

    #[test]
    fn settled_canonical_file_actions_keep_aggregates_and_safe_targets() {
        let mut app = test_app();
        let calls = [
            ("read", serde_json::json!({"path": "src/read.rs"})),
            ("list", serde_json::json!({"path": "src"})),
            ("search_name", serde_json::json!({"query": "lib.rs"})),
            (
                "search_content",
                serde_json::json!({"pattern": "needle\nprivate", "path": "src"}),
            ),
            (
                "write",
                serde_json::json!({"path": "src/new.rs", "content": "new\n"}),
            ),
            (
                "edit",
                serde_json::json!({
                    "path": "src/edit.rs",
                    "search": "old",
                    "replace": "new"
                }),
            ),
            (
                "patch",
                serde_json::json!({
                    "patch": "diff --git a/src/patch.rs b/src/patch.rs\n--- a/src/patch.rs\n+++ b/src/patch.rs\n@@ -1 +1 @@\n-old\n+new\n"
                }),
            ),
        ];

        for (action, payload) in calls {
            let id = format!("file-{action}");
            let mut input = payload;
            input["action"] = serde_json::json!(action);
            handle_tool_call_started(&mut app, &id, "File", &input);
            handle_tool_call_complete(&mut app, &id, "File", &Ok(ToolResult::success("ok")));
            app.flush_active_cell();
        }

        let activity = settled_file_activity(&app);
        assert_eq!(
            activity.summary,
            FileActivitySummary {
                files_read: 1,
                dirs_listed: 1,
                patterns_searched: 2,
                files_written: 3,
            }
        );
        assert_eq!(activity.read, ["src/read.rs"]);
        assert_eq!(activity.list, ["src"]);
        assert_eq!(activity.search, ["lib.rs", "needle private"]);
        assert_eq!(
            activity.write,
            ["src/new.rs", "src/edit.rs", "src/patch.rs"]
        );
    }

    #[test]
    fn multifile_receipt_counts_semantic_file_outcomes_in_work_label() {
        let mut app = test_app();
        let input = serde_json::json!({
            "action": "patch",
            "patch": "--- a/update.rs\n+++ b/update.rs\n@@ -1 +1 @@\n-old\n+new\n"
        });
        handle_tool_call_started(&mut app, "file-multi", "File", &input);
        let result = ToolResult::success("ok").with_metadata(serde_json::json!({
            "mutation": {
                "diff": "diff --git a/old.rs b/new.rs\nrename from old.rs\nrename to new.rs\n--- a/update.rs\n+++ b/update.rs\n@@ -1 +1 @@\n-old\n+new\n--- /dev/null\n+++ b/create.rs\n@@ -0,0 +1 @@\n+created\n--- a/delete.rs\n+++ /dev/null\n@@ -1 +0,0 @@\n-deleted\n",
                "files": [
                    { "path": "update.rs", "outcome": "updated" },
                    { "path": "create.rs", "outcome": "created" },
                    { "path": "delete.rs", "outcome": "deleted" }
                ],
                "renames": [{ "from": "old.rs", "to": "new.rs" }]
            }
        }));
        handle_tool_call_complete(&mut app, "file-multi", "File", &Ok(result));
        app.flush_active_cell();

        let activity = settled_file_activity(&app);
        assert_eq!(activity.summary.files_written, 4);
        let write_row = activity_rows(activity)
            .into_iter()
            .find(|row| row.row.label.starts_with("Wrote"))
            .expect("write row");
        assert_eq!(write_row.row.label, "Wrote 4 files");
        assert_eq!(
            write_row.row.detail,
            "4 files · 1 created · 1 updated · 1 deleted · 1 renamed · +2 -2"
        );
    }

    fn mutation_activity(mode: InlineDiffMode) -> SettledFileActivity {
        let result = ToolResult::success("ok").with_metadata(serde_json::json!({
            "mutation": {
                "diff": "--- /Users/alice/private.rs\n+++ /Users/alice/private.rs\n@@ -1 +1 @@\n-old\n+new\n",
                "files": [{
                    "path": "/Users/alice/private.rs",
                    "outcome": "updated"
                }],
                "renames": []
            }
        }));
        let receipt = FileMutationReceipt::from_success(Path::new("/workspace/project"), &result)
            .expect("receipt");
        SettledFileActivity {
            summary: FileActivitySummary {
                files_written: 1,
                ..FileActivitySummary::default()
            },
            write: vec!["src/public.rs".to_string()],
            mutations: vec![receipt],
            inline_diff_mode: mode,
            ..SettledFileActivity::default()
        }
    }

    fn mutation_activity_body(mode: InlineDiffMode) -> (String, String, String) {
        let row = activity_rows(mutation_activity(mode))
            .into_iter()
            .next()
            .expect("activity row")
            .row;
        let SidebarRowAction::InspectWork { body, .. } =
            row.primary_action.expect("inspect action")
        else {
            panic!("write row must open Work inspection")
        };
        (row.label, row.detail, body)
    }

    #[test]
    fn work_mutation_rows_keep_labels_privacy_and_all_inline_modes() {
        let (label, detail, full) = mutation_activity_body(InlineDiffMode::Full);
        assert_eq!(label, "Wrote 1 files");
        assert_eq!(detail, "Updated <external file> · +1 -1");
        assert!(full.contains("-old"), "{full}");
        assert!(full.contains("+new"), "{full}");
        assert!(!full.contains("alice"), "{full}");
        assert!(full.contains("exact change evidence"), "{full}");

        let (_, _, summary) = mutation_activity_body(InlineDiffMode::Summary);
        assert!(
            summary.contains("Updated <external file> · +1 -1"),
            "{summary}"
        );
        assert!(!summary.contains("-old"), "{summary}");
        assert!(!summary.contains("+new"), "{summary}");
        assert!(!summary.contains("alice"), "{summary}");

        let (_, detail, off) = mutation_activity_body(InlineDiffMode::Off);
        assert_eq!(detail, "Updated <external file>");
        assert!(off.contains("Updated <external file>"), "{off}");
        assert!(!off.contains("+1 -1"), "{off}");
        assert!(!off.contains("-old"), "{off}");
        assert!(!off.contains("alice"), "{off}");
        assert!(off.contains("exact change evidence"), "{off}");
    }

    #[test]
    fn recent_only_summary_expires_after_ttl_and_user_turn() {
        let mut recent = operation(NodeState::Completed, "recent");
        recent.binding.as_mut().expect("binding").durable = true;
        let mut snapshot = WorkGraphSnapshot::new();
        snapshot.nodes = vec![recent];

        let mut surface = surface();
        surface.set_presentation_now_ms(0);
        let rows = graph_rows(
            &mut surface,
            &snapshot,
            None,
            Vec::new(),
            None,
            SettledFileActivity::default(),
        );
        assert!(
            rows.iter().any(|row| row.id.0.starts_with("section:")),
            "recent-only should surface briefly: {rows:?}"
        );

        surface.set_presentation_now_ms(RECENT_ONLY_TTL_MS);
        let expired = graph_rows(
            &mut surface,
            &snapshot,
            None,
            Vec::new(),
            None,
            SettledFileActivity::default(),
        );
        assert!(
            expired.is_empty(),
            "recent-only must collapse after TTL: {expired:?}"
        );
        // Catalog retains durable history for inspector/history.
        assert!(
            surface
                .catalog_rows
                .iter()
                .any(|row| row.label == "operation recent"),
            "catalog must keep recent work after live expiry"
        );

        // New completion fingerprint re-surfaces once.
        let mut newer = operation(NodeState::Completed, "newer");
        newer.binding.as_mut().expect("binding").durable = true;
        snapshot.nodes.push(newer);
        surface.set_presentation_now_ms(RECENT_ONLY_TTL_MS + 10);
        let resurfaced = graph_rows(
            &mut surface,
            &snapshot,
            None,
            Vec::new(),
            None,
            SettledFileActivity::default(),
        );
        assert!(
            !resurfaced.is_empty(),
            "a new completion may surface once after expiry"
        );

        // User turn hides immediately while still recent-only.
        surface.note_user_turn_or_new_operation();
        surface.set_presentation_now_ms(RECENT_ONLY_TTL_MS + 11);
        let after_turn = graph_rows(
            &mut surface,
            &snapshot,
            None,
            Vec::new(),
            None,
            SettledFileActivity::default(),
        );
        assert!(
            after_turn.is_empty(),
            "user turn must hide recent-only immediately: {after_turn:?}"
        );
    }

    #[test]
    fn needs_input_and_ready_never_expire_with_clock() {
        let mut snapshot = WorkGraphSnapshot::new();
        snapshot.nodes = vec![
            operation(NodeState::Blocked, "blocked"),
            operation(NodeState::Ready, "ready"),
        ];
        let mut surface = surface();
        surface.set_presentation_now_ms(0);
        let _ = graph_rows(
            &mut surface,
            &snapshot,
            None,
            Vec::new(),
            None,
            SettledFileActivity::default(),
        );
        surface.set_presentation_now_ms(60_000);
        let rows = graph_rows(
            &mut surface,
            &snapshot,
            None,
            Vec::new(),
            None,
            SettledFileActivity::default(),
        );
        assert!(
            rows[0].label.starts_with("Work · Needs input:"),
            "{}",
            rows[0].label
        );
        assert!(rows.iter().any(|row| row.label == "operation blocked"));
        assert!(rows.iter().any(|row| row.label == "operation ready"));
    }

    #[test]
    fn activity_receipts_aggregate_and_expire_without_raw_payloads() {
        let activity = SettledFileActivity {
            summary: FileActivitySummary {
                files_read: 1,
                patterns_searched: 2,
                files_written: 1,
                ..FileActivitySummary::default()
            },
            read: vec!["src/lib.rs".to_string()],
            search: vec!["(?i)super_secret_pattern_xyz".to_string()],
            write: vec!["src/main.rs".to_string()],
            ..SettledFileActivity::default()
        };
        let mut surface = surface();
        surface.set_presentation_now_ms(0);
        let rows = ordered_rows(&mut surface, None, None, Vec::new(), None, activity.clone());
        let activity_row = rows
            .iter()
            .find(|row| row.id.0 == "activity:aggregate")
            .expect("aggregate activity");
        assert!(activity_row.label.contains("Read 1 files"));
        assert!(activity_row.label.contains("Searched 2 patterns"));
        assert!(!activity_row.label.contains("super_secret_pattern_xyz"));
        assert!(!activity_row.detail.contains("super_secret_pattern_xyz"));

        surface.set_presentation_now_ms(ACTIVITY_RECEIPT_TTL_MS);
        let expired = ordered_rows(&mut surface, None, None, Vec::new(), None, activity);
        assert!(
            expired.iter().all(|row| row.id.0 != "activity:aggregate"),
            "activity receipt must expire after TTL: {expired:?}"
        );
    }

    #[test]
    fn summary_subject_prefers_attention_over_active_and_ready() {
        let mut snapshot = WorkGraphSnapshot::new();
        snapshot.nodes = vec![
            operation(NodeState::Active, "running"),
            operation(NodeState::Blocked, "choose a release target"),
            operation(NodeState::Ready, "review rebuilt binary"),
        ];
        let rows = graph_rows(
            &mut surface(),
            &snapshot,
            None,
            Vec::new(),
            None,
            SettledFileActivity::default(),
        );
        assert_eq!(
            rows[0].label,
            "Work · Needs input: operation choose a release target · 1 blocked"
        );
    }
}