Skip to content

HK-hub/AgentSkills / archify

archify

Flagged

Create polished, validated architecture, workflow, sequence, data-flow, and lifecycle/state diagrams as explorable standalone HTML with inline SVG, dark/light themes, semantic navigation, optional trace motion, an optional 1200×630 Share Card PNG, and PNG/JPEG/WebP/SVG/WebM export. Accept plain-language requirements or pasted Mermaid flowchart, sequenceDiagram, and stateDiagram input; inspect repository evidence when the diagram must reflect real code. Use when the user asks to visualize system architecture, infrastructure, cloud/security/network topology, technical workflows, approval or CI/CD flows, API call sequences, request lifecycles, data pipelines, ETL/ELT, data lineage, state machines, or to convert/beautify Mermaid. Prefer typed JSON IR renderers and deterministic validation; deliver static output by default, enable motion only when requested, and use optional post-commit opening only for an interactive local handoff.

FileKindSize
LICENSEother1.1 KB
SKILL.mdskill md70.7 KB
assets/template.htmlother585.9 KB
bin/archify.mjsscript47.6 KB
bin/open-artifact.mjsscript2.2 KB
bin/preview.mjsscript23.5 KB
delta/architecture-delta.mjsscript68.8 KB
examples/agent-run.lifecycle.jsonconfig4.3 KB
examples/agent-tool-call.workflow.jsonconfig6.3 KB
examples/async-job-roundtrip.sequence.jsonconfig4.4 KB
examples/cache-miss-request.sequence.jsonconfig4.3 KB
examples/checkout-platform.base.architecture.jsonconfig2.3 KB
examples/checkout-platform.head.architecture.jsonconfig2.4 KB
examples/dataflow-product-analytics.htmlother602.5 KB
examples/deployment-release.lifecycle.jsonconfig4.3 KB
examples/event-stream.dataflow.jsonconfig5.4 KB
examples/incident-response.workflow.jsonconfig5.3 KB
examples/lifecycle-agent-run.htmlother595.6 KB
examples/product-analytics.dataflow.jsonconfig5.6 KB
examples/production-deployment.architecture.jsonconfig5.4 KB
examples/release-delivery.workflow.jsonconfig5.1 KB
examples/sequence-cache-miss-request.htmlother598.6 KB
examples/web-app-rendered.htmlother596.6 KB
examples/web-app.architecture.jsonconfig3.8 KB
examples/workflow-agent-tool-call-rendered.htmlother604.8 KB
package-lock.jsonmanifest2.5 KB
package.jsonmanifest1016 B
recipes/scenarios.mjsscript27.2 KB
renderers/architecture/grid.mjsscript2.0 KB
renderers/architecture/render-architecture.mjsscript20.7 KB
renderers/dataflow/README.mdmarkdown3.6 KB
renderers/dataflow/render-dataflow.mjsscript16.9 KB
renderers/lifecycle/README.mdmarkdown4.5 KB
renderers/lifecycle/render-lifecycle.mjsscript20.8 KB
renderers/sequence/README.mdmarkdown3.8 KB
renderers/sequence/render-sequence.mjsscript17.1 KB
renderers/shared/cli.mjsscript9.4 KB
renderers/shared/diagnostics.mjsscript4.0 KB
renderers/shared/engineering-profiles.mjsscript6.8 KB
renderers/shared/generated-validators.mjsscript278.4 KB
renderers/shared/geometry.mjsscript44.0 KB
renderers/shared/layout-report.mjsscript1015 B
renderers/shared/repository-evidence.mjsscript11.2 KB
renderers/shared/utils.mjsscript8.1 KB
renderers/shared/validator.mjsscript3.4 KB
renderers/workflow/README.mdmarkdown4.9 KB
renderers/workflow/render-workflow.mjsscript25.2 KB
schemas/README.mdmarkdown6.6 KB
schemas/architecture.schema.jsonconfig5.5 KB
schemas/common.schema.jsonconfig1.7 KB
schemas/dataflow.schema.jsonconfig5.1 KB
schemas/lifecycle.schema.jsonconfig5.5 KB
schemas/sequence.schema.jsonconfig4.3 KB
schemas/workflow.schema.jsonconfig7.4 KB
scripts/check-render-output.mjsscript28.8 KB
scripts/generate-validators.mjsscript2.3 KB
scripts/render-examples.mjsscript1.2 KB
test/animation.test.mjsscript8.2 KB
test/architecture-delta.test.mjsscript22.2 KB
test/authored-reachability.test.mjsscript4.4 KB
test/automatic-port-spread.test.mjsscript8.7 KB
test/chapter-delta-preview.test.mjsscript7.3 KB
test/chapter-handoff.test.mjsscript4.9 KB
test/chapter-rail.test.mjsscript4.2 KB
test/cli.test.mjsscript27.4 KB
test/cursor-onboarding.test.mjsscript3.5 KB
test/degraded.test.mjsscript6.8 KB
test/delivery-contract.test.mjsscript1.5 KB
test/diagram-guide.test.mjsscript4.7 KB
test/engineering-profile.test.mjsscript10.0 KB
test/finder.test.mjsscript5.3 KB
test/fixtures/v1-baseline/agent-run.lifecycle.jsonconfig3.5 KB
test/fixtures/v1-baseline/agent-tool-call.workflow.jsonconfig5.2 KB
test/fixtures/v1-baseline/cache-miss-request.sequence.jsonconfig3.5 KB
test/fixtures/v1-baseline/product-analytics.dataflow.jsonconfig4.7 KB
test/fixtures/v1-baseline/web-app.architecture.jsonconfig3.0 KB
test/gallery.test.mjsscript6.2 KB
test/generate-validators.test.mjsscript1.4 KB
test/geometry.test.mjsscript25.5 KB
test/golden.mjsscript8.0 KB
test/grid.test.mjsscript1.7 KB
test/guide-page.test.mjsscript2.0 KB
test/guide.test.mjsscript3.3 KB
test/guided-views.test.mjsscript7.3 KB
test/intent-trace.test.mjsscript4.8 KB
test/landing.test.mjsscript5.4 KB
test/layout-rules.test.mjsscript23.8 KB
test/motion-governor.test.mjsscript6.3 KB
test/open-artifact.test.mjsscript3.1 KB
test/presentation.test.mjsscript3.2 KB
test/preset-tryon.test.mjsscript4.7 KB
test/preview-contract.test.mjsscript2.0 KB
test/preview.test.mjsscript21.9 KB
test/proof-aperture.test.mjsscript4.5 KB
test/reach-share-card.test.mjsscript8.1 KB
test/readme-showcase.test.mjsscript8.9 KB
test/real-repository-proof.test.mjsscript5.1 KB
test/relationship-direct-explorer.test.mjsscript6.2 KB
test/relationship-lens.test.mjsscript7.0 KB
test/relationship-permalink.test.mjsscript6.3 KB
test/relationship-pulse.test.mjsscript6.6 KB
test/render-output-checks.test.mjsscript21.2 KB
test/repair-receipt.test.mjsscript6.7 KB
test/repository-evidence.test.mjsscript9.1 KB
test/route-journey.test.mjsscript8.0 KB
test/route-probe.test.mjsscript6.1 KB
test/route-share-card.test.mjsscript9.5 KB
test/semantic-camera.test.mjsscript4.7 KB
test/semantic-flow.test.mjsscript4.7 KB
test/semantic-legend-gateway.test.mjsscript6.1 KB
test/semantic-lens.test.mjsscript5.4 KB
test/semantic-passport.test.mjsscript5.6 KB
test/semantic-radar.test.mjsscript5.5 KB
test/semantic-zoom.test.mjsscript4.2 KB
test/settled-flow.test.mjsscript5.2 KB
test/share-card-export.test.mjsscript6.8 KB
test/skill-metadata.test.mjsscript1.2 KB
test/start-page.test.mjsscript4.5 KB
test/story-beat-navigator.test.mjsscript6.4 KB
test/story-carrier.test.mjsscript4.7 KB
test/story-director-strip.test.mjsscript5.2 KB
test/story-follow-camera.test.mjsscript5.8 KB
test/story-horizon.test.mjsscript5.2 KB
test/story-moment-link.test.mjsscript5.5 KB
test/story-shelf.test.mjsscript4.7 KB
test/story-trail.test.mjsscript4.1 KB
test/v1-compatibility.test.mjsscript6.1 KB
test/webm-artifact.smoke.mjsscript83.3 KB

renderers/architecture/render-architecture.mjs

View on GitHub
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { esc, renderDefinitions, renderSemanticSigil, textUnits } from '../shared/utils.mjs';
import { animateAttr, focusEdgeAttrs, focusNodeAttrs, focusNodeTitle, loadDiagram, writeDiagram, svgAccessibleText, svgRootAttrs } from '../shared/cli.mjs';
import { componentBox, boundaryBox, connectionPath } from '../shared/layout-report.mjs';
import { throwDiagnosticProblems } from '../shared/diagnostics.mjs';
import { gridLayout, resolveComponentPos, validateGridPlacement } from './grid.mjs';
import {
  asArray,
  isFinitePoint,
  rectsOverlap,
  segmentIntersectsRect,
  cleanFlowProblems,
  cleanCrossingProblems,
  cleanAmbiguousCorridorProblems,
  cleanBorderRunProblems,
  cleanRouteRhythmProblems,
  cleanLabelRouteClearanceProblems,
  suggestLabelObstacleFix,
  suggestComponentSeparation,
  anchor,
  automaticPortSpread,
  defaultFromSide,
  defaultToSide,
  chosenSide,
  polylinePath,
  routePointsValue,
  roundedPath,
  labelPoint,
  componentFill,
  componentText,
  arrowClassMap,
  variantAccent,
} from '../shared/geometry.mjs';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const layoutJsonMode = process.argv.includes('--layout-json');
const cliArgs = process.argv.filter((arg) => arg !== '--layout-json');
const { diagram: arch, template, outPath, sourceEvidence } = loadDiagram({
  rendererDir: __dirname,
  diagramType: 'architecture',
  defaultExample: 'web-app.architecture.json',
  argv: cliArgs,
});

const grid = gridLayout(arch);

const layout = {
  defaultW: 120,
  defaultH: 60,
  margin: 40,
  // Boundary padding — the 30/50 rule that was a hand-arithmetic footgun
  // (CHANGELOG v2.2.1): 30px on top/left/right, plus 20px extra at the bottom.
  boundaryPad: 30,
  boundaryExtraBottom: 20,
  legendH: 28,
};

// ---- Measure components from free coordinates --------------------------------
function measureComponent(c) {
  const [x, y] = resolveComponentPos(c, grid);
  const [w, h] = Array.isArray(c.size) ? c.size : [layout.defaultW, layout.defaultH];
  return { ...c, x, y, width: w, height: h, cx: x + w / 2, cy: y + h / 2 };
}

const components = new Map(asArray(arch.components).map((c) => [c.id, measureComponent(c)]));
const componentSteps = new Map();
for (const [index, conn] of asArray(arch.connections).entries()) {
  if (!componentSteps.has(conn.from)) componentSteps.set(conn.from, index);
  if (!componentSteps.has(conn.to)) componentSteps.set(conn.to, index + 1);
}
for (const [index, c] of asArray(arch.components).entries()) {
  if (!componentSteps.has(c.id)) componentSteps.set(c.id, index);
}

// ---- Boundaries computed from the `wraps` id list ---------------------------
function boundaryRect(boundary) {
  const members = asArray(boundary.wraps).map((id) => components.get(id)).filter(Boolean);
  if (!members.length) return null;
  const minX = Math.min(...members.map((m) => m.x));
  const minY = Math.min(...members.map((m) => m.y));
  const maxX = Math.max(...members.map((m) => m.x + m.width));
  const maxY = Math.max(...members.map((m) => m.y + m.height));
  const pad = boundary.pad ?? layout.boundaryPad;
  return {
    ...boundary,
    x: minX - pad,
    y: minY - pad,
    width: maxX - minX + pad * 2,
    height: maxY - minY + pad + layout.boundaryExtraBottom,
  };
}

const boundaries = asArray(arch.boundaries).map(boundaryRect).filter(Boolean);
const compositionFrames = boundaries.map((boundary, index) => ({
  ...boundary,
  id: boundary.id || index,
  kind: boundary.kind || 'boundary',
  radius: boundary.kind === 'security-group' ? 8 : 12,
}));

function componentContext(component) {
  const scopes = boundaries
    .filter((boundary) => asArray(boundary.wraps).includes(component.id))
    .sort((a, b) => (b.width * b.height) - (a.width * a.height))
    .map((boundary) => boundary.label);
  return scopes.length ? scopes.join(' › ') : 'Architecture component';
}

// ---- Auto viewBox: fit all geometry + a legend row --------------------------
function autoViewBox() {
  let maxX = 0;
  let maxY = 0;
  for (const c of components.values()) {
    maxX = Math.max(maxX, c.x + c.width);
    maxY = Math.max(maxY, c.y + c.height);
  }
  for (const b of boundaries) {
    maxX = Math.max(maxX, b.x + b.width);
    maxY = Math.max(maxY, b.y + b.height);
  }
  return [
    Math.ceil(maxX + layout.margin),
    Math.ceil(maxY + layout.margin + layout.legendH),
  ];
}

const viewBox = arch.meta?.viewBox || autoViewBox();
const legendY = () => viewBox[1] - 16;

// ---- Validation: mechanical correctness, never layout taste -----------------
function validateArchitecture() {
  const problems = [];
  if (arch.schema_version !== 1) problems.push('Architecture files must set "schema_version": 1.');
  if (arch.diagram_type !== 'architecture') problems.push('Architecture files must set "diagram_type": "architecture".');
  if (!arch.meta?.title) problems.push('Architecture files must include meta.title.');
  if (!Array.isArray(arch.components) || arch.components.length < 1) {
    problems.push('Architecture diagrams need at least one component.');
  }
  if (arch.connections !== undefined && !Array.isArray(arch.connections)) problems.push('Architecture "connections" must be an array.');
  if (arch.boundaries !== undefined && !Array.isArray(arch.boundaries)) problems.push('Architecture "boundaries" must be an array.');
  if (arch.cards !== undefined && !Array.isArray(arch.cards)) problems.push('Architecture "cards" must be an array.');
  if (components.size !== asArray(arch.components).length) problems.push('Component ids must be unique.');
  if (grid) {
    validateGridPlacement(arch, grid, problems);
  } else {
    for (const c of asArray(arch.components)) {
      if (!Array.isArray(c.pos) || c.pos.length !== 2) {
        problems.push(`Component "${c.id}" must include pos [x, y] when layout.mode is omitted (free placement).`);
      }
    }
  }

  for (const c of components.values()) {
    if (!isFinitePoint(c.x, c.y, c.width, c.height)) {
      problems.push(`Component "${c.id}" has non-finite pos/size — pos and size must be [number, number].`);
      continue;
    }
    if (c.width <= 0 || c.height <= 0) {
      problems.push(`Component "${c.id}" has invalid size ${c.width}x${c.height} — width and height must be greater than 0.`);
      continue;
    }
    if (c.x < 0 || c.y < 0 || c.x + c.width > viewBox[0] || c.y + c.height > viewBox[1]) {
      problems.push(`Component "${c.id}" falls outside the viewBox ${viewBox[0]}x${viewBox[1]} — adjust pos/size or set a larger meta.viewBox.`);
    }
    const estLabelW = textUnits(c.label) * 6.6;
    if (estLabelW > c.width + 8) {
      problems.push(`Label "${c.label}" (~${Math.round(estLabelW)}px) is wider than component "${c.id}" (${c.width}px) — shorten the label, move detail to sublabel, or widen size.`);
    }
  }

  // Component overlap — the highest-traffic hand-placement failure mode.
  const list = [...components.values()];
  for (let i = 0; i < list.length; i += 1) {
    for (let j = i + 1; j < list.length; j += 1) {
      if (rectsOverlap(list[i], list[j], 8)) {
        problems.push(`Components "${list[i].id}" and "${list[j].id}" are less than 8px apart — move one or shrink its size.\n${suggestComponentSeparation(list[i], list[j], 8)}`);
      }
    }
  }

  // Boundaries: every wrapped id must exist; the computed box must stay in view.
  for (const boundary of asArray(arch.boundaries)) {
    for (const id of asArray(boundary.wraps)) {
      if (!components.has(id)) problems.push(`Boundary "${boundary.label}" wraps unknown component "${id}".`);
    }
  }
  for (const b of boundaries) {
    if (b.x < 0 || b.y < 0 || b.x + b.width > viewBox[0] || b.y + b.height > viewBox[1]) {
      problems.push(`Boundary "${b.label}" extends outside the viewBox — its members sit too close to the canvas edge; add margin or enlarge meta.viewBox.`);
    }
  }

  for (const conn of asArray(arch.connections)) {
    if (!components.has(conn.from)) problems.push(`Connection "${conn.label || conn.from}" references unknown source "${conn.from}".`);
    if (!components.has(conn.to)) problems.push(`Connection "${conn.label || conn.to}" references unknown target "${conn.to}".`);
    if (components.has(conn.from) && components.has(conn.to)) {
      const routed = pathFor(conn);
      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.`);
    }
  }

  problems.push(...cleanFlowProblems({
    relations: arch.connections,
    endpointIds: new Set(components.keys()),
    obstacles: components.values(),
    pathFor,
    diagramType: 'architecture',
    relationCollection: 'connections',
    obstacleKind: 'component',
    profile: arch.meta?.quality_profile,
    routeHint: 'adjust fromSide/toSide, set route/via, or move the component'
  }));
  problems.push(...cleanCrossingProblems({
    relations: arch.connections,
    endpointIds: new Set(components.keys()),
    pathFor,
    diagramType: 'architecture',
    relationCollection: 'connections',
    profile: arch.meta?.quality_profile,
    routeHint: 'adjust route/via or fromSide/toSide so the connections use separate corridors'
  }));
  problems.push(...cleanAmbiguousCorridorProblems({
    relations: arch.connections,
    endpointIds: new Set(components.keys()),
    pathFor,
    diagramType: 'architecture',
    relationCollection: 'connections',
    profile: arch.meta?.quality_profile,
    routeHint: 'adjust route/via or fromSide/toSide so unrelated connections do not visually merge'
  }));
  problems.push(...cleanBorderRunProblems({
    relations: arch.connections,
    endpointIds: new Set(components.keys()),
    frames: compositionFrames,
    pathFor,
    diagramType: 'architecture',
    relationCollection: 'connections',
    profile: arch.meta?.quality_profile,
    routeHint: 'adjust route/via or fromSide/toSide so the connection crosses the boundary perpendicularly instead of following its border'
  }));
  problems.push(...cleanRouteRhythmProblems({
    relations: arch.connections,
    endpointIds: new Set(components.keys()),
    pathFor,
    diagramType: 'architecture',
    relationCollection: 'connections',
    profile: arch.meta?.quality_profile,
    routeHint: 'move route/via points into a wider corridor or move the component so every turn has room to read'
  }));

  // Connection labels must not land on top of components.
  const labelRects = [];
  for (const [connectionIndex, conn] of asArray(arch.connections).entries()) {
    if (!conn.label || !components.has(conn.from) || !components.has(conn.to)) continue;
    const [lx, ly] = labelPoint(conn, pathFor(conn).points);
    const w = Math.max(30, textUnits(conn.label) * 4.8 + 10);
    labelRects.push({ relation: conn, relationIndex: connectionIndex, label: conn.label, x: lx - w / 2, y: ly - 10, width: w, height: 14, lx, ly });
  }
  for (const rect of labelRects) {
    for (const c of components.values()) {
      if (rectsOverlap(rect, c, -2)) {
        problems.push(`Label "${rect.label}" overlaps component "${c.id}" — adjust labelDx/labelDy/labelSegment or set labelAt.\n${suggestLabelObstacleFix(rect, rect.lx, rect.ly, c)}`);
      }
    }
  }
  problems.push(...cleanLabelRouteClearanceProblems({
    relations: arch.connections,
    labels: labelRects,
    endpointIds: new Set(components.keys()),
    pathFor,
    diagramType: 'architecture',
    relationCollection: 'connections',
    profile: arch.meta?.quality_profile,
  }));

  if (problems.length) {
    throwDiagnosticProblems('Architecture layout validation failed', problems, {
      subject: { diagramType: 'architecture' },
    });
  }
}

function buildLayoutReport() {
  const labels = [];
  for (const conn of asArray(arch.connections)) {
    if (!conn.label || !components.has(conn.from) || !components.has(conn.to)) continue;
    const [lx, ly] = labelPoint(conn, pathFor(conn).points);
    const w = Math.max(30, textUnits(conn.label) * 4.8 + 10);
    labels.push({
      text: conn.label,
      x: Math.round(lx - w / 2),
      y: Math.round(ly - 10),
      width: Math.round(w),
      height: 14,
      labelAt: [Math.round(lx), Math.round(ly)],
    });
  }
  return {
    ok: true,
    diagram_type: 'architecture',
    layout: grid ? { mode: 'grid', ...grid } : { mode: 'free' },
    viewBox,
    components: [...components.values()].map(componentBox),
    boundaries: boundaries.map(boundaryBox),
    connections: asArray(arch.connections)
      .filter((conn) => components.has(conn.from) && components.has(conn.to))
      .map((conn) => {
        const routed = pathFor(conn);
        const labelAt = conn.label ? labelPoint(conn, routed.points) : null;
        return connectionPath(conn, routed, labelAt);
      }),
    labels,
  };
}

// ---- Connection routing ------------------------------------------------------
function routeClearsComponents(conn, points, clearance = 2) {
  const endpointIds = new Set([conn.from, conn.to]);
  for (const component of components.values()) {
    if (endpointIds.has(component.id)) continue;
    for (let index = 0; index < points.length - 1; index += 1) {
      if (segmentIntersectsRect({ start: points[index], end: points[index + 1] }, component, clearance)) {
        return false;
      }
    }
  }
  return true;
}

function routeVia(conn, from, to, start, end) {
  if (conn.via) return conn.via;
  switch (conn.route || 'auto') {
    case 'straight':
      return [];
    case 'orthogonal-h': {
      const midX = (start[0] + end[0]) / 2;
      return [[midX, start[1]], [midX, end[1]]];
    }
    case 'orthogonal-v': {
      const midY = (start[1] + end[1]) / 2;
      return [[start[0], midY], [end[0], midY]];
    }
    case 'auto':
    default: {
      // Direct line unless the anchors are clearly orthogonal-friendly.
      if (Math.abs(start[0] - end[0]) < 4 || Math.abs(start[1] - end[1]) < 4) return [];
      const midX = (start[0] + end[0]) / 2;
      const horizontalFirst = [[midX, start[1]], [midX, end[1]]];
      if (routeClearsComponents(conn, [start, ...horizontalFirst, end])) return horizontalFirst;

      // The only fallback is the complementary in-bounds dogleg. Both
      // candidates stay between the authored anchors, preserve two bends, and
      // remain deterministic. If neither is safe, keep the original route so
      // the universal Clean Flow gate returns the actionable hard failure.
      const midY = (start[1] + end[1]) / 2;
      const verticalFirst = [[start[0], midY], [end[0], midY]];
      if (routeClearsComponents(conn, [start, ...verticalFirst, end])) return verticalFirst;
      return horizontalFirst;
    }
  }
}

const pathCache = new Map();
const automaticPorts = automaticPortSpread(arch.connections, components);
function pathFor(conn) {
  if (pathCache.has(conn)) return pathCache.get(conn);
  const from = components.get(conn.from);
  const to = components.get(conn.to);
  const ports = automaticPorts.get(conn);
  const start = ports?.from || anchor(from, chosenSide(conn.fromSide, defaultFromSide(from, to)));
  const end = ports?.to || anchor(to, chosenSide(conn.toSide, defaultToSide(from, to)));
  const points = [start, ...routeVia(conn, from, to, start, end), end];
  const routed = { d: roundedPath(points, 8), points };
  pathCache.set(conn, routed);
  return routed;
}

// ---- Rendering ---------------------------------------------------------------
function renderBoundary(b, index) {
  const cls = b.kind === 'security-group' ? 'c-security-group' : 'c-region';
  const labelCls = b.kind === 'security-group' ? 't-security' : 't-cloud';
  const rx = b.kind === 'security-group' ? 8 : 12;
  return `        <rect data-graph-role="structural-frame" data-composition-frame-kind="${esc(b.kind || 'boundary')}" data-composition-frame-id="${index}" x="${b.x}" y="${b.y}" width="${b.width}" height="${b.height}" rx="${rx}" class="${cls}" stroke-width="1"/>
        <text x="${b.x + 8}" y="${b.y + 18}" class="${labelCls}" font-size="9" font-weight="600">${esc(b.label)}</text>`;
}

function renderConnectionPath(conn, index) {
  const [cls, marker] = arrowClassMap[conn.variant || 'default'] || arrowClassMap.default;
  const routed = pathFor(conn);
  const strokeWidth = conn.width || (conn.variant === 'emphasis' ? 1.8 : 1.5);
  return `        <path ${focusEdgeAttrs(conn.from, conn.to, conn.label, index, conn.id)} data-composition-points="${routePointsValue(routed.points)}" d="${routed.d}" class="${cls}"${animateAttr(arch.meta, 'edge', index)} stroke-width="${strokeWidth}" marker-end="url(#${marker})"/>`;
}

function renderConnectionLabel(conn, index) {
  if (!conn.label) return '';
  const [lx, ly] = labelPoint(conn, pathFor(conn).points);
  const w = Math.max(30, textUnits(conn.label) * 4.8 + 10);
  return `        <g data-detail="context" ${focusEdgeAttrs(conn.from, conn.to, conn.label, index, conn.id)}>
          <rect x="${lx - w / 2}" y="${ly - 10}" width="${w}" height="14" rx="3" class="c-mask"/>
          <text x="${lx}" y="${ly}" class="${variantAccent(conn.variant)}" font-size="8" text-anchor="middle">${esc(conn.label)}</text>
        </g>`;
}

function renderComponent(c) {
  const fill = componentFill[c.type] || 'c-external';
  const accent = componentText[c.type] || 't-muted';
  const cx = c.cx;
  const hasSub = c.sublabel != null && c.sublabel !== '';
  const labelY = hasSub ? c.y + c.height / 2 - 2 : c.y + c.height / 2 + 4;
  const sub = hasSub
    ? `\n        <text data-detail="context" x="${cx}" y="${c.y + c.height / 2 + 14}" class="t-muted" font-size="9" text-anchor="middle">${esc(c.sublabel)}</text>`
    : '';
  const tag = c.tag
    ? `\n        <text data-detail="fine" x="${cx}" y="${c.y + c.height - 8}" class="${accent}" font-size="7" text-anchor="middle">${esc(c.tag)}</text>`
    : '';
  const passport = { kind: c.type, sublabel: c.sublabel, tag: c.tag, context: componentContext(c) };
  return `        <g ${focusNodeAttrs(c.id, c.label, passport)}>
          ${focusNodeTitle(c.label, passport)}
          <rect x="${c.x}" y="${c.y}" width="${c.width}" height="${c.height}" rx="6" class="c-mask"/>
          <rect x="${c.x}" y="${c.y}" width="${c.width}" height="${c.height}" rx="6" class="${fill}"${animateAttr(arch.meta, 'node', componentSteps.get(c.id))} stroke-width="1.5"/>
          ${renderSemanticSigil(c.type, { x: c.x + 6, y: c.y + 6 })}
          <text${hasSub ? ' data-detail-anchor' : ''} x="${cx}" y="${labelY}" class="t-primary" font-size="11" font-weight="600" text-anchor="middle">${esc(c.label)}</text>${sub}${tag}
        </g>`;
}

// Auto legend: one swatch per component type actually used, left to right.
const TYPE_LABELS = {
  frontend: 'Frontend', backend: 'Backend', database: 'Database', cloud: 'Cloud',
  security: 'Security', messagebus: 'Message bus', external: 'External',
};
function renderLegend() {
  const used = [];
  const seen = new Set();
  for (const c of components.values()) {
    if (!seen.has(c.type)) { seen.add(c.type); used.push(c.type); }
  }
  const y = legendY();
  let x = layout.margin;
  const parts = ['        <g data-legend-bridge>',
    `          <text x="${x}" y="${y - 13}" class="t-primary" font-size="9" font-weight="600">Legend</text>`];
  for (const type of used) {
    parts.push(`          <g data-legend-kind="${esc(type)}">`);
    parts.push(`            <rect x="${x}" y="${y - 8}" width="14" height="9" rx="2" class="${componentFill[type] || 'c-external'}" stroke-width="1"/>`);
    parts.push(`            <text x="${x + 20}" y="${y}" class="t-muted" font-size="8">${TYPE_LABELS[type] || type}</text>`);
    parts.push('          </g>');
    x += 30 + (textUnits(TYPE_LABELS[type] || type) * 5 + 34);
  }
  parts.push('        </g>');
  return parts.join('\n');
}

function renderSvg() {
  return `      <svg viewBox="0 0 ${viewBox[0]} ${viewBox[1]}" ${svgRootAttrs(arch.meta, 'architecture diagram')}>
${svgAccessibleText(arch.meta, 'architecture diagram')}
${renderDefinitions()}

        <!-- Background Grid -->
        <rect width="100%" height="100%" fill="url(#grid)" />

        <!-- Boundaries (behind everything) -->
${boundaries.map(renderBoundary).join('\n\n')}

        <!-- Connection paths (before components for correct z-order) -->
${asArray(arch.connections).map(renderConnectionPath).join('\n')}

        <!-- Components -->
${[...components.values()].map(renderComponent).join('\n\n')}

        <!-- Connection labels -->
${asArray(arch.connections).map(renderConnectionLabel).join('\n')}

        <!-- Legend -->
${renderLegend()}
      </svg>`;
}

validateArchitecture();
if (layoutJsonMode) {
  console.log(JSON.stringify(buildLayoutReport(), null, 2));
  process.exit(0);
}
writeDiagram({
  outPath,
  template,
  diagramType: 'architecture',
  meta: arch.meta,
  footerLabel: 'Architecture diagram',
  svg: renderSvg(),
  cards: arch.cards,
  sourceEvidence,
});
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 471kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall