Skip to content

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

Resolve colliding automatic architecture labels near their existing routes

tt-a1i71e67b54b038
diff --git a/archify/references/authoring-contract.md b/archify/references/authoring-contract.md
index 9891ceb4..318aee0f 100644
--- a/archify/references/authoring-contract.md
+++ b/archify/references/authoring-contract.md
@@ -154,6 +154,15 @@ apply the other geometry rules above.
### Spacing and labels
+In showcase Architecture, an unpinned connection label keeps its default position
+when clear. If it collides, the renderer tries a bounded set of nearby positions
+along the existing route, avoiding nodes, boundary titles, other labels and
+other routes within the resolved canvas. Explicit `labelAt`, `labelDx`, `labelDy`
+or `labelSegment` (including zero) disables this fallback. Routes and topology
+stay unchanged; if no nearby position is clear, validation reports the original
+collision. Inspect resolved labels with `--layout-json` before adding controls.
+Standard placement retains its existing behavior.
+
Spacing recommendations mean clear gap between boxes, not center distance. A 200px center distance between 165px-wide nodes leaves only 35px of clear gap.
For a relationship label, require:
diff --git a/archify/renderers/architecture/labels.mjs b/archify/renderers/architecture/labels.mjs
new file mode 100644
index 00000000..960293af
--- /dev/null
+++ b/archify/renderers/architecture/labels.mjs
@@ -0,0 +1,61 @@
+import { normalizeRoutePoints, rectsOverlap, segmentRectClearance } from '../shared/geometry.mjs';
+
+// A bounded fallback for an unpinned label whose usual position collides.
+// It never routes an edge, moves a node, expands the canvas, or rewrites input.
+export function placeAutomaticLabels({ labels, routes, components, titles, viewBox, placementBottom = viewBox[1] }) {
+ const placed = [...labels];
+ const obstacles = [...components, ...titles];
+ const segments = routes.flatMap(({ relationIndex, points }) => {
+ const normalized = normalizeRoutePoints(points);
+ return normalized.slice(1).map((end, index) => ({ relationIndex, start: normalized[index], end }));
+ });
+ const inside = rect => (
+ rect.x >= 0 && rect.y >= 0
+ && rect.x + rect.width <= viewBox[0] && rect.y + rect.height <= viewBox[1]
+ );
+ const masksRoute = rect => segments.some(segment => segment.relationIndex !== rect.relationIndex
+ && segmentRectClearance(segment, rect) + 0.0001 < 4);
+ const overlapsLabel = (rect, index, gap = 0) => placed.some((other, otherIndex) => (
+ otherIndex !== index && rectsOverlap(rect, other, gap)
+ ));
+ const clear = (rect, index) => (
+ inside(rect) && rect.y + rect.height <= placementBottom
+ && !obstacles.some(obstacle => rectsOverlap(rect, obstacle, 2))
+ && !overlapsLabel(rect, index, 2) && !masksRoute(rect)
+ );
+
+ for (const [index, label] of placed.entries()) {
+ const relation = label.relation;
+ if (['labelAt', 'labelDx', 'labelDy', 'labelSegment'].some(key => relation[key] !== undefined)) continue;
+ // Match actual defect thresholds before searching; a valid placement is
+ // not a reason to restyle the diagram. New placements leave extra space.
+ if (inside(label) && !components.some(component => rectsOverlap(label, component, -2))
+ && !titles.some(title => rectsOverlap(label, title))
+ && !overlapsLabel(label, index) && !masksRoute(label)) continue;
+ for (const segment of segments.filter(segment => segment.relationIndex === label.relationIndex)) {
+ const [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 => {
+ 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]];
+ });
+ } 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 => {
+ 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]];
+ });
+ }
+ const replacement = candidates.map(([lx, ly]) => ({
+ ...label, lx, ly, x: lx - label.width / 2, y: ly - 10,
+ })).find(rect => clear(rect, index));
+ if (replacement) {
+ placed[index] = replacement;
+ break;
+ }
+ }
+ }
+ return placed;
+}
diff --git a/archify/renderers/architecture/render-architecture.mjs b/archify/renderers/architecture/render-architecture.mjs
index 3b2f2fa4..0d5780c4 100644
--- a/archify/renderers/architecture/render-architecture.mjs
+++ b/archify/renderers/architecture/render-architecture.mjs
@@ -11,6 +11,7 @@ import { minimumReadableSourceTextPx } from '../shared/desktop-readability.mjs';
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 {
asArray,
isFinitePoint,
@@ -144,9 +145,10 @@ const architectureLegendEntries = resolveLegend(
// One source for connection label geometry: the rect the containment rule
// measures is the rect the SVG mask draws, the auto canvas covers, the legend
// avoids, and the layout report publishes.
+const resolvedLabelPoints = new Map();
function connectionLabelBox(conn) {
if (!conn.label) return null;
- const [lx, ly] = labelPoint(conn, pathFor(conn).points);
+ const [lx, ly] = resolvedLabelPoints.get(conn) || labelPoint(conn, pathFor(conn).points);
const width = Math.max(30, textUnits(conn.label) * 4.8 + 10);
return { x: lx - width / 2, y: ly - 10, width, height: 14, lx, ly };
}
@@ -301,7 +303,7 @@ function layoutBoundaryTitles(rawBoundaries, minimumFontSize) {
const { pathFor, connectionSides, connectionEndpointSide } = createRouter(components, arch.connections);
// The auto canvas has to cover these rects; an authored viewBox is never
// resized to fit them — there the containment rule reports the clipping.
-const connectionLabels = connectionLabelRects();
+let connectionLabels = connectionLabelRects();
// Unlabelled outer corridors are geometry too. Fitting only nodes and labels
// can clip a valid explicit via route while every browser overflow check passes.
const connectionGeometry = [
@@ -371,6 +373,28 @@ function componentContext(component) {
const viewBox = arch.meta?.viewBox || autoViewBoxFor(boundaries, connectionGeometry);
const legendY = () => viewBox[1] - 16;
+// Fit titles and canvas from the original geometry first. Fallback labels must
+// fit inside that canvas, so moving a label cannot trigger title reflow or a
+// canvas/label feedback loop. Keep standard and every authored label control.
+if (arch.meta?.quality_profile === 'showcase') {
+ connectionLabels = placeAutomaticLabels({
+ labels: connectionLabels,
+ routes: asArray(arch.connections).flatMap((conn, relationIndex) => (
+ components.has(conn.from) && components.has(conn.to)
+ ? [{ relationIndex, points: pathFor(conn).points }] : []
+ )),
+ components: [...components.values()],
+ titles: boundaries.map(boundary => boundary.title),
+ viewBox,
+ // Leave the resolved legend band available; moving a label must not hide
+ // an otherwise visible legend. Existing labels keep their placement.
+ placementBottom: architectureLegendEntries.length
+ ? legendY() - 32 - legendFootprint(architectureLegendEntries, { width: viewBox[0] - layout.margin * 2 }).extraHeight
+ : viewBox[1],
+ });
+ for (const rect of connectionLabels) resolvedLabelPoints.set(rect.relation, [rect.lx, rect.ly]);
+}
+
// ---- Validation: mechanical correctness, never layout taste -----------------
function validateArchitecture() {
const problems = [];
@@ -707,7 +731,7 @@ function buildLayoutReport() {
.filter((conn) => components.has(conn.from) && components.has(conn.to))
.map((conn) => {
const routed = pathFor(conn);
- const labelAt = conn.label ? labelPoint(conn, routed.points) : null;
+ const labelAt = conn.label ? resolvedLabelPoints.get(conn) || labelPoint(conn, routed.points) : null;
return connectionPath(conn, routed, labelAt);
}),
labels,
diff --git a/archify/test/architecture-automatic-labels.test.mjs b/archify/test/architecture-automatic-labels.test.mjs
new file mode 100644
index 00000000..6f69dd60
--- /dev/null
+++ b/archify/test/architecture-automatic-labels.test.mjs
@@ -0,0 +1,120 @@
+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';
+import { collectLabelRouteClearance, rectsOverlap, labelPoint } from '../renderers/shared/geometry.mjs';
+
+const root = fileURLToPath(new URL('../', import.meta.url));
+const cli = path.join(root, 'bin/archify.mjs');
+function inspect(t, diagram, extra = []) {
+ const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-auto-labels-'));
+ t.after(() => fs.rmSync(cwd, { recursive: true, force: true }));
+ const input = path.join(cwd, 'source.json');
+ const source = JSON.stringify(diagram);
+ fs.writeFileSync(input, source);
+ const result = spawnSync(process.execPath, [cli, 'validate', 'architecture', input, '--layout-json', ...extra], { encoding: 'utf8' });
+ assert.equal(result.stderr, '');
+ assert.equal(fs.readFileSync(input, 'utf8'), source);
+ return { result, report: JSON.parse(result.stdout), cwd, input };
+}
+function vertical() {
+ return {
+ schema_version: 1, diagram_type: 'architecture',
+ meta: { title: 'Cache read', 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] },
+ ],
+ connections: [{ id: 'read', from: 'api', to: 'cache', label: 'Read cache' }],
+ };
+}
+function assertLabelsClear(diagram, report) {
+ for (const label of report.labels) {
+ for (const component of report.components) assert.equal(rectsOverlap(label, component, -2), false);
+ }
+ const hits = collectLabelRouteClearance({
+ labels: report.labels.map((label, relationIndex) => ({ ...label, relationIndex, relation: diagram.connections[relationIndex] })),
+ routedRelations: report.connections.map((route, relationIndex) => ({ ...route, relationIndex, relation: diagram.connections[relationIndex] })),
+ threshold: 4,
+ });
+ assert.deepEqual(hits, []);
+}
+
+test('vertical auto label clears the source without moving endpoints and is consistent in delivered SVG', t => {
+ const diagram = vertical();
+ const { result, report, input, cwd } = inspect(t, diagram);
+ assert.equal(result.status, 0, result.stdout);
+ assert.deepEqual(report.connections[0].points, [[180, 130], [180, 320]]);
+ assert.deepEqual(report.viewBox, diagram.meta.viewBox);
+ assertLabelsClear(diagram, report);
+ assert.notDeepEqual(report.connections[0].labelAt, labelPoint(diagram.connections[0], report.connections[0].points));
+ const output = path.join(cwd, 'out.html');
+ const delivery = spawnSync(process.execPath, [cli, 'deliver', 'architecture', input, output, '--json'], { encoding: 'utf8' });
+ assert.equal(delivery.status, 0, delivery.stdout + delivery.stderr);
+ const [x, y] = report.connections[0].labelAt;
+ assert.ok(fs.readFileSync(output, 'utf8').includes(`<text x="${x}" y="${y}"`));
+ const check = spawnSync(process.execPath, [cli, 'check', output, '--require-provenance'], { encoding: 'utf8' });
+ assert.equal(check.status, 0, check.stdout + check.stderr);
+});
+
+test('frozen K2.8 draft loses two label defects but retains its actual route 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']);
+ assertLabelsClear(diagram, report);
+ const standard = structuredClone(diagram);
+ standard.meta.quality_profile = 'standard';
+ const old = inspect(t, standard).report;
+ assert.deepEqual(report.components, old.components);
+ assert.deepEqual(report.connections.map(c => c.points), old.connections.map(c => c.points));
+ assert.deepEqual(report.viewBox, old.viewBox);
+ assert.deepEqual(report.connections.map(c => [c.from, c.to, c.label]), old.connections.map(c => [c.from, c.to, c.label]));
+ assert.deepEqual(report.labels, inspect(t, diagram).report.labels);
+});
+
+for (const control of [{ labelDx: 0 }, { labelDy: 0 }, { labelSegment: 0 }, { labelAt: [180, 120] }]) {
+ test(`explicit ${Object.keys(control)[0]} preserves the authored collision and failure`, t => {
+ const diagram = vertical();
+ Object.assign(diagram.connections[0], control);
+ const { report, result } = inspect(t, diagram);
+ assert.equal(result.status, 1);
+ assert.deepEqual(report.connections[0].labelAt, [180, 120]);
+ assert.ok(report.diagnostics.some(d => /overlaps component/.test(d.message)));
+ });
+}
+
+test('standard preserves default placement and failure', t => {
+ const diagram = vertical();
+ diagram.meta.quality_profile = 'standard';
+ const { result, report } = inspect(t, diagram);
+ assert.equal(result.status, 1);
+ assert.deepEqual(report.connections[0].labelAt, [180, 120]);
+});
+
+test('clear horizontal label and explicit route points stay unchanged', t => {
+ const diagram = vertical();
+ diagram.components[1].pos = [340, 70];
+ diagram.connections[0].label = 'Read';
+ diagram.connections[0].via = [[300, 100]];
+ const { result, report } = inspect(t, diagram);
+ assert.equal(result.status, 0, result.stdout);
+ assert.deepEqual(report.connections[0].points, [[240, 100], [300, 100], [340, 100]]);
+ assert.deepEqual(report.connections[0].labelAt, [320, 90]);
+});
+
+test('no nearby valid position preserves the diagnostic instead of 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] },
+ );
+ const { result, report } = inspect(t, diagram);
+ assert.equal(result.status, 1);
+ assert.deepEqual(report.connections[0].labelAt, [180, 120]);
+ assert.equal(report.labels[0].text, 'Read cache');
+});
diff --git a/archify/test/fixtures/architecture-label-repair/worldscope.json b/archify/test/fixtures/architecture-label-repair/worldscope.json
new file mode 100644
index 00000000..fcc9f2cc
--- /dev/null
+++ b/archify/test/fixtures/architecture-label-repair/worldscope.json
@@ -0,0 +1,37 @@
+{
+ "schema_version": 1,
+ "diagram_type": "architecture",
+ "meta": {
+ "title": "WorldScope 系统架构",
+ "locale": "zh-CN",
+ "quality_profile": "showcase"
+ },
+ "components": [
+ { "id": "browser", "type": "frontend", "label": "React 工作台", "sublabel": "浏览器端交互界面", "pos": [60, 110], "size": [150, 64] },
+ { "id": "api", "type": "backend", "label": "读取模型 API", "sublabel": "FastAPI", "pos": [290, 110], "size": [150, 64] },
+ { "id": "agent", "type": "backend", "label": "地图 Agent", "sublabel": "Agent 编排", "pos": [530, 110], "size": [150, 64] },
+ { "id": "llm", "type": "external", "label": "模型端点", "sublabel": "外部 LLM 服务", "pos": [790, 110], "size": [150, 64] },
+ { "id": "sources", "type": "external", "label": "公开数据源", "sublabel": "外部公开数据", "pos": [60, 300], "size": [150, 64] },
+ { "id": "worker", "type": "backend", "label": "采集 Worker", "sublabel": "定时采集任务", "pos": [410, 300], "size": [150, 64] },
+ { "id": "cache", "type": "database", "label": "Redis", "sublabel": "缓存 / last-good", "pos": [290, 480], "size": [150, 64] },
+ { "id": "context", "type": "database", "label": "World Context", "sublabel": "PostgreSQL + PostGIS", "pos": [560, 480], "size": [170, 64] }
+ ],
+ "boundaries": [
+ { "kind": "region", "label": "后端服务", "wraps": ["api", "agent", "worker"] }
+ ],
+ "connections": [
+ { "id": "browser-to-api", "from": "browser", "to": "api", "label": "REST / SSE" },
+ { "id": "api-to-agent", "from": "api", "to": "agent", "label": "受信附件身份" },
+ { "id": "agent-to-llm", "from": "agent", "to": "llm", "label": "流式回答" },
+ { "id": "api-to-context", "from": "api", "to": "context", "label": "事实检索" },
+ { "id": "agent-to-context", "from": "agent", "to": "context", "label": "证据检索" },
+ { "id": "api-to-cache", "from": "api", "to": "cache", "label": "读取缓存" },
+ { "id": "sources-to-worker", "from": "sources", "to": "worker", "label": "定时采集" },
+ { "id": "worker-to-context", "from": "worker", "to": "context", "label": "写入证据" },
+ { "id": "worker-to-cache", "from": "worker", "to": "cache", "label": "刷新 last-good" }
+ ],
+ "cards": [
+ { "dot": "cyan", "title": "读取路径", "items": ["React 工作台经 REST / SSE 访问 FastAPI", "API 直查 World Context 事实库并读穿 Redis 缓存", "地图 Agent 携受信附件身份向模型端点流式提问"] },
+ { "dot": "emerald", "title": "采集路径", "items": ["Worker 定时从公开数据源采集证据", "证据写入 PostgreSQL + PostGIS 持久事实库", "同时刷新 Redis 的 last-good 快照"] }
+ ]
+}