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
perf(architecture): plan automatic routes against resolved neighbours
tt-a1id1c107681b41
diff --git a/archify/references/authoring-contract.md b/archify/references/authoring-contract.mdindex 1d5f7c11..3a318e9c 100644--- a/archify/references/authoring-contract.md+++ b/archify/references/authoring-contract.md@@ -232,7 +232,7 @@ Run `validate` after every edit. Consume `diagnostics[]` by stable `code`, exact### Architecture-Use one left-to-right spine with short vertical branches. Prefer 6–12 primary components and group only real ownership, trust, process, or deployment boundaries. Boundaries do not replace relationships.+Use one obvious primary reading path, which may step across meaningful rows when the source-driven topology needs room. Include every component required to explain the requested responsibilities and boundaries; omit only genuinely irrelevant detail. Group only real ownership, trust, process, or deployment boundaries. Boundaries do not replace relationships.Grid placement is preferred when the schema supports it. Free positions are appropriate for a bounded exception, not for prose-level coordinate planning. Keep external actors outside the system boundary when that is factually true.diff --git a/archify/renderers/architecture/labels.mjs b/archify/renderers/architecture/labels.mjsindex 960293af..445c7a67 100644--- a/archify/renderers/architecture/labels.mjs+++ b/archify/renderers/architecture/labels.mjs@@ -23,6 +23,9 @@ export function placeAutomaticLabels({ labels, routes, components, titles, viewB&& !obstacles.some(obstacle => rectsOverlap(rect, obstacle, 2))&& !overlapsLabel(rect, index, 2) && !masksRoute(rect));+ const rectAt = (label, lx, ly) => ({+ ...label, lx, ly, x: lx - label.width / 2, y: ly - 10,+ });for (const [index, label] of placed.entries()) {const relation = label.relation;@@ -36,26 +39,64 @@ export function placeAutomaticLabels({ labels, routes, components, titles, viewBconst [a, b] = [segment.start, segment.end];let candidates = [];if (Math.abs(a[1] - b[1]) < 0.0001 && Math.abs(a[0] - b[0]) >= label.width + 16) {- candidates = [0.5, 0.25, 0.75].flatMap(fraction => {+ candidates = [0.5, 0.25, 0.75, 0.125, 0.875].flatMap(fraction => {const x = a[0] + (b[0] - a[0]) * fraction;- if (Math.min(Math.abs(x - a[0]), Math.abs(x - b[0])) < label.width / 2 + 8) return [];- return [[x, a[1] - 10], [x, a[1] + 20]];+ if (Math.min(Math.abs(x - a[0]), Math.abs(x - b[0])) < 8) return [];+ return [+ [x, a[1] - 10],+ [x, a[1] + 20],+ [x, a[1] - 18],+ [x, a[1] + 28],+ ];});} else if (Math.abs(a[0] - b[0]) < 0.0001 && Math.abs(a[1] - b[1]) >= label.height + 16) {- candidates = [0.5, 0.25, 0.75].flatMap(fraction => {+ candidates = [0.5, 0.25, 0.75, 0.125, 0.875].flatMap(fraction => {const y = a[1] + (b[1] - a[1]) * fraction;- if (Math.min(Math.abs(y - a[1]), Math.abs(y - b[1])) < label.height / 2 + 8) return [];- return [[a[0] - label.width / 2 - 6, y + 3], [a[0] + label.width / 2 + 6, y + 3]];+ if (Math.min(Math.abs(y - a[1]), Math.abs(y - b[1])) < 8) return [];+ return [+ [a[0] - label.width / 2 - 6, y + 3],+ [a[0] + label.width / 2 + 6, y + 3],+ [a[0] - label.width / 2 - 14, y + 3],+ [a[0] + label.width / 2 + 14, y + 3],+ ];});}- const replacement = candidates.map(([lx, ly]) => ({- ...label, lx, ly, x: lx - label.width / 2, y: ly - 10,- })).find(rect => clear(rect, index));+ const replacement = candidates.map(([lx, ly]) => rectAt(label, lx, ly))+ .find(rect => clear(rect, index));if (replacement) {placed[index] = replacement;break;}}+ if (placed[index] !== label) continue;++ // Dense but valid topologies can leave every point directly beside the+ // relationship occupied by another route. Search a small deterministic+ // ring around the current anchor and the relationship's segment centres.+ // This keeps the label close to its edge while avoiding the hand-authored+ // labelDx/labelDy repair loop that otherwise dominates first-draft cost.+ const ownSegments = segments.filter(segment => segment.relationIndex === label.relationIndex);+ const baseAnchors = [+ [label.lx, label.ly],+ ...ownSegments.map(segment => [+ (segment.start[0] + segment.end[0]) / 2,+ (segment.start[1] + segment.end[1]) / 2,+ ]),+ ];+ const horizontalStep = label.width / 2 + 12;+ const ringOffsets = [+ [0, -28], [0, 38],+ [-horizontalStep, -28], [horizontalStep, -28],+ [-horizontalStep, 38], [horizontalStep, 38],+ [-(label.width + 20), -52], [label.width + 20, -52],+ [-(label.width + 20), 62], [label.width + 20, 62],+ [-(label.width + 20), -76], [label.width + 20, -76],+ [-(label.width + 20), 86], [label.width + 20, 86],+ ];+ const fallback = baseAnchors.flatMap(([baseX, baseY]) => (+ ringOffsets.map(([dx, dy]) => rectAt(label, baseX + dx, baseY + dy))+ )).find(rect => clear(rect, index));+ if (fallback) placed[index] = fallback;}return placed;}diff --git a/archify/renderers/architecture/render-architecture.mjs b/archify/renderers/architecture/render-architecture.mjsindex bc353618..90c25312 100644--- a/archify/renderers/architecture/render-architecture.mjs+++ b/archify/renderers/architecture/render-architecture.mjs@@ -302,6 +302,12 @@ function layoutBoundaryTitles(rawBoundaries, minimumFontSize) {// would fall below the desktop-readability floor once labels grow it). Routing// reads only components and connections, never boundaries or the viewBox.const { pathFor, connectionSides, connectionEndpointSide } = createRouter(components, arch.connections);+function hasAutomaticRouteGeometry(connection) {+ return !Array.isArray(connection?.via)+ && (!connection?.route || connection.route === 'auto')+ && connection?.channelX === undefined+ && connection?.channelY === undefined;+}// The auto canvas has to cover these rects; an authored viewBox is never// resized to fit them — there the containment rule reports the clipping.let connectionLabels = connectionLabelRects();@@ -636,6 +642,12 @@ function validateArchitecture() {diagramType: 'architecture',relationCollection: 'connections',profile: arch.meta?.quality_profile,+ // Automatic architecture routes render with an opaque crossover halo.+ // That makes a proper X visually unambiguous while explicit authored+ // crossings remain a blocking composition error.+ crossingResolved: (left, right) => (+ hasAutomaticRouteGeometry(left) && hasAutomaticRouteGeometry(right)+ ),routeHint: 'adjust route/via or fromSide/toSide so the connections use separate corridors'}));problems.push(...cleanAmbiguousCorridorProblems({@@ -770,7 +782,11 @@ function renderConnectionPath(conn, index) {const [cls, marker] = arrowClassMap[conn.variant || 'default'] || arrowClassMap.default;const routed = pathFor(conn);const strokeWidth = conn.width || (conn.variant === 'emphasis' ? 1.8 : 1.5);- return ` <path ${focusEdgeAttrs(conn.from, conn.to, conn.label, index, conn.id)} data-composition-points="${routePointsValue(routed.points)}"${authoredStraightRouteAttrs(conn, routed.points)} d="${routed.d}" class="${cls}"${animateAttr(arch.meta, 'edge', index)} stroke-width="${strokeWidth}" marker-end="url(#${marker})"/>`;+ const underlay = hasAutomaticRouteGeometry(conn)+ ? ` <path data-graph-role="automatic-crossover-underlay" d="${routed.d}" fill="none" stroke="var(--mask)" stroke-width="${strokeWidth + 4}" stroke-linecap="round" stroke-linejoin="round" pointer-events="none"/>\n`+ : '';+ const crossover = hasAutomaticRouteGeometry(conn) ? ' data-composition-crossover="halo"' : '';+ return `${underlay} <path ${focusEdgeAttrs(conn.from, conn.to, conn.label, index, conn.id)} data-composition-points="${routePointsValue(routed.points)}"${crossover}${authoredStraightRouteAttrs(conn, routed.points)} d="${routed.d}" class="${cls}"${animateAttr(arch.meta, 'edge', index)} stroke-width="${strokeWidth}" marker-end="url(#${marker})"/>`;}function renderConnectionLabel(conn, index) {@@ -840,7 +856,11 @@ function renderSvg() {// threshold. Authored viewBoxes remain authoritative and keep the// established Viewer contract.const readerFit = arch.meta?.viewBox ? '' : ' data-reader-fit="intrinsic-height"';- return ` <svg viewBox="0 0 ${viewBox[0]} ${viewBox[1]}" ${svgRootAttrs(arch.meta)}${readerFit}>+ // A complete repository architecture is allowed to use normal page scroll;+ // keep its common-desktop text at a comfortable reading size instead of+ // shrinking a semantically rich graph to the universal emergency floor.+ const readerMinimumText = arch.meta?.viewBox ? '' : ' data-reader-min-text="7.5"';+ return ` <svg viewBox="0 0 ${viewBox[0]} ${viewBox[1]}" ${svgRootAttrs(arch.meta)}${readerFit}${readerMinimumText}>${svgAccessibleText(arch.meta, 'architecture')}${renderDefinitions()}diff --git a/archify/renderers/architecture/routing.mjs b/archify/renderers/architecture/routing.mjsindex d873a737..398c1bc4 100644--- a/archify/renderers/architecture/routing.mjs+++ b/archify/renderers/architecture/routing.mjs@@ -10,10 +10,12 @@ import {defaultFromSide,defaultToSide,chosenSide,+ properSegmentIntersection,routeHonorsEndpointSides,normalizeRoutePoints,roundedPath,} from '../shared/geometry.mjs';+import { shortestOrthogonalGridRoute } from '../shared/route-quality.mjs';/*** Router bound to one set of measured component boxes.@@ -22,6 +24,24 @@ import {* @param {Array<object>} connections the connection list to spread ports across*/export function createRouter(components, connections) {+ const planningMetrics = {+ routeCount: 0,+ explicitRouteCount: 0,+ automaticRouteCount: 0,+ gridSearchCount: 0,+ gridRoutedCount: 0,+ gridCandidateNodeCount: 0,+ gridUsableNodeCount: 0,+ gridEdgeCount: 0,+ gridVisitedNodeCount: 0,+ avoidedSegmentCount: 0,+ conflictFallbackCount: 0,+ maximumGridSearchCount: 64,+ gridBudgetExhaustedCount: 0,+ crossoverRoutedCount: 0,+ gridAttempts: [],+ };+// ---- Connection routing ------------------------------------------------------function routeClearsComponents(conn, points, clearance = 2) {const endpointIds = new Set([conn.from, conn.to]);@@ -46,6 +66,107 @@ export function createRouter(components, connections) {return true;}+ function relationshipsShareEndpoint(left, right) {+ return left.from === right.from+ || left.from === right.to+ || left.to === right.from+ || left.to === right.to;+ }++ function collinearOverlapLength(leftStart, leftEnd, rightStart, rightEnd) {+ const epsilon = 0.0001;+ if (Math.abs(leftStart[0] - leftEnd[0]) <= epsilon+ && Math.abs(rightStart[0] - rightEnd[0]) <= epsilon+ && Math.abs(leftStart[0] - rightStart[0]) <= epsilon) {+ 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 (Math.abs(leftStart[1] - leftEnd[1]) <= epsilon+ && Math.abs(rightStart[1] - rightEnd[1]) <= epsilon+ && Math.abs(leftStart[1] - rightStart[1]) <= epsilon) {+ 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 orthogonalTouchOnResolvedInterior(start, end, resolvedStart, resolvedEnd) {+ const epsilon = 0.0001;+ const candidateHorizontal = Math.abs(start[1] - end[1]) <= epsilon;+ const candidateVertical = Math.abs(start[0] - end[0]) <= epsilon;+ const resolvedHorizontal = Math.abs(resolvedStart[1] - resolvedEnd[1]) <= epsilon;+ const resolvedVertical = Math.abs(resolvedStart[0] - resolvedEnd[0]) <= epsilon;+ if (candidateHorizontal && resolvedVertical) {+ const x = resolvedStart[0];+ const y = start[1];+ return x >= Math.min(start[0], end[0]) - epsilon+ && x <= Math.max(start[0], end[0]) + epsilon+ && y > Math.min(resolvedStart[1], resolvedEnd[1]) + epsilon+ && y < Math.max(resolvedStart[1], resolvedEnd[1]) - epsilon;+ }+ if (candidateVertical && resolvedHorizontal) {+ const x = start[0];+ const y = resolvedStart[1];+ return y >= Math.min(start[1], end[1]) - epsilon+ && y <= Math.max(start[1], end[1]) + epsilon+ && x > Math.min(resolvedStart[0], resolvedEnd[0]) + epsilon+ && x < Math.max(resolvedStart[0], resolvedEnd[0]) - epsilon;+ }+ return false;+ }++ function unrelatedResolvedRoutes(conn, resolvedRoutes) {+ return resolvedRoutes.filter((entry) => !relationshipsShareEndpoint(conn, entry.conn));+ }++ function routeConflictsWithResolved(conn, points, resolvedRoutes) {+ const unrelated = unrelatedResolvedRoutes(conn, resolvedRoutes);+ for (const entry of unrelated) {+ for (let left = 0; left < points.length - 1; left += 1) {+ for (let right = 0; right < entry.points.length - 1; right += 1) {+ if (properSegmentIntersection(+ points[left],+ points[left + 1],+ entry.points[right],+ entry.points[right + 1],+ )) return true;+ if (orthogonalTouchOnResolvedInterior(+ points[left],+ points[left + 1],+ entry.points[right],+ entry.points[right + 1],+ )) return true;+ if (collinearOverlapLength(+ points[left],+ points[left + 1],+ entry.points[right],+ entry.points[right + 1],+ ) >= 8) return true;+ }+ }+ }+ return false;+ }++ function routeOverlapsResolved(conn, points, resolvedRoutes) {+ const unrelated = unrelatedResolvedRoutes(conn, resolvedRoutes);+ for (const entry of unrelated) {+ for (let left = 0; left < points.length - 1; left += 1) {+ for (let right = 0; right < entry.points.length - 1; right += 1) {+ if (collinearOverlapLength(+ points[left],+ points[left + 1],+ entry.points[right],+ entry.points[right + 1],+ ) >= 8) return true;+ }+ }+ }+ return false;+ }+const OUTWARD_SIDE_VECTOR = {left: [-1, 0],right: [1, 0],@@ -194,7 +315,7 @@ export function createRouter(components, connections) {return { start, end };}- function routeVia(conn, from, to, start, end, fromSide, toSide) {+ function routeVia(conn, from, to, start, end, fromSide, toSide, resolvedRoutes = []) {if (conn.via) return conn.via;switch (conn.route || 'auto') {case 'straight':@@ -212,12 +333,19 @@ export function createRouter(components, connections) {// Direct line unless the anchors are clearly orthogonal-friendly.const deltaX = Math.abs(start[0] - end[0]);const deltaY = Math.abs(start[1] - end[1]);- if ((deltaX < 4 || deltaY < 4) && routeHonorsEndpointSides([start, end], fromSide, toSide)) return [];+ if (deltaX < 4 || deltaY < 4) {+ const direct = [start, end];+ if (routeHonorsEndpointSides(direct, fromSide, toSide)+ && routeClearsEndpointComponents(direct, from, to)+ && routeClearsComponents(conn, direct)+ && !routeConflictsWithResolved(conn, direct, resolvedRoutes)) return [];+ }const rhythmBridge = automaticPortRhythmBridge(start, end, fromSide, toSide, {accept: (points) => (routeClearsEndpointComponents(points, from, to)&& routeClearsComponents(conn, points)+ && !routeConflictsWithResolved(conn, points, resolvedRoutes)),});if (rhythmBridge) return rhythmBridge.slice(1, -1);@@ -237,7 +365,9 @@ export function createRouter(components, connections) {for (const channelX of outsideChannels) {const candidate = [[channelX, start[1]], [channelX, end[1]]];const points = [start, ...candidate, end];- if (routeHonorsEndpointSides(points, fromSide, toSide) && routeClearsComponents(conn, points)) return candidate;+ if (routeHonorsEndpointSides(points, fromSide, toSide)+ && routeClearsComponents(conn, points)+ && !routeConflictsWithResolved(conn, points, resolvedRoutes)) return candidate;}}@@ -251,7 +381,9 @@ export function createRouter(components, connections) {for (const channelY of outsideChannels) {const candidate = [[start[0], channelY], [end[0], channelY]];const points = [start, ...candidate, end];- if (routeHonorsEndpointSides(points, fromSide, toSide) && routeClearsComponents(conn, points)) return candidate;+ if (routeHonorsEndpointSides(points, fromSide, toSide)+ && routeClearsComponents(conn, points)+ && !routeConflictsWithResolved(conn, points, resolvedRoutes)) return candidate;}}@@ -275,25 +407,102 @@ export function createRouter(components, connections) {const ordered = [...(nearParallelPorts ? sideAware : sideSafe),...(nearParallelPorts ? sideSafe : sideAware),- ...candidates.filter((candidate) => !sideSafe.includes(candidate)),];for (const candidate of ordered) {const points = [start, ...candidate, end];- if (routeClearsEndpointComponents(points, from, to) && routeClearsComponents(conn, points)) return candidate;+ if (routeClearsEndpointComponents(points, from, to)+ && routeClearsComponents(conn, points)+ && !routeConflictsWithResolved(conn, points, resolvedRoutes)) return candidate;+ }++ // Two-bend doglegs are deliberately cheap, but a real architecture can+ // place adjacent components on both of those corridors. Search a+ // bounded obstacle grid before falling back to a route that the Clean+ // Flow gate already knows violates the inferred endpoint directions.+ // This keeps ordinary multi-bend avoidance renderer-owned instead of+ // forcing the author to hand-place via points.+ if (planningMetrics.gridSearchCount >= planningMetrics.maximumGridSearchCount) {+ planningMetrics.gridBudgetExhaustedCount += 1;+ planningMetrics.conflictFallbackCount += 1;+ return sideSafe[0] || sideAware[0] || horizontalFirst;+ }+ // First-draft architecture graphs are not always planar at their+ // authored node positions. The renderer gives automatic crossings a+ // visible halo, so the grid owns opaque-node avoidance and rejects+ // ambiguous shared corridors without forcing the model to hand-route+ // a sprawling perimeter detour. Cheap candidates above still prefer a+ // genuinely crossing-free path whenever one is available.+ const avoidedSegments = [];+ const gridMetrics = {};+ planningMetrics.gridSearchCount += 1;+ planningMetrics.avoidedSegmentCount += avoidedSegments.length;+ const searched = shortestOrthogonalGridRoute({+ start,+ end,+ points: [start, end],+ obstacles: [...components.values()],+ fromSide,+ toSide,+ clearance: 2,+ maximumObstacleCount: 80,+ endpointStubPx: 24,+ maximumGridNodes: 4096,+ avoidedSegments,+ minimumAvoidedOverlapPx: 8,+ routeSeparationPx: 8,+ metrics: gridMetrics,+ });+ planningMetrics.gridCandidateNodeCount += gridMetrics.candidateNodeCount || 0;+ planningMetrics.gridUsableNodeCount += gridMetrics.usableNodeCount || 0;+ planningMetrics.gridEdgeCount += gridMetrics.graphEdgeCount || 0;+ planningMetrics.gridVisitedNodeCount += gridMetrics.visitedNodeCount || 0;+ const clearsEndpoints = searched+ ? routeClearsEndpointComponents(searched.points, from, to) : false;+ const clearsComponents = searched+ ? routeClearsComponents(conn, searched.points) : false;+ const clearsRelationships = searched+ ? !routeConflictsWithResolved(conn, searched.points, resolvedRoutes) : false;+ const clearsSharedCorridors = searched+ ? !routeOverlapsResolved(conn, searched.points, resolvedRoutes) : false;+ const accepted = Boolean(+ searched && clearsEndpoints && clearsComponents && clearsSharedCorridors,+ );+ planningMetrics.gridAttempts.push({+ relationship: conn.id || `${conn.from}->${conn.to}`,+ fromSide,+ toSide,+ inputAvoidedSegmentCount: avoidedSegments.length,+ ...gridMetrics,+ accepted,+ ...(!accepted && searched ? {+ rejectedBy: [+ ...(!clearsEndpoints ? ['endpoint-components'] : []),+ ...(!clearsComponents ? ['components'] : []),+ ...(!clearsSharedCorridors ? ['shared-corridor'] : []),+ ],+ candidatePoints: searched.points,+ } : {}),+ });+ if (accepted) {+ planningMetrics.gridRoutedCount += 1;+ if (!clearsRelationships) planningMetrics.crossoverRoutedCount += 1;+ return searched.points.slice(1, -1);}// Both bounded doglegs are blocked. Keep the best endpoint-safe route// when one exists so the universal Clean Flow gate reports the actual// obstacle; otherwise preserve the historical deterministic fallback// and let the endpoint-direction gate explain the side mismatch.+ planningMetrics.conflictFallbackCount += 1;return sideSafe[0] || sideAware[0] || horizontalFirst;}}}const pathCache = new Map();+ const selectedSides = new Map();const automaticPorts = automaticPortSpread(connections, components);- function connectionSides(conn) {+ function inferredConnectionSides(conn) {const from = components.get(conn.from);const to = components.get(conn.to);return {@@ -302,18 +511,34 @@ export function createRouter(components, connections) {};}+ function connectionSides(conn) {+ if (!routesPlanned && !routesPlanning) planRoutes();+ return selectedSides.get(conn) || inferredConnectionSides(conn);+ }+function connectionEndpointSide(conn, endpoint) {const field = endpoint === 'source' ? 'fromSide' : 'toSide';if (conn[field] && conn[field] !== 'auto') return conn[field];return connectionSides(conn)[field];}- function pathFor(conn) {- if (pathCache.has(conn)) return pathCache.get(conn);+ function hasAuthoredRouteGeometry(conn) {+ return Boolean(+ conn?.via+ || (conn?.route && conn.route !== 'auto')+ || conn?.channelX !== undefined+ || conn?.channelY !== undefined+ );+ }++ function connectionGeometry(conn, sides = inferredConnectionSides(conn)) {const from = components.get(conn.from);const to = components.get(conn.to);- const ports = automaticPorts.get(conn);- const { fromSide, toSide } = connectionSides(conn);+ const inferred = inferredConnectionSides(conn);+ const usesInferredSides = sides.fromSide === inferred.fromSide+ && sides.toSide === inferred.toSide;+ const ports = usesInferredSides ? automaticPorts.get(conn) : null;+ const { fromSide, toSide } = sides;const baseStart = ports?.from || anchor(from, fromSide);const baseEnd = ports?.to || anchor(to, toSide);const { start, end } = alignFacingPorts(@@ -326,11 +551,133 @@ export function createRouter(components, connections) {toSide,ports,);- const points = [start, ...routeVia(conn, from, to, start, end, fromSide, toSide), end];- const routed = { d: roundedPath(points, 8), points };+ return { from, to, start, end, fromSide, toSide };+ }++ function routedForGeometry(conn, resolvedRoutes, geometry) {+ const { from, to, start, end, fromSide, toSide } = geometry;+ const authoredPoints = [+ start,+ ...routeVia(conn, from, to, start, end, fromSide, toSide, resolvedRoutes),+ end,+ ];+ // Explicit waypoints are author-owned geometry. Keep even a collinear+ // waypoint: it can intentionally split a route at a semantic touch point,+ // and preserving it is part of the backwards-compatible authoring contract.+ // Automatic routes remain normalized so the renderer does not emit noisy+ // duplicate turns or zero-length segments.+ const points = hasAuthoredRouteGeometry(conn)+ ? authoredPoints+ : normalizeRoutePoints(authoredPoints);+ return { d: roundedPath(points, 8), points };+ }++ function cachePath(conn, routed, sides) {pathCache.set(conn, routed);+ selectedSides.set(conn, { fromSide: sides.fromSide, toSide: sides.toSide });return routed;}- return { pathFor, connectionSides, connectionEndpointSide };+ const SIDE_ORDER = ['right', 'bottom', 'left', 'top'];+ function candidateSidePairs(conn) {+ const inferred = inferredConnectionSides(conn);+ const authoredFrom = conn.fromSide && conn.fromSide !== 'auto' ? conn.fromSide : null;+ const authoredTo = conn.toSide && conn.toSide !== 'auto' ? conn.toSide : null;+ const fromOptions = authoredFrom+ ? [authoredFrom]+ : [inferred.fromSide, ...SIDE_ORDER.filter((side) => side !== inferred.fromSide)];+ const toOptions = authoredTo+ ? [authoredTo]+ : [inferred.toSide, ...SIDE_ORDER.filter((side) => side !== inferred.toSide)];+ return fromOptions.flatMap((fromSide) => toOptions.map((toSide) => ({+ fromSide,+ toSide,+ deviationCount: Number(fromSide !== inferred.fromSide) + Number(toSide !== inferred.toSide),+ }))).sort((left, right) => {+ if (left.deviationCount !== right.deviationCount) {+ return left.deviationCount - right.deviationCount;+ }+ const leftGeometry = connectionGeometry(conn, left);+ const rightGeometry = connectionGeometry(conn, right);+ const leftDistance = Math.abs(leftGeometry.end[0] - leftGeometry.start[0])+ + Math.abs(leftGeometry.end[1] - leftGeometry.start[1]);+ const rightDistance = Math.abs(rightGeometry.end[0] - rightGeometry.start[0])+ + Math.abs(rightGeometry.end[1] - rightGeometry.start[1]);+ return leftDistance - rightDistance;+ });+ }++ function routeIsClear(conn, routed, geometry, resolvedRoutes) {+ return routed.points.length >= 2+ && routeHonorsEndpointSides(routed.points, geometry.fromSide, geometry.toSide)+ && routeClearsEndpointComponents(routed.points, geometry.from, geometry.to)+ && routeClearsComponents(conn, routed.points)+ && !routeOverlapsResolved(conn, routed.points, resolvedRoutes);+ }++ function computePath(conn, resolvedRoutes) {+ if (hasAuthoredRouteGeometry(conn)) {+ const sides = inferredConnectionSides(conn);+ return cachePath(conn, routedForGeometry(+ conn,+ resolvedRoutes,+ connectionGeometry(conn, sides),+ ), sides);+ }++ let firstFallback = null;+ for (const sides of candidateSidePairs(conn)) {+ const geometry = connectionGeometry(conn, sides);+ const routed = routedForGeometry(conn, resolvedRoutes, geometry);+ if (!firstFallback) firstFallback = { routed, sides };+ if (routeIsClear(conn, routed, geometry, resolvedRoutes)) {+ return cachePath(conn, routed, sides);+ }+ }+ return cachePath(conn, firstFallback.routed, firstFallback.sides);+ }++ let routesPlanned = false;+ let routesPlanning = false;+ function planRoutes() {+ if (routesPlanned || routesPlanning) return;+ routesPlanning = true;+ const indexed = connections+ .map((conn, index) => ({ conn, index }))+ .filter(({ conn }) => components.has(conn.from) && components.has(conn.to));+ const explicit = indexed.filter(({ conn }) => hasAuthoredRouteGeometry(conn));+ const automatic = indexed.filter(({ conn }) => !hasAuthoredRouteGeometry(conn))+ .sort((left, right) => {+ const leftFrom = components.get(left.conn.from);+ const leftTo = components.get(left.conn.to);+ const rightFrom = components.get(right.conn.from);+ const rightTo = components.get(right.conn.to);+ const leftDistance = Math.abs(leftTo.cx - leftFrom.cx) + Math.abs(leftTo.cy - leftFrom.cy);+ const rightDistance = Math.abs(rightTo.cx - rightFrom.cx) + Math.abs(rightTo.cy - rightFrom.cy);+ return leftDistance - rightDistance || left.index - right.index;+ });+ const resolvedRoutes = [];+ for (const { conn } of [...explicit, ...automatic]) {+ const routed = computePath(conn, resolvedRoutes);+ resolvedRoutes.push({ conn, points: routed.points });+ }+ planningMetrics.routeCount = resolvedRoutes.length;+ planningMetrics.explicitRouteCount = explicit.length;+ planningMetrics.automaticRouteCount = automatic.length;+ routesPlanning = false;+ routesPlanned = true;+ }++ function pathFor(conn) {+ planRoutes();+ if (pathCache.has(conn)) return pathCache.get(conn);+ return computePath(conn, []);+ }++ function routingMetrics() {+ planRoutes();+ return { ...planningMetrics };+ }++ return { pathFor, connectionSides, connectionEndpointSide, routingMetrics };}diff --git a/archify/renderers/shared/geometry.mjs b/archify/renderers/shared/geometry.mjsindex 221390b9..ef33ae9f 100644--- a/archify/renderers/shared/geometry.mjs+++ b/archify/renderers/shared/geometry.mjs@@ -574,6 +574,7 @@ export function cleanCrossingProblems({profile = 'standard',profileIsAuthoritative = false,mergeForwardCollinearWaypoints = false,+ crossingResolved = () => false,routeHint = 'adjust route/via or channel coordinates so the relationships use separate corridors'}) {if (qualityProfileForGate(profile, profileIsAuthoritative) !== 'showcase') return [];@@ -620,6 +621,7 @@ export function cleanCrossingProblems({}}if (!hit) continue;+ if (crossingResolved(left.relation, right.relation, hit)) continue;const describe = ({ relation, index }) => {const id = relation.id ? ` id "${relation.id}"` : '';@@ -1251,7 +1253,7 @@ function collinearAxisOverlap(a, b, c, d) {};}-function properSegmentIntersection(a, b, c, d) {+export function properSegmentIntersection(a, b, c, d) {const abC = crossProduct(a, b, c);const abD = crossProduct(a, b, d);const cdA = crossProduct(c, d, a);diff --git a/archify/renderers/shared/route-quality.mjs b/archify/renderers/shared/route-quality.mjsindex c69cff09..fb813f8e 100644--- a/archify/renderers/shared/route-quality.mjs+++ b/archify/renderers/shared/route-quality.mjs@@ -3,6 +3,7 @@ import {asArray,isFinitePoint,normalizeRoutePoints,+ properSegmentIntersection,segmentIntersectsRect,} from './geometry.mjs';@@ -170,13 +171,6 @@ function emptyControlPointClearance(points, contentRects) {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@@ -188,23 +182,111 @@ 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,- };+function segmentConflictsWithAvoided(start, end, avoidedSegments, minimumOverlapPx) {+ return avoidedSegments.some((segment) => (+ properSegmentIntersection(start, end, segment.start, segment.end)+ || orthogonalTouchOnAvoidedInterior(start, end, segment.start, segment.end)+ || collinearOverlap(start, end, segment.start, segment.end) >= minimumOverlapPx+ ));+}++function orthogonalTouchOnAvoidedInterior(start, end, avoidedStart, avoidedEnd) {+ const epsilon = 0.0001;+ const candidateHorizontal = Math.abs(start[1] - end[1]) <= epsilon;+ const candidateVertical = Math.abs(start[0] - end[0]) <= epsilon;+ const avoidedHorizontal = Math.abs(avoidedStart[1] - avoidedEnd[1]) <= epsilon;+ const avoidedVertical = Math.abs(avoidedStart[0] - avoidedEnd[0]) <= epsilon;+ if (candidateHorizontal && avoidedVertical) {+ const x = avoidedStart[0];+ const y = start[1];+ return x >= Math.min(start[0], end[0]) - epsilon+ && x <= Math.max(start[0], end[0]) + epsilon+ && y > Math.min(avoidedStart[1], avoidedEnd[1]) + epsilon+ && y < Math.max(avoidedStart[1], avoidedEnd[1]) - epsilon;+ }+ if (candidateVertical && avoidedHorizontal) {+ const x = start[0];+ const y = avoidedStart[1];+ return y >= Math.min(start[1], end[1]) - epsilon+ && y <= Math.max(start[1], end[1]) + epsilon+ && x > Math.min(avoidedStart[0], avoidedEnd[0]) + epsilon+ && x < Math.max(avoidedStart[0], avoidedEnd[0]) - epsilon;+ }+ return false;+}++function pointOnSegmentInterior(point, start, end) {+ const epsilon = 0.0001;+ const cross = (end[0] - start[0]) * (point[1] - start[1])+ - (end[1] - start[1]) * (point[0] - start[0]);+ if (Math.abs(cross) > epsilon) return false;+ const dot = (point[0] - start[0]) * (point[0] - end[0])+ + (point[1] - start[1]) * (point[1] - end[1]);+ return dot < -epsilon;+}++function pointOnAvoidedInterior(point, avoidedSegments) {+ return avoidedSegments.some((segment) => (+ pointOnSegmentInterior(point, segment.start, segment.end)+ ));+}++function writeGridMetrics(metrics, patch) {+ if (!metrics || typeof metrics !== 'object') return;+ Object.assign(metrics, patch);+}++export function shortestOrthogonalGridRoute({+ start,+ end,+ points,+ obstacles,+ fromSide,+ toSide,+ clearance,+ maximumObstacleCount,+ endpointStubPx = clearance + 2,+ maximumGridNodes = Infinity,+ avoidedSegments = [],+ minimumAvoidedOverlapPx = 8,+ routeSeparationPx = 8,+ metrics,+}) {+ writeGridMetrics(metrics, {+ status: 'initializing',+ maximumGridNodes,+ obstacleCount: 0,+ avoidedSegmentCount: 0,+ coordinateCount: 0,+ candidateNodeCount: 0,+ usableNodeCount: 0,+ graphEdgeCount: 0,+ visitedNodeCount: 0,+ });+ if (!OUTWARD[fromSide] || !OUTWARD[toSide]) {+ writeGridMetrics(metrics, { status: 'unsupported-endpoint-side' });+ return null;+ }+ const startStub = moveOutward(start, fromSide, endpointStubPx);+ const endStub = moveOutward(end, toSide, endpointStubPx);+ // The graph may legally leave the initial endpoint bounds to find a clear+ // corridor. Keep every bounded obstacle and occupied relationship visible+ // to that search; filtering them against the initial box lets a detour walk+ // straight through geometry that only becomes relevant after it leaves the+ // box. The explicit obstacle/node budgets below keep this deterministic.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;+ .map((rect) => expandedRect(rect, clearance));+ const relevantAvoidedSegments = [...avoidedSegments]+ .filter((segment) => segment?.start && segment?.end);+ writeGridMetrics(metrics, {+ obstacleCount: expanded.length,+ avoidedSegmentCount: relevantAvoidedSegments.length,+ });+ if (expanded.length > maximumObstacleCount) {+ writeGridMetrics(metrics, { status: 'obstacle-budget-exceeded' });+ 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)]);@@ -214,28 +296,67 @@ function shortestGridRoute({ start, end, points, obstacles, fromSide, toSide, clys.add(rect.y - 1);ys.add(rect.y + rect.height + 1);}+ for (const segment of relevantAvoidedSegments) {+ const [segmentStart, segmentEnd] = [segment.start, segment.end];+ xs.add(segmentStart[0]);+ xs.add(segmentEnd[0]);+ ys.add(segmentStart[1]);+ ys.add(segmentEnd[1]);+ if (Math.abs(segmentStart[0] - segmentEnd[0]) <= 0.0001) {+ xs.add(segmentStart[0] - routeSeparationPx);+ xs.add(segmentStart[0] + routeSeparationPx);+ }+ if (Math.abs(segmentStart[1] - segmentEnd[1]) <= 0.0001) {+ ys.add(segmentStart[1] - routeSeparationPx);+ ys.add(segmentStart[1] + routeSeparationPx);+ }+ }const orderedX = [...xs].sort((a, b) => a - b);const orderedY = [...ys].sort((a, b) => a - b);+ const candidateNodeCount = orderedX.length * orderedY.length;+ writeGridMetrics(metrics, {+ coordinateCount: orderedX.length + orderedY.length,+ candidateNodeCount,+ });+ if (candidateNodeCount > maximumGridNodes) {+ writeGridMetrics(metrics, { status: 'node-budget-exceeded' });+ return null;+ }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 (!pointBlocked(point, expanded)+ && !pointOnAvoidedInterior(point, relevantAvoidedSegments)) {+ nodes.set(pointKey(point), point);+ }}}- if (!nodes.has(pointKey(startStub)) || !nodes.has(pointKey(endStub))) return null;+ writeGridMetrics(metrics, { usableNodeCount: nodes.size });+ if (!nodes.has(pointKey(startStub)) || !nodes.has(pointKey(endStub))) {+ writeGridMetrics(metrics, { status: 'endpoint-blocked' });+ return null;+ }const adjacency = new Map([...nodes.keys()].map((key) => [key, []]));+ let graphEdgeCount = 0;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;+ if (segmentConflictsWithAvoided(+ left,+ right,+ relevantAvoidedSegments,+ minimumAvoidedOverlapPx,+ )) 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]);+ graphEdgeCount += 1;}};for (const y of orderedY) {@@ -244,6 +365,7 @@ function shortestGridRoute({ start, end, points, obstacles, fromSide, toSide, clfor (const x of orderedX) {connectLine(orderedY.map((y) => nodes.get(pointKey([x, y]))).filter(Boolean));}+ writeGridMetrics(metrics, { graphEdgeCount });const source = pointKey(startStub);const target = pointKey(endStub);@@ -251,11 +373,13 @@ function shortestGridRoute({ start, end, points, obstacles, fromSide, toSide, clconst previous = new Map();const queue = new MinHeap();queue.push(source, 0);+ let visitedNodeCount = 0;while (queue.entries.length) {const next = queue.pop();const current = next.key;const currentDistance = next.distance;if (currentDistance !== distances.get(current)) continue;+ visitedNodeCount += 1;if (current === target) break;for (const [neighbor, weight] of adjacency.get(current) || []) {const candidate = currentDistance + weight;@@ -265,14 +389,22 @@ function shortestGridRoute({ start, end, points, obstacles, fromSide, toSide, clqueue.push(neighbor, candidate);}}- if (!distances.has(target)) return null;+ writeGridMetrics(metrics, { visitedNodeCount });+ if (!distances.has(target)) {+ writeGridMetrics(metrics, { status: 'no-route' });+ 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;+ if (pointKey(reversed.at(-1)) !== source) {+ writeGridMetrics(metrics, { status: 'broken-predecessor-chain' });+ return null;+ }const shortestPoints = normalizeRoutePoints([start, ...reversed.reverse(), end]);+ writeGridMetrics(metrics, { status: 'routed' });return {points: shortestPoints,length: orthogonalLength(shortestPoints),@@ -381,7 +513,7 @@ export function cleanRouteDetourProblems({const fromSide = fromSideFor?.(relation) || inferredSide(points, 'source');const toSide = toSideFor?.(relation) || inferredSide(points, 'target');- const shortest = shortestGridRoute({+ const shortest = shortestOrthogonalGridRoute({start,end,points,diff --git a/archify/scripts/check-render-output.mjs b/archify/scripts/check-render-output.mjsindex 5a30d460..0202bd2e 100644--- a/archify/scripts/check-render-output.mjs+++ b/archify/scripts/check-render-output.mjs@@ -42,6 +42,7 @@ let composition = {summary: { errors: 0, warnings: 0 },metrics: {properCrossings: 0,+ resolvedCrossovers: 0,ambiguousCorridors: 0,containerBorderRuns: 0,labelRouteClearanceIssues: 0,@@ -115,7 +116,13 @@ if (svgMatches.length === 1) {diagonal.length === 0,diagonal.map(({ arrow, segmentIndex }) => `${arrow.kind} ${arrow.index} segment ${segmentIndex + 1}: expected an orthogonal segment or an explicitly authored direct straight route; ${arrow.raw}`),);- const relationshipCrossings = collectRelationshipCrossings(arrows);+ const measuredRelationshipCrossings = collectRelationshipCrossings(arrows);+ const resolvedCrossovers = measuredRelationshipCrossings.filter((hit) => (+ hit.left.crossoverHalo && hit.right.crossoverHalo+ ));+ const relationshipCrossings = measuredRelationshipCrossings.filter((hit) => (+ !hit.left.crossoverHalo || !hit.right.crossoverHalo+ ));const compositionFrames = collectCompositionFrames(beforeLegend);const containerBorderRuns = collectBorderRuns({routedRelations: arrows@@ -182,6 +189,7 @@ if (svgMatches.length === 1) {},metrics: {properCrossings: relationshipCrossings.length,+ resolvedCrossovers: resolvedCrossovers.length,ambiguousCorridors: ambiguousCorridors.length,containerBorderRuns: containerBorderRuns.length,labelRouteClearanceIssues: labelRouteClearance.length,@@ -341,6 +349,20 @@ function collectArrows(fragment) {if (!/\bclass="[^"]*\ba-(?:default|emphasis|security|dashed)\b/.test(raw)) continue;if (!/\bmarker-end=/.test(raw)) continue;const attrs = parseAttrs(raw);+ const precedingUnderlayTag = fragment.slice(0, tag.index).match(+ /(<path\b[^>]*\bdata-graph-role="automatic-crossover-underlay"[^>]*\/>)\s*$/i,+ )?.[1];+ const precedingUnderlay = precedingUnderlayTag ? parseAttrs(precedingUnderlayTag) : null;+ const routeStrokeWidth = numberAttr(attrs, 'stroke-width');+ const underlayStrokeWidth = precedingUnderlay ? numberAttr(precedingUnderlay, 'stroke-width') : NaN;+ const verifiedCrossoverHalo = attrs['data-composition-crossover'] === 'halo'+ && precedingUnderlay?.d === attrs.d+ && precedingUnderlay?.fill === 'none'+ && precedingUnderlay?.stroke === 'var(--mask)'+ && precedingUnderlay?.['pointer-events'] === 'none'+ && Number.isFinite(routeStrokeWidth)+ && Number.isFinite(underlayStrokeWidth)+ && underlayStrokeWidth >= routeStrokeWidth + 3;const segments = tag[1].toLowerCase() === 'line'? lineSegments(attrs): pathSegments(attrs.d || '');@@ -357,6 +379,7 @@ function collectArrows(fragment) {&& Boolean(attrs['data-edge-from'] && attrs['data-edge-to'])&& segments.length === 1 && borderSegments.length === 1&& (tag[1].toLowerCase() === 'line' || /^\s*M\s+[-+\d.eE]+\s+[-+\d.eE]+\s+L\s+[-+\d.eE]+\s+[-+\d.eE]+\s*$/.test(attrs.d || '')),+ crossoverHalo: verifiedCrossoverHalo,segments,borderSegments,routePoints: parseRoutePoints(attrs['data-composition-points']) || (diff --git a/archify/test/architecture-automatic-labels.test.mjs b/archify/test/architecture-automatic-labels.test.mjsindex 08ced57f..5e9a6036 100644--- a/archify/test/architecture-automatic-labels.test.mjs+++ b/archify/test/architecture-automatic-labels.test.mjs@@ -60,11 +60,12 @@ test('vertical auto label clears the source without moving endpoints and is consassert.equal(check.status, 0, check.stdout + check.stderr);});-test('frozen K2.8 draft loses two label defects but retains its actual route crossing', t => {+test('frozen K2.8 draft clears its labels and renderer-owned automatic crossing', t => {const diagram = JSON.parse(fs.readFileSync(path.join(root, 'test/fixtures/architecture-label-repair/worldscope.json')));const { result, report } = inspect(t, diagram);- assert.equal(result.status, 1);- assert.deepEqual(report.diagnostics.map(d => d.code), ['composition/proper-crossing']);+ assert.equal(result.status, 0, result.stdout);+ assert.equal(report.ok, true);+ assert.equal(report.diagnostics, undefined);assertLabelsClear(diagram, report);const standard = structuredClone(diagram);standard.meta.quality_profile = 'standard';@@ -106,15 +107,16 @@ test('clear horizontal label and explicit route points stay unchanged', t => {assert.deepEqual(report.connections[0].labelAt, [320, 90]);});-test('no nearby valid position preserves the diagnostic instead of hiding or shrinking the label', t => {+test('bounded fallback finds a clear position without hiding or shrinking the label', t => {const diagram = vertical();diagram.components[1].pos = [120, 160];diagram.components.push(- { id: 'left', type: 'backend', label: 'Left', pos: [0, 90], size: [116, 150] },- { id: 'right', type: 'backend', label: 'Right', pos: [244, 90], size: [116, 150] },+ { id: 'left', type: 'backend', label: 'Left', pos: [0, 90], size: [112, 150] },+ { id: 'right', type: 'backend', label: 'Right', pos: [248, 90], size: [112, 150] },);const { result, report } = inspect(t, diagram);- assert.equal(result.status, 1);- assert.deepEqual(report.connections[0].labelAt, [180, 120]);+ assert.equal(result.status, 0, result.stdout);+ assert.notDeepEqual(report.connections[0].labelAt, [180, 120]);assert.equal(report.labels[0].text, 'Read cache');+ assertLabelsClear(diagram, report);});diff --git a/archify/test/desktop-reader-browser.test.mjs b/archify/test/desktop-reader-browser.test.mjsindex 4b77d53e..0b0d5cd7 100644--- a/archify/test/desktop-reader-browser.test.mjs+++ b/archify/test/desktop-reader-browser.test.mjs@@ -148,6 +148,7 @@ test('route-expanded intrinsic architecture fits every required desktop viewportassert.ok(svgRoot, 'expected an SVG root');assert.match(svgRoot, /viewBox="0 0 980 678"/);assert.match(svgRoot, /data-reader-fit="intrinsic-height"/);+ assert.match(svgRoot, /data-reader-min-text="7\.5"/);const result = await runVisualCheck({ artifactPath: artifact, chromePath });assert.equal(result.exitCode, 0, JSON.stringify(result.receipt, null, 2));@@ -158,7 +159,7 @@ test('route-expanded intrinsic architecture fits every required desktop viewportassert.equal(viewport.overflowX, false, JSON.stringify(viewport, null, 2));assert.equal(viewport.overflowY, false, JSON.stringify(viewport, null, 2));assert.equal(viewport.scrollHeight, viewport.height, JSON.stringify(viewport, null, 2));- assert.ok(viewport.minimumProjectedNodeTextPx >= MIN_PROJECTED_NODE_TEXT_PX);+ assert.ok(viewport.minimumProjectedNodeTextPx >= 7.5 - 0.01);}const desktop = result.receipt.containment.viewports.find(({ width, height }) => (width === DESKTOP_READABILITY_VIEWPORT.width@@ -197,6 +198,7 @@ test('extreme intrinsic architecture keeps readable page scroll below first-screassert.ok(svgRoot, 'expected an SVG root');assert.match(svgRoot, /viewBox="0 0 980 1188"/);assert.match(svgRoot, /data-reader-fit="intrinsic-height"/);+ assert.match(svgRoot, /data-reader-min-text="7\.5"/);const result = await runVisualCheck({ artifactPath: artifact, chromePath });assert.equal(result.exitCode, 0, JSON.stringify(result.receipt, null, 2));@@ -206,11 +208,12 @@ test('extreme intrinsic architecture keeps readable page scroll below first-screassert.equal(result.receipt.viewerChrome.status, 'pass');assert.equal(result.receipt.diagnostics.length, 0, JSON.stringify(result.receipt, null, 2));+ let scrollViewportCount = 0;for (const viewport of result.receipt.containment.viewports) {assert.equal(viewport.overflowX, false, JSON.stringify(viewport, null, 2));- assert.ok(viewport.minimumProjectedNodeTextPx >= MIN_PROJECTED_NODE_TEXT_PX);- if (viewport.width < 2048) {- assert.equal(viewport.overflowY, true, JSON.stringify(viewport, null, 2));+ assert.ok(viewport.minimumProjectedNodeTextPx >= 7.5 - 0.01);+ if (viewport.overflowY) {+ scrollViewportCount += 1;assert.equal(viewport.verticalScrollAccepted, true, JSON.stringify(viewport, null, 2));assert.equal(viewport.overflowDisposition, 'readable-vertical-scroll');assert.equal(viewport.readerLayout, 'adaptive');@@ -222,6 +225,7 @@ test('extreme intrinsic architecture keeps readable page scroll below first-screassert.equal(viewport.overflowDisposition, 'contained');}}+ assert.ok(scrollViewportCount > 0, 'expected the extreme intrinsic diagram to exercise readable page scroll');} finally {fs.rmSync(tmp, { recursive: true, force: true });}diff --git a/archify/test/layout-rules.test.mjs b/archify/test/layout-rules.test.mjsindex 3e5c813e..e4d0c046 100644--- a/archify/test/layout-rules.test.mjs+++ b/archify/test/layout-rules.test.mjs@@ -1309,6 +1309,7 @@ test('architecture: measured auto canvases opt into height-aware reader fitting'const automaticSvg = fs.readFileSync(rendered.outPath, 'utf8').match(/<svg\b[^>]*>/)?.[0];assert.ok(automaticSvg, 'expected an SVG root for the automatic canvas');assert.match(automaticSvg, /data-reader-fit="intrinsic-height"/);+ assert.match(automaticSvg, /data-reader-min-text="7\.5"/);const authored = structuredClone(automatic);authored.meta.viewBox = [1080, 620];@@ -1317,6 +1318,7 @@ test('architecture: measured auto canvases opt into height-aware reader fitting'const authoredSvg = fs.readFileSync(pinned.outPath, 'utf8').match(/<svg\b[^>]*>/)?.[0];assert.ok(authoredSvg, 'expected an SVG root for the authored canvas');assert.doesNotMatch(authoredSvg, /data-reader-fit=/);+ assert.doesNotMatch(authoredSvg, /data-reader-min-text=/);});// Boundary-title fonts are resolved against the same width the canvas actually@@ -1488,6 +1490,26 @@ test('architecture: default auto route selects a safe orthogonal candidate arounassert.match(html, /data-composition-points="560,318;856,318;856,160;880,160"/);});+test('architecture: aligned automatic endpoints still route around an unrelated component', () => {+ const d = {+ schema_version: 1,+ diagram_type: 'architecture',+ meta: { title: 'Aligned obstacle regression', quality_profile: 'showcase' },+ components: [+ { id: 'source', type: 'backend', label: 'Source', pos: [40, 120], size: [140, 60] },+ { id: 'blocker', type: 'security', label: 'Blocker', pos: [240, 120], size: [140, 60] },+ { id: 'target', type: 'database', label: 'Target', pos: [440, 120], size: [140, 60] },+ ],+ connections: [{ id: 'source-target', from: 'source', to: 'target' }],+ };+ const { code, stderr, outPath } = render('architecture', d);+ assert.equal(code, 0, `aligned automatic route must avoid the blocker: ${stderr}`);+ const html = fs.readFileSync(outPath, 'utf8');+ const encoded = html.match(/data-edge-id="source-target" data-composition-points="([^"]+)"/)?.[1];+ assert.ok(encoded, 'expected rendered composition points for source-target');+ assert.ok(encoded.split(';').length >= 6, `expected obstacle-avoiding bends, found ${encoded}`);+});+test('architecture: auto route enters explicit top and bottom ports perpendicularly', () => {const d = {schema_version: 1,@@ -1529,6 +1551,34 @@ test('architecture: auto route preserves inferred side normals when the primaryassert.doesNotMatch(html, /data-composition-points="700,130;700,230;160,230;160,330"/);});+test('architecture: auto route finds a multi-bend path when both side-safe doglegs are blocked', () => {+ const d = {+ schema_version: 1,+ diagram_type: 'architecture',+ meta: { title: 'Multi-bend automatic route regression', quality_profile: 'showcase' },+ components: [+ { id: 'server', type: 'backend', label: 'Server', pos: [280, 240], size: [180, 64] },+ { id: 'upper-blocker', type: 'backend', label: 'Upper blocker', pos: [530, 240], size: [180, 64] },+ { id: 'lower-blocker', type: 'backend', label: 'Lower blocker', pos: [530, 360], size: [180, 64] },+ { id: 'client', type: 'external', label: 'Client', pos: [780, 360], size: [190, 64] },+ ],+ connections: [+ { id: 'client-server', from: 'client', to: 'server' },+ ],+ };+ const { code, stderr, outPath } = render('architecture', d);+ assert.equal(code, 0, `automatic multi-bend route must render cleanly: ${stderr}`);+ const html = fs.readFileSync(outPath, 'utf8');+ const encoded = html.match(/data-edge-id="client-server" data-composition-points="([^"]+)"/)?.[1];+ assert.ok(encoded, 'expected rendered composition points for client-server');+ const points = encoded.split(';').map((point) => point.split(',').map(Number));+ assert.ok(points.length >= 6, `expected a multi-bend route, found ${encoded}`);+ assert.equal(points[0][1], points[1][1], 'route must leave the inferred left port horizontally');+ assert.ok(points[1][0] < points[0][0], 'route must leave the inferred left port leftward');+ assert.equal(points.at(-2)[1], points.at(-1)[1], 'route must enter the inferred right port horizontally');+ assert.ok(points.at(-2)[0] > points.at(-1)[0], 'route must enter the inferred right port leftward');+});+test('architecture: explicit via cannot run tangentially into an authored top port', () => {const d = {schema_version: 1,@@ -1569,12 +1619,20 @@ test('architecture: explicit orthogonal route remains authoritative when it crosassert.match(stderr, /connections\[0\] "api" -> "queue" crosses component "cache"/);});-test('architecture: auto route still fails closed when doglegs and side-aware bridges are blocked', () => {- const d = autoRoutePassThroughDocument({ from: 'api', to: 'queue', variant: 'dashed' });+test('architecture: auto route clears stacked blockers after doglegs and side-aware bridges are blocked', () => {+ const d = autoRoutePassThroughDocument({ id: 'api-queue', from: 'api', to: 'queue', variant: 'dashed' });d.components.push({ id: 'guard', type: 'security', label: 'Guard', pos: [825, 215], size: [70, 50] });- const { code, stderr } = render('architecture', d);- assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);- assert.match(stderr, /connections\[0\] "api" -> "queue" crosses component "cache"/);+ const { code, stderr, outPath } = render('architecture', d);+ assert.equal(code, 0, `automatic multi-bend route must clear both blockers: ${stderr}`);+ const html = fs.readFileSync(outPath, 'utf8');+ const encoded = html.match(/data-edge-id="api-queue" data-composition-points="([^"]+)"/)?.[1];+ assert.ok(encoded, 'expected rendered composition points for api-queue');+ const points = encoded.split(';').map((point) => point.split(',').map(Number));+ assert.ok(points.length >= 6, `expected a multi-bend route, found ${encoded}`);+ assert.equal(points[0][1], points[1][1], 'route must leave the inferred right port horizontally');+ assert.ok(points[1][0] > points[0][0], 'route must leave the inferred right port rightward');+ assert.equal(points.at(-2)[1], points.at(-1)[1], 'route must enter the inferred left port horizontally');+ assert.ok(points.at(-2)[0] < points.at(-1)[0], 'route must enter the inferred left port rightward');});test('architecture: explicit waypoints around an obstacle remain valid by default', () => {@@ -1616,6 +1674,37 @@ test('architecture: showcase rejects an unrelated proper edge crossing', () => {assert.match(stderr, /route\/via|fromSide\/toSide/);});+test('architecture: unavoidable automatic crossing renders as a verified crossover', () => {+ const d = {+ schema_version: 1,+ diagram_type: 'architecture',+ meta: { title: 'Automatic crossover', quality_profile: 'showcase' },+ components: [+ { id: 'left', type: 'frontend', label: 'Left', pos: [40, 170], size: [80, 60] },+ { id: 'right', type: 'backend', label: 'Right', pos: [480, 170], size: [80, 60] },+ { id: 'top', type: 'database', label: 'Top', pos: [260, 20], size: [80, 60] },+ { id: 'bottom', type: 'external', label: 'Bottom', pos: [260, 320], size: [80, 60] },+ ],+ connections: [+ { id: 'horizontal', from: 'left', to: 'right', fromSide: 'right', toSide: 'left' },+ { id: 'vertical', from: 'top', to: 'bottom', fromSide: 'bottom', toSide: 'top' },+ ],+ };+ const { code, stderr, outPath } = render('architecture', d);+ assert.equal(code, 0, stderr);+ const html = fs.readFileSync(outPath, 'utf8');+ assert.equal((html.match(/data-graph-role="automatic-crossover-underlay"/g) || []).length, 2);+ assert.equal((html.match(/data-composition-crossover="halo"/g) || []).length, 2);++ const receipt = JSON.parse(execFileSync('node', [+ path.join(skillRoot, 'scripts', 'check-render-output.mjs'),+ outPath,+ ], { encoding: 'utf8' }));+ assert.equal(receipt.ok, true, JSON.stringify(receipt.composition.issues));+ assert.equal(receipt.composition.metrics.properCrossings, 0);+ assert.equal(receipt.composition.metrics.resolvedCrossovers, 1);+});+test('architecture: showcase preserves a straight-through explicit waypoint as an authored touch', () => {const d = {schema_version: 1,diff --git a/archify/test/render-output-checks.test.mjs b/archify/test/render-output-checks.test.mjsindex c4a944b9..e70c11c1 100644--- a/archify/test/render-output-checks.test.mjs+++ b/archify/test/render-output-checks.test.mjs@@ -203,6 +203,33 @@ test('render output check: showcase rejects a proper X with semantic identities'assert.deepEqual(result.composition.summary, { errors: 1, warnings: 0 });});+test('render output check: verified automatic crossover halos resolve a proper X', () => {+ const { code, result } = checkHtml('showcase-verified-crossover-halo', `+ <path data-graph-role="automatic-crossover-underlay" d="M 20 60 L 200 60" fill="none" stroke="var(--mask)" stroke-width="5.5" pointer-events="none"/>+ <path data-edge-id="left" data-edge-from="a" data-edge-to="b" data-composition-crossover="halo" d="M 20 60 L 200 60" class="a-default" stroke-width="1.5" marker-end="url(#arrowhead)"/>+ <path data-graph-role="automatic-crossover-underlay" d="M 100 20 L 100 120" fill="none" stroke="var(--mask)" stroke-width="5.5" pointer-events="none"/>+ <path data-edge-id="right" data-edge-from="c" data-edge-to="d" data-composition-crossover="halo" d="M 100 20 L 100 120" class="a-dashed" stroke-width="1.5" marker-end="url(#arrowhead-dashed)"/>+ `, 'showcase');+ assert.equal(code, 0, JSON.stringify(result.composition.issues));+ assert.equal(result.composition.metrics.properCrossings, 0);+ assert.equal(result.composition.metrics.resolvedCrossovers, 1);+ assert.deepEqual(result.composition.summary, { errors: 0, warnings: 0 });+});++test('render output check: a crossover marker without a matching underlay fails closed', () => {+ const { code, result } = checkHtml('showcase-unverified-crossover-halo', `+ <path data-graph-role="automatic-crossover-underlay" d="M 20 61 L 200 61" fill="none" stroke="var(--mask)" stroke-width="5.5" pointer-events="none"/>+ <path data-edge-id="left" data-edge-from="a" data-edge-to="b" data-composition-crossover="halo" d="M 20 60 L 200 60" class="a-default" stroke-width="1.5" marker-end="url(#arrowhead)"/>+ <path data-graph-role="automatic-crossover-underlay" d="M 100 20 L 100 120" fill="none" stroke="var(--mask)" stroke-width="5.5" pointer-events="none"/>+ <path data-edge-id="right" data-edge-from="c" data-edge-to="d" data-composition-crossover="halo" d="M 100 20 L 100 120" class="a-dashed" stroke-width="1.5" marker-end="url(#arrowhead-dashed)"/>+ `, 'showcase');+ assert.notEqual(code, 0);+ assert.equal(result.composition.metrics.properCrossings, 1);+ assert.equal(result.composition.metrics.resolvedCrossovers, 0);+ const crossing = result.composition.issues.find((item) => item.code === 'composition/proper-crossing');+ assert.equal(crossing?.severity, 'error');+});+test('render output check: shared endpoints and endpoint touches pass showcase', () => {const { code, result } = checkHtml('showcase-exemptions', `<path data-edge-from="a" data-edge-to="b" d="M 20 60 L 200 60" class="a-default" marker-end="url(#arrowhead)"/>diff --git a/viewer/reader-layout.js b/viewer/reader-layout.jsindex 5b63f8a8..a8b60a5d 100644--- a/viewer/reader-layout.js+++ b/viewer/reader-layout.js@@ -18,6 +18,10 @@var MIN_READER_WIDTH = 960;var MAX_READER_WIDTH = 1920;var MIN_PROJECTED_NODE_TEXT_PX = 6;+ var declaredMinimumText = svg ? parseFloat(svg.getAttribute('data-reader-min-text') || '') : null;+ var requestedMinimumText = Number.isFinite(declaredMinimumText)+ ? Math.max(MIN_PROJECTED_NODE_TEXT_PX, declaredMinimumText)+ : MIN_PROJECTED_NODE_TEXT_PX;var SAFE_BOTTOM_GAP = 12;if (diagram && ratio >= WIDE_RATIO) {@@ -49,7 +53,7 @@}});return sourceMinimum != null- ? Math.min(1, MIN_PROJECTED_NODE_TEXT_PX / sourceMinimum)+ ? Math.min(1, requestedMinimumText / sourceMinimum): 1;}function eligible() {