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): keep automatic labels near their routes

tt-a1ie3230f9420ae
diff --git a/archify/SKILL.md b/archify/SKILL.md
index ab549f8e..03141704 100644
--- a/archify/SKILL.md
+++ b/archify/SKILL.md
@@ -39,7 +39,7 @@ Use this bounded path for ordinary generation. Do not read the optional Viewer R
A passing receipt proves that the included `validate`, `deliver`, strict `check`, and deterministic real-browser `browser-check` gates passed. Do not read its full sidecar or rerun individual commands afterward; use a standalone command only for an explicitly separate execution or focused failure diagnosis.
-5. A non-zero exit is never success. Use its compact stdout or `evidence.summaryReceipt`; read the full receipt only if the summary is truncated and lacks enough evidence for a coherent repair. After a validation failure, edit the connected neighborhood named by the evidence in one coherent change. When several affected routes share nodes, read [Architecture layout repair](references/architecture-layout-repair.md) for Architecture, then reposition those nodes and their neighbors together. Choose endpoint sides for the main rail and return corridors as part of that same repair; reserve detailed waypoints or label overrides for an isolated remaining defect. Keep unrelated geometry intact. Do not run validate, layout, render, or finalize first; edit the existing JSON in place. Geometry never authorizes deleting or merging a source-backed component, relationship, reference, view, card, boundary, or semantic label; reroute, reposition, or add readable canvas space instead. After the edit, rerun the complete `finalize` command from step 4 once, retaining `--quality showcase` and `--repo-root <repo-root>` for repository-backed candidates. After editing, omit any earlier `--candidate-sha256`: it binds the previous candidate. Use `--layout-json` before the edit only when compact evidence lacks needed geometry. A receipt with only 4 artifact checks is basic validation: require all 9 checks with 0 composition errors and 0 warnings. Fix `meta.quality_profile` before geometry. For workflow v2, use the stable compiler receipt; solver internals are not authoring controls. Use standalone `validate` only for focused diagnosis, with `--repo-root <repo-root>` for a repository. A passing validation returns `candidateFrozen: true`; do not edit, revalidate, or reread it. Run its `nextAction.arguments`, replacing only `<output.html>`. Retry later environment or evidence failures against the frozen candidate. If measured evidence requires a source edit, treat it as a new candidate and rerun the complete `finalize` command without the old hash. If one issue survives two focused repairs, inspect measured geometry or the relevant contract; after one evidence-based retry, stop truthfully. A lower error count never justifies changing meaning.
+5. A non-zero exit is never success. Use its compact stdout or `evidence.summaryReceipt`; read the full receipt only if the summary is truncated and lacks enough evidence for a coherent repair. After a validation failure, edit the connected neighborhood named by the evidence in one coherent change. When several affected routes share nodes, read [Architecture layout repair](references/architecture-layout-repair.md) for Architecture, then reposition those nodes and their neighbors together. Choose endpoint sides for the main rail and return corridors as part of that same repair; reserve detailed waypoints or label overrides for an isolated remaining defect. Keep unrelated geometry intact. Do not run validate, layout, render, or finalize first; edit the existing JSON in place. Geometry never authorizes deleting or merging a source-backed component, relationship, reference, view, card, boundary, or semantic label; reroute, reposition, or add readable canvas space instead. After the edit, rerun the complete `finalize` command from step 4 once, retaining `--quality showcase` and `--repo-root <repo-root>` for repository-backed candidates. If that output already has browser evidence from a different candidate, preserve it and add a fresh `--out-dir <output-stem>.review-<revision>` for the new candidate; use the same directory for its `visual-check`. After editing, omit any earlier `--candidate-sha256`: it binds the previous candidate. Use `--layout-json` before the edit only when compact evidence lacks needed geometry. A receipt with only 4 artifact checks is basic validation: require all 9 checks with 0 composition errors and 0 warnings. Fix `meta.quality_profile` before geometry. For workflow v2, use the stable compiler receipt; solver internals are not authoring controls. Use standalone `validate` only for focused diagnosis, with `--repo-root <repo-root>` for a repository. A passing validation returns `candidateFrozen: true`; do not edit, revalidate, or reread it. Run its `nextAction.arguments`, replacing only `<output.html>`. Retry later environment or evidence failures against the frozen candidate. If measured evidence requires a source edit, treat it as a new candidate and rerun the complete `finalize` command without the old hash. If one issue survives two focused repairs, inspect measured geometry or the relevant contract; after one evidence-based retry, stop truthfully. A lower error count never justifies changing meaning.
## Update awareness
diff --git a/archify/references/architecture-layout-repair.md b/archify/references/architecture-layout-repair.md
index f8d7882e..6614a66d 100644
--- a/archify/references/architecture-layout-repair.md
+++ b/archify/references/architecture-layout-repair.md
@@ -7,6 +7,6 @@ Use this after actual visual review finds several tangled routes. A successful m
1. Trace the affected relationships and their endpoints in the JSON. Before choosing coordinates, write the reader’s main path as an ordered list of existing edges, then identify shared state and real feedback cycles. Every neighboring pair in that main path must have the relationship being explained; place other components on branches beside their actual owner. Use `validate architecture <candidate.json> --layout-json --repo-root <root>` once if the compact receipt and screenshot do not reveal the needed route or label geometry; omit `--repo-root` only for a design without repository evidence. Do not guess repeated waypoint coordinates.
2. Place those connected main-path neighbors in reading order. Put shared state between its readers/writers, on an adjacent row if necessary, so one writer does not need a line across the whole execution area. Arrange a feedback cycle in its actual edge order around an open rectangle, with other consumers beside their owner. For example, if the edges are `client → API → dispatcher → worker → collector → runner → dispatcher`, put the first four on the upper row, collector below worker, and runner below dispatcher: the return then uses the lower row and a short upward edge. This illustrates adjacency, not a graph or set of coordinates to copy; use only relationships present in the candidate. Preserve every edge and its actual direction.
3. Assign simple endpoint sides with that placement: facing ports for the main rail, a distinct side for the return direction of a bidirectional pair, and side/top/bottom ports for branches. This is one coordinated layout change, not one correction per edge. Only use detailed `via` or label coordinates for a remaining measured defect. Keep external actors outside the resolved boundary rectangle, including its padding; not listing a node in `wraps` does not visually exclude it. Keep an internal relationship and its label inside the shared boundary unless crossing it conveys a real fact; do not imply an external hop merely to avoid another route.
-4. Compact unused gaps while preserving measured label space and the previous text size. Keep the main interaction and all required nodes readable in the default desktop view; do not trade crossings for a large blank canvas, tiny text, or a chain that doubles back without a semantic reason.
+4. When `composition/label-gap` reports a measured minimum, enlarge that clear gap or move the connected group onto another readable row. Keep the full label beside its own route; placing it in distant empty space does not repair the relationship. Compact unused gaps while preserving measured label space and the previous text size. Keep the main interaction and all required nodes readable in the default desktop view; do not trade crossings for a large blank canvas, tiny text, or a chain that doubles back without a semantic reason.
-Run the complete `finalize` once after the edit, then `visual-check` on the successful artifact and inspect its desktop captures. Trace the main path, each secondary chain, and every affected arrow and label. A bounded second repair may address a remaining specific defect. If it still fails visual acceptance, retain the candidate and report the concrete gap; do not count it as a successful repair or continue blind coordinate changes.
+Run the complete `finalize` once after the edit, then `visual-check` on the successful artifact and inspect its desktop captures. When replacing an already reviewed artifact, use one fresh `--out-dir` for both commands as described in [the delivery contract](delivery-contract.md#a-new-candidate-at-an-existing-output-path). Trace the main path, each secondary chain, and every affected arrow and label. A bounded second repair may address a remaining specific defect. If it still fails visual acceptance, retain the candidate and report the concrete gap; do not count it as a successful repair or continue blind coordinate changes.
diff --git a/archify/references/delivery-contract.md b/archify/references/delivery-contract.md
index d61ee9d5..aa66991e 100644
--- a/archify/references/delivery-contract.md
+++ b/archify/references/delivery-contract.md
@@ -462,6 +462,17 @@ a capable environment.
`browser-check` applies the same private-snapshot, identity, ownership, and no-clobber rules to its single JSON receipt. Its namespace is separate from `visual-check`, so a browser-only rerun cannot remove capture evidence.
+## A new candidate at an existing output path
+
+Browser evidence belongs to exact artifact bytes. After editing a candidate whose previous HTML already has browser evidence, choose a fresh evidence directory before running the next `finalize`; this preserves the old receipts and captures without an avoidable ownership-conflict retry:
+
+```bash
+node bin/archify.mjs finalize architecture candidate.json diagram.html --quality showcase --repo-root <root> --out-dir diagram.review-2 --json
+node bin/archify.mjs visual-check diagram.html --out-dir diagram.review-2 --json --require-provenance
+```
+
+Keep the requested HTML path stable. Use a new revision directory for each changed candidate, and retain the same directory for retries of unchanged bytes. For a diagram without repository evidence, omit `--repo-root`. Let the commands create their output directory. A prior validation failure that produced no HTML or browser evidence needs no new directory. Never remove unknown evidence to make a retry pass.
+
## Optional opening
Add `--open` only when the user wants an immediate local preview. It runs after
diff --git a/archify/renderers/architecture/labels.mjs b/archify/renderers/architecture/labels.mjs
index bdc3547c..825cc207 100644
--- a/archify/renderers/architecture/labels.mjs
+++ b/archify/renderers/architecture/labels.mjs
@@ -75,8 +75,9 @@ export function placeAutomaticLabels({
// 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.
+ // A collision-free island above a node is not a readable edge label.
+ // Keep the mask within two label heights of its own route; if no nearby
+ // slot fits, retain the collision so validation can request more space.
const ownSegments = segments.filter(segment => segment.relationIndex === label.relationIndex);
const baseAnchors = [
[label.lx, label.ly],
@@ -97,7 +98,9 @@ export function placeAutomaticLabels({
];
const fallback = baseAnchors.flatMap(([baseX, baseY]) => (
ringOffsets.map(([dx, dy]) => rectAt(label, baseX + dx, baseY + dy))
- )).find(rect => clear(rect, index));
+ )).find(rect => clear(rect, index) && ownSegments.some(segment => (
+ segmentRectClearance(segment, rect) <= label.height * 2
+ )));
if (fallback) placed[index] = fallback;
}
return placed;
diff --git a/archify/renderers/architecture/render-architecture.mjs b/archify/renderers/architecture/render-architecture.mjs
index 38bfb20a..e6c9c383 100644
--- a/archify/renderers/architecture/render-architecture.mjs
+++ b/archify/renderers/architecture/render-architecture.mjs
@@ -751,8 +751,24 @@ function validateArchitecture() {
// Connection labels must not land on top of components.
const labelRects = connectionLabels;
for (const rect of labelRects) {
- for (const c of components.values()) {
- if (rectsOverlap(rect, c, -2)) {
+ const blockedComponents = [...components.values()].filter(c => rectsOverlap(rect, c, -2));
+ const labelPinned = ['labelAt', 'labelDx', 'labelDy', 'labelSegment'].some(key => rect.relation[key] !== undefined);
+ const points = pathFor(rect.relation).points;
+ const shortHorizontalGap = points.length === 2 && Math.abs(points[0][1] - points[1][1]) < 0.0001
+ ? Math.abs(points[1][0] - points[0][0]) : null;
+ const requiredGap = Math.ceil(rect.width + 16);
+ if (arch.meta?.quality_profile === 'showcase' && !labelPinned && blockedComponents.length
+ && shortHorizontalGap != null && shortHorizontalGap < requiredGap) {
+ const message = `Label "${rect.label}" has only ${Math.round(shortHorizontalGap)}px between "${rect.relation.from}" and "${rect.relation.to}"; it needs at least ${requiredGap}px to stay beside its route — increase that clear gap or place the connected nodes on another readable row, preserving the label.`;
+ problems.push(message);
+ diagnostics.push({
+ code: 'composition/label-gap', severity: 'error', message,
+ subject: { diagramType: 'architecture', collection: 'connections', id: rect.relation.id, from: rect.relation.from, to: rect.relation.to },
+ evidence: { clearGapPx: shortHorizontalGap, minimumGapPx: requiredGap, labelWidthPx: rect.width, obstacles: blockedComponents.map(c => c.id) },
+ supportedFixes: [`increase the clear gap between the connected nodes to at least ${requiredGap}px`, 'reposition the connected nodes together while preserving the full relationship label'],
+ });
+ } else {
+ for (const c of blockedComponents) {
problems.push(`Label "${rect.label}" overlaps component "${c.id}" — adjust labelDx/labelDy/labelSegment or set labelAt.\n${suggestLabelObstacleFix(rect, rect.lx, rect.ly, c, 'component', viewBox, components.values())}`);
}
}
diff --git a/archify/test/architecture-automatic-labels.test.mjs b/archify/test/architecture-automatic-labels.test.mjs
index 5e9a6036..c419ffab 100644
--- a/archify/test/architecture-automatic-labels.test.mjs
+++ b/archify/test/architecture-automatic-labels.test.mjs
@@ -120,3 +120,37 @@ test('bounded fallback finds a clear position without hiding or shrinking the la
assert.equal(report.labels[0].text, 'Read cache');
assertLabelsClear(diagram, report);
});
+
+test('a short gap cannot pass by relocating its label above an endpoint', t => {
+ const diagram = {
+ schema_version: 1, diagram_type: 'architecture',
+ meta: { title: 'Authentication', output: 'diagram.html', quality_profile: 'showcase' },
+ components: [
+ { id: 'client', type: 'frontend', label: 'Client', pos: [45, 55], size: [180, 72] },
+ { id: 'gateway', type: 'cloud', label: 'Gateway', pos: [310, 55], size: [220, 72] },
+ ],
+ connections: [{ id: 'login', from: 'client', to: 'gateway', label: '登录 · 配对 · 加密帧' }],
+ };
+ const crowded = inspect(t, diagram);
+ assert.equal(crowded.result.status, 1, crowded.result.stdout);
+ const diagnostic = crowded.report.diagnostics.find(d => d.code === 'composition/label-gap');
+ assert.ok(diagnostic, crowded.result.stdout);
+ assert.equal(diagnostic.subject.id, 'login');
+ assert.ok(diagnostic.evidence.minimumGapPx > diagnostic.evidence.clearGapPx);
+ assert.ok(diagnostic.supportedFixes.some(fix => /increase the clear gap/.test(fix)));
+
+ for (const control of [{ labelDx: 0 }, { labelAt: [267.5, 81] }]) {
+ const pinned = structuredClone(diagram);
+ Object.assign(pinned.connections[0], control);
+ const explicit = inspect(t, pinned);
+ assert.equal(explicit.result.status, 1);
+ assert.ok(explicit.report.diagnostics.some(d => /overlaps component/.test(d.message)));
+ assert.ok(!explicit.report.diagnostics.some(d => d.code === 'composition/label-gap'));
+ }
+
+ diagram.components[1].pos[0] = 390;
+ const repaired = inspect(t, diagram);
+ assert.equal(repaired.result.status, 0, repaired.result.stdout);
+ assertLabelsClear(diagram, repaired.report);
+ assert.equal(repaired.report.labels[0].text, diagram.connections[0].label);
+});
diff --git a/archify/test/architecture-first-draft.test.mjs b/archify/test/architecture-first-draft.test.mjs
index 5363226f..6c2a0e35 100644
--- a/archify/test/architecture-first-draft.test.mjs
+++ b/archify/test/architecture-first-draft.test.mjs
@@ -84,16 +84,23 @@ test('architecture: wide incoming arrows reserve a whole side before routing', (
}
});
-// These candidates are unmodified first drafts from the repair study: authors
-// declared no route controls, yet the router accepted routes that the
-// showcase composition gate then rejected (a frame border used as a corridor,
-// a 3px jog, a 10px interior turn). Every one cost a hand-routing repair loop.
+// Keep the original first drafts: route-floor repairs must stay fixed, but
+// their cramped labels must not pass by being moved far from their own edge.
+function assertOnlyLabelDefects(receipt) {
+ assert.equal(receipt.ok, false);
+ assert.ok(receipt.diagnostics.length > 0);
+ for (const issue of receipt.diagnostics) {
+ assert.ok(issue.code === 'composition/label-gap'
+ || issue.code === 'composition/label-route-clearance'
+ || /^Label ".*" overlaps component /.test(issue.message), JSON.stringify(issue));
+ }
+}
for (const name of ['audit-luna', 'audit-terra', 'queue-sol']) {
- test(`architecture: first draft ${name} validates for showcase without route controls`, () => {
+ test(`architecture: first draft ${name} preserves route floors and reports crowded labels`, () => {
const { status, receipt } = validate('architecture', path.join(fixtures, `${name}.architecture.json`));
- assert.equal(status, 0, JSON.stringify(receipt.diagnostics, null, 2));
- assert.equal(receipt.ok, true);
- assert.equal(receipt.composition.summary.errors, 0);
+ assert.equal(status, 1);
+ assertOnlyLabelDefects(receipt);
+ assert.ok(receipt.diagnostics.some(issue => issue.code === 'composition/label-gap'));
});
}
@@ -134,7 +141,9 @@ test('architecture: a self-loop with cramped explicit sides names the loop and t
const repaired = path.join(tmp, 'queue-luna.architecture.json');
fs.writeFileSync(repaired, JSON.stringify(candidate));
const result = validate('architecture', repaired);
- assert.equal(result.status, 0, JSON.stringify(result.receipt.diagnostics, null, 2));
+ assert.equal(result.status, 1);
+ assertOnlyLabelDefects(result.receipt);
+ assert.ok(!result.receipt.diagnostics.some(issue => issue.code === 'layout/self-loop-ports'));
} finally {
fs.rmSync(tmp, { recursive: true, force: true });
}
diff --git a/archify/test/layout-rules.test.mjs b/archify/test/layout-rules.test.mjs
index f8c0e060..3edfd9a0 100644
--- a/archify/test/layout-rules.test.mjs
+++ b/archify/test/layout-rules.test.mjs
@@ -1872,15 +1872,26 @@ test('architecture: automatic reciprocal adjacent routes keep the showcase inter
!('route' in connection) && !('via' in connection) && !('fromSide' in connection) && !('toSide' in connection)
)));
- const { code, stderr, outPath } = render('architecture', doc);
- assert.equal(code, 0, stderr);
- const html = fs.readFileSync(outPath, 'utf8');
- for (const id of ['request-envelope', 'json-response']) {
- const encoded = html.match(new RegExp(
- `data-edge-id="${id}" data-composition-points="([^"]+)"`,
- ))?.[1];
- assert.ok(encoded, `expected rendered composition points for ${id}`);
- const points = encoded.split(';').map((point) => point.split(',').map(Number));
+ // The route remains valid, but these full labels do not fit a 60px gap.
+ // Inspect geometry even on failure instead of accepting detached labels.
+ const input = path.join(tmp, 'reciprocal-label-gap.json');
+ fs.writeFileSync(input, JSON.stringify({ ...doc, meta: { ...doc.meta, output: 'reciprocal.html' } }));
+ let report;
+ try {
+ execFileSync('node', [path.join(skillRoot, 'bin/archify.mjs'), 'validate', 'architecture', input, '--layout-json'], { encoding: 'utf8' });
+ assert.fail('crowded labels must be rejected');
+ } catch (error) {
+ assert.equal(error.status, 1);
+ report = JSON.parse(error.stdout);
+ }
+ assert.ok(report.diagnostics.length > 0);
+ assert.ok(report.diagnostics.every(issue => issue.code === 'composition/label-gap'
+ || issue.code === 'composition/label-route-clearance'
+ || /^Label ".*" overlaps component /.test(issue.message)), JSON.stringify(report.diagnostics));
+ for (const [index, { id }] of doc.connections.entries()) {
+ const points = report.connections[index]?.points;
+ assert.ok(points, `expected composition points for ${id}`);
+ const encoded = JSON.stringify(points);
const interiorLengths = points.slice(1, -2).map((point, index) => (
Math.abs(point[0] - points[index + 2][0]) + Math.abs(point[1] - points[index + 2][1])
));