frame 0.1.7

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
use std::collections::{HashMap, HashSet};
use std::path::Path;

use chrono::Local;

use crate::io::actors::IdScope;
use crate::model::project::Project;
use crate::model::task::{Metadata, Task, TaskState};
use crate::model::task_id::{TaskId, Token};
use crate::model::track::{SectionKind, Track, TrackNode};
use crate::ops::ids::Mint;
use crate::ops::task_ops::renumber_subtasks;

/// Result of a clean operation
#[derive(Debug, Default)]
pub struct CleanResult {
    /// IDs assigned to tasks that were missing them
    pub ids_assigned: Vec<IdAssignment>,
    /// Added dates filled in
    pub dates_assigned: Vec<DateAssignment>,
    /// Duplicate IDs resolved (reassigned)
    pub duplicates_resolved: Vec<DuplicateResolution>,
    /// Tasks archived from done sections
    pub tasks_archived: Vec<ArchiveRecord>,
    /// Dangling dependency references
    pub dangling_deps: Vec<DanglingDep>,
    /// Broken file references (ref/spec)
    pub broken_refs: Vec<BrokenRef>,
    /// Top-level tasks moved to the correct section based on state
    pub sections_reconciled: Vec<SectionReconcile>,
    /// Suggestions (e.g., all subtasks done → suggest parent done)
    pub suggestions: Vec<Suggestion>,
}

#[derive(Debug, Clone)]
pub struct IdAssignment {
    pub track_id: String,
    pub assigned_id: String,
    pub title: String,
}

#[derive(Debug, Clone)]
pub struct DateAssignment {
    pub track_id: String,
    pub task_id: String,
    pub date: String,
    pub kind: DateKind,
}

/// Which date a [`DateAssignment`] filled in. Both are reported the same way, but
/// naming the field keeps `T-001 → 2026-07-31` from being ambiguous now that
/// clean fills two kinds of date.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DateKind {
    Added,
    Resolved,
}

impl DateKind {
    pub fn key(self) -> &'static str {
        match self {
            DateKind::Added => "added",
            DateKind::Resolved => "resolved",
        }
    }
}

#[derive(Debug, Clone)]
pub struct DuplicateResolution {
    pub track_id: String,
    pub original_id: String,
    pub new_id: String,
    pub title: String,
}

#[derive(Debug, Clone)]
pub struct ArchiveRecord {
    pub track_id: String,
    pub task_id: String,
    pub title: String,
}

#[derive(Debug, Clone)]
pub struct DanglingDep {
    pub track_id: String,
    pub task_id: String,
    pub dep_id: String,
}

#[derive(Debug, Clone)]
pub struct BrokenRef {
    pub track_id: String,
    pub task_id: String,
    pub path: String,
    pub kind: RefKind,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RefKind {
    Ref,
    Spec,
}

#[derive(Debug, Clone)]
pub struct SectionReconcile {
    pub track_id: String,
    pub task_id: String,
    pub from: SectionKind,
    pub to: SectionKind,
}

#[derive(Debug, Clone)]
pub struct Suggestion {
    pub track_id: String,
    pub task_id: String,
    pub kind: SuggestionKind,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SuggestionKind {
    /// All subtasks are done — parent could be marked done
    AllSubtasksDone,
}

// ---------------------------------------------------------------------------
// Lightweight ID + date + dedup assignment (used by TUI on load/reload)
// ---------------------------------------------------------------------------

/// Assign missing IDs and dates, and resolve duplicate IDs across the project.
///
/// This runs steps 1–3 of the clean pipeline (ID assignment, date assignment,
/// duplicate ID resolution). Returns the list of track IDs that were modified,
/// so callers can selectively save only those tracks.
///
/// `scope` honors the strict null policy: with [`IdScope::Mint`] any IDs minted
/// are scoped to that namespace (`None` = null); with [`IdScope::Unclaimed`] the
/// minting steps (ID assignment and duplicate reassignment) are **skipped** —
/// tasks are left ID-less — while date filling and section reconciliation still
/// run, since those mint nothing.
pub fn ensure_ids_and_dates(project: &mut Project, scope: IdScope) -> Vec<String> {
    let mut result = CleanResult::default();
    let mut modified = HashSet::new();

    for (track_id, track) in &mut project.tracks {
        let before_ids = result.ids_assigned.len();
        let before_dates = result.dates_assigned.len();

        let prefix = project.config.ids.prefixes.get(track_id.as_str()).cloned();

        if let (Some(pfx), IdScope::Mint(ns)) = (&prefix, &scope) {
            let mint = Mint::new(&project.frame_dir, track_id, pfx, ns.as_ref());
            assign_missing_ids(track, track_id, mint, &mut result);
        }
        assign_missing_dates(track, track_id, &mut result);

        if result.ids_assigned.len() > before_ids || result.dates_assigned.len() > before_dates {
            modified.insert(track_id.clone());
        }
    }

    // Resolve duplicate IDs (cross-track and within-track) — minting, so only
    // when this clone owns a namespace.
    if let IdScope::Mint(ns) = &scope {
        let before_dups = result.duplicates_resolved.len();
        resolve_duplicate_ids(project, ns.as_ref(), &mut result);
        for dup in &result.duplicates_resolved[before_dups..] {
            modified.insert(dup.track_id.clone());
        }
    }

    // Reconcile misplaced tasks (e.g., parked task in Backlog section) — no
    // minting, so it runs regardless of claim state.
    for (track_id, track) in &mut project.tracks {
        if reconcile_sections_for_track(track, track_id, &mut result) {
            modified.insert(track_id.clone());
        }
    }

    modified.into_iter().collect()
}

// ---------------------------------------------------------------------------
// Section reconciliation — move misplaced top-level tasks to correct section
// ---------------------------------------------------------------------------

use crate::ops::task_ops::canonical_section;

/// Move top-level tasks that are in the wrong section to the correct one.
/// For example, a `[~]` parked task sitting in `## Backlog` gets moved to `## Parked`.
/// Returns true if any tasks were moved (i.e., the track was modified).
fn reconcile_sections_for_track(
    track: &mut Track,
    track_id: &str,
    result: &mut CleanResult,
) -> bool {
    // Collect (task_id, current_section, target_section) for misplaced tasks.
    // We iterate sections in order, checking only top-level tasks.
    let mut moves: Vec<(String, SectionKind, SectionKind)> = Vec::new();

    for node in &track.nodes {
        if let TrackNode::Section { kind, tasks, .. } = node {
            for task in tasks {
                let target = canonical_section(task.state);
                if target != *kind
                    && let Some(ref id) = task.id
                {
                    moves.push((id.to_string(), *kind, target));
                }
            }
        }
    }

    if moves.is_empty() {
        return false;
    }

    for (task_id, from, to) in &moves {
        crate::ops::task_ops::move_task_between_sections(track, task_id, *from, *to);
        result.sections_reconciled.push(SectionReconcile {
            track_id: track_id.to_string(),
            task_id: task_id.clone(),
            from: *from,
            to: *to,
        });
    }

    true
}

/// Reconcile sections across all tracks in a project.
/// Returns the list of track IDs that were modified.
pub fn reconcile_sections(project: &mut Project) -> Vec<String> {
    let mut result = CleanResult::default();
    let mut modified = Vec::new();

    for (track_id, track) in &mut project.tracks {
        if reconcile_sections_for_track(track, track_id, &mut result) {
            modified.push(track_id.clone());
        }
    }

    modified
}

// ---------------------------------------------------------------------------
// Main clean entry point
// ---------------------------------------------------------------------------

/// Run clean operations on a project (mutates in place).
///
/// Operations:
/// 1. Assign IDs to tasks missing them
/// 2. Assign `added:` dates where missing
/// 3. Duplicate ID resolution (first by track order keeps ID; duplicates reassigned)
///    3b. Reconcile sections (move misplaced tasks to correct section by state)
/// 4. Validate deps (flag dangling)
/// 5. Validate file refs (flag broken paths)
/// 6. State suggestions (all subtasks done → suggest parent done)
/// 7. Archive done tasks past threshold
///
/// Returns a report of all changes made and issues found.
///
/// `scope` honors the strict null policy: with [`IdScope::Mint`] any IDs minted
/// (newly assigned or reassigned duplicates) are scoped to that namespace
/// (`None` = null); with [`IdScope::Unclaimed`] those minting steps are skipped
/// so the clone never mints null IDs it doesn't own. Archival and thresholds
/// key on task state and `resolved:` dates, not ID structure, so they run
/// identically regardless of `scope`.
pub fn clean_project(project: &mut Project, scope: IdScope) -> CleanResult {
    let mut result = CleanResult::default();

    for (track_id, track) in &mut project.tracks {
        let prefix = project.config.ids.prefixes.get(track_id.as_str()).cloned();

        // 1. Assign missing IDs (minting — only when this clone owns a namespace)
        if let (Some(pfx), IdScope::Mint(ns)) = (&prefix, &scope) {
            let mint = Mint::new(&project.frame_dir, track_id, pfx, ns.as_ref());
            assign_missing_ids(track, track_id, mint, &mut result);
        }

        // 2. Assign missing added dates
        assign_missing_dates(track, track_id, &mut result);
    }

    // 3. Duplicate ID resolution (minting — only when this clone owns a namespace)
    if let IdScope::Mint(ns) = &scope {
        resolve_duplicate_ids(project, ns.as_ref(), &mut result);
    }

    // 3b. Reconcile misplaced tasks (e.g., parked task in Backlog section)
    for (track_id, track) in &mut project.tracks {
        reconcile_sections_for_track(track, track_id, &mut result);
    }

    // Collect all task IDs across all tracks for dep validation (after duplicate resolution)
    let all_task_ids = collect_all_task_ids(project);

    for (track_id, track) in &mut project.tracks {
        // 4. Validate deps
        validate_deps(track, track_id, &all_task_ids, &mut result);

        // 5. Validate refs/specs
        validate_refs(track, track_id, &project.root, &mut result);

        // 6. State suggestions
        collect_suggestions(track, track_id, &mut result);
    }

    // 7. Archive done tasks past threshold
    archive_done_tasks(project, &mut result);

    // 8. Fill missing resolved dates. After archival by design — see
    //    `assign_missing_resolved_dates`.
    for (track_id, track) in &mut project.tracks {
        assign_missing_resolved_dates(track, track_id, &mut result);
    }

    result
}

// ---------------------------------------------------------------------------
// 1. Assign missing IDs
// ---------------------------------------------------------------------------

fn assign_missing_ids(track: &mut Track, track_id: &str, mint: Mint<'_>, result: &mut CleanResult) {
    // Reserve exactly as many numbers as there are ID-less top-level tasks, in
    // one reservation, then walk them out in order. Subtasks are numbered
    // relative to their parent, so they need nothing reserved — but they are
    // still assigned when no top-level task is missing an ID.
    let needed = count_missing_top_level_ids(track);
    let mut max = if needed > 0 {
        (mint.next_n(track, needed) - 1) as usize
    } else {
        0
    };

    let (prefix, token) = (mint.prefix(), mint.token());
    for node in &mut track.nodes {
        if let TrackNode::Section { tasks, .. } = node {
            assign_ids_in_tasks(tasks, track_id, prefix, token, &mut max, result);
        }
    }
}

/// How many top-level tasks are missing an ID — the size of the block
/// [`assign_ids_in_tasks`] is about to consume. Subtasks are numbered relative to
/// their parent, so they need nothing from the track's frontier.
fn count_missing_top_level_ids(track: &Track) -> u32 {
    let mut n = 0;
    for node in &track.nodes {
        if let TrackNode::Section { tasks, .. } = node {
            n += tasks.iter().filter(|t| t.id.is_none()).count() as u32;
        }
    }
    n
}

fn assign_ids_in_tasks(
    tasks: &mut [Task],
    track_id: &str,
    prefix: &str,
    token: Option<&Token>,
    max: &mut usize,
    result: &mut CleanResult,
) {
    for task in tasks.iter_mut() {
        if task.id.is_none() {
            *max += 1;
            let new_id = TaskId::with_number(prefix, *max as u32, token);
            task.id = Some(new_id.clone());
            task.mark_dirty();
            result.ids_assigned.push(IdAssignment {
                track_id: track_id.to_string(),
                assigned_id: new_id.to_string(),
                title: task.title.clone(),
            });
        }
        // Recurse into subtasks — subtasks with no ID also get assigned
        // (subtask IDs are parent_id.N)
        assign_subtask_ids(task, track_id, token, result);
    }
}

fn assign_subtask_ids(
    parent: &mut Task,
    track_id: &str,
    token: Option<&Token>,
    result: &mut CleanResult,
) {
    let parent_id = match &parent.id {
        Some(id) => id.clone(),
        None => return, // Parent must have an ID first
    };

    // Find the max existing child number in this namespace to avoid collisions
    // after deletions. E.g., if subtasks are [.1, .2, .4] (after deleting .3),
    // next should be .5 not .4.
    let mut max_num: u32 = 0;
    for sub in parent.subtasks.iter() {
        if let Some(n) = sub
            .id
            .as_ref()
            .and_then(|id| id.child_number_of(&parent_id, token))
        {
            max_num = max_num.max(n);
        }
    }

    for sub in parent.subtasks.iter_mut() {
        if sub.id.is_none() {
            max_num += 1;
            let sub_id = TaskId::child_of(&parent_id, max_num, token);
            sub.id = Some(sub_id.clone());
            sub.mark_dirty();
            result.ids_assigned.push(IdAssignment {
                track_id: track_id.to_string(),
                assigned_id: sub_id.to_string(),
                title: sub.title.clone(),
            });
        }
        // Recurse deeper
        assign_subtask_ids(sub, track_id, token, result);
    }
}

// ---------------------------------------------------------------------------
// 2. Assign missing added dates
// ---------------------------------------------------------------------------

fn assign_missing_dates(track: &mut Track, track_id: &str, result: &mut CleanResult) {
    let today = today_str();
    for node in &mut track.nodes {
        if let TrackNode::Section { tasks, .. } = node {
            assign_dates_in_tasks(tasks, track_id, &today, result);
        }
    }
}

fn assign_dates_in_tasks(
    tasks: &mut [Task],
    track_id: &str,
    today: &str,
    result: &mut CleanResult,
) {
    for task in tasks.iter_mut() {
        let has_added = task
            .metadata
            .iter()
            .any(|m| matches!(m, Metadata::Added(_)));
        if !has_added {
            task.metadata.insert(0, Metadata::Added(today.to_string()));
            task.mark_dirty();
            result.dates_assigned.push(DateAssignment {
                track_id: track_id.to_string(),
                task_id: task.id.as_ref().map(|i| i.to_string()).unwrap_or_default(),
                date: today.to_string(),
                kind: DateKind::Added,
            });
        }

        assign_dates_in_tasks(&mut task.subtasks, track_id, today, result);
    }
}

// ---------------------------------------------------------------------------
// 2b. Assign missing resolved dates
// ---------------------------------------------------------------------------

/// Fill `resolved:` on done tasks that lack it, matching the condition
/// `fr check` warns on and the position `fr state <id> done` writes it in (last).
///
/// Reachable by ticking a checkbox in the editor, which is a supported workflow,
/// so it belongs in clean rather than behind `fr check --fix`: a user wants it
/// filled silently, exactly as `added:` already is.
///
/// **Runs after archival, and the order is load-bearing.** Archive retention
/// ranks done tasks by `resolved:`, treating a missing date as oldest — so a task
/// with no date is archived first. Filling the date earlier in the run would
/// stamp it with today, making the oldest task look like the newest completion:
/// it would be retained over genuinely recent work and surface at the top of
/// `fr recent`. Filling afterwards leaves that ranking exactly as it was.
fn assign_missing_resolved_dates(track: &mut Track, track_id: &str, result: &mut CleanResult) {
    let today = today_str();
    for node in &mut track.nodes {
        if let TrackNode::Section { tasks, .. } = node {
            assign_resolved_in_tasks(tasks, track_id, &today, result);
        }
    }
}

fn assign_resolved_in_tasks(
    tasks: &mut [Task],
    track_id: &str,
    today: &str,
    result: &mut CleanResult,
) {
    for task in tasks.iter_mut() {
        if task.state == TaskState::Done
            && !task
                .metadata
                .iter()
                .any(|m| matches!(m, Metadata::Resolved(_)))
        {
            task.metadata.push(Metadata::Resolved(today.to_string()));
            task.mark_dirty();
            result.dates_assigned.push(DateAssignment {
                track_id: track_id.to_string(),
                task_id: task.id.as_ref().map(|i| i.to_string()).unwrap_or_default(),
                date: today.to_string(),
                kind: DateKind::Resolved,
            });
        }
        assign_resolved_in_tasks(&mut task.subtasks, track_id, today, result);
    }
}

// ---------------------------------------------------------------------------
// 3. Duplicate ID resolution
// ---------------------------------------------------------------------------

/// A duplicate occurrence awaiting a fresh ID.
struct Duplicate {
    old_id: String,
    track_id: String,
    /// The ID of the task this one is nested under, or `None` at top level.
    /// A subtask's replacement ID has to extend its parent's, so this decides
    /// which allocator the replacement comes from.
    parent_id: Option<String>,
}

/// Find and resolve duplicate IDs across the project.
///
/// The first occurrence by track order (as listed in `project.toml`) then by
/// position within the track keeps its ID. Subsequent duplicates are reassigned
/// new IDs via the standard `max + 1` rule. Dependencies pointing to the
/// reassigned ID are updated across all tracks.
///
/// A duplicate that is a **subtask** is renumbered under its own parent, not
/// given a top-level number. Both allocators are `max + 1`, but they number
/// different things: minting `BAC-207` for a task nested under `BAC-153` resolves
/// the collision while breaking the rule that a subtask's ID extends its
/// parent's, leaving damage `fr check` reports as `ChildIdNotUnderParent`.
fn resolve_duplicate_ids(project: &mut Project, token: Option<&Token>, result: &mut CleanResult) {
    // Build ordered track list from config (defines precedence)
    let track_order: Vec<String> = project
        .config
        .tracks
        .iter()
        .map(|tc| tc.id.clone())
        .collect();

    // Pass 1: Walk all tasks in track order, identify duplicate IDs.
    // First occurrence keeps the ID; subsequent occurrences are collected for reassignment.
    let mut seen_ids: HashSet<String> = HashSet::new();
    let mut duplicates: Vec<Duplicate> = Vec::new();

    for config_track_id in &track_order {
        if let Some((_, track)) = project
            .tracks
            .iter()
            .find(|(tid, _)| tid == config_track_id)
        {
            for node in &track.nodes {
                if let TrackNode::Section { tasks, .. } = node {
                    find_duplicates_in_tasks(
                        tasks,
                        config_track_id,
                        None,
                        &mut seen_ids,
                        &mut duplicates,
                    );
                }
            }
        }
    }

    if duplicates.is_empty() {
        return;
    }

    // Pass 2: Compute new IDs for each duplicate.
    // old_id → new_id mapping (note: multiple tasks can share the same old_id,
    // so we use a Vec to track all reassignments)
    let mut reassignments: HashMap<String, Vec<String>> = HashMap::new();
    // Also build a flat old→new map for dep rewriting (maps old_id to the LAST
    // assigned new_id — but for deps we want to keep pointing to the *keeper*,
    // not the reassigned duplicate, so we DON'T rewrite deps from old to new.
    // Actually per design: "Dependencies pointing to the reassigned ID are updated."
    // This means: if task A has dep on ID "X", and "X" was reassigned to "X-NEW",
    // then A's dep should still point to "X" (the keeper). The reassigned task
    // got a NEW id so nothing should dep on it by the old id anymore.
    // Wait — actually the design says deps pointing to the reassigned ID are updated.
    // That means if someone had `dep: DUP-001` and DUP-001 was the duplicate that
    // got reassigned to M-005, the dep should be updated to M-005.
    // But that's ambiguous — the keeper also has id DUP-001, so the dep is still valid.
    // The most sensible interpretation: deps continue to point at the keeper (which
    // retains the original ID), so no dep rewriting is needed for the common case.
    // Only if a dep pointed at a task that was specifically the duplicate instance
    // would it need updating — but deps are by ID string, not by instance.
    // So if the keeper retains the ID, deps pointing to that ID are still valid.
    // We don't need to rewrite deps. The design note about "deps updated" likely
    // refers to cross-track moves where the old ID disappears entirely.
    //
    // Re-reading the design: "Dependencies pointing to the reassigned ID are updated
    // across all tracks." This means: if a dep references an ID that was reassigned
    // (i.e., the duplicate's old ID was changed), those deps should be updated.
    // But since the keeper ALSO has that same old ID, the dep still resolves.
    // So dep rewriting is only needed if ALL instances of an ID were reassigned
    // (which never happens — the first keeps its ID). Therefore: no dep rewriting needed.

    // Child numbers already handed out in this batch, keyed by parent ID. Like
    // `staged` below, these aren't in the track yet, so two duplicates under one
    // parent would otherwise both be offered the same number.
    let mut staged_children: HashMap<String, u32> = HashMap::new();

    for dup in &duplicates {
        let Duplicate {
            old_id,
            track_id: dup_track_id,
            parent_id,
        } = dup;
        let prefix = project
            .config
            .ids
            .prefixes
            .get(dup_track_id.as_str())
            .cloned();
        let Some(pfx) = prefix else { continue };

        // Find the track the duplicate lives in
        let track = project
            .tracks
            .iter()
            .find(|(tid, _)| tid == dup_track_id)
            .map(|(_, t)| t);
        let Some(track) = track else { continue };

        // A nested duplicate is renumbered under its own parent. Falls through to
        // the top-level mint if the parent has gone missing or its ID doesn't
        // match the grammar, where there is no child number to hand out.
        let new_id = match parent_id
            .as_deref()
            .and_then(|pid| next_child_id_under(track, pid, token, &mut staged_children))
        {
            Some(child_id) => child_id,
            None => {
                // Reassignments already computed in this batch aren't in the
                // track yet, so they have to be floored in explicitly.
                let staged = reassignments
                    .values()
                    .flatten()
                    .filter_map(|new_id| TaskId::parse(new_id).top_level_number(&pfx, token))
                    .max()
                    .unwrap_or(0);

                let mint = Mint::new(&project.frame_dir, dup_track_id, &pfx, token);
                TaskId::with_number(&pfx, mint.next_above(track, staged), token).to_string()
            }
        };
        reassignments
            .entry(old_id.clone())
            .or_default()
            .push(new_id);
    }

    // Pass 3: Apply reassignments by walking tasks in the same track order.
    // For each duplicate ID, we consume the next new_id from the reassignments vec.
    let mut reassignment_cursors: HashMap<String, usize> = HashMap::new();
    let mut seen_in_apply: HashSet<String> = HashSet::new();

    for config_track_id in &track_order {
        if let Some((_, track)) = project
            .tracks
            .iter_mut()
            .find(|(tid, _)| tid == config_track_id)
        {
            for node in &mut track.nodes {
                if let TrackNode::Section { tasks, .. } = node {
                    apply_duplicate_reassignments(
                        tasks,
                        config_track_id,
                        token,
                        &reassignments,
                        &mut reassignment_cursors,
                        &mut seen_in_apply,
                        result,
                    );
                }
            }
        }
    }
}

/// The next free child number under `parent_id`, rendered as a full child ID.
///
/// `None` when the parent is gone or its own ID doesn't match the grammar —
/// there is no child number to extend in either case, and the caller falls back
/// to a top-level mint rather than inventing one.
///
/// `staged` carries the numbers already handed out under each parent in this
/// batch, which the track does not show yet.
fn next_child_id_under(
    track: &Track,
    parent_id: &str,
    token: Option<&Token>,
    staged: &mut HashMap<String, u32>,
) -> Option<String> {
    let parent = crate::ops::task_ops::find_task_in_track(track, parent_id)?;
    let parent_task_id = parent.id.as_ref().filter(|id| id.is_structured())?;

    let scanned = crate::ops::task_ops::next_child_number(parent, token) as u32;
    let slot = staged.entry(parent_id.to_string()).or_insert(0);
    let number = scanned.max(*slot + 1);
    *slot = number;
    Some(TaskId::child_of(parent_task_id, number, token).to_string())
}

fn find_duplicates_in_tasks(
    tasks: &[Task],
    track_id: &str,
    parent_id: Option<&str>,
    seen: &mut HashSet<String>,
    duplicates: &mut Vec<Duplicate>,
) {
    for task in tasks {
        if task
            .id
            .as_ref()
            .is_some_and(|id| !seen.insert(id.to_string()))
        {
            let id = task.id.as_ref().unwrap();
            duplicates.push(Duplicate {
                old_id: id.to_string(),
                track_id: track_id.to_string(),
                parent_id: parent_id.map(str::to_string),
            });
        }
        find_duplicates_in_tasks(
            &task.subtasks,
            track_id,
            task.id.as_deref(),
            seen,
            duplicates,
        );
    }
}

/// Walk tasks in order, applying reassignments to duplicate instances.
/// The first time we see an ID, it's the keeper (skip). Second+ times, reassign.
#[allow(clippy::too_many_arguments)]
fn apply_duplicate_reassignments(
    tasks: &mut [Task],
    track_id: &str,
    token: Option<&Token>,
    reassignments: &HashMap<String, Vec<String>>,
    cursors: &mut HashMap<String, usize>,
    seen: &mut HashSet<String>,
    result: &mut CleanResult,
) {
    for task in tasks.iter_mut() {
        let dup_old: Option<String> = task
            .id
            .as_ref()
            .map(|id| id.to_string())
            .filter(|id| reassignments.contains_key(id) && !seen.insert(id.clone()));
        if let Some(old_id) = dup_old {
            // This is a duplicate occurrence — reassign
            let cursor = cursors.entry(old_id.clone()).or_insert(0);
            if let Some(new_id) = reassignments.get(&old_id).and_then(|ids| ids.get(*cursor)) {
                task.id = Some(TaskId::parse(new_id));
                task.mark_dirty();
                renumber_subtasks(task, new_id, token);
                result.duplicates_resolved.push(DuplicateResolution {
                    track_id: track_id.to_string(),
                    original_id: old_id.clone(),
                    new_id: new_id.clone(),
                    title: task.title.clone(),
                });
                *cursor += 1;
            }
        }
        apply_duplicate_reassignments(
            &mut task.subtasks,
            track_id,
            token,
            reassignments,
            cursors,
            seen,
            result,
        );
    }
}

// ---------------------------------------------------------------------------
// 4. Validate deps
// ---------------------------------------------------------------------------

fn validate_deps(
    track: &Track,
    track_id: &str,
    all_ids: &HashSet<String>,
    result: &mut CleanResult,
) {
    for node in &track.nodes {
        if let TrackNode::Section { tasks, .. } = node {
            validate_deps_in_tasks(tasks, track_id, all_ids, result);
        }
    }
}

fn validate_deps_in_tasks(
    tasks: &[Task],
    track_id: &str,
    all_ids: &HashSet<String>,
    result: &mut CleanResult,
) {
    for task in tasks {
        let task_id = task.id.as_deref().unwrap_or("");
        for meta in &task.metadata {
            if let Metadata::Dep(deps) = meta {
                for dep_id in deps {
                    if !all_ids.contains(dep_id) {
                        result.dangling_deps.push(DanglingDep {
                            track_id: track_id.to_string(),
                            task_id: task_id.to_string(),
                            dep_id: dep_id.clone(),
                        });
                    }
                }
            }
        }
        validate_deps_in_tasks(&task.subtasks, track_id, all_ids, result);
    }
}

// ---------------------------------------------------------------------------
// 4. Validate file refs
// ---------------------------------------------------------------------------

fn validate_refs(track: &Track, track_id: &str, project_root: &Path, result: &mut CleanResult) {
    for node in &track.nodes {
        if let TrackNode::Section { tasks, .. } = node {
            validate_refs_in_tasks(tasks, track_id, project_root, result);
        }
    }
}

fn validate_refs_in_tasks(
    tasks: &[Task],
    track_id: &str,
    project_root: &Path,
    result: &mut CleanResult,
) {
    for task in tasks {
        let task_id = task.id.as_deref().unwrap_or("");
        for meta in &task.metadata {
            match meta {
                Metadata::Ref(refs) => {
                    for r in refs {
                        if !path_exists(project_root, r) {
                            result.broken_refs.push(BrokenRef {
                                track_id: track_id.to_string(),
                                task_id: task_id.to_string(),
                                path: r.clone(),
                                kind: RefKind::Ref,
                            });
                        }
                    }
                }
                Metadata::Spec(spec) => {
                    // spec can have #section suffix — strip it for file check
                    let file_path = spec.split('#').next().unwrap_or(spec);
                    if !path_exists(project_root, file_path) {
                        result.broken_refs.push(BrokenRef {
                            track_id: track_id.to_string(),
                            task_id: task_id.to_string(),
                            path: spec.clone(),
                            kind: RefKind::Spec,
                        });
                    }
                }
                _ => {}
            }
        }
        validate_refs_in_tasks(&task.subtasks, track_id, project_root, result);
    }
}

fn path_exists(project_root: &Path, relative_path: &str) -> bool {
    project_root.join(relative_path).exists()
}

// ---------------------------------------------------------------------------
// 5. State suggestions
// ---------------------------------------------------------------------------

fn collect_suggestions(track: &Track, track_id: &str, result: &mut CleanResult) {
    for node in &track.nodes {
        if let TrackNode::Section { tasks, .. } = node {
            collect_suggestions_in_tasks(tasks, track_id, result);
        }
    }
}

fn collect_suggestions_in_tasks(tasks: &[Task], track_id: &str, result: &mut CleanResult) {
    for task in tasks {
        if !task.subtasks.is_empty()
            && task.state != TaskState::Done
            && task.subtasks.iter().all(|s| s.state == TaskState::Done)
        {
            result.suggestions.push(Suggestion {
                track_id: track_id.to_string(),
                task_id: task.id.as_ref().map(|i| i.to_string()).unwrap_or_default(),
                kind: SuggestionKind::AllSubtasksDone,
            });
        }
        collect_suggestions_in_tasks(&task.subtasks, track_id, result);
    }
}

// ---------------------------------------------------------------------------
// 6. Archive done tasks past threshold
// ---------------------------------------------------------------------------

fn archive_done_tasks(project: &mut Project, result: &mut CleanResult) {
    if !project.config.clean.archive_per_track {
        return;
    }
    let threshold = project.config.clean.done_threshold;
    let retain = project.config.clean.done_retain;

    for (track_id, track) in &mut project.tracks {
        let done_tasks = track.section_tasks(SectionKind::Done);
        let done_task_count = done_tasks.len();
        if done_task_count <= threshold {
            continue;
        }

        // If we'd retain everything, skip archiving entirely
        if retain >= done_task_count {
            continue;
        }

        // Build (index, resolved_date) pairs, sort by resolved date descending.
        // Tasks without a resolved date get "" so they sort as oldest.
        let mut indexed: Vec<(usize, String)> = done_tasks
            .iter()
            .enumerate()
            .map(|(i, task)| {
                let resolved = task
                    .metadata
                    .iter()
                    .find_map(|m| {
                        if let Metadata::Resolved(d) = m {
                            Some(d.clone())
                        } else {
                            None
                        }
                    })
                    .unwrap_or_default();
                (i, resolved)
            })
            .collect();
        indexed.sort_by(|a, b| b.1.cmp(&a.1)); // most recent first

        // The top `retain` entries stay; the rest get archived
        let retain_indices: HashSet<usize> = indexed.iter().take(retain).map(|(i, _)| *i).collect();

        let tasks_to_archive: Vec<&Task> = done_tasks
            .iter()
            .enumerate()
            .filter(|(i, _)| !retain_indices.contains(i))
            .map(|(_, t)| t)
            .collect();
        if tasks_to_archive.is_empty() {
            continue;
        }

        let archive_path = project
            .frame_dir
            .join("archive")
            .join(format!("{}.md", track_id));
        if let Some(parent) = archive_path.parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        let existing = std::fs::read_to_string(&archive_path).unwrap_or_default();

        // Appending is not idempotent, so a task the archive already holds must
        // not be written a second time. That state is reachable: the archive is
        // written *before* the track is updated (below), deliberately, so a task
        // is never lost if the second write doesn't land — but if it doesn't (a
        // crash, or a `git checkout`/`reset` reverting the track file), the task
        // stays in Done and the next clean would archive it again.
        let already_archived = archived_task_ids(&existing);
        let (fresh, duplicates): (Vec<&Task>, Vec<&Task>) =
            tasks_to_archive.iter().partition(|task| {
                task.id
                    .as_ref()
                    .is_none_or(|id| !already_archived.contains(id.as_str()))
            });

        // The live copy of an already-archived task is about to be dropped from
        // the track. It should be identical to the archived one, but if it was
        // edited after that first write those edits would vanish silently — so
        // preserve it where anything lost goes.
        for task in &duplicates {
            let id = task.id.as_ref().map(|i| i.to_string()).unwrap_or_default();
            crate::io::recovery::log_recovery(
                &project.frame_dir,
                crate::io::recovery::RecoveryEntry {
                    timestamp: chrono::Utc::now(),
                    category: crate::io::recovery::RecoveryCategory::Conflict,
                    description: format!(
                        "{} was already in archive/{}.md — live copy removed from the track, not appended again",
                        id, track_id
                    ),
                    fields: vec![
                        ("track".to_string(), track_id.clone()),
                        ("task".to_string(), id),
                    ],
                    body: crate::parse::serialize_tasks(&[(*task).clone()], 0).join("\n"),
                },
            );
        }

        let archive_content =
            crate::parse::serialize_tasks(&fresh.iter().copied().cloned().collect::<Vec<_>>(), 0)
                .join("\n");

        // Nothing new to append (every task was already archived): skip the
        // write, but still extract below — leaving them in Done would make every
        // future clean retry the same no-op.
        if !archive_content.is_empty() {
            let new_content = if existing.is_empty() {
                format!("# Archive — {}\n\n{}", track_id, archive_content)
            } else {
                format!("{}\n{}", existing.trim_end(), archive_content)
            };

            // Write archive — if this fails, leave tasks in place
            if crate::io::recovery::atomic_write(&archive_path, new_content.as_bytes()).is_err() {
                eprintln!(
                    "warning: could not write archive for {}, skipping",
                    track_id
                );
                continue;
            }
        }

        // Only NOW extract non-retained tasks from the Done section
        let archived = extract_done_tasks_except(track, &retain_indices);
        for task in &archived {
            result.tasks_archived.push(ArchiveRecord {
                track_id: track_id.clone(),
                task_id: task.id.as_ref().map(|i| i.to_string()).unwrap_or_default(),
                title: task.title.clone(),
            });
        }
    }
}

/// The task IDs an archive file already holds, read straight from its task lines
/// (`- [x] \`ID\` …`) rather than parsed into tasks — this only needs to know
/// which IDs are present, and a raw scan can't be thrown off by note bodies or
/// hand-editing.
fn archived_task_ids(existing: &str) -> HashSet<String> {
    existing
        .lines()
        .filter_map(|line| {
            let trimmed = line.trim_start();
            if !trimmed.starts_with("- [") {
                return None;
            }
            let (_, after) = trimmed.split_once('`')?;
            let (id, _) = after.split_once('`')?;
            (!id.is_empty()).then(|| id.to_string())
        })
        .collect()
}

/// Remove done tasks from the track EXCEPT those at the given indices.
/// Returns the removed tasks.
fn extract_done_tasks_except(track: &mut Track, retain_indices: &HashSet<usize>) -> Vec<Task> {
    for node in &mut track.nodes {
        if let TrackNode::Section {
            kind: SectionKind::Done,
            tasks,
            ..
        } = node
        {
            let mut archived = Vec::new();
            let mut retained = Vec::new();
            for (i, task) in std::mem::take(tasks).into_iter().enumerate() {
                if retain_indices.contains(&i) {
                    retained.push(task);
                } else {
                    archived.push(task);
                }
            }
            *tasks = retained;
            return archived;
        }
    }
    Vec::new()
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn today_str() -> String {
    Local::now().format("%Y-%m-%d").to_string()
}

/// Collect all task IDs across every track in the project.
fn collect_all_task_ids(project: &Project) -> HashSet<String> {
    let mut ids = HashSet::new();
    for (_, track) in &project.tracks {
        for node in &track.nodes {
            if let TrackNode::Section { tasks, .. } = node {
                collect_ids_from_tasks(tasks, &mut ids);
            }
        }
    }
    ids
}

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

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::config::{
        AgentConfig, CleanConfig, IdConfig, ProjectConfig, ProjectInfo, TrackConfig, UiConfig,
    };
    use crate::parse::parse_track;
    use indexmap::IndexMap;
    use std::path::PathBuf;
    use tempfile::TempDir;

    fn make_config(prefixes: Vec<(&str, &str)>) -> ProjectConfig {
        let mut prefix_map = IndexMap::new();
        for (k, v) in &prefixes {
            prefix_map.insert(k.to_string(), v.to_string());
        }
        ProjectConfig {
            project: ProjectInfo {
                name: "test".to_string(),
            },
            agent: AgentConfig::default(),
            tracks: vec![TrackConfig {
                id: "main".to_string(),
                name: "Main".to_string(),
                state: "active".to_string(),
                file: "tracks/main.md".to_string(),
            }],
            clean: CleanConfig::default(),
            ids: IdConfig {
                prefixes: prefix_map,
            },
            ui: UiConfig::default(),
        }
    }

    fn make_project(track_src: &str, prefixes: Vec<(&str, &str)>) -> Project {
        let track = parse_track(track_src);
        Project {
            root: PathBuf::from("/tmp/test"),
            frame_dir: PathBuf::from("/tmp/test/frame"),
            config: make_config(prefixes),
            tracks: vec![("main".to_string(), track)],
            inbox: None,
        }
    }

    // --- 1. Assign missing IDs ---

    #[test]
    fn test_assign_missing_ids() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` Has ID
- [ ] Missing ID task
- [ ] Another missing

## Done
",
            vec![("main", "M")],
        );

        let result = clean_project(&mut project, IdScope::Mint(None));
        assert_eq!(result.ids_assigned.len(), 2);
        assert_eq!(result.ids_assigned[0].assigned_id, "M-002");
        assert_eq!(result.ids_assigned[0].title, "Missing ID task");
        assert_eq!(result.ids_assigned[1].assigned_id, "M-003");

        // Verify tasks were actually modified
        let backlog = project.tracks[0].1.backlog();
        assert_eq!(backlog[1].id.as_deref(), Some("M-002"));
        assert_eq!(backlog[2].id.as_deref(), Some("M-003"));
        assert!(backlog[1].dirty);
    }

    #[test]
    fn test_assign_missing_ids_no_prefix() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] No prefix configured

## Done
",
            vec![], // no prefixes
        );

        let result = clean_project(&mut project, IdScope::Mint(None));
        // Should not assign IDs if no prefix configured
        assert!(result.ids_assigned.is_empty());
    }

    #[test]
    fn test_assign_subtask_ids() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` Parent
  - [ ] Sub without ID
  - [ ] `M-001.2` Has ID

## Done
",
            vec![("main", "M")],
        );

        let result = clean_project(&mut project, IdScope::Mint(None));
        // Only the first subtask should get an ID assigned
        let sub_assignments: Vec<_> = result
            .ids_assigned
            .iter()
            .filter(|a| a.assigned_id.contains('.'))
            .collect();
        assert_eq!(sub_assignments.len(), 1);
        // Max existing child number is 2 (from M-001.2), so next is .3
        assert_eq!(sub_assignments[0].assigned_id, "M-001.3");
    }

    // --- 2. Assign missing dates ---

    #[test]
    fn test_assign_missing_dates() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` Has date
  - added: 2025-05-01
- [ ] `M-002` Missing date

## Done
",
            vec![("main", "M")],
        );

        let result = clean_project(&mut project, IdScope::Mint(None));
        assert_eq!(result.dates_assigned.len(), 1);
        assert_eq!(result.dates_assigned[0].task_id, "M-002");

        // Verify the task got the date
        let backlog = project.tracks[0].1.backlog();
        assert!(
            backlog[1]
                .metadata
                .iter()
                .any(|m| matches!(m, Metadata::Added(_)))
        );
    }

    #[test]
    fn test_assigns_missing_resolved_date() {
        let mut project = make_project(
            "\
# Main

## Done

- [x] `M-001` Has a resolved date
  - added: 2025-05-01
  - resolved: 2025-05-02
- [x] `M-002` Ticked done by hand, no resolved date
  - added: 2025-05-01
",
            vec![("main", "M")],
        );

        let result = clean_project(&mut project, IdScope::Mint(None));

        let resolved: Vec<_> = result
            .dates_assigned
            .iter()
            .filter(|d| d.kind == DateKind::Resolved)
            .collect();
        assert_eq!(resolved.len(), 1, "only the dateless done task");
        assert_eq!(resolved[0].task_id, "M-002");

        let done = project.tracks[0].1.done();
        assert!(
            done[1]
                .metadata
                .iter()
                .any(|m| matches!(m, Metadata::Resolved(_)))
        );
    }

    #[test]
    fn test_resolved_date_is_not_assigned_to_unfinished_tasks() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` Todo
  - added: 2025-05-01
- [~] `M-002` Parked
  - added: 2025-05-01
",
            vec![("main", "M")],
        );

        let result = clean_project(&mut project, IdScope::Mint(None));

        assert!(
            !result
                .dates_assigned
                .iter()
                .any(|d| d.kind == DateKind::Resolved),
            "only done tasks get a resolved date"
        );
    }

    /// Filling `resolved:` must not disturb archive retention, which ranks done
    /// tasks by that date and treats a missing one as oldest. Stamping the date
    /// before archival would make the oldest task look like the newest
    /// completion — it would be retained over genuinely recent work. The fill
    /// therefore runs after archival; this pins the ordering.
    #[test]
    fn test_missing_resolved_date_still_archives_first() {
        let root = PathBuf::from("/tmp/test-resolved-order");
        let track = parse_track(
            "\
# Main

## Done

- [x] `M-001` Dateless — must archive first
  - added: 2025-01-01
- [x] `M-002` Older
  - added: 2025-01-02
  - resolved: 2025-05-01
- [x] `M-003` Newest
  - added: 2025-01-03
  - resolved: 2025-05-20
",
        );

        let mut config = make_config(vec![("main", "M")]);
        config.clean.done_threshold = 1;
        config.clean.done_retain = 2;

        let mut project = Project {
            root: root.clone(),
            frame_dir: root.join("frame"),
            config,
            tracks: vec![("main".to_string(), track)],
            inbox: None,
        };

        let result = clean_project(&mut project, IdScope::Mint(None));

        let archived: Vec<&str> = result
            .tasks_archived
            .iter()
            .map(|a| a.task_id.as_str())
            .collect();
        assert_eq!(
            archived,
            vec!["M-001"],
            "the dateless task ranks oldest and is archived, not stamped with today"
        );

        let retained: Vec<&str> = project.tracks[0]
            .1
            .done()
            .iter()
            .filter_map(|t| t.id.as_deref())
            .collect();
        assert_eq!(retained, vec!["M-002", "M-003"]);
    }

    #[test]
    fn test_no_duplicate_dates() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` Already has date
  - added: 2025-01-01

## Done
",
            vec![("main", "M")],
        );

        let result = clean_project(&mut project, IdScope::Mint(None));
        assert!(result.dates_assigned.is_empty());
    }

    // --- 3. Validate deps ---

    #[test]
    fn test_dangling_deps() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` Task with good dep
  - dep: M-002
- [ ] `M-002` Target task
- [ ] `M-003` Task with bad dep
  - dep: NONEXIST-999

## Done
",
            vec![("main", "M")],
        );

        let result = clean_project(&mut project, IdScope::Mint(None));
        assert_eq!(result.dangling_deps.len(), 1);
        assert_eq!(result.dangling_deps[0].task_id, "M-003");
        assert_eq!(result.dangling_deps[0].dep_id, "NONEXIST-999");
    }

    #[test]
    fn test_cross_track_deps_valid() {
        let track_a = parse_track(
            "\
# Track A

## Backlog

- [ ] `A-001` Task A
  - dep: B-001

## Done
",
        );
        let track_b = parse_track(
            "\
# Track B

## Backlog

- [ ] `B-001` Task B

## Done
",
        );
        let mut project = Project {
            root: PathBuf::from("/tmp/test"),
            frame_dir: PathBuf::from("/tmp/test/frame"),
            config: {
                let mut cfg = make_config(vec![("a", "A"), ("b", "B")]);
                cfg.tracks = vec![
                    TrackConfig {
                        id: "a".to_string(),
                        name: "A".to_string(),
                        state: "active".to_string(),
                        file: "tracks/a.md".to_string(),
                    },
                    TrackConfig {
                        id: "b".to_string(),
                        name: "B".to_string(),
                        state: "active".to_string(),
                        file: "tracks/b.md".to_string(),
                    },
                ];
                cfg
            },
            tracks: vec![("a".to_string(), track_a), ("b".to_string(), track_b)],
            inbox: None,
        };

        let result = clean_project(&mut project, IdScope::Mint(None));
        assert!(result.dangling_deps.is_empty());
    }

    // --- 4. Validate refs ---

    #[test]
    fn test_broken_refs() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join("frame/tracks")).unwrap();
        // Create a file that exists
        std::fs::write(root.join("existing.md"), "hi").unwrap();

        let track = parse_track(
            "\
# Main

## Backlog

- [ ] `M-001` Task with refs
  - ref: existing.md
  - ref: missing.md
  - spec: also_missing.md#section

## Done
",
        );

        let mut project = Project {
            root: root.to_path_buf(),
            frame_dir: root.join("frame"),
            config: make_config(vec![("main", "M")]),
            tracks: vec![("main".to_string(), track)],
            inbox: None,
        };

        let result = clean_project(&mut project, IdScope::Mint(None));
        assert_eq!(result.broken_refs.len(), 2);
        assert_eq!(result.broken_refs[0].path, "missing.md");
        assert_eq!(result.broken_refs[0].kind, RefKind::Ref);
        assert_eq!(result.broken_refs[1].path, "also_missing.md#section");
        assert_eq!(result.broken_refs[1].kind, RefKind::Spec);
    }

    #[test]
    fn test_valid_refs() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join("frame/tracks")).unwrap();
        std::fs::create_dir_all(root.join("doc")).unwrap();
        std::fs::write(root.join("doc/spec.md"), "spec").unwrap();

        let track = parse_track(
            "\
# Main

## Backlog

- [ ] `M-001` Task with valid ref
  - spec: doc/spec.md#section

## Done
",
        );

        let mut project = Project {
            root: root.to_path_buf(),
            frame_dir: root.join("frame"),
            config: make_config(vec![("main", "M")]),
            tracks: vec![("main".to_string(), track)],
            inbox: None,
        };

        let result = clean_project(&mut project, IdScope::Mint(None));
        assert!(result.broken_refs.is_empty());
    }

    // --- 5. Suggestions ---

    #[test]
    fn test_suggest_parent_done_when_all_subtasks_done() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` Parent with all done subs
  - [x] `M-001.1` Sub one
    - resolved: 2025-05-10
  - [x] `M-001.2` Sub two
    - resolved: 2025-05-11
- [ ] `M-002` Parent with mixed subs
  - [x] `M-002.1` Done sub
  - [ ] `M-002.2` Todo sub

## Done
",
            vec![("main", "M")],
        );

        let result = clean_project(&mut project, IdScope::Mint(None));
        assert_eq!(result.suggestions.len(), 1);
        assert_eq!(result.suggestions[0].task_id, "M-001");
        assert_eq!(result.suggestions[0].kind, SuggestionKind::AllSubtasksDone);
    }

    #[test]
    fn test_no_suggestion_for_already_done_parent() {
        let mut project = make_project(
            "\
# Main

## Backlog

## Done

- [x] `M-001` Already done parent
  - resolved: 2025-05-10
  - [x] `M-001.1` Sub one
  - [x] `M-001.2` Sub two
",
            vec![("main", "M")],
        );

        let result = clean_project(&mut project, IdScope::Mint(None));
        assert!(result.suggestions.is_empty());
    }

    #[test]
    fn test_no_suggestion_for_leaf_tasks() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` Leaf task with no subtasks

## Done
",
            vec![("main", "M")],
        );

        let result = clean_project(&mut project, IdScope::Mint(None));
        assert!(result.suggestions.is_empty());
    }

    // --- 6. Archive done tasks ---

    #[test]
    fn test_archive_done_past_threshold() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join("frame/tracks")).unwrap();

        // Build a track with many done tasks to exceed threshold
        let mut done_lines = String::new();
        for i in 0..100 {
            done_lines.push_str(&format!(
                "- [x] `M-{:03}` Done task {}\n  - added: 2025-01-01\n  - resolved: 2025-05-{:02}\n",
                i, i, (i % 28) + 1
            ));
        }

        let src = format!(
            "\
# Main

## Backlog

- [ ] `M-200` Active task

## Done

{}",
            done_lines.trim_end()
        );

        let track = parse_track(&src);

        let mut config = make_config(vec![("main", "M")]);
        config.clean.done_threshold = 10; // low threshold to trigger archive
        config.clean.done_retain = 0; // retain none so all 100 are archived

        let mut project = Project {
            root: root.to_path_buf(),
            frame_dir: root.join("frame"),
            config,
            tracks: vec![("main".to_string(), track)],
            inbox: None,
        };

        let result = clean_project(&mut project, IdScope::Mint(None));
        assert_eq!(result.tasks_archived.len(), 100);

        // Done section should now be empty
        let done = project.tracks[0].1.done();
        assert!(done.is_empty());

        // Archive file should exist
        let archive_path = root.join("frame/archive/main.md");
        assert!(archive_path.exists());
    }

    /// A task the archive already holds must not be appended twice.
    ///
    /// Reachable because the archive is written before the track is updated: if
    /// that second write is lost (crash, or a git revert of the track file), the
    /// task is still in Done and the next clean would archive it again. This is
    /// what produced a doubled archive in a real project.
    #[test]
    fn test_archive_does_not_duplicate_an_already_archived_task() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join("frame/archive")).unwrap();

        // The state left behind by an interrupted clean: already in the archive,
        // still in Done.
        std::fs::write(
            root.join("frame/archive/main.md"),
            "# Archive \u{2014} main\n\n- [x] `M-001` First\n  - resolved: 2025-05-01\n",
        )
        .unwrap();

        let track = parse_track(
            "\
# Main

## Backlog

## Done

- [x] `M-001` First
  - added: 2025-01-01
  - resolved: 2025-05-01
- [x] `M-002` Second
  - added: 2025-01-02
  - resolved: 2025-05-02
",
        );

        let mut config = make_config(vec![("main", "M")]);
        config.clean.done_threshold = 1;
        config.clean.done_retain = 0;

        let mut project = Project {
            root: root.to_path_buf(),
            frame_dir: root.join("frame"),
            config,
            tracks: vec![("main".to_string(), track)],
            inbox: None,
        };

        clean_project(&mut project, IdScope::Mint(None));

        let archive = std::fs::read_to_string(root.join("frame/archive/main.md")).unwrap();
        assert_eq!(
            archive.matches("`M-001`").count(),
            1,
            "M-001 was appended twice:\n{archive}"
        );
        assert_eq!(
            archive.matches("`M-002`").count(),
            1,
            "M-002 should be archived once:\n{archive}"
        );
        // Both leave the track either way — leaving the duplicate in Done would
        // make every future clean retry it.
        assert!(project.tracks[0].1.done().is_empty());

        // The live copy of the skipped task is preserved where lost data goes.
        let log = std::fs::read_to_string(root.join("frame/.recovery.log")).unwrap();
        assert!(log.contains("M-001"), "recovery log should hold it:\n{log}");
        assert!(log.contains("already in archive/main.md"), "{log}");
    }

    /// Every task already archived: nothing to append, but Done still drains.
    #[test]
    fn test_archive_all_duplicates_still_clears_done() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join("frame/archive")).unwrap();
        let original = "# Archive \u{2014} main\n\n- [x] `M-001` First\n  - resolved: 2025-05-01\n";
        std::fs::write(root.join("frame/archive/main.md"), original).unwrap();

        let track = parse_track(
            "\
# Main

## Backlog

## Done

- [x] `M-001` First
  - added: 2025-01-01
  - resolved: 2025-05-01
",
        );

        let mut config = make_config(vec![("main", "M")]);
        config.clean.done_threshold = 0;
        config.clean.done_retain = 0;

        let mut project = Project {
            root: root.to_path_buf(),
            frame_dir: root.join("frame"),
            config,
            tracks: vec![("main".to_string(), track)],
            inbox: None,
        };

        clean_project(&mut project, IdScope::Mint(None));

        assert_eq!(
            std::fs::read_to_string(root.join("frame/archive/main.md")).unwrap(),
            original,
            "archive should be untouched when there is nothing new to append"
        );
        assert!(project.tracks[0].1.done().is_empty());
    }

    #[test]
    fn test_archived_task_ids_reads_task_lines_only() {
        let ids = archived_task_ids(
            "\
# Archive \u{2014} main

- [x] `M-001` First
  - note:
    A note mentioning `M-999` in prose, and a fake `- [x] `M-998`` line.
  - [x] `M-001.1` Subtask
- [x] `M-a7` Another namespace
",
        );
        assert!(ids.contains("M-001"));
        assert!(ids.contains("M-001.1"), "subtask lines count too");
        assert!(ids.contains("M-a7"));
        assert!(!ids.contains("M-999"), "prose is not a task line");
        assert_eq!(ids.len(), 3, "{ids:?}");
    }

    #[test]
    fn test_no_archive_under_threshold() {
        let mut project = make_project(
            "\
# Main

## Backlog

## Done

- [x] `M-001` One done task
  - resolved: 2025-05-10
",
            vec![("main", "M")],
        );

        let result = clean_project(&mut project, IdScope::Mint(None));
        assert!(result.tasks_archived.is_empty());
    }

    #[test]
    fn test_archive_threshold_counts_tasks_not_lines() {
        // 5 tasks with verbose metadata = many lines but only 5 tasks.
        // With threshold of 5, should NOT archive (5 <= 5).
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join("frame/tracks")).unwrap();

        let src = "\
# Main

## Backlog

- [ ] `M-100` Active task

## Done

- [x] `M-001` Task one
  - added: 2025-01-01
  - resolved: 2025-05-01
  - note:
    A long multi-line note that spans
    several lines to inflate the line count
    well beyond what a simple task would use.
- [x] `M-002` Task two
  - added: 2025-01-02
  - resolved: 2025-05-02
  - note:
    Another verbose note here
    with multiple lines
- [x] `M-003` Task three
  - added: 2025-01-03
  - resolved: 2025-05-03
  - spec: doc/spec.md
  - ref: doc/ref1.md, doc/ref2.md
  - note: Short note
- [x] `M-004` Task four
  - added: 2025-01-04
  - resolved: 2025-05-04
- [x] `M-005` Task five
  - added: 2025-01-05
  - resolved: 2025-05-05
";

        let track = parse_track(src);

        let mut config = make_config(vec![("main", "M")]);
        config.clean.done_threshold = 5; // exactly 5 tasks

        let mut project = Project {
            root: root.to_path_buf(),
            frame_dir: root.join("frame"),
            config,
            tracks: vec![("main".to_string(), track)],
            inbox: None,
        };

        let result = clean_project(&mut project, IdScope::Mint(None));
        // 5 tasks <= threshold of 5, so nothing should be archived
        assert!(result.tasks_archived.is_empty());
        assert_eq!(project.tracks[0].1.done().len(), 5);
    }

    #[test]
    fn test_archive_triggers_above_task_threshold() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join("frame/tracks")).unwrap();

        let src = "\
# Main

## Backlog

- [ ] `M-100` Active task

## Done

- [x] `M-001` Task one
  - added: 2025-01-01
  - resolved: 2025-05-01
- [x] `M-002` Task two
  - added: 2025-01-02
  - resolved: 2025-05-02
- [x] `M-003` Task three
  - added: 2025-01-03
  - resolved: 2025-05-03
";

        let track = parse_track(src);

        let mut config = make_config(vec![("main", "M")]);
        config.clean.done_threshold = 2; // 3 tasks > 2
        config.clean.done_retain = 0; // retain none so all 3 are archived

        let mut project = Project {
            root: root.to_path_buf(),
            frame_dir: root.join("frame"),
            config,
            tracks: vec![("main".to_string(), track)],
            inbox: None,
        };

        let result = clean_project(&mut project, IdScope::Mint(None));
        assert_eq!(result.tasks_archived.len(), 3);
        assert!(project.tracks[0].1.done().is_empty());
    }

    #[test]
    fn test_archive_retains_most_recent() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join("frame/tracks")).unwrap();

        let src = "\
# Main

## Backlog

- [ ] `M-100` Active task

## Done

- [x] `M-001` Oldest task
  - added: 2025-01-01
  - resolved: 2025-05-01
- [x] `M-002` No resolved date
  - added: 2025-01-02
- [x] `M-003` Middle task
  - added: 2025-01-03
  - resolved: 2025-05-10
- [x] `M-004` Most recent
  - added: 2025-01-04
  - resolved: 2025-05-20
- [x] `M-005` Second most recent
  - added: 2025-01-05
  - resolved: 2025-05-15
";

        let track = parse_track(src);

        let mut config = make_config(vec![("main", "M")]);
        config.clean.done_threshold = 2; // 5 tasks > 2, triggers archive
        config.clean.done_retain = 2; // keep the 2 most recent

        let mut project = Project {
            root: root.to_path_buf(),
            frame_dir: root.join("frame"),
            config,
            tracks: vec![("main".to_string(), track)],
            inbox: None,
        };

        let result = clean_project(&mut project, IdScope::Mint(None));

        // 5 tasks - 2 retained = 3 archived
        assert_eq!(result.tasks_archived.len(), 3);

        // The 2 most recent (by resolved date) should remain
        let done = project.tracks[0].1.done();
        assert_eq!(done.len(), 2);
        let retained_ids: Vec<&str> = done.iter().filter_map(|t| t.id.as_deref()).collect();
        // M-004 (2025-05-20) and M-005 (2025-05-15) are most recent
        assert!(retained_ids.contains(&"M-004"));
        assert!(retained_ids.contains(&"M-005"));

        // The archived tasks should include M-001, M-002 (no date), and M-003
        let archived_ids: Vec<&str> = result
            .tasks_archived
            .iter()
            .map(|a| a.task_id.as_str())
            .collect();
        assert!(archived_ids.contains(&"M-001"));
        assert!(archived_ids.contains(&"M-002"));
        assert!(archived_ids.contains(&"M-003"));
    }

    #[test]
    fn test_archive_retain_exceeds_count() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join("frame/tracks")).unwrap();

        let src = "\
# Main

## Backlog

- [ ] `M-100` Active task

## Done

- [x] `M-001` Task one
  - added: 2025-01-01
  - resolved: 2025-05-01
- [x] `M-002` Task two
  - added: 2025-01-02
  - resolved: 2025-05-02
- [x] `M-003` Task three
  - added: 2025-01-03
  - resolved: 2025-05-03
";

        let track = parse_track(src);

        let mut config = make_config(vec![("main", "M")]);
        config.clean.done_threshold = 2; // 3 > 2, would normally trigger
        config.clean.done_retain = 5; // but retain 5 > count of 3

        let mut project = Project {
            root: root.to_path_buf(),
            frame_dir: root.join("frame"),
            config,
            tracks: vec![("main".to_string(), track)],
            inbox: None,
        };

        let result = clean_project(&mut project, IdScope::Mint(None));

        // Nothing should be archived since retain >= count
        assert!(result.tasks_archived.is_empty());
        assert_eq!(project.tracks[0].1.done().len(), 3);

        // No archive file should have been created
        let archive_path = root.join("frame/archive/main.md");
        assert!(!archive_path.exists());
    }

    // --- 3. Duplicate ID resolution ---

    #[test]
    fn test_resolve_duplicate_ids_cross_track() {
        let track_a = parse_track(
            "\
# Track A

## Backlog

- [ ] `DUP-001` First occurrence in A
  - added: 2025-05-01

## Done
",
        );
        let track_b = parse_track(
            "\
# Track B

## Backlog

- [ ] `DUP-001` Duplicate in B
  - added: 2025-05-02

## Done
",
        );
        let mut project = Project {
            root: PathBuf::from("/tmp/test"),
            frame_dir: PathBuf::from("/tmp/test/frame"),
            config: {
                let mut cfg = make_config(vec![("a", "A"), ("b", "B")]);
                cfg.tracks = vec![
                    TrackConfig {
                        id: "a".to_string(),
                        name: "A".to_string(),
                        state: "active".to_string(),
                        file: "tracks/a.md".to_string(),
                    },
                    TrackConfig {
                        id: "b".to_string(),
                        name: "B".to_string(),
                        state: "active".to_string(),
                        file: "tracks/b.md".to_string(),
                    },
                ];
                cfg
            },
            tracks: vec![("a".to_string(), track_a), ("b".to_string(), track_b)],
            inbox: None,
        };

        let result = clean_project(&mut project, IdScope::Mint(None));

        // Track A's DUP-001 should be kept, track B's should be reassigned
        assert_eq!(result.duplicates_resolved.len(), 1);
        assert_eq!(result.duplicates_resolved[0].track_id, "b");
        assert_eq!(result.duplicates_resolved[0].original_id, "DUP-001");
        assert_eq!(result.duplicates_resolved[0].title, "Duplicate in B");

        // Track A keeps its ID
        let a_backlog = project.tracks[0].1.backlog();
        assert_eq!(a_backlog[0].id.as_deref(), Some("DUP-001"));

        // Track B got a new ID (B-prefix, max+1)
        let b_backlog = project.tracks[1].1.backlog();
        assert_eq!(b_backlog[0].id.as_deref(), Some("B-001"));
    }

    #[test]
    fn test_resolve_duplicate_ids_within_track() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` First occurrence
  - added: 2025-05-01
- [ ] `M-001` Duplicate in same track
  - added: 2025-05-02

## Done
",
            vec![("main", "M")],
        );

        let result = clean_project(&mut project, IdScope::Mint(None));

        assert_eq!(result.duplicates_resolved.len(), 1);
        assert_eq!(result.duplicates_resolved[0].original_id, "M-001");
        assert_eq!(
            result.duplicates_resolved[0].title,
            "Duplicate in same track"
        );

        let backlog = project.tracks[0].1.backlog();
        assert_eq!(backlog[0].id.as_deref(), Some("M-001"));
        assert_eq!(backlog[1].id.as_deref(), Some("M-002"));
    }

    #[test]
    fn test_resolve_duplicate_ids_track_order_precedence() {
        // Track order in config is [b, a], so track B should keep the ID
        let track_a = parse_track(
            "\
# Track A

## Backlog

- [ ] `X-001` In track A
  - added: 2025-05-01

## Done
",
        );
        let track_b = parse_track(
            "\
# Track B

## Backlog

- [ ] `X-001` In track B
  - added: 2025-05-02

## Done
",
        );
        let mut project = Project {
            root: PathBuf::from("/tmp/test"),
            frame_dir: PathBuf::from("/tmp/test/frame"),
            config: {
                let mut cfg = make_config(vec![("a", "A"), ("b", "B")]);
                // Track B comes first in config → it has precedence
                cfg.tracks = vec![
                    TrackConfig {
                        id: "b".to_string(),
                        name: "B".to_string(),
                        state: "active".to_string(),
                        file: "tracks/b.md".to_string(),
                    },
                    TrackConfig {
                        id: "a".to_string(),
                        name: "A".to_string(),
                        state: "active".to_string(),
                        file: "tracks/a.md".to_string(),
                    },
                ];
                cfg
            },
            tracks: vec![("a".to_string(), track_a), ("b".to_string(), track_b)],
            inbox: None,
        };

        let result = clean_project(&mut project, IdScope::Mint(None));

        // Track B is first in config, so it keeps X-001. Track A's gets reassigned.
        assert_eq!(result.duplicates_resolved.len(), 1);
        assert_eq!(result.duplicates_resolved[0].track_id, "a");
        assert_eq!(result.duplicates_resolved[0].original_id, "X-001");

        // Track A got reassigned with A-prefix
        let a_backlog = project
            .tracks
            .iter()
            .find(|(id, _)| id == "a")
            .unwrap()
            .1
            .backlog();
        assert_eq!(a_backlog[0].id.as_deref(), Some("A-001"));

        // Track B keeps its ID
        let b_backlog = project
            .tracks
            .iter()
            .find(|(id, _)| id == "b")
            .unwrap()
            .1
            .backlog();
        assert_eq!(b_backlog[0].id.as_deref(), Some("X-001"));
    }

    #[test]
    fn test_resolve_duplicate_ids_renumbers_subtasks() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` First
  - added: 2025-05-01
- [ ] `M-001` Duplicate parent with subtasks
  - added: 2025-05-02
  - [ ] `M-001.1` Sub one
    - added: 2025-05-02
  - [ ] `M-001.2` Sub two
    - added: 2025-05-02

## Done
",
            vec![("main", "M")],
        );

        let result = clean_project(&mut project, IdScope::Mint(None));

        assert_eq!(result.duplicates_resolved.len(), 1);
        let backlog = project.tracks[0].1.backlog();
        // First keeps M-001
        assert_eq!(backlog[0].id.as_deref(), Some("M-001"));
        // Duplicate gets M-002
        assert_eq!(backlog[1].id.as_deref(), Some("M-002"));
        // Subtasks renumbered
        assert_eq!(backlog[1].subtasks[0].id.as_deref(), Some("M-002.1"));
        assert_eq!(backlog[1].subtasks[1].id.as_deref(), Some("M-002.2"));
    }

    /// The collision two worktrees of one clone can still produce: both add a
    /// subtask to the same parent, both mint `.4`, the merge keeps both.
    ///
    /// Resolution has to come from the *parent's* child numbering. Minting a
    /// top-level `M-002` here would make the ID unique while breaking the rule
    /// that a subtask's ID extends its parent's.
    #[test]
    fn test_resolve_duplicate_subtask_renumbers_under_its_parent() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` Parent
  - added: 2025-05-01
  - [ ] `M-001.4` Mine
    - added: 2025-05-01
  - [ ] `M-001.4` Theirs
    - added: 2025-05-01

## Done
",
            vec![("main", "M")],
        );

        let result = clean_project(&mut project, IdScope::Mint(None));

        assert_eq!(result.duplicates_resolved.len(), 1);
        assert_eq!(result.duplicates_resolved[0].original_id, "M-001.4");
        assert_eq!(result.duplicates_resolved[0].new_id, "M-001.5");

        let backlog = project.tracks[0].1.backlog();
        assert_eq!(backlog.len(), 1, "no task was promoted to top level");
        assert_eq!(backlog[0].subtasks[0].id.as_deref(), Some("M-001.4"));
        assert_eq!(backlog[0].subtasks[1].id.as_deref(), Some("M-001.5"));
    }

    /// Two collisions under one parent in a single pass: the second cannot be
    /// offered the number the first just took, which the track does not show yet.
    #[test]
    fn test_resolve_duplicate_subtasks_stage_within_one_parent() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` Parent
  - added: 2025-05-01
  - [ ] `M-001.1` Original
    - added: 2025-05-01
  - [ ] `M-001.1` Copy one
    - added: 2025-05-01
  - [ ] `M-001.1` Copy two
    - added: 2025-05-01

## Done
",
            vec![("main", "M")],
        );

        clean_project(&mut project, IdScope::Mint(None));

        let subs = &project.tracks[0].1.backlog()[0].subtasks;
        let ids: Vec<_> = subs.iter().filter_map(|s| s.id.as_deref()).collect();
        assert_eq!(ids, vec!["M-001.1", "M-001.2", "M-001.3"]);
    }

    /// A duplicate nested two deep is renumbered under *its* parent, not the
    /// top-level task at the root of the branch.
    #[test]
    fn test_resolve_duplicate_grandchild_renumbers_under_its_own_parent() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` Parent
  - added: 2025-05-01
  - [ ] `M-001.1` Child
    - added: 2025-05-01
    - [ ] `M-001.1.2` Grandchild
      - added: 2025-05-01
    - [ ] `M-001.1.2` Grandchild twin
      - added: 2025-05-01

## Done
",
            vec![("main", "M")],
        );

        clean_project(&mut project, IdScope::Mint(None));

        let grandkids = &project.tracks[0].1.backlog()[0].subtasks[0].subtasks;
        assert_eq!(grandkids[0].id.as_deref(), Some("M-001.1.2"));
        assert_eq!(grandkids[1].id.as_deref(), Some("M-001.1.3"));
    }

    /// A renumbered subtask carries its own descendants with it.
    #[test]
    fn test_resolve_duplicate_subtask_rekeys_descendants() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` Parent
  - added: 2025-05-01
  - [ ] `M-001.1` Original
    - added: 2025-05-01
  - [ ] `M-001.1` Twin
    - added: 2025-05-01
    - [ ] `M-001.1.1` Twin's child
      - added: 2025-05-01

## Done
",
            vec![("main", "M")],
        );

        clean_project(&mut project, IdScope::Mint(None));

        let twin = &project.tracks[0].1.backlog()[0].subtasks[1];
        assert_eq!(twin.id.as_deref(), Some("M-001.2"));
        assert_eq!(twin.subtasks[0].id.as_deref(), Some("M-001.2.1"));
    }

    /// A duplicated subtask under a token-namespace clean is renumbered in that
    /// namespace, still under its parent.
    #[test]
    fn test_resolve_duplicate_subtask_in_token_namespace() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` Parent
  - added: 2025-05-01
  - [ ] `M-001.1` Original
    - added: 2025-05-01
  - [ ] `M-001.1` Twin
    - added: 2025-05-01

## Done
",
            vec![("main", "M")],
        );

        let token = Token::new("b").unwrap();
        clean_project(&mut project, IdScope::Mint(Some(token)));

        let subs = &project.tracks[0].1.backlog()[0].subtasks;
        assert_eq!(subs[0].id.as_deref(), Some("M-001.1"));
        assert_eq!(subs[1].id.as_deref(), Some("M-001.b1"));
    }

    /// The resolved project is clean by `fr check`'s reckoning — no leftover
    /// duplicate, and no subtask whose id escaped its parent.
    #[test]
    fn test_resolve_duplicate_subtask_leaves_no_check_finding() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` Parent
  - added: 2025-05-01
  - [ ] `M-001.4` Mine
    - added: 2025-05-01
  - [ ] `M-001.4` Theirs
    - added: 2025-05-01

## Done
",
            vec![("main", "M")],
        );

        clean_project(&mut project, IdScope::Mint(None));

        let check = crate::ops::check::check_project(&project);
        assert!(
            !check
                .errors
                .iter()
                .any(|e| matches!(e, crate::ops::check::CheckError::DuplicateId { .. })),
            "duplicate survived: {:?}",
            check.errors
        );
        assert!(
            !check.warnings.iter().any(|w| matches!(
                w,
                crate::ops::check::CheckWarning::ChildIdNotUnderParent { .. }
            )),
            "resolution misparented a subtask: {:?}",
            check.warnings
        );
    }

    #[test]
    fn test_no_duplicates_no_changes() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` Task one
  - added: 2025-05-01
- [ ] `M-002` Task two
  - added: 2025-05-01

## Done
",
            vec![("main", "M")],
        );

        let result = clean_project(&mut project, IdScope::Mint(None));
        assert!(result.duplicates_resolved.is_empty());
    }

    // --- Combined clean operations ---

    #[test]
    fn test_clean_assigns_ids_then_validates_deps() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` Task one
  - dep: M-002
- [ ] `M-002` Task two

## Done
",
            vec![("main", "M")],
        );

        let result = clean_project(&mut project, IdScope::Mint(None));
        // Deps should be valid (M-002 exists)
        assert!(result.dangling_deps.is_empty());
    }

    #[test]
    fn test_clean_full_run() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join("frame/tracks")).unwrap();
        std::fs::write(root.join("doc.md"), "doc").unwrap();

        let track = parse_track(
            "\
# Main

## Backlog

- [ ] `M-001` Has everything
  - added: 2025-05-01
  - dep: M-002
  - ref: doc.md
- [ ] Missing ID and date
- [ ] `M-002` Second task

## Done
",
        );

        let mut project = Project {
            root: root.to_path_buf(),
            frame_dir: root.join("frame"),
            config: make_config(vec![("main", "M")]),
            tracks: vec![("main".to_string(), track)],
            inbox: None,
        };

        let result = clean_project(&mut project, IdScope::Mint(None));

        // Should have assigned 1 ID
        assert_eq!(result.ids_assigned.len(), 1);
        assert_eq!(result.ids_assigned[0].title, "Missing ID and date");

        // Should have assigned dates to tasks missing them
        assert!(!result.dates_assigned.is_empty());

        // No dangling deps (M-002 exists)
        assert!(result.dangling_deps.is_empty());

        // No broken refs (doc.md exists)
        assert!(result.broken_refs.is_empty());
    }

    // --- ensure_ids_and_dates ---

    #[test]
    fn test_ensure_ids_and_dates_basic() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` Has ID and date
  - added: 2025-05-01
- [ ] Missing everything

## Done
",
            vec![("main", "M")],
        );

        let modified = ensure_ids_and_dates(&mut project, IdScope::Mint(None));
        assert_eq!(modified, vec!["main".to_string()]);

        let backlog = project.tracks[0].1.backlog();
        // Second task should now have an ID
        assert_eq!(backlog[1].id.as_deref(), Some("M-002"));
        // Second task should now have an added date
        assert!(
            backlog[1]
                .metadata
                .iter()
                .any(|m| matches!(m, Metadata::Added(_)))
        );
    }

    #[test]
    fn test_ensure_ids_and_dates_no_changes() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` All good
  - added: 2025-05-01
- [ ] `M-002` Also good
  - added: 2025-05-02

## Done
",
            vec![("main", "M")],
        );

        let modified = ensure_ids_and_dates(&mut project, IdScope::Mint(None));
        assert!(modified.is_empty());
    }

    #[test]
    fn test_ensure_ids_and_dates_no_prefix() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] No prefix configured

## Done
",
            vec![], // no prefixes
        );

        let modified = ensure_ids_and_dates(&mut project, IdScope::Mint(None));
        // Should still assign dates even without a prefix
        assert_eq!(modified, vec!["main".to_string()]);
        // But should NOT assign IDs
        let backlog = project.tracks[0].1.backlog();
        assert!(backlog[0].id.is_none());
        // Should have an added date
        assert!(
            backlog[0]
                .metadata
                .iter()
                .any(|m| matches!(m, Metadata::Added(_)))
        );
    }

    #[test]
    fn test_ensure_ids_and_dates_resolves_duplicates() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` First occurrence
  - added: 2025-05-01
- [ ] `M-001` Duplicate
  - added: 2025-05-02

## Done
",
            vec![("main", "M")],
        );

        let modified = ensure_ids_and_dates(&mut project, IdScope::Mint(None));
        assert!(modified.contains(&"main".to_string()));

        let backlog = project.tracks[0].1.backlog();
        assert_eq!(backlog[0].id.as_deref(), Some("M-001"));
        assert_eq!(backlog[1].id.as_deref(), Some("M-002"));
    }

    // --- Section reconciliation ---

    #[test]
    fn test_reconcile_parked_task_in_backlog() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` Normal task
  - added: 2025-05-01
- [~] `M-002` Should be in Parked
  - added: 2025-05-02

## Done
",
            vec![("main", "M")],
        );

        let result = clean_project(&mut project, IdScope::Mint(None));
        assert_eq!(result.sections_reconciled.len(), 1);
        assert_eq!(result.sections_reconciled[0].task_id, "M-002");
        assert_eq!(result.sections_reconciled[0].from, SectionKind::Backlog);
        assert_eq!(result.sections_reconciled[0].to, SectionKind::Parked);

        // Task should now be in Parked section
        assert_eq!(project.tracks[0].1.parked().len(), 1);
        assert_eq!(project.tracks[0].1.parked()[0].id.as_deref(), Some("M-002"));
        // And removed from Backlog
        assert_eq!(project.tracks[0].1.backlog().len(), 1);
    }

    #[test]
    fn test_reconcile_done_task_in_backlog() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [x] `M-001` Done but stuck in Backlog
  - added: 2025-05-01
  - resolved: 2025-05-10

## Done
",
            vec![("main", "M")],
        );

        let result = clean_project(&mut project, IdScope::Mint(None));
        assert_eq!(result.sections_reconciled.len(), 1);
        assert_eq!(result.sections_reconciled[0].to, SectionKind::Done);

        assert_eq!(project.tracks[0].1.done().len(), 1);
        assert!(project.tracks[0].1.backlog().is_empty());
    }

    #[test]
    fn test_reconcile_unparked_task_in_parked() {
        let mut project = make_project(
            "\
# Main

## Backlog

## Parked

- [ ] `M-001` Unparked but stuck in Parked section
  - added: 2025-05-01

## Done
",
            vec![("main", "M")],
        );

        let result = clean_project(&mut project, IdScope::Mint(None));
        assert_eq!(result.sections_reconciled.len(), 1);
        assert_eq!(result.sections_reconciled[0].from, SectionKind::Parked);
        assert_eq!(result.sections_reconciled[0].to, SectionKind::Backlog);

        assert_eq!(project.tracks[0].1.backlog().len(), 1);
        assert!(project.tracks[0].1.parked().is_empty());
    }

    #[test]
    fn test_reconcile_no_changes_when_correct() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` Normal task
  - added: 2025-05-01

## Parked

- [~] `M-002` Correctly parked
  - added: 2025-05-02

## Done

- [x] `M-003` Correctly done
  - added: 2025-05-03
  - resolved: 2025-05-10
",
            vec![("main", "M")],
        );

        let result = clean_project(&mut project, IdScope::Mint(None));
        assert!(result.sections_reconciled.is_empty());
    }

    #[test]
    fn test_reconcile_via_ensure_ids_and_dates() {
        let mut project = make_project(
            "\
# Main

## Backlog

- [~] `M-001` Parked in wrong section
  - added: 2025-05-01

## Done
",
            vec![("main", "M")],
        );

        let modified = ensure_ids_and_dates(&mut project, IdScope::Mint(None));
        assert!(modified.contains(&"main".to_string()));
        assert_eq!(project.tracks[0].1.parked().len(), 1);
        assert!(project.tracks[0].1.backlog().is_empty());
    }

    #[test]
    fn test_assign_subtask_ids_after_deletion() {
        // If subtask .3 was deleted from [.1, .2, .3, .4], and a new subtask
        // without an ID is added, it should get .5, not .4 (which already exists).
        let track = parse_track(
            "\
# Test

## Backlog

- [ ] `T-001` Parent
  - [ ] `T-001.1` Sub 1
  - [ ] `T-001.2` Sub 2
  - [ ] `T-001.4` Sub 4
  - [ ] New subtask without ID

## Done",
        );

        let config = make_config(vec![("main", "T")]);
        let root = TempDir::new().unwrap();
        let mut project = Project {
            config,
            root: root.path().to_path_buf(),
            frame_dir: root.path().join("frame"),
            tracks: vec![("main".to_string(), track)],
            inbox: None,
        };

        let modified = ensure_ids_and_dates(&mut project, IdScope::Mint(None));
        assert!(modified.contains(&"main".to_string()));

        // The new subtask should get .5 (not .4 which already exists)
        let parent =
            crate::ops::task_ops::find_task_in_track(&project.tracks[0].1, "T-001").unwrap();
        let new_sub = &parent.subtasks[3];
        assert_eq!(new_sub.id.as_deref(), Some("T-001.5"));
    }

    // --- Namespace-scoped minting (Phase 3) ---

    #[test]
    fn test_clean_assigns_missing_ids_in_token_namespace() {
        let token = Token::new("a").unwrap();
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` Has null ID
- [ ] Missing ID task
  - [ ] Missing subtask ID

## Done
",
            vec![("main", "M")],
        );

        // Cleaning in actor `a`'s clone mints into the empty `a` namespace.
        let result = clean_project(&mut project, IdScope::Mint(Some(token.clone())));
        let assigned: Vec<&str> = result
            .ids_assigned
            .iter()
            .map(|a| a.assigned_id.as_str())
            .collect();
        assert_eq!(assigned, vec!["M-a1", "M-a1.a1"]);
        // The pre-existing null ID is untouched.
        assert_eq!(
            project.tracks[0].1.backlog()[0].id.as_deref(),
            Some("M-001")
        );
    }

    #[test]
    fn test_clean_resolves_duplicates_in_token_namespace() {
        let token = Token::new("a").unwrap();
        let mut project = make_project(
            "\
# Main

## Backlog

- [ ] `M-001` First occurrence
  - added: 2025-05-01
- [ ] `M-001` Duplicate
  - added: 2025-05-02

## Done
",
            vec![("main", "M")],
        );

        clean_project(&mut project, IdScope::Mint(Some(token.clone())));
        let backlog = project.tracks[0].1.backlog();
        // Keeper retains its null ID; the duplicate is reassigned in `a`'s namespace.
        assert_eq!(backlog[0].id.as_deref(), Some("M-001"));
        assert_eq!(backlog[1].id.as_deref(), Some("M-a1"));
    }

    #[test]
    fn test_clean_archival_unchanged_by_token() {
        // Archival keys on state + resolved date, not ID structure, so a tokened
        // clean archives exactly what a null clean does.
        let src = "\
# Main

## Backlog

- [ ] `M-100` Active task

## Done

- [x] `M-001` Task one
  - added: 2025-01-01
  - resolved: 2025-05-01
- [x] `M-002` Task two
  - added: 2025-01-02
  - resolved: 2025-05-02
- [x] `M-003` Task three
  - added: 2025-01-03
  - resolved: 2025-05-03
";
        let archived_count = |scope: IdScope| {
            let tmp = TempDir::new().unwrap();
            let root = tmp.path();
            std::fs::create_dir_all(root.join("frame/tracks")).unwrap();
            let mut config = make_config(vec![("main", "M")]);
            config.clean.done_threshold = 2;
            config.clean.done_retain = 0;
            let mut project = Project {
                root: root.to_path_buf(),
                frame_dir: root.join("frame"),
                config,
                tracks: vec![("main".to_string(), parse_track(src))],
                inbox: None,
            };
            clean_project(&mut project, scope).tasks_archived.len()
        };
        // Null creator, a tokened clone, and an unclaimed clone all archive the
        // same set — archival is independent of ID minting.
        assert_eq!(archived_count(IdScope::Mint(None)), 3);
        assert_eq!(archived_count(IdScope::Mint(Token::new("a"))), 3);
        assert_eq!(archived_count(IdScope::Unclaimed), 3);
    }

    // --- Strict null policy: passive paths on an unclaimed clone (Phase 3.x) ---

    fn project_with_idless_task() -> Project {
        make_project(
            "\
# Main

## Backlog

- [ ] `M-001` Has an ID
- [ ] Missing an ID

## Done
",
            vec![("main", "M")],
        )
    }

    #[test]
    fn test_unclaimed_passive_skips_id_assignment() {
        // An unclaimed clone must NOT mint null on a passive path: the ID-less
        // task stays ID-less.
        let mut project = project_with_idless_task();
        let modified = ensure_ids_and_dates(&mut project, IdScope::Unclaimed);
        let backlog = project.tracks[0].1.backlog();
        assert!(
            backlog[1].id.is_none(),
            "unclaimed clone must not mint an ID"
        );
        // The date-only normalization still ran (it mints nothing).
        assert!(
            backlog[1]
                .metadata
                .iter()
                .any(|m| matches!(m, Metadata::Added(_)))
        );
        assert!(modified.contains(&"main".to_string()));
    }

    #[test]
    fn test_null_creator_passive_mints_null() {
        // The `fr init` creator deliberately owns null, so it still mints null.
        let mut project = project_with_idless_task();
        ensure_ids_and_dates(&mut project, IdScope::Mint(None));
        assert_eq!(
            project.tracks[0].1.backlog()[1].id.as_deref(),
            Some("M-002")
        );
    }

    #[test]
    fn test_tokened_passive_mints_in_namespace() {
        let mut project = project_with_idless_task();
        ensure_ids_and_dates(&mut project, IdScope::Mint(Token::new("a")));
        assert_eq!(project.tracks[0].1.backlog()[1].id.as_deref(), Some("M-a1"));
    }

    #[test]
    fn test_unclaimed_clean_skips_minting_but_archives() {
        // `clean_project` on an unclaimed clone skips ID assignment and duplicate
        // resolution, but still archives done tasks.
        let mut project = project_with_idless_task();
        let result = clean_project(&mut project, IdScope::Unclaimed);
        assert!(result.ids_assigned.is_empty());
        assert!(project.tracks[0].1.backlog()[1].id.is_none());
    }

    /// The `fr clean` incident, at the level it was reported: a track the user
    /// never touched, one task missing a `resolved:` date, and a mis-indented
    /// prose line on a *different*, already-done task.
    ///
    /// Filling the date makes that one task dirty, which rewrites the file —
    /// and the rewrite used to drop the prose line, because the parser had
    /// consumed it without recording it. The damage arrived inside a large,
    /// boring clean diff, on a task and a track unrelated to the work in hand.
    #[test]
    fn test_clean_keeps_a_stray_line_on_an_untouched_task() {
        let source = "\
# Main

## Done

- [x] `M-001` Sharded map lowering
  - added: 2026-07-01
  - resolved: 2026-07-20
    **Shape.** A sharded map whose callback produces a per-row output.
- [x] `M-002` Needs a resolved date
  - added: 2026-07-02
";
        let mut project = make_project(source, vec![("main", "M")]);
        let result = clean_project(&mut project, IdScope::Mint(None));

        // The date fill is what triggered the rewrite.
        assert!(
            result
                .dates_assigned
                .iter()
                .any(|d| d.task_id == "M-002" && d.kind == DateKind::Resolved),
            "expected clean to fill M-002's resolved date: {:?}",
            result.dates_assigned
        );

        let written = crate::parse::serialize_track(&project.tracks[0].1);
        assert!(
            written.contains("**Shape.** A sharded map whose callback produces a per-row output."),
            "clean deleted a line from an untouched task: {written}"
        );
    }

    /// Archiving must carry a stranded line with it rather than leave it behind
    /// — the incident report checked the archive too, and the line was in
    /// neither place. It travels with the task that holds it, which is the task
    /// *below* it; when a whole Done section is archived together, as here, that
    /// keeps its position exactly.
    #[test]
    fn test_archive_carries_a_stranded_line() {
        let tmp = TempDir::new().unwrap();
        let root = tmp.path();
        std::fs::create_dir_all(root.join("frame/tracks")).unwrap();

        let src = "\
# Main

## Backlog

- [ ] `M-200` Active task

## Done

- [x] `M-001` Sharded map lowering
  - added: 2026-07-01
  - resolved: 2026-07-20
    **Shape.** A sharded map whose callback produces a per-row output.
- [x] `M-002` Unrelated finished work
  - added: 2026-07-02
  - resolved: 2026-07-21
";

        let mut config = make_config(vec![("main", "M")]);
        config.clean.done_threshold = 1;
        config.clean.done_retain = 0;

        let mut project = Project {
            root: root.to_path_buf(),
            frame_dir: root.join("frame"),
            config,
            tracks: vec![("main".to_string(), parse_track(src))],
            inbox: None,
        };

        let result = clean_project(&mut project, IdScope::Mint(None));
        assert_eq!(result.tasks_archived.len(), 2);

        let archive = std::fs::read_to_string(root.join("frame/archive/main.md")).unwrap();
        assert!(
            archive.contains("**Shape.** A sharded map whose callback produces a per-row output."),
            "archiving dropped the stranded line: {archive}"
        );
        let track = crate::parse::serialize_track(&project.tracks[0].1);
        assert!(
            !track.contains("**Shape."),
            "the line was left behind in the track as well: {track}"
        );
    }
}