Skip to content

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

feat(routing): hold automatic routes to the composition floors before the gate

tt-a1i7b5b71c78f9e
diff --git a/archify.zip b/archify.zip
index 8b7f9cbd..a0c86519 100644
Binary files a/archify.zip and b/archify.zip differ
diff --git a/archify/renderers/architecture/labels.mjs b/archify/renderers/architecture/labels.mjs
index 445c7a67..bdc3547c 100644
--- a/archify/renderers/architecture/labels.mjs
+++ b/archify/renderers/architecture/labels.mjs
@@ -2,7 +2,9 @@ import { normalizeRoutePoints, rectsOverlap, segmentRectClearance } from '../sha
// A bounded fallback for an unpinned label whose usual position collides.
// It never routes an edge, moves a node, expands the canvas, or rewrites input.
-export function placeAutomaticLabels({ labels, routes, components, titles, viewBox, placementBottom = viewBox[1] }) {
+export function placeAutomaticLabels({
+ labels, routes, components, titles, viewBox, placementBottom = viewBox[1], fallbackRing = true,
+}) {
const placed = [...labels];
const obstacles = [...components, ...titles];
const segments = routes.flatMap(({ relationIndex, points }) => {
@@ -68,7 +70,7 @@ export function placeAutomaticLabels({ labels, routes, components, titles, viewB
break;
}
}
- if (placed[index] !== label) continue;
+ if (placed[index] !== label || !fallbackRing) continue;
// Dense but valid topologies can leave every point directly beside the
// relationship occupied by another route. Search a small deterministic
@@ -100,3 +102,22 @@ export function placeAutomaticLabels({ labels, routes, components, titles, viewB
}
return placed;
}
+
+// The rect a single unpinned label would occupy given only its own route and
+// the nodes: what the planner reserves before the remaining routes are laid.
+// Only a placement beside the route itself is worth reserving; a label that
+// would already need the fallback ring is left to the final placement pass.
+export function reservedLabelRect({
+ label, points, routes = [], labels = [], components, viewBox = [Infinity, Infinity], placementBottom = Infinity,
+}) {
+ const [rect] = placeAutomaticLabels({
+ labels: [{ ...label, relationIndex: -1 }, ...labels.map(other => ({ ...other, relationIndex: -2 }))],
+ routes: [{ relationIndex: -1, points }, ...routes],
+ components,
+ titles: [],
+ viewBox,
+ placementBottom,
+ fallbackRing: false,
+ });
+ return components.some(component => rectsOverlap(rect, component, -2)) ? null : rect;
+}
diff --git a/archify/renderers/architecture/render-architecture.mjs b/archify/renderers/architecture/render-architecture.mjs
index 69eb62dc..8487aa66 100644
--- a/archify/renderers/architecture/render-architecture.mjs
+++ b/archify/renderers/architecture/render-architecture.mjs
@@ -11,7 +11,7 @@ import { minimumReadableSourceTextPx } from '../shared/desktop-readability.mjs';
import { translateMessage as i18nText } from '../shared/i18n.mjs';
import { gridLayout, resolveComponentPos, validateGridPlacement } from './grid.mjs';
import { createRouter } from './routing.mjs';
-import { placeAutomaticLabels } from './labels.mjs';
+import { placeAutomaticLabels, reservedLabelRect } from './labels.mjs';
import { cleanRouteDetourProblems } from '../shared/route-quality.mjs';
import {
asArray,
@@ -149,7 +149,10 @@ const architectureLegendEntries = resolveLegend(
const resolvedLabelPoints = new Map();
function connectionLabelBox(conn) {
if (!conn.label) return null;
- const [lx, ly] = resolvedLabelPoints.get(conn) || labelPoint(conn, pathFor(conn).points);
+ return connectionLabelBoxAt(conn, resolvedLabelPoints.get(conn) || labelPoint(conn, pathFor(conn).points));
+}
+
+function connectionLabelBoxAt(conn, [lx, ly]) {
const width = Math.max(30, textUnits(conn.label) * 4.8 + 10);
return { x: lx - width / 2, y: ly - 10, width, height: 14, lx, ly };
}
@@ -300,8 +303,23 @@ function layoutBoundaryTitles(rawBoundaries, minimumFontSize) {
// part of the derived canvas, so the title convergence must measure the same
// width the diagram actually renders into (a title sized for a narrower canvas
// would fall below the desktop-readability floor once labels grow it). Routing
-// reads only components and connections, never boundaries or the viewBox.
-const { pathFor, connectionSides, connectionEndpointSide } = createRouter(components, arch.connections);
+// reads components, connections and the member-derived boundary frames (so an
+// automatic route never borrows a frame border as its corridor), never the
+// title-expanded frames or the viewBox.
+const rawBoundaries = asArray(arch.boundaries).map(boundaryRect).filter(Boolean);
+const { pathFor, connectionSides, connectionEndpointSide } = createRouter(components, arch.connections, {
+ frames: rawBoundaries.map((boundary) => ({
+ ...boundary,
+ radius: boundary.kind === 'security-group' ? 8 : 12,
+ })),
+ labelRectFor: (conn, points, { routes, labels }) => (conn.label ? reservedLabelRect({
+ label: { relation: conn, label: conn.label, ...connectionLabelBoxAt(conn, labelPoint(conn, points)) },
+ points,
+ routes: routes.map((route, index) => ({ relationIndex: index, points: route })),
+ labels,
+ components: [...components.values()],
+ }) : null),
+});
function hasAutomaticRouteGeometry(connection) {
return !Array.isArray(connection?.via)
&& (!connection?.route || connection.route === 'auto')
@@ -320,7 +338,6 @@ const connectionGeometry = [
.flatMap((conn) => pathFor(conn).points.map(([x, y]) => ({ x, y, width: 0, height: 0 }))),
];
-const rawBoundaries = asArray(arch.boundaries).map(boundaryRect).filter(Boolean);
function resolveBoundaryTitles() {
if (!enforcesBoundaryTitleComposition || rawBoundaries.length === 0) {
return {
@@ -612,7 +629,20 @@ function validateArchitecture() {
}
const [start, end] = [routed.points[0], routed.points[routed.points.length - 1]];
const distance = Math.hypot(end[0] - start[0], end[1] - start[1]);
- if (distance < 24) problems.push(`Connection "${conn.label || `${conn.from}->${conn.to}`}" is too short (${Math.round(distance)}px; minimum 24px) — place its components farther apart.`);
+ if (distance < 24 && conn.from === conn.to) {
+ // "Move the components apart" cannot be executed for a self-loop; the
+ // ports sit on one component and the sides decide how far apart.
+ const message = `Self-loop "${conn.id || conn.label || conn.from}" on component "${conn.from}" has its two ports only ${Math.round(distance)}px apart (minimum 24px) — remove fromSide/toSide so the renderer can choose the loop's sides, or set fromSide and toSide to different sides.`;
+ diagnostics.push({
+ code: 'layout/self-loop-ports', severity: 'error', message,
+ subject: { diagramType: 'architecture', collection: 'connections', index: asArray(arch.connections).indexOf(conn), ...(conn.id ? { id: conn.id } : {}), from: conn.from, to: conn.to },
+ evidence: { distancePx: Math.round(distance), minimumPx: 24, fromSide: connectionEndpointSide(conn, 'source'), toSide: connectionEndpointSide(conn, 'target'), points: routed.points },
+ supportedFixes: ['remove fromSide/toSide from the self-loop', 'set fromSide and toSide to different sides of the component'],
+ });
+ problems.push(message);
+ } else if (distance < 24) {
+ problems.push(`Connection "${conn.label || `${conn.from}->${conn.to}`}" is too short (${Math.round(distance)}px; minimum 24px) — place its components farther apart.`);
+ }
}
}
diff --git a/archify/renderers/architecture/routing.mjs b/archify/renderers/architecture/routing.mjs
index 398c1bc4..9d030b57 100644
--- a/archify/renderers/architecture/routing.mjs
+++ b/archify/renderers/architecture/routing.mjs
@@ -14,6 +14,9 @@ import {
routeHonorsEndpointSides,
normalizeRoutePoints,
roundedPath,
+ collectBorderRuns,
+ collectRouteRhythmIssues,
+ frameBorderSegments,
} from '../shared/geometry.mjs';
import { shortestOrthogonalGridRoute } from '../shared/route-quality.mjs';
@@ -22,8 +25,63 @@ import { shortestOrthogonalGridRoute } from '../shared/route-quality.mjs';
*
* @param {Map<string, {x,y,width,height,cx,cy}>} components measured boxes by id
* @param {Array<object>} connections the connection list to spread ports across
+ * @param {object} [options]
+ * @param {Array<{x,y,width,height,radius?}>} [options.frames] structural frames
+ * (boundaries) whose borders an automatic route may cross but never follow
+ * @param {number} [options.interiorSegmentPx] showcase floor for interior segments
+ * @param {number} [options.microSegmentPx] floor for any segment
+ * @param {(conn: object, points: number[][], context: {routes: number[][][], labels: object[]}) => object|null} [options.labelRectFor]
+ * default label rect of a routed relationship given the routes and label
+ * rects resolved so far; later automatic routes keep clear of it so a dense
+ * fan-out does not leave the label nowhere to go
*/
-export function createRouter(components, connections) {
+export function createRouter(components, connections, {
+ frames = [],
+ interiorSegmentPx = 16,
+ microSegmentPx = 8,
+ labelRectFor = null,
+} = {}) {
+ const frameBorders = frames.flatMap((frame) => frameBorderSegments(frame));
+ const LABEL_CLEARANCE = 4;
+ // Labels of already-routed relationships, reserved while planning the rest.
+ let reservedLabels = [];
+ let honourReservedLabels = true;
+
+ function routeClearsReservedLabels(conn, points) {
+ if (!honourReservedLabels) return true;
+ for (const entry of reservedLabels) {
+ if (entry.conn === conn) continue;
+ for (let index = 0; index < points.length - 1; index += 1) {
+ if (segmentIntersectsRect({ start: points[index], end: points[index + 1] }, entry.rect, LABEL_CLEARANCE)) {
+ return false;
+ }
+ }
+ }
+ return true;
+ }
+
+ // The grid search adds its own 2px component clearance; pre-expand so a
+ // reserved label keeps the same 4px clearance the placement pass demands.
+ function reservedLabelObstacles(gridClearance) {
+ if (!honourReservedLabels) return [];
+ const grow = LABEL_CLEARANCE - gridClearance;
+ return reservedLabels.map(({ rect }) => ({
+ x: rect.x - grow,
+ y: rect.y - grow,
+ width: rect.width + grow * 2,
+ height: rect.height + grow * 2,
+ }));
+ }
+
+ // Automatic routes are held to the same composition floors the showcase
+ // gate enforces afterwards. Accepting a route here that the gate rejects
+ // only hands the author a hand-routing repair the planner could have made.
+ function routeMeetsCompositionFloors(points) {
+ if (collectRouteRhythmIssues({ routedRelations: [{ points }], interiorSegmentPx, microSegmentPx }).length) {
+ return false;
+ }
+ return !frames.length || collectBorderRuns({ routedRelations: [{ points }], frames }).length === 0;
+ }
const planningMetrics = {
routeCount: 0,
explicitRouteCount: 0,
@@ -53,7 +111,7 @@ export function createRouter(components, connections) {
}
}
}
- return true;
+ return routeClearsReservedLabels(conn, points);
}
function routeClearsEndpointComponents(points, from, to) {
@@ -338,6 +396,7 @@ export function createRouter(components, connections) {
if (routeHonorsEndpointSides(direct, fromSide, toSide)
&& routeClearsEndpointComponents(direct, from, to)
&& routeClearsComponents(conn, direct)
+ && routeMeetsCompositionFloors(direct)
&& !routeConflictsWithResolved(conn, direct, resolvedRoutes)) return [];
}
@@ -345,6 +404,7 @@ export function createRouter(components, connections) {
accept: (points) => (
routeClearsEndpointComponents(points, from, to)
&& routeClearsComponents(conn, points)
+ && routeMeetsCompositionFloors(points)
&& !routeConflictsWithResolved(conn, points, resolvedRoutes)
),
});
@@ -367,6 +427,7 @@ export function createRouter(components, connections) {
const points = [start, ...candidate, end];
if (routeHonorsEndpointSides(points, fromSide, toSide)
&& routeClearsComponents(conn, points)
+ && routeMeetsCompositionFloors(points)
&& !routeConflictsWithResolved(conn, points, resolvedRoutes)) return candidate;
}
}
@@ -383,6 +444,7 @@ export function createRouter(components, connections) {
const points = [start, ...candidate, end];
if (routeHonorsEndpointSides(points, fromSide, toSide)
&& routeClearsComponents(conn, points)
+ && routeMeetsCompositionFloors(points)
&& !routeConflictsWithResolved(conn, points, resolvedRoutes)) return candidate;
}
}
@@ -412,6 +474,7 @@ export function createRouter(components, connections) {
const points = [start, ...candidate, end];
if (routeClearsEndpointComponents(points, from, to)
&& routeClearsComponents(conn, points)
+ && routeMeetsCompositionFloors(points)
&& !routeConflictsWithResolved(conn, points, resolvedRoutes)) return candidate;
}
@@ -440,7 +503,7 @@ export function createRouter(components, connections) {
start,
end,
points: [start, end],
- obstacles: [...components.values()],
+ obstacles: [...components.values(), ...reservedLabelObstacles(2)],
fromSide,
toSide,
clearance: 2,
@@ -450,6 +513,9 @@ export function createRouter(components, connections) {
avoidedSegments,
minimumAvoidedOverlapPx: 8,
routeSeparationPx: 8,
+ minimumSegmentPx: interiorSegmentPx,
+ borderSegments: frameBorders,
+ bendPenaltyPx: 48,
metrics: gridMetrics,
});
planningMetrics.gridCandidateNodeCount += gridMetrics.candidateNodeCount || 0;
@@ -464,8 +530,9 @@ export function createRouter(components, connections) {
? !routeConflictsWithResolved(conn, searched.points, resolvedRoutes) : false;
const clearsSharedCorridors = searched
? !routeOverlapsResolved(conn, searched.points, resolvedRoutes) : false;
+ const meetsFloors = searched ? routeMeetsCompositionFloors(searched.points) : false;
const accepted = Boolean(
- searched && clearsEndpoints && clearsComponents && clearsSharedCorridors,
+ searched && clearsEndpoints && clearsComponents && clearsSharedCorridors && meetsFloors,
);
planningMetrics.gridAttempts.push({
relationship: conn.id || `${conn.from}->${conn.to}`,
@@ -479,6 +546,7 @@ export function createRouter(components, connections) {
...(!clearsEndpoints ? ['endpoint-components'] : []),
...(!clearsComponents ? ['components'] : []),
...(!clearsSharedCorridors ? ['shared-corridor'] : []),
+ ...(!meetsFloors ? ['composition-floors'] : []),
],
candidatePoints: searched.points,
} : {}),
@@ -612,6 +680,7 @@ export function createRouter(components, connections) {
&& routeHonorsEndpointSides(routed.points, geometry.fromSide, geometry.toSide)
&& routeClearsEndpointComponents(routed.points, geometry.from, geometry.to)
&& routeClearsComponents(conn, routed.points)
+ && routeMeetsCompositionFloors(routed.points)
&& !routeOverlapsResolved(conn, routed.points, resolvedRoutes);
}
@@ -626,14 +695,38 @@ export function createRouter(components, connections) {
}
let firstFallback = null;
- for (const sides of candidateSidePairs(conn)) {
- const geometry = connectionGeometry(conn, sides);
- const routed = routedForGeometry(conn, resolvedRoutes, geometry);
- if (!firstFallback) firstFallback = { routed, sides };
- if (routeIsClear(conn, routed, geometry, resolvedRoutes)) {
- return cachePath(conn, routed, sides);
+ const clearRoute = () => {
+ for (const sides of candidateSidePairs(conn)) {
+ const geometry = connectionGeometry(conn, sides);
+ const routed = routedForGeometry(conn, resolvedRoutes, geometry);
+ if (!firstFallback) firstFallback = { routed, sides };
+ if (routeIsClear(conn, routed, geometry, resolvedRoutes)) return { routed, sides };
}
+ return null;
+ };
+ const routeLength = ({ routed }) => routed.points.slice(1)
+ .reduce((total, point, index) => total + Math.abs(point[0] - routed.points[index][0]) + Math.abs(point[1] - routed.points[index][1]), 0);
+
+ // Reserved labels are a preference, not an obstacle. A route that has no
+ // corridor around them, or that would have to detour far around them,
+ // takes the plain route instead and the label placement pass moves the
+ // label; only a modest extra length is worth keeping a label in place.
+ honourReservedLabels = true;
+ let chosen = clearRoute();
+ if (reservedLabels.length) {
+ honourReservedLabels = false;
+ if (!chosen) chosen = clearRoute();
+ else {
+ const direct = Math.abs(chosen.routed.points.at(-1)[0] - chosen.routed.points[0][0])
+ + Math.abs(chosen.routed.points.at(-1)[1] - chosen.routed.points[0][1]);
+ if (routeLength(chosen) > direct * 1.25 + 64) {
+ const plain = clearRoute();
+ if (plain && routeLength(plain) * 1.25 + 64 < routeLength(chosen)) chosen = plain;
+ }
+ }
+ honourReservedLabels = true;
}
+ if (chosen) return cachePath(conn, chosen.routed, chosen.sides);
return cachePath(conn, firstFallback.routed, firstFallback.sides);
}
@@ -657,9 +750,15 @@ export function createRouter(components, connections) {
return leftDistance - rightDistance || left.index - right.index;
});
const resolvedRoutes = [];
+ reservedLabels = [];
for (const { conn } of [...explicit, ...automatic]) {
const routed = computePath(conn, resolvedRoutes);
resolvedRoutes.push({ conn, points: routed.points });
+ const rect = labelRectFor?.(conn, routed.points, {
+ routes: resolvedRoutes.map((entry) => entry.points),
+ labels: reservedLabels.map((entry) => entry.rect),
+ });
+ if (rect) reservedLabels.push({ conn, rect });
}
planningMetrics.routeCount = resolvedRoutes.length;
planningMetrics.explicitRouteCount = explicit.length;
diff --git a/archify/renderers/lifecycle/render-lifecycle.mjs b/archify/renderers/lifecycle/render-lifecycle.mjs
index 9d830c67..7cbc63fb 100644
--- a/archify/renderers/lifecycle/render-lifecycle.mjs
+++ b/archify/renderers/lifecycle/render-lifecycle.mjs
@@ -4,7 +4,7 @@ import { esc, renderDefinitions, renderSemanticSigil, textUnits } from '../share
import { animateAttr, focusEdgeAttrs, focusNodeAttrs, focusNodeTitle, loadDiagramWithBrandMarks, writeDiagram, svgAccessibleText, svgRootAttrs } from '../shared/cli.mjs';
import { throwDiagnosticProblems } from '../shared/diagnostics.mjs';
import { createRouter } from '../architecture/routing.mjs';
-import { placeAutomaticLabels } from '../architecture/labels.mjs';
+import { placeAutomaticLabels, reservedLabelRect } from '../architecture/labels.mjs';
import { resolveLegend, renderLegend as renderResolvedLegend } from '../shared/legend.mjs';
import { availableNodeTextWidth, fittedNodeFontSize, minimumNodeTextWidth, nodeLabelLayout } from '../shared/text-fit.mjs';
import { brandLabelFitWidth, brandMarkFor, brandMetadataFor, brandTopRailProblem, renderBrandMark } from '../shared/brand-marks.mjs';
@@ -388,7 +388,17 @@ function plannerRouted(transition) {
}
const plannedTransitions = asArray(lifecycle.transitions).filter(plannerRouted);
-const planner = createRouter(states, plannedTransitions);
+const planner = createRouter(states, plannedTransitions, {
+ labelRectFor: (transition, points, { routes, labels }) => (transition.label ? reservedLabelRect({
+ label: { relation: transition, label: transition.label, ...transitionLabelBoxAt(transition, labelPoint(transition, points)) },
+ points,
+ routes: routes.map((route, index) => ({ relationIndex: index, points: route })),
+ labels,
+ components: [...states.values()],
+ viewBox,
+ placementBottom: lifecycleAreaBottom(),
+ }) : null),
+});
function transitionSides(transition) {
if (plannerRouted(transition)) return planner.connectionSides(transition);
@@ -436,7 +446,13 @@ function pathFor(transition) {
const resolvedLabelPoints = new Map();
function transitionLabelBox(transition) {
- const [lx, ly] = resolvedLabelPoints.get(transition) || labelPoint(transition, pathFor(transition).points);
+ return transitionLabelBoxAt(
+ transition,
+ resolvedLabelPoints.get(transition) || labelPoint(transition, pathFor(transition).points),
+ );
+}
+
+function transitionLabelBoxAt(transition, [lx, ly]) {
const longestLine = Math.max(textUnits(transition.label), textUnits(transition.note || ''));
const width = Math.max(32, longestLine * 4.9 + 12);
const height = transition.note ? 27 : 16;
diff --git a/archify/renderers/shared/geometry.mjs b/archify/renderers/shared/geometry.mjs
index b4fc9677..b0e87930 100644
--- a/archify/renderers/shared/geometry.mjs
+++ b/archify/renderers/shared/geometry.mjs
@@ -1189,7 +1189,7 @@ function collinearForward(a, b, c) {
return (b[0] - a[0]) * (c[0] - b[0]) + (b[1] - a[1]) * (c[1] - b[1]) >= -0.0001;
}
-function frameBorderSegments(frame) {
+export function frameBorderSegments(frame) {
if (!frame || typeof frame !== 'object') return [];
if (frame.shape === 'line') {
const start = frame.start || [frame.x1, frame.y1];
diff --git a/archify/renderers/shared/route-quality.mjs b/archify/renderers/shared/route-quality.mjs
index 5ae761ca..ca84537b 100644
--- a/archify/renderers/shared/route-quality.mjs
+++ b/archify/renderers/shared/route-quality.mjs
@@ -251,6 +251,8 @@ export function shortestOrthogonalGridRoute({
minimumAvoidedOverlapPx = 8,
routeSeparationPx = 8,
minimumSegmentPx = 8,
+ borderSegments = [],
+ bendPenaltyPx = 0,
metrics,
}) {
writeGridMetrics(metrics, {
@@ -280,6 +282,10 @@ export function shortestOrthogonalGridRoute({
.map((rect) => expandedRect(rect, clearance));
const relevantAvoidedSegments = [...avoidedSegments]
.filter((segment) => segment?.start && segment?.end);
+ // Frame borders may be crossed perpendicularly but never borrowed as a
+ // corridor: the composition gate rejects any collinear run along them.
+ const relevantBorderSegments = [...borderSegments]
+ .filter((segment) => segment?.start && segment?.end);
writeGridMetrics(metrics, {
obstacleCount: expanded.length,
avoidedSegmentCount: relevantAvoidedSegments.length,
@@ -312,6 +318,16 @@ export function shortestOrthogonalGridRoute({
ys.add(segmentStart[1] + routeSeparationPx);
}
}
+ for (const segment of relevantBorderSegments) {
+ if (Math.abs(segment.start[0] - segment.end[0]) <= 0.0001) {
+ xs.add(segment.start[0] - routeSeparationPx);
+ xs.add(segment.start[0] + routeSeparationPx);
+ }
+ if (Math.abs(segment.start[1] - segment.end[1]) <= 0.0001) {
+ ys.add(segment.start[1] - routeSeparationPx);
+ ys.add(segment.start[1] + routeSeparationPx);
+ }
+ }
// Grid lines closer than a readable segment would let the search emit a
// micro jog between two obstacle edges; keep the endpoint stubs and coalesce
// the rest so every turn the route can take is at least one segment long.
@@ -347,7 +363,7 @@ export function shortestOrthogonalGridRoute({
const adjacency = new Map([...nodes.keys()].map((key) => [key, []]));
let graphEdgeCount = 0;
- const connectLine = (line) => {
+ const connectLine = (line, axis) => {
for (let index = 0; index < line.length - 1; index += 1) {
const left = line[index];
const right = line[index + 1];
@@ -358,53 +374,80 @@ export function shortestOrthogonalGridRoute({
relevantAvoidedSegments,
minimumAvoidedOverlapPx,
)) continue;
+ if (relevantBorderSegments.some((segment) => (
+ collinearOverlap(left, right, segment.start, segment.end) > 0.0001
+ ))) continue;
const distance = Math.abs(right[0] - left[0]) + Math.abs(right[1] - left[1]);
const leftKey = pointKey(left);
const rightKey = pointKey(right);
- adjacency.get(leftKey).push([rightKey, distance]);
- adjacency.get(rightKey).push([leftKey, distance]);
+ adjacency.get(leftKey).push([rightKey, distance, axis === 'h' ? 'R' : 'D']);
+ adjacency.get(rightKey).push([leftKey, distance, axis === 'h' ? 'L' : 'U']);
graphEdgeCount += 1;
}
};
for (const y of orderedY) {
- connectLine(orderedX.map((x) => nodes.get(pointKey([x, y]))).filter(Boolean));
+ connectLine(orderedX.map((x) => nodes.get(pointKey([x, y]))).filter(Boolean), 'h');
}
for (const x of orderedX) {
- connectLine(orderedY.map((y) => nodes.get(pointKey([x, y]))).filter(Boolean));
+ connectLine(orderedY.map((y) => nodes.get(pointKey([x, y]))).filter(Boolean), 'v');
}
writeGridMetrics(metrics, { graphEdgeCount });
+ // The search state carries the incoming direction so a turn can cost extra
+ // and a reversal is never taken: the pure shortest path hugs every obstacle
+ // corner with a staircase of short jogs, while a bend-penalised one takes
+ // the same corridor in a few long strokes. The first stub already leaves
+ // the endpoint along its side and the last one arrives along the end side.
+ const directionOf = ([dx, dy]) => (dx > 0 ? 'R' : dx < 0 ? 'L' : dy > 0 ? 'D' : 'U');
+ const opposite = { R: 'L', L: 'R', D: 'U', U: 'D' };
+ const stateKey = (key, direction) => `${key}|${direction}`;
+ const sourceAxis = directionOf(OUTWARD[fromSide]);
+ const targetAxis = opposite[directionOf(OUTWARD[toSide])];
const source = pointKey(startStub);
const target = pointKey(endStub);
- const distances = new Map([[source, 0]]);
+ const sourceState = stateKey(source, sourceAxis);
+ const distances = new Map([[sourceState, 0]]);
const previous = new Map();
const queue = new MinHeap();
- queue.push(source, 0);
+ queue.push(sourceState, 0);
let visitedNodeCount = 0;
+ let targetState = null;
while (queue.entries.length) {
const next = queue.pop();
const current = next.key;
const currentDistance = next.distance;
if (currentDistance !== distances.get(current)) continue;
visitedNodeCount += 1;
- if (current === target) break;
- for (const [neighbor, weight] of adjacency.get(current) || []) {
- const candidate = currentDistance + weight;
- if (candidate >= (distances.get(neighbor) ?? Infinity)) continue;
- distances.set(neighbor, candidate);
- previous.set(neighbor, current);
- queue.push(neighbor, candidate);
+ const [currentNode, currentAxis] = current.split('|');
+ if (currentNode === target) {
+ // Arriving on the wrong axis costs one final turn onto the end stub.
+ const arrival = currentDistance + (currentAxis === targetAxis ? 0 : bendPenaltyPx);
+ if (targetState == null || arrival < targetState.distance) {
+ targetState = { key: current, distance: arrival };
+ }
+ if (currentAxis === targetAxis || bendPenaltyPx === 0) break;
+ continue;
+ }
+ if (targetState && currentDistance >= targetState.distance) break;
+ for (const [neighbor, weight, axis] of adjacency.get(currentNode) || []) {
+ if (axis === opposite[currentAxis]) continue;
+ const candidate = currentDistance + weight + (axis === currentAxis ? 0 : bendPenaltyPx);
+ const neighborState = stateKey(neighbor, axis);
+ if (candidate >= (distances.get(neighborState) ?? Infinity)) continue;
+ distances.set(neighborState, candidate);
+ previous.set(neighborState, current);
+ queue.push(neighborState, candidate);
}
}
writeGridMetrics(metrics, { visitedNodeCount });
- if (!distances.has(target)) {
+ if (!targetState) {
writeGridMetrics(metrics, { status: 'no-route' });
return null;
}
const reversed = [];
- for (let key = target; key; key = previous.get(key)) {
- reversed.push(nodes.get(key));
- if (key === source) break;
+ for (let key = targetState.key; key; key = previous.get(key)) {
+ reversed.push(nodes.get(key.split('|')[0]));
+ if (key === sourceState) break;
}
if (pointKey(reversed.at(-1)) !== source) {
writeGridMetrics(metrics, { status: 'broken-predecessor-chain' });
diff --git a/archify/test/architecture-first-draft.test.mjs b/archify/test/architecture-first-draft.test.mjs
new file mode 100644
index 00000000..6cf0c32a
--- /dev/null
+++ b/archify/test/architecture-first-draft.test.mjs
@@ -0,0 +1,77 @@
+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';
+
+const skillRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const cli = path.join(skillRoot, 'bin/archify.mjs');
+const fixtures = path.join(skillRoot, 'test/fixtures/architecture-first-draft');
+
+function validate(type, input, ...extra) {
+ const result = spawnSync(process.execPath, [cli, 'validate', type, input, '--quality', 'showcase', '--json', ...extra], { encoding: 'utf8' });
+ return { status: result.status, receipt: JSON.parse(result.stdout) };
+}
+
+function layout(input) {
+ const result = spawnSync(process.execPath, [cli, 'validate', 'architecture', input, '--quality', 'showcase', '--layout-json'], { encoding: 'utf8' });
+ return JSON.parse(result.stdout);
+}
+
+// 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.
+for (const name of ['audit-luna', 'audit-terra', 'queue-sol']) {
+ test(`architecture: first draft ${name} validates for showcase without route controls`, () => {
+ 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);
+ });
+}
+
+test('architecture: the planner keeps a long automatic route to a few strokes instead of an obstacle-hugging staircase', () => {
+ const { connections } = layout(path.join(fixtures, 'audit-luna.architecture.json'));
+ const route = connections.find((conn) => conn.from === 'policy' && conn.to === 'review');
+ assert.ok(route, 'policy -> review is routed');
+ assert.ok(route.points.length <= 5, `expected at most 4 bends, got ${JSON.stringify(route.points)}`);
+});
+
+test('architecture: an automatic route beside a boundary keeps off the frame border', () => {
+ const { connections, boundaries } = layout(path.join(fixtures, 'queue-sol.architecture.json'));
+ const route = connections.find((conn) => conn.from === 'worker' && conn.to === 'dead-letter');
+ const frame = boundaries.find((boundary) => boundary.wraps.includes('worker'));
+ const right = frame.x + frame.width;
+ for (const [x] of route.points.slice(1, -1)) assert.notEqual(Math.round(x), Math.round(right));
+});
+
+test('architecture: a self-loop with cramped explicit sides names the loop and the executable fix', () => {
+ const input = path.join(fixtures, 'queue-luna.architecture.json');
+ const { status, receipt } = validate('architecture', input);
+ assert.equal(status, 1);
+ const issue = receipt.diagnostics.find((entry) => entry.code === 'layout/self-loop-ports');
+ assert.ok(issue, JSON.stringify(receipt.diagnostics, null, 2));
+ assert.equal(issue.subject.id, 'retry');
+ assert.match(issue.message, /remove fromSide\/toSide/);
+ assert.doesNotMatch(issue.message, /farther apart/);
+
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-self-loop-'));
+ try {
+ const candidate = JSON.parse(fs.readFileSync(input, 'utf8'));
+ for (const conn of candidate.connections) {
+ if (conn.from === conn.to) {
+ delete conn.fromSide;
+ delete conn.toSide;
+ }
+ }
+ 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));
+ } finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+});
diff --git a/archify/test/fixtures/architecture-first-draft/audit-luna.architecture.json b/archify/test/fixtures/architecture-first-draft/audit-luna.architecture.json
new file mode 100644
index 00000000..16d1e261
--- /dev/null
+++ b/archify/test/fixtures/architecture-first-draft/audit-luna.architecture.json
@@ -0,0 +1,324 @@
+{
+ "schema_version": 1,
+ "diagram_type": "architecture",
+ "meta": {
+ "title": "跨租户审计日志导出与脱敏编排服务(含异步导出、留存策略和人工复核边界)",
+ "locale": "zh-CN",
+ "quality_profile": "showcase",
+ "views": [
+ {
+ "id": "request-execution",
+ "label": "请求到导出",
+ "focus": [
+ "caller",
+ "entry",
+ "scheduler",
+ "query",
+ "redactor",
+ "writer"
+ ],
+ "note": "沿入口、排队、分段查询、脱敏与对象写出的实际调用路径阅读。"
+ },
+ {
+ "id": "policy-boundary",
+ "label": "策略与边界",
+ "focus": [
+ "policy",
+ "scheduler",
+ "redactor",
+ "writer",
+ "review"
+ ],
+ "note": "区分代码执行的策略使用、配置声明的存储与留存,以及人工复核的可选接口。"
+ },
+ {
+ "id": "outputs-notice",
+ "label": "输出与通知",
+ "focus": [
+ "writer",
+ "notifier",
+ "topic",
+ "review"
+ ],
+ "note": "查看文件结果、完成事件和人工复核请求各自的职责与实现状态。"
+ }
+ ],
+ "output": "audit-luna.html"
+ },
+ "components": [
+ {
+ "id": "caller",
+ "type": "external",
+ "label": "调用方",
+ "sublabel": "tenantId + range",
+ "pos": [
+ 40,
+ 330
+ ],
+ "size": [
+ 150,
+ 66
+ ]
+ },
+ {
+ "id": "entry",
+ "type": "backend",
+ "label": "审计导出入口",
+ "sublabel": "requestAuditExport",
+ "pos": [
+ 270,
+ 330
+ ],
+ "size": [
+ 170,
+ 66
+ ]
+ },
+ {
+ "id": "policy",
+ "type": "security",
+ "label": "策略配置",
+ "sublabel": "policy · 配置声明",
+ "pos": [
+ 275,
+ 105
+ ],
+ "size": [
+ 180,
+ 70
+ ],
+ "tag": "180d / 10000 rows"
+ },
+ {
+ "id": "scheduler",
+ "type": "backend",
+ "label": "导出计划器",
+ "sublabel": "createExport().schedule",
+ "pos": [
+ 510,
+ 330
+ ],
+ "size": [
+ 190,
+ 66
+ ]
+ },
+ {
+ "id": "query",
+ "type": "database",
+ "label": "审计日志查询",
+ "sublabel": "queryAuditLog · 内存占位实现",
+ "pos": [
+ 750,
+ 210
+ ],
+ "size": [
+ 205,
+ 70
+ ],
+ "tag": "source rows"
+ },
+ {
+ "id": "redactor",
+ "type": "security",
+ "label": "脱敏处理",
+ "sublabel": "redact(row, redactFields)",
+ "pos": [
+ 750,
+ 390
+ ],
+ "size": [
+ 205,
+ 70
+ ],
+ "tag": "token / ipAddress"
+ },
+ {
+ "id": "writer",
+ "type": "cloud",
+ "label": "对象结果写出",
+ "sublabel": "writeObject · 路径返回",
+ "pos": [
+ 1010,
+ 390
+ ],
+ "size": [
+ 190,
+ 70
+ ],
+ "tag": "audit-export-bucket"
+ },
+ {
+ "id": "notifier",
+ "type": "backend",
+ "label": "完成通知器",
+ "sublabel": "notifyReady",
+ "pos": [
+ 1260,
+ 300
+ ],
+ "size": [
+ 170,
+ 66
+ ]
+ },
+ {
+ "id": "topic",
+ "type": "messagebus",
+ "label": "通知主题",
+ "sublabel": "audit-export-ready · 配置通道",
+ "pos": [
+ 1480,
+ 195
+ ],
+ "size": [
+ 200,
+ 70
+ ]
+ },
+ {
+ "id": "review",
+ "type": "messagebus",
+ "label": "人工复核队列",
+ "sublabel": "requestReview · 可调用声明",
+ "pos": [
+ 1480,
+ 400
+ ],
+ "size": [
+ 200,
+ 70
+ ],
+ "tag": "privacy-review"
+ }
+ ],
+ "boundaries": [
+ {
+ "kind": "region",
+ "label": "导出编排运行时(已实现调用链)",
+ "wraps": [
+ "entry",
+ "scheduler",
+ "query",
+ "redactor",
+ "writer",
+ "notifier"
+ ],
+ "pad": 26
+ },
+ {
+ "kind": "security-group",
+ "label": "配置驱动的数据边界",
+ "wraps": [
+ "policy",
+ "redactor",
+ "writer"
+ ],
+ "pad": 18
+ }
+ ],
+ "connections": [
+ {
+ "id": "request",
+ "from": "caller",
+ "to": "entry",
+ "label": "requestAuditExport(request)",
+ "variant": "emphasis"
+ },
+ {
+ "id": "policy-entry",
+ "from": "policy",
+ "to": "entry",
+ "label": "导入 policy"
+ },
+ {
+ "id": "policy-schedule",
+ "from": "policy",
+ "to": "scheduler",
+ "label": "maxRowsPerPart"
+ },
+ {
+ "id": "schedule",
+ "from": "entry",
+ "to": "scheduler",
+ "label": "schedule(job) → queued"
+ },
+ {
+ "id": "plan-query",
+ "from": "scheduler",
+ "to": "query",
+ "label": "run → queryAuditLog"
+ },
+ {
+ "id": "query-redact",
+ "from": "query",
+ "to": "redactor",
+ "label": "rows"
+ },
+ {
+ "id": "redact-write",
+ "from": "redactor",
+ "to": "writer",
+ "label": "redacted rows → writeObject"
+ },
+ {
+ "id": "retention",
+ "from": "policy",
+ "to": "writer",
+ "label": "objectStore + retentionDays"
+ },
+ {
+ "id": "ready",
+ "from": "writer",
+ "to": "notifier",
+ "label": "files → notifyReady"
+ },
+ {
+ "id": "event",
+ "from": "notifier",
+ "to": "topic",
+ "label": "audit-export-ready",
+ "variant": "emphasis"
+ },
+ {
+ "id": "review-declared",
+ "from": "policy",
+ "to": "review",
+ "label": "reviewQueue 配置",
+ "variant": "dashed"
+ },
+ {
+ "id": "review-api",
+ "from": "notifier",
+ "to": "review",
+ "label": "requestReview(job, reason, queue)",
+ "variant": "dashed"
+ }
+ ],
+ "cards": [
+ {
+ "dot": "cyan",
+ "title": "实际执行链",
+ "items": [
+ "入口校验 tenantId 与 range 后返回 queued 计划",
+ "run 异步查询、逐行脱敏、写对象并通知完成"
+ ]
+ },
+ {
+ "dot": "amber",
+ "title": "配置驱动边界",
+ "items": [
+ "脱敏字段、分段上限、对象存储名与 180 天留存来自 policy",
+ "queryAuditLog 与 writeObject 是受控 fixture 中的占位实现"
+ ]
+ },
+ {
+ "dot": "rose",
+ "title": "人工复核状态",
+ "items": [
+ "requestReview 只构造 manual-review 对象并未在主链路调用",
+ "reviewQueue 是配置声明,不能据此推断已有消费者或人工处理流程"
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/archify/test/fixtures/architecture-first-draft/audit-terra.architecture.json b/archify/test/fixtures/architecture-first-draft/audit-terra.architecture.json
new file mode 100644
index 00000000..90f3649b
--- /dev/null
+++ b/archify/test/fixtures/architecture-first-draft/audit-terra.architecture.json
@@ -0,0 +1,329 @@
+{
+ "schema_version": 1,
+ "diagram_type": "architecture",
+ "meta": {
+ "title": "跨租户审计日志导出与脱敏编排服务(含异步导出、留存策略和人工复核边界)",
+ "locale": "zh-CN",
+ "quality_profile": "showcase",
+ "views": [
+ {
+ "id": "entry-and-plan",
+ "label": "入口与排队计划",
+ "focus": [
+ "caller",
+ "entry",
+ "plan",
+ "policy"
+ ],
+ "note": "入口仅校验 tenantId 与 range,并返回 queued 计划;未见运行闭包被调用。"
+ },
+ {
+ "id": "conditional-execution",
+ "label": "条件执行与数据边界",
+ "focus": [
+ "plan",
+ "execution",
+ "query-stub",
+ "redactor",
+ "writer-stub",
+ "result"
+ ],
+ "note": "下方流程由计划携带的 run 闭包指向;代码未展示谁调用它,查询与写入是本地桩。"
+ },
+ {
+ "id": "declared-integrations",
+ "label": "通知与人工复核边界",
+ "focus": [
+ "execution",
+ "notifier",
+ "review-declaration",
+ "policy"
+ ],
+ "note": "通知函数只组装返回对象;人工复核队列与函数均为声明,未接入正常路径。"
+ }
+ ],
+ "output": "audit-terra.html"
+ },
+ "components": [
+ {
+ "id": "caller",
+ "type": "external",
+ "label": "导出请求调用方",
+ "sublabel": "提供 tenantId 与 range",
+ "pos": [
+ 35,
+ 235
+ ],
+ "size": [
+ 150,
+ 72
+ ]
+ },
+ {
+ "id": "entry",
+ "type": "backend",
+ "label": "请求入口 requestAuditExport",
+ "sublabel": "缺 tenantId 或 range 返回 400",
+ "pos": [
+ 250,
+ 235
+ ],
+ "size": [
+ 190,
+ 72
+ ]
+ },
+ {
+ "id": "plan",
+ "type": "messagebus",
+ "label": "导出计划(内存对象)",
+ "sublabel": "queued、parts 与 run 闭包",
+ "pos": [
+ 510,
+ 235
+ ],
+ "size": [
+ 180,
+ 72
+ ]
+ },
+ {
+ "id": "policy",
+ "type": "security",
+ "label": "策略配置 policy",
+ "sublabel": "180 天、字段、分片、名称",
+ "pos": [
+ 505,
+ 55
+ ],
+ "size": [
+ 195,
+ 72
+ ]
+ },
+ {
+ "id": "execution",
+ "type": "backend",
+ "label": "exportParts 执行函数",
+ "sublabel": "仅由 run 闭包引用,调用者未展示",
+ "pos": [
+ 510,
+ 440
+ ],
+ "size": [
+ 205,
+ 74
+ ]
+ },
+ {
+ "id": "query-stub",
+ "type": "database",
+ "label": "审计日志查询桩",
+ "sublabel": "按 tenantId 与 part 返回本地示例行",
+ "pos": [
+ 790,
+ 385
+ ],
+ "size": [
+ 195,
+ 72
+ ]
+ },
+ {
+ "id": "redactor",
+ "type": "security",
+ "label": "字段脱敏",
+ "sublabel": "过滤 policy.redactFields",
+ "pos": [
+ 790,
+ 530
+ ],
+ "size": [
+ 180,
+ 72
+ ]
+ },
+ {
+ "id": "writer-stub",
+ "type": "cloud",
+ "label": "结果对象写入桩",
+ "sublabel": "返回 bucket/tenantId/行数 路径字符串",
+ "pos": [
+ 1040,
+ 530
+ ],
+ "size": [
+ 220,
+ 72
+ ]
+ },
+ {
+ "id": "notifier",
+ "type": "external",
+ "label": "完成通知函数",
+ "sublabel": "组装 audit-export-ready 返回对象",
+ "pos": [
+ 1035,
+ 385
+ ],
+ "size": [
+ 220,
+ 72
+ ]
+ },
+ {
+ "id": "result",
+ "type": "external",
+ "label": "执行结果(若 run 被调用)",
+ "sublabel": "files 与 expiresAfterDays",
+ "pos": [
+ 1040,
+ 690
+ ],
+ "size": [
+ 215,
+ 72
+ ]
+ },
+ {
+ "id": "review-declaration",
+ "type": "external",
+ "label": "人工复核(仅声明)",
+ "sublabel": "privacy-review 与 requestReview 未接入",
+ "pos": [
+ 255,
+ 55
+ ],
+ "size": [
+ 205,
+ 72
+ ]
+ }
+ ],
+ "boundaries": [
+ {
+ "kind": "region",
+ "label": "入口与计划模块边界",
+ "wraps": [
+ "entry",
+ "plan",
+ "policy"
+ ],
+ "pad": 24
+ },
+ {
+ "kind": "region",
+ "label": "条件执行中的租户数据处理",
+ "wraps": [
+ "execution",
+ "query-stub",
+ "redactor",
+ "writer-stub",
+ "notifier",
+ "result"
+ ],
+ "pad": 24
+ }
+ ],
+ "connections": [
+ {
+ "id": "request",
+ "from": "caller",
+ "to": "entry",
+ "label": "导出请求:tenantId + range",
+ "variant": "emphasis"
+ },
+ {
+ "id": "schedule",
+ "from": "entry",
+ "to": "plan",
+ "label": "schedule({ tenantId, range })",
+ "variant": "emphasis"
+ },
+ {
+ "id": "policy-to-plan",
+ "from": "policy",
+ "to": "plan",
+ "label": "maxRowsPerPart 用于分片"
+ },
+ {
+ "id": "policy-to-execution",
+ "from": "policy",
+ "to": "execution",
+ "label": "脱敏、留存、对象与通知名称"
+ },
+ {
+ "id": "run-reference",
+ "from": "plan",
+ "to": "execution",
+ "label": "run 闭包引用(未见调用)",
+ "variant": "dashed"
+ },
+ {
+ "id": "query",
+ "from": "execution",
+ "to": "query-stub",
+ "label": "queryAuditLog(tenantId, part)"
+ },
+ {
+ "id": "redact",
+ "from": "query-stub",
+ "to": "redactor",
+ "label": "示例行 → 移除 token、ipAddress",
+ "variant": "security"
+ },
+ {
+ "id": "write",
+ "from": "redactor",
+ "to": "writer-stub",
+ "label": "writeObject(本地路径字符串)"
+ },
+ {
+ "id": "notify",
+ "from": "execution",
+ "to": "notifier",
+ "label": "notifyReady(job, files, topic)",
+ "variant": "dashed"
+ },
+ {
+ "id": "return",
+ "from": "execution",
+ "to": "result",
+ "label": "返回 files + expiresAfterDays"
+ },
+ {
+ "id": "review-declared",
+ "from": "policy",
+ "to": "review-declaration",
+ "label": "reviewQueue 配置;无运行时调用",
+ "variant": "dashed"
+ }
+ ],
+ "cards": [
+ {
+ "dot": "emerald",
+ "title": "实际入口行为",
+ "items": [
+ "入口只校验 tenantId 与 range,然后返回 queued 导出计划。",
+ "计划保存 run 闭包;当前源码未展示任何执行器、队列消费者或调用点。"
+ ]
+ },
+ {
+ "dot": "cyan",
+ "title": "条件执行时的数据边界",
+ "items": [
+ "执行函数把 tenantId 传给查询桩,并按配置移除 token 与 ipAddress。",
+ "对象写入桩只返回路径字符串;未观察到真实对象存储 I/O。",
+ "留存策略只作为 expiresAfterDays 返回,未观察到删除或生命周期执行。"
+ ]
+ },
+ {
+ "dot": "amber",
+ "title": "通知与复核的未实现边界",
+ "items": [
+ "notifyReady 只构造通知对象,未观察到主题发布。",
+ "privacy-review 与 requestReview 存在声明,但未从导出路径调用或入队。"
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/archify/test/fixtures/architecture-first-draft/queue-luna.architecture.json b/archify/test/fixtures/architecture-first-draft/queue-luna.architecture.json
new file mode 100644
index 00000000..cce4da1f
--- /dev/null
+++ b/archify/test/fixtures/architecture-first-draft/queue-luna.architecture.json
@@ -0,0 +1,291 @@
+{
+ "schema_version": 1,
+ "diagram_type": "architecture",
+ "meta": {
+ "title": "Queue Gateway Architecture",
+ "quality_profile": "showcase",
+ "views": [
+ {
+ "id": "request-and-queue",
+ "label": "Request to queue",
+ "focus": [
+ "tenant",
+ "gateway",
+ "queue",
+ "worker"
+ ],
+ "note": "Follow a tenant request into the bounded waiting queue and worker runtime."
+ },
+ {
+ "id": "worker-integrations",
+ "label": "Worker integrations",
+ "focus": [
+ "worker",
+ "auth",
+ "billing",
+ "result"
+ ],
+ "note": "See the configured authentication, billing, and result boundaries used by each worker attempt."
+ },
+ {
+ "id": "failure-recovery",
+ "label": "Retry and dead letter",
+ "focus": [
+ "worker",
+ "dead-letter",
+ "queue"
+ ],
+ "note": "Trace retries through the attempt limit and the final dead-letter handoff."
+ }
+ ],
+ "output": "queue-luna.html"
+ },
+ "components": [
+ {
+ "id": "tenant",
+ "type": "external",
+ "label": "Tenant Request",
+ "sublabel": "tenant + payload",
+ "pos": [
+ 60,
+ 330
+ ],
+ "size": [
+ 150,
+ 70
+ ]
+ },
+ {
+ "id": "gateway",
+ "type": "backend",
+ "label": "Job Gateway",
+ "sublabel": "submitJob · 202 queued",
+ "pos": [
+ 280,
+ 330
+ ],
+ "size": [
+ 180,
+ 70
+ ]
+ },
+ {
+ "id": "queue",
+ "type": "messagebus",
+ "label": "Waiting Queue",
+ "sublabel": "in-memory · FIFO shift",
+ "tag": "concurrency 3",
+ "pos": [
+ 535,
+ 330
+ ],
+ "size": [
+ 190,
+ 70
+ ]
+ },
+ {
+ "id": "worker",
+ "type": "backend",
+ "label": "Worker Runtime",
+ "sublabel": "runWorker · async attempts",
+ "pos": [
+ 805,
+ 330
+ ],
+ "size": [
+ 190,
+ 70
+ ]
+ },
+ {
+ "id": "auth",
+ "type": "security",
+ "label": "Tenant Auth",
+ "sublabel": "tenant-token-service",
+ "pos": [
+ 535,
+ 115
+ ],
+ "size": [
+ 190,
+ 70
+ ]
+ },
+ {
+ "id": "billing",
+ "type": "cloud",
+ "label": "Billing Provider",
+ "sublabel": "billing-provider",
+ "pos": [
+ 805,
+ 115
+ ],
+ "size": [
+ 190,
+ 70
+ ]
+ },
+ {
+ "id": "result",
+ "type": "database",
+ "label": "Result Store",
+ "sublabel": "job-result-store",
+ "pos": [
+ 1080,
+ 330
+ ],
+ "size": [
+ 190,
+ 70
+ ]
+ },
+ {
+ "id": "dead-letter",
+ "type": "messagebus",
+ "label": "Dead-Letter Queue",
+ "sublabel": "after 3",
+ "pos": [
+ 805,
+ 545
+ ],
+ "size": [
+ 190,
+ 70
+ ]
+ }
+ ],
+ "boundaries": [
+ {
+ "kind": "region",
+ "label": "Gateway queue runtime",
+ "wraps": [
+ "gateway",
+ "queue",
+ "worker"
+ ],
+ "pad": 32
+ },
+ {
+ "kind": "security-group",
+ "label": "Configured service boundaries",
+ "wraps": [
+ "auth",
+ "billing",
+ "result"
+ ],
+ "pad": 28
+ }
+ ],
+ "connections": [
+ {
+ "id": "submit",
+ "from": "tenant",
+ "to": "gateway",
+ "label": "submitJob(request)",
+ "variant": "emphasis"
+ },
+ {
+ "id": "enqueue",
+ "from": "gateway",
+ "to": "queue",
+ "label": "enqueue · 202 jobId",
+ "variant": "emphasis"
+ },
+ {
+ "id": "dispatch",
+ "from": "queue",
+ "to": "worker",
+ "label": "dispatch when active < 3"
+ },
+ {
+ "id": "authorize",
+ "from": "worker",
+ "to": "auth",
+ "label": "authorizeTenant",
+ "variant": "security",
+ "fromSide": "top",
+ "toSide": "bottom"
+ },
+ {
+ "id": "token",
+ "from": "auth",
+ "to": "worker",
+ "label": "tenant token",
+ "variant": "security",
+ "fromSide": "bottom",
+ "toSide": "top"
+ },
+ {
+ "id": "bill",
+ "from": "worker",
+ "to": "billing",
+ "label": "callProvider(payload, token)",
+ "variant": "emphasis",
+ "fromSide": "top",
+ "toSide": "bottom"
+ },
+ {
+ "id": "save",
+ "from": "worker",
+ "to": "result",
+ "label": "saveResult(job.id, result)"
+ },
+ {
+ "id": "retry",
+ "from": "worker",
+ "to": "worker",
+ "label": "retry until maxAttempts = 2",
+ "variant": "dashed",
+ "fromSide": "bottom",
+ "toSide": "bottom"
+ },
+ {
+ "id": "dead-letter",
+ "from": "worker",
+ "to": "dead-letter",
+ "label": "final failure → dead-letter",
+ "variant": "dashed",
+ "fromSide": "bottom",
+ "toSide": "top"
+ },
+ {
+ "id": "complete",
+ "from": "worker",
+ "to": "queue",
+ "label": "finally: active--, pump()",
+ "variant": "dashed",
+ "fromSide": "left",
+ "toSide": "bottom"
+ }
+ ],
+ "cards": [
+ {
+ "dot": "cyan",
+ "title": "Request path",
+ "items": [
+ "submitJob validates tenant and payload",
+ "Accepted jobs return status 202 with a jobId",
+ "Queue pump starts work while active < 3"
+ ]
+ },
+ {
+ "dot": "emerald",
+ "title": "Worker contract",
+ "items": [
+ "Each attempt authorizes the tenant",
+ "Billing provider receives payload and token",
+ "Successful results are saved to job-result-store"
+ ]
+ },
+ {
+ "dot": "rose",
+ "title": "Failure path",
+ "items": [
+ "The worker retries through maxAttempts = 2",
+ "After the final failed attempt it returns a dead-letter record with after = 3",
+ "Completion decrements active and pumps the next waiting job"
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/archify/test/fixtures/architecture-first-draft/queue-sol.architecture.json b/archify/test/fixtures/architecture-first-draft/queue-sol.architecture.json
new file mode 100644
index 00000000..f9ce77b5
--- /dev/null
+++ b/archify/test/fixtures/architecture-first-draft/queue-sol.architecture.json
@@ -0,0 +1,294 @@
+{
+ "schema_version": 1,
+ "diagram_type": "architecture",
+ "meta": {
+ "title": "Queue Gateway Architecture",
+ "locale": "en",
+ "quality_profile": "showcase",
+ "views": [
+ {
+ "id": "request-and-queue",
+ "label": "Request and queue",
+ "focus": [
+ "tenant",
+ "gateway",
+ "waiting",
+ "queue-controller",
+ "worker"
+ ],
+ "note": "Follow admission into the in-memory waiting list and dispatch under the active-worker limit."
+ },
+ {
+ "id": "configured-boundaries",
+ "label": "Configured boundaries",
+ "focus": [
+ "worker",
+ "auth",
+ "billing",
+ "result-store"
+ ],
+ "note": "Each attempt authorizes the tenant, invokes the configured billing provider, then saves the result."
+ },
+ {
+ "id": "failure-and-retry",
+ "label": "Retry and dead letter",
+ "focus": [
+ "worker",
+ "dead-letter"
+ ],
+ "note": "A caught failure retries once; the second failure moves the job to the dead-letter result."
+ }
+ ],
+ "output": "queue-sol.html"
+ },
+ "components": [
+ {
+ "id": "tenant",
+ "type": "external",
+ "label": "Tenant request",
+ "sublabel": "tenant + payload",
+ "pos": [
+ 40,
+ 320
+ ],
+ "size": [
+ 140,
+ 64
+ ]
+ },
+ {
+ "id": "gateway",
+ "type": "backend",
+ "label": "Gateway",
+ "sublabel": "validate · enqueue · 202",
+ "pos": [
+ 240,
+ 320
+ ],
+ "size": [
+ 160,
+ 64
+ ]
+ },
+ {
+ "id": "waiting",
+ "type": "messagebus",
+ "label": "Waiting queue",
+ "sublabel": "in-memory FIFO array",
+ "pos": [
+ 470,
+ 320
+ ],
+ "size": [
+ 165,
+ 64
+ ]
+ },
+ {
+ "id": "queue-controller",
+ "type": "backend",
+ "label": "Queue controller",
+ "sublabel": "pump · active < 3",
+ "tag": "concurrency 3",
+ "pos": [
+ 470,
+ 110
+ ],
+ "size": [
+ 165,
+ 68
+ ]
+ },
+ {
+ "id": "worker",
+ "type": "backend",
+ "label": "Worker attempt loop",
+ "sublabel": "authorize · bill · save",
+ "tag": "maxAttempts 2",
+ "pos": [
+ 710,
+ 320
+ ],
+ "size": [
+ 180,
+ 68
+ ]
+ },
+ {
+ "id": "auth",
+ "type": "security",
+ "label": "Tenant auth boundary",
+ "sublabel": "tenant-token-service",
+ "pos": [
+ 710,
+ 110
+ ],
+ "size": [
+ 180,
+ 68
+ ]
+ },
+ {
+ "id": "billing",
+ "type": "external",
+ "label": "Billing boundary",
+ "sublabel": "billing-provider",
+ "pos": [
+ 950,
+ 110
+ ],
+ "size": [
+ 170,
+ 68
+ ]
+ },
+ {
+ "id": "result-store",
+ "type": "database",
+ "label": "Result boundary",
+ "sublabel": "job-result-store",
+ "pos": [
+ 1190,
+ 110
+ ],
+ "size": [
+ 175,
+ 68
+ ]
+ },
+ {
+ "id": "dead-letter",
+ "type": "messagebus",
+ "label": "Dead-letter result",
+ "sublabel": "after marker: 3",
+ "pos": [
+ 950,
+ 530
+ ],
+ "size": [
+ 175,
+ 68
+ ]
+ }
+ ],
+ "boundaries": [
+ {
+ "kind": "region",
+ "label": "Queue gateway process",
+ "wraps": [
+ "gateway",
+ "waiting",
+ "queue-controller",
+ "worker"
+ ]
+ },
+ {
+ "kind": "region",
+ "label": "Configured integration identifiers",
+ "wraps": [
+ "auth",
+ "billing",
+ "result-store"
+ ]
+ }
+ ],
+ "connections": [
+ {
+ "id": "submit",
+ "from": "tenant",
+ "to": "gateway",
+ "label": "submit tenant + payload",
+ "variant": "emphasis"
+ },
+ {
+ "id": "enqueue",
+ "from": "gateway",
+ "to": "waiting",
+ "label": "enqueue; return 202 queued",
+ "variant": "emphasis"
+ },
+ {
+ "id": "queue-ready",
+ "from": "waiting",
+ "to": "queue-controller",
+ "label": "shift next waiting job"
+ },
+ {
+ "id": "dispatch",
+ "from": "queue-controller",
+ "to": "worker",
+ "label": "dispatch while active < 3",
+ "variant": "emphasis"
+ },
+ {
+ "id": "authorize",
+ "from": "worker",
+ "to": "auth",
+ "label": "authorize tenant"
+ },
+ {
+ "id": "bill",
+ "from": "auth",
+ "to": "billing",
+ "label": "call provider with token",
+ "variant": "security"
+ },
+ {
+ "id": "save",
+ "from": "billing",
+ "to": "result-store",
+ "label": "save successful result",
+ "variant": "emphasis"
+ },
+ {
+ "id": "retry",
+ "from": "worker",
+ "to": "worker",
+ "label": "caught error → retry attempt 2",
+ "variant": "dashed"
+ },
+ {
+ "id": "dead-letter-path",
+ "from": "worker",
+ "to": "dead-letter",
+ "label": "second caught failure → dead letter",
+ "variant": "dashed"
+ }
+ ],
+ "cards": [
+ {
+ "dot": "cyan",
+ "title": "Admission and waiting",
+ "items": [
+ "Missing tenant or payload returns 400",
+ "Accepted jobs enter an in-memory FIFO and return 202 queued"
+ ]
+ },
+ {
+ "dot": "emerald",
+ "title": "Bounded dispatch",
+ "items": [
+ "pump() dispatches only while active < concurrency",
+ "finally decrements active and pumps the next waiting job"
+ ]
+ },
+ {
+ "dot": "violet",
+ "title": "Configured boundaries",
+ "items": [
+ "Every attempt authorizes before the billing provider call",
+ "Successful results are saved to the configured result-store identifier",
+ "The fixture implements these integrations as local functions; no network protocol is declared"
+ ]
+ },
+ {
+ "dot": "rose",
+ "title": "Failure semantics",
+ "items": [
+ "maxAttempts = 2 creates one retry after the first failure",
+ "The second failure moves to dead letter",
+ "deadLetterAfter = 3 is stored as an output marker; it does not create a third attempt"
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/archify/test/fixtures/lifecycle-planner/approval.lifecycle.json b/archify/test/fixtures/lifecycle-planner/approval.lifecycle.json
new file mode 100644
index 00000000..868102f8
--- /dev/null
+++ b/archify/test/fixtures/lifecycle-planner/approval.lifecycle.json
@@ -0,0 +1,297 @@
+{
+ "schema_version": 1,
+ "diagram_type": "lifecycle",
+ "meta": {
+ "title": "Document Approval Lifecycle",
+ "output": "approval.lifecycle.html",
+ "locale": "en",
+ "quality_profile": "showcase",
+ "views": [
+ {
+ "id": "happy-path",
+ "label": "Happy path",
+ "focus": [
+ "draft",
+ "submitted",
+ "under_review",
+ "approved",
+ "scheduled",
+ "published",
+ "archived"
+ ],
+ "note": "The document moves from Draft through review and scheduling to Published and finally Archived."
+ },
+ {
+ "id": "review-gate",
+ "label": "Review gate",
+ "focus": [
+ "submitted",
+ "under_review",
+ "changes_requested",
+ "draft"
+ ],
+ "note": "Submitted waits under a 72h SLA; requested changes loop the document back to Draft."
+ },
+ {
+ "id": "publish-retry",
+ "label": "Publish retry",
+ "focus": [
+ "approved",
+ "scheduled",
+ "publish_failed",
+ "published"
+ ],
+ "note": "A failed publish job gets exactly one automatic retry back into Scheduled."
+ },
+ {
+ "id": "exits",
+ "label": "Terminal exits",
+ "focus": [
+ "submitted",
+ "under_review",
+ "rejected",
+ "withdrawn",
+ "published",
+ "archived"
+ ],
+ "note": "Rejected, Withdrawn and Archived are final; no transition leaves them."
+ }
+ ]
+ },
+ "lanes": [
+ {
+ "id": "main",
+ "label": "Approval phases"
+ },
+ {
+ "id": "held",
+ "label": "Held states"
+ },
+ {
+ "id": "terminal",
+ "label": "Exits + retry"
+ }
+ ],
+ "states": [
+ {
+ "id": "draft",
+ "type": "start",
+ "label": "Draft",
+ "sublabel": "author editing",
+ "lane": "main",
+ "col": 0,
+ "step": "01",
+ "tag": "editable"
+ },
+ {
+ "id": "submitted",
+ "type": "waiting",
+ "label": "Submitted",
+ "sublabel": "awaiting reviewer, SLA 72h",
+ "lane": "main",
+ "col": 1,
+ "step": "02",
+ "tag": "timer"
+ },
+ {
+ "id": "under_review",
+ "type": "decision",
+ "label": "Under Review",
+ "sublabel": "reviewer decides",
+ "lane": "main",
+ "col": 2,
+ "step": "03",
+ "tag": "gate"
+ },
+ {
+ "id": "approved",
+ "type": "active",
+ "label": "Approved",
+ "sublabel": "ready to schedule",
+ "lane": "main",
+ "col": 3,
+ "step": "04",
+ "tag": "signed off"
+ },
+ {
+ "id": "published",
+ "type": "success",
+ "label": "Published",
+ "sublabel": "publicly visible",
+ "lane": "main",
+ "col": 4,
+ "step": "05",
+ "tag": "live"
+ },
+ {
+ "id": "changes_requested",
+ "type": "failure",
+ "label": "Changes Requested",
+ "sublabel": "reviewer feedback",
+ "lane": "held",
+ "col": 0,
+ "tag": "rework"
+ },
+ {
+ "id": "scheduled",
+ "type": "waiting",
+ "label": "Scheduled",
+ "sublabel": "publish date set",
+ "lane": "held",
+ "col": 1,
+ "tag": "timer"
+ },
+ {
+ "id": "archived",
+ "type": "neutral",
+ "label": "Archived",
+ "sublabel": "read-only record",
+ "lane": "held",
+ "col": 2,
+ "tag": "terminal"
+ },
+ {
+ "id": "rejected",
+ "type": "failure",
+ "label": "Rejected",
+ "sublabel": "reviewer declined",
+ "lane": "terminal",
+ "col": 0,
+ "tag": "terminal"
+ },
+ {
+ "id": "withdrawn",
+ "type": "neutral",
+ "label": "Withdrawn",
+ "sublabel": "author pulled back",
+ "lane": "terminal",
+ "col": 1,
+ "tag": "terminal"
+ },
+ {
+ "id": "publish_failed",
+ "type": "failure",
+ "label": "Publish Failed",
+ "sublabel": "one automatic retry",
+ "lane": "terminal",
+ "col": 2,
+ "tag": "retry"
+ }
+ ],
+ "transitions": [
+ {
+ "id": "t-submit",
+ "from": "draft",
+ "to": "submitted",
+ "label": "author submits"
+ },
+ {
+ "id": "t-claim",
+ "from": "submitted",
+ "to": "under_review",
+ "label": "reviewer claims within 72h"
+ },
+ {
+ "id": "t-approve",
+ "from": "under_review",
+ "to": "approved",
+ "label": "reviewer approves"
+ },
+ {
+ "id": "t-schedule",
+ "from": "approved",
+ "to": "scheduled",
+ "label": "publish date set"
+ },
+ {
+ "id": "t-publish",
+ "from": "scheduled",
+ "to": "published",
+ "label": "publish time reached"
+ },
+ {
+ "id": "t-archive",
+ "from": "published",
+ "to": "archived",
+ "label": "retention period ends"
+ },
+ {
+ "id": "t-changes",
+ "from": "under_review",
+ "to": "changes_requested",
+ "label": "reviewer requests changes",
+ "variant": "dashed"
+ },
+ {
+ "id": "t-rework",
+ "from": "changes_requested",
+ "to": "draft",
+ "label": "author reopens draft",
+ "variant": "dashed"
+ },
+ {
+ "id": "t-fail",
+ "from": "scheduled",
+ "to": "publish_failed",
+ "label": "publish job errors",
+ "variant": "dashed"
+ },
+ {
+ "id": "t-retry",
+ "from": "publish_failed",
+ "to": "scheduled",
+ "label": "automatic retry (1x)",
+ "variant": "dashed"
+ },
+ {
+ "id": "t-reject",
+ "from": "under_review",
+ "to": "rejected",
+ "label": "reviewer rejects",
+ "variant": "security"
+ },
+ {
+ "id": "t-withdraw-submitted",
+ "from": "submitted",
+ "to": "withdrawn",
+ "label": "author withdraws",
+ "variant": "security"
+ },
+ {
+ "id": "t-withdraw-review",
+ "from": "under_review",
+ "to": "withdrawn",
+ "label": "author withdraws",
+ "variant": "security"
+ }
+ ],
+ "cards": [
+ {
+ "dot": "cyan",
+ "title": "Main Rail",
+ "items": [
+ "Five ordered phases from Draft to Published",
+ "Under Review is the only decision point",
+ "Archived closes the record after the retention period"
+ ]
+ },
+ {
+ "dot": "amber",
+ "title": "Wait States",
+ "items": [
+ "Submitted waits for a reviewer under a 72h SLA",
+ "Scheduled holds an approved document until its publish time",
+ "A failed publish job gets exactly one automatic retry"
+ ]
+ },
+ {
+ "dot": "rose",
+ "title": "Loops and Exits",
+ "items": [
+ "Changes Requested returns the document to Draft for rework",
+ "Rejected is a reviewer decision; Withdrawn is an author decision",
+ "Withdrawn is reachable from Submitted or Under Review"
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/archify/test/layout-rules.test.mjs b/archify/test/layout-rules.test.mjs
index 5881501a..38e3b8ba 100644
--- a/archify/test/layout-rules.test.mjs
+++ b/archify/test/layout-rules.test.mjs
@@ -1628,7 +1628,10 @@ test('architecture: auto route clears stacked blockers after doglegs and side-aw
const encoded = html.match(/data-edge-id="api-queue" data-composition-points="([^"]+)"/)?.[1];
assert.ok(encoded, 'expected rendered composition points for api-queue');
const points = encoded.split(';').map((point) => point.split(',').map(Number));
- assert.ok(points.length >= 6, `expected a multi-bend route, found ${encoded}`);
+ // The bend-penalised planner takes the 50px gap between the two blockers in
+ // two turns; the pure shortest path used to staircase around them.
+ assert.ok(points.length >= 4, `expected a routed detour, found ${encoded}`);
+ assert.ok(points.slice(1, -1).some(([x]) => x > 775 && x < 825), `route must pass between the blockers, found ${encoded}`);
assert.equal(points[0][1], points[1][1], 'route must leave the inferred right port horizontally');
assert.ok(points[1][0] > points[0][0], 'route must leave the inferred right port rightward');
assert.equal(points.at(-2)[1], points.at(-1)[1], 'route must enter the inferred left port horizontally');
diff --git a/archify/test/lifecycle-planner.test.mjs b/archify/test/lifecycle-planner.test.mjs
index e1750da8..df9cbcfc 100644
--- a/archify/test/lifecycle-planner.test.mjs
+++ b/archify/test/lifecycle-planner.test.mjs
@@ -54,3 +54,26 @@ test('lifecycle: planner routes render as one semantic edge with a crossover mas
fs.rmSync(tmp, { recursive: true, force: true });
}
});
+
+// A real first draft from the authoring experiments: thirteen unrouted
+// transitions, three of them fanning out of one state's bottom side. Before
+// the planner reserved label space, the parallel routes left "reviewer
+// requests changes" nowhere to go and the author had to hand-route.
+test('lifecycle: a fan-out first draft keeps every label beside its own transition', () => {
+ const approval = path.join(skillRoot, 'test/fixtures/lifecycle-planner/approval.lifecycle.json');
+ const { status, receipt } = validate(approval);
+ assert.equal(status, 0, JSON.stringify(receipt.diagnostics, null, 2));
+ assert.equal(receipt.composition.summary.errors, 0);
+
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-lifecycle-fanout-'));
+ try {
+ const output = path.join(tmp, 'approval.html');
+ execFileSync(process.execPath, [renderer, approval, output]);
+ const html = fs.readFileSync(output, 'utf8');
+ const publish = html.match(/data-edge-id="t-publish" data-composition-points="([^"]+)"/)?.[1];
+ assert.ok(publish, 'the publish transition renders');
+ assert.ok(publish.split(';').length <= 4, `publish keeps at most two turns: ${publish}`);
+ } finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+});