Skip to content

Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.

fix(architecture): remove avoidable route bends

tt-a1i1e857dd148a3
diff --git a/archify/references/authoring-contract.md b/archify/references/authoring-contract.md
index 358dc5e5..3af34129 100644
--- a/archify/references/authoring-contract.md
+++ b/archify/references/authoring-contract.md
@@ -158,6 +158,7 @@ Generate one responsive artifact for laptops and external displays, preserving t
- Automatic Port Spread is a default renderer behavior for architecture, workflow, and data-flow 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.
+- Showcase reply pins: a relationship pinned to leave and enter the same side fails with `composition/pinned-reply-detour` when it has a reply in the opposite direction and both would render as straight parallel lines without `fromSide`/`toSide`. Remove both relationships' side pins.
- 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.
diff --git a/archify/references/authoring-defaults.md b/archify/references/authoring-defaults.md
index 915d30f5..68ca7838 100644
--- a/archify/references/authoring-defaults.md
+++ b/archify/references/authoring-defaults.md
@@ -22,7 +22,7 @@ Place Architecture nodes by their actual connections before assigning coordinate
Before writing positions, trace each non-main relationship: its straight or one-bend corridor must not pass another node or cross another relationship. If it does, move the endpoint that is off the main path. Start the main actor and its first connected step together near the canvas origin; use content rows for vertical rhythm. Omit `meta.viewBox` for a fresh Architecture so the Reader measures intrinsic height. Keep supplied fixed geometry authoritative.
-Start with automatic routes and endpoint sides. Pin a side only for a necessary branch, return, or supplied geometry. Reserve `via`, `channelX`, `channelY`, and label coordinates for measured defects. Before writing positions, budget each labeled main-path edge at `6.5px × ASCII units + 21px` of clear gap, counting CJK as two units; use its own label length, not a row-wide fixed gap. Size Architecture sublabels for their preferred 9px text at `5.4px × text units + 8px`, with CJK counting twice; keep supporting copy concise without dropping required facts. Do not trade readability or meaning for fewer crossings. The [Geometry reference](authoring-contract.md#executable-geometry-rules) has measured spacing, port, canvas, and route rules for a diagnosed layout problem.
+Start with automatic routes and endpoint sides. Pin a side only for a necessary branch, return, or supplied geometry. A reply between adjacent nodes in one row or column is not a return: leave both directions automatic so they render as two parallel straight lines. Reserve `via`, `channelX`, `channelY`, and label coordinates for measured defects. Before writing positions, budget each labeled main-path edge at `6.5px × ASCII units + 21px` of clear gap, counting CJK as two units; use its own label length, not a row-wide fixed gap. Size Architecture sublabels for their preferred 9px text at `5.4px × text units + 8px`, with CJK counting twice; keep supporting copy concise without dropping required facts. Do not trade readability or meaning for fewer crossings. The [Geometry reference](authoring-contract.md#executable-geometry-rules) has measured spacing, port, canvas, and route rules for a diagnosed layout problem.
## Evidence and schema
diff --git a/archify/renderers/architecture/render-architecture.mjs b/archify/renderers/architecture/render-architecture.mjs
index 4b67b6d9..39670e71 100644
--- a/archify/renderers/architecture/render-architecture.mjs
+++ b/archify/renderers/architecture/render-architecture.mjs
@@ -311,7 +311,7 @@ function layoutBoundaryTitles(rawBoundaries, minimumFontSize) {
// automatic route never borrows a frame border as its corridor), never the
// title-expanded frames or the viewBox.
const rawBoundaries = asArray(arch.boundaries).map(boundaryRect).filter(Boolean);
-const { pathFor, connectionSides, connectionEndpointSide } = createRouter(components, arch.connections, {
+const routerOptions = {
distinctAutomaticPorts: true,
preferReadableRoutes: true,
frames: rawBoundaries.map((boundary) => ({
@@ -325,7 +325,8 @@ const { pathFor, connectionSides, connectionEndpointSide } = createRouter(compon
labels,
components: [...components.values()],
}) : null),
-});
+};
+const { pathFor, connectionSides, connectionEndpointSide } = createRouter(components, arch.connections, routerOptions);
function hasAutomaticRouteGeometry(connection) {
return !Array.isArray(connection?.via)
&& (!connection?.route || connection.route === 'auto')
@@ -777,6 +778,30 @@ function validateArchitecture() {
relationCollection: 'connections',
profile: arch.meta?.quality_profile,
}));
+ // A reply pinned to leave and enter one side detours around both nodes,
+ // although an unpinned reciprocal pair renders as two straight lanes.
+ if ((process.env.ARCHIFY_QUALITY_PROFILE || arch.meta?.quality_profile) === 'showcase') {
+ const relations = asArray(arch.connections);
+ const reported = new Set();
+ for (const [index, conn] of relations.entries()) {
+ if (reported.has(conn) || !components.has(conn.from) || !components.has(conn.to)
+ || !hasAutomaticRouteGeometry(conn) || !conn.fromSide || conn.fromSide === 'auto' || conn.fromSide !== conn.toSide) continue;
+ const reply = relations.find((other) => other.from === conn.to && other.to === conn.from && hasAutomaticRouteGeometry(other));
+ if (!reply) continue;
+ const unpinned = new Map([conn, reply].map((relation) => [relation, { ...relation, fromSide: undefined, toSide: undefined }]));
+ const trial = createRouter(components, relations.map((relation) => unpinned.get(relation) || relation), routerOptions);
+ if (![...unpinned.values()].every((relation) => trial.pathFor(relation).points.length === 2)) continue;
+ reported.add(conn).add(reply);
+ const message = `[composition/pinned-reply-detour] architecture connections[${index}]${conn.id ? ` id "${conn.id}"` : ''} "${conn.from}" -> "${conn.to}" is pinned to leave and enter the ${conn.fromSide} side, so it detours around both nodes; without fromSide/toSide it and its reply "${reply.id || `${reply.from}->${reply.to}`}" render as two parallel straight lines — remove fromSide and toSide from both.`;
+ problems.push(message);
+ diagnostics.push({
+ code: 'composition/pinned-reply-detour', severity: 'error', message,
+ subject: { diagramType: 'architecture', collection: 'connections', id: conn.id, from: conn.from, to: conn.to },
+ evidence: { side: conn.fromSide, replyId: reply.id, points: pathFor(conn).points, unpinnedPoints: [...unpinned.values()].map((relation) => trial.pathFor(relation).points) },
+ supportedFixes: [`remove fromSide and toSide from "${conn.id || `${conn.from}->${conn.to}`}" and its reply`],
+ });
+ }
+ }
// Connection labels must not land on top of components.
const labelRects = connectionLabels;
diff --git a/archify/renderers/architecture/routing.mjs b/archify/renderers/architecture/routing.mjs
index 12a1c39e..f768da18 100644
--- a/archify/renderers/architecture/routing.mjs
+++ b/archify/renderers/architecture/routing.mjs
@@ -327,6 +327,7 @@ export function createRouter(components, connections = [], {
.filter((points) => !collinearBacktrack(points[0], points[1], points[2] || points[1]))
.filter((points) => !collinearBacktrack(points.at(-3) || points.at(-2), points.at(-2), points.at(-1)))
.filter((points) => routeHonorsEndpointSides(points, fromSide, toSide))
+ .sort((a, b) => a.length - b.length)
.map((points) => points.slice(1, -1));
}
@@ -527,15 +528,22 @@ export function createRouter(components, connections = [], {
...(nearParallelPorts ? sideAware : sideSafe),
...(nearParallelPorts ? sideSafe : sideAware),
];
+ let firstFeasible = null;
for (const candidate of ordered) {
const points = [start, ...candidate, end];
- if (routeClearsEndpointComponents(points, from, to)
+ if (!(routeClearsEndpointComponents(points, from, to)
&& routeClearsComponents(conn, points)
&& routeMeetsCompositionFloors(points)
&& !routeConflictsWithResolved(conn, points, resolvedRoutes)
&& (!distinctAutomaticPorts || (!routeOverlapsResolved(conn, points, resolvedRoutes)
- && !siblingCrossings(conn, points, resolvedRoutes)))) return candidate;
+ && !siblingCrossings(conn, points, resolvedRoutes))))) continue;
+ if (!conn.label || !labelRectFor || labelRectFor(conn, points, {
+ routes: resolvedRoutes.map((entry) => entry.points),
+ labels: reservedLabels.map((entry) => entry.rect),
+ })) return candidate;
+ firstFeasible ||= candidate;
}
+ if (firstFeasible) return firstFeasible;
// Siblings fanning out from one side all want the same midpoint
// channel. Step outward through the corridor to a free parallel
// channel before searching.
@@ -1010,6 +1018,39 @@ export function createRouter(components, connections = [], {
};
const withinScene = ([x, y]) => x >= bounds.left && x <= bounds.right && y >= bounds.top && y <= bounds.bottom;
const jointlyImproved = new Set();
+ const endpointSlotsClear = (candidateRoutes, others, sidesOf) => {
+ const entries = [...others, ...candidateRoutes];
+ for (const candidate of candidateRoutes) {
+ const sides = sidesOf(candidate.conn);
+ for (const [componentId, side, point] of [
+ [candidate.conn.from, sides.fromSide, candidate.points[0]],
+ [candidate.conn.to, sides.toSide, candidate.points.at(-1)],
+ ]) {
+ const coordinate = side === 'left' || side === 'right' ? 1 : 0;
+ for (const other of entries) {
+ if (other.conn === candidate.conn) continue;
+ const otherSides = sidesOf(other.conn);
+ for (const [otherId, otherSide, otherPoint] of [
+ [other.conn.from, otherSides.fromSide, other.points[0]],
+ [other.conn.to, otherSides.toSide, other.points.at(-1)],
+ ]) {
+ if (componentId === otherId && side === otherSide
+ && Math.abs(point[coordinate] - otherPoint[coordinate])
+ < portSpacing(candidate.conn, other.conn) - 0.0001) return false;
+ }
+ }
+ }
+ }
+ return true;
+ };
+ const labelClears = (rect, owner, entries, labels) => {
+ if (!rect) return !owner.label;
+ if (!withinScene([rect.x, rect.y])
+ || !withinScene([rect.x + rect.width, rect.y + rect.height])
+ || labels.some((other) => rectsOverlap(rect, other.rect, 2))) return false;
+ return entries.every((entry) => entry.conn === owner || entry.points.slice(1).every((end, index) =>
+ !segmentIntersectsRect({ start: entry.points[index], end }, rect, LABEL_CLEARANCE)));
+ };
function improveReciprocalPairs() {
// A one-route sweep cannot repair reciprocal facing edges whose initial
// spread groups differ. Try both direct lanes together after final side
@@ -1057,40 +1098,8 @@ export function createRouter(components, connections = [], {
end[axis] = lane;
return { points: [start, end], d: roundedPath([start, end], 8) };
};
- const endpointSlotsClear = (candidateRoutes) => {
- const entries = [...others, ...candidateRoutes];
- for (const candidate of candidateRoutes) {
- const sides = candidate.conn === conn ? firstSides : secondSides;
- for (const [componentId, side, point] of [
- [candidate.conn.from, sides.fromSide, candidate.points[0]],
- [candidate.conn.to, sides.toSide, candidate.points.at(-1)],
- ]) {
- const coordinate = side === 'left' || side === 'right' ? 1 : 0;
- for (const other of entries) {
- if (other.conn === candidate.conn) continue;
- const otherSides = other.conn === conn ? firstSides
- : other.conn === second.conn ? secondSides : selectedSides.get(other.conn);
- for (const [otherId, otherSide, otherPoint] of [
- [other.conn.from, otherSides.fromSide, other.points[0]],
- [other.conn.to, otherSides.toSide, other.points.at(-1)],
- ]) {
- if (componentId === otherId && side === otherSide
- && Math.abs(point[coordinate] - otherPoint[coordinate])
- < portSpacing(candidate.conn, other.conn) - 0.0001) return false;
- }
- }
- }
- }
- return true;
- };
- const labelClears = (rect, owner, entries, labels) => {
- if (!rect) return !owner.label;
- if (!withinScene([rect.x, rect.y])
- || !withinScene([rect.x + rect.width, rect.y + rect.height])
- || labels.some((other) => rectsOverlap(rect, other.rect, 2))) return false;
- return entries.every((entry) => entry.conn === owner || entry.points.slice(1).every((end, index) =>
- !segmentIntersectsRect({ start: entry.points[index], end }, rect, LABEL_CLEARANCE)));
- };
+ const pairSides = (candidate) => (candidate === conn ? firstSides
+ : candidate === second.conn ? secondSides : selectedSides.get(candidate));
let best = null;
let bestCost = readabilityCost(conn, first, [...others, second])
+ readabilityCost(second.conn, second, [...others, first]);
@@ -1101,7 +1110,7 @@ export function createRouter(components, connections = [], {
const secondRoute = { conn: second.conn, ...direct(secondGeometry, secondLane) };
const candidates = [firstRoute, secondRoute];
if (!candidates.every((entry) => entry.points.every(withinScene))) continue;
- if (!endpointSlotsClear(candidates)) continue;
+ if (!endpointSlotsClear(candidates, others, pairSides)) continue;
if (!candidates.every((entry, index) => {
const geometry = entry.conn === conn ? firstGeometry : secondGeometry;
if (!portHasCornerClearance(geometry.from, geometry.fromSide, entry.points[0])
@@ -1152,7 +1161,7 @@ export function createRouter(components, connections = [], {
improveReciprocalPairs();
for (const entry of resolvedRoutes) {
const { conn } = entry;
- if (jointlyImproved.has(conn) || hasAuthoredRouteGeometry(conn) || conn.labelAt) continue;
+ if (jointlyImproved.has(conn) || hasAuthoredRouteGeometry(conn) || hasAuthoredLabelPlacement(conn)) continue;
const others = resolvedRoutes.filter((other) => other !== entry);
// Preserve uncomplicated routes and their established inferred sides.
// Spend the comparison budget where the complete scene has a reading
@@ -1185,6 +1194,51 @@ export function createRouter(components, connections = [], {
reservedLabels = reservedLabels.filter((label) => label.conn !== conn);
if (best.rect) reservedLabels.push({ conn, rect: best.rect });
}
+ // A dogleg between facing sides whose nodes overlap across the route
+ // can run straight inside that overlap. Every other route, slot and
+ // label stays fixed, and the straight lane must pass the same checks.
+ for (const entry of resolvedRoutes) {
+ const { conn } = entry;
+ if (entry.points.length !== 4 || jointlyImproved.has(conn)
+ || hasAuthoredRouteGeometry(conn) || hasAuthoredLabelPlacement(conn)) continue;
+ const sides = selectedSides.get(conn);
+ const facing = `${sides.fromSide}>${sides.toSide}`;
+ const axis = facing === 'right>left' || facing === 'left>right' ? 1
+ : facing === 'bottom>top' || facing === 'top>bottom' ? 0 : null;
+ if (axis === null) continue;
+ const geometry = connectionGeometry(conn, sides);
+ const [origin, size] = axis === 1 ? ['y', 'height'] : ['x', 'width'];
+ const low = Math.max(geometry.from[origin], geometry.to[origin]) + AUTOMATIC_PORT_CORNER_GUTTER;
+ const high = Math.min(geometry.from[origin] + geometry.from[size], geometry.to[origin] + geometry.to[size])
+ - AUTOMATIC_PORT_CORNER_GUTTER;
+ if (high < low) continue;
+ const start = entry.points[0];
+ const end = entry.points.at(-1);
+ const clamp = (value) => Math.min(high, Math.max(low, value));
+ const others = resolvedRoutes.filter((other) => other !== entry);
+ const otherLabels = reservedLabels.filter((label) => label.conn !== conn);
+ const crossingsBefore = crossingCount(conn, entry.points, others);
+ for (const lane of new Set([start[axis], end[axis], (start[axis] + end[axis]) / 2, (low + high) / 2].map(clamp))) {
+ const points = [[...start], [...end]];
+ points[0][axis] = lane;
+ points[1][axis] = lane;
+ const routed = { conn, points, d: roundedPath(points, 8) };
+ if (!points.every(withinScene)
+ || !endpointSlotsClear([routed], others, (candidate) => selectedSides.get(candidate))
+ || !routeIsClear(conn, routed, geometry, others)
+ || crossingCount(conn, points, others) > crossingsBefore) continue;
+ const rect = labelRectFor?.(conn, points, {
+ routes: [...others.map((other) => other.points), points],
+ labels: otherLabels.map((label) => label.rect),
+ });
+ if (!labelClears(rect, conn, others, otherLabels)) continue;
+ cachePath(conn, { points, d: routed.d }, sides);
+ entry.points = points;
+ planningMetrics.readabilityImprovedCount += 1;
+ reservedLabels = [...otherLabels, ...(rect ? [{ conn, rect }] : [])];
+ break;
+ }
+ }
} finally {
allowGridSearch = true;
}
diff --git a/test/architecture-route-bends.test.mjs b/test/architecture-route-bends.test.mjs
new file mode 100644
index 00000000..d06a7b9f
--- /dev/null
+++ b/test/architecture-route-bends.test.mjs
@@ -0,0 +1,87 @@
+import { test } from 'node:test';
+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 { fileURLToPath } from 'node:url';
+import { createRouter } from '../archify/renderers/architecture/routing.mjs';
+
+const cli = fileURLToPath(new URL('../archify/bin/archify.mjs', import.meta.url));
+
+function box(id, x, y, width = 230, height = 80) {
+ return [id, { id, x, y, width, height, cx: x + width / 2, cy: y + height / 2 }];
+}
+
+// The hive runtime case: a bottom-to-left relationship shares the runtime's
+// bottom side with an upward security link. Both a three-bend stub route and
+// a one-bend corner pass every check at the same length.
+function scene(labelRectFor) {
+ const boxes = new Map([box('runtime', 440, 230), box('tasks', 870, 450), box('tunnel', 440, 650)]);
+ const connections = [
+ { id: 'tasks', from: 'runtime', to: 'tasks', label: 'watch', fromSide: 'bottom', toSide: 'left' },
+ { id: 'tunnel', from: 'tunnel', to: 'runtime', fromSide: 'top', toSide: 'bottom' },
+ ];
+ const router = createRouter(boxes, connections, { distinctAutomaticPorts: true, preferReadableRoutes: true, labelRectFor });
+ return router.pathFor(connections[0]).points;
+}
+
+test('architecture takes the fewest-bend route among equally long side-aware candidates', () => {
+ const points = scene();
+ assert.equal(points.length, 3, JSON.stringify(points));
+ assert.deepEqual(points.at(-1), [870, 490]);
+ assert.equal(points[1][1], 490);
+});
+
+test('architecture keeps a feasible route with label room over a fewer-bend route without it', () => {
+ const points = scene((conn, route) => (route.length > 3 ? { x: 0, y: 0, width: 1, height: 1 } : null));
+ assert.equal(points.length, 5, JSON.stringify(points));
+});
+
+function validate(t, profile, replySides) {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-pinned-reply-'));
+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
+ const input = path.join(directory, 'diagram.json');
+ fs.writeFileSync(input, JSON.stringify({
+ schema_version: 1,
+ diagram_type: 'architecture',
+ meta: { title: 'Reply', output: 'diagram.html', quality_profile: profile },
+ components: [
+ { id: 'runtime', type: 'backend', label: 'Runtime', pos: [40, 120], size: [200, 80] },
+ { id: 'agents', type: 'backend', label: 'Agents', pos: [440, 120], size: [200, 80] },
+ ],
+ connections: [
+ { id: 'spawn', from: 'runtime', to: 'agents', label: 'spawn' },
+ { id: 'report', from: 'agents', to: 'runtime', label: 'report', ...replySides },
+ ],
+ }));
+ const result = spawnSync(process.execPath, [cli, 'validate', 'architecture', input, '--quality', profile, '--json'], {
+ cwd: directory, encoding: 'utf8',
+ });
+ return { status: result.status, receipt: JSON.parse(result.stdout) };
+}
+
+test('showcase rejects a reply pinned around both nodes when the pair fits two straight lanes', t => {
+ const { status, receipt } = validate(t, 'showcase', { fromSide: 'top', toSide: 'top' });
+ assert.equal(status, 1);
+ const diagnosis = receipt.diagnostics.find(({ code }) => code === 'composition/pinned-reply-detour');
+ assert.ok(diagnosis, JSON.stringify(receipt.diagnostics));
+ assert.equal(diagnosis.subject.id, 'report');
+ assert.equal(diagnosis.evidence.replyId, 'spawn');
+ assert.ok(diagnosis.evidence.unpinnedPoints.every((points) => points.length === 2));
+ assert.equal(validate(t, 'showcase', {}).status, 0);
+ assert.equal(validate(t, 'standard', { fromSide: 'top', toSide: 'top' }).status, 0);
+});
+
+test('architecture straightens a dogleg between facing nodes that overlap across the route', () => {
+ const boxes = new Map([box('api', 40, 100, 200, 80), box('worker', 440, 130, 200, 80), box('store', 440, 330, 200, 80)]);
+ const connections = [
+ { id: 'run', from: 'api', to: 'worker' },
+ { id: 'save', from: 'worker', to: 'store' },
+ ];
+ const router = createRouter(boxes, connections, { distinctAutomaticPorts: true, preferReadableRoutes: true });
+ const points = router.pathFor(connections[0]).points;
+ assert.equal(points.length, 2, JSON.stringify(points));
+ assert.equal(points[0][1], points[1][1]);
+ assert.ok(points[0][1] >= 146 && points[0][1] <= 164, JSON.stringify(points));
+});