Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.
HTML agent-skillsai-agentsarchitecture-diagramclaude-codeclaude-skillscodexcoding-agentsdeepseek-harnessdeveloper-toolsdiagramsdiagrams-as-codedsh-pluginflowchartllmmermaidopencodesequence-diagramsoftware-architecturesystem-designvisualization
feat(architecture): diagnose clean-route detours before delivery
tt-a1i0492922df104
diff --git a/archify/recipes/scenarios.mjs b/archify/recipes/scenarios.mjsindex 137cce05..d6660ae5 100644--- a/archify/recipes/scenarios.mjs+++ b/archify/recipes/scenarios.mjs@@ -273,7 +273,7 @@ const RAW_RECIPES = ['desktop viewport budget for the complete page, including header and necessary cards','validate after each edit, then inspect the final HTML in a browser',],- prompt: 'Use Archify to repair this existing diagram while preserving its diagram type, topology, meaningful labels, and presentation settings. Follow references/authoring-contract.md in this order: (1) schema and missing/invalid meta.quality_profile; (2) node overlap or out-of-range placement; (3) edge-through-node and endpoint-direction errors; (4) crossings, ambiguous corridors, border runs, and route rhythm; (5) labels: label-to-node, label-to-label, then label-to-route clearance. Run validate after every edit and use diagnostics[] code, subject, evidence, and supportedFixes; apply one diagnosed geometry control at a time. Where the current schema supports via, it is an ordered array of absolute SVG [x, y] intermediate points: the route is [start, ...via, end], with start/end supplied by the node anchors. Explicit via points override automatic routing; they are not offsets or a request for automatic obstacle avoidance. For an orthogonal repair, align adjacent points on the same x or y and make the first/final segment respect fromSide/toSide; use only controls supported by the current diagram mode. Follow references/delivery-contract.md for the viewport budget: check 1440×900, 1600×1000, 1920×1080, and 2048×1320; require document.documentElement.scrollWidth <= window.innerWidth. Prefer document.documentElement.scrollHeight <= window.innerHeight, but preserve a Reader-declared readable vertical page scroll when visual-check explicitly accepts it after reaching the projected-text floor. Budget the entire page, including header, diagram, and necessary cards. Repair every other overflow by removing only redundant content or compacting spacing first; do not hide overflow, clip content, introduce an internal diagram scroller, stretch the SVG, or shrink typography to force a pass. Inspect readability and vertical balance at the largest viewport. Validate, then deliver and inspect the final HTML; report browser evidence and visual review truthfully.',+ prompt: 'Use Archify to repair this existing diagram while preserving its diagram type, topology, meaningful labels, and presentation settings. Follow references/authoring-contract.md in this order: (1) schema and missing/invalid meta.quality_profile; (2) node overlap or out-of-range placement; (3) edge-through-node and endpoint-direction errors; (4) crossings, ambiguous corridors, border runs, excessive detours, and route rhythm; (5) labels: label-to-node, label-to-label, then label-to-route clearance. Run validate after every edit and use diagnostics[] code, subject, evidence, and supportedFixes; apply one diagnosed geometry control at a time. Where the current schema supports via, it is an ordered array of absolute SVG [x, y] intermediate points: the route is [start, ...via, end], with start/end supplied by the node anchors. Explicit via points override automatic routing; they are not offsets or a request for automatic obstacle avoidance. For an orthogonal repair, align adjacent points on the same x or y and make the first/final segment respect fromSide/toSide; use only controls supported by the current diagram mode. Follow references/delivery-contract.md for the viewport budget: check 1440×900, 1600×1000, 1920×1080, and 2048×1320; require document.documentElement.scrollWidth <= window.innerWidth. Prefer document.documentElement.scrollHeight <= window.innerHeight, but preserve a Reader-declared readable vertical page scroll when browser-check explicitly accepts it after reaching the projected-text floor. Budget the entire page, including header, diagram, and necessary cards. Repair every other overflow by removing only redundant content or compacting spacing first; do not hide overflow, clip content, introduce an internal diagram scroller, stretch the SVG, or shrink typography to force a pass. Let finalize run the required browser evidence; run perceptual visual review only when requested or escalated by the delivery contract.',},zh: {title: '布局修复', question: '现有图为什么仍然溢出、重叠或连线穿过节点,应该先修什么?',@@ -286,7 +286,7 @@ const RAW_RECIPES = ['包含标题和必要卡片的整页桌面视口预算','每次修改后 validate,最终在浏览器中检查 HTML',],- prompt: '用 Archify 修复这张现有图,保留图表类型、拓扑、有意义的标签和表现设置。遵循 references/authoring-contract.md 的顺序:(1) schema 错误及缺失或无效的 meta.quality_profile;(2) 节点重叠或越界;(3) 连线穿过节点及端点方向错误;(4) 交叉、含混的共享通道、贴边走线和转弯节奏;(5) 标签与节点、标签与标签、标签与连线的间距。每次修改后运行 validate,依据 diagnostics[] 的 code、subject、evidence 和 supportedFixes,每次只应用一项有诊断依据的几何控制。当前 schema 支持 via 时,它是按顺序排列的绝对 SVG [x, y] 中间点数组:路径为 [start, ...via, end],起终点由节点锚点提供。显式 via 会覆盖自动路由,不是偏移量,也不会请求自动绕障。修复正交走线时,相邻点应共享 x 或 y,首尾线段应遵守 fromSide/toSide;只使用当前模式支持的控制字段。视口预算遵循 references/delivery-contract.md:检查 1440×900、1600×1000、1920×1080 和 2048×1320,要求 document.documentElement.scrollWidth <= window.innerWidth。优先满足 document.documentElement.scrollHeight <= window.innerHeight;如果 visual-check 明确确认 Reader 已达到投影文字下限并接受可读的页面纵向滚动,则保留该滚动。预算覆盖整页,包括标题、主图和必要卡片。其他溢出先通过移除冗余内容或压缩间距修复,不得靠隐藏溢出、裁切、内部滚动区、拉伸 SVG 或缩小字体强行通过。在最大视口检查可读性和纵向平衡。验证后执行 deliver 并检查最终 HTML,如实报告浏览器证据和视觉检查结果。',+ prompt: '用 Archify 修复这张现有图,保留图表类型、拓扑、有意义的标签和表现设置。遵循 references/authoring-contract.md 的顺序:(1) schema 错误及缺失或无效的 meta.quality_profile;(2) 节点重叠或越界;(3) 连线穿过节点及端点方向错误;(4) 交叉、含混的共享通道、贴边走线、过度绕行和转弯节奏;(5) 标签与节点、标签与标签、标签与连线的间距。每次修改后运行 validate,依据 diagnostics[] 的 code、subject、evidence 和 supportedFixes,每次只应用一项有诊断依据的几何控制。当前 schema 支持 via 时,它是按顺序排列的绝对 SVG [x, y] 中间点数组:路径为 [start, ...via, end],起终点由节点锚点提供。显式 via 会覆盖自动路由,不是偏移量,也不会请求自动绕障。修复正交走线时,相邻点应共享 x 或 y,首尾线段应遵守 fromSide/toSide;只使用当前模式支持的控制字段。视口预算遵循 references/delivery-contract.md:检查 1440×900、1600×1000、1920×1080 和 2048×1320,要求 document.documentElement.scrollWidth <= window.innerWidth。优先满足 document.documentElement.scrollHeight <= window.innerHeight;如果 browser-check 明确确认 Reader 已达到投影文字下限并接受可读的页面纵向滚动,则保留该滚动。预算覆盖整页,包括标题、主图和必要卡片。其他溢出先通过移除冗余内容或压缩间距修复,不得靠隐藏溢出、裁切、内部滚动区、拉伸 SVG 或缩小字体强行通过。让 finalize 执行必需的浏览器证据;只在用户要求或 delivery contract 规定的升级条件下进行感知视觉审阅。',},},];diff --git a/archify/references/authoring-contract.md b/archify/references/authoring-contract.mdindex 318aee0f..1d5f7c11 100644--- a/archify/references/authoring-contract.md+++ b/archify/references/authoring-contract.md@@ -108,6 +108,7 @@ in the generated viewer.- In architecture, data-flow, and lifecycle diagrams, explicit `route: "straight"` requests one direct segment, which may be diagonal when endpoint sides are not pinned. The artifact checker preserves this intent; explicit sides, opaque-node clearance, and other quality gates still apply. `via` takes precedence and retains existing rules, including data-flow's requirement for orthogonal via segments.- Automatic Port Spread is a default renderer behavior for architecture, workflow, data-flow, and lifecycle diagrams. Shared automatic endpoints spread deterministically and symmetrically with a 16px corner gutter. It does not apply to sequence messages, single relationships, or explicit `via`, `channelX`, `channelY`, `labelAt`, or non-`auto` routes.- Showcase route rhythm: every nonzero segment must be at least 8px; every interior segment must be at least 16px. When spread ports are nearly parallel, the router uses a 24px endpoint stub and a 16px outside bridge instead of manufacturing a tiny dogleg.+- Showcase route compactness: an explicit Architecture route fails with `composition/excessive-route-detour` when its orthogonal length is at least 2.5 times an obstacle-aware legal route, adds at least 200px, and sends a control point at least 96px beyond the content envelope. The evidence records both lengths, ratio, excess, bounds, and excursion. Remove an unnecessary `via` or move the diagnosed corridor inward instead of enlarging the canvas. Related relationships that overlap on the same outer corridor by at least 32px are treated as an intentional bus and remain valid.- Shared endpoint corridors are allowed only when they remain semantically unambiguous. Unrelated collinear overlap of 8px or more fails showcase.- Container borders are intentional pass-through geometry, but a long edge running along a structural border is not.- An edge crossing an unrelated opaque node is always a hard failure, independent of quality profile.@@ -221,7 +222,7 @@ Compare diagnostics by code, subject, and stage instead of total count alone.1. Fix missing/invalid `meta.quality_profile` and schema errors.2. Fix node overlap or out-of-range placement.3. Fix edge-through-node and endpoint-direction errors.-4. Fix crossings, ambiguous corridors, border runs, and route rhythm.+4. Fix crossings, ambiguous corridors, border runs, excessive detours, and route rhythm.5. Fix label-to-node, label-to-label, then label-to-route clearance.6. Fix labels that leave the canvas: move the label with `labelAt`/`labelDx`/`labelDy`/`labelSegment`, or widen `meta.viewBox`. Suggested `labelDx`/`labelDy` values replace the authored field; they are not added to it.diff --git a/archify/renderers/architecture/render-architecture.mjs b/archify/renderers/architecture/render-architecture.mjsindex f1b34912..bc353618 100644--- a/archify/renderers/architecture/render-architecture.mjs+++ b/archify/renderers/architecture/render-architecture.mjs@@ -12,6 +12,7 @@ import { translateMessage as i18nText } from '../shared/i18n.mjs';import { gridLayout, resolveComponentPos, validateGridPlacement } from './grid.mjs';import { createRouter } from './routing.mjs';import { placeAutomaticLabels } from './labels.mjs';+import { cleanRouteDetourProblems } from '../shared/route-quality.mjs';import {asArray,isFinitePoint,@@ -665,6 +666,18 @@ function validateArchitecture() {profile: arch.meta?.quality_profile,routeHint: 'move route/via points into a wider corridor or move the component so every turn has room to read'}));+ problems.push(...cleanRouteDetourProblems({+ relations: arch.connections,+ obstacles: components.values(),+ contentRects: [...components.values(), ...boundaries],+ endpointIds: new Set(components.keys()),+ pathFor,+ fromSideFor: (conn) => connectionEndpointSide(conn, 'source'),+ toSideFor: (conn) => connectionEndpointSide(conn, 'target'),+ diagramType: 'architecture',+ relationCollection: 'connections',+ profile: arch.meta?.quality_profile,+ }));// Connection labels must not land on top of components.const labelRects = connectionLabels;diff --git a/archify/renderers/shared/route-quality.mjs b/archify/renderers/shared/route-quality.mjsnew file mode 100644index 00000000..c69cff09--- /dev/null+++ b/archify/renderers/shared/route-quality.mjs@@ -0,0 +1,430 @@+import { recordDiagnostic } from './diagnostics.mjs';+import {+ asArray,+ isFinitePoint,+ normalizeRoutePoints,+ segmentIntersectsRect,+} from './geometry.mjs';++const DEFAULTS = Object.freeze({+ clearance: 2,+ minimumDetourRatio: 2.5,+ minimumExcessLengthPx: 200,+ minimumEmptyExcursionPx: 96,+ maximumObstacleCount: 80,+ sharedCorridorMinimumPx: 32,+});++const OUTWARD = Object.freeze({+ left: [-1, 0],+ right: [1, 0],+ top: [0, -1],+ bottom: [0, 1],+});++function rounded(value) {+ return Math.round(value * 100) / 100;+}++function pointKey(point) {+ return `${point[0]}\u0000${point[1]}`;+}++class MinHeap {+ constructor() {+ this.entries = [];+ }++ push(key, distance) {+ const entry = { key, distance };+ this.entries.push(entry);+ let index = this.entries.length - 1;+ while (index > 0) {+ const parent = Math.floor((index - 1) / 2);+ if (this.entries[parent].distance <= distance) break;+ this.entries[index] = this.entries[parent];+ index = parent;+ }+ this.entries[index] = entry;+ }++ pop() {+ if (!this.entries.length) return null;+ const first = this.entries[0];+ const last = this.entries.pop();+ if (!this.entries.length) return first;+ let index = 0;+ while (true) {+ const left = index * 2 + 1;+ const right = left + 1;+ if (left >= this.entries.length) break;+ const child = right < this.entries.length+ && this.entries[right].distance < this.entries[left].distance ? right : left;+ if (this.entries[child].distance >= last.distance) break;+ this.entries[index] = this.entries[child];+ index = child;+ }+ this.entries[index] = last;+ return first;+ }+}++function orthogonalLength(points) {+ let total = 0;+ for (let index = 0; index < points.length - 1; index += 1) {+ const [x1, y1] = points[index];+ const [x2, y2] = points[index + 1];+ if (x1 !== x2 && y1 !== y2) return null;+ total += Math.abs(x2 - x1) + Math.abs(y2 - y1);+ }+ return total;+}++function inferredSide(points, endpoint) {+ if (points.length < 2) return null;+ const start = endpoint === 'source' ? points[0] : points.at(-2);+ const end = endpoint === 'source' ? points[1] : points.at(-1);+ const dx = end[0] - start[0];+ const dy = end[1] - start[1];+ if (endpoint === 'source') {+ if (dx > 0 && dy === 0) return 'right';+ if (dx < 0 && dy === 0) return 'left';+ if (dy > 0 && dx === 0) return 'bottom';+ if (dy < 0 && dx === 0) return 'top';+ } else {+ if (dx > 0 && dy === 0) return 'left';+ if (dx < 0 && dy === 0) return 'right';+ if (dy > 0 && dx === 0) return 'top';+ if (dy < 0 && dx === 0) return 'bottom';+ }+ return null;+}++function moveOutward(point, side, distance) {+ const [dx, dy] = OUTWARD[side] || [0, 0];+ return [point[0] + dx * distance, point[1] + dy * distance];+}++function expandedRect(rect, clearance) {+ return {+ id: rect.id,+ x: rect.x - clearance,+ y: rect.y - clearance,+ width: rect.width + clearance * 2,+ height: rect.height + clearance * 2,+ };+}++function boundsForRects(rects) {+ const usable = [...rects].filter((rect) => (+ rect && isFinitePoint(rect.x, rect.y, rect.width, rect.height)+ && rect.width >= 0 && rect.height >= 0+ ));+ if (!usable.length) return null;+ const left = Math.min(...usable.map((rect) => rect.x));+ const top = Math.min(...usable.map((rect) => rect.y));+ const right = Math.max(...usable.map((rect) => rect.x + rect.width));+ const bottom = Math.max(...usable.map((rect) => rect.y + rect.height));+ return { left, top, right, bottom, width: right - left, height: bottom - top };+}++function boundsForPoints(points) {+ if (!points.length) return null;+ const xs = points.map(([x]) => x);+ const ys = points.map(([, y]) => y);+ const left = Math.min(...xs);+ const top = Math.min(...ys);+ const right = Math.max(...xs);+ const bottom = Math.max(...ys);+ return { left, top, right, bottom, width: right - left, height: bottom - top };+}++function outsideExcursion(routeBounds, contentBounds) {+ if (!routeBounds || !contentBounds) return null;+ const sides = {+ left: Math.max(0, contentBounds.left - routeBounds.left),+ top: Math.max(0, contentBounds.top - routeBounds.top),+ right: Math.max(0, routeBounds.right - contentBounds.right),+ bottom: Math.max(0, routeBounds.bottom - contentBounds.bottom),+ };+ return { ...sides, maximum: Math.max(...Object.values(sides)) };+}++function pointDistanceFromRect(point, rect) {+ const dx = Math.max(rect.x - point[0], 0, point[0] - (rect.x + rect.width));+ const dy = Math.max(rect.y - point[1], 0, point[1] - (rect.y + rect.height));+ return dx + dy;+}++function emptyControlPointClearance(points, contentRects) {+ const controls = points.slice(1, -1);+ const rects = [...contentRects].filter((rect) => (+ rect && isFinitePoint(rect.x, rect.y, rect.width, rect.height)+ && rect.width >= 0 && rect.height >= 0+ ));+ if (!controls.length || !rects.length) return null;+ const distances = controls.map((point) => Math.min(+ ...rects.map((rect) => pointDistanceFromRect(point, rect)),+ ));+ const maximum = Math.max(...distances);+ return { maximum, point: controls[distances.indexOf(maximum)] };+}++function rectsIntersect(left, right) {+ return left.x <= right.x + right.width+ && left.x + left.width >= right.x+ && left.y <= right.y + right.height+ && left.y + left.height >= right.y;+}++function pointBlocked(point, obstacles) {+ return obstacles.some((rect) => (+ point[0] >= rect.x && point[0] <= rect.x + rect.width+ && point[1] >= rect.y && point[1] <= rect.y + rect.height+ ));+}++function segmentBlocked(start, end, obstacles) {+ return obstacles.some((rect) => segmentIntersectsRect({ start, end }, rect));+}++function shortestGridRoute({ start, end, points, obstacles, fromSide, toSide, clearance, maximumObstacleCount }) {+ if (!OUTWARD[fromSide] || !OUTWARD[toSide]) return null;+ const stubDistance = clearance + 2;+ const startStub = moveOutward(start, fromSide, stubDistance);+ const endStub = moveOutward(end, toSide, stubDistance);+ const routeBounds = boundsForPoints([...points, startStub, endStub]);+ const searchRect = {+ x: routeBounds.left - 24,+ y: routeBounds.top - 24,+ width: routeBounds.width + 48,+ height: routeBounds.height + 48,+ };+ const expanded = [...obstacles]+ .filter((rect) => rect && isFinitePoint(rect.x, rect.y, rect.width, rect.height))+ .map((rect) => expandedRect(rect, clearance))+ .filter((rect) => rectsIntersect(rect, searchRect));+ if (expanded.length > maximumObstacleCount) return null;++ const xs = new Set([startStub[0], endStub[0], ...points.map(([x]) => x)]);+ const ys = new Set([startStub[1], endStub[1], ...points.map(([, y]) => y)]);+ for (const rect of expanded) {+ xs.add(rect.x - 1);+ xs.add(rect.x + rect.width + 1);+ ys.add(rect.y - 1);+ ys.add(rect.y + rect.height + 1);+ }+ const orderedX = [...xs].sort((a, b) => a - b);+ const orderedY = [...ys].sort((a, b) => a - b);+ const nodes = new Map();+ for (const x of orderedX) {+ for (const y of orderedY) {+ const point = [x, y];+ if (!pointBlocked(point, expanded)) nodes.set(pointKey(point), point);+ }+ }+ if (!nodes.has(pointKey(startStub)) || !nodes.has(pointKey(endStub))) return null;++ const adjacency = new Map([...nodes.keys()].map((key) => [key, []]));+ const connectLine = (line) => {+ for (let index = 0; index < line.length - 1; index += 1) {+ const left = line[index];+ const right = line[index + 1];+ if (segmentBlocked(left, right, expanded)) continue;+ const distance = Math.abs(right[0] - left[0]) + Math.abs(right[1] - left[1]);+ const leftKey = pointKey(left);+ const rightKey = pointKey(right);+ adjacency.get(leftKey).push([rightKey, distance]);+ adjacency.get(rightKey).push([leftKey, distance]);+ }+ };+ for (const y of orderedY) {+ connectLine(orderedX.map((x) => nodes.get(pointKey([x, y]))).filter(Boolean));+ }+ for (const x of orderedX) {+ connectLine(orderedY.map((y) => nodes.get(pointKey([x, y]))).filter(Boolean));+ }++ const source = pointKey(startStub);+ const target = pointKey(endStub);+ const distances = new Map([[source, 0]]);+ const previous = new Map();+ const queue = new MinHeap();+ queue.push(source, 0);+ while (queue.entries.length) {+ const next = queue.pop();+ const current = next.key;+ const currentDistance = next.distance;+ if (currentDistance !== distances.get(current)) continue;+ if (current === target) break;+ for (const [neighbor, weight] of adjacency.get(current) || []) {+ const candidate = currentDistance + weight;+ if (candidate >= (distances.get(neighbor) ?? Infinity)) continue;+ distances.set(neighbor, candidate);+ previous.set(neighbor, current);+ queue.push(neighbor, candidate);+ }+ }+ if (!distances.has(target)) return null;+ const reversed = [];+ for (let key = target; key; key = previous.get(key)) {+ reversed.push(nodes.get(key));+ if (key === source) break;+ }+ if (pointKey(reversed.at(-1)) !== source) return null;+ const shortestPoints = normalizeRoutePoints([start, ...reversed.reverse(), end]);+ return {+ points: shortestPoints,+ length: orthogonalLength(shortestPoints),+ obstacleCount: expanded.length,+ };+}++function collinearOverlap(leftStart, leftEnd, rightStart, rightEnd) {+ if (leftStart[0] === leftEnd[0] && rightStart[0] === rightEnd[0]+ && leftStart[0] === rightStart[0]) {+ return Math.max(0, Math.min(Math.max(leftStart[1], leftEnd[1]), Math.max(rightStart[1], rightEnd[1]))+ - Math.max(Math.min(leftStart[1], leftEnd[1]), Math.min(rightStart[1], rightEnd[1])));+ }+ if (leftStart[1] === leftEnd[1] && rightStart[1] === rightEnd[1]+ && leftStart[1] === rightStart[1]) {+ return Math.max(0, Math.min(Math.max(leftStart[0], leftEnd[0]), Math.max(rightStart[0], rightEnd[0]))+ - Math.max(Math.min(leftStart[0], leftEnd[0]), Math.min(rightStart[0], rightEnd[0])));+ }+ return 0;+}++function segmentOutsideContent(start, end, contentBounds) {+ if (!contentBounds) return false;+ const midpoint = [(start[0] + end[0]) / 2, (start[1] + end[1]) / 2];+ return midpoint[0] < contentBounds.left || midpoint[0] > contentBounds.right+ || midpoint[1] < contentBounds.top || midpoint[1] > contentBounds.bottom;+}++function sharesOuterCorridor({ relation, relations, pathFor, points, contentBounds, minimumOverlap }) {+ for (const other of asArray(relations)) {+ if (!other || other === relation) continue;+ const related = relation.from === other.from || relation.from === other.to+ || relation.to === other.from || relation.to === other.to;+ if (!related) continue;+ const otherPoints = normalizeRoutePoints(pathFor(other)?.points || []);+ for (let left = 0; left < points.length - 1; left += 1) {+ if (!segmentOutsideContent(points[left], points[left + 1], contentBounds)) continue;+ for (let right = 0; right < otherPoints.length - 1; right += 1) {+ if (collinearOverlap(points[left], points[left + 1], otherPoints[right], otherPoints[right + 1]) >= minimumOverlap) {+ return true;+ }+ }+ }+ }+ return false;+}++function relationshipSubject(diagramType, relationCollection, relationIndex, relation) {+ return {+ diagramType,+ collection: relationCollection,+ index: relationIndex,+ ...(relation.id ? { id: relation.id } : {}),+ from: relation.from,+ to: relation.to,+ };+}++/**+ * Reject conspicuous authored detours without penalizing routes whose length is+ * explained by opaque-node avoidance or a related shared outer corridor.+ */+export function cleanRouteDetourProblems({+ relations,+ obstacles,+ contentRects = obstacles,+ endpointIds,+ pathFor,+ fromSideFor,+ toSideFor,+ diagramType,+ relationCollection,+ profile,+ thresholds = {},+}) {+ if (profile !== 'showcase') return [];+ const policy = { ...DEFAULTS, ...thresholds };+ const obstacleList = [...obstacles];+ const contentBounds = boundsForRects(contentRects);+ const problems = [];+ for (const [relationIndex, relation] of asArray(relations).entries()) {+ if (!relation || !endpointIds?.has(relation.from) || !endpointIds?.has(relation.to)) continue;+ if (!Array.isArray(relation.via) || relation.via.length === 0) continue;+ const points = normalizeRoutePoints(pathFor(relation)?.points || []);+ if (points.length < 3 || !points.every((point) => Array.isArray(point) && isFinitePoint(...point))) continue;+ const actualLength = orthogonalLength(points);+ if (!Number.isFinite(actualLength)) continue;+ const start = points[0];+ const end = points.at(-1);+ const manhattan = Math.abs(end[0] - start[0]) + Math.abs(end[1] - start[1]);+ if (actualLength < manhattan * policy.minimumDetourRatio+ || actualLength - manhattan < policy.minimumExcessLengthPx) continue;+ const routeBounds = boundsForPoints(points);+ const excursion = outsideExcursion(routeBounds, contentBounds);+ const emptyClearance = emptyControlPointClearance(points, obstacleList);+ if (Math.max(excursion?.maximum || 0, emptyClearance?.maximum || 0)+ < policy.minimumEmptyExcursionPx) continue;+ if (sharesOuterCorridor({+ relation,+ relations,+ pathFor,+ points,+ contentBounds,+ minimumOverlap: policy.sharedCorridorMinimumPx,+ })) continue;++ const fromSide = fromSideFor?.(relation) || inferredSide(points, 'source');+ const toSide = toSideFor?.(relation) || inferredSide(points, 'target');+ const shortest = shortestGridRoute({+ start,+ end,+ points,+ obstacles: obstacleList,+ fromSide,+ toSide,+ clearance: policy.clearance,+ maximumObstacleCount: policy.maximumObstacleCount,+ });+ if (!shortest || !Number.isFinite(shortest.length) || shortest.length <= 0) continue;+ const detourRatio = actualLength / shortest.length;+ const excessLength = actualLength - shortest.length;+ if (detourRatio < policy.minimumDetourRatio || excessLength < policy.minimumExcessLengthPx) continue;++ const relationId = relation.id ? ` id "${relation.id}"` : '';+ const message = `[composition/excessive-route-detour] ${diagramType} ${relationCollection}[${relationIndex}]${relationId} "${relation.from}" -> "${relation.to}" travels ${Math.round(actualLength)}px, ${rounded(detourRatio)}x the ${Math.round(shortest.length)}px shortest obstacle-clearing orthogonal route, and reaches ${Math.round(excursion.maximum)}px beyond the content bounds — remove the distant via corridor or move it close to the connected content.`;+ const supportedFix = 'remove the distant via points and retry automatic routing, or keep the endpoint sides and move the via corridor near the connected nodes while preserving labels and direction';+ recordDiagnostic({+ code: 'composition/excessive-route-detour',+ severity: 'error',+ message,+ subject: relationshipSubject(diagramType, relationCollection, relationIndex, relation),+ evidence: {+ points,+ actualLengthPx: rounded(actualLength),+ shortestLegalPoints: shortest.points,+ shortestLegalLengthPx: rounded(shortest.length),+ detourRatio: rounded(detourRatio),+ excessLengthPx: rounded(excessLength),+ routeBounds,+ contentBounds,+ emptyExcursionPx: excursion,+ emptyControlPointClearancePx: emptyClearance,+ obstacleCount: shortest.obstacleCount,+ thresholds: {+ minimumDetourRatio: policy.minimumDetourRatio,+ minimumExcessLengthPx: policy.minimumExcessLengthPx,+ minimumEmptyExcursionPx: policy.minimumEmptyExcursionPx,+ },+ },+ supportedFixes: [supportedFix],+ });+ problems.push(message);+ }+ return problems;+}diff --git a/archify/test/architecture-automatic-labels.test.mjs b/archify/test/architecture-automatic-labels.test.mjsindex 6f69dd60..08ced57f 100644--- a/archify/test/architecture-automatic-labels.test.mjs+++ b/archify/test/architecture-automatic-labels.test.mjs@@ -23,7 +23,7 @@ function inspect(t, diagram, extra = []) {function vertical() {return {schema_version: 1, diagram_type: 'architecture',- meta: { title: 'Cache read', quality_profile: 'showcase', viewBox: [480, 480] },+ meta: { title: 'Cache read', output: 'diagram.html', quality_profile: 'showcase', viewBox: [480, 480] },components: [{ id: 'api', type: 'backend', label: 'API', pos: [120, 70] },{ id: 'cache', type: 'database', label: 'Cache', pos: [120, 320] },diff --git a/archify/test/architecture-repair-evidence.test.mjs b/archify/test/architecture-repair-evidence.test.mjsindex f4e855d3..2044c5a9 100644--- a/archify/test/architecture-repair-evidence.test.mjs+++ b/archify/test/architecture-repair-evidence.test.mjs@@ -15,7 +15,7 @@ function setup(t, positions, viewBox = [600, 420]) {const input = path.join(cwd, 'source.json');const diagram = {schema_version: 1, diagram_type: 'architecture',- meta: { title: 'Backend', quality_profile: 'standard', viewBox },+ meta: { title: 'Backend', output: 'diagram.html', quality_profile: 'standard', viewBox },components: positions.map((pos, index) => ({ id: `n${index}`, type: 'backend', label: `Node ${index}`, pos, size: [120, 60] })),boundaries: [{ kind: 'region', label: 'Backend', wraps: positions.map((_, i) => `n${i}`) }],};diff --git a/archify/test/fixtures/architecture-label-repair/worldscope.json b/archify/test/fixtures/architecture-label-repair/worldscope.jsonindex fcc9f2cc..e9f061e9 100644--- a/archify/test/fixtures/architecture-label-repair/worldscope.json+++ b/archify/test/fixtures/architecture-label-repair/worldscope.json@@ -3,6 +3,7 @@"diagram_type": "architecture","meta": {"title": "WorldScope 系统架构",+ "output": "worldscope.html","locale": "zh-CN","quality_profile": "showcase"},diff --git a/archify/test/fixtures/architecture-viewport/readable-scroll-worldscope.architecture.json b/archify/test/fixtures/architecture-viewport/readable-scroll-worldscope.architecture.jsonindex f31d061a..2c25b295 100644--- a/archify/test/fixtures/architecture-viewport/readable-scroll-worldscope.architecture.json+++ b/archify/test/fixtures/architecture-viewport/readable-scroll-worldscope.architecture.json@@ -3,6 +3,7 @@"diagram_type": "architecture","meta": {"title": "WorldScope 极高路线可读滚动",+ "output": "readable-scroll-worldscope.html","locale": "zh-CN","quality_profile": "showcase"},diff --git a/archify/test/fixtures/architecture-viewport/route-expanded-worldscope.architecture.json b/archify/test/fixtures/architecture-viewport/route-expanded-worldscope.architecture.jsonindex c20dbe34..4010ca43 100644--- a/archify/test/fixtures/architecture-viewport/route-expanded-worldscope.architecture.json+++ b/archify/test/fixtures/architecture-viewport/route-expanded-worldscope.architecture.json@@ -3,6 +3,7 @@"diagram_type": "architecture","meta": {"title": "WorldScope 系统架构",+ "output": "route-expanded-worldscope.html","locale": "zh-CN","quality_profile": "showcase"},diff --git a/archify/test/route-detour.test.mjs b/archify/test/route-detour.test.mjsnew file mode 100644index 00000000..43f7a995--- /dev/null+++ b/archify/test/route-detour.test.mjs@@ -0,0 +1,162 @@+import assert from 'node:assert/strict';+import { spawnSync } from 'node:child_process';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import test from 'node:test';+import { fileURLToPath } from 'node:url';++const root = fileURLToPath(new URL('../', import.meta.url));+const cli = path.join(root, 'bin/archify.mjs');++function component(id, pos, size = [120, 60]) {+ return { id, type: 'backend', label: id, pos, size };+}++function validate(t, diagram, extra = []) {+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-route-detour-'));+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));+ const input = path.join(directory, 'diagram.json');+ fs.writeFileSync(input, JSON.stringify(diagram));+ const result = spawnSync(process.execPath, [+ cli, 'validate', 'architecture', input, '--quality', diagram.meta.quality_profile,+ '--layout-json', '--json', ...extra,+ ], { cwd: directory, encoding: 'utf8' });+ assert.equal(result.stderr, '', result.stderr);+ return { result, receipt: JSON.parse(result.stdout) };+}++function longDetour(profile = 'showcase') {+ return {+ schema_version: 1,+ diagram_type: 'architecture',+ meta: { title: 'Long detour', output: 'diagram.html', quality_profile: profile },+ components: [+ component('sources', [60, 300], [150, 64]),+ component('worker', [410, 300], [150, 64]),+ component('cache', [290, 480], [150, 64]),+ ],+ connections: [{+ id: 'sources-to-worker', from: 'sources', to: 'worker', label: 'collect',+ fromSide: 'bottom', toSide: 'bottom', via: [[135, 1120], [485, 1120]],+ }],+ };+}++test('showcase rejects an authored route whose empty-space detour is far longer than a legal orthogonal route', t => {+ const { result, receipt } = validate(t, longDetour());+ assert.equal(result.status, 1);+ const diagnosis = receipt.diagnostics.find(({ code }) => code === 'composition/excessive-route-detour');+ assert.ok(diagnosis, JSON.stringify(receipt));+ assert.equal(diagnosis.subject.id, 'sources-to-worker');+ assert.equal(diagnosis.evidence.actualLengthPx, 1862);+ assert.equal(diagnosis.evidence.shortestLegalLengthPx, 358);+ assert.equal(diagnosis.evidence.detourRatio, 5.2);+ assert.equal(diagnosis.evidence.emptyExcursionPx.bottom, 576);+ assert.equal(diagnosis.evidence.emptyControlPointClearancePx.maximum, 731);+ assert.deepEqual(diagnosis.evidence.shortestLegalPoints, [+ [135, 364], [135, 368], [485, 368], [485, 364],+ ]);+ assert.match(diagnosis.supportedFixes.join(' '), /remove the distant via points/);+});++test('an unnecessary control corridor is diagnosed inside a large content envelope', t => {+ const diagram = {+ schema_version: 1,+ diagram_type: 'architecture',+ meta: { title: 'Internal empty corridor', output: 'diagram.html', quality_profile: 'showcase' },+ components: [+ component('source', [60, 100]),+ component('target', [410, 100]),+ component('lower-content', [60, 700]),+ ],+ connections: [{+ id: 'internal-detour', from: 'source', to: 'target',+ fromSide: 'bottom', toSide: 'bottom', via: [[120, 500], [470, 500]],+ }],+ };+ const { result, receipt } = validate(t, diagram);+ assert.equal(result.status, 1);+ const diagnosis = receipt.diagnostics.find(({ code }) => code === 'composition/excessive-route-detour');+ assert.ok(diagnosis, JSON.stringify(receipt));+ assert.equal(diagnosis.evidence.emptyExcursionPx.maximum, 0);+ assert.equal(diagnosis.evidence.emptyControlPointClearancePx.maximum, 340);+});++test('the same relationship passes after the unnecessary authored detour is removed', t => {+ const diagram = longDetour();+ diagram.connections[0] = { id: 'sources-to-worker', from: 'sources', to: 'worker', label: 'collect' };+ const { result, receipt } = validate(t, diagram);+ assert.equal(result.status, 0, result.stdout);+ assert.equal(receipt.ok, true);+});++test('standard keeps authored route freedom while showcase owns the compactness gate', t => {+ const { result, receipt } = validate(t, longDetour('standard'));+ assert.equal(result.status, 0, result.stdout);+ assert.equal(receipt.ok, true);+});++test('an explicit route around an opaque obstacle is not reported as an excessive detour', t => {+ const diagram = {+ schema_version: 1,+ diagram_type: 'architecture',+ meta: { title: 'Obstacle route', output: 'diagram.html', quality_profile: 'showcase' },+ components: [+ component('source', [60, 100]),+ component('blocker', [240, 80], [100, 100]),+ component('target', [410, 100]),+ ],+ connections: [{+ id: 'around-blocker', from: 'source', to: 'target',+ fromSide: 'right', toSide: 'left',+ via: [[200, 130], [200, 190], [390, 190], [390, 130]],+ }],+ };+ const { result, receipt } = validate(t, diagram);+ assert.equal(result.status, 0, result.stdout);+ assert.equal(receipt.ok, true);+});++test('a related shared outer corridor is treated as an intentional bus', t => {+ const diagram = {+ schema_version: 1,+ diagram_type: 'architecture',+ meta: { title: 'Shared bus', output: 'diagram.html', quality_profile: 'showcase' },+ components: [+ component('source', [60, 100]),+ component('first', [410, 100]),+ component('second', [410, 260]),+ ],+ connections: [+ {+ id: 'bus-first', from: 'source', to: 'first',+ fromSide: 'bottom', toSide: 'bottom', via: [[120, 700], [470, 700]],+ },+ {+ id: 'bus-second', from: 'source', to: 'second',+ fromSide: 'bottom', toSide: 'bottom', via: [[120, 700], [470, 700]],+ },+ ],+ };+ const { receipt } = validate(t, diagram);+ assert.equal(+ receipt.diagnostics?.some(({ code }) => code === 'composition/excessive-route-detour') || false,+ false,+ JSON.stringify(receipt),+ );+});++test('a direct relationship crossing a region boundary is not a detour', t => {+ const diagram = {+ schema_version: 1,+ diagram_type: 'architecture',+ meta: { title: 'Boundary crossing', output: 'diagram.html', quality_profile: 'showcase' },+ components: [component('outside', [40, 120]), component('inside', [340, 120])],+ boundaries: [{ kind: 'region', label: 'Runtime', wraps: ['inside'] }],+ connections: [{ id: 'enter', from: 'outside', to: 'inside' }],+ };+ const { result, receipt } = validate(t, diagram);+ assert.equal(result.status, 0, result.stdout);+ assert.equal(receipt.ok, true);+});