Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.
HTML agent-skillsai-agentsarchitecture-diagramclaude-codeclaude-skillscodexcoding-agentsdeepseek-harnessdeveloper-toolsdiagramsdiagrams-as-codedsh-pluginflowchartllmmermaidopencodesequence-diagramsoftware-architecturesystem-designvisualization
fix(architecture): improve route choices and expose layout review evidence
tt-a1i284276c85dfd
diff --git a/archify.zip b/archify.zipindex a805f621..bf231839 100644Binary files a/archify.zip and b/archify.zip differdiff --git a/archify/SKILL.md b/archify/SKILL.mdindex 79fac578..03035196 100644--- a/archify/SKILL.md+++ b/archify/SKILL.md@@ -28,7 +28,7 @@ Use this bounded path for ordinary generation. Do not read the optional Viewer R1. Choose `architecture`, `workflow`, `sequence`, `dataflow`, or `lifecycle` from the question.2. Use the exact paths in the Type router; do not list `schemas/` or `examples/` first. For Architecture, select the matching showcase example in the Type router before loading it with `references/authoring-defaults.md` in one parallel batch; it includes boundaries, guided views, and conclusion cards. For Workflow, read defaults and its starter together. Read the relevant schema definition for any new field, enum choice, or constrained text; an example shows shape, not every allowed value or length. Boundary kinds and guided-view notes need their schema constraints before writing. For Sequence, Dataflow, and Lifecycle, read defaults, schema, common schema, and example together. Fresh authorship means new IDs, domain wording, and layout; examples provide shape, not facts. Do not run help, doctor, validate a starter, create a temporary diagram, pre-create/list output paths, or query brands. Only for explicitly requested branded marks may you query `node bin/archify.mjs brands "<name>" --json`; read `references/brand-marks.md` only for an unknown brand with a user-provided URL.-3. Artifact first: once requested scope and source evidence are covered, write the candidate directly; do not plan coordinates in prose. For Architecture, default to a system overview: one clear main path, short side branches, and sparse labels. Choose abstraction for the reader's question using [Composition and meaning](references/authoring-defaults.md#composition-and-meaning). Split an overview node only when combining it would mislead the reader about a requested interaction or important boundary; expand internals when the user asks for that mechanism. Keep source evidence for every claim. Never use node, relationship, source-reference, view, card, or boundary counts as an authoring target, ceiling, or performance lever. Add guided views and conclusion cards only when they answer an additional reader question. Set `meta.quality_profile` to `"showcase"` unless the user requests dense `standard`. Keep forward flow monotonic where practical, branches beside their owner, shared stores outside the main lane, and feedback paths on the perimeter; wrap broad systems into meaningful rows. Leave clear gaps for actual relationship labels and add whitespace rather than route controls. On the first draft, let the renderer route every connection: omit `via`, `route`, `fromSide`, `toSide`, `channelX`, `channelY`, `labelAt`, `labelDx`, `labelDy`, and `labelSegment` unless the user supplied that exact route intent. Add the smallest control only after a measured diagnostic.+3. Artifact first: once requested scope and source evidence are covered, write the candidate directly; do not plan coordinates in prose. For Architecture, default to a system overview: one clear main path, short side branches, and sparse labels. Choose abstraction for the reader's question using [Composition and meaning](references/authoring-defaults.md#composition-and-meaning). Split an overview node only when combining it would mislead the reader about a requested interaction or important boundary; expand internals when the user asks for that mechanism. Keep source evidence for every claim. Never use node, relationship, source-reference, view, card, or boundary counts as an authoring target, ceiling, or performance lever. Add guided views and conclusion cards only when they answer an additional reader question. Set `meta.quality_profile` to `"showcase"` unless the user requests dense `standard`. Place nodes by their actual connections using Layout and routing in the defaults: main-path neighbors stay adjacent, branches sit beside their owner, and return paths have an outside corridor. Check every relationship against that placement before writing positions; automatic routing cannot rearrange nodes. Leave clear gaps for actual relationship labels and add whitespace rather than route controls. On the first draft, let the renderer route every connection: omit `via`, `route`, `fromSide`, `toSide`, `channelX`, `channelY`, `labelAt`, `labelDx`, `labelDy`, and `labelSegment` unless the user supplied that exact route intent. Add the smallest control only after a measured diagnostic.4. Once the complete first candidate is written, run `finalize` directly. Its first gate is showcase validation; successful first drafts need no separate pre-validation. Keep the candidate unchanged while the command runs:```bash@@ -39,7 +39,7 @@ Use this bounded path for ordinary generation. Do not read the optional Viewer RA passing receipt proves that the included `validate`, `deliver`, strict `check`, and deterministic real-browser `browser-check` gates passed. Do not read its full sidecar or rerun individual commands afterward; use a standalone command only for an explicitly separate execution or focused failure diagnosis.-5. A non-zero exit is never success. Use its compact stdout or `evidence.summaryReceipt`; read the full receipt only if the summary is truncated and lacks enough evidence for a coherent repair. After a validation failure, the next action is the smallest coherent local edit named by that evidence, not prose coordinate exploration or whole-candidate replacement. Do not run validate, layout, render, or finalize first; edit the existing JSON in place. Geometry never authorizes deleting or merging a source-backed component, relationship, reference, view, card, boundary, or semantic label; reroute, reposition, or add readable canvas space instead. After the edit, rerun the complete `finalize` command from step 4 once, retaining `--quality showcase` and `--repo-root <repo-root>` for repository-backed candidates. After editing, omit any earlier `--candidate-sha256`: it binds the previous candidate. Use `--layout-json` before the edit only when compact evidence lacks needed geometry. A receipt with only 4 artifact checks is basic validation: require all 9 checks with 0 composition errors and 0 warnings. Fix `meta.quality_profile` before geometry. For workflow v2, use the stable compiler receipt; solver internals are not authoring controls. Use standalone `validate` only for focused diagnosis, with `--repo-root <repo-root>` for a repository. A passing validation returns `candidateFrozen: true`; do not edit, revalidate, or reread it. Run its `nextAction.arguments`, replacing only `<output.html>`. Retry later environment or evidence failures against the frozen candidate. If measured evidence requires a source edit, treat it as a new candidate and rerun the complete `finalize` command without the old hash. If one issue survives two focused repairs, inspect measured geometry or the relevant contract; after one evidence-based retry, stop truthfully. A lower error count never justifies changing meaning.+5. A non-zero exit is never success. Use its compact stdout or `evidence.summaryReceipt`; read the full receipt only if the summary is truncated and lacks enough evidence for a coherent repair. After a validation failure, edit the connected neighborhood named by the evidence in one coherent change. When several affected routes share nodes, reposition those nodes and their neighbors together before adjusting individual lines; reserve isolated side or label controls for an isolated remaining defect. Keep unrelated geometry intact. Do not run validate, layout, render, or finalize first; edit the existing JSON in place. Geometry never authorizes deleting or merging a source-backed component, relationship, reference, view, card, boundary, or semantic label; reroute, reposition, or add readable canvas space instead. After the edit, rerun the complete `finalize` command from step 4 once, retaining `--quality showcase` and `--repo-root <repo-root>` for repository-backed candidates. After editing, omit any earlier `--candidate-sha256`: it binds the previous candidate. Use `--layout-json` before the edit only when compact evidence lacks needed geometry. A receipt with only 4 artifact checks is basic validation: require all 9 checks with 0 composition errors and 0 warnings. Fix `meta.quality_profile` before geometry. For workflow v2, use the stable compiler receipt; solver internals are not authoring controls. Use standalone `validate` only for focused diagnosis, with `--repo-root <repo-root>` for a repository. A passing validation returns `candidateFrozen: true`; do not edit, revalidate, or reread it. Run its `nextAction.arguments`, replacing only `<output.html>`. Retry later environment or evidence failures against the frozen candidate. If measured evidence requires a source edit, treat it as a new candidate and rerun the complete `finalize` command without the old hash. If one issue survives two focused repairs, inspect measured geometry or the relevant contract; after one evidence-based retry, stop truthfully. A lower error count never justifies changing meaning.## Update awarenessdiff --git a/archify/bin/finalize.mjs b/archify/bin/finalize.mjsindex 65c11743..8db3f333 100644--- a/archify/bin/finalize.mjs+++ b/archify/bin/finalize.mjs@@ -508,10 +508,19 @@ export function compactFinalizeReceipt(receipt) {].filter((key) => Number.isFinite(metrics?.[key]) && metrics[key] > 0).map((key) => [key, metrics[key]]));if (receipt.ok && Object.keys(reviewSignals).length) {+ const routeReview = receipt.stages?.check?.receipt?.composition?.routeReview;compact.visualReviewRecommendation = {action: 'inspect-route-readability',signals: reviewSignals,reason: 'Automated gates passed, but crossings or detours still need perceptual review before claiming visual quality.',+ ...(routeReview ? {+ affectedRoutes: {+ crossings: routeReview.crossings.slice(0, 8),+ detours: routeReview.detours.slice(0, 8),+ truncated: routeReview.crossings.length > 8 || routeReview.detours.length > 8,+ },+ repair: 'Trace these relationships at the desktop viewport. If several routes tangle around the same nodes, reposition that connected neighborhood together, preserving all semantics and unrelated geometry; rerun finalize once. Use a local side or label control only for an isolated remaining defect.',+ } : {}),};}if (!receipt.ok && receipt.status === 'fail' && receipt.failedStage === 'validate') {diff --git a/archify/references/authoring-defaults.md b/archify/references/authoring-defaults.mdindex d49e2303..c3f547a4 100644--- a/archify/references/authoring-defaults.md+++ b/archify/references/authoring-defaults.md@@ -48,11 +48,12 @@ Set required `meta.output` to a portable POSIX-relative `.html` path, such as `r## Layout and routing-- Treat the standalone desktop viewer as a first-screen artifact by default, not a shallow strip. Generate one responsive artifact for laptops and external displays, preserving the authored SVG/viewBox, proportions, semantic geometry, and normal document flow. Use enough authored vertical rhythm for the diagram panel and necessary conclusion cards to occupy a wide or tall desktop as a balanced whole. For a fresh Architecture, omit `meta.viewBox` by default so the renderer measures the real content and declares intrinsic-height Reader behavior. Author a fixed viewBox only when the user supplied fixed geometry or measured evidence shows it is necessary and the resulting text remains comfortably readable.+- Treat the standalone desktop viewer as a first-screen artifact by default, not a shallow strip. Generate one responsive artifact for laptops and external displays, preserving the authored SVG/viewBox, proportions, semantic geometry, and normal document flow. Start the first meaningful row near the canvas origin and use real content rows to create vertical rhythm; empty leading rows only enlarge the canvas and shrink the drawing. Keep the diagram panel and necessary conclusion cards balanced across wide and tall desktops. For a fresh Architecture, omit `meta.viewBox` by default so the renderer measures the real content and declares intrinsic-height Reader behavior. Author a fixed viewBox only when the user supplied fixed geometry or measured evidence shows it is necessary and the resulting text remains comfortably readable.- Let `finalize` run the real browser check at 1440×900, 1600×1000, 1920×1080, and 2048×1320. Require zero horizontal overflow. Prefer full first-screen containment only when the complete diagram stays comfortably readable. The 6px projected-text check is a hard failure floor, not a layout target; at 1440px, aim for ordinary context text around 7.5px or larger. If semantic completeness needs more room, add meaningful vertical rows and use Reader-declared vertical page scroll with an intrinsic-height diagram instead of merging responsibilities, dropping evidence, or squeezing typography. Repair every other overflow by removing genuinely redundant content or compacting spacing before shrinking nodes, labels, or the main panel. Never counterfeit a pass with `overflow: hidden`, clipped content, an internal diagram scroller, stretched SVG height, or smaller typography. See [Automated browser evidence](delivery-contract.md#automated-browser-evidence) for the authoritative rule.- Architecture sublabels render at a preferred 9px before responsive projection. Size each component for that preferred size (`5.4px × text units + 8px`, counting each CJK character as two units) instead of relying on shrink-to-fit. If a supporting phrase would make the node disproportionately wide, keep the node's exact role or protocol concise and preserve the supplementary fact in a guided-view note or conclusion card. Never remove a responsibility, protocol, or boundary fact just to shorten text.- If the largest viewport still has a conspicuous empty lower band at the viewer's width cap, redistribute authored Y positions and increase the viewBox height proportionally; do not add filler copy or decorative cards.- Spacing means clear gap, not center distance. For a relationship label, clear gap must exceed its measured mask width; follow the label-preserving repair order.+- Place Architecture nodes from connectivity before assigning coordinates: lay the main interaction path in order, place a branch beside the node it actually connects to, and place a shared store beside its main readers/writers. A category row (all runtimes, then all workers, then all stores) is useful only when the actual edges also follow it. Keep each tightly connected neighborhood together; give real return paths a clear outside corridor. Mentally trace every relationship across the proposed boxes before writing: if an unrelated node or another neighborhood blocks it, move the connected neighborhood now. The router chooses paths around fixed boxes; it does not rearrange a poor node layout. This is part of writing the first JSON, not an extra planning document or tool pass.- For a medium Architecture, encode one obvious main path, but let it step across multiple rows when one horizontal rail would create a shallow strip, long empty corridors, or force semantic compression. Put short branches above or below their nearest hub. The first draft leaves every connection on automatic routing and omits `via`, `route`, `fromSide`, `toSide`, `channelX`, `channelY`, and label-position controls unless the user supplied that exact route intent. After a measured diagnostic, add only the smallest named control: at a crowded hub reserve facing sides for the main path and other sides for branches, or give a real return edge one compact outer side pair or perimeter corridor. Never make unrelated orthogonal segments share the same axis for 8px or more; keep nonzero segments at least 8px and interior turns at least 16px.- Before writing, apply `6.5px × ASCII units + 21px`, counting each CJK character as two units, to every labeled connection on the main path. Treat the result as that edge's minimum clear gap, never as one fixed gap shared across the row. Increase the gap or choose a clear segment when the budget does not fit; do not wait for a predictable label-route collision.- Automatic routes own their endpoint sides. A relationship does not accept a `side` field; only after a diagnostic proves endpoint routing is required, use `fromSide` or `toSide` on the diagnosed endpoint. Each endpoint side is a direction contract: the first and final segment must leave/enter perpendicular to that side.diff --git a/archify/references/delivery-contract.md b/archify/references/delivery-contract.mdindex 660a1175..deed20f5 100644--- a/archify/references/delivery-contract.md+++ b/archify/references/delivery-contract.md@@ -261,7 +261,7 @@ Complete stage receipts and timings remain available for auditing in`<path>-summary.json`. Read the full receipt only when the compact summary istruncated and its shown subjects and evidence cannot identify a coherent localrepair, or when complete audit evidence was explicitly requested. The compact-receipt reports `visualReview: "not-requested"`; the automated gate does not create images or require a perceptual reviewer. A compact `visualReviewRecommendation` retains positive crossover and route-detour metrics from the strict check so the author can apply the review escalation below without reading the full receipt. A recommendation does not change the machine exit code or claim that review happened.+receipt reports `visualReview: "not-requested"`; the automated gate does not create images or require a perceptual reviewer. A compact `visualReviewRecommendation` retains positive crossover and route-detour metrics from the strict check so the author can apply the review escalation below without reading the full receipt. A recommendation does not change the machine exit code or claim that review happened. Its `affectedRoutes` identifies crossing pairs and detours (up to eight of each, with a truncation flag); the full strict-check `composition.routeReview` retains all affected relationships. Use these IDs to trace the routes in the captured default viewport. When multiple defects share a hub, repair that connected neighborhood together before tuning individual sides or labels; preserve every semantic fact and unrelated geometry.A passing finalizer receipt is sufficient evidence for all four gates. Merelynaming the gates or requiring each one to pass does not require replaying theirdiff --git a/archify/renderers/architecture/render-architecture.mjs b/archify/renderers/architecture/render-architecture.mjsindex 949ca75f..538b9477 100644--- a/archify/renderers/architecture/render-architecture.mjs+++ b/archify/renderers/architecture/render-architecture.mjs@@ -313,6 +313,7 @@ function layoutBoundaryTitles(rawBoundaries, minimumFontSize) {const rawBoundaries = asArray(arch.boundaries).map(boundaryRect).filter(Boolean);const { pathFor, connectionSides, connectionEndpointSide } = createRouter(components, arch.connections, {distinctAutomaticPorts: true,+ preferReadableRoutes: true,frames: rawBoundaries.map((boundary) => ({...boundary,radius: boundary.kind === 'security-group' ? 8 : 12,diff --git a/archify/renderers/architecture/routing.mjs b/archify/renderers/architecture/routing.mjsindex 77aae0a7..ee62bc4e 100644--- a/archify/renderers/architecture/routing.mjs+++ b/archify/renderers/architecture/routing.mjs@@ -41,12 +41,14 @@ export function createRouter(components, connections = [], {microSegmentPx = 8,labelRectFor = null,distinctAutomaticPorts = false,+ preferReadableRoutes = false,} = {}) {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;+ let allowGridSearch = true;function routeClearsReservedLabels(conn, points) {if (!honourReservedLabels) return true;@@ -98,6 +100,8 @@ export function createRouter(components, connections = [], {maximumGridSearchCount: 64,gridBudgetExhaustedCount: 0,crossoverRoutedCount: 0,+ readabilityCandidateCount: 0,+ readabilityImprovedCount: 0,gridAttempts: [],};@@ -488,6 +492,9 @@ export function createRouter(components, connections = [], {// Flow gate already knows violates the inferred endpoint directions.// This keeps ordinary multi-bend avoidance renderer-owned instead of// forcing the author to hand-place via points.+ // Alternative endpoint pairs are cheap probes, not another grid-search+ // budget. A legal short bridge often beats the first grid detour.+ if (!allowGridSearch) return sideSafe[0] || sideAware[0] || horizontalFirst;if (planningMetrics.gridSearchCount >= planningMetrics.maximumGridSearchCount) {planningMetrics.gridBudgetExhaustedCount += 1;planningMetrics.conflictFallbackCount += 1;@@ -746,6 +753,24 @@ export function createRouter(components, connections = [], {&& !routeOverlapsResolved(conn, routed.points, resolvedRoutes);}+ function crossingCount(conn, points, resolvedRoutes) {+ return resolvedRoutes.reduce((total, entry) => total + Number(+ !(relationshipsShareEndpoint(conn, entry.conn)+ && (!distinctAutomaticPorts || hasAuthoredRouteGeometry(entry.conn) || entry.conn.labelAt || conn.labelAt))+ && points.slice(1).some((end, index) => entry.points.slice(1).some((otherEnd, otherIndex) =>+ properSegmentIntersection(points[index], end, entry.points[otherIndex], otherEnd))),+ ), 0);+ }++ function readabilityCost(conn, routed, resolvedRoutes) {+ const points = routed.points;+ const length = points.slice(1).reduce((total, point, index) => total+ + Math.abs(point[0] - points[index][0]) + Math.abs(point[1] - points[index][1]), 0);+ // A crossover is a reading cost even with a halo. Keep it finite: avoiding+ // one crossing must not justify an arbitrarily long perimeter excursion.+ return length + Math.max(0, points.length - 2) * 48 + crossingCount(conn, points, resolvedRoutes) * 160;+ }+function computePath(conn, resolvedRoutes) {if (hasAuthoredRouteGeometry(conn)) {const sides = inferredConnectionSides(conn);@@ -758,13 +783,17 @@ export function createRouter(components, connections = [], {let firstFallback = null;const clearRoute = () => {+ let firstClear = 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 { routed, sides };+ if (routeIsClear(conn, routed, geometry, resolvedRoutes)) {+ firstClear = { routed, sides };+ break;+ }}- return null;+ return firstClear;};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);@@ -822,6 +851,61 @@ export function createRouter(components, connections = [], {});if (rect) reservedLabels.push({ conn, rect });}+ // Improve against the complete set of routes, not only earlier edges.+ // A greedy side change during the initial pass can steal a later edge's+ // corridor. This bounded sweep only changes one route at a time, keeping+ // every other route and label as an obstacle/reference.+ if (preferReadableRoutes) {+ const scenePoints = resolvedRoutes.flatMap((entry) => entry.points);+ for (const rect of [...components.values(), ...frames, ...reservedLabels.map((entry) => entry.rect)]) {+ scenePoints.push([rect.x, rect.y], [rect.x + rect.width, rect.y + rect.height]);+ }+ const bounds = {+ left: Math.min(...scenePoints.map(([x]) => x)), right: Math.max(...scenePoints.map(([x]) => x)),+ top: Math.min(...scenePoints.map(([, y]) => y)), bottom: Math.max(...scenePoints.map(([, y]) => y)),+ };+ const withinScene = ([x, y]) => x >= bounds.left && x <= bounds.right && y >= bounds.top && y <= bounds.bottom;+ allowGridSearch = false;+ try {+ for (const entry of resolvedRoutes) {+ const { conn } = entry;+ if (hasAuthoredRouteGeometry(conn) || conn.labelAt) continue;+ const others = resolvedRoutes.filter((other) => other !== entry);+ // Preserve uncomplicated routes and their established inferred sides.+ // Spend the comparison budget where the complete scene has a reading+ // cost: a crossover or more than two bends.+ if (entry.points.length <= 4 && crossingCount(conn, entry.points, others) === 0) continue;+ let best = null;+ let bestCost = readabilityCost(conn, { points: entry.points }, others);+ for (const sides of candidateSidePairs(conn)) {+ const geometry = connectionGeometry(conn, sides);+ const routed = routedForGeometry(conn, others, geometry);+ planningMetrics.readabilityCandidateCount += 1;+ if (!routed.points.every(withinScene) || !routeIsClear(conn, routed, geometry, others)) continue;+ const cost = readabilityCost(conn, routed, others);+ if (cost < bestCost) {+ const rect = labelRectFor?.(conn, routed.points, {+ routes: [...others.map((other) => other.points), routed.points],+ labels: reservedLabels.filter((label) => label.conn !== conn).map((label) => label.rect),+ });+ // A shorter route must not expand the canvas and shrink every+ // label at the default viewport. Include its reserved label too.+ if (rect && (!withinScene([rect.x, rect.y]) || !withinScene([rect.x + rect.width, rect.y + rect.height]))) continue;+ best = { routed, sides, rect };+ bestCost = cost;+ }+ }+ if (!best) continue;+ cachePath(conn, best.routed, best.sides);+ entry.points = best.routed.points;+ planningMetrics.readabilityImprovedCount += 1;+ reservedLabels = reservedLabels.filter((label) => label.conn !== conn);+ if (best.rect) reservedLabels.push({ conn, rect: best.rect });+ }+ } finally {+ allowGridSearch = true;+ }+ }planningMetrics.routeCount = resolvedRoutes.length;planningMetrics.explicitRouteCount = explicit.length;planningMetrics.automaticRouteCount = automatic.length;diff --git a/archify/scripts/check-render-output.mjs b/archify/scripts/check-render-output.mjsindex 2bf89ddc..fea6db2c 100644--- a/archify/scripts/check-render-output.mjs+++ b/archify/scripts/check-render-output.mjs@@ -226,6 +226,24 @@ if (svgMatches.length === 1) {...roundedRouteMetrics(routeMetrics),},suggestedLimits: { bendsPerRelationship: 2, stretch: 1.35, segmentPx: 16, microSegmentPx: 8 },+ // Perceptual review needs the affected relationships, not just a total.+ // These are review evidence, not new pass/fail thresholds: a short, clear+ // crossover can be preferable to a long crossing-free detour.+ routeReview: {+ crossings: resolvedCrossovers.map((hit) => ({+ left: relationshipRecord(hit.left),+ right: relationshipRecord(hit.right),+ point: hit.point,+ })),+ detours: routedRelationships.flatMap((entry) => {+ const metrics = routeBudgetMetrics({ routedRelations: [entry] });+ return metrics.routesOverSuggestedBends || metrics.routesOverSuggestedStretch ? [{+ relationship: relationshipRecord(entry.relation),+ bends: metrics.maxBends,+ stretch: metrics.maxStretch == null ? null : Math.round(metrics.maxStretch * 1000) / 1000,+ }] : [];+ }),+ },desktopReadability: desktopReadability.evidence,issues: [...containerBorderRuns.map((hit) => ({diff --git a/archify/test/architecture-readable-routing-labels.test.mjs b/archify/test/architecture-readable-routing-labels.test.mjsnew file mode 100644index 00000000..b600b468--- /dev/null+++ b/archify/test/architecture-readable-routing-labels.test.mjs@@ -0,0 +1,126 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { createRouter } from '../renderers/architecture/routing.mjs';+import { reservedLabelRect } from '../renderers/architecture/labels.mjs';+import { labelPoint, rectsOverlap, segmentIntersectsRect } from '../renderers/shared/geometry.mjs';++function fixture() {+ const boxes = new Map(Array.from({ length: 6 }, (_, index) => {+ const x = (index % 3) * 260 + 40;+ const y = Math.floor(index / 3) * 250 + 40;+ return [String(index), { id: String(index), x, y, width: 150, height: 70, cx: x + 75, cy: y + 35 }];+ }));+ const connections = [['5', '4'], ['1', '5'], ['1', '3'], ['0', '2'], ['5', '3'], ['3', '1'], ['5', '0'], ['2', '4']]+ .map(([from, to], index) => ({ id: `edge-${index}`, from, to }));+ return { boxes, connections };+}++function productionLabelRectFor(boxes) {+ const resolved = new Map();+ const callback = (conn, points, { routes, labels }) => {+ if (!conn.label) return null;+ const [lx, ly] = labelPoint(conn, points);+ // These fixture labels are ASCII, so this matches architecture textUnits.+ const width = Math.max(30, conn.label.length * 4.8 + 10);+ const rect = reservedLabelRect({+ label: { relation: conn, label: conn.label, lx, ly, x: lx - width / 2, y: ly - 10, width, height: 14 },+ points,+ routes: routes.map((route, relationIndex) => ({ relationIndex, points: route })),+ labels,+ components: [...boxes.values()],+ });+ const key = `${conn.id}:${JSON.stringify(points)}`;+ resolved.set(key, rect);+ return rect;+ };+ callback.rectFor = (conn, points) => resolved.get(`${conn.id}:${JSON.stringify(points)}`) || null;+ return callback;+}++function routeScene(boxes, connections, preferReadableRoutes) {+ const labelRectFor = productionLabelRectFor(boxes);+ const router = createRouter(boxes, connections, {+ distinctAutomaticPorts: true,+ preferReadableRoutes,+ labelRectFor,+ });+ const routes = connections.map((conn) => router.pathFor(conn).points);+ const labels = connections.flatMap((conn, index) => {+ if (!conn.label) return [];+ const rect = labelRectFor.rectFor(conn, routes[index]);+ assert.ok(rect, `expected a reserved placement for ${conn.id}`);+ return [{ conn, rect }];+ });+ return { router, routes, labels };+}++function boundsFor(boxes, routes, labels) {+ const points = [+ ...routes.flat(),+ ...[...boxes.values()].flatMap((box) => [[box.x, box.y], [box.x + box.width, box.y + box.height]]),+ ...labels.flatMap(({ rect }) => [[rect.x, rect.y], [rect.x + rect.width, rect.y + rect.height]]),+ ];+ return {+ left: Math.min(...points.map(([x]) => x)),+ right: Math.max(...points.map(([x]) => x)),+ top: Math.min(...points.map(([, y]) => y)),+ bottom: Math.max(...points.map(([, y]) => y)),+ };+}++function assertInsideBounds(point, bounds, subject) {+ assert.ok(point[0] >= bounds.left && point[0] <= bounds.right, `${subject} expands horizontal scene bounds: ${point}`);+ assert.ok(point[1] >= bounds.top && point[1] <= bounds.bottom, `${subject} expands vertical scene bounds: ${point}`);+}++test('architecture readability sweep keeps reserved labels clear and their extents inside the original scene', () => {+ const { boxes, connections } = fixture();+ connections[0].label = 'reserved label';+ connections[3].label = 'second relationship';++ const baseline = routeScene(boxes, connections, false);+ const swept = routeScene(boxes, connections, true);+ const originalBounds = boundsFor(boxes, baseline.routes, baseline.labels);++ assert.ok(swept.router.routingMetrics().readabilityImprovedCount > 0, 'the sweep exercised label-aware route changes');+ assert.ok(swept.labels.some(({ conn, rect }) => {+ const previous = baseline.labels.find((entry) => entry.conn.id === conn.id)?.rect;+ return previous && (rect.x !== previous.x || rect.y !== previous.y);+ }), 'a moved route gets a freshly reserved label position');++ for (const route of swept.routes) {+ for (const point of route) assertInsideBounds(point, originalBounds, 'route');+ }+ for (const { rect } of swept.labels) {+ assertInsideBounds([rect.x, rect.y], originalBounds, 'label');+ assertInsideBounds([rect.x + rect.width, rect.y + rect.height], originalBounds, 'label');+ }++ for (let left = 0; left < swept.labels.length; left += 1) {+ const label = swept.labels[left];+ for (let right = left + 1; right < swept.labels.length; right += 1) {+ assert.equal(rectsOverlap(label.rect, swept.labels[right].rect, 2), false, 'reserved labels remain distinct');+ }+ for (let routeIndex = 0; routeIndex < swept.routes.length; routeIndex += 1) {+ if (connections[routeIndex].id === label.conn.id) continue;+ for (let segment = 0; segment < swept.routes[routeIndex].length - 1; segment += 1) {+ assert.equal(segmentIntersectsRect({+ start: swept.routes[routeIndex][segment],+ end: swept.routes[routeIndex][segment + 1],+ }, label.rect, 4), false, `${connections[routeIndex].id} must not borrow ${label.conn.id}'s label space`);+ }+ }+ }+});++test('architecture readability sweep leaves authored route presets and channel-pinned routes unchanged', () => {+ const { boxes, connections } = fixture();+ connections[0] = { ...connections[0], route: 'orthogonal-h' };+ connections[3] = { ...connections[3], channelX: 123 };++ const baseline = routeScene(boxes, connections, false);+ const swept = routeScene(boxes, connections, true);+ for (const index of [0, 3]) {+ assert.deepEqual(swept.routes[index], baseline.routes[index], `${connections[index].id} keeps authored routing geometry`);+ }+});diff --git a/archify/test/architecture-readable-routing.test.mjs b/archify/test/architecture-readable-routing.test.mjsnew file mode 100644index 00000000..a2816a6e--- /dev/null+++ b/archify/test/architecture-readable-routing.test.mjs@@ -0,0 +1,59 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { createRouter } from '../renderers/architecture/routing.mjs';+import { properSegmentIntersection, routeBudgetMetrics } from '../renderers/shared/geometry.mjs';++function fixture() {+ const boxes = new Map(Array.from({ length: 6 }, (_, index) => {+ const x = (index % 3) * 260 + 40;+ const y = Math.floor(index / 3) * 250 + 40;+ return [String(index), { id: String(index), x, y, width: 150, height: 70, cx: x + 75, cy: y + 35 }];+ }));+ const connections = [['5', '4'], ['1', '5'], ['1', '3'], ['0', '2'], ['5', '3'], ['3', '1'], ['5', '0'], ['2', '4']]+ .map(([from, to], index) => ({ id: `edge-${index}`, from, to }));+ return { boxes, connections };+}++function crossings(routes) {+ let count = 0;+ for (let left = 0; left < routes.length; left += 1) {+ for (let right = left + 1; right < routes.length; right += 1) {+ if (routes[left].slice(1).some((end, index) => routes[right].slice(1).some((otherEnd, otherIndex) =>+ properSegmentIntersection(routes[left][index], end, routes[right][otherIndex], otherEnd)))) count += 1;+ }+ }+ return count;+}++test('architecture improves complete-scene crossings and bends without extra grid searches or changed input', () => {+ const { boxes, connections } = fixture();+ const before = JSON.stringify({ boxes: [...boxes], connections });+ const routers = [false, true].map((preferReadableRoutes) => createRouter(boxes, connections, {+ distinctAutomaticPorts: true, preferReadableRoutes,+ }));+ const routes = routers.map((router) => connections.map((conn) => router.pathFor(conn).points));+ assert.equal(crossings(routes[0]), 11, 'fixture exposes the first-legal-route regression');+ assert.equal(crossings(routes[1]), 9);+ const metrics = routes.map((points) => routeBudgetMetrics({ routedRelations: points.map((route) => ({ points: route })) }));+ assert.ok(metrics[1].routesOverSuggestedBends < metrics[0].routesOverSuggestedBends);+ assert.ok(metrics[1].maxStretch <= metrics[0].maxStretch);+ const scene = [...routes[0].flat(), ...[...boxes.values()].flatMap((rect) => [[rect.x, rect.y], [rect.x + rect.width, rect.y + rect.height]])];+ for (const [x, y] of routes[1].flat()) {+ assert.ok(x >= Math.min(...scene.map((point) => point[0])) && x <= Math.max(...scene.map((point) => point[0])));+ assert.ok(y >= Math.min(...scene.map((point) => point[1])) && y <= Math.max(...scene.map((point) => point[1])));+ }+ assert.equal(routers[1].routingMetrics().gridSearchCount, routers[0].routingMetrics().gridSearchCount);+ assert.ok(routers[1].routingMetrics().readabilityCandidateCount <= connections.length * 16);+ assert.equal(JSON.stringify({ boxes: [...boxes], connections }), before);+});++test('readability sweep preserves explicit geometry and endpoint-side contracts', () => {+ const { boxes, connections } = fixture();+ connections[0] = { ...connections[0], fromSide: 'right', toSide: 'left', via: [[240, 75]] };+ connections[3] = { ...connections[3], fromSide: 'bottom', toSide: 'top' };+ const routers = [false, true].map((preferReadableRoutes) => createRouter(boxes, connections, {+ distinctAutomaticPorts: true, preferReadableRoutes,+ }));+ assert.deepEqual(routers[1].pathFor(connections[0]), routers[0].pathFor(connections[0]));+ assert.deepEqual(routers[1].connectionSides(connections[3]), { fromSide: 'bottom', toSide: 'top' });+});diff --git a/archify/test/finalize.test.mjs b/archify/test/finalize.test.mjsindex ff721fde..35d9b559 100644--- a/archify/test/finalize.test.mjs+++ b/archify/test/finalize.test.mjs@@ -279,6 +279,19 @@ test('compact success retains route-quality review signals without claiming percassert.equal('visualReviewRecommendation' in uncomplicated, false);});+test('compact success bounds review context and preserves relationship identity', () => {+ const crossings = Array.from({ length: 10 }, (_, index) => ({ left: { id: `edge-${index}` }, right: { id: 'hub' }, point: [index, 50] }));+ const detours = [{ relationship: { id: 'return', from: 'worker', to: 'api' }, bends: 4, stretch: 1.5 }];+ const compact = compactFinalizeReceipt({ ok: true, stages: { check: { receipt: { composition: {+ metrics: { resolvedCrossovers: 10, routesOverSuggestedBends: 1 }, routeReview: { crossings, detours },+ } } } } });+ assert.deepEqual(compact.visualReviewRecommendation.affectedRoutes, {+ crossings: crossings.slice(0, 8), detours, truncated: true,+ });+ assert.equal(crossings.length, 10, 'compaction does not truncate the full evidence');+ assert.equal(compact.visualReview, 'not-requested');+});+test('compact failure receipts retain diverse actionable subjects without embedding full stage evidence', () => {const diagnostics = Array.from({ length: 20 }, (_, index) => ({code: 'composition/proper-crossing',diff --git a/archify/test/ordinary-model-floor.test.mjs b/archify/test/ordinary-model-floor.test.mjsindex 04731de3..96c83fee 100644--- a/archify/test/ordinary-model-floor.test.mjs+++ b/archify/test/ordinary-model-floor.test.mjs@@ -930,7 +930,7 @@ test('packaged skill puts a bounded ordinary-model path before progressive featu'Do not read its full sidecar or rerun individual commands afterward','A non-zero exit is never success','Do not read `bin/` implementation',- 'not prose coordinate exploration or whole-candidate replacement',+ 'reposition those nodes and their neighbors together','After the edit, rerun the complete `finalize` command from step 4 once',]) {assert.match(diff --git a/archify/test/render-output-checks.test.mjs b/archify/test/render-output-checks.test.mjsindex 26ff2b0d..4db7a82d 100644--- a/archify/test/render-output-checks.test.mjs+++ b/archify/test/render-output-checks.test.mjs@@ -629,6 +629,13 @@ test('render output check: independent shared-endpoint crossings still recommendassert.equal(result.composition.metrics.routesOverSuggestedStretch, 0);const summary = compactFinalizeReceipt({ ok: true, stages: { check: { receipt: result } } });assert.deepEqual(summary.visualReviewRecommendation.signals, { resolvedCrossovers: 1 });+ const affected = summary.visualReviewRecommendation.affectedRoutes;+ assert.equal(affected.crossings.length, 1);+ assert.equal(affected.crossings[0].left.id, 'first');+ assert.equal(affected.crossings[0].right.id, 'second');+ assert.deepEqual(affected.crossings[0].point, [120, 80]);+ assert.deepEqual(affected.detours, []);+ assert.equal(affected.truncated, false);assert.equal(summary.visualReview, 'not-requested');// A legacy/authored shared junction must keep its existing interpretation.for (const preserved of [diff --git a/docs/gallery.html b/docs/gallery.htmlindex 3dab589a..000be77a 100644--- a/docs/gallery.html+++ b/docs/gallery.html@@ -754,6 +754,23 @@ receipt 99 checks / 11 artifacts / deterministic hashes</pre>"segmentPx": 16,"microSegmentPx": 8},+ "routeReview": {+ "crossings": [],+ "detours": [+ {+ "relationship": {+ "id": "approval-check",+ "from": "router",+ "to": "approval",+ "label": "needs approval?",+ "collectionIndex": 0,+ "artifactIndex": 1+ },+ "bends": 3,+ "stretch": 1.184+ }+ ]+ },"desktopReadability": {"budgetBasis": "legacy-930","readerContract": "declared-wide-v1",@@ -876,6 +893,10 @@ receipt 99 checks / 11 artifacts / deterministic hashes</pre>"segmentPx": 16,"microSegmentPx": 8},+ "routeReview": {+ "crossings": [],+ "detours": []+ },"desktopReadability": {"budgetBasis": "recognized-declared-wide","readerContract": "declared-wide-v1",@@ -1003,6 +1024,10 @@ receipt 99 checks / 11 artifacts / deterministic hashes</pre>"segmentPx": 16,"microSegmentPx": 8},+ "routeReview": {+ "crossings": [],+ "detours": []+ },"desktopReadability": {"budgetBasis": "legacy-930","readerContract": "declared-wide-v1",@@ -1125,6 +1150,10 @@ receipt 99 checks / 11 artifacts / deterministic hashes</pre>"segmentPx": 16,"microSegmentPx": 8},+ "routeReview": {+ "crossings": [],+ "detours": []+ },"desktopReadability": {"budgetBasis": "legacy-930","readerContract": "declared-wide-v1",@@ -1265,6 +1294,44 @@ receipt 99 checks / 11 artifacts / deterministic hashes</pre>"segmentPx": 16,"microSegmentPx": 8},+ "routeReview": {+ "crossings": [],+ "detours": [+ {+ "relationship": {+ "from": "page",+ "to": "triage",+ "label": "",+ "collectionIndex": 1,+ "artifactIndex": 2+ },+ "bends": 2,+ "stretch": 1.8+ },+ {+ "relationship": {+ "from": "contain",+ "to": "recover",+ "label": "",+ "collectionIndex": 3,+ "artifactIndex": 4+ },+ "bends": 2,+ "stretch": 1.914+ },+ {+ "relationship": {+ "from": "declare",+ "to": "update",+ "label": "",+ "collectionIndex": 7,+ "artifactIndex": 8+ },+ "bends": 3,+ "stretch": 3.465+ }+ ]+ },"desktopReadability": {"budgetBasis": "legacy-930","readerContract": "declared-wide-v1",@@ -1405,6 +1472,23 @@ receipt 99 checks / 11 artifacts / deterministic hashes</pre>"segmentPx": 16,"microSegmentPx": 8},+ "routeReview": {+ "crossings": [],+ "detours": [+ {+ "relationship": {+ "id": "consent-enrichment",+ "from": "edge",+ "to": "consent",+ "label": "identity + consent",+ "collectionIndex": 2,+ "artifactIndex": 3+ },+ "bends": 3,+ "stretch": 1.369+ }+ ]+ },"desktopReadability": {"budgetBasis": "legacy-930","readerContract": "declared-wide-v1",@@ -1527,6 +1611,10 @@ receipt 99 checks / 11 artifacts / deterministic hashes</pre>"segmentPx": 16,"microSegmentPx": 8},+ "routeReview": {+ "crossings": [],+ "detours": []+ },"desktopReadability": {"budgetBasis": "legacy-930","readerContract": "declared-wide-v1",@@ -1667,6 +1755,22 @@ receipt 99 checks / 11 artifacts / deterministic hashes</pre>"segmentPx": 16,"microSegmentPx": 8},+ "routeReview": {+ "crossings": [],+ "detours": [+ {+ "relationship": {+ "from": "validate",+ "to": "dlq",+ "label": "invalid event",+ "collectionIndex": 8,+ "artifactIndex": 9+ },+ "bends": 4,+ "stretch": 2.663+ }+ ]+ },"desktopReadability": {"budgetBasis": "legacy-930","readerContract": "declared-wide-v1",@@ -1807,6 +1911,35 @@ receipt 99 checks / 11 artifacts / deterministic hashes</pre>"segmentPx": 16,"microSegmentPx": 8},+ "routeReview": {+ "crossings": [],+ "detours": [+ {+ "relationship": {+ "id": "failed-retry",+ "from": "failed",+ "to": "executing",+ "label": "",+ "collectionIndex": 3,+ "artifactIndex": 5+ },+ "bends": 3,+ "stretch": 3.267+ },+ {+ "relationship": {+ "id": "approval-cancelled",+ "from": "approval",+ "to": "cancelled",+ "label": "",+ "collectionIndex": 5,+ "artifactIndex": 7+ },+ "bends": 3,+ "stretch": 2.368+ }+ ]+ },"desktopReadability": {"budgetBasis": "legacy-930","readerContract": "declared-wide-v1",@@ -1929,6 +2062,10 @@ receipt 99 checks / 11 artifacts / deterministic hashes</pre>"segmentPx": 16,"microSegmentPx": 8},+ "routeReview": {+ "crossings": [],+ "detours": []+ },"desktopReadability": {"budgetBasis": "legacy-930","readerContract": "declared-wide-v1",@@ -2069,6 +2206,23 @@ receipt 99 checks / 11 artifacts / deterministic hashes</pre>"segmentPx": 16,"microSegmentPx": 8},+ "routeReview": {+ "crossings": [],+ "detours": [+ {+ "relationship": {+ "id": "jwt-verification",+ "from": "auth",+ "to": "api",+ "label": "verify JWT",+ "collectionIndex": 1,+ "artifactIndex": 2+ },+ "bends": 3,+ "stretch": 1+ }+ ]+ },"desktopReadability": {"budgetBasis": "recognized-declared-wide","readerContract": "declared-wide-v1",diff --git a/docs/gallery/manifest.json b/docs/gallery/manifest.jsonindex 757ec93e..ddbf8902 100644--- a/docs/gallery/manifest.json+++ b/docs/gallery/manifest.json@@ -106,6 +106,23 @@"segmentPx": 16,"microSegmentPx": 8},+ "routeReview": {+ "crossings": [],+ "detours": [+ {+ "relationship": {+ "id": "approval-check",+ "from": "router",+ "to": "approval",+ "label": "needs approval?",+ "collectionIndex": 0,+ "artifactIndex": 1+ },+ "bends": 3,+ "stretch": 1.184+ }+ ]+ },"desktopReadability": {"budgetBasis": "legacy-930","readerContract": "declared-wide-v1",@@ -228,6 +245,10 @@"segmentPx": 16,"microSegmentPx": 8},+ "routeReview": {+ "crossings": [],+ "detours": []+ },"desktopReadability": {"budgetBasis": "recognized-declared-wide","readerContract": "declared-wide-v1",@@ -355,6 +376,10 @@"segmentPx": 16,"microSegmentPx": 8},+ "routeReview": {+ "crossings": [],+ "detours": []+ },"desktopReadability": {"budgetBasis": "legacy-930","readerContract": "declared-wide-v1",@@ -477,6 +502,10 @@"segmentPx": 16,"microSegmentPx": 8},+ "routeReview": {+ "crossings": [],+ "detours": []+ },"desktopReadability": {"budgetBasis": "legacy-930","readerContract": "declared-wide-v1",@@ -617,6 +646,44 @@"segmentPx": 16,"microSegmentPx": 8},+ "routeReview": {+ "crossings": [],+ "detours": [+ {+ "relationship": {+ "from": "page",+ "to": "triage",+ "label": "",+ "collectionIndex": 1,+ "artifactIndex": 2+ },+ "bends": 2,+ "stretch": 1.8+ },+ {+ "relationship": {+ "from": "contain",+ "to": "recover",+ "label": "",+ "collectionIndex": 3,+ "artifactIndex": 4+ },+ "bends": 2,+ "stretch": 1.914+ },+ {+ "relationship": {+ "from": "declare",+ "to": "update",+ "label": "",+ "collectionIndex": 7,+ "artifactIndex": 8+ },+ "bends": 3,+ "stretch": 3.465+ }+ ]+ },"desktopReadability": {"budgetBasis": "legacy-930","readerContract": "declared-wide-v1",@@ -757,6 +824,23 @@"segmentPx": 16,"microSegmentPx": 8},+ "routeReview": {+ "crossings": [],+ "detours": [+ {+ "relationship": {+ "id": "consent-enrichment",+ "from": "edge",+ "to": "consent",+ "label": "identity + consent",+ "collectionIndex": 2,+ "artifactIndex": 3+ },+ "bends": 3,+ "stretch": 1.369+ }+ ]+ },"desktopReadability": {"budgetBasis": "legacy-930","readerContract": "declared-wide-v1",@@ -879,6 +963,10 @@"segmentPx": 16,"microSegmentPx": 8},+ "routeReview": {+ "crossings": [],+ "detours": []+ },"desktopReadability": {"budgetBasis": "legacy-930","readerContract": "declared-wide-v1",@@ -1019,6 +1107,22 @@"segmentPx": 16,"microSegmentPx": 8},+ "routeReview": {+ "crossings": [],+ "detours": [+ {+ "relationship": {+ "from": "validate",+ "to": "dlq",+ "label": "invalid event",+ "collectionIndex": 8,+ "artifactIndex": 9+ },+ "bends": 4,+ "stretch": 2.663+ }+ ]+ },"desktopReadability": {"budgetBasis": "legacy-930","readerContract": "declared-wide-v1",@@ -1159,6 +1263,35 @@"segmentPx": 16,"microSegmentPx": 8},+ "routeReview": {+ "crossings": [],+ "detours": [+ {+ "relationship": {+ "id": "failed-retry",+ "from": "failed",+ "to": "executing",+ "label": "",+ "collectionIndex": 3,+ "artifactIndex": 5+ },+ "bends": 3,+ "stretch": 3.267+ },+ {+ "relationship": {+ "id": "approval-cancelled",+ "from": "approval",+ "to": "cancelled",+ "label": "",+ "collectionIndex": 5,+ "artifactIndex": 7+ },+ "bends": 3,+ "stretch": 2.368+ }+ ]+ },"desktopReadability": {"budgetBasis": "legacy-930","readerContract": "declared-wide-v1",@@ -1281,6 +1414,10 @@"segmentPx": 16,"microSegmentPx": 8},+ "routeReview": {+ "crossings": [],+ "detours": []+ },"desktopReadability": {"budgetBasis": "legacy-930","readerContract": "declared-wide-v1",@@ -1421,6 +1558,23 @@"segmentPx": 16,"microSegmentPx": 8},+ "routeReview": {+ "crossings": [],+ "detours": [+ {+ "relationship": {+ "id": "jwt-verification",+ "from": "auth",+ "to": "api",+ "label": "verify JWT",+ "collectionIndex": 1,+ "artifactIndex": 2+ },+ "bends": 3,+ "stretch": 1+ }+ ]+ },"desktopReadability": {"budgetBasis": "recognized-declared-wide","readerContract": "declared-wide-v1",