IdleRobotYieldService.cs 77.2 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Rcs.Application.Services;
using Rcs.Application.Services.PathFind;
using Rcs.Application.Services.PathFind.Models;
using Rcs.Application.Services.PathFind.Realtime;
using Rcs.Application.Services.Protocol;
using Rcs.Application.Shared;
using Rcs.Domain.Entities;
using Rcs.Domain.Enums;
using Rcs.Domain.Models.VDA5050;
using Rcs.Domain.Repositories;
using Rcs.Domain.Settings;
using Rcs.Domain.ValueObjects;
using Rcs.Infrastructure.PathFinding.Services;
using StackExchange.Redis;

namespace Rcs.Infrastructure.PathFinding.Realtime;

/// <summary>
/// 空闲机器人让行服务实现。
/// 当执行任务的机器人路径被空闲机器人阻挡时,主动请求空闲机器人移开。
/// @author zzy
/// </summary>
public class IdleRobotYieldService : IIdleRobotYieldService
{
    private const string YieldCooldownKeyPrefix = "rcs:yield:cooldown";
    private const string YieldKeyMarker = "yield";

    private readonly IRobotCacheService _robotCacheService;
    private readonly IAgvPathService _agvPathService;
    private readonly IUnifiedTrafficControlService _trafficControl;
    private readonly IVdaPathSegmentationService _vdaPathSegmentationService;
    private readonly IServiceProvider _serviceProvider;
    private readonly IRobotRepository _robotRepository;
    private readonly IConnectionMultiplexer _redis;
    private readonly IVdaOrderGateService _vdaOrderGateService;
    private readonly ILogger<IdleRobotYieldService> _logger;
    private readonly AppSettings _settings;

    public IdleRobotYieldService(
        IRobotCacheService robotCacheService,
        IAgvPathService agvPathService,
        IUnifiedTrafficControlService trafficControl,
        IVdaPathSegmentationService vdaPathSegmentationService,
        IServiceProvider serviceProvider,
        IRobotRepository robotRepository,
        IConnectionMultiplexer redis,
        IVdaOrderGateService vdaOrderGateService,
        ILogger<IdleRobotYieldService> logger,
        IOptions<AppSettings> settings)
    {
        _robotCacheService = robotCacheService;
        _agvPathService = agvPathService;
        _trafficControl = trafficControl;
        _vdaPathSegmentationService = vdaPathSegmentationService;
        _serviceProvider = serviceProvider;
        _robotRepository = robotRepository;
        _redis = redis;
        _vdaOrderGateService = vdaOrderGateService;
        _logger = logger;
        _settings = settings.Value;
    }

    /// <inheritdoc />
    public async Task<IdleYieldResult> ExecuteYieldAsync(
        IdleRobotYieldRequest request,
        Robot requestingRobot,
        VdaSegmentedPathCache requestingCache,
        CancellationToken ct = default)
    {
        try
        {
            // 1. 获取空闲机器人信息
            var robot = await _robotRepository.GetByIdAsync(request.IdleRobotId, ct) as Robot;
            if (robot == null || !robot.Active)
            {
                return new IdleYieldResult { Success = false, FailureReason = "Robot not found or inactive" };
            }

            var taskSnapshot = await GetIdleRobotTaskSnapshotAsync(robot.RobotId, ct);
            if (taskSnapshot.HasInProgressTaskOrSubTask)
            {
                _logger.LogInformation(
                    "[让行] 让行车存在执行中任务或子任务,拒绝按空闲车处理: IdleRobot={IdleRobotId}",
                    robot.RobotId);
                return new IdleYieldResult
                {
                    Success = false,
                    FailureReason = "Robot has in-progress task/subtask, not idle"
                };
            }

            // 2. 若已存在进行中的让行任务,优先续发当前让行,避免重复创建新让行订单。
            var (activeYieldCacheKey, activeYieldCache) = await GetLatestYieldCacheAsync(robot.RobotId, ct);
            if (activeYieldCache != null && !string.IsNullOrWhiteSpace(activeYieldCacheKey))
            {
                if (IsAllYieldSegmentsSent(activeYieldCache))
                {
                    if (await IsYieldCompletionConfirmedAsync(robot, activeYieldCache, ct))
                    {
                        await CleanupYieldLocksOnCompletionAsync(robot, activeYieldCache, ct);
                        await DeleteYieldCacheAsync(activeYieldCacheKey);
                        await _vdaOrderGateService.MarkSessionCompletedAsync(
                            robot.RobotId,
                            VdaOrderChannel.Yield,
                            activeYieldCache.YieldOrderId,
                            activeYieldCache.OrderUpdateId,
                            ct);
                    }
                    else
                    {
                        _logger.LogDebug(
                            "[让行] 让行缓存已全发送但状态未确认完成,继续保持让行优先: IdleRobot={IdleRobotId}, YieldOrderId={YieldOrderId}",
                            request.IdleRobotId,
                            activeYieldCache.YieldOrderId);
                        return new IdleYieldResult
                        {
                            Success = true,
                            OrderId = activeYieldCache.YieldOrderId,
                            TargetNodeCode = activeYieldCache.TargetNodeCode
                        };
                    }
                }
                else
                {
                    var continued = await TryContinueYieldDispatchAsync(
                        robot.RobotManufacturer,
                        robot.RobotSerialNumber,
                        ct);
                    if (continued)
                    {
                        _logger.LogInformation(
                            "[让行] 命中进行中让行任务,继续当前让行: IdleRobot={IdleRobotId}, YieldOrderId={YieldOrderId}",
                            request.IdleRobotId,
                            activeYieldCache.YieldOrderId);
                        return new IdleYieldResult
                        {
                            Success = true,
                            OrderId = activeYieldCache.YieldOrderId,
                            TargetNodeCode = activeYieldCache.TargetNodeCode
                        };
                    }

                    _logger.LogWarning(
                        "[让行] 检测到进行中让行任务但续发未完成,将回退到新建让行流程: IdleRobot={IdleRobotId}, YieldOrderId={YieldOrderId}",
                        request.IdleRobotId,
                        activeYieldCache.YieldOrderId);
                }
            }

            // 3. 检查冷却期(仅新建让行时生效)。
            if (await IsInYieldCooldownAsync(request.IdleRobotId))
            {
                return new IdleYieldResult { Success = false, FailureReason = "Robot in yield cooldown" };
            }

            // 4. 验证机器人确实空闲
            var status = await _robotCacheService.GetStatusAsync(robot.RobotManufacturer, robot.RobotSerialNumber);
            if (status?.Status != RobotStatus.Idle)
            {
                return new IdleYieldResult { Success = false, FailureReason = $"Robot not idle, current status: {status?.Status}" };
            }

            var location = await _robotCacheService.GetLocationAsync(robot.RobotManufacturer, robot.RobotSerialNumber);
            var currentNodeCode = await RobotNavigationNodeResolver.ResolveAsync(
                _agvPathService,
                request.MapId,
                location,
                fallbackLastNodeCode: status?.LastNode,
                ct: ct);
            if (string.IsNullOrWhiteSpace(currentNodeCode))
            {
                return new IdleYieldResult { Success = false, FailureReason = "Unable to resolve idle robot current node" };
            }

            var currentTheta = location?.Theta ?? robot.CurrentTheta ?? 0d;
            var graph = await _agvPathService.GetOrBuildGraphAsync(request.MapId);
            if (graph == null)
            {
                return new IdleYieldResult { Success = false, FailureReason = "Graph not available" };
            }

            var skipYieldResult = await TrySkipYieldWhenSubTaskCanProceedAsync(
                request,
                requestingRobot,
                robot,
                taskSnapshot,
                graph,
                currentNodeCode,
                currentTheta,
                ct);
            if (skipYieldResult != null)
            {
                return skipYieldResult;
            }

            var remainingTaskLockCandidates = NextSegmentLockScopeBuilder.BuildRemainingTaskLockCandidates(
                requestingCache,
                graph,
                requestingRobot);
            if (remainingTaskLockCandidates.Count == 0)
            {
                return new IdleYieldResult { Success = false, FailureReason = "Remaining task lock scope unavailable" };
            }

            // 5. 查找让行目标节点
            var targetNodeCode = request.TargetNodeCode
                ?? await FindNearestYieldTargetAsync(
                    request.MapId,
                    request.MapCode,
                    robot,
                    request.BlockingNodeCode,
                    currentNodeCode,
                    currentTheta,
                    request.IdleRobotId,
                    requestingRobot,
                    requestingCache,
                    ct);
            if (string.IsNullOrWhiteSpace(targetNodeCode))
            {
                return new IdleYieldResult { Success = false, FailureReason = "No available yield target node" };
            }

            var targetNode = graph.Nodes.Values.FirstOrDefault(node =>
                string.Equals(node.NodeCode, targetNodeCode, StringComparison.OrdinalIgnoreCase));
            var forbiddenTargetResource = targetNode == null
                ? null
                : GetYieldForbiddenResource(graph, targetNode.NodeId);
            if (forbiddenTargetResource != null)
            {
                _logger.LogDebug(
                    "[让行] 让行目标位于不允许避让资源区域,跳过: IdleRobot={IdleRobotId}, Target={TargetNodeCode}, Resource={ResourceCode}",
                    robot.RobotId,
                    targetNodeCode,
                    forbiddenTargetResource.ResourceCode);
                return new IdleYieldResult { Success = false, FailureReason = "Yield target node is in forbidden yield resource" };
            }

            // 6. 规划让行路径
            var pathSegments = await PlanYieldPathAsync(
                robot,
                request.MapId,
                graph,
                currentNodeCode,
                currentTheta,
                targetNodeCode,
                ct);
            if (pathSegments.Count == 0)
            {
                return new IdleYieldResult { Success = false, FailureReason = "No path to target node" };
            }

            // 7. 按主流程规则切割让行路径并先保存缓存
            var orderId = $"YIELD-{Guid.NewGuid():N}";
            var segmentedPath = _vdaPathSegmentationService.SplitSegmentsByBoundary(
                pathSegments,
                graph,
                robot,
                hasTerminalAction: false);
            if (segmentedPath.Count == 0)
            {
                return new IdleYieldResult { Success = false, FailureReason = "Yield path segmentation failed" };
            }

            var cache = BuildYieldSegmentedPathCache(
                robot,
                request.MapId,
                request.MapCode,
                targetNodeCode,
                orderId,
                segmentedPath);
            var cacheKey = BuildYieldCacheKey(robot.RobotId, orderId);
            if (!await SaveYieldCacheAsync(cacheKey, cache, ct))
            {
                return new IdleYieldResult { Success = false, FailureReason = "Yield cache save failed" };
            }

            // 8. 仅下发首段
            if (!TryLocateCurrentYieldResourceSegment(cache, out var currentJunctionIndex, out var currentResourceIndex, out var currentSegment))
            {
                return new IdleYieldResult { Success = false, FailureReason = "Yield segmented cache has no dispatchable segment" };
            }

            var mqttClientService = _serviceProvider.GetRequiredService<IMqttClientService>();
            var gateResult = await _vdaOrderGateService.TryAcquireAsync(
                robot.RobotId,
                VdaOrderChannel.Yield,
                cache.YieldOrderId,
                cache.OrderUpdateId,
                ct);
            if (!gateResult.Success)
            {
                return new IdleYieldResult { Success = false, FailureReason = gateResult.Message };
            }

            Domain.Models.VDA5050.Order order;
            var nextHeaderId = checked((int)(robot.HeaderId + 1));
            var gateLease = gateResult.Lease;
            try
            {
                if (cache.OrderUpdateId > 0 && _settings.Vda5050.EnableOrderUpdatePrecheck)
                {
                    var precheck = await _vdaOrderGateService.ValidateOrderUpdatePrecheckAsync(
                        robot.RobotId,
                        VdaOrderChannel.Yield,
                        robot.RobotManufacturer,
                        robot.RobotSerialNumber,
                        cache.YieldOrderId,
                        cache.OrderUpdateId,
                        ct);
                    if (!precheck.Success)
                    {
                        await _vdaOrderGateService.RecordOrderUpdateDowngradeAsync(
                            robot.RobotId,
                            VdaOrderChannel.Yield,
                            cache.YieldOrderId,
                            cache.OrderUpdateId,
                            precheck.Reason,
                            ct);

                        var downgradedCache = await RebuildYieldCacheAfterPrecheckFailureAsync(
                            robot,
                            cache,
                            ct);
                        if (downgradedCache == null)
                        {
                            return new IdleYieldResult { Success = false, FailureReason = "Yield downgrade rebuild failed" };
                        }

                        cache = downgradedCache;
                        graph = await _agvPathService.GetOrBuildGraphAsync(cache.MapId) ?? graph;
                        if (!TryLocateCurrentYieldResourceSegment(cache, out currentJunctionIndex, out currentResourceIndex, out currentSegment))
                        {
                            return new IdleYieldResult { Success = false, FailureReason = "Yield cache has no dispatchable segment after downgrade" };
                        }
                    }
                }

                var isFinalDispatch = IsFinalYieldResourceSegment(cache, currentJunctionIndex, currentResourceIndex);
                var startSequenceId = ResolveYieldStartSequenceId(cache);
                nextHeaderId = checked((int)(robot.HeaderId + 1));
                order = BuildYieldOrder(
                    robot,
                    cache.YieldOrderId,
                    nextHeaderId,
                    cache.OrderUpdateId,
                    currentSegment.Segments,
                    graph,
                    cache.MapCode,
                    startSequenceId,
                    isFinalDispatch);

                await _vdaOrderGateService.MarkSessionSendingAsync(
                    robot.RobotId,
                    VdaOrderChannel.Yield,
                    order.OrderId,
                    order.OrderUpdateId,
                    null,
                    ct);

                await mqttClientService.PublishOrderAsync(
                    robot.ProtocolName,
                    robot.ProtocolVersion,
                    robot.RobotManufacturer,
                    robot.RobotSerialNumber,
                    order,
                    ct: ct);

                await _vdaOrderGateService.MarkSessionSentAsync(
                    robot.RobotId,
                    VdaOrderChannel.Yield,
                    order.OrderId,
                    order.OrderUpdateId,
                    ct);
                await PersistRobotHeaderIdAsync(robot, nextHeaderId, ct);
                cache.LastSentSequenceId = GetLastReleasedSequenceId(order, startSequenceId);
            }
            catch (Exception ex)
            {
                await _vdaOrderGateService.MarkSessionFailedAsync(
                    robot.RobotId,
                    VdaOrderChannel.Yield,
                    cache.YieldOrderId,
                    cache.OrderUpdateId,
                    ex.Message,
                    ct);
                throw;
            }
            finally
            {
                if (gateLease != null)
                {
                    await gateLease.DisposeAsync();
                }
            }

            var expectedPlanVersion = cache.PlanVersion;
            if (TryMarkYieldResourceSent(cache, currentJunctionIndex, currentResourceIndex))
            {
                if (cache.PlanVersion <= expectedPlanVersion)
                {
                    cache.PlanVersion = expectedPlanVersion + 1;
                }

                if (!await TryPersistYieldCacheCasWithFallbackAsync(cacheKey, cache, expectedPlanVersion, ct))
                {
                    _logger.LogWarning(
                        "[让行] 首段下发后更新让行缓存失败: IdleRobot={IdleRobotId}, CacheKey={CacheKey}",
                        request.IdleRobotId,
                        cacheKey);
                }
            }

            // 9. 设置冷却期
            var cooldownSeconds = _settings.GlobalNavigation?.Coordinator?.IdleYieldCooldownSeconds ?? 30;
            await SetYieldCooldownAsync(request.IdleRobotId, cooldownSeconds);

            _logger.LogInformation(
                "[让行] 已下发让行订单: IdleRobot={IdleRobotId}, From={From}, To={To}, OrderId={OrderId}",
                request.IdleRobotId, currentNodeCode, targetNodeCode, cache.YieldOrderId);

            return new IdleYieldResult
            {
                Success = true,
                OrderId = cache.YieldOrderId,
                TargetNodeCode = targetNodeCode
            };
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "[让行] 执行让行异常: IdleRobot={IdleRobotId}", request.IdleRobotId);
            return new IdleYieldResult { Success = false, FailureReason = ex.Message };
        }
    }

    /// <inheritdoc />
    public async Task<string?> FindNearestYieldTargetAsync(
        Guid mapId,
        string mapCode,
        Robot robot,
        string blockingAnchorNodeCode,
        string idleCurrentNodeCode,
        double idleCurrentTheta,
        Guid excludeRobotId,
        Robot requestingRobot,
        VdaSegmentedPathCache requestingCache,
        CancellationToken ct = default)
    {
        ct.ThrowIfCancellationRequested();
        var graph = await _agvPathService.GetOrBuildGraphAsync(mapId);
        if (graph == null) return null;

        var idleCurrentNode = graph.Nodes.Values.FirstOrDefault(n =>
            string.Equals(n.NodeCode, idleCurrentNodeCode, StringComparison.OrdinalIgnoreCase));
        if (idleCurrentNode == null) return null;

        var remainingTaskLockCandidates = NextSegmentLockScopeBuilder.BuildRemainingTaskLockCandidates(
            requestingCache,
            graph,
            requestingRobot);
        if (remainingTaskLockCandidates.Count == 0)
        {
            _logger.LogDebug(
                "[让行] 请求车剩余任务扫掠锁候选为空: RequestingRobot={RequestingRobotId}",
                requestingRobot.RobotId);
            return null;
        }

        var remainingTaskResourceKeys = NextSegmentLockScopeBuilder.BuildResourceKeys(remainingTaskLockCandidates);
        if (remainingTaskResourceKeys.Count == 0)
        {
            _logger.LogDebug(
                "[让行] 请求车剩余任务扫掠资源键为空: RequestingRobot={RequestingRobotId}",
                requestingRobot.RobotId);
            return null;
        }

        var remainingTaskSweptZones = NextSegmentLockScopeBuilder.BuildRemainingTaskSweptZones(
            requestingCache,
            graph,
            requestingRobot);
        if (remainingTaskSweptZones.Count == 0)
        {
            _logger.LogDebug(
                "[让行] 请求车剩余任务连续扫掠区为空: RequestingRobot={RequestingRobotId}",
                requestingRobot.RobotId);
            return null;
        }

        var orderedCandidates = BuildDivergentYieldCandidates(
            graph,
            idleCurrentNode,
            idleCurrentNodeCode,
            blockingAnchorNodeCode);
        if (orderedCandidates.Count == 0)
        {
            return null;
        }

        foreach (var candidate in orderedCandidates)
        {
            ct.ThrowIfCancellationRequested();

            if (await _trafficControl.IsNodeOccupiedByOtherAsync(mapCode, candidate.Node.NodeCode, excludeRobotId))
            {
                _logger.LogDebug(
                    "[让行] 候选目标被占用,跳过: IdleRobot={IdleRobotId}, Target={TargetNodeCode}, Hop={Hop}",
                    robot.RobotId,
                    candidate.Node.NodeCode,
                    candidate.Hop);
                continue;
            }

            var parkingLockCandidates = NextSegmentLockScopeBuilder.BuildNodeParkingLockCandidates(
                candidate.Node.NodeCode,
                graph,
                robot);
            if (parkingLockCandidates.Count == 0)
            {
                _logger.LogDebug(
                    "[让行] 无法构建目标驻车扫掠锁候选,跳过: IdleRobot={IdleRobotId}, Target={TargetNodeCode}, Hop={Hop}",
                    robot.RobotId,
                    candidate.Node.NodeCode,
                    candidate.Hop);
                continue;
            }

            var parkingResourceKeys = NextSegmentLockScopeBuilder.BuildResourceKeys(parkingLockCandidates);
            if (parkingResourceKeys.Overlaps(remainingTaskResourceKeys))
            {
                var overlapResources = parkingResourceKeys
                    .Where(remainingTaskResourceKeys.Contains)
                    .Take(8)
                    .ToList();
                _logger.LogDebug(
                    "[让行] 候选目标驻车扫掠资源与任务车剩余任务资源交集命中,跳过: IdleRobot={IdleRobotId}, Target={TargetNodeCode}, Hop={Hop}, OverlapResources={OverlapResources}",
                    robot.RobotId,
                    candidate.Node.NodeCode,
                    candidate.Hop,
                    overlapResources);
                continue;
            }

            var parkingSweptZones = NextSegmentLockScopeBuilder.BuildNodeParkingSweptZones(
                candidate.Node.NodeCode,
                graph,
                robot);
            if (parkingSweptZones.Count == 0)
            {
                _logger.LogDebug(
                    "[让行] 无法构建目标驻车连续扫掠区,跳过: IdleRobot={IdleRobotId}, Target={TargetNodeCode}, Hop={Hop}",
                    robot.RobotId,
                    candidate.Node.NodeCode,
                    candidate.Hop);
                continue;
            }

            var geometricIntersection = SweptAreaCoverageResolver.ZonesIntersect(
                parkingSweptZones,
                remainingTaskSweptZones);
            if (geometricIntersection)
            {
                _logger.LogDebug(
                    "[让行] 候选与任务车剩余扫掠区存在几何交集,跳过: IdleRobot={IdleRobotId}, Target={TargetNodeCode}, Hop={Hop}",
                    robot.RobotId,
                    candidate.Node.NodeCode,
                    candidate.Hop);
                continue;
            }

            var plannedPath = await PlanYieldPathAsync(
                robot,
                mapId,
                graph,
                idleCurrentNodeCode,
                idleCurrentTheta,
                candidate.Node.NodeCode,
                ct);
            if (plannedPath.Count == 0)
            {
                _logger.LogDebug(
                    "[让行] 候选目标不可达,跳过: IdleRobot={IdleRobotId}, Target={TargetNodeCode}, Hop={Hop}",
                    robot.RobotId,
                    candidate.Node.NodeCode,
                    candidate.Hop);
                continue;
            }

            var pathSweptLockCandidates = NextSegmentLockScopeBuilder.BuildSweptLockCandidates(
                plannedPath,
                graph,
                robot);
            var sweptNodeCodes = DistinctCodesInOrder(pathSweptLockCandidates
                .SelectMany(segment => new[] { segment.FromNodeCode, segment.ToNodeCode }));
            var sweptEdgeCodes = DistinctCodesInOrder(pathSweptLockCandidates
                .Select(segment => segment.EdgeCode));
            var sweptEdgeDirectionMap = BuildEdgeDirectionMap(pathSweptLockCandidates);

            if (await HasAnyExternalLocksAsync(
                    mapCode,
                    sweptNodeCodes,
                    sweptEdgeCodes,
                    sweptEdgeDirectionMap,
                    excludeRobotId,
                    robot.RobotId,
                    candidate.Node.NodeCode,
                    candidate.Hop,
                    ct))
            {
                continue;
            }

            var forbiddenResource = GetYieldForbiddenResource(graph, candidate.Node.NodeId);
            if (forbiddenResource != null)
            {
                _logger.LogDebug(
                    "[让行] 候选目标位于不允许避让资源区域,跳过: IdleRobot={IdleRobotId}, Target={TargetNodeCode}, Hop={Hop}, Resource={ResourceCode}",
                    robot.RobotId,
                    candidate.Node.NodeCode,
                    candidate.Hop,
                    forbiddenResource.ResourceCode);
                continue;
            }

            _logger.LogInformation(
                "[让行] 选中零资源键交集且零几何交集让行目标: IdleRobot={IdleRobotId}, Target={TargetNodeCode}, Hop={Hop}, Distance={Distance}",
                robot.RobotId,
                candidate.Node.NodeCode,
                candidate.Hop,
                candidate.DistanceSquared);
            return candidate.Node.NodeCode;
        }

        _logger.LogInformation(
            "[让行] 发散搜索结束,未找到满足零资源键交集且零几何交集的可用让行目标: IdleRobot={IdleRobotId}",
            robot.RobotId);
        return null;
    }

    /// <inheritdoc />
    public async Task<bool> IsInYieldCooldownAsync(Guid robotId)
    {
        try
        {
            var db = _redis.GetDatabase();
            var key = $"{YieldCooldownKeyPrefix}:{robotId:N}";
            return await db.KeyExistsAsync(key);
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "[让行] 检查冷却期异常: RobotId={RobotId}", robotId);
            return false;
        }
    }

    /// <inheritdoc />
    public async Task SetYieldCooldownAsync(Guid robotId, int cooldownSeconds)
    {
        try
        {
            var db = _redis.GetDatabase();
            var key = $"{YieldCooldownKeyPrefix}:{robotId:N}";
            await db.StringSetAsync(key, "1", TimeSpan.FromSeconds(cooldownSeconds));
        }
        catch (Exception ex)
        {
            _logger.LogWarning(ex, "[让行] 设置冷却期异常: RobotId={RobotId}", robotId);
        }
    }

    /// <inheritdoc />
    public async Task<bool> TryContinueYieldDispatchAsync(
        string robotManufacturer,
        string robotSerialNumber,
        CancellationToken ct = default)
    {
        var hasActiveYield = false;

        try
        {
            var robot = await _robotRepository.GetByManufacturerAndSerialNumberAsync(
                robotManufacturer,
                robotSerialNumber,
                ct) as Robot;
            if (robot == null || !robot.Active)
            {
                return false;
            }

            var (cacheKey, cache) = await GetLatestYieldCacheAsync(robot.RobotId, ct);
            if (cache == null || string.IsNullOrWhiteSpace(cacheKey))
            {
                return false;
            }

            hasActiveYield = true;
            if (IsAllYieldSegmentsSent(cache))
            {
                if (await IsYieldCompletionConfirmedAsync(robot, cache, ct))
                {
                    await CleanupYieldLocksOnCompletionAsync(robot, cache, ct);
                    await DeleteYieldCacheAsync(cacheKey);
                    await _vdaOrderGateService.MarkSessionCompletedAsync(
                        robot.RobotId,
                        VdaOrderChannel.Yield,
                        cache.YieldOrderId,
                        cache.OrderUpdateId,
                        ct);
                    return false;
                }

                return true;
            }

            if (!await IsReadyForNextYieldDispatchAsync(robot, cache, ct))
            {
                _logger.LogDebug(
                    "[让行] 让行缓存存在但尚未到续发时机,保持让行优先: IdleRobot={IdleRobotId}, YieldOrderId={YieldOrderId}",
                    robot.RobotId,
                    cache.YieldOrderId);
                return true;
            }

            if (!TryLocateCurrentYieldResourceSegment(cache, out var junctionIndex, out var resourceIndex, out var segmentItem))
            {
                await DeleteYieldCacheAsync(cacheKey);
                return false;
            }

            var graph = await _agvPathService.GetOrBuildGraphAsync(cache.MapId);
            if (graph == null)
            {
                _logger.LogWarning(
                    "[让行] 让行续发失败,地图图结构不可用: IdleRobot={IdleRobotId}, YieldOrderId={YieldOrderId}",
                    robot.RobotId,
                    cache.YieldOrderId);
                return true;
            }

            var mqttClientService = _serviceProvider.GetRequiredService<IMqttClientService>();
            var gateResult = await _vdaOrderGateService.TryAcquireAsync(
                robot.RobotId,
                VdaOrderChannel.Yield,
                cache.YieldOrderId,
                cache.OrderUpdateId,
                ct);
            if (!gateResult.Success)
            {
                _logger.LogDebug(
                    "[让行] 让行续发门闩阻断: IdleRobot={IdleRobotId}, YieldOrderId={YieldOrderId}, Message={Message}",
                    robot.RobotId,
                    cache.YieldOrderId,
                    gateResult.Message);
                return true;
            }

            Domain.Models.VDA5050.Order order;
            var nextHeaderId = checked((int)(robot.HeaderId + 1));
            var gateLease = gateResult.Lease;
            try
            {
                if (cache.OrderUpdateId > 0 && _settings.Vda5050.EnableOrderUpdatePrecheck)
                {
                    var precheck = await _vdaOrderGateService.ValidateOrderUpdatePrecheckAsync(
                        robot.RobotId,
                        VdaOrderChannel.Yield,
                        robot.RobotManufacturer,
                        robot.RobotSerialNumber,
                        cache.YieldOrderId,
                        cache.OrderUpdateId,
                        ct);
                    if (!precheck.Success)
                    {
                        await _vdaOrderGateService.RecordOrderUpdateDowngradeAsync(
                            robot.RobotId,
                            VdaOrderChannel.Yield,
                            cache.YieldOrderId,
                            cache.OrderUpdateId,
                            precheck.Reason,
                            ct);

                        var downgradedCache = await RebuildYieldCacheAfterPrecheckFailureAsync(
                            robot,
                            cache,
                            ct);
                        if (downgradedCache == null)
                        {
                            _logger.LogWarning(
                                "[让行] 让行续发降级重建失败: IdleRobot={IdleRobotId}, YieldOrderId={YieldOrderId}",
                                robot.RobotId,
                                cache.YieldOrderId);
                            return true;
                        }

                        cache = downgradedCache;
                        if (!TryLocateCurrentYieldResourceSegment(cache, out junctionIndex, out resourceIndex, out segmentItem))
                        {
                            _logger.LogWarning(
                                "[让行] 让行续发降级后无可发送分段: IdleRobot={IdleRobotId}, YieldOrderId={YieldOrderId}",
                                robot.RobotId,
                                cache.YieldOrderId);
                            return true;
                        }

                        graph = await _agvPathService.GetOrBuildGraphAsync(cache.MapId) ?? graph;
                    }
                }

                var isFinalDispatch = IsFinalYieldResourceSegment(cache, junctionIndex, resourceIndex);
                var startSequenceId = ResolveYieldStartSequenceId(cache);
                nextHeaderId = checked((int)(robot.HeaderId + 1));
                order = BuildYieldOrder(
                    robot,
                    cache.YieldOrderId,
                    nextHeaderId,
                    cache.OrderUpdateId,
                    segmentItem.Segments,
                    graph,
                    cache.MapCode,
                    startSequenceId,
                    isFinalDispatch);

                await _vdaOrderGateService.MarkSessionSendingAsync(
                    robot.RobotId,
                    VdaOrderChannel.Yield,
                    order.OrderId,
                    order.OrderUpdateId,
                    null,
                    ct);

                await mqttClientService.PublishOrderAsync(
                    robot.ProtocolName,
                    robot.ProtocolVersion,
                    robot.RobotManufacturer,
                    robot.RobotSerialNumber,
                    order,
                    ct: ct);

                await _vdaOrderGateService.MarkSessionSentAsync(
                    robot.RobotId,
                    VdaOrderChannel.Yield,
                    order.OrderId,
                    order.OrderUpdateId,
                    ct);
                await PersistRobotHeaderIdAsync(robot, nextHeaderId, ct);
                cache.LastSentSequenceId = GetLastReleasedSequenceId(order, startSequenceId);
            }
            catch (Exception ex)
            {
                await _vdaOrderGateService.MarkSessionFailedAsync(
                    robot.RobotId,
                    VdaOrderChannel.Yield,
                    cache.YieldOrderId,
                    cache.OrderUpdateId,
                    ex.Message,
                    ct);
                throw;
            }
            finally
            {
                if (gateLease != null)
                {
                    await gateLease.DisposeAsync();
                }
            }

            var expectedPlanVersion = cache.PlanVersion;
            if (TryMarkYieldResourceSent(cache, junctionIndex, resourceIndex))
            {
                if (cache.PlanVersion <= expectedPlanVersion)
                {
                    cache.PlanVersion = expectedPlanVersion + 1;
                }

                if (!await TryPersistYieldCacheCasWithFallbackAsync(cacheKey, cache, expectedPlanVersion, ct))
                {
                    _logger.LogWarning(
                        "[让行] 让行续发后缓存CAS更新失败: IdleRobot={IdleRobotId}, YieldOrderId={YieldOrderId}, ExpectedPlanVersion={PlanVersion}",
                        robot.RobotId,
                        cache.YieldOrderId,
                        expectedPlanVersion);
                }
            }

            if (IsAllYieldSegmentsSent(cache))
            {
                if (await IsYieldCompletionConfirmedAsync(robot, cache, ct))
                {
                    await CleanupYieldLocksOnCompletionAsync(robot, cache, ct);
                    await DeleteYieldCacheAsync(cacheKey);
                    await _vdaOrderGateService.MarkSessionCompletedAsync(
                        robot.RobotId,
                        VdaOrderChannel.Yield,
                        cache.YieldOrderId,
                        cache.OrderUpdateId,
                        ct);
                }
            }

            _logger.LogInformation(
                "[让行] 已续发让行分段: IdleRobot={IdleRobotId}, YieldOrderId={YieldOrderId}, OrderUpdateId={OrderUpdateId}, JunctionIndex={JunctionIndex}, ResourceIndex={ResourceIndex}",
                robot.RobotId,
                cache.YieldOrderId,
                order.OrderUpdateId,
                junctionIndex,
                resourceIndex);
            return true;
        }
        catch (Exception ex)
        {
            _logger.LogWarning(
                ex,
                "[让行] 续发让行分段异常: Manufacturer={Manufacturer}, SerialNumber={SerialNumber}",
                robotManufacturer,
                robotSerialNumber);
            return hasActiveYield;
        }
    }

    private async Task<(string? CacheKey, YieldSegmentedPathCache? Cache)> GetLatestYieldCacheAsync(
        Guid robotId,
        CancellationToken ct)
    {
        var endPoints = _redis.GetEndPoints();
        if (endPoints.Length == 0)
        {
            return (null, null);
        }

        var server = _redis.GetServer(endPoints.First());
        var db = _redis.GetDatabase();
        var pattern = $"{_settings.Redis.KeyPrefixes.VdaPath}:{robotId}:{YieldKeyMarker}:*";

        string? latestKey = null;
        YieldSegmentedPathCache? latestCache = null;

        foreach (var key in server.Keys(pattern: pattern))
        {
            ct.ThrowIfCancellationRequested();
            var keyText = key.ToString();
            if (!IsYieldCachePayloadKey(keyText, robotId))
            {
                continue;
            }

            var cacheValue = await db.StringGetAsync(key);
            if (cacheValue.IsNullOrEmpty)
            {
                continue;
            }

            YieldSegmentedPathCache? candidate;
            try
            {
                candidate = JsonSerializer.Deserialize<YieldSegmentedPathCache>(cacheValue.ToString());
            }
            catch (Exception ex) when (ex is JsonException or NotSupportedException)
            {
                _logger.LogDebug(ex, "[让行] 跳过无法反序列化的让行缓存Key: {CacheKey}", keyText);
                continue;
            }

            if (candidate == null)
            {
                continue;
            }

            if (latestCache == null || candidate.CreatedAt > latestCache.CreatedAt)
            {
                latestKey = keyText;
                latestCache = candidate;
            }
        }

        return (latestKey, latestCache);
    }

    private bool IsAllYieldSegmentsSent(YieldSegmentedPathCache cache)
    {
        return !cache.JunctionSegments
            .SelectMany(junction => junction.ResourceSegments)
            .Any(resource => !resource.IsSent);
    }

    private async Task<YieldSegmentedPathCache?> RebuildYieldCacheAfterPrecheckFailureAsync(
        Robot robot,
        YieldSegmentedPathCache cache,
        CancellationToken ct)
    {
        var graph = await _agvPathService.GetOrBuildGraphAsync(cache.MapId);
        if (graph == null)
        {
            return null;
        }

        var status = await _robotCacheService.GetStatusAsync(robot.RobotManufacturer, robot.RobotSerialNumber);
        var location = await _robotCacheService.GetLocationAsync(robot.RobotManufacturer, robot.RobotSerialNumber);
        var currentNodeCode = await RobotNavigationNodeResolver.ResolveAsync(
            _agvPathService,
            cache.MapId,
            location,
            fallbackLastNodeCode: status?.LastNode,
            ct: ct);

        var currentTheta = location?.Theta ?? robot.CurrentTheta ?? 0d;
        var remainingSegments = CollectRemainingYieldSegments(cache);
        List<PathSegmentWithCode> plannedSegments = new();

        if (!string.IsNullOrWhiteSpace(currentNodeCode) &&
            !string.IsNullOrWhiteSpace(cache.TargetNodeCode) &&
            !string.Equals(currentNodeCode, cache.TargetNodeCode, StringComparison.OrdinalIgnoreCase))
        {
            plannedSegments = await PlanYieldPathAsync(
                robot,
                cache.MapId,
                graph,
                currentNodeCode,
                currentTheta,
                cache.TargetNodeCode,
                ct);
        }

        if (plannedSegments.Count == 0)
        {
            plannedSegments = remainingSegments;
        }

        if (plannedSegments.Count == 0)
        {
            return null;
        }

        var segmentedPath = _vdaPathSegmentationService.SplitSegmentsByBoundary(
            plannedSegments,
            graph,
            robot,
            hasTerminalAction: false);
        if (segmentedPath.Count == 0)
        {
            return null;
        }

        return BuildYieldSegmentedPathCache(
            robot,
            cache.MapId,
            cache.MapCode,
            cache.TargetNodeCode,
            $"YIELD-{Guid.NewGuid():N}",
            segmentedPath);
    }

    private static List<PathSegmentWithCode> CollectRemainingYieldSegments(YieldSegmentedPathCache cache)
    {
        var remaining = new List<PathSegmentWithCode>();
        foreach (var junction in cache.JunctionSegments)
        {
            foreach (var resource in junction.ResourceSegments)
            {
                if (resource.IsSent || resource.Segments.Count == 0)
                {
                    continue;
                }

                remaining.AddRange(resource.Segments);
            }
        }

        return remaining;
    }

    private async Task<bool> IsYieldCompletionConfirmedAsync(
        Robot robot,
        YieldSegmentedPathCache cache,
        CancellationToken ct)
    {
        if (!IsAllYieldSegmentsSent(cache))
        {
            return false;
        }

        var status = await _robotCacheService.GetStatusAsync(robot.RobotManufacturer, robot.RobotSerialNumber);
        if (status == null)
        {
            return false;
        }

        if (status.Driving)
        {
            return false;
        }

        if (IsNodeCodeMatchWithVirtualSuffix(status.LastNode, cache.TargetNodeCode))
        {
            return true;
        }

        if (string.Equals(status.CurrentOrderId, cache.YieldOrderId, StringComparison.OrdinalIgnoreCase))
        {
            return (status.CurrentOrderUpdateId ?? 0) >= (uint)Math.Max(0, cache.OrderUpdateId);
        }

        return false;
    }

    private async Task CleanupYieldLocksOnCompletionAsync(
        Robot robot,
        YieldSegmentedPathCache cache,
        CancellationToken ct)
    {
        try
        {
            var status = await _robotCacheService.GetStatusAsync(robot.RobotManufacturer, robot.RobotSerialNumber);
            var releasedCount = await _trafficControl.ReleaseAllRobotLocksAsync(
                robot.RobotId,
                cache.MapCode,
                status?.LastNode);

            _logger.LogInformation(
                "[让行] 让行完成后已清理机器人资源锁: IdleRobot={IdleRobotId}, YieldOrderId={YieldOrderId}, ReleasedCount={ReleasedCount}, KeepNode={KeepNode}",
                robot.RobotId,
                cache.YieldOrderId,
                releasedCount,
                status?.LastNode);
        }
        catch (Exception ex)
        {
            _logger.LogWarning(
                ex,
                "[让行] 让行完成后清理资源锁异常: IdleRobot={IdleRobotId}, YieldOrderId={YieldOrderId}",
                robot.RobotId,
                cache.YieldOrderId);
        }
    }

    private async Task<bool> IsReadyForNextYieldDispatchAsync(
        Robot robot,
        YieldSegmentedPathCache cache,
        CancellationToken ct)
    {
        if (!TryGetLastSentYieldSegment(cache, out var lastSentSegment))
        {
            return true;
        }

        var status = await _robotCacheService.GetStatusAsync(
            robot.RobotManufacturer,
            robot.RobotSerialNumber);
        var lastNode = status?.LastNode;
        if (string.IsNullOrWhiteSpace(lastNode))
        {
            return false;
        }

        return IsNodeCodeMatchWithVirtualSuffix(lastNode, lastSentSegment.ToNodeCode) ||
               IsNodeCodeMatchWithVirtualSuffix(lastNode, lastSentSegment.FromNodeCode);
    }

    private static bool TryGetLastSentYieldSegment(
        YieldSegmentedPathCache cache,
        out PathSegmentWithCode lastSegment)
    {
        for (var j = cache.JunctionSegments.Count - 1; j >= 0; j--)
        {
            var junction = cache.JunctionSegments[j];
            for (var r = junction.ResourceSegments.Count - 1; r >= 0; r--)
            {
                var resource = junction.ResourceSegments[r];
                if (!resource.IsSent || resource.Segments.Count == 0)
                {
                    continue;
                }

                lastSegment = resource.Segments[^1];
                return true;
            }
        }

        lastSegment = null!;
        return false;
    }

    private static bool TryLocateCurrentYieldResourceSegment(
        YieldSegmentedPathCache cache,
        out int junctionIndex,
        out int resourceIndex,
        out VdaSegmentCacheItem segmentItem)
    {
        var jStart = Math.Max(0, cache.CurrentJunctionIndex);
        for (var j = jStart; j < cache.JunctionSegments.Count; j++)
        {
            var junction = cache.JunctionSegments[j];
            var rStart = j == jStart ? Math.Max(0, cache.CurrentResourceIndex) : 0;
            for (var r = rStart; r < junction.ResourceSegments.Count; r++)
            {
                var candidate = junction.ResourceSegments[r];
                if (candidate.IsSent || candidate.Segments.Count == 0)
                {
                    continue;
                }

                cache.CurrentJunctionIndex = j;
                cache.CurrentResourceIndex = r;
                junctionIndex = j;
                resourceIndex = r;
                segmentItem = candidate;
                return true;
            }
        }

        junctionIndex = -1;
        resourceIndex = -1;
        segmentItem = null!;
        return false;
    }

    private static bool IsFinalYieldResourceSegment(
        YieldSegmentedPathCache cache,
        int currentJunctionIndex,
        int currentResourceIndex)
    {
        for (var j = currentJunctionIndex; j < cache.JunctionSegments.Count; j++)
        {
            var junction = cache.JunctionSegments[j];
            var rStart = j == currentJunctionIndex ? currentResourceIndex + 1 : 0;
            for (var r = rStart; r < junction.ResourceSegments.Count; r++)
            {
                var candidate = junction.ResourceSegments[r];
                if (!candidate.IsSent && candidate.Segments.Count > 0)
                {
                    return false;
                }
            }
        }

        return true;
    }

    private static bool TryMarkYieldResourceSent(
        YieldSegmentedPathCache cache,
        int currentJunctionIndex,
        int currentResourceIndex)
    {
        if (currentJunctionIndex < 0 || currentJunctionIndex >= cache.JunctionSegments.Count)
        {
            return false;
        }

        var junction = cache.JunctionSegments[currentJunctionIndex];
        if (currentResourceIndex < 0 || currentResourceIndex >= junction.ResourceSegments.Count)
        {
            return false;
        }

        var current = junction.ResourceSegments[currentResourceIndex];
        current.SendStatus = SegmentSendStatus.Sent;
        current.IsSent = true;

        var nextJunctionIndex = currentJunctionIndex;
        var nextResourceIndex = currentResourceIndex + 1;
        if (nextResourceIndex >= junction.ResourceSegments.Count)
        {
            nextJunctionIndex++;
            nextResourceIndex = 0;
        }

        cache.CurrentJunctionIndex = nextJunctionIndex;
        cache.CurrentResourceIndex = nextResourceIndex;
        cache.OrderUpdateId = Math.Max(0, cache.OrderUpdateId) + 1;
        return true;
    }

    private YieldSegmentedPathCache BuildYieldSegmentedPathCache(
        Robot robot,
        Guid mapId,
        string mapCode,
        string targetNodeCode,
        string orderId,
        List<List<List<PathSegmentWithCode>>> segmentedPath)
    {
        var junctionSegments = segmentedPath
            .Select(junctionGroup => new VdaJunctionSegmentCache
            {
                ResourceSegments = junctionGroup.Select(resourceGroup => new VdaSegmentCacheItem
                {
                    SendStatus = SegmentSendStatus.Pending,
                    IsSent = false,
                    Segments = resourceGroup
                }).ToList()
            })
            .ToList();

        return new YieldSegmentedPathCache
        {
            YieldOrderId = orderId,
            RobotId = robot.RobotId,
            MapId = mapId,
            MapCode = mapCode,
            TargetNodeCode = targetNodeCode,
            CreatedAt = DateTime.Now,
            CurrentJunctionIndex = 0,
            CurrentResourceIndex = 0,
            OrderUpdateId = 0,
            LastSentSequenceId = 0,
            PlanVersion = 1,
            JunctionSegments = junctionSegments
        };
    }

    private async Task<bool> SaveYieldCacheAsync(
        string cacheKey,
        YieldSegmentedPathCache cache,
        CancellationToken ct)
    {
        ct.ThrowIfCancellationRequested();
        var db = _redis.GetDatabase();
        var payload = JsonSerializer.Serialize(cache);
        var tx = db.CreateTransaction();
        _ = tx.StringSetAsync(cacheKey, payload);
        _ = tx.StringSetAsync(BuildYieldPlanVersionKey(cacheKey), cache.PlanVersion.ToString());
        return await tx.ExecuteAsync();
    }

    private async Task<bool> TryPersistYieldCacheCasWithFallbackAsync(
        string cacheKey,
        YieldSegmentedPathCache cache,
        long expectedPlanVersion,
        CancellationToken ct)
    {
        var db = _redis.GetDatabase();
        if (await TryPersistYieldCacheCasAsync(db, cacheKey, cache, expectedPlanVersion, ct))
        {
            return true;
        }

        var latestVersionValue = await db.StringGetAsync(BuildYieldPlanVersionKey(cacheKey));
        if (latestVersionValue.IsNullOrEmpty || !long.TryParse(latestVersionValue.ToString(), out var latestVersion))
        {
            return false;
        }

        if (cache.PlanVersion <= latestVersion)
        {
            cache.PlanVersion = latestVersion + 1;
        }

        return await TryPersistYieldCacheCasAsync(db, cacheKey, cache, latestVersion, ct);
    }

    private static async Task<bool> TryPersistYieldCacheCasAsync(
        IDatabase db,
        string cacheKey,
        YieldSegmentedPathCache cache,
        long expectedPlanVersion,
        CancellationToken ct)
    {
        ct.ThrowIfCancellationRequested();
        var payload = JsonSerializer.Serialize(cache);
        var planVersionKey = BuildYieldPlanVersionKey(cacheKey);

        for (var attempt = 0; attempt < 2; attempt++)
        {
            var tx = db.CreateTransaction();
            tx.AddCondition(Condition.StringEqual(planVersionKey, expectedPlanVersion.ToString()));
            _ = tx.StringSetAsync(cacheKey, payload);
            _ = tx.StringSetAsync(planVersionKey, cache.PlanVersion.ToString());
            if (await tx.ExecuteAsync())
            {
                return true;
            }

            if (attempt == 0)
            {
                await db.StringSetAsync(planVersionKey, expectedPlanVersion.ToString(), when: When.NotExists);
            }
        }

        return false;
    }

    private async Task DeleteYieldCacheAsync(string cacheKey)
    {
        var db = _redis.GetDatabase();
        await db.KeyDeleteAsync(cacheKey);
        await db.KeyDeleteAsync(BuildYieldPlanVersionKey(cacheKey));
    }

    private async Task PersistRobotHeaderIdAsync(Robot robot, int nextHeaderId, CancellationToken ct)
    {
        robot.HeaderId = nextHeaderId;

        var trackedRobot = await _robotRepository.GetByIdAsync(robot.RobotId, ct) as Robot;
        if (trackedRobot == null)
        {
            await _robotRepository.UpdateAsync(robot, ct);
            await _robotRepository.SaveChangesAsync(ct);
            return;
        }

        if (!ReferenceEquals(trackedRobot, robot))
        {
            trackedRobot.HeaderId = nextHeaderId;
        }

        await _robotRepository.SaveChangesAsync(ct);
    }

    private string BuildYieldCacheKey(Guid robotId, string yieldOrderId)
        => $"{_settings.Redis.KeyPrefixes.VdaPath}:{robotId}:{YieldKeyMarker}:{yieldOrderId}";

    private static string BuildYieldPlanVersionKey(string payloadKey) => $"{payloadKey}:planVersion";

    private static bool IsYieldCachePayloadKey(string keyText, Guid robotId)
    {
        if (string.IsNullOrWhiteSpace(keyText) ||
            keyText.EndsWith(":planVersion", StringComparison.OrdinalIgnoreCase))
        {
            return false;
        }

        var marker = $":{robotId}:{YieldKeyMarker}:";
        return keyText.Contains(marker, StringComparison.OrdinalIgnoreCase);
    }

    private static bool IsNodeCodeMatchWithVirtualSuffix(string? actualNodeCode, string? expectedNodeCode)
    {
        if (string.IsNullOrWhiteSpace(actualNodeCode) || string.IsNullOrWhiteSpace(expectedNodeCode))
        {
            return false;
        }

        if (string.Equals(actualNodeCode, expectedNodeCode, StringComparison.OrdinalIgnoreCase))
        {
            return true;
        }

        var normalizedActual = NormalizeVirtualNodeCodeForComparison(actualNodeCode);
        var normalizedExpected = NormalizeVirtualNodeCodeForComparison(expectedNodeCode);
        return string.Equals(normalizedActual, normalizedExpected, StringComparison.OrdinalIgnoreCase);
    }

    private static string NormalizeVirtualNodeCodeForComparison(string nodeCode)
    {
        var trimCode = nodeCode.Trim();
        if (trimCode.Length == 0)
        {
            return trimCode;
        }

        var dashIndex = trimCode.LastIndexOf('-');
        if (dashIndex <= 0 || dashIndex >= trimCode.Length - 1)
        {
            return trimCode;
        }

        var suffix = trimCode[(dashIndex + 1)..];
        for (var i = 0; i < suffix.Length; i++)
        {
            if (!char.IsDigit(suffix[i]))
            {
                return trimCode;
            }
        }

        return trimCode[..dashIndex];
    }

    /// <summary>
    /// 计算两个节点平面距离的平方值。
    /// </summary>
    private static double DistanceSquared(PathNode from, PathNode to)
    {
        var dx = from.X - to.X;
        var dy = from.Y - to.Y;
        return dx * dx + dy * dy;
    }

    /// <summary>
    /// 使用正式寻路服务规划让行路径。
    /// </summary>
    private async Task<List<PathSegmentWithCode>> PlanYieldPathAsync(
        Robot robot,
        Guid mapId,
        PathGraph graph,
        string fromNodeCode,
        double currentTheta,
        string toNodeCode,
        CancellationToken ct)
    {
        if (string.Equals(fromNodeCode, toNodeCode, StringComparison.OrdinalIgnoreCase))
            return new List<PathSegmentWithCode>();

        var start = graph.Nodes.Values.FirstOrDefault(n =>
            string.Equals(n.NodeCode, fromNodeCode, StringComparison.OrdinalIgnoreCase));
        var target = graph.Nodes.Values.FirstOrDefault(n =>
            string.Equals(n.NodeCode, toNodeCode, StringComparison.OrdinalIgnoreCase));
        if (start == null || target == null)
            return new List<PathSegmentWithCode>();

        var request = new PathRequest
        {
            RobotId = robot.RobotId,
            MapId = mapId,
            StartNodeId = start.NodeId,
            EndNodeId = target.NodeId,
            CurrentTheta = currentTheta,
            IsLoaded = false,
            Priority = 0,
            BatteryLevel = robot.BatteryLevel ?? 100,
            MovementType = robot.MovementType,
            ForkRadOffsets = robot.ForkRadOffset,
            RequiredEndRad = target.Theta
        };

        var pathResult = await _agvPathService.CalculatePathAsync(request, ct);
        if (!pathResult.Success || pathResult.Segments.Count == 0)
        {
            return new List<PathSegmentWithCode>();
        }

        return _agvPathService.EnrichSegmentsWithCode(pathResult.Segments, graph);
    }

    private async Task<IdleRobotTaskSnapshot> GetIdleRobotTaskSnapshotAsync(Guid robotId, CancellationToken ct)
    {
        using var scope = _serviceProvider.CreateScope();
        var taskRepository = scope.ServiceProvider.GetRequiredService<IRobotTaskRepository>();
        var robotTasks = (await taskRepository.GetByRobotIdAsync(robotId, ct)).ToList();

        var hasInProgressTaskOrSubTask = robotTasks.Any(task =>
            task.Status == Rcs.Domain.Entities.TaskStatus.InProgress ||
            task.SubTasks.Any(subTask => subTask.Status == Rcs.Domain.Entities.TaskStatus.InProgress));

        var activeTasks = robotTasks
            .Where(task =>
                task.Status == Rcs.Domain.Entities.TaskStatus.Assigned ||
                task.Status == Rcs.Domain.Entities.TaskStatus.InProgress)
            .ToList();

        return new IdleRobotTaskSnapshot(
            hasInProgressTaskOrSubTask,
            activeTasks);
    }

    private async Task<IdleYieldResult?> TrySkipYieldWhenSubTaskCanProceedAsync(
        IdleRobotYieldRequest request,
        Robot requestingRobot,
        Robot idleRobot,
        IdleRobotTaskSnapshot taskSnapshot,
        PathGraph graph,
        string currentNodeCode,
        double currentTheta,
        CancellationToken ct)
    {
        var nextExecutable = await SelectNextExecutableByExecutionQueueRuleAsync(
            idleRobot,
            request.MapId,
            graph,
            currentNodeCode,
            currentTheta,
            taskSnapshot.ActiveTasks,
            ct);
        if (nextExecutable == null)
        {
            return null;
        }

        var task = nextExecutable.Task;
        var nextSubTask = nextExecutable.SubTask;

        if (string.IsNullOrWhiteSpace(request.MapCode))
        {
            _logger.LogDebug(
                "[让行] 地图编码为空,跳过待执行子任务直执判定: IdleRobot={IdleRobotId}, TaskId={TaskId}, SubTaskId={SubTaskId}",
                idleRobot.RobotId,
                task.TaskId,
                nextSubTask.SubTaskId);
            return null;
        }

        if (!graph.Nodes.TryGetValue(nextSubTask.EndNodeId, out var targetNode) ||
            string.IsNullOrWhiteSpace(targetNode.NodeCode))
        {
            _logger.LogDebug(
                "[让行] 待执行子任务终点不在当前地图图结构,回退让行流程: IdleRobot={IdleRobotId}, TaskId={TaskId}, SubTaskId={SubTaskId}, EndNodeId={EndNodeId}",
                idleRobot.RobotId,
                task.TaskId,
                nextSubTask.SubTaskId,
                nextSubTask.EndNodeId);
            return null;
        }

        var targetNodeCode = targetNode.NodeCode;
        if (string.Equals(currentNodeCode, targetNodeCode, StringComparison.OrdinalIgnoreCase))
        {
            _logger.LogInformation(
                "[让行] 让行车待执行子任务可直接执行(当前位置即目标节点),跳过让行: IdleRobot={IdleRobotId}, TaskId={TaskId}, SubTaskId={SubTaskId}, TargetNode={TargetNodeCode}",
                idleRobot.RobotId,
                task.TaskId,
                nextSubTask.SubTaskId,
                targetNodeCode);
            return new IdleYieldResult
            {
                Success = false,
                FailureReason = "Pending subtask can proceed directly, skip yield"
            };
        }

        var plannedPath = await PlanYieldPathAsync(
            idleRobot,
            request.MapId,
            graph,
            currentNodeCode,
            currentTheta,
            targetNodeCode,
            ct);
        if (plannedPath.Count == 0)
        {
            _logger.LogDebug(
                "[让行] 待执行子任务路径不可达,回退让行流程: IdleRobot={IdleRobotId}, TaskId={TaskId}, SubTaskId={SubTaskId}, TargetNode={TargetNodeCode}",
                idleRobot.RobotId,
                task.TaskId,
                nextSubTask.SubTaskId,
                targetNodeCode);
            return null;
        }

        var sweptLockCandidates = NextSegmentLockScopeBuilder.BuildSweptLockCandidates(
            plannedPath,
            graph,
            idleRobot);
        var sweptNodeCodes = DistinctCodesInOrder(sweptLockCandidates
            .SelectMany(segment => new[] { segment.FromNodeCode, segment.ToNodeCode }));
        var sweptEdgeCodes = DistinctCodesInOrder(sweptLockCandidates
            .Select(segment => segment.EdgeCode));
        var sweptEdgeDirectionMap = BuildEdgeDirectionMap(sweptLockCandidates);

        var hasExternalLocks = await HasAnyExternalLocksAsync(
            request.MapCode,
            sweptNodeCodes,
            sweptEdgeCodes,
            sweptEdgeDirectionMap,
            requestingRobot.RobotId,
            idleRobot.RobotId,
            targetNodeCode,
            targetHop: -1,
            ct);
        if (hasExternalLocks)
        {
            return null;
        }

        _logger.LogInformation(
            "[让行] 让行车待执行子任务路径与外部资源锁无冲突,跳过让行: IdleRobot={IdleRobotId}, TaskId={TaskId}, SubTaskId={SubTaskId}, TargetNode={TargetNodeCode}",
            idleRobot.RobotId,
            task.TaskId,
            nextSubTask.SubTaskId,
            targetNodeCode);
        return new IdleYieldResult
        {
            Success = false,
            FailureReason = "Pending subtask can proceed directly, skip yield"
        };
    }

    private async Task<ExecutableSubTaskCandidate?> SelectNextExecutableByExecutionQueueRuleAsync(
        Robot robot,
        Guid mapId,
        PathGraph graph,
        string currentNodeCode,
        double currentTheta,
        IReadOnlyList<RobotTask> activeTasks,
        CancellationToken ct)
    {
        if (activeTasks.Count == 0)
        {
            return null;
        }

        var candidates = new List<ExecutableSubTaskCandidate>();
        foreach (var task in activeTasks)
        {
            ct.ThrowIfCancellationRequested();

            if (!task.SubTasks.Any() && task.Status == Rcs.Domain.Entities.TaskStatus.InProgress)
            {
                continue;
            }

            // 与 TaskExecutionBackgroundService.BuildExecutionQueueAsync 保持一致:复用领域方法判定下一条可执行子任务。
            var nextSubTask = task.GetNextExecutableSubTask();
            if (task.SubTasks.Any() && nextSubTask == null)
            {
                continue;
            }

            if (nextSubTask == null)
            {
                continue;
            }

            var pathCost = await CalculateExecutionQueueLikePathCostAsync(
                robot,
                mapId,
                graph,
                currentNodeCode,
                currentTheta,
                task,
                nextSubTask,
                ct);
            if (pathCost == double.MaxValue || double.IsNaN(pathCost) || double.IsInfinity(pathCost))
            {
                continue;
            }

            candidates.Add(new ExecutableSubTaskCandidate(task, nextSubTask, pathCost));
        }

        return candidates
            .OrderByDescending(candidate => candidate.Task.Priority)
            .ThenBy(candidate => candidate.PathCost)
            .ThenBy(candidate => candidate.CreatedAtMilliseconds)
            .ThenBy(candidate => candidate.Task.TaskId)
            .FirstOrDefault();
    }

    private async Task<double> CalculateExecutionQueueLikePathCostAsync(
        Robot robot,
        Guid mapId,
        PathGraph graph,
        string currentNodeCode,
        double currentTheta,
        RobotTask task,
        RobotSubTask subTask,
        CancellationToken ct)
    {
        if (!graph.Nodes.TryGetValue(subTask.EndNodeId, out var targetNode))
        {
            return double.MaxValue;
        }

        var startNode = graph.Nodes.Values.FirstOrDefault(node =>
            string.Equals(node.NodeCode, currentNodeCode, StringComparison.OrdinalIgnoreCase));
        if (startNode == null)
        {
            return double.MaxValue;
        }

        if (startNode.NodeId == targetNode.NodeId)
        {
            return 0d;
        }

        var request = new PathRequest
        {
            RobotId = robot.RobotId,
            MapId = mapId,
            StartNodeId = startNode.NodeId,
            EndNodeId = targetNode.NodeId,
            CurrentTheta = currentTheta,
            IsLoaded = !string.IsNullOrWhiteSpace(task.ContainerID),
            Priority = task.Priority,
            BatteryLevel = robot.BatteryLevel ?? 100,
            MovementType = robot.MovementType,
            ForkRadOffsets = robot.ForkRadOffset,
            RequiredEndRad = targetNode.Theta
        };

        try
        {
            var pathResult = await _agvPathService.CalculatePathAsync(request, ct);
            if (!pathResult.Success || double.IsNaN(pathResult.TotalCost) || double.IsInfinity(pathResult.TotalCost))
            {
                return double.MaxValue;
            }

            return pathResult.TotalCost;
        }
        catch
        {
            return double.MaxValue;
        }
    }

    private static List<YieldTargetCandidate> BuildDivergentYieldCandidates(
        PathGraph graph,
        PathNode idleCurrentNode,
        string idleCurrentNodeCode,
        string blockingAnchorNodeCode)
    {
        var visited = new HashSet<Guid> { idleCurrentNode.NodeId };
        var hopByNodeId = new Dictionary<Guid, int> { [idleCurrentNode.NodeId] = 0 };
        var queue = new Queue<Guid>();
        queue.Enqueue(idleCurrentNode.NodeId);

        while (queue.Count > 0)
        {
            var currentId = queue.Dequeue();
            if (!graph.Nodes.TryGetValue(currentId, out var currentNode))
            {
                continue;
            }

            var currentHop = hopByNodeId[currentId];
            var neighborIds = currentNode.OutEdges
                .Select(edge => edge.ToNodeId)
                .Concat(currentNode.InEdges.Select(edge => edge.FromNodeId))
                .Distinct();

            foreach (var neighborId in neighborIds)
            {
                if (!graph.Nodes.ContainsKey(neighborId) || !visited.Add(neighborId))
                {
                    continue;
                }

                hopByNodeId[neighborId] = currentHop + 1;
                queue.Enqueue(neighborId);
            }
        }

        return graph.Nodes.Values
            .Where(node => node.Active && !string.IsNullOrWhiteSpace(node.NodeCode))
            .Where(node => !string.Equals(node.NodeCode, idleCurrentNodeCode, StringComparison.OrdinalIgnoreCase))
            .Where(node => !string.Equals(node.NodeCode, blockingAnchorNodeCode, StringComparison.OrdinalIgnoreCase))
            .Where(node => hopByNodeId.ContainsKey(node.NodeId))
            .Select(node => new YieldTargetCandidate(
                node,
                hopByNodeId[node.NodeId],
                DistanceSquared(idleCurrentNode, node)))
            .OrderBy(candidate => candidate.Hop)
            .ThenBy(candidate => candidate.DistanceSquared)
            .ThenBy(candidate => candidate.Node.NodeCode, StringComparer.OrdinalIgnoreCase)
            .ToList();
    }

    private static PathResource? GetYieldForbiddenResource(
        PathGraph graph,
        Guid nodeId)
    {
        return graph.Resources.FirstOrDefault(resource =>
            !resource.AllowYield &&
            resource.NodeIds.Contains(nodeId));
    }

    private static List<string> DistinctCodesInOrder(IEnumerable<string?> codes)
    {
        var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
        var result = new List<string>();
        foreach (var code in codes)
        {
            if (string.IsNullOrWhiteSpace(code) || !seen.Add(code))
            {
                continue;
            }

            result.Add(code);
        }

        return result;
    }

    private static Dictionary<string, (string FromNodeCode, string ToNodeCode)> BuildEdgeDirectionMap(
        IEnumerable<PathSegmentWithCode> lockCandidates)
    {
        return lockCandidates
            .Where(segment => !string.IsNullOrWhiteSpace(segment.EdgeCode))
            .GroupBy(segment => segment.EdgeCode!, StringComparer.OrdinalIgnoreCase)
            .ToDictionary(
                group => group.Key,
                group =>
                {
                    var preferred = group.FirstOrDefault(segment =>
                        !string.IsNullOrWhiteSpace(segment.FromNodeCode) &&
                        !string.IsNullOrWhiteSpace(segment.ToNodeCode)) ?? group.First();
                    return (preferred.FromNodeCode, preferred.ToNodeCode);
                },
                StringComparer.OrdinalIgnoreCase);
    }

    private async Task<bool> HasAnyExternalLocksAsync(
        string mapCode,
        IReadOnlyCollection<string> nodeCodes,
        IReadOnlyCollection<string> edgeCodes,
        Dictionary<string, (string FromNodeCode, string ToNodeCode)> edgeDirectionMap,
        Guid selfRobotId,
        Guid idleRobotId,
        string targetNodeCode,
        int targetHop,
        CancellationToken ct)
    {
        ct.ThrowIfCancellationRequested();

        if (nodeCodes.Count == 0 && edgeCodes.Count == 0)
        {
            _logger.LogDebug(
                "[让行] 候选路径扫掠锁范围为空,按严格约束跳过: IdleRobot={IdleRobotId}, Target={TargetNodeCode}, Hop={Hop}",
                idleRobotId,
                targetNodeCode,
                targetHop);
            return true;
        }

        var conflictResult = await _trafficControl.CheckPathConflictAsync(
            mapCode,
            nodeCodes,
            edgeCodes,
            selfRobotId,
            edgeDirectionMap.Count > 0 ? edgeDirectionMap : null);

        if (conflictResult.Conflicts.Count == 0 && conflictResult.SameDirectionConflicts.Count == 0)
        {
            return false;
        }

        var conflictResources = conflictResult.Conflicts
            .Select(conflict =>
                conflict.ConflictType == ConflictType.NodeOccupied
                    ? $"N:{conflict.NodeCode}"
                    : $"E:{conflict.EdgeCode}")
            .Concat(conflictResult.SameDirectionConflicts.Select(conflict => $"E:{conflict.EdgeCode}"))
            .Where(resource => !string.IsNullOrWhiteSpace(resource))
            .Distinct(StringComparer.OrdinalIgnoreCase)
            .Take(8)
            .ToList();

        var conflictingRobots = conflictResult.Conflicts
            .Concat(conflictResult.SameDirectionConflicts)
            .Select(conflict => conflict.ConflictingRobotId)
            .Distinct()
            .ToList();

        _logger.LogDebug(
            "[让行] 候选路径扫掠区命中外部资源锁,跳过: IdleRobot={IdleRobotId}, Target={TargetNodeCode}, Hop={Hop}, HardConflicts={HardConflictCount}, SameDirectionConflicts={SameDirectionConflictCount}, ConflictingRobots={ConflictingRobots}, Resources={Resources}",
            idleRobotId,
            targetNodeCode,
            targetHop,
            conflictResult.Conflicts.Count,
            conflictResult.SameDirectionConflicts.Count,
            conflictingRobots,
            conflictResources);
        return true;
    }

    private sealed record IdleRobotTaskSnapshot(
        bool HasInProgressTaskOrSubTask,
        IReadOnlyList<RobotTask> ActiveTasks);

    private sealed record ExecutableSubTaskCandidate(
        RobotTask Task,
        RobotSubTask SubTask,
        double PathCost)
    {
        public long CreatedAtMilliseconds { get; } = Task.CreatedAt.Ticks / TimeSpan.TicksPerMillisecond;
    }

    /// <summary>
    /// 构建让行 VDA5050 Order。
    /// </summary>
    private static int ResolveYieldStartSequenceId(YieldSegmentedPathCache cache)
    {
        if (cache.OrderUpdateId <= 0)
        {
            return 0;
        }

        if (cache.LastSentSequenceId > 0)
        {
            return cache.LastSentSequenceId;
        }

        var inferred = InferYieldLastSentSequenceId(cache);
        cache.LastSentSequenceId = inferred;
        return inferred;
    }

    private static int InferYieldLastSentSequenceId(YieldSegmentedPathCache cache)
    {
        var sequenceId = 0;
        foreach (var junction in cache.JunctionSegments)
        {
            foreach (var resource in junction.ResourceSegments)
            {
                if (!(resource.IsSent || resource.SendStatus == SegmentSendStatus.Sent))
                {
                    return sequenceId;
                }

                sequenceId += resource.Segments.Count * 2;
            }
        }

        return sequenceId;
    }

    private static int GetLastReleasedSequenceId(Domain.Models.VDA5050.Order order, int startSequenceId)
    {
        var lastReleasedNodeSeq = order.Nodes
            .Where(n => n.Released)
            .Select(n => n.SequenceId)
            .DefaultIfEmpty(startSequenceId)
            .Max();

        var lastReleasedEdgeSeq = order.Edges
            .Where(e => e.Released)
            .Select(e => e.SequenceId)
            .DefaultIfEmpty(startSequenceId)
            .Max();

        return Math.Max(lastReleasedNodeSeq, lastReleasedEdgeSeq);
    }

    private Domain.Models.VDA5050.Order BuildYieldOrder(
        Robot robot,
        string orderId,
        int headerId,
        int orderUpdateId,
        List<PathSegmentWithCode> segments,
        PathGraph graph,
        string mapCode,
        int startSequenceId,
        bool isFinalDispatch)
    {
        var nodes = new List<Node>();
        var edges = new List<Edge>();
        var sequenceId = Math.Max(0, startSequenceId);
        var coordinateScale = robot.CoordinateScale > 0 ? robot.CoordinateScale : 1d;

        for (var i = 0; i < segments.Count; i++)
        {
            var seg = segments[i];

            // 添加起点节点(仅第一段)
            if (i == 0 && graph.Nodes.TryGetValue(seg.FromNodeId, out var fromNode))
            {
                nodes.Add(new Node
                {
                    NodeId = seg.FromNodeCode,
                    SequenceId = sequenceId,
                    Released = true,
                    NodeDescription = "Yield start",
                    NodePosition = new NodePosition
                    {
                        X = fromNode.X / coordinateScale,
                        Y = fromNode.Y / coordinateScale,
                        MapId = mapCode,
                        AllowedDeviationXY = fromNode.MaxCoordinateOffset ?? PositionConstants.AllowedDeviationPosition / coordinateScale
                    },
                    Actions = new List<Domain.Models.VDA5050.Action>()
                });
            }

            // 添加边
            var edgeSequenceId = sequenceId + 1;
            var nodeSequenceId = sequenceId + 2;
            var startNodeCode = nodes.Count > 0 ? nodes[^1].NodeId : seg.FromNodeCode;

            edges.Add(new Edge
            {
                EdgeId = seg.EdgeCode,
                SequenceId = edgeSequenceId,
                Released = true,
                StartNodeId = startNodeCode,
                EndNodeId = seg.ToNodeCode,
                MaxSpeed = seg.MaxSpeed,
                Orientation = seg.Angle
            });

            // 添加终点节点
            if (graph.Nodes.TryGetValue(seg.ToNodeId, out var toNode))
            {
                nodes.Add(new Node
                {
                    NodeId = seg.ToNodeCode,
                    SequenceId = nodeSequenceId,
                    Released = true,
                    NodeDescription = i == segments.Count - 1
                        ? (isFinalDispatch ? "Yield target" : "Yield waypoint")
                        : "Yield waypoint",
                    NodePosition = new NodePosition
                    {
                        X = toNode.X / coordinateScale,
                        Y = toNode.Y / coordinateScale,
                        MapId = mapCode,
                        AllowedDeviationXY = toNode.MaxCoordinateOffset ?? PositionConstants.AllowedDeviationPosition / coordinateScale
                    },
                    Actions = new List<Domain.Models.VDA5050.Action>()
                });
            }

            sequenceId = nodeSequenceId;
        }

        return new Domain.Models.VDA5050.Order
        {
            HeaderId = headerId,
            Timestamp = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffzzz"),
            Version = robot.ProtocolVersion,
            Manufacturer = robot.RobotManufacturer,
            SerialNumber = robot.RobotSerialNumber,
            ZoneSetId = mapCode,
            OrderId = orderId,
            OrderUpdateId = orderUpdateId,
            Nodes = nodes,
            Edges = edges
        };
    }

    private sealed record YieldTargetCandidate(PathNode Node, int Hop, double DistanceSquared);
}