Skip to content

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

fix: preserve readable content and authored geometry in automatic layouts

tt-a1ibbdc83815da6
diff --git a/archify/references/authoring-contract.md b/archify/references/authoring-contract.md
index 865b0c04..95c6f6ec 100644
--- a/archify/references/authoring-contract.md
+++ b/archify/references/authoring-contract.md
@@ -283,7 +283,7 @@ After every edit, rerun the complete `finalize` as the delivery contract require
Choose overview or mechanism detail using [Composition and meaning](authoring-defaults.md#composition-and-meaning). Use one obvious primary reading path, which may step across meaningful rows when the requested topology needs room. Keep the overview readable at its chosen abstraction; expand implementation details when they answer the reader's question. Group only real ownership, trust, process, or deployment boundaries. Boundaries do not replace relationships.
-Grid placement is preferred when the schema supports it. Free positions are appropriate for a bounded exception, not for prose-level coordinate planning. Keep external actors outside the system boundary when that is factually true. A boundary is drawn as the padded box around all of its members, so place them as one compact axis-aligned cluster (no empty bay that lets a non-member sit inside the padded frame) and keep every non-member outside that box; `layout/boundary-encloses-non-member` reports a component the box swallows.
+Grid placement is preferred when the schema supports it. Free positions are appropriate for a bounded exception, not for prose-level coordinate planning. Keep external actors outside the system boundary when that is factually true. A boundary is drawn as the padded box around all of its members, so place them as one compact axis-aligned cluster (no empty bay that lets a non-member sit inside the padded frame) and keep every non-member outside that box; `layout/boundary-encloses-non-member` reports a component the box swallows in showcase quality. Standard retains its existing acceptance behavior.
### Workflow
@@ -317,7 +317,7 @@ not settle viewport fit. These are repair directions, not guaranteed coordinates
### Sequence
-Participants are ordered by conversation role. Messages own their vertical order. Use return/async/security variants for meaning, not decoration; sequence does not use Automatic Port Spread. A segment's `from`/`to` edges must stay at least 4px off every message arrow (`message.y`): an edge along an arrow leaves the reader unable to tell which phase the message belongs to, and the renderer reports it.
+Participants are ordered by conversation role. Messages own their vertical order. Use return/async/security variants for meaning, not decoration; sequence does not use Automatic Port Spread. A segment's `from`/`to` edges must stay at least 4px off every message arrow (`message.y`): an edge along an arrow leaves the reader unable to tell which phase the message belongs to, and showcase quality reports `sequence/segment-message-border-run`. Standard retains its existing acceptance behavior.
First-draft shape: every message needs an `id`, `from`, `to`, `label`, and integer `y` at least 160. `from` and `to` must be different participants — self-messages are unsupported (`sequence/self-message-unsupported`). Optional phase bands are `segments[]` with only `from`, `to`, and `label` (no segment `id`). Inventing `pos`/`size` on participants fails schema validation — order alone places them. Omit `meta.viewBox` so automatic height fits the timeline + legend (minimum 327px readable band) instead of a fixed 760px floor, and so 2–3 participant spreads pack below the 920px default when labels fit (4+ stay at 920px; long labels still widen).
diff --git a/archify/renderers/architecture/render-architecture.mjs b/archify/renderers/architecture/render-architecture.mjs
index d96280c7..243d424e 100644
--- a/archify/renderers/architecture/render-architecture.mjs
+++ b/archify/renderers/architecture/render-architecture.mjs
@@ -662,7 +662,9 @@ function validateArchitecture() {
// a member. Report it instead of letting the picture claim false ownership.
// A box the frame border visibly cuts through does not claim membership,
// and earlier valid inputs depend on that, so only full enclosure fails.
- if (enforcesBoundaryTitleComposition) {
+ // This new composition gate applies to showcase; standard keeps its existing
+ // acceptance contract while authors can opt into the stricter check.
+ if (arch.meta?.quality_profile === 'showcase') {
for (const b of boundaries) {
const members = new Set(asArray(b.wraps));
for (const component of components.values()) {
diff --git a/archify/renderers/dataflow/render-dataflow.mjs b/archify/renderers/dataflow/render-dataflow.mjs
index 05dcb9c8..4a151f66 100644
--- a/archify/renderers/dataflow/render-dataflow.mjs
+++ b/archify/renderers/dataflow/render-dataflow.mjs
@@ -82,11 +82,13 @@ const automaticShowcase = qualityProfile === 'showcase'
const stageRight = stageX(asArray(dataflow.stages).length - 1) + layout.stageW / 2;
const nodeRights = asArray(dataflow.nodes).map(node =>
stageX(node.stage) + (node.width || layout.nodeW) / 2).filter(Number.isFinite);
+const pinnedLabelRights = asArray(dataflow.flows).filter(flow => flow.label && Array.isArray(flow.labelAt) && isFinitePoint(...flow.labelAt))
+ .map(flow => flow.labelAt[0] + flowLabelSize(flow).width / 2);
// Automatic width fits stages/nodes with 24px right pad. The old 940px floor
// left a blank third of the canvas on 2–3 stage drafts; five default stages
// still measure ~1068 and stay unchanged. Height starts at 720 and is refit
// by heightForLabels for automatic showcase.
-const contentWidth = Math.ceil(Math.max(stageRight, ...nodeRights, 0) + 24);
+const contentWidth = Math.ceil(Math.max(stageRight, ...nodeRights, ...pinnedLabelRights, 0) + 24);
const viewBox = dataflow.meta?.viewBox || [
Math.max(480, contentWidth),
720,
diff --git a/archify/renderers/erd/render-erd.mjs b/archify/renderers/erd/render-erd.mjs
index 937aea2d..fa1dc8ec 100644
--- a/archify/renderers/erd/render-erd.mjs
+++ b/archify/renderers/erd/render-erd.mjs
@@ -1044,6 +1044,7 @@ function validateEr() {
relationship.from === relationship.to ? null : relationship));
const headerDetails = [];
const domainDetails = [];
+ const attributeDetails = [];
for (const entity of entities.values()) {
const header = entityHeader(entity);
if (!header.problem) continue;
@@ -1115,7 +1116,7 @@ function validateEr() {
}
validateErGridPlacement(er, grid, bands, problems);
const seenEntityIds = new Set();
- for (const entity of asArray(er.entities)) {
+ for (const [entityIndex, entity] of asArray(er.entities).entries()) {
if (seenEntityIds.has(entity.id)) problems.push(`Entity ids must be unique; "${entity.id}" is declared twice.`);
seenEntityIds.add(entity.id);
@@ -1135,9 +1136,21 @@ function validateEr() {
const available = entityWidth(entity) - layout.padX * 2 - keyColumnWidth(entity);
const needed = nameUnits * layout.rowFont + (typeUnits ? typeUnits * layout.typeFont + 8 : 0);
if (needed > available) {
- problems.push(
- `Entity "${entity.id}" attribute ${attributeIndex} "${attribute.name}" needs ${Math.ceil(needed)}px of text but only ${Math.floor(available)}px is available — widen the entity, shorten the attribute name, or drop the type.`,
- );
+ const requiredEntityWidth = Math.ceil(needed + layout.padX * 2 + keyColumnWidth(entity));
+ const fix = `For this attribute row's text capacity, set entities[${entityIndex}].width to at least ${requiredEntityWidth}px, preserving the attribute name, type and key roles.`;
+ const message = `Entity "${entity.id}" attribute ${attributeIndex} "${attribute.name}" needs ${Math.ceil(needed)}px of text but only ${Math.floor(available)}px is available — ${fix}`;
+ problems.push(message);
+ attributeDetails.push({
+ code: 'erd/attribute-text-capacity', severity: 'error', message,
+ subject: { diagramType: 'erd', entityId: entity.id, attributeIndex, attributeName: attribute.name },
+ evidence: {
+ entityWidth: entityWidth(entity), requiredEntityWidth,
+ availableTextWidth: available, requiredTextWidth: needed,
+ paddingWidth: layout.padX * 2, keyColumnWidth: keyColumnWidth(entity),
+ nameFontSize: layout.rowFont, typeFontSize: layout.typeFont,
+ },
+ supportedFixes: [fix],
+ });
}
}
}
@@ -1303,7 +1316,7 @@ function validateEr() {
throwDiagnosticProblems('Entity-relationship layout validation failed', problems, {
code: 'layout/constraint',
subject: { diagramType: 'erd' },
- diagnostics: [...headerDetails, ...domainDetails, ...portSpacingDetails],
+ diagnostics: [...headerDetails, ...domainDetails, ...portSpacingDetails, ...attributeDetails],
});
}
}
@@ -1317,7 +1330,7 @@ function buildLayoutReport() {
relationships: relationships
.filter(renderableRelationship)
.map((relationship) => ({
- ...relationshipPath(relationship, pathFor(relationship), relationship.labelAt),
+ ...relationshipPath(relationship, pathFor(relationship), relationship.labelAt || resolvedLabelPoints.get(relationship)),
fromCardinality: cardinalityOf(relationship, 'from'),
toCardinality: cardinalityOf(relationship, 'to'),
})),
diff --git a/archify/renderers/sequence/render-sequence.mjs b/archify/renderers/sequence/render-sequence.mjs
index a45595c4..6020ff8e 100644
--- a/archify/renderers/sequence/render-sequence.mjs
+++ b/archify/renderers/sequence/render-sequence.mjs
@@ -64,6 +64,26 @@ function legendRequiredHeight(width) {
// desktop reading minimum; an inherently crowded row still fails below.
const spreadParticipantWidth = (canvasWidth) => Math.max(86,
Math.min(190, Math.round((canvasWidth - 124) / Math.max(1, asArray(sequence.participants).length)) - 24));
+function spreadColumnGeometry(canvasWidth) {
+ const count = Math.max(1, asArray(sequence.participants).length);
+ const width = spreadParticipantWidth(canvasWidth);
+ const span = count * width + (count - 1) * 16;
+ const margin = Math.max(40, Math.min(62, canvasWidth - 40 - span));
+ return { width, margin, gap: count > 1 ? Math.max(width + 16, (canvasWidth - 40 - margin - width) / (count - 1)) : 108 };
+}
+// Evaluate the same spread coordinates and full masks used by the renderer;
+// short participant names alone do not imply a compact timeline will fit.
+function timelineLabelsFit(canvasWidth) {
+ const { width, margin, gap } = spreadColumnGeometry(canvasWidth);
+ const centers = new Map(asArray(sequence.participants).map((participant, index) => [participant.id, margin + width / 2 + index * gap]));
+ const unitWidth = sequence.meta?.quality_profile === 'showcase' ? 6.6 : 5.2;
+ return asArray(sequence.messages).every((message) => {
+ if (!centers.has(message.from) || !centers.has(message.to)) return true;
+ const center = (centers.get(message.from) + centers.get(message.to)) / 2;
+ const halfWidth = Math.max(34, textUnits(message.label) * unitWidth + 12) / 2;
+ return center - halfWidth >= 0 && center + halfWidth <= canvasWidth;
+ }) && asArray(sequence.segments).every((segment) => 56 + Math.max(42, textUnits(segment.label) * 5.2 + 14) <= canvasWidth - 48);
+}
const readableCanvasWidth = Math.floor(DESKTOP_READER_DIAGRAM_WIDTH * participantTextFit.sublabelPreferred / MIN_PROJECTED_NODE_TEXT_PX);
function automaticCanvasWidth() {
const participantsFit = (width) => asArray(sequence.participants).every((participant) => (
@@ -81,7 +101,7 @@ function automaticCanvasWidth() {
for (const candidate of [560, 640, 720, 800, 920]) {
const box = spreadParticipantWidth(candidate);
const span = count * box + (count - 1) * 16;
- if (box >= 86 && participantsFit(box) && candidate - 80 >= span) return candidate;
+ if (box >= 86 && participantsFit(box) && candidate - 80 >= span && timelineLabelsFit(candidate)) return candidate;
}
}
return 920;
@@ -99,7 +119,11 @@ function automaticCanvasWidth() {
// usable; an authored viewBox is honored and validated below.
const SEQUENCE_MIN_AUTO_HEIGHT = 327;
const automaticWidth = sequence.meta?.viewBox ? null : automaticCanvasWidth();
-const automaticHeight = Math.max(SEQUENCE_MIN_AUTO_HEIGHT, legendRequiredHeight(automaticWidth));
+// Timeline clearance is independent of legend visibility. Messages need 18px
+// before the lifeline bottom; notes, activations and frames need their footer.
+const timelineRequiredHeight = Math.max(contentBottom + 65,
+ ...asArray(sequence.messages).map((message) => message.y + 18 + 65));
+const automaticHeight = Math.max(SEQUENCE_MIN_AUTO_HEIGHT, timelineRequiredHeight, legendRequiredHeight(automaticWidth));
const viewBox = sequence.meta?.viewBox || [automaticWidth, automaticHeight];
// The timeline scales with viewBox height: a taller viewBox gains message room,
// a shorter one shrinks the readable band (validated below) instead of clipping.
@@ -110,17 +134,17 @@ const viewBox = sequence.meta?.viewBox || [automaticWidth, automaticHeight];
const columnFit = sequence.meta?.column_fit || 'spread';
const participantCount = Math.max(1, asArray(sequence.participants).length);
const preferredSideMargin = 62;
-const participantW = columnFit === 'spread' ? spreadParticipantWidth(viewBox[0]) : 86;
+const spreadGeometry = spreadColumnGeometry(viewBox[0]);
+const participantW = columnFit === 'spread' ? spreadGeometry.width : 86;
// Narrow feasible frames can reduce the left margin, while ordinary frames
// keep 62px. Compute card width first so this does not change its sizing rule.
-const minimumParticipantSpan = participantCount * participantW + (participantCount - 1) * 16;
const sideMargin = columnFit === 'spread'
- ? Math.max(40, Math.min(preferredSideMargin, viewBox[0] - 40 - minimumParticipantSpan))
+ ? spreadGeometry.margin
: preferredSideMargin;
// Fit the authored width when feasible, preserving a real 16px card gutter.
// Infeasible frames retain that minimum and fail the capacity check below.
const colGap = columnFit === 'spread' && participantCount > 1
- ? Math.max(participantW + 16, (viewBox[0] - 40 - sideMargin - participantW) / (participantCount - 1))
+ ? spreadGeometry.gap
: 108;
// Showcase is the fast-authoring default; standard retains legacy label geometry.
@@ -140,7 +164,9 @@ const layout = {
legendY: viewBox[1] - 54,
leftX: columnFit === 'spread' ? sideMargin + participantW / 2 : sideMargin,
colGap,
- labelH: readableMessages ? 18 : 16
+ labelH: readableMessages ? 18 : 16,
+ noteFontSize: 7,
+ noteBaselineOffset: 18,
};
// Automatic showcase spread can guarantee a readable fit within its bounded
@@ -217,10 +243,27 @@ function messageRouteBox(message) {
};
}
+function messageNoteBox(message) {
+ const geometry = messageGeometry(message);
+ if (!message.note || !geometry) return null;
+ const font = layout.noteFontSize;
+ const baseline = message.y + layout.noteBaselineOffset;
+ return {
+ x: Math.min(geometry.start, geometry.end) + 12,
+ // Include conservative ascent/descent for CJK and fallback fonts, as in
+ // the shared node text geometry. Rendering uses this same baseline/font.
+ y: baseline - font * 1.2,
+ width: minimumNodeTextWidth(message.note, font),
+ height: font * 1.5,
+ baseline,
+ font,
+ };
+}
+
function segmentLabelBox(segment) {
const labelW = Math.max(42, textUnits(segment.label) * 5.2 + 14);
const occupied = asArray(sequence.messages)
- .flatMap((message) => [messageLabelBox(message), messageRouteBox(message)])
+ .flatMap((message) => [messageLabelBox(message), messageRouteBox(message), messageNoteBox(message)])
.filter(Boolean);
const label = { x: 56, y: segment.from - 22, width: labelW, height: 18 };
for (let attempt = 0; attempt < 4; attempt += 1) {
@@ -238,7 +281,7 @@ function segmentLabelBox(segment) {
.map((other) => ({ x: 56, y: other.from - 22, width: Math.max(42, textUnits(other.label) * 5.2 + 14), height: 18 }));
const inside = { x: 56, y: segment.from + 4, width: labelW, height: 18 };
for (let attempt = 0; attempt < 4 && inside.y + inside.height <= segment.to - 2; attempt += 1) {
- if (![...occupied, ...otherTitles].some((rect) => rectsOverlap(inside, rect, 2))) return inside;
+ if (![...occupied, ...otherTitles, ...participants.values()].some((rect) => rectsOverlap(inside, rect, 2))) return inside;
inside.y += 22;
}
return label;
@@ -494,13 +537,21 @@ function validateSequence() {
// A frame edge may pass behind a masked message label, but an edge that
// runs along the arrow itself leaves the reader unable to tell which phase
// the message belongs to.
- if (sequence.meta?.quality_profile) {
+ if (sequence.meta?.quality_profile === 'showcase') {
for (const edge of ['from', 'to']) {
const border = segment[edge];
const cut = asArray(sequence.messages).filter((message) => typeof message.y === 'number'
&& Math.abs(border - message.y) < 4);
for (const message of cut) {
- problems.push(`Segment "${segment.label}" ${edge === 'from' ? 'top' : 'bottom'} edge at y ${border} runs along message "${message.label}" (arrow at y ${message.y}) — move the edge to at least ${message.y + 4} to leave the message above it, or to at most ${message.y - 4} to leave it below.`);
+ const problem = `Segment "${segment.label}" ${edge === 'from' ? 'top' : 'bottom'} edge at y ${border} runs along message "${message.label}" (arrow at y ${message.y}) — move the edge to at least ${message.y + 4} to leave the message above it, or to at most ${message.y - 4} to leave it below.`;
+ const segmentIndex = asArray(sequence.segments).indexOf(segment);
+ problems.push(problem);
+ diagnostics.push({
+ code: 'sequence/segment-message-border-run', severity: 'error', message: problem,
+ subject: { diagramType: 'sequence', collection: 'segments', index: segmentIndex, path: `/segments/${segmentIndex}/${edge}` },
+ evidence: { segmentLabel: segment.label, edge, borderY: border, messageIndex: messageList.indexOf(message), messageLabel: message.label, messageY: message.y, minimumClearancePx: 4 },
+ supportedFixes: [`set /segments/${segmentIndex}/${edge} to at least ${message.y + 4} to leave the message above it`, `set /segments/${segmentIndex}/${edge} to at most ${message.y - 4} to leave the message below it`],
+ });
}
}
}
@@ -619,8 +670,9 @@ function renderMessage(message, index) {
const [cls, marker] = arrowClass[message.variant || 'default'] || arrowClass.default;
const strokeWidth = message.variant === 'emphasis' ? 1.8 : 1.4;
const dash = message.variant === 'return' ? ' stroke-dasharray="3,5"' : '';
- const note = message.note
- ? `\n <text data-detail="fine" x="${Math.min(start, end) + 12}" y="${message.y + 18}" class="t-dim" font-size="7">${esc(message.note)}</text>`
+ const noteBox = messageNoteBox(message);
+ const note = noteBox
+ ? `\n <text data-detail="fine" x="${noteBox.x}" y="${noteBox.baseline}" class="t-dim" font-size="${noteBox.font}">${esc(message.note)}</text>`
: '';
return ` <g ${focusEdgeAttrs(message.from, message.to, message.label, index, message.id)}>
<path data-composition-edge-from="${esc(message.from)}" data-composition-edge-to="${esc(message.to)}"${message.id ? ` data-composition-edge-id="${esc(message.id)}"` : ''} data-composition-points="${routePointsValue([[start, message.y], [end, message.y]])}" d="M ${start} ${message.y} L ${end} ${message.y}" class="${cls}"${animateAttr(sequence.meta, 'edge', index)} stroke-width="${strokeWidth}"${dash} marker-end="url(#${marker})"/>
diff --git a/archify/renderers/workflow/workflow-compiler.mjs b/archify/renderers/workflow/workflow-compiler.mjs
index fcfdf285..41601cb9 100644
--- a/archify/renderers/workflow/workflow-compiler.mjs
+++ b/archify/renderers/workflow/workflow-compiler.mjs
@@ -2274,20 +2274,40 @@ function routeContainsChannelPin(points, field, value) {
});
}
-function hasClearStraightAutomaticRoute(edge) {
- if (!independentAutomaticRoute(edge) || edge.from === edge.to) return false;
+function clearStraightAutomaticPlan(edge) {
+ if (!independentAutomaticRoute(edge) || edge.from === edge.to) return null;
// Relative label pins are not absolute, but they still participate in
// placed-label conflict evidence. Reserving a straight path for them first
// can change which edge owns the corridor and scramble supportedFixes.
if (edge.labelDx !== undefined || edge.labelDy !== undefined || edge.labelSegment !== undefined) {
- return false;
+ return null;
}
const from = nodes.get(edge.from);
const to = nodes.get(edge.to);
const start = anchor(from, defaultFromSide(from, to));
const end = anchor(to, defaultToSide(from, to));
const aligned = Math.abs(start[0] - end[0]) < 0.0001 || Math.abs(start[1] - end[1]) < 0.0001;
- return aligned && routeClearsUnrelatedNodes(edge, [start, end]);
+ if (!aligned || !routeClearsUnrelatedNodes(edge, [start, end])) return null;
+ // Facing centres are only a cheap filter. Port selection, labels and route
+ // costs can still select a bent route; reserving that route first would let
+ // a long branch displace a shorter one. Preview the ordinary planner and
+ // reserve only its selected straight route, without registering obstacles.
+ const hadSides = readableSideCache.has(edge);
+ const previousSides = readableSideCache.get(edge);
+ try {
+ const plan = withDiagnosticRecordingSuppressed(() => readableAutomaticRoute(
+ edge, from, to, edgeSides(edge), automaticPorts.get(edge),
+ ));
+ return plan.points.length === 2 ? plan : null;
+ } catch (error) {
+ // A preview does not own layout feedback or failure diagnostics. Let the
+ // ordinary routing order establish them with its complete preceding scene.
+ if (error instanceof WorkflowLayoutFeedback || Array.isArray(error?.archifyDiagnostics)) return null;
+ throw error;
+ } finally {
+ if (hadSides) readableSideCache.set(edge, previousSides);
+ else readableSideCache.delete(edge);
+ }
}
function validateReadablePinnedGeometry() {
@@ -2316,9 +2336,11 @@ function validateReadablePinnedGeometry() {
));
if (discoverFixes && !hasLabelPins) {
for (const edge of workflow.edges) {
- if (!nodes.has(edge.from) || !nodes.has(edge.to) || !hasClearStraightAutomaticRoute(edge)) continue;
+ if (!nodes.has(edge.from) || !nodes.has(edge.to)) continue;
+ const plan = clearStraightAutomaticPlan(edge);
+ if (!plan) continue;
validateReadableRouteControls(edge);
- pathFor(edge);
+ pathFor(edge, plan);
}
}
// Routing order feedback: an automatic edge that an earlier automatic edge
@@ -4301,6 +4323,70 @@ function automaticPortCandidates(edge, node, side, preferred, counterpart) {
return candidates.length ? candidates : [preferred];
}
+function automaticEndpointRepairs(edge, selected, from, to, naturalFromSide, naturalToSide) {
+ if (!independentAutomaticRoute(edge)
+ || ['labelDx', 'labelDy', 'labelSegment', 'bias'].some(field => edge[field] !== undefined)
+ || selected.cost.properCrossingCount !== 0 || selected.cost.sharedCorridorPx === 0
+ || selected.points.length < 3) return [];
+ const corridorHits = (points) => [...pathCache].flatMap(([relation, routed]) => (
+ collectAmbiguousCorridors({
+ routedRelations: [{ relation: edge, points }, { relation, points: routed.points }],
+ includeSharedEndpoints: () => true,
+ allowShortWorkflowTrunks: true,
+ })
+ ));
+ const originalHits = corridorHits(selected.points);
+ const originalNeighbours = new Set(originalHits.map(hit => hit.right.relation));
+ const strokeWidth = relation => relation.width || (relation.variant === 'emphasis' ? 1.8 : 1.4);
+ const arrowRelation = relation => ({ ...relation, width: strokeWidth(relation) });
+ const ownArrow = arrowRelation(edge);
+ const incoming = [...(nodeRoutes.get(edge.to) ?? [])].map(([relation, routed]) => ({
+ relation: arrowRelation(relation), points: routed.points,
+ }));
+ const repairs = [];
+ for (const endpoint of ['from', 'to']) {
+ const first = endpoint === 'from';
+ const endpointIndex = first ? 0 : selected.points.length - 1;
+ const segmentIndex = first ? 0 : selected.points.length - 2;
+ if (!originalHits.some(hit => hit.leftSegment === segmentIndex)) continue;
+ const node = first ? from : to;
+ const side = first ? selected.fromSide : selected.toSide;
+ const axis = side === 'left' || side === 'right' ? 1 : 0;
+ const minimum = (axis ? node.y : node.x) + 16;
+ const maximum = (axis ? node.y + node.height : node.x + node.width) - 16;
+ // Keep the side, its perpendicular stub, and the existing corner gutter.
+ // Small slides can separate source strokes or a source from an arrow even
+ // when the normal 12px port-spread step cannot fit on a 52px node side.
+ for (const offset of [-8, 8, -10, 10]) {
+ const points = selected.points.map(point => [...point]);
+ points[endpointIndex][axis] += offset;
+ points[first ? 1 : points.length - 2][axis] += offset;
+ if (points[endpointIndex][axis] < minimum || points[endpointIndex][axis] > maximum) continue;
+ const endpointFootprint = (first ? 0.5 : 3.5) * strokeWidth(edge);
+ const clearPort = [...(nodeRoutes.get(node.id) ?? [])].every(([relation, routed]) => (
+ ['from', 'to'].every(otherEndpoint => {
+ if (relation[otherEndpoint] !== node.id) return true;
+ const point = otherEndpoint === 'from' ? routed.points[0] : routed.points.at(-1);
+ if (Math.abs(point[1 - axis] - points[endpointIndex][1 - axis]) > 0.0001) return true;
+ const otherFootprint = (otherEndpoint === 'from' ? 0.5 : 3.5) * strokeWidth(relation);
+ return Math.abs(point[axis] - points[endpointIndex][axis]) + 0.0001 >= endpointFootprint + otherFootprint;
+ })
+ ));
+ if (!clearPort) continue;
+ if (!readableCandidateIsFeasible(edge, points, from, to, selected.fromSide, selected.toSide)) continue;
+ const cost = readableCandidateCost(edge, points, selected.cost.stableCandidateOrdinal, naturalFromSide, naturalToSide);
+ if (cost.properCrossingCount !== 0 || cost.sharedCorridorPx >= selected.cost.sharedCorridorPx) continue;
+ if (corridorHits(points).some(hit => !originalNeighbours.has(hit.right.relation))) continue;
+ if (collectArrowheadCollisions({
+ routedRelations: [{ relation: ownArrow, points }, ...incoming],
+ allowShortWorkflowTrunks: true,
+ }).some(hit => hit.left.relation === ownArrow || hit.right.relation === ownArrow)) continue;
+ repairs.push({ ...selected, points, cost });
+ }
+ }
+ return repairs;
+}
+
function readableAutomaticRoute(edge, from, to, primarySides, primaryPorts) {
const authoredFrom = edge.fromSide && edge.fromSide !== 'auto' ? edge.fromSide : null;
const authoredTo = edge.toSide && edge.toSide !== 'auto' ? edge.toSide : null;
@@ -4439,6 +4525,7 @@ function readableAutomaticRoute(edge, from, to, primarySides, primaryPorts) {
plans.sort((left, right) => compareCost(left.cost, right.cost));
if (plans.length) {
+ const endpointRepairs = automaticEndpointRepairs(edge, plans[0], from, to, naturalFromSide, naturalToSide);
const repairSeeds = plans[0].cost.sharedCorridorPx > 0
? plans.filter((plan, index) => plans.findIndex(other => (
other.fromSide === plan.fromSide && other.toSide === plan.toSide
@@ -4466,6 +4553,7 @@ function readableAutomaticRoute(edge, from, to, primarySides, primaryPorts) {
alternatives.sort((a, b) => compareCost(a.cost, b.cost));
if (alternatives.length) plans.push(alternatives[0]);
}
+ plans.push(...endpointRepairs);
plans.sort((a, b) => compareCost(a.cost, b.cost));
const selected = plans[0];
return {
@@ -4669,7 +4757,7 @@ function registerRouted(edge, routed) {
return routed;
}
-function pathFor(edge) {
+function pathFor(edge, automaticPlan = null) {
if (pathCache.has(edge)) return pathCache.get(edge);
const from = nodes.get(edge.from);
const to = nodes.get(edge.to);
@@ -4692,7 +4780,7 @@ function pathFor(edge) {
&& edge.channelY === undefined
&& (!edge.route || edge.route === 'auto');
if (readableAutomatic) {
- const planned = readableAutomaticRoute(
+ const planned = automaticPlan || readableAutomaticRoute(
edge,
from,
to,
diff --git a/test/architecture-first-draft.test.mjs b/test/architecture-first-draft.test.mjs
index 7ea9c74b..8726a379 100644
--- a/test/architecture-first-draft.test.mjs
+++ b/test/architecture-first-draft.test.mjs
@@ -176,3 +176,21 @@ test('architecture: a component inside a boundary frame it is not wrapped by is
const example = validate('architecture', path.join(skillRoot, 'examples', 'production-deployment.architecture.json'));
assert.equal(example.status, 0, JSON.stringify(example.receipt?.diagnostics));
});
+
+test('architecture: non-member enclosure keeps standard compatibility and rejects misleading showcase membership', (t) => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-boundary-profile-'));
+ t.after(() => fs.rmSync(tmp, { recursive: true, force: true }));
+ const candidate = JSON.parse(fs.readFileSync(path.join(fixtures, 'queue-sol.architecture.json'), 'utf8'));
+ // Isolate ownership from the source fixture's unrelated label-gap defects.
+ for (const connection of candidate.connections) delete connection.label;
+ const input = path.join(tmp, 'boundary.json');
+ for (const quality of ['standard', 'showcase']) {
+ candidate.meta.quality_profile = quality;
+ fs.writeFileSync(input, JSON.stringify(candidate));
+ const result = spawnSync(process.execPath, [cli, 'validate', 'architecture', input, '--quality', quality, '--json'], { encoding: 'utf8' });
+ const receipt = JSON.parse(result.stdout);
+ assert.equal(result.status, quality === 'standard' ? 0 : 1, result.stdout + result.stderr);
+ const enclosure = receipt.diagnostics?.filter(issue => issue.code === 'layout/boundary-encloses-non-member') || [];
+ assert.equal(enclosure.length, quality === 'standard' ? 0 : 1);
+ }
+});
diff --git a/test/dataflow-automatic-layout.test.mjs b/test/dataflow-automatic-layout.test.mjs
index a025d12d..10da00c7 100644
--- a/test/dataflow-automatic-layout.test.mjs
+++ b/test/dataflow-automatic-layout.test.mjs
@@ -50,6 +50,30 @@ function pipeline() {
};
}
+test('automatic dataflow width contains a nearby authored label without moving its pin', t => {
+ const diagram = {
+ schema_version: 1, diagram_type: 'dataflow',
+ meta: { title: 'Pinned payload', output: 'diagram.html', quality_profile: 'showcase' },
+ stages: [{ label: 'Source' }, { label: 'Sink' }],
+ nodes: [
+ { id: 'source', type: 'backend', label: 'Source', stage: 0, row: 0 },
+ { id: 'sink', type: 'backend', label: 'Sink', stage: 1, row: 0 },
+ { id: 'archive', type: 'backend', label: 'Archive', stage: 1, row: 1 },
+ ],
+ flows: [{ id: 'flow', from: 'sink', to: 'archive', label: 'versioned transaction payload contract', labelAt: [435, 225] }],
+ };
+ const { result, receipt, input, output, env } = inspect(t, diagram);
+ assert.equal(result.status, 0, JSON.stringify(receipt));
+ const rendered = spawnSync(process.execPath, [cli, 'render', 'dataflow', input, output], { encoding: 'utf8', env });
+ assert.equal(rendered.status, 0, rendered.stdout + rendered.stderr);
+ const html = fs.readFileSync(output, 'utf8');
+ const width = Number(html.match(/<svg viewBox="0 0 (\d+) /)[1]);
+ assert.ok(width >= 535 && width < 940, `pin should fit without the old width floor, got ${width}`);
+ assert.match(html, /<text x="435" y="225"/);
+ assert.match(html, /versioned transaction payload contract/);
+ assert.match(html, /data-composition-points="315,186;315,242"/);
+});
+
test('five-stage unpinned pipeline passes first draft with complete text and projected typography', t => {
const diagram = pipeline();
const { result, receipt, input, output, env } = inspect(t, diagram);
diff --git a/test/erd-label-capacity.test.mjs b/test/erd-label-capacity.test.mjs
new file mode 100644
index 00000000..31a6be85
--- /dev/null
+++ b/test/erd-label-capacity.test.mjs
@@ -0,0 +1,277 @@
+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 { rectsOverlap, segmentRectClearanceWithin } from '../archify/renderers/shared/geometry.mjs';
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const cli = path.join(root, 'archify/bin/archify.mjs');
+const renderer = path.join(root, 'archify/renderers/erd/render-erd.mjs');
+const rows = count => Array.from({ length: count }, (_, index) => ({ name: `field_${index}`, type: 'TEXT' }));
+
+function fixture(quality = 'standard') {
+ return {
+ schema_version: 1, diagram_type: 'erd', meta: { title: 'Branch labels', locale: 'en', quality_profile: quality },
+ layout: { mode: 'grid', gapX: 72, gapY: 40, entityW: 260 },
+ entities: [
+ { id: 'parent', label: 'Parent', row: 1, col: 0, attributes: rows(9) },
+ { id: 'category', label: 'Category', row: 3, col: 0, attributes: rows(12) },
+ { id: 'item', label: 'Item', row: 0, col: 1, width: 290, attributes: rows(28) },
+ ],
+ relationships: [
+ { id: 'parent_link', from: 'item', to: 'parent', label: 'parentId', fromCardinality: 'many', toCardinality: 'one' },
+ { id: 'category_link', from: 'item', to: 'category', label: 'categoryId', fromCardinality: 'many', toCardinality: 'one' },
+ ],
+ };
+}
+
+function verticalFixture(quality = 'standard') {
+ const document = fixture(quality);
+ document.entities = [
+ { id: 'parent', label: 'Parent', row: 0, col: 0, attributes: rows(3) },
+ { id: 'category', label: 'Category', row: 2, col: 0, attributes: rows(3) },
+ { id: 'item', label: 'Item', row: 1, col: 0, width: 290, attributes: rows(3) },
+ ];
+ document.relationships[0].from = 'parent';
+ document.relationships[0].to = 'item';
+ return document;
+}
+
+function invoke(t, document, command = 'render') {
+ const folder = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-erd-label-capacity-'));
+ t.after(() => fs.rmSync(folder, { recursive: true, force: true }));
+ const input = path.join(folder, 'input.json');
+ const output = path.join(folder, 'output.html');
+ fs.writeFileSync(input, JSON.stringify(document));
+ const result = spawnSync(process.execPath, [cli, command, 'erd', input, ...(command === 'render' ? [output] : ['--json'])], {
+ encoding: 'utf8', env: { ...process.env, ARCHIFY_UPDATE_CHECK_DISABLED: '1' },
+ });
+ return { ...result, input, output, html: fs.existsSync(output) ? fs.readFileSync(output, 'utf8') : '' };
+}
+
+function boxes(html, label) {
+ const number = '(-?[\\d.]+)';
+ const rect = `x="${number}" y="${number}" width="${number}" height="${number}"`;
+ return [...html.matchAll(new RegExp(`<rect ${rect}[^>]*class="${label ? 'c-mask' : 'c-database er-table'}"[^>]*>${label ? `\\s*<text[^>]*>${label}<\\/text>` : ''}`, 'g'))]
+ .map(match => ({ x: +match[1], y: +match[2], width: +match[3], height: +match[4] }));
+}
+
+function routes(html) {
+ return [...html.matchAll(/<path\b[^>]*data-edge-label="([^"]*)"[^>]*data-composition-points="([^"]+)"[^>]*marker-end[^>]*>/g)]
+ .map(match => ({ label: match[1], points: match[2].split(';').map(pair => pair.split(',').map(Number)) }));
+}
+
+test('ERD automatic vertical labels clear authored table geometry in both profiles', t => {
+ for (const quality of ['standard', 'showcase']) {
+ const result = invoke(t, verticalFixture(quality));
+ assert.equal(result.status, 0, result.stderr + result.stdout);
+ assert.match(result.html, /parentId/);
+ assert.match(result.html, /categoryId/);
+ const entities = boxes(result.html);
+ assert.deepEqual(entities.map(box => box.width), [260, 260, 290]);
+ assert.deepEqual(entities.map(box => box.height), [96, 96, 96]);
+ assert.deepEqual(entities.map(box => [box.x, box.y]), [[47, 40], [47, 312], [32, 176]]);
+ const paths = routes(result.html);
+ for (const label of ['parentId', 'categoryId']) {
+ const [rect] = boxes(result.html, label);
+ assert.ok(rect, `rendered label ${label}`);
+ assert.ok(entities.every(entity => !rectsOverlap(rect, entity, 2)));
+ for (const route of paths.filter(route => route.label !== label)) {
+ for (let index = 1; index < route.points.length; index++) {
+ assert.ok(segmentRectClearanceWithin({ start: route.points[index - 1], end: route.points[index] }, rect, 4) >= 4);
+ }
+ }
+ }
+ }
+});
+
+test('ERD zero-valued label controls keep the authored failure', t => {
+ for (const key of ['labelDx', 'labelDy', 'labelSegment']) {
+ const document = verticalFixture();
+ document.relationships.forEach(relationship => { relationship[key] = 0; });
+ const result = invoke(t, document, 'validate');
+ assert.equal(result.status, 1, `${key}: ${result.stdout}`);
+ assert.match(result.stdout, /Label.*overlaps entity/);
+ }
+});
+
+test('ERD bundled labels stay beside unique branches and clear the shared trunk', t => {
+ const result = invoke(t, fixture());
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ const shared = [...result.html.matchAll(/<path data-er-trunk="" data-composition-points="([^"]+)"/g)]
+ .map(match => match[1].split(';').map(pair => pair.split(',').map(Number)));
+ assert.ok(shared.length, 'the fixture retains its shared trunk');
+ const paths = routes(result.html);
+ for (const label of ['parentId', 'categoryId']) {
+ const [rect] = boxes(result.html, label);
+ assert.ok(boxes(result.html).every(entity => !rectsOverlap(rect, entity, 2)));
+ for (const points of shared) {
+ for (let index = 1; index < points.length; index++) {
+ assert.ok(segmentRectClearanceWithin({ start: points[index - 1], end: points[index] }, rect, 4) >= 4, `${label} must not annotate the shared bus`);
+ }
+ }
+ const own = paths.find(route => route.label === label).points;
+ const uniqueStubs = [own.slice(0, 2), own.slice(-2)];
+ assert.ok(uniqueStubs.some(([start, end]) => segmentRectClearanceWithin({ start, end }, rect, 22) <= 22), `${label} stays beside its unique source or target stub`);
+ }
+});
+
+test('ERD explicit label points stay exactly where authored', t => {
+ const document = fixture();
+ document.relationships[0].labelAt = [200, 600];
+ document.relationships[1].labelAt = [200, 900];
+ const result = invoke(t, document);
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ assert.match(result.html, /<text x="200" y="600"[^>]*>parentId<\/text>/);
+ assert.match(result.html, /<text x="200" y="900"[^>]*>categoryId<\/text>/);
+ assert.deepEqual(labelReport(result).relationships.map(relationship => relationship.labelAt), [[200, 600], [200, 900]]);
+});
+
+test('ERD authored waypoints and canvas stay authoritative', t => {
+ const document = fixture();
+ document.meta.viewBox = [720, 340];
+ document.entities = [
+ { id: 'parent', label: 'Parent', pos: [32, 40], width: 240, attributes: rows(3) },
+ { id: 'item', label: 'Item', pos: [400, 140], width: 240, attributes: rows(3) },
+ ];
+ document.relationships = [{ id: 'link', from: 'parent', to: 'item', label: 'reference',
+ fromSide: 'right', toSide: 'left', via: [[336, 88], [336, 188]],
+ fromCardinality: 'one', toCardinality: 'many' }];
+ const result = invoke(t, document);
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ assert.match(result.html, /viewBox="0 0 720 340"/);
+ assert.deepEqual(boxes(result.html), [{ x: 32, y: 40, width: 240, height: 96 }, { x: 400, y: 140, width: 240, height: 96 }]);
+ assert.deepEqual(routes(result.html)[0].points, [[272, 88], [336, 88], [336, 188], [400, 188]]);
+});
+
+test('ERD grid-owned gaps grow to fit labels without changing fields or table dimensions', t => {
+ const document = fixture();
+ document.layout = { mode: 'grid' };
+ document.entities = [
+ { id: 'parent', label: 'Parent', row: 0, col: 0, attributes: rows(9) },
+ { id: 'item', label: 'Item', row: 0, col: 1, attributes: rows(9) },
+ ];
+ document.relationships = [{ id: 'link', from: 'parent', to: 'item', label: 'foreign_reference', fromCardinality: 'one', toCardinality: 'many' }];
+ const result = invoke(t, document);
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ const entities = boxes(result.html);
+ assert.deepEqual(entities.map(entity => [entity.width, entity.height]), [[240, 216], [240, 216]]);
+ const [label] = boxes(result.html, 'foreign_reference');
+ assert.ok(entities.every(entity => !rectsOverlap(label, entity, 2)));
+ const gap = entities[1].x - entities[0].x - entities[0].width;
+ assert.ok(gap >= label.width + 48, 'the gap holds the label and both cardinality glyphs');
+ for (const attribute of document.entities[0].attributes) assert.match(result.html, new RegExp(attribute.name));
+});
+
+test('ERD automatic labels stay clear of domain captions and the legend', t => {
+ const document = verticalFixture();
+ document.entities.forEach(entity => { entity.tag = `${entity.label} domain`; });
+ document.meta.legend = { entries: { one: { label: 'One referenced entity' } } };
+ const result = invoke(t, document);
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ const viewBox = result.html.match(/viewBox="0 0 ([\d.]+) ([\d.]+)"/);
+ assert.ok(viewBox);
+ const height = +viewBox[2];
+ const captions = [...result.html.matchAll(/<text data-domain-label="" x="([\d.]+)" y="([\d.]+)"[^>]*>([^<]+)<\/text>/g)]
+ .map(match => ({ x: +match[1], y: +match[2] - 10, width: match[3].length * 9 * 0.6, height: 12 }));
+ assert.equal(captions.length, 3);
+ for (const label of ['parentId', 'categoryId']) {
+ const [rect] = boxes(result.html, label);
+ assert.ok(captions.every(caption => !rectsOverlap(rect, caption, 2)));
+ assert.ok(rect.y >= 0 && rect.x >= 0 && rect.y + rect.height < height - 40);
+ }
+});
+
+test('ERD capacity diagnostics give an executable full width without deleting text', t => {
+ const document = fixture();
+ document.entities = [{ id: 'parent', label: 'Parent', row: 0, col: 0, width: 240,
+ attributes: [{ name: 'external_reference_code', type: 'varchar(128)', key: ['pk', 'uk'] }] }];
+ document.relationships = [];
+ const result = invoke(t, document, 'validate');
+ assert.equal(result.status, 1);
+ const diagnostic = JSON.parse(result.stdout).diagnostics.find(entry => entry.code === 'erd/attribute-text-capacity');
+ assert.ok(diagnostic, result.stdout);
+ assert.deepEqual(diagnostic.subject, { diagramType: 'erd', entityId: 'parent', attributeIndex: 0, attributeName: 'external_reference_code' });
+ assert.ok(diagnostic.evidence.requiredEntityWidth > 240);
+ assert.equal(diagnostic.evidence.keyColumnWidth, 50);
+ assert.equal(diagnostic.evidence.paddingWidth, 24);
+ assert.equal(diagnostic.evidence.nameFontSize, 11);
+ assert.equal(diagnostic.evidence.typeFontSize, 10.5);
+ assert.equal(diagnostic.evidence.requiredEntityWidth, 310, 'name + type + text gap + key badges + both paddings');
+ assert.ok(Math.abs(diagnostic.evidence.requiredTextWidth - 235.4) < 0.0001);
+ assert.equal(diagnostic.evidence.availableTextWidth, 166);
+ assert.match(diagnostic.supportedFixes[0], /For this attribute row's text capacity/);
+ assert.match(diagnostic.supportedFixes[0], /entities\[0\]\.width/);
+ assert.doesNotMatch(diagnostic.message + diagnostic.supportedFixes.join(' '), /drop|shorten/);
+ document.entities[0].width = diagnostic.evidence.requiredEntityWidth - 1;
+ const tooNarrow = invoke(t, document, 'validate');
+ assert.equal(tooNarrow.status, 1);
+ assert.ok(JSON.parse(tooNarrow.stdout).diagnostics.some(entry => entry.code === 'erd/attribute-text-capacity'));
+ document.entities[0].width = diagnostic.evidence.requiredEntityWidth;
+ const repaired = invoke(t, document);
+ assert.equal(repaired.status, 0, repaired.stderr + repaired.stdout);
+ assert.match(repaired.html, /external_reference_code/);
+ assert.match(repaired.html, /varchar\(128\)/);
+ assert.match(repaired.html, /font-size="11">external_reference_code<\/text>/);
+ assert.match(repaired.html, /class="er-type" font-size="10.5"[^>]*>varchar\(128\)<\/text>/);
+ for (const key of ['pk', 'uk']) assert.match(repaired.html, new RegExp(`data-er-badge="${key}"`));
+});
+
+function labelReport(result) {
+ const reported = spawnSync(process.execPath, [renderer, result.input, result.output, '--layout-json'], { encoding: 'utf8' });
+ assert.equal(reported.status, 0, reported.stdout + reported.stderr);
+ return JSON.parse(reported.stdout);
+}
+
+function labelPoint(html, label) {
+ const text = html.match(new RegExp(`<text x="([\\d.-]+)" y="([\\d.-]+)"[^>]*>${label}<\\/text>`));
+ assert.ok(text, `rendered text for ${label}`);
+ return [Number(text[1]), Number(text[2])];
+}
+
+test('ERD layout report exposes each resolved automatic label at its rendered point', t => {
+ for (const document of [verticalFixture(), fixture()]) {
+ const result = invoke(t, document);
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ const report = labelReport(result);
+ for (const relationship of report.relationships) {
+ assert.deepEqual(relationship.labelAt, labelPoint(result.html, relationship.label).map(Math.round), 'the report uses the shared serializer rounding of the rendered point');
+ }
+ }
+});
+
+test('ERD origin labelAt remains authored in SVG and report while public validation rejects its overflow', t => {
+ const document = verticalFixture('showcase');
+ document.relationships[0].labelAt = [0, 0];
+ const result = invoke(t, document, 'validate');
+ assert.equal(result.status, 1, result.stdout);
+ const raw = spawnSync(process.execPath, [renderer, result.input, result.output], { encoding: 'utf8' });
+ assert.equal(raw.status, 0, raw.stdout + raw.stderr);
+ assert.deepEqual(labelPoint(fs.readFileSync(result.output, 'utf8'), 'parentId'), [0, 0]);
+ assert.deepEqual(labelReport(result).relationships.find(relationship => relationship.label === 'parentId').labelAt, [0, 0]);
+});
+
+test('ERD capacity uses inherited widths, the entity index and no type gap when type is omitted', t => {
+ const document = fixture();
+ document.layout.entityW = 180;
+ document.entities = [
+ { id: 'first', label: 'First', row: 0, col: 0, attributes: [{ name: 'id' }] },
+ { id: 'second', label: 'Second', row: 0, col: 1, attributes: [{ name: 'a'.repeat(48) }] },
+ ];
+ document.relationships = [];
+ const result = invoke(t, document, 'validate');
+ assert.equal(result.status, 1, result.stdout);
+ const diagnostic = JSON.parse(result.stdout).diagnostics.find(entry => entry.code === 'erd/attribute-text-capacity');
+ assert.equal(diagnostic.subject.entityId, 'second');
+ assert.equal(diagnostic.evidence.entityWidth, 180);
+ assert.equal(diagnostic.evidence.keyColumnWidth, 30);
+ assert.equal(diagnostic.evidence.requiredEntityWidth, 371);
+ assert.match(diagnostic.supportedFixes[0], /entities\[1\]\.width/);
+ document.entities[1].width = diagnostic.evidence.requiredEntityWidth;
+ const repaired = invoke(t, document);
+ assert.equal(repaired.status, 0, repaired.stdout + repaired.stderr);
+ assert.match(repaired.html, new RegExp(document.entities[1].attributes[0].name));
+});
diff --git a/test/fixtures/workflow-first-draft/automatic-fanout.workflow.json b/test/fixtures/workflow-first-draft/automatic-fanout.workflow.json
new file mode 100644
index 00000000..fb66f8b1
--- /dev/null
+++ b/test/fixtures/workflow-first-draft/automatic-fanout.workflow.json
@@ -0,0 +1,88 @@
+{
+ "schema_version": 2,
+ "diagram_type": "workflow",
+ "meta": {
+ "title": "Automatic fan-out",
+ "output": "fan-out.html",
+ "quality_profile": "standard"
+ },
+ "lanes": [
+ {
+ "id": "ui",
+ "label": "Processing lane"
+ },
+ {
+ "id": "runtime",
+ "label": "Runtime workers and process management"
+ },
+ {
+ "id": "model",
+ "label": "Model execution workers"
+ },
+ {
+ "id": "tools",
+ "label": "Processing lane"
+ },
+ {
+ "id": "policy",
+ "label": "Processing lane",
+ "variant": "exception"
+ },
+ {
+ "id": "ledger",
+ "label": "Processing lane"
+ }
+ ],
+ "nodes": [
+ {
+ "id": "start",
+ "lane": "runtime",
+ "col": 0,
+ "type": "backend",
+ "label": "Process task",
+ "sublabel": "Details"
+ },
+ {
+ "id": "begin",
+ "lane": "runtime",
+ "col": 1,
+ "type": "backend",
+ "label": "Process task",
+ "sublabel": "Details"
+ },
+ {
+ "id": "llm",
+ "lane": "model",
+ "col": 2,
+ "type": "backend",
+ "label": "Process task",
+ "sublabel": "Prepare the request",
+ "tag": "Process status"
+ },
+ {
+ "id": "messages",
+ "lane": "ledger",
+ "col": 1,
+ "type": "database",
+ "label": "Process task",
+ "sublabel": "Additional process detail"
+ }
+ ],
+ "edges": [
+ {
+ "id": "begin-messages",
+ "from": "begin",
+ "to": "messages",
+ "label": "Transfer data",
+ "variant": "dashed",
+ "role": "branch"
+ },
+ {
+ "id": "begin-llm",
+ "from": "begin",
+ "to": "llm",
+ "label": "Transfer data",
+ "variant": "emphasis"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/test/sequence-column-fit.test.mjs b/test/sequence-column-fit.test.mjs
index 8f94450a..a0ebdfce 100644
--- a/test/sequence-column-fit.test.mjs
+++ b/test/sequence-column-fit.test.mjs
@@ -257,6 +257,50 @@ test('few-participant automatic spread packs below 920px when labels fit', () =>
assert.match(fourHtml, /viewBox="0 0 920 /);
});
+function compactSequence() {
+ return {
+ schema_version: 1, diagram_type: 'sequence',
+ meta: { title: 'Complete timeline', quality_profile: 'showcase' },
+ participants: [{ id: 'client', type: 'external', label: 'Client' }, { id: 'api', type: 'backend', label: 'API' }],
+ messages: [{ id: 'request', from: 'client', to: 'api', y: 200, label: 'ping' }],
+ };
+}
+
+test('compact automatic sequence includes full message and segment label footprints', () => {
+ for (const content of ['message', 'segment']) {
+ const doc = compactSequence();
+ const label = 'POST /api/v1/accounts/{accountId}/transactions/{transactionId}/settlement?include=balance,ledger';
+ if (content === 'message') doc.messages[0].label = label;
+ else doc.segments = [{ from: 160, to: 250, label }];
+ const html = render(doc, true);
+ const width = Number(html.match(/<svg viewBox="0 0 (\d+) /)[1]);
+ assert.ok(width > 560 && width < 920, `${content} should widen only enough to fit, got ${width}`);
+ assert.ok(html.includes(label), 'full authored label remains in the SVG');
+ if (content === 'message') {
+ const boxes = participantBoxes(html);
+ const center = (boxes[0].x + boxes[0].width / 2 + boxes[1].x + boxes[1].width / 2) / 2;
+ const labelWidth = textUnits(label) * 6.6 + 12;
+ assert.ok(center - labelWidth / 2 >= 0 && center + labelWidth / 2 <= width);
+ } else assert.ok(56 + textUnits(label) * 5.2 + 14 <= width - 48);
+ }
+});
+
+test('automatic timeline height includes late content when its legend is empty', () => {
+ for (const legend of [{ mode: 'hidden' }, { entries: { default: { visible: false } } }]) {
+ const doc = compactSequence();
+ doc.meta.legend = legend;
+ doc.messages[0].y = 500;
+ doc.messages[0].note = 'Complete note';
+ doc.activations = [{ participant: 'api', from: 480, to: 530 }];
+ doc.segments = [{ from: 160, to: 540, label: 'Phase' }];
+ const html = render(doc, true);
+ const height = Number(html.match(/<svg viewBox="0 0 \d+ (\d+)"/)[1]);
+ assert.ok(height >= 583 && height < 760, `late content should fit in a compact timeline, got ${height}`);
+ assert.match(html, /Complete note/);
+ assert.match(html, /data-composition-points="[^\"]*,500;/);
+ }
+});
+
test('eight participants fit the automatic 920px canvas with default and explicit spread', () => {
const doc = {
schema_version: 1, diagram_type: 'sequence', meta: { title: 'Eight participants' },
diff --git a/test/sequence-segment-labels.test.mjs b/test/sequence-segment-labels.test.mjs
index ca28622a..5cee661c 100644
--- a/test/sequence-segment-labels.test.mjs
+++ b/test/sequence-segment-labels.test.mjs
@@ -8,23 +8,25 @@ import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const renderer = path.resolve(__dirname, '..', 'archify', 'renderers', 'sequence', 'render-sequence.mjs');
+const cli = path.resolve(__dirname, '..', 'archify', 'bin', 'archify.mjs');
// An unedited first draft with two abutting segments (140-300, 300-520). On
// dev the first label climbed behind the participant headers and the second
// climbed into the first segment, where it named the wrong phase.
const fixture = path.join(__dirname, 'fixtures', 'sequence-first-draft', 'scan-to-pay.sequence.json');
const PARTICIPANT_BOTTOM = 72 + 60;
-function render(diagram) {
+function render(diagram, publicCli = false) {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-sequence-segments-'));
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, html: result.status === 0 ? fs.readFileSync(output, 'utf8') : '' };
+ const args = publicCli ? [cli, 'render', 'sequence', input, output] : [renderer, input, output];
+ const result = spawnSync(process.execPath, args, { cwd: directory, encoding: 'utf8' });
+ return { ...result, input, html: result.status === 0 ? fs.readFileSync(output, 'utf8') : '' };
}
const labels = (html) => [...html.matchAll(/data-segment-id="(\d+)">\s*<rect x="([\d.]+)" y="([\d.-]+)" width="([\d.]+)" height="([\d.]+)"/g)]
- .map((match) => ({ index: +match[1], y: +match[3], height: +match[5] }));
+ .map((match) => ({ index: +match[1], x: +match[2], y: +match[3], width: +match[4], height: +match[5] }));
test('abutting segment labels stay in their own phase and clear of the participant headers', () => {
const diagram = JSON.parse(fs.readFileSync(fixture, 'utf8'));
@@ -89,3 +91,60 @@ test('a segment edge running along a message arrow is reported with the move tha
assert.notEqual(result.status, 0);
assert.match(result.stderr + result.stdout, /Segment "Create" bottom edge at y 298 runs along message "PATCH chunk 1\.\.n" \(arrow at y 300\) — move the edge to at least 304/);
});
+
+test('inside title candidates stay below low participant headers', () => {
+ const diagram = JSON.parse(fs.readFileSync(fixture, 'utf8'));
+ diagram.segments = [{ from: 120, to: 300, label: 'Phase' }];
+ const result = render(diagram);
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ assert.ok(labels(result.html)[0].y >= PARTICIPANT_BOTTOM);
+});
+
+test('inside segment title clears a message note after avoiding participant headers', () => {
+ const diagram = {
+ schema_version: 1, diagram_type: 'sequence',
+ meta: { title: 'Annotated phase', output: 'phase.html', quality_profile: 'showcase', viewBox: [920, 760] },
+ participants: [{ id: 'client', type: 'external', label: 'Client' }, { id: 'api', type: 'backend', label: 'API' }],
+ messages: [{ from: 'client', to: 'api', y: 160, label: 'ping', note: 'diagnostic annotation' }],
+ segments: [{ from: 120, to: 300, label: 'Processing phase title covering the annotation' }],
+ };
+ const result = render(diagram, true);
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ const [title] = labels(result.html);
+ const note = result.html.match(/<text data-detail="fine" x="([\d.]+)" y="([\d.]+)" class="t-dim" font-size="([\d.]+)">diagnostic annotation<\/text>/);
+ assert.ok(note, 'the full authored annotation remains visible');
+ assert.deepEqual(note.slice(1).map(Number), [176, 178, 7], 'note position and font remain authored geometry');
+ assert.ok(title.y >= PARTICIPANT_BOTTOM, 'title clears the participant headers');
+ assert.ok(title.x <= Number(note[1]) && title.x + title.width > Number(note[1]), 'fixture shares horizontal space with the note');
+ const baseline = Number(note[2]);
+ const font = Number(note[3]);
+ assert.ok(title.y + title.height <= baseline - font * 1.2 || title.y >= baseline + font * 0.3,
+ `title at y${title.y}..${title.y + title.height} must clear the annotation around baseline ${baseline}`);
+});
+
+for (const profile of ['standard', 'showcase']) {
+ test(`near-border message preserves ${profile} acceptance policy`, () => {
+ const diagram = {
+ schema_version: 1, diagram_type: 'sequence',
+ meta: { title: 'Phase boundary', output: 'phase.html', quality_profile: profile, viewBox: [920, 760] },
+ participants: [{ id: 'client', type: 'external', label: 'Client' }, { id: 'api', type: 'backend', label: 'API' }],
+ messages: [{ from: 'client', to: 'api', y: 200, label: 'ping' }],
+ segments: [{ from: 140, to: 202, label: 'Phase' }],
+ };
+ const result = render(diagram);
+ if (profile === 'standard') assert.equal(result.status, 0, result.stdout + result.stderr);
+ else {
+ assert.notEqual(result.status, 0);
+ assert.match(result.stdout + result.stderr, /bottom edge at y 202 runs along message "ping"/);
+ const validated = spawnSync(process.execPath, [cli, 'validate', 'sequence', result.input, '--json'], { encoding: 'utf8' });
+ const diagnostic = JSON.parse(validated.stdout).diagnostics.find(entry => entry.code === 'sequence/segment-message-border-run');
+ assert.equal(diagnostic.subject.path, '/segments/0/to');
+ assert.equal(diagnostic.evidence.borderY, 202);
+ assert.equal(diagnostic.evidence.messageY, 200);
+ assert.deepEqual(diagnostic.supportedFixes, [
+ 'set /segments/0/to to at least 204 to leave the message above it',
+ 'set /segments/0/to to at most 196 to leave the message below it',
+ ]);
+ }
+ });
+}
diff --git a/test/workflow-straight-reservation.test.mjs b/test/workflow-straight-reservation.test.mjs
new file mode 100644
index 00000000..962e68ce
--- /dev/null
+++ b/test/workflow-straight-reservation.test.mjs
@@ -0,0 +1,153 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { spawnSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { compileWorkflow } from '../archify/renderers/workflow/workflow-compiler.mjs';
+import { labelPoint } from '../archify/renderers/shared/geometry.mjs';
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const fixture = path.join(root, 'test/fixtures/workflow-first-draft/automatic-fanout.workflow.json');
+const cli = path.join(root, 'archify/bin/archify.mjs');
+const load = () => JSON.parse(fs.readFileSync(fixture, 'utf8'));
+const length = points => points.slice(1).reduce((sum, point, index) => (
+ sum + Math.hypot(point[0] - points[index][0], point[1] - points[index][1])
+), 0);
+const edgeById = (result, id) => result.receipt.edges.find(edge => edge.id === id);
+
+function assertShortFanOut(result) {
+ assert.equal(result.ok, true, JSON.stringify(result.diagnostics));
+ assert.deepEqual(result.receipt.diagnostics, []);
+ const main = edgeById(result, 'begin-llm');
+ const branch = edgeById(result, 'begin-messages');
+ // On the old straight-first path the branch grew to 1494px and displaced
+ // the main edge. Bound the user-visible detour, without choosing its ports
+ // or freezing a better future automatic route to these exact coordinates.
+ assert.ok(length(main.points) <= 200, JSON.stringify(main));
+ assert.ok(length(branch.points) <= 650, JSON.stringify(branch));
+ assert.ok(main.points.length - 2 <= 2);
+ assert.ok(branch.points.length - 2 <= 4);
+}
+
+test('a facing but non-straight automatic branch keeps short collision-free routes in both profiles', () => {
+ for (const qualityProfile of ['standard', 'showcase']) {
+ assertShortFanOut(compileWorkflow({ workflow: load(), qualityProfile }));
+ }
+});
+
+test('public validation and rendered SVG preserve the mixed fan-out without a large detour', t => {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-straight-reservation-'));
+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
+ const run = args => spawnSync(process.execPath, [cli, ...args], {
+ encoding: 'utf8', env: { ...process.env, ARCHIFY_UPDATE_CHECK_DISABLED: '1' },
+ });
+ const validated = run(['validate', 'workflow', fixture, '--quality', 'showcase', '--json']);
+ assert.equal(validated.status, 0, validated.stdout + validated.stderr);
+ const receipt = JSON.parse(validated.stdout);
+ for (const metric of ['properCrossings', 'ambiguousCorridors', 'arrowheadCollisions']) {
+ assert.equal(receipt.composition.metrics[metric], 0, metric);
+ }
+ const output = path.join(directory, 'fan-out.html');
+ const rendered = run(['render', 'workflow', fixture, output, '--quality', 'showcase']);
+ assert.equal(rendered.status, 0, rendered.stdout + rendered.stderr);
+ const html = fs.readFileSync(output, 'utf8');
+ for (const id of ['begin-llm', 'begin-messages']) {
+ const tag = [...html.matchAll(/<path\b[^>]*>/g)].map(match => match[0])
+ .find(value => value.includes(`data-edge-id="${id}"`));
+ assert.ok(tag, id);
+ const points = tag.match(/data-composition-points="([^"]+)"/)[1]
+ .split(';').map(pair => pair.split(',').map(Number));
+ assert.ok(length(points) <= (id === 'begin-llm' ? 200 : 650), id);
+ }
+});
+
+test('an already valid same-style fan-out keeps short routes rather than moving to an outer corridor', () => {
+ const workflow = load();
+ workflow.edges[0].variant = 'emphasis';
+ delete workflow.edges[0].role;
+ assertShortFanOut(compileWorkflow({ workflow, qualityProfile: 'showcase' }));
+});
+
+test('straight reservation preserves input content and deterministic node geometry', () => {
+ const workflow = load();
+ const before = JSON.stringify(workflow);
+ const first = compileWorkflow({ workflow, qualityProfile: 'showcase' });
+ const reordered = structuredClone(workflow);
+ reordered.nodes.reverse();
+ reordered.edges.reverse();
+ const second = compileWorkflow({ workflow: reordered, qualityProfile: 'showcase' });
+ assert.equal(JSON.stringify(workflow), before);
+ assert.deepEqual(second, first);
+ assert.equal(first.receipt.nodes.length, workflow.nodes.length);
+ assert.equal(first.receipt.edges.length, workflow.edges.length);
+});
+
+test('explicit canvas, node dimensions, endpoint sides and absolute waypoints stay authoritative', () => {
+ const workflow = load();
+ workflow.meta.viewBox = [1024, 1000];
+ workflow.nodes.forEach(node => { node.width = node.id === 'messages' ? 128 : 92; });
+ Object.assign(workflow.edges[0], {
+ fromSide: 'right', toSide: 'top', via: [[276, 246], [276, 483], [214, 483]],
+ });
+ const before = JSON.stringify(workflow);
+ const result = compileWorkflow({ workflow, qualityProfile: 'standard' });
+ assert.equal(result.ok, true, JSON.stringify(result.diagnostics));
+ assert.deepEqual(result.receipt.diagnostics, []);
+ assert.equal(JSON.stringify(workflow), before);
+ assert.deepEqual(result.receipt.viewBox, workflow.meta.viewBox);
+ for (const node of workflow.nodes) {
+ assert.equal(result.receipt.nodes.find(entry => entry.id === node.id).width, node.width);
+ }
+ const edge = edgeById(result, 'begin-messages');
+ assert.deepEqual(edge.points.slice(1, -1), workflow.edges[0].via);
+ const source = result.receipt.nodes.find(node => node.id === 'begin');
+ const target = result.receipt.nodes.find(node => node.id === 'messages');
+ assert.equal(edge.points[0][0], source.x + source.width);
+ assert.equal(edge.points.at(-1)[1], target.y);
+ // The neighbour may slide its own port to distinguish its stroke from the
+ // pinned branch. It must leave the authored route and all boxes untouched.
+ const showcase = compileWorkflow({ workflow, qualityProfile: 'showcase' });
+ assert.equal(showcase.ok, true, JSON.stringify(showcase.diagnostics));
+ assert.deepEqual(showcase.receipt.diagnostics, []);
+ assert.deepEqual(showcase.receipt.nodes, result.receipt.nodes);
+ assert.deepEqual(showcase.receipt.viewBox, workflow.meta.viewBox);
+ assert.deepEqual(edgeById(showcase, 'begin-messages').points, edge.points);
+ const main = edgeById(showcase, 'begin-llm');
+ assert.ok(length(main.points) <= 200, JSON.stringify(main));
+ assert.notDeepEqual(main.points[0], edge.points[0]);
+});
+
+test('endpoint clearance repair does not move the neighbours authored endpoint-side controls', () => {
+ const workflow = load();
+ workflow.meta.viewBox = [1024, 1000];
+ workflow.nodes.forEach(node => { node.width = node.id === 'messages' ? 128 : 92; });
+ Object.assign(workflow.edges[0], {
+ fromSide: 'right', toSide: 'top', via: [[276, 246], [276, 483], [214, 483]],
+ });
+ // With both source sides pinned, the collision remains actionable; a
+ // successful repair must never be obtained by silently sliding either pin.
+ workflow.edges[1].fromSide = 'right';
+ const result = compileWorkflow({ workflow, qualityProfile: 'standard' });
+ assert.equal(result.ok, true, JSON.stringify(result.diagnostics));
+ assert.ok(result.receipt.diagnostics.some(diagnostic => diagnostic.code === 'composition/ambiguous-corridor'));
+ const branch = edgeById(result, 'begin-messages');
+ assert.deepEqual(branch.points.slice(1, -1), workflow.edges[0].via);
+ const source = result.receipt.nodes.find(node => node.id === 'begin');
+ const main = edgeById(result, 'begin-llm');
+ assert.equal(main.points[0][0], source.x + source.width);
+ assert.deepEqual(main.points[0], branch.points[0]);
+});
+
+test('authored zero-valued relative label controls retain their source segment anchor', () => {
+ const workflow = load();
+ Object.assign(workflow.edges[0], { labelDx: 0, labelDy: 0, labelSegment: 0 });
+ const before = JSON.stringify(workflow);
+ const result = compileWorkflow({ workflow, qualityProfile: 'standard' });
+ assert.equal(result.ok, true, JSON.stringify(result.diagnostics));
+ assert.equal(JSON.stringify(workflow), before);
+ const edge = edgeById(result, 'begin-messages');
+ const label = result.receipt.labels.find(entry => entry.edge === 'begin-messages');
+ assert.deepEqual([label.x, label.y], labelPoint(workflow.edges[0], edge.points));
+});