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
fix(lifecycle): clear dense labels and shared source ticks
tt-a1i344f4add37cf
diff --git a/archify/renderers/lifecycle/README.md b/archify/renderers/lifecycle/README.mdindex 652f89d3..f87398d0 100644--- a/archify/renderers/lifecycle/README.md+++ b/archify/renderers/lifecycle/README.md@@ -46,7 +46,7 @@ The geometry follows from the structure alone:| Other states | One row per distance from the main path. A state starts under the states it connects to in the row above; overlapping states pack side by side. || Between rows | Orthogonal routes through a shared gap. Horizontal runs take separate tracks, chosen to minimise crossings; near-vertical routes snap straight or widen to a readable jog. || Shared exits | When one state is entered from several main-path phases through transitions that share label, note and variant, consecutive phases receive a dashed composite frame and one exit per target, as in a UML superstate; non-consecutive phases share a bus with junction dots. Exits that differ stay separate connectors with their own labels. |-| Same lower row | Neighbours connect side to side, parallel transitions fanning out around the shared edge (at most five per pair of states); other pairs loop under the row. |+| Same lower row | Neighbours connect side to side, parallel transitions fanning out around the shared edge (at most five per pair of states). Dense parallel labels and notes increase their lane spacing and the height of that lower row to keep clear; other pairs loop under the row. || Labels | Above main-path arrows, on arc and loop runs, otherwise beside the segment next to the lower state. Every label keeps clear of other routes, states and labels; if one cannot, all spacing grows and layout repeats. |Every route carries a crossover halo, so an unavoidable crossing (for example,@@ -87,7 +87,9 @@ with supported fixes.The final artifact check applies the shared composition gates (orthogonalsegments, crossings, corridors, label clearance and route rhythm). Routes of oneshared-exit bus declare `data-composition-junction`; they may share only that-horizontal bus and, when they end at the same state, the merged drop into it.+horizontal bus, the identical first tick from the same source port, and, when+they end at the same state, the merged drop into it. Internal vertical runs+remain subject to the corridor check.## Design rulesdiff --git a/archify/renderers/lifecycle/render-lifecycle.mjs b/archify/renderers/lifecycle/render-lifecycle.mjsindex 6e211e41..85ca8246 100644--- a/archify/renderers/lifecycle/render-lifecycle.mjs+++ b/archify/renderers/lifecycle/render-lifecycle.mjs@@ -273,6 +273,40 @@ function layout({ spineGap, rowGap, drop, firstTrack, ports: portMode }) {const adjacent = (transition) => transition.from !== transition.to&& Math.abs(rowOrder[depthOf(transition.from)].indexOf(transition.from) - rowOrder[depthOf(transition.from)].indexOf(transition.to)) === 1;const sides = ofKind('same').filter(adjacent);+ // Side labels ride on the line for groups of three or more. Reserve their+ // actual height before placing rows: horizontal gap growth cannot clear a+ // label trapped between two full-width parallel strokes.+ const sideGroups = new Map();+ for (const transition of sides) {+ const key = [transition.from, transition.to].sort().join('\u0000');+ if (!sideGroups.has(key)) sideGroups.set(key, []);+ sideGroups.get(key).push(transition);+ }+ const sideLanes = [];+ const rowHeights = rows.map(() => STATE_H);+ for (const group of sideGroups.values()) {+ const rightward = (transition) => states.get(transition.from).x < states.get(transition.to).x;+ const ordered = [...group.filter(rightward), ...group.filter((transition) => !rightward(transition))];+ if (ordered.length > 5) {+ const message = `${ordered.length} transitions between the neighbouring states "${ordered[0].from}" and "${ordered[0].to}" cannot spread apart on the shared edge; at most five stay legible.`;+ throwDiagnosticProblems('Lifecycle validation failed', [message], {+ subject: { diagramType: 'lifecycle' },+ diagnostics: [structureProblem('lifecycle/crowded-side-transitions', message,+ { collection: 'transitions', from: ordered[0].from, to: ordered[0].to },+ ['merge the triggers into one transition label'])],+ });+ }+ let step = Math.min(20, 48 / (ordered.length - 1));+ if (ordered.length > 2) {+ const heights = ordered.map((transition) => hasLabel(transition) ? labelBox(transition).height : 0);+ step = Math.max(step, ...heights.map((height) => height ? height / 2 + CLEARANCE : 0),+ ...heights.slice(1).map((height, index) => height && heights[index] ? (height + heights[index]) / 2 + 4 : 0));+ const row = depthOf(ordered[0].from);+ // Keep every side port eight pixels inside the rounded state corners.+ rowHeights[row] = Math.max(rowHeights[row], step * (ordered.length - 1) + 16);+ }+ sideLanes.push({ ordered, step });+ }for (const transition of ofKind('same').filter((transition) => !adjacent(transition))) {connectors.push({ kind: 'loop', transition, gap: depthOf(transition.from), order: transitions.indexOf(transition) });}@@ -336,14 +370,15 @@ function layout({ spineGap, rowGap, drop, firstTrack, ports: portMode }) {for (let row = 0; row < rowCount; row += 1) {for (const state of rows[row]) {state.y = rowTop[row];- state.cy = rowTop[row] + STATE_H / 2;+ state.height = rowHeights[row];+ state.cy = rowTop[row] + state.height / 2;}- const bottom = rowTop[row] + STATE_H;+ const bottom = rowTop[row] + rowHeights[row];const count = assignTracks(runs.filter((run) => run.connector.gap === row));trackY[row] = (track) => bottom + firstTrack + track * TRACK_STEP;if (row + 1 < rowCount) rowTop.push((count ? trackY[row](count - 1) : bottom + firstTrack) + drop);}- const rowBottom = (row) => rowTop[row] + STATE_H;+ const rowBottom = (row) => rowTop[row] + rowHeights[row];// Routes, keyed by transition.const routes = new Map();@@ -405,25 +440,7 @@ function layout({ spineGap, rowGap, drop, firstTrack, ports: portMode }) {}// Parallel transitions between two neighbours spread symmetrically around// the shared edge, left-to-right ones first; a reciprocal pair lands at ±10.- const sideGroups = new Map();- for (const transition of sides) {- const key = [transition.from, transition.to].sort().join('\u0000');- if (!sideGroups.has(key)) sideGroups.set(key, []);- sideGroups.get(key).push(transition);- }- for (const group of sideGroups.values()) {- const rightward = (transition) => states.get(transition.from).x < states.get(transition.to).x;- const ordered = [...group.filter(rightward), ...group.filter((transition) => !rightward(transition))];- const step = Math.min(20, 48 / (ordered.length - 1));- if (step < 12) {- const message = `${ordered.length} transitions between the neighbouring states "${ordered[0].from}" and "${ordered[0].to}" cannot spread apart on the shared edge; at most five stay legible.`;- throwDiagnosticProblems('Lifecycle validation failed', [message], {- subject: { diagramType: 'lifecycle' },- diagnostics: [structureProblem('lifecycle/crowded-side-transitions', message,- { collection: 'transitions', from: ordered[0].from, to: ordered[0].to },- ['merge the triggers into one transition label'])],- });- }+ for (const { ordered, step } of sideLanes) {ordered.forEach((transition, index) => {const from = states.get(transition.from);const to = states.get(transition.to);@@ -924,9 +941,10 @@ function renderState(state) {const { label: labelFont, sublabel: sublabelFont, tag: tagFont } = fonts(state, state.width);// Baselines keep each row's full glyph box (ascent and descent) separate.const [labelY, sublabelY, tagY] = hasSub && state.tag ? [23, 40, 55] : hasSub ? [27, 45] : state.tag ? [29, 0, 50] : [37];- const rows = [{ text: state.label, font: labelFont, y: labelY }];- if (hasSub) rows.push({ text: state.sublabel, font: sublabelFont, y: sublabelY });- if (state.tag) rows.push({ text: state.tag, font: tagFont, y: tagY });+ const textOffset = (state.height - STATE_H) / 2;+ const rows = [{ text: state.label, font: labelFont, y: labelY + textOffset }];+ if (hasSub) rows.push({ text: state.sublabel, font: sublabelFont, y: sublabelY + textOffset });+ if (state.tag) rows.push({ text: state.tag, font: tagFont, y: tagY + textOffset });const labelLayout = nodeLabelLayout({width: state.width, height: state.height, rows,brand: Boolean(brandMarkFor(state)), source: Boolean(sourceEvidence?.nodes?.[state.id]?.length), side: 'left', step: state.step,diff --git a/archify/renderers/shared/geometry.mjs b/archify/renderers/shared/geometry.mjsindex 8a0992be..20850751 100644--- a/archify/renderers/shared/geometry.mjs+++ b/archify/renderers/shared/geometry.mjs@@ -702,8 +702,9 @@ export function cleanCrossingProblems({// The counterflow-only opt-in serves older workflow exports without a root// readable-v2 contract; full shared-endpoint checking takes precedence.// Relationships a renderer declares on one junction (a Lifecycle exit bracket)-// may share that junction's horizontal bus and, when they end at the same-// state, the merged drop into it; other overlaps between them count.+// may share that junction's horizontal bus, the first tick from a common+// source port and, when they end at the same state, the merged drop into it;+// other overlaps between them count.// Tiny overlaps below the route rhythm// floor are ignored to avoid turning sub-pixel rounding into a quality debt.export function collectAmbiguousCorridors({@@ -748,9 +749,15 @@ export function collectAmbiguousCorridors({);if (!overlap || overlap.length + 0.0001 < minOverlapPx) continue;if (allowShortWorkflowTrunks && shortWorkflowTrunk(left, right, leftSegment, rightSegment, overlap.length)) continue;- // Only the horizontal bus itself is shared — and, for two bracket- // relations ending at the same state, their merged drop into it.- if (sharedBus && (Math.abs(overlap.start[1] - overlap.end[1]) < 0.0001 || left.relation.to === right.relation.to)) continue;+ // A multi-target bracket repeats its source tick for each target.+ // Limit that exemption to the first segment at the same source port:+ // a common source identity cannot waive an interior vertical overlap.+ const sharedSourceTick = left.sourceEndpoint !== false && right.sourceEndpoint !== false+ && left.relation.from === right.relation.from && leftSegment === 0 && rightSegment === 0+ && Math.abs(left.points[0][0] - right.points[0][0]) < 0.0001+ && Math.abs(left.points[0][1] - right.points[0][1]) < 0.0001;+ if (sharedBus && (Math.abs(overlap.start[1] - overlap.end[1]) < 0.0001+ || left.relation.to === right.relation.to || sharedSourceTick)) continue;if (counterflowOnly) {const leftDelta = left.points[leftSegment + 1].map((value, axis) => value - left.points[leftSegment][axis]);const rightDelta = right.points[rightSegment + 1].map((value, axis) => value - right.points[rightSegment][axis]);diff --git a/test/lifecycle-junction.test.mjs b/test/lifecycle-junction.test.mjsnew file mode 100644index 00000000..6328a4ba--- /dev/null+++ b/test/lifecycle-junction.test.mjs@@ -0,0 +1,106 @@+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 { collectAmbiguousCorridors, collectArrowheadCollisions } from '../archify/renderers/shared/geometry.mjs';++const skillRoot = fileURLToPath(new URL('../archify/', import.meta.url));+const state = (id, type = 'active') => ({ id, type, label: id });+const bus = {+ schema_version: 3, diagram_type: 'lifecycle',+ meta: { title: 'Shared exits', output: 'bus.html', quality_profile: 'showcase' },+ mainPath: ['a', 'b', 'c'],+ states: [state('a', 'start'), state('b'), state('c', 'success'), state('x', 'failure'), state('y', 'failure')],+ transitions: [+ { from: 'a', to: 'b' }, { from: 'b', to: 'c' },+ ...['a', 'c'].flatMap(from => ['x', 'y'].map(to => ({ from, to, label: 'exit' }))),+ ],+};++test('multi-target lifecycle bus passes the public artifact checker and validation', (t) => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-lifecycle-junction-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ const input = path.join(dir, 'bus.json');+ const output = path.join(dir, 'bus.html');+ fs.writeFileSync(input, JSON.stringify(bus));+ const render = spawnSync(process.execPath, [path.join(skillRoot, 'renderers/lifecycle/render-lifecycle.mjs'), input, output], { encoding: 'utf8' });+ assert.equal(render.status, 0, render.stderr);+ assert.match(fs.readFileSync(output, 'utf8'), /data-composition-junction="a\+c"/);+ const check = spawnSync(process.execPath, [path.join(skillRoot, 'scripts/check-render-output.mjs'), output], { encoding: 'utf8' });+ const receipt = JSON.parse(check.stdout);+ assert.equal(check.status, 0, check.stdout);+ assert.equal(receipt.composition.metrics.ambiguousCorridors, 0);+ assert.equal(receipt.composition.metrics.arrowheadCollisions, 0);+ const validate = spawnSync(process.execPath, [path.join(skillRoot, 'bin/archify.mjs'), 'validate', 'lifecycle', input, '--json'], { encoding: 'utf8' });+ assert.equal(validate.status, 0, validate.stdout + validate.stderr);+});++const route = (from, to, points, junction = 'a+c') => ({ relation: { from, to, junction }, points });+const corridors = (...routedRelations) => collectAmbiguousCorridors({ routedRelations, includeSharedEndpoints: () => true });++test('one junction shares only the first tick at the same source port', () => {+ const first = route('a', 'x', [[20, 20], [20, 60], [100, 60], [100, 100]]);+ const second = route('a', 'y', [[20, 20], [20, 60], [160, 60], [160, 100]]);+ assert.deepEqual(corridors(first, second), []);+ assert.equal(corridors(first, { ...second, sourceEndpoint: false }).length, 1,+ 'a disconnected interior subpath is not the source tick');+ const differentPort = route('a', 'y', [[20, 30], [20, 60], [160, 60], [160, 100]]);+ assert.equal(corridors(first, differentPort).length, 1, 'source identity alone does not declare a common port');+ const unrelated = route('b', 'y', second.points);+ assert.equal(corridors(first, unrelated).length, 1, 'junction identity alone does not declare a common source');+});++test('interior vertical overlap remains ambiguous within the same junction', () => {+ const first = route('a', 'x', [[20, 20], [20, 60], [100, 60], [100, 120], [160, 120]]);+ const second = route('a', 'y', [[20, 20], [20, 40], [100, 40], [100, 100], [220, 100]]);+ const hits = corridors(first, second);+ assert.equal(hits.length, 1);+ assert.equal(hits[0].leftSegment, 2);+ assert.equal(hits[0].rightSegment, 2);+ assert.equal(hits[0].overlapLength, 40);+});++test('public checker rejects interior vertical overlaps even when the junction and source match', (t) => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-junction-overlap-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));+ for (const junction of ['a+c', 'other']) {+ const first = route('a', 'x', [[20, 20], [20, 60], [100, 60], [100, 120], [160, 120]]);+ const second = route('a', 'y', [[20, 20], [20, 40], [100, 40], [100, 100], [220, 100]], junction);+ const strokes = [first, second].map(({ relation, points }) => {+ const d = points.map(([x, y], index) => `${index ? 'L' : 'M'} ${x} ${y}`).join(' ');+ return `<path data-graph-role="automatic-crossover-underlay" d="${d}" fill="none" stroke="var(--mask)" stroke-width="5" pointer-events="none"/>+ <path d="${d}" data-edge-from="${relation.from}" data-edge-to="${relation.to}"+ data-composition-junction="${relation.junction}" data-composition-independent="true"+ data-composition-crossover="halo" class="a-default" stroke-width="1.5" marker-end="url(#arrow)"/>`;+ }).join('\n');+ const file = path.join(dir, `${junction}.html`);+ fs.writeFileSync(file, `<html><body><svg viewBox="0 0 300 200" data-quality-profile="showcase">${strokes}</svg></body></html>`);+ const checked = spawnSync(process.execPath, [path.join(skillRoot, 'scripts/check-render-output.mjs'), file], { encoding: 'utf8' });+ const receipt = JSON.parse(checked.stdout);+ assert.equal(checked.status, 1);+ assert.equal(receipt.composition.metrics.ambiguousCorridors, 1);+ const issue = receipt.composition.issues.find(entry => entry.code === 'composition/ambiguous-corridor');+ assert.equal(issue.segmentIndex, 2);+ assert.equal(issue.otherSegmentIndex, 2);+ assert.equal(issue.overlapLength, 40);+ }+});++test('different junctions cannot share a source tick or a bus', () => {+ const first = route('a', 'x', [[20, 20], [20, 60], [100, 60], [100, 100]]);+ const second = route('a', 'y', [[20, 20], [20, 60], [160, 60], [160, 100]], 'other');+ assert.equal(corridors(first, second).length, 1);+});++test('same-target junction merged drops retain a single arrowhead', () => {+ const first = route('a', 'x', [[20, 20], [20, 60], [100, 60], [100, 100]]);+ const second = route('c', 'x', [[160, 20], [160, 60], [100, 60], [100, 100]]);+ assert.deepEqual(corridors(first, second), []);+ assert.deepEqual(collectArrowheadCollisions({ routedRelations: [first, second] }), []);+ second.relation.junction = 'other';+ assert.equal(corridors(first, second).length, 1);+ assert.equal(collectArrowheadCollisions({ routedRelations: [first, second] }).length, 1);+});diff --git a/test/lifecycle-layout.test.mjs b/test/lifecycle-layout.test.mjsindex aa4d71b9..29630a4d 100644--- a/test/lifecycle-layout.test.mjs+++ b/test/lifecycle-layout.test.mjs@@ -179,6 +179,71 @@ test('a reciprocal pair still lands just above and below the shared edge', () =>assert.deepEqual(points(result.svg, 'f', 'w').map((point) => point[1]), [cy + 10, cy + 10]);});+test('dense neighbour transitions keep every label and note clear in its own lane', () => {+ const cases = [+ ['five short labels', 'abcde'.split('').map((label) => ({ from: 'w', to: 'f', label }))],+ ['four labels with notes', Array.from({ length: 4 }, (_, index) => ({ from: 'w', to: 'f', label: `way ${index}`, note: `note ${index}` }))],+ ['five mixed directions and label heights', [+ { from: 'w', to: 'f', label: 'one', note: 'first note' },+ { from: 'f', to: 'w', label: 'two' },+ { from: 'w', to: 'f', note: 'third note' },+ { from: 'f', to: 'w', label: 'four', note: 'fourth note' },+ { from: 'w', to: 'f', label: 'five' },+ ]],+ ['five unlabelled transitions', Array.from({ length: 5 }, () => ({ from: 'w', to: 'f' }))],+ ];+ for (const [name, extra] of cases) {+ const doc = neighbourCase(extra);+ // A following row must move down with the enlarged neighbour row.+ doc.states.push(state('next', 'success'));+ doc.transitions.push({ from: 'f', to: 'next' });+ const result = render(doc);+ assert.equal(result.code, 0, `${name}: ${result.stderr}`);+ assert.equal(result.check.ok, true, `${name}: ${JSON.stringify(result.check.composition.issues)}`);+ const routes = [...allPoints(result.svg, 'w', 'f'), ...allPoints(result.svg, 'f', 'w')];+ assert.equal(routes.length, extra.length, name);+ assert.equal(new Set(routes.map((route) => route[0][1])).size, extra.length, name);+ const lower = box(result.svg, 'w');+ const partner = box(result.svg, 'f');+ assert.equal(box(result.svg, 'a').height, 64, `${name}: main path retains its height`);+ assert.equal(box(result.svg, 'next').height, 64, `${name}: following row retains its height`);+ if (extra.every((transition) => !transition.label && !transition.note)) {+ assert.equal(lower.height, 64, `${name}: no label footprint needs extra height`);+ }+ assert.equal(lower.height, partner.height, `${name}: one lower row keeps aligned bounds`);+ assert.ok(routes.every((route) => route.every(([, y]) => y > lower.y && y < lower.y + lower.height)),+ `${name}: every arrow attaches inside the state side`);+ assert.ok(box(result.svg, 'next').y > lower.y + lower.height, `${name}: following row clears the full state height`);+ const edgeLabels = [...result.svg.matchAll(/<g data-detail="(?:context|fine)" [^>]*data-edge-from="(?:w|f)" data-edge-to="(?:w|f)"[^>]*>[\s\S]*?<\/g>/g)]+ .map((match) => match[0]).join('');+ for (const transition of extra) {+ for (const text of [transition.label, transition.note].filter(Boolean)) {+ assert.equal(edgeLabels.split(`>${text}</text>`).length - 1, 1, `${name}: preserves ${text}`);+ }+ }+ }+});++test('one lower row accommodates the tallest of several parallel neighbour groups', () => {+ const doc = neighbourCase('abcde'.split('').map((label) => ({ from: 'w', to: 'f', label })));+ doc.states.push(state('g', 'waiting'));+ doc.transitions.push({ from: 'b', to: 'g' }, ...Array.from({ length: 4 }, (_, index) => ({+ from: 'f', to: 'g', label: `way ${index}`, note: `note ${index}`,+ })));+ const result = render(doc);+ assert.equal(result.code, 0, result.stderr);+ assert.equal(result.check.ok, true, JSON.stringify(result.check.composition.issues));+ const boxes = ['w', 'f', 'g'].map((id) => box(result.svg, id));+ assert.equal(new Set(boxes.map((state) => state.y)).size, 1, 'all partners stay in one row');+ assert.equal(new Set(boxes.map((state) => state.height)).size, 1, 'all partners retain the same centre and bottom');+ const centre = boxes[0].y + boxes[0].height / 2;+ for (const [from, to, count] of [['w', 'f', 5], ['f', 'g', 4]]) {+ const routes = allPoints(result.svg, from, to);+ assert.equal(routes.length, count);+ assert.equal((routes[0][0][1] + routes.at(-1)[0][1]) / 2, centre, 'each group fans around the common row centre');+ }+});+test('more than five parallel transitions between neighbours are a typed error', () => {const result = render(neighbourCase(Array.from({ length: 6 }, (_, index) => ({ from: 'w', to: 'f', label: `way ${index}` }))));assert.notEqual(result.code, 0);