Skip to content

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

97.4 KB
Raw Blame
// Per-rule coverage for the renderers' layout validators. The golden suite's
// negative cases mostly trip ajv SCHEMA rules; this file targets the hand-
// written LAYOUT rules (the `problems.push(...)` checks) — the layer that has
// regressed before — by mutating a valid example into exactly one violation
// and asserting the renderer exits non-zero with the expected message.
//
// It also locks the error-message CONTRACT: representative messages must carry
// both the numeric threshold and a remediation hint, since the consumer is an
// LLM that fixes the JSON from the message alone.
//
//   node --test test/*.test.mjs

import { test } from 'node:test';
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { minimumReadableSourceTextPx } from '../archify/renderers/shared/desktop-readability.mjs';
import { segmentRectClearanceWithin, segmentIntersectsRect } from '../archify/renderers/shared/geometry.mjs';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const skillRoot = path.resolve(__dirname, '..', 'archify');
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-rules-'));

const EXAMPLES = {
  workflow: 'agent-tool-call.workflow.json',
  sequence: 'cache-miss-request.sequence.json',
  dataflow: 'product-analytics.dataflow.json',
  lifecycle: 'agent-run.lifecycle.json',
  architecture: 'web-app.architecture.json',
};

function load(mode) {
  return JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples', EXAMPLES[mode]), 'utf8'));
}

// Returns { code, stderr }. Never throws on non-zero exit.
function render(mode, doc) {
  const input = path.join(tmp, `${mode}-${Math.abs(hash(JSON.stringify(doc)))}.json`);
  const outPath = path.join(tmp, `${mode}-${Math.abs(hash(JSON.stringify(doc)))}.html`);
  const renderDoc = structuredClone(doc);
  renderDoc.meta = { ...renderDoc.meta, output: `${mode}-layout-rules.html` };
  fs.writeFileSync(input, JSON.stringify(renderDoc));
  try {
    execFileSync('node', [
      path.join(skillRoot, `renderers/${mode}/render-${mode}.mjs`),
      input,
      outPath,
    ], { stdio: ['ignore', 'ignore', 'pipe'] });
    return { code: 0, stderr: '', outPath };
  } catch (err) {
    return { code: err.status ?? 1, stderr: String(err.stderr || ''), outPath };
  }
}

function validateCli(mode, doc, quality = 'showcase') {
  const input = path.join(tmp, `${mode}-cli-${Math.abs(hash(JSON.stringify(doc)))}.json`);
  const cliDoc = structuredClone(doc);
  cliDoc.meta = { ...cliDoc.meta, output: `${mode}-validation.html` };
  fs.writeFileSync(input, JSON.stringify(cliDoc));
  try {
    const stdout = execFileSync('node', [
      path.join(skillRoot, 'bin', 'archify.mjs'),
      'validate',
      mode,
      input,
      '--quality',
      quality,
      '--json',
    ], { encoding: 'utf8' });
    return { code: 0, result: JSON.parse(stdout) };
  } catch (err) {
    return {
      code: err.status ?? 1,
      result: JSON.parse(String(err.stdout || '{}')),
    };
  }
}

function deliverCli(mode, doc, quality = 'showcase') {
  const input = path.join(tmp, `${mode}-deliver-${Math.abs(hash(JSON.stringify(doc)))}.json`);
  const outPath = path.join(tmp, `${mode}-deliver-${Math.abs(hash(JSON.stringify(doc)))}.html`);
  const cliDoc = structuredClone(doc);
  cliDoc.meta = { ...cliDoc.meta, output: `${mode}-delivery.html` };
  fs.writeFileSync(input, JSON.stringify(cliDoc));
  try {
    const stdout = execFileSync('node', [
      path.join(skillRoot, 'bin', 'archify.mjs'),
      'deliver',
      mode,
      input,
      outPath,
      '--quality',
      quality,
      '--json',
    ], { encoding: 'utf8' });
    return { code: 0, result: JSON.parse(stdout), outPath };
  } catch (err) {
    return {
      code: err.status ?? 1,
      result: JSON.parse(String(err.stdout || '{}')),
      outPath,
    };
  }
}

function hash(s) {
  let h = 0;
  for (let i = 0; i < s.length; i += 1) h = (h * 31 + s.charCodeAt(i)) | 0;
  return h;
}

function workflowEdgePoints(html, id) {
  const escapedId = id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  const pointsAttribute = html.match(
    new RegExp(`data-edge-id="${escapedId}" data-composition-points="([^"]+)"`),
  )?.[1];
  assert.ok(pointsAttribute, `expected rendered workflow edge points for ${id}`);
  return pointsAttribute.split(';').map((point) => point.split(',').map(Number));
}

function workflowNodeRect(html, id) {
  const escapedId = id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  const match = html.match(new RegExp(
    `<g id="node-${escapedId}"[^>]*>[\\s\\S]*?<rect x="([^"]+)" y="([^"]+)" width="([^"]+)" height="([^"]+)"`,
  ));
  assert.ok(match, `expected rendered workflow node rect for ${id}`);
  const [, x, y, width, height] = match.map(Number);
  return { x, y, width, height };
}

function boundaryFrameRect(html, index) {
  const match = html.match(new RegExp(
    `<rect data-graph-role="structural-frame"[^>]*data-composition-frame-id="${index}"[^>]*x="([^"]+)" y="([^"]+)" width="([^"]+)" height="([^"]+)"`,
  ));
  assert.ok(match, `expected boundary frame ${index}`);
  const [, x, y, width, height] = match.map(Number);
  return { x, y, width, height };
}

function boundaryTitleMasks(html) {
  return [...html.matchAll(
    /<g data-graph-role="structural-frame-label"[^>]*data-composition-frame-id="(\d+)"[^>]*>[\s\S]*?<rect data-graph-role="structural-frame-label-mask" x="([^"]+)" y="([^"]+)" width="([^"]+)" height="([^"]+)"/g,
  )].map((match) => ({
    index: Number(match[1]),
    x: Number(match[2]),
    y: Number(match[3]),
    width: Number(match[4]),
    height: Number(match[5]),
  }));
}

function rectContainsRect(outer, inner) {
  return outer.x <= inner.x
    && outer.y <= inner.y
    && outer.x + outer.width >= inner.x + inner.width
    && outer.y + outer.height >= inner.y + inner.height;
}

function rectanglesOverlap(left, right) {
  return left.x < right.x + right.width
    && left.x + left.width > right.x
    && left.y < right.y + right.height
    && left.y + left.height > right.y;
}

function workflowEdgeLabelPoint(html, id) {
  const escapedId = id.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  const match = html.match(new RegExp(
    `<g data-detail="context"[^>]*data-edge-id="${escapedId}"[^>]*>[\\s\\S]*?<text x="([^"]+)" y="([^"]+)"`,
  ));
  assert.ok(match, `expected rendered workflow edge label for ${id}`);
  return match.slice(1).map(Number);
}

function axisOverlapLength(a1, a2, b1, b2) {
  return Math.max(0, Math.min(Math.max(a1, a2), Math.max(b1, b2))
    - Math.max(Math.min(a1, a2), Math.min(b1, b2)));
}

function workflowNodeBorderOverlap(points, rect) {
  const hits = [];
  for (let index = 0; index < points.length - 1; index += 1) {
    const [start, end] = [points[index], points[index + 1]];
    if (start[0] === end[0] && (start[0] === rect.x || start[0] === rect.x + rect.width)) {
      const length = axisOverlapLength(start[1], end[1], rect.y, rect.y + rect.height);
      if (length > 0) hits.push({ segment: index, length, start, end });
    }
    if (start[1] === end[1] && (start[1] === rect.y || start[1] === rect.y + rect.height)) {
      const length = axisOverlapLength(start[0], end[0], rect.x, rect.x + rect.width);
      if (length > 0) hits.push({ segment: index, length, start, end });
    }
  }
  return hits;
}

function assertRelationshipsAvoidAllNodeBorders(html, relationships, diagramNodes) {
  for (const [edgeIndex, edge] of relationships.entries()) {
    const edgeId = edge.id || `edge-${edgeIndex}`;
    const points = workflowEdgePoints(html, edgeId);
    for (const node of diagramNodes) {
      const hits = workflowNodeBorderOverlap(points, workflowNodeRect(html, node.id));
      assert.deepEqual(
        hits,
        [],
        `workflow edge ${edgeId} runs along node ${node.id} border: ${JSON.stringify(hits)}`,
      );
    }
  }
}

function assertWorkflowEdgesAvoidAllNodeBorders(html, doc) {
  assertRelationshipsAvoidAllNodeBorders(html, doc.edges, doc.nodes);
}

// [name, mode, mutate(doc), expectedSubstrings[]] — every mutation introduces
// exactly one layout violation. Each expected substring must appear in stderr.
const CASES = [
  // ---- workflow layout rules ----
  ['workflow: unknown lane', 'workflow', (d) => { d.nodes[0].lane = 'ghost'; }, ['unknown lane "ghost"']],
  ['workflow: node label wider than box', 'workflow',
    (d) => { d.nodes[0].label = 'An Extremely Long Node Label That Overflows'; }, ['wider than component', 'shorten the label']],
  ['workflow: node sublabel wider than its legible minimum', 'workflow',
    (d) => { d.nodes[0].sublabel = 'This supporting sentence is much too long for one workflow node'; }, ['Sublabel', 'legible', 'increase node.width']],
  ['workflow: node tag wider than its legible minimum', 'workflow',
    (d) => { d.nodes[0].tag = 'This tag is far too long to sit inside one workflow node box'; },
    ['Tag', 'legible', 'increase node.width']],
  ['workflow: viewBox width below schema min', 'workflow',
    (d) => { d.meta.viewBox = [699, 900]; }, ['700']],
  ['workflow: nodes too close in a lane', 'workflow',
    (d) => { d.nodes.push({ ...d.nodes[0], id: 'dupe', col: d.nodes[0].col }); }, ['less than 8px apart']],
  ['workflow: empty group', 'workflow',
    (d) => { d.groups = [{ id: 'empty', label: 'Empty group', lane: 'ui', fromCol: 3, toCol: 4 }]; }, ['does not contain any nodes']],
  ['workflow: mainPath missing edge', 'workflow',
    (d) => { d.mainPath = ['user', 'planner']; }, ['mainPath step "user" -> "planner" has no matching edge']],
  ['workflow: mainPath moves backward', 'workflow',
    (d) => { d.mainPath = ['external', 'trace']; }, ['moves backward from col']],
  ['workflow: phase ranges overlap', 'workflow',
    (d) => { d.phases[2].fromCol = d.phases[1].toCol; }, ['overlaps phase', 'start at col 4 or later']],

  // ---- sequence layout rules ----
  ['sequence: message references unknown participant', 'sequence',
    (d) => { d.messages[0].from = 'ghost'; }, ['unknown source "ghost"']],
  ['sequence: message y outside timeline', 'sequence',
    (d) => { d.messages[0].y = 9000; }, ['outside the readable timeline', 'keep y between']],
  ['sequence: segment to <= from', 'sequence',
    (d) => { d.segments = [{ from: 400, to: 300, label: 'bad' }]; }, ['invalid y range', 'greater than']],
  ['sequence: segment label exceeds segment frame available width', 'sequence',
    (d) => { d.segments[0].label = 'Long Segment Label '.repeat(10); },
    ['exceeds the segment frame\'s available width', 'increase meta.viewBox[0]']],
  ['sequence: participant sublabel wider than its legible minimum', 'sequence',
    (d) => { d.participants[0].sublabel = 'This supporting sentence is far too long for one sequence participant'; },
    ['sequence/participant-sublabel-overflow', 'Sublabel', 'legible', 'shorten the sublabel']],

  // ---- dataflow layout rules ----
  ['dataflow: flow missing label', 'dataflow',
    (d) => { delete d.flows[0].label; }, ['label']],
  ['dataflow: flow references unknown node', 'dataflow',
    (d) => { d.flows[0].to = 'ghost'; }, ['unknown target "ghost"']],
  ['dataflow: explicit via keeps every route segment orthogonal', 'dataflow',
    (d) => {
      d.flows[0].via = [[195, 140], [195, 260]];
    }, ['diagonal segment', 'align via[0]']],
  ['dataflow: node sublabel wider than its legible minimum', 'dataflow',
    (d) => { d.nodes[0].sublabel = 'This supporting sentence is far too long for one data-flow node box'; },
    ['Sublabel', 'legible', 'increase node.width']],
  ['dataflow: node tag wider than its legible minimum', 'dataflow',
    (d) => { d.nodes[0].tag = 'This tag is far too long to sit inside one data-flow node box'; },
    ['Tag', 'legible', 'increase node.width']],

  // ---- lifecycle layout rules ----
  ['lifecycle: mainPath names an unknown state', 'lifecycle',
    (d) => { d.mainPath[1] = 'ghost'; }, ['mainPath[1] "ghost" is not a state']],
  ['lifecycle: mainPath step without a transition', 'lifecycle',
    (d) => { d.transitions = d.transitions.filter((t) => !(t.from === 'planning' && t.to === 'executing')); },
    ['mainPath step "planning" -> "executing" has no transition']],
  ['lifecycle: state sublabel wider than its legible minimum', 'lifecycle',
    (d) => { d.states[0].sublabel = 'This supporting sentence is far too long for one lifecycle state box'; },
    ['Sublabel', 'legible', 'shorten the sublabel']],
  ['lifecycle: state tag wider than its legible minimum', 'lifecycle',
    (d) => { d.states[0].tag = 'This tag is far too long to sit inside one lifecycle state box at all'; },
    ['Tag', 'legible', 'shorten the tag']],

  // ---- architecture layout rules ----
  ['architecture: components overlap', 'architecture',
    (d) => { d.components[1].pos = [...d.components[0].pos]; }, ['less than 8px apart']],
  ['architecture: connection references unknown component', 'architecture',
    (d) => { d.connections[0].to = 'ghost'; }, ['unknown target "ghost"']],
  ['architecture: boundary wraps unknown component', 'architecture',
    (d) => { d.boundaries[0].wraps.push('ghost'); }, ['wraps unknown component "ghost"']],
  ['architecture: boundary title must fit inside its own frame', 'architecture',
    (d) => {
      d.meta.quality_profile = 'standard';
      d.meta.viewBox = [500, 400];
      d.components = [{
        id: 'narrow',
        type: 'backend',
        label: 'Narrow',
        pos: [330, 100],
        size: [128, 60],
      }];
      delete d.meta.views;
      d.connections = [];
      d.cards = [];
      d.boundaries = [{
        kind: 'region',
        label: 'A boundary title that cannot fit its narrow authored frame',
        wraps: ['narrow'],
        pad: 0,
      }];
    }, ['Boundary label', 'fit', 'shorten']],
  ['architecture: boundary title must stay inside the authored viewBox', 'architecture',
    (d) => {
      d.meta.quality_profile = 'standard';
      d.meta.viewBox = [500, 400];
      d.components = [{
        id: 'near-top',
        type: 'backend',
        label: 'Near top',
        pos: [120, 8],
        size: [128, 60],
      }];
      delete d.meta.views;
      d.connections = [];
      d.cards = [];
      d.boundaries = [{
        kind: 'region',
        label: 'Viewport title',
        wraps: ['near-top'],
        pad: 0,
      }];
    }, ['Boundary label', 'outside the viewBox', 'move wrapped components']],
  ['architecture: label wider than component', 'architecture',
    (d) => { d.components[0].label = 'An Extremely Long Component Label Overflow'; }, ['wider than component', 'shorten the label']],
  ['architecture: component sublabel wider than its legible minimum', 'architecture',
    (d) => { d.components[0].sublabel = 'This supporting sentence is far too long for one architecture component'; },
    ['Sublabel', 'legible', 'widen size']],
  ['architecture: component tag wider than its legible minimum', 'architecture',
    (d) => { d.components[0].tag = 'This tag is far too long to sit inside one architecture component box'; },
    ['Tag', 'legible', 'widen size']],
  ['architecture: component overlap suggests fix', 'architecture',
    (d) => { d.components[1].pos = [...d.components[0].pos]; }, ['Suggested fix', 'move "']],

];

for (const [name, mode, mutate, expected] of CASES) {
  test(name, () => {
    const doc = load(mode);
    mutate(doc);
    const { code, stderr } = render(mode, doc);
    assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
    assert.doesNotMatch(stderr, /TypeError|is not a function|Cannot read/, `crashed instead of reporting:\n${stderr}`);
    for (const sub of expected) {
      assert.ok(stderr.includes(sub), `expected "${sub}" in stderr:\n${stderr}`);
    }
  });
}

test('workflow: exact 8px clearance retains the floating-point tolerance (#583)', () => {
  // A label pin retains the compatibility rank policy. The historical pair
  // is therefore still checked at the validator's 8px boundary.
  const doc = {
    schema_version: 2, diagram_type: 'workflow',
    meta: { title: 'Pinned clearance rounding', quality_profile: 'showcase' },
    lanes: [{ id: 'upper', label: 'Upper: the first lane' }, { id: 'lower', label: 'Lower lane: second lane' }],
    nodes: [
      { id: 's0', lane: 'lower', col: 0, type: 'backend', label: 'Start', width: 160 },
      ...[1, 2, 3, 4, 5].map(col => ({ id: `a${col}`, lane: 'upper', col, type: 'backend', label: `Step ${col}`, width: 160 })),
    ],
    edges: [
      { id: 's0-a1', from: 's0', to: 'a1', fromSide: 'top', toSide: 'left' },
      { id: 'a3-a4', from: 'a3', to: 'a4', label: 'next', labelAt: [870, 82] },
    ],
  };
  const rendered = render('workflow', doc);
  assert.equal(rendered.code, 0, rendered.stderr);
  const html = fs.readFileSync(rendered.outPath, 'utf8');
  const left = workflowNodeRect(html, 'a4');
  const right = workflowNodeRect(html, 'a5');
  assert.ok(Math.abs(right.x - (left.x + left.width) - 8) < 1e-6);
  assert.ok(left.x + left.width + 8 > right.x, 'the pair must need the floating-point tolerance');
});

test('workflow: same-lane nodes the solver separated by its exact minimum keep passing (#583)', () => {
  // Redacted reproduction from #583: the neighbour constraint produced a column
  // distance the check re-derived from the nodes' left edges as 1.14e-13px past
  // a5. The compiler rejected the layout it had just produced, with an empty
  // supportedFixes list. Neighbours now keep a 32px route corridor.
  const doc = {
    schema_version: 2,
    diagram_type: 'workflow',
    meta: { title: 'Clearance rounding', quality_profile: 'showcase' },
    lanes: [
      { id: 'upper', label: 'Upper: the first lane' },
      { id: 'lower', label: 'Lower lane: second lane' },
    ],
    nodes: [
      { id: 's0', lane: 'lower', col: 0, type: 'backend', label: 'Start', width: 160 },
      { id: 'a1', lane: 'upper', col: 1, type: 'backend', label: 'Step one', width: 160 },
      { id: 'a2', lane: 'upper', col: 2, type: 'backend', label: 'Step two', width: 160 },
      { id: 'a3', lane: 'upper', col: 3, type: 'backend', label: 'Step three', width: 160 },
      { id: 'a4', lane: 'upper', col: 4, type: 'backend', label: 'Step four', width: 160 },
      { id: 'a5', lane: 'upper', col: 5, type: 'backend', label: 'Step five', width: 160 },
    ],
    edges: [
      { id: 's0-a1', from: 's0', to: 'a1', fromSide: 'top', toSide: 'left' },
      { id: 'a3-a4', from: 'a3', to: 'a4' },
    ],
  };

  const { code, result } = validateCli('workflow', doc);
  assert.equal(code, 0, JSON.stringify(result, null, 2));
  assert.equal(result.ok, true, JSON.stringify(result.diagnostics, null, 2));

  // The painted pair must sit on the minimum, not comfortably clear of it, or
  // this regression would pass with the tolerance set to anything.
  const rendered = render('workflow', doc);
  assert.equal(rendered.code, 0, rendered.stderr);
  const html = fs.readFileSync(rendered.outPath, 'utf8');
  const left = workflowNodeRect(html, 'a4');
  const right = workflowNodeRect(html, 'a5');
  const paintedGap = right.x - (left.x + left.width);
  assert.ok(
    Math.abs(paintedGap - 32) < 1e-6,
    `expected a4 and a5 to paint 32px apart, measured ${paintedGap}`,
  );

  const overlapping = JSON.parse(JSON.stringify(doc));
  overlapping.nodes[5].col = 4;
  const { result: overlapResult } = validateCli('workflow', overlapping);
  assert.equal(overlapResult.ok, false, JSON.stringify(overlapResult, null, 2));
  assert.ok(
    overlapResult.diagnostics.some((diagnostic) => diagnostic.code === 'workflow/node-overlap'),
    JSON.stringify(overlapResult.diagnostics, null, 2),
  );
});

test('architecture: ordinary boundaries may express orthogonal overlapping memberships', () => {
  const d = load('architecture');
  // users sits outside the region and cdn inside it, so the frames overlap
  // without either one drawing a component it does not wrap.
  d.boundaries[1].wraps = ['users', 'cdn'];
  const { code, stderr, outPath } = render('architecture', d);
  assert.equal(code, 0, stderr);
  const html = fs.readFileSync(outPath, 'utf8');
  assert.equal(rectanglesOverlap(boundaryFrameRect(html, 0), boundaryFrameRect(html, 1)), true);
  const masks = boundaryTitleMasks(html);
  assert.equal(masks.length, 2);
  assert.equal(rectanglesOverlap(masks[0], masks[1]), false);
});

test('architecture: profile-less v1 keeps rendering when a boundary title cannot meet strict composition', () => {
  const d = load('architecture');
  delete d.meta.quality_profile;
  d.meta.viewBox = [500, 400];
  d.components = [{
    id: 'narrow',
    type: 'backend',
    label: 'Narrow',
    pos: [330, 100],
    size: [128, 60],
  }];
  delete d.meta.views;
  d.connections = [];
  d.cards = [];
  d.boundaries = [{
    kind: 'region',
    label: 'A boundary title that cannot fit its narrow authored frame',
    wraps: ['narrow'],
    pad: 0,
  }];

  const { code, stderr } = render('architecture', d);
  assert.equal(code, 0, stderr);
});

test('architecture: profile-less v1 keeps legacy boundary geometry at the top edge', () => {
  const d = load('architecture');
  delete d.meta.quality_profile;
  d.meta.viewBox = [500, 400];
  d.components = [{
    id: 'near-top',
    type: 'backend',
    label: 'Near top',
    pos: [120, 22],
    size: [128, 60],
  }];
  delete d.meta.views;
  d.connections = [];
  d.cards = [];
  d.boundaries = [{
    kind: 'region',
    label: 'Legacy top edge',
    wraps: ['near-top'],
    pad: 0,
  }];

  const { code, stderr } = render('architecture', d);
  assert.equal(code, 0, stderr);
});

test('architecture: deployment ownership requires nested membership geometry to agree', () => {
  const d = JSON.parse(fs.readFileSync(
    path.join(skillRoot, 'examples/production-deployment.architecture.json'),
    'utf8',
  ));
  d.boundaries.find((boundary) => boundary.label === 'private application network').pad = 260;
  const { code, stderr } = render('architecture', d);
  assert.notEqual(code, 0);
  assert.match(stderr, /final frames partially overlap/);
  assert.match(stderr, /adjust wraps, pad, or component positions/);
});

test('architecture: boundary labels reserve readable space above wrapped components', () => {
  const d = load('architecture');
  d.boundaries = [{
    kind: 'security-group',
    label: 'Tool effects and permissions',
    wraps: ['lb', 'api'],
    pad: 14,
  }];

  const { code, stderr, outPath } = render('architecture', d);
  assert.equal(code, 0, stderr);
  const html = fs.readFileSync(outPath, 'utf8');
  const label = html.match(
    /<text data-boundary-label="" x="[^"]+" y="([^"]+)" class="t-security" font-size="[^"]+" font-weight="600">Tool effects and permissions<\/text>/,
  );
  assert.ok(label, 'expected the security boundary label');
  const labelBaseline = Number(label[1]);
  const firstWrappedNodeY = Math.min(
    workflowNodeRect(html, 'lb').y,
    workflowNodeRect(html, 'api').y,
  );
  assert.ok(
    labelBaseline <= firstWrappedNodeY - 4,
    `expected the boundary label baseline (${labelBaseline}) to clear the first wrapped node (${firstWrappedNodeY})`,
  );
});

test('architecture: auto viewBox keeps expanded boundary titles readable at desktop scale', () => {
  const d = load('architecture');
  delete d.meta.viewBox;
  d.meta.quality_profile = 'showcase';
  delete d.meta.views;
  d.components = [{
    id: 'node',
    type: 'backend',
    label: 'Current node',
    pos: [800, 100],
    size: [120, 60],
  }];
  d.connections = [];
  d.cards = [];
  d.boundaries = [{
    kind: 'region',
    label: 'Disaster recovery boundary Disaster recovery boundary Disaster recovery boundary',
    wraps: ['node'],
    pad: 30,
  }];

  const { code, stderr, outPath } = render('architecture', d);
  assert.equal(code, 0, stderr);
  const html = fs.readFileSync(outPath, 'utf8');
  const viewBoxWidth = Number(html.match(/\bviewBox="0 0 ([\d.]+) [\d.]+"/)?.[1]);
  const sourceFontPx = Number(html.match(/<text data-boundary-label[^>]*font-size="([\d.]+)"/)?.[1]);
  const projectedFontPx = sourceFontPx * Math.min(1, 930 / viewBoxWidth);
  assert.ok(
    projectedFontPx >= 6,
    `expected the final ${viewBoxWidth}px viewBox to project its ${sourceFontPx}px boundary title at 6px or larger, got ${projectedFontPx}px`,
  );
});

test('architecture: boundary labels and their masks paint above relationship routes', () => {
  const d = load('architecture');
  const { code, stderr, outPath } = render('architecture', d);
  assert.equal(code, 0, stderr);
  const html = fs.readFileSync(outPath, 'utf8');
  const lastRoute = html.lastIndexOf('data-composition-points=');
  const firstBoundaryLabel = html.indexOf('data-graph-role="structural-frame-label"');
  assert.ok(lastRoute >= 0, 'expected at least one rendered relationship route');
  assert.ok(firstBoundaryLabel >= 0, 'expected a foreground boundary label group');
  assert.ok(
    firstBoundaryLabel > lastRoute,
    'boundary labels must paint after relationship routes so routes cannot cross the title text',
  );
  assert.match(
    html.slice(firstBoundaryLabel, firstBoundaryLabel + 500),
    /data-graph-role="structural-frame-label-mask"/,
    'expected an opaque mask behind the foreground boundary title',
  );
});

test('architecture: nested boundary title rails stay inside frames and avoid labels and nodes', () => {
  const d = JSON.parse(fs.readFileSync(
    path.join(skillRoot, 'examples/production-deployment.architecture.json'),
    'utf8',
  ));
  const { code, stderr, outPath } = render('architecture', d);
  assert.equal(code, 0, stderr);
  const html = fs.readFileSync(outPath, 'utf8');
  const masks = boundaryTitleMasks(html);
  assert.equal(masks.length, d.boundaries.length);

  for (const mask of masks) {
    assert.ok(
      rectContainsRect(boundaryFrameRect(html, mask.index), mask),
      `boundary title mask ${mask.index} must stay inside its frame: ${JSON.stringify(mask)}`,
    );
    for (const component of d.components) {
      assert.equal(
        rectanglesOverlap(mask, workflowNodeRect(html, component.id)),
        false,
        `boundary title mask ${mask.index} overlaps component ${component.id}`,
      );
    }
  }

  for (let left = 0; left < masks.length; left += 1) {
    for (let right = left + 1; right < masks.length; right += 1) {
      assert.equal(
        rectanglesOverlap(masks[left], masks[right]),
        false,
        `boundary title masks ${left} and ${right} overlap`,
      );
    }
  }
});

test('architecture: boundary title masks cannot obscure connection labels', () => {
  const d = {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Boundary and connection labels', quality_profile: 'standard', viewBox: [700, 500] },
    components: [
      { id: 'scoped', type: 'backend', label: 'Scoped', pos: [250, 100], size: [120, 60] },
      { id: 'source', type: 'external', label: 'Source', pos: [50, 300], size: [100, 50] },
      { id: 'target', type: 'external', label: 'Target', pos: [500, 300], size: [100, 50] },
    ],
    boundaries: [{ kind: 'region', label: 'Runtime scope', wraps: ['scoped'] }],
    connections: [{
      from: 'source',
      to: 'target',
      label: 'Route label',
      route: 'straight',
      labelAt: [270, 88],
    }],
  };

  const repaired = render('architecture', d);
  assert.equal(repaired.code, 0, repaired.stderr);
  const html = fs.readFileSync(repaired.outPath, 'utf8');
  const match = html.match(/<g data-detail="context" data-edge-from="source" data-edge-to="target"[^>]*>[\s\S]*?<rect x="([^"]+)" y="([^"]+)" width="([^"]+)" height="([^"]+)"/);
  assert.ok(match, 'expected the authored connection label mask');
  const [, x, y, width, height] = match.map(Number);
  const connectionMask = { x, y, width, height };
  const titleMasks = boundaryTitleMasks(html);
  assert.equal(titleMasks.length, 1);
  for (const titleMask of titleMasks) {
    assert.equal(rectanglesOverlap(titleMask, connectionMask), false);
  }
  assert.match(html, /<text x="270" y="88"[^>]*>Route label<\/text>/);

  // A mask covering the complete rail cannot be repaired by sliding the title.
  // Retain rejection and executable author guidance for that real collision.
  d.connections[0].label = 'Route label across complete frame';
  d.connections[0].labelAt = [310, 88];
  const { code, stderr } = render('architecture', d);
  assert.notEqual(code, 0);
  assert.match(stderr, /Boundary label "Runtime scope" overlaps connection label "Route label across complete frame"/);
  assert.match(stderr, /labelAt\/labelDx\/labelDy\/labelSegment/);
});

// ---- sublabel/tag shrink-to-fit: the render half of the same rule ----
// Validation only rejects text that cannot fit even at its legible minimum.
// Everything between "fits at the preferred size" and that floor must shrink,
// not overflow — otherwise the common case still paints over its neighbours.
const SHRINK_CASES = [
  // [mode, mutate(doc), preferredFontSize, selector for the sublabel <text>]
  ['architecture', (d) => { d.components[0].sublabel = 'Browser and mobile apps'; }, 9],
  ['sequence', (d) => {
    // On a wider canvas 7px is already the smallest size that reads on desktop.
    d.meta.column_fit = 'fixed';
    d.meta.viewBox = [930, 580];
    d.participants[0].sublabel = 'long browser session';
  }, 7],
  ['dataflow', (d) => { d.nodes[0].sublabel = 'browser SDK and mobile SDK'; }, 7],
  ['lifecycle', (d) => { d.states[0].sublabel = 'request accepted, validated, then queued now'; }, 9],
];

for (const [mode, mutate, preferred] of SHRINK_CASES) {
  test(`${mode}: an over-long sublabel shrinks to fit instead of overflowing`, () => {
    const d = load(mode);
    mutate(d);
    const { code, stderr, outPath } = render(mode, d);
    assert.equal(code, 0, stderr);
    const html = fs.readFileSync(outPath, 'utf8');
    const sub = html.match(/<text data-detail="context"[^>]*font-size="([\d.]+)"[^>]*>/);
    assert.ok(sub, 'expected a sublabel <text> in the rendered SVG');
    const fontSize = Number(sub[1]);
    assert.ok(
      fontSize < preferred,
      `expected the sublabel to shrink below the ${preferred}px preferred size, got ${fontSize}`,
    );
    assert.ok(fontSize >= 6, `expected the sublabel to stay legible, got ${fontSize}`);
  });
}

const TAG_SHRINK_CASES = [
  // [mode, collection, tag, preferredFontSize]
  ['architecture', 'components', 'owner: platform operations team', 7],
  ['dataflow', 'nodes', 'owner: analytics platform', 7],
  ['lifecycle', 'states', 'owner: platform operations pod on weekday shift', 8],
  ['workflow', 'nodes', 'owner: runtime execution squad A', 7],
];

for (const [mode, collection, tag, preferred] of TAG_SHRINK_CASES) {
  test(`${mode}: an over-long tag shrinks to fit instead of overflowing`, () => {
    const d = load(mode);
    d[collection][0].tag = tag;
    const { code, stderr, outPath } = render(mode, d);
    assert.equal(code, 0, stderr);
    const html = fs.readFileSync(outPath, 'utf8');
    const escapedTag = tag.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    const match = html.match(new RegExp(
      `<text data-detail="fine"[^>]*font-size="([\\d.]+)"[^>]*>${escapedTag}</text>`,
    ));
    assert.ok(match, `expected a tag <text> for "${tag}" in the rendered SVG`);
    const fontSize = Number(match[1]);
    assert.ok(
      fontSize < preferred,
      `expected the tag to shrink below the ${preferred}px preferred size, got ${fontSize}`,
    );
    assert.ok(fontSize >= 6, `expected the tag to stay legible, got ${fontSize}`);
  });
}

test('contract: a too-wide label is never redirected into sublabel', () => {
  // Every renderer used to advise "move detail to sublabel" for an over-long
  // label. Sublabels are measured now, so that advice would move the problem
  // rather than fix it.
  const LABELS = {
    workflow: 'An Extremely Long Node Label That Overflows',
    sequence: 'An Extremely Long Participant Label That Overflows',
    dataflow: 'An Extremely Long Node Label That Overflows',
    lifecycle: 'An Extremely Long State Label That Overflows',
    architecture: 'An Extremely Long Component Label Overflow',
  };
  const FIELD = {
    workflow: 'nodes', sequence: 'participants', dataflow: 'nodes',
    lifecycle: 'states', architecture: 'components',
  };
  for (const [mode, label] of Object.entries(LABELS)) {
    const d = load(mode);
    d[FIELD[mode]][0].label = label;
    const { code, stderr } = render(mode, d);
    assert.notEqual(code, 0, `${mode}: expected non-zero exit; stderr:\n${stderr}`);
    assert.ok(stderr.includes('wider than'), `${mode}: expected a width message:\n${stderr}`);
    assert.ok(
      !/move detail to sublabel/.test(stderr),
      `${mode}: label advice still points at the measured sublabel field:\n${stderr}`,
    );
  }
});

// ---- error-message contract: threshold + remediation, not just a path ----
test('contract: short-edge message carries both the px minimum and a fix verb', () => {
  const d = load('workflow');
  // Force a too-short labeled edge between adjacent same-lane columns.
  d.nodes.push({ id: 'a1', lane: d.nodes[0].lane, col: 0, type: 'backend', label: 'A' });
  d.nodes.push({ id: 'a2', lane: d.nodes[0].lane, col: 0, type: 'backend', label: 'B', yOffset: 30 });
  d.edges.push({ from: 'a1', to: 'a2', label: 'x', route: 'straight' });
  const { stderr } = render('workflow', d);
  // Whatever rule fires, the messages must remain actionable (threshold + verb).
  assert.match(stderr, /\d+px|at least \d+|0\.\.\d+|less than/);
});

test('contract: ajv path errors are annotated with the element id', () => {
  const d = load('workflow');
  d.nodes[3].colour = 'red'; // unknown property → ajv additionalProperties
  const { stderr } = render('workflow', d);
  // Only meaningful when ajv is installed; skip the assertion in degraded mode.
  if (!/schema validation failed/.test(stderr)) return;
  assert.match(stderr, /id\/label:/);
});

test('workflow: same-lane offset auto edge stays orthogonal', () => {
  const d = {
    schema_version: 1,
    diagram_type: 'workflow',
    meta: { title: 'Same-lane offset route' },
    lanes: [{ id: 'main', label: 'Main lane' }],
    nodes: [
      { id: 'left', lane: 'main', col: 1, type: 'backend', label: 'A', width: 32, height: 38, yOffset: -14 },
      { id: 'right', lane: 'main', col: 2, type: 'backend', label: 'B', width: 32, height: 38, yOffset: 14 },
    ],
    edges: [{ from: 'left', to: 'right' }],
  };
  const { code, stderr, outPath } = render('workflow', d);
  assert.equal(code, 0, stderr);
  const html = fs.readFileSync(outPath, 'utf8');
  assert.doesNotMatch(html, /M 236 105 L 284 133/);
  assert.match(html, /data-composition-points="236,105;260,105;260,133;284,133"/);
});

test('workflow: automatic routing uses one bend and avoids every node border', () => {
  const d = JSON.parse(fs.readFileSync(
    path.join(skillRoot, '..', 'test', 'fixtures/automatic-routing-node-border-clearance.workflow.json'),
    'utf8',
  ));
  const { code, stderr, outPath } = render('workflow', d);
  assert.equal(code, 0, stderr);
  const html = fs.readFileSync(outPath, 'utf8');
  const points = workflowEdgePoints(html, 'stdin');
  const target = workflowNodeRect(html, 'team_send');
  assert.equal(points.length, 3, `expected one bend, received ${JSON.stringify(points)}`);
  assert.equal(points[0][0], points[1][0], 'edge must leave the source vertically');
  assert.ok(points[1][1] < points[0][1], 'edge must leave the source through its top side');
  assert.equal(points[1][1], points[2][1], 'edge must enter the target horizontally');
  assert.ok(points[2][0] > points[1][0], 'edge must enter the target through its left side');
  assert.equal(points[2][0], target.x, 'edge must stop at the target border');
  assert.ok(
    points[2][1] > target.y && points[2][1] < target.y + target.height,
    'edge must meet the target inside its left-side anchor range',
  );
  assertWorkflowEdgesAvoidAllNodeBorders(html, d);

  const [labelX, labelY] = workflowEdgeLabelPoint(html, 'stdin');
  assert.equal(labelX, points[0][0], 'the label should use the longer vertical segment');
  assert.ok(labelY > points[1][1] && labelY < points[0][1], 'the label should stay inside that segment');
});

test('workflow: shared automatic endpoints avoid every node border', () => {
  const d = {
    schema_version: 1,
    diagram_type: 'workflow',
    meta: { title: 'Shared endpoint border invariant' },
    lanes: [
      { id: 'target-lane', label: 'Target' },
      { id: 'source-lane', label: 'Sources' },
    ],
    nodes: [
      { id: 'target', lane: 'target-lane', col: 2, type: 'backend', label: 'Target' },
      { id: 'source-left', lane: 'source-lane', col: 1, type: 'backend', label: 'Left' },
      { id: 'source-right', lane: 'source-lane', col: 3, type: 'backend', label: 'Right' },
    ],
    edges: [
      { id: 'left-to-target', from: 'source-left', to: 'target' },
      { id: 'right-to-target', from: 'source-right', to: 'target' },
    ],
  };
  const { code, stderr, outPath } = render('workflow', d);
  assert.equal(code, 0, stderr);
  assertWorkflowEdgesAvoidAllNodeBorders(fs.readFileSync(outPath, 'utf8'), d);
});

test('workflow: blocked first one-bend candidate selects the clear one-bend orientation', () => {
  const d = {
    schema_version: 1,
    diagram_type: 'workflow',
    meta: { title: 'Blocked one-bend candidate', quality_profile: 'showcase' },
    lanes: [
      { id: 'target-lane', label: 'Target' },
      { id: 'obstacle-lane', label: 'Obstacle' },
      { id: 'source-lane', label: 'Source' },
    ],
    nodes: [
      { id: 'target', lane: 'target-lane', col: 3, type: 'backend', label: 'Target' },
      { id: 'obstacle', lane: 'obstacle-lane', col: 1, type: 'security', label: 'Obstacle' },
      { id: 'source', lane: 'source-lane', col: 1, type: 'backend', label: 'Source' },
    ],
    edges: [{ id: 'clear-corner', from: 'source', to: 'target' }],
  };
  const { code, stderr, outPath } = render('workflow', d);
  assert.equal(code, 0, stderr);
  const points = workflowEdgePoints(fs.readFileSync(outPath, 'utf8'), 'clear-corner');
  assert.equal(points.length, 3, `expected the alternate one-bend route, received ${JSON.stringify(points)}`);
  assert.equal(points[0][1], points[1][1], 'blocked vertical-first candidate must switch to horizontal-first');
  assert.ok(points[1][0] > points[0][0], 'edge must leave the source through its right side');
  assert.equal(points[1][0], points[2][0], 'edge must enter the target vertically');
  assert.ok(points[2][1] < points[1][1], 'edge must enter the target through its bottom side');
});

test('workflow: explicit drop routing remains authoritative over the one-bend preference', () => {
  const d = {
    schema_version: 1,
    diagram_type: 'workflow',
    meta: { title: 'Explicit route compatibility', quality_profile: 'showcase' },
    lanes: [
      { id: 'target-lane', label: 'Target' },
      { id: 'source-lane', label: 'Source' },
    ],
    nodes: [
      { id: 'target', lane: 'target-lane', col: 3, type: 'backend', label: 'Target' },
      { id: 'source', lane: 'source-lane', col: 1, type: 'backend', label: 'Source' },
    ],
    edges: [{
      id: 'authored-drop',
      from: 'source',
      to: 'target',
      route: 'drop',
      fromSide: 'top',
      toSide: 'bottom',
    }],
  };
  const { code, stderr, outPath } = render('workflow', d);
  assert.equal(code, 0, stderr);
  const points = workflowEdgePoints(fs.readFileSync(outPath, 'utf8'), 'authored-drop');
  assert.equal(points.length, 4, `explicit drop route was replaced: ${JSON.stringify(points)}`);
  assert.equal(points[0][0], points[1][0]);
  assert.equal(points[1][1], points[2][1]);
  assert.equal(points[2][0], points[3][0]);
});

test('workflow: authored endpoint sides that follow a border are rejected generically', () => {
  const d = {
    schema_version: 1,
    diagram_type: 'workflow',
    meta: { title: 'Authored endpoint border run' },
    lanes: [
      { id: 'target-lane', label: 'Target' },
      { id: 'source-lane', label: 'Source' },
    ],
    nodes: [
      { id: 'target', lane: 'target-lane', col: 3, type: 'backend', label: 'Target' },
      { id: 'source', lane: 'source-lane', col: 1, type: 'backend', label: 'Source' },
    ],
    edges: [{
      id: 'invalid-drop',
      from: 'source',
      to: 'target',
      route: 'drop',
      fromSide: 'right',
      toSide: 'left',
    }],
  };
  const { code, stderr } = render('workflow', d);
  assert.notEqual(code, 0);
  assert.match(stderr, /\[clean-flow\/endpoint-side-direction\] workflow edges\[0\] id "invalid-drop"/);
  assert.match(stderr, /cross node borders perpendicularly/);
});

test('dataflow: authored endpoint sides that follow a border are rejected generically', () => {
  const d = {
    schema_version: 1,
    diagram_type: 'dataflow',
    meta: { title: 'Data-flow endpoint border run' },
    stages: [{ label: 'Source' }, { label: 'Target' }],
    nodes: [
      { id: 'source', stage: 0, row: 0, type: 'backend', label: 'Source' },
      { id: 'target', stage: 1, row: 2, type: 'database', label: 'Target' },
    ],
    flows: [{
      id: 'invalid-bottom',
      from: 'source',
      to: 'target',
      label: 'payload',
      route: 'bottom-channel',
      fromSide: 'right',
      toSide: 'left',
    }],
  };
  const { code, stderr } = render('dataflow', d);
  assert.notEqual(code, 0);
  assert.match(stderr, /\[clean-flow\/endpoint-side-direction\] dataflow flows\[0\] id "invalid-bottom"/);
  assert.match(stderr, /cross node borders perpendicularly/);
});

test('workflow: explicit labelAt remains authoritative on an automatic one-bend edge', () => {
  const d = JSON.parse(fs.readFileSync(
    path.join(skillRoot, '..', 'test', 'fixtures/automatic-routing-node-border-clearance.workflow.json'),
    'utf8',
  ));
  d.edges[0].labelAt = [350, 166];
  const { code, stderr, outPath } = render('workflow', d);
  assert.equal(code, 0, stderr);
  const html = fs.readFileSync(outPath, 'utf8');
  assert.deepEqual(workflowEdgeLabelPoint(html, 'stdin'), [350, 166]);
});

test('workflow: bounded font fitting keeps an ordinary long sublabel inside its node', () => {
  const d = load('workflow');
  d.nodes[0].width = 92;
  d.nodes[0].sublabel = 'shell/browser / MCP';
  const { code, stderr, outPath } = render('workflow', d);
  assert.equal(code, 0, stderr);
  const html = fs.readFileSync(outPath, 'utf8');
  assert.match(html, /font-size="7\.3"[^>]*>shell\/browser \/ MCP<\/text>/);
});

test('workflow: edge crossing a non-endpoint node is rejected', () => {
  const d = {
    schema_version: 1,
    diagram_type: 'workflow',
    meta: { title: 'Crossing edge route', quality_profile: 'standard' },
    lanes: [{ id: 'main', label: 'Main lane' }],
    nodes: [
      { id: 'left', lane: 'main', col: 0, type: 'backend', label: 'Left', width: 60 },
      { id: 'middle', lane: 'main', col: 2, type: 'database', label: 'Middle', width: 70 },
      { id: 'right', lane: 'main', col: 4, type: 'backend', label: 'Right', width: 60 },
    ],
    edges: [{ from: 'left', to: 'right', route: 'straight' }],
  };
  const { code, stderr } = render('workflow', d);
  assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
  assert.match(stderr, /crosses node "middle"/);
  assert.match(stderr, /fromSide\/toSide|channel|lane\/column/);
});

test('architecture: Clean Flow Gate rejects a connection through a component', () => {
  const d = {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Opaque component crossing', quality_profile: 'standard' },
    components: [
      { id: 'left', type: 'frontend', label: 'Left', pos: [60, 120], size: [100, 54] },
      { id: 'middle', type: 'security', label: 'Middle', pos: [270, 120], size: [100, 54] },
      { id: 'right', type: 'backend', label: 'Right', pos: [480, 120], size: [100, 54] },
    ],
    connections: [{ id: 'direct', from: 'left', to: 'right', route: 'straight' }],
  };
  const { code, stderr } = render('architecture', d);
  assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
  assert.match(stderr, /\[clean-flow\/edge-through-node\] architecture connections\[0\] id "direct"/);
  assert.match(stderr, /crosses component "middle"/);
  assert.match(stderr, /segment 0 .*2px clearance/);
});

test('dataflow: showcase rejects a pinned relationship label that hides another route', () => {
  const d = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples', 'event-stream.dataflow.json'), 'utf8'));
  const approvedReplay = d.flows.find((flow) => flow.label === 'approved replay');
  delete approvedReplay.labelAt;
  delete approvedReplay.labelDx;
  delete approvedReplay.labelDy;
  delete approvedReplay.labelSegment;
  // Zero is still an authored pin. Keep this deliberately bad placement fixed
  // so the negative case tests the gate rather than automatic label repair.
  approvedReplay.labelDx = 0;
  const { code, stderr } = render('dataflow', d);
  assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
  assert.match(stderr, /\[composition\/label-route-clearance\] showcase dataflow/);
  assert.match(stderr, /approved replay.*failure sample/);
  assert.match(stderr, /labelAt.*labelDx.*labelDy.*labelSegment/);
});

test('dataflow: an unpinned two-line label repairs its other-route collision without changing semantics or paths', () => {
  const d = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples', 'event-stream.dataflow.json'), 'utf8'));
  const approvedReplay = d.flows.find((flow) => flow.label === 'approved replay');
  for (const key of ['labelAt', 'labelDx', 'labelDy', 'labelSegment']) delete approvedReplay[key];
  const { code, stderr, outPath } = render('dataflow', d);
  assert.equal(code, 0, stderr);
  const html = fs.readFileSync(outPath, 'utf8');
  const group = html.match(/<g data-detail="context"[^>]*data-edge-label="approved replay"[^>]*>[\s\S]*?<\/g>/)?.[0];
  assert.ok(group);
  const bounds = group.match(/<rect x="([^"]+)" y="([^"]+)" width="([^"]+)" height="([^"]+)"/).slice(1).map(Number);
  const [x, y, width, height] = bounds;
  const mask = { x, y, width, height };
  assert.equal(height, 27, 'both authored label lines must retain their full mask');
  const paths = (artifact) => [...artifact.matchAll(/<path[^>]*data-edge-key="(\d+)"[^>]*data-composition-points="([^"]+)"/g)]
    .map(([, key, points]) => ({ key: Number(key), points: points.split(';').map(point => point.split(',').map(Number)) }));
  const routes = paths(html);
  assert.equal(routes.length, d.flows.length);
  const replayIndex = d.flows.indexOf(approvedReplay);
  for (const route of routes.filter(route => route.key !== replayIndex)) {
    for (const [index, end] of route.points.slice(1).entries()) {
      assert.ok(segmentRectClearanceWithin({ start: route.points[index], end }, mask, 4) >= 4,
        `repaired label must clear flow ${route.key} segment ${index}: ${JSON.stringify(mask)}`);
    }
  }
  for (const flow of d.flows) {
    assert.ok(html.includes(`>${flow.label}</text>`), flow.label);
    if (flow.classification) assert.ok(html.includes(`>${flow.classification}</text>`), flow.classification);
  }
  for (const node of d.nodes) assert.ok(html.includes(`>${node.label}</text>`), node.label);
  // Standard permits this explicit collision, providing a reference for every
  // authored route without weakening the showcase gate in the negative case.
  const pinned = structuredClone(d);
  pinned.meta.quality_profile = 'standard';
  pinned.flows[replayIndex].labelDx = 0;
  const reference = render('dataflow', pinned);
  assert.equal(reference.code, 0, reference.stderr);
  assert.deepEqual(routes, paths(fs.readFileSync(reference.outPath, 'utf8')));
});

test('dataflow: validator and SVG share the 27px CJK/emoji classification mask', () => {
  const d = load('dataflow');
  const flow = d.flows[0];
  flow.label = '写入🚀';
  flow.classification = '机密🔐';
  const { code, stderr, outPath } = render('dataflow', d);
  assert.equal(code, 0, stderr);
  const html = fs.readFileSync(outPath, 'utf8');
  const group = html.match(/<g data-detail="context"[^>]*data-edge-id="web-clickstream"[^>]*>[\s\S]*?<\/g>/)?.[0] || '';
  assert.match(group, /data-edge-label="写入🚀"/);
  assert.match(group, /<rect x="[^\"]+" y="[^\"]+" width="41\.4" height="27" rx="4" class="c-mask"\/>/);
  assert.match(group, />机密🔐<\/text>/);
});

test('architecture: showcase rejects a connection label that hides another route', () => {
  const d = load('architecture');
  d.connections[0].labelAt = [620, 330];
  const { code, stderr } = render('architecture', d);
  assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
  assert.match(stderr, /\[composition\/label-route-clearance\] showcase architecture/);
  assert.match(stderr, /HTTPS.*lb-to-api/);
});

test('workflow: showcase rejects an edge label that hides another route', () => {
  const d = {
    schema_version: 1,
    diagram_type: 'workflow',
    meta: {
      title: 'Workflow label-route clearance',
      quality_profile: 'showcase',
      viewBox: [720, 400],
      legend: { mode: 'hidden' },
    },
    lanes: [
      { id: 'label', label: 'Label owner' },
      { id: 'route', label: 'Other route' },
    ],
    nodes: [
      { id: 'a', lane: 'label', col: 0, type: 'backend', label: 'A' },
      { id: 'b', lane: 'label', col: 2, type: 'backend', label: 'B' },
      { id: 'c', lane: 'route', col: 0, type: 'backend', label: 'C' },
      { id: 'd', lane: 'route', col: 2, type: 'backend', label: 'D' },
    ],
    edges: [
      { id: 'labeled-edge', from: 'a', to: 'b', label: 'plan', labelAt: [200, 243] },
      { id: 'other-route', from: 'c', to: 'd' },
    ],
  };
  const { code, stderr } = render('workflow', d);
  assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
  assert.match(stderr, /\[composition\/label-route-clearance\] showcase workflow/);
  assert.match(stderr, /plan.*other-route/);
});

test('sequence: showcase rejects a message label that hides an adjacent route', () => {
  const d = load('sequence');
  d.messages = d.messages.slice(0, 2);
  d.messages[0].label = 'customer authorization context';
  d.messages[0].y = 250;
  d.messages[1].label = 'ok';
  d.messages[1].y = 245;
  d.segments = [];
  d.activations = [];
  const { code, stderr } = render('sequence', d);
  assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
  assert.match(stderr, /\[composition\/label-route-clearance\] showcase sequence/);
  assert.match(stderr, /customer authorization context.*dashboard-request/);
});

// A label rect that leaves the viewBox is clipped by the SVG canvas, so the
// artifact ships truncated text while every post-render check still passes.
function offCanvasLabelDocument() {
  return {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Off-canvas label', quality_profile: 'showcase', viewBox: [720, 400] },
    components: [
      { id: 'left', type: 'frontend', label: 'Left', pos: [60, 160], size: [120, 54] },
      { id: 'right', type: 'backend', label: 'Right', pos: [420, 160], size: [120, 54] },
    ],
    connections: [{
      id: 'left-to-right',
      from: 'left',
      to: 'right',
      label: 'a very long edge label that runs off the canvas',
      labelAt: [640, 140],
    }],
  };
}

test('architecture: showcase rejects a connection label that leaves the canvas', () => {
  const { code, stderr } = render('architecture', offCanvasLabelDocument());
  assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
  assert.match(stderr, /\[composition\/label-canvas-containment\] showcase architecture label "a very long edge label that runs off the canvas" on connections\[0\] id "left-to-right"/);
  assert.match(stderr, /extends past the right edge by 37\.8px/);
  assert.match(stderr, /viewBox 720x400/);
  assert.match(stderr, /labelAt.*labelDx.*labelDy.*labelSegment/);
});

test('architecture: standard keeps a label that leaves the canvas renderable', () => {
  const d = offCanvasLabelDocument();
  d.meta.quality_profile = 'standard';
  const { code, stderr } = render('architecture', d);
  assert.equal(code, 0, stderr);
});

// The same pin is a defect on the fixed-v1 canvas and a legitimate layout on
// readable-v2; see collectLabelCanvasOverflow in renderers/shared/geometry.mjs.
function offCanvasWorkflowLabelDocument(schemaVersion) {
  return {
    schema_version: schemaVersion,
    diagram_type: 'workflow',
    meta: {
      title: 'Workflow label off canvas',
      quality_profile: 'showcase',
      viewBox: [720, 400],
      legend: { mode: 'hidden' },
    },
    lanes: [{ id: 'main', label: 'Main flow' }],
    nodes: [
      { id: 'a', lane: 'main', col: 0, type: 'backend', label: 'A' },
      { id: 'b', lane: 'main', col: 2, type: 'backend', label: 'B' },
    ],
    edges: [{ id: 'a-to-b', from: 'a', to: 'b', label: 'dispatch the planned tool call', labelAt: [700, 240] }],
  };
}

test('workflow: showcase rejects a v1 edge label that leaves the canvas', () => {
  const { code, stderr } = render('workflow', offCanvasWorkflowLabelDocument(1));
  assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
  assert.match(stderr, /\[composition\/label-canvas-containment\] showcase workflow label "dispatch the planned tool call" on edges\[0\] id "a-to-b"/);
  assert.match(stderr, /extends past the right edge by 57px \(label rect \[623, 230, 154, 14\]; viewBox 720x400\)/);
});

test('workflow: readable-v2 contains the same pinned label without this rule', () => {
  const grown = offCanvasWorkflowLabelDocument(2);
  delete grown.meta.viewBox;
  const { code, stderr, outPath } = render('workflow', grown);
  assert.equal(code, 0, stderr);
  const html = fs.readFileSync(outPath, 'utf8');
  const [, width] = html.match(/viewBox="0 0 (\d+) (\d+)"/).map(Number);
  assert.ok(width >= 777, `expected the v2 canvas to contain the label rect, got width ${width}`);

  // An authored v2 viewBox that cannot hold the layout is already rejected by
  // the compiler's own contract, with its own minimum in the message.
  const pinned = render('workflow', offCanvasWorkflowLabelDocument(2));
  assert.notEqual(pinned.code, 0, `expected non-zero exit; stderr:\n${pinned.stderr}`);
  assert.match(pinned.stderr, /cannot contain the readable-v2 layout; minimum \d+×\d+/);
  assert.doesNotMatch(pinned.stderr, /label-canvas-containment/);
});

test('dataflow: showcase rejects a flow label that leaves the canvas', () => {
  const d = load('dataflow');
  d.flows[0].label = 'clickstream ingest with enrichment';
  d.flows[0].labelAt = [1070, 400];
  const { code, stderr } = render('dataflow', d);
  assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
  assert.match(stderr, /\[composition\/label-canvas-containment\] showcase dataflow label "clickstream ingest with enrichment" on flows\[0\]/);
  assert.match(stderr, /extends past the right edge by 79\.3px .*viewBox 1080x520/);
});

// The repair side of the same contract: a suggested labelAt, applied verbatim,
// must clear the obstacle the message names. Both 27px two-line forms used to
// get an "above" hint that landed the rect back on the obstacle, so the
// validator answered its own fix with the identical message.
function suggestedLabelAts(stderr) {
  return [...new Set(stderr.match(/set labelAt \[-?\d+, -?\d+\]/g) || [])]
    .map((match) => match.match(/\[(-?\d+), (-?\d+)\]/).slice(1, 3).map(Number));
}

test('dataflow: obstacle hints for a two-line classification label survive being applied', () => {
  const d = load('dataflow');
  d.flows[0].labelAt = [100, 150];
  const { code, stderr } = render('dataflow', d);
  assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
  assert.match(stderr, /Label "clickstream" overlaps node "web"/);
  const suggestions = suggestedLabelAts(stderr);
  assert.equal(suggestions.length, 2, stderr);
  for (const labelAt of suggestions) {
    const applied = load('dataflow');
    applied.flows[0].labelAt = labelAt;
    const result = render('dataflow', applied);
    assert.equal(result.code, 0, `labelAt [${labelAt}]: ${result.stderr}`);
  }
});

test('sequence: showcase rejects a message label that leaves the canvas', () => {
  const d = load('sequence');
  d.messages = d.messages.slice(0, 1);
  d.messages[0].label = 'request the cached dashboard payload for the current reporting window and retry budget';
  d.segments = [];
  d.activations = [];
  const { code, stderr } = render('sequence', d);
  assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
  assert.match(stderr, /\[composition\/label-canvas-containment\] showcase sequence label ".*" on messages\[0\]/);
  assert.match(stderr, /extends past the left edge by 99\.2px .*viewBox 1080x580/);
  assert.match(stderr, /shorten the label, reorder participants, or enlarge meta\.viewBox/);
});

// An auto canvas is derived geometry, so it has to cover the label rects the
// containment rule measures. An authored viewBox is the author's decision and
// is never resized; there the rule reports the clipping instead.
test('architecture: an auto viewBox grows to contain a wide connection label', () => {
  const d = {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Auto canvas with a wide label', quality_profile: 'showcase' },
    components: [
      { id: 'left', type: 'frontend', label: 'Left', pos: [60, 160], size: [120, 54] },
      { id: 'right', type: 'backend', label: 'Right', pos: [420, 160], size: [120, 54] },
    ],
    connections: [{
      id: 'left-to-right',
      from: 'left',
      to: 'right',
      label: 'a very long edge label that runs off the canvas',
      labelAt: [640, 140],
    }],
  };
  const { code, stderr, outPath } = render('architecture', d);
  assert.equal(code, 0, stderr);
  const html = fs.readFileSync(outPath, 'utf8');
  const [, width] = html.match(/viewBox="0 0 (\d+) (\d+)"/).map(Number);
  const mask = html.match(/<g data-detail="context"[^>]*>\s*<rect x="([\d.-]+)"[^>]*width="([\d.]+)"/);
  const labelRight = Number(mask[1]) + Number(mask[2]);
  assert.ok(labelRight <= width, `label right edge ${labelRight} exceeds the ${width}px auto canvas`);

  const authored = structuredClone(d);
  authored.meta.viewBox = [720, 400];
  const pinned = render('architecture', authored);
  assert.notEqual(pinned.code, 0, `expected non-zero exit; stderr:\n${pinned.stderr}`);
  assert.match(pinned.stderr, /\[composition\/label-canvas-containment\]/);
});

test('architecture: measured auto canvases opt into height-aware reader fitting', () => {
  const automatic = load('architecture');
  delete automatic.meta.viewBox;
  const rendered = render('architecture', automatic);
  assert.equal(rendered.code, 0, rendered.stderr);
  const automaticSvg = fs.readFileSync(rendered.outPath, 'utf8').match(/<svg\b[^>]*>/)?.[0];
  assert.ok(automaticSvg, 'expected an SVG root for the automatic canvas');
  assert.match(automaticSvg, /data-reader-fit="intrinsic-height"/);
  assert.match(automaticSvg, /data-reader-min-text="7\.5"/);

  const authored = structuredClone(automatic);
  authored.meta.viewBox = [1080, 620];
  const pinned = render('architecture', authored);
  assert.equal(pinned.code, 0, pinned.stderr);
  const authoredSvg = fs.readFileSync(pinned.outPath, 'utf8').match(/<svg\b[^>]*>/)?.[0];
  assert.ok(authoredSvg, 'expected an SVG root for the authored canvas');
  assert.match(authoredSvg, /data-reader-fit="authored-height"/);
  assert.match(authoredSvg, /data-diagram-type="architecture"/);
  assert.doesNotMatch(authoredSvg, /data-reader-min-text=/);
});

// Automatic Sequence declares width-first; Dataflow declares intrinsic-height.
// Both default canvases need an explicit automatic Reader fit below the wide ratio.
for (const [mode, doc, authoredViewBox] of [
  ['sequence', {
    schema_version: 1, diagram_type: 'sequence',
    meta: { title: 'Ping', output: 'seq.html' },
    participants: [{ id: 'a', type: 'external', label: 'Client' }, { id: 'b', type: 'backend', label: 'Server' }],
    messages: [{ from: 'a', to: 'b', y: 160, label: 'ping' }],
  }, [1080, 560]],
  ['dataflow', {
    schema_version: 1, diagram_type: 'dataflow',
    meta: { title: 'Pipe', output: 'df.html' },
    stages: [{ label: 'In' }, { label: 'Out' }],
    nodes: [
      { id: 'a', type: 'frontend', label: 'Client', stage: 0, row: 0 },
      { id: 'b', type: 'database', label: 'Store', stage: 1, row: 0 },
    ],
    flows: [{ from: 'a', to: 'b', label: 'write' }],
  }, [1080, 520]],
]) {
  test(`${mode}: default canvas declares automatic Reader fit, authored viewBox does not`, () => {
    const automatic = render(mode, doc);
    assert.equal(automatic.code, 0, automatic.stderr);
    const automaticSvg = fs.readFileSync(automatic.outPath, 'utf8').match(/<svg\b[^>]*>/)?.[0];
    assert.ok(automaticSvg, `expected an SVG root for the default ${mode} canvas`);
    assert.match(automaticSvg, new RegExp(`data-reader-fit="${mode === 'sequence' ? 'width-first' : 'intrinsic-height'}"`));

    const authored = structuredClone(doc);
    authored.meta.viewBox = authoredViewBox;
    const pinned = render(mode, authored);
    assert.equal(pinned.code, 0, pinned.stderr);
    const authoredSvg = fs.readFileSync(pinned.outPath, 'utf8').match(/<svg\b[^>]*>/)?.[0];
    assert.ok(authoredSvg, `expected an SVG root for the authored ${mode} canvas`);
    assert.doesNotMatch(authoredSvg, /data-reader-fit=/);
  });
}

// Boundary-title fonts are resolved against the same width the canvas actually
// renders into. When a connection label alone widens the auto canvas past the
// desktop reader width, the title font must rise with it — otherwise validate
// would pass an artifact the desktop-readability check rejects.
test('architecture: label-driven canvas growth keeps boundary titles at the readability floor', () => {
  const d = {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Label-grown canvas', quality_profile: 'showcase' },
    boundaries: [{
      kind: 'region',
      label: 'Shared production tenant isolation and compliance perimeter for the primary region',
      wraps: ['a', 'b', 'c'],
    }],
    components: [
      { id: 'a', type: 'frontend', label: 'A', pos: [60, 160], size: [140, 54] },
      { id: 'b', type: 'backend', label: 'B', pos: [480, 160], size: [140, 54] },
      { id: 'c', type: 'backend', label: 'C', pos: [860, 160], size: [140, 54] },
      { id: 'd', type: 'database', label: 'D', pos: [860, 320], size: [140, 54] },
    ],
    connections: [{
      id: 'c-to-d',
      from: 'c',
      to: 'd',
      label: 'streaming replication of the full transaction journal with retries',
      labelAt: [1310, 300],
    }],
  };
  const { code, stderr, outPath } = render('architecture', d);
  assert.equal(code, 0, stderr);
  const html = fs.readFileSync(outPath, 'utf8');
  const [, width] = html.match(/viewBox="0 0 (\d+) (\d+)"/).map(Number);
  assert.ok(width > 1395, `expected the label to grow the canvas past 1395px, got ${width}`);
  const floor = minimumReadableSourceTextPx(width);
  const fonts = [...html.matchAll(/data-boundary-label=""[^>]*font-size="([\d.]+)"/g)]
    .map(([, size]) => Number(size));
  assert.equal(fonts.length, 1, 'expected exactly one boundary title');
  assert.ok(
    fonts[0] + 1e-6 >= floor,
    `boundary title font ${fonts[0]} is below the ${floor}px floor for the ${width}px canvas`,
  );
});

// The validator must not answer an off-canvas defect with another off-canvas
// coordinate: every suggested labelAt has to keep the whole label rect inside.
test('architecture: label obstacle fixes stay inside the viewBox', () => {
  const d = {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Label on a component near the edge', quality_profile: 'showcase', viewBox: [720, 400] },
    components: [
      { id: 'left', type: 'frontend', label: 'Left', pos: [40, 180], size: [120, 54] },
      { id: 'right', type: 'backend', label: 'Right', pos: [540, 336], size: [160, 54] },
    ],
    connections: [{
      id: 'left-to-right',
      from: 'left',
      to: 'right',
      label: 'synchronous call with retries and backoff',
      labelAt: [660, 360],
    }],
  };
  const { code, stderr } = render('architecture', d);
  assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
  assert.match(stderr, /overlaps component "right"/);
  const rect = stderr.match(/label rect: \[(-?\d+), (-?\d+), (\d+), (\d+)\]/);
  assert.ok(rect, `expected a label rect in stderr:\n${stderr}`);
  const width = Number(rect[3]);
  const height = Number(rect[4]);
  const suggestions = suggestedLabelAts(stderr);
  assert.ok(suggestions.length > 0, `expected at least one labelAt suggestion:\n${stderr}`);
  for (const [x, y] of suggestions) {
    assert.ok(x - width / 2 >= 0 && x + width / 2 <= 720, `labelAt [${x}, ${y}] leaves the 720px canvas width (label width ${width})`);
    assert.ok(y - 10 >= 0 && y - 10 + height <= 400, `labelAt [${x}, ${y}] leaves the 400px canvas height (label height ${height})`);
  }
});

// Reading the coordinates is not enough: a hint is only executable if applying
// it to the document actually clears both the obstacle and the canvas edge.
// The relative form is where that breaks — its delta has to be measured from
// the document's own labelDx/labelDy, and it means nothing at all while an
// authored labelAt is present, because labelPoint returns labelAt unchanged.
function pinnedLabelDocument(labelControls) {
  return {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Label pinned to the right edge', quality_profile: 'showcase', viewBox: [720, 400] },
    components: [
      { id: 'edge', type: 'cloud', label: 'Edge', pos: [560, 60], size: [140, 54] },
      { id: 'sink', type: 'database', label: 'Sink', pos: [560, 240], size: [140, 54] },
    ],
    connections: [{
      id: 'edge-to-sink',
      from: 'edge',
      to: 'sink',
      label: 'batched telemetry upload with retry and backoff',
      ...labelControls,
    }],
  };
}

function suggestedLabelFixes(stderr) {
  const unique = new Map();
  for (const [hint, x, y] of stderr.matchAll(/set labelAt \[(-?\d+), (-?\d+)\]/g)) {
    unique.set(hint, { labelAt: [Number(x), Number(y)] });
  }
  for (const [hint, dx, dy] of stderr.matchAll(/set labelDx (-?\d+) with labelDy (-?\d+)/g)) {
    unique.set(hint, { labelDx: Number(dx), labelDy: Number(dy) });
  }
  for (const [hint, dy] of stderr.matchAll(/or set (labelDy (-?\d+))/g)) {
    unique.set(hint, { labelDy: Number(dy) });
  }
  return [...unique];
}

test('architecture: an automatic label clears its source and authored canvas edge without manual controls', () => {
  const { code, stderr } = render('architecture', pinnedLabelDocument({}));
  assert.equal(code, 0, stderr);
});

for (const [name, labelControls, expectedFixes] of [
  ['an authored zero labelDy', { labelDy: 0 }, 4],
  ['an authored labelDx', { labelDx: 120 }, 4],
  ['an authored labelAt', { labelAt: [660, 104] }, 2],
]) {
  test(`architecture: every label obstacle fix renders clean when applied to a document with ${name}`, () => {
    const source = pinnedLabelDocument(labelControls);
    const { code, stderr } = render('architecture', source);
    assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
    assert.match(stderr, /overlaps component "edge"/);
    assert.match(stderr, /\[composition\/label-canvas-containment\]/);

    const fixes = suggestedLabelFixes(stderr);
    assert.equal(fixes.length, expectedFixes, `unexpected suggestion set:\n${stderr}`);
    // An authored labelAt outranks labelDx/labelDy, so a relative suggestion
    // there would be a fix that changes nothing.
    if (Array.isArray(labelControls.labelAt)) assert.doesNotMatch(stderr, /set labelD[xy] /);

    for (const [hint, patch] of fixes) {
      const repaired = structuredClone(source);
      Object.assign(repaired.connections[0], patch);
      const result = render('architecture', repaired);
      assert.equal(result.code, 0, `applying "${hint}" still fails:\n${result.stderr}`);
    }
  });
}

function autoRoutePassThroughDocument(connection) {
  return {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Auto-route pass-through regression' },
    components: [
      { id: 'api', type: 'backend', label: 'API', pos: [400, 280], size: [160, 76] },
      { id: 'cache', type: 'database', label: 'Cache', pos: [645, 130], size: [130, 60] },
      { id: 'queue', type: 'cloud', label: 'Queue', pos: [880, 130] },
    ],
    connections: [connection],
  };
}

function componentRect(component) {
  const [width, height] = component.size || [120, 60];
  return { x: component.pos[0], y: component.pos[1], width, height };
}

function assertRouteContact(point, adjacent, expected) {
  if (Array.isArray(expected)) {
    assert.deepEqual(point, expected, 'route must attach to its authored port');
    return;
  }
  const { x, y, width, height } = expected;
  const [px, py] = point;
  const [ax, ay] = adjacent;
  const normalContact = (
    (py > y && py < y + height && ay === py
      && ((px === x && ax < px) || (px === x + width && ax > px)))
    || (px > x && px < x + width && ax === px
      && ((py === y && ay < py) || (py === y + height && ay > py)))
  );
  assert.ok(normalContact, `route must contact its node perpendicularly from outside: ${JSON.stringify({ point, adjacent, expected })}`);
}

function assertAutomaticRoute(html, from, to, obstacles = []) {
  const encoded = html.match(/data-composition-points="([^"]+)"/)?.[1];
  assert.ok(encoded, 'expected a rendered route');
  const points = encoded.split(';').map(point => point.split(',').map(Number));
  assert.ok(points.length >= 2 && points.every(point => point.length === 2 && point.every(Number.isFinite)));
  assertRouteContact(points[0], points[1], from);
  assertRouteContact(points.at(-1), points.at(-2), to);
  for (let i = 1; i < points.length; i++) {
    const start = points[i - 1];
    const end = points[i];
    assert.ok((start[0] === end[0]) !== (start[1] === end[1]), 'route segments must be nonzero and orthogonal');
    for (const obstacle of obstacles) {
      assert.equal(segmentIntersectsRect({ start, end }, obstacle), false, 'route must avoid unrelated nodes');
    }
  }
  return points;
}

test('architecture: default auto route selects a safe orthogonal candidate around an unrelated component', () => {
  const d = autoRoutePassThroughDocument({ from: 'api', to: 'queue', variant: 'dashed' });
  const { code, stderr, outPath } = render('architecture', d);
  assert.equal(code, 0, stderr);
  const html = fs.readFileSync(outPath, 'utf8');
  assertAutomaticRoute(html, componentRect(d.components[0]), componentRect(d.components[2]),
    [componentRect(d.components[1])]);
});

test('architecture: aligned automatic endpoints still route around an unrelated component', () => {
  const d = {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Aligned obstacle regression', quality_profile: 'showcase' },
    components: [
      { id: 'source', type: 'backend', label: 'Source', pos: [40, 120], size: [140, 60] },
      { id: 'blocker', type: 'security', label: 'Blocker', pos: [240, 120], size: [140, 60] },
      { id: 'target', type: 'database', label: 'Target', pos: [440, 120], size: [140, 60] },
    ],
    connections: [{ id: 'source-target', from: 'source', to: 'target' }],
  };
  const { code, stderr, outPath } = render('architecture', d);
  assert.equal(code, 0, `aligned automatic route must avoid the blocker: ${stderr}`);
  const html = fs.readFileSync(outPath, 'utf8');
  const encoded = html.match(/data-edge-id="source-target" data-composition-points="([^"]+)"/)?.[1];
  assert.ok(encoded, 'expected rendered composition points for source-target');
  assert.ok(encoded.split(';').length >= 6, `expected obstacle-avoiding bends, found ${encoded}`);
});

test('architecture: auto route enters explicit top and bottom ports perpendicularly', () => {
  const d = {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Endpoint direction regression' },
    components: [
      { id: 'cli-agents', type: 'external', label: 'CLI Agents', pos: [300, 100], size: [100, 60] },
      { id: 'tasks-watch', type: 'backend', label: 'Tasks Watcher', pos: [100, 240], size: [100, 60] },
    ],
    connections: [
      { id: 'tasks-file', from: 'cli-agents', to: 'tasks-watch', variant: 'dashed', fromSide: 'bottom', toSide: 'top' },
    ],
  };
  const { code, stderr, outPath } = render('architecture', d);
  assert.equal(code, 0, stderr);
  const html = fs.readFileSync(outPath, 'utf8');
  const points = assertAutomaticRoute(html, [350, 160], [150, 240]);
  assert.equal(points[1][0], 350, 'leave the bottom port vertically');
  assert.ok(points[1][1] > 160, 'leave downward');
  assert.equal(points.at(-2)[0], 150, 'enter the top port vertically');
  assert.ok(points.at(-2)[1] < 240, 'enter from above');
});

test('architecture: auto route keeps normal node contacts when the primary dogleg is blocked', () => {
  const d = {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Inferred endpoint direction regression' },
    components: [
      { id: 'workspace', type: 'frontend', label: 'Workspace UI', pos: [40, 300], size: [120, 60] },
      { id: 'runtime-server', type: 'backend', label: 'Runtime Server', pos: [220, 300], size: [120, 60] },
      { id: 'runtime-store', type: 'backend', label: 'Runtime Store', pos: [400, 300], size: [120, 60] },
      { id: 'stream-hub', type: 'messagebus', label: 'Terminal Stream Hub', pos: [700, 100], size: [120, 60] },
    ],
    connections: [
      { id: 'terminal-return', from: 'stream-hub', to: 'workspace' },
    ],
  };
  const { code, stderr, outPath } = render('architecture', d);
  assert.equal(code, 0, stderr);
  const html = fs.readFileSync(outPath, 'utf8');
  assertAutomaticRoute(html, componentRect(d.components[3]), componentRect(d.components[0]),
    d.components.slice(1, 3).map(componentRect));
});

test('architecture: auto route finds a multi-bend path when both side-safe doglegs are blocked', () => {
  const d = {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Multi-bend automatic route regression', quality_profile: 'showcase' },
    components: [
      { id: 'server', type: 'backend', label: 'Server', pos: [280, 240], size: [180, 64] },
      { id: 'upper-blocker', type: 'backend', label: 'Upper blocker', pos: [530, 240], size: [180, 64] },
      { id: 'lower-blocker', type: 'backend', label: 'Lower blocker', pos: [530, 360], size: [180, 64] },
      { id: 'client', type: 'external', label: 'Client', pos: [780, 360], size: [190, 64] },
    ],
    connections: [
      { id: 'client-server', from: 'client', to: 'server' },
    ],
  };
  const { code, stderr, outPath } = render('architecture', d);
  assert.equal(code, 0, `automatic multi-bend route must render cleanly: ${stderr}`);
  const html = fs.readFileSync(outPath, 'utf8');
  const encoded = html.match(/data-edge-id="client-server" data-composition-points="([^"]+)"/)?.[1];
  assert.ok(encoded, 'expected rendered composition points for client-server');
  const points = encoded.split(';').map((point) => point.split(',').map(Number));
  assert.ok(points.length >= 6, `expected a multi-bend route, found ${encoded}`);
  assert.equal(points[0][1], points[1][1], 'route must leave the inferred left port horizontally');
  assert.ok(points[1][0] < points[0][0], 'route must leave the inferred left port leftward');
  assert.equal(points.at(-2)[1], points.at(-1)[1], 'route must enter the inferred right port horizontally');
  assert.ok(points.at(-2)[0] > points.at(-1)[0], 'route must enter the inferred right port leftward');
});

test('architecture: explicit via cannot run tangentially into an authored top port', () => {
  const d = {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Tangent endpoint regression' },
    components: [
      { id: 'cli-agents', type: 'external', label: 'CLI Agents', pos: [300, 100], size: [100, 60] },
      { id: 'tasks-watch', type: 'backend', label: 'Tasks Watcher', pos: [100, 240], size: [100, 60] },
    ],
    connections: [
      {
        id: 'tasks-file',
        from: 'cli-agents',
        to: 'tasks-watch',
        variant: 'dashed',
        fromSide: 'bottom',
        toSide: 'top',
        via: [[350, 200], [100, 200], [100, 240]],
      },
    ],
  };
  const { code, stderr } = render('architecture', d);
  assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
  assert.match(stderr, /\[clean-flow\/endpoint-side-direction\] architecture connections\[0\] id "tasks-file"/);
  assert.match(stderr, /final segment 3 \[100, 240\] -> \[150, 240\]/);
  assert.match(stderr, /toSide "top".*vertical downward from above/);
});

test('architecture: explicit orthogonal route remains authoritative when it crosses a component', () => {
  const d = autoRoutePassThroughDocument({
    from: 'api',
    to: 'queue',
    variant: 'dashed',
    route: 'orthogonal-h',
  });
  const { code, stderr } = render('architecture', d);
  assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
  assert.match(stderr, /connections\[0\] "api" -> "queue" crosses component "cache"/);
});

test('architecture: auto route clears stacked blockers after doglegs and side-aware bridges are blocked', () => {
  const d = autoRoutePassThroughDocument({ id: 'api-queue', from: 'api', to: 'queue', variant: 'dashed' });
  d.components.push({ id: 'guard', type: 'security', label: 'Guard', pos: [825, 215], size: [70, 50] });
  const { code, stderr, outPath } = render('architecture', d);
  assert.equal(code, 0, `automatic route must clear both blockers: ${stderr}`);
  const html = fs.readFileSync(outPath, 'utf8');
  // Automatic ports may choose another clear side; both blockers must still
  // be avoided and both endpoint contacts must remain perpendicular.
  assertAutomaticRoute(html, componentRect(d.components[0]), componentRect(d.components[2]),
    [componentRect(d.components[1]), componentRect(d.components[3])]);
});

test('architecture: explicit waypoints around an obstacle remain valid by default', () => {
  const d = autoRoutePassThroughDocument({
    from: 'api',
    to: 'queue',
    variant: 'dashed',
    fromSide: 'right',
    toSide: 'top',
    via: [[620, 318], [620, 100], [940, 100]],
  });
  const { code, stderr } = render('architecture', d);
  assert.equal(code, 0, stderr);
});

test('architecture: showcase rejects an unrelated proper edge crossing', () => {
  const d = {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Showcase crossing', quality_profile: 'showcase' },
    components: [
      { id: 'a', type: 'frontend', label: 'A', pos: [60, 80], size: [60, 40] },
      { id: 'b', type: 'backend', label: 'B', pos: [360, 260], size: [60, 40] },
      { id: 'c', type: 'database', label: 'C', pos: [60, 260], size: [60, 40] },
      { id: 'd', type: 'external', label: 'D', pos: [360, 80], size: [60, 40] },
    ],
    connections: [
      { id: 'down-right', from: 'a', to: 'b', route: 'orthogonal-h' },
      { id: 'up-right', from: 'c', to: 'd', route: 'orthogonal-v', fromSide: 'top', toSide: 'bottom' },
    ],
  };
  const { code, stderr } = render('architecture', d);
  assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
  assert.match(stderr, /\[composition\/proper-crossing\] showcase architecture/);
  assert.match(stderr, /connections\[0\] id "down-right"/);
  assert.match(stderr, /connections\[1\] id "up-right"/);
  assert.match(stderr, /at \[240, 190\]/);
  assert.match(stderr, /segments 1 and 1/);
  assert.match(stderr, /route\/via|fromSide\/toSide/);
});

test('architecture: unavoidable automatic crossing renders as a verified crossover', () => {
  const d = {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Automatic crossover', quality_profile: 'showcase' },
    components: [
      { id: 'left', type: 'frontend', label: 'Left', pos: [40, 170], size: [80, 60] },
      { id: 'right', type: 'backend', label: 'Right', pos: [480, 170], size: [80, 60] },
      { id: 'top', type: 'database', label: 'Top', pos: [260, 20], size: [80, 60] },
      { id: 'bottom', type: 'external', label: 'Bottom', pos: [260, 320], size: [80, 60] },
    ],
    connections: [
      { id: 'horizontal', from: 'left', to: 'right', fromSide: 'right', toSide: 'left' },
      { id: 'vertical', from: 'top', to: 'bottom', fromSide: 'bottom', toSide: 'top' },
    ],
  };
  const { code, stderr, outPath } = render('architecture', d);
  assert.equal(code, 0, stderr);
  const html = fs.readFileSync(outPath, 'utf8');
  const svg = html.match(/<svg\b[\s\S]*?<\/svg>/i)?.[0] || '';
  assert.equal((svg.match(/data-graph-role="automatic-crossover-underlay"/g) || []).length, 2);
  assert.equal((svg.match(/data-graph-role="automatic-crossover"/g) || []).length, 2);
  assert.equal((svg.match(/data-composition-crossover="halo"/g) || []).length, 2);
  assert.equal((svg.match(/data-edge-from=/g) || []).length, 2);
  assert.doesNotMatch(svg, /automatic-crossover-underlay"[^>]*data-edge-/);

  const receipt = JSON.parse(execFileSync('node', [
    path.join(skillRoot, 'scripts', 'check-render-output.mjs'),
    outPath,
  ], { encoding: 'utf8' }));
  assert.equal(receipt.ok, true, JSON.stringify(receipt.composition.issues));
  assert.equal(receipt.composition.metrics.properCrossings, 0);
  assert.equal(receipt.composition.metrics.resolvedCrossovers, 1);
});

test('architecture: showcase preserves a straight-through explicit waypoint as an authored touch', () => {
  const d = {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: {
      title: 'Forward-collinear waypoint compatibility',
      quality_profile: 'showcase',
      viewBox: [600, 320],
      legend: { mode: 'hidden' },
    },
    components: [
      { id: 'a', type: 'backend', label: 'A', pos: [50, 100], size: [80, 60] },
      { id: 'b', type: 'backend', label: 'B', pos: [450, 100], size: [80, 60] },
      { id: 'c', type: 'backend', label: 'C', pos: [260, 0], size: [80, 60] },
      { id: 'd', type: 'backend', label: 'D', pos: [260, 200], size: [80, 60] },
    ],
    connections: [
      { id: 'horizontal', from: 'a', to: 'b', via: [[300, 130]] },
      { id: 'vertical', from: 'c', to: 'd' },
    ],
  };

  const { code, stderr } = render('architecture', d);
  assert.equal(code, 0, stderr);
});

test('architecture: standard keeps the same proper crossing renderable', () => {
  const d = {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Standard crossing', quality_profile: 'standard' },
    components: [
      { id: 'a', type: 'frontend', label: 'A', pos: [60, 80], size: [60, 40] },
      { id: 'b', type: 'backend', label: 'B', pos: [360, 260], size: [60, 40] },
      { id: 'c', type: 'database', label: 'C', pos: [60, 260], size: [60, 40] },
      { id: 'd', type: 'external', label: 'D', pos: [360, 80], size: [60, 40] },
    ],
    connections: [
      { from: 'a', to: 'b', route: 'orthogonal-h' },
      { from: 'c', to: 'd', route: 'orthogonal-v', fromSide: 'top', toSide: 'bottom' },
    ],
  };
  const { code, stderr } = render('architecture', d);
  assert.equal(code, 0, stderr);
});

function ambiguousCorridorDocument(profile) {
  return {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Ambiguous corridor', quality_profile: profile },
    components: [
      { id: 'a', type: 'frontend', label: 'A', pos: [40, 60], size: [60, 40] },
      { id: 'b', type: 'backend', label: 'B', pos: [400, 60], size: [60, 40] },
      { id: 'c', type: 'database', label: 'C', pos: [120, 220], size: [60, 40] },
      { id: 'd', type: 'external', label: 'D', pos: [480, 220], size: [60, 40] },
    ],
    connections: [
      { id: 'first', from: 'a', to: 'b', fromSide: 'right', toSide: 'left', route: 'straight' },
      { id: 'second', from: 'c', to: 'd', fromSide: 'top', toSide: 'top', via: [[150, 80], [390, 80], [390, 180], [510, 180]] },
    ],
  };
}

test('architecture: showcase rejects an unrelated shared route corridor', () => {
  const { code, stderr } = render('architecture', ambiguousCorridorDocument('showcase'));
  assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
  assert.match(stderr, /\[composition\/ambiguous-corridor\] showcase architecture/);
  assert.match(stderr, /connections\[0\] id "first" "a" -> "b" shares a 240px corridor with connections\[1\] id "second" "c" -> "d"/);
  assert.match(stderr, /\[150, 80\] -> \[390, 80\]/);
  assert.match(stderr, /do not visually merge/);
});

test('architecture: standard keeps an ambiguous corridor renderable for repair', () => {
  const { code, stderr } = render('architecture', ambiguousCorridorDocument('standard'));
  assert.equal(code, 0, stderr);
});

test('architecture: route rhythm warns in standard and blocks a showcase micro segment', () => {
  const base = {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Readable turn rhythm' },
    components: [
      { id: 'a', type: 'frontend', label: 'A', pos: [60, 80], size: [60, 40] },
      { id: 'b', type: 'backend', label: 'B', pos: [360, 80], size: [60, 40] },
    ],
    connections: [
      { id: 'tight', from: 'a', to: 'b', fromSide: 'right', toSide: 'bottom', via: [[125, 100], [125, 160], [390, 160]] },
    ],
  };
  const standard = structuredClone(base);
  standard.meta.quality_profile = 'standard';
  assert.equal(render('architecture', standard).code, 0);

  const showcase = structuredClone(base);
  showcase.meta.quality_profile = 'showcase';
  const { code, stderr } = render('architecture', showcase);
  assert.notEqual(code, 0);
  assert.match(stderr, /\[composition\/micro-segment\] showcase architecture connections\[0\] id "tight"/);
  assert.match(stderr, /5px source-stub segment 0/);
  assert.match(stderr, /wider corridor|move the component/);
});

test('architecture: automatic reciprocal adjacent routes keep the showcase interior floor', () => {
  const doc = {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Automatic adjacent request and response', quality_profile: 'showcase' },
    components: [
      { id: 'listener', type: 'backend', label: 'Node HTTP listener', pos: [260, 270], size: [170, 78] },
      { id: 'handler', type: 'backend', label: 'HTTP request handler', pos: [490, 270], size: [180, 84] },
    ],
    connections: [
      { id: 'request-envelope', from: 'listener', to: 'handler', label: 'method · path · body' },
      { id: 'json-response', from: 'handler', to: 'listener', label: '401 / 400 / 404 / 409 / 202 / 200' },
    ],
  };
  assert.ok(doc.connections.every((connection) => (
    !('route' in connection) && !('via' in connection) && !('fromSide' in connection) && !('toSide' in connection)
  )));

  // The route remains valid, but these full labels do not fit a 60px gap.
  // Inspect geometry even on failure instead of accepting detached labels.
  const input = path.join(tmp, 'reciprocal-label-gap.json');
  fs.writeFileSync(input, JSON.stringify({ ...doc, meta: { ...doc.meta, output: 'reciprocal.html' } }));
  let report;
  try {
    execFileSync('node', [path.join(skillRoot, 'bin/archify.mjs'), 'validate', 'architecture', input, '--layout-json'], { encoding: 'utf8' });
    assert.fail('crowded labels must be rejected');
  } catch (error) {
    assert.equal(error.status, 1);
    report = JSON.parse(error.stdout);
  }
  assert.ok(report.diagnostics.length > 0);
  assert.ok(report.diagnostics.every(issue => issue.code === 'composition/label-gap'
    || issue.code === 'composition/label-route-clearance'
    || /^Label ".*" overlaps component /.test(issue.message)), JSON.stringify(report.diagnostics));
  for (const [index, { id }] of doc.connections.entries()) {
    const points = report.connections[index]?.points;
    assert.ok(points, `expected composition points for ${id}`);
    const encoded = JSON.stringify(points);
    const interiorLengths = points.slice(1, -2).map((point, index) => (
      Math.abs(point[0] - points[index + 2][0]) + Math.abs(point[1] - points[index + 2][1])
    ));
    assert.ok(interiorLengths.every((length) => length >= 16), `${id} has cramped interior: ${encoded}`);
  }
});

test('architecture: container border run is blocking in standard and showcase', () => {
  for (const profile of ['standard', 'showcase']) {
    const d = load('architecture');
    d.meta.quality_profile = profile;
    d.connections.find((connection) => connection.id === 'jwt-verification').via = [[620, 142], [620, 270], [735, 270]];
    const { code, stderr } = render('architecture', d);
    assert.notEqual(code, 0, `expected ${profile} to reject a border run`);
    assert.match(stderr, /\[composition\/container-border-run\] architecture connections\[1\] id "jwt-verification"/);
    assert.match(stderr, /security-group "sg-api :443\/:8000" top border/);
  }
});

test('architecture: vertically offset nodes keep valid automatic contacts through delivery', () => {
  // Regression for issue #376. The hub sits above the spoke with a horizontal
  // offset (dx = -164, dy = +200). Inferring left/right from the bare sign
  // of dx made the Clean Flow Gate reject the router's own valid contact.
  // Automatic ports may change; routing and delivery must agree on their
  // actual perpendicular endpoint contacts.
  const doc = {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: {
      title: 'Hub above an offset spoke',
      output: 'hub-spoke.html',
      quality_profile: 'standard',
      viewBox: [640, 360],
    },
    components: [
      { id: 'hub', type: 'cloud', label: 'Hub', pos: [200, 40], size: [176, 52] },
      { id: 'spoke', type: 'cloud', label: 'Spoke', pos: [40, 240], size: [168, 52] },
    ],
    connections: [{ id: 'hub-spoke', from: 'hub', to: 'spoke' }],
  };

  const { code, stderr, outPath } = render('architecture', doc);
  assert.equal(code, 0, `automatic offset route must render cleanly: ${stderr}`);
  assert.doesNotMatch(stderr, /clean-flow\/endpoint-side-direction/);

  const html = fs.readFileSync(outPath, 'utf8');
  assertAutomaticRoute(html, componentRect(doc.components[0]), componentRect(doc.components[1]));

  // The CLI validation surface agrees with the renderer.
  const cli = validateCli('architecture', doc, 'standard');
  assert.equal(cli.code, 0, `validate must accept the inferred vertical route: ${JSON.stringify(cli.result)}`);

  // The public delivery path must accept the same inferred route and verify
  // the committed artifact, without authored side, route, or via fields.
  const delivery = deliverCli('architecture', doc, 'standard');
  assert.equal(delivery.code, 0, `deliver must accept the inferred vertical route: ${JSON.stringify(delivery.result)}`);
  assert.equal(delivery.result.ok, true);
  assert.equal(fs.existsSync(delivery.outPath), true);
});

test('dataflow: stage border run is blocking and the inter-stage gutter passes', () => {
  const bad = load('dataflow');
  bad.flows.find((flow) => flow.id === 'web-clickstream').via = [[184, 157], [184, 271]];
  const failed = render('dataflow', bad);
  assert.notEqual(failed.code, 0);
  assert.match(failed.stderr, /\[composition\/container-border-run\] dataflow flows\[0\] id "web-clickstream"/);
  assert.match(failed.stderr, /stage "Sources" right border for 114px/);

  const clean = load('dataflow');
  const passed = render('dataflow', clean);
  assert.equal(passed.code, 0, passed.stderr);
});

test('sequence: a message cannot masquerade as a time-segment border', () => {
  const d = load('sequence');
  d.messages.find((message) => message.id === 'cache-read').y = d.segments[1].from;
  const { code, stderr } = render('sequence', d);
  assert.notEqual(code, 0);
  assert.match(stderr, /\[composition\/container-border-run\] sequence messages\[4\] id "cache-read"/);
  assert.match(stderr, /segment "Fallback" top border/);
});

test('dataflow: Clean Flow Gate rejects a flow through an unrelated node', () => {
  const d = {
    schema_version: 1,
    diagram_type: 'dataflow',
    meta: { title: 'Opaque data node crossing', quality_profile: 'standard' },
    stages: [{ label: 'Source' }, { label: 'Middle' }, { label: 'Sink' }],
    nodes: [
      { id: 'left', type: 'frontend', label: 'Left', stage: 0, row: 1 },
      { id: 'middle', type: 'security', label: 'Middle', stage: 1, row: 1 },
      { id: 'right', type: 'database', label: 'Right', stage: 2, row: 1 },
    ],
    flows: [{ id: 'direct', from: 'left', to: 'right', label: 'payload', route: 'straight', labelAt: [315, 190] }],
  };
  const { code, stderr } = render('dataflow', d);
  assert.notEqual(code, 0, `expected non-zero exit; stderr:\n${stderr}`);
  assert.match(stderr, /\[clean-flow\/edge-through-node\] dataflow flows\[0\] id "direct"/);
  assert.match(stderr, /crosses node "middle"/);
  assert.match(stderr, /stage\/row/);
});

test('sequence: lifelines and activation bars remain intentional pass-through geometry', () => {
  const d = load('sequence');
  const { code, stderr } = render('sequence', d);
  assert.equal(code, 0, stderr);
  assert.doesNotMatch(stderr, /Clean Flow Gate/);
});

test('sequence: segment titles render as foreground badges near their borders and clear of headers', () => {
  const d = load('sequence');
  const { code, stderr, outPath } = render('sequence', d);
  assert.equal(code, 0, stderr);
  const html = fs.readFileSync(outPath, 'utf8');
  const firstSegment = d.segments[0];
  const segmentLabelsAt = html.indexOf('<!-- Segment Labels -->');
  const activationsAt = html.indexOf('<!-- Activations -->');
  const messagesAt = html.indexOf('<!-- Messages -->');

  assert.ok(segmentLabelsAt > messagesAt, 'segment labels should stay above lifelines, messages, and activations');
  assert.ok(messagesAt > activationsAt, 'message arrows and labels should stay above activation bars');
  const badge = html.match(/<g data-graph-role="segment-label" data-segment-id="0">([\s\S]*?)<\/g>/);
  assert.ok(badge, 'the first phase keeps its foreground badge');
  assert.match(badge[1], new RegExp(`<text [^>]*>${firstSegment.label}</text>`), 'the full phase title stays visible');
  const mask = badge[1].match(/<rect x="([\d.]+)" y="([\d.]+)" width="([\d.]+)" height="([\d.]+)"[^>]*class="c-mask"/);
  assert.ok(mask, 'the title keeps a background mask above the frame');
  const [x, y, width, height] = mask.slice(1).map(Number);
  assert.ok(y <= firstSegment.from && y + height >= firstSegment.from - 4,
    'the automatic title remains attached to its own top border');
  assert.ok(y + height < firstSegment.to, 'the title does not drift beyond its own phase');

  const headers = [...html.matchAll(/<g [^>]*data-node-id="[^"]+"[^>]*>[\s\S]*?<rect x="([\d.]+)" y="([\d.]+)" width="([\d.]+)" height="([\d.]+)"[^>]*class="c-mask"/g)];
  assert.equal(headers.length, d.participants.length, 'all participant header masks are checked');
  for (const header of headers) {
    const [headerX, headerY, headerWidth, headerHeight] = header.slice(1).map(Number);
    const overlap = x < headerX + headerWidth && x + width > headerX
      && y < headerY + headerHeight && y + height > headerY;
    assert.equal(overlap, false, 'the full title badge clears participant cards, not only their main labels');
  }
});

test('sequence: segment title badge clears a nearby first message label', () => {
  const d = load('sequence');
  const firstSegment = d.segments[0];
  const firstMessage = d.messages[0];
  firstSegment.from = 180;
  firstMessage.y = firstSegment.from + 5;

  const { code, stderr, outPath } = render('sequence', d);
  assert.equal(code, 0, stderr);
  const html = fs.readFileSync(outPath, 'utf8');
  const segment = html.match(
    /<g data-graph-role="segment-label" data-segment-id="0">\s*<rect x="([^"]+)" y="([^"]+)" width="([^"]+)" height="([^"]+)"/,
  );
  const message = html.match(new RegExp(
    `<g [^>]*data-edge-id="${firstMessage.id}"[\\s\\S]*?<rect x="([^"]+)" y="([^"]+)" width="([^"]+)" height="([^"]+)"`,
  ));
  assert.ok(segment, 'expected the first segment badge rectangle');
  assert.ok(message, 'expected the first message label rectangle');

  const [segmentX, segmentY, segmentW, segmentH] = segment.slice(1).map(Number);
  const [messageX, messageY, messageW, messageH] = message.slice(1).map(Number);
  const overlaps = segmentX < messageX + messageW
    && segmentX + segmentW > messageX
    && segmentY < messageY + messageH
    && segmentY + segmentH > messageY;
  assert.equal(overlaps, false, 'segment title badge must not cover the first message label');
});

test('sequence: segment label exceeding segment frame available width fails layout validation with remediation', () => {
  const d = load('sequence');
  d.meta.viewBox[0] = 820;
  d.meta.column_fit = 'fixed';
  d.segments[0].label = 'Phase 1: Dual-Certificate mTLS Handshake & Distributed Token Verification Protocol Negotiation'.repeat(2);

  const { code, stderr } = render('sequence', d);
  assert.equal(code, 1);
  assert.match(stderr, /Segment "Phase 1: Dual-Certificate mTLS Handshake & Distributed Token Verification Protocol NegotiationPhase 1: Dual-Certificate mTLS Handshake & Distributed Token Verification Protocol Negotiation" label \(~992px\) exceeds the segment frame's available width \(716px\) — shorten the label or increase meta\.viewBox\[0\] to at least 1096\./);

  // Remediating by increasing viewBox[0] to the suggested minimum allows it to pass cleanly
  d.meta.viewBox[0] = 1096;
  const fixed = render('sequence', d);
  assert.equal(fixed.code, 0, fixed.stderr);
});

test('sequence: segment label boundary containment within canvas vs segment frame and exact-fit', () => {
  // Available width in this fixed-column boundary scenario (viewBox[0] = 820):
  // frame right edge = 820 - 48 = 772
  // labelBox.x = 56
  // availableWidth = 772 - 56 = 716px
  // 135 ASCII units -> labelW = 135 * 5.2 + 14 = 716px -> label right edge = 56 + 716 = 772px (exact fit)
  // 136 ASCII units -> labelW = 136 * 5.2 + 14 = 721.2px -> label right edge = 56 + 721.2 = 777.2px
  // (777.2px <= 820 canvas width, but > 772 segment frame edge)

  // 1. Fits within canvas (777.2 <= 820) but exceeds segment frame (777.2 > 772)
  const dExceed = load('sequence');
  dExceed.meta.viewBox[0] = 820;
  dExceed.meta.column_fit = 'fixed';
  dExceed.segments[0].label = 'A'.repeat(136);
  const resExceed = render('sequence', dExceed);
  assert.equal(resExceed.code, 1, 'label exceeding segment frame must fail even if within canvas');
  assert.match(resExceed.stderr, /label \(~721px\) exceeds the segment frame's available width \(716px\) — shorten the label or increase meta\.viewBox\[0\] to at least 826\./);

  // 2. Exact-fit case at the frame's right edge (56 + 716 = 772 === 820 - 48)
  const dExact = load('sequence');
  dExact.meta.viewBox[0] = 820;
  dExact.meta.column_fit = 'fixed';
  dExact.segments[0].label = 'A'.repeat(135);
  const resExact = render('sequence', dExact);
  assert.equal(resExact.code, 0, `exact-fit label at segment frame boundary must pass cleanly: ${resExact.stderr}`);
});

process.on('exit', () => fs.rmSync(tmp, { recursive: true, force: true }));