frame 0.1.5

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

use crossterm::event::{
    self, DisableBracketedPaste, EnableBracketedPaste, Event, KeyEventKind,
    KeyboardEnhancementFlags, PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags,
};
use crossterm::execute;
use crossterm::terminal::{
    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use ratatui::Terminal;
use ratatui::backend::CrosstermBackend;
use ratatui::text::Line;

use regex::Regex;

use crate::io::lock::FileLock;
use crate::io::project_io::{self, discover_project, load_project};
use crate::io::watcher::{FileEvent, FrameWatcher};
use crate::model::{Metadata, Project, SectionKind, Task, TaskState, Track};
use crate::parse::{parse_inbox, parse_track};

use super::input;
use super::render;
use super::theme::Theme;
use super::undo::{Operation, UndoStack};

/// Which view is currently displayed
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum View {
    /// Track view for an active track (index into active_track_ids)
    Track(usize),
    /// All tracks overview
    Tracks,
    /// Board view (kanban-style cross-track view)
    Board,
    /// Inbox
    Inbox,
    /// Recently completed tasks
    Recent,
    /// Detail view for a single task
    Detail { track_id: String, task_id: String },
    /// Project-wide search results
    Search,
}

/// Which column the cursor is in on the board view
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BoardColumn {
    Ready,
    InProgress,
    Done,
}

impl BoardColumn {
    pub fn index(self) -> usize {
        match self {
            BoardColumn::Ready => 0,
            BoardColumn::InProgress => 1,
            BoardColumn::Done => 2,
        }
    }

    pub fn from_index(i: usize) -> Self {
        match i {
            0 => BoardColumn::Ready,
            1 => BoardColumn::InProgress,
            _ => BoardColumn::Done,
        }
    }
}

/// Board filtering mode
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BoardMode {
    Cc,
    All,
}

/// A single item in a board column's flat list
#[derive(Debug, Clone)]
pub enum BoardItem {
    TrackHeader {
        track_name: String,
    },
    Task {
        track_id: String,
        task_id: String,
        title: String,
        id_display: String,
        state: TaskState,
        tags: Vec<String>,
    },
}

/// Board view state
#[derive(Debug, Clone)]
pub struct BoardState {
    pub focus_column: BoardColumn,
    /// Cursor index within each column (independent)
    pub cursor: [usize; 3],
    /// Scroll offset for each column (independent)
    pub scroll: [usize; 3],
    pub mode: BoardMode,
    /// Number of visible columns in the current layout (set by renderer)
    pub visible_columns: usize,
    /// Tasks pinned to a column during grace period after state change.
    /// Maps (track_id, task_id) → (original effective state, deadline).
    pub column_pins: Vec<BoardColumnPin>,
}

/// Keeps a task visually pinned to its current board column during the grace period
/// after a state change (e.g. Todo→Active stays in Ready column briefly).
#[derive(Debug, Clone)]
pub struct BoardColumnPin {
    pub track_id: String,
    pub task_id: String,
    /// The state to use for column placement during the grace period
    pub pinned_state: TaskState,
    pub deadline: std::time::Instant,
}

/// Regions in the detail view that can be navigated
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DetailRegion {
    Title,
    Tags,
    Added,
    Deps,
    Spec,
    Refs,
    Note,
    Subtasks,
}

impl DetailRegion {
    /// Whether this region is editable
    pub fn is_editable(self) -> bool {
        !matches!(self, DetailRegion::Added | DetailRegion::Subtasks)
    }
}

/// Source of a search result (which collection it came from)
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SearchResultKind {
    Track { track_idx: usize, track_id: String },
    Inbox { item_index: usize },
    Archive { track_id: String },
}

/// A field annotation line shown below a search result when the match is in a non-title field
#[derive(Debug, Clone)]
pub struct MatchAnnotation {
    pub field: crate::ops::search::MatchField,
    pub snippet: String,
}

/// A single search result item displayed in the Search view
#[derive(Debug, Clone)]
pub struct SearchResultItem {
    pub kind: SearchResultKind,
    pub task_id: String,
    pub title: String,
    pub state: Option<TaskState>,
    pub tags: Vec<String>,
    pub annotations: Vec<MatchAnnotation>,
    pub title_matches: bool,
    pub id_matches: bool,
}

/// Grouped project search results
#[derive(Debug, Clone)]
pub struct SearchResults {
    pub query: String,
    pub regex: Regex,
    pub items: Vec<SearchResultItem>,
    /// (start_index, label, match_count) for group headers
    pub groups: Vec<(usize, String, usize)>,
    pub cursor: usize,
    pub scroll_offset: usize,
    pub return_view: View,
}

/// Inline edit history for undo/redo within an editing session
#[derive(Debug, Clone, Default)]
pub struct EditHistory {
    /// Snapshots of (buffer, cursor_pos) — for single-line edits
    /// or (buffer, cursor_line, cursor_col) serialized as (buffer, combined) for multi-line
    entries: Vec<(String, usize, usize)>,
    /// Current position in history (points to the currently displayed state)
    position: usize,
}

impl EditHistory {
    pub fn new(initial_buffer: &str, cursor_pos: usize, cursor_line: usize) -> Self {
        EditHistory {
            entries: vec![(initial_buffer.to_string(), cursor_pos, cursor_line)],
            position: 0,
        }
    }

    /// Save a snapshot (call after each text-modifying action)
    pub fn snapshot(&mut self, buffer: &str, cursor_pos: usize, cursor_line: usize) {
        // If buffer hasn't changed, just update the cursor position in place
        // so that undo restores the most recent cursor location
        if let Some(last) = self.entries.get_mut(self.position)
            && last.0 == buffer
        {
            last.1 = cursor_pos;
            last.2 = cursor_line;
            return;
        }
        // Truncate any redo entries
        self.entries.truncate(self.position + 1);
        self.entries
            .push((buffer.to_string(), cursor_pos, cursor_line));
        self.position = self.entries.len() - 1;
    }

    /// Undo: move back in history. Returns (buffer, cursor_pos, cursor_line) or None.
    pub fn undo(&mut self) -> Option<(&str, usize, usize)> {
        if self.position > 0 {
            self.position -= 1;
            let (buf, pos, line) = &self.entries[self.position];
            Some((buf, *pos, *line))
        } else {
            None
        }
    }

    /// Redo: move forward in history. Returns (buffer, cursor_pos, cursor_line) or None.
    pub fn redo(&mut self) -> Option<(&str, usize, usize)> {
        if self.position + 1 < self.entries.len() {
            self.position += 1;
            let (buf, pos, line) = &self.entries[self.position];
            Some((buf, *pos, *line))
        } else {
            None
        }
    }
}

/// What kind of autocomplete is active
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AutocompleteKind {
    /// Tag names (from config tag_colors + existing tags in project)
    Tag,
    /// Task IDs (all task IDs across tracks)
    TaskId,
    /// File paths (walk project directory)
    FilePath,
    /// Task IDs for jump-to-task (entries are "ID  title", whole buffer is filter)
    JumpTaskId,
}

/// State for the autocomplete dropdown
#[derive(Debug, Clone)]
pub struct AutocompleteState {
    /// What kind of autocomplete entries to show
    pub kind: AutocompleteKind,
    /// All candidate entries (unfiltered)
    pub candidates: Vec<String>,
    /// Filtered entries matching current input
    pub filtered: Vec<String>,
    /// Currently selected index in filtered list
    pub selected: usize,
    /// Whether the dropdown is visible
    pub visible: bool,
}

impl AutocompleteState {
    pub fn new(kind: AutocompleteKind, candidates: Vec<String>) -> Self {
        let filtered = candidates.clone();
        AutocompleteState {
            kind,
            candidates,
            filtered,
            selected: 0,
            visible: true,
        }
    }

    /// Compute the byte offset within the edit buffer where the current completion
    /// word starts. This is the position where accepted text will be inserted,
    /// and is used to align the autocomplete popup horizontally.
    pub fn word_start_in_buffer(&self, buffer: &str) -> usize {
        match self.kind {
            AutocompleteKind::Tag => {
                // Last word starts after the last space (the word may begin with #)
                buffer.rfind(' ').map(|i| i + 1).unwrap_or(0)
            }
            AutocompleteKind::TaskId => {
                // Last entry starts after the last comma or whitespace
                buffer
                    .rfind(|c: char| c == ',' || c.is_whitespace())
                    .map(|i| {
                        // Skip any trailing whitespace after the delimiter
                        let rest = &buffer[i + 1..];
                        let trimmed = rest.len() - rest.trim_start().len();
                        i + 1 + trimmed
                    })
                    .unwrap_or(0)
            }
            AutocompleteKind::FilePath => {
                // Last entry starts after the last space
                buffer.rfind(' ').map(|i| i + 1).unwrap_or(0)
            }
            AutocompleteKind::JumpTaskId => {
                // Whole buffer is the filter text
                0
            }
        }
    }

    /// Filter candidates based on the current input fragment
    pub fn filter(&mut self, input: &str) {
        let query = input.to_lowercase();
        self.filtered = self
            .candidates
            .iter()
            .filter(|c| c.to_lowercase().contains(&query))
            .cloned()
            .collect();
        // Clamp selected
        if self.selected >= self.filtered.len() {
            self.selected = 0;
        }
    }

    /// Move selection up
    pub fn move_up(&mut self) {
        if !self.filtered.is_empty() {
            if self.selected == 0 {
                self.selected = self.filtered.len() - 1;
            } else {
                self.selected -= 1;
            }
        }
    }

    /// Move selection down
    pub fn move_down(&mut self) {
        if !self.filtered.is_empty() {
            self.selected = (self.selected + 1) % self.filtered.len();
        }
    }

    /// Get the currently selected entry
    pub fn selected_entry(&self) -> Option<&str> {
        self.filtered.get(self.selected).map(|s| s.as_str())
    }
}

/// Which view to return to when leaving the detail view
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReturnView {
    Track(usize),
    Recent,
    Board,
}

/// State for the detail view
#[derive(Debug, Clone)]
pub struct DetailState {
    /// Which region the cursor is on
    pub region: DetailRegion,
    /// Scroll offset for the detail view
    pub scroll_offset: usize,
    /// The list of regions present for the current task (computed on render)
    pub regions: Vec<DetailRegion>,
    /// View to return to on Esc
    pub return_view: ReturnView,
    /// Whether we're editing in the detail view
    pub editing: bool,
    /// For multi-line note editing: the buffer
    pub edit_buffer: String,
    /// For multi-line note editing: cursor position (line, col)
    pub edit_cursor_line: usize,
    pub edit_cursor_col: usize,
    /// Original value before editing (for cancel/undo)
    pub edit_original: String,
    /// Cursor index in flattened subtask list (when region is Subtasks)
    pub subtask_cursor: usize,
    /// Flattened subtask IDs (rebuilt on each render)
    pub flat_subtask_ids: Vec<String>,
    /// Selection anchor for multi-line editing (line, col). None = no selection.
    pub multiline_selection_anchor: Option<(usize, usize)>,
    /// Horizontal scroll offset for multi-line note editing
    pub note_h_scroll: usize,
    /// Sticky column for visual-row cursor movement (in visual-column space)
    pub sticky_col: Option<usize>,
    /// Total rendered lines (set during render, used for scroll clamping)
    pub total_lines: usize,
    /// Virtual cursor line for note view-mode scrolling (None = not scrolling)
    pub note_view_line: Option<usize>,
    /// Line index of the note header in rendered content (set during render)
    pub note_header_line: Option<usize>,
    /// Last line index belonging to note content, before subtasks (set during render)
    pub note_content_end: usize,
    /// Which regions have non-empty content (parallel to `regions`, set during render)
    pub regions_populated: Vec<bool>,
}

/// State for the triage flow (inbox item → track task)
#[derive(Debug, Clone)]
pub enum TriageStep {
    /// Step 1: selecting which track to send the item to
    SelectTrack,
    /// Step 2: selecting position within the track (t=top, b=bottom, a=after)
    SelectPosition { track_id: String },
}

/// Source of a triage/move operation
#[derive(Debug, Clone)]
pub enum TriageSource {
    /// Triaging an inbox item
    Inbox { index: usize },
    /// Cross-track move of an existing task
    CrossTrackMove {
        source_track_id: String,
        task_id: String,
    },
    /// Bulk cross-track move of selected tasks
    BulkCrossTrackMove { source_track_id: String },
}

/// State for the triage flow
#[derive(Debug, Clone)]
pub struct TriageState {
    /// Source of this triage operation
    pub source: TriageSource,
    /// Current step
    pub step: TriageStep,
    /// Screen position for the position-selection popup (set when transitioning from track selection)
    pub popup_anchor: Option<(u16, u16)>,
    /// Cursor for position selection (0=Top, 1=Bottom, 2=Cancel)
    pub position_cursor: u8,
}

/// Confirmation prompt state
#[derive(Debug, Clone)]
pub struct ConfirmState {
    pub message: String,
    pub action: ConfirmAction,
}

/// What to do when confirmation is accepted
#[derive(Debug, Clone)]
pub enum ConfirmAction {
    DeleteInboxItem { index: usize },
    ArchiveTrack { track_id: String },
    DeleteTrack { track_id: String },
    DeleteTask { track_id: String, task_id: String },
    BulkDeleteTasks { task_ids: Vec<(String, String)> },
    PruneRecovery,
    UnarchiveTrack { track_id: String },
    ImportTasks { track_id: String, file_path: String },
}

/// The kind of pending section move (grace period)
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PendingMoveKind {
    /// Task marked done in Backlog → will move to Done section
    ToDone,
    /// Task reopened from Done → will move to Backlog
    ToBacklog,
    /// Task parked in Backlog → will move to Parked section
    ToParked,
    /// Task un-parked in Parked → will move to Backlog section
    FromParked,
}

/// A pending section move with a grace period
#[derive(Debug, Clone)]
pub struct PendingMove {
    pub kind: PendingMoveKind,
    pub track_id: String,
    pub task_id: String,
    pub deadline: Instant,
    /// The task state before this pending move was created (for board view grace period)
    pub old_state: Option<TaskState>,
}

/// A pending subtask hide with a grace period (subtask stays visible briefly after being marked done)
#[derive(Debug, Clone)]
pub struct PendingSubtaskHide {
    pub track_id: String,
    pub task_id: String,
    pub deadline: Instant,
}

/// State filter for track view filtering
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StateFilter {
    Active,
    Todo,
    Blocked,
    Parked,
    /// Ready: todo or active with all deps resolved
    Ready,
}

impl StateFilter {
    /// Display name for the filter indicator
    pub fn label(self) -> &'static str {
        match self {
            StateFilter::Active => "active",
            StateFilter::Todo => "todo",
            StateFilter::Blocked => "blocked",
            StateFilter::Parked => "parked",
            StateFilter::Ready => "ready",
        }
    }
}

/// Filter state for track view (global across all tracks)
#[derive(Debug, Clone, Default)]
pub struct FilterState {
    /// State filter (at most one active at a time)
    pub state_filter: Option<StateFilter>,
    /// Tag filter (at most one tag at a time)
    pub tag_filter: Option<String>,
}

impl FilterState {
    pub fn is_active(&self) -> bool {
        self.state_filter.is_some() || self.tag_filter.is_some()
    }

    pub fn clear_all(&mut self) {
        self.state_filter = None;
        self.tag_filter = None;
    }

    pub fn clear_state(&mut self) {
        self.state_filter = None;
    }
}

/// An action that can be repeated with the `.` key
#[derive(Debug, Clone)]
pub enum RepeatableAction {
    /// Cycle state (Space)
    CycleState,
    /// Set absolute state (x=Done, b=Blocked, o=Todo, ~=Parked)
    SetState(TaskState),
    /// Tag edit: adds and removes (e.g., +cc +ready -design)
    TagEdit {
        adds: Vec<String>,
        removes: Vec<String>,
    },
    /// Dep edit: adds and removes (e.g., +EFF-014 -EFF-003)
    DepEdit {
        adds: Vec<String>,
        removes: Vec<String>,
    },
    /// Toggle cc tag
    ToggleCcTag,
    /// Enter edit mode on a region (e=Title, t=Tags, @=Refs, d=Deps, n=Note)
    EnterEdit(RepeatEditRegion),
}

/// Which region to re-enter edit mode for (used by RepeatableAction::EnterEdit)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RepeatEditRegion {
    Title,
    Tags,
    Deps,
    Refs,
    Note,
}

/// A single entry in the dep popup's flattened display list
#[derive(Debug, Clone)]
pub enum DepPopupEntry {
    /// Section header ("Blocked by" or "Blocking")
    SectionHeader { label: &'static str },
    /// A dependency task entry
    Task {
        task_id: String,
        title: String,
        state: Option<TaskState>,
        track_id: Option<String>,
        /// Depth in the expand tree (0 = direct dep, 1 = dep's dep, etc.)
        depth: usize,
        /// Whether this entry has children that can be expanded
        has_children: bool,
        is_expanded: bool,
        /// True if this is a circular reference
        is_circular: bool,
        /// True if the task ID was not found in any track
        is_dangling: bool,
        /// True if this is in the "Blocked by" section (vs "Blocking")
        is_upstream: bool,
    },
    /// "(nothing)" placeholder for empty sections
    Nothing,
}

/// State for the dep popup overlay
#[derive(Debug, Clone)]
pub struct DepPopupState {
    /// The root task ID whose deps we're showing
    pub root_task_id: String,
    /// Track ID of the root task
    pub root_track_id: String,
    /// Flattened entries for display
    pub entries: Vec<DepPopupEntry>,
    /// Cursor index into entries (skips section headers)
    pub cursor: usize,
    /// Scroll offset
    pub scroll_offset: usize,
    /// Set of expanded entry keys (task_id + upstream/downstream)
    pub expanded: HashSet<String>,
    /// Set of task IDs visited during expansion (for cycle detection)
    pub visited: HashSet<String>,
    /// Inverse dep index: task_id -> list of task_ids that depend on it
    pub inverse_deps: HashMap<String, Vec<String>>,
}

/// Fixed color palette for tag color assignment
pub const TAG_COLOR_PALETTE: &[(&str, &str)] = &[
    ("red", "#FF4444"),
    ("yellow", "#FFD700"),
    ("green", "#44FF88"),
    ("cyan", "#44DDFF"),
    ("blue", "#4488FF"),
    ("purple", "#CC66FF"),
    ("pink", "#FB4196"),
    ("white", "#FFFFFF"),
    ("dim", "#5A5580"),
    ("text", "#A09BFE"),
];

/// State for the tag color editor popup
#[derive(Debug, Clone)]
pub struct TagColorPopupState {
    /// Sorted list of (tag_name, current_hex_color_or_none)
    pub tags: Vec<(String, Option<String>)>,
    /// Cursor index into the tag list
    pub cursor: usize,
    /// Scroll offset for long lists
    pub scroll_offset: usize,
    /// Whether the palette picker is open on the current tag
    pub picker_open: bool,
    /// Selected swatch index in the palette (0..PALETTE.len())
    pub picker_cursor: usize,
}

/// State for the prefix rename flow (edit → confirm → execute)
#[derive(Debug, Clone)]
pub struct PrefixRenameState {
    /// Track being renamed
    pub track_id: String,
    /// Track display name (for the confirmation popup)
    pub track_name: String,
    /// Current (old) prefix
    pub old_prefix: String,
    /// New prefix being entered
    pub new_prefix: String,
    /// Whether we're in the confirmation step (true) or still editing (false)
    pub confirming: bool,
    /// Blast radius counts (populated when entering confirmation)
    pub task_id_count: usize,
    pub dep_ref_count: usize,
    pub affected_track_count: usize,
    /// Validation error message (empty when valid)
    pub validation_error: String,
}

/// State for the project picker popup
#[derive(Debug, Clone)]
pub struct ProjectPickerState {
    /// List of project entries
    pub entries: Vec<crate::io::registry::ProjectEntry>,
    /// Cursor index
    pub cursor: usize,
    /// Scroll offset
    pub scroll_offset: usize,
    /// Sort mode: true = alphabetical, false = recent (default)
    pub sort_alpha: bool,
    /// Path of the currently open project (if any)
    pub current_project_path: Option<String>,
    /// Entry pending removal confirmation
    pub confirm_remove: Option<usize>,
}

impl ProjectPickerState {
    pub fn new(
        mut entries: Vec<crate::io::registry::ProjectEntry>,
        current_path: Option<String>,
    ) -> Self {
        // Default: sort by last_accessed_tui, most recent first
        entries.sort_by(|a, b| {
            let ta = a.last_accessed_tui.unwrap_or_default();
            let tb = b.last_accessed_tui.unwrap_or_default();
            tb.cmp(&ta)
        });
        Self {
            entries,
            cursor: 0,
            scroll_offset: 0,
            sort_alpha: false,
            current_project_path: current_path,
            confirm_remove: None,
        }
    }

    pub fn move_up(&mut self) {
        if !self.entries.is_empty() {
            if self.cursor == 0 {
                self.cursor = self.entries.len() - 1;
            } else {
                self.cursor -= 1;
            }
        }
        self.confirm_remove = None;
    }

    pub fn move_down(&mut self) {
        if !self.entries.is_empty() {
            self.cursor = (self.cursor + 1) % self.entries.len();
        }
        self.confirm_remove = None;
    }

    pub fn selected_entry(&self) -> Option<&crate::io::registry::ProjectEntry> {
        self.entries.get(self.cursor)
    }

    pub fn toggle_sort(&mut self) {
        self.sort_alpha = !self.sort_alpha;
        if self.sort_alpha {
            self.entries
                .sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
        } else {
            self.entries.sort_by(|a, b| {
                let ta = a.last_accessed_tui.unwrap_or_default();
                let tb = b.last_accessed_tui.unwrap_or_default();
                tb.cmp(&ta)
            });
        }
        self.cursor = 0;
        self.scroll_offset = 0;
        self.confirm_remove = None;
    }

    pub fn remove_selected(&mut self) {
        if self.entries.is_empty() {
            return;
        }
        // If already confirming this index, do the removal
        if self.confirm_remove == Some(self.cursor) {
            let entry = &self.entries[self.cursor];
            crate::io::registry::remove_by_path(&entry.path);
            self.entries.remove(self.cursor);
            if self.cursor >= self.entries.len() && self.cursor > 0 {
                self.cursor -= 1;
            }
            self.confirm_remove = None;
        } else {
            self.confirm_remove = Some(self.cursor);
        }
    }
}

/// Current interaction mode
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Mode {
    Navigate,
    Search,
    /// Inline title editing (for new tasks or editing existing)
    Edit,
    /// Task/track reordering mode
    Move,
    /// Triage mode (inbox → track)
    Triage,
    /// Confirmation prompt (e.g., delete inbox item)
    Confirm,
    /// Multi-select mode for bulk operations (track view only)
    Select,
    /// Command palette mode (fuzzy action launcher)
    Command,
}

/// What kind of edit operation is in progress
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EditTarget {
    /// Creating a new task (title edit). Stores the assigned task ID and track_id.
    /// `parent_id` is Some for subtasks.
    NewTask {
        task_id: String,
        track_id: String,
        parent_id: Option<String>,
    },
    /// Editing an existing task's title
    ExistingTitle {
        task_id: String,
        track_id: String,
        original_title: String,
    },
    /// Editing an existing task's tags (inline from track view)
    ExistingTags {
        task_id: String,
        track_id: String,
        original_tags: String,
    },
    /// Creating a new inbox item (title edit)
    NewInboxItem {
        /// Index where the placeholder was inserted
        index: usize,
    },
    /// Editing an existing inbox item's title
    ExistingInboxTitle {
        index: usize,
        original_title: String,
    },
    /// Editing an existing inbox item's tags
    ExistingInboxTags { index: usize, original_tags: String },
    /// Creating a new track (name edit in Tracks view)
    NewTrackName,
    /// Editing an existing track's name (in Tracks view)
    ExistingTrackName {
        track_id: String,
        original_name: String,
    },
    /// Selecting a tag for filter (using autocomplete)
    FilterTag,
    /// Bulk tag edit in SELECT mode (+tag -tag syntax)
    BulkTags,
    /// Bulk dep edit in SELECT mode (+ID -ID syntax)
    BulkDeps,
    /// Jump-to-task prompt (J key)
    JumpTo,
    /// Editing a track's prefix (P key in Tracks view)
    ExistingPrefix {
        track_id: String,
        original_prefix: String,
    },
    /// Import file path prompt (from palette)
    ImportFilePath { track_id: String },
}

/// State for MOVE mode
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MoveState {
    /// Moving a task within a track's backlog (supports reparenting)
    Task {
        track_id: String,
        task_id: String,
        original_parent_id: Option<String>,
        original_section: SectionKind,
        original_sibling_index: usize,
        original_depth: usize,
        /// Expand keys that were force-expanded to keep the moving task visible.
        /// These are removed from the expanded set when the task moves away or
        /// when the move is confirmed/cancelled.
        force_expanded: HashSet<String>,
    },
    /// Moving an active track in the tracks list
    Track {
        track_id: String,
        original_index: usize,
    },
    /// Moving an inbox item
    InboxItem { original_index: usize },
    /// Bulk move of selected tasks within a track
    BulkTask {
        track_id: String,
        /// The removed tasks with their original backlog indices, in original order
        removed_tasks: Vec<(usize, Task)>,
        /// Current insertion point index in the (reduced) backlog
        insert_pos: usize,
    },
}

/// Per-track UI state (cursor, scroll, expand/collapse)
#[derive(Debug, Clone, Default)]
pub struct TrackViewState {
    /// Cursor index into the flat visible items list
    pub cursor: usize,
    /// Scroll offset (first visible row)
    pub scroll_offset: usize,
    /// Set of expanded task IDs (or synthetic keys for tasks without IDs)
    pub expanded: HashSet<String>,
}

/// A flattened item in the track view's visible list
#[derive(Debug, Clone)]
pub enum FlatItem {
    /// A task from a specific section
    Task {
        section: SectionKind,
        /// Path through the task tree: indices at each nesting level
        path: Vec<usize>,
        depth: usize,
        has_children: bool,
        is_expanded: bool,
        is_last_sibling: bool,
        /// For building tree continuation lines: whether each ancestor is the last sibling
        ancestor_last: Vec<bool>,
        /// True if this task is shown only as ancestor context for a matching descendant
        /// (dimmed, non-selectable, cursor skips over it)
        is_context: bool,
    },
    /// The "── Parked ──" separator
    ParkedSeparator,
    /// Stand-in row during bulk move showing "━━━ N tasks ━━━"
    BulkMoveStandin { count: usize },
    /// Summary row showing "X/Y done" for hidden done subtasks
    DoneSummary {
        depth: usize,
        done_count: usize,
        total_count: usize,
        ancestor_last: Vec<bool>,
    },
}

/// Main application state
pub struct App {
    pub project: Project,
    pub view: View,
    pub mode: Mode,
    pub should_quit: bool,
    /// Set to true after a project switch so the event loop can reinitialize the file watcher
    pub watcher_needs_restart: bool,
    pub theme: Theme,
    /// IDs of active tracks (in display order)
    pub active_track_ids: Vec<String>,
    /// Per-track view state
    pub track_states: HashMap<String, TrackViewState>,
    /// Cursor for tracks view
    pub tracks_cursor: usize,
    /// Minimum name column width for tracks view (prevents columns shifting left mid-session)
    pub tracks_name_col_min: usize,
    /// Cursor for inbox view
    pub inbox_cursor: usize,
    /// Cursor for recent view
    pub recent_cursor: usize,
    /// Scroll offset for inbox view
    pub inbox_scroll: usize,
    /// Index of inbox item whose note is being edited (None when not editing)
    pub inbox_note_index: Option<usize>,
    /// Scroll offset for the inline note editor in inbox view
    pub inbox_note_editor_scroll: usize,
    /// Scroll offset for recent view
    pub recent_scroll: usize,
    /// Help overlay visible
    pub show_help: bool,
    /// Scroll offset for help overlay
    pub help_scroll: usize,
    /// Search mode: current query being typed
    pub search_input: String,
    /// Last executed search pattern
    pub last_search: Option<String>,
    /// Current search match index (for n/N cycling)
    pub search_match_idx: usize,
    /// Search history (most recent first, max 200)
    pub search_history: Vec<String>,
    /// Current position in search history (None = new/draft, Some(0) = most recent, etc.)
    pub search_history_index: Option<usize>,
    /// Draft search text (preserved while browsing history)
    pub search_draft: String,
    /// Wrap-around message shown after n/N wraps (cleared on next n/N or Esc)
    pub search_wrap_message: Option<String>,
    /// Number of matches for the current search pattern in the current view
    pub search_match_count: Option<usize>,
    /// True when user hit Enter with 0 matches (for red background highlight)
    pub search_zero_confirmed: bool,
    /// True after first Q press; second Q quits
    pub quit_pending: bool,
    /// Transient centered status message (cleared on next keypress)
    pub status_message: Option<String>,
    /// If true, status_message renders with error style (bright text on red bg)
    pub status_is_error: bool,
    /// Consecutive Esc presses in Navigate mode (shows quit hint at 5+)
    pub esc_streak: u8,
    /// Edit mode: text buffer for inline editing
    pub edit_buffer: String,
    /// Edit mode: cursor position within the buffer
    pub edit_cursor: usize,
    /// Edit mode: what is being edited
    pub edit_target: Option<EditTarget>,
    /// Saved cursor position to restore on edit cancel (for new task inserts)
    pub pre_edit_cursor: Option<usize>,
    /// Move mode state
    pub move_state: Option<MoveState>,
    /// Undo/redo stack (session-only, not persisted)
    pub undo_stack: UndoStack,
    /// Pending external file reload paths (queued while in EDIT/MOVE mode)
    pub pending_reload_paths: Vec<PathBuf>,
    /// Conflict text shown when external change conflicts with in-progress edit
    pub conflict_text: Option<String>,
    /// Timestamp of last save we performed (used to ignore our own write notifications)
    pub last_save_at: Option<Instant>,
    /// Last-known mtime for each track file (keyed by track_id)
    pub track_mtimes: HashMap<String, SystemTime>,
    /// Detail view state
    pub detail_state: Option<DetailState>,
    /// Stack of (track_id, task_id) for parent breadcrumbs when drilling into subtasks
    pub detail_stack: Vec<(String, String)>,
    /// Autocomplete state (active during EDIT mode for certain fields)
    pub autocomplete: Option<AutocompleteState>,
    /// Screen position (x, y) where the edit text area starts, used to anchor autocomplete dropdown
    pub autocomplete_anchor: Option<(u16, u16)>,
    /// Inline edit history for undo/redo within an editing session
    pub edit_history: Option<EditHistory>,
    /// Selection anchor for text selection in edit mode (None = no selection)
    /// Selection range is from min(anchor, edit_cursor) to max(anchor, edit_cursor)
    pub edit_selection_anchor: Option<usize>,
    /// True when in edit mode for a new subtask and no character has been typed yet.
    /// Used to detect `-` as first keystroke for outdent behavior.
    pub edit_is_fresh: bool,
    /// Desired position (among active tracks) for new track insertion.
    /// Set by tracks_add_track / tracks_prepend / tracks_insert_after;
    /// consumed by the NewTrackName confirm handler.
    pub new_track_insert_pos: Option<usize>,
    /// Triage flow state (active during Mode::Triage)
    pub triage_state: Option<TriageState>,
    /// Confirmation prompt state (active during Mode::Confirm)
    pub confirm_state: Option<ConfirmState>,
    /// State color for current flash (None = undo yellow-orange default)
    pub flash_state: Option<TaskState>,
    /// Task ID to flash-highlight after undo/redo navigation
    pub flash_task_id: Option<String>,
    /// Multiple task IDs to flash (for bulk undo)
    pub flash_task_ids: HashSet<String>,
    /// Track ID to flash-highlight in tracks view after undo/redo
    pub flash_track_id: Option<String>,
    /// Detail region to flash (for field edit undo — flashes the specific region, not header)
    pub flash_detail_region: Option<DetailRegion>,
    /// When the flash started (for auto-clearing after timeout)
    pub flash_started: Option<Instant>,
    /// Pending section moves (grace period before moving tasks between sections)
    pub pending_moves: Vec<PendingMove>,
    /// Pending subtask hides (grace period before hiding done subtasks)
    pub pending_subtask_hides: Vec<PendingSubtaskHide>,
    /// Expanded task IDs in the Recent view (for tree structure)
    pub recent_expanded: HashSet<String>,
    /// Global filter state for track views (not persisted)
    pub filter_state: FilterState,
    /// True when 'f' prefix key has been pressed, waiting for second key
    pub filter_pending: bool,
    /// Selected task IDs in SELECT mode (empty = not in select mode)
    pub selection: HashSet<String>,
    /// Anchor flat-item index for V range select preview (None = not in range select mode)
    pub range_anchor: Option<usize>,
    /// Last repeatable action for `.` key (persists across tab switches)
    pub last_action: Option<RepeatableAction>,
    /// Command palette state (active during Mode::Command)
    pub command_palette: Option<super::command_actions::CommandPaletteState>,
    /// Dep popup state (overlay showing dependency relationships)
    pub dep_popup: Option<DepPopupState>,
    /// Tag color editor popup state
    pub tag_color_popup: Option<TagColorPopupState>,
    /// Prefix rename state (active during prefix rename flow)
    pub prefix_rename: Option<PrefixRenameState>,
    /// Project picker popup state
    pub project_picker: Option<ProjectPickerState>,
    /// Debug mode: show raw KeyEvent info in status row
    pub key_debug: bool,
    /// Last raw KeyEvent description (for debug display)
    pub last_key_event: Option<String>,
    /// Whether Kitty keyboard protocol is active
    pub kitty_enabled: bool,
    /// Horizontal scroll offset for single-line edit (character-based)
    pub edit_h_scroll: usize,
    /// Available width for edit field (set during render, read during input)
    pub last_edit_available_width: u16,
    /// Tab bar scroll offset: index of first visible track tab when in scroll mode
    pub tab_scroll: usize,
    /// Show startup hints in status bar until first real keypress
    pub show_startup_hints: bool,
    /// Effective note wrap setting (override > config > true)
    pub note_wrap: bool,
    /// Recovery notification message (shown in status bar)
    pub recovery_message: Option<String>,
    /// When the recovery message was set
    pub recovery_message_at: Option<Instant>,
    /// Whether to show the recovery log overlay
    pub show_recovery_log: bool,
    /// Scroll offset for recovery log overlay
    pub recovery_log_scroll: usize,
    /// Cached recovery log lines for overlay display
    pub recovery_log_lines: Vec<String>,
    /// Total visual line count after wrapping (set by renderer)
    pub recovery_log_wrapped_count: usize,
    /// For each logical line, the visual line offset where it starts (set by renderer)
    pub recovery_log_line_offsets: Vec<usize>,

    /// Whether the results overlay is visible
    pub show_results_overlay: bool,
    /// Title for the results overlay
    pub results_overlay_title: String,
    /// Styled lines for the results overlay
    pub results_overlay_lines: Vec<Line<'static>>,
    /// Scroll offset for the results overlay
    pub results_overlay_scroll: usize,

    /// Project-wide search results (active when in View::Search or after jumping from it)
    pub project_search_results: Option<SearchResults>,
    /// History of project search queries (most recent first, max 200)
    pub project_search_history: Vec<String>,
    /// Current project search input text
    pub project_search_input: String,
    /// Position in project search history (None = new/draft)
    pub project_search_history_index: Option<usize>,
    /// Draft project search text (preserved while browsing history)
    pub project_search_draft: String,
    /// When true, Mode::Search is routed to project search handler instead of view search
    pub project_search_active: bool,
    /// Board view state
    pub board_state: BoardState,
}

impl App {
    pub fn new(project: Project) -> Self {
        let active_track_ids: Vec<String> = project
            .config
            .tracks
            .iter()
            .filter(|t| t.state == "active")
            .map(|t| t.id.clone())
            .collect();

        let theme = Theme::from_config(&project.config.ui);
        let note_wrap = project.config.ui.note_wrap;

        let initial_view = if active_track_ids.is_empty() {
            View::Tracks
        } else {
            View::Track(0)
        };

        // Record initial mtimes for all track files
        let mut track_mtimes = HashMap::new();
        for tc in &project.config.tracks {
            let path = project.frame_dir.join(&tc.file);
            if let Ok(meta) = std::fs::metadata(&path)
                && let Ok(mtime) = meta.modified()
            {
                track_mtimes.insert(tc.id.clone(), mtime);
            }
        }

        // Initialize track states with default expand for first task
        let mut track_states = HashMap::new();
        for track_id in &active_track_ids {
            let mut state = TrackViewState::default();
            // Expand first task by default
            if let Some(track) = Self::find_track_in_project(&project, track_id) {
                let backlog = track.backlog();
                if let Some(first) = backlog.first() {
                    let key = task_expand_key(first, SectionKind::Backlog, &[0]);
                    state.expanded.insert(key);
                }
            }
            track_states.insert(track_id.clone(), state);
        }

        App {
            project,
            view: initial_view,
            mode: Mode::Navigate,
            should_quit: false,
            watcher_needs_restart: false,
            theme,
            active_track_ids,
            track_states,
            tracks_cursor: 0,
            tracks_name_col_min: 0,
            inbox_cursor: 0,
            recent_cursor: 0,
            inbox_scroll: 0,
            inbox_note_index: None,
            inbox_note_editor_scroll: 0,
            recent_scroll: 0,
            show_help: false,
            help_scroll: 0,
            search_input: String::new(),
            last_search: None,
            search_match_idx: 0,
            search_history: Vec::new(),
            search_history_index: None,
            search_draft: String::new(),
            search_wrap_message: None,
            search_match_count: None,
            search_zero_confirmed: false,
            quit_pending: false,
            status_message: None,
            status_is_error: false,
            esc_streak: 0,
            edit_buffer: String::new(),
            edit_cursor: 0,
            edit_target: None,
            pre_edit_cursor: None,
            move_state: None,
            undo_stack: UndoStack::new(),
            pending_reload_paths: Vec::new(),
            conflict_text: None,
            last_save_at: None,
            track_mtimes,
            detail_state: None,
            detail_stack: Vec::new(),
            autocomplete: None,
            autocomplete_anchor: None,
            edit_history: None,
            edit_selection_anchor: None,
            edit_is_fresh: false,
            new_track_insert_pos: None,
            triage_state: None,
            confirm_state: None,
            flash_state: None,
            flash_task_id: None,
            flash_task_ids: HashSet::new(),
            flash_track_id: None,
            flash_detail_region: None,
            flash_started: None,
            pending_moves: Vec::new(),
            pending_subtask_hides: Vec::new(),
            recent_expanded: HashSet::new(),
            filter_state: FilterState::default(),
            filter_pending: false,
            selection: HashSet::new(),
            range_anchor: None,
            last_action: None,
            command_palette: None,
            dep_popup: None,
            tag_color_popup: None,
            prefix_rename: None,
            project_picker: None,
            key_debug: false,
            last_key_event: None,
            kitty_enabled: false,
            edit_h_scroll: 0,
            last_edit_available_width: 0,
            tab_scroll: 0,
            show_startup_hints: true,
            note_wrap,
            recovery_message: None,
            recovery_message_at: None,
            show_recovery_log: false,
            recovery_log_scroll: 0,
            recovery_log_lines: Vec::new(),
            recovery_log_wrapped_count: 0,
            recovery_log_line_offsets: Vec::new(),
            show_results_overlay: false,
            results_overlay_title: String::new(),
            results_overlay_lines: Vec::new(),
            results_overlay_scroll: 0,
            project_search_results: None,
            project_search_history: Vec::new(),
            project_search_input: String::new(),
            project_search_history_index: None,
            project_search_draft: String::new(),
            project_search_active: false,
            board_state: BoardState {
                focus_column: BoardColumn::Ready,
                cursor: [0; 3],
                scroll: [0; 3],
                mode: BoardMode::Cc,
                visible_columns: 3,
                column_pins: Vec::new(),
            },
        }
    }

    pub fn find_track_in_project<'a>(project: &'a Project, track_id: &str) -> Option<&'a Track> {
        project
            .tracks
            .iter()
            .find(|(id, _)| id == track_id)
            .map(|(_, track)| track)
    }

    /// Get the display name for a track by its ID
    pub fn track_name<'a>(&'a self, track_id: &'a str) -> &'a str {
        self.project
            .config
            .tracks
            .iter()
            .find(|t| t.id == track_id)
            .map(|t| t.name.as_str())
            .unwrap_or(track_id)
    }

    /// Count inbox items
    pub fn inbox_count(&self) -> usize {
        self.project
            .inbox
            .as_ref()
            .map_or(0, |inbox| inbox.items.len())
    }

    /// Build the three board columns: [Ready, InProgress, Done]
    pub fn build_board_columns(&self) -> [Vec<BoardItem>; 3] {
        let cc_mode = self.board_state.mode == BoardMode::Cc;
        let tag_filter = self.filter_state.tag_filter.as_deref();
        let done_days = self.project.config.ui.board_done_days;

        let mut ready: Vec<BoardItem> = Vec::new();
        let mut in_progress: Vec<BoardItem> = Vec::new();
        let mut done_items: Vec<(String, BoardItem)> = Vec::new(); // (resolved_date, item)

        for track_id in &self.active_track_ids {
            let track = match Self::find_track_in_project(&self.project, track_id) {
                Some(t) => t,
                None => continue,
            };
            let track_name = self.track_name(track_id).to_string();
            let prefix = self
                .project
                .config
                .ids
                .prefixes
                .get(track_id.as_str())
                .cloned()
                .unwrap_or_default();

            let mut has_ready = false;
            let mut has_active = false;

            for task in track.backlog() {
                // Skip subtasks — board shows top-level only
                let task_id = match &task.id {
                    Some(id) => id.clone(),
                    None => continue,
                };

                let id_display = if prefix.is_empty() {
                    task_id.clone()
                } else {
                    format!("{}-{}", prefix, task_id)
                };

                // Apply tag filter
                if let Some(tf) = tag_filter
                    && !task.tags.iter().any(|t| t == tf)
                {
                    continue;
                }

                // Check if this task has a column pin (board grace period) or
                // a pending section move. Either keeps the task in its original column.
                let pin = self
                    .board_state
                    .column_pins
                    .iter()
                    .find(|p| p.track_id == *track_id && p.task_id == task_id);

                let pending_move = self
                    .pending_moves
                    .iter()
                    .find(|pm| pm.track_id == *track_id && pm.task_id == task_id);

                let effective_state = if let Some(p) = pin {
                    p.pinned_state
                } else {
                    match pending_move {
                        Some(pm)
                            if matches!(
                                pm.kind,
                                PendingMoveKind::ToDone | PendingMoveKind::ToParked
                            ) =>
                        {
                            pm.old_state.unwrap_or(task.state)
                        }
                        _ => task.state,
                    }
                };

                match effective_state {
                    TaskState::Todo => {
                        // Check all deps resolved (skip for pending-move tasks, they were already shown)
                        if pin.is_none() && pending_move.is_none() && !self.all_deps_resolved(task)
                        {
                            continue;
                        }
                        // CC mode filter
                        if cc_mode && !task.tags.iter().any(|t| t == "cc") {
                            continue;
                        }
                        if !has_ready {
                            ready.push(BoardItem::TrackHeader {
                                track_name: track_name.clone(),
                            });
                            has_ready = true;
                        }
                        ready.push(BoardItem::Task {
                            track_id: track_id.clone(),
                            task_id: task_id.clone(),
                            title: task.title.clone(),
                            id_display,
                            state: task.state,
                            tags: task.tags.clone(),
                        });
                    }
                    TaskState::Active => {
                        if cc_mode && !task.tags.iter().any(|t| t == "cc") {
                            continue;
                        }
                        if !has_active {
                            in_progress.push(BoardItem::TrackHeader {
                                track_name: track_name.clone(),
                            });
                            has_active = true;
                        }
                        in_progress.push(BoardItem::Task {
                            track_id: track_id.clone(),
                            task_id: task_id.clone(),
                            title: task.title.clone(),
                            id_display,
                            state: task.state,
                            tags: task.tags.clone(),
                        });
                    }
                    _ => {}
                }
            }

            // Collect done tasks from the Done section
            if done_days > 0 {
                for task in track.section_tasks(SectionKind::Done) {
                    let task_id = match &task.id {
                        Some(id) => id.clone(),
                        None => continue,
                    };

                    // Check for a pending reopen (PendingMove::ToBacklog) — task was
                    // reopened but the section move hasn't fired yet (grace period).
                    let pending_reopen = self.pending_moves.iter().any(|pm| {
                        pm.kind == PendingMoveKind::ToBacklog
                            && pm.track_id == *track_id
                            && pm.task_id == task_id
                    });

                    if task.state != TaskState::Done && !pending_reopen {
                        continue;
                    }

                    // Apply tag filter
                    if let Some(tf) = tag_filter
                        && !task.tags.iter().any(|t| t == tf)
                    {
                        continue;
                    }

                    // CC mode: require #cc or #cc-added
                    if cc_mode && !task.tags.iter().any(|t| t == "cc" || t == "cc-added") {
                        continue;
                    }

                    // Check resolved date within done_days
                    let resolved_date = task.metadata.iter().find_map(|m| {
                        if let Metadata::Resolved(d) = m {
                            Some(d.clone())
                        } else {
                            None
                        }
                    });

                    let resolved_str = match &resolved_date {
                        Some(d) => d.clone(),
                        None => continue,
                    };

                    if !self.is_within_done_days(&resolved_str, done_days) {
                        continue;
                    }

                    let id_display = if prefix.is_empty() {
                        task_id.clone()
                    } else {
                        format!("{}-{}", prefix, task_id)
                    };

                    done_items.push((
                        resolved_str,
                        BoardItem::Task {
                            track_id: track_id.clone(),
                            task_id,
                            title: task.title.clone(),
                            id_display,
                            state: task.state,
                            tags: task.tags.clone(),
                        },
                    ));
                }
            }
        }

        // Sort done items by resolved date descending
        done_items.sort_by(|a, b| b.0.cmp(&a.0));
        let done: Vec<BoardItem> = done_items.into_iter().map(|(_, item)| item).collect();

        [ready, in_progress, done]
    }

    /// Check if all dependency targets of a task are done
    fn all_deps_resolved(&self, task: &Task) -> bool {
        for meta in &task.metadata {
            if let Metadata::Dep(deps) = meta {
                for dep_id in deps {
                    // Search all tracks for this dep
                    let mut found_done = false;
                    for (_, track) in &self.project.tracks {
                        if let Some(dep_task) =
                            crate::ops::task_ops::find_task_in_track(track, dep_id)
                        {
                            if dep_task.state == TaskState::Done {
                                found_done = true;
                            }
                            break;
                        }
                    }
                    if !found_done {
                        return false;
                    }
                }
            }
        }
        true
    }

    /// Check if a resolved date string is within the last N days
    fn is_within_done_days(&self, date_str: &str, days: u32) -> bool {
        let resolved = match chrono::NaiveDate::parse_from_str(date_str, "%Y-%m-%d") {
            Ok(d) => d,
            Err(_) => return false,
        };
        let today = chrono::Local::now().date_naive();
        let cutoff = today - chrono::Duration::days(i64::from(days));
        resolved >= cutoff
    }

    /// Get the (track_id, task_id) at the current board cursor position
    pub fn board_cursor_task_id(&self) -> Option<(String, String)> {
        let col_idx = self.board_state.focus_column.index();
        let columns = self.build_board_columns();
        let column = &columns[col_idx];
        let cursor = self.board_state.cursor[col_idx];
        match column.get(cursor) {
            Some(BoardItem::Task {
                track_id, task_id, ..
            }) => Some((track_id.clone(), task_id.clone())),
            _ => None,
        }
    }

    /// Count selectable tasks (excludes headers) in a board column
    pub fn board_task_count(&self, columns: &[Vec<BoardItem>], col: BoardColumn) -> usize {
        columns[col.index()]
            .iter()
            .filter(|item| matches!(item, BoardItem::Task { .. }))
            .count()
    }

    /// Get the selection range (start, end) for the single-line edit buffer, if any.
    /// Returns (start, end) where start <= end.
    pub fn edit_selection_range(&self) -> Option<(usize, usize)> {
        let anchor = self.edit_selection_anchor?;
        let cursor = self.edit_cursor;
        Some((anchor.min(cursor), anchor.max(cursor)))
    }

    /// Delete the selected text and return the cursor to the start of selection.
    /// Returns true if there was a selection to delete.
    pub fn delete_selection(&mut self) -> bool {
        if let Some((start, end)) = self.edit_selection_range()
            && start != end
        {
            self.edit_buffer.drain(start..end);
            self.edit_cursor = start;
            self.edit_selection_anchor = None;
            return true;
        }
        self.edit_selection_anchor = None;
        false
    }

    /// Get the selected text in single-line edit mode (if any).
    pub fn get_selection_text(&self) -> Option<String> {
        let (start, end) = self.edit_selection_range()?;
        if start == end {
            return None;
        }
        Some(self.edit_buffer[start..end].to_string())
    }

    /// Toggle note wrap on/off and persist the override to state
    pub fn toggle_note_wrap(&mut self) {
        self.note_wrap = !self.note_wrap;
    }

    /// Start flashing a task (highlight after undo/redo navigation)
    pub fn flash_task(&mut self, task_id: &str) {
        self.flash_task_id = Some(task_id.to_string());
        self.flash_task_ids.clear();
        self.flash_track_id = None;
        self.flash_detail_region = None;
        self.flash_started = Some(Instant::now());
    }

    /// Start flashing multiple tasks (for bulk undo)
    pub fn flash_tasks(&mut self, task_ids: HashSet<String>) {
        self.flash_task_id = None;
        self.flash_task_ids = task_ids;
        self.flash_track_id = None;
        self.flash_started = Some(Instant::now());
    }

    /// Start flashing a track row in tracks view
    pub fn flash_track(&mut self, track_id: &str) {
        self.flash_track_id = Some(track_id.to_string());
        self.flash_task_id = None;
        self.flash_task_ids.clear();
        self.flash_started = Some(Instant::now());
    }

    /// Check if a specific task is currently flashing
    pub fn is_flashing(&self, task_id: &str) -> bool {
        if let Some(started) = self.flash_started {
            if started.elapsed() >= Duration::from_millis(300) {
                return false;
            }
            if self.flash_task_id.as_deref() == Some(task_id) {
                return true;
            }
            if self.flash_task_ids.contains(task_id) {
                return true;
            }
        }
        false
    }

    /// Check if a specific track is currently flashing (tracks view)
    pub fn is_track_flashing(&self, track_id: &str) -> bool {
        if let (Some(flash_id), Some(started)) = (&self.flash_track_id, self.flash_started) {
            flash_id == track_id && started.elapsed() < Duration::from_millis(300)
        } else {
            false
        }
    }

    /// Clear flash if the timeout has expired
    pub fn clear_expired_flash(&mut self) {
        if let Some(started) = self.flash_started
            && started.elapsed() >= Duration::from_millis(300)
        {
            self.flash_state = None;
            self.flash_task_id = None;
            self.flash_task_ids.clear();
            self.flash_track_id = None;
            self.flash_detail_region = None;
            self.flash_started = None;
        }
    }

    /// Check if a task has a pending move
    pub fn has_pending_move(&self, track_id: &str, task_id: &str) -> bool {
        self.pending_moves
            .iter()
            .any(|pm| pm.track_id == track_id && pm.task_id == task_id)
    }

    /// Cancel a pending move for a task. Returns the cancelled move if found.
    pub fn cancel_pending_move(&mut self, track_id: &str, task_id: &str) -> Option<PendingMove> {
        let idx = self
            .pending_moves
            .iter()
            .position(|pm| pm.track_id == track_id && pm.task_id == task_id)?;
        Some(self.pending_moves.remove(idx))
    }

    /// Execute a single pending move. Returns the track_id that was modified.
    fn execute_pending_move(&mut self, pm: &PendingMove) -> Option<String> {
        use crate::ops::task_ops::move_task_between_sections;
        let track = self.find_track_mut(&pm.track_id)?;
        match pm.kind {
            PendingMoveKind::ToDone => {
                let source_index = move_task_between_sections(
                    track,
                    &pm.task_id,
                    SectionKind::Backlog,
                    SectionKind::Done,
                )?;
                // Push SectionMove undo entry
                self.undo_stack.push(Operation::SectionMove {
                    track_id: pm.track_id.clone(),
                    task_id: pm.task_id.clone(),
                    from_section: SectionKind::Backlog,
                    to_section: SectionKind::Done,
                    from_index: source_index,
                });
                Some(pm.track_id.clone())
            }
            PendingMoveKind::ToBacklog => {
                // For reopen flush: move from Done to Backlog top
                // No extra undo entry — the existing Reopen operation handles full reversal
                move_task_between_sections(
                    track,
                    &pm.task_id,
                    SectionKind::Done,
                    SectionKind::Backlog,
                )?;
                // Now remove the resolved date (kept during grace period for sort stability)
                let track = self.find_track_mut(&pm.track_id)?;
                let task = crate::ops::task_ops::find_task_mut_in_track(track, &pm.task_id)?;
                task.metadata.retain(|m| m.key() != "resolved");
                task.mark_dirty();
                Some(pm.track_id.clone())
            }
            PendingMoveKind::ToParked => {
                let source_index = move_task_between_sections(
                    track,
                    &pm.task_id,
                    SectionKind::Backlog,
                    SectionKind::Parked,
                )?;
                self.undo_stack.push(Operation::SectionMove {
                    track_id: pm.track_id.clone(),
                    task_id: pm.task_id.clone(),
                    from_section: SectionKind::Backlog,
                    to_section: SectionKind::Parked,
                    from_index: source_index,
                });
                Some(pm.track_id.clone())
            }
            PendingMoveKind::FromParked => {
                // Un-park flush: move from Parked to Backlog top
                // No extra undo entry — the StateChange undo handles reversal
                move_task_between_sections(
                    track,
                    &pm.task_id,
                    SectionKind::Parked,
                    SectionKind::Backlog,
                )?;
                Some(pm.track_id.clone())
            }
        }
    }

    /// Cancel a pending subtask hide for a specific task.
    pub fn cancel_pending_subtask_hide(&mut self, track_id: &str, task_id: &str) {
        self.pending_subtask_hides
            .retain(|ph| ph.track_id != track_id || ph.task_id != task_id);
    }

    /// Flush expired subtask hides (remove entries past deadline — purely visual, no file save).
    pub fn flush_expired_subtask_hides(&mut self) {
        let now = Instant::now();
        self.pending_subtask_hides.retain(|ph| now < ph.deadline);
    }

    /// Reset all subtask hide deadlines (called on every keypress).
    pub fn reset_pending_subtask_hide_deadlines(&mut self) {
        let new_deadline = Instant::now() + std::time::Duration::from_secs(5);
        for ph in &mut self.pending_subtask_hides {
            ph.deadline = new_deadline;
        }
    }

    /// Reset the deadline on all pending moves (called on every keypress to keep
    /// tasks visible while the user is interacting).
    pub fn reset_pending_move_deadlines(&mut self) {
        let new_deadline = Instant::now() + std::time::Duration::from_secs(5);
        for pm in &mut self.pending_moves {
            pm.deadline = new_deadline;
        }
    }

    /// Flush all pending moves whose deadline has expired. Returns modified track IDs.
    pub fn flush_expired_pending_moves(&mut self) -> Vec<String> {
        let now = Instant::now();
        let expired: Vec<PendingMove> = self
            .pending_moves
            .iter()
            .filter(|pm| now >= pm.deadline)
            .cloned()
            .collect();
        self.pending_moves.retain(|pm| now < pm.deadline);
        // Collect expiring column pins so we can flash tasks that move columns
        let expiring_pins: Vec<String> = self
            .board_state
            .column_pins
            .iter()
            .filter(|p| now >= p.deadline)
            .map(|p| p.task_id.clone())
            .collect();
        self.board_state.column_pins.retain(|p| now < p.deadline);
        if !expiring_pins.is_empty() {
            let ids: std::collections::HashSet<String> = expiring_pins.into_iter().collect();
            self.flash_tasks(ids);
        }

        // Flash tasks that are about to move columns via pending moves
        let moving_task_ids: std::collections::HashSet<String> = expired
            .iter()
            .filter(|pm| matches!(pm.kind, PendingMoveKind::ToBacklog))
            .map(|pm| pm.task_id.clone())
            .collect();

        let mut modified = Vec::new();
        for pm in &expired {
            if let Some(tid) = self.execute_pending_move(pm)
                && !modified.contains(&tid)
            {
                modified.push(tid);
            }
        }

        if !moving_task_ids.is_empty() {
            self.flash_tasks(moving_task_ids);
        }

        modified
    }

    /// Flush all pending moves immediately (used on view change, quit). Returns modified track IDs.
    pub fn flush_all_pending_moves(&mut self) -> Vec<String> {
        let all: Vec<PendingMove> = std::mem::take(&mut self.pending_moves);
        self.board_state.column_pins.clear();
        let mut modified = Vec::new();
        for pm in &all {
            if let Some(tid) = self.execute_pending_move(pm)
                && !modified.contains(&tid)
            {
                modified.push(tid);
            }
        }
        modified
    }

    /// Open the tag color editor popup
    pub fn open_tag_color_popup(&mut self) {
        let tag_names = self.collect_all_tags();
        let tags: Vec<(String, Option<String>)> = tag_names
            .into_iter()
            .map(|tag| {
                // Check config first (explicit user setting), then theme defaults
                let hex = self
                    .project
                    .config
                    .ui
                    .tag_colors
                    .get(&tag)
                    .cloned()
                    .or_else(|| {
                        self.theme.tag_colors.get(&tag).and_then(|color| {
                            if let ratatui::style::Color::Rgb(r, g, b) = color {
                                Some(format!("#{:02X}{:02X}{:02X}", r, g, b))
                            } else {
                                None
                            }
                        })
                    });
                (tag, hex)
            })
            .collect();
        self.tag_color_popup = Some(TagColorPopupState {
            tags,
            cursor: 0,
            scroll_offset: 0,
            picker_open: false,
            picker_cursor: 0,
        });
    }

    /// Collect all unique tags from config tag_colors + all tasks in the project
    pub fn collect_all_tags(&self) -> Vec<String> {
        let mut tags: HashSet<String> = HashSet::new();

        // Tags from config tag_colors keys
        for key in self.project.config.ui.tag_colors.keys() {
            tags.insert(key.clone());
        }

        // Tags from theme tag_colors (includes hardcoded defaults like 'cc')
        for key in self.theme.tag_colors.keys() {
            tags.insert(key.clone());
        }

        // Tags from UI default_tags
        for tag in &self.project.config.ui.default_tags {
            tags.insert(tag.clone());
        }

        // Tags from all tasks across all tracks
        for (_, track) in &self.project.tracks {
            Self::collect_tags_from_tasks(track.backlog(), &mut tags);
            Self::collect_tags_from_tasks(track.parked(), &mut tags);
            Self::collect_tags_from_tasks(track.done(), &mut tags);
        }

        // Tags from inbox items
        if let Some(inbox) = &self.project.inbox {
            for item in &inbox.items {
                for tag in &item.tags {
                    tags.insert(tag.clone());
                }
            }
        }

        let mut sorted: Vec<String> = tags.into_iter().collect();
        sorted.sort();
        sorted
    }

    fn collect_tags_from_tasks(tasks: &[Task], tags: &mut HashSet<String>) {
        for task in tasks {
            for tag in &task.tags {
                tags.insert(tag.clone());
            }
            Self::collect_tags_from_tasks(&task.subtasks, tags);
        }
    }

    /// Collect all task IDs across all tracks
    pub fn collect_all_task_ids(&self) -> Vec<String> {
        let mut ids: Vec<String> = Vec::new();
        for (_, track) in &self.project.tracks {
            Self::collect_ids_from_tasks(track.backlog(), &mut ids);
            Self::collect_ids_from_tasks(track.parked(), &mut ids);
            Self::collect_ids_from_tasks(track.done(), &mut ids);
        }
        ids.sort();
        ids
    }

    fn collect_ids_from_tasks(tasks: &[Task], ids: &mut Vec<String>) {
        for task in tasks {
            if let Some(ref id) = task.id {
                ids.push(id.clone());
            }
            Self::collect_ids_from_tasks(&task.subtasks, ids);
        }
    }

    /// Collect all task IDs across active tracks only (for jump-to-task).
    /// Each entry is "ID  title" for display in autocomplete.
    pub fn collect_active_track_task_ids(&self) -> Vec<String> {
        let mut entries: Vec<String> = Vec::new();
        for track_id in &self.active_track_ids {
            if let Some(track) = Self::find_track_in_project(&self.project, track_id) {
                Self::collect_id_title_from_tasks(track.backlog(), &mut entries);
                Self::collect_id_title_from_tasks(track.parked(), &mut entries);
                Self::collect_id_title_from_tasks(track.done(), &mut entries);
            }
        }
        entries.sort();
        entries
    }

    fn collect_id_title_from_tasks(tasks: &[Task], entries: &mut Vec<String>) {
        for task in tasks {
            if let Some(ref id) = task.id {
                entries.push(format!("{}  {}", id, task.title));
            }
            Self::collect_id_title_from_tasks(&task.subtasks, entries);
        }
    }

    /// Collect file paths from the project directory (for ref/spec autocomplete).
    /// Scoped to `ref_paths` dirs if configured; filters to `ref_extensions` if set;
    /// always excludes directories.
    pub fn collect_file_paths(&self) -> Vec<String> {
        let mut paths: Vec<String> = Vec::new();
        let frame_dir = &self.project.frame_dir;
        let project_root = frame_dir.parent().unwrap_or(frame_dir);
        let extensions = &self.project.config.ui.ref_extensions;
        let ref_paths = &self.project.config.ui.ref_paths;

        if ref_paths.is_empty() {
            Self::walk_dir_for_paths(project_root, project_root, &mut paths, 3, extensions);
        } else {
            for rp in ref_paths {
                let dir = project_root.join(rp);
                if dir.is_dir() {
                    Self::walk_dir_for_paths(project_root, &dir, &mut paths, 3, extensions);
                }
            }
        }
        paths.sort();
        paths
    }

    fn walk_dir_for_paths(
        base: &std::path::Path,
        dir: &std::path::Path,
        paths: &mut Vec<String>,
        max_depth: usize,
        extensions: &[String],
    ) {
        if max_depth == 0 {
            return;
        }
        let entries = match std::fs::read_dir(dir) {
            Ok(e) => e,
            Err(_) => return,
        };
        for entry in entries.flatten() {
            let path = entry.path();
            let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");

            // Skip hidden dirs/files, node_modules, target, .git
            if name.starts_with('.') || name == "node_modules" || name == "target" {
                continue;
            }

            if path.is_dir() {
                Self::walk_dir_for_paths(base, &path, paths, max_depth - 1, extensions);
            } else if path.is_file() {
                // Filter by extension if ref_extensions is configured
                if !extensions.is_empty() {
                    let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
                    if !extensions.iter().any(|e| e.eq_ignore_ascii_case(ext)) {
                        continue;
                    }
                }
                if let Ok(rel) = path.strip_prefix(base) {
                    paths.push(rel.to_string_lossy().to_string());
                }
            }
        }
    }

    /// Get the active search regex for highlighting.
    /// In Search mode: compiles from current input. In Navigate: compiles from last_search.
    pub fn active_search_re(&self) -> Option<Regex> {
        let pattern = match &self.mode {
            Mode::Search if !self.search_input.is_empty() => self.search_input.as_str(),
            Mode::Navigate => self.last_search.as_deref()?,
            _ => return None,
        };
        Regex::new(&format!("(?i){}", pattern))
            .or_else(|_| Regex::new(&format!("(?i){}", regex::escape(pattern))))
            .ok()
    }

    /// Get the currently active track ID (if in track view)
    pub fn current_track_id(&self) -> Option<&str> {
        match &self.view {
            View::Track(idx) => self.active_track_ids.get(*idx).map(|s| s.as_str()),
            _ => None,
        }
    }

    /// Get the track for the current view
    pub fn current_track(&self) -> Option<&Track> {
        let track_id = self.current_track_id()?;
        Self::find_track_in_project(&self.project, track_id)
    }

    /// Get or create the TrackViewState for a track
    pub fn get_track_state(&mut self, track_id: &str) -> &mut TrackViewState {
        if !self.track_states.contains_key(track_id) {
            self.track_states
                .insert(track_id.to_string(), TrackViewState::default());
        }
        self.track_states.get_mut(track_id).unwrap()
    }

    /// Find which active track contains a given task ID.
    /// Returns the track_id if found.
    pub fn find_task_track_id(&self, task_id: &str) -> Option<String> {
        for track_id in &self.active_track_ids {
            if let Some(track) = Self::find_track_in_project(&self.project, track_id)
                && crate::ops::task_ops::find_task_in_track(track, task_id).is_some()
            {
                return Some(track_id.clone());
            }
        }
        None
    }

    /// Jump to a task by ID: switch track if needed, expand parent chain, move cursor.
    /// Returns true if the jump succeeded.
    pub fn jump_to_task(&mut self, task_id: &str) -> bool {
        let target_track_id = match self.find_task_track_id(task_id) {
            Some(id) => id,
            None => return false,
        };

        // Switch to the target track's tab
        let track_idx = match self
            .active_track_ids
            .iter()
            .position(|id| id == &target_track_id)
        {
            Some(idx) => idx,
            None => return false,
        };
        self.close_detail_fully();
        self.view = View::Track(track_idx);

        // Expand parent chain: for "EFF-014.2.1", expand "EFF-014" and "EFF-014.2"
        self.expand_parent_chain(&target_track_id, task_id);

        // Build flat items and find the target task
        let flat_items = self.build_flat_items(&target_track_id);
        let track = match Self::find_track_in_project(&self.project, &target_track_id) {
            Some(t) => t,
            None => return false,
        };
        for (i, item) in flat_items.iter().enumerate() {
            if let FlatItem::Task { section, path, .. } = item
                && let Some(task) = resolve_task_from_flat(track, *section, path)
                && task.id.as_deref() == Some(task_id)
            {
                let state = self.get_track_state(&target_track_id);
                state.cursor = i;
                return true;
            }
        }
        false
    }

    /// Expand the parent chain for a task ID so it becomes visible in the flat list.
    /// For "EFF-014.2.1", expands "EFF-014" and "EFF-014.2".
    fn expand_parent_chain(&mut self, track_id: &str, task_id: &str) {
        // Walk up the ID hierarchy: "A.B.C" → expand "A" then "A.B"
        let parts: Vec<&str> = task_id.split('.').collect();
        if parts.len() <= 1 {
            return; // top-level task, nothing to expand
        }

        // Collect ancestor IDs that exist in the track
        let mut ancestors_to_expand = Vec::new();
        if let Some(track) = Self::find_track_in_project(&self.project, track_id) {
            for i in 1..parts.len() {
                let ancestor_id = parts[..i].join(".");
                if crate::ops::task_ops::find_task_in_track(track, &ancestor_id).is_some() {
                    ancestors_to_expand.push(ancestor_id);
                }
            }
        }

        // Now expand them (separate borrow)
        let state = self.get_track_state(track_id);
        for ancestor_id in ancestors_to_expand {
            state.expanded.insert(ancestor_id);
        }
    }

    /// Build the inverse dependency index: for each task ID, which tasks depend on it.
    pub fn build_dep_index(project: &Project) -> HashMap<String, Vec<String>> {
        let mut index: HashMap<String, Vec<String>> = HashMap::new();
        for (_, track) in &project.tracks {
            for node in &track.nodes {
                if let crate::model::TrackNode::Section { tasks, .. } = node {
                    Self::collect_deps_recursive(tasks, &mut index);
                }
            }
        }
        index
    }

    fn collect_deps_recursive(tasks: &[Task], index: &mut HashMap<String, Vec<String>>) {
        for task in tasks {
            if let Some(task_id) = &task.id {
                for m in &task.metadata {
                    if let Metadata::Dep(deps) = m {
                        for dep_id in deps {
                            index
                                .entry(dep_id.clone())
                                .or_default()
                                .push(task_id.clone());
                        }
                    }
                }
            }
            Self::collect_deps_recursive(&task.subtasks, index);
        }
    }

    /// Open the dep popup for a given task
    pub fn open_dep_popup(&mut self, track_id: &str, task_id: &str) {
        let inverse_deps = Self::build_dep_index(&self.project);
        let mut state = DepPopupState {
            root_task_id: task_id.to_string(),
            root_track_id: track_id.to_string(),
            entries: Vec::new(),
            cursor: 0,
            scroll_offset: 0,
            expanded: HashSet::new(),
            visited: HashSet::new(),
            inverse_deps,
        };
        // Build the entry list
        self.rebuild_dep_popup_entries(&mut state);
        // Set initial cursor to first selectable entry
        state.cursor = state
            .entries
            .iter()
            .position(|e| matches!(e, DepPopupEntry::Task { .. }))
            .unwrap_or(0);
        self.dep_popup = Some(state);
    }

    /// Rebuild the flattened entry list for the dep popup.
    /// Called on open and after expand/collapse.
    pub fn rebuild_dep_popup_entries(&self, state: &mut DepPopupState) {
        let task_id = state.root_task_id.clone();
        state.entries.clear();

        // Gather direct upstream deps (what this task depends on)
        let mut upstream_ids: Vec<String> = Vec::new();
        for (_, track) in &self.project.tracks {
            if let Some(task) = crate::ops::task_ops::find_task_in_track(track, &task_id) {
                for m in &task.metadata {
                    if let Metadata::Dep(deps) = m {
                        upstream_ids.extend(deps.iter().cloned());
                    }
                }
                break;
            }
        }

        // Gather direct downstream deps (what this task blocks)
        let downstream_ids: Vec<String> = state
            .inverse_deps
            .get(&task_id)
            .cloned()
            .unwrap_or_default();

        // Auto-expand logic: 1-2 entries → expand one level, 3+ → collapsed
        let auto_expand_upstream = upstream_ids.len() <= 2;
        let auto_expand_downstream = downstream_ids.len() <= 2;
        if state.expanded.is_empty() {
            // Only auto-expand on initial open
            if auto_expand_upstream {
                for id in &upstream_ids {
                    state.expanded.insert(format!("up:{}", id));
                }
            }
            if auto_expand_downstream {
                for id in &downstream_ids {
                    state.expanded.insert(format!("down:{}", id));
                }
            }
        }

        // "Blocked by" section
        state.entries.push(DepPopupEntry::SectionHeader {
            label: "Blocked by",
        });
        if upstream_ids.is_empty() {
            state.entries.push(DepPopupEntry::Nothing);
        } else {
            for dep_id in &upstream_ids {
                let mut visited = HashSet::new();
                visited.insert(task_id.to_string());
                self.add_dep_entry(state, dep_id, 0, true, &mut visited);
            }
        }

        // "Blocking" section
        state
            .entries
            .push(DepPopupEntry::SectionHeader { label: "Blocking" });
        if downstream_ids.is_empty() {
            state.entries.push(DepPopupEntry::Nothing);
        } else {
            for dep_id in &downstream_ids {
                let mut visited = HashSet::new();
                visited.insert(task_id.to_string());
                self.add_dep_entry(state, dep_id, 0, false, &mut visited);
            }
        }
    }

    /// Add a single dep entry and its expanded children recursively
    fn add_dep_entry(
        &self,
        state: &mut DepPopupState,
        dep_id: &str,
        depth: usize,
        is_upstream: bool,
        visited: &mut HashSet<String>,
    ) {
        // Cycle detection
        if visited.contains(dep_id) {
            state.entries.push(DepPopupEntry::Task {
                task_id: dep_id.to_string(),
                title: String::new(),
                state: None,
                track_id: None,
                depth,
                has_children: false,
                is_expanded: false,
                is_circular: true,
                is_dangling: false,
                is_upstream,
            });
            return;
        }

        // Find the task across all tracks
        let mut found_task: Option<(&str, &Task)> = None;
        for (tid, track) in &self.project.tracks {
            if let Some(task) = crate::ops::task_ops::find_task_in_track(track, dep_id) {
                found_task = Some((tid.as_str(), task));
                break;
            }
        }

        if let Some((found_track_id, task)) = found_task {
            // Determine if this entry has children (further deps to explore)
            let children_ids = if is_upstream {
                // In "Blocked by": children are what this dep itself depends on
                let mut ids = Vec::new();
                for m in &task.metadata {
                    if let Metadata::Dep(deps) = m {
                        ids.extend(deps.iter().cloned());
                    }
                }
                ids
            } else {
                // In "Blocking": children are what this dep is also blocking
                state.inverse_deps.get(dep_id).cloned().unwrap_or_default()
            };
            let has_children = !children_ids.is_empty();

            let expand_key = format!("{}:{}", if is_upstream { "up" } else { "down" }, dep_id);
            let is_expanded = state.expanded.contains(&expand_key);

            state.entries.push(DepPopupEntry::Task {
                task_id: dep_id.to_string(),
                title: task.title.clone(),
                state: Some(task.state),
                track_id: Some(found_track_id.to_string()),
                depth,
                has_children,
                is_expanded,
                is_circular: false,
                is_dangling: false,
                is_upstream,
            });

            // Recurse into expanded children
            if is_expanded && has_children {
                visited.insert(dep_id.to_string());
                for child_id in &children_ids {
                    self.add_dep_entry(state, child_id, depth + 1, is_upstream, visited);
                }
                visited.remove(dep_id);
            }
        } else {
            // Dangling reference
            state.entries.push(DepPopupEntry::Task {
                task_id: dep_id.to_string(),
                title: String::new(),
                state: None,
                track_id: None,
                depth,
                has_children: false,
                is_expanded: false,
                is_circular: false,
                is_dangling: true,
                is_upstream,
            });
        }
    }

    /// Get the ID prefix for a track (e.g., "EFF" for "effects")
    pub fn track_prefix(&self, track_id: &str) -> Option<&str> {
        self.project
            .config
            .ids
            .prefixes
            .get(track_id)
            .map(|s| s.as_str())
    }

    /// Get the file path for a track (relative to frame_dir)
    pub fn track_file(&self, track_id: &str) -> Option<&str> {
        self.project
            .config
            .tracks
            .iter()
            .find(|tc| tc.id == track_id)
            .map(|tc| tc.file.as_str())
    }

    /// Find a mutable track reference by ID
    pub fn find_track_mut(&mut self, track_id: &str) -> Option<&mut Track> {
        self.project
            .tracks
            .iter_mut()
            .find(|(id, _)| id == track_id)
            .map(|(_, track)| track)
    }

    /// Read and parse a single track file from disk, updating stored mtime.
    pub fn read_track_from_disk(&mut self, track_id: &str) -> Option<Track> {
        let file = self.track_file(track_id)?;
        let path = self.project.frame_dir.join(file);
        let meta = std::fs::metadata(&path).ok()?;
        let text = std::fs::read_to_string(&path).ok()?;
        if let Ok(mtime) = meta.modified() {
            self.track_mtimes.insert(track_id.to_string(), mtime);
        }
        Some(parse_track(&text))
    }

    /// Replace a track's in-memory data.
    pub fn replace_track(&mut self, track_id: &str, new_track: Track) {
        if let Some(entry) = self
            .project
            .tracks
            .iter_mut()
            .find(|(id, _)| id == track_id)
        {
            entry.1 = new_track;
        }
    }

    /// Check if the track file on disk has been modified since we last loaded/saved it.
    pub fn track_changed_on_disk(&self, track_id: &str) -> bool {
        let file = match self.track_file(track_id) {
            Some(f) => f,
            None => return false,
        };
        let path = self.project.frame_dir.join(file);
        let disk_mtime = match std::fs::metadata(&path).and_then(|m| m.modified()) {
            Ok(t) => t,
            Err(_) => return false,
        };
        match self.track_mtimes.get(track_id) {
            Some(known) => disk_mtime > *known,
            None => true, // no recorded mtime — treat as changed
        }
    }

    /// Show a save error as a status message, if any.
    pub fn show_save_error(&mut self, result: Result<(), Box<dyn std::error::Error>>) {
        if let Err(e) = result {
            self.status_message = Some(format!("Save error: {}", e));
        }
    }

    /// Save the inbox to disk with file locking. Records save time.
    pub fn save_inbox(&mut self) -> Result<(), Box<dyn std::error::Error>> {
        let inbox = self.project.inbox.as_ref().ok_or("no inbox loaded")?;
        let _lock = FileLock::acquire_default(&self.project.frame_dir)?;
        project_io::save_inbox(&self.project.frame_dir, inbox)?;
        self.last_save_at = Some(Instant::now());
        Ok(())
    }

    /// Save a track to disk with file locking. Records save time and mtime.
    pub fn save_track(&mut self, track_id: &str) -> Result<(), Box<dyn std::error::Error>> {
        let file = self
            .track_file(track_id)
            .ok_or("track not found")?
            .to_string();
        let track =
            Self::find_track_in_project(&self.project, track_id).ok_or("track not found")?;
        let _lock = FileLock::acquire_default(&self.project.frame_dir)?;
        project_io::save_track(&self.project.frame_dir, &file, track)?;
        self.last_save_at = Some(Instant::now());
        // Record the new mtime so we know this is our write
        let path = self.project.frame_dir.join(&file);
        if let Ok(mtime) = std::fs::metadata(&path).and_then(|m| m.modified()) {
            self.track_mtimes.insert(track_id.to_string(), mtime);
        }
        Ok(())
    }

    /// Save track, logging to recovery on failure and setting status message.
    pub fn save_track_logged(&mut self, track_id: &str) {
        if let Err(e) = self.save_track(track_id) {
            crate::io::recovery::log_recovery(
                &self.project.frame_dir,
                crate::io::recovery::RecoveryEntry {
                    timestamp: chrono::Utc::now(),
                    category: crate::io::recovery::RecoveryCategory::Write,
                    description: format!("track save failed: {}", track_id),
                    fields: vec![("Error".to_string(), e.to_string())],
                    body: String::new(),
                },
            );
            self.recovery_message = Some(format!("Save failed for {}: {}", track_id, e));
            self.recovery_message_at = Some(Instant::now());
        }
    }

    /// Save inbox, logging to recovery on failure and setting status message.
    pub fn save_inbox_logged(&mut self) {
        if let Err(e) = self.save_inbox() {
            crate::io::recovery::log_recovery(
                &self.project.frame_dir,
                crate::io::recovery::RecoveryEntry {
                    timestamp: chrono::Utc::now(),
                    category: crate::io::recovery::RecoveryCategory::Write,
                    description: "inbox save failed".to_string(),
                    fields: vec![("Error".to_string(), e.to_string())],
                    body: String::new(),
                },
            );
            self.recovery_message = Some(format!("Inbox save failed: {}", e));
            self.recovery_message_at = Some(Instant::now());
        }
    }

    /// Resolve the task ID from the current cursor position in a track view.
    /// Returns (track_id, task_id, section) if the cursor is on a task.
    pub fn cursor_task_id(&self) -> Option<(String, String, SectionKind)> {
        let track_id = self.current_track_id()?.to_string();
        let flat_items = self.build_flat_items(&track_id);
        let cursor = self.track_states.get(&track_id).map_or(0, |s| s.cursor);
        let item = flat_items.get(cursor)?;

        if let FlatItem::Task { section, path, .. } = item {
            let track = Self::find_track_in_project(&self.project, &track_id)?;
            let task = resolve_task_from_flat(track, *section, path)?;
            let task_id = task.id.clone()?;
            Some((track_id, task_id, *section))
        } else {
            None
        }
    }

    /// Reload changed files from disk. Returns the edit target's task_id if it was externally modified.
    pub fn reload_changed_files(&mut self, paths: &[std::path::PathBuf]) -> Option<String> {
        let mut edited_task_conflict = None;

        // Determine which task is being edited (if any)
        let editing_task_id = match &self.edit_target {
            Some(EditTarget::NewTask { task_id, .. })
            | Some(EditTarget::ExistingTitle { task_id, .. })
            | Some(EditTarget::ExistingTags { task_id, .. }) => Some(task_id.clone()),
            _ => None,
        };
        let editing_track_id = match &self.edit_target {
            Some(EditTarget::NewTask { track_id, .. })
            | Some(EditTarget::ExistingTitle { track_id, .. })
            | Some(EditTarget::ExistingTags { track_id, .. }) => Some(track_id.clone()),
            _ => None,
        };

        for path in paths {
            let file_name = match path.file_name().and_then(|n| n.to_str()) {
                Some(name) => name.to_string(),
                None => continue,
            };

            // Compute relative path from frame_dir to distinguish files in
            // subdirectories (e.g., archive/main.md vs tracks/main.md).
            let rel_path = path
                .strip_prefix(&self.project.frame_dir)
                .ok()
                .and_then(|p| p.to_str())
                .map(|s| s.to_string());

            if is_inbox_path(&file_name, rel_path.as_deref()) {
                if let Ok(text) = std::fs::read_to_string(path) {
                    let (inbox, dropped) = parse_inbox(&text);
                    if !dropped.is_empty() {
                        crate::io::recovery::log_recovery(
                            &self.project.frame_dir,
                            crate::io::recovery::RecoveryEntry {
                                timestamp: chrono::Utc::now(),
                                category: crate::io::recovery::RecoveryCategory::Parser,
                                description: "dropped lines".to_string(),
                                fields: vec![("Source".to_string(), "inbox.md".to_string())],
                                body: dropped.join("\n"),
                            },
                        );
                    }
                    self.project.inbox = Some(inbox);
                }
                continue;
            }

            if file_name == "project.toml" {
                // Config changes — skip for now (would need full re-init)
                continue;
            }
            if let Some((track_id, _track_file)) =
                resolve_track_for_path(&self.project.config.tracks, &file_name, rel_path.as_deref())
                && let Ok(text) = std::fs::read_to_string(path)
            {
                let new_track = parse_track(&text);

                // Check if the edited task was modified externally
                if editing_track_id.as_deref() == Some(&track_id)
                    && let Some(ref edit_task_id) = editing_task_id
                {
                    // Check if the task exists in the new track and has different content
                    if let Some(old_track) = Self::find_track_in_project(&self.project, &track_id) {
                        let old_task =
                            crate::ops::task_ops::find_task_in_track(old_track, edit_task_id);
                        let new_task =
                            crate::ops::task_ops::find_task_in_track(&new_track, edit_task_id);

                        match (old_task, new_task) {
                            (Some(old), Some(new)) if old.title != new.title => {
                                // Task was modified externally — conflict
                                edited_task_conflict = Some(edit_task_id.clone());
                            }
                            (Some(_), None) => {
                                // Task was removed externally — conflict
                                edited_task_conflict = Some(edit_task_id.clone());
                            }
                            _ => {}
                        }
                    }
                }

                // Replace the track data and update mtime
                if let Some(entry) = self
                    .project
                    .tracks
                    .iter_mut()
                    .find(|(id, _)| id == &track_id)
                {
                    entry.1 = new_track;
                }
                if let Ok(mtime) = std::fs::metadata(path).and_then(|m| m.modified()) {
                    self.track_mtimes.insert(track_id, mtime);
                }
            }
        }

        // Auto-assign IDs and dates to any newly-loaded tasks
        let modified_tracks = crate::ops::clean::ensure_ids_and_dates(&mut self.project);
        for track_id in &modified_tracks {
            let _ = self.save_track(track_id);
        }

        // Push sync marker to undo stack
        self.undo_stack.push_sync_marker();

        edited_task_conflict
    }

    /// Build the list of regions present for a task (for detail view navigation)
    pub fn build_detail_regions(task: &Task) -> Vec<DetailRegion> {
        use crate::model::Metadata;
        let mut regions = vec![DetailRegion::Title];

        // Tags region always present (can add tags even if none exist)
        regions.push(DetailRegion::Tags);

        // Added date
        if task
            .metadata
            .iter()
            .any(|m| matches!(m, Metadata::Added(_)))
        {
            regions.push(DetailRegion::Added);
        }

        // Deps
        regions.push(DetailRegion::Deps);

        // Spec
        regions.push(DetailRegion::Spec);

        // Refs
        regions.push(DetailRegion::Refs);

        // Note
        regions.push(DetailRegion::Note);

        // Subtasks
        if !task.subtasks.is_empty() {
            regions.push(DetailRegion::Subtasks);
        }

        regions
    }

    /// Check if a detail region has non-empty content for the given task
    pub fn is_detail_region_populated(task: &Task, region: DetailRegion) -> bool {
        use crate::model::Metadata;
        match region {
            DetailRegion::Title => true,
            DetailRegion::Tags => !task.tags.is_empty(),
            DetailRegion::Added => true, // only in regions list if present
            DetailRegion::Subtasks => true, // only in regions list if present
            DetailRegion::Deps => task
                .metadata
                .iter()
                .any(|m| matches!(m, Metadata::Dep(v) if !v.is_empty())),
            DetailRegion::Spec => task.metadata.iter().any(|m| matches!(m, Metadata::Spec(_))),
            DetailRegion::Refs => task
                .metadata
                .iter()
                .any(|m| matches!(m, Metadata::Ref(v) if !v.is_empty())),
            DetailRegion::Note => task
                .metadata
                .iter()
                .any(|m| matches!(m, Metadata::Note(s) if !s.is_empty())),
        }
    }

    /// Close detail view fully: clear state and stack
    pub fn close_detail_fully(&mut self) {
        self.detail_state = None;
        self.detail_stack.clear();
    }

    /// Open the detail view for a task
    pub fn open_detail(&mut self, track_id: String, task_id: String) {
        // If already in detail view, push current onto stack for back-navigation
        let return_view = if let View::Detail {
            track_id: ref cur_track,
            task_id: ref cur_task,
        } = self.view
        {
            self.detail_stack
                .push((cur_track.clone(), cur_task.clone()));
            // Preserve the return_view from current detail state
            self.detail_state
                .as_ref()
                .map(|ds| ds.return_view.clone())
                .unwrap_or(ReturnView::Track(0))
        } else {
            match &self.view {
                View::Track(idx) => ReturnView::Track(*idx),
                View::Recent => ReturnView::Recent,
                View::Board => ReturnView::Board,
                _ => ReturnView::Track(0),
            }
        };

        // Build initial regions from the task
        let regions = if let Some(track) = Self::find_track_in_project(&self.project, &track_id) {
            if let Some(task) = crate::ops::task_ops::find_task_in_track(track, &task_id) {
                Self::build_detail_regions(task)
            } else {
                vec![DetailRegion::Title]
            }
        } else {
            vec![DetailRegion::Title]
        };

        let initial_region = regions.first().copied().unwrap_or(DetailRegion::Title);

        self.detail_state = Some(DetailState {
            region: initial_region,
            scroll_offset: 0,
            regions,
            return_view,
            editing: false,
            edit_buffer: String::new(),
            edit_cursor_line: 0,
            edit_cursor_col: 0,
            edit_original: String::new(),
            subtask_cursor: 0,
            flat_subtask_ids: Vec::new(),
            multiline_selection_anchor: None,
            note_h_scroll: 0,
            sticky_col: None,
            total_lines: 0,
            note_view_line: None,
            note_header_line: None,
            note_content_end: 0,
            regions_populated: Vec::new(),
        });
        self.view = View::Detail { track_id, task_id };
    }

    /// Build the flat list of visible items for a track view
    pub fn build_flat_items(&self, track_id: &str) -> Vec<FlatItem> {
        let track = match Self::find_track_in_project(&self.project, track_id) {
            Some(t) => t,
            None => return Vec::new(),
        };
        let state = self.track_states.get(track_id);
        let expanded = state.map(|s| &s.expanded);

        // Build set of subtask IDs still in grace period (visible despite being done)
        let now = Instant::now();
        let grace_ids: HashSet<String> = self
            .pending_subtask_hides
            .iter()
            .filter(|ph| ph.track_id == track_id && now < ph.deadline)
            .map(|ph| ph.task_id.clone())
            .collect();

        let mut items = Vec::new();

        // Backlog tasks
        let backlog = track.backlog();
        flatten_tasks(
            backlog,
            SectionKind::Backlog,
            0,
            &mut items,
            expanded,
            &[],
            &grace_ids,
        );

        // Parked section (if non-empty)
        let parked = track.parked();
        if !parked.is_empty() {
            items.push(FlatItem::ParkedSeparator);
            flatten_tasks(
                parked,
                SectionKind::Parked,
                0,
                &mut items,
                expanded,
                &[],
                &grace_ids,
            );
        }

        // Done tasks are NOT shown in track view (they're in Recent)

        // Apply filter if active
        if self.filter_state.is_active() {
            apply_filter(&mut items, track, &self.filter_state, &self.project);
        }

        items
    }
}

/// Resolve a task reference from a track using section + index path
pub fn resolve_task_from_flat<'a>(
    track: &'a Track,
    section: SectionKind,
    path: &[usize],
) -> Option<&'a Task> {
    let tasks = track.section_tasks(section);
    if path.is_empty() {
        return None;
    }
    let mut current = tasks.get(path[0])?;
    for &idx in &path[1..] {
        current = current.subtasks.get(idx)?;
    }
    Some(current)
}

/// Recursively flatten subtask IDs in depth-first order
pub fn flatten_subtask_ids(task: &Task) -> Vec<String> {
    let mut ids = Vec::new();
    flatten_subtask_ids_inner(&task.subtasks, &mut ids);
    ids
}

fn flatten_subtask_ids_inner(tasks: &[Task], ids: &mut Vec<String>) {
    for task in tasks {
        if let Some(ref id) = task.id {
            ids.push(id.clone());
        }
        flatten_subtask_ids_inner(&task.subtasks, ids);
    }
}

/// Generate a unique key for a task's expand/collapse state
pub fn task_expand_key(task: &Task, section: SectionKind, path: &[usize]) -> String {
    if let Some(id) = &task.id {
        id.clone()
    } else {
        let section_str = match section {
            SectionKind::Backlog => "b",
            SectionKind::Parked => "p",
            SectionKind::Done => "d",
        };
        format!(
            "_{}_{}",
            section_str,
            path.iter()
                .map(|i| i.to_string())
                .collect::<Vec<_>>()
                .join("_")
        )
    }
}

/// Recursively flatten tasks into visible items based on expand state
fn flatten_tasks(
    tasks: &[Task],
    section: SectionKind,
    depth: usize,
    items: &mut Vec<FlatItem>,
    expanded: Option<&HashSet<String>>,
    ancestor_last: &[bool],
    grace_ids: &HashSet<String>,
) {
    flatten_tasks_inner(
        tasks,
        section,
        depth,
        items,
        expanded,
        ancestor_last,
        &[],
        grace_ids,
    );
}

#[allow(clippy::too_many_arguments)]
fn flatten_tasks_inner(
    tasks: &[Task],
    section: SectionKind,
    depth: usize,
    items: &mut Vec<FlatItem>,
    expanded: Option<&HashSet<String>>,
    ancestor_last: &[bool],
    parent_path: &[usize],
    grace_ids: &HashSet<String>,
) {
    let count = tasks.len();

    // For subtasks (depth > 0), determine which are visible vs hidden
    if depth > 0 {
        let total_count = count;
        let mut visible_indices: Vec<usize> = Vec::new();
        let mut done_count = 0usize;

        for (i, task) in tasks.iter().enumerate() {
            let is_done = task.state == TaskState::Done;
            if is_done {
                done_count += 1;
                // Visible during grace period
                let in_grace = task.id.as_ref().is_some_and(|id| grace_ids.contains(id));
                if in_grace {
                    visible_indices.push(i);
                }
            } else {
                visible_indices.push(i);
            }
        }

        let hidden_count = done_count.saturating_sub(
            // done tasks that are in grace (still visible)
            tasks
                .iter()
                .filter(|t| {
                    t.state == TaskState::Done
                        && t.id.as_ref().is_some_and(|id| grace_ids.contains(id))
                })
                .count(),
        );

        // Insert DoneSummary if any subtasks are actually hidden
        if hidden_count > 0 {
            items.push(FlatItem::DoneSummary {
                depth,
                done_count,
                total_count,
                ancestor_last: ancestor_last.to_vec(),
            });
        }

        // Flatten only visible subtasks
        let visible_count = visible_indices.len();
        for (vi, &real_idx) in visible_indices.iter().enumerate() {
            let task = &tasks[real_idx];
            // is_last_sibling: last visible subtask, and no DoneSummary comes after
            // (DoneSummary is before visible subtasks, so last visible is truly last)
            let is_last = vi == visible_count - 1;
            let has_children = !task.subtasks.is_empty();

            let mut path = parent_path.to_vec();
            path.push(real_idx); // use real index to preserve resolve_task_from_flat correctness

            let key = task_expand_key(task, section, &path);
            let is_expanded = has_children && expanded.is_some_and(|set| set.contains(&key));

            items.push(FlatItem::Task {
                section,
                path: path.clone(),
                depth,
                has_children,
                is_expanded,
                is_last_sibling: is_last,
                ancestor_last: ancestor_last.to_vec(),
                is_context: false,
            });

            if is_expanded {
                let mut new_ancestor_last = ancestor_last.to_vec();
                new_ancestor_last.push(is_last);
                flatten_tasks_inner(
                    &task.subtasks,
                    section,
                    depth + 1,
                    items,
                    expanded,
                    &new_ancestor_last,
                    &path,
                    grace_ids,
                );
            }
        }
    } else {
        // Top-level tasks: no done-subtask hiding at this level
        for (i, task) in tasks.iter().enumerate() {
            let is_last = i == count - 1;
            let has_children = !task.subtasks.is_empty();

            let mut path = parent_path.to_vec();
            path.push(i);

            let key = task_expand_key(task, section, &path);
            let is_expanded = has_children && expanded.is_some_and(|set| set.contains(&key));

            items.push(FlatItem::Task {
                section,
                path: path.clone(),
                depth,
                has_children,
                is_expanded,
                is_last_sibling: is_last,
                ancestor_last: ancestor_last.to_vec(),
                is_context: false,
            });

            if is_expanded {
                let mut new_ancestor_last = ancestor_last.to_vec();
                new_ancestor_last.push(is_last);
                flatten_tasks_inner(
                    &task.subtasks,
                    section,
                    depth + 1,
                    items,
                    expanded,
                    &new_ancestor_last,
                    &path,
                    grace_ids,
                );
            }
        }
    }
}

/// Check if a task matches the given filter criteria
fn task_matches_filter(task: &Task, filter: &FilterState, project: &Project) -> bool {
    // Check state filter
    if let Some(sf) = &filter.state_filter {
        let state_ok = match sf {
            StateFilter::Active => task.state == TaskState::Active,
            StateFilter::Todo => task.state == TaskState::Todo,
            StateFilter::Blocked => task.state == TaskState::Blocked,
            StateFilter::Parked => task.state == TaskState::Parked,
            StateFilter::Ready => {
                (task.state == TaskState::Todo || task.state == TaskState::Active)
                    && !has_unresolved_deps(task, project)
            }
        };
        if !state_ok {
            return false;
        }
    }

    // Check tag filter
    if let Some(ref tag) = filter.tag_filter
        && !task.tags.iter().any(|t| t == tag)
    {
        return false;
    }

    true
}

/// Check if a task has unresolved (non-done) dependencies
fn has_unresolved_deps(task: &Task, project: &Project) -> bool {
    use crate::ops::task_ops;
    for m in &task.metadata {
        if let Metadata::Dep(deps) = m {
            for dep_id in deps {
                for (_, track) in &project.tracks {
                    if let Some(dep_task) = task_ops::find_task_in_track(track, dep_id)
                        && dep_task.state != TaskState::Done
                    {
                        return true;
                    }
                }
            }
        }
    }
    false
}

/// Check if a task or any of its subtasks (recursively) matches the filter
fn has_matching_descendant(task: &Task, filter: &FilterState, project: &Project) -> bool {
    for sub in &task.subtasks {
        if task_matches_filter(sub, filter, project) {
            return true;
        }
        if has_matching_descendant(sub, filter, project) {
            return true;
        }
    }
    false
}

/// Apply filter to the flat items list: remove non-matching tasks and mark context-only ancestors.
/// A task is kept if it matches the filter OR if it has a matching descendant (shown as context).
fn apply_filter(items: &mut Vec<FlatItem>, track: &Track, filter: &FilterState, project: &Project) {
    // First pass: determine which items match and which are context-only
    let mut keep = vec![false; items.len()];
    let mut context = vec![false; items.len()];

    for (i, item) in items.iter().enumerate() {
        if let FlatItem::Task { section, path, .. } = item
            && let Some(task) = resolve_task_from_flat(track, *section, path)
        {
            if task_matches_filter(task, filter, project) {
                keep[i] = true;
                // Mark all ancestors as context (they need to be shown for hierarchy)
                mark_ancestors_kept(items, i, &mut keep, &mut context);
            } else if has_matching_descendant(task, filter, project) {
                keep[i] = true;
                context[i] = true;
            }
        }
        // ParkedSeparator: keep if any parked task is kept (handled below)
    }

    // Keep DoneSummary if its parent task is kept
    for i in 0..items.len() {
        if let FlatItem::DoneSummary { depth, .. } = &items[i] {
            let summary_depth = *depth;
            // Walk backwards to find the nearest Task at depth-1 (the parent)
            for j in (0..i).rev() {
                if let FlatItem::Task { depth: d, .. } = &items[j]
                    && *d == summary_depth.saturating_sub(1)
                {
                    keep[i] = keep[j];
                    break;
                }
            }
        }
    }

    // Keep ParkedSeparator only if at least one Parked task is kept
    for (i, item) in items.iter().enumerate() {
        if matches!(item, FlatItem::ParkedSeparator) {
            let has_parked = items[i + 1..].iter().enumerate().any(|(j, fi)| {
                matches!(
                    fi,
                    FlatItem::Task {
                        section: SectionKind::Parked,
                        ..
                    }
                ) && keep[i + 1 + j]
            });
            keep[i] = has_parked;
        }
    }

    // Apply: set is_context flags and remove non-kept items
    let mut idx = 0;
    items.retain_mut(|item| {
        let retained = keep[idx];
        if retained
            && let FlatItem::Task {
                is_context: ctx, ..
            } = item
        {
            *ctx = context[idx];
        }
        idx += 1;
        retained
    });
}

/// Mark ancestor items as kept (context) by walking up the path hierarchy
fn mark_ancestors_kept(
    items: &[FlatItem],
    child_idx: usize,
    keep: &mut [bool],
    context: &mut [bool],
) {
    if let FlatItem::Task { path, section, .. } = &items[child_idx] {
        if path.len() <= 1 {
            return; // top-level task, no ancestors
        }
        let child_section = *section;
        // Walk backwards to find ancestor items (shorter path prefixes in the same section)
        for ancestor_len in 1..path.len() {
            let ancestor_path = &path[..ancestor_len];
            for (j, item) in items[..child_idx].iter().enumerate().rev() {
                if let FlatItem::Task {
                    path: p,
                    section: s,
                    ..
                } = item
                    && *s == child_section
                    && p.as_slice() == ancestor_path
                {
                    if !keep[j] {
                        keep[j] = true;
                        context[j] = true;
                    }
                    break;
                }
            }
        }
    }
}

/// Restore UI state from .state.json
pub fn restore_ui_state(app: &mut App) {
    use crate::io::state::read_ui_state;

    let ui_state = match read_ui_state(&app.project.frame_dir) {
        Some(s) => s,
        None => return,
    };

    // Restore view
    match ui_state.view.as_str() {
        "tracks" => app.view = View::Tracks,
        "board" => app.view = View::Board,
        "inbox" => app.view = View::Inbox,
        "recent" => app.view = View::Recent,
        "track" => {
            if let Some(idx) = app
                .active_track_ids
                .iter()
                .position(|id| id == &ui_state.active_track)
            {
                app.view = View::Track(idx);
            }
        }
        _ => {}
    }

    // Restore board state
    if let Some(mode_str) = &ui_state.board_mode {
        app.board_state.mode = match mode_str.as_str() {
            "all" => BoardMode::All,
            _ => BoardMode::Cc,
        };
    }
    if let Some(col) = ui_state.board_focus_column {
        app.board_state.focus_column = BoardColumn::from_index(col);
    }

    // Restore per-track state
    for (track_id, track_ui) in &ui_state.tracks {
        let state = app.get_track_state(track_id);
        state.cursor = track_ui.cursor;
        state.scroll_offset = track_ui.scroll_offset;
        state.expanded = track_ui.expanded.clone();
    }

    // Restore last search
    app.last_search = ui_state.last_search;

    // Restore search history
    app.search_history = ui_state.search_history;

    // Restore project search history
    app.project_search_history = ui_state.project_search_history;

    // Restore note wrap override
    if let Some(wrap_override) = ui_state.note_wrap_override {
        app.note_wrap = wrap_override;
    }
}

/// Save UI state to .state.json
pub fn save_ui_state(app: &App) {
    use crate::io::state::{TrackUiState, UiState, write_ui_state};

    let view_to_save = if app.view == View::Search {
        // On quit from Search view, save the return_view instead
        app.project_search_results
            .as_ref()
            .map(|sr| sr.return_view.clone())
            .unwrap_or(View::Recent)
    } else {
        app.view.clone()
    };
    let (view_str, active_track) = match &view_to_save {
        View::Track(idx) => (
            "track".to_string(),
            app.active_track_ids.get(*idx).cloned().unwrap_or_default(),
        ),
        View::Detail { track_id, .. } => ("track".to_string(), track_id.clone()),
        View::Tracks => ("tracks".to_string(), String::new()),
        View::Board => ("board".to_string(), String::new()),
        View::Inbox => ("inbox".to_string(), String::new()),
        View::Recent => ("recent".to_string(), String::new()),
        View::Search => ("recent".to_string(), String::new()),
    };

    let mut tracks = HashMap::new();
    for (track_id, state) in &app.track_states {
        tracks.insert(
            track_id.clone(),
            TrackUiState {
                cursor: state.cursor,
                expanded: state.expanded.clone(),
                scroll_offset: state.scroll_offset,
            },
        );
    }

    let note_wrap_override = if app.note_wrap != app.project.config.ui.note_wrap {
        Some(app.note_wrap)
    } else {
        None
    };

    let board_mode = Some(match app.board_state.mode {
        BoardMode::Cc => "cc".to_string(),
        BoardMode::All => "all".to_string(),
    });

    let ui_state = UiState {
        view: view_str,
        active_track,
        tracks,
        last_search: app.last_search.clone(),
        search_history: app.search_history.clone(),
        note_wrap_override,
        project_search_history: app.project_search_history.clone(),
        board_mode,
        board_focus_column: Some(app.board_state.focus_column.index()),
    };

    let _ = write_ui_state(&app.project.frame_dir, &ui_state);
}

/// Set the terminal window/tab title via OSC 0.
pub fn set_window_title(name: &str) {
    let _ = write!(io::stdout(), "\x1b]0;frame · {}\x07", name);
    let _ = io::stdout().flush();
}

/// Clear the terminal window/tab title (restore default).
pub fn clear_window_title() {
    let _ = write!(io::stdout(), "\x1b]0;\x07");
    let _ = io::stdout().flush();
}

/// Run the TUI application.
/// If `project_dir_override` is set, use that as the starting directory.
pub fn run(project_dir_override: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
    // Discover and load project
    let start_dir = match project_dir_override {
        Some(dir) => std::fs::canonicalize(dir)
            .map_err(|e| format!("cannot resolve -C path '{}': {}", dir, e))?,
        None => std::env::current_dir()?,
    };

    // If we can't find a project, check the registry for the picker
    let root = match discover_project(&start_dir) {
        Ok(root) => root,
        Err(_) => {
            // No project found — launch project picker
            return run_project_picker();
        }
    };
    let mut project = load_project(&root)?;

    // Auto-assign IDs and dates so all tasks are interactive from the start
    let modified_tracks = crate::ops::clean::ensure_ids_and_dates(&mut project);
    if !modified_tracks.is_empty() {
        let _lock = FileLock::acquire_default(&project.frame_dir)?;
        for track_id in &modified_tracks {
            if let Some(tc) = project.config.tracks.iter().find(|tc| tc.id == *track_id) {
                let file = &tc.file;
                if let Some(track) = project
                    .tracks
                    .iter()
                    .find(|(id, _)| id == track_id)
                    .map(|(_, t)| t)
                {
                    let _ = project_io::save_track(&project.frame_dir, file, track);
                }
            }
        }
    }

    // Auto-register and touch TUI timestamp
    crate::io::registry::register_project(&project.config.project.name, &project.root);
    crate::io::registry::touch_tui(&project.root);

    let mut app = App::new(project);

    // Restore saved UI state
    restore_ui_state(&mut app);

    // Start file watcher (non-fatal if it fails)
    let watcher = FrameWatcher::start(&app.project.frame_dir).ok();

    // Setup terminal
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen)?;

    // Kitty keyboard protocol: enabled by default (detection via
    // supports_keyboard_enhancement() is unreliable). Can be overridden
    // in project.toml with [ui] kitty_keyboard = true/false.
    let kitty_setting = app.project.config.ui.kitty_keyboard.unwrap_or(true);
    let kitty_enabled = if kitty_setting {
        execute!(
            stdout,
            PushKeyboardEnhancementFlags(
                KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES
                    | KeyboardEnhancementFlags::REPORT_EVENT_TYPES
                    | KeyboardEnhancementFlags::REPORT_ALL_KEYS_AS_ESCAPE_CODES
            )
        )
        .is_ok()
    } else {
        false
    };

    // Bracketed paste: terminal signals paste start/end so we get a single
    // Event::Paste(String) instead of individual key events for each character.
    let _ = execute!(stdout, EnableBracketedPaste);

    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;
    terminal.clear()?;

    // Install panic hook to restore terminal on panic
    let original_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |panic_info| {
        let _ = write!(io::stdout(), "\x1b]0;\x07");
        let _ = io::stdout().flush();
        let _ = disable_raw_mode();
        let _ = execute!(io::stdout(), DisableBracketedPaste);
        let _ = execute!(io::stdout(), PopKeyboardEnhancementFlags);
        let _ = execute!(io::stdout(), LeaveAlternateScreen);
        original_hook(panic_info);
    }));

    // Record kitty protocol status on app for debug display
    app.kitty_enabled = kitty_enabled;

    // Set terminal window title
    set_window_title(&app.project.config.project.name);

    // Run event loop
    let result = run_event_loop(&mut terminal, &mut app, watcher);

    // Save UI state before exit
    save_ui_state(&app);

    // Restore terminal
    clear_window_title();
    disable_raw_mode()?;
    let _ = execute!(terminal.backend_mut(), DisableBracketedPaste);
    let _ = execute!(terminal.backend_mut(), PopKeyboardEnhancementFlags);
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    terminal.show_cursor()?;

    result
}

/// Launch the TUI in project-picker-only mode (when no project is found).
fn run_project_picker() -> Result<(), Box<dyn std::error::Error>> {
    let reg = crate::io::registry::read_registry();
    if reg.projects.is_empty() {
        println!("No projects registered.");
        println!();
        println!("Run `fr init` in a project directory to get started,");
        println!("or `fr projects add <path>` to register an existing project.");
        return Ok(());
    }

    // Setup terminal
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;
    terminal.clear()?;

    // Install panic hook to restore terminal on panic
    let original_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |panic_info| {
        let _ = disable_raw_mode();
        let _ = execute!(io::stdout(), LeaveAlternateScreen);
        original_hook(panic_info);
    }));

    let mut picker = ProjectPickerState::new(reg.projects, None);
    let theme = super::theme::Theme::default();

    let selected_path = loop {
        terminal.draw(|frame| {
            let area = frame.area();
            // Dark background
            frame.render_widget(
                ratatui::widgets::Block::default()
                    .style(ratatui::style::Style::default().bg(theme.background)),
                area,
            );
            render::project_picker::render_project_picker_standalone(frame, &picker, &theme, area);
        })?;

        if crossterm::event::poll(Duration::from_millis(250))?
            && let crossterm::event::Event::Key(key) = crossterm::event::read()?
            && (key.kind == crossterm::event::KeyEventKind::Press
                || (key.kind == crossterm::event::KeyEventKind::Repeat
                    && matches!(
                        key.code,
                        crossterm::event::KeyCode::Up
                            | crossterm::event::KeyCode::Down
                            | crossterm::event::KeyCode::Char('j')
                            | crossterm::event::KeyCode::Char('k')
                    )))
        {
            use crossterm::event::{KeyCode, KeyModifiers};
            match (key.modifiers, key.code) {
                (_, KeyCode::Char('q')) | (_, KeyCode::Esc) => break None,
                (_, KeyCode::Up) | (_, KeyCode::Char('k')) => picker.move_up(),
                (_, KeyCode::Down) | (_, KeyCode::Char('j')) => picker.move_down(),
                (_, KeyCode::Enter) => {
                    if let Some(entry) = picker.selected_entry() {
                        break Some(entry.path.clone());
                    }
                }
                (KeyModifiers::SHIFT, KeyCode::Char('X'))
                | (KeyModifiers::NONE, KeyCode::Char('X')) => {
                    picker.remove_selected();
                }
                (_, KeyCode::Char('s')) => picker.toggle_sort(),
                _ => {}
            }
        }
    };

    // Restore terminal
    disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    terminal.show_cursor()?;

    // If a project was selected, load and run it
    if let Some(path) = selected_path {
        let root_path = std::path::PathBuf::from(&path);
        if !root_path.join("frame").exists() {
            return Err(format!("project not found at {}", path).into());
        }
        crate::io::registry::touch_tui(&root_path);
        return run(Some(&path));
    }

    Ok(())
}

/// Format a KeyEvent into a compact debug string like "Left mod=CTRL|ALT" or "Char('a') mod=NONE"
fn format_key_debug(key: &crossterm::event::KeyEvent) -> String {
    use crossterm::event::KeyModifiers;
    let code = format!("{:?}", key.code);
    let mut mods = Vec::new();
    if key.modifiers.contains(KeyModifiers::CONTROL) {
        mods.push("CTRL");
    }
    if key.modifiers.contains(KeyModifiers::ALT) {
        mods.push("ALT");
    }
    if key.modifiers.contains(KeyModifiers::SHIFT) {
        mods.push("SHIFT");
    }
    if key.modifiers.contains(KeyModifiers::SUPER) {
        mods.push("SUPER");
    }
    if key.modifiers.contains(KeyModifiers::HYPER) {
        mods.push("HYPER");
    }
    if key.modifiers.contains(KeyModifiers::META) {
        mods.push("META");
    }
    let mod_str = if mods.is_empty() {
        "NONE".to_string()
    } else {
        mods.join("|")
    };
    format!("{} mod={} state={:?}", code, mod_str, key.state)
}

fn run_event_loop(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    app: &mut App,
    mut watcher: Option<FrameWatcher>,
) -> Result<(), Box<dyn std::error::Error>> {
    let mut save_counter = 0u32;
    loop {
        // Reinitialize file watcher after project switch
        if app.watcher_needs_restart {
            app.watcher_needs_restart = false;
            watcher = FrameWatcher::start(&app.project.frame_dir).ok();
        }
        app.clear_expired_flash();

        // Flush expired pending moves and column pins (only in Navigate mode)
        if app.mode == Mode::Navigate
            && (!app.pending_moves.is_empty() || !app.board_state.column_pins.is_empty())
        {
            let modified = app.flush_expired_pending_moves();
            for tid in &modified {
                app.save_track_logged(tid);
            }
        }

        // Flush expired subtask hides (purely visual, no file save needed)
        if !app.pending_subtask_hides.is_empty() {
            app.flush_expired_subtask_hides();
        }

        terminal.draw(|frame| render::render(frame, app))?;

        // Poll for file watcher events
        if let Some(w) = watcher.as_ref() {
            let events = w.poll();
            if !events.is_empty() {
                // Collect all changed paths, dedup
                let mut all_paths = Vec::new();
                for evt in events {
                    match evt {
                        FileEvent::Changed(paths) => all_paths.extend(paths),
                    }
                }
                all_paths.sort();
                all_paths.dedup();

                // If we saved recently (within 1s), assume this is our own write notification
                let is_self_write = app
                    .last_save_at
                    .is_some_and(|t| t.elapsed() < Duration::from_secs(1));
                if is_self_write {
                    app.last_save_at = None; // consume the suppression
                } else if !all_paths.is_empty() {
                    // External change detected
                    if matches!(
                        app.mode,
                        Mode::Edit | Mode::Move | Mode::Triage | Mode::Confirm | Mode::Command
                    ) {
                        // Queue reload for when we leave modal mode
                        app.pending_reload_paths.extend(all_paths);
                    } else {
                        handle_external_reload(app, &all_paths);
                    }
                }
            }
        }

        if event::poll(Duration::from_millis(250))? {
            let old_view = app.view.clone();
            let evt = event::read()?;
            let handled = match evt {
                Event::Key(key)
                    if key.kind == KeyEventKind::Press
                        || (key.kind == KeyEventKind::Repeat
                            && is_repeatable_key(&app.mode, &key)) =>
                {
                    // Capture raw key event for debug display
                    if app.key_debug {
                        app.last_key_event = Some(format_key_debug(&key));
                    }
                    input::handle_key(app, key);
                    true
                }
                Event::Paste(text) => {
                    input::handle_paste(app, &text);
                    true
                }
                _ => false,
            };

            if handled {
                // Reset grace period on any keypress so tasks don't move
                // out from under the user while they're interacting
                if !app.pending_moves.is_empty() {
                    app.reset_pending_move_deadlines();
                }
                if !app.pending_subtask_hides.is_empty() {
                    app.reset_pending_subtask_hide_deadlines();
                }

                // Flush all pending moves on view change
                if app.view != old_view && !app.pending_moves.is_empty() {
                    let modified = app.flush_all_pending_moves();
                    for tid in &modified {
                        app.save_track_logged(tid);
                    }
                }

                // Clear subtask hide grace periods on view/tab change
                if app.view != old_view {
                    app.pending_subtask_hides.clear();
                }

                // Process pending reload when returning to Navigate mode
                if !app.pending_reload_paths.is_empty() && app.mode == Mode::Navigate {
                    let paths = std::mem::take(&mut app.pending_reload_paths);
                    handle_pending_reload(app, &paths);
                }

                // Debounced state save: every ~5 key presses
                save_counter += 1;
                if save_counter >= 5 {
                    save_ui_state(app);
                    save_counter = 0;
                }
            }
        }

        if app.should_quit {
            // Flush all pending moves before exit
            let modified = app.flush_all_pending_moves();
            for tid in &modified {
                app.save_track_logged(tid);
            }
            break;
        }
    }
    Ok(())
}

/// Whether a key repeat event should be processed. In typing modes all keys
/// repeat; in navigation modes only movement keys repeat.
fn is_repeatable_key(mode: &Mode, key: &crossterm::event::KeyEvent) -> bool {
    use crossterm::event::KeyCode;
    match mode {
        Mode::Edit | Mode::Search | Mode::Triage | Mode::Command => true,
        _ => matches!(
            key.code,
            KeyCode::Up
                | KeyCode::Down
                | KeyCode::Left
                | KeyCode::Right
                | KeyCode::PageUp
                | KeyCode::PageDown
                | KeyCode::Home
                | KeyCode::End
                | KeyCode::Tab
                | KeyCode::BackTab
                | KeyCode::Char('j')
                | KeyCode::Char('k')
                | KeyCode::Char('h')
                | KeyCode::Char('l')
        ),
    }
}

/// Handle an external file reload (when specific changed paths are known)
fn handle_external_reload(app: &mut App, paths: &[std::path::PathBuf]) {
    // Clear subtask hide grace entries for affected tracks
    let affected_track_ids: HashSet<String> = paths
        .iter()
        .filter_map(|p| {
            let file_name = p.file_name()?.to_str()?;
            let rel = p
                .strip_prefix(&app.project.frame_dir)
                .ok()
                .and_then(|r| r.to_str());
            resolve_track_for_path(&app.project.config.tracks, file_name, rel).map(|(id, _)| id)
        })
        .collect();
    app.pending_subtask_hides
        .retain(|ph| !affected_track_ids.contains(&ph.track_id));

    let conflict_task = app.reload_changed_files(paths);
    if conflict_task.is_some() {
        // Save the orphaned edit text in conflict_text
        if !app.edit_buffer.is_empty() {
            app.conflict_text = Some(app.edit_buffer.clone());
        }
        // Cancel the edit mode
        app.mode = Mode::Navigate;
        app.edit_target = None;
        app.edit_buffer.clear();
        app.edit_cursor = 0;
    }
    // Auto-clean after external reload
    run_auto_clean(app);
}

/// Handle a pending reload using the stored changed paths
fn handle_pending_reload(app: &mut App, paths: &[PathBuf]) {
    // Dedup paths (may have accumulated duplicates)
    let mut deduped: Vec<PathBuf> = Vec::new();
    for p in paths {
        if !deduped.contains(p) {
            deduped.push(p.clone());
        }
    }
    // This is after EDIT/MOVE completed, so no conflict possible — just reload
    app.reload_changed_files(&deduped);
    // Auto-clean after reload
    run_auto_clean(app);
}

/// Run auto-clean on the project after external changes are detected.
/// Assigns missing IDs/dates and saves affected tracks. Shows status message if anything changed.
fn run_auto_clean(app: &mut App) {
    use crate::ops::clean::clean_project;

    let result = clean_project(&mut app.project);

    let has_changes = !result.ids_assigned.is_empty()
        || !result.dates_assigned.is_empty()
        || !result.duplicates_resolved.is_empty()
        || !result.sections_reconciled.is_empty()
        || !result.tasks_archived.is_empty();

    if has_changes {
        // Collect affected track IDs
        let mut affected_tracks: std::collections::HashSet<String> =
            std::collections::HashSet::new();
        for id_a in &result.ids_assigned {
            affected_tracks.insert(id_a.track_id.clone());
        }
        for date_a in &result.dates_assigned {
            affected_tracks.insert(date_a.track_id.clone());
        }
        for dup in &result.duplicates_resolved {
            affected_tracks.insert(dup.track_id.clone());
        }
        for rec in &result.sections_reconciled {
            affected_tracks.insert(rec.track_id.clone());
        }
        for arc in &result.tasks_archived {
            affected_tracks.insert(arc.track_id.clone());
        }

        // Save affected tracks
        for track_id in &affected_tracks {
            let _ = app.save_track(track_id);
        }

        // Add sync marker to undo stack so user can't undo past the external change
        app.undo_stack.push(crate::tui::undo::Operation::SyncMarker);

        // Show subtle status message
        let count = result.ids_assigned.len()
            + result.dates_assigned.len()
            + result.duplicates_resolved.len()
            + result.sections_reconciled.len()
            + result.tasks_archived.len();
        app.status_message = Some(format!(
            "Auto-cleaned: {} fix{}",
            count,
            if count == 1 { "" } else { "es" }
        ));
    }
}

// ---------------------------------------------------------------------------
// File-watcher path resolution helpers
// ---------------------------------------------------------------------------

/// Check whether a changed file is the real top-level inbox.md (not archive/inbox.md).
fn is_inbox_path(file_name: &str, rel_path: Option<&str>) -> bool {
    file_name == "inbox.md" && rel_path.is_none_or(|r| r == "inbox.md")
}

/// Resolve a changed file path to a track config entry.
/// Uses the relative path from frame_dir when available (preferred — exact match).
/// Falls back to filename-only matching when the path can't be relativized.
fn resolve_track_for_path(
    tracks: &[crate::model::config::TrackConfig],
    file_name: &str,
    rel_path: Option<&str>,
) -> Option<(String, String)> {
    tracks
        .iter()
        .find(|tc| {
            if let Some(rel) = rel_path {
                tc.file == rel
            } else {
                tc.file == file_name || tc.file.ends_with(&format!("/{}", file_name))
            }
        })
        .map(|tc| (tc.id.clone(), tc.file.clone()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::config::TrackConfig;

    fn sample_tracks() -> Vec<TrackConfig> {
        vec![
            TrackConfig {
                id: "main".to_string(),
                name: "Main".to_string(),
                state: "active".to_string(),
                file: "tracks/main.md".to_string(),
            },
            TrackConfig {
                id: "research".to_string(),
                name: "Research".to_string(),
                state: "active".to_string(),
                file: "tracks/research.md".to_string(),
            },
        ]
    }

    // --- is_inbox_path ---

    #[test]
    fn inbox_top_level_matches() {
        assert!(is_inbox_path("inbox.md", Some("inbox.md")));
    }

    #[test]
    fn inbox_archive_does_not_match() {
        assert!(!is_inbox_path("inbox.md", Some("archive/inbox.md")));
    }

    #[test]
    fn inbox_no_rel_path_matches() {
        // Fallback when strip_prefix fails — accept it
        assert!(is_inbox_path("inbox.md", None));
    }

    #[test]
    fn non_inbox_does_not_match() {
        assert!(!is_inbox_path("main.md", Some("tracks/main.md")));
    }

    // --- resolve_track_for_path ---

    #[test]
    fn track_file_matches_by_rel_path() {
        let tracks = sample_tracks();
        let result = resolve_track_for_path(&tracks, "main.md", Some("tracks/main.md"));
        assert_eq!(
            result,
            Some(("main".to_string(), "tracks/main.md".to_string()))
        );
    }

    #[test]
    fn archive_file_does_not_match_track() {
        let tracks = sample_tracks();
        let result = resolve_track_for_path(&tracks, "main.md", Some("archive/main.md"));
        assert_eq!(result, None);
    }

    #[test]
    fn archive_tracks_subdir_does_not_match() {
        let tracks = sample_tracks();
        let result = resolve_track_for_path(&tracks, "main.md", Some("archive/_tracks/main.md"));
        assert_eq!(result, None);
    }

    #[test]
    fn different_track_name_in_archive() {
        let tracks = sample_tracks();
        let result = resolve_track_for_path(&tracks, "research.md", Some("archive/research.md"));
        assert_eq!(result, None);
    }

    #[test]
    fn correct_track_file_matches() {
        let tracks = sample_tracks();
        let result = resolve_track_for_path(&tracks, "research.md", Some("tracks/research.md"));
        assert_eq!(
            result,
            Some(("research".to_string(), "tracks/research.md".to_string()))
        );
    }

    #[test]
    fn fallback_filename_matching_when_no_rel_path() {
        let tracks = sample_tracks();
        // When rel_path is None, falls back to filename suffix matching
        let result = resolve_track_for_path(&tracks, "main.md", None);
        assert_eq!(
            result,
            Some(("main".to_string(), "tracks/main.md".to_string()))
        );
    }

    #[test]
    fn unrelated_md_file_does_not_match() {
        let tracks = sample_tracks();
        let result = resolve_track_for_path(&tracks, "notes.md", Some("notes.md"));
        assert_eq!(result, None);
    }

    #[test]
    fn flat_track_config_matches_exactly() {
        // Track config with file directly in frame_dir (no subdirectory)
        let tracks = vec![TrackConfig {
            id: "main".to_string(),
            name: "Main".to_string(),
            state: "active".to_string(),
            file: "main.md".to_string(),
        }];
        let result = resolve_track_for_path(&tracks, "main.md", Some("main.md"));
        assert_eq!(result, Some(("main".to_string(), "main.md".to_string())));
    }

    #[test]
    fn flat_config_archive_does_not_match() {
        let tracks = vec![TrackConfig {
            id: "main".to_string(),
            name: "Main".to_string(),
            state: "active".to_string(),
            file: "main.md".to_string(),
        }];
        let result = resolve_track_for_path(&tracks, "main.md", Some("archive/main.md"));
        assert_eq!(result, None);
    }
}