Skip to content

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

fix(class): route first drafts without crossings and place colliding labels clear of types and markers

tt-a1ib077efce052e
diff --git a/archify/renderers/class/render-class.mjs b/archify/renderers/class/render-class.mjs
index d4a72c4d..9ae4b4bc 100644
--- a/archify/renderers/class/render-class.mjs
+++ b/archify/renderers/class/render-class.mjs
@@ -40,6 +40,7 @@ import {
suggestLabelObstacleFix,
} from '../shared/geometry.mjs';
import { createRouter } from '../architecture/routing.mjs';
+import { placeAutomaticLabels } from '../shared/automatic-labels.mjs';
import { connectionPath as relationshipPath } from '../shared/layout-report.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -436,6 +437,12 @@ const busPaths = new Map();
const router = createRouter(types, routable.filter((relationship) => !busPaths.has(relationship)), {
sideFor,
maxPortSpacing: PORT_SPACING,
+ // As for the ERD: re-plan a route against the complete scene when it crosses
+ // or bends needlessly, and look for a detour that crosses nothing before the
+ // obstacle search that may cross earlier routes. The showcase gate rejects
+ // any proper crossing, so the shorter crossing route only buys a repair.
+ preferReadableRoutes: true,
+ crossingFreeGridFirst: true,
});
function pathFor(relationship) {
const points = busPaths.get(relationship);
@@ -460,7 +467,11 @@ function relationshipLabelWidth(relationship) {
// A label sits on the segment with the most room unless the author picks one:
// above a horizontal run, beside a vertical one, so it never covers its own
// line or lands on the box the relationship leaves.
+const resolvedLabelPoints = new Map();
function relationshipLabelPoint(relationship) {
+ return resolvedLabelPoints.get(relationship) ?? defaultRelationshipLabelPoint(relationship);
+}
+function defaultRelationshipLabelPoint(relationship) {
if (relationship.labelAt) return relationship.labelAt;
const points = pathFor(relationship).points;
const width = relationshipLabelWidth(relationship);
@@ -484,6 +495,52 @@ function relationshipLabelBox(relationship) {
return { x: lx - width / 2, y: ly - 10, width, height: 14 };
}
+// The default point picks the roomiest segment but knows nothing about other
+// routes, markers, or types near it. A colliding unpinned label goes through the
+// shared bounded placer (architecture, dataflow, and erd use it too), with
+// every end marker reserved, so it moves beside its own route instead of
+// failing the gate; a clear default is kept as it is.
+const MARKER_REACH = 20;
+// Half the tallest marker plus the 2-unit overlap the placer tolerates.
+const MARKER_HALF = 10;
+function markerBox([x, y], side) {
+ if (side === 'left') return { x: x - MARKER_REACH, y: y - MARKER_HALF, width: MARKER_REACH, height: MARKER_HALF * 2 };
+ if (side === 'right') return { x, y: y - MARKER_HALF, width: MARKER_REACH, height: MARKER_HALF * 2 };
+ if (side === 'top') return { x: x - MARKER_HALF, y: y - MARKER_REACH, width: MARKER_HALF * 2, height: MARKER_REACH };
+ return { x: x - MARKER_HALF, y, width: MARKER_HALF * 2, height: MARKER_REACH };
+}
+{
+ const labels = routable.filter((relationship) => relationship.label).map((relationship) => {
+ const [lx, ly] = defaultRelationshipLabelPoint(relationship);
+ return { relation: relationship, relationIndex: relationships.indexOf(relationship), label: relationship.label,
+ ...relationshipLabelBox(relationship), lx, ly };
+ });
+ if (labels.length) {
+ const markers = routable.flatMap((relationship) => {
+ const { points } = pathFor(relationship);
+ return [
+ markerBox(points[0], connectionEndpointSide(relationship, 'source')),
+ markerBox(points.at(-1), connectionEndpointSide(relationship, 'target')),
+ ];
+ });
+ const footprint = legendEntries.length
+ ? layout.legendH + legendFootprint(legendEntries, { width: Math.max(1, viewBox[0] - layout.margin * 2) }).extraHeight
+ : 0;
+ const placed = placeAutomaticLabels({
+ labels,
+ routes: routable.map((relationship) => ({ relationIndex: relationships.indexOf(relationship), points: pathFor(relationship).points })),
+ components: [...types.values(), ...markers],
+ titles: [],
+ viewBox,
+ placementBottom: viewBox[1] - footprint,
+ keepFallbackNearRoute: true,
+ });
+ placed.forEach((rect, index) => {
+ if (rect !== labels[index]) resolvedLabelPoints.set(rect.relation, [rect.lx, rect.ly]);
+ });
+ }
+}
+
// ---- Validation ----------------------------------------------------------------
function detail(code, message, subject, evidence, supportedFixes) {
return { code, severity: 'error', message, subject: { diagramType: 'class', ...subject }, evidence, supportedFixes };
diff --git a/test/class-first-draft-layout.test.mjs b/test/class-first-draft-layout.test.mjs
new file mode 100644
index 00000000..5f46f3d3
--- /dev/null
+++ b/test/class-first-draft-layout.test.mjs
@@ -0,0 +1,93 @@
+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 { properSegmentIntersection, rectsOverlap } from '../archify/renderers/shared/geometry.mjs';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const skillRoot = path.resolve(__dirname, '..', 'archify');
+const renderer = path.join(skillRoot, 'renderers', 'class', 'render-class.mjs');
+const cli = path.join(skillRoot, 'bin', 'archify.mjs');
+const fixtures = path.join(__dirname, 'fixtures', 'class-first-draft');
+
+function render(diagram) {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-class-first-draft-'));
+ const input = path.join(directory, 'candidate.json');
+ const output = path.join(directory, 'candidate.html');
+ fs.writeFileSync(input, JSON.stringify(diagram));
+ const result = spawnSync(process.execPath, [renderer, input, output], { cwd: directory, encoding: 'utf8' });
+ return { ...result, input, html: result.status === 0 ? fs.readFileSync(output, 'utf8') : '' };
+}
+
+const attrs = (tag) => Object.fromEntries([...tag.matchAll(/([a-zA-Z-]+)="([^"]*)"/g)].map((match) => [match[1], match[2]]));
+const svgOf = (html) => html.match(/<svg\b[\s\S]*?<\/svg>/i)[0];
+
+function routes(html) {
+ return [...svgOf(html).matchAll(/<path\b[^>]*data-class-relationship[^>]*>/g)].map((match) => attrs(match[0]))
+ .filter((route) => route['data-composition-points'])
+ .map((route) => ({
+ id: route['data-edge-id'],
+ from: route['data-edge-from'],
+ to: route['data-edge-to'],
+ points: route['data-composition-points'].split(';').map((pair) => pair.split(',').map(Number)),
+ }));
+}
+
+function labelBoxes(html) {
+ return [...svgOf(html).matchAll(/<g data-detail="context"[^>]*data-edge-id="([^"]+)"[^>]*>\s*<rect x="([\d.-]+)" y="([\d.-]+)" width="([\d.]+)" height="([\d.]+)"/g)]
+ .map((match) => ({ id: match[1], x: +match[2], y: +match[3], width: +match[4], height: +match[5] }));
+}
+
+function properCrossings(html) {
+ const all = routes(html);
+ const crossings = [];
+ for (const [index, left] of all.entries()) {
+ for (const right of all.slice(index + 1)) {
+ if ([left.from, left.to].some((id) => id === right.from || id === right.to)) continue;
+ const crosses = left.points.slice(1).some((end, i) => right.points.slice(1).some((otherEnd, j) => (
+ properSegmentIntersection(left.points[i], end, right.points[j], otherEnd))));
+ if (crosses) crossings.push([left.id, right.id]);
+ }
+ }
+ return crossings;
+}
+
+for (const name of ['notifications', 'repository', 'shapes']) {
+ test(`unpinned class first draft "${name}" passes showcase without a crossing or a repair`, () => {
+ const diagram = JSON.parse(fs.readFileSync(path.join(fixtures, `${name}.class.json`), 'utf8'));
+ assert.equal(diagram.meta.quality_profile, 'showcase');
+ const result = render(diagram);
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ assert.deepEqual(properCrossings(result.html), []);
+ assert.ok(labelBoxes(result.html).length > 0, 'the fixture draws relationship labels');
+ const validation = spawnSync(process.execPath, [cli, 'validate', 'class', result.input, '--quality', 'showcase', '--json'], { encoding: 'utf8' });
+ assert.equal(validation.status, 0, validation.stdout + validation.stderr);
+ });
+}
+
+test('the repository draft keeps the "publishes" label off the Order type', () => {
+ const diagram = JSON.parse(fs.readFileSync(path.join(fixtures, 'repository.class.json'), 'utf8'));
+ const result = render(diagram);
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ const order = [...svgOf(result.html).matchAll(/data-node-id="order"[\s\S]{0,400}?<rect x="([\d.]+)" y="([\d.]+)" width="([\d.]+)" height="([\d.]+)"/g)]
+ .map((match) => ({ x: +match[1], y: +match[2], width: +match[3], height: +match[4] }))[0];
+ assert.ok(order, 'the Order type is drawn');
+ for (const label of labelBoxes(result.html)) assert.ok(!rectsOverlap(label, order), `label ${label.id} overlaps Order`);
+});
+
+test('a pinned label point is never moved by the automatic placer', () => {
+ const diagram = JSON.parse(fs.readFileSync(path.join(fixtures, 'shapes.class.json'), 'utf8'));
+ const relationship = diagram.relationships.find((entry) => entry.label);
+ const before = render(diagram);
+ const [authored] = labelBoxes(before.html).filter((box) => box.id === relationship.id);
+ relationship.labelAt = [authored.x + authored.width / 2 + 4, authored.y + 10];
+ const pinned = render(diagram);
+ assert.equal(pinned.status, 0, pinned.stdout + pinned.stderr);
+ const [moved] = labelBoxes(pinned.html).filter((box) => box.id === relationship.id);
+ assert.equal(moved.x, authored.x + 4);
+ assert.equal(moved.y, authored.y);
+});
diff --git a/test/fixtures/class-first-draft/README.md b/test/fixtures/class-first-draft/README.md
new file mode 100644
index 00000000..a8e60ec2
--- /dev/null
+++ b/test/fixtures/class-first-draft/README.md
@@ -0,0 +1,16 @@
+# Class first-draft regressions
+
+Unedited first drafts written from the Skill's class guidance (grid layout,
+automatic routes, a short verb label on each association). None of them pinned
+a position, route, or label point, and each failed `validate --quality
+showcase` on `dev` before the class first-draft routing and label fixes:
+
+| Fixture | Failure on `dev` |
+| --- | --- |
+| `notifications.class.json` | "records to" crossed the "has" route and sat 2 units from a route |
+| `repository.class.json` | "publishes" crossed "creates" through the gap under OrderService, and its label overlapped the Order type |
+| `shapes.class.json` | "包含" (contains) sat on the inheritance trunk, inside the route clearance |
+
+The regression test asserts that each renders at `showcase` and that the
+specific defects stay fixed. A draft that passes is one valid answer, not a
+layout recommendation.
diff --git a/test/fixtures/class-first-draft/notifications.class.json b/test/fixtures/class-first-draft/notifications.class.json
new file mode 100644
index 00000000..25266132
--- /dev/null
+++ b/test/fixtures/class-first-draft/notifications.class.json
@@ -0,0 +1,202 @@
+{
+ "schema_version": 1,
+ "diagram_type": "class",
+ "meta": {
+ "title": "Notification service types",
+ "locale": "en",
+ "quality_profile": "showcase"
+ },
+ "layout": {
+ "mode": "grid"
+ },
+ "types": [
+ {
+ "id": "dispatcher",
+ "label": "NotificationDispatcher",
+ "kind": "class",
+ "sublabel": "Routes a message to its channels",
+ "row": 0,
+ "col": 0,
+ "attributes": [
+ {
+ "name": "channels",
+ "type": "List<Channel>",
+ "visibility": "private"
+ },
+ {
+ "name": "store",
+ "type": "DeliveryStore",
+ "visibility": "private"
+ }
+ ],
+ "methods": [
+ {
+ "name": "dispatch",
+ "parameters": "message: Notification",
+ "returns": "DeliveryReport",
+ "visibility": "public"
+ }
+ ]
+ },
+ {
+ "id": "channel",
+ "label": "Channel",
+ "kind": "interface",
+ "sublabel": "One delivery transport",
+ "row": 0,
+ "col": 1.5,
+ "methods": [
+ {
+ "name": "send",
+ "parameters": "message: Notification",
+ "returns": "Result",
+ "visibility": "public",
+ "abstract": true
+ },
+ {
+ "name": "supports",
+ "parameters": "kind: Kind",
+ "returns": "boolean",
+ "visibility": "public",
+ "abstract": true
+ }
+ ]
+ },
+ {
+ "id": "notification",
+ "label": "Notification",
+ "kind": "record",
+ "sublabel": "Immutable message payload",
+ "row": 1,
+ "col": 0,
+ "attributes": [
+ {
+ "name": "id",
+ "type": "UUID"
+ },
+ {
+ "name": "recipient",
+ "type": "UserId"
+ },
+ {
+ "name": "kind",
+ "type": "Kind"
+ },
+ {
+ "name": "body",
+ "type": "String"
+ }
+ ]
+ },
+ {
+ "id": "email",
+ "label": "EmailChannel",
+ "kind": "class",
+ "sublabel": "SMTP delivery",
+ "row": 1,
+ "col": 1,
+ "methods": [
+ {
+ "name": "send",
+ "parameters": "message: Notification",
+ "returns": "Result",
+ "visibility": "public"
+ }
+ ]
+ },
+ {
+ "id": "push",
+ "label": "PushChannel",
+ "kind": "class",
+ "sublabel": "Mobile push delivery",
+ "row": 1,
+ "col": 2,
+ "methods": [
+ {
+ "name": "send",
+ "parameters": "message: Notification",
+ "returns": "Result",
+ "visibility": "public"
+ }
+ ]
+ },
+ {
+ "id": "store",
+ "label": "DeliveryStore",
+ "kind": "abstract",
+ "sublabel": "Persists delivery attempts",
+ "row": 2,
+ "col": 0,
+ "methods": [
+ {
+ "name": "record",
+ "parameters": "attempt: Attempt",
+ "returns": "void",
+ "visibility": "public",
+ "abstract": true
+ }
+ ]
+ },
+ {
+ "id": "kind",
+ "label": "Kind",
+ "kind": "enum",
+ "sublabel": "Message category",
+ "row": 2,
+ "col": 1,
+ "attributes": [
+ {
+ "name": "SECURITY"
+ },
+ {
+ "name": "MARKETING"
+ },
+ {
+ "name": "SYSTEM"
+ }
+ ]
+ }
+ ],
+ "relationships": [
+ {
+ "id": "r_channels",
+ "from": "dispatcher",
+ "to": "channel",
+ "kind": "aggregation",
+ "label": "fans out to"
+ },
+ {
+ "id": "r_email",
+ "from": "email",
+ "to": "channel",
+ "kind": "realization"
+ },
+ {
+ "id": "r_push",
+ "from": "push",
+ "to": "channel",
+ "kind": "realization"
+ },
+ {
+ "id": "r_msg",
+ "from": "dispatcher",
+ "to": "notification",
+ "kind": "dependency",
+ "label": "dispatches"
+ },
+ {
+ "id": "r_store",
+ "from": "dispatcher",
+ "to": "store",
+ "kind": "association",
+ "label": "records in"
+ },
+ {
+ "id": "r_kind",
+ "from": "notification",
+ "to": "kind",
+ "kind": "association",
+ "label": "has"
+ }
+ ]
+}
diff --git a/test/fixtures/class-first-draft/repository.class.json b/test/fixtures/class-first-draft/repository.class.json
new file mode 100644
index 00000000..c1d326b2
--- /dev/null
+++ b/test/fixtures/class-first-draft/repository.class.json
@@ -0,0 +1,201 @@
+{
+ "schema_version": 1,
+ "diagram_type": "class",
+ "meta": {
+ "title": "Order repository layer",
+ "locale": "en",
+ "quality_profile": "showcase"
+ },
+ "layout": {
+ "mode": "grid"
+ },
+ "types": [
+ {
+ "id": "controller",
+ "label": "OrderController",
+ "kind": "class",
+ "row": 0,
+ "col": 0,
+ "attributes": [
+ {
+ "name": "service",
+ "type": "OrderService",
+ "visibility": "private"
+ }
+ ],
+ "methods": [
+ {
+ "name": "create",
+ "visibility": "public",
+ "parameters": "req: Request",
+ "returns": "Response"
+ }
+ ]
+ },
+ {
+ "id": "service",
+ "label": "OrderService",
+ "kind": "class",
+ "row": 0,
+ "col": 1,
+ "attributes": [
+ {
+ "name": "repo",
+ "type": "OrderRepository",
+ "visibility": "private"
+ },
+ {
+ "name": "events",
+ "type": "EventBus",
+ "visibility": "private"
+ }
+ ],
+ "methods": [
+ {
+ "name": "place",
+ "visibility": "public",
+ "parameters": "cmd: PlaceOrder",
+ "returns": "Order"
+ }
+ ]
+ },
+ {
+ "id": "repo",
+ "label": "OrderRepository",
+ "kind": "interface",
+ "row": 0,
+ "col": 2,
+ "methods": [
+ {
+ "name": "save",
+ "visibility": "public",
+ "parameters": "o: Order",
+ "returns": "void"
+ },
+ {
+ "name": "find",
+ "visibility": "public",
+ "parameters": "id: OrderId",
+ "returns": "Order"
+ }
+ ]
+ },
+ {
+ "id": "pgrepo",
+ "label": "PgOrderRepository",
+ "kind": "class",
+ "row": 1,
+ "col": 2,
+ "attributes": [
+ {
+ "name": "pool",
+ "type": "Pool",
+ "visibility": "private"
+ }
+ ]
+ },
+ {
+ "id": "order",
+ "label": "Order",
+ "kind": "class",
+ "row": 1,
+ "col": 1,
+ "attributes": [
+ {
+ "name": "lines",
+ "type": "OrderLine[]",
+ "visibility": "private"
+ },
+ {
+ "name": "status",
+ "type": "Status",
+ "visibility": "private"
+ }
+ ],
+ "methods": [
+ {
+ "name": "total",
+ "visibility": "public",
+ "returns": "Money"
+ }
+ ]
+ },
+ {
+ "id": "line",
+ "label": "OrderLine",
+ "kind": "class",
+ "row": 1,
+ "col": 0,
+ "attributes": [
+ {
+ "name": "sku",
+ "type": "string",
+ "visibility": "public"
+ },
+ {
+ "name": "qty",
+ "type": "number",
+ "visibility": "public"
+ }
+ ]
+ },
+ {
+ "id": "bus",
+ "label": "EventBus",
+ "kind": "interface",
+ "row": 2,
+ "col": 1,
+ "methods": [
+ {
+ "name": "publish",
+ "visibility": "public",
+ "parameters": "e: Event",
+ "returns": "void"
+ }
+ ]
+ }
+ ],
+ "relationships": [
+ {
+ "id": "controller_service_dependency",
+ "from": "controller",
+ "to": "service",
+ "kind": "dependency",
+ "label": "calls"
+ },
+ {
+ "id": "service_repo_dependency",
+ "from": "service",
+ "to": "repo",
+ "kind": "dependency",
+ "label": "persists via"
+ },
+ {
+ "id": "pgrepo_repo_realization",
+ "from": "pgrepo",
+ "to": "repo",
+ "kind": "realization"
+ },
+ {
+ "id": "service_order_dependency",
+ "from": "service",
+ "to": "order",
+ "kind": "dependency",
+ "label": "creates"
+ },
+ {
+ "id": "order_line_composition",
+ "from": "order",
+ "to": "line",
+ "kind": "composition",
+ "label": "has"
+ },
+ {
+ "id": "service_bus_dependency",
+ "from": "service",
+ "to": "bus",
+ "kind": "dependency",
+ "label": "publishes"
+ }
+ ]
+}
diff --git a/test/fixtures/class-first-draft/shapes.class.json b/test/fixtures/class-first-draft/shapes.class.json
new file mode 100644
index 00000000..b7b18f3c
--- /dev/null
+++ b/test/fixtures/class-first-draft/shapes.class.json
@@ -0,0 +1,179 @@
+{
+ "schema_version": 1,
+ "diagram_type": "class",
+ "meta": {
+ "title": "图形编辑器核心类",
+ "locale": "zh-CN",
+ "quality_profile": "showcase"
+ },
+ "layout": {
+ "mode": "grid"
+ },
+ "types": [
+ {
+ "id": "shape",
+ "label": "Shape",
+ "kind": "abstract",
+ "row": 0,
+ "col": 1,
+ "attributes": [
+ {
+ "name": "id",
+ "type": "string",
+ "visibility": "protected"
+ }
+ ],
+ "methods": [
+ {
+ "name": "draw",
+ "visibility": "public",
+ "parameters": "ctx: Canvas",
+ "returns": "void"
+ },
+ {
+ "name": "bounds",
+ "visibility": "public",
+ "returns": "Rect"
+ }
+ ]
+ },
+ {
+ "id": "rect",
+ "label": "Rectangle",
+ "kind": "class",
+ "row": 1,
+ "col": 0,
+ "attributes": [
+ {
+ "name": "w",
+ "type": "number",
+ "visibility": "private"
+ },
+ {
+ "name": "h",
+ "type": "number",
+ "visibility": "private"
+ }
+ ]
+ },
+ {
+ "id": "circle",
+ "label": "Circle",
+ "kind": "class",
+ "row": 1,
+ "col": 1,
+ "attributes": [
+ {
+ "name": "r",
+ "type": "number",
+ "visibility": "private"
+ }
+ ]
+ },
+ {
+ "id": "group",
+ "label": "Group",
+ "kind": "class",
+ "row": 1,
+ "col": 2,
+ "attributes": [
+ {
+ "name": "children",
+ "type": "Shape[]",
+ "visibility": "private"
+ }
+ ],
+ "methods": [
+ {
+ "name": "add",
+ "visibility": "public",
+ "parameters": "s: Shape",
+ "returns": "void"
+ }
+ ]
+ },
+ {
+ "id": "doc",
+ "label": "Document",
+ "kind": "class",
+ "row": 0,
+ "col": 0,
+ "attributes": [
+ {
+ "name": "shapes",
+ "type": "Shape[]",
+ "visibility": "private"
+ }
+ ],
+ "methods": [
+ {
+ "name": "render",
+ "visibility": "public",
+ "returns": "void"
+ }
+ ]
+ },
+ {
+ "id": "history",
+ "label": "History",
+ "kind": "class",
+ "row": 0,
+ "col": 2,
+ "attributes": [
+ {
+ "name": "stack",
+ "type": "Command[]",
+ "visibility": "private"
+ }
+ ],
+ "methods": [
+ {
+ "name": "undo",
+ "visibility": "public",
+ "returns": "void"
+ }
+ ]
+ }
+ ],
+ "relationships": [
+ {
+ "id": "rect_shape_inheritance",
+ "from": "rect",
+ "to": "shape",
+ "kind": "inheritance"
+ },
+ {
+ "id": "circle_shape_inheritance",
+ "from": "circle",
+ "to": "shape",
+ "kind": "inheritance"
+ },
+ {
+ "id": "group_shape_inheritance",
+ "from": "group",
+ "to": "shape",
+ "kind": "inheritance"
+ },
+ {
+ "id": "group_shape_composition",
+ "from": "group",
+ "to": "shape",
+ "kind": "composition",
+ "label": "包含"
+ },
+ {
+ "id": "doc_shape_aggregation",
+ "from": "doc",
+ "to": "shape",
+ "kind": "aggregation",
+ "label": "持有"
+ },
+ {
+ "id": "doc_history_composition",
+ "from": "doc",
+ "to": "history",
+ "kind": "composition",
+ "label": "撤销栈"
+ }
+ ]
+}