tix-tracker 0.10.0

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

use std::collections::HashMap;
use std::collections::HashSet;
use std::io::Write;

use crate::config::{BoardConfiguration, Config};
use crate::error::{Result, TixError};
use crate::model::{Issue, Status};
use crate::storage::Store;

pub mod beads;
pub mod glab;
pub mod linear;
pub mod token;

/// The supported external tracker, selected via `--target gitlab|linear`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tool {
    GitLab,
    Linear,
}

impl Tool {
    #[must_use]
    pub fn from_target(target: &str) -> Result<Tool> {
        match target {
            "gitlab" => Ok(Tool::GitLab),
            "linear" => Ok(Tool::Linear),
            other => Err(TixError::InvalidInput(format!(
                "unknown --target '{other}' — use gitlab or linear"
            ))),
        }
    }

    /// The token env var that wins over any `tix.toml` token — the tool's
    /// **primary** name, which is what the `tix.toml` warning and the injection
    /// tests name.
    #[must_use]
    pub fn token_var(self) -> &'static str {
        match self {
            Tool::GitLab => "GITLAB_TOKEN",
            Tool::Linear => "LINEAR_TOKEN",
        }
    }

    /// Every environment variable that can carry this tool's token, in
    /// precedence order.
    ///
    /// `token_var` is the primary name tix documents; the extras are the names
    /// the **tool itself** already reads, so a user who has the tracker
    /// configured does not have to export a second, tix-specific variable. The
    /// canonical `linear-cli` reads `LINEAR_API_KEY` (its help shows
    /// `printf '%s\n' "$LINEAR_API_KEY" | linear config set-key`), so that is
    /// accepted after tix's own `LINEAR_TOKEN`.
    #[must_use]
    pub fn token_vars(self) -> &'static [&'static str] {
        match self {
            Tool::GitLab => &["GITLAB_TOKEN"],
            Tool::Linear => &["LINEAR_TOKEN", "LINEAR_API_KEY"],
        }
    }

    /// The binary shelled out to.
    #[must_use]
    pub fn binary(self) -> &'static str {
        match self {
            Tool::GitLab => "glab",
            Tool::Linear => "linear-cli",
        }
    }

    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Tool::GitLab => "gitlab",
            Tool::Linear => "linear",
        }
    }
}

impl std::fmt::Display for Tool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// The captured result of a spawned external tool.
///
/// `ProcessRunner` waits synchronously on the child (never kills it), so a
/// blocking tool blocks the sync — the contract's supported "wait" model for
/// `glab`/`linear-cli`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandOutcome {
    pub success: bool,
    pub status: Option<i32>,
    pub stdout: String,
    pub stderr: String,
}

impl CommandOutcome {
    /// The human-readable output chosen for error reporting: stderr when the
    /// tool failed and produced any, otherwise stdout.
    #[must_use]
    pub fn text(&self) -> &str {
        if self.success {
            &self.stdout
        } else if !self.stderr.trim().is_empty() {
            &self.stderr
        } else {
            &self.stdout
        }
    }
}

/// Spawn seam: production uses [`ProcessRunner`]; tests inject a
/// `FakeRunner` that records argv/env without spawning anything.
pub trait CommandRunner: Send {
    fn run(
        &self,
        program: &str,
        args: &[String],
        env: &[(String, String)],
    ) -> Result<CommandOutcome>;

    /// Downcasting hook so tests can inspect recorded calls on a fake.
    fn as_any(&self) -> &dyn std::any::Any;
}

/// Production runner: `std::process::Command` with a synchronous output wait.
///
/// A missing binary surfaces as [`TixError::External`] with the contract's
/// exit-3 wording (`contracts/external-tools.md`: "missing binary ... exit 3").
pub struct ProcessRunner;

impl CommandRunner for ProcessRunner {
    fn run(
        &self,
        program: &str,
        args: &[String],
        env: &[(String, String)],
    ) -> Result<CommandOutcome> {
        use std::process::Command;
        let mut cmd = Command::new(program);
        cmd.args(args);
        for (key, value) in env {
            cmd.env(key, value);
        }
        let output = cmd.output().map_err(|e| {
            if e.kind() == std::io::ErrorKind::NotFound {
                TixError::External(not_found_message(program))
            } else {
                TixError::External(format!("`{program}` failed to start: {e}"))
            }
        })?;
        Ok(CommandOutcome {
            success: output.status.success(),
            status: output.status.code(),
            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
        })
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// Common surface both tracker adapters implement so the orchestration is
/// tool-agnostic.
///
/// `status` is the *remote* state/label already computed by the pure mapping
/// helpers (e.g. `closed`, `Done`, or the first work column). GitLab conveys
/// "done" via a separate close call ([`TrackerAdapter::mark_done`]); Linear
/// conveys it with `-s Done` ([`TrackerAdapter::done_via_status`]).
pub trait TrackerAdapter {
    fn tool(&self) -> Tool;

    /// Create a remote issue and return its remote id (GitLab `iid`, Linear
    /// `identifier`).
    fn create_issue(
        &mut self,
        title: &str,
        body: &str,
        labels: &[String],
        assignee: Option<&str>,
        priority: Option<&str>,
        status: &str,
    ) -> Result<String>;

    /// Update an existing remote issue in place.
    #[allow(clippy::too_many_arguments)]
    fn update_issue(
        &mut self,
        remote_ref: &str,
        title: &str,
        body: &str,
        labels: &[String],
        assignee: Option<&str>,
        priority: Option<&str>,
        status: &str,
    ) -> Result<()>;

    /// Convey "done" (GitLab: `issue close <id>`). Only invoked when
    /// `done_via_status` is false.
    fn mark_done(&mut self, remote_ref: &str) -> Result<()>;

    /// List open remote issues (the import source). Closed/done issues are
    /// excluded.
    fn list_open(&mut self) -> Result<Vec<RemoteIssue>>;

    /// Linear sets done through the status flag; GitLab needs a separate
    /// close call.
    fn done_via_status(&self) -> bool;

    /// Send the relationships this tracker can express, after the issue itself
    /// exists (WP07 T030/T031).
    ///
    /// **Required, not defaulted.** A default no-op would let a tracker be added
    /// that silently never syncs relationships — the failure mode is a local
    /// relation that appears to sync and does not, which is the same silent-loss
    /// shape as a dropped edge. Two implementors is a small price for making the
    /// omission a compile error.
    ///
    /// The relationships arrive already filtered by
    /// [`map_relation_to_remote`], so an adapter never decides representability:
    /// it sends what the shared seam says it can send, and reports the rest. A
    /// `blocks` edge reaches here; a `related` edge never does.
    fn set_relations(&mut self, remote_ref: &str, relations: &[MappedRelation]) -> Result<()>;

    /// Send the project associations this tracker can express, after the issue
    /// itself exists (WP08 T036).
    ///
    /// **Required, not defaulted**, for the same reason [`Self::set_relations`] is:
    /// a default no-op would let a tracker be added that silently never syncs
    /// project membership, which is the silent-loss shape C-005 forbids. Both
    /// adapters implement `PROJECT_WIRE_VERIFIED`'s answer, which is "nothing", and
    /// the signature is why a future tracker cannot answer with a different shape.
    ///
    /// The associations arrive already filtered by [`map_project_to_remote`], so an
    /// adapter never decides representability — and while `PROJECT_WIRE_VERIFIED` is
    /// empty it never receives a sendable value either, so both implementations
    /// return without spawning anything. A run that cannot express membership must
    /// send **nothing**: an empty membership flag that the tool interpreted as
    /// "clear it" would delete remote state on a run that had nothing to say, which
    /// is the same trap `set_relations` avoids by returning early on an empty set.
    fn set_projects(&mut self, remote_ref: &str, projects: &[MappedProject]) -> Result<()>;

    /// Send the epic references this tracker can express, after the issue itself
    /// exists (WP08, mission `epics-work-items-01M3BYW4`).
    ///
    /// **Required, not defaulted**, for the reason [`Self::set_relations`] and
    /// [`Self::set_projects`] give: a default no-op would let a tracker be added
    /// that silently never syncs an epic reference, which is the silent-loss shape
    /// C-007 forbids. The signature is why a future tracker cannot answer with a
    /// different shape.
    ///
    /// The references arrive already filtered by [`map_epic_to_remote`], so an
    /// adapter never decides representability. Both adapters implement
    /// `EPIC_WIRE_VERIFIED`'s answer, which is "nothing": neither `glab` nor
    /// `linear-cli` carries an epic membership list, so both return without spawning
    /// anything, and an empty set must spawn nothing (an empty flag the tool read as
    /// "clear it" would delete remote state on a run with nothing to say — the same
    /// trap `set_relations` avoids by returning early).
    fn set_epics(&mut self, remote_ref: &str, epics: &[MappedEpic]) -> Result<()>;
}

/// A remote issue parsed from the tracker's JSON list output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteIssue {
    /// Remote id (GitLab `iid`, Linear `identifier`).
    pub id: String,
    pub title: String,
    pub description: String,
    pub labels: Vec<String>,
    /// Remote state (`closed` / `Done` / a column label, ...).
    pub state: String,
    /// ISO-8601 `updated_at`; `None` when the tool omitted it.
    pub updated_at: Option<String>,
    /// Best-effort single assignee (bare name, no `@`).
    pub assignee: Option<String>,
    /// The remote id of this issue's parent, when the remote reported one.
    ///
    /// A **remote** id, not a local number, because it is read from a remote
    /// payload and the two id spaces are not interchangeable. It is resolved to a
    /// local number by `local_parent_number` before anything is written, and
    /// `None` — rather than a guess — when it cannot be resolved.
    pub parent: Option<String>,
    /// The project references the remote reported for this issue (WP08).
    ///
    /// Read from the payload, in the order the payload listed them, and matched
    /// against the local registry by **id** before anything is written. An empty
    /// vector is the answer for a payload that reported none, which is every
    /// GitLab payload today: nothing in this build ever *sends* a membership, so
    /// this is only ever what the remote side already said.
    pub projects: Vec<RemoteProject>,
    /// The epic references the remote reported for this issue (WP08, mission
    /// `epics-work-items-01M3BYW4`).
    ///
    /// Read from the payload, in the order the payload listed them, and matched
    /// against the local registry by **id** before anything is written. An empty
    /// vector is the answer for a payload that reported none — and for both trackers
    /// today nothing in this build ever *sends* one (`EPIC_WIRE_VERIFIED` is empty),
    /// so this is only ever what the remote already said.
    pub epics: Vec<RemoteEpic>,
}

/// What one export or import run did, and what it could not do.
///
/// Returned rather than only written to the caller's `Write`, so a caller can
/// surface the diagnostics without scraping its own output — and so the count and
/// the diagnostics cannot disagree. Both entry points had `Result<usize>`; a count
/// alone cannot express "three issues synced, one relationship could not be".
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SyncReport {
    /// Issues created, updated, or overwritten.
    pub handled: usize,
    /// Local data the remote could not represent — relationships, parent
    /// references, health values, project associations, and epic references — in
    /// encounter order.
    pub diagnostics: Vec<RemoteMappingDiagnostic>,
    /// Items whose **status** the transition policy refused (WP07 T031).
    ///
    /// Counted separately from `handled` because an import can do both: an issue
    /// whose title and body imported fine while its status was refused still counts
    /// as handled — the file was written — and also as skipped, because a column did
    /// not move. A single number cannot express that, and the report line it backs
    /// (`overwrote … without its status`) is the one a user has to be able to find.
    pub skipped: usize,
}

impl SyncReport {
    /// Record one unrepresentable relationship: keep the diagnostic for the
    /// caller, and say so on the human-facing stream too.
    fn note(&mut self, mapped: MappedRelation, out: &mut dyn Write) -> std::io::Result<()> {
        if let MappedRelation::Unsupported(diagnostic) = mapped {
            writeln!(out, "{diagnostic}")?;
            self.diagnostics.push(diagnostic);
        }
        Ok(())
    }

    /// The same, for a **parent** reference.
    ///
    /// Its own method rather than coercing a `MappedParent` into a
    /// `MappedRelation`: a parent is not a relationship, and the first cut did
    /// exactly that with an empty `field` and an empty `value` on the remote arm
    /// — which reads as though something were being sent when nothing is. The
    /// coercion compiled, produced the right output, and was wrong in a way only
    /// reading the type would have caught.
    fn note_parent(&mut self, mapped: MappedParent, out: &mut dyn Write) -> std::io::Result<()> {
        if let MappedParent::Unsupported(diagnostic) = mapped {
            writeln!(out, "{diagnostic}")?;
            self.diagnostics.push(diagnostic);
        }
        Ok(())
    }

    /// The same, for a **project association**.
    ///
    /// Its own method for the reason [`SyncReport::note_parent`] gives: a project
    /// membership is not a relationship, and coercing a `MappedProject` into a
    /// `MappedRelation` would put a project id where a relationship id belongs.
    /// The three methods share the diagnostic type and the count, which is the
    /// vocabulary that matters.
    fn note_project(&mut self, mapped: MappedProject, out: &mut dyn Write) -> std::io::Result<()> {
        if let MappedProject::Unsupported(diagnostic) = mapped {
            writeln!(out, "{diagnostic}")?;
            self.diagnostics.push(diagnostic);
        }
        Ok(())
    }

    /// The same, for an **epic reference** (WP08, mission
    /// `epics-work-items-01M3BYW4`).
    ///
    /// Its own method for the reason [`SyncReport::note_project`] gives: an epic
    /// reference is not a relationship, and coercing a `MappedEpic` into a
    /// `MappedRelation` would put an epic id where a relationship id belongs. The
    /// four methods share the diagnostic type and the count, which is the vocabulary
    /// that matters.
    fn note_epic(&mut self, mapped: MappedEpic, out: &mut dyn Write) -> std::io::Result<()> {
        if let MappedEpic::Unsupported(diagnostic) = mapped {
            writeln!(out, "{diagnostic}")?;
            self.diagnostics.push(diagnostic);
        }
        Ok(())
    }
}

/// The record emitted when a remote tracker cannot hold a piece of local data —
/// a relation (FR-005, C-005, `data-model.md` §6), a parent reference, a health
/// value, a project association (WP08, mission `first-class-projects-01M3BYBW`),
/// or an epic reference (WP08, mission `epics-work-items-01M3BYW4`).
///
/// The four fields are fixed by the data model. `field` is the important one: it
/// is what makes the diagnostic actionable rather than a shrug, and
/// `data-model.md` §6 requires it for exactly that reason — "so the message can
/// name it".
///
/// One type for all of them because the vocabulary matters more than the noun: a
/// reader of `tix export` output learns one shape ("tool: field cannot represent
/// this local data (subject) — reason") and does not have to recognise which kind
/// of local data each line is about. The **subject** in `relation_id` is whatever
/// the diagnostic is about — a relationship id, an `issue->parent` pair, a health
/// scope, an `issue->project` pair, or an `issue->epic` pair.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteMappingDiagnostic {
    /// The local item the diagnostic is about: a relationship id, an
    /// `issue->parent` pair, a health scope, or an `issue->project` pair.
    pub relation_id: String,
    /// The specific unsupported remote field or relation name.
    pub field: String,
    /// Which adapter produced the diagnostic.
    pub tool: Tool,
    /// Human-readable text, safe for CLI output, the TUI, and lint.
    pub message: String,
}

impl std::fmt::Display for RemoteMappingDiagnostic {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // "this local data", not "this relationship": the type now carries project
        // associations and health values too, and a line that called an association
        // a relationship would send the reader looking for an edge that is not there.
        write!(
            f,
            "{}: {} cannot represent this local data ({}) — {}",
            self.tool.as_str(),
            self.field,
            self.relation_id,
            self.message
        )
    }
}

/// The outcome of mapping one local relationship for one tracker: either a
/// remote representation, or a diagnostic naming why there is none.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MappedRelation {
    /// The remote representation to send: the relation `field` (the remote
    /// relation kind, e.g. `blocks`) and the `value` the adapter needs. For a
    /// relation verb taking two endpoints (Linear's `relations add`) the `value`
    /// is the **target's remote identifier** (`ENG-42`); a tracker whose verb
    /// carries the target inside a field renders its own value there.
    Remote { field: String, value: String },
    /// The tracker cannot express this relation. The **local** relation is
    /// untouched — C-005 is that a relation the remote cannot hold still survives.
    Unsupported(RemoteMappingDiagnostic),
}

/// The remote fields each tracker can express for a typed relation, and the one it
/// maps every blocking edge onto.
///
/// This is the whole of the representability decision, and it is deliberately a
/// table keyed on `(Tool, RelationKind)` rather than logic spread across the two
/// adapters. Two consequences worth stating:
///
/// - **It is derived from what the adapters can actually send**, not from a guess
///   about their APIs. `linear-cli relations add -r <kind> <FROM> <TO>` is the only
///   relation verb either CLI exposes, so `blocks` maps for Linear and nothing else
///   does; `glab` exposes no relation verb at all (see `RELATION_CLI_ABSENT`).
/// - **`blocks` maps; `related`, `duplicates`, and `blocked_by` do not.** Both
///   trackers' issue-update CLIs carry a title, body, labels, assignee, and state —
///   and no field for "this issue is related to that one". Guessing otherwise
///   would mean writing a title into a field, which is not a mapping.
///
/// `blocked_by` is the inverse of `blocks`, not a third thing, so it is reported
/// against the same remote field: naming `blocking` for it would be true but would
/// send the reader looking for a relation the tracker does not have.
///
/// ## Linear is wire-verified; GitLab is verified to have no command at all
///
/// The mapping knows what each tracker's *model* can express — GitLab and Linear
/// both have blocking relations in their APIs — and the adapters drive a **CLI**,
/// so what matters is whether the CLI exposes a verb.
///
/// **Linear's does.** `linear-cli` 0.3.28 (nesszer/linear-cli, the
/// `cargo:linear-cli` crate) has `relations add --relation
/// <blocks|blocked-by|related|duplicate> <FROM> <TO>`, checked against the
/// installed binary on 2026-10-09. Four shapes parse — they fail only with
/// `No workspace selected` (exit 1, no workspace configured here):
/// `relations add -r blocks ENG-1 ENG-2`, `issues create "T" -t ENG -d D -p 2 -s
/// Todo -o json`, `issues update ENG-1 -T T -d D -s Done -o json`, and
/// `issues list -t ENG -s Todo -o json`; and two clap errors confirm the shape —
/// `linear-cli issue create "T"` (exit 2, `unrecognized subcommand 'issue'`) and
/// `linear-cli issues create --title T` (exit 2, `unexpected argument
/// '--title'`). The API path itself is unverified (no workspace), so the
/// adapter is checked at the grammar level and end to end against the fake.
///
/// Sending an unverified command line is not a conservative default; it is a
/// production failure with a confusing message. So the seam maps, and an adapter
/// sends only what a verified verb carries; **GitLab remains on the separate,
/// permanent `RELATION_CLI_ABSENT` list** below — the two answers must not blur.
///
/// The follow-up this closes: verify the verb against the real CLI, add the tool
/// to this list, and implement its `set_relations` ([`Tool::Linear`] does).
const RELATION_WIRE_VERIFIED: &[Tool] = &[Tool::Linear];

/// Tools whose CLI is **verified to expose no relation command at all**.
///
/// This is a *different, permanent* answer from "not yet verified", and the two
/// must not share wording. A reader told "the verb is not verified" will reasonably
/// wait for (or go looking for) the missing command; a reader told the CLI has no
/// such command can stop.
///
/// `glab` 1.119.0, checked against the installed binary (tix #1354):
/// `glab issue update --help` lists no `--blocking` (or any relation) flag, and
/// `glab issue` has no relation/`link` subcommand. GitLab's *model* has issue links
/// and the REST API exposes them, but the CLI this adapter drives does not.
const RELATION_CLI_ABSENT: &[Tool] = &[Tool::GitLab];

// ---------------------------------------------------------------------------
// WP08 — the parent reference across a sync round trip
// ---------------------------------------------------------------------------

/// The CLI verbs that would carry a parent reference, per adapter.
///
/// **Empty: no adapter has a verified parent verb.** Both trackers' *models* have
/// a hierarchy — GitLab has epics and child issues, Linear has parent issues — but
/// the adapters drive a CLI, and whether `glab issue create --parent` or
/// `linear-cli issues create --parent` exists is a claim about a program this
/// repository cannot run. (Linear's `relations add` is verified for *relations*
/// and is on `RELATION_WIRE_VERIFIED`; that is a different verb and says nothing
/// about a parent, and the fake in `tests/bin/` accepts no parent flag.)
///
/// So the seam maps, and nothing is sent until a verb is verified. What *does*
/// work today — and is what the round trip covers — is that the reference
/// survives: the local parent is retained, the mapping is reported, and an import
/// restores a parent that came from the remote. Flipping a tool on here is a
/// one-line change plus its adapter implementation, once the verb is confirmed by
/// hand.
const PARENT_WIRE_VERIFIED: &[Tool] = &[];

/// The remote field each adapter would carry a parent in, if its verb existed.
///
/// Present so the diagnostic can *name* the thing that is missing, rather than
/// saying only that something is. A reader told "GitLab cannot express this" will
/// not go looking for the flag.
const GITLAB_PARENT_FIELD: &str = "parent";
const LINEAR_PARENT_FIELD: &str = "parent";

/// What one parent reference maps to on the wire.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MappedParent {
    /// The remote value to send, as a field/value pair like a relation.
    Remote { field: String, value: String },
    /// The adapter cannot carry it. The **local** reference is untouched, which is
    /// the same contract the relationship mapper follows (C-005): a reference the
    /// remote cannot hold still survives here.
    Unsupported(RemoteMappingDiagnostic),
}

/// Map one local parent reference to its remote representation, or say why not.
///
/// Pure: no adapter, no I/O, no configuration, and shared by both trackers so a
/// future one cannot be added with a divergent contract (T033).
#[must_use]
pub fn map_parent_to_remote(tool: Tool, issue_number: u32, parent: Option<u32>) -> MappedParent {
    let Some(parent) = parent else {
        // No reference is not a mapping problem. Reporting it would put a
        // diagnostic on every parentless issue in the repository, which is every
        // diagnostic being ignored.
        return MappedParent::Remote {
            field: parent_field(tool).to_string(),
            value: String::new(),
        };
    };
    let field = parent_field(tool);
    if PARENT_WIRE_VERIFIED.contains(&tool) {
        return MappedParent::Remote {
            field: field.to_string(),
            value: format!("#{parent}"),
        };
    }
    MappedParent::Unsupported(RemoteMappingDiagnostic {
        relation_id: format!("{issue_number}->{parent}"),
        field: field.to_string(),
        tool,
        message: format!(
            "#{issue_number}'s parent #{parent} is expressible in {}'s model as \
             `{field}`, but the CLI verb that would carry it is not verified, so \
             nothing is sent; the local reference is kept",
            tool.as_str()
        ),
    })
}

/// The field an adapter would carry a parent in.
fn parent_field(tool: Tool) -> &'static str {
    match tool {
        Tool::GitLab => GITLAB_PARENT_FIELD,
        Tool::Linear => LINEAR_PARENT_FIELD,
    }
}

// ---------------------------------------------------------------------------
// WP08 (mission first-class-projects-01M3BYBW) — project associations across a
// sync round trip
// ---------------------------------------------------------------------------
//
// ## The two directions are not symmetric, and each says so
//
// **Outward: nothing leaves the machine, ever.** GitLab's and Linear's *models*
// both know what a project is; the CLIs these adapters drive do not. `glab`
// already passes the one project an issue lives in (`--project <path>`) on every
// call and exposes no membership field at all, and Linear's issue carries a
// single `project` — so neither can hold the *list* this mission's C-003
// requires. Multi-membership is the intake's named risk, and the contract's
// answer for it is C-005, not a guess: every association diagnoses, and the local
// association list is untouched. Sending one member of a list would be a silent
// drop with extra steps.
//
// **Inward: a payload that reports associations is honoured.** The read direction
// is deliberately *not* gated the way the relation mapper's is, and the reason is
// not convenience. `map_relation_from_remote` must refuse an unrecognised field
// because turning remote text into a local edge can invent a relationship no
// export ever made. A project id cannot: it is matched against the local
// **registry** before anything is written, and an id the registry does not know
// is refused with a diagnostic rather than written (C-005). So the worst an
// invented id can produce is a named diagnostic, never local data. Reading a
// field a payload reported is also not the same claim as sending one — the same
// distinction `GlabIssue::parent` already draws.
//
// This is what makes the round trip non-vacuous: the export says what cannot
// leave, the import applies what came back through the project **service**, and
// the association list is byte-stable either way (NFR-002).

/// A project reference a remote reported on one issue.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteProject {
    /// The remote's project identity. It is the **only** thing an import matches
    /// on (C-002): an id is allocated once and never changes, so a remote that
    /// renames a project still names the same one.
    pub id: String,
    /// The remote's display name for the project, when it sent one.
    ///
    /// Carried for the diagnostics — a reader recognises "the remote calls it
    /// *Platform hardening*" — and **never** matched on. The local display name
    /// stays the registry's (C-002), so a remote rename cannot change it, and it
    /// is the only remote text in a diagnostic, which is why that diagnostic is
    /// scrubbed.
    pub name: Option<String>,
}

/// Parse the project references one remote issue reported.
///
/// **Pure and total**, in the shape [`crate::sync::mod`'s parent parser] is: an
/// unrecognised payload yields no references — which the import then reports
/// nothing about — rather than a deserialisation failure that aborts the whole
/// list. Accepted, for both trackers, because the field's exact shape is a claim
/// about a program this repository cannot run:
///
/// - an array of ids (`"projects": ["p-1", …]`) or of objects;
/// - a single id, or a single object (`"project": {"id": …}`);
/// - an object's id under `id`, `identifier`, `key`, or `project_id`, as a
///   string or a number (`iid`-style numeric ids are real on the wire);
/// - its name under `name`, `title`, or `display_name`, as a string.
///
/// **Entry order is preserved**, which is what keeps a round trip byte-stable
/// (NFR-002): reordering here would reorder the local list.
///
/// An entry with a name but no id is **kept** with an empty id, so the import can
/// report it by name instead of dropping it in silence; an entry with neither is
/// not a reference at all and yields nothing.
#[must_use]
pub fn remote_projects(value: Option<&serde_json::Value>) -> Vec<RemoteProject> {
    fn id_of(value: &serde_json::Value) -> String {
        match value {
            serde_json::Value::String(s) => s.clone(),
            serde_json::Value::Number(n) => n.to_string(),
            _ => String::new(),
        }
    }
    fn one(value: &serde_json::Value) -> Option<RemoteProject> {
        match value {
            serde_json::Value::String(_) | serde_json::Value::Number(_) => Some(RemoteProject {
                id: id_of(value),
                name: None,
            }),
            serde_json::Value::Object(map) => {
                let id = ["id", "identifier", "key", "project_id"]
                    .iter()
                    .find_map(|key| map.get(*key))
                    .map(id_of)
                    .unwrap_or_default();
                let name = ["name", "title", "display_name"]
                    .iter()
                    .find_map(|key| map.get(*key))
                    .and_then(serde_json::Value::as_str)
                    .map(str::to_string);
                if id.trim().is_empty() && name.is_none() {
                    return None;
                }
                Some(RemoteProject { id, name })
            }
            _ => None,
        }
    }
    let Some(value) = value else {
        return Vec::new();
    };
    match value {
        serde_json::Value::Array(items) => items.iter().filter_map(one).collect(),
        other => one(other).into_iter().collect(),
    }
}

/// The remote field each adapter would carry an issue's project associations in.
///
/// The two differ because the trackers' models differ, and the diagnostic names
/// the field the reader should stop looking for:
///
/// - **GitLab** — `projects`. An issue JSON carries the one project that owns it;
///   the field a *membership list* would need is `projects`, which no `glab`
///   command exposes.
/// - **Linear** — `project`. Its issue carries exactly one project, so the field
///   that exists is named and the list it cannot hold is what diagnoses.
const GITLAB_PROJECT_FIELD: &str = "projects";
const LINEAR_PROJECT_FIELD: &str = "project";

/// The field an adapter would carry project associations in.
fn project_field(tool: Tool) -> &'static str {
    match tool {
        Tool::GitLab => GITLAB_PROJECT_FIELD,
        Tool::Linear => LINEAR_PROJECT_FIELD,
    }
}

/// Tools verified to drive project **membership** from their CLI.
///
/// **Empty, and not because the verb is merely unverified.** The relation and
/// parent tables are empty pending a verb confirmation; this one is empty because
/// neither CLI has a verb to confirm: `glab issue update --help` (1.119.0) lists
/// `--project` only as *which project owns the issue*, and Linear's issue carries
/// one `project` with no list form. So an issue with three projects cannot be
/// expressed as three of anything, and C-003's multi-membership — the intake's
/// named risk — is what makes this terminal rather than pending.
///
/// The table still exists rather than a bare `unsupported` constant so the seam
/// has the same shape as the other three, and so a future tracker that *does*
/// model membership in its CLI is a one-line addition plus its `set_projects`.
const PROJECT_WIRE_VERIFIED: &[Tool] = &[];

/// What one local project association maps to on the wire.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MappedProject {
    /// The remote value to send, as a field/value pair like a relation.
    Remote { field: String, value: String },
    /// The adapter cannot carry it. The **local** association is untouched — C-005
    /// is that a membership the remote cannot hold still survives.
    Unsupported(RemoteMappingDiagnostic),
}

/// Map one local project association to its remote representation, or say why not.
///
/// Pure: no adapter, no I/O, no configuration. Both trackers share it, so a future
/// one cannot be added with a divergent contract — and the representability
/// decision lives in exactly one place instead of once per adapter.
///
/// `issue_number` appears in the message because the diagnostic has to be
/// actionable: the association list can be long, and "project `p-3` cannot be
/// sent" without the issue is a shrug.
#[must_use]
pub fn map_project_to_remote(tool: Tool, issue_number: u32, project_id: &str) -> MappedProject {
    let field = project_field(tool);
    let id = project_id.trim();
    if id.is_empty() {
        // Not a representability question: there is nothing to send, and an empty
        // entry in the list is a repair job rather than a remote capability gap.
        return MappedProject::Unsupported(RemoteMappingDiagnostic {
            relation_id: format!("{issue_number}->"),
            field: field.to_string(),
            tool,
            message: format!(
                "issue #{issue_number} carries a project association with no id, so there \
                 is nothing to send; the entry is kept locally — dissociating the empty \
                 reference, or editing the issue's project list, clears it"
            ),
        });
    }
    if PROJECT_WIRE_VERIFIED.contains(&tool) {
        return MappedProject::Remote {
            field: field.to_string(),
            value: id.to_string(),
        };
    }
    MappedProject::Unsupported(RemoteMappingDiagnostic {
        relation_id: format!("{issue_number}->{id}"),
        field: field.to_string(),
        tool,
        message: format!(
            "#{issue_number}'s membership of project `{id}` has no {} field to travel in \
             — {} — so nothing is sent and the local association is kept",
            tool.as_str(),
            project_absence_reason(tool)
        ),
    })
}

/// Why a tracker's CLI cannot carry a project membership, per tool.
///
/// A **permanent** claim about the CLI the adapter drives, not "not yet
/// verified", and the wording says so for the same reason `RELATION_CLI_ABSENT`
/// does: a reader told "the verb is unverified" will wait for it, and there is
/// nothing to wait for. The two reasons differ, so the message does.
fn project_absence_reason(tool: Tool) -> &'static str {
    match tool {
        Tool::GitLab => {
            "`glab` names one owning project (`--project`) and exposes no membership field"
        }
        Tool::Linear => {
            "Linear's issue carries one `project` and no list, so a second \
                         membership has nowhere to go"
        }
    }
}

/// Map one remote project reference back onto a local association id, or say why
/// not.
///
/// The reverse value is **local-shaped**, like [`map_relation_from_remote`]'s: the
/// frontmatter key the association lives under ([`crate::projects::PROJECTS_KEY`])
/// and the id, not a copy of the tool's field name — echoing the field back would
/// make the same association read differently per tracker, which is the opposite
/// of a shared seam.
///
/// Not gated on [`PROJECT_WIRE_VERIFIED`], and the module header records why: an
/// id is validated against the local registry before anything is written, so this
/// direction cannot invent local data the way an unverified relation field could.
#[must_use]
pub fn map_project_from_remote(tool: Tool, remote: &RemoteProject) -> MappedProject {
    let id = remote.id.trim();
    if id.is_empty() {
        return MappedProject::Unsupported(RemoteMappingDiagnostic {
            relation_id: remote.name.clone().unwrap_or_default(),
            field: project_field(tool).to_string(),
            tool,
            message: format!(
                "the remote reported a project it named `{}` but gave no id, and an id is \
                 the only thing a local association can match on; nothing was associated \
                 and the local list is unchanged",
                remote.name.as_deref().unwrap_or("")
            ),
        });
    }
    MappedProject::Remote {
        field: crate::projects::PROJECTS_KEY.to_string(),
        value: id.to_string(),
    }
}

/// Redact the resolved secret from a diagnostic's message.
///
/// The diagnostics this module builds itself are made of local ids and field
/// names. The **import** builds four — a reference it cannot read, a project the
/// registry does not declare, an epic the registry does not declare, and a service
/// refusal — and the first three quote the name a remote payload reported. Remote
/// output is the one input that can carry a credential, which is why the import's
/// diagnostics go through here, using the same [`scrub_secret`] the adapters use on
/// their errors.
fn scrub_diagnostic(diagnostic: &mut RemoteMappingDiagnostic, secret: Option<&str>) {
    if let Some(secret) = secret {
        diagnostic.message = scrub_secret(&diagnostic.message, secret);
        diagnostic.relation_id = scrub_secret(&diagnostic.relation_id, secret);
    }
}

// ---------------------------------------------------------------------------
// WP08 (mission epics-work-items-01M3BYW4) — epic references across a sync
// round trip
// ---------------------------------------------------------------------------
//
// ## What the adapters can actually express
//
// **Outward: nothing leaves the machine, and that is the derived answer, not a
// placeholder.** Research R7 states GitLab's adapter has no epic concept and the
// `grep` confirms it: neither `glab` nor `linear-cli` carries an epic membership
// list. `glab`'s issue JSON names at most one epic (`epic_iid`, which this adapter
// already reads as the issue's single parent) and exposes no flag to send one;
// Linear has no epic level at all. Because the mission allows **several** epics per
// issue (C-003), an adapter that sent one member of a list would be a silent drop
// with extra steps — which C-007 forbids outright. So every reference diagnoses and
// the local list is untouched.
//
// **Inward: a payload that reports epic ids is honoured.** Like the project seam,
// the read direction is deliberately *not* gated: the id is matched against the
// local **registry** before anything is written, so the worst an invented id can
// produce is a named diagnostic, never local data (C-007).
//
// This is what makes the round trip non-vacuous: the export says what cannot leave,
// the import applies what came back through the epic **service**
// ([`Store::reference_epic`], the same path `tix edit --add-epic` takes), and the
// reference list is byte-stable either way (NFR-002).

/// An epic reference a remote reported on one issue.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RemoteEpic {
    /// The remote's epic identity. It is the **only** thing an import matches on
    /// (C-003): an epic id is allocated once and never changes, so a remote that
    /// renames an epic still names the same one.
    pub id: String,
    /// The remote's display name for the epic, when it sent one.
    ///
    /// Carried for the diagnostics — a reader recognises "the remote calls it
    /// *Sync hardening*" — and **never** matched on. The local display name stays
    /// the registry's (C-003), so a remote rename cannot change it; it is the only
    /// remote text in a diagnostic, which is why that diagnostic is scrubbed.
    pub name: Option<String>,
}

/// Parse the epic references one remote issue reported.
///
/// **Pure and total**, in the shape [`remote_projects`] is: an unrecognised payload
/// yields no references — which the import then reports nothing about — rather than
/// a deserialisation failure that aborts the whole list. Accepted, for both
/// trackers, because the field's exact shape is a claim about a program this
/// repository cannot run:
///
/// - an array of ids (`"epics": ["e-1", …]`) or of objects;
/// - a single id, or a single object (`"epic": {"id": …}`);
/// - an object's id under `id`, `identifier`, `key`, or `epic_id`, as a string or a
///   number (numeric ids are real on the wire);
/// - its name under `name`, `title`, or `display_name`, as a string.
///
/// **Entry order is preserved**, which is what keeps a round trip byte-stable
/// (NFR-002): reordering here would reorder the local list. An entry with a name
/// but no id is **kept** with an empty id, so the import can report it by name
/// instead of dropping it in silence; an entry with neither is not a reference at
/// all and yields nothing.
#[must_use]
pub fn remote_epics(value: Option<&serde_json::Value>) -> Vec<RemoteEpic> {
    fn id_of(value: &serde_json::Value) -> String {
        match value {
            serde_json::Value::String(s) => s.clone(),
            serde_json::Value::Number(n) => n.to_string(),
            _ => String::new(),
        }
    }
    fn one(value: &serde_json::Value) -> Option<RemoteEpic> {
        match value {
            serde_json::Value::String(_) | serde_json::Value::Number(_) => Some(RemoteEpic {
                id: id_of(value),
                name: None,
            }),
            serde_json::Value::Object(map) => {
                let id = ["id", "identifier", "key", "epic_id"]
                    .iter()
                    .find_map(|key| map.get(*key))
                    .map(id_of)
                    .unwrap_or_default();
                let name = ["name", "title", "display_name"]
                    .iter()
                    .find_map(|key| map.get(*key))
                    .and_then(serde_json::Value::as_str)
                    .map(str::to_string);
                if id.trim().is_empty() && name.is_none() {
                    return None;
                }
                Some(RemoteEpic { id, name })
            }
            _ => None,
        }
    }
    let Some(value) = value else {
        return Vec::new();
    };
    match value {
        serde_json::Value::Array(items) => items.iter().filter_map(one).collect(),
        other => one(other).into_iter().collect(),
    }
}

/// The remote field an adapter would carry an issue's epic references in.
///
/// **One constant, not a per-tool table.** Unlike a project association — where
/// the two models genuinely name different fields (`projects` for GitLab's owning
/// project vs Linear's single `project`) — both trackers would name an epic
/// membership list `epics`, so a per-tool indirection would carry no information.
/// The per-tool difference lives in [`epic_absence_reason`], which is where it
/// actually is: `glab` names at most one epic per issue (`epic_iid`), while Linear
/// has no epic level at all.
const EPIC_FIELD: &str = "epics";

/// Tools verified to drive an epic **membership** from their CLI.
///
/// **Empty, and derived from the adapters rather than assumed.** `glab`'s issue
/// carries at most one epic (`epic_iid`) and exposes no flag to set it or to hold a
/// list; Linear has no epic level. So an issue in three epics cannot be expressed as
/// three of anything, and C-003's multi-membership is what makes this terminal
/// rather than pending — the same reasoning `PROJECT_WIRE_VERIFIED` records.
///
/// The table still exists rather than a bare `unsupported` constant so the seam has
/// the same shape as the other three, and so a future tracker that *does* model an
/// epic list in its CLI is a one-line addition plus its `set_epics`.
const EPIC_WIRE_VERIFIED: &[Tool] = &[];

/// What one local epic reference maps to on the wire.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MappedEpic {
    /// The remote value to send, as a field/value pair like a relation.
    Remote { field: String, value: String },
    /// The adapter cannot carry it. The **local** reference is untouched — C-007 is
    /// that a reference the remote cannot hold still survives.
    Unsupported(RemoteMappingDiagnostic),
}

/// Map one local epic reference to its remote representation, or say why not.
///
/// Pure: no adapter, no I/O, no configuration. Both trackers share it, so a future
/// one cannot be added with a divergent contract — and the representability decision
/// lives in exactly one place instead of once per adapter.
///
/// `issue_number` appears in the message because the diagnostic has to be
/// actionable: the reference list can be long, and "epic `e-3` cannot be sent"
/// without the issue is a shrug.
#[must_use]
pub fn map_epic_to_remote(tool: Tool, issue_number: u32, epic_id: &str) -> MappedEpic {
    let field = EPIC_FIELD;
    let id = epic_id.trim();
    if id.is_empty() {
        // Not a representability question: there is nothing to send, and an empty
        // entry in the list is a repair job rather than a remote capability gap.
        return MappedEpic::Unsupported(RemoteMappingDiagnostic {
            relation_id: format!("{issue_number}->"),
            field: field.to_string(),
            tool,
            message: format!(
                "issue #{issue_number} carries an epic reference with no id, so there is \
                 nothing to send; the entry is kept locally — dereferencing the empty \
                 reference, or editing the issue's epic list, clears it"
            ),
        });
    }
    if EPIC_WIRE_VERIFIED.contains(&tool) {
        return MappedEpic::Remote {
            field: field.to_string(),
            value: id.to_string(),
        };
    }
    MappedEpic::Unsupported(RemoteMappingDiagnostic {
        relation_id: format!("{issue_number}->{id}"),
        field: field.to_string(),
        tool,
        message: format!(
            "#{issue_number}'s reference to epic `{id}` has no {} field to travel in \
             — {} — so nothing is sent and the local reference is kept",
            tool.as_str(),
            epic_absence_reason(tool)
        ),
    })
}

/// Why a tracker's CLI cannot carry an epic membership, per tool.
///
/// A **permanent** claim about the CLI the adapter drives, not "not yet verified",
/// and the wording says so for the same reason `PROJECT_WIRE_VERIFIED`'s reason
/// does: a reader told "the verb is unverified" will wait for it, and there is
/// nothing to wait for. The two reasons differ, so the message does.
fn epic_absence_reason(tool: Tool) -> &'static str {
    match tool {
        Tool::GitLab => {
            "`glab` names at most one epic per issue (`epic_iid`) and exposes no flag \
             to send one, so a membership list has nowhere to go"
        }
        Tool::Linear => {
            "Linear has no epic level at all — the nearest concept is a project — so an \
             epic reference has nowhere to go"
        }
    }
}

/// Map one remote epic reference back onto a local reference id, or say why not.
///
/// The reverse value is **local-shaped**, like [`map_project_from_remote`]'s: the
/// frontmatter key the reference lives under ([`crate::epics::EPICS_KEY`]) and the
/// id, not a copy of the tool's field name — echoing the field back would make the
/// same reference read differently per tracker, which is the opposite of a shared
/// seam.
///
/// Not gated on [`EPIC_WIRE_VERIFIED`], and the module header records why: an id is
/// validated against the local registry before anything is written, so this
/// direction cannot invent local data the way an unverified relation field could.
#[must_use]
pub fn map_epic_from_remote(tool: Tool, remote: &RemoteEpic) -> MappedEpic {
    let id = remote.id.trim();
    if id.is_empty() {
        return MappedEpic::Unsupported(RemoteMappingDiagnostic {
            relation_id: remote.name.clone().unwrap_or_default(),
            field: EPIC_FIELD.to_string(),
            tool,
            message: format!(
                "the remote reported an epic it named `{}` but gave no id, and an id is \
                 the only thing a local reference can match on; nothing was referenced \
                 and the local list is unchanged",
                remote.name.as_deref().unwrap_or("")
            ),
        });
    }
    MappedEpic::Remote {
        field: crate::epics::EPICS_KEY.to_string(),
        value: id.to_string(),
    }
}

/// The remote field GitLab's model carries an issue's health in.
///
/// Named so the diagnostic can say *what* is missing rather than only that something
/// is: a reader told "GitLab cannot carry this" will not go looking for the flag.
const GITLAB_HEALTH_FIELD: &str = "health_status";

/// The remote field Linear's model would need for an issue's health. Linear has no
/// issue level health, so the constant names the field a future adapter would have to
/// introduce — and the mapping says which of the two reasons applies.
const LINEAR_HEALTH_FIELD: &str = "health";

/// Tools whose **model has no field** for an issue's health at all.
///
/// The claim is different from "the verb is not verified", and the message says
/// which, for the same reason `RELATION_CLI_ABSENT` does: a reader who is told
/// "GitLab can express this but the verb is unverified" will look for the verb.
const HEALTH_MODEL_ABSENT: &[Tool] = &[Tool::Linear];

/// Tools verified to drive the health field from their CLI.
///
/// Empty, and for the same reason `PARENT_WIRE_VERIFIED` is: whether `glab issue
/// create --health-status ...` exists is a claim about a program this repository
/// cannot run. The fakes in `tests/bin/` accept no health flag at all, which is
/// better evidence of the surface than an assumption made after it. Flipping a
/// tool on here is a one-line change plus its adapter implementation, once the
/// verb is confirmed by hand.
const HEALTH_WIRE_VERIFIED: &[Tool] = &[];

/// What one local health value maps to on the wire.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MappedHealth {
    /// The remote value to send, as a field/value pair like a relation.
    Remote { field: String, value: String },
    /// The adapter cannot carry it. The **local** value is untouched, which is the
    /// same contract the relationship and parent mappers follow (C-008): a value the
    /// remote cannot hold still survives here, and a remote that lacks the field can
    /// never clear it.
    Unsupported(RemoteMappingDiagnostic),
}

/// Map one local health value to its remote representation, or say why not (T022,
/// T023).
///
/// Pure: no adapter, no I/O, no configuration. Shared by both trackers so a future
/// one cannot be added with a divergent contract, and the representability table
/// lives in exactly one place.
///
/// Only an **issue**-scoped value has a remote home: a rollup belongs to this
/// repository's memberships, and a remote that knew nothing of the parent would carry
/// a number the local side derived. A non-issue scope is therefore reported, never
/// silently sent as if it were the issue's own health.
#[must_use]
pub fn map_health_to_remote(
    tool: Tool,
    scope: &crate::health::HealthScope,
    state: crate::health::HealthState,
) -> MappedHealth {
    let field = health_field(tool);
    if HEALTH_MODEL_ABSENT.contains(&tool) {
        return MappedHealth::Unsupported(RemoteMappingDiagnostic {
            relation_id: scope.as_str(),
            field: field.to_string(),
            tool,
            message: format!(
                "{}'s issue model has no health field, so `{}` stays local; a remote that \
                 cannot carry the value never clears it",
                tool.as_str(),
                state.as_str()
            ),
        });
    }
    let crate::health::HealthScope::Issue(number) = scope else {
        return MappedHealth::Unsupported(RemoteMappingDiagnostic {
            relation_id: scope.as_str(),
            field: field.to_string(),
            tool,
            message: format!(
                "`{}` is a derived value for {}, which has no remote representation; only \
                 an issue's own health can be sent, so the local value is kept",
                state.as_str(),
                scope
            ),
        });
    };
    if HEALTH_WIRE_VERIFIED.contains(&tool) {
        return MappedHealth::Remote {
            field: field.to_string(),
            value: state.as_str().to_string(),
        };
    }
    MappedHealth::Unsupported(RemoteMappingDiagnostic {
        relation_id: format!("issue:{number}"),
        field: field.to_string(),
        tool,
        message: format!(
            "issue #{number}'s `{}` is expressible in {}'s model as `{field}`, but the CLI \
             verb that would carry it is not verified, so nothing is sent; the local value \
             is kept",
            state.as_str(),
            tool.as_str()
        ),
    })
}

/// The field an adapter carries an issue's health in.
fn health_field(tool: Tool) -> &'static str {
    match tool {
        Tool::GitLab => GITLAB_HEALTH_FIELD,
        Tool::Linear => LINEAR_HEALTH_FIELD,
    }
}

// ---------------------------------------------------------------------------
// WP07 (mission roadmap-initiatives-01M3C8SX) — initiatives across a sync
// round trip
// ---------------------------------------------------------------------------
//
// ## What the adapters can actually express, checked rather than assumed
//
// An initiative is a portfolio-level record, and this module's plan is explicit
// that the sync side carries **unsupported-field diagnostics only** — no adapter
// gains an initiative sender here. The representability answer is still derived
// from the CLIs the adapters drive, and the two trackers' answers differ in
// *reason* even though both end at "nothing is sent":
//
// - **GitLab: the CLI has no initiative command at all.** `glab` 1.119.0 (checked
//   against the installed binary on 2026-10-09) lists no `initiative` command:
//   `glab --help` has `issue` and `milestone`, and its experimental `work-items`
//   tree covers epics, issues and tasks. GitLab's *model* has no initiative either.
//   That is a **permanent** answer, like [`RELATION_CLI_ABSENT`], and the wording
//   says so: a reader told "the verb is unverified" would wait for one, and there
//   is nothing to wait for.
// - **Linear: the verb exists, but it cannot hold the record.** `linear-cli` 0.3.28
//   (checked the same day) *does* expose `initiatives list|get|create|update|delete`;
//   `linear-cli initiatives list -o json` parses and fails only with `No workspace
//   selected` (exit 1), which is a grammar-level verification of the command line.
//   So the honest statement is not "there is no verb" — it is that the
//   `create`/`update` verbs take only a **name**, a **description** and a
//   **status**, so they cannot carry the local record's `owner`, `priority`,
//   `labels`, `target_date`, or its typed project/epic/milestone associations.
//   Sending the fields they *can* take while dropping the rest would be a silent
//   drop with extra steps (C-005/C-007), so the whole local record is kept.
//
// `INITIATIVE_WIRE_VERIFIED` is empty, and `initiative_absence_reason` carries the
// per-tool difference so the two answers never blur. The table exists rather than a
// bare `unsupported` constant for the same reason the parent/health tables do: a
// future tracker that models the whole record in its CLI is a one-line addition plus
// its `set_initiatives`.

/// The remote field an adapter would carry an initiative in.
///
/// Both trackers would name it `initiatives`, so — unlike a project association,
/// where the two models genuinely name different fields — a per-tool indirection
/// would carry no information. The per-tool difference lives in
/// [`initiative_absence_reason`], which is where it actually is.
const INITIATIVE_FIELD: &str = "initiatives";

/// Tools whose CLI is **verified to expose no initiative command at all**.
///
/// A *permanent* answer, distinct from "not yet verified", for the same reason
/// [`RELATION_CLI_ABSENT`] is: a reader told "the verb is unverified" will reasonably
/// wait for it, and `glab` has no such command to wait for.
const INITIATIVE_CLI_ABSENT: &[Tool] = &[Tool::GitLab];

/// Tools verified to drive an initiative from their CLI.
///
/// **Empty**, and deliberately so on both trackers. No adapter implements a
/// `set_initiatives`, and the one CLI that exposes initiative verbs
/// (`linear-cli`) cannot carry the record's fields — see the section header. The
/// table is the same shape as the other four so a future tracker that *does* model
/// the whole record is a one-line addition plus its adapter method.
const INITIATIVE_WIRE_VERIFIED: &[Tool] = &[];

/// What one local initiative maps to on the wire.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MappedInitiative {
    /// The remote value to send, as a field/value pair like a relation. A verified
    /// adapter would put the **remote reference** in `value`; until one exists this
    /// arm is unreachable, exactly as [`MappedParent::Remote`] is.
    Remote { field: String, value: String },
    /// The target cannot carry the record. The **local** record is untouched,
    /// which is the contract every other mapper follows (C-005): a record the
    /// remote cannot hold still survives, and a remote that lacks the field can
    /// never clear it.
    Unsupported(RemoteMappingDiagnostic),
}

/// Map one local initiative to its remote representation, or say why not (T034,
/// T035).
///
/// Pure: no adapter, no I/O, no configuration. Shared by both trackers so a future
/// one cannot be added with a divergent contract — and the representability
/// decision lives in exactly one place instead of once per adapter.
///
/// `initiative_id` is the **stable** id (C-002), never a display name: it is the
/// subject the diagnostic names, and the value a verified adapter would send.
#[must_use]
pub fn map_initiative_to_remote(tool: Tool, initiative_id: &str) -> MappedInitiative {
    let field = INITIATIVE_FIELD;
    if INITIATIVE_WIRE_VERIFIED.contains(&tool) {
        return MappedInitiative::Remote {
            field: field.to_string(),
            value: initiative_id.to_string(),
        };
    }
    MappedInitiative::Unsupported(RemoteMappingDiagnostic {
        relation_id: initiative_id.to_string(),
        field: field.to_string(),
        tool,
        message: initiative_absence_reason(tool).to_string(),
    })
}

/// Why a tracker's CLI cannot carry a local initiative, per tool.
///
/// The two reasons differ and the message must not blur them: GitLab's is a
/// **permanent** "the CLI has no such command", while Linear's is "the verb exists
/// but cannot hold the record's fields". A reader told the wrong one would either
/// wait for a command that will never appear or look for a flag that is not there.
fn initiative_absence_reason(tool: Tool) -> &'static str {
    if INITIATIVE_CLI_ABSENT.contains(&tool) {
        return "the CLI exposes no initiative command at all, so the whole local record is \
                kept; a remote that cannot hold an initiative never clears one";
    }
    "the CLI's `initiatives` verbs take only a name, a description and a status — they \
     cannot carry `owner`, `priority`, `labels`, `target_date`, or the typed \
     project/epic/milestone associations — so sending those three fields would drop the \
     rest; the whole local record is kept instead"
}

const GITLAB_BLOCKING_FIELD: &str = "blocking";
const GITLAB_BLOCKING_VALUE: &str = "blocks";
const LINEAR_BLOCKING_FIELD: &str = "blocks";
const LINEAR_BLOCKING_VALUE: &str = "blocks";

/// Map one local relationship to its remote representation, or say why not.
///
/// Pure: no adapter, no I/O, no configuration. Both trackers share it, so a future
/// one cannot be added with a divergent contract (T033) — and the representability
/// table lives in exactly one place instead of once per adapter.
///
/// `target` is the **target issue's remote reference**, if it is known: Linear's
/// `relations add` needs the target's remote identifier (`ENG-42`), and an edge
/// whose target has not been exported yet cannot be sent. Passing `None` therefore
/// yields a diagnostic that names the target and says so — never a guessed
/// identifier (C-005: the local edge survives). Trackers whose verb does not need a
/// second endpoint (or none of whose verbs are verified) ignore `target`.
#[must_use]
pub fn map_relation_to_remote(
    tool: Tool,
    relation: &crate::relationships::Relationship,
    target: Option<&str>,
) -> MappedRelation {
    use crate::relationships::RelationKind;
    let (field, value) = match tool {
        Tool::GitLab => (GITLAB_BLOCKING_FIELD, GITLAB_BLOCKING_VALUE),
        Tool::Linear => (LINEAR_BLOCKING_FIELD, LINEAR_BLOCKING_VALUE),
    };
    // The tracker's *model* can express a blocking edge — and the adapter drives a
    // CLI whose verb is verified only for the tools on `RELATION_WIRE_VERIFIED`.
    let model_supports = matches!(
        relation.kind,
        RelationKind::Blocks | RelationKind::BlockedBy
    );
    if model_supports && RELATION_WIRE_VERIFIED.contains(&tool) {
        let value = match tool {
            // Linear's `relations add` takes the target's **remote identifier** as
            // its second endpoint. Without one there is nothing to send, and a
            // guessed identifier would be worse than a diagnostic.
            Tool::Linear => match target {
                Some(target) => target.to_string(),
                None => {
                    return MappedRelation::Unsupported(RemoteMappingDiagnostic {
                        relation_id: relation.id.clone(),
                        field: field.to_string(),
                        tool,
                        message: format!(
                            "`{}` targets #{}, which has not been exported yet, so its \
                             remote identifier is unknown and the edge cannot be sent; \
                             the local edge is kept",
                            relation.kind.as_str(),
                            relation.to
                        ),
                    });
                }
            },
            // GitLab is never on `RELATION_WIRE_VERIFIED` (its CLI has no relation
            // command at all), so this arm is unreachable today; its rendering is
            // left exactly as it was rather than "fixed" into an unverified shape.
            Tool::GitLab => format!("{value} #{}", relation.to),
        };
        return MappedRelation::Remote {
            field: field.to_string(),
            value,
        };
    }
    if model_supports {
        // Expressible in the model, not drivable from the CLI. A *different* claim
        // from "unsupported", and the message says which — a reader who is told
        // "GitLab cannot express this" will not go looking for the verb. And for a
        // CLI verified to have no relation command at all, the message must not say
        // "not verified": there is nothing to verify (tix #1354).
        let reason = if RELATION_CLI_ABSENT.contains(&tool) {
            format!(
                "the {} CLI exposes no issue-relation command, so it cannot be sent",
                tool.as_str()
            )
        } else {
            "the CLI verb that would carry it is not verified, so nothing is sent".to_string()
        };
        return MappedRelation::Unsupported(RemoteMappingDiagnostic {
            relation_id: relation.id.clone(),
            field: field.to_string(),
            tool,
            message: format!(
                "`{}` is expressible in {}'s model as `{field}`, but {reason}; the local \
                 edge is kept",
                relation.kind.as_str(),
                tool.as_str()
            ),
        });
    }
    MappedRelation::Unsupported(RemoteMappingDiagnostic {
        relation_id: relation.id.clone(),
        field: field.to_string(),
        tool,
        message: format!(
            "`{}` is a local-only relation; {} has no field for it, so the local \
             edge is kept and the remote one is not created",
            relation.kind.as_str(),
            tool.as_str()
        ),
    })
}

/// The inverse: read a remote relation back to a local kind and target.
///
/// Symmetric with [`map_relation_to_remote`] by construction — the blocking field
/// maps back to `blocks`, and nothing else maps back at all. A remote payload
/// carrying a field this function does not recognise yields a diagnostic rather
/// than a default, so an import cannot invent a relation the export never made.
#[must_use]
pub fn map_relation_from_remote(
    tool: Tool,
    field: &str,
    value: &str,
    relation_id: &str,
) -> MappedRelation {
    let expected = match tool {
        Tool::GitLab => GITLAB_BLOCKING_FIELD,
        Tool::Linear => LINEAR_BLOCKING_FIELD,
    };
    // Gated the same way as the forward direction: without a verified verb there is
    // no payload this could have received, and coercing one would invent a
    // relationship the export never made.
    if field == expected && RELATION_WIRE_VERIFIED.contains(&tool) {
        // The value this module writes is `"{kind} #{n}"`, so the target is the
        // **last** whitespace-separated token. Taking the first reads the kind word
        // and fails — which is what an earlier version did, and it made the round
        // trip look asymmetric when only the parser was.
        if let Some(target) = value
            .split_whitespace()
            .last()
            .and_then(|t| t.strip_prefix('#'))
            .and_then(|t| t.parse::<u32>().ok())
        {
            // The reverse value is **local**-shaped — the canonical kind spelling
            // and a `#`-prefixed number — not a copy of the remote field name.
            // GitLab's field is `blocking` and Linear's is `blocks`; echoing the
            // field back would make the round trip return different text per
            // tracker for the same relationship, which is the opposite of
            // symmetric.
            return MappedRelation::Remote {
                field: "kind".to_string(),
                value: format!("blocks #{target}"),
            };
        }
        return MappedRelation::Unsupported(RemoteMappingDiagnostic {
            relation_id: relation_id.to_string(),
            field: field.to_string(),
            tool,
            message: format!(
                "`{value}` is not a target issue number, so the remote relation \
                 cannot be read back; no local edge was created"
            ),
        });
    }
    MappedRelation::Unsupported(RemoteMappingDiagnostic {
        relation_id: relation_id.to_string(),
        field: field.to_string(),
        tool,
        message: format!(
            "`{field}` is not a relation field {} writes, so it is ignored; the \
             local relationship set is unchanged",
            tool.as_str()
        ),
    })
}

/// Map a local column to the remote state/label sent to the tracker
/// (`contracts/external-tools.md` mapping table).
///
/// - GitLab: done → `closed`, anything else → `opened`.
/// - Linear: done → `Done`, otherwise the first non-done column label.
#[must_use]
pub fn local_to_remote_status(tool: Tool, local_status: &str, config: &Config) -> String {
    let board = config.default_config();
    match tool {
        Tool::GitLab => {
            if is_done_column(board, local_status, config) {
                "closed".into()
            } else {
                "opened".into()
            }
        }
        Tool::Linear => {
            if is_done_column(board, local_status, config) {
                "Done".into()
            } else {
                first_work_column(board, config).to_string()
            }
        }
    }
}

/// Map a remote state/label back onto a local column. Closed/Done maps to
/// the effective done column; anything else lands in the column whose name
/// matches (case-insensitive), else the first column — per the contract's
/// "whose name matches, else into the first column".
#[must_use]
pub fn remote_to_local_status(tool: Tool, remote_status: &str, config: &Config) -> String {
    let board = config.default_config();
    // WP07 T032: the *service's* completion column, not `done_column`. See
    // `completion_column` for why choosing one local column is this module's business
    // while the meaning of "complete" is not.
    let done = completion_column(board, config);
    match tool {
        Tool::GitLab => {
            if remote_status == "closed" {
                done
            } else {
                board
                    .columns
                    .first()
                    .cloned()
                    .unwrap_or_else(|| "todo".into())
            }
        }
        Tool::Linear => {
            if remote_status == "Done" {
                done
            } else {
                board
                    .columns
                    .iter()
                    .find(|c| c.eq_ignore_ascii_case(remote_status))
                    .cloned()
                    .unwrap_or_else(|| {
                        board
                            .columns
                            .first()
                            .cloned()
                            .unwrap_or_else(|| "todo".into())
                    })
            }
        }
    }
}

/// Whether `local_status` is the board's **completion** column, by the service.
///
/// WP07 T032. This was `board.effective_done_column() == Some(local_status)` — a
/// column-*name* comparison, which is a second local definition of "done" and exactly
/// what C-004 forbids. It agreed with the service on a board with no
/// `category_map` — every existing configuration — and disagreed on precisely the
/// boards this mission exists to support: a board mapping `shipped` to `completed`
/// exports `shipped` as *open* and leaves `done_column` (mapped to `active`) as
/// *closed*.
///
/// `sync/mod.rs` is out of this mission's map; the edit is the completion
/// reconciliation T032 names, and the rationale is recorded here and in
/// `decisions/WP07-verification.md`.
fn is_done_column(board: &BoardConfiguration, local_status: &str, config: &Config) -> bool {
    let resolution =
        crate::workflow::resolution(config, board, crate::workflow::active_board_name(config));
    resolution
        .resolve(local_status)
        .is_some_and(crate::workflow::WorkflowCategory::is_complete)
}

/// The board's completion **column**, chosen by the service rather than by
/// `done_column`.
///
/// The remote trackers have a two-state notion of "closed", so the export path has to
/// pick one local column to send as closed. That is a **remote-translation** concern
/// and belongs here; deciding what "complete" *means* is not, and is the service's.
///
/// Preferring the column the service calls complete means a board whose completion
/// category sits on a column other than `done_column` still round-trips: export
/// closes the column that is genuinely complete, and import brings it back to that
/// same column rather than to `done_column`.
fn completion_column(board: &BoardConfiguration, config: &Config) -> String {
    // WP09: this was a private re-implementation — the same "first complete column,
    // else `done_column`, else `done`" rule the service now owns, duplicated here so
    // that `first_work_column` and `remote_to_local_status` could each have a total
    // `String`. It is the module's own doc comment, written in WP07, that says a
    // second local definition is a C-004 defect, so the duplicate had to go.
    crate::workflow::completion_column_or_default(board, config)
}

/// The first column that is **not** the board's completion column, or the
/// completion column when every column is complete.
///
/// WP09: "not the done column" is a question about **completion**, so it is asked of
/// the service rather than of `done_column`. On a board whose `category_map` puts
/// `completed` on `shipped` while `done_column` is `done`, the old version returned
/// `todo` as the first *work* column when `shipped` is the first column that is
/// genuinely finished — so an export labelled a shipped issue as work in progress.
fn first_work_column<'a>(board: &'a BoardConfiguration, config: &Config) -> &'a str {
    // The lifetime is `board`'s, and the `done` fallback cannot borrow from `config`
    // — so the completion column is compared as a `String` and the fallback is a
    // literal. The alternative, returning `&'a str` from a local, is what forces the
    // old `unwrap_or("done")` to exist at all.
    let done = crate::workflow::completion_column_or_default(board, config);
    board
        .columns
        .iter()
        .find(|c| c.as_str() != done)
        .map_or("done", String::as_str)
}

/// The inverse of `model::civil_from_days` (Howard Hinnant's
/// `days_from_civil`): calendar date → days since the Unix epoch.
#[must_use]
pub fn days_from_civil(y: i64, m: u32, d: u32) -> i64 {
    let y = if m <= 2 { y - 1 } else { y };
    let era = if y >= 0 { y } else { y - 399 } / 400;
    let yoe = y - era * 400; // [0, 399]
    let mp = (m + 9) % 12; // [0, 11]
    let doy = i64::from((153 * mp + 2) / 5 + d - 1); // [0, 365]
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096]
    era * 146_097 + doe - 719_468
}

/// Parse `YYYY-MM-DD` into days since the Unix epoch.
#[must_use]
pub fn date_to_epoch_days(ymd: &str) -> Option<i64> {
    let mut parts = ymd.trim().split('-');
    let y: i64 = parts.next()?.parse().ok()?;
    let m: u32 = parts.next()?.parse().ok()?;
    let d: u32 = parts.next()?.parse().ok()?;
    if parts.next().is_some() {
        return None;
    }
    if !(1..=12).contains(&m) || !(1..=31).contains(&d) {
        return None;
    }
    Some(days_from_civil(y, m, d))
}

/// Parse an ISO-8601 remote timestamp into epoch seconds. Accepts
/// `YYYY-MM-DDTHH:MM:SS` (the `T` may be a space) with optional fractional
/// seconds and a `Z` or `±HH:MM` zone.
#[must_use]
pub fn iso_to_epoch_secs(input: &str) -> Option<i64> {
    let (date, time) = input.trim().split_once(['T', ' '])?;
    let days = date_to_epoch_days(date)?;
    let (time, zone) = split_zone(time);
    let mut hms = time.split(':');
    let hh: i64 = hms.next()?.parse().ok()?;
    let mm: i64 = hms.next()?.parse().ok()?;
    let ss_part = hms.next()?;
    let whole: i64 = ss_part.split('.').next()?.parse().ok()?;
    if !(0..=23).contains(&hh) || !(0..=59).contains(&mm) || !(0..=59).contains(&whole) {
        return None;
    }
    let mut secs = days * 86_400 + hh * 3600 + mm * 60 + whole;
    if let Some((zh, zm)) = zone {
        secs -= zh * 3600 + zm * 60;
    }
    Some(secs)
}

/// Split `HH:MM:SS[.frac][zone]` into the bare time and an optional
/// `(hours, minutes)` zone offset (already sign-adjusted).
fn split_zone(time: &str) -> (&str, Option<(i64, i64)>) {
    if time.ends_with('Z') || time.ends_with('z') {
        return (&time[..time.len() - 1], Some((0, 0)));
    }
    match time.rfind(['+', '-']) {
        Some(i) if i > 0 => {
            let (bare, zone) = time.split_at(i);
            let sign = if zone.starts_with('-') { -1i64 } else { 1i64 };
            let digits = &zone[1..];
            let (zh, zm) = if let Some((h, m)) = digits.split_once(':') {
                (h.parse::<i64>().ok(), m.parse::<i64>().ok())
            } else if digits.len() == 2 {
                (digits.parse::<i64>().ok(), Some(0))
            } else if digits.len() >= 3 {
                let (h, m) = digits.split_at(digits.len() - 2);
                (h.parse::<i64>().ok(), m.parse::<i64>().ok())
            } else {
                (None, None)
            };
            match (zh, zm) {
                (Some(zh), Some(zm)) => (bare, Some((sign * zh, sign * zm))),
                _ => (bare, None),
            }
        }
        Some(_) | None => (time, None),
    }
}

/// The conflict rule: the remote wins when its `updated_at` is strictly later
/// than the local issue's `updated` (a `YYYY-MM-DD` interpreted as end of
/// day). A remote timestamp that cannot be parsed counts as *not newer*, so
/// the local issue is kept.
#[must_use]
pub fn is_remote_newer(remote_updated_at: &str, local_updated: &str) -> bool {
    let Some(remote) = iso_to_epoch_secs(remote_updated_at) else {
        return false;
    };
    let local_end_of_day = date_to_epoch_days(local_updated).map_or(0, |d| d * 86_400 + 86_399);
    remote > local_end_of_day
}

/// Redact a resolved secret from text flowing through error/report surfaces.
#[must_use]
pub fn scrub_secret(text: &str, secret: &str) -> String {
    if secret.is_empty() {
        return text.to_string();
    }
    text.replace(secret, "<token>")
}

/// The contract's missing-binary wording (`contracts/external-tools.md`):
/// exit code 3 with `required tool not found: <tool> — install from <source>`.
fn not_found_message(program: &str) -> String {
    match program {
        "glab" => "required tool not found: glab — install from https://gitlab.com/gitlab-org/cli"
            .to_string(),
        _ => format!("required tool not found: {program} — install it and retry"),
    }
}

/// A dry-run stand-in for a remote reference that pass 1 of a real run would
/// create. Used only in the preview, so an edge to a not-yet-exported issue reads
/// as sendable without inventing an identifier.
const DRY_RUN_NEW_REF: &str = "<new remote id>";

/// `tix export`: mirror local issues to the remote tracker, recording the
/// remote id back into the local `gitlab_id`/`linear_id` so a re-run updates
/// instead of creating duplicates (idempotency, FR-Remote-sync).
///
/// Returns the number of issues handled (created or updated — `close` on an
/// updated GitLab done issue is not counted separately).
pub fn export(
    store: &Store,
    tool: Tool,
    config: &Config,
    dry_run: bool,
    out: &mut dyn Write,
) -> Result<SyncReport> {
    let mut adapter = adapter_for(tool, config)?;
    let mut report = SyncReport::default();
    // Built **once** for the whole run, which is the service's rule: resolution is
    // not rebuilt per issue. See `workflow::resolution`.
    let resolution = crate::workflow::resolution(config, config.default_config(), "default");

    if dry_run {
        for issue in store.list()? {
            match remote_ref(tool, &issue) {
                Some(r) => {
                    writeln!(out, "would update {tool} issue {r} \"{}\"", issue.title)?;
                }
                None => {
                    writeln!(out, "would create {tool} issue \"{}\"", issue.title)?;
                }
            }
        }
        writeln!(out, "dry run — {tool} CLI was not invoked")?;
        report.handled = store.list()?.len();
        // Every issue a real run would export, plus the remote references the
        // existing ones already carry. A relation endpoint that is **in the export
        // set** is resolvable: pass 1 will give it a remote reference, so the edge
        // is sendable and the preview must say so rather than report it as
        // unsendable. Only a target genuinely absent from the export set (nothing a
        // real run would create) is reported as unsendable.
        let export_set: HashSet<u32> = store.list()?.into_iter().map(|i| i.number).collect();
        let existing: HashMap<u32, String> = store
            .list()?
            .into_iter()
            .filter_map(|i| remote_ref(tool, &i).map(|r| (i.number, r.to_string())))
            .collect();
        // The dry run reports the same diagnostics a real run would, so
        // "preview then commit" is not the only way to find out that a
        // relationship cannot leave the machine.
        for issue in store.list()? {
            for rel in store.relationships_for(issue.number)? {
                // The same adjacency rule as the real pass 2: one edge, from its
                // declaring side, so a dry run previews exactly what a real run does
                // rather than reporting an edge twice.
                if rel.from != issue.number {
                    continue;
                }
                let other = if rel.from == issue.number {
                    rel.to
                } else {
                    rel.from
                };
                let target = if let Some(r) = existing.get(&other) {
                    Some(r.as_str())
                } else if export_set.contains(&other) {
                    // Unknown until pass 1 runs; a marker keeps the edge sendable in
                    // the preview without inventing an identifier.
                    Some(DRY_RUN_NEW_REF)
                } else {
                    None
                };
                match map_relation_to_remote(tool, &rel, target) {
                    MappedRelation::Remote { field, value } => {
                        writeln!(out, "would export {tool} {field} {value} ({})", rel.id)?;
                    }
                    unsupported @ MappedRelation::Unsupported(_) => {
                        report.note(unsupported, out)?
                    }
                }
            }
            // And the parent, so a dry run surfaces exactly what a real run would.
            if issue.parent.is_some() {
                report.note_parent(map_parent_to_remote(tool, issue.number, issue.parent), out)?;
            }
            // And every project association, for the same reason: on both trackers
            // the answer is "it cannot leave the machine", and a user previewing an
            // export is exactly who needs to know that before running it.
            for project_id in issue.projects.as_deref().unwrap_or_default() {
                report.note_project(map_project_to_remote(tool, issue.number, project_id), out)?;
            }
            // And every epic reference, for the same reason (C-007): the answer is
            // the same on both trackers, and a preview that hid it would be the one
            // place a reader could not learn it.
            for epic_id in issue.epics.as_deref().unwrap_or_default() {
                report.note_epic(map_epic_to_remote(tool, issue.number, epic_id), out)?;
            }
        }
        return Ok(report);
    }

    // **Pass 1** — create or update every issue, and record `issue.number -> remote
    // reference`. Projects and epics are sent here, because they hang off the issue
    // itself and need no other endpoint to exist.
    let mut remote_ids: HashMap<u32, String> = HashMap::new();
    let mut handled = 0;
    for mut issue in store.list()? {
        let remote_status = local_to_remote_status(tool, issue.status.display(), config);
        let labels: Vec<String> = issue.labels.clone();
        let assignee = issue.assignee.as_deref();
        let priority = issue.priority.to_string();
        match remote_ref(tool, &issue) {
            Some(r) => {
                let r = r.to_string();
                adapter.update_issue(
                    &r,
                    &issue.title,
                    &issue.body,
                    &labels,
                    assignee,
                    Some(&priority),
                    &remote_status,
                )?;
                if !adapter.done_via_status() && crate::workflow::is_completed(&issue, &resolution)
                {
                    adapter.mark_done(&r)?;
                }
                writeln!(out, "updated {tool} issue {r} \"{}\"", issue.title)?;
            }
            None => {
                let id = adapter.create_issue(
                    &issue.title,
                    &issue.body,
                    &labels,
                    assignee,
                    Some(&priority),
                    &remote_status,
                )?;
                if !adapter.done_via_status() && crate::workflow::is_completed(&issue, &resolution)
                {
                    adapter.mark_done(&id)?;
                }
                match tool {
                    Tool::GitLab => issue.gitlab_id = Some(id.clone()),
                    Tool::Linear => issue.linear_id = Some(id.clone()),
                }
                store.update(&issue.filename, &issue)?;
                writeln!(
                    out,
                    "created {tool} issue {id} \"{}\" (remote id recorded)",
                    issue.title
                )?;
            }
        }
        // The parent reference is offered to the same shared mapper, on the same
        // "after the issue" footing as a relationship: a parent only means
        // something once the parent itself exists remotely. Nothing is sent while
        // `PARENT_WIRE_VERIFIED` is empty, so this reports rather than acts — and
        // the local reference is untouched either way.
        report.note_parent(map_parent_to_remote(tool, issue.number, issue.parent), out)?;

        // Project associations are offered to the same shared mapper, on the same
        // "after the issue" footing as a relationship: what it accepts is sent to the
        // adapter, what it does not becomes a diagnostic naming the field. Nothing is
        // sendable on either tracker — see `PROJECT_WIRE_VERIFIED` — so this reports
        // rather than acts, and the local list is untouched either way (C-005). A
        // diagnostic is emitted whether or not the issue has a remote id yet, unlike
        // the relationship block below: the membership cannot be sent regardless, so
        // suppressing the report while the id is still missing would hide the one
        // fact the reader needs.
        let mut sendable_projects: Vec<MappedProject> = Vec::new();
        for project_id in issue.projects.as_deref().unwrap_or_default() {
            match map_project_to_remote(tool, issue.number, project_id) {
                MappedProject::Remote { field, value } => {
                    writeln!(out, "exported {tool} {field} {value} (#{})", issue.number)?;
                    sendable_projects.push(MappedProject::Remote { field, value });
                }
                unsupported @ MappedProject::Unsupported(_) => {
                    report.note_project(unsupported, out)?;
                }
            }
        }

        // Epic references are offered to the same shared mapper, on the same
        // "after the issue" footing: what it accepts would be sent to the adapter,
        // what it does not becomes a diagnostic naming the field. Nothing is
        // sendable on either tracker — see `EPIC_WIRE_VERIFIED` — so this reports
        // rather than acts, and the local reference list is untouched either way
        // (C-007). A diagnostic is emitted whether or not the issue has a remote id
        // yet, for the same reason the project block gives: the reference cannot be
        // sent regardless, so suppressing the report while the id is missing would
        // hide the one fact the reader needs.
        let mut sendable_epics: Vec<MappedEpic> = Vec::new();
        for epic_id in issue.epics.as_deref().unwrap_or_default() {
            match map_epic_to_remote(tool, issue.number, epic_id) {
                MappedEpic::Remote { field, value } => {
                    writeln!(out, "exported {tool} {field} {value} (#{})", issue.number)?;
                    sendable_epics.push(MappedEpic::Remote { field, value });
                }
                unsupported @ MappedEpic::Unsupported(_) => {
                    report.note_epic(unsupported, out)?;
                }
            }
        }

        let remote = match remote_ref(tool, &issue) {
            Some(r) => r.to_string(),
            None => match tool {
                Tool::GitLab => issue.gitlab_id.clone(),
                Tool::Linear => issue.linear_id.clone(),
            }
            .unwrap_or_default(),
        };
        if !remote.is_empty() {
            adapter.set_projects(&remote, &sendable_projects)?;
            adapter.set_epics(&remote, &sendable_epics)?;
            remote_ids.insert(issue.number, remote);
        }
        handled += 1;
    }

    // **Pass 2** — the relationships, now that **both** endpoints exist remotely.
    // An edge is only meaningful once both issues have a remote reference, and on a
    // first export the target is frequently created *after* the issue the edge is
    // stored on, so this cannot run inside pass 1. Each is offered to the shared
    // mapper with the target's resolved remote reference: what it accepts is sent to
    // the adapter, what it does not (including a target that was never exported)
    // becomes a diagnostic naming the field. The adapter never decides
    // representability.
    for issue in store.list()? {
        let Some(remote) = remote_ids.get(&issue.number).cloned() else {
            continue;
        };
        let mut sendable = Vec::new();
        for rel in store.relationships_for(issue.number)? {
            // `relationships_for` is an **adjacency** lookup: it returns every edge
            // that *touches* this issue, in its stored form (`from` is the declaring
            // side). Send each edge exactly once, from its declaring side — Linear's
            // `relations add` is additive, so sending it from both endpoints would
            // create a duplicate remote edge (and print the line twice).
            if rel.from != issue.number {
                continue;
            }
            // `from` is now this issue, so the other endpoint is `to`; spelled out
            // rather than assumed, so the adjacency semantics are not re-learnt by
            // the next reader.
            let other = if rel.from == issue.number {
                rel.to
            } else {
                rel.from
            };
            let target = remote_ids.get(&other).map(String::as_str);
            match map_relation_to_remote(tool, &rel, target) {
                MappedRelation::Remote { field, value } => {
                    writeln!(out, "exported {tool} {field} {value} ({})", rel.id)?;
                    sendable.push(MappedRelation::Remote { field, value });
                }
                unsupported @ MappedRelation::Unsupported(_) => report.note(unsupported, out)?,
            }
        }
        adapter.set_relations(&remote, &sendable)?;
    }
    report.handled = handled;
    writeln!(
        out,
        "exported {handled} issue(s) to {tool} ({} diagnostic(s) — local data the remote \
         cannot hold)",
        report.diagnostics.len()
    )?;
    Ok(report)
}

/// `tix import`: pull open remote issues into local files.
///
/// Conflict resolution: a remote issue that already tracks a local one skips
/// the local file when the local `updated` is later or equal; when the remote
/// `updated_at` is newer the local file is overwritten (fields + body, keeping
/// `created`), with the previous file first copied into the centralized backup
/// directory (`.tix-backups/` beside the issues directory, #1581).
///
/// `policy` is the explicit triage-entry policy (WP07 T034). It decides **only
/// where a newly created file lands and what the report says about it**: the
/// conflict rules above, remote ids, and adapter behaviour are untouched, and
/// the overwrite path never consults it (T036).
///
/// Returns the number of local files created or overwritten.
pub fn import(
    store: &Store,
    tool: Tool,
    config: &Config,
    out: &mut dyn Write,
    policy: crate::triage::import_policy::ImportPolicy,
) -> Result<SyncReport> {
    let mut adapter = adapter_for(tool, config)?;
    import_with_adapter(store, tool, config, out, policy, adapter.as_mut())
}

/// [`import`] with the adapter injected — the [`CommandRunner`] pattern, so the
/// orchestration under test is the real one and the remote side is a fake that
/// returns canned [`RemoteIssue`]s without spawning a process (WP07 T037).
///
/// `command`s like `tix import` still go through [`import`]; this entry point
/// exists so a test can hold every input of the triage policy in one place —
/// config, policy, and the remote payloads — instead of installing a fake
/// binary on `PATH` and running the compiled CLI to reach it.
pub fn import_with_adapter(
    store: &Store,
    tool: Tool,
    config: &Config,
    out: &mut dyn Write,
    policy: crate::triage::import_policy::ImportPolicy,
    adapter: &mut dyn TrackerAdapter,
) -> Result<SyncReport> {
    // Resolved **before** the loop: a policy this project cannot represent
    // refuses the whole import, not the third item of it.
    let router = crate::triage::import_policy::resolve(config, policy)?;
    let remote_issues = adapter.list_open()?;
    let mut report = SyncReport::default();
    let mut handled = 0;
    // Remote ids imported this run, paired with the local number each one landed
    // on. A parent is named by a **remote** id in the payload, so the reference can
    // only be restored after the parent itself has been created — which is why
    // this is a second pass rather than something set while building each issue.
    let mut imported: Vec<(String, u32)> = Vec::new();
    // `(child remote id, parent remote id)` for every payload that named one.
    let mut claims: Vec<(String, String)> = Vec::new();
    // `(remote issue id, the project references that payload reported)` — WP08.
    // Collected for **every** payload, and applied after the issues exist, so a
    // payload's order cannot decide whether an association lands (T037 step 4).
    let mut project_payloads: Vec<(String, Vec<RemoteProject>)> = Vec::new();
    // `(remote issue id, the epic references that payload reported)` — WP08. Same
    // second-pass treatment as the project payloads, so the order a payload's issues
    // arrive in cannot decide whether a reference lands.
    let mut epic_payloads: Vec<(String, Vec<RemoteEpic>)> = Vec::new();
    // `(remote issue id, the local number it landed on)` for every payload this run
    // found a local counterpart for — created here or already tracked. Distinct from
    // `imported`, which is create-only and is what the parent pass resolves
    // references through.
    let mut located: Vec<(String, u32)> = Vec::new();
    for remote in remote_issues.clone() {
        if let Some(parent) = remote.parent.clone() {
            claims.push((remote.id.clone(), parent));
        }
        if !remote.projects.is_empty() {
            project_payloads.push((remote.id.clone(), remote.projects.clone()));
        }
        if !remote.epics.is_empty() {
            epic_payloads.push((remote.id.clone(), remote.epics.clone()));
        }
        let tracked = store
            .list()?
            .into_iter()
            .find(|i| remote_ref(tool, i) == Some(remote.id.as_str()));
        match tracked {
            None => {
                // WP07 T034/T035: the placement decision is made here, once, from
                // the remote state and the configured entry column — before any
                // byte of the file exists. `requested` comes from this module's
                // own mapper rather than being re-derived by the policy, so the
                // two answers can be compared in the report instead of guessed at.
                let requested = remote_to_local_status(tool, &remote.state, config);
                let mapping = router.place(&remote.state, &requested);
                let mut issue = Issue {
                    projects: None,
                    id: None,
                    number: 0,
                    title: remote.title.clone(),
                    status: Status::new(mapping.landed.clone()),
                    labels: remote.labels.clone(),
                    priority: crate::model::Priority::Medium,
                    assignee: remote.assignee.clone(),
                    estimate: None,
                    commit: None,
                    gitlab_id: None,
                    linear_id: None,
                    mission: None,
                    task: None,
                    relationships: vec![],
                    related_issues: vec![],
                    files: vec![],
                    cycles: None,
                    milestones: None,
                    reviewer: None,
                    start_date: None,
                    due_date: None,
                    created: crate::model::today(),
                    type_: None,
                    updated: crate::model::today(),
                    filename: String::new(),
                    body: String::new(),
                    history: crate::model::History::new(),
                    has_retired_links_key: false,
                    time_entries: vec![],
                    parent: None,
                    series: None,
                    health: None,
                    epics: None,
                    extra_frontmatter: std::collections::BTreeMap::new(),
                    archived: false,
                    entered_at: None,
                    source: None,
                };
                // T035: entry metadata through the same seam every other entry
                // uses. The queue's age is measured from `entered_at`, so an issue
                // that entered the board through an import has to record that it
                // did — and `import` is the origin data-model §2 documents for it.
                //
                // The **landing column** decides, not `mapping.routed`: `routed` is a
                // policy notion, so under `--triage-policy remote` (or a default whose
                // remote-mapped column happens to be the entry column) an imported
                // issue landed in the inbox with no stamp and the queue reported
                // `unknown` for an issue it was listing. On a project with no
                // `[triage]` section the shared rule stamps nothing, which is the
                // outcome the old guard was reaching for.
                crate::triage::record_entry_if_inbox(config, &mut issue, "import")?;
                match tool {
                    Tool::GitLab => issue.gitlab_id = Some(remote.id.clone()),
                    Tool::Linear => issue.linear_id = Some(remote.id.clone()),
                }
                // WP07 T031: a **column check** on the incoming status, and only
                // that. `remote_to_local_status` already lands on a column the board
                // configures — the service's completion column, or a name match, or
                // the first — so this is the belt to that braces, and it means an
                // import can never create a file in a column the board lacks. The
                // create path performs the same check (WP05), so this is belt *and*
                // braces for the remote-sourced case.
                //
                // Not a transition evaluation: a new issue is not leaving anywhere, so
                // the terminal lock has nothing to say. Importing an issue directly
                // into a terminal column is legitimate.
                let (_, resolution) = crate::workflow::active_resolution(config);
                if resolution.resolve(issue.status.display()).is_none() {
                    // Reported, not written. A skipped item is visible and the rest of
                    // the batch still lands.
                    writeln!(
                        out,
                        "skipped {tool} issue {} \"{}\": `{}` is not a column on board `{}`",
                        remote.id, remote.title, issue.status, resolution.board
                    )?;
                    report.skipped += 1;
                    continue;
                }
                // One transaction per imported issue (#1580), never one over the
                // whole import: each remote issue has its own outcome, and a
                // failure on one must not roll back the others. `create` claims a
                // number and writes the file, so the claim and the bytes are one
                // unit.
                let path =
                    store.transaction(|| store.create(&mut issue, &remote.description, None))?;
                imported.push((remote.id.clone(), issue.number));
                located.push((remote.id.clone(), issue.number));
                let name = path
                    .file_name()
                    .map(|n| n.to_string_lossy().to_string())
                    .unwrap_or_default();
                // T035: the mapping is named in the same line that names the file,
                // and `report_clause` is empty exactly when the default policy
                // decided nothing — so a legacy project's report is byte-identical
                // to what it was, and a project that routed says where the remote
                // state asked for and where the issue landed.
                let clause = mapping.report_clause();
                writeln!(
                    out,
                    "imported {tool} issue {} \"{}\" as #{} ({}) [{name}]{clause}",
                    remote.id, remote.title, issue.number, issue.status
                )?;
                handled += 1;
            }
            Some(local) => {
                // The payload found its local issue. Recorded before the branches
                // below, because the association pass needs to attach a remote
                // payload's projects to it whether or not this run also overwrote
                // its fields — "kept" is a statement about title and body, not about
                // membership.
                located.push((remote.id.clone(), local.number));
                if is_remote_newer(remote.updated_at.as_deref().unwrap_or(""), &local.updated) {
                    let backup = crate::backup::save(&store.issues_dir, &local.filename);
                    // Captured before `local` is moved into `overwritten`: the
                    // skip path restores the local status, and reading it back off
                    // `overwritten` after the assignment would restore the status the
                    // *incoming* value was about to overwrite.
                    let local_status = local.status.clone();
                    let mut overwritten = local;
                    let keep_created = overwritten.created.clone();
                    overwritten.title = remote.title.clone();
                    overwritten.body = remote.description.clone();
                    overwritten.labels = remote.labels.clone();
                    let incoming = Status::new(remote_to_local_status(tool, &remote.state, config));
                    // WP07 T031: validate the incoming status as a **transition**,
                    // because this *is* one — an existing issue moving columns.
                    //
                    // **Skip-and-report**, which is the disposition the design settles
                    // (T031 step 3). The alternative, apply-and-report, would make a
                    // board's policy non-binding for the one path nobody watches, and
                    // a remote whose states the board forbids would quietly win.
                    // Skipping keeps the local file truthful and puts the conflict in
                    // the report where a human will see it. Recorded here rather than
                    // in `data-model.md` §8, which is a protected path for this lane.
                    let (_, resolution) = crate::workflow::active_resolution(config);
                    let transition = crate::workflow::validate_transition(
                        &overwritten,
                        incoming.display(),
                        &resolution,
                        config,
                        None,
                    );
                    if let crate::workflow::TransitionOutcome::Rejected(diagnostic) = transition {
                        // The status is left alone; the other fields still import,
                        // because they are not what the policy governs. The file is
                        // rewritten, so this is a **partial** import — reported as such
                        // rather than as a plain overwrite.
                        overwritten.status = local_status.clone();
                        overwritten.title = remote.title.clone();
                        overwritten.body = remote.description.clone();
                        overwritten.labels = remote.labels.clone();
                        if let Some(a) = &remote.assignee {
                            overwritten.assignee = Some(a.clone());
                        }
                        overwritten.created = keep_created;
                        overwritten.bump_updated();
                        let filename = overwritten.filename.clone();
                        // One transaction for the item's corpus write (#1580): the
                        // `update` writes the file and may then reconcile its
                        // location, so those two mutations are one unit. The
                        // backup copy above is deliberately out-of-corpus and is
                        // not part of the journaled set.
                        store.transaction(|| store.update(&filename, &overwritten))?;
                        writeln!(
                            out,
                            "overwrote {tool} issue {} \"{}\" without its status: {diagnostic} \
                             (kept {})",
                            remote.id, overwritten.title, overwritten.status
                        )?;
                        report.skipped += 1;
                        handled += 1;
                        continue;
                    }
                    overwritten.status = incoming;
                    if let Some(a) = &remote.assignee {
                        overwritten.assignee = Some(a.clone());
                    }
                    overwritten.created = keep_created;
                    overwritten.bump_updated();
                    let filename = overwritten.filename.clone();

                    // An import that moves a locally-blocked issue into the
                    // board's completion column goes through the same blocked-move
                    // policy as every other surface -- WP04 T016 step 6 names
                    // "any bulk or import path" explicitly, and an import that
                    // can end an issue in the completion column with open
                    // blockers is the sharpest form of that.
                    //
                    // It **records** the acknowledgement rather than refusing, and
                    // the asymmetry is deliberate. There is no interactive
                    // confirmation available mid-import, and refusing would make
                    // `tix import` unusable whenever one issue in a batch carries
                    // a stale blocker -- turning a stale local edge into a
                    // permanently un-syncable board. The user ran the import;
                    // that is the decision, and the event exists to preserve it.
                    // Where a human is present to answer, refusing is right
                    // (`tix move`, `tix edit --status`, `move_issue`); here the
                    // honest record is that the import did it.
                    let guard = crate::commands::mv::blocked_move_guard(
                        config,
                        store,
                        &overwritten,
                        overwritten.status.display(),
                    )?;
                    if let Some(warning) = guard.warning() {
                        overwritten.history.append_now(
                            &crate::storage::actor_identity(),
                            crate::model::HistoryEventKind::BlockedMoveAcknowledged,
                            &format!("imported to {}: {warning}", overwritten.status.display()),
                        );
                    }
                    store.transaction(|| store.update(&filename, &overwritten))?;
                    let backup_label = backup
                        .as_ref()
                        .map(|p| p.display().to_string())
                        .unwrap_or_else(|| "none".to_string());
                    writeln!(
                        out,
                        "overwrote {tool} issue {} \"{}\" (remote newer; backup at {backup_label})",
                        remote.id, overwritten.title
                    )?;
                    handled += 1;
                } else {
                    writeln!(
                        out,
                        "kept {tool} issue {} \"{}\" (local updated later or equal)",
                        remote.id, remote.title
                    )?;
                }
            }
        }
    }
    restore_imported_parents(store, tool, &claims, &imported, &mut report, out)?;
    apply_imported_projects(
        store,
        config,
        tool,
        &project_payloads,
        &located,
        &mut report,
        out,
    )?;
    apply_imported_epics(
        store,
        config,
        tool,
        &epic_payloads,
        &located,
        &mut report,
        out,
    )?;
    writeln!(out, "imported {handled} {tool} issue(s)")?;
    report.handled = handled;
    Ok(report)
}

/// Restore the parent references an import's payload reported.
///
/// A **second pass**, because a payload names a parent by *remote* id and the
/// parent may well be imported after its child. Setting the field while building
/// each issue would therefore succeed or fail depending on the order the remote
/// happened to return, which is the order-dependence NFR-003 forbids.
///
/// Every write goes through [`crate::hierarchy::set_parent`] rather than a field
/// assignment, so an imported reference obeys the same rules as a CLI write: it is
/// validated before anything is written, and a refusal leaves the file
/// byte-identical. T032's note is explicit — "an import that would create a cycle
/// is a defect, not a special case" — and the service is what decides that, not
/// this loop.
///
/// `claims` is `(child remote id, parent remote id)` and `imported` is
/// `(remote id, local number)`. A pair where either side does not resolve becomes a
/// diagnostic rather than a write: a reference to an issue this run did not import
/// is exactly the unresolved-parent state WP05 added a finding for, and
/// manufacturing it here would be this loop's own defect.
fn restore_imported_parents(
    store: &Store,
    tool: Tool,
    claims: &[(String, String)],
    imported: &[(String, u32)],
    report: &mut SyncReport,
    out: &mut dyn Write,
) -> Result<()> {
    for (child_remote, parent_remote) in claims {
        let child = imported
            .iter()
            .find(|(id, _)| id == child_remote)
            .map(|(_, number)| *number);
        let parent = imported
            .iter()
            .find(|(id, _)| id == parent_remote)
            .map(|(_, number)| *number);
        let (Some(child), Some(parent)) = (child, parent) else {
            report.note_parent(
                MappedParent::Unsupported(RemoteMappingDiagnostic {
                    relation_id: format!("{child_remote}->{parent_remote}"),
                    field: parent_field(tool).to_string(),
                    tool,
                    message: format!(
                        "remote issue {child_remote} reports parent {parent_remote}, \
                         which this import did not create — it may be closed, \
                         filtered out, or in another project; no local reference is \
                         written, so the issue stays parentless rather than \
                         unresolved"
                    ),
                }),
                out,
            )?;
            continue;
        };
        // Through `Store::set_parent`, which resolves, validates with the
        // hierarchy service, writes, and records the one History entry — the
        // same path `tix edit --parent` takes, so an imported reference is
        // indistinguishable from a typed one. A refusal is reported and nothing is
        // written.
        let (child_sel, parent_sel) = (child.to_string(), parent.to_string());
        match store.set_parent(&child_sel, &parent_sel) {
            Ok(_) => writeln!(out, "restored parent of {tool} issue #{child} to #{parent}")?,
            Err(e) => {
                writeln!(
                    out,
                    "could not restore the parent of {tool} issue #{child}: {e}; the \
                     reference was not written"
                )?;
                report.diagnostics.push(RemoteMappingDiagnostic {
                    relation_id: format!("{child}->{parent}"),
                    field: parent_field(tool).to_string(),
                    tool,
                    message: format!(
                        "the remote reports #{child} under #{parent}, but the hierarchy \
                         service refused it: {e}"
                    ),
                });
            }
        }
    }
    Ok(())
}

/// Apply the project associations an import's payloads reported (WP08 T037).
///
/// A **second pass**, like [`restore_imported_parents`], because the association
/// belongs to an issue that must exist locally first and because the order a
/// remote happened to list its issues in must not decide the outcome (T037 step
/// 4). Every payload that found a local issue is in `located`, so an issue created
/// *after* its sibling still gets its memberships.
///
/// ## Every write goes through the project service
///
/// [`Store::associate`] is the same path `tix project add` will take, so
/// uniqueness, reference validation and the one History entry per accepted change
/// are the service's decisions rather than a second membership rule here. An
/// already-present association is the service's idempotent no-op: it writes
/// nothing, appends nothing, and leaves the canonical file byte-stable — which is
/// what makes a repeated import a true no-op (T037 step 3).
///
/// ## Matching is by id, and only by id
///
/// `resolve_project_id` also accepts a project *name*, because a human selects
/// projects by name. An import must not: a name is a display label (C-002), so a
/// remote that renames a project — or a local registry whose name happens to
/// equal the remote's id — would resolve to the wrong project, or to a second
/// association for a membership that is already there. The registry is therefore
/// consulted by **key** before the service is called, which both enforces
/// id-only matching and makes the refusal diagnosable instead of an
/// `unknown_project` error string.
///
/// ## An unknown id is diagnosed, never written
///
/// Writing the association would manufacture a dangling reference — one per
/// issue, per run, for a project the registry has never heard of: the "missing
/// reference storm" T037 step 4 names. The remote keeps the association, the
/// local file is untouched, and the diagnostic names the field, the tool and the
/// id (C-005). The registry itself is **never** written: the local
/// `[projects.<id>]` section is this repository's configuration (C-001) and not
/// the remote's to rewrite, which is also why there is no window in which a
/// partially written registry could exist.
///
/// A payload the import skipped — an issue whose remote state is not a column on
/// the board — was already reported on its own line and has no local issue to
/// attach a membership to, so it is passed over here rather than diagnosed twice.
fn apply_imported_projects(
    store: &Store,
    config: &Config,
    tool: Tool,
    payloads: &[(String, Vec<RemoteProject>)],
    located: &[(String, u32)],
    report: &mut SyncReport,
    out: &mut dyn Write,
) -> Result<()> {
    if payloads.is_empty() {
        return Ok(());
    }
    // Resolved once, with a **no-op** warning sink: this is the same resolution the
    // adapters use, and quoting the project name the remote reported is the one
    // place remote output reaches a diagnostic, so it has to be scrubbed. The sink
    // is silent because `token::resolve` already warned on the adapter's behalf for
    // this run — warning twice per import would be noise, not extra safety.
    let secret = token::resolve(tool, config, &token::RealEnv, &mut |_| {})
        .secret()
        .map(str::to_string);
    for (remote_id, projects) in payloads {
        let Some(local_number) = located
            .iter()
            .find(|(id, _)| id == remote_id)
            .map(|(_, number)| *number)
        else {
            continue;
        };
        for project in projects {
            let project_id = match map_project_from_remote(tool, project) {
                MappedProject::Remote { value, .. } => value,
                MappedProject::Unsupported(mut diagnostic) => {
                    scrub_diagnostic(&mut diagnostic, secret.as_deref());
                    report.note_project(MappedProject::Unsupported(diagnostic), out)?;
                    continue;
                }
            };
            if !config.projects.contains_key(project_id.as_str()) {
                let mut diagnostic = RemoteMappingDiagnostic {
                    relation_id: format!("{local_number}->{project_id}"),
                    field: project_field(tool).to_string(),
                    tool,
                    message: format!(
                        "the remote reports #{local_number} in project `{project_id}`{}, \
                         which this repository's registry does not declare; nothing was \
                         written — the association stays on the remote and no missing \
                         reference was created locally",
                        project
                            .name
                            .as_deref()
                            .map(|name| format!(" (`{name}`)"))
                            .unwrap_or_default()
                    ),
                };
                scrub_diagnostic(&mut diagnostic, secret.as_deref());
                report.note_project(MappedProject::Unsupported(diagnostic), out)?;
                continue;
            }
            match store.associate(&local_number.to_string(), &project_id) {
                Ok(applied) if applied.changed => {
                    writeln!(
                        out,
                        "associated {tool} issue #{local_number} with {}",
                        crate::projects::association_detail(&project_id, true)
                    )?;
                }
                // Already associated: the service's no-op, so nothing was written and
                // no History entry was appended. Silent on purpose — a report line per
                // unchanged association would make every re-import look like work.
                Ok(_) => {}
                Err(error) => {
                    let mut diagnostic = RemoteMappingDiagnostic {
                        relation_id: format!("{local_number}->{project_id}"),
                        field: project_field(tool).to_string(),
                        tool,
                        message: format!(
                            "the remote reports #{local_number} in project `{project_id}`, \
                             but the project service refused the association: {error}; the \
                             local association list is unchanged"
                        ),
                    };
                    scrub_diagnostic(&mut diagnostic, secret.as_deref());
                    report.note_project(MappedProject::Unsupported(diagnostic), out)?;
                }
            }
        }
    }
    Ok(())
}

/// Apply the epic references an import's payloads reported (WP08, mission
/// `epics-work-items-01M3BYW4`).
///
/// A **second pass**, like [`apply_imported_projects`], because the reference
/// belongs to an issue that must exist locally first and because the order a remote
/// happened to list its issues in must not decide the outcome. Every payload that
/// found a local issue is in `located`, so an issue created *after* its sibling
/// still gets its references.
///
/// ## Every write goes through the epic service
///
/// [`Store::reference_epic`] is the same path `tix edit --add-epic` takes, so
/// uniqueness, reference validation and the one History entry per accepted change
/// are the service's decisions rather than a second reference rule here. An
/// already-present reference is the service's idempotent no-op: it writes nothing,
/// appends nothing, and leaves the canonical file byte-stable — which is what makes
/// a repeated import a true no-op (T039 step 3).
///
/// ## Matching is by id, and only by id
///
/// `resolve_epic_id` also accepts an epic *name*, because a human selects epics by
/// name. An import must not: a name is a display label (C-003), so a remote that
/// renames an epic — or a local registry whose name happens to equal the remote's id
/// — would resolve to the wrong epic, or to a second reference for a reference that
/// is already there. The registry is therefore consulted by **key** before the
/// service is called, which both enforces id-only matching and makes the refusal
/// diagnosable instead of an `unknown_epic` error string.
///
/// ## An unknown id is diagnosed, never written
///
/// Writing the reference would manufacture a dangling reference — one per issue, per
/// run, for an epic the registry has never heard of: the "missing reference storm"
/// T039 step 4 names. The remote keeps the reference, the local file is untouched,
/// and the diagnostic names the field, the tool and the id (C-007). The registry
/// itself is **never** written: the local `[epics.<id>]` section is this repository's
/// configuration (C-004) and not the remote's to rewrite, which is also why there is
/// no window in which a partially written registry could exist.
///
/// A payload the import skipped — an issue whose remote state is not a column on the
/// board — was already reported on its own line and has no local issue to attach a
/// reference to, so it is passed over here rather than diagnosed twice.
fn apply_imported_epics(
    store: &Store,
    config: &Config,
    tool: Tool,
    payloads: &[(String, Vec<RemoteEpic>)],
    located: &[(String, u32)],
    report: &mut SyncReport,
    out: &mut dyn Write,
) -> Result<()> {
    if payloads.is_empty() {
        return Ok(());
    }
    // Resolved once, with a **no-op** warning sink: the same resolution the adapters
    // use, and quoting the epic name the remote reported is the one place remote
    // output reaches a diagnostic, so it has to be scrubbed. The sink is silent
    // because `token::resolve` already warned on the adapter's behalf for this run.
    let secret = token::resolve(tool, config, &token::RealEnv, &mut |_| {})
        .secret()
        .map(str::to_string);
    for (remote_id, epics) in payloads {
        let Some(local_number) = located
            .iter()
            .find(|(id, _)| id == remote_id)
            .map(|(_, number)| *number)
        else {
            continue;
        };
        for epic in epics {
            let epic_id = match map_epic_from_remote(tool, epic) {
                MappedEpic::Remote { value, .. } => value,
                MappedEpic::Unsupported(mut diagnostic) => {
                    scrub_diagnostic(&mut diagnostic, secret.as_deref());
                    report.note_epic(MappedEpic::Unsupported(diagnostic), out)?;
                    continue;
                }
            };
            if !config.epics.contains_key(epic_id.as_str()) {
                let mut diagnostic = RemoteMappingDiagnostic {
                    relation_id: format!("{local_number}->{epic_id}"),
                    field: EPIC_FIELD.to_string(),
                    tool,
                    message: format!(
                        "the remote reports #{local_number} in epic `{epic_id}`{}, which \
                         this repository's registry does not declare; nothing was written \
                         — the reference stays on the remote and no missing reference \
                         was created locally",
                        epic.name
                            .as_deref()
                            .map(|name| format!(" (`{name}`)"))
                            .unwrap_or_default()
                    ),
                };
                scrub_diagnostic(&mut diagnostic, secret.as_deref());
                report.note_epic(MappedEpic::Unsupported(diagnostic), out)?;
                continue;
            }
            match store.reference_epic(&local_number.to_string(), &epic_id) {
                Ok(applied) if applied.changed => {
                    writeln!(
                        out,
                        "referenced {tool} issue #{local_number} with {}",
                        crate::epics::reference_detail(&epic_id, true)
                    )?;
                }
                // Already referenced: the service's no-op, so nothing was written and
                // no History entry was appended. Silent on purpose — a report line per
                // unchanged reference would make every re-import look like work.
                Ok(_) => {}
                Err(error) => {
                    let mut diagnostic = RemoteMappingDiagnostic {
                        relation_id: format!("{local_number}->{epic_id}"),
                        field: EPIC_FIELD.to_string(),
                        tool,
                        message: format!(
                            "the remote reports #{local_number} in epic `{epic_id}`, but \
                             the epic service refused the reference: {error}; the local \
                             reference list is unchanged"
                        ),
                    };
                    scrub_diagnostic(&mut diagnostic, secret.as_deref());
                    report.note_epic(MappedEpic::Unsupported(diagnostic), out)?;
                }
            }
        }
    }
    Ok(())
}

/// Whether a computed **remote** status conveys "done" in that tracker's own
/// vocabulary.
///
/// Deliberately **not** the completion decision. `closed` is GitLab's word and
/// `Done` is Linear's; neither is a local column name, so this cannot be a
/// category question, and routing it through the service would mean asking the
/// service about a string from a different vocabulary.
///
/// It used to decide *local* completion at the export call sites, by mapping the
/// local status out to a remote string and testing that — a round trip that can
/// disagree with the category rule on any board with a category_map. Those call
/// sites now ask \`workflow::is_completed\` about the local issue (C-004), and this
/// function keeps only the narrower job it can actually do: telling an adapter
/// whether its own status update already closed the remote issue.
fn remote_ref(tool: Tool, issue: &Issue) -> Option<&str> {
    match tool {
        Tool::GitLab => issue.gitlab_id.as_deref(),
        Tool::Linear => issue.linear_id.as_deref(),
    }
}

/// Build and configure the adapter for `tool`: resolves the token with env
/// precedence, validates the `[export]` target section, and returns the
/// tool-specific adapter wired to a [`ProcessRunner`].
fn adapter_for(tool: Tool, config: &Config) -> Result<Box<dyn TrackerAdapter>> {
    // The contract's warning starts with "warning:" — no `tix:` prefix.
    let mut warn = |w: &str| eprintln!("{w}");
    let resolution = token::resolve(tool, config, &token::RealEnv, &mut warn);
    let secret = resolution.secret().map(str::to_string);
    match tool {
        Tool::GitLab => {
            let rc = config.export.gitlab.as_ref().ok_or_else(|| {
                TixError::Config("no `[export.gitlab]` section in tix.toml — run `tix init --with gitlab` or edit tix.toml".to_string())
            })?;
            let project = rc.project.clone().ok_or_else(|| {
                TixError::Config("`[export.gitlab].project` is not set — add `project = \"acme/tix\"` to tix.toml".to_string())
            })?;
            Ok(Box::new(glab::GitLabAdapter::new(
                ProcessRunner,
                secret,
                rc.base_url.clone(),
                project,
            )))
        }
        Tool::Linear => {
            let rc = config.export.linear.as_ref().ok_or_else(|| {
                TixError::Config("no `[export.linear]` section in tix.toml — run `tix init --with linear` or edit tix.toml".to_string())
            })?;
            let team = rc.team.clone().ok_or_else(|| {
                TixError::Config(
                    "`[export.linear].team` is not set — add `team = \"Eng\"` to tix.toml"
                        .to_string(),
                )
            })?;
            Ok(Box::new(linear::LinearAdapter::new(
                ProcessRunner,
                secret,
                team,
            )))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn target_parsing_accepts_only_the_two_contract_targets() {
        assert_eq!(Tool::from_target("gitlab").unwrap(), Tool::GitLab);
        assert_eq!(Tool::from_target("linear").unwrap(), Tool::Linear);
        assert!(Tool::from_target("github").is_err());
        assert_eq!(Tool::GitLab.token_var(), "GITLAB_TOKEN");
        assert_eq!(Tool::Linear.token_var(), "LINEAR_TOKEN");
        assert_eq!(Tool::GitLab.binary(), "glab");
        assert_eq!(Tool::Linear.binary(), "linear-cli");
    }

    #[test]
    fn gitlab_status_mapping() {
        let config = Config::default();
        assert_eq!(
            local_to_remote_status(Tool::GitLab, "todo", &config),
            "opened"
        );
        assert_eq!(
            local_to_remote_status(Tool::GitLab, "done", &config),
            "closed"
        );
        assert_eq!(
            remote_to_local_status(Tool::GitLab, "opened", &config),
            "todo"
        );
        assert_eq!(
            remote_to_local_status(Tool::GitLab, "closed", &config),
            "done"
        );
        assert_eq!(
            remote_to_local_status(Tool::GitLab, "anything-else", &config),
            "todo"
        );
    }

    #[test]
    fn linear_status_mapping() {
        let config = Config::default();
        assert_eq!(
            local_to_remote_status(Tool::Linear, "todo", &config),
            "todo"
        );
        assert_eq!(
            local_to_remote_status(Tool::Linear, "in review", &config),
            "todo"
        );
        assert_eq!(
            local_to_remote_status(Tool::Linear, "done", &config),
            "Done"
        );
        assert_eq!(
            remote_to_local_status(Tool::Linear, "In Progress", &config),
            "in progress"
        );
        assert_eq!(
            remote_to_local_status(Tool::Linear, "Done", &config),
            "done"
        );
        assert_eq!(
            remote_to_local_status(Tool::Linear, "Unknown", &config),
            "todo"
        );
    }

    #[test]
    fn days_from_civil_roundtrips_civil_from_days() {
        // spot-check independent epoch anchors (known values)
        assert_eq!(days_from_civil(1970, 1, 1), 0);
        assert_eq!(days_from_civil(2000, 1, 1), 10957);
        assert_eq!(days_from_civil(1970, 1, 2), 1);
        assert_eq!(days_from_civil(2026, 5, 11), 20584);
    }

    #[test]
    fn date_to_epoch_days_parses_only_yyyymmdd() {
        assert_eq!(date_to_epoch_days("1970-01-01"), Some(0));
        assert_eq!(date_to_epoch_days("2026-05-11"), Some(20_584));
        assert_eq!(date_to_epoch_days("not-a-date"), None);
        assert_eq!(date_to_epoch_days("2026-13-01"), None);
        assert_eq!(date_to_epoch_days("2026-05-11T10:00:00"), None);
    }

    #[test]
    fn iso_to_epoch_secs_accepts_contract_timestamp_shapes() {
        let day = days_from_civil(2026, 5, 11) * 86_400;
        assert_eq!(iso_to_epoch_secs("2026-05-11T00:00:00Z"), Some(day));
        assert_eq!(iso_to_epoch_secs("2026-05-11 00:00:00"), Some(day));
        assert_eq!(iso_to_epoch_secs("2026-05-11T00:00:00.123Z"), Some(day));
        assert_eq!(
            iso_to_epoch_secs("2026-05-11T00:00:00+02:00"),
            Some(day - 7200)
        );
        assert_eq!(
            iso_to_epoch_secs("2026-05-11T00:00:00-05:30"),
            Some(day + 19_800)
        );
        assert_eq!(
            iso_to_epoch_secs("2026-05-11T10:30:00Z"),
            Some(day + 37_800)
        );
        assert_eq!(iso_to_epoch_secs("garbage"), None);
    }

    #[test]
    fn remote_newer_wins_only_when_strictly_after_local_end_of_day() {
        // local `updated` = 2026-05-11 is interpreted as end of day.
        assert!(is_remote_newer("2026-05-12T00:00:00Z", "2026-05-11"));
        assert!(!is_remote_newer("2026-05-11 13:00:00", "2026-05-11"));
        assert!(!is_remote_newer("2026-05-11T23:59:59Z", "2026-05-11"));
        assert!(!is_remote_newer("2026-05-10T23:59:59Z", "2026-05-11"));
        // unparseable remote timestamp keeps the local issue
        assert!(!is_remote_newer("not-a-time", "2026-05-11"));
    }

    #[test]
    fn scrub_replaces_secret_everywhere_and_preserves_text() {
        assert_eq!(
            scrub_secret("token=sekrit end", "sekrit"),
            "token=<token> end"
        );
        assert_eq!(
            scrub_secret("token=sekrit token=sekrit", "sekrit"),
            "token=<token> token=<token>"
        );
        assert_eq!(scrub_secret("no secret here", "sekrit"), "no secret here");
        assert_eq!(scrub_secret("empty secret", ""), "empty secret");
    }

    // ---- WP07 T029: the relationship mapping seam ----

    fn rel(kind: crate::relationships::RelationKind) -> crate::relationships::Relationship {
        let mut r = crate::relationships::Relationship::new(1, 2, kind, "Ship it");
        r.id = "rel_TEST".to_string();
        r
    }

    /// Every relationship either maps or diagnoses, and the diagnostic
    /// distinguishes the reasons (T029 step 5, re-pointed once Linear's
    /// `relations add` was verified).
    ///
    /// - `blocks`/`blocked_by` for **Linear** — expressible in the model and
    ///   drivable from the CLI, so they **map**, carrying the target's remote
    ///   identifier.
    /// - `blocks`/`blocked_by` for **GitLab** — expressible in the model but the
    ///   CLI is **verified to have no relation command at all** (tix #1354), so it
    ///   diagnoses and says *that*, never "not verified".
    /// - `related`/`duplicates` — no remote field at all.
    #[test]
    fn every_relationship_maps_only_where_the_wire_is_verified_and_otherwise_diagnoses() {
        for tool in [Tool::GitLab, Tool::Linear] {
            for kind in [
                crate::relationships::RelationKind::Blocks,
                crate::relationships::RelationKind::BlockedBy,
                crate::relationships::RelationKind::Related,
                crate::relationships::RelationKind::Duplicates,
            ] {
                let model_supports = matches!(
                    kind,
                    crate::relationships::RelationKind::Blocks
                        | crate::relationships::RelationKind::BlockedBy
                );
                match map_relation_to_remote(tool, &rel(kind), Some("ENG-42")) {
                    MappedRelation::Remote { field, value } => {
                        assert!(
                            model_supports && RELATION_WIRE_VERIFIED.contains(&tool),
                            "{tool}/{kind} mapped, so the tool must model the kind and \
                             be on the verified wire"
                        );
                        assert_ne!(field, "");
                        if tool == Tool::Linear {
                            assert_eq!(
                                value, "ENG-42",
                                "Linear sends the target's remote identifier"
                            );
                        } else {
                            assert!(value.contains('#'));
                        }
                    }
                    MappedRelation::Unsupported(d) => {
                        assert!(
                            !RELATION_WIRE_VERIFIED.contains(&tool) || !model_supports,
                            "{tool}/{kind} is on the verified wire and modelled, so it \
                             must map, not diagnose"
                        );
                        assert_eq!(d.tool, tool, "the diagnostic names the tool");
                        assert_eq!(d.relation_id, "rel_TEST");
                        assert!(
                            !d.field.is_empty(),
                            "the diagnostic must name the specific field: {d}"
                        );
                        assert!(d.to_string().contains(&d.field), "and print it: {d}");
                        if model_supports {
                            assert!(
                                RELATION_CLI_ABSENT.contains(&tool)
                                    && d.message.contains("exposes no issue-relation command")
                                    && !d.message.contains("not verified"),
                                "{tool}/{kind}: a model-supported kind on an unverified \
                                 tool must name the real reason; a CLI verified to have \
                                 no relation command must say so, not 'not verified': {d}"
                            );
                        } else {
                            assert!(
                                !d.message.contains("not verified"),
                                "{tool}/{kind}: a kind with no remote field must not \
                                 blame an unverified verb: {d}"
                            );
                        }
                    }
                }
            }
        }
    }

    /// A blocking edge whose target has no remote reference is **reported, never
    /// guessed** (C-005): Linear's `relations add` needs the target's remote
    /// identifier, and inventing one would be worse than a diagnostic.
    #[test]
    fn a_relation_without_a_remote_target_is_reported_not_guessed() {
        let MappedRelation::Unsupported(d) = map_relation_to_remote(
            Tool::Linear,
            &rel(crate::relationships::RelationKind::Blocks),
            None,
        ) else {
            panic!("a missing target must not map");
        };
        assert_eq!(d.tool, Tool::Linear);
        assert_eq!(d.field, "blocks");
        assert!(
            d.message.contains("#2") && d.message.contains("not been exported"),
            "the diagnostic names the target and why: {d}"
        );
    }

    /// The forward and reverse directions agree about the verified list.
    ///
    /// The reverse direction must **not** invent an edge from a payload the forward
    /// direction would never have written — otherwise an import could create a
    /// relationship the export never made, which is the mirror image of the silent
    /// drop the contract forbids. So it maps exactly when the wire is verified.
    #[test]
    fn the_reverse_direction_maps_exactly_when_the_wire_is_verified() {
        for tool in [Tool::GitLab, Tool::Linear] {
            let field = match tool {
                Tool::GitLab => "blocking",
                Tool::Linear => "blocks",
            };
            match map_relation_from_remote(tool, field, "blocks #2", "rel_TEST") {
                MappedRelation::Remote { .. } => assert!(
                    RELATION_WIRE_VERIFIED.contains(&tool),
                    "{tool}: the reverse direction mapped, so the wire must be verified"
                ),
                MappedRelation::Unsupported(d) => {
                    assert!(
                        !RELATION_WIRE_VERIFIED.contains(&tool),
                        "{tool}: the wire is verified, so the reverse direction must map"
                    );
                    assert_eq!(d.tool, tool);
                    assert_ne!(d.relation_id, "");
                }
            }
        }
    }

    /// A remote payload the export could not have written is **ignored with a
    /// diagnostic**, never turned into a local edge.
    ///
    /// The alternative — coercing an unrecognised field to a default kind — would
    /// let an import invent a relationship the export never made, which is the
    /// mirror image of silently dropping a local one.
    #[test]
    fn an_unrecognised_remote_relation_field_never_becomes_a_local_edge() {
        for tool in [Tool::GitLab, Tool::Linear] {
            for (field, value) in [
                ("parent", "#2"),
                ("blocks", "not-a-number"),
                ("whatever", ""),
            ] {
                match map_relation_from_remote(tool, field, value, "rel_X") {
                    MappedRelation::Remote { .. } => {
                        panic!("{tool}: `{field}={value}` must not become a local edge")
                    }
                    MappedRelation::Unsupported(d) => {
                        assert_eq!(d.tool, tool);
                        assert_eq!(d.field, field, "the diagnostic names the field");
                    }
                }
            }
        }
    }

    /// The two adapters cannot drift: the seam is one function, keyed on `Tool`
    /// (T033 step 5, and T029's note).
    ///
    /// Asserted by construction — a single `map_relation_to_remote` serves both —
    /// and pinned here so adding a tracker-specific branch to one of them is a
    /// red test rather than a silent divergence.
    #[test]
    fn both_trackers_share_one_mapping_seam() {
        let source = include_str!("mod.rs");
        let fns = [
            "pub fn map_relation_to_remote",
            "pub fn map_relation_from_remote",
        ];
        for f in fns {
            assert_eq!(
                source.matches(&format!("{f}(")).count(),
                1,
                "{f} must be *defined* exactly once, in this module, for both \
                 trackers — a doc comment naming it is not a second implementation"
            );
        }
        // And neither adapter file may define its own copy. `include_str!` needs a
        // literal, so the pair is spelled out rather than looped over.
        for (name, text) in [
            ("glab.rs", include_str!("glab.rs")),
            ("linear.rs", include_str!("linear.rs")),
        ] {
            assert!(
                !text.contains("fn map_relation_to_remote")
                    && !text.contains("fn map_relation_from_remote"),
                "{name} must not define its own mapping seam; the shared one is \\
                 keyed on `Tool` precisely so the two cannot diverge"
            );
        }
    }

    /// A `SyncReport` records the count and the diagnostics together, so a caller
    /// cannot report success while quietly dropping a relationship.
    #[test]
    fn a_sync_report_carries_both_the_count_and_the_diagnostics() {
        let mut report = SyncReport::default();
        let mut sink: Vec<u8> = Vec::new();
        report
            .note(
                map_relation_to_remote(
                    Tool::GitLab,
                    &rel(crate::relationships::RelationKind::Related),
                    None,
                ),
                &mut sink,
            )
            .unwrap();
        report
            .note(
                map_relation_to_remote(
                    Tool::GitLab,
                    &rel(crate::relationships::RelationKind::Blocks),
                    None,
                ),
                &mut sink,
            )
            .unwrap();
        // Both are diagnostics: GitLab is not wire-verified, so the mapped
        // branch is unreachable and the count cannot be 1.
        let expected = if RELATION_WIRE_VERIFIED.contains(&Tool::GitLab) {
            1
        } else {
            2
        };
        assert_eq!(
            report.diagnostics.len(),
            expected,
            "the report records every relation the tool cannot carry"
        );
        assert_eq!(report.handled, 0, "no issues were handled here");
        // It is on the human stream too, so the count and the output agree.
        let text = String::from_utf8(sink).unwrap();
        assert!(
            text.contains("cannot represent"),
            "the stream says so: {text}"
        );
    }
    // ---- WP07 T032/T033: completion comes from the service, nowhere else ----

    /// A board whose `category_map` puts `completed` on `shipped` while
    /// `done_column` is `done` — so the two disagree, and a name comparison picks the
    /// wrong one. Every assertion below is vacuous on the default board, which is why
    /// this fixture exists rather than `Config::default()`.
    fn split_completion_config() -> Config {
        Config {
            kanban: crate::config::KanbanSection {
                configurations: indexmap::IndexMap::from([(
                    "default".to_string(),
                    crate::config::BoardConfiguration {
                        columns: vec!["todo".into(), "shipped".into(), "done".into()],
                        done_column: Some("done".to_string()),
                        category_map: indexmap::IndexMap::from([
                            ("todo".to_string(), "unstarted".to_string()),
                            ("shipped".to_string(), "completed".to_string()),
                            ("done".to_string(), "active".to_string()),
                        ]),
                        ..Default::default()
                    },
                )]),
            },
            ..Config::default()
        }
    }

    #[test]
    fn t032_a_remote_closed_state_maps_to_the_services_completion_column() {
        // Not to `done_column`. The remote's `closed` must round-trip to the column
        // the *service* calls complete, or export and import disagree with each other
        // and with the board.
        let config = split_completion_config();
        assert_eq!(
            remote_to_local_status(Tool::GitLab, "closed", &config),
            "shipped",
            "a closed GitLab issue belongs in the column that is actually complete"
        );
        assert_eq!(
            remote_to_local_status(Tool::Linear, "Done", &config),
            "shipped"
        );
    }

    #[test]
    fn t032_export_closes_the_column_the_service_calls_complete() {
        // The other direction. A name comparison exported `shipped` as *open* and
        // closed `done` instead — the tracker and the board disagreeing about the same
        // issue in both directions at once.
        let config = split_completion_config();
        assert_eq!(
            local_to_remote_status(Tool::GitLab, "shipped", &config),
            "closed"
        );
        assert_eq!(
            local_to_remote_status(Tool::GitLab, "done", &config),
            "opened"
        );
        assert_eq!(
            local_to_remote_status(Tool::Linear, "shipped", &config),
            "Done"
        );
    }

    #[test]
    fn t032_a_closed_remote_state_mapped_to_a_canceled_column_is_not_complete() {
        // T033 step 4. `canceled` is terminal but **not** complete (contract §4), so
        // an export that sends a `canceled` column as closed would be claiming the
        // work is finished when it was abandoned. The local side is the service's
        // answer, so it says no.
        let mut config = split_completion_config();
        config
            .kanban
            .configurations
            .get_mut("default")
            .unwrap()
            .category_map
            .insert("done".to_string(), "canceled".to_string());
        let board = config.default_config();
        // `shipped` is still `completed`, so it still exports as closed…
        assert_eq!(
            local_to_remote_status(Tool::GitLab, "shipped", &config),
            "closed"
        );
        // …and `done` is now `canceled`, which is terminal and not complete, so it does
        // not. The remote has only two states, so the honest outcome is that `canceled`
        // cannot be represented distinctly — and the local definition is what decides,
        // not the remote's vocabulary.
        assert!(
            !is_done_column(board, "done", &config),
            "a canceled column is not locally complete"
        );
    }

    #[test]
    fn t032_the_existing_round_trips_are_unchanged() {
        // T032 step 5: this is a refactor of *where the decision comes from*, not a
        // protocol change. The default board's behaviour must be identical.
        let config = Config::default();
        assert_eq!(
            local_to_remote_status(Tool::GitLab, "done", &config),
            "closed"
        );
        assert_eq!(
            local_to_remote_status(Tool::GitLab, "todo", &config),
            "opened"
        );
        assert_eq!(
            remote_to_local_status(Tool::GitLab, "closed", &config),
            "done"
        );
        assert_eq!(
            remote_to_local_status(Tool::Linear, "Done", &config),
            "done"
        );
        // "In Progress" case-insensitively matches the board's `in progress` column,
        // and a name match wins over the first column. The first draft of this
        // assertion expected `todo` — which is the *first* column, and therefore the
        // answer when no name matches. It was asserting the opposite rule to the one
        // it claimed to pin.
        assert_eq!(
            remote_to_local_status(Tool::Linear, "In Progress", &config),
            "in progress",
            "a name match wins over the first column"
        );
        assert_eq!(
            remote_to_local_status(Tool::Linear, "No Such State", &config),
            "todo",
            "and with no match at all, the first column"
        );
    }

    #[test]
    fn t032_the_sync_seam_holds_no_local_completion_definition() {
        // T032 step 4, as a structural guard. The module header says a second local
        // definition is a C-004 defect, and this is what keeps that from being
        // "improved" back in: the seam may only *translate* a remote state word, and
        // the completion test may only come from the service.
        let source = include_str!("mod.rs");
        // Assembled from fragments so this assertion does not match **itself**: the
        // first version spelled the forbidden name out in full, so the very line
        // asserting its absence satisfied the check. That is the grep equivalent of a
        // test that proves itself, and it was found because the test went red while
        // the function was, in fact, absent.
        let forbidden = ["fn remote", "status_is_done"].concat();
        assert!(
            !source.contains(&forbidden),
            "the dead second definition is removed and must not come back"
        );
        // The only local completion question in the module is the service call.
        let uses_service = source.matches("WorkflowCategory::is_complete").count();
        assert!(
            uses_service >= 2,
            "both `is_done_column` and `completion_column` must ask the service, found \
             {uses_service} uses"
        );
    }

    // ------------------------------------------------------------------
    // WP08 (mission first-class-projects-01M3BYBW) — project associations
    // ------------------------------------------------------------------

    /// A representable association maps, and the reverse direction is
    /// **local**-shaped: the frontmatter key and the id, not a copy of the tool's
    /// field name (T035 step 1).
    #[test]
    fn t035_a_project_association_maps_back_to_its_local_id() {
        for tool in [Tool::GitLab, Tool::Linear] {
            let remote = RemoteProject {
                id: "p-1".to_string(),
                name: Some("One".to_string()),
            };
            match map_project_from_remote(tool, &remote) {
                MappedProject::Remote { field, value } => {
                    assert_eq!(field, crate::projects::PROJECTS_KEY);
                    assert_eq!(value, "p-1", "the id, never the remote's name");
                }
                MappedProject::Unsupported(d) => {
                    panic!("{tool}: a reported id must map back: {d}")
                }
            }
        }
    }

    /// Every association diagnoses on both trackers, and the diagnostic names the
    /// **field**, the **tool** and the issue — the three things that make it
    /// actionable rather than a shrug (T035 step 6, C-005).
    ///
    /// Written so it still holds if a tracker joins `PROJECT_WIRE_VERIFIED`: the
    /// mapped branch is then the assertion, not the diagnostic's.
    #[test]
    fn t035_every_project_association_diagnoses_with_its_field_its_tool_and_its_reason() {
        for tool in [Tool::GitLab, Tool::Linear] {
            match map_project_to_remote(tool, 3, "p-7") {
                MappedProject::Remote { field, value } => {
                    assert!(
                        PROJECT_WIRE_VERIFIED.contains(&tool),
                        "{tool}: an association mapped without a verified membership field"
                    );
                    assert_eq!(field, project_field(tool));
                    assert_eq!(value, "p-7");
                }
                MappedProject::Unsupported(d) => {
                    assert_eq!(d.tool, tool, "the diagnostic names the tool");
                    assert_eq!(d.field, project_field(tool), "and the field");
                    assert_eq!(
                        d.relation_id, "3->p-7",
                        "and the issue and the association it is about"
                    );
                    let text = d.to_string();
                    for needle in [d.field.as_str(), "p-7", "#3"] {
                        assert!(text.contains(needle), "`{needle}` missing from: {text}");
                    }
                    // Neither CLI has a membership verb to wait for, so the message
                    // must not promise one — the same distinction
                    // `RELATION_CLI_ABSENT` draws.
                    assert!(
                        !d.message.contains("not verified"),
                        "{tool}: there is no membership verb to verify: {text}"
                    );
                }
            }
        }
        // The reasons are per tool because the two CLIs differ, and they say which.
        assert!(project_absence_reason(Tool::GitLab).contains("--project"));
        assert!(project_absence_reason(Tool::Linear).contains("one `project`"));
        assert_ne!(
            project_absence_reason(Tool::GitLab),
            project_absence_reason(Tool::Linear)
        );
    }

    /// An association with no id is a repair job, not a remote capability gap, and
    /// the local entry is not quietly sent as somebody else's project.
    #[test]
    fn t035_an_association_with_no_id_is_diagnosed_and_kept() {
        for tool in [Tool::GitLab, Tool::Linear] {
            match map_project_to_remote(tool, 4, "   ") {
                MappedProject::Remote { .. } => panic!("{tool}: nothing to send"),
                MappedProject::Unsupported(d) => {
                    assert_eq!(d.tool, tool);
                    assert_eq!(d.field, project_field(tool));
                    assert!(d.message.contains("no id"), "{}", d.message);
                    assert!(
                        d.message.contains("kept locally"),
                        "and says the entry survives: {}",
                        d.message
                    );
                }
            }
        }
    }

    /// A payload's references are read **in order**, in every shape the two trackers
    /// are known to use, and an entry that cannot yield an id is still reported by
    /// name instead of being dropped (T035 step 1, NFR-002 for the order).
    #[test]
    fn t035_remote_project_reading_keeps_order_and_accepts_every_known_shape() {
        let list: serde_json::Value =
            serde_json::from_str(r#"["p-1", {"id": "p-2", "name": "Two"}, 3]"#).unwrap();
        assert_eq!(
            remote_projects(Some(&list)),
            vec![
                RemoteProject {
                    id: "p-1".into(),
                    name: None
                },
                RemoteProject {
                    id: "p-2".into(),
                    name: Some("Two".into())
                },
                RemoteProject {
                    id: "3".into(),
                    name: None
                },
            ],
            "the payload's order is the list's order"
        );
        // Linear's single `project`, under any of the id spellings.
        for raw in [
            r#"{"identifier": "p-9"}"#,
            r#"{"project_id": "p-9"}"#,
            r#""p-9""#,
        ] {
            let value: serde_json::Value = serde_json::from_str(raw).unwrap();
            assert_eq!(
                remote_projects(Some(&value)),
                vec![RemoteProject {
                    id: "p-9".into(),
                    name: None
                }],
                "{raw}"
            );
        }
        // A named entry with no id survives, so the import can report it.
        let named: serde_json::Value =
            serde_json::from_str(r#"[{"name": "Unidentified"}]"#).unwrap();
        assert_eq!(
            remote_projects(Some(&named)),
            vec![RemoteProject {
                id: String::new(),
                name: Some("Unidentified".into())
            }]
        );
        // Absent, null, and shapes carrying nothing at all yield no references.
        assert_eq!(remote_projects(None), [] as [crate::sync::RemoteProject; 0]);
        assert_eq!(
            remote_projects(Some(&serde_json::Value::Null)),
            [] as [crate::sync::RemoteProject; 0]
        );
        assert_eq!(
            remote_projects(Some(&serde_json::json!([true, false]))),
            [] as [crate::sync::RemoteProject; 0]
        );
    }

    /// An entry the remote named but did not identify cannot be matched on, and the
    /// diagnostic quotes the name so a reader can see which project it meant.
    #[test]
    fn t035_a_remote_project_with_no_id_is_diagnosed_never_guessed_at() {
        for tool in [Tool::GitLab, Tool::Linear] {
            let remote = RemoteProject {
                id: "  ".to_string(),
                name: Some("Named but unidentified".to_string()),
            };
            match map_project_from_remote(tool, &remote) {
                MappedProject::Remote { .. } => {
                    panic!("{tool}: an absent id cannot become a local association")
                }
                MappedProject::Unsupported(d) => {
                    assert_eq!(d.tool, tool);
                    assert_eq!(d.field, project_field(tool));
                    assert!(d.message.contains("Named but unidentified"));
                    assert!(d.message.contains("no id"));
                }
            }
        }
    }

    /// A diagnostic built from **remote output** is scrubbed before it is reported
    /// (T036 step 6). The project name is the remote text this seam quotes, which is
    /// exactly how a credential could reach a report.
    #[test]
    fn t036_a_project_diagnostic_built_from_remote_output_is_scrubbed() {
        let mut diagnostic = RemoteMappingDiagnostic {
            relation_id: "1->lin-secret".to_string(),
            field: LINEAR_PROJECT_FIELD.to_string(),
            tool: Tool::Linear,
            message: "the remote reports #1 in project `p-1` (`lin-secret`)".to_string(),
        };
        scrub_diagnostic(&mut diagnostic, Some("lin-secret"));
        assert!(
            diagnostic.message.contains("<token>"),
            "{}",
            diagnostic.message
        );
        assert!(!diagnostic.message.contains("lin-secret"));
        assert!(!diagnostic.relation_id.contains("lin-secret"));

        // With no secret configured there is nothing to redact, and the diagnostic is
        // reported unchanged rather than withheld.
        let mut untouched = RemoteMappingDiagnostic {
            relation_id: "1->p-1".to_string(),
            field: LINEAR_PROJECT_FIELD.to_string(),
            tool: Tool::Linear,
            message: "no secret here".to_string(),
        };
        let expected = untouched.clone();
        scrub_diagnostic(&mut untouched, None);
        assert_eq!(untouched, expected);
    }

    /// Neither tracker sends a membership, both adapters implement the same seam,
    /// and the seam itself is defined once (T036 steps 3 and 5, T038 step 6).
    ///
    /// Structural assertions on purpose: the compiler already requires `set_projects`
    /// on both adapters (it is a required trait method), and these keep a
    /// tracker-specific mapping from being added to one adapter file later.
    #[test]
    fn t036_no_tracker_sends_a_membership_and_both_adapters_share_the_seam() {
        for tool in [Tool::GitLab, Tool::Linear] {
            assert!(!PROJECT_WIRE_VERIFIED.contains(&tool));
            assert!(matches!(
                map_project_to_remote(tool, 1, "p-1"),
                MappedProject::Unsupported(_)
            ));
        }
        let source = include_str!("mod.rs");
        for f in [
            "pub fn map_project_to_remote",
            "pub fn map_project_from_remote",
        ] {
            assert_eq!(
                source.matches(&format!("{f}(")).count(),
                1,
                "{f} must be *defined* exactly once, in this module, for both trackers"
            );
        }
        for (name, text) in [
            ("glab.rs", include_str!("glab.rs")),
            ("linear.rs", include_str!("linear.rs")),
        ] {
            assert!(
                !text.contains("fn map_project_to_remote")
                    && !text.contains("fn map_project_from_remote"),
                "{name} must not define its own mapping seam"
            );
            assert!(
                text.contains("fn set_projects"),
                "{name} must implement the shared membership seam"
            );
        }
    }

    /// The report carries a project diagnostic with the count, on the stream and in
    /// the returned value, so a caller cannot report success while dropping one.
    #[test]
    fn t037_a_report_records_a_project_diagnostic_and_prints_the_field() {
        let mut report = SyncReport::default();
        let mut sink: Vec<u8> = Vec::new();
        report
            .note_project(map_project_to_remote(Tool::GitLab, 2, "p-1"), &mut sink)
            .unwrap();
        assert_eq!(report.diagnostics.len(), 1);
        assert_eq!(report.handled, 0);
        let text = String::from_utf8(sink).unwrap();
        assert!(text.contains("gitlab: projects"), "{text}");
        assert!(text.contains("p-1"), "{text}");
        assert_eq!(report.diagnostics[0].field, GITLAB_PROJECT_FIELD);
    }

    // ---- WP08 T037–T040: the epic-reference mapping seam ----------------

    /// A reported epic id maps back to the local reference key and id, on both
    /// trackers (T037 step 1, C-003).
    #[test]
    fn t037_an_epic_reference_maps_back_to_its_local_id() {
        for tool in [Tool::GitLab, Tool::Linear] {
            let remote = RemoteEpic {
                id: "e-1".to_string(),
                name: Some("One".to_string()),
            };
            match map_epic_from_remote(tool, &remote) {
                MappedEpic::Remote { field, value } => {
                    assert_eq!(field, crate::epics::EPICS_KEY);
                    assert_eq!(value, "e-1", "the id, never the remote's name");
                }
                MappedEpic::Unsupported(d) => {
                    panic!("{tool}: a reported id must map back: {d}")
                }
            }
        }
    }

    /// Every epic reference diagnoses on both trackers, and the diagnostic names the
    /// **field**, the **tool** and the issue — the three things that make it
    /// actionable rather than a shrug (T037 step 6, C-007).
    ///
    /// Written so it still holds if a tracker joins `EPIC_WIRE_VERIFIED`: the mapped
    /// branch is then the assertion, not the diagnostic's.
    #[test]
    fn t037_every_epic_reference_diagnoses_with_its_field_its_tool_and_its_reason() {
        for tool in [Tool::GitLab, Tool::Linear] {
            match map_epic_to_remote(tool, 3, "e-7") {
                MappedEpic::Remote { field, value } => {
                    assert!(
                        EPIC_WIRE_VERIFIED.contains(&tool),
                        "{tool}: a reference mapped without a verified epic field"
                    );
                    assert_eq!(field, EPIC_FIELD);
                    assert_eq!(value, "e-7");
                }
                MappedEpic::Unsupported(d) => {
                    assert_eq!(d.tool, tool, "the diagnostic names the tool");
                    assert_eq!(d.field, EPIC_FIELD, "and the field");
                    assert_eq!(
                        d.relation_id, "3->e-7",
                        "and the issue and the reference it is about"
                    );
                    let text = d.to_string();
                    for needle in [d.field.as_str(), "e-7", "#3"] {
                        assert!(text.contains(needle), "`{needle}` missing from: {text}");
                    }
                    // Neither CLI has an epic verb to wait for, so the message must
                    // not promise one.
                    assert!(
                        !d.message.contains("not verified"),
                        "{tool}: there is no epic verb to verify: {text}"
                    );
                }
            }
        }
        // The reasons are per tool because the two CLIs differ, and they say which.
        assert!(epic_absence_reason(Tool::GitLab).contains("epic_iid"));
        assert!(epic_absence_reason(Tool::Linear).contains("project"));
        assert_ne!(
            epic_absence_reason(Tool::GitLab),
            epic_absence_reason(Tool::Linear)
        );
    }

    /// A reference with no id is a repair job, not a remote capability gap, and the
    /// local entry is not quietly sent as somebody else's epic.
    #[test]
    fn t037_an_epic_reference_with_no_id_is_diagnosed_and_kept() {
        for tool in [Tool::GitLab, Tool::Linear] {
            match map_epic_to_remote(tool, 4, "   ") {
                MappedEpic::Remote { .. } => panic!("{tool}: nothing to send"),
                MappedEpic::Unsupported(d) => {
                    assert_eq!(d.tool, tool);
                    assert_eq!(d.field, EPIC_FIELD);
                    assert!(d.message.contains("no id"), "{}", d.message);
                    assert!(
                        d.message.contains("kept locally"),
                        "and says the entry survives: {}",
                        d.message
                    );
                }
            }
        }
    }

    /// A payload's references are read **in order**, in every shape the two trackers
    /// are known to use, and an entry that cannot yield an id is still reported by
    /// name instead of being dropped (T037 step 1, NFR-002 for the order).
    #[test]
    fn t037_remote_epic_reading_keeps_order_and_accepts_every_known_shape() {
        let list: serde_json::Value =
            serde_json::from_str(r#"["e-1", {"id": "e-2", "name": "Two"}, 3]"#).unwrap();
        assert_eq!(
            remote_epics(Some(&list)),
            vec![
                RemoteEpic {
                    id: "e-1".into(),
                    name: None
                },
                RemoteEpic {
                    id: "e-2".into(),
                    name: Some("Two".into())
                },
                RemoteEpic {
                    id: "3".into(),
                    name: None
                },
            ],
            "the payload's order is the list's order"
        );
        // A single reference, under any of the id spellings.
        for raw in [
            r#"{"identifier": "e-9"}"#,
            r#"{"epic_id": "e-9"}"#,
            r#""e-9""#,
        ] {
            let value: serde_json::Value = serde_json::from_str(raw).unwrap();
            assert_eq!(
                remote_epics(Some(&value)),
                vec![RemoteEpic {
                    id: "e-9".into(),
                    name: None
                }],
                "{raw}"
            );
        }
        // A named entry with no id survives, so the import can report it.
        let named: serde_json::Value =
            serde_json::from_str(r#"[{"name": "Unidentified"}]"#).unwrap();
        assert_eq!(
            remote_epics(Some(&named)),
            vec![RemoteEpic {
                id: String::new(),
                name: Some("Unidentified".into())
            }]
        );
        // Absent, null, and shapes carrying nothing at all yield no references.
        assert_eq!(remote_epics(None), [] as [crate::sync::RemoteEpic; 0]);
        assert_eq!(
            remote_epics(Some(&serde_json::Value::Null)),
            [] as [crate::sync::RemoteEpic; 0]
        );
        assert_eq!(
            remote_epics(Some(&serde_json::json!([true, false]))),
            [] as [crate::sync::RemoteEpic; 0]
        );
    }

    /// An entry the remote named but did not identify cannot be matched on, and the
    /// diagnostic quotes the name so a reader can see which epic it meant.
    #[test]
    fn t037_a_remote_epic_with_no_id_is_diagnosed_never_guessed_at() {
        for tool in [Tool::GitLab, Tool::Linear] {
            let remote = RemoteEpic {
                id: "  ".to_string(),
                name: Some("Named but unidentified".to_string()),
            };
            match map_epic_from_remote(tool, &remote) {
                MappedEpic::Remote { .. } => {
                    panic!("{tool}: an absent id cannot become a local reference")
                }
                MappedEpic::Unsupported(d) => {
                    assert_eq!(d.tool, tool);
                    assert_eq!(d.field, EPIC_FIELD);
                    assert!(d.message.contains("Named but unidentified"));
                    assert!(d.message.contains("no id"));
                }
            }
        }
    }

    /// A diagnostic built from **remote output** is scrubbed before it is reported
    /// (T038 step 6). The epic name is the remote text this seam quotes, which is
    /// exactly how a credential could reach a report.
    #[test]
    fn t038_a_remote_epic_diagnostic_is_scrubbed() {
        let mut diagnostic = RemoteMappingDiagnostic {
            relation_id: "1->lin-secret".to_string(),
            field: EPIC_FIELD.to_string(),
            tool: Tool::Linear,
            message: "the remote reports #1 in epic `e-1` (`lin-secret`)".to_string(),
        };
        scrub_diagnostic(&mut diagnostic, Some("lin-secret"));
        assert!(
            diagnostic.message.contains("<token>"),
            "{}",
            diagnostic.message
        );
        assert!(!diagnostic.message.contains("lin-secret"));
        assert!(!diagnostic.relation_id.contains("lin-secret"));
    }

    /// Neither tracker sends an epic reference, both adapters implement the same
    /// seam, and the seam itself is defined once (T038 step 6).
    ///
    /// Structural assertions on purpose: the compiler already requires `set_epics` on
    /// both adapters (it is a required trait method), and these keep a
    /// tracker-specific mapping from being added to one adapter file later.
    #[test]
    fn t038_no_tracker_sends_an_epic_reference_and_both_adapters_share_the_seam() {
        for tool in [Tool::GitLab, Tool::Linear] {
            assert!(!EPIC_WIRE_VERIFIED.contains(&tool));
            assert!(matches!(
                map_epic_to_remote(tool, 1, "e-1"),
                MappedEpic::Unsupported(_)
            ));
        }
        let source = include_str!("mod.rs");
        for f in ["pub fn map_epic_to_remote", "pub fn map_epic_from_remote"] {
            assert_eq!(
                source.matches(&format!("{f}(")).count(),
                1,
                "{f} must be *defined* exactly once, in this module, for both trackers"
            );
        }
        for (name, text) in [
            ("glab.rs", include_str!("glab.rs")),
            ("linear.rs", include_str!("linear.rs")),
        ] {
            assert!(
                !text.contains("fn map_epic_to_remote")
                    && !text.contains("fn map_epic_from_remote"),
                "{name} must not define its own mapping seam"
            );
            assert!(
                text.contains("fn set_epics"),
                "{name} must implement the shared epic seam"
            );
        }
    }

    /// The report carries an epic diagnostic with the count, on the stream and in the
    /// returned value, so a caller cannot report success while dropping one.
    #[test]
    fn t038_a_report_records_an_epic_diagnostic_and_prints_the_field() {
        let mut report = SyncReport::default();
        let mut sink: Vec<u8> = Vec::new();
        report
            .note_epic(map_epic_to_remote(Tool::GitLab, 2, "e-1"), &mut sink)
            .unwrap();
        assert_eq!(report.diagnostics.len(), 1);
        assert_eq!(report.handled, 0);
        let text = String::from_utf8(sink).unwrap();
        assert!(text.contains("gitlab: epics"), "{text}");
        assert!(text.contains("e-1"), "{text}");
        assert_eq!(report.diagnostics[0].field, EPIC_FIELD);
    }
}