Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.
HTML agent-skillsai-agentsarchitecture-diagramclaude-codeclaude-skillscodexcoding-agentsdeepseek-harnessdeveloper-toolsdiagramsdiagrams-as-codedsh-pluginflowchartllmmermaidopencodesequence-diagramsoftware-architecturesystem-designvisualization
fix(sequence): structured note diagnostics and tie-safe lane gaps (#676)
yarrbakr0021fd32ea9d
diff --git a/archify/renderers/sequence/README.md b/archify/renderers/sequence/README.mdindex 8f7c4e2a..d8e5fa22 100644--- a/archify/renderers/sequence/README.md+++ b/archify/renderers/sequence/README.md@@ -73,7 +73,7 @@ muted text color.| Message `y` range | `[160, height − 83]` || Message spacing | ≥28px vertical between messages that share horizontal space || Arrow span | ≥60px horizontal between the two participants |-| Message notes | 7px fine-detail text under the arrow, wrapped at 11px line spacing inside one gap between neighbouring lifelines (the widest gap the message spans, the left-most on a tie, where notes have always started), clear of activation bars; long unbroken text breaks after `/ . - ? & = # _`, otherwise at any character, so the full note is kept in every export. In `showcase`, a note that reaches a later message fails with the `y` that message needs, a note past the canvas content limit fails with the `meta.viewBox[1]` it needs, and segment labels step up clear of notes or fail when no clear position remains |+| Message notes | 7px fine-detail text under the arrow, wrapped at 11px line spacing inside one gap between neighbouring lifelines (the widest gap the message spans; gaps within 0.5px count as equal and resolve to the left-most, where notes have always started), clear of activation bars; long unbroken text breaks after `/ . - ? & = # _`, otherwise at any character, so the full note is kept in every export. In `showcase`, a note that reaches a later message fails as `sequence/note-overlap` with the `y` that message needs, a note past the canvas content limit fails as `sequence/note-canvas-limit` with the `meta.viewBox[1]` it needs, and a segment label still covering a message label, route or note after its four upward steps fails as `sequence/segment-label-overlap`; each diagnostic names the source path and offers a verified `supportedFixes` edit when one exists || Segments | y pixel ranges with `to > from`, inside `[72, lifeline bottom + 20]` || Legend | last row baseline at height − 54; extra rows wrap upward and stay 12px below the timeline content |diff --git a/archify/renderers/sequence/render-sequence.mjs b/archify/renderers/sequence/render-sequence.mjsindex 311642e0..0137f200 100644--- a/archify/renderers/sequence/render-sequence.mjs+++ b/archify/renderers/sequence/render-sequence.mjs@@ -83,6 +83,9 @@ const NOTE_ARROW_INSET = 7;const NOTE_TEXT_INSET = 12;// Activation bars reach 5px past a lifeline; keep 6px of air beyond them.const NOTE_LIFELINE_CLEARANCE = 11;+// Spread columns share one computed gap, but subtracting floating-point column+// centres can differ in the last digits; such gaps still count as equal.+const NOTE_GAP_TOLERANCE = 0.5;const NOTE_BREAK_AFTER = new Set(['/', '.', '-', '?', '&', '=', '#', '_']);const noteSegmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });const noteLayouts = new Map();@@ -140,7 +143,7 @@ function noteGapIndex(fromIndex, toIndex) {let best = null;for (let gap = low; gap < high; gap += 1) {const width = participantX(gap + 1) - participantX(gap);- if (!best || width > best.width) best = { gap, width };+ if (!best || width > best.width + NOTE_GAP_TOLERANCE) best = { gap, width };}return best?.gap ?? null;}@@ -273,19 +276,56 @@ function messageRouteBox(message) {};}+// Message labels, routes and notes a segment label must not cover, with the+// source path of each so a failure can name what it hides.+function segmentLabelOccupants() {+ return asArray(sequence.messages).flatMap((message, messageIndex) => [+ { kind: 'message label', path: `/messages/${messageIndex}/label`, message, rect: messageLabelBox(message) },+ { kind: 'message route', path: `/messages/${messageIndex}/y`, message, rect: messageRouteBox(message) },+ { kind: 'note', path: `/messages/${messageIndex}/note`, message, rect: noteRect(message) },+ ]).filter((occupant) => occupant.rect);+}+function segmentLabelBox(segment) {const labelW = Math.max(42, textUnits(segment.label) * 5.2 + 14);- const occupied = asArray(sequence.messages)- .flatMap((message) => [messageLabelBox(message), messageRouteBox(message), noteRect(message)])- .filter(Boolean);+ const occupied = segmentLabelOccupants();const label = { x: 56, y: segment.from - 22, width: labelW, height: 18 };for (let attempt = 0; attempt < 4; attempt += 1) {- if (!occupied.some((rect) => rectsOverlap(label, rect, 2))) break;+ if (!occupied.some(({ rect }) => rectsOverlap(label, rect, 2))) break;label.y -= 22;}return label;}+// Whether moving one message to `y` keeps it readable: inside the timeline,+// 28px from messages sharing its horizontal span, and clear of every other+// label, route and note. Used to offer only repairs that hold.+function messageFitsAt(messageIndex, y) {+ const messages = asArray(sequence.messages);+ if (y < layout.lifelineTop + 18 || y > layout.lifelineBottom - 18) return false;+ const span = (message) => {+ const from = participants.get(message.from)?.cx;+ const to = participants.get(message.to)?.cx;+ return [Math.min(from, to), Math.max(from, to)];+ };+ const moved = { ...messages[messageIndex], y };+ const [left, right] = span(moved);+ const movedRects = [messageLabelBox(moved), messageRouteBox(moved), noteRect(moved)].filter(Boolean);+ return messages.every((other, otherIndex) => {+ if (otherIndex === messageIndex || typeof other.y !== 'number') return true;+ const [otherLeft, otherRight] = span(other);+ if (Math.abs(other.y - y) < 28 && left < otherRight && otherLeft < right) return false;+ const otherRects = [messageLabelBox(other), messageRouteBox(other), noteRect(other)].filter(Boolean);+ return !movedRects.some((rect) => otherRects.some((otherRect) => rectsOverlap(rect, otherRect, 2)));+ });+}++// The first occupant the segment label still covers after its upward steps.+function segmentLabelBlocker(segment) {+ const label = segmentLabelBox(segment);+ return segmentLabelOccupants().find(({ rect }) => rectsOverlap(label, rect, 2)) || null;+}+const compositionFrames = asArray(sequence.segments).map((segment, index) => ({id: index,label: segment.label,@@ -473,6 +513,16 @@ function validateSequence() {// later message or the canvas bottom needs the diagram changed; authored y// values and viewBox stay as written. Showcase only, so standard keeps// accepting existing diagrams.+ const report = (problem, detail) => {+ problems.push(problem);+ diagnostics.push({ severity: 'error', message: problem, ...detail });+ };+ const bounds = (rect) => ({+ x: Math.round(rect.x * 10) / 10,+ y: Math.round(rect.y * 10) / 10,+ width: Math.round(rect.width * 10) / 10,+ height: Math.round(rect.height * 10) / 10,+ });if (readableMessages) {const messages = asArray(sequence.messages);const noteFloor = layout.lifelineBottom + 20;@@ -481,26 +531,57 @@ function validateSequence() {if (!note) return;const lines = note.lines.length === 1 ? '1 line' : `${note.lines.length} lines`;const bottom = Math.ceil(note.bottom);+ const ownRect = noteRect(message);+ const subject = {+ diagramType: 'sequence',+ message: message.label ?? null,+ path: `/messages/${messageIndex}/note`,+ from: message.from,+ to: message.to,+ };if (note.bottom > noteFloor) {- const requiredHeight = Math.ceil(viewBox[1] + note.bottom - noteFloor);- problems.push(`Note on message "${message.label}" wraps to ${lines} and ends at y=${bottom}, below the canvas content limit y=${noteFloor} — set meta.viewBox[1] to at least ${requiredHeight}, move the message up, or shorten the note.`);+ // A visible legend needs its own room below the note as well.+ const requiredHeight = Math.max(Math.ceil(viewBox[1] + note.bottom - noteFloor), legendRequiredHeight(viewBox[0]));+ const fix = sequence.meta?.viewBox+ ? `set /meta/viewBox/1 to ${requiredHeight}`+ : `set /meta/viewBox to [${viewBox[0]}, ${requiredHeight}]`;+ report(`Note on message "${message.label}" wraps to ${lines} and ends at y=${bottom}, below the canvas content limit y=${noteFloor} — set meta.viewBox[1] to at least ${requiredHeight}, move the message up, or shorten the note.`, {+ code: 'sequence/note-canvas-limit',+ subject,+ evidence: { lines: note.lines.length, note: bounds(ownRect), canvasLimitY: noteFloor, viewBoxHeight: viewBox[1], requiredViewBoxHeight: requiredHeight },+ supportedFixes: [fix],+ });}- const ownRect = noteRect(message);const blocker = messages.map((other, otherIndex) => {if (otherIndex === messageIndex || typeof other.y !== 'number' || other.y <= message.y) return null;- const rects = [messageLabelBox(other), messageRouteBox(other), noteRect(other)].filter(Boolean);- return rects.some((rect) => rectsOverlap(ownRect, rect, 2)) ? other : null;+ const hit = [+ ['message label', messageLabelBox(other)],+ ['message route', messageRouteBox(other)],+ ['note', noteRect(other)],+ ].find(([, rect]) => rect && rectsOverlap(ownRect, rect, 2));+ return hit ? { message: other, index: otherIndex, kind: hit[0], rect: hit[1] } : null;}).filter(Boolean)- .sort((a, b) => a.y - b.y)[0];+ .sort((a, b) => a.message.y - b.message.y)[0];if (!blocker) return;const requiredY = Math.ceil(note.bottom + 22);- problems.push(`Note on message "${message.label}" wraps to ${lines} (down to y=${bottom}) and reaches message "${blocker.label}" at y=${blocker.y} — move "${blocker.label}" and later messages down so it sits at y=${requiredY} or below, or shorten the note.`);+ const blockerPath = `/messages/${blocker.index}/y`;+ report(`Note on message "${message.label}" wraps to ${lines} (down to y=${bottom}) and reaches message "${blocker.message.label}" at y=${blocker.message.y} — move "${blocker.message.label}" and later messages down so it sits at y=${requiredY} or below, or shorten the note.`, {+ code: 'sequence/note-overlap',+ subject,+ evidence: {+ lines: note.lines.length,+ note: bounds(ownRect),+ blocker: { message: blocker.message.label ?? null, path: blockerPath, y: blocker.message.y, kind: blocker.kind, bounds: bounds(blocker.rect) },+ requiredY,+ },+ supportedFixes: messageFitsAt(blocker.index, requiredY) ? [`set ${blockerPath} to ${requiredY}`] : [],+ });});}- for (const segment of asArray(sequence.segments)) {+ asArray(sequence.segments).forEach((segment, segmentIndex) => {if (segment.to <= segment.from) {problems.push(`Segment "${segment.label}" has invalid y range (from ${segment.from} to ${segment.to}) — "to" must be greater than "from".`);}@@ -513,18 +594,34 @@ function validateSequence() {const requiredWidth = Math.ceil(labelBox.x + labelBox.width + 48);problems.push(`Segment "${segment.label}" label (~${Math.round(labelBox.width)}px) exceeds the segment frame's available width (${availableWidth}px) — shorten the label or increase meta.viewBox[0] to at least ${requiredWidth}.`);}- // Segment labels are drawn above notes and step up to stay clear of them;- // in showcase, a label with no clear position would hide note text.- if (readableMessages) {- const covered = asArray(sequence.messages).find((message) => {- const rect = noteRect(message);- return rect && rectsOverlap(labelBox, rect, 2);- });- if (covered) {- problems.push(`Segment "${segment.label}" label would cover the note on message "${covered.label}" — move the segment start (from: ${segment.from}) or that message so they are further apart, or shorten the note.`);+ // Segment labels are drawn above messages and notes and step up to stay+ // clear of them; in showcase, a label left covering any of them fails.+ const covered = readableMessages ? segmentLabelBlocker(segment) : null;+ if (covered) {+ // Offer the nearest start whose label lands clear, inside the segment.+ let clearFrom = null;+ for (let distance = 1; distance <= 300 && clearFrom === null; distance += 1) {+ for (const candidate of [segment.from + distance, segment.from - distance]) {+ if (candidate < layout.topY || candidate >= segment.to) continue;+ if (!segmentLabelBlocker({ ...segment, from: candidate })) {+ clearFrom = candidate;+ break;+ }+ }}+ const fromPath = `/segments/${segmentIndex}/from`;+ report(`Segment "${segment.label}" label would cover the ${covered.kind} of message "${covered.message.label}" — move the segment start (from: ${segment.from}) or that message so they are further apart${covered.kind === 'note' ? ', or shorten the note' : ''}.`, {+ code: 'sequence/segment-label-overlap',+ subject: { diagramType: 'sequence', segment: segment.label ?? null, path: fromPath },+ evidence: {+ label: bounds(labelBox),+ attempts: 4,+ covered: { kind: covered.kind, message: covered.message.label ?? null, path: covered.path, bounds: bounds(covered.rect) },+ },+ supportedFixes: clearFrom === null ? [] : [`set ${fromPath} to ${clearFrom}`],+ });}- }+ });for (const activation of asArray(sequence.activations)) {if (!participants.has(activation.participant)) problems.push(`Activation references unknown participant "${activation.participant}".`);diff --git a/test/sequence-note-wrap.test.mjs b/test/sequence-note-wrap.test.mjsindex 05375277..9db6de9a 100644--- a/test/sequence-note-wrap.test.mjs+++ b/test/sequence-note-wrap.test.mjs@@ -138,6 +138,19 @@ test('a short note on a reverse message that skips a participant keeps its origiassert.match(html, new RegExp(`<text data-detail="fine" x="${client + 19}" y="218" class="t-dim" font-size="7">from replica</text>`));});+test('equal spread gaps that differ only by floating-point rounding keep the left-most gap', (t) => {+ // Six and seven spread columns produce middle gaps such as 141.80000000000007.+ for (const count of [6, 7]) {+ const ids = Array.from({ length: count }, (_, index) => `p${index}`);+ for (const [from, to] of [[ids.at(-1), ids[0]], [ids[0], ids.at(-1)]]) {+ const html = render(t, sequence({ participants: ids, messages: [{ from, to, y: 200, label: 'reply', note: 'ok' }] }));+ const [first] = lifelines(html);+ const [note] = notes(html);+ assert.ok(Math.abs(note.x - (first + 19)) < 1e-9, `${count} participants, ${from} → ${to}: note at ${note.x}, expected ${first + 19}`);+ }+ }+});+// Fixed columns keep the first note beside the segment label column at x=56.test('a segment label steps up clear of a wrapped note', (t) => {const spec = sequence({@@ -155,6 +168,46 @@ test('a segment label steps up clear of a wrapped note', (t) => {`segment label at y=${labelY} clears the note from ${noteTop}`);});+// Read one structured diagnostic from `validate --json` and apply its single+// supported fix ("set /json/pointer to value") to a copy of the input.+function failure(t, spec, code) {+ const { result } = run(t, 'validate', spec);+ assert.notEqual(result.status, 0, 'validate must fail');+ const diagnostic = JSON.parse(result.stdout).diagnostics.find((entry) => entry.code === code);+ assert.ok(diagnostic, `expected ${code} in ${result.stdout}`);+ assert.equal(diagnostic.severity, 'error');+ return diagnostic;+}++function applyFix(spec, fix) {+ const [, pointer, value] = fix.match(/^set (\/\S+) to (.+)$/);+ const copy = structuredClone(spec);+ const keys = pointer.slice(1).split('/');+ const parent = keys.slice(0, -1).reduce((node, key) => {+ node[key] ??= {};+ return node[key];+ }, copy);+ parent[keys.at(-1)] = JSON.parse(value);+ return copy;+}++test('a segment label left covering a message label reports it with a verified fix', (t) => {+ // The reviewer's case: the wrapped note pushes the label up onto "request".+ const spec = sequence({ messages: [{ from: 'client', to: 'api', y: 200, label: 'request', note: LONG_NOTE }] });+ spec.meta.column_fit = 'fixed';+ spec.segments = [{ label: 'Fallback', from: 280, to: 360 }];+ const diagnostic = failure(t, spec, 'sequence/segment-label-overlap');+ assert.deepEqual(diagnostic.subject, { diagramType: 'sequence', segment: 'Fallback', path: '/segments/0/from' });+ assert.equal(diagnostic.evidence.attempts, 4);+ assert.equal(diagnostic.evidence.covered.kind, 'message label');+ assert.equal(diagnostic.evidence.covered.path, '/messages/0/label');+ assert.equal(diagnostic.evidence.covered.message, 'request');+ assert.equal(diagnostic.supportedFixes.length, 1);+ assert.match(diagnostic.supportedFixes[0], /^set \/segments\/0\/from to \d+$/);+ const repaired = run(t, 'validate', applyFix(spec, diagnostic.supportedFixes[0])).result;+ assert.equal(repaired.status, 0, repaired.stdout);+});+test('a segment label with no clear position names the note it would cover', (t) => {const spec = sequence({messages: [@@ -164,9 +217,12 @@ test('a segment label with no clear position names the note it would cover', (t)});spec.meta.column_fit = 'fixed';spec.segments = [{ label: 'Fallback', from: 360, to: 400 }];- const { result } = run(t, 'validate', spec);- assert.notEqual(result.status, 0);- assert.match(result.stdout, /Segment \\"Fallback\\" label would cover the note on message \\"request\\"/);+ const diagnostic = failure(t, spec, 'sequence/segment-label-overlap');+ assert.equal(diagnostic.evidence.covered.kind, 'note');+ assert.equal(diagnostic.evidence.covered.path, '/messages/1/note');+ for (const fix of diagnostic.supportedFixes) {+ assert.equal(run(t, 'validate', applyFix(spec, fix)).result.status, 0, `${fix} must hold`);+ }});test('a wrapped note below an authored canvas reports the height it needs', (t) => {@@ -174,11 +230,15 @@ test('a wrapped note below an authored canvas reports the height it needs', (t)...sequence({ messages: [{ id: 'late', from: 'client', to: 'api', y: 660, label: 'late', note: LONG_NOTE.repeat(3) }] }),meta: { title: 'Fixed canvas', output: 'note.html', quality_profile: 'showcase', column_fit: 'spread', viewBox: [920, height], legend: { mode: 'hidden' } },});- const failed = run(t, 'validate', spec(760)).result;- assert.notEqual(failed.status, 0);- const required = Number(failed.stdout.match(/set meta\.viewBox\[1\] to at least (\d+)/)?.[1]);- assert.ok(required > 760, failed.stdout);- const repaired = run(t, 'validate', spec(required)).result;+ const diagnostic = failure(t, spec(760), 'sequence/note-canvas-limit');+ assert.equal(diagnostic.subject.path, '/messages/0/note');+ assert.equal(diagnostic.subject.message, 'late');+ assert.equal(diagnostic.evidence.viewBoxHeight, 760);+ assert.equal(diagnostic.evidence.canvasLimitY, 760 - 65 + 20);+ assert.ok(diagnostic.evidence.note.y + diagnostic.evidence.note.height > diagnostic.evidence.canvasLimitY);+ const required = diagnostic.evidence.requiredViewBoxHeight;+ assert.deepEqual(diagnostic.supportedFixes, [`set /meta/viewBox/1 to ${required}`]);+ const repaired = run(t, 'validate', applyFix(spec(760), diagnostic.supportedFixes[0])).result;assert.equal(repaired.status, 0, repaired.stdout);const standard = spec(760);standard.meta.quality_profile = 'standard';@@ -193,15 +253,18 @@ test('a wrapped note that reaches the next message names the message and the y i{ id: 'reply', from: 'api', to: 'client', y: replyY, label: 'reply', variant: 'return' },],});- const failed = run(t, 'validate', crowded(230)).result;- assert.notEqual(failed.status, 0);- const receipt = JSON.parse(failed.stdout);- const message = receipt.diagnostics.map((entry) => entry.message).join('\n');- assert.match(message, /Note on message "request" wraps to \d+ lines/);- const requiredY = Number(message.match(/move "reply" and later messages down so it sits at y=(\d+) or below/)?.[1]);- assert.ok(requiredY > 230, message);-- const repaired = run(t, 'validate', crowded(requiredY)).result;+ const diagnostic = failure(t, crowded(230), 'sequence/note-overlap');+ assert.match(diagnostic.message, /Note on message "request" wraps to \d+ lines/);+ assert.deepEqual(diagnostic.subject, { diagramType: 'sequence', message: 'request', path: '/messages/0/note', from: 'client', to: 'api' });+ assert.equal(diagnostic.evidence.blocker.path, '/messages/1/y');+ assert.equal(diagnostic.evidence.blocker.message, 'reply');+ assert.equal(diagnostic.evidence.blocker.y, 230);+ assert.ok(diagnostic.evidence.lines > 1);+ const requiredY = diagnostic.evidence.requiredY;+ assert.ok(requiredY > 230);+ assert.deepEqual(diagnostic.supportedFixes, [`set /messages/1/y to ${requiredY}`]);++ const repaired = run(t, 'validate', applyFix(crowded(230), diagnostic.supportedFixes[0])).result;assert.equal(repaired.status, 0, repaired.stdout);const html = render(t, crowded(requiredY));assert.equal(decode(notes(html)[0].lines.join(' ')), LONG_NOTE);