From d2f410e1149597b9743c5e195f6b54a1504cf2d4 Mon Sep 17 00:00:00 2001
From: Junjie <fallin.jie@qq.com>
Date: 星期五, 20 三月 2026 20:18:26 +0800
Subject: [PATCH] #

---
 src/main/java/com/zy/common/utils/NavigateUtils.java |  866 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 files changed, 842 insertions(+), 24 deletions(-)

diff --git a/src/main/java/com/zy/common/utils/NavigateUtils.java b/src/main/java/com/zy/common/utils/NavigateUtils.java
index dde22c1..152b125 100644
--- a/src/main/java/com/zy/common/utils/NavigateUtils.java
+++ b/src/main/java/com/zy/common/utils/NavigateUtils.java
@@ -4,6 +4,7 @@
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -11,17 +12,22 @@
 import com.zy.asrs.domain.path.StationPathProfileConfig;
 import com.zy.asrs.domain.path.StationPathResolvedPolicy;
 import com.zy.asrs.domain.path.StationPathRuleConfig;
+import com.zy.asrs.domain.vo.StationTaskTraceSegmentVo;
+import com.zy.asrs.entity.BasStationOpt;
 import com.zy.asrs.domain.vo.StationTaskTraceVo;
 import com.zy.asrs.domain.vo.StationCycleCapacityVo;
 import com.zy.asrs.domain.vo.StationCycleLoopVo;
 import com.zy.asrs.entity.BasDevp;
 import com.zy.asrs.entity.BasStation;
+import com.zy.asrs.service.BasStationOptService;
 import com.zy.asrs.service.BasDevpService;
 import com.zy.asrs.service.BasStationService;
 import com.zy.asrs.service.StationCycleCapacityService;
 import com.zy.asrs.service.StationPathPolicyService;
 import com.zy.core.News;
 import com.zy.core.model.StationObjModel;
+import com.zy.core.model.command.StationCommand;
+import com.zy.core.enums.StationCommandType;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Component;
 
@@ -39,6 +45,9 @@
 import com.zy.core.thread.StationThread;
 import com.zy.core.trace.StationTaskTraceRegistry;
 
+import java.util.Date;
+import java.util.LinkedHashMap;
+
 @Component
 public class NavigateUtils {
 
@@ -50,9 +59,12 @@
     private static final double WAIT_ISSUED_RESERVE_SECONDS = 8.0d;
     private static final double WAIT_PENDING_QUEUE_SECONDS = 5.0d;
     private static final double WAIT_RUN_BLOCK_SECONDS = 30.0d;
+    private static final int DEADLOCK_PREFIX_LOOKAHEAD = 6;
 
     @Autowired
     private BasStationService basStationService;
+    @Autowired
+    private BasStationOptService basStationOptService;
     @Autowired
     private StationPathPolicyService stationPathPolicyService;
     @Autowired
@@ -61,6 +73,21 @@
     private StationTaskTraceRegistry stationTaskTraceRegistry;
 
     public synchronized List<NavigateNode> calcByStationId(Integer startStationId, Integer endStationId) {
+        return calcByStationId(startStationId, endStationId, null, false);
+    }
+
+    public synchronized List<NavigateNode> calcByStationId(Integer startStationId, Integer endStationId, Integer currentTaskNo) {
+        return calcByStationId(startStationId, endStationId, currentTaskNo, false);
+    }
+
+    public synchronized List<NavigateNode> calcReachablePathByStationId(Integer startStationId, Integer endStationId) {
+        return calcByStationId(startStationId, endStationId, null, true);
+    }
+
+    private synchronized List<NavigateNode> calcByStationId(Integer startStationId,
+                                                            Integer endStationId,
+                                                            Integer currentTaskNo,
+                                                            boolean reachabilityOnly) {
         BasStation startStation = basStationService.getById(startStationId);
         if (startStation == null) {
             throw new CoolException("鏈壘鍒拌 璧风偣 瀵瑰簲鐨勭珯鐐规暟鎹�");
@@ -114,7 +141,9 @@
 
         startTime = System.currentTimeMillis();
         News.info("[WCS Debug] 绔欑偣璺緞鏉冮噸寮�濮嬪垎鏋�,startStationId={},endStationId={}", startStationId, endStationId);
-        List<NavigateNode> list = findStationBestPathTwoStage(allList, resolvedPolicy);
+        List<NavigateNode> list = reachabilityOnly
+                ? findStationReachablePath(allList, resolvedPolicy, startStationId, endStationId)
+                : findStationBestPathTwoStage(allList, resolvedPolicy, currentTaskNo, startStationId, endStationId);
         News.info("[WCS Debug] 绔欑偣璺緞鏉冮噸鍒嗘瀽瀹屾垚锛岃�楁椂锛歿}ms", System.currentTimeMillis() - startTime);
 
         //鍘婚噸
@@ -272,7 +301,42 @@
         return new StationPathResolvedPolicy();
     }
 
-    private List<NavigateNode> findStationBestPathTwoStage(List<List<NavigateNode>> allList, StationPathResolvedPolicy resolvedPolicy) {
+    private List<NavigateNode> findStationReachablePath(List<List<NavigateNode>> allList,
+                                                        StationPathResolvedPolicy resolvedPolicy,
+                                                        Integer startStationId,
+                                                        Integer endStationId) {
+        if (allList == null || allList.isEmpty()) {
+            return new ArrayList<>();
+        }
+
+        StationPathRuleConfig ruleConfig = resolvedPolicy.getRuleConfig() == null
+                ? new StationPathRuleConfig()
+                : resolvedPolicy.getRuleConfig();
+
+        List<List<NavigateNode>> filteredCandidates = applyRuleFilters(allList, ruleConfig, true);
+        if (filteredCandidates.isEmpty() && hasWaypoint(ruleConfig) && !strictWaypoint(ruleConfig)) {
+            filteredCandidates = applyRuleFilters(allList, ruleConfig, false);
+            News.info("[WCS Debug] 绔欑偣璺緞鍙揪鎬ц鍒欏凡闄嶇骇锛屽拷鐣ュ叧閿�旂粡鐐圭害鏉熷悗閲嶈瘯");
+        }
+        if (filteredCandidates.isEmpty()) {
+            if (resolvedPolicy.matchedRule()) {
+                News.warn("绔欑偣璺緞瑙勫垯鍛戒腑浣嗘棤鍙揪璺緞锛宺uleCode={},startStationId={},endStationId={}",
+                        resolvedPolicy.getRuleEntity() == null ? "" : resolvedPolicy.getRuleEntity().getRuleCode(),
+                        startStationId, endStationId);
+                return new ArrayList<>();
+            }
+            filteredCandidates = allList;
+        }
+
+        filteredCandidates.sort((left, right) -> compareReachabilityPath(left, right));
+        return filteredCandidates.isEmpty() ? new ArrayList<>() : filteredCandidates.get(0);
+    }
+
+    private List<NavigateNode> findStationBestPathTwoStage(List<List<NavigateNode>> allList,
+                                                           StationPathResolvedPolicy resolvedPolicy,
+                                                           Integer currentTaskNo,
+                                                           Integer startStationId,
+                                                           Integer endStationId) {
         if (allList == null || allList.isEmpty()) {
             return new ArrayList<>();
         }
@@ -310,12 +374,19 @@
 
         Map<Integer, StationProtocol> statusMap = loadStationStatusMap();
         Map<Integer, Double> stationLoopLoadMap = loadStationLoopLoadMap();
-        StationTrafficSnapshot trafficSnapshot = loadStationTrafficSnapshot(statusMap);
+        StationTrafficSnapshot trafficSnapshot = loadStationTrafficSnapshot(statusMap, currentTaskNo);
+        LoopMergeGuardContext loopMergeGuardContext = loadLoopMergeGuardContext();
+        Set<LoopMergeEntry> mandatoryLoopMergeEntrySet = resolveMandatoryLoopMergeEntrySet(filteredCandidates, loopMergeGuardContext);
         Set<Integer> outStationIdSet = loadAllOutStationIdSet();
         List<PathCandidateMetrics> metricsList = new ArrayList<>();
         int skippedByOtherOutStation = 0;
+        int skippedByLoopMergeGuard = 0;
         for (List<NavigateNode> path : filteredCandidates) {
             if (path == null || path.isEmpty()) {
+                continue;
+            }
+            if (!isLoopMergePathAllowed(path, statusMap, trafficSnapshot, loopMergeGuardContext, mandatoryLoopMergeEntrySet)) {
+                skippedByLoopMergeGuard++;
                 continue;
             }
             PathCandidateMetrics metrics = buildCandidateMetrics(path, statusMap, stationLoopLoadMap, trafficSnapshot, profileConfig, ruleConfig, globalPolicy, outStationIdSet);
@@ -328,8 +399,10 @@
         if (metricsList.isEmpty()) {
             if (globalPolicy.forceSkipPassOtherOutStation && skippedByOtherOutStation > 0) {
                 News.warn("[WCS Debug] 绔欑偣璺緞鍊欓�夊叏閮ㄨ杩囨护锛屽洜缁忚繃鍏朵粬鍑哄簱绔欑偣,startStationId={},endStationId={}",
-                        resolvedPolicy.getRuleEntity() == null ? null : resolvedPolicy.getRuleEntity().getStartStationId(),
-                        resolvedPolicy.getRuleEntity() == null ? null : resolvedPolicy.getRuleEntity().getEndStationId());
+                        startStationId, endStationId);
+            } else if (skippedByLoopMergeGuard > 0) {
+                News.warn("[WCS Debug] 绔欑偣璺緞鍊欓�夊叏閮ㄨ杩囨护锛屽洜鍒嗗弶鍙f彃鍏ョ幆绾夸富骞蹭細褰卞搷涓诲共閬�,startStationId={},endStationId={}",
+                        startStationId, endStationId);
             }
             return new ArrayList<>();
         }
@@ -592,6 +665,7 @@
         metrics.congestionScore = calcCongestionScore(stationIdList, trafficSnapshot);
         metrics.queueDepthScore = calcQueueDepthScore(stationIdList, trafficSnapshot);
         metrics.estimatedWaitSeconds = calcEstimatedWaitSeconds(stationIdList, trafficSnapshot);
+        metrics.deadlockRiskScore = calcDeadlockRiskScore(stationIdList, trafficSnapshot);
         metrics.runBlockCount = countRunBlockCount(stationIdList, statusMap);
         metrics.loopPenalty = calcLoopPenalty(stationIdList, stationLoopLoadMap);
         metrics.passOtherOutStationCount = countPassOtherOutStations(path, outStationIdSet);
@@ -618,6 +692,7 @@
                 safeDouble(profileConfig.getS2BusyWeight(), 2.0d) * congWeightFactor * metrics.congestionScore
                         + safeDouble(profileConfig.getS2QueueWeight(), 2.5d) * metrics.queueDepthScore
                         + safeDouble(profileConfig.getS2WaitWeight(), 1.5d) * (metrics.estimatedWaitSeconds / 60.0d)
+                        + safeDouble(profileConfig.getS2DeadlockWeight(), 8.0d) * metrics.deadlockRiskScore
                         + safeDouble(profileConfig.getS2RunBlockWeight(), 10.0d) * metrics.runBlockCount
                         + safeDouble(profileConfig.getS2LoopLoadWeight(), 12.0d) * metrics.loopPenalty;
         return metrics;
@@ -639,6 +714,16 @@
             }
         }
         return count;
+    }
+
+    private int compareReachabilityPath(List<NavigateNode> left, List<NavigateNode> right) {
+        int leftLen = left == null ? Integer.MAX_VALUE : left.size();
+        int rightLen = right == null ? Integer.MAX_VALUE : right.size();
+        int leftTurnCount = countTurnCount(left);
+        int rightTurnCount = countTurnCount(right);
+        int leftLiftCount = countLiftTransferCount(left);
+        int rightLiftCount = countLiftTransferCount(right);
+        return compareDouble(leftLen, rightLen, leftTurnCount, rightTurnCount, leftLiftCount, rightLiftCount);
     }
 
     private int countLiftTransferCount(List<NavigateNode> path) {
@@ -693,6 +778,36 @@
             score += trafficSnapshot.estimatedWaitSecondsMap.getOrDefault(stationId, 0.0d);
         }
         return score;
+    }
+
+    private double calcDeadlockRiskScore(List<Integer> stationIdList, StationTrafficSnapshot trafficSnapshot) {
+        if (trafficSnapshot == null || trafficSnapshot.traceRouteList.isEmpty() || stationIdList == null || stationIdList.size() <= 1) {
+            return 0.0d;
+        }
+        List<Integer> candidateFutureStations = distinctPositiveStationIds(stationIdList.subList(1, stationIdList.size()));
+        if (candidateFutureStations.isEmpty()) {
+            return 0.0d;
+        }
+
+        double totalRisk = 0.0d;
+        for (TraceRouteSnapshot routeSnapshot : trafficSnapshot.traceRouteList) {
+            if (routeSnapshot == null) {
+                continue;
+            }
+            OverlapMetrics pendingMetrics = calcOrderedOverlapMetrics(candidateFutureStations, routeSnapshot.pendingStationIds);
+            OverlapMetrics issuedMetrics = calcOrderedOverlapMetrics(candidateFutureStations, routeSnapshot.issuedStationIds);
+
+            totalRisk += pendingMetrics.sequentialRisk * 0.9d;
+            totalRisk += issuedMetrics.sequentialRisk * 1.2d;
+            totalRisk += pendingMetrics.sharedCount * 0.12d;
+            totalRisk += issuedMetrics.sharedCount * 0.18d;
+
+            int currentHitIndex = findFirstOverlapIndex(candidateFutureStations, routeSnapshot.currentStationId);
+            if (currentHitIndex >= 0) {
+                totalRisk += prefixRiskFactor(currentHitIndex) * 1.5d;
+            }
+        }
+        return totalRisk;
     }
 
     private int countRunBlockCount(List<Integer> stationIdList, Map<Integer, StationProtocol> statusMap) {
@@ -887,7 +1002,159 @@
         return stationLoopLoadMap;
     }
 
-    private StationTrafficSnapshot loadStationTrafficSnapshot(Map<Integer, StationProtocol> statusMap) {
+    private LoopMergeGuardContext loadLoopMergeGuardContext() {
+        LoopMergeGuardContext context = new LoopMergeGuardContext();
+        try {
+            if (stationCycleCapacityService == null) {
+                return context;
+            }
+            StationCycleCapacityVo capacityVo = stationCycleCapacityService.getLatestSnapshot();
+            if (capacityVo == null || capacityVo.getLoopList() == null || capacityVo.getLoopList().isEmpty()) {
+                return context;
+            }
+
+            Map<Integer, Set<Integer>> stationGraph = loadUndirectedStationGraph();
+            if (stationGraph.isEmpty()) {
+                return context;
+            }
+
+            for (StationCycleLoopVo loopVo : capacityVo.getLoopList()) {
+                List<Integer> rawStationIdList = loopVo == null ? Collections.emptyList() : loopVo.getStationIdList();
+                List<Integer> loopStationIdList = distinctPositiveStationIds(rawStationIdList);
+                if (loopStationIdList.size() < 3) {
+                    continue;
+                }
+                Set<Integer> loopStationSet = new HashSet<>(loopStationIdList);
+                for (Integer stationId : loopStationSet) {
+                    context.loopStationIdSet.add(stationId);
+                    Set<Integer> graphNeighborSet = stationGraph.getOrDefault(stationId, Collections.emptySet());
+                    Set<Integer> loopNeighborSet = new LinkedHashSet<>();
+                    for (Integer neighborStationId : graphNeighborSet) {
+                        if (neighborStationId != null && loopStationSet.contains(neighborStationId)) {
+                            loopNeighborSet.add(neighborStationId);
+                        }
+                    }
+                    if (!loopNeighborSet.isEmpty()) {
+                        context.loopNeighborMap.computeIfAbsent(stationId, key -> new LinkedHashSet<>()).addAll(loopNeighborSet);
+                    }
+                }
+            }
+        } catch (Exception ignore) {
+        }
+        return context;
+    }
+
+    private Set<LoopMergeEntry> resolveMandatoryLoopMergeEntrySet(List<List<NavigateNode>> candidatePathList,
+                                                                  LoopMergeGuardContext loopMergeGuardContext) {
+        if (candidatePathList == null || candidatePathList.isEmpty()
+                || loopMergeGuardContext == null || loopMergeGuardContext.loopStationIdSet.isEmpty()) {
+            return Collections.emptySet();
+        }
+
+        Set<LoopMergeEntry> intersectionSet = null;
+        for (List<NavigateNode> path : candidatePathList) {
+            Set<LoopMergeEntry> entrySet = extractLoopMergeEntrySet(path, loopMergeGuardContext);
+            if (intersectionSet == null) {
+                intersectionSet = new HashSet<>(entrySet);
+            } else {
+                intersectionSet.retainAll(entrySet);
+            }
+            if (intersectionSet.isEmpty()) {
+                return Collections.emptySet();
+            }
+        }
+        return intersectionSet == null ? Collections.emptySet() : intersectionSet;
+    }
+
+    private Set<LoopMergeEntry> extractLoopMergeEntrySet(List<NavigateNode> path,
+                                                         LoopMergeGuardContext loopMergeGuardContext) {
+        Set<LoopMergeEntry> result = new HashSet<>();
+        if (path == null || path.size() < 2 || loopMergeGuardContext == null || loopMergeGuardContext.loopStationIdSet.isEmpty()) {
+            return result;
+        }
+
+        List<Integer> stationIdList = extractStationIdList(path);
+        for (int i = 1; i < stationIdList.size(); i++) {
+            Integer prevStationId = stationIdList.get(i - 1);
+            Integer currentStationId = stationIdList.get(i);
+            if (prevStationId == null || currentStationId == null) {
+                continue;
+            }
+            if (loopMergeGuardContext.loopStationIdSet.contains(prevStationId)
+                    || !loopMergeGuardContext.loopStationIdSet.contains(currentStationId)) {
+                continue;
+            }
+            result.add(new LoopMergeEntry(prevStationId, currentStationId));
+        }
+        return result;
+    }
+
+    private Map<Integer, Set<Integer>> loadUndirectedStationGraph() {
+        Map<Integer, Set<Integer>> graph = new HashMap<>();
+        List<Integer> levList = loadStationLevList();
+        if (levList.isEmpty()) {
+            return graph;
+        }
+
+        NavigateSolution navigateSolution = new NavigateSolution();
+        for (Integer lev : levList) {
+            if (lev == null) {
+                continue;
+            }
+            List<List<NavigateNode>> stationMap;
+            try {
+                stationMap = navigateSolution.getStationMap(lev);
+            } catch (Exception ignore) {
+                continue;
+            }
+            if (stationMap == null || stationMap.isEmpty()) {
+                continue;
+            }
+
+            for (List<NavigateNode> row : stationMap) {
+                for (NavigateNode node : safeList(row)) {
+                    Integer stationId = extractStationId(node);
+                    if (stationId == null) {
+                        continue;
+                    }
+                    graph.computeIfAbsent(stationId, key -> new LinkedHashSet<>());
+                    List<NavigateNode> nextNodeList = navigateSolution.extend_current_node(stationMap, node);
+                    for (NavigateNode nextNode : safeList(nextNodeList)) {
+                        Integer nextStationId = extractStationId(nextNode);
+                        if (nextStationId == null || stationId.equals(nextStationId)) {
+                            continue;
+                        }
+                        graph.computeIfAbsent(nextStationId, key -> new LinkedHashSet<>());
+                        graph.get(stationId).add(nextStationId);
+                        graph.get(nextStationId).add(stationId);
+                    }
+                }
+            }
+        }
+        return graph;
+    }
+
+    private List<Integer> loadStationLevList() {
+        List<Integer> levList = new ArrayList<>();
+        if (basStationService == null) {
+            return levList;
+        }
+        try {
+            List<BasStation> stationList = basStationService.list(new QueryWrapper<BasStation>().select("station_lev"));
+            Set<Integer> seen = new HashSet<>();
+            for (BasStation station : safeList(stationList)) {
+                Integer lev = station == null ? null : station.getStationLev();
+                if (lev != null && seen.add(lev)) {
+                    levList.add(lev);
+                }
+            }
+            Collections.sort(levList);
+        } catch (Exception ignore) {
+        }
+        return levList;
+    }
+
+    private StationTrafficSnapshot loadStationTrafficSnapshot(Map<Integer, StationProtocol> statusMap, Integer currentTaskNo) {
         StationTrafficSnapshot snapshot = new StationTrafficSnapshot();
         Map<Integer, Integer> busyMap = new HashMap<>();
         Map<Integer, Integer> issuedReserveMap = new HashMap<>();
@@ -906,12 +1173,18 @@
             }
         }
 
-        for (StationTaskTraceVo traceVo : loadActiveTraceList()) {
+        for (StationTaskTraceVo traceVo : loadActiveTraceList(currentTaskNo, statusMap)) {
             if (traceVo == null) {
                 continue;
             }
             List<Integer> pendingStationIds = distinctPositiveStationIds(traceVo.getPendingStationIds());
             List<Integer> issuedStationIds = distinctPositiveStationIds(traceVo.getLatestIssuedSegmentPath());
+            TraceRouteSnapshot routeSnapshot = new TraceRouteSnapshot();
+            routeSnapshot.taskNo = traceVo.getTaskNo();
+            routeSnapshot.currentStationId = traceVo.getCurrentStationId();
+            routeSnapshot.pendingStationIds = pendingStationIds;
+            routeSnapshot.issuedStationIds = issuedStationIds;
+            snapshot.traceRouteList.add(routeSnapshot);
             Set<Integer> pendingSet = new HashSet<>(pendingStationIds);
             for (Integer stationId : issuedStationIds) {
                 if (stationId == null || !pendingSet.contains(stationId)) {
@@ -972,28 +1245,171 @@
         return snapshot;
     }
 
-    private List<StationTaskTraceVo> loadActiveTraceList() {
-        if (stationTaskTraceRegistry == null) {
-            return Collections.emptyList();
-        }
-        List<StationTaskTraceVo> traceList;
-        try {
-            traceList = stationTaskTraceRegistry.listLatestTraces();
-        } catch (Exception ignore) {
-            return Collections.emptyList();
-        }
-        if (traceList == null || traceList.isEmpty()) {
-            return Collections.emptyList();
+    private boolean isLoopMergePathAllowed(List<NavigateNode> path,
+                                           Map<Integer, StationProtocol> statusMap,
+                                           StationTrafficSnapshot trafficSnapshot,
+                                           LoopMergeGuardContext loopMergeGuardContext,
+                                           Set<LoopMergeEntry> mandatoryLoopMergeEntrySet) {
+        if (path == null || path.size() < 2 || loopMergeGuardContext == null || loopMergeGuardContext.loopStationIdSet.isEmpty()) {
+            return true;
         }
 
-        List<StationTaskTraceVo> result = new ArrayList<>();
-        for (StationTaskTraceVo traceVo : traceList) {
-            if (!isPlanningActiveTrace(traceVo)) {
+        List<Integer> stationIdList = extractStationIdList(path);
+        if (stationIdList.size() < 2) {
+            return true;
+        }
+
+        for (int i = 1; i < stationIdList.size(); i++) {
+            Integer prevStationId = stationIdList.get(i - 1);
+            Integer currentStationId = stationIdList.get(i);
+            if (prevStationId == null || currentStationId == null) {
                 continue;
             }
-            result.add(traceVo);
+            if (loopMergeGuardContext.loopStationIdSet.contains(prevStationId)
+                    || !loopMergeGuardContext.loopStationIdSet.contains(currentStationId)) {
+                continue;
+            }
+
+            Set<Integer> trunkNeighborSet = loopMergeGuardContext.loopNeighborMap.getOrDefault(currentStationId, Collections.emptySet());
+            if (trunkNeighborSet.size() < 2) {
+                continue;
+            }
+
+            LoopMergeEntry currentEntry = new LoopMergeEntry(prevStationId, currentStationId);
+            for (Integer trunkNeighborStationId : trunkNeighborSet) {
+                if (isStationOccupiedForLoopMerge(trunkNeighborStationId, statusMap, trafficSnapshot)) {
+                    return false;
+                }
+            }
+            boolean mandatoryEntry = mandatoryLoopMergeEntrySet != null && mandatoryLoopMergeEntrySet.contains(currentEntry);
+            if (!mandatoryEntry && !isLoopTrunkVeryIdle(currentStationId, loopMergeGuardContext, statusMap, trafficSnapshot)) {
+                return false;
+            }
         }
-        return result;
+        return true;
+    }
+
+    private boolean isLoopTrunkVeryIdle(Integer mergeStationId,
+                                        LoopMergeGuardContext loopMergeGuardContext,
+                                        Map<Integer, StationProtocol> statusMap,
+                                        StationTrafficSnapshot trafficSnapshot) {
+        if (mergeStationId == null || loopMergeGuardContext == null) {
+            return false;
+        }
+        Set<Integer> guardStationIdSet = collectLoopNeighborWindow(mergeStationId, loopMergeGuardContext, 2);
+        if (guardStationIdSet.isEmpty()) {
+            return false;
+        }
+        for (Integer stationId : guardStationIdSet) {
+            if (isStationOccupiedForLoopMerge(stationId, statusMap, trafficSnapshot)) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    private Set<Integer> collectLoopNeighborWindow(Integer centerStationId,
+                                                   LoopMergeGuardContext loopMergeGuardContext,
+                                                   int depth) {
+        Set<Integer> visited = new LinkedHashSet<>();
+        if (centerStationId == null || depth < 0 || loopMergeGuardContext == null) {
+            return visited;
+        }
+
+        Set<Integer> frontier = new LinkedHashSet<>();
+        frontier.add(centerStationId);
+        visited.add(centerStationId);
+        for (int step = 0; step < depth; step++) {
+            Set<Integer> nextFrontier = new LinkedHashSet<>();
+            for (Integer stationId : frontier) {
+                for (Integer neighborStationId : loopMergeGuardContext.loopNeighborMap.getOrDefault(stationId, Collections.emptySet())) {
+                    if (neighborStationId != null && visited.add(neighborStationId)) {
+                        nextFrontier.add(neighborStationId);
+                    }
+                }
+            }
+            if (nextFrontier.isEmpty()) {
+                break;
+            }
+            frontier = nextFrontier;
+        }
+        return visited;
+    }
+
+    private boolean isStationOccupiedForLoopMerge(Integer stationId,
+                                                  Map<Integer, StationProtocol> statusMap,
+                                                  StationTrafficSnapshot trafficSnapshot) {
+        if (stationId == null) {
+            return false;
+        }
+
+        StationProtocol protocol = statusMap == null ? null : statusMap.get(stationId);
+        if (protocol != null) {
+            if ((protocol.getTaskNo() != null && protocol.getTaskNo() > 0) || protocol.isRunBlock()) {
+                return true;
+            }
+        }
+
+        if (trafficSnapshot == null) {
+            return false;
+        }
+        if (trafficSnapshot.queueDepthMap.getOrDefault(stationId, 0) > 0) {
+            return true;
+        }
+
+        for (TraceRouteSnapshot routeSnapshot : trafficSnapshot.traceRouteList) {
+            if (routeSnapshot == null) {
+                continue;
+            }
+            if (stationId.equals(routeSnapshot.currentStationId)) {
+                return true;
+            }
+            if (containsStation(routeSnapshot.issuedStationIds, stationId)
+                    || containsStation(routeSnapshot.pendingStationIds, stationId)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private boolean containsStation(List<Integer> stationIdList, Integer stationId) {
+        if (stationId == null || stationIdList == null || stationIdList.isEmpty()) {
+            return false;
+        }
+        for (Integer currentStationId : stationIdList) {
+            if (stationId.equals(currentStationId)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private List<StationTaskTraceVo> loadActiveTraceList(Integer currentTaskNo, Map<Integer, StationProtocol> statusMap) {
+        Map<Integer, StationTaskTraceVo> traceMap = new LinkedHashMap<>();
+        if (stationTaskTraceRegistry != null) {
+            try {
+                List<StationTaskTraceVo> traceList = stationTaskTraceRegistry.listLatestTraces();
+                if (traceList != null) {
+                    for (StationTaskTraceVo traceVo : traceList) {
+                        if (!isPlanningActiveTrace(traceVo)) {
+                            continue;
+                        }
+                        if (currentTaskNo != null && currentTaskNo.equals(traceVo.getTaskNo())) {
+                            continue;
+                        }
+                        if (traceVo.getTaskNo() != null) {
+                            traceMap.put(traceVo.getTaskNo(), traceVo);
+                        }
+                    }
+                }
+            } catch (Exception ignore) {
+            }
+        }
+        Map<Integer, StationTaskTraceVo> fallbackTraceMap = loadFallbackActiveTraceMap(currentTaskNo, statusMap, traceMap.keySet());
+        if (!fallbackTraceMap.isEmpty()) {
+            traceMap.putAll(fallbackTraceMap);
+        }
+        return new ArrayList<>(traceMap.values());
     }
 
     private boolean isPlanningActiveTrace(StationTaskTraceVo traceVo) {
@@ -1004,6 +1420,275 @@
         return StationTaskTraceRegistry.STATUS_WAITING.equals(status)
                 || StationTaskTraceRegistry.STATUS_RUNNING.equals(status)
                 || StationTaskTraceRegistry.STATUS_REROUTED.equals(status);
+    }
+
+    private Map<Integer, StationTaskTraceVo> loadFallbackActiveTraceMap(Integer currentTaskNo,
+                                                                        Map<Integer, StationProtocol> statusMap,
+                                                                        Set<Integer> existingTaskNoSet) {
+        if (basStationOptService == null || statusMap == null || statusMap.isEmpty()) {
+            return Collections.emptyMap();
+        }
+
+        Map<Integer, StationProtocol> activeTaskProtocolMap = new LinkedHashMap<>();
+        for (StationProtocol protocol : statusMap.values()) {
+            if (protocol == null || protocol.getTaskNo() == null || protocol.getTaskNo() <= 0) {
+                continue;
+            }
+            if (!Boolean.TRUE.equals(protocol.isLoading())) {
+                continue;
+            }
+            if (currentTaskNo != null && currentTaskNo.equals(protocol.getTaskNo())) {
+                continue;
+            }
+            if (existingTaskNoSet != null && existingTaskNoSet.contains(protocol.getTaskNo())) {
+                continue;
+            }
+            activeTaskProtocolMap.putIfAbsent(protocol.getTaskNo(), protocol);
+        }
+        if (activeTaskProtocolMap.isEmpty()) {
+            return Collections.emptyMap();
+        }
+
+        List<Integer> taskNoList = new ArrayList<>(activeTaskProtocolMap.keySet());
+        int limit = Math.max(50, taskNoList.size() * 8);
+        List<BasStationOpt> optList;
+        try {
+            optList = basStationOptService.list(new QueryWrapper<BasStationOpt>()
+                    .select("id", "task_no", "send_time", "command", "mode", "send", "target_station_id")
+                    .in("task_no", taskNoList)
+                    .eq("send", 1)
+                    .orderByDesc("send_time")
+                    .last("limit " + limit));
+        } catch (Exception ignore) {
+            return Collections.emptyMap();
+        }
+        if (optList == null || optList.isEmpty()) {
+            return Collections.emptyMap();
+        }
+
+        Map<Integer, List<FallbackMoveCommand>> fallbackCommandMap = new LinkedHashMap<>();
+        for (BasStationOpt opt : optList) {
+            FallbackMoveCommand moveCommand = parseFallbackMoveCommand(opt);
+            if (moveCommand == null || moveCommand.taskNo == null) {
+                continue;
+            }
+            if (!activeTaskProtocolMap.containsKey(moveCommand.taskNo)) {
+                continue;
+            }
+            fallbackCommandMap.computeIfAbsent(moveCommand.taskNo, key -> new ArrayList<>()).add(moveCommand);
+        }
+
+        Map<Integer, StationTaskTraceVo> result = new LinkedHashMap<>();
+        for (Map.Entry<Integer, StationProtocol> entry : activeTaskProtocolMap.entrySet()) {
+            Integer taskNo = entry.getKey();
+            StationProtocol protocol = entry.getValue();
+            StationTaskTraceVo fallbackTrace = buildFallbackTraceVo(taskNo, protocol, fallbackCommandMap.get(taskNo));
+            if (fallbackTrace != null) {
+                result.put(taskNo, fallbackTrace);
+            }
+        }
+        return result;
+    }
+
+    private FallbackMoveCommand parseFallbackMoveCommand(BasStationOpt opt) {
+        if (opt == null || opt.getTaskNo() == null || opt.getTaskNo() <= 0) {
+            return null;
+        }
+        try {
+            StationCommand command = JSON.parseObject(opt.getCommand(), StationCommand.class);
+            if (command == null || command.getCommandType() != StationCommandType.MOVE) {
+                return null;
+            }
+            List<Integer> navigatePath = distinctPositiveStationIds(command.getNavigatePath());
+            if (navigatePath.isEmpty()) {
+                return null;
+            }
+            FallbackMoveCommand item = new FallbackMoveCommand();
+            item.taskNo = opt.getTaskNo();
+            item.traceVersion = command.getTraceVersion();
+            item.segmentNo = command.getSegmentNo();
+            item.segmentCount = command.getSegmentCount();
+            item.stationId = command.getStationId();
+            item.targetStaNo = command.getTargetStaNo();
+            item.navigatePath = navigatePath;
+            item.sendTime = opt.getSendTime();
+            return item;
+        } catch (Exception ignore) {
+            return null;
+        }
+    }
+
+    private StationTaskTraceVo buildFallbackTraceVo(Integer taskNo,
+                                                    StationProtocol protocol,
+                                                    List<FallbackMoveCommand> commandList) {
+        if (taskNo == null || protocol == null || commandList == null || commandList.isEmpty()) {
+            return null;
+        }
+
+        Integer latestTraceVersion = null;
+        long latestTimestamp = 0L;
+        for (FallbackMoveCommand item : commandList) {
+            if (item == null) {
+                continue;
+            }
+            if (item.traceVersion != null && (latestTraceVersion == null || item.traceVersion > latestTraceVersion)) {
+                latestTraceVersion = item.traceVersion;
+            }
+            long ts = item.sendTime == null ? 0L : item.sendTime.getTime();
+            if (ts > latestTimestamp) {
+                latestTimestamp = ts;
+            }
+        }
+
+        List<FallbackMoveCommand> sameTraceCommandList = new ArrayList<>();
+        for (FallbackMoveCommand item : commandList) {
+            if (item == null) {
+                continue;
+            }
+            if (latestTraceVersion == null || latestTraceVersion.equals(item.traceVersion)) {
+                sameTraceCommandList.add(item);
+            }
+        }
+        sameTraceCommandList.sort((a, b) -> {
+            int av = a.segmentNo == null ? Integer.MAX_VALUE : a.segmentNo;
+            int bv = b.segmentNo == null ? Integer.MAX_VALUE : b.segmentNo;
+            if (av != bv) {
+                return Integer.compare(av, bv);
+            }
+            long at = a.sendTime == null ? 0L : a.sendTime.getTime();
+            long bt = b.sendTime == null ? 0L : b.sendTime.getTime();
+            return Long.compare(at, bt);
+        });
+
+        List<Integer> issuedPath = new ArrayList<>();
+        List<StationTaskTraceSegmentVo> segmentList = new ArrayList<>();
+        FallbackMoveCommand latestCommand = null;
+        for (FallbackMoveCommand item : sameTraceCommandList) {
+            if (item == null || item.navigatePath == null || item.navigatePath.isEmpty()) {
+                continue;
+            }
+            appendMergedPath(issuedPath, item.navigatePath);
+            segmentList.add(toTraceSegment(item));
+            if (latestCommand == null || compareFallbackCommand(item, latestCommand) > 0) {
+                latestCommand = item;
+            }
+        }
+        if (issuedPath.isEmpty()) {
+            return null;
+        }
+
+        Integer currentStationId = protocol.getStationId();
+        List<Integer> passedStationIds = new ArrayList<>();
+        List<Integer> pendingStationIds = new ArrayList<>();
+        if (currentStationId != null) {
+            int currentIndex = issuedPath.indexOf(currentStationId);
+            if (currentIndex >= 0) {
+                passedStationIds = copyIntegerSubList(issuedPath, 0, currentIndex);
+                pendingStationIds = copyIntegerSubList(issuedPath, currentIndex + 1, issuedPath.size());
+            } else {
+                pendingStationIds = new ArrayList<>(issuedPath);
+            }
+        } else {
+            pendingStationIds = new ArrayList<>(issuedPath);
+        }
+
+        StationTaskTraceVo vo = new StationTaskTraceVo();
+        vo.setTaskNo(taskNo);
+        vo.setThreadImpl("DB_FALLBACK");
+        vo.setStatus(StationTaskTraceRegistry.STATUS_RUNNING);
+        vo.setTraceVersion(latestTraceVersion == null ? 1 : latestTraceVersion);
+        vo.setStartStationId(issuedPath.isEmpty() ? null : issuedPath.get(0));
+        vo.setCurrentStationId(currentStationId);
+        vo.setFinalTargetStationId(protocol.getTargetStaNo() != null ? protocol.getTargetStaNo()
+                : latestCommand == null ? null : latestCommand.targetStaNo);
+        vo.setBlockedStationId(null);
+        vo.setFullPathStationIds(new ArrayList<>(issuedPath));
+        vo.setIssuedStationIds(new ArrayList<>(issuedPath));
+        vo.setPassedStationIds(passedStationIds);
+        vo.setPendingStationIds(pendingStationIds);
+        vo.setLatestIssuedSegmentPath(latestCommand == null ? Collections.emptyList() : new ArrayList<>(latestCommand.navigatePath));
+        vo.setSegmentList(segmentList);
+        vo.setIssuedSegmentCount(segmentList.size());
+        vo.setTotalSegmentCount(latestCommand == null || latestCommand.segmentCount == null
+                ? segmentList.size()
+                : latestCommand.segmentCount);
+        vo.setUpdatedAt(latestTimestamp > 0L ? latestTimestamp : System.currentTimeMillis());
+        vo.setEvents(Collections.emptyList());
+        return vo;
+    }
+
+    private int compareFallbackCommand(FallbackMoveCommand a, FallbackMoveCommand b) {
+        int av = a == null || a.segmentNo == null ? Integer.MIN_VALUE : a.segmentNo;
+        int bv = b == null || b.segmentNo == null ? Integer.MIN_VALUE : b.segmentNo;
+        if (av != bv) {
+            return Integer.compare(av, bv);
+        }
+        long at = a == null || a.sendTime == null ? 0L : a.sendTime.getTime();
+        long bt = b == null || b.sendTime == null ? 0L : b.sendTime.getTime();
+        return Long.compare(at, bt);
+    }
+
+    private StationTaskTraceSegmentVo toTraceSegment(FallbackMoveCommand item) {
+        StationTaskTraceSegmentVo segmentVo = new StationTaskTraceSegmentVo();
+        if (item == null) {
+            return segmentVo;
+        }
+        segmentVo.setSegmentNo(item.segmentNo);
+        segmentVo.setSegmentCount(item.segmentCount);
+        segmentVo.setStationId(item.stationId);
+        segmentVo.setTargetStationId(item.targetStaNo);
+        segmentVo.setSegmentPath(item.navigatePath == null ? Collections.emptyList() : new ArrayList<>(item.navigatePath));
+        segmentVo.setIssued(Boolean.TRUE);
+        return segmentVo;
+    }
+
+    private void appendMergedPath(List<Integer> target, List<Integer> source) {
+        if (target == null || source == null || source.isEmpty()) {
+            return;
+        }
+        if (target.isEmpty()) {
+            target.addAll(source);
+            return;
+        }
+        int overlap = 0;
+        int maxOverlap = Math.min(target.size(), source.size());
+        for (int size = maxOverlap; size >= 1; size--) {
+            boolean matched = true;
+            for (int i = 0; i < size; i++) {
+                Integer left = target.get(target.size() - size + i);
+                Integer right = source.get(i);
+                if (left == null || !left.equals(right)) {
+                    matched = false;
+                    break;
+                }
+            }
+            if (matched) {
+                overlap = size;
+                break;
+            }
+        }
+        for (int i = overlap; i < source.size(); i++) {
+            Integer stationId = source.get(i);
+            if (stationId != null) {
+                target.add(stationId);
+            }
+        }
+    }
+
+    private List<Integer> copyIntegerSubList(List<Integer> source, int fromIndex, int toIndex) {
+        if (source == null || source.isEmpty()) {
+            return new ArrayList<>();
+        }
+        int from = Math.max(0, fromIndex);
+        int to = Math.min(source.size(), Math.max(from, toIndex));
+        List<Integer> result = new ArrayList<>();
+        for (int i = from; i < to; i++) {
+            Integer value = source.get(i);
+            if (value != null) {
+                result.add(value);
+            }
+        }
+        return result;
     }
 
     private List<Integer> distinctPositiveStationIds(List<Integer> stationIdList) {
@@ -1028,6 +1713,79 @@
             return;
         }
         target.put(stationId, target.getOrDefault(stationId, 0) + delta);
+    }
+
+    private OverlapMetrics calcOrderedOverlapMetrics(List<Integer> candidateStations, List<Integer> routeStations) {
+        OverlapMetrics metrics = new OverlapMetrics();
+        if (candidateStations == null || candidateStations.isEmpty() || routeStations == null || routeStations.isEmpty()) {
+            return metrics;
+        }
+
+        Map<Integer, Integer> routeIndexMap = new HashMap<>();
+        for (int i = 0; i < routeStations.size(); i++) {
+            Integer stationId = routeStations.get(i);
+            if (stationId != null && !routeIndexMap.containsKey(stationId)) {
+                routeIndexMap.put(stationId, i);
+            }
+        }
+        if (routeIndexMap.isEmpty()) {
+            return metrics;
+        }
+
+        for (int i = 0; i < candidateStations.size(); i++) {
+            Integer stationId = candidateStations.get(i);
+            if (stationId != null && routeIndexMap.containsKey(stationId)) {
+                metrics.sharedCount++;
+            }
+        }
+
+        for (int candidateStart = 0; candidateStart < candidateStations.size(); candidateStart++) {
+            Integer firstStation = candidateStations.get(candidateStart);
+            Integer routeStart = routeIndexMap.get(firstStation);
+            if (routeStart == null) {
+                continue;
+            }
+
+            int length = 1;
+            int prevRouteIndex = routeStart;
+            for (int j = candidateStart + 1; j < candidateStations.size(); j++) {
+                Integer nextRouteIndex = routeIndexMap.get(candidateStations.get(j));
+                if (nextRouteIndex == null || nextRouteIndex.intValue() != prevRouteIndex + 1) {
+                    break;
+                }
+                length++;
+                prevRouteIndex = nextRouteIndex;
+            }
+
+            double risk = length * prefixRiskFactor(candidateStart);
+            if (risk > metrics.sequentialRisk) {
+                metrics.sequentialRisk = risk;
+            }
+        }
+        return metrics;
+    }
+
+    private int findFirstOverlapIndex(List<Integer> stationIdList, Integer targetStationId) {
+        if (stationIdList == null || stationIdList.isEmpty() || targetStationId == null) {
+            return -1;
+        }
+        for (int i = 0; i < stationIdList.size(); i++) {
+            Integer stationId = stationIdList.get(i);
+            if (targetStationId.equals(stationId)) {
+                return i;
+            }
+        }
+        return -1;
+    }
+
+    private double prefixRiskFactor(int candidateIndex) {
+        if (candidateIndex < 0) {
+            return 0.0d;
+        }
+        if (candidateIndex >= DEADLOCK_PREFIX_LOOKAHEAD) {
+            return 0.15d;
+        }
+        return (double) (DEADLOCK_PREFIX_LOOKAHEAD - candidateIndex) / (double) DEADLOCK_PREFIX_LOOKAHEAD;
     }
 
     private int compareDouble(double left, double right, int thenLeft1, int thenRight1, int thenLeft2, int thenRight2) {
@@ -1067,6 +1825,7 @@
         private double congestionScore;
         private double queueDepthScore;
         private double estimatedWaitSeconds;
+        private double deadlockRiskScore;
         private int runBlockCount;
         private int softDeviationCount;
         private double loopPenalty;
@@ -1078,6 +1837,65 @@
         private final Map<Integer, Double> congestionScoreMap = new HashMap<>();
         private final Map<Integer, Integer> queueDepthMap = new HashMap<>();
         private final Map<Integer, Double> estimatedWaitSecondsMap = new HashMap<>();
+        private final List<TraceRouteSnapshot> traceRouteList = new ArrayList<>();
+    }
+
+    private static class TraceRouteSnapshot {
+        private Integer taskNo;
+        private Integer currentStationId;
+        private List<Integer> pendingStationIds = Collections.emptyList();
+        private List<Integer> issuedStationIds = Collections.emptyList();
+    }
+
+    private static class OverlapMetrics {
+        private int sharedCount;
+        private double sequentialRisk;
+    }
+
+    private static class FallbackMoveCommand {
+        private Integer taskNo;
+        private Integer traceVersion;
+        private Integer segmentNo;
+        private Integer segmentCount;
+        private Integer stationId;
+        private Integer targetStaNo;
+        private List<Integer> navigatePath = Collections.emptyList();
+        private Date sendTime;
+    }
+
+    private static class LoopMergeGuardContext {
+        private final Set<Integer> loopStationIdSet = new HashSet<>();
+        private final Map<Integer, Set<Integer>> loopNeighborMap = new HashMap<>();
+    }
+
+    private static class LoopMergeEntry {
+        private final Integer fromStationId;
+        private final Integer toStationId;
+
+        private LoopMergeEntry(Integer fromStationId, Integer toStationId) {
+            this.fromStationId = fromStationId;
+            this.toStationId = toStationId;
+        }
+
+        @Override
+        public boolean equals(Object obj) {
+            if (this == obj) {
+                return true;
+            }
+            if (!(obj instanceof LoopMergeEntry)) {
+                return false;
+            }
+            LoopMergeEntry other = (LoopMergeEntry) obj;
+            return (fromStationId == null ? other.fromStationId == null : fromStationId.equals(other.fromStationId))
+                    && (toStationId == null ? other.toStationId == null : toStationId.equals(other.toStationId));
+        }
+
+        @Override
+        public int hashCode() {
+            int result = fromStationId == null ? 0 : fromStationId.hashCode();
+            result = 31 * result + (toStationId == null ? 0 : toStationId.hashCode());
+            return result;
+        }
     }
 
     private static class PathGlobalPolicy {

--
Gitblit v1.9.1