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
feat: improve diagram authoring feedback and readability (#805)
tt-a1i07a2848dce39
diff --git a/archify.zip b/archify.zipindex 59b52548..b8c9b1ff 100644Binary files a/archify.zip and b/archify.zip differdiff --git a/archify/SKILL.md b/archify/SKILL.mdindex 9c7332df..abcab46a 100644--- a/archify/SKILL.md+++ b/archify/SKILL.md@@ -10,7 +10,7 @@ metadata:# Archify-Create an interactive HTML diagram from typed JSON. Static output is the default; enable motion only when requested.+Create an interactive HTML diagram from typed JSON.Run commands from your working directory. Unless the user names another location, give each new diagram request its own folder `.archify/<type>-<slug>-<YYYYMMDD-HHMMSS>/` there (local time, chosen once when the request starts): keep `candidate.json` and `<slug>.html` in it, set `meta.output` to that HTML path relative to the working directory, and reuse the folder for every repair rerun. A later request gets a new folder, so earlier versions stay intact. Replace `bin/archify.mjs` in the commands below with the installed package's absolute path, or its path relative to your working directory; input and output paths resolve from that working directory.diff --git a/archify/bin/archify.mjs b/archify/bin/archify.mjsindex 62c9bfe9..f2ca6a4b 100755--- a/archify/bin/archify.mjs+++ b/archify/bin/archify.mjs@@ -1871,9 +1871,9 @@ function recordDeliveryFailure(options) {return recorded;}-// Locale warnings for a successfully rendered candidate. The renderer prints-// them to stderr; receipts carry the same diagnostics from the same pure-// resolver so an agent can repair a translation gap from structured output.+// Locale warnings for a successfully rendered candidate. Diagnostic renderers+// record them without printing text; validate/deliver disclose them before+// checking the artifact and reuse the same diagnostics in successful receipts.async function specificationLocaleDiagnostics(type, specification) {let meta;try {@@ -2188,25 +2188,30 @@ function invalidProvenance(artifactPath, sidecar, reason, evidence = {}) {};}+const COMMAND_USAGE = {+ render: '<type> <input.json> [output.html] [--quality standard|showcase] [--repo-root path]',+ compare: 'architecture <base.json> <head.json> [output.html] [--receipt path] [--json] [--quality standard|showcase] [--repo-root path]',+ deliver: '<type> <input.json> [output.html] [--json] [--open] [--quality standard|showcase] [--repo-root path]',+ finalize: '<type> <input.json> <output.html> [--json] [--receipt path] [--out-dir <dir>] [--quality standard|showcase] [--repo-root path] [--candidate-sha256 hex]',+ preview: '<type> <input.json> [output.html] [--no-open] [--quality standard|showcase] [--repo-root path]',+ validate: '<type> <input.json> [--json] [--layout-json] [--quality standard|showcase] [--repo-root path]',+ migrate: 'workflow <old.json> <new.json> --to-schema 2 [--output portable.html] [--json] [--repo-root path]',+ inspect: '<type> <input.json>',+ check: '<output.html> [--json] [--require-provenance]',+ 'browser-check': '<output.html> [--json|--summary] [--require-provenance] [--out-dir <dir>]',+ 'visual-check': '<output.html> [--json|--summary] [--require-provenance] [--out-dir <dir>]',+ guide: '[scenario or question] [--json] [--lang en|zh]',+ brands: ['[name, alias, domain, or category] [--json]', 'capture <url> [--json]'],+ examples: '',+ doctor: '',+ demo: '[output-directory]',+};+function usage() {+ const commands = Object.entries(COMMAND_USAGE).flatMap(([command, forms]) =>+ (Array.isArray(forms) ? forms : [forms]).map(form => ` archify ${command}${form ? ` ${form}` : ''}`));return `Usage:- archify render <type> <input.json> [output.html] [--quality standard|showcase] [--repo-root path]- archify compare architecture <base.json> <head.json> [output.html] [--receipt path] [--json] [--quality standard|showcase] [--repo-root path]- archify deliver <type> <input.json> [output.html] [--json] [--open] [--quality standard|showcase] [--repo-root path]- archify finalize <type> <input.json> <output.html> [--json] [--receipt path] [--out-dir <dir>] [--quality standard|showcase] [--repo-root path] [--candidate-sha256 hex]- archify preview <type> <input.json> [output.html] [--no-open] [--quality standard|showcase] [--repo-root path]- archify validate <type> <input.json> [--json] [--layout-json] [--quality standard|showcase] [--repo-root path]- archify migrate workflow <old.json> <new.json> --to-schema 2 [--output portable.html] [--json] [--repo-root path]- archify inspect <type> <input.json>- archify check <output.html> [--json] [--require-provenance]- archify browser-check <output.html> [--json|--summary] [--require-provenance] [--out-dir <dir>]- archify visual-check <output.html> [--json|--summary] [--require-provenance] [--out-dir <dir>]- archify guide [scenario or question] [--json] [--lang en|zh]- archify brands [name, alias, domain, or category] [--json]- archify brands capture <url> [--json]- archify examples- archify doctor- archify demo [output-directory]+${commands.join('\n')}Types:architecture, workflow, sequence, dataflow, lifecycle, erd, tree, class, timeline, waterfall@@ -4826,6 +4831,8 @@ async function commandDeliver(args) {return;}if (render.stderr) process.stderr.write(render.stderr);+ const localeWarnings = await specificationLocaleDiagnostics(type, specification);+ for (const warning of localeWarnings) process.stderr.write(`archify: ${warning.message}\n`);try {const renderedCandidate = fs.readFileSync(candidatePath);if (preparedDeliveryTargets.artifact.mode !== null) {@@ -4943,7 +4950,6 @@ async function commandDeliver(args) {return;}const engineeringProfile = engineeringProfileFromArtifact(artifact);- const localeWarnings = await specificationLocaleDiagnostics(type, specification);const receipt = {schemaVersion: 1,receiptId,@@ -6936,6 +6942,8 @@ async function commandValidate(args, invocation = {}) {exitCode = render.status ?? 1;} else {if (render.stderr) process.stderr.write(render.stderr);+ const localeWarnings = await specificationLocaleDiagnostics(type, specification);+ for (const warning of localeWarnings) process.stderr.write(`archify: ${warning.message}\n`);const checkMaxBuffer = artifactCheckMaxBuffer();const check = runNode([path.join(skillRoot, 'scripts/check-render-output.mjs'), out], {stdio: 'pipe',@@ -6982,7 +6990,6 @@ async function commandValidate(args, invocation = {}) {...artifactIdentity(specification),};const resolvedQuality = quality || result.composition.profile || 'standard';- const localeWarnings = await specificationLocaleDiagnostics(type, specification);const receipt = {schemaVersion: 1,ok: true,@@ -7048,9 +7055,13 @@ async function commandValidate(args, invocation = {}) {}const [command, ...args] = process.argv.slice(2);+// Reuse the canonical help metadata rather than a separate help registry.+// Only the sole --help form bypasses command argument parsing and operations.+const soleCommandHelp = args.length === 1 && args[0] === '--help'+ && Object.hasOwn(COMMAND_USAGE, command);try {- switch (command) {+ switch (soleCommandHelp ? '--help' : command) {case undefined:case '-h':case '--help':diff --git a/archify/bin/finalize.mjs b/archify/bin/finalize.mjsindex d3b39f0f..728c6f64 100644--- a/archify/bin/finalize.mjs+++ b/archify/bin/finalize.mjs@@ -612,6 +612,13 @@ export function compactFinalizeReceipt(receipt) {addDiagnostic(entry, index);}for (const [index, entry] of allDiagnostics.entries()) addDiagnostic(entry, index);+ const truncated = allDiagnostics.length > selectedDiagnostics.length;+ const omittedCounts = new Map();+ if (truncated) {+ for (const [index, entry] of allDiagnostics.entries()) {+ omittedCounts.set(entry.code, (omittedCounts.get(entry.code) || 0) + (selectedIndexes.has(index) ? 0 : 1));+ }+ }const compact = {schemaVersion: 1,ok: receipt.ok,@@ -627,7 +634,8 @@ export function compactFinalizeReceipt(receipt) {diagnosticSummary: {total: allDiagnostics.length,shown: selectedDiagnostics.length,- truncated: allDiagnostics.length > selectedDiagnostics.length,+ truncated,+ ...(truncated ? { omittedByCode: Object.fromEntries([...omittedCounts].filter(([, count]) => count > 0)) } : {}),},evidence: receipt.evidence,...(receipt.update && receipt.update.status !== 'unavailable'diff --git a/archify/examples/lifecycle-agent-run.html b/archify/examples/lifecycle-agent-run.htmlindex 56abd288..5b02faa9 100644--- a/archify/examples/lifecycle-agent-run.html+++ b/archify/examples/lifecycle-agent-run.html@@ -5183,7 +5183,7 @@ OTHER DEALINGS IN THE FONT SOFTWARE.</g><g data-detail="context" data-edge-from="approval" data-edge-to="executing" data-edge-label="approved" data-edge-key="5" data-edge-id="approval-executing"><rect x="505" y="165" width="60" height="16" rx="4" class="c-mask"/>- <text x="535" y="176.5" class="t-edge-default" font-size="10" text-anchor="middle">approved</text>+ <text x="535" y="176.5" class="t-muted" font-size="10" text-anchor="middle">approved</text></g><g data-detail="context" data-edge-from="approval" data-edge-to="cancelled" data-edge-label="user denies" data-edge-key="6" data-edge-id="approval-cancelled"><rect x="402" y="304" width="78" height="16" rx="4" class="c-mask"/>@@ -5199,11 +5199,11 @@ OTHER DEALINGS IN THE FONT SOFTWARE.</g><g data-detail="context" data-edge-from="reviewing" data-edge-to="blocked" data-edge-label="needs input" data-edge-key="9" data-edge-id="reviewing-blocked"><rect x="757" y="165" width="78" height="16" rx="4" class="c-mask"/>- <text x="796" y="176.5" class="t-edge-default" font-size="10" text-anchor="middle">needs input</text>+ <text x="796" y="176.5" class="t-muted" font-size="10" text-anchor="middle">needs input</text></g><g data-detail="context" data-edge-from="blocked" data-edge-to="reviewing" data-edge-label="input given" data-edge-key="10" data-edge-id="blocked-reviewing"><rect x="873" y="156" width="78" height="16" rx="4" class="c-mask"/>- <text x="912" y="167.5" class="t-edge-default" font-size="10" text-anchor="middle">input given</text>+ <text x="912" y="167.5" class="t-muted" font-size="10" text-anchor="middle">input given</text></g><g data-detail="context" data-edge-from="blocked" data-edge-to="expired" data-edge-label="no reply 24h" data-edge-key="11" data-edge-id="blocked-expired"><rect x="764" y="304" width="84" height="16" rx="4" class="c-mask"/>diff --git a/archify/examples/sequence-cache-miss-request.html b/archify/examples/sequence-cache-miss-request.htmlindex 348b8c50..4f9b0053 100644--- a/archify/examples/sequence-cache-miss-request.html+++ b/archify/examples/sequence-cache-miss-request.html@@ -5107,16 +5107,16 @@ OTHER DEALINGS IN THE FONT SOFTWARE.<!-- Segment Labels --><g data-graph-role="segment-label" data-segment-id="0">- <rect x="56" y="128" width="50.4" height="18" rx="3" class="c-mask"/>- <text x="62" y="141" class="t-dim" font-size="9" font-weight="600">Request</text>+ <rect x="56" y="134" width="50.4" height="18" rx="3" class="c-mask"/>+ <text x="62" y="147" class="t-muted" font-size="9" font-weight="600">Request</text></g><g data-graph-role="segment-label" data-segment-id="1"><rect x="56" y="238" width="55.6" height="18" rx="3" class="c-mask"/>- <text x="62" y="251" class="t-dim" font-size="9" font-weight="600">Fallback</text>+ <text x="62" y="251" class="t-muted" font-size="9" font-weight="600">Fallback</text></g><g data-graph-role="segment-label" data-segment-id="2"><rect x="56" y="358" width="97.2" height="18" rx="3" class="c-mask"/>- <text x="62" y="371" class="t-dim" font-size="9" font-weight="600">Response + trace</text>+ <text x="62" y="371" class="t-muted" font-size="9" font-weight="600">Response + trace</text></g><!-- Participants -->diff --git a/archify/examples/workflow-agent-tool-call-rendered.html b/archify/examples/workflow-agent-tool-call-rendered.htmlindex 0726793e..a93c4804 100644--- a/archify/examples/workflow-agent-tool-call-rendered.html+++ b/archify/examples/workflow-agent-tool-call-rendered.html@@ -4980,17 +4980,17 @@ OTHER DEALINGS IN THE FONT SOFTWARE.<!-- Swimlanes --><rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-0" x="40" y="52" width="1040" height="106" rx="10" class="c-lane" stroke-width="1"/>- <text x="54" y="74" class="t-dim" font-size="10" font-weight="600">01 / User Interface</text>+ <text x="54" y="74" class="t-muted" font-size="10" font-weight="600">01 / User Interface</text><rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-1" x="40" y="178" width="1040" height="114" rx="10" class="c-lane" stroke-width="1"/>- <text x="54" y="200" class="t-dim" font-size="10" font-weight="600">02 / Agent Runtime</text>+ <text x="54" y="200" class="t-muted" font-size="10" font-weight="600">02 / Agent Runtime</text><rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-2" x="40" y="312" width="1040" height="114" rx="10" class="c-lane" stroke-width="1"/><rect data-graph-role="structural-frame" data-composition-frame-kind="exception-lane" data-composition-frame-id="lane-2-exception" x="46" y="318" width="1028" height="102" rx="8" class="c-security-group" stroke-width="1"/><text x="54" y="334" class="t-security" font-size="10" font-weight="600">EX / Policy & Recovery</text><rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-3" x="40" y="446" width="1040" height="114" rx="10" class="c-lane" stroke-width="1"/>- <text x="54" y="468" class="t-dim" font-size="10" font-weight="600">04 / Tool Execution & Evidence</text>+ <text x="54" y="468" class="t-muted" font-size="10" font-weight="600">04 / Tool Execution & Evidence</text><!-- Phase headers --><line x1="68" y1="35" x2="324" y2="35" class="a-default" stroke-width="1.1"/>diff --git a/archify/references/authoring-contract.md b/archify/references/authoring-contract.mdindex 95c6f6ec..1414387a 100644--- a/archify/references/authoring-contract.md+++ b/archify/references/authoring-contract.md@@ -502,9 +502,15 @@ the initial state; every consecutive pair needs a transition. The renderer ownsall geometry: the main path is one row, transitions back to an earlier phase(or skipping ahead) become arcs above it, and every other state sits below thestate it branches from, one row deeper per step away from the main path.-Exits that several consecutive phases share (for example “cancel” from any-running phase) are drawn once from a composite frame around those phases; give-them the same label. There are no lanes, columns, sizes, or routing controls.+Equivalent exits share one arrow only when their labels, notes and variants+match and exactly one group from at least two main-path phases qualifies for+that target. Consecutive phases receive a composite frame; non-consecutive+phases share a bus. Other exits stay separate, including distinct notes on+their original transitions. Do not remove or copy notes to force sharing.+There are no lanes, columns, sizes, or routing controls. Layout retries retain+the transition text's minimum gap and stop widening the main-path row when its+minimum width would exceed the original text readability budget; the final+width and label-clearance checks still apply.Keep the main path to the phases a reader follows, at most about six states,and keep transition labels short. A recoverable failure needs a real transitiondiff --git a/archify/references/authoring-defaults.md b/archify/references/authoring-defaults.mdindex d1a3e8fe..92f0000d 100644--- a/archify/references/authoring-defaults.md+++ b/archify/references/authoring-defaults.md@@ -40,7 +40,7 @@ Omit `meta.visual_preset` for classic, `meta.subtitle` for a title-only header,For a fresh Workflow use schema v2 and omit `meta.viewBox` so the compiler measures the real footprint; do not add empty canvas just to satisfy a viewport ratio. Preserve supplied fixed geometry and v1 sources. In an unpinned draft, omit node `width`: a node starts at 92px and grows to fit its label, sublabel and tag up to 200px. Explicit canvases and absolute route or label pins retain the previous geometry contract. Use its [layout contracts](../renderers/workflow/README.md#layout-contracts) when lane or group geometry needs detail.-For a fresh Sequence omit `meta.viewBox` and `meta.column_fit`: automatic height fits the timeline (no 760px floor), 2–3 short-label participants pack below 920px when labels fit, and the canvas still widens for crowded labels up to its readable width; preserve an authored `meta.viewBox`. Set `meta.column_fit: "fixed"` explicitly when historical fixed coordinates are required; use `spread` when a wide viewBox leaves unused horizontal space or meaningful labels need width. Describe a participant's internal action in a note on its surrounding real cross-participant message, preserving its meaning and order; Sequence self-message loops are not supported.+For a fresh Sequence omit `meta.viewBox` and `meta.column_fit`: automatic height fits the timeline (no 760px floor), 2–3 short-label participants pack below 920px when labels fit, and the canvas still widens for crowded labels up to its readable width; preserve an authored `meta.viewBox`. Set `meta.column_fit: "fixed"` explicitly when historical fixed coordinates are required; use `spread` when a wide viewBox leaves unused horizontal space or meaningful labels need width. Describe a participant's internal action in a note on its surrounding real cross-participant message, preserving its meaning and order; Sequence self-message loops are not supported. For fresh placement, budget vertical space for that note before placing the next message: 28px is the basic spacing for messages without notes, not a note budget. A note extends below its message; allow at least 44px for one rendered line, 55px for two, or 66px for three before the next message sharing that space (for example, a three-line note at y=200 needs the next message at y=266 or later). Wrapping depends on the final lane width, so leave more room for longer notes and preserve every note's meaning rather than deleting it. These gaps do not guarantee clearance from segment titles, other notes or activations. Supplied fixed y values remain authoritative; in an agent-authored fresh draft, adjust later messages, segment bounds and activation bounds together as needed, preserving order and meaning, and use `sequence/note-overlap` evidence for repairs within those constraints.For a fresh Dataflow start with the stage/row grid of 2 to 5 stages and rows 0 to 4, and follow the canonical [Dataflow canvas and showcase defaults](authoring-contract.md#dataflow). Adjacent stage centres sit 215px apart and default nodes are 112px wide, leaving about 100px between them, so keep a flow label within about 17 text units, counting CJK as two, and move further detail into a card; add dimensions or route controls for supplied geometry or a measured constraint.diff --git a/archify/references/delivery-contract.md b/archify/references/delivery-contract.mdindex 8898da14..4d167bb9 100644--- a/archify/references/delivery-contract.md+++ b/archify/references/delivery-contract.md@@ -266,7 +266,7 @@ validation result, then runs strict `check --require-provenance` andand preserves that stage's full receipt. Its stdout is one compact JSONobject with gate statuses, bounded actionable diagnostics, artifact identity,and evidence paths. The same compact object is written atomically to-`<output-stem>.finalize-summary.json`; use that file for normal failure repair.+`<output-stem>.finalize-summary.json`; use that file for normal failure repair. When diagnostics are truncated, `diagnosticSummary.omittedByCode` counts the unshown entries by diagnostic code without replacing their full subject and repair evidence in the full receipt.Complete stage receipts and timings remain available for auditing in`<output-stem>.finalize.json`. With `--out-dir`, both files are written there;`--receipt <path.json>` overrides the full receipt path and derives a distinctdiff --git a/archify/renderers/dataflow/render-dataflow.mjs b/archify/renderers/dataflow/render-dataflow.mjsindex b595dd71..3f61f603 100644--- a/archify/renderers/dataflow/render-dataflow.mjs+++ b/archify/renderers/dataflow/render-dataflow.mjs@@ -601,7 +601,8 @@ function fitAutomaticWidthToLabels(labels) {// Give the shared placer room for complete initial plates before its search;// width growth here does not recompute the measured nodes or cached routes.fitAutomaticWidthToLabels(initialLabelRects);-if (automaticShowcase) viewBox[1] = heightForLabels(initialLabelRects);+if (automaticShowcase) viewBox[1] = heightForLabels(initialLabelRects)+ + Math.max(0, ...initialLabelRects.map(rect => rect.height - layout.labelH));const compositionFrames = asArray(dataflow.stages).map(stageFrame);const resolvedLabelRects = (automaticShowcase ? placeAutomaticLabels({@@ -614,6 +615,7 @@ const resolvedLabelRects = (automaticShowcase ? placeAutomaticLabels({titles: compositionFrames.map(frame => ({ ...frame, height: layout.stageH })),viewBox,placementBottom: viewBox[1] - layout.stageBottomPad,+ maxOwnRouteDistance: 36,}) : initialLabelRects).map(rect => {// Dataflow has compact 16px plates. Permit one clearance gutter beyond// two plate heights (36px), which covers a label immediately above a node,@@ -661,6 +663,7 @@ for (const [index, rect] of resolvedLabelRects.entries()) {viewBox,placementBottom: viewBox[1] - layout.stageBottomPad,keepFallbackNearRoute: true,+ maxOwnRouteDistance: 36,})[index];// An exhausted shared search returns its supplied preferred rect. That is// not proof of a safe replacement: preserve the previously accepted labeldiff --git a/archify/renderers/lifecycle/README.md b/archify/renderers/lifecycle/README.mdindex f87398d0..397d169c 100644--- a/archify/renderers/lifecycle/README.md+++ b/archify/renderers/lifecycle/README.md@@ -45,12 +45,15 @@ The geometry follows from the structure alone:| Loops and skips | A transition between two non-consecutive main-path states (or back to an earlier one, or a self-transition) is an arc above the row. Shorter arcs nest inside longer ones; ports order so an outer riser never crosses an inner arc. || Other states | One row per distance from the main path. A state starts under the states it connects to in the row above; overlapping states pack side by side. || Between rows | Orthogonal routes through a shared gap. Horizontal runs take separate tracks, chosen to minimise crossings; near-vertical routes snap straight or widen to a readable jog. |-| Shared exits | When one state is entered from several main-path phases through transitions that share label, note and variant, consecutive phases receive a dashed composite frame and one exit per target, as in a UML superstate; non-consecutive phases share a bus with junction dots. Exits that differ stay separate connectors with their own labels. |+| Shared exits | A target with exactly one group of identical label, note and variant from at least two main-path phases shares an exit: consecutive phases receive a dashed composite frame, as in a UML superstate; non-consecutive phases share a bus with junction dots. Other exits keep separate connectors and their own labels. If several groups qualify for the same target, all exits stay separate. || Same lower row | Neighbours connect side to side, parallel transitions fanning out around the shared edge (at most five per pair of states). Dense parallel labels and notes increase their lane spacing and the height of that lower row to keep clear; other pairs loop under the row. |-| Labels | Above main-path arrows, on arc and loop runs, otherwise beside the segment next to the lower state. Every label keeps clear of other routes, states and labels; if one cannot, all spacing grows and layout repeats. |+| Labels | Above main-path arrows, on arc and loop runs, otherwise beside the segment next to the lower state. Every label keeps clear of other routes, states and labels; if one cannot, lower-row and route spacing grow and layout repeats, for at most five rounds. Main-path gaps stop growing before their minimum row width exceeds the text readability budget; gaps still fit their transition text. |Every route carries a crossover halo, so an unavoidable crossing (for example,two overlapping loops) stays legible. Lines are orthogonal with rounded corners.+Keep a distinct note on its original transition. Do not remove or copy notes to+make different exits qualify for sharing. The final width and label-clearance+checks still apply after layout retries.## Legend and state marksdiff --git a/archify/renderers/lifecycle/render-lifecycle.mjs b/archify/renderers/lifecycle/render-lifecycle.mjsindex 6d1b26d2..f203efa0 100644--- a/archify/renderers/lifecycle/render-lifecycle.mjs+++ b/archify/renderers/lifecycle/render-lifecycle.mjs@@ -87,6 +87,11 @@ for (const state of states.values()) {state.width = preferredWidth(state);state.height = STATE_H;}+const smallestText = Math.min(LABEL_FONT, ...[...states.values()].flatMap((state) => {+ const fitted = fonts(state, state.width);+ return [fitted.label, state.sublabel ? fitted.sublabel : Infinity];+}));+const readableWidthBudget = Math.floor(DESKTOP_READER_DIAGRAM_WIDTH * smallestText / MIN_PROJECTED_NODE_TEXT_PX);function labelBox(transition) {const text = transition.label || '';@@ -109,6 +114,11 @@ for (const transition of transitions) {const to = spineIndex.get(transition.to);if (from !== undefined && to === from + 1 && !spineEdges.has(from)) spineEdges.set(from, transition);}+const mainPathStateWidth = mainPath.reduce((sum, id) => sum + states.get(id).width, 0);+const minimumSpineGaps = mainPath.slice(0, -1).map((_, index) => {+ const edge = spineEdges.get(index);+ return (edge && hasLabel(edge) ? labelBox(edge).width : 0) + 26;+});// Every other state sits in a row below the main path at its distance from// it, so each transition stays within one row or joins two adjacent rows.@@ -149,18 +159,25 @@ for (const transition of ofKind('between')) {if (!downByTarget.has(transition.to)) downByTarget.set(transition.to, []);downByTarget.get(transition.to).push(transition);}-// A merged exit promises one meaning, so a target joins a bracket only when-// every transition into it shares label, note and variant; differing exits-// keep separate connectors instead of painting over each other.+// A merged exit promises one meaning. Only a target with one eligible+// complete-signature bucket joins a bracket; all other exits stay singles.const exitSignature = (transition) => [transition.label ?? '', transition.note ?? '', variantOf(transition)].join('\u0000');const brackets = new Map();for (const [target, list] of downByTarget) {- const sources = [...new Set(list.map((transition) => transition.from))].sort((a, b) => spineIndex.get(a) - spineIndex.get(b));- if (sources.length < 2 || new Set(list.map(exitSignature)).size > 1) continue;+ const buckets = new Map();+ for (const transition of list) {+ const signature = exitSignature(transition);+ if (!buckets.has(signature)) buckets.set(signature, []);+ buckets.get(signature).push(transition);+ }+ const eligible = [...buckets.values()].filter((bucket) => new Set(bucket.map((transition) => transition.from)).size >= 2);+ if (eligible.length !== 1) continue;+ const [group] = eligible;+ const sources = [...new Set(group.map((transition) => transition.from))].sort((a, b) => spineIndex.get(a) - spineIndex.get(b));const key = sources.join('\u0000');if (!brackets.has(key)) brackets.set(key, { key, sources, targets: [], transitions: [] });brackets.get(key).targets.push(target);- brackets.get(key).transitions.push(...list);+ brackets.get(key).transitions.push(...group);}const bracketOf = new Map();for (const bracket of brackets.values()) {@@ -190,7 +207,7 @@ const isFinal = (state) => !outgoing.has(state.id);// and keeps the placed layout with the fewest bends and short jogs.let spacing = { spineGap: 72, rowGap: 44, drop: 58, firstTrack: 34 };let geometry;-// Labels that could not be placed at a tighter spacing, which widened every gap.+// Labels that could not be placed at tighter spacing and prompted retries.const spacingWideners = new Set();for (let round = 0; round < SPACING_ROUNDS; round += 1) {const candidates = ['partner', 'even'].map((ports) => ({ ports, ...layout({ ...spacing, ports }) }));@@ -203,7 +220,13 @@ for (let round = 0; round < SPACING_ROUNDS; round += 1) {const closest = [...candidates].sort((a, b) => a.unplacedLabels.length - b.unplacedLabels.length)[0];for (const transition of closest.unplacedLabels) spacingWideners.add(transition);}- spacing = { spineGap: spacing.spineGap + 28, rowGap: spacing.rowGap + 28, drop: spacing.drop + 14, firstTrack: spacing.firstTrack + 6 };+ const nextSpineGap = spacing.spineGap + 28;+ // The canvas includes this whole row. Widening beyond its text budget+ // cannot succeed; keep its current gaps while other spacing still grows.+ const nextMainPathWidth = MARGIN_X * 2 + mainPathStateWidth+ + minimumSpineGaps.reduce((sum, minimum) => sum + Math.max(nextSpineGap, minimum), 0);+ spacing = { spineGap: nextMainPathWidth > readableWidthBudget ? spacing.spineGap : nextSpineGap,+ rowGap: spacing.rowGap + 28, drop: spacing.drop + 14, firstTrack: spacing.firstTrack + 6 };}function routeCost(routes) {@@ -225,9 +248,7 @@ function layout({ spineGap, rowGap, drop, firstTrack, ports: portMode }) {const state = states.get(id);state.x = cursor;state.cx = cursor + state.width / 2;- const edge = spineEdges.get(index);- const labelWidth = edge && hasLabel(edge) ? labelBox(edge).width : 0;- cursor += state.width + Math.max(spineGap, labelWidth + 26);+ cursor += state.width + Math.max(spineGap, minimumSpineGaps[index] ?? 26);});for (let row = 1; row < rowCount; row += 1) placeRow(row, rowGap);@@ -883,39 +904,41 @@ function validateStructure() {function validateLayout() {const problems = [];const diagnostics = [];- const smallest = Math.min(LABEL_FONT, ...[...states.values()].flatMap((state) => {- const fitted = fonts(state, state.width);- return [fitted.label, state.sublabel ? fitted.sublabel : Infinity];- }));- const budget = Math.floor(DESKTOP_READER_DIAGRAM_WIDTH * smallest / MIN_PROJECTED_NODE_TEXT_PX);- if (viewBox[0] > budget) {+ // The common width factor cancels when comparing the two text lines.+ const widthDriver = (transition) => {+ const label = textUnits(transition.label || '') * LABEL_FONT;+ const note = textUnits(transition.note || '') * NOTE_FONT;+ return label === note ? 'label+note' : label > note ? 'label' : 'note';+ };+ const preserveConditions = 'preserve every condition; shorten wording only, or move complete detail to a card explicitly associated with the same transition; shorter wording may not resolve other layout constraints';+ if (viewBox[0] > readableWidthBudget) {// A labelled main-path step widens its gap past the default spacing.const wideStepLabels = mainPath.slice(0, -1).flatMap((id, index) => {const edge = spineEdges.get(index);const excessPx = edge && hasLabel(edge) ? Math.round(labelBox(edge).width + 26 - spacing.spineGap) : 0;- return excessPx > 0 ? [{ from: edge.from, to: edge.to, label: edge.label || edge.note, excessPx }] : [];+ return excessPx > 0 ? [{ from: edge.from, to: edge.to, label: edge.label || edge.note, excessPx, widthDriver: widthDriver(edge) }] : [];}).sort((a, b) => b.excessPx - a.excessPx);const widenerLabels = [...spacingWideners].map((transition) => `"${transition.label || transition.note}"`);const labelFixes = [- ...(widenerLabels.length ? [`relieve the routes crowding ${widenerLabels.join(', ')}: those labels found no clear spot at the base spacing, so every gap widened by 28px; drop labels both endpoints imply, merge exits that share a target, or move a secondary transition elsewhere`] : []),- ...(wideStepLabels.length ? [`shorten the main-path transition labels that widen their gaps: ${wideStepLabels.map((step) => `"${step.label}" (+${step.excessPx}px)`).join(', ')}`] : []),+ ...(widenerLabels.length ? [`relieve the routes crowding ${widenerLabels.join(', ')}: those label/note boxes found no clear spot at the base spacing, so lower-row and route spacing grew; main-path gap growth is bounded by the text readability budget. Only equivalent exits with identical labels, notes and variants can share an arrow; keep distinct notes separate, or move a secondary transition elsewhere`] : []),+ ...(wideStepLabels.length ? [`review the width-driving main-path transition text: ${wideStepLabels.map((step) => `"${step.from}" -> "${step.to}" ${step.widthDriver.replace('+', ' and ')} (+${step.excessPx}px)`).join(', ')}; ${preserveConditions}`] : []),];- const message = `The lifecycle is ${viewBox[0]}px wide; at ${smallest}px text it stays readable on a desktop only up to ${budget}px.${labelFixes.length ? ` Transition labels set most of that width.` : ''}`;+ const message = `The lifecycle is ${viewBox[0]}px wide; at ${smallestText}px text it stays readable on a desktop only up to ${readableWidthBudget}px.${wideStepLabels.length ? ` Transition labels or notes widen their main-path gaps.` : ''}`;diagnostics.push({code: 'lifecycle/too-wide', severity: 'error', message,subject: { diagramType: 'lifecycle', path: '/mainPath' },- evidence: { viewBoxWidth: viewBox[0], budgetPx: budget, mainPathStates: mainPath.length, lowerRowStates: offStates.length, wideStepLabels, spacingWideners: [...spacingWideners].map((transition) => ({ from: transition.from, to: transition.to, label: transition.label || transition.note })) },+ evidence: { viewBoxWidth: viewBox[0], budgetPx: readableWidthBudget, mainPathStates: mainPath.length, lowerRowStates: offStates.length, wideStepLabels, spacingWideners: [...spacingWideners].map((transition) => ({ from: transition.from, to: transition.to, label: transition.label || transition.note, widthDriver: widthDriver(transition) })) },supportedFixes: [...labelFixes, 'shorten state labels and sublabels', 'move secondary phases off mainPath or merge adjacent phases', 'split the lifecycle into two diagrams'],});problems.push(message);}for (const transition of geometry.unplacedLabels) {- const message = `Transition "${transition.from}" -> "${transition.to}" label "${transition.label || transition.note}" cannot be placed clear of nearby routes.`;+ const message = `Transition "${transition.from}" -> "${transition.to}" label "${transition.label || transition.note}" cannot be placed clear of nearby routes.${transition.note ? ' Its note contributes to the label box; the box size and nearby geometry both affect placement.' : ''}`;diagnostics.push({code: 'lifecycle/label-unplaced', severity: 'error', message,subject: { diagramType: 'lifecycle', collection: 'transitions', index: transitions.indexOf(transition), from: transition.from, to: transition.to },- evidence: {},- supportedFixes: ['shorten the transition label', 'give exits that share a target the same label so they share one arrow'],+ evidence: { widthDriver: widthDriver(transition) },+ supportedFixes: [`review the transition ${transition.note ? transition.label ? 'label and note' : 'note' : 'label'} wording; ${preserveConditions}`, 'only equivalent exits with identical labels, notes and variants can share one arrow; keep distinct notes on separate exits without removing them to force sharing'],});problems.push(message);}@@ -1019,13 +1042,14 @@ function renderTransition(transition, index) {function renderLabel(transition, index) {const rect = geometry.placedLabels.get(transition);if (!rect) return '';- const accent = edgeLabelAccent(variantOf(transition));+ const variant = variantOf(transition);+ const accent = variant === 'default' ? 't-muted' : edgeLabelAccent(variant);const baseline = rect.y + (transition.label ? 11.5 : 11);const label = transition.label? `\n <text x="${rect.cx}" y="${baseline}" class="${accent}" font-size="${LABEL_FONT}" text-anchor="middle">${esc(transition.label)}</text>`: '';const note = transition.note- ? `\n <text data-detail="fine" x="${rect.cx}" y="${baseline + (transition.label ? 12 : 0)}" class="t-dim" font-size="${NOTE_FONT}" text-anchor="middle">${esc(transition.note)}</text>`+ ? `\n <text data-detail="fine" x="${rect.cx}" y="${baseline + (transition.label ? 12 : 0)}" class="t-muted" font-size="${NOTE_FONT}" text-anchor="middle">${esc(transition.note)}</text>`: '';return ` <g data-detail="${transition.label ? 'context' : 'fine'}" ${focusEdgeAttrs(transition.from, transition.to, transition.label || transition.note, index, transition.id)}><rect x="${rect.x}" y="${rect.y}" width="${rect.width}" height="${rect.height}" rx="4" class="c-mask"/>${label}${note}diff --git a/archify/renderers/sequence/render-sequence.mjs b/archify/renderers/sequence/render-sequence.mjsindex 72f9d864..6d676d02 100644--- a/archify/renderers/sequence/render-sequence.mjs+++ b/archify/renderers/sequence/render-sequence.mjs@@ -53,9 +53,8 @@ const LEGEND_BLOCK_HEIGHT = 86;// desktop reading minimum; an inherently crowded row still fails below.const spreadParticipantWidth = (canvasWidth) => Math.max(86,Math.min(190, Math.round((canvasWidth - 124) / Math.max(1, asArray(sequence.participants).length)) - 24));-function spreadColumnGeometry(canvasWidth) {+function spreadColumnGeometry(canvasWidth, width = spreadParticipantWidth(canvasWidth)) {const count = Math.max(1, asArray(sequence.participants).length);- const width = spreadParticipantWidth(canvasWidth);const span = count * width + (count - 1) * 16;const margin = Math.max(40, Math.min(62, canvasWidth - 40 - span));return { width, margin, gap: count > 1 ? Math.max(width + 16, (canvasWidth - 40 - margin - width) / (count - 1)) : 108 };@@ -113,8 +112,36 @@ const automaticWidth = sequence.meta?.viewBox ? null : automaticCanvasWidth();const canvasWidth = sequence.meta?.viewBox?.[0] ?? automaticWidth;const columnFit = sequence.meta?.column_fit || 'spread';const participantCount = Math.max(1, asArray(sequence.participants).length);+// Resolve the actual final-canvas text floor before choosing header geometry.+// Notes and automatic height must use the resulting column gaps below.+const readableMessages = sequence.meta?.quality_profile === 'showcase';+const readableAutomaticSublabel = readableMessages && automaticWidth !== null && columnFit === 'spread';+const readableSublabelMinimum = readableAutomaticSublabel+ ? Math.max(participantTextFit.sublabelMinimum, Math.ceil(minimumReadableSourceTextPx(canvasWidth) * 10) / 10)+ : participantTextFit.sublabelMinimum;+const readableSublabelPreferred = Math.max(participantTextFit.sublabelPreferred, readableSublabelMinimum);++function participantSpreadGeometry() {+ const nominal = spreadColumnGeometry(canvasWidth);+ const participants = asArray(sequence.participants);+ // Preserve every already-fitting row and all authored/fixed geometry. Only+ // a failed primary label opens this bounded use of spare horizontal room.+ if (automaticWidth === null || columnFit !== 'spread'+ || !participants.some((participant) => textUnits(participant.label) * 6.8 > nominal.width + 6)) return nominal;+ const required = Math.ceil(Math.max(nominal.width, ...participants.map((participant) => Math.max(+ textUnits(participant.label) * 6.8 - 6,+ participant.sublabel ? minimumNodeTextWidth(participant.sublabel, readableSublabelMinimum)+ + nominal.width - availableNodeTextWidth(nominal.width) : 0,+ ))));+ const capacity = Math.floor(Math.min(190, (canvasWidth - 80 - (participantCount - 1) * 16) / participantCount));+ // Keep the existing real failures if ordinary text or the brand rail cannot+ // fit the minimum candidate. Do not clamp a demand into infeasible geometry.+ if (required > capacity || participants.some((participant) => brandTopRailProblem(participant, required, 8, 'Participant'))) return nominal;+ return spreadColumnGeometry(canvasWidth, required);+}+const preferredSideMargin = 62;-const spreadGeometry = spreadColumnGeometry(canvasWidth);+const spreadGeometry = participantSpreadGeometry();const participantW = columnFit === 'spread' ? spreadGeometry.width : 86;// Narrow feasible frames can reduce the left margin, while ordinary frames// keep 62px. Compute card width first so this does not change its sizing rule.@@ -268,7 +295,6 @@ const viewBox = sequence.meta?.viewBox || [automaticWidth, automaticHeight];// a shorter one shrinks the readable band (validated below) instead of clipping.// Showcase is the fast-authoring default; standard retains legacy label geometry.-const readableMessages = sequence.meta?.quality_profile === 'showcase';const messageFontSize = readableMessages ? 11 : 9;const messageUnitWidth = readableMessages ? 6.6 : 5.2;const layout = {@@ -287,15 +313,6 @@ const layout = {labelH: readableMessages ? 18 : 16,};-// Automatic showcase spread can guarantee a readable fit within its bounded-// canvas. Standard, fixed columns and authored canvases retain historical text-// sizing; composition reports their projected readability under its own policy.-const readableAutomaticSublabel = readableMessages && automaticWidth !== null && columnFit === 'spread';-const readableSublabelMinimum = readableAutomaticSublabel- ? Math.max(participantTextFit.sublabelMinimum, Math.ceil(minimumReadableSourceTextPx(viewBox[0]) * 10) / 10)- : participantTextFit.sublabelMinimum;-const readableSublabelPreferred = Math.max(participantTextFit.sublabelPreferred, readableSublabelMinimum);-const participantBoxWidthNote = automaticWidth? `participant boxes are ${participantW}px: the automatic ${viewBox[0]}px canvas cannot widen further without its 7px sublabels falling below the desktop reading minimum, so keep meta.viewBox omitted`: columnFit === 'spread'@@ -367,7 +384,7 @@ function segmentLabelOccupants() {]).filter((occupant) => occupant.rect);}-function segmentLabelBox(segment) {+function legacySegmentLabelBox(segment) {const labelW = Math.max(42, textUnits(segment.label) * 5.2 + 14);const occupied = segmentLabelOccupants();const label = { x: 56, y: segment.from - 22, width: labelW, height: 18 };@@ -393,6 +410,62 @@ function segmentLabelBox(segment) {return label;}+function segmentLabelBox(segment) {+ const label = legacySegmentLabelBox(segment);+ const headers = [...participants.values()];+ const coveredHeaders = headers.filter((header) => rectsOverlap(label, header, 0));+ if (!coveredHeaders.length || label.y + label.height > segment.from) return label;++ const others = asArray(sequence.segments).filter((other) => other !== segment);+ // Only the unique first, non-overlapping phase gets this local adjustment.+ // Nested phases keep their authored bounds and the existing title policy.+ if (others.some((other) => other.from <= segment.from+ || (other.from < segment.to && other.to > segment.from))) return label;++ const candidate = { ...label, y: Math.max(...coveredHeaders.map((header) => header.y + header.height)) + 2 };+ const bottom = candidate.y + candidate.height;+ // The badge must still touch its own top border, before the first message;+ // moving it deep into the phase would name the wrong part of the timeline.+ if (candidate.y > segment.from || bottom < segment.from || bottom > segment.to - 2) return label;++ const obstacles = [+ ...segmentLabelOccupants().map(({ rect }) => rect),+ ...headers,+ // Use actual legacy placements: another title may have climbed above its+ // nominal slot. Calling the unchanged helper keeps this non-recursive.+ ...others.map(legacySegmentLabelBox),+ ];+ if (!obstacles.some((rect) => rectsOverlap(candidate, rect, 2))) return candidate;++ // Only this blocked header-clear strip gains a horizontal fallback. Keep+ // successful legacy placements intact, including their activation policy.+ const fallbackObstacles = [+ ...obstacles,+ ...asArray(sequence.activations).flatMap((activation) => {+ const participant = participants.get(activation.participant);+ return participant ? [{+ x: participant.cx - 5, y: activation.from,+ width: 10, height: activation.to - activation.from,+ }] : [];+ }),+ ];+ // Every free interval on this strip starts at the left frame inset or just+ // beyond an obstacle. Scan those finite boundaries instead of pixel steps.+ const boundaries = [...new Set([+ candidate.x,+ ...fallbackObstacles+ .filter((rect) => candidate.y < rect.y + rect.height + 2+ && rect.y < candidate.y + candidate.height + 2)+ .map((rect) => rect.x + rect.width + 2),+ ])].filter((x) => x >= candidate.x && x + candidate.width <= viewBox[0] - 48)+ .sort((a, b) => a - b);+ for (const x of boundaries) {+ const shifted = { ...candidate, x };+ if (!fallbackObstacles.some((rect) => rectsOverlap(shifted, rect, 2))) return shifted;+ }+ 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.@@ -875,7 +948,7 @@ function renderSegmentLabel(segment, index) {const label = segmentLabelBox(segment);return ` <g data-graph-role="segment-label" data-segment-id="${index}"><rect x="${label.x}" y="${label.y}" width="${label.width}" height="${label.height}" rx="3" class="c-mask"/>- <text x="${label.x + 6}" y="${label.y + 13}" class="t-dim" font-size="9" font-weight="600">${esc(segment.label)}</text>+ <text x="${label.x + 6}" y="${label.y + 13}" class="t-muted" font-size="9" font-weight="600">${esc(segment.label)}</text></g>`;}@@ -912,7 +985,7 @@ function renderMessage(message, index) {? noteBox.lines.map((line, lineIndex) => `<tspan x="${noteBox.x}" dy="${lineIndex ? NOTE_LINE_HEIGHT : 0}">${esc(line)}</tspan>`).join(''): esc(message.note);const note = noteBox- ? `\n <text data-detail="fine" x="${noteBox.x}" y="${noteBox.baseline}" class="t-dim" font-size="${NOTE_FONT_SIZE}">${noteContent}</text>`+ ? `\n <text data-detail="fine" x="${noteBox.x}" y="${noteBox.baseline}" class="t-muted" font-size="${NOTE_FONT_SIZE}">${noteContent}</text>`: '';return ` <g ${focusEdgeAttrs(message.from, message.to, message.label, index, message.id)}><path data-composition-edge-from="${esc(message.from)}" data-composition-edge-to="${esc(message.to)}"${message.id ? ` data-composition-edge-id="${esc(message.id)}"` : ''} data-composition-points="${routePointsValue([[start, message.y], [end, message.y]])}" d="M ${start} ${message.y} L ${end} ${message.y}" class="${cls}"${animateAttr(sequence.meta, 'edge', index)} stroke-width="${strokeWidth}"${dash} marker-end="url(#${marker})"/>diff --git a/archify/renderers/shared/automatic-labels.mjs b/archify/renderers/shared/automatic-labels.mjsindex a44eb5fc..2c5072ee 100644--- a/archify/renderers/shared/automatic-labels.mjs+++ b/archify/renderers/shared/automatic-labels.mjs@@ -5,7 +5,7 @@ import { createSpatialGrid } from './spatial-grid.mjs';// It never routes an edge, moves a node, expands the canvas, or rewrites input.export function placeAutomaticLabels({labels, routes, components, titles, viewBox, placementBottom = viewBox[1], fallbackRing = true, keepFallbackNearRoute = false,- gridSweep = false,+ gridSweep = false, maxOwnRouteDistance = Infinity,}) {const placed = [...labels];const obstacles = [...components, ...titles];@@ -47,6 +47,9 @@ export function placeAutomaticLabels({inside(rect) && rect.y + rect.height <= placementBottom&& !obstacles.some(obstacle => rectsOverlap(rect, obstacle, 2))&& !overlapsLabel(rect, index, 2) && !masksRoute(rect)+ && (!Number.isFinite(maxOwnRouteDistance) || segments.some(segment =>+ segment.relationIndex === rect.relationIndex+ && segmentRectClearanceWithin(segment, rect, maxOwnRouteDistance) <= maxOwnRouteDistance)));const rectAt = (label, lx, ly) => ({...label, lx, ly, x: lx - label.width / 2, y: ly - 10,diff --git a/archify/renderers/shared/cli.mjs b/archify/renderers/shared/cli.mjsindex 9c5341e0..c09d714c 100644--- a/archify/renderers/shared/cli.mjs+++ b/archify/renderers/shared/cli.mjs@@ -27,15 +27,17 @@ let renderCandidateSequence = 0;// meta.locale is renderer-owned Viewer UI, not authored content. Each message// resolves as: valid meta.translations value → bundled catalog enrolled in// locales/manifest.json → English (see i18n.mjs). Every fallback is disclosed-// on stderr unconditionally so render/deliver/validate report it even without-// ARCHIFY_DIAGNOSTIC_FORMAT; the CLI receipts carry the same diagnostics.+// by human renderers on stderr. Diagnostic JSON mode records warnings without+// mixing text into failure receipts; validate/deliver disclose them publicly.function applyLocaleTranslations(diagramType, diagram) {const locale = diagram.meta?.locale;if (!locale) return;registerLocale(locale, diagram.meta.translations);for (const diagnostic of localeDiagnostics(diagramType, diagram.meta)) {recordDiagnostic(diagnostic);- console.warn(`archify: ${diagnostic.message}`);+ if (process.env.ARCHIFY_DIAGNOSTIC_FORMAT !== 'json') {+ console.warn(`archify: ${diagnostic.message}`);+ }}}diff --git a/archify/renderers/shared/diagnostics.mjs b/archify/renderers/shared/diagnostics.mjsindex 09dc03cb..9fbd25d5 100644Binary files a/archify/renderers/shared/diagnostics.mjs and b/archify/renderers/shared/diagnostics.mjs differdiff --git a/archify/renderers/workflow/README.md b/archify/renderers/workflow/README.mdindex 38bc9393..5c1d370b 100644--- a/archify/renderers/workflow/README.md+++ b/archify/renderers/workflow/README.md@@ -100,7 +100,15 @@ node archify/bin/archify.mjs validate workflow input.workflow.json --layout-jsonThe receipt reports the selected contract, measured `viewBox` and`requiredViewBox`, solved columns, nodes, edges, labels, and causal diagnostics.-It deliberately omits solver iterations and candidate scores.+It deliberately omits solver iterations and candidate scores. A complete plan+rejected by a late layout, canvas, or text check also includes this geometry with+`ok: false`; validation still exits non-zero and writes no HTML. Its `viewBox`+is the attempted frame at rejection, while `requiredViewBox` is the measured+footprint of that same rejected plan. Labels use their anchor coordinates,+not the top-left corner of the label mask. Early or incomplete failures retain+only the contract and causal diagnostics. Failed geometry is repair evidence,+not acceptance; migration failure reports may also gain measured canvas evidence+without accepting the rejected plan.## Legend@@ -214,8 +222,9 @@ An infeasible preset returns `workflow/route-preset-conflict` with the actualrejected `evidence.invariant`. For node clearance it also identifies the node,segment, endpoint role, and required clearance. Use that obstacle to revisethe connected placement or route constraints, then revalidate; minimum segment-lengths alone do not establish a clear path. Advertised `supportedFixes` are-verified against the complete workflow.+lengths alone do not establish a clear path. Concrete alternatives for+`workflow/route-preset-conflict` are checked by replanning the complete workflow+at the active quality profile.## Design Rules@@ -275,10 +284,12 @@ pass-through containers. Text width is estimated CJK-aware: fullwidth glyphscount as two units.Diagnostics are causal: a rank-capacity failure suppresses derivative short-edge, endpoint-direction, and label-overlap findings. Every-`supportedFixes[]` entry is verified by replanning the proposed edit, and a-diagnostic never proposes removing a semantic label when label presence does-not cause the failed invariant.+edge, endpoint-direction, and label-overlap findings. `supportedFixes[]` can+contain concrete edits checked by the compiler's fix search or general repair+guidance from shared composition checks. General guidance is not a verified+edit. After any edit, rerun the complete `finalize` command. A diagnostic never+proposes removing a semantic label when label presence does not cause the+failed invariant.Set `meta.quality_profile` to `showcase` for polished delivery. Unrelated properX crossings then fail with `composition/proper-crossing`; default `standard`diff --git a/archify/renderers/workflow/render-workflow.mjs b/archify/renderers/workflow/render-workflow.mjsindex 329558af..1030238a 100644--- a/archify/renderers/workflow/render-workflow.mjs+++ b/archify/renderers/workflow/render-workflow.mjs@@ -1,7 +1,7 @@import path from 'node:path';import { fileURLToPath } from 'node:url';import { loadDiagramWithBrandMarks, writeDiagram } from '../shared/cli.mjs';-import { throwDiagnosticError } from '../shared/diagnostics.mjs';+import { recordDiagnostic, throwDiagnosticError, withIsolatedDiagnosticRecording } from '../shared/diagnostics.mjs';import { compileWorkflow } from './workflow-compiler.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));@@ -11,11 +11,21 @@ const { diagram: workflow, template, outPath, sourceEvidence } = await loadDiagrdefaultExample: 'agent-tool-call.workflow.json'});-const compiled = compileWorkflow({- workflow,- qualityProfile: process.env.ARCHIFY_QUALITY_PROFILE || workflow.meta?.quality_profile,- sourceEvidence,-});+let compiled;+try {+ compiled = withIsolatedDiagnosticRecording(() => compileWorkflow({+ workflow,+ qualityProfile: process.env.ARCHIFY_QUALITY_PROFILE || workflow.meta?.quality_profile,+ sourceEvidence,+ }));+} catch (error) {+ // The scope has restored the caller's recording. Keep a typed escape visible+ // alongside earlier failures without publishing abandoned compile attempts.+ if (Array.isArray(error?.archifyDiagnostics)) {+ for (const diagnostic of error.archifyDiagnostics) recordDiagnostic(diagnostic);+ }+ throw error;+}const layoutJson = process.argv.includes('--layout-json');diff --git a/archify/renderers/workflow/workflow-compiler.mjs b/archify/renderers/workflow/workflow-compiler.mjsindex 41601cb9..938f54ac 100644--- a/archify/renderers/workflow/workflow-compiler.mjs+++ b/archify/renderers/workflow/workflow-compiler.mjs@@ -78,6 +78,7 @@ const READABLE_CANDIDATE_COST_PRIORITY = Object.freeze(['sharedCorridorPx','automaticForwardReversePx','labelRouteClearanceDeficit',+ 'oppositeParallelDeficit','interiorPreferred28Deficit','bendCount','stretchMilli',@@ -686,11 +687,12 @@ function cloneWorkflow(value) {return JSON.parse(JSON.stringify(value));}-function canonicalReadableWorkflow(workflow) {+function canonicalReadableWorkflow(workflow, widthOverrides) {if (workflow.schema_version !== 2) return workflow;for (const node of asArray(workflow.nodes)) {const width = !preservesWorkflowAbsoluteGeometry(workflow)- && !Number.isFinite(node.width) && automaticNodeWidth(node);+ && !Number.isFinite(node.width)+ && Math.max(automaticNodeWidth(node) || 0, widthOverrides?.get(node.id) || 0);if (width) automaticNodeWidths.set(node, width);else automaticNodeWidths.delete(node);}@@ -1331,6 +1333,7 @@ function compileWorkflowInternal({sourceEvidence,discoverFixes = true,layoutFeedback = {},+ widthOverrides,} = {}) {if (!inputWorkflow || typeof inputWorkflow !== 'object' || Array.isArray(inputWorkflow)) {const diagnostics = [{@@ -1373,7 +1376,7 @@ function compileWorkflowInternal({inputDiagnostics,);}- const workflow = canonicalReadableWorkflow(qualityResolvedWorkflow);+ const workflow = canonicalReadableWorkflow(qualityResolvedWorkflow, widthOverrides);const semanticDiagnostics = semanticContractDiagnostics(workflow);if (semanticDiagnostics.length) {return compilerFailure(@@ -1414,6 +1417,7 @@ const {} = laneGeometry;let viewBox = laneGeometry.initialViewBox;let requiredViewBox = [...viewBox];+let measuredPlanReady = false;function workflowLegendLayout(obstacles = []) {return {@@ -1544,6 +1548,11 @@ const edgeIndexByEdge = new Map(asArray(workflow.edges).map((edge, index) => [edfunction acceptsFix(mutator) {if (!discoverFixes) return false;const candidate = cloneWorkflow(workflow);+ // Migration projections carry geometry provenance outside their JSON.+ // Keep that metadata without making ordinary authored pins sticky.+ for (const symbol of Object.getOwnPropertySymbols(workflow)) {+ candidate[symbol] = workflow[symbol];+ }mutator(candidate);return withDiagnosticRecordingSuppressed(() => compileWorkflowWithFeedback({workflow: candidate,@@ -1898,13 +1907,26 @@ function throwReadableLabelRoutePinConflict(hit, routePoints = null) {const routePinned = hasAuthoredRouteAssertions(routeEdge);if (!labelPinned && !routePinned) return false;const alternatives = verifiedLabelRoutePinAlternatives(labelEdge, routeEdge);+ const labelNudges = labelPinned && discoverFixes ? verifiedLabelAtAlternatives(labelEdge) : [];+ // A passing replacement proves the label pin is causal even if its removal+ // recreates the collision under the ordinary automatic reservation policy.+ const conflictingRefs = labelNudges.length+ && !alternatives.conflictingRefs.some(({ edge, field }) => edge === labelEdge && field === 'labelAt')+ ? [{ edge: labelEdge, edgeIndex: workflow.edges.indexOf(labelEdge), field: 'labelAt' }, ...alternatives.conflictingRefs]+ : alternatives.conflictingRefs;+ const supportedFixes = [+ ...labelNudges,+ ...alternatives.repairs.filter(({ removalSet }) => (+ !labelNudges.length || removalSet.length !== 1 || removalSet[0].field !== 'labelAt'+ )).map(({ message }) => message),+ ];const actualRoutePoints = routePoints|| pathCache.get(routeEdge)?.points|| pathFor(routeEdge).points;- const diagnosticEdge = alternatives.conflictingRefs[0]?.edge+ const diagnosticEdge = conflictingRefs[0]?.edge|| (labelPinned ? labelEdge : routeEdge);throwExplicitPinConflict(diagnosticEdge, 'explicit label-route clearance', {- conflictingPins: alternatives.conflictingPins,+ conflictingPins: conflictingRefs.map(({ edge, field }) => authoredPinEvidence(edge, field)),...(labelPinned ? { labelAt: [...labelEdge.labelAt] } : {}),labelRect: {x: hit.rect.x,@@ -1922,9 +1944,7 @@ function throwReadableLabelRoutePinConflict(hit, routePoints = null) {routeSegment: { from: [...hit.start], to: [...hit.end] },clearancePx: Math.round(hit.clearance * 10) / 10,minimumPx: hit.threshold,- }, [- ...verifiedRepairsWithLabelNudges(alternatives),- ]);+ }, supportedFixes);return true;}@@ -2323,9 +2343,9 @@ function validateReadablePinnedGeometry() {}// Reserve clear straight automatic routes before ID-ordered bending edges so// a later edge cannot steal a corridor that already has one good straight path.- // Skip during discoverFixes probes (discoverFixes === false): those probes- // strip labelAt/via and would otherwise look "automatic", recreating the pin- // geometry and shrinking causal pin sets (round-23 regression).+ // Fix probes use the same reservation policy as public compilation. A+ // verified labelAt replacement retains causal label-pin evidence even when+ // deleting that pin lets automatic routing recreate its collision.// Skip when any edge carries a relative/absolute label pin: straight-first// would reorder corridors and scramble placed-label conflict evidence.const hasLabelPins = workflow.edges.some((edge) => (@@ -2334,7 +2354,7 @@ function validateReadablePinnedGeometry() {|| edge.labelDy !== undefined|| edge.labelSegment !== undefined));- if (discoverFixes && !hasLabelPins) {+ if (!hasLabelPins) {for (const edge of workflow.edges) {if (!nodes.has(edge.from) || !nodes.has(edge.to)) continue;const plan = clearStraightAutomaticPlan(edge);@@ -2977,6 +2997,7 @@ function validateWorkflow() {}));}+ measuredPlanReady = hasCompleteMeasuredPlan();if (problems.length) {throwDiagnosticProblems('Workflow layout validation failed', problems, {subject: { diagramType: 'workflow' },@@ -3717,6 +3738,14 @@ function properAxisCrossing(a, b, c, d) {&& y < Math.max(vertical[0][1], vertical[1][1]) - 0.0001;}+function isReadableAutomaticRoute(edge) {+ return workflow.schema_version === 2+ && !Array.isArray(edge.via)+ && edge.channelX === undefined+ && edge.channelY === undefined+ && (!edge.route || edge.route === 'auto');+}+function independentAutomaticRoute(edge) {return workflow.schema_version === 2&& !edge.via && edge.channelX === undefined && edge.channelY === undefined@@ -3729,6 +3758,7 @@ function independentAutomaticRoute(edge) {function routeInteractionMetrics(edge, points) {let properCrossingCount = 0;let sharedCorridorPx = 0;+ let oppositeParallelDeficit = 0;const extent = routeBounds(points);const nearbyRoutes = obstacleGrid.query({minX: extent.minX - 8, minY: extent.minY - 8,@@ -3741,6 +3771,9 @@ function routeInteractionMetrics(edge, points) {const routed = item.routed;const sharedEndpoint = [edge.from, edge.to].some((id) => id === otherEdge.from || id === otherEdge.to);if (sharedEndpoint && workflow.schema_version !== 2) continue;+ if (isReadableAutomaticRoute(edge)) {+ oppositeParallelDeficit += longCounterflowDeficit(points, routed.points);+ }sharedCorridorPx += collectAmbiguousCorridors({routedRelations: [{ relation: edge, points }, { relation: otherEdge, points: routed.points }],includeSharedEndpoints: () => workflow.schema_version === 2,@@ -3754,7 +3787,33 @@ function routeInteractionMetrics(edge, points) {}}}- return { properCrossingCount, sharedCorridorPx };+ return { properCrossingCount, sharedCorridorPx, oppositeParallelDeficit };+}++// Prefer a clear existing track for long, close counterflow. This is only a+// candidate preference: same-direction trunks and short endpoint runs stay+// under the existing route contracts, and authored geometry is never edited.+function longCounterflowDeficit(points, otherPoints) {+ const left = normalizeRoutePoints(points);+ const right = normalizeRoutePoints(otherPoints);+ let worst = 0;+ for (let a = 1; a < left.length; a += 1) {+ for (let b = 1; b < right.length; b += 1) {+ const horizontal = Math.abs(left[a][1] - left[a - 1][1]) <= 0.0001+ && Math.abs(right[b][1] - right[b - 1][1]) <= 0.0001;+ const vertical = Math.abs(left[a][0] - left[a - 1][0]) <= 0.0001+ && Math.abs(right[b][0] - right[b - 1][0]) <= 0.0001;+ if (!horizontal && !vertical) continue;+ const axis = horizontal ? 0 : 1;+ if ((left[a][axis] - left[a - 1][axis]) * (right[b][axis] - right[b - 1][axis]) >= 0) continue;+ const gap = Math.abs(left[a][1 - axis] - right[b][1 - axis]);+ if (gap <= 0.0001 || gap >= 8) continue;+ const overlap = Math.min(Math.max(left[a][axis], left[a - 1][axis]), Math.max(right[b][axis], right[b - 1][axis]))+ - Math.max(Math.min(left[a][axis], left[a - 1][axis]), Math.min(right[b][axis], right[b - 1][axis]));+ worst = Math.max(worst, Math.max(0, overlap - 24) * (8 - gap));+ }+ }+ return worst;}function automaticForwardReversePx(edge, points) {@@ -3810,6 +3869,7 @@ function readableCandidateCost(properCrossingCount: interaction.properCrossingCount,sharedCorridorPx: interaction.sharedCorridorPx,labelRouteClearanceDeficit: labelRouteClearanceDeficit(edge, points),+ oppositeParallelDeficit: interaction.oppositeParallelDeficit,interiorPreferred28Deficit,bendCount: Math.max(0, points.length - 2),stretchMilli: Math.round((directLength > 0 ? routeLength / directLength : 1) * 1000),@@ -4100,6 +4160,20 @@ function readablePresetVia(edge, from, to, start, end, fromSide, toSide) {const edgeIndex = workflow.edges.indexOf(edge);const edgeName = workflowEdgeName(edge);const supportedFixes = [];+ if (discoverFixes && rejection.invariant === 'edge-label node clearance' && edge.label+ && ['labelAt', 'labelDx', 'labelDy', 'labelSegment'].every((field) => edge[field] === undefined)) {+ for (let segment = 0; segment < Math.min(points.length - 1, 3); segment += 1) {+ const fix = verifiedEdgeFix(+ edge,+ `set labelSegment on edge "${edgeName}" to ${segment}`,+ (candidate) => { candidate.labelSegment = segment; },+ );+ if (fix) {+ supportedFixes.push(fix);+ break;+ }+ }+ }for (const candidatePreset of ['straight', 'drop', 'outside-right', 'return-left', 'bottom-channel', 'up-channel']) {if (candidatePreset === preset) continue;if (acceptsFix((document) => {@@ -4774,12 +4848,7 @@ function pathFor(edge, automaticPlan = null) {}const ports = automaticPorts.get(edge);const { fromSide, toSide } = edgeSides(edge);- const readableAutomatic = workflow.schema_version === 2- && !Array.isArray(edge.via)- && edge.channelX === undefined- && edge.channelY === undefined- && (!edge.route || edge.route === 'auto');- if (readableAutomatic) {+ if (isReadableAutomaticRoute(edge)) {const planned = automaticPlan || readableAutomaticRoute(edge,from,@@ -4870,8 +4939,9 @@ function measuredContentBounds() {for (const node of nodes.values()) includeRect(node, `node ${node.id}`);for (const [index, edge] of workflow.edges.entries()) {if (!nodes.has(edge.from) || !nodes.has(edge.to)) continue;- for (const point of pathFor(edge).points) includePoint(point, `edge ${edge.id || index}`);- const label = labelRectFor(edge, index);+ const routed = pathCache.get(edge);+ for (const point of routed.points) includePoint(point, `edge ${edge.id || index}`);+ const label = LABEL_RECT_CACHE.get(routed);if (label) includeRect(label, `edge ${edge.id || index} label mask`);}for (const phase of asArray(workflow.phases)) {@@ -4920,16 +4990,25 @@ function measuredContentBounds() {};}+function measuredPlanFootprint() {+ const bounds = measuredContentBounds();+ return {+ bounds,+ requiredViewBox: [+ Math.max(minimumCanvasWidth, Math.ceil(bounds.right + 16)),+ Math.max(autoHeight, Math.ceil(bounds.bottom + 18)),+ ],+ };+}+function finalizeReadableViewBox() {if (workflow.schema_version !== 2) {requiredViewBox = [...viewBox];return;}- const bounds = measuredContentBounds();- requiredViewBox = [- Math.max(minimumCanvasWidth, Math.ceil(bounds.right + 16)),- Math.max(autoHeight, Math.ceil(bounds.bottom + 18)),- ];+ const footprint = measuredPlanFootprint();+ const { bounds } = footprint;+ requiredViewBox = footprint.requiredViewBox;const outsideOrigin = bounds.left < 0 || bounds.top < 0;if (outsideOrigin) {const hasAbsolutePins = hasAbsoluteWorkflowPins(workflow);@@ -4988,7 +5067,7 @@ function renderLane(lane, index) {const exception = lane.variant === 'exception'? `\n <rect data-graph-role="structural-frame" data-composition-frame-kind="exception-lane" data-composition-frame-id="lane-${index}-exception" x="${layout.laneX + 6}" y="${y + 6}" width="${layout.laneW - 12}" height="${height - 12}" rx="8" class="c-security-group" stroke-width="1"/>`: '';- const labelClass = lane.variant === 'exception' ? 't-security' : 't-dim';+ const labelClass = lane.variant === 'exception' ? 't-security' : 't-muted';const prefix = lane.variant === 'exception' ? 'EX' : String(index + 1).padStart(2, '0');return ` <rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-${index}" x="${layout.laneX}" y="${y}" width="${layout.laneW}" height="${height}" rx="10" class="c-lane" stroke-width="1"/>${exception}<text x="${layout.laneX + 14}" y="${y + 22}" class="${labelClass}" font-size="10" font-weight="600">${prefix} / ${esc(lane.label)}</text>`;@@ -5111,7 +5190,7 @@ function renderEdgeLabel(edge, index) {const labelW = workflowLabelWidth(edge.label);return ` <g data-detail="context" ${focusEdgeAttrs(edge.from, edge.to, edge.label, index, edge.id)}><rect x="${lx - labelW / 2}" y="${ly - 10}" width="${labelW}" height="14" rx="3" class="c-mask"/>- <text x="${lx}" y="${ly}" class="${edgeLabelAccent(edge.variant)}" font-size="8" text-anchor="middle">${esc(edge.label)}</text>+ <text x="${lx}" y="${ly}" class="${!edge.variant || edge.variant === 'default' ? 't-muted' : edgeLabelAccent(edge.variant)}" font-size="8" text-anchor="middle">${esc(edge.label)}</text></g>`;}@@ -5171,45 +5250,87 @@ ${renderLegend()}}+function hasCompleteMeasuredPlan() {+ if (nodes.size !== workflow.nodes.length || pathCache.size !== workflow.edges.length+ || !layout.colXs.every(Number.isFinite) || !viewBox.every(Number.isFinite)) return false;+ for (const node of nodes.values()) {+ if (!isFinitePoint(node.x, node.y, node.width, node.height)+ || node.width <= 0 || node.height <= 0) return false;+ }+ for (const edge of workflow.edges) {+ if (!nodes.has(edge.from) || !nodes.has(edge.to)) return false;+ const routed = pathCache.get(edge);+ if (!Array.isArray(routed?.points) || routed.points.length < 2+ || !routed.points.every((point) => Array.isArray(point)+ && point.length === 2 && point.every(Number.isFinite))) return false;+ if (!edge.label) continue;+ const rect = LABEL_RECT_CACHE.get(routed);+ if (!rect || !isFinitePoint(rect.x, rect.y, rect.width, rect.height, rect.lx, rect.ly)+ || rect.width <= 0 || rect.height <= 0) return false;+ }+ return true;+}++function measuredPlanReceipt(diagnostics, requiredFrame) {+ return {+ contract: layout.contract,+ viewBox: [...viewBox],+ requiredViewBox: [...requiredFrame],+ columns: [...layout.colXs],+ nodes: [...nodes.values()].map((node) => ({+ id: node.id,+ lane: node.lane,+ col: node.col,+ x: node.x,+ y: node.y,+ width: node.width,+ height: node.height,+ })),+ edges: workflow.edges.map((edge) => ({+ id: edge.id ?? null,+ from: edge.from,+ to: edge.to,+ points: pathCache.get(edge).points.map((point) => [...point]),+ })),+ labels: workflow.edges.flatMap((edge) => {+ if (!edge.label || !nodes.has(edge.from) || !nodes.has(edge.to)) return [];+ const { lx: x, ly: y } = LABEL_RECT_CACHE.get(pathCache.get(edge));+ return [{ edge: edge.id ?? null, label: edge.label, x, y, width: workflowLabelWidth(edge.label), height: 14 }];+ }),+ diagnostics,+ };+}++try {validateReadableInputsBeforeRouting();validateReadablePinnedGeometry();validateWorkflow();finalizeReadableViewBox();validateReadableNodeText();+ // A rendering failure is not a measured validation rejection.+ measuredPlanReady = false;const svg = renderSvg();- const receipt = {- contract: layout.contract,- viewBox: [...viewBox],- requiredViewBox: [...requiredViewBox],- columns: [...layout.colXs],- nodes: [...nodes.values()].map((node) => ({- id: node.id,- lane: node.lane,- col: node.col,- x: node.x,- y: node.y,- width: node.width,- height: node.height,- })),- edges: workflow.edges.map((edge) => ({- id: edge.id ?? null,- from: edge.from,- to: edge.to,- points: pathFor(edge).points.map((point) => [...point]),- })),- labels: workflow.edges.flatMap((edge) => {- if (!edge.label || !nodes.has(edge.from) || !nodes.has(edge.to)) return [];- const [x, y] = workflowEdgeLabelPoint(edge, pathFor(edge).points);- return [{ edge: edge.id ?? null, label: edge.label, x, y, width: workflowLabelWidth(edge.label), height: 14 }];- }),- diagnostics: workflowDiagnostics,- };+ const receipt = measuredPlanReceipt(workflowDiagnostics, requiredViewBox);return { ok: true, svg, receipt };} catch (error) {if (!Array.isArray(error?.archifyDiagnostics)) throw error;const diagnostics = error.archifyDiagnostics.map((diagnostic) => ({ ...diagnostic }));- return compilerFailure(layout.contract, diagnostics, error.message);+ const failure = compilerFailure(layout.contract, diagnostics, error.message);+ if (measuredPlanReady) {+ try {+ const footprint = measuredPlanFootprint();+ if (footprint.requiredViewBox.every(Number.isFinite)) {+ failure.receipt = {+ ...measuredPlanReceipt(diagnostics, footprint.requiredViewBox),+ ok: false,+ };+ }+ } catch {+ // Supplemental evidence must never replace the causal diagnostics.+ }+ }+ return failure;}}@@ -5281,7 +5402,7 @@ function compileWithRouteOrderFeedback(options) {return best;}-function compileWorkflowWithFeedback({ workflow, qualityProfile, sourceEvidence, discoverFixes = true } = {}) {+function compileWithLayoutFeedback({ workflow, qualityProfile, sourceEvidence, discoverFixes, widthOverrides }) {let layoutFeedback = {};for (let attempt = 0; attempt <= MAX_READABLE_LAYOUT_FEEDBACK_ROUNDS; attempt += 1) {try {@@ -5291,6 +5412,7 @@ function compileWorkflowWithFeedback({ workflow, qualityProfile, sourceEvidence,sourceEvidence,discoverFixes,layoutFeedback,+ widthOverrides,});} catch (error) {if (!(error instanceof WorkflowLayoutFeedback)) throw error;@@ -5338,6 +5460,54 @@ function compileWorkflowWithFeedback({ workflow, qualityProfile, sourceEvidence,throw new Error('unreachable readable-v2 layout feedback state');}+function compileWorkflowWithFeedback({ workflow, qualityProfile, sourceEvidence, discoverFixes = true } = {}) {+ const options = { workflow, qualityProfile, sourceEvidence, discoverFixes };+ let result = compileWithLayoutFeedback(options);+ // Keep successful output and authored geometry exactly as before. Check the+ // original migration policy before cloning, since its Symbol is not JSON.+ if (result.ok || workflow?.schema_version !== 2+ || (qualityProfile || workflow.meta?.quality_profile) !== 'showcase'+ || preservesWorkflowAbsoluteGeometry(workflow)) return result;++ let repairWorkflow;+ const widthOverrides = new Map();+ let minimumTick = 60;+ // Each of the 6.1..8.0 minimum-font ticks can trigger at most one batch.+ // Widths are fixed throughout a route/rank solver epoch; every new epoch+ // starts with empty geometry feedback and measures its own final canvas.+ // Only a complete measured receipt carries nodes; early diagnostic-only+ // failures must never start sizing feedback.+ while (!result.ok && result.receipt?.contract === 'readable-v2'+ && Array.isArray(result.receipt.nodes)) {+ const errors = result.diagnostics.filter(({ severity }) => severity !== 'warning');+ if (!errors.length || errors.some(({ code }) => code !== 'workflow/sublabel-readability')) break;+ const minimum = Math.max(...errors.map(({ evidence }) => evidence.requiredFontPx));+ const maximum = Math.min(...errors.map(({ evidence }) => evidence.maximumSlotFontPx));+ if (!Number.isFinite(minimum) || !Number.isFinite(maximum) || minimum > maximum) break;+ const tick = Math.round(minimum * 10);+ if (tick <= minimumTick || tick > 80) break;+ minimumTick = tick;++ const measuredWidths = new Map(result.receipt.nodes.map(({ id, width }) => [id, width]));+ let changed = false;+ for (const node of workflow.nodes) {+ if (Number.isFinite(node.width) || !node.sublabel) continue;+ const currentWidth = measuredWidths.get(node.id);+ const needed = minimumNodeTextWidth(node.sublabel, minimum);+ if (needed <= availableNodeTextWidth(currentWidth)) continue;+ const padding = currentWidth - availableNodeTextWidth(currentWidth);+ const width = Math.min(200, Math.ceil((needed + padding) / 4) * 4);+ if (width <= currentWidth) continue;+ widthOverrides.set(node.id, width);+ changed = true;+ }+ if (!changed) break;+ repairWorkflow ||= cloneWorkflow(workflow);+ result = compileWithLayoutFeedback({ ...options, workflow: repairWorkflow, widthOverrides });+ }+ return result;+}+export function compileWorkflow({ workflow, qualityProfile, sourceEvidence } = {}) {return compileWorkflowWithFeedback({ workflow, qualityProfile, sourceEvidence });}diff --git a/docs/assets/archify-live-proof.gif b/docs/assets/archify-live-proof.gifindex a0c9720b..c005faa1 100644Binary files a/docs/assets/archify-live-proof.gif and b/docs/assets/archify-live-proof.gif differdiff --git a/docs/assets/archify-live-proof.json b/docs/assets/archify-live-proof.jsonindex 644ce7b0..7b674250 100644--- a/docs/assets/archify-live-proof.json+++ b/docs/assets/archify-live-proof.json@@ -7,13 +7,13 @@"fps": 10,"frameCount": 54,"durationSeconds": 5.4,- "bytes": 852437,- "sha256": "70c5e7ffa3df7e5bb387c9dd08407722c630124f4c686dd0eee86eefa7721499",+ "bytes": 847102,+ "sha256": "af374a1d12b12ac4fbc1b29d35f9dcf966c2ac31889c76f9ca3abfdb50d4abee","scenes": [{"id": "signal-flow","artifact": "docs/gallery/artifacts/agent-tool-call.workflow.html",- "artifactSha256": "6190fddb3c799c96a9a6d0d23313856cc7158f477cd505aa36f96e9359c204dc",+ "artifactSha256": "23e174e48a9c29eb3d5e682df80fbcb6a6ebc8b6eccc7ad5dca0915124648e7b","hash": "#focus=planner&reach=downstream","eyebrow": "WORKFLOW · SIGNAL FLOW","title": "Agent Tool Call",@@ -31,7 +31,7 @@{"id": "classic","artifact": "docs/gallery/artifacts/cache-miss.sequence.html",- "artifactSha256": "80e93b231b50398c4c34b77fe7ad6494c6e9c46bb031b43ac1b4b40f21f98a1c",+ "artifactSha256": "5a3481c7ce649ab276c812fe6ad6ca9cd0ec80944cb2c7f354e02707670104b7","hash": "#route=web~db","eyebrow": "SEQUENCE · CLASSIC","title": "Cache Miss Request",diff --git a/docs/gallery.html b/docs/gallery.htmlindex ca7feb10..ef28f67d 100644--- a/docs/gallery.html+++ b/docs/gallery.html@@ -302,7 +302,7 @@<div class="receipt-cell"><span class="receipt-label">Artifact</span><span class="receipt-value ok">9/9 pass</span></div><div class="receipt-cell"><span class="receipt-label">Composition</span><span class="receipt-value ok" title="0 crossings · 0 border runs · 0 micro segments · 0 cramped turns">SHOWCASE · PASS</span></div><div class="receipt-cell"><span class="receipt-label">Graph</span><span class="receipt-value">12N · 11E</span></div>- <div class="receipt-cell"><span class="receipt-label">SHA-256</span><span class="receipt-value" title="6190fddb3c799c96a9a6d0d23313856cc7158f477cd505aa36f96e9359c204dc">6190fddb3c79</span></div>+ <div class="receipt-cell"><span class="receipt-label">SHA-256</span><span class="receipt-value" title="23e174e48a9c29eb3d5e682df80fbcb6a6ebc8b6eccc7ad5dca0915124648e7b">23e174e48a9c</span></div></div><div class="card-actions"><a class="card-link primary" href="gallery/artifacts/agent-tool-call.workflow.html#focus=planner" target="_blank" rel="noopener" data-en="Explore focus ↗" data-zh="探索聚焦路径 ↗">Explore focus ↗</a>@@ -361,7 +361,7 @@<div class="receipt-cell"><span class="receipt-label">Artifact</span><span class="receipt-value ok">9/9 pass</span></div><div class="receipt-cell"><span class="receipt-label">Composition</span><span class="receipt-value ok" title="0 crossings · 0 border runs · 0 micro segments · 0 cramped turns">SHOWCASE · PASS</span></div><div class="receipt-cell"><span class="receipt-label">Graph</span><span class="receipt-value">7N · 12E</span></div>- <div class="receipt-cell"><span class="receipt-label">SHA-256</span><span class="receipt-value" title="80e93b231b50398c4c34b77fe7ad6494c6e9c46bb031b43ac1b4b40f21f98a1c">80e93b231b50</span></div>+ <div class="receipt-cell"><span class="receipt-label">SHA-256</span><span class="receipt-value" title="5a3481c7ce649ab276c812fe6ad6ca9cd0ec80944cb2c7f354e02707670104b7">5a3481c7ce64</span></div></div><div class="card-actions"><a class="card-link primary" href="gallery/artifacts/cache-miss.sequence.html#focus=redis" target="_blank" rel="noopener" data-en="Explore focus ↗" data-zh="探索聚焦路径 ↗">Explore focus ↗</a>@@ -390,7 +390,7 @@<div class="receipt-cell"><span class="receipt-label">Artifact</span><span class="receipt-value ok">9/9 pass</span></div><div class="receipt-cell"><span class="receipt-label">Composition</span><span class="receipt-value ok" title="0 crossings · 0 border runs · 0 micro segments · 0 cramped turns">SHOWCASE · PASS</span></div><div class="receipt-cell"><span class="receipt-label">Graph</span><span class="receipt-value">10N · 10E</span></div>- <div class="receipt-cell"><span class="receipt-label">SHA-256</span><span class="receipt-value" title="1a384f3fdfdc1110ab49ef64ec5a5f5c5e9d2cff046b0259e083d8f8b292f1e7">1a384f3fdfdc</span></div>+ <div class="receipt-cell"><span class="receipt-label">SHA-256</span><span class="receipt-value" title="37988d97b59899bfefcbf87d5004a4eacef5abda48298813c10aab65d1de0ead">37988d97b598</span></div></div><div class="card-actions"><a class="card-link primary" href="gallery/artifacts/release-delivery.workflow.html#focus=approval" target="_blank" rel="noopener" data-en="Explore focus ↗" data-zh="探索聚焦路径 ↗">Explore focus ↗</a>@@ -419,7 +419,7 @@<div class="receipt-cell"><span class="receipt-label">Artifact</span><span class="receipt-value ok">9/9 pass</span></div><div class="receipt-cell"><span class="receipt-label">Composition</span><span class="receipt-value ok" title="0 crossings · 0 border runs · 0 micro segments · 0 cramped turns">SHOWCASE · PASS</span></div><div class="receipt-cell"><span class="receipt-label">Graph</span><span class="receipt-value">11N · 10E</span></div>- <div class="receipt-cell"><span class="receipt-label">SHA-256</span><span class="receipt-value" title="3b48c070771a1f3a11df5cb44fe8a90c71b49ec85a1f324a4223c83395725d83">3b48c070771a</span></div>+ <div class="receipt-cell"><span class="receipt-label">SHA-256</span><span class="receipt-value" title="a138695070035204c2f86452d28107117fba0ba282fa8e452d5e4069399974ce">a13869507003</span></div></div><div class="card-actions"><a class="card-link primary" href="gallery/artifacts/incident-response.workflow.html#focus=triage" target="_blank" rel="noopener" data-en="Explore focus ↗" data-zh="探索聚焦路径 ↗">Explore focus ↗</a>@@ -477,7 +477,7 @@<div class="receipt-cell"><span class="receipt-label">Artifact</span><span class="receipt-value ok">9/9 pass</span></div><div class="receipt-cell"><span class="receipt-label">Composition</span><span class="receipt-value ok" title="0 crossings · 0 border runs · 0 micro segments · 0 cramped turns">SHOWCASE · PASS</span></div><div class="receipt-cell"><span class="receipt-label">Graph</span><span class="receipt-value">7N · 14E</span></div>- <div class="receipt-cell"><span class="receipt-label">SHA-256</span><span class="receipt-value" title="39a09a8bcc82a5481efce3bd8e7fc50b402f5094ae93fb98ea3e38c6bfb16c81">39a09a8bcc82</span></div>+ <div class="receipt-cell"><span class="receipt-label">SHA-256</span><span class="receipt-value" title="deee38ce18d5c4e40f4a1a89f437e17b466f74b8e2d884d1b175dea899ea2024">deee38ce18d5</span></div></div><div class="card-actions"><a class="card-link primary" href="gallery/artifacts/async-job-roundtrip.sequence.html#focus=queue" target="_blank" rel="noopener" data-en="Explore focus ↗" data-zh="探索聚焦路径 ↗">Explore focus ↗</a>@@ -535,7 +535,7 @@<div class="receipt-cell"><span class="receipt-label">Artifact</span><span class="receipt-value ok">9/9 pass</span></div><div class="receipt-cell"><span class="receipt-label">Composition</span><span class="receipt-value ok" title="0 crossings · 0 border runs · 0 micro segments · 0 cramped turns">SHOWCASE · PASS</span></div><div class="receipt-cell"><span class="receipt-label">Graph</span><span class="receipt-value">10N · 12E</span></div>- <div class="receipt-cell"><span class="receipt-label">SHA-256</span><span class="receipt-value" title="e363fdb54f2a6cb3ef3262b081515212524f4b24a0cb5103f3dd301fe8764c5d">e363fdb54f2a</span></div>+ <div class="receipt-cell"><span class="receipt-label">SHA-256</span><span class="receipt-value" title="c752421f922941aaf84237c8389a9c614722461d56e7340205f47339a07a0d2e">c752421f9229</span></div></div><div class="card-actions"><a class="card-link primary" href="gallery/artifacts/agent-run.lifecycle.html#focus=approval" target="_blank" rel="noopener" data-en="Explore focus ↗" data-zh="探索聚焦路径 ↗">Explore focus ↗</a>@@ -564,7 +564,7 @@<div class="receipt-cell"><span class="receipt-label">Artifact</span><span class="receipt-value ok">9/9 pass</span></div><div class="receipt-cell"><span class="receipt-label">Composition</span><span class="receipt-value ok" title="0 crossings · 0 border runs · 0 micro segments · 0 cramped turns">SHOWCASE · PASS</span></div><div class="receipt-cell"><span class="receipt-label">Graph</span><span class="receipt-value">12N · 15E</span></div>- <div class="receipt-cell"><span class="receipt-label">SHA-256</span><span class="receipt-value" title="c3f8c43cf89164778bcb43412d9b8a6652248f6c7e76ddfe4691e429fea2d607">c3f8c43cf891</span></div>+ <div class="receipt-cell"><span class="receipt-label">SHA-256</span><span class="receipt-value" title="3a8385ab976303cd612a2cd6267531f1ff884789025c8da460799989b9a1de66">3a8385ab9763</span></div></div><div class="card-actions"><a class="card-link primary" href="gallery/artifacts/deployment-release.lifecycle.html#focus=live" target="_blank" rel="noopener" data-en="Explore focus ↗" data-zh="探索聚焦路径 ↗">Explore focus ↗</a>@@ -701,8 +701,8 @@ receipt 108 checks / 12 artifacts / deterministic hashes</pre>"engineeringProfile": null,"nodeCount": 12,"edgeCount": 11,- "artifactBytes": 784769,- "artifactSha256": "6190fddb3c799c96a9a6d0d23313856cc7158f477cd505aa36f96e9359c204dc",+ "artifactBytes": 784775,+ "artifactSha256": "23e174e48a9c29eb3d5e682df80fbcb6a6ebc8b6eccc7ad5dca0915124648e7b","sourceBytes": 4939,"sourceSha256": "d67965d50872c97e4ff3476271e645bf19fab6b3ab44e111bdb44b063e3aa36f","checks": [@@ -969,8 +969,8 @@ receipt 108 checks / 12 artifacts / deterministic hashes</pre>"engineeringProfile": null,"nodeCount": 7,"edgeCount": 12,- "artifactBytes": 779300,- "artifactSha256": "80e93b231b50398c4c34b77fe7ad6494c6e9c46bb031b43ac1b4b40f21f98a1c",+ "artifactBytes": 779306,+ "artifactSha256": "5a3481c7ce649ab276c812fe6ad6ca9cd0ec80944cb2c7f354e02707670104b7","sourceBytes": 3805,"sourceSha256": "f8486daa803fff6c295cecca4604c561fbbf9acb2e83326022b5a87639e8afe6","checks": [@@ -1103,8 +1103,8 @@ receipt 108 checks / 12 artifacts / deterministic hashes</pre>"engineeringProfile": null,"nodeCount": 10,"edgeCount": 10,- "artifactBytes": 780273,- "artifactSha256": "1a384f3fdfdc1110ab49ef64ec5a5f5c5e9d2cff046b0259e083d8f8b292f1e7",+ "artifactBytes": 780283,+ "artifactSha256": "37988d97b59899bfefcbf87d5004a4eacef5abda48298813c10aab65d1de0ead","sourceBytes": 4510,"sourceSha256": "dbd5c174af66296caec372e7214cf4df7158b50a563508e16826b95ab8d1cd6c","checks": [@@ -1243,8 +1243,8 @@ receipt 108 checks / 12 artifacts / deterministic hashes</pre>"engineeringProfile": null,"nodeCount": 11,"edgeCount": 10,- "artifactBytes": 777593,- "artifactSha256": "3b48c070771a1f3a11df5cb44fe8a90c71b49ec85a1f324a4223c83395725d83",+ "artifactBytes": 777603,+ "artifactSha256": "a138695070035204c2f86452d28107117fba0ba282fa8e452d5e4069399974ce","sourceBytes": 4723,"sourceSha256": "630be98449925d2716ecb8439f404b2bff5fe65ba905b0ad0baea6d96890c526","checks": [@@ -1564,8 +1564,8 @@ receipt 108 checks / 12 artifacts / deterministic hashes</pre>"engineeringProfile": null,"nodeCount": 7,"edgeCount": 14,- "artifactBytes": 779646,- "artifactSha256": "39a09a8bcc82a5481efce3bd8e7fc50b402f5094ae93fb98ea3e38c6bfb16c81",+ "artifactBytes": 779652,+ "artifactSha256": "deee38ce18d5c4e40f4a1a89f437e17b466f74b8e2d884d1b175dea899ea2024","sourceBytes": 3766,"sourceSha256": "b8c6c52f1763ede2933c77deb8da59b3e06917bc41d27e66df896136456b859a","checks": [@@ -1868,8 +1868,8 @@ receipt 108 checks / 12 artifacts / deterministic hashes</pre>"engineeringProfile": null,"nodeCount": 10,"edgeCount": 12,- "artifactBytes": 785682,- "artifactSha256": "e363fdb54f2a6cb3ef3262b081515212524f4b24a0cb5103f3dd301fe8764c5d",+ "artifactBytes": 785661,+ "artifactSha256": "c752421f922941aaf84237c8389a9c614722461d56e7340205f47339a07a0d2e","sourceBytes": 3260,"sourceSha256": "5ba36f5ce91ed428cb48b599e275424916d82b619b9a3231cbd1bbc3966fc54b","checks": [@@ -1990,8 +1990,8 @@ receipt 108 checks / 12 artifacts / deterministic hashes</pre>"engineeringProfile": null,"nodeCount": 12,"edgeCount": 15,- "artifactBytes": 792458,- "artifactSha256": "c3f8c43cf89164778bcb43412d9b8a6652248f6c7e76ddfe4691e429fea2d607",+ "artifactBytes": 792430,+ "artifactSha256": "3a8385ab976303cd612a2cd6267531f1ff884789025c8da460799989b9a1de66","sourceBytes": 4155,"sourceSha256": "e3dc105d03c1c9881160006cdace23cb5d8533803e337caf0ec287c64e775275","checks": [diff --git a/docs/gallery/artifacts/agent-run.lifecycle.html b/docs/gallery/artifacts/agent-run.lifecycle.htmlindex 56abd288..5b02faa9 100644--- a/docs/gallery/artifacts/agent-run.lifecycle.html+++ b/docs/gallery/artifacts/agent-run.lifecycle.html@@ -5183,7 +5183,7 @@ OTHER DEALINGS IN THE FONT SOFTWARE.</g><g data-detail="context" data-edge-from="approval" data-edge-to="executing" data-edge-label="approved" data-edge-key="5" data-edge-id="approval-executing"><rect x="505" y="165" width="60" height="16" rx="4" class="c-mask"/>- <text x="535" y="176.5" class="t-edge-default" font-size="10" text-anchor="middle">approved</text>+ <text x="535" y="176.5" class="t-muted" font-size="10" text-anchor="middle">approved</text></g><g data-detail="context" data-edge-from="approval" data-edge-to="cancelled" data-edge-label="user denies" data-edge-key="6" data-edge-id="approval-cancelled"><rect x="402" y="304" width="78" height="16" rx="4" class="c-mask"/>@@ -5199,11 +5199,11 @@ OTHER DEALINGS IN THE FONT SOFTWARE.</g><g data-detail="context" data-edge-from="reviewing" data-edge-to="blocked" data-edge-label="needs input" data-edge-key="9" data-edge-id="reviewing-blocked"><rect x="757" y="165" width="78" height="16" rx="4" class="c-mask"/>- <text x="796" y="176.5" class="t-edge-default" font-size="10" text-anchor="middle">needs input</text>+ <text x="796" y="176.5" class="t-muted" font-size="10" text-anchor="middle">needs input</text></g><g data-detail="context" data-edge-from="blocked" data-edge-to="reviewing" data-edge-label="input given" data-edge-key="10" data-edge-id="blocked-reviewing"><rect x="873" y="156" width="78" height="16" rx="4" class="c-mask"/>- <text x="912" y="167.5" class="t-edge-default" font-size="10" text-anchor="middle">input given</text>+ <text x="912" y="167.5" class="t-muted" font-size="10" text-anchor="middle">input given</text></g><g data-detail="context" data-edge-from="blocked" data-edge-to="expired" data-edge-label="no reply 24h" data-edge-key="11" data-edge-id="blocked-expired"><rect x="764" y="304" width="84" height="16" rx="4" class="c-mask"/>diff --git a/docs/gallery/artifacts/agent-tool-call.workflow.html b/docs/gallery/artifacts/agent-tool-call.workflow.htmlindex 0726793e..a93c4804 100644--- a/docs/gallery/artifacts/agent-tool-call.workflow.html+++ b/docs/gallery/artifacts/agent-tool-call.workflow.html@@ -4980,17 +4980,17 @@ OTHER DEALINGS IN THE FONT SOFTWARE.<!-- Swimlanes --><rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-0" x="40" y="52" width="1040" height="106" rx="10" class="c-lane" stroke-width="1"/>- <text x="54" y="74" class="t-dim" font-size="10" font-weight="600">01 / User Interface</text>+ <text x="54" y="74" class="t-muted" font-size="10" font-weight="600">01 / User Interface</text><rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-1" x="40" y="178" width="1040" height="114" rx="10" class="c-lane" stroke-width="1"/>- <text x="54" y="200" class="t-dim" font-size="10" font-weight="600">02 / Agent Runtime</text>+ <text x="54" y="200" class="t-muted" font-size="10" font-weight="600">02 / Agent Runtime</text><rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-2" x="40" y="312" width="1040" height="114" rx="10" class="c-lane" stroke-width="1"/><rect data-graph-role="structural-frame" data-composition-frame-kind="exception-lane" data-composition-frame-id="lane-2-exception" x="46" y="318" width="1028" height="102" rx="8" class="c-security-group" stroke-width="1"/><text x="54" y="334" class="t-security" font-size="10" font-weight="600">EX / Policy & Recovery</text><rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-3" x="40" y="446" width="1040" height="114" rx="10" class="c-lane" stroke-width="1"/>- <text x="54" y="468" class="t-dim" font-size="10" font-weight="600">04 / Tool Execution & Evidence</text>+ <text x="54" y="468" class="t-muted" font-size="10" font-weight="600">04 / Tool Execution & Evidence</text><!-- Phase headers --><line x1="68" y1="35" x2="324" y2="35" class="a-default" stroke-width="1.1"/>diff --git a/docs/gallery/artifacts/async-job-roundtrip.sequence.html b/docs/gallery/artifacts/async-job-roundtrip.sequence.htmlindex 21194391..b387af92 100644--- a/docs/gallery/artifacts/async-job-roundtrip.sequence.html+++ b/docs/gallery/artifacts/async-job-roundtrip.sequence.html@@ -5125,16 +5125,16 @@ OTHER DEALINGS IN THE FONT SOFTWARE.<!-- Segment Labels --><g data-graph-role="segment-label" data-segment-id="0">- <rect x="56" y="128" width="45.2" height="18" rx="3" class="c-mask"/>- <text x="62" y="141" class="t-dim" font-size="9" font-weight="600">Accept</text>+ <rect x="56" y="134" width="45.2" height="18" rx="3" class="c-mask"/>+ <text x="62" y="147" class="t-muted" font-size="9" font-weight="600">Accept</text></g><g data-graph-role="segment-label" data-segment-id="1"><rect x="56" y="284" width="92" height="18" rx="3" class="c-mask"/>- <text x="62" y="297" class="t-dim" font-size="9" font-weight="600">Background work</text>+ <text x="62" y="297" class="t-muted" font-size="9" font-weight="600">Background work</text></g><g data-graph-role="segment-label" data-segment-id="2"><rect x="56" y="532" width="107.60000000000001" height="18" rx="3" class="c-mask"/>- <text x="62" y="545" class="t-dim" font-size="9" font-weight="600">Notify + reconcile</text>+ <text x="62" y="545" class="t-muted" font-size="9" font-weight="600">Notify + reconcile</text></g><!-- Participants -->diff --git a/docs/gallery/artifacts/cache-miss.sequence.html b/docs/gallery/artifacts/cache-miss.sequence.htmlindex 348b8c50..4f9b0053 100644--- a/docs/gallery/artifacts/cache-miss.sequence.html+++ b/docs/gallery/artifacts/cache-miss.sequence.html@@ -5107,16 +5107,16 @@ OTHER DEALINGS IN THE FONT SOFTWARE.<!-- Segment Labels --><g data-graph-role="segment-label" data-segment-id="0">- <rect x="56" y="128" width="50.4" height="18" rx="3" class="c-mask"/>- <text x="62" y="141" class="t-dim" font-size="9" font-weight="600">Request</text>+ <rect x="56" y="134" width="50.4" height="18" rx="3" class="c-mask"/>+ <text x="62" y="147" class="t-muted" font-size="9" font-weight="600">Request</text></g><g data-graph-role="segment-label" data-segment-id="1"><rect x="56" y="238" width="55.6" height="18" rx="3" class="c-mask"/>- <text x="62" y="251" class="t-dim" font-size="9" font-weight="600">Fallback</text>+ <text x="62" y="251" class="t-muted" font-size="9" font-weight="600">Fallback</text></g><g data-graph-role="segment-label" data-segment-id="2"><rect x="56" y="358" width="97.2" height="18" rx="3" class="c-mask"/>- <text x="62" y="371" class="t-dim" font-size="9" font-weight="600">Response + trace</text>+ <text x="62" y="371" class="t-muted" font-size="9" font-weight="600">Response + trace</text></g><!-- Participants -->diff --git a/docs/gallery/artifacts/deployment-release.lifecycle.html b/docs/gallery/artifacts/deployment-release.lifecycle.htmlindex e742095a..79b8f338 100644--- a/docs/gallery/artifacts/deployment-release.lifecycle.html+++ b/docs/gallery/artifacts/deployment-release.lifecycle.html@@ -5217,7 +5217,7 @@ OTHER DEALINGS IN THE FONT SOFTWARE.</g><g data-detail="context" data-edge-from="verifying" data-edge-to="building" data-edge-label="tests fail" data-edge-key="4" data-edge-id="verifying-building"><rect x="432" y="32" width="72" height="16" rx="4" class="c-mask"/>- <text x="468" y="43.5" class="t-edge-default" font-size="10" text-anchor="middle">tests fail</text>+ <text x="468" y="43.5" class="t-muted" font-size="10" text-anchor="middle">tests fail</text></g><g data-detail="context" data-edge-from="verifying" data-edge-to="approval" data-edge-label="needs sign-off" data-edge-key="5" data-edge-id="verifying-approval"><rect x="597" y="189" width="96" height="16" rx="4" class="c-mask"/>@@ -5225,7 +5225,7 @@ OTHER DEALINGS IN THE FONT SOFTWARE.</g><g data-detail="context" data-edge-from="approval" data-edge-to="ready" data-edge-label="approved" data-edge-key="6" data-edge-id="approval-ready"><rect x="731" y="189" width="60" height="16" rx="4" class="c-mask"/>- <text x="761" y="200.5" class="t-edge-default" font-size="10" text-anchor="middle">approved</text>+ <text x="761" y="200.5" class="t-muted" font-size="10" text-anchor="middle">approved</text></g><g data-detail="context" data-edge-from="approval" data-edge-to="cancelled" data-edge-label="denied" data-edge-key="7" data-edge-id="approval-cancelled"><rect x="658" y="328" width="48" height="16" rx="4" class="c-mask"/>@@ -5237,7 +5237,7 @@ OTHER DEALINGS IN THE FONT SOFTWARE.</g><g data-detail="context" data-edge-from="paused" data-edge-to="live" data-edge-label="recovered" data-edge-key="9" data-edge-id="paused-live"><rect x="1074" y="172" width="66" height="16" rx="4" class="c-mask"/>- <text x="1107" y="183.5" class="t-edge-default" font-size="10" text-anchor="middle">recovered</text>+ <text x="1107" y="183.5" class="t-muted" font-size="10" text-anchor="middle">recovered</text></g><g data-detail="context" data-edge-from="paused" data-edge-to="rollback" data-edge-label="breach persists" data-edge-key="10" data-edge-id="paused-rollback"><rect x="947" y="328" width="102" height="16" rx="4" class="c-mask"/>@@ -5253,7 +5253,7 @@ OTHER DEALINGS IN THE FONT SOFTWARE.</g><g data-detail="context" data-edge-from="building" data-edge-to="aborted" data-edge-label="abort" data-edge-key="13" data-edge-id="building-aborted"><rect x="420" y="177" width="42" height="16" rx="4" class="c-mask"/>- <text x="441" y="188.5" class="t-edge-default" font-size="10" text-anchor="middle">abort</text>+ <text x="441" y="188.5" class="t-muted" font-size="10" text-anchor="middle">abort</text></g><!-- Legend -->diff --git a/docs/gallery/artifacts/incident-response.workflow.html b/docs/gallery/artifacts/incident-response.workflow.htmlindex aaace856..c16316b8 100644--- a/docs/gallery/artifacts/incident-response.workflow.html+++ b/docs/gallery/artifacts/incident-response.workflow.html@@ -4980,19 +4980,19 @@ OTHER DEALINGS IN THE FONT SOFTWARE.<!-- Swimlanes --><rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-0" x="40" y="52" width="640" height="104" rx="10" class="c-lane" stroke-width="1"/>- <text x="54" y="74" class="t-dim" font-size="10" font-weight="600">01 / Signals</text>+ <text x="54" y="74" class="t-muted" font-size="10" font-weight="600">01 / Signals</text><rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-1" x="40" y="176" width="640" height="104" rx="10" class="c-lane" stroke-width="1"/>- <text x="54" y="198" class="t-dim" font-size="10" font-weight="600">02 / Incident Command</text>+ <text x="54" y="198" class="t-muted" font-size="10" font-weight="600">02 / Incident Command</text><rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-2" x="40" y="300" width="640" height="104" rx="10" class="c-lane" stroke-width="1"/>- <text x="54" y="322" class="t-dim" font-size="10" font-weight="600">03 / Service Mitigation</text>+ <text x="54" y="322" class="t-muted" font-size="10" font-weight="600">03 / Service Mitigation</text><rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-3" x="40" y="424" width="640" height="104" rx="10" class="c-lane" stroke-width="1"/>- <text x="54" y="446" class="t-dim" font-size="10" font-weight="600">04 / Recovery Evidence</text>+ <text x="54" y="446" class="t-muted" font-size="10" font-weight="600">04 / Recovery Evidence</text><rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-4" x="40" y="548" width="640" height="104" rx="10" class="c-lane" stroke-width="1"/>- <text x="54" y="570" class="t-dim" font-size="10" font-weight="600">05 / Stakeholder Communication</text>+ <text x="54" y="570" class="t-muted" font-size="10" font-weight="600">05 / Stakeholder Communication</text><rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-5" x="40" y="672" width="640" height="104" rx="10" class="c-lane" stroke-width="1"/><rect data-graph-role="structural-frame" data-composition-frame-kind="exception-lane" data-composition-frame-id="lane-5-exception" x="46" y="678" width="628" height="92" rx="8" class="c-security-group" stroke-width="1"/>diff --git a/docs/gallery/artifacts/release-delivery.workflow.html b/docs/gallery/artifacts/release-delivery.workflow.htmlindex d894a680..051b42b7 100644--- a/docs/gallery/artifacts/release-delivery.workflow.html+++ b/docs/gallery/artifacts/release-delivery.workflow.html@@ -4980,19 +4980,19 @@ OTHER DEALINGS IN THE FONT SOFTWARE.<!-- Swimlanes --><rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-0" x="40" y="52" width="640" height="104" rx="10" class="c-lane" stroke-width="1"/>- <text x="54" y="74" class="t-dim" font-size="10" font-weight="600">01 / Developer</text>+ <text x="54" y="74" class="t-muted" font-size="10" font-weight="600">01 / Developer</text><rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-1" x="40" y="176" width="640" height="104" rx="10" class="c-lane" stroke-width="1"/>- <text x="54" y="198" class="t-dim" font-size="10" font-weight="600">02 / Continuous Integration</text>+ <text x="54" y="198" class="t-muted" font-size="10" font-weight="600">02 / Continuous Integration</text><rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-2" x="40" y="300" width="640" height="104" rx="10" class="c-lane" stroke-width="1"/>- <text x="54" y="322" class="t-dim" font-size="10" font-weight="600">03 / Release Governance</text>+ <text x="54" y="322" class="t-muted" font-size="10" font-weight="600">03 / Release Governance</text><rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-3" x="40" y="424" width="640" height="104" rx="10" class="c-lane" stroke-width="1"/>- <text x="54" y="446" class="t-dim" font-size="10" font-weight="600">04 / Production Environment</text>+ <text x="54" y="446" class="t-muted" font-size="10" font-weight="600">04 / Production Environment</text><rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-4" x="40" y="548" width="640" height="104" rx="10" class="c-lane" stroke-width="1"/>- <text x="54" y="570" class="t-dim" font-size="10" font-weight="600">05 / Release Communication</text>+ <text x="54" y="570" class="t-muted" font-size="10" font-weight="600">05 / Release Communication</text><rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-5" x="40" y="672" width="640" height="104" rx="10" class="c-lane" stroke-width="1"/><rect data-graph-role="structural-frame" data-composition-frame-kind="exception-lane" data-composition-frame-id="lane-5-exception" x="46" y="678" width="628" height="92" rx="8" class="c-security-group" stroke-width="1"/>diff --git a/docs/gallery/manifest.json b/docs/gallery/manifest.jsonindex 1379eb8e..7dd3b4cf 100644--- a/docs/gallery/manifest.json+++ b/docs/gallery/manifest.json@@ -19,8 +19,8 @@"engineeringProfile": null,"nodeCount": 12,"edgeCount": 11,- "artifactBytes": 784769,- "artifactSha256": "6190fddb3c799c96a9a6d0d23313856cc7158f477cd505aa36f96e9359c204dc",+ "artifactBytes": 784775,+ "artifactSha256": "23e174e48a9c29eb3d5e682df80fbcb6a6ebc8b6eccc7ad5dca0915124648e7b","sourceBytes": 4939,"sourceSha256": "d67965d50872c97e4ff3476271e645bf19fab6b3ab44e111bdb44b063e3aa36f","checks": [@@ -287,8 +287,8 @@"engineeringProfile": null,"nodeCount": 7,"edgeCount": 12,- "artifactBytes": 779300,- "artifactSha256": "80e93b231b50398c4c34b77fe7ad6494c6e9c46bb031b43ac1b4b40f21f98a1c",+ "artifactBytes": 779306,+ "artifactSha256": "5a3481c7ce649ab276c812fe6ad6ca9cd0ec80944cb2c7f354e02707670104b7","sourceBytes": 3805,"sourceSha256": "f8486daa803fff6c295cecca4604c561fbbf9acb2e83326022b5a87639e8afe6","checks": [@@ -421,8 +421,8 @@"engineeringProfile": null,"nodeCount": 10,"edgeCount": 10,- "artifactBytes": 780273,- "artifactSha256": "1a384f3fdfdc1110ab49ef64ec5a5f5c5e9d2cff046b0259e083d8f8b292f1e7",+ "artifactBytes": 780283,+ "artifactSha256": "37988d97b59899bfefcbf87d5004a4eacef5abda48298813c10aab65d1de0ead","sourceBytes": 4510,"sourceSha256": "dbd5c174af66296caec372e7214cf4df7158b50a563508e16826b95ab8d1cd6c","checks": [@@ -561,8 +561,8 @@"engineeringProfile": null,"nodeCount": 11,"edgeCount": 10,- "artifactBytes": 777593,- "artifactSha256": "3b48c070771a1f3a11df5cb44fe8a90c71b49ec85a1f324a4223c83395725d83",+ "artifactBytes": 777603,+ "artifactSha256": "a138695070035204c2f86452d28107117fba0ba282fa8e452d5e4069399974ce","sourceBytes": 4723,"sourceSha256": "630be98449925d2716ecb8439f404b2bff5fe65ba905b0ad0baea6d96890c526","checks": [@@ -882,8 +882,8 @@"engineeringProfile": null,"nodeCount": 7,"edgeCount": 14,- "artifactBytes": 779646,- "artifactSha256": "39a09a8bcc82a5481efce3bd8e7fc50b402f5094ae93fb98ea3e38c6bfb16c81",+ "artifactBytes": 779652,+ "artifactSha256": "deee38ce18d5c4e40f4a1a89f437e17b466f74b8e2d884d1b175dea899ea2024","sourceBytes": 3766,"sourceSha256": "b8c6c52f1763ede2933c77deb8da59b3e06917bc41d27e66df896136456b859a","checks": [@@ -1186,8 +1186,8 @@"engineeringProfile": null,"nodeCount": 10,"edgeCount": 12,- "artifactBytes": 785682,- "artifactSha256": "e363fdb54f2a6cb3ef3262b081515212524f4b24a0cb5103f3dd301fe8764c5d",+ "artifactBytes": 785661,+ "artifactSha256": "c752421f922941aaf84237c8389a9c614722461d56e7340205f47339a07a0d2e","sourceBytes": 3260,"sourceSha256": "5ba36f5ce91ed428cb48b599e275424916d82b619b9a3231cbd1bbc3966fc54b","checks": [@@ -1308,8 +1308,8 @@"engineeringProfile": null,"nodeCount": 12,"edgeCount": 15,- "artifactBytes": 792458,- "artifactSha256": "c3f8c43cf89164778bcb43412d9b8a6652248f6c7e76ddfe4691e429fea2d607",+ "artifactBytes": 792430,+ "artifactSha256": "3a8385ab976303cd612a2cd6267531f1ff884789025c8da460799989b9a1de66","sourceBytes": 4155,"sourceSha256": "e3dc105d03c1c9881160006cdace23cb5d8533803e337caf0ec287c64e775275","checks": [diff --git a/examples/lifecycle-agent-run.html b/examples/lifecycle-agent-run.htmlindex 56abd288..5b02faa9 100644--- a/examples/lifecycle-agent-run.html+++ b/examples/lifecycle-agent-run.html@@ -5183,7 +5183,7 @@ OTHER DEALINGS IN THE FONT SOFTWARE.</g><g data-detail="context" data-edge-from="approval" data-edge-to="executing" data-edge-label="approved" data-edge-key="5" data-edge-id="approval-executing"><rect x="505" y="165" width="60" height="16" rx="4" class="c-mask"/>- <text x="535" y="176.5" class="t-edge-default" font-size="10" text-anchor="middle">approved</text>+ <text x="535" y="176.5" class="t-muted" font-size="10" text-anchor="middle">approved</text></g><g data-detail="context" data-edge-from="approval" data-edge-to="cancelled" data-edge-label="user denies" data-edge-key="6" data-edge-id="approval-cancelled"><rect x="402" y="304" width="78" height="16" rx="4" class="c-mask"/>@@ -5199,11 +5199,11 @@ OTHER DEALINGS IN THE FONT SOFTWARE.</g><g data-detail="context" data-edge-from="reviewing" data-edge-to="blocked" data-edge-label="needs input" data-edge-key="9" data-edge-id="reviewing-blocked"><rect x="757" y="165" width="78" height="16" rx="4" class="c-mask"/>- <text x="796" y="176.5" class="t-edge-default" font-size="10" text-anchor="middle">needs input</text>+ <text x="796" y="176.5" class="t-muted" font-size="10" text-anchor="middle">needs input</text></g><g data-detail="context" data-edge-from="blocked" data-edge-to="reviewing" data-edge-label="input given" data-edge-key="10" data-edge-id="blocked-reviewing"><rect x="873" y="156" width="78" height="16" rx="4" class="c-mask"/>- <text x="912" y="167.5" class="t-edge-default" font-size="10" text-anchor="middle">input given</text>+ <text x="912" y="167.5" class="t-muted" font-size="10" text-anchor="middle">input given</text></g><g data-detail="context" data-edge-from="blocked" data-edge-to="expired" data-edge-label="no reply 24h" data-edge-key="11" data-edge-id="blocked-expired"><rect x="764" y="304" width="84" height="16" rx="4" class="c-mask"/>diff --git a/examples/sequence-cache-miss-request.html b/examples/sequence-cache-miss-request.htmlindex 348b8c50..4f9b0053 100644--- a/examples/sequence-cache-miss-request.html+++ b/examples/sequence-cache-miss-request.html@@ -5107,16 +5107,16 @@ OTHER DEALINGS IN THE FONT SOFTWARE.<!-- Segment Labels --><g data-graph-role="segment-label" data-segment-id="0">- <rect x="56" y="128" width="50.4" height="18" rx="3" class="c-mask"/>- <text x="62" y="141" class="t-dim" font-size="9" font-weight="600">Request</text>+ <rect x="56" y="134" width="50.4" height="18" rx="3" class="c-mask"/>+ <text x="62" y="147" class="t-muted" font-size="9" font-weight="600">Request</text></g><g data-graph-role="segment-label" data-segment-id="1"><rect x="56" y="238" width="55.6" height="18" rx="3" class="c-mask"/>- <text x="62" y="251" class="t-dim" font-size="9" font-weight="600">Fallback</text>+ <text x="62" y="251" class="t-muted" font-size="9" font-weight="600">Fallback</text></g><g data-graph-role="segment-label" data-segment-id="2"><rect x="56" y="358" width="97.2" height="18" rx="3" class="c-mask"/>- <text x="62" y="371" class="t-dim" font-size="9" font-weight="600">Response + trace</text>+ <text x="62" y="371" class="t-muted" font-size="9" font-weight="600">Response + trace</text></g><!-- Participants -->diff --git a/examples/workflow-agent-tool-call-rendered.html b/examples/workflow-agent-tool-call-rendered.htmlindex 0726793e..a93c4804 100644--- a/examples/workflow-agent-tool-call-rendered.html+++ b/examples/workflow-agent-tool-call-rendered.html@@ -4980,17 +4980,17 @@ OTHER DEALINGS IN THE FONT SOFTWARE.<!-- Swimlanes --><rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-0" x="40" y="52" width="1040" height="106" rx="10" class="c-lane" stroke-width="1"/>- <text x="54" y="74" class="t-dim" font-size="10" font-weight="600">01 / User Interface</text>+ <text x="54" y="74" class="t-muted" font-size="10" font-weight="600">01 / User Interface</text><rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-1" x="40" y="178" width="1040" height="114" rx="10" class="c-lane" stroke-width="1"/>- <text x="54" y="200" class="t-dim" font-size="10" font-weight="600">02 / Agent Runtime</text>+ <text x="54" y="200" class="t-muted" font-size="10" font-weight="600">02 / Agent Runtime</text><rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-2" x="40" y="312" width="1040" height="114" rx="10" class="c-lane" stroke-width="1"/><rect data-graph-role="structural-frame" data-composition-frame-kind="exception-lane" data-composition-frame-id="lane-2-exception" x="46" y="318" width="1028" height="102" rx="8" class="c-security-group" stroke-width="1"/><text x="54" y="334" class="t-security" font-size="10" font-weight="600">EX / Policy & Recovery</text><rect data-graph-role="structural-frame" data-composition-frame-kind="lane" data-composition-frame-id="lane-3" x="40" y="446" width="1040" height="114" rx="10" class="c-lane" stroke-width="1"/>- <text x="54" y="468" class="t-dim" font-size="10" font-weight="600">04 / Tool Execution & Evidence</text>+ <text x="54" y="468" class="t-muted" font-size="10" font-weight="600">04 / Tool Execution & Evidence</text><!-- Phase headers --><line x1="68" y1="35" x2="324" y2="35" class="a-default" stroke-width="1.1"/>diff --git a/scripts/browser-test-inventory.mjs b/scripts/browser-test-inventory.mjsindex 76836bfa..02232e6a 100644--- a/scripts/browser-test-inventory.mjs+++ b/scripts/browser-test-inventory.mjs@@ -34,4 +34,7 @@ export const browserTestFiles = ['tree-branches-browser.test.mjs','class-motion-browser.test.mjs','dataflow-label-visibility-browser.test.mjs',+ 'workflow-edge-label-contrast-browser.test.mjs',+ 'lifecycle-note-contrast-browser.test.mjs',+ 'sequence-segment-contrast-browser.test.mjs',];diff --git a/test/cli.test.mjs b/test/cli.test.mjsindex 12330680..24600641 100644--- a/test/cli.test.mjs+++ b/test/cli.test.mjs@@ -191,6 +191,46 @@ test('cli: help lists commands and diagram types', () => {assert.match(result.stdout, /architecture, workflow, sequence, dataflow, lifecycle/);});+test('cli: sole subcommand --help returns canonical usage without operations', (t) => {+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-cli-help-'));+ t.after(() => fs.rmSync(scratch, { recursive: true, force: true }));+ const global = run(['--help'], { cwd: scratch });+ assert.equal(global.status, 0, global.stderr);+ const commands = ['render', 'compare', 'deliver', 'finalize', 'preview', 'validate',+ 'migrate', 'inspect', 'check', 'browser-check', 'visual-check', 'guide', 'brands',+ 'examples', 'doctor', 'demo'];+ for (const command of commands) {+ const result = run([command, '--help'], { cwd: scratch });+ assert.equal(result.status, 0, `${command}: ${result.stderr}`);+ assert.equal(result.stderr, '', command);+ assert.equal(result.stdout, global.stdout, `${command} uses canonical help bytes`);+ assert.deepEqual(fs.readdirSync(scratch), [], `${command} help creates no artifact or evidence`);+ }+});++test('cli: subcommand help keeps unknown and mixed arguments failing', () => {+ const unknown = run(['not-a-command', '--help']);+ assert.equal(unknown.status, 2);+ assert.equal(unknown.stdout, '');+ assert.match(unknown.stderr, /Unknown command "not-a-command"/);+ const mixed = run(['visual-check', '--help', 'missing.html']);+ assert.equal(mixed.status, 1);+ assert.equal(mixed.stdout, '');+ assert.equal(mixed.stderr, 'Unknown visual-check option "--help".\n');+ const json = run(['validate', '--help', '--json']);+ assert.equal(json.status, 2);+ assert.equal(json.stderr, '');+ const receipt = JSON.parse(json.stdout);+ assert.equal(receipt.ok, false);+ assert.equal(receipt.stage, 'arguments');+ assert.equal(receipt.diagnostics[0].code, 'cli/unknown-option');+ assert.equal(receipt.diagnostics[0].subject.option, '--help');+ const bogus = run(['visual-check', '--bogus']);+ assert.equal(bogus.status, 1);+ assert.equal(bogus.stdout, '');+ assert.equal(bogus.stderr, 'Unknown visual-check option "--bogus".\n');+});+test('cli: doctor reports a complete installation is ready', () => {const result = run(['doctor']);assert.equal(result.status, 0, result.stderr);diff --git a/test/dataflow-label-visibility.test.mjs b/test/dataflow-label-visibility.test.mjsindex 82af5831..bf01a6f2 100644--- a/test/dataflow-label-visibility.test.mjs+++ b/test/dataflow-label-visibility.test.mjs@@ -127,3 +127,24 @@ test('an exhausted label search preserves the previous accepted placement insteaassert.deepEqual(launch.mask, { x: 164.75, y: 136, width: 85.5, height: 27 });for (const index of anchors.keys()) assert.ok(!rectsOverlap(launch.mask, flow(html, `block${index}`).mask, -2));});++test('unpinned reciprocal two-line labels remain readable beside their own routes', t => {+ const diagram = JSON.parse(fs.readFileSync(new URL('./fixtures/dataflow-bidirectional-labels.json', import.meta.url)));+ const html = render(t, diagram);+ const svg = html.match(/<svg\b[^]*?<\/svg>/)[0];+ const rendered = diagram.flows.map(relation => ({ id: relation.id, ...flow(html, relation.id) }));+ for (const [index, relation] of diagram.flows.entries()) {+ const { points, mask } = rendered[index];+ assert.ok(svg.includes(`>${relation.label}</text>`), relation.label);+ assert.ok(svg.includes(`>${relation.classification}</text>`), relation.classification);+ assert.equal(mask.height, 27);+ assert.ok(points.slice(1).some((end, segmentIndex) =>+ segmentRectClearanceWithin({ start: points[segmentIndex], end }, mask, 36) <= 36),+ JSON.stringify(rendered[index]));+ for (const other of rendered) {+ if (other.id === relation.id) continue;+ assert.ok(clearRoute(mask, other.points), JSON.stringify({ label: rendered[index], other }));+ assert.ok(!rectsOverlap(mask, other.mask), JSON.stringify({ label: rendered[index], other }));+ }+ }+});diff --git a/test/edge-label-color.test.mjs b/test/edge-label-color.test.mjsindex c874b31c..31db60d6 100644--- a/test/edge-label-color.test.mjs+++ b/test/edge-label-color.test.mjs@@ -80,7 +80,7 @@ function classForLabel(html, id, label) {return match[1];}-test('edge labels use the same variant color contract as their paths in every shared renderer and preset', () => {+test('edge labels retain variant colors with readable workflow and Lifecycle default labels in every preset', () => {for (const [type, config] of Object.entries(CASES)) {for (const preset of PRESETS) {const html = render(type, config, preset);@@ -89,7 +89,7 @@ test('edge labels use the same variant color contract as their paths in every shassert.equal(classForEdge(html, id), `a-${variant}`, `${type}/${preset}/${variant} path`);assert.equal(classForLabel(html, id, `L${VARIANTS.indexOf(variant)}`),- `t-edge-${variant}`,+ ['workflow', 'lifecycle'].includes(type) && variant === 'default' ? 't-muted' : `t-edge-${variant}`,`${type}/${preset}/${variant} label`,);}@@ -97,6 +97,33 @@ test('edge labels use the same variant color contract as their paths in every sh}});+test('Lifecycle default labels respect explicit variants, implicit spine emphasis and note-only content', () => {+ const source = JSON.parse(fs.readFileSync(path.join(skillRoot, CASES.lifecycle.input), 'utf8'));+ source.meta.quality_profile = 'standard';+ source.transitions[0].variant = 'default'; // Explicit default overrides spine emphasis.+ delete source.transitions[1].variant; // The next spine step still defaults to emphasis.+ delete source.transitions[13].variant; // An ordinary branch defaults to neutral text.+ Object.assign(source.transitions[14], { variant: 'default', note: 'withdrawn' });+ delete source.transitions[14].label;+ const input = path.join(tmp, 'lifecycle-default-boundaries.json');+ const output = path.join(tmp, 'lifecycle-default-boundaries.html');+ fs.writeFileSync(input, JSON.stringify(source));+ const result = spawnSync(process.execPath, [cli, 'render', 'lifecycle', input, output], { cwd: skillRoot, encoding: 'utf8' });+ assert.equal(result.status, 0, result.stderr || result.stdout);+ const html = fs.readFileSync(output, 'utf8');+ for (const [index, variant, labelClass] of [[0, 'default', 't-muted'], [1, 'emphasis', 't-edge-emphasis'], [13, 'default', 't-muted']]) {+ const edge = source.transitions[index];+ assert.equal(classForEdge(html, edge.id), `a-${variant}`, `${edge.id} path`);+ assert.equal(classForLabel(html, edge.id, edge.label), labelClass, `${edge.id} label`);+ }+ const noteOnly = source.transitions[14];+ assert.equal(classForEdge(html, noteOnly.id), 'a-default');+ const group = html.match(new RegExp(`<g data-detail="fine"[^>]*data-edge-id="${escapePattern(noteOnly.id)}"[^>]*>([\\s\\S]*?)</g>`));+ assert.ok(group, 'note-only default retains its fine-detail label group');+ assert.equal([...group[1].matchAll(/<text\b/g)].length, 1, 'note-only edge does not acquire a primary label');+ assert.match(group[1], /<text data-detail="fine"[^>]*class="t-muted"[^>]*>withdrawn<\/text>/);+});+test('sequence message labels match their line color and lifelines stop above the legend', () => {const source = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples/cache-miss-request.sequence.json'), 'utf8'));const variants = ['emphasis', 'security', 'dashed', 'default', 'return'];diff --git a/test/finalize.test.mjs b/test/finalize.test.mjsindex 43386f23..aae3975f 100644--- a/test/finalize.test.mjs+++ b/test/finalize.test.mjs@@ -373,7 +373,7 @@ test('compact failure receipts retain diverse actionable subjects without embeddconst compact = compactFinalizeReceipt(receipt);assert.equal(compact.diagnostics.length, 8);assert.equal(new Set(compact.diagnostics.map(({ subject }) => subject.id)).size, 8);- assert.deepEqual(compact.diagnosticSummary, { total: 20, shown: 8, truncated: true });+ assert.deepEqual(compact.diagnosticSummary, { total: 20, shown: 8, truncated: true, omittedByCode: { 'composition/proper-crossing': 12 } });assert.equal(compact.nextAction.action, 'edit-in-place');assert.match(compact.nextAction.constraint, /Preserve all semantics and user-fixed geometry/);assert.match(compact.nextAction.constraint, /local repair or connected-scene reflow/);@@ -381,6 +381,33 @@ test('compact failure receipts retain diverse actionable subjects without embeddassert.ok(JSON.stringify(compact).length < JSON.stringify(receipt).length / 4);});+test('compact failure summaries count omitted entries by code with repeated subjects', () => {+ const codes = ['composition/proper-crossing', 'layout/constraint', '__proto__'];+ const diagnostics = Array.from({ length: 14 }, (_, index) => ({+ code: codes[index % codes.length],+ message: `Failure ${index}`,+ subject: { id: `edge-${Math.floor(index / 3)}` },+ }));+ const receipt = { ok: false, status: 'fail', diagnostics };+ const originalDiagnostics = structuredClone(diagnostics);+ const compact = compactFinalizeReceipt(receipt);+ assert.deepEqual(compact.diagnostics.map(({ message }) => message),+ [0, 1, 2, 3, 6, 9, 12, 4].map(index => `Failure ${index}`));+ const omitted = diagnostics.filter(entry => !compact.diagnostics.some(shown => shown.message === entry.message));+ assert.equal(omitted.length, compact.diagnosticSummary.total - compact.diagnosticSummary.shown);+ assert.deepEqual(compact.diagnosticSummary.omittedByCode, { 'layout/constraint': 3, ['__proto__']: 3 });+ assert.deepEqual(Object.entries(compact.diagnosticSummary.omittedByCode), [+ ['layout/constraint', omitted.filter(({ code }) => code === 'layout/constraint').length],+ ['__proto__', omitted.filter(({ code }) => code === '__proto__').length],+ ]);+ assert.equal(Object.values(compact.diagnosticSummary.omittedByCode).reduce((sum, count) => sum + count, 0), omitted.length);+ assert.deepEqual(receipt.diagnostics, originalDiagnostics);+ for (const entries of [[], diagnostics.slice(0, 8)]) {+ const summary = compactFinalizeReceipt({ ...receipt, diagnostics: entries }).diagnosticSummary;+ assert.equal('omittedByCode' in summary, false);+ }+});+test('merged viewport-overflow diagnostics preserve each subject, evidence, and detection source', async t => {const directory = workspace(t);const input = path.join(directory, 'diagram.json');diff --git a/test/fixtures/dataflow-bidirectional-labels.json b/test/fixtures/dataflow-bidirectional-labels.jsonnew file mode 100644index 00000000..4545a013--- /dev/null+++ b/test/fixtures/dataflow-bidirectional-labels.json@@ -0,0 +1,52 @@+{+ "schema_version": 1,+ "diagram_type": "dataflow",+ "meta": {+ "title": "Client and service exchange",+ "output": "diagram.html",+ "locale": "en",+ "quality_profile": "showcase"+ },+ "stages": [+ {+ "label": "Client"+ },+ {+ "label": "Service"+ }+ ],+ "nodes": [+ {+ "id": "client",+ "type": "frontend",+ "label": "Client",+ "stage": 0,+ "row": 1+ },+ {+ "id": "service",+ "type": "backend",+ "label": "Service",+ "stage": 1,+ "row": 1+ }+ ],+ "flows": [+ {+ "id": "request",+ "from": "client",+ "to": "service",+ "label": "request payload",+ "classification": "JSON request",+ "variant": "emphasis"+ },+ {+ "id": "response",+ "from": "service",+ "to": "client",+ "label": "response payload v1",+ "classification": "JSON response",+ "variant": "default"+ }+ ]+}diff --git a/test/fixtures/lifecycle-dense-exit-notes.json b/test/fixtures/lifecycle-dense-exit-notes.jsonnew file mode 100644index 00000000..f1c6641f--- /dev/null+++ b/test/fixtures/lifecycle-dense-exit-notes.json@@ -0,0 +1,157 @@+{+ "schema_version": 3,+ "diagram_type": "lifecycle",+ "meta": {+ "title": "Request processing exits",+ "locale": "en",+ "output": "request-lifecycle.html",+ "quality_profile": "showcase"+ },+ "mainPath": [+ "queued",+ "preparing",+ "parsing",+ "working",+ "complete"+ ],+ "states": [+ {+ "id": "queued",+ "type": "start",+ "label": "Queued",+ "sublabel": "Request saved"+ },+ {+ "id": "preparing",+ "type": "active",+ "label": "Preparing",+ "sublabel": "Worker assigned"+ },+ {+ "id": "parsing",+ "type": "active",+ "label": "Parsing",+ "sublabel": "Input decoded"+ },+ {+ "id": "working",+ "type": "active",+ "label": "Working",+ "sublabel": "Task active"+ },+ {+ "id": "complete",+ "type": "success",+ "label": "Complete",+ "sublabel": "Result checked"+ },+ {+ "id": "cancelled",+ "type": "failure",+ "label": "Cancelled"+ },+ {+ "id": "expired",+ "type": "failure",+ "label": "Expired"+ },+ {+ "id": "failed",+ "type": "failure",+ "label": "Failed"+ }+ ],+ "transitions": [+ {+ "id": "advance-0",+ "from": "queued",+ "to": "preparing",+ "label": "assign worker"+ },+ {+ "id": "advance-1",+ "from": "preparing",+ "to": "parsing",+ "label": "decode input"+ },+ {+ "id": "advance-2",+ "from": "parsing",+ "to": "working",+ "label": "start work"+ },+ {+ "id": "advance-3",+ "from": "working",+ "to": "complete",+ "label": "finish result"+ },+ {+ "id": "cancel-0",+ "from": "queued",+ "to": "cancelled",+ "label": "cancel",+ "variant": "dashed"+ },+ {+ "id": "cancel-1",+ "from": "preparing",+ "to": "cancelled",+ "label": "cancel",+ "variant": "dashed"+ },+ {+ "id": "cancel-2",+ "from": "working",+ "to": "cancelled",+ "label": "cancel",+ "variant": "dashed",+ "note": "worker confirms cancellation"+ },+ {+ "id": "deadline-0",+ "from": "queued",+ "to": "expired",+ "label": "deadline",+ "variant": "security",+ "note": "deadline reached before work"+ },+ {+ "id": "deadline-1",+ "from": "preparing",+ "to": "expired",+ "label": "deadline",+ "variant": "security"+ },+ {+ "id": "deadline-2",+ "from": "working",+ "to": "expired",+ "label": "deadline",+ "variant": "security",+ "note": "idle deadline resets on progress"+ },+ {+ "id": "fail-0",+ "from": "preparing",+ "to": "failed",+ "label": "failed",+ "variant": "security"+ },+ {+ "id": "fail-1",+ "from": "working",+ "to": "failed",+ "label": "failed",+ "variant": "security",+ "note": "decode or execution failed"+ },+ {+ "id": "fail-2",+ "from": "parsing",+ "to": "failed",+ "label": "failed",+ "variant": "security"+ }+ ]+}diff --git a/test/fixtures/lifecycle-shared-exit-fallback.json b/test/fixtures/lifecycle-shared-exit-fallback.jsonnew file mode 100644index 00000000..a18e7e4c--- /dev/null+++ b/test/fixtures/lifecycle-shared-exit-fallback.json@@ -0,0 +1,83 @@+{+ "schema_version": 3,+ "diagram_type": "lifecycle",+ "meta": {+ "title": "Two exit signatures",+ "locale": "en",+ "quality_profile": "showcase",+ "output": "multiple-subgroups.html"+ },+ "mainPath": [+ "phase-one",+ "phase-two",+ "phase-three"+ ],+ "states": [+ {+ "id": "phase-one",+ "type": "start",+ "label": "First"+ },+ {+ "id": "phase-two",+ "type": "active",+ "label": "Second"+ },+ {+ "id": "phase-three",+ "type": "success",+ "label": "Third"+ },+ {+ "id": "held",+ "type": "waiting",+ "label": "Held"+ }+ ],+ "transitions": [+ {+ "id": "advance-one",+ "from": "phase-one",+ "to": "phase-two",+ "label": "next"+ },+ {+ "id": "advance-two",+ "from": "phase-two",+ "to": "phase-three",+ "label": "next"+ },+ {+ "id": "team-first",+ "from": "phase-one",+ "to": "held",+ "label": "hold",+ "note": "Team check",+ "variant": "dashed"+ },+ {+ "id": "team-second",+ "from": "phase-three",+ "to": "held",+ "label": "hold",+ "note": "Team check",+ "variant": "dashed"+ },+ {+ "id": "owner-second",+ "from": "phase-one",+ "to": "held",+ "label": "hold",+ "note": "Owner check",+ "variant": "dashed"+ },+ {+ "id": "owner-third",+ "from": "phase-three",+ "to": "held",+ "label": "hold",+ "note": "Owner check",+ "variant": "dashed"+ }+ ]+}diff --git a/test/fixtures/lifecycle-shared-exit-subgroup.json b/test/fixtures/lifecycle-shared-exit-subgroup.jsonnew file mode 100644index 00000000..f87f0a27--- /dev/null+++ b/test/fixtures/lifecycle-shared-exit-subgroup.json@@ -0,0 +1,75 @@+{+ "schema_version": 3,+ "diagram_type": "lifecycle",+ "meta": {+ "title": "One shared exit subgroup",+ "locale": "en",+ "quality_profile": "showcase",+ "output": "single-subgroup.html"+ },+ "mainPath": [+ "phase-one",+ "phase-two",+ "phase-three"+ ],+ "states": [+ {+ "id": "phase-one",+ "type": "start",+ "label": "First"+ },+ {+ "id": "phase-two",+ "type": "active",+ "label": "Second"+ },+ {+ "id": "phase-three",+ "type": "success",+ "label": "Third"+ },+ {+ "id": "held",+ "type": "waiting",+ "label": "Held"+ }+ ],+ "transitions": [+ {+ "id": "advance-one",+ "from": "phase-one",+ "to": "phase-two",+ "label": "next"+ },+ {+ "id": "advance-two",+ "from": "phase-two",+ "to": "phase-three",+ "label": "next"+ },+ {+ "id": "hold-first",+ "from": "phase-one",+ "to": "held",+ "label": "hold",+ "note": "Team check",+ "variant": "dashed"+ },+ {+ "id": "hold-second",+ "from": "phase-two",+ "to": "held",+ "label": "hold",+ "note": "Team check",+ "variant": "dashed"+ },+ {+ "id": "hold-third",+ "from": "phase-three",+ "to": "held",+ "label": "hold",+ "note": "Owner check",+ "variant": "dashed"+ }+ ]+}diff --git a/test/i18n.test.mjs b/test/i18n.test.mjsindex 13c2cc5d..69686424 100644--- a/test/i18n.test.mjs+++ b/test/i18n.test.mjs@@ -464,9 +464,12 @@ test('validate and deliver receipts carry locale warnings as structured diagnostlocale: 'fr',translations: { ...FR_PARTIAL_TRANSLATIONS, 'viewer.common.closee': 'Fermer' },})));- const validated = cliJson(['validate', 'architecture', input, '--json']);- const delivered = cliJson(['deliver', 'architecture', input, path.join(tmp, 'receipt-fr.html'), '--json']);- for (const receipt of [validated, delivered]) {+ const cli = path.join(skillRoot, 'bin/archify.mjs');+ for (const command of ['validate', 'deliver']) {+ const args = [cli, command, 'architecture', input, ...(command === 'deliver' ? [path.join(tmp, 'receipt-fr.html')] : [])];+ const machine = spawnSync(process.execPath, [...args, '--json'], { cwd: tmp, encoding: 'utf8' });+ assert.equal(machine.status, 0, machine.stderr || machine.stdout);+ const receipt = JSON.parse(machine.stdout);assert.equal(receipt.ok, true);assert.deepEqual(receipt.diagnostics.map((entry) => [entry.code, entry.severity]), [['i18n/invalid-translation', 'warning'],@@ -477,6 +480,12 @@ test('validate and deliver receipts carry locale warnings as structured diagnostassert.equal(coverage.missingKeys.length, 10);for (const key of coverage.missingKeys) assert.equal(coverage.englishSource[key], translateMessage('en', key));assert.deepEqual(receipt.diagnostics[0].evidence.unknownKeys, ['viewer.common.closee']);+ const expectedWarnings = receipt.diagnostics.map(entry => `archify: ${entry.message}\n`).join('');+ assert.equal(machine.stderr, expectedWarnings, `${command}: JSON success discloses each warning once`);+ const human = spawnSync(process.execPath, args, { cwd: tmp, encoding: 'utf8' });+ assert.equal(human.status, 0, human.stderr || human.stdout);+ assert.equal(human.stderr, expectedWarnings, `${command}: human success discloses each warning once`);+ assert.ok(human.stdout.trim());}const clean = path.join(tmp, 'receipt-ko.json');diff --git a/test/layout-rules.test.mjs b/test/layout-rules.test.mjsindex d6c1a13a..3cefcc8c 100644--- a/test/layout-rules.test.mjs+++ b/test/layout-rules.test.mjs@@ -2056,7 +2056,7 @@ test('sequence: lifelines and activation bars remain intentional pass-through geassert.doesNotMatch(stderr, /Clean Flow Gate/);});-test('sequence: segment titles render as foreground badges above their borders', () => {+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);@@ -2066,10 +2066,26 @@ test('sequence: segment titles render as foreground badges above their borders',const activationsAt = html.indexOf('<!-- Activations -->');const messagesAt = html.indexOf('<!-- Messages -->');- assert.ok(segmentLabelsAt > activationsAt, 'segment labels should stay above lifelines, messages, and activations');+ 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');- assert.match(html, new RegExp(`data-graph-role="segment-label"[^>]*data-segment-id="0"`));- assert.match(html, new RegExp(`<text x="62" y="${firstSegment.from - 9}"[^>]*>${firstSegment.label}</text>`));+ 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', () => {diff --git a/test/lifecycle-layout.test.mjs b/test/lifecycle-layout.test.mjsindex 37b3c431..80139a35 100644--- a/test/lifecycle-layout.test.mjs+++ b/test/lifecycle-layout.test.mjs@@ -57,6 +57,16 @@ function box(svg, id) {return { x: Number(group[1]), y: Number(group[2]), width: Number(group[3]), height: Number(group[4]) };}+function edgePath(svg, id) {+ const tags = [...svg.matchAll(new RegExp(`<path [^>]*data-edge-id="${id}"[^>]*>`, 'g'))];+ assert.equal(tags.length, 1, `one visible route for ${id}`);+ return tags[0][0];+}+function edgeLabels(svg) {+ return [...svg.matchAll(/<g data-detail="(?:context|fine)" [^>]*data-edge-id="([^"]+)"[^>]*>[\s\S]*?<\/g>/g)]+ .map((match) => ({ id: match[1], markup: match[0] }));+}+test('bundled examples pass the showcase artifact check without crossings', () => {for (const name of ['agent-run.lifecycle.json', 'deployment-release.lifecycle.json']) {const doc = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples', name), 'utf8'));@@ -274,6 +284,53 @@ test('exits to one target with different labels or variants stay separate connecassert.match(result.svg, />after 24h<\/text>/);});+test('one eligible shared-exit subgroup preserves the independent note and every relationship', () => {+ const fixture = path.join(__dirname, 'fixtures/lifecycle-shared-exit-subgroup.json');+ const bytes = fs.readFileSync(fixture, 'utf8');+ const doc = JSON.parse(bytes);+ const result = render(doc);+ assert.equal(result.code, 0, result.stderr);+ assert.equal(result.check.ok, true, JSON.stringify(result.check.composition.issues));+ for (const transition of doc.transitions) {+ assert.match(edgePath(result.svg, transition.id), new RegExp(`data-edge-from="${transition.from}" data-edge-to="${transition.to}"`));+ }+ for (const item of doc.states) assert.match(result.svg, new RegExp(`data-node-id="${item.id}"`));+ const first = edgePath(result.svg, 'hold-first');+ const second = edgePath(result.svg, 'hold-second');+ const junction = first.match(/data-composition-junction="([^"]+)"/)?.[1];+ assert.ok(junction, 'equivalent exits declare their shared junction');+ assert.equal(second.match(/data-composition-junction="([^"]+)"/)?.[1], junction);+ assert.equal(first.match(/data-composition-points="([^"]+)"/)[1], second.match(/data-composition-points="([^"]+)"/)[1]);+ assert.doesNotMatch(edgePath(result.svg, 'hold-third'), /data-composition-junction/);+ const labels = edgeLabels(result.svg);+ const team = labels.filter(({ markup }) => markup.includes('>Team check</text>'));+ const owner = labels.filter(({ markup }) => markup.includes('>Owner check</text>'));+ assert.equal(team.length, 1, 'the shared note has one visible owner');+ assert.ok(['hold-first', 'hold-second'].includes(team[0].id));+ assert.deepEqual(owner.map(({ id }) => id), ['hold-third'], 'the distinct note belongs only to its original relationship');+ assert.equal((result.svg.match(/>hold<\/text>/g) || []).length, 2);+ assert.equal(fs.readFileSync(fixture, 'utf8'), bytes);+});++test('multiple eligible shared-exit signatures fall back to complete independent connectors', () => {+ const fixture = path.join(__dirname, 'fixtures/lifecycle-shared-exit-fallback.json');+ const doc = JSON.parse(fs.readFileSync(fixture, 'utf8'));+ const result = render(doc);+ assert.equal(result.code, 0, result.stderr);+ assert.equal(result.check.ok, true, JSON.stringify(result.check.composition.issues));+ assert.doesNotMatch(result.svg, /data-composition-junction/);+ const labels = edgeLabels(result.svg);+ for (const transition of doc.transitions) {+ assert.match(edgePath(result.svg, transition.id), new RegExp(`data-edge-from="${transition.from}" data-edge-to="${transition.to}"`));+ if (!transition.note) continue;+ const owned = labels.filter(({ id }) => id === transition.id);+ assert.equal(owned.length, 1, `one label owner for ${transition.id}`);+ assert.ok(owned[0].markup.includes(`>${transition.label}</text>`) && owned[0].markup.includes(`>${transition.note}</text>`));+ }+ assert.equal((result.svg.match(/>Team check<\/text>/g) || []).length, 2);+ assert.equal((result.svg.match(/>Owner check<\/text>/g) || []).length, 2);+});+test('the artifact checker flags identical overlapping lifecycle routes', () => {const result = render(neighbourCase([{ from: 'w', to: 'f', label: 'retry' },@@ -357,14 +414,83 @@ test('nodeLabelLayout reserves the source badge footprint on the right rail', ()assert.ok(both.ys[0] >= 19 + 2);});-test('a too-wide lifecycle names the crowded labels that widened every gap', async () => {- const { spawnSync } = await import('node:child_process');- const { fileURLToPath } = await import('node:url');+test('dense automatic exit notes pass public readability validation without losing authored content', () => {+ const fixture = path.join(__dirname, 'fixtures/lifecycle-dense-exit-notes.json');+ const bytes = fs.readFileSync(fixture, 'utf8');+ const doc = JSON.parse(bytes);+ const validated = spawnSync(process.execPath, [path.join(skillRoot, 'bin/archify.mjs'), 'validate', 'lifecycle', fixture,+ '--quality', 'showcase', '--json'], { encoding: 'utf8' });+ assert.equal(validated.status, 0, validated.stdout + validated.stderr);+ const receipt = JSON.parse(validated.stdout);+ assert.equal(receipt.ok, true);+ assert.ok(receipt.checks.length && receipt.checks.every((entry) => entry.ok));+ const result = render(doc);+ assert.equal(result.code, 0, result.stderr);+ assert.equal(result.check.ok, true, JSON.stringify(result.check.composition.issues));+ for (const item of doc.states) {+ assert.match(result.svg, new RegExp(`data-node-id="${item.id}"`));+ assert.ok(result.svg.includes(`>${item.label}</text>`));+ if (item.sublabel) assert.ok(result.svg.includes(`>${item.sublabel}</text>`));+ }+ const labels = edgeLabels(result.svg);+ for (const transition of doc.transitions) {+ assert.match(edgePath(result.svg, transition.id), new RegExp(`data-edge-from="${transition.from}" data-edge-to="${transition.to}"`));+ assert.ok(result.svg.includes(`>${transition.label}</text>`));+ if (!transition.note) continue;+ const owned = labels.filter(({ id }) => id === transition.id);+ assert.equal(owned.length, 1, `one note owner for ${transition.id}`);+ assert.ok(owned[0].markup.includes(`>${transition.note}</text>`));+ }+ assert.equal(fs.readFileSync(fixture, 'utf8'), bytes);+});++test('long transition notes are identified in width and placement diagnostics without discarding conditions', () => {+ const condition = 'Only proceed when the request is confirmed and the worker owns the active lease. ';+ const spine = { from: 'ready', to: 'done', label: 'go', note: condition.repeat(5) };+ const exit = { from: 'ready', to: 'stopped', label: 'stop', note: condition.repeat(15) };+ const doc = base({+ meta: { title: 'Transition note diagnostics', output: 'note-diagnostics.html', quality_profile: 'showcase' },+ mainPath: ['ready', 'done'],+ states: [state('ready', 'start', 'Ready'), state('done', 'success', 'Done'), state('stopped', 'failure', 'Stopped')],+ transitions: [spine, exit],+ });+ const input = path.join(tmp, 'long-note-diagnostics.json');+ const source = JSON.stringify(doc);+ fs.writeFileSync(input, source);+ const cli = path.join(skillRoot, 'bin/archify.mjs');+ const result = spawnSync(process.execPath, [cli, 'validate', 'lifecycle', input, '--json'], { encoding: 'utf8' });+ assert.notEqual(result.status, 0, 'the diagnostic change does not make this layout valid');+ const receipt = JSON.parse(result.stdout);+ const wide = receipt.diagnostics.find(entry => entry.code === 'lifecycle/too-wide');+ const unplaced = receipt.diagnostics.find(entry => entry.code === 'lifecycle/label-unplaced' && entry.subject.to === exit.to);+ assert.ok(wide && unplaced, result.stdout);+ assert.deepEqual(wide.subject, { diagramType: 'lifecycle', path: '/mainPath' });+ const step = wide.evidence.wideStepLabels.find(entry => entry.from === spine.from && entry.to === spine.to);+ assert.equal(step.label, spine.label, 'the existing label evidence remains compatible');+ assert.ok(step.excessPx > 0);+ assert.equal(step.widthDriver, 'note');+ assert.deepEqual(unplaced.subject, { diagramType: 'lifecycle', collection: 'transitions', index: 1, from: exit.from, to: exit.to });+ assert.equal(unplaced.evidence.widthDriver, 'note');+ for (const diagnostic of [wide, unplaced]) {+ const advice = diagnostic.supportedFixes.join('\n');+ assert.match(advice, /note/);+ assert.match(advice, /preserve.*condition|without removing conditions/);+ assert.match(advice, /detail.*same transition/);+ assert.match(advice, /may not.*(?:constraints|placement)/);+ }+ assert.equal(fs.readFileSync(input, 'utf8'), source, 'diagnosis preserves every authored condition');+});++test('an inherently too-wide lifecycle reports its budget and bounded spacing advice', () => {const cli = fileURLToPath(new URL('../archify/bin/archify.mjs', import.meta.url));const fixture = fileURLToPath(new URL('./fixtures/lifecycle-crowded-wide.json', import.meta.url));const result = spawnSync(process.execPath, [cli, 'validate', 'lifecycle', fixture, '--json'], { encoding: 'utf8' });+ assert.notEqual(result.status, 0);const diagnostic = JSON.parse(result.stdout).diagnostics.find((entry) => entry.code === 'lifecycle/too-wide');assert.ok(diagnostic, result.stdout);+ assert.ok(diagnostic.evidence.viewBoxWidth > diagnostic.evidence.budgetPx);assert.ok(diagnostic.evidence.spacingWideners.length > 0);- assert.match(diagnostic.supportedFixes[0], /found no clear spot at the base spacing, so every gap widened by 28px/);+ assert.match(diagnostic.supportedFixes[0], /main-path gap growth is bounded by the text readability budget/);+ assert.match(diagnostic.supportedFixes[0], /identical labels, notes and variants/);+ assert.doesNotMatch(diagnostic.supportedFixes[0], /every gap widened/);});diff --git a/test/lifecycle-note-contrast-browser.test.mjs b/test/lifecycle-note-contrast-browser.test.mjsnew file mode 100644index 00000000..cb099607--- /dev/null+++ b/test/lifecycle-note-contrast-browser.test.mjs@@ -0,0 +1,143 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { execFileSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { ChromeVisualBrowser, findChrome } from '../archify/bin/visual-check.mjs';++const cli = fileURLToPath(new URL('../archify/bin/archify.mjs', import.meta.url));+const fixture = fileURLToPath(new URL('./fixtures/lifecycle-dense-exit-notes.json', import.meta.url));++test('Lifecycle notes retain their content and reading depth with readable Full-detail ink', async (t) => {+ if (!Object.hasOwn(process.env, 'ARCHIFY_CHROME')) return t.skip('Set ARCHIFY_CHROME for real browser checks');+ const chrome = findChrome();+ assert.ok(chrome, 'The configured browser regression requires Chrome');+ const source = fs.readFileSync(fixture);+ const expected = JSON.parse(source).transitions.filter(edge => edge.note)+ .map(edge => ({ id: edge.id, label: edge.label, note: edge.note }));+ assert.ok(expected.length > 0, 'the public fixture carries transition notes');+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-lifecycle-note-contrast-'));+ t.after(() => fs.rmSync(scratch, { recursive: true, force: true }));+ const artifact = path.join(scratch, 'lifecycle.html');+ const input = path.join(scratch, 'lifecycle.json');+ const document = JSON.parse(source);+ document.transitions.find(edge => edge.id === 'advance-0').variant = 'default';+ fs.writeFileSync(input, JSON.stringify(document));+ execFileSync(process.execPath, [cli, 'render', 'lifecycle', input, artifact]);+ assert.deepEqual(fs.readFileSync(fixture), source, 'rendering preserves the authored notes');+ const browser = new ChromeVisualBrowser(chrome);+ t.after(() => browser.close());+ const session = await browser.sessionPromise;+ async function run(expression) {+ const result = await browser.cdp.send('Runtime.evaluate', {+ expression, awaitPromise: true, returnByValue: true,+ }, session);+ assert.equal(result.exceptionDetails, undefined, result.exceptionDetails?.exception?.description);+ return result.result?.value;+ }+ // Sample the same primary label in both depths without another browser session.+ const primaryLabel = `(() => {+ const label = document.querySelector('g[data-edge-id="advance-0"] text:not([data-detail="fine"])');+ const ink = getComputedStyle(label);+ const muted = getComputedStyle(document.querySelector('g[data-edge-id] text[data-detail="fine"]'));+ const ancestors = [];+ for (let node = label; node; node = node.parentElement) {+ const style = getComputedStyle(node);+ ancestors.push({ opacity: Number(style.opacity), display: style.display, visibility: style.visibility });+ }+ return { text: label.textContent, role: label.getAttribute('class'), fill: ink.fill,+ mutedFill: muted.fill, fillOpacity: Number(ink.fillOpacity), ancestors };+ })()`;+ function assertPrimaryLabel(label) {+ assert.equal(label.text, 'assign worker');+ assert.equal(label.role, 't-muted', 'default primary label uses readable neutral text');+ assert.equal(label.fill, label.mutedFill, 'default label resolves to the existing readable muted ink');+ assert.equal(label.fillOpacity, 1);+ for (const ancestor of label.ancestors) {+ assert.equal(ancestor.opacity, 1, 'primary label and every ancestor remain opaque');+ assert.notEqual(ancestor.visibility, 'hidden');+ assert.notEqual(ancestor.display, 'none');+ }+ }+ for (const theme of ['light', 'dark']) {+ await t.test(`${theme} Read hides notes and Full meets opaque-plate contrast`, async () => {+ await browser.inspect({ artifactPath: artifact, width: 1440, height: 1100, theme });+ const read = await run(`(async () => {+ Archify.view.reset();+ await Archify.readerLayout.whenStable();+ await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));+ const panel = document.querySelector('.diagram-container');+ return { primary: ${primaryLabel}, detail: panel.dataset.detailLevel, notes: [...panel.querySelectorAll('g[data-edge-id] text[data-detail="fine"]')].map(note => ({+ id: note.parentElement.dataset.edgeId, note: note.textContent,+ noteOpacity: getComputedStyle(note).opacity,+ label: note.parentElement.querySelector('text:not([data-detail="fine"])').textContent,+ labelOpacity: getComputedStyle(note.parentElement.querySelector('text:not([data-detail="fine"])')).opacity,+ groupOpacity: getComputedStyle(note.parentElement).opacity,+ })) };+ })()`);+ assert.equal(read.detail, 'read');+ assertPrimaryLabel(read.primary);+ assert.deepEqual(read.notes.map(({ id, label, note }) => ({ id, label, note })), expected);+ for (const note of read.notes) {+ assert.equal(note.noteOpacity, '0', 'Read hides auxiliary notes');+ assert.equal(note.labelOpacity, '1', 'Read keeps the primary label');+ assert.equal(note.groupOpacity, '1', 'the label group remains visible');+ }+ const full = await run(`(async () => {+ Archify.view.reveal([...document.querySelectorAll('[data-node-id]')].map(node => node.dataset.nodeId), { instant: true, maxScale: 1 });+ const panel = document.querySelector('.diagram-container');+ await Promise.all(panel.getAnimations({ subtree: true }).map(animation => animation.finished.catch(() => {})));+ const rgba = value => {+ const channels = value.match(/[\\d.]+/g).map(Number);+ return [...channels.slice(0, 3), channels[3] ?? 1];+ };+ const luminance = rgb => rgb.slice(0, 3).map(c => {+ c /= 255;+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;+ }).reduce((sum, c, i) => sum + c * [0.2126, 0.7152, 0.0722][i], 0);+ return { primary: ${primaryLabel}, theme: document.documentElement.dataset.theme, preset: document.documentElement.dataset.preset,+ detail: panel.dataset.detailLevel, notes: [...panel.querySelectorAll('g[data-edge-id] text[data-detail="fine"]')].map(note => {+ const group = note.parentElement, mask = group.querySelector(':scope > rect.c-mask');+ const ink = getComputedStyle(note), plate = getComputedStyle(mask);+ const foreground = rgba(ink.fill), background = rgba(plate.fill);+ const ancestors = [];+ for (let node = note; node; node = node.parentElement) {+ const style = getComputedStyle(node);+ ancestors.push({ opacity: Number(style.opacity), display: style.display, visibility: style.visibility });+ }+ const inkAlpha = foreground[3] * Number(ink.fillOpacity);+ const rendered = foreground.slice(0, 3).map((c, i) => c * inkAlpha + background[i] * (1 - inkAlpha));+ const a = luminance(rendered), b = luminance(background);+ return { id: group.dataset.edgeId, note: note.textContent,+ label: group.querySelector('text:not([data-detail="fine"])').textContent,+ ancestors, maskOpacity: Number(plate.opacity), maskVisibility: plate.visibility, maskDisplay: plate.display,+ maskAlpha: background[3] * Number(plate.fillOpacity), inkAlpha,+ foreground: rendered, background: background.slice(0, 3),+ ratio: (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05) };+ }) };+ })()`);+ assert.equal(full.theme, theme);+ assert.equal(full.preset, 'classic');+ assert.equal(full.detail, 'full');+ assertPrimaryLabel(full.primary);+ assert.deepEqual(full.notes.map(({ id, label, note }) => ({ id, label, note })), expected);+ for (const note of full.notes) {+ for (const ancestor of note.ancestors) {+ assert.equal(ancestor.opacity, 1, 'Full ink and every ancestor are opaque');+ assert.notEqual(ancestor.visibility, 'hidden');+ assert.notEqual(ancestor.display, 'none');+ }+ assert.equal(note.maskOpacity, 1);+ assert.equal(note.maskAlpha, 1, 'the same-group plate supplies an opaque background');+ assert.notEqual(note.maskVisibility, 'hidden');+ assert.notEqual(note.maskDisplay, 'none');+ assert.equal(note.inkAlpha, 1);+ t.diagnostic(`${theme} ${note.id} opaque-plate contrast ${note.ratio.toFixed(3)}:1; ink ${note.foreground}; plate ${note.background}`);+ assert.ok(Number.isFinite(note.ratio) && note.ratio >= 4.5,+ `${theme} ${note.id} note contrast ${note.ratio.toFixed(3)}:1 must be at least 4.5:1`);+ }+ });+ }+});diff --git a/test/render-failure-diagnostics.test.mjs b/test/render-failure-diagnostics.test.mjsindex 0110440a..b54ebe2f 100644--- a/test/render-failure-diagnostics.test.mjs+++ b/test/render-failure-diagnostics.test.mjs@@ -125,6 +125,102 @@ test('render layout rejection exposes the existing diagnostic and preserves an eassert.deepEqual(failure.diagnostics[0].subject, { diagramType: 'architecture' });}assert.equal(fs.readFileSync(output, 'utf8'), 'trusted artifact');++ // A locale warning must not replace the classified layout error or make+ // the renderer's single JSON failure receipt unparsable.+ const withWarning = JSON.parse(fs.readFileSync(input, 'utf8'));+ withWarning.meta.locale = 'en-US';+ fs.writeFileSync(input, JSON.stringify(withWarning));+ for (const command of ['validate', 'deliver']) {+ const machine = run([cli, command, 'architecture', input, ...(command === 'deliver' ? [output] : []), '--json'], cwd);+ assert.equal(machine.status, 1);+ assert.equal(machine.stderr, '');+ const failure = JSON.parse(machine.stdout);+ assert.equal(failure.ok, false);+ const warning = failure.diagnostics.find(entry => entry.code === 'i18n/locale-fallback');+ const layout = failure.diagnostics.find(entry => entry.code === 'layout/constraint');+ assert.equal(warning?.severity, 'warning');+ assert.equal(layout?.severity, 'error');+ assert.deepEqual(layout.subject, { diagramType: 'architecture' });+ assert.match(layout.message, /shorten the label or widen size/);+ assert.ok(Array.isArray(layout.supportedFixes));+ assert.equal(fs.readFileSync(output, 'utf8'), 'trusted artifact');+ }+ const direct = run([path.join(skillRoot, 'renderers/architecture/render-architecture.mjs'), input, output], cwd, true);+ assert.equal(direct.status, 1);+ assert.equal(direct.stdout, '');+ const receipt = JSON.parse(direct.stderr);+ assert.ok(receipt.diagnostics.some(entry => entry.code === 'i18n/locale-fallback'));+ assert.ok(receipt.diagnostics.some(entry => entry.code === 'layout/constraint'));+ assert.equal(fs.readFileSync(output, 'utf8'), 'trusted artifact');+});++test('locale warnings cannot classify an unrelated native renderer error', t => {+ const cwd = workspace(t);+ const input = path.join(cwd, 'warning.json');+ const output = path.join(cwd, 'diagram.html');+ const document = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples/web-app.architecture.json'), 'utf8'));+ document.meta.locale = 'en-US';+ fs.writeFileSync(input, JSON.stringify(document));+ const helper = new URL('../archify/renderers/shared/cli.mjs', import.meta.url).href;+ const script = `import { loadDiagram } from ${JSON.stringify(helper)};+ loadDiagram({ rendererDir: ${JSON.stringify(path.join(skillRoot, 'renderers/architecture'))}, diagramType: 'architecture', argv: ['node', 'renderer', ${JSON.stringify(input)}, ${JSON.stringify(output)}] });+ throw new TypeError('unrelated implementation defect');`;+ const human = run(['--input-type=module', '-e', script], cwd);+ assert.equal(human.status, 1);+ assert.match(human.stderr, /archify: meta\.locale "en-US"/);+ assert.match(human.stderr, /TypeError: unrelated implementation defect/);+ const machine = run(['--input-type=module', '-e', script], cwd, true);+ assert.equal(machine.status, 1);+ const receipt = JSON.parse(machine.stderr);+ assert.deepEqual(receipt.diagnostics.map(entry => entry.code), ['internal/unclassified']);+ assert.equal(fs.existsSync(output), false);+});++test('direct renderer warning modes preserve the successful artifact contract', t => {+ const cwd = workspace(t);+ const input = path.join(cwd, 'warning.json');+ const output = path.join(cwd, 'diagram.html');+ const document = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples/web-app.architecture.json'), 'utf8'));+ document.meta.locale = 'en-US';+ fs.writeFileSync(input, JSON.stringify(document));+ const renderer = path.join(skillRoot, 'renderers/architecture/render-architecture.mjs');+ const human = run([renderer, input, output], cwd);+ assert.equal(human.status, 0, human.stderr);+ assert.equal(human.stdout, `${output}\n`);+ assert.equal(human.stderr.trim().split('\n').length, 1);+ assert.match(human.stderr, /^archify: meta\.locale "en-US"/);+ const artifact = fs.readFileSync(output);+ const machine = run([renderer, input, output], cwd, true);+ assert.equal(machine.status, 0, machine.stderr);+ assert.equal(machine.stdout, `${output}\n`);+ assert.equal(machine.stderr, '');+ assert.deepEqual(fs.readFileSync(output), artifact);+});++test('public post-render checker failures retain the locale warning once', t => {+ const cwd = workspace(t);+ const input = path.join(cwd, 'warning.json');+ const output = path.join(cwd, 'diagram.html');+ const document = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples/web-app.architecture.json'), 'utf8'));+ document.meta.locale = 'en-US';+ fs.writeFileSync(input, JSON.stringify(document));+ fs.writeFileSync(output, 'trusted artifact');+ for (const command of ['validate', 'deliver']) {+ const result = spawnSync(process.execPath, [cli, command, 'architecture', input, ...(command === 'deliver' ? [output] : []), '--json'], {+ cwd,+ encoding: 'utf8',+ env: { ...process.env, ARCHIFY_CHECK_MAX_BUFFER: '1' },+ });+ assert.notEqual(result.status, 0);+ const receipt = JSON.parse(result.stdout);+ assert.equal(receipt.ok, false);+ assert.equal(receipt.stage, 'check');+ assert.ok(receipt.diagnostics.some(entry => entry.code === 'artifact/check-output-limit'));+ assert.equal(result.stderr.trim().split('\n').length, 1);+ assert.match(result.stderr, /^archify: meta\.locale "en-US"/);+ assert.equal(fs.readFileSync(output, 'utf8'), 'trusted artifact');+ }});test('unexpected renderer exceptions keep native debugging information and are not relabelled as input errors', t => {@@ -161,6 +257,115 @@ test('a recorded layout diagnostic cannot hide a later unclassified exception',assert.deepEqual(JSON.parse(classified.stderr).diagnostics.map(d => d.message), ['earlier layout problem', 'final layout problem']);});+test('isolated diagnostic work preserves typed lookup without polluting later failures', t => {+ const script = `import assert from 'node:assert/strict';+ import { recordDiagnostic, throwDiagnosticProblems, rendererFailure, withIsolatedDiagnosticRecording } from ${JSON.stringify(diagnosticModule)};+ const local = { code: 'composition/proper-crossing', severity: 'error', message: 'same problem',+ subject: { id: 'local' }, evidence: { point: [12, 34] }, supportedFixes: ['move local route'] };+ const outer = { ...local, subject: { id: 'outer' }, evidence: { point: [56, 78] }, supportedFixes: ['move outer route'] };+ function recover() {+ try { throwDiagnosticProblems('rejected', [local.message]); }+ catch (error) { return error; }+ }+ let captured;+ const result = withIsolatedDiagnosticRecording(() => {+ recordDiagnostic(local);+ captured = recover();+ return captured;+ });+ assert.equal(result, captured);+ assert.deepEqual(result.archifyDiagnostics, [local]);+ recordDiagnostic(outer);+ const terminal = recover();+ assert.deepEqual(terminal.archifyDiagnostics, [outer]);+ // Exact local repeats must record after leaving the speculative scope.+ recordDiagnostic(local);+ assert.deepEqual(rendererFailure(terminal).diagnostics, [outer, local]);`;+ const result = run(['--input-type=module', '-e', script], workspace(t), true);+ assert.equal(result.status, 0, result.stderr);+});++test('nested isolated diagnostics restore each caller and retain earlier plus terminal failures', t => {+ const script = `import assert from 'node:assert/strict';+ import { recordDiagnostic, throwDiagnosticError, throwDiagnosticProblems, rendererFailure, withIsolatedDiagnosticRecording } from ${JSON.stringify(diagnosticModule)};+ const detail = id => ({ code: 'layout/constraint', severity: 'error', message: 'same problem',+ subject: { id }, evidence: { node: id }, supportedFixes: ['move ' + id] });+ const outer = detail('outer'), local = detail('local'), nested = detail('nested');+ function recover(expected) {+ try { throwDiagnosticProblems('rejected', [expected.message]); assert.fail('problem must throw'); }+ catch (error) { assert.deepEqual(error.archifyDiagnostics, [expected]); }+ }+ recordDiagnostic(outer);+ withIsolatedDiagnosticRecording(() => {+ recordDiagnostic(local);+ withIsolatedDiagnosticRecording(() => { recordDiagnostic(nested); recover(nested); });+ recover(local);+ });+ recover(outer);+ const terminal = { ...detail('terminal'), message: 'terminal problem' };+ try { throwDiagnosticError('rejected', [terminal]); assert.fail('terminal must throw'); }+ catch (error) { assert.deepEqual(rendererFailure(error).diagnostics, [outer, terminal]); }`;+ const result = run(['--input-type=module', '-e', script], workspace(t), true);+ assert.equal(result.status, 0, result.stderr);+});++test('isolated diagnostic exceptions restore recording and preserve error identity', t => {+ const script = `import assert from 'node:assert/strict';+ import { recordDiagnostic, throwDiagnosticError, rendererFailure, withIsolatedDiagnosticRecording } from ${JSON.stringify(diagnosticModule)};+ const detail = id => ({ code: 'layout/constraint', severity: 'error', message: id + ' problem',+ subject: { id }, evidence: { node: id }, supportedFixes: ['move ' + id] });+ const earlier = detail('earlier'), abandoned = detail('abandoned'), terminal = detail('terminal');+ recordDiagnostic(earlier);+ const untyped = new TypeError('implementation defect');+ try {+ withIsolatedDiagnosticRecording(() => { recordDiagnostic(abandoned); throw untyped; });+ assert.fail('exception must escape');+ } catch (error) {+ assert.equal(error, untyped);+ assert.equal(rendererFailure(error).diagnostics[0].code, 'internal/unclassified');+ }+ try { throwDiagnosticError('rejected', [terminal]); assert.fail('terminal must throw'); }+ catch (error) { assert.deepEqual(rendererFailure(error).diagnostics, [earlier, terminal]); }+ const typed = Object.assign(new Error('typed escape'), { archifyDiagnostics: [detail('escape')] });+ try {+ withIsolatedDiagnosticRecording(() => { recordDiagnostic(abandoned); throw typed; });+ assert.fail('typed exception must escape');+ } catch (error) {+ assert.equal(error, typed);+ // The caller publishes only the escaped error after recording is restored.+ for (const diagnostic of error.archifyDiagnostics) recordDiagnostic(diagnostic);+ assert.deepEqual(rendererFailure(error).diagnostics, [earlier, terminal, detail('escape')]);+ }`;+ const result = run(['--input-type=module', '-e', script], workspace(t), true);+ assert.equal(result.status, 0, result.stderr);+});++test('isolated diagnostic scopes compose with recording suppression in either order', t => {+ for (const composition of ['scope inside suppression', 'suppression inside scope']) {+ const script = `import assert from 'node:assert/strict';+ import { recordDiagnostic, throwDiagnosticError, rendererFailure, withIsolatedDiagnosticRecording, withDiagnosticRecordingSuppressed } from ${JSON.stringify(diagnosticModule)};+ const detail = id => ({ code: 'layout/constraint', severity: 'error', message: id + ' problem',+ subject: { id }, evidence: {}, supportedFixes: [] });+ const earlier = detail('earlier'), terminal = detail('terminal');+ recordDiagnostic(earlier);+ const localWork = () => {+ recordDiagnostic(detail('local'));+ withDiagnosticRecordingSuppressed(() => recordDiagnostic(detail('suppressed')));+ recordDiagnostic(detail('later local'));+ };+ ${composition === 'scope inside suppression'+ ? `withDiagnosticRecordingSuppressed(() => {+ withIsolatedDiagnosticRecording(localWork);+ recordDiagnostic(detail('still suppressed'));+ });`+ : 'withIsolatedDiagnosticRecording(localWork);'}+ try { throwDiagnosticError('rejected', [terminal]); assert.fail('terminal must throw'); }+ catch (error) { assert.deepEqual(rendererFailure(error).diagnostics, [earlier, terminal]); }`;+ const result = run(['--input-type=module', '-e', script], workspace(t), true);+ assert.equal(result.status, 0, `${composition}: ${result.stderr}`);+ }+});+test('repeated problem messages keep their own subject and evidence', t => {const cwd = workspace(t);const message = 'Connection "ghost" references unknown target "ghost".';diff --git a/test/sequence-column-fit.test.mjs b/test/sequence-column-fit.test.mjsindex a0ebdfce..20a615c3 100644--- a/test/sequence-column-fit.test.mjs+++ b/test/sequence-column-fit.test.mjs@@ -6,6 +6,7 @@ import os from 'node:os';import path from 'node:path';import { fileURLToPath } from 'node:url';import { textUnits } from '../archify/renderers/shared/utils.mjs';+import { minimumNodeTextWidth } from '../archify/renderers/shared/text-fit.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));const skillRoot = path.resolve(__dirname, '..', 'archify');@@ -351,11 +352,117 @@ test('automatic spread canvas widens for participant labels up to the readable wfor (const box of participantBoxes(html)) assert.ok(box.width + 6 >= textUnits('Team operations') * 6.8, JSON.stringify(box));doc.participants[6].label = 'Stdin dispatcher queue';+ const requiredBox = Math.ceil(textUnits(doc.participants[6].label) * 6.8 - 6);+ assert.ok(8 * requiredBox + 7 * 16 + 80 > 1085,+ 'even the entire bounded row cannot hold these uniform boxes with real gutters and margins');const crowded = renderOutcome(doc);assert.notEqual(crowded.code, 0);assert.match(crowded.stderr, /shorten it to at most \d+ text units[^]*keep meta\.viewBox omitted/);});+function sevenParticipantCapacity() {+ return {+ schema_version: 1, diagram_type: 'sequence',+ meta: { title: 'Seven participant capacity', quality_profile: 'showcase' },+ participants: Array.from({ length: 7 }, (_, index) => ({+ id: `p${index}`, type: 'backend',+ label: index === 0 ? 'ParticipantEndpoint' : index === 6 ? '中文参与者终端接口' : `P${index}`,+ sublabel: index === 6 ? 'ABCDEFGHIJKLMNOPQRSTUVWXYZab' : `context ${index}`,+ ...(index === 2 ? { brand: 'redis' } : {}),+ })),+ messages: [{ id: 'send', from: 'p0', to: 'p6', y: 200, label: 'send' }],+ };+}++test('automatic spread uses feasible header capacity without losing endpoint text or sublabel readability', () => {+ const doc = sevenParticipantCapacity();+ const original = JSON.stringify(doc);+ const html = render(doc, true);+ const boxes = participantBoxes(html);+ const width = Number(html.match(/<svg viewBox="0 0 (\d+) /)[1]);+ assert.equal(boxes.length, doc.participants.length);+ assert.ok(width <= 1085);+ assert.ok(boxes[0].x >= 40 && boxes.at(-1).x + boxes.at(-1).width <= width - 40);+ for (let index = 0; index < boxes.length; index++) {+ const box = boxes[index];+ const participant = doc.participants[index];+ assert.ok(box.width >= 86 && box.width <= 190);+ assert.ok(textUnits(participant.label) * 6.8 <= box.width + 6);+ if (index) assert.ok(box.x - boxes[index - 1].x - boxes[index - 1].width >= 16);+ assert.ok(html.includes(`>${participant.label}</text>`));+ const sublabel = html.match(new RegExp(`font-size="([\\d.]+)"[^>]*>${participant.sublabel}</text>`));+ assert.ok(sublabel, participant.sublabel);+ const font = Number(sublabel[1]);+ assert.ok(font * Math.min(1, 930 / width) >= 6);+ assert.ok(minimumNodeTextWidth(participant.sublabel, font) <= box.width - 8);+ }+ assert.match(html, /data-brand-mark="redis"/);+ assert.deepEqual([...html.matchAll(/<g id="node-([^"]+)"/g)].map(match => match[1]), doc.participants.map(p => p.id));+ assert.equal(JSON.stringify(doc), original, 'rendering preserves all authored content');+ assert.equal(html, render({ ...doc, meta: { ...doc.meta, column_fit: 'spread' } }, true));+});++test('feasible automatic header fallback preserves authored viewBox and fixed rejection', () => {+ const doc = sevenParticipantCapacity();+ const authored = renderOutcome({ ...doc, meta: { ...doc.meta, viewBox: [1085, 620] } }, true);+ assert.notEqual(authored.code, 0);+ assert.match(authored.stderr, /wider than component "p0" \(113px\)/);+ const fixed = renderOutcome({ ...doc, meta: { ...doc.meta, column_fit: 'fixed' } }, true);+ assert.notEqual(fixed.code, 0);+ assert.match(fixed.stderr, /participant boxes are 86px/);+});++test('automatic header fallback retains failure when actual sublabel or brand rail cannot fit', () => {+ const sublabel = sevenParticipantCapacity();+ sublabel.participants[6].sublabel += 'c';+ const outcome = renderOutcome(sublabel, true);+ assert.notEqual(outcome.code, 0);+ assert.match(outcome.stderr, /7px minimum that stays readable on this 1085px canvas/);+ assert.match(outcome.stderr, /participant boxes are 113px/);+ const standard = structuredClone(sublabel);+ standard.meta.quality_profile = 'standard';+ assert.equal(renderOutcome(standard, true).code, 0, 'standard retains its historical 6px minimum');++ const branded = sevenParticipantCapacity();+ branded.participants[0].brand = 'redis';+ const brandOutcome = renderOutcome(branded, true);+ assert.notEqual(brandOutcome.code, 0);+ assert.match(brandOutcome.stderr, /Participant "p0" brand top rail/);+ assert.match(brandOutcome.stderr, /participant boxes are 113px/);+});++test('automatic header fallback wraps boundary notes before height while preserving timeline y and real collisions', () => {+ const doc = sevenParticipantCapacity();+ const token = `${'x'.repeat(25)}文`;+ doc.messages[0].y = 700;+ doc.messages[0].note = token;+ doc.segments = [{ from: 160, to: 720, label: 'Phase' }];+ doc.activations = [{ participant: 'p2', from: 680, to: 710 }];+ const original = JSON.stringify(doc);+ const html = render(doc, true);+ const boxes = participantBoxes(html);+ const lanes = boxes.map(box => box.x + box.width / 2);+ const note = html.match(/<text data-detail="fine" x="([\d.]+)" y="([\d.]+)"[^>]*>(.*?)<\/text>/);+ assert.ok(note);+ const lines = [...note[3].matchAll(/<tspan[^>]*>([^<]*)<\/tspan>/g)].map(match => match[1]);+ assert.ok(lines.length > 1, 'the note crosses the final gap wrapping boundary');+ assert.equal(lines.join(''), token);+ assert.equal(Number(note[1]), lanes[0] + 19);+ assert.equal(Number(note[2]), doc.messages[0].y + 18);+ for (const line of lines) assert.ok(Number(note[1]) + minimumNodeTextWidth(line, 7) <= lanes[1] - 11);+ const height = Number(html.match(/<svg viewBox="0 0 \d+ (\d+)"/)[1]);+ assert.ok(height - 65 >= Number(note[2]) + (lines.length - 1) * 11 + 4);+ assert.match(html, /data-composition-points="[^\"]*,700;/);+ assert.match(html, /y="680" width="10" height="30"/);+ assert.match(html, /y="160"[^>]*height="560"/);+ assert.equal(JSON.stringify(doc), original);++ doc.messages.push({ id: 'reply', from: 'p1', to: 'p0', y: 730, label: 'reply' });+ const collision = renderOutcome(doc, true);+ assert.notEqual(collision.code, 0);+ assert.match(collision.stderr, /Note on message "send"[^]*reaches message "reply" at y=730/);+});+test('a widened automatic canvas reports sublabels at the size that stays readable there', () => {const participant = (id, label, sublabel) => ({ id, type: 'backend', label, ...(sublabel ? { sublabel } : {}) });const doc = {diff --git a/test/sequence-note-export-browser.test.mjs b/test/sequence-note-export-browser.test.mjsindex 7948153d..5e9525b6 100644--- a/test/sequence-note-export-browser.test.mjs+++ b/test/sequence-note-export-browser.test.mjs@@ -98,4 +98,59 @@ test('SVG and PNG exports keep every line of a wrapped sequence note', {const png = await run(`noteExport('png').then(blob=>new Promise((resolve,reject)=>{const reader=new FileReader();reader.onload=()=>resolve(String(reader.result).split(',')[1]);reader.onerror=reject;reader.readAsDataURL(blob);}))`);fs.writeFileSync(process.env.ARCHIFY_NOTE_EXPORT_EVIDENCE, Buffer.from(png, 'base64'));}++ // This fixture has no segment overlays: the note sits on the panel over+ // the body background. Measure computed colors in Full detail, not a class+ // name, and retain the default Read/export checks above.+ await run(`for(let i=0;i<3;i++) Archify.view.zoomIn();+ new Promise((resolve,reject)=>{+ const deadline=performance.now()+2000;+ function settled(){+ if(getComputedStyle(document.querySelector('text[data-detail="fine"]')).opacity==='1') return resolve();+ if(performance.now()>deadline) return reject(new Error('Full-detail note did not become visible'));+ requestAnimationFrame(settled);+ }+ settled();+ })`);+ for (const theme of ['dark', 'light']) {+ await t.test(`${theme} Full-detail note has at least 4.5:1 contrast`, async () => {+ await run(`document.documentElement.setAttribute('data-theme', ${JSON.stringify(theme)});+ new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)))`);+ const colors = await run(`(() => {+ const note = document.querySelector('text[data-detail="fine"]');+ const panel = document.querySelector('.diagram-container');+ const style = getComputedStyle(note);+ const rgba = value => {+ const parts = value.match(/[\\d.]+/g).map(Number);+ return [...parts.slice(0, 3), parts[3] ?? 1];+ };+ const over = (front, back) => front.slice(0, 3).map((c, i) => c * front[3] + back[i] * (1 - front[3]));+ const body = rgba(getComputedStyle(document.body).backgroundColor);+ const background = over(rgba(getComputedStyle(panel).backgroundColor), body);+ const fill = rgba(style.fill);+ fill[3] *= Number(style.fillOpacity);+ const foreground = over(fill, background);+ const luminance = rgb => rgb.map(c => {+ c /= 255;+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;+ }).reduce((sum, c, i) => sum + c * [0.2126, 0.7152, 0.0722][i], 0);+ const a = luminance(foreground), b = luminance(background);+ return { ratio: (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05),+ foreground, background, bodyAlpha: body[3], opacity: style.opacity,+ visibility: style.visibility, display: style.display,+ detail: panel.getAttribute('data-detail-level'),+ svgBackgroundAlpha: rgba(getComputedStyle(note.ownerSVGElement).backgroundColor)[3],+ segments: document.querySelectorAll('[data-composition-frame-kind="segment"]').length };+ })()`);+ assert.equal(colors.detail, 'full');+ assert.equal(colors.opacity, '1', 'contrast is measured on a visible note');+ assert.notEqual(colors.visibility, 'hidden');+ assert.notEqual(colors.display, 'none');+ assert.equal(colors.bodyAlpha, 1, 'body provides the opaque background');+ assert.equal(colors.svgBackgroundAlpha, 0, 'SVG leaves the panel background visible');+ assert.equal(colors.segments, 0, 'no segment overlay changes the note background');+ t.diagnostic(`${theme} note contrast ${colors.ratio.toFixed(3)}:1; foreground ${colors.foreground}; background ${colors.background}`);+ assert.ok(colors.ratio >= 4.5, `${theme} note contrast ${colors.ratio.toFixed(3)}:1 must be at least 4.5:1`);+ });+ }});diff --git a/test/sequence-note-wrap.test.mjs b/test/sequence-note-wrap.test.mjsindex 6b8ee5fc..f4c98608 100644--- a/test/sequence-note-wrap.test.mjs+++ b/test/sequence-note-wrap.test.mjs@@ -50,7 +50,7 @@ function lifelines(html) {}function notes(html) {- return [...html.matchAll(/<text data-detail="fine" x="([\d.]+)" y="([\d.]+)" class="t-dim" font-size="7">([\s\S]*?)<\/text>/g)]+ return [...html.matchAll(/<text data-detail="fine" x="([\d.]+)" y="([\d.]+)" class="[^"]*" font-size="7">([\s\S]*?)<\/text>/g)].map((match) => {const tspans = [...match[3].matchAll(/<tspan x="([\d.]+)" dy="([\d.]+)">([^<]*)<\/tspan>/g)];return {@@ -116,7 +116,10 @@ test('text without any punctuation breaks at a character boundary', (t) => {test('a short note keeps its original single-line markup', (t) => {const html = render(t, sequence({ messages: [{ from: 'api', to: 'client', y: 200, label: 'reply', note: 'cached for 5 minutes' }] }));const [client] = lifelines(html);- assert.match(html, new RegExp(`<text data-detail="fine" x="${client + 19}" y="218" class="t-dim" font-size="7">cached for 5 minutes</text>`));+ const [note] = notes(html);+ assert.equal(note.x, client + 19);+ assert.equal(note.y, 218);+ assert.equal(note.raw, 'cached for 5 minutes');assert.doesNotMatch(html, /<tspan/);});@@ -135,7 +138,10 @@ test('a note on a message that skips participants stays in the left-most gap, intest('a short note on a reverse message that skips a participant keeps its original position', (t) => {const html = render(t, sequence({ messages: [{ from: 'db', to: 'client', y: 200, label: 'result', note: 'from replica' }] }));const [client] = lifelines(html);- assert.match(html, new RegExp(`<text data-detail="fine" x="${client + 19}" y="218" class="t-dim" font-size="7">from replica</text>`));+ const [note] = notes(html);+ assert.equal(note.x, client + 19);+ assert.equal(note.y, 218);+ assert.equal(note.raw, 'from replica');});test('equal spread gaps that differ only by floating-point rounding keep the left-most gap', (t) => {diff --git a/test/sequence-segment-contrast-browser.test.mjs b/test/sequence-segment-contrast-browser.test.mjsnew file mode 100644index 00000000..161cf9c8--- /dev/null+++ b/test/sequence-segment-contrast-browser.test.mjs@@ -0,0 +1,100 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { execFileSync } from 'node:child_process';+import { fileURLToPath, pathToFileURL } from 'node:url';+import { ChromeVisualBrowser, findChrome } from '../archify/bin/visual-check.mjs';++const skillRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'archify');+const chrome = process.env.ARCHIFY_CHROME ? findChrome() : null;+const TITLE = 'Preparation phase';++// Phase headings identify authored timeline sections in Read and Full detail.+// A real browser resolves the preset/theme ink and the opaque title plate.+test('sequence phase headings retain readable contrast in Read and Full detail', {+ skip: chrome ? false : 'Set ARCHIFY_CHROME to run real-browser contrast checks.',+}, async (t) => {+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-segment-contrast-'));+ t.after(() => fs.rmSync(scratch, { recursive: true, force: true }));+ const input = path.join(scratch, 'segment.json');+ const file = path.join(scratch, 'segment.html');+ fs.writeFileSync(input, JSON.stringify({+ schema_version: 1, diagram_type: 'sequence',+ meta: { title: 'Phase heading contrast', output: 'segment.html', quality_profile: 'showcase' },+ participants: [+ { id: 'client', type: 'external', label: 'Client' },+ { id: 'api', type: 'backend', label: 'API' },+ { id: 'worker', type: 'cloud', label: 'Worker' },+ { id: 'db', type: 'database', label: 'DB' },+ ],+ segments: [{ from: 145, to: 205, label: TITLE }],+ messages: [{ from: 'client', to: 'api', y: 170, label: 'Begin request' }],+ }));+ execFileSync(process.execPath, [path.join(skillRoot, 'renderers/sequence/render-sequence.mjs'), input, file]);+ const browser = new ChromeVisualBrowser(chrome);+ t.after(() => browser.close());+ const session = await browser.sessionPromise;+ const send = (method, params = {}) => browser.cdp.send(method, params, session);+ async function run(expression) {+ const result = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });+ assert.equal(result.exceptionDetails, undefined, result.exceptionDetails?.exception?.description);+ return result.result?.value;+ }+ await send('Emulation.setDeviceMetricsOverride', { width: 1440, height: 900, deviceScaleFactor: 1, mobile: false });+ const loaded = browser.cdp.waitFor('Page.loadEventFired', session);+ await send('Page.navigate', { url: pathToFileURL(file).href });+ await loaded;+ await run('document.fonts.ready');+ await run('Archify.readerLayout.whenStable()');+ for (const mode of ['read', 'full']) {+ if (mode === 'full') await run('for (let i = 0; i < 3; i++) Archify.view.zoomIn()');+ for (const preset of ['classic', 'signal-flow', 'blueprint', 'editorial']) {+ for (const theme of ['light', 'dark']) {+ await t.test(`${preset} ${theme} ${mode} phase heading has at least 4.5:1 contrast`, async () => {+ await run(`document.documentElement.setAttribute('data-theme', ${JSON.stringify(theme)});+ document.documentElement.setAttribute('data-preset', ${JSON.stringify(preset)});+ document.querySelector('.diagram-container > svg').setAttribute('data-preset', ${JSON.stringify(preset)});+ new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))`);+ const colors = await run(`(() => {+ const group = document.querySelector('[data-graph-role="segment-label"]');+ const title = group.querySelector('text'), plate = group.querySelector('rect');+ const style = getComputedStyle(title), plateStyle = getComputedStyle(plate);+ const rgba = value => {+ const parts = value.match(/[\\d.]+/g).map(Number);+ return [...parts.slice(0, 3), parts[3] ?? 1];+ };+ const background = rgba(plateStyle.fill), foreground = rgba(style.fill);+ const luminance = rgb => rgb.slice(0, 3).map(c => {+ c /= 255;+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;+ }).reduce((sum, c, i) => sum + c * [0.2126, 0.7152, 0.0722][i], 0);+ const a = luminance(foreground), b = luminance(background);+ const visible = [title, plate, group].every(el => {+ const s = getComputedStyle(el);+ return s.opacity === '1' && s.visibility === 'visible' && s.display !== 'none';+ });+ const box = title.getBBox(), plateBox = plate.getBBox();+ return { ratio: (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05),+ foreground, background, fillOpacity: style.fillOpacity, plateFillOpacity: plateStyle.fillOpacity,+ visible, title: title.textContent, count: document.querySelectorAll('[data-graph-role="segment-label"]').length,+ detail: document.querySelector('.diagram-container').dataset.detailLevel,+ contained: box.x >= plateBox.x && box.y >= plateBox.y && box.x + box.width <= plateBox.x + plateBox.width && box.y + box.height <= plateBox.y + plateBox.height };+ })()`);+ assert.equal(colors.count, 1);+ assert.equal(colors.title, TITLE, 'the authored heading is retained');+ assert.equal(colors.detail, mode);+ assert.equal(colors.visible, true, 'contrast is measured on visible text and plate');+ assert.equal(colors.contained, true, 'the measured plate lies behind the complete heading');+ assert.equal(colors.foreground[3], 1);+ assert.equal(colors.background[3], 1, 'the title plate is opaque');+ assert.equal(colors.fillOpacity, '1');+ assert.equal(colors.plateFillOpacity, '1');+ t.diagnostic(`${preset} ${theme} ${mode}: ${colors.ratio.toFixed(5)}:1; foreground ${colors.foreground}; plate ${colors.background}`);+ assert.ok(colors.ratio >= 4.5, `phase heading contrast ${colors.ratio.toFixed(3)}:1 must be at least 4.5:1`);+ });+ }+ }+ }+});diff --git a/test/sequence-segment-labels.test.mjs b/test/sequence-segment-labels.test.mjsindex 634f211c..73525a39 100644--- a/test/sequence-segment-labels.test.mjs+++ b/test/sequence-segment-labels.test.mjs@@ -110,6 +110,85 @@ test('inside title candidates stay below low participant headers', () => {assert.ok(labels(result.html)[0].y >= PARTICIPANT_BOTTOM);});+// The real history drafts started their first frame at 144/145 and their+// first arrow at 174/175. The renderer's 18px title was partly behind the+// participant cards, even though the strip below those cards was free.+function headerDraft(from = 145, firstY = 175) {+ return {+ schema_version: 1, diagram_type: 'sequence',+ meta: { title: 'History phases', output: 'phase.html', quality_profile: 'showcase', viewBox: [920, 760] },+ participants: ['build', 'snapshot', 'page', 'browser', 'reader']+ .map((id) => ({ id, type: 'backend', label: id })),+ messages: [{ from: 'build', to: 'snapshot', y: firstY, label: 'ping', note: 'keep this annotation' }],+ segments: [{ from, to: 400, label: '构建期:读取固定文件;两种构建分支' }],+ };+}++function assertAuthoredTimeline(html, diagram) {+ const frames = [...html.matchAll(/data-composition-frame-id="(\d+)" x="48" y="([\d.]+)" width="[\d.]+" height="([\d.]+)"/g)]+ .map((match) => ({ from: +match[2], to: +match[2] + +match[3] }));+ assert.deepEqual(frames, diagram.segments.map(({ from, to }) => ({ from, to })), 'authored phase bounds stay fixed');+ const routes = [...html.matchAll(/<path data-composition-edge-from="[^"]+"[^>]* d="M [\d.]+ ([\d.]+) L [\d.]+ \1"/g)]+ .map((match) => +match[1]);+ assert.deepEqual(routes, diagram.messages.map(({ y }) => y), 'authored arrows stay fixed');+ const note = html.match(/<text data-detail="fine" x="[\d.]+" y="([\d.]+)"[^>]*font-size="([\d.]+)">keep this annotation<\/text>/);+ assert.ok(note, 'the authored note stays complete');+ assert.deepEqual(note.slice(1).map(Number), [diagram.messages.find((message) => message.note).y + 18, 7],+ 'the annotation keeps its authored baseline and font');+}++for (const from of [145, 144]) {+ test(`first phase from ${from} clears headers without moving its frame, arrows or note`, () => {+ const diagram = headerDraft(from, from + 30);+ if (from === 144) {+ // These arrows defeat all four legacy inside slots near the frame top.+ diagram.messages[0].note = undefined;+ diagram.messages.push(+ { from: 'snapshot', to: 'build', y: 211, label: 'missing' },+ { from: 'build', to: 'page', y: 252, label: 'guide', note: 'keep this annotation' },+ );+ }+ const result = render(diagram);+ assert.equal(result.status, 0, result.stdout + result.stderr);+ const [title] = labels(result.html);+ assert.ok(title.y >= PARTICIPANT_BOTTOM + 2, 'the full title clears the participant cards');+ assert.ok(title.y <= from && title.y + title.height >= from, 'the title still names its own top border');+ assert.ok(title.y + title.height + 2 <= diagram.messages[0].y - 20, 'the first message label stays clear');+ assertAuthoredTimeline(result.html, diagram);+ });+}++test('a header-adjacent title cannot cover an earlier first message', () => {+ const diagram = headerDraft(145, 160);+ const result = render(diagram);+ assert.equal(result.status, 0, result.stdout + result.stderr);+ const [title] = labels(result.html);+ assert.ok(title.y >= 160 + 22 + 2, 'the occupied header strip retains the safe inside fallback');+ assertAuthoredTimeline(result.html, diagram);+});++test('a nested frame keeps the existing title placement', () => {+ const diagram = headerDraft();+ diagram.segments.push({ from: 250, to: 350, label: 'Nested detail' });+ const result = render(diagram);+ assert.equal(result.status, 0, result.stdout + result.stderr);+ assert.ok(labels(result.html)[0].y + 18 < diagram.segments[0].from,+ 'the header-only adjustment does not reinterpret nested phase bounds');+ assertAuthoredTimeline(result.html, diagram);+});++test('a header-adjacent title keeps clear of another title that moved above its nominal slot', () => {+ const diagram = headerDraft();+ diagram.messages[0].note = undefined;+ diagram.segments[0].to = 154;+ diagram.segments.push({ from: 194, to: 350, label: '读取快照与生成页面' });+ const result = render(diagram);+ assert.equal(result.status, 0, result.stdout + result.stderr);+ const [first, next] = labels(result.html);+ assert.ok(next.y < diagram.segments[1].from - 22, 'the other title actually moved up from its nominal slot');+ assert.ok(!rectOverlaps(first, next), 'the new header strip does not introduce a title collision');+});+test('inside segment title clears a message note after avoiding participant headers', () => {const diagram = {schema_version: 1, diagram_type: 'sequence',@@ -121,7 +200,7 @@ test('inside segment title clears a message note after avoiding participant headconst result = render(diagram, true);assert.equal(result.status, 0, result.stdout + result.stderr);const [title] = labels(result.html);- const note = result.html.match(/<text data-detail="fine" x="([\d.]+)" y="([\d.]+)" class="t-dim" font-size="([\d.]+)">diagnostic annotation<\/text>/);+ const note = result.html.match(/<text data-detail="fine" x="([\d.]+)" y="([\d.]+)" class="[^"]*" font-size="([\d.]+)">diagnostic annotation<\/text>/);assert.ok(note, 'the full authored annotation remains visible');assert.deepEqual(note.slice(1).map(Number), [176, 178, 7], 'note position and font remain authored geometry');assert.ok(title.y >= PARTICIPANT_BOTTOM, 'title clears the participant headers');@@ -178,3 +257,83 @@ test('the unedited payment draft reports its note overlap with a valid spacing rconst compatible = render(diagram, true);assert.equal(compatible.status, 0, compatible.stdout + compatible.stderr);});++function neutralTitleDraft() {+ return {+ schema_version: 1, diagram_type: 'sequence',+ meta: { title: 'Segment title clearance probe', output: 'diagram.html', quality_profile: 'showcase', locale: 'zh-CN' },+ participants: [+ { id: 'a', type: 'external', label: '甲方' },+ { id: 'b', type: 'backend', label: '乙方' },+ { id: 'c', type: 'cloud', label: '丙方' },+ { id: 'd', type: 'backend', label: '丁方' },+ ],+ segments: [{ from: 145, to: 205, label: '准备阶段确认目标以后开始前' }],+ messages: [{ from: 'a', to: 'b', y: 170, label: '请求开始以后等待返回值' }],+ };+}++const rectOverlaps = (a, b, gap = 2) => a.x < b.x + b.width + gap && b.x < a.x + a.width + gap+ && a.y < b.y + b.height + gap && b.y < a.y + a.height + gap;++function maskRects(html) {+ return [...html.matchAll(/<rect x="([\d.-]+)" y="([\d.-]+)" width="([\d.]+)" height="([\d.]+)" rx="[\d.]+" class="c-mask"\/>/g)]+ .map((match) => ({ x: +match[1], y: +match[2], width: +match[3], height: +match[4] }));+}++function assertClearTitle(result, diagram) {+ assert.equal(result.status, 0, result.stdout + result.stderr);+ const [title] = labels(result.html);+ for (const rect of maskRects(result.html)) {+ if (JSON.stringify(rect) === JSON.stringify({ x: title.x, y: title.y, width: title.width, height: title.height })) continue;+ assert.ok(!rectOverlaps(title, rect), `title must clear mask ${JSON.stringify(rect)}`);+ }+ assert.ok(title.y <= diagram.segments[0].from && title.y + title.height >= diagram.segments[0].from,+ 'the title remains on its own top border');+ assert.match(result.html, /font-size="9" font-weight="600">准备阶段确认目标以后开始前<\/text>/);+ assert.match(result.html, /font-size="(?:9|11)" text-anchor="middle">请求开始以后等待返回值<\/text>/);+ const frame = result.html.match(/data-composition-frame-id="0" x="48" y="([\d.]+)" width="[\d.]+" height="([\d.]+)"/);+ assert.deepEqual(frame.slice(1).map(Number), [145, 60]);+ const arrow = result.html.match(/data-composition-edge-from="a"[^>]*d="M [\d.]+ ([\d.]+) L [\d.]+ \1"/);+ assert.ok(arrow, 'the authored request arrow stays at y170');+ assert.equal(+arrow[1], 170);+}++test('first title clears participants and the request mask without editing authored geometry', () => {+ const diagram = neutralTitleDraft();+ assertClearTitle(render(diagram), diagram);+});++for (const column_fit of ['fixed', 'spread']) {+ for (const quality_profile of ['standard', 'showcase']) {+ test(`blocked first title finds a clear strip with ${column_fit} columns and ${quality_profile} acceptance`, () => {+ const diagram = neutralTitleDraft();+ Object.assign(diagram.meta, { column_fit, quality_profile, viewBox: [920, 760] });+ const result = render(diagram);+ assertClearTitle(result, diagram);+ });+ }+}++test('horizontal fallback clears activation bars without changing their geometry', () => {+ const diagram = neutralTitleDraft();+ diagram.activations = [{ participant: 'b', from: 145, to: 200 }];+ const result = render(diagram);+ assertClearTitle(result, diagram);+ const activation = maskRects(result.html).find((rect) => rect.width === 10 && rect.y === 145);+ assert.ok(activation);+ assert.equal(activation.height, 55, 'activation keeps its authored time bounds and width');+});++test('an exhausted horizontal strip preserves compatible legacy placement', () => {+ const diagram = neutralTitleDraft();+ diagram.segments[0].label = '阶段'.repeat(35);+ const result = render(diagram);+ assert.equal(result.status, 0, result.stdout + result.stderr);+ const [title] = labels(result.html);+ assert.equal(title.x, 56, 'no out-of-frame slot is forced');+ assert.equal(title.y, 123, 'exhaustion does not introduce a new acceptance failure');+ assert.ok(title.x + title.width <= 872);+ assert.ok(maskRects(result.html).some((rect) => rect.y === 72 && rectOverlaps(title, rect)),+ 'the retained overlap remains unresolved rather than being called repaired');+});diff --git a/test/sequence-width-default-browser.test.mjs b/test/sequence-width-default-browser.test.mjsindex cb3860fe..554590f7 100644--- a/test/sequence-width-default-browser.test.mjs+++ b/test/sequence-width-default-browser.test.mjs@@ -9,6 +9,46 @@ import { ChromeVisualBrowser, findChrome } from '../archify/bin/visual-check.mjsconst cli = fileURLToPath(new URL('../archify/bin/archify.mjs', import.meta.url));+const contains = (outer, inner) => inner.left >= outer.left - 0.1 && inner.right <= outer.right + 0.1+ && inner.top >= outer.top - 0.1 && inner.bottom <= outer.bottom + 0.1;+const overlaps = (a, b) => Math.min(a.right, b.right) > Math.max(a.left, b.left) + 0.1+ && Math.min(a.bottom, b.bottom) > Math.max(a.top, b.top) + 0.1;++async function observeSequence(browser, session) {+ const evaluated = await browser.cdp.send('Runtime.evaluate', {+ returnByValue: true,+ expression: `(() => {+ const svg = document.querySelector('.diagram-container > svg');+ const box = el => {+ const r = el.getBoundingClientRect();+ return { left: r.left, top: r.top, right: r.right, bottom: r.bottom, width: r.width, height: r.height };+ };+ const visible = el => {+ const style = getComputedStyle(el), r = el.getBoundingClientRect();+ return style.display !== 'none' && style.visibility !== 'hidden' && Number(style.opacity) > 0 && r.width > 0 && r.height > 0;+ };+ return {+ theme: document.documentElement.dataset.theme,+ viewBox: svg.getAttribute('viewBox'), canvas: box(svg),+ nodes: [...svg.querySelectorAll('g[data-node-id]')].map(node => {+ const rect = node.querySelector('rect'), label = node.querySelector('text[data-node-label]');+ return { label: label.textContent, box: box(rect), text: box(label), sigil: box(node.querySelector('[data-semantic-sigil]')),+ visible: visible(label), font: parseFloat(getComputedStyle(label).fontSize) * svg.getScreenCTM().a,+ geometry: [Number(rect.getAttribute('x')), Number(rect.getAttribute('width'))],+ sublabel: (() => {+ const el = node.querySelector('text[data-detail="context"]');+ return el && { value: el.textContent, box: box(el), visible: visible(el), font: parseFloat(getComputedStyle(el).fontSize) * svg.getScreenCTM().a };+ })() };+ }),+ messageMasks: [...svg.querySelectorAll('g[data-detail="context"]')].filter(el => el.querySelector('rect.c-mask')).map(el => ({ box: box(el.querySelector('rect.c-mask')), text: box(el.querySelector('text')) })),+ text: [...svg.querySelectorAll('text')].filter(visible).map(el => ({ value: el.textContent, box: box(el) })),+ };+ })()`,+ }, session);+ assert.equal(evaluated.exceptionDetails, undefined);+ return evaluated.result.value;+}+test('authored sequence canvases default to spread and keep real browser labels inside their columns', async (t) => {if (!Object.hasOwn(process.env, 'ARCHIFY_CHROME')) return t.skip('Set ARCHIFY_CHROME for real browser checks');const chrome = findChrome();@@ -40,38 +80,8 @@ test('authored sequence canvases default to spread and keep real browser labelsexecFileSync(process.execPath, [cli, 'render', 'sequence', input, output], { stdio: ['ignore', 'pipe', 'pipe'] });for (const theme of ['light', 'dark']) {await browser.inspect({ artifactPath: output, width: 1440, height: 900, theme });- const evaluated = await browser.cdp.send('Runtime.evaluate', {- returnByValue: true,- expression: `(() => {- const svg = document.querySelector('.diagram-container > svg');- const box = el => {- const r = el.getBoundingClientRect();- return { left: r.left, top: r.top, right: r.right, bottom: r.bottom, width: r.width, height: r.height };- };- const visible = el => {- const style = getComputedStyle(el), r = el.getBoundingClientRect();- return style.display !== 'none' && style.visibility !== 'hidden' && Number(style.opacity) > 0 && r.width > 0 && r.height > 0;- };- return {- theme: document.documentElement.dataset.theme,- viewBox: svg.getAttribute('viewBox'), canvas: box(svg),- nodes: [...svg.querySelectorAll('g[data-node-id]')].map(node => {- const rect = node.querySelector('rect'), label = node.querySelector('text[data-node-label]');- return { label: label.textContent, box: box(rect), text: box(label), sigil: box(node.querySelector('[data-semantic-sigil]')),- visible: visible(label), font: parseFloat(getComputedStyle(label).fontSize) * svg.getScreenCTM().a,- geometry: [Number(rect.getAttribute('x')), Number(rect.getAttribute('width'))] };- }),- text: [...svg.querySelectorAll('text')].filter(visible).map(el => ({ value: el.textContent, box: box(el) })),- };- })()`,- }, session);- assert.equal(evaluated.exceptionDetails, undefined);- const observed = evaluated.result.value;+ const observed = await observeSequence(browser, session);const where = `${canvasWidth}px/${fit}/${theme}`;- const contains = (outer, inner) => inner.left >= outer.left - 0.1 && inner.right <= outer.right + 0.1- && inner.top >= outer.top - 0.1 && inner.bottom <= outer.bottom + 0.1;- const overlaps = (a, b) => Math.min(a.right, b.right) > Math.max(a.left, b.left) + 0.1- && Math.min(a.bottom, b.bottom) > Math.max(a.top, b.top) + 0.1;assert.equal(observed.theme, theme, where);assert.equal(observed.viewBox, `0 0 ${canvasWidth} 620`, where + ': authored viewBox changed');assert.deepEqual(observed.nodes.map(node => node.label), spec.participants.map(node => node.label), where);@@ -107,3 +117,75 @@ test('authored sequence canvases default to spread and keep real browser labelsfs.rmSync(dir, { recursive: true, force: true });}});++test('automatic sequence spread recovers crowded headers without losing real browser glyphs or masks', async (t) => {+ if (!Object.hasOwn(process.env, 'ARCHIFY_CHROME')) return t.skip('Set ARCHIFY_CHROME for real browser checks');+ const chrome = findChrome();+ assert.ok(chrome, 'The configured browser regression requires Chrome');+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-sequence-capacity-'));+ const browser = new ChromeVisualBrowser(chrome);+ try {+ const session = await browser.sessionPromise;+ // Synthetic endpoints require more than the nominal seven-column width,+ // but fit within the existing automatic canvas, margins and card gutters.+ const spec = {+ schema_version: 1, diagram_type: 'sequence',+ meta: { title: 'Event delivery', quality_profile: 'showcase', output: 'diagram.html' },+ participants: ['NotificationGateway', 'Access', 'Policy', 'Events', 'Cache', 'Store', '审计DeliveryService']+ .map((label, i) => ({ id: `p${i}`, type: 'backend', label, sublabel: ['入口', 'token', 'rules', 'queue', 'hot', 'data', '审计'][i] })),+ messages: [{ from: 'p0', to: 'p1', y: 180, label: 'send' }],+ };+ const input = path.join(dir, 'capacity.json');+ const output = path.join(dir, 'capacity.html');+ fs.writeFileSync(input, JSON.stringify(spec));+ execFileSync(process.execPath, [cli, 'render', 'sequence', input, output], { stdio: ['ignore', 'pipe', 'pipe'] });+ let geometry;+ for (const theme of ['light', 'dark']) {+ await browser.inspect({ artifactPath: output, width: 1440, height: 900, theme });+ const observed = await observeSequence(browser, session);+ const where = `automatic capacity/${theme}`;+ const canvasWidth = Number(observed.viewBox.split(' ')[2]);+ assert.equal(observed.theme, theme, where);+ assert.ok(canvasWidth <= 1085, where + ': preserve the automatic desktop width cap');+ assert.deepEqual(observed.nodes.map(node => node.label), spec.participants.map(node => node.label), where);+ assert.deepEqual(observed.nodes.map(node => node.sublabel?.value), spec.participants.map(node => node.sublabel), where);+ for (const node of observed.nodes) {+ assert.ok(node.visible && node.font >= 7.5, where + ': primary label must remain readable');+ assert.ok(node.sublabel.visible && node.sublabel.font >= 6.5, where + ': sublabel must remain readable');+ assert.ok(contains(observed.canvas, node.box), where + ': participant escapes canvas');+ for (const text of [node.text, node.sublabel.box]) {+ assert.ok(contains(node.box, text), where + ': real glyph bounds escape participant: ' + node.label);+ assert.ok(!overlaps(text, node.sigil), where + ': text overlaps semantic sigil');+ }+ }+ const boxes = observed.nodes.map(node => node.geometry);+ assert.ok(boxes[0][0] >= 40 && canvasWidth - boxes.at(-1)[0] - boxes.at(-1)[1] >= 40,+ where + ': keep both outer card margins');+ for (let i = 1; i < boxes.length; i++) {+ assert.ok(boxes[i][0] - boxes[i - 1][0] - boxes[i - 1][1] >= 16 - 0.01,+ where + ': keep the minimum card gutter');+ }+ assert.equal(observed.messageMasks.length, spec.messages.length, where + ': message mask missing');+ for (const mask of observed.messageMasks) {+ // Column recovery changes horizontal geometry. SVG font bounds can+ // overhang the mask vertically on unchanged baseline output too.+ assert.ok(mask.text.left >= mask.box.left - 0.1 && mask.text.right <= mask.box.right + 0.1,+ where + ': message glyphs escape the mask horizontally');+ assert.ok(contains(observed.canvas, mask.box), where + ': message mask escapes canvas');+ for (const node of observed.nodes) assert.ok(!overlaps(mask.box, node.box), where + ': message mask covers a header');+ }+ for (let i = 0; i < observed.text.length; i++) {+ const text = observed.text[i];+ assert.ok(contains(observed.canvas, text.box), where + ': visible text escapes canvas: ' + text.value);+ for (const other of observed.text.slice(i + 1)) {+ assert.ok(!overlaps(text.box, other.box), where + ': visible labels overlap: ' + text.value + ' / ' + other.value);+ }+ }+ if (geometry) assert.deepEqual(boxes, geometry, where + ': theme changed column geometry');+ else geometry = boxes;+ }+ } finally {+ await browser.close();+ fs.rmSync(dir, { recursive: true, force: true });+ }+});diff --git a/test/workflow-automatic-width.test.mjs b/test/workflow-automatic-width.test.mjsnew file mode 100644index 00000000..661965e2--- /dev/null+++ b/test/workflow-automatic-width.test.mjs@@ -0,0 +1,242 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import { compileWorkflow } from '../archify/renderers/workflow/workflow-compiler.mjs';+import { intrinsicWorkflow } from '../archify/renderers/workflow/workflow-migration-geometry.mjs';+import { migrateWorkflowDocument } from '../archify/migrations/workflow-v2.mjs';++function lendingWorkflow() {+ return {+ schema_version: 2,+ diagram_type: 'workflow',+ meta: { title: 'Library lending', locale: 'en', quality_profile: 'showcase', output: 'library-lending.html' },+ lanes: [{ id: 'desk', label: 'Library lending: verify the borrower record, confirm membership is current, check borrowing limits, and approve available books for loan' }],+ nodes: [+ { id: 'verify', lane: 'desk', col: 0, type: 'backend', label: 'Verify', sublabel: 'Review borrower records' },+ { id: 'lend', lane: 'desk', col: 1, type: 'backend', label: 'Lend' },+ ],+ edges: [{ id: 'eligible', from: 'verify', to: 'lend', label: 'eligible' }],+ };+}++const clone = (value) => JSON.parse(JSON.stringify(value));+const digest = (value) => createHash('sha256').update(value).digest('hex');+const widthOf = (result, id) => result.receipt.nodes.find((node) => node.id === id).width;++function compileSuccessfully(workflow, qualityProfile) {+ const result = compileWorkflow({ workflow, qualityProfile });+ assert.equal(result.ok, true, JSON.stringify(result.diagnostics));+ return result;+}++function assertReadableSublabels(result) {+ // The desktop contract has a 930px diagram budget and a 6px projected floor.+ const minimum = Math.max(6, Math.ceil(6 * result.receipt.viewBox[0] / 930 * 10) / 10);+ const rows = [...result.svg.matchAll(/data-detail="context"[^>]*font-size="([\d.]+)"[^>]*>([^<]+)<\/text>/g)];+ assert.ok(rows.length);+ for (const [, font] of rows) assert.ok(Number(font) >= minimum && Number(font) <= 8);+}++function cascadeWorkflow(labelLength = 21) {+ const workflow = lendingWorkflow();+ workflow.meta.legend = { mode: 'hidden' };+ workflow.lanes[0].label = 'Desk';+ workflow.nodes = Array.from({ length: 6 }, (_, col) => ({+ id: `n${col}`, lane: 'desk', col, type: 'backend',+ label: col < 2 ? 'Step' : 'A'.repeat(labelLength),+ ...(col === 0 ? { sublabel: 'Review borrower records' } : {}),+ ...(col === 1 ? { sublabel: 'Check borrower records' } : {}),+ }));+ workflow.edges = Array.from({ length: 5 }, (_, index) => ({ id: `e${index}`, from: `n${index}`, to: `n${index + 1}` }));+ return workflow;+}++test('omitted workflow widths fit sublabels at the final showcase canvas minimum', () => {+ const workflow = lendingWorkflow();+ const before = JSON.stringify(workflow);+ const result = compileWorkflow({ workflow });+ assert.equal(result.ok, true, JSON.stringify(result.diagnostics));+ assert.equal(JSON.stringify(workflow), before);+ const verify = result.receipt.nodes.find(({ id }) => id === 'verify');+ assert.ok(verify.width > 92 && verify.width <= 200);+ assert.match(result.svg, />Review borrower records<\/text>/);+ assert.equal(result.receipt.edges.length, 1);+ assert.equal(result.receipt.nodes.length, 2);+ assertReadableSublabels(result);+});++test('automatic width feedback handles a new sublabel failure caused by the first batch', () => {+ // Original canvas is 976px: n0 needs 6.3px, while n1 still fits. Growing n0+ // crosses the 6.4px boundary and requires n1 to grow in the next epoch.+ const workflow = cascadeWorkflow();+ const before = JSON.stringify(workflow);+ const result = compileSuccessfully(workflow);+ assert.ok(widthOf(result, 'n0') > 92);+ assert.ok(widthOf(result, 'n1') > 92);+ assert.ok(result.receipt.nodes.every(({ width }) => width <= 200));+ assertReadableSublabels(result);+ assert.equal(JSON.stringify(workflow), before);+});++test('a mixed document repairs automatic widths and preserves explicit widths and endpoint sides', () => {+ const workflow = lendingWorkflow();+ workflow.nodes[1].width = 108;+ Object.assign(workflow.edges[0], { fromSide: 'right', toSide: 'left' });+ const result = compileSuccessfully(workflow);+ assert.ok(widthOf(result, 'verify') > 92);+ assert.equal(widthOf(result, 'lend'), 108);+ assert.equal(workflow.nodes[0].width, undefined);+ assert.equal(workflow.nodes[1].width, 108);+ assertReadableSublabels(result);++ // Keep a real explicit failure after repairing the other node. The source+ // order differs from canonical rank order, so its JSON pointer must still+ // name the authored node rather than the sorted clone's index.+ workflow.nodes[1].width = 92;+ workflow.nodes[1].sublabel = 'Review borrower records';+ workflow.nodes.reverse();+ const before = JSON.stringify(workflow);+ const mixedFailure = compileWorkflow({ workflow });+ assert.equal(mixedFailure.ok, false);+ assert.ok(widthOf(mixedFailure, 'verify') > 92);+ assert.equal(widthOf(mixedFailure, 'lend'), 92);+ assert.deepEqual(mixedFailure.diagnostics.map(({ subject }) => [subject.node, subject.path]), [['lend', '/nodes/0/sublabel']]);+ assert.equal(JSON.stringify(workflow), before);+});++test('same-object edits and quality overrides agree with a fresh input after every compile', () => {+ const workflow = lendingWorkflow();+ const check = (qualityProfile) => {+ const before = JSON.stringify(workflow);+ const reused = compileWorkflow({ workflow, qualityProfile });+ assert.deepEqual(reused, compileWorkflow({ workflow: clone(workflow), qualityProfile }));+ assert.equal(JSON.stringify(workflow), before);+ return reused;+ };+ workflow.nodes[0].sublabel = 'Review';+ assert.equal(widthOf(check(), 'verify'), 92);+ workflow.nodes[0].sublabel = 'Review borrower records';+ assert.ok(widthOf(check(), 'verify') > 92);+ workflow.nodes[0].sublabel = 'Review';+ assert.equal(widthOf(check(), 'verify'), 92);+ workflow.nodes[0].sublabel = 'Review borrower records';+ workflow.meta.quality_profile = 'standard';+ assert.ok(widthOf(check('showcase'), 'verify') > 92);+ assert.equal(widthOf(check('standard'), 'verify'), 92);+ workflow.meta.quality_profile = 'showcase';+ workflow.nodes[0].width = 92;+ assert.equal(check().ok, false);+ delete workflow.nodes[0].width;+ assert.equal(check().ok, true);+ workflow.meta.viewBox = [1000, 420];+ assert.equal(widthOf(check(), 'verify'), 92);+ delete workflow.meta.viewBox;+ assert.equal(check().ok, true);+ for (const pin of [{ via: [[300, 100]] }, { labelAt: [200, 100] }, { channelX: 200 }, { channelY: 100 }]) {+ Object.assign(workflow.edges[0], pin);+ assert.equal(check().ok, false);+ for (const key of Object.keys(pin)) delete workflow.edges[0][key];+ assert.equal(check().ok, true);+ }+ workflow.schema_version = 1;+ check();+ workflow.schema_version = 2;+ assert.equal(check().ok, true);+});++test('migration absolute-geometry policy survives eligibility checks before cloning', () => {+ const original = lendingWorkflow();+ original.meta.viewBox = [1000, 420];+ const planned = intrinsicWorkflow(original);+ assert.equal(planned.meta.viewBox, undefined);+ const result = compileWorkflow({ workflow: planned });+ assert.equal(result.ok, false);+ assert.equal(widthOf(result, 'verify'), 92);+ assert.ok(result.diagnostics.some(({ code }) => code === 'workflow/sublabel-readability'));+});++test('public migration verifies overlap advice under the original geometry policy', () => {+ const authored = lendingWorkflow();+ authored.schema_version = 1;+ authored.meta.viewBox = [1000, 420];+ authored.nodes[1].col = 0;+ const before = JSON.stringify(authored);+ const migration = migrateWorkflowDocument(authored);+ assert.equal(migration.ok, false);+ assert.equal(JSON.stringify(authored), before);+ const overlap = migration.newSchemaDiagnostics.find(({ code }) => code === 'workflow/node-overlap');+ assert.ok(overlap);++ // Applying the free-column edit still leaves the public migration blocked;+ // that edit alone must not be advertised as a verified repair.+ const edited = clone(authored);+ edited.nodes[1].col = 1;+ const editedBefore = JSON.stringify(edited);+ const appliedMigration = migrateWorkflowDocument(edited);+ assert.equal(appliedMigration.ok, false);+ assert.ok(appliedMigration.newSchemaDiagnostics.some(({ code }) => code === 'workflow/sublabel-readability'));+ assert.equal(JSON.stringify(edited), editedBefore);+ const applied = compileWorkflow({ workflow: intrinsicWorkflow(edited) });+ assert.equal(applied.ok, false);+ assert.equal(widthOf(applied, 'verify'), 92);+ assert.ok(applied.diagnostics.some(({ code }) => code === 'workflow/sublabel-readability'));+ assert.deepEqual(overlap.supportedFixes, []);+});++test('ordinary authored canvas removal advice can still verify an automatic-width repair', () => {+ const authored = lendingWorkflow();+ authored.meta.viewBox = [800, 420];+ const before = JSON.stringify(authored);+ const result = compileWorkflow({ workflow: authored });+ assert.equal(result.ok, false);+ assert.equal(JSON.stringify(authored), before);+ const capacity = result.diagnostics.find(({ code }) => code === 'workflow/viewbox-capacity');+ assert.ok(capacity);+ assert.ok(capacity.supportedFixes.includes('omit meta.viewBox so the compiler can use its measured intrinsic canvas'));+ delete authored.meta.viewBox;+ const applied = compileSuccessfully(authored);+ assert.equal(widthOf(applied, 'verify'), 96);+});++test('explicit undersizing, automatic capacity and the fixed text-row ceiling remain failures', () => {+ const explicit = lendingWorkflow();+ explicit.nodes[0].width = 92;+ const explicitResult = compileWorkflow({ workflow: explicit });+ assert.equal(explicitResult.ok, false);+ assert.equal(widthOf(explicitResult, 'verify'), 92);+ assert.equal(explicitResult.diagnostics[0].code, 'workflow/sublabel-readability');++ const capacity = lendingWorkflow();+ capacity.nodes[0].sublabel = 'x'.repeat(53);+ const capResult = compileWorkflow({ workflow: capacity });+ assert.equal(capResult.ok, false);+ assert.equal(widthOf(capResult, 'verify'), 200);+ assert.ok(capResult.diagnostics.some(({ code, evidence }) => code === 'workflow/sublabel-readability'+ && evidence.requiredFontPx <= 8 && evidence.requiredTextWidthPx > evidence.availableTextWidthPx));++ const rowCeiling = cascadeWorkflow();+ for (const node of rowCeiling.nodes.slice(2)) node.width = 400;+ const rowResult = compileWorkflow({ workflow: rowCeiling });+ assert.equal(rowResult.ok, false);+ assert.equal(widthOf(rowResult, 'n0'), 92);+ assert.ok(rowResult.diagnostics.some(({ code, evidence }) => code === 'workflow/sublabel-readability' && evidence.requiredFontPx > 8));+});++test('already successful automatic and preserved-geometry output keeps exact baseline bytes', () => {+ // Captured from e80d489 / compiler 611550d1 before this repair. These bytes+ // protect the error-only compatibility promise, not a new automatic layout.+ const cases = [+ [(w) => { w.nodes[0].sublabel = 'Review'; }, 'b92b134384403165ea109af78c863c2a3e75fb5e77f9642f219aa69a158443ab', '534b97cba075f71755547834250d05b71a12c56b01c66dde92b39abced0cf540'],+ [(w) => { w.nodes[0].sublabel = 'Review borrower records and loan eligibility'; }, '989036d464c2f2e32d48efd3368fd74ffd55c0d54dd22f459d87bea3f24840d7', '87d8b7618a419fcb4947e1d48c7d8217e2e116de259e79bcc5b7e362b3ae7e61'],+ [(w) => { w.meta.quality_profile = 'standard'; }, 'b39439ec2a8e885ed645203f73525850b660757b87b6ed8b8af90c6e50730763', '534b97cba075f71755547834250d05b71a12c56b01c66dde92b39abced0cf540'],+ [(w) => { w.meta.viewBox = [1000, 420]; }, 'f92bddb54c34b69d0fc50a9dea7f2dd78570bb004c46d2e3cd9bbebbde3fde95', 'fbcb1e66f972c89f9f56bba923766b0adc3f11c3d300739c50f3ef7d7855d606'],+ [(w) => { w.nodes[0].width = 104; }, '2db4c04e21e24e2b995044fcc7039f55f0769561684ddcef508025fa87f29400', '974133d390cdfbaa38658000eb01dece4860fd98c242159c6ff0e9afc290f56e'],+ ];+ for (const [edit, svgHash, receiptHash] of cases) {+ const workflow = lendingWorkflow();+ edit(workflow);+ const result = compileSuccessfully(workflow);+ assert.equal(digest(result.svg), svgHash);+ assert.equal(digest(JSON.stringify(result.receipt)), receiptHash);+ }+});diff --git a/test/workflow-compiler-hard-contract.test.mjs b/test/workflow-compiler-hard-contract.test.mjsindex 1587a381..55048112 100644--- a/test/workflow-compiler-hard-contract.test.mjs+++ b/test/workflow-compiler-hard-contract.test.mjs@@ -120,7 +120,7 @@ function assertExplicitPinConflict(result, context) {result.diagnostics.some(({ code }) => code === 'workflow/explicit-pin-conflict'),`${context} must report workflow/explicit-pin-conflict:\n${JSON.stringify(result.diagnostics, null, 2)}`,);- assert.deepEqual(result.receipt.diagnostics, result.diagnostics);+ assert.deepEqual(result.receipt, { contract: result.receipt.contract, diagnostics: result.diagnostics });}function assertSupportedFixesNameChangedEdge(diagnostic, edgeIds) {@@ -754,6 +754,187 @@ test('readable-v2 treats an infeasible route preset as a candidate-family confli}});+test('readable-v2 verifies preset repairs with the public straight-route reservation', () => {+ const document = workflow({+ lanes: [{ id: 'top', label: 'Top' }, { id: 'middle', label: 'Middle' }, { id: 'bottom', label: 'Bottom' }],+ nodes: [+ { id: 'left', lane: 'middle', col: 0, type: 'backend', label: 'Left' },+ { id: 'right', lane: 'middle', col: 3, type: 'backend', label: 'Right' },+ { id: 'above', lane: 'top', col: 1, type: 'backend', label: 'Above' },+ { id: 'below', lane: 'bottom', col: 1, type: 'backend', label: 'Below' },+ ],+ edges: [+ { id: 'a-preset', from: 'left', to: 'right', label: 'PIN', route: 'outside-right', fromSide: 'right', toSide: 'right' },+ { id: 'z-auto', from: 'above', to: 'below' },+ ],+ });+ // Source indexes also differ from canonical edge order in the reversed input.+ for (const edges of [document.edges, [...document.edges].reverse()]) {+ const authored = { ...clone(document), edges: clone(edges) };+ const original = clone(authored);+ const result = compileWorkflow({ workflow: authored, qualityProfile: 'showcase' });+ assert.equal(result.ok, false);+ const diagnostic = result.diagnostics.find(({ code }) => code === 'workflow/route-preset-conflict');+ assert.ok(diagnostic, JSON.stringify(result.diagnostics, null, 2));++ const routeOnly = clone(authored);+ const routeOnlyEdge = routeOnly.edges.find(({ id }) => id === 'a-preset');+ delete routeOnlyEdge.route;+ const retainedSides = compileWorkflow({ workflow: routeOnly, qualityProfile: 'showcase' });+ assertExplicitPinConflict(retainedSides, 'removing the preset does not remove authored right/right sides');+ assert.equal(retainedSides.diagnostics[0].evidence.invariant, 'explicit route-route crossing');+ assert.equal(routeOnlyEdge.fromSide, 'right');+ assert.equal(routeOnlyEdge.toSide, 'right');++ for (const fix of diagnostic.supportedFixes) {+ const repaired = clone(authored);+ const target = repaired.edges.find(({ id }) => id === 'a-preset');+ const replacement = fix.match(/^set edge "a-preset" route to verified preset "([^"\n]+)"$/);+ if (replacement) target.route = replacement[1];+ else {+ assert.match(fix, /^remove route from edge "a-preset" so readable-v2 can use its verified automatic candidate$/);+ delete target.route;+ }+ const { route: oldRoute, ...originalAssertions } = original.edges.find(({ id }) => id === 'a-preset');+ const { route: newRoute, ...remainingAssertions } = target;+ assert.deepEqual(remainingAssertions, originalAssertions, 'a route suggestion preserves sides, label and topology');+ const verified = compileWorkflow({ workflow: repaired, qualityProfile: 'showcase' });+ assert.equal(verified.ok, true, `advertised preset repair must pass public compilation: ${fix}\n${JSON.stringify(verified.diagnostics, null, 2)}`);+ }++ const automatic = clone(routeOnly);+ const automaticEdge = automatic.edges.find(({ id }) => id === 'a-preset');+ delete automaticEdge.fromSide;+ delete automaticEdge.toSide;+ const unpinned = compileWorkflow({ workflow: automatic, qualityProfile: 'showcase' });+ assert.equal(unpinned.ok, true, 'the same topology and label are repairable when all route assertions are removed');+ assert.deepEqual(authored, original, 'fix discovery preserves the authored input');+ }+});++function outsideRightLabelWorkflow() {+ return workflow({+ lanes: [{ id: 'undo', label: 'Undo' }, { id: 'return', label: 'Follow-up' }],+ nodes: [+ { id: 'receipt', lane: 'undo', col: 5, type: 'database', label: 'Receipt' },+ { id: 'rescan', lane: 'return', col: 5, type: 'backend', label: 'Rescan' },+ ],+ edges: [{+ id: 'follow-up', from: 'receipt', to: 'rescan', label: '成功后按需另行 Scan',+ role: 'branch', variant: 'dashed', route: 'outside-right', fromSide: 'right', toSide: 'right',+ }],+ });+}++function presetLabelDiagnostic(result) {+ assert.equal(result.ok, false);+ const diagnostic = result.diagnostics.find(({ code }) => code === 'workflow/route-preset-conflict');+ assert.ok(diagnostic, JSON.stringify(result.diagnostics, null, 2));+ assert.equal(diagnostic.evidence.invariant, 'edge-label node clearance');+ return diagnostic;+}++function applySegmentSuggestion(document, diagnostic) {+ const suggestions = diagnostic.supportedFixes.filter((fix) => fix.startsWith('set labelSegment '));+ assert.equal(suggestions.length, 1, JSON.stringify(diagnostic.supportedFixes));+ assert.equal(diagnostic.supportedFixes[0], suggestions[0], 'prefer the verified local repair before route changes');+ const match = suggestions[0].match(/^set labelSegment on edge "follow-up" to (\d+)$/);+ assert.ok(match, `the segment repair must identify the edge and an executable index: ${suggestions[0]}`);+ const segment = Number(match[1]);+ assert.ok(segment < diagnostic.evidence.points.length - 1, 'only an actual route segment may be advertised');+ const repaired = clone(document);+ repaired.edges[0].labelSegment = segment;+ return repaired;+}++for (const qualityProfile of ['standard', 'showcase']) {+ test(`readable-v2 preset label repair preserves the explicit route and semantic content (${qualityProfile})`, () => {+ const document = outsideRightLabelWorkflow();+ const original = clone(document);+ const diagnostic = presetLabelDiagnostic(compileWorkflow({ workflow: document, qualityProfile }));+ const repaired = applySegmentSuggestion(document, diagnostic);+ assert.ok(diagnostic.supportedFixes.slice(1).includes(+ 'remove route from edge "follow-up" so readable-v2 can use its verified automatic candidate',+ ), 'retain the original verified route suggestion after the local repair');+ const verified = compileWorkflow({ workflow: repaired, qualityProfile });+ assert.equal(verified.ok, true, JSON.stringify(verified.diagnostics, null, 2));+ assert.deepEqual(document, original, 'suggestion discovery must not mutate the authored input');+ assert.deepEqual(repaired, {+ ...original, edges: [{ ...original.edges[0], labelSegment: repaired.edges[0].labelSegment }],+ }, 'applying the suggestion changes only labelSegment');+ const unlabeled = clone(original);+ delete unlabeled.edges[0].label;+ const baseline = compileWorkflow({ workflow: unlabeled, qualityProfile });+ assert.equal(baseline.ok, true);+ assert.deepEqual(verified.receipt.edges, baseline.receipt.edges, 'the explicit preset route must remain intact');+ assert.deepEqual(verified.receipt.nodes, baseline.receipt.nodes);+ assert.match(verified.svg, />成功后按需另行 Scan<\/text>/);+ const label = verified.receipt.labels[0];+ const rect = { x: label.x - label.width / 2, y: label.y - 10, width: label.width, height: label.height };+ for (const node of verified.receipt.nodes) {+ assert.ok(rect.x + rect.width <= node.x || rect.x >= node.x + node.width+ || rect.y + rect.height <= node.y || rect.y >= node.y + node.height,+ `the complete semantic label mask must clear node ${node.id}`);+ }+ });+}++test('readable-v2 preset label repair requires a complete same-profile pass', () => {+ const document = outsideRightLabelWorkflow();+ document.nodes[0].width = 132;+ document.nodes[0].sublabel = 'chain / debate / synthesis 调度';+ for (const col of [0, 1, 2, 3, 4]) {+ document.nodes.push({ id: `wide-${col}`, lane: 'undo', col, type: 'backend', label: `Step ${col}`, width: 200 });+ }+ const original = clone(document);+ const manuallyRepaired = clone(document);+ manuallyRepaired.edges[0].labelSegment = 1;+ const stillFailing = compileWorkflow({ workflow: manuallyRepaired, qualityProfile: 'showcase' });+ assert.equal(stillFailing.ok, false);+ assert.ok(stillFailing.diagnostics.some(({ code }) => code === 'workflow/sublabel-readability'));+ assert.ok(stillFailing.diagnostics.every(({ code }) => code !== 'workflow/route-preset-conflict'));+ const diagnostic = presetLabelDiagnostic(compileWorkflow({ workflow: document, qualityProfile: 'showcase' }));+ assert.ok(diagnostic.supportedFixes.every((fix) => !fix.startsWith('set labelSegment ')),+ 'clearing only the current label collision is not a verified full-workflow repair');+ assert.deepEqual(document, original);+});++test('readable-v2 preset label repair respects authored zero-valued controls', () => {+ for (const field of ['labelSegment', 'labelDx', 'labelDy']) {+ const document = outsideRightLabelWorkflow();+ document.edges[0][field] = 0;+ const original = clone(document);+ const diagnostic = presetLabelDiagnostic(compileWorkflow({ workflow: document, qualityProfile: 'standard' }));+ assert.ok(diagnostic.supportedFixes.every((fix) => !fix.startsWith('set labelSegment ')), `${field}: 0 is authored`);+ assert.deepEqual(document, original);+ }+});++test('workflow validate JSON exposes an executable preset label repair', (t) => {+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-preset-label-repair-'));+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));+ const input = path.join(directory, 'workflow.json');+ const cli = fileURLToPath(new URL('../archify/bin/archify.mjs', import.meta.url));+ const document = outsideRightLabelWorkflow();+ const original = JSON.stringify(document);+ fs.writeFileSync(input, original);+ const validate = () => spawnSync(process.execPath, [+ cli, 'validate', 'workflow', input, '--quality', 'showcase', '--json',+ ], { encoding: 'utf8' });+ const failed = validate();+ assert.equal(failed.status, 1, failed.stdout + failed.stderr);+ const receipt = JSON.parse(failed.stdout);+ const diagnostic = receipt.diagnostics.find(({ code }) => code === 'workflow/route-preset-conflict');+ assert.ok(diagnostic, failed.stdout);+ assert.equal(fs.readFileSync(input, 'utf8'), original);+ fs.writeFileSync(input, JSON.stringify(applySegmentSuggestion(document, diagnostic)));+ const passed = validate();+ assert.equal(passed.status, 0, passed.stdout + passed.stderr);+ const verified = JSON.parse(passed.stdout);+ assert.equal(verified.ok, true);+ assert.ok(verified.checks.length > 0 && verified.checks.every((check) => check.ok));+});+test('readable-v2 never accepts a same-lane drop through the preset-only fallback', () => {const document = oneLaneWorkflow([{id: 'ab',@@ -1415,6 +1596,17 @@ test('readable-v2 derives both causal pins when label plans before the authoreddiagnostic.supportedFixes.includes('remove via from edge "z-route" so readable-v2 can replan the remaining authored label-route pins'),JSON.stringify(diagnostic.supportedFixes, null, 2),);+ for (const fix of diagnostic.supportedFixes) {+ const repaired = clone(document);+ const replacement = fix.match(/^set labelAt on edge "a-label" to \[(-?\d+(?:\.\d+)?), (-?\d+(?:\.\d+)?)\]$/);+ if (replacement) repaired.edges[1].labelAt = replacement.slice(1).map(Number);+ else {+ assert.equal(fix, 'remove via from edge "z-route" so readable-v2 can replan the remaining authored label-route pins');+ delete repaired.edges[0].via;+ }+ const verified = compileWorkflow({ workflow: repaired });+ assert.equal(verified.ok, true, `advertised causal pin repair must pass public compilation: ${fix}\n${JSON.stringify(verified.diagnostics, null, 2)}`);+ }});test('readable-v2 classifies an authored labelAt colliding with an earlier automatic route', () => {@@ -2014,6 +2206,7 @@ test('readable-v2 never advertises an unverified blocking-node repair', () => {assert.equal(result.ok, false);const diagnostic = result.diagnostics.find(({ code }) => code === 'workflow/solver-budget-exhausted');assert.ok(diagnostic, JSON.stringify(result.diagnostics, null, 2));+ assert.deepEqual(result.receipt, { contract: result.receipt.contract, diagnostics: result.diagnostics });assert.deepEqual(diagnostic.supportedFixes, []);});@@ -2128,7 +2321,7 @@ test('compileWorkflow enforces the canonical workflow schema at its public boundassert.ok(result.diagnostics.every(({ supportedFixes }) => (Array.isArray(supportedFixes) && supportedFixes.length === 0)));- assert.deepEqual(result.receipt.diagnostics, result.diagnostics);+ assert.deepEqual(result.receipt, { contract: result.receipt.contract, diagnostics: result.diagnostics });}});@@ -2367,3 +2560,198 @@ test('fixed-v1 verifies the exact serialized values in every rounded-width repai);}});+++function rejectedLabelWorkflow() {+ const document = oneLaneWorkflow([{+ id: 'ab', from: 'a', to: 'b', label: 'send', labelAt: [88, 119],+ }]);+ document.schema_version = 1;+ document.meta.quality_profile = 'showcase';+ return document;+}++const rejectedLabelDiagnostic = {+ code: 'layout/constraint', severity: 'error',+ message: 'Label "send" overlaps node "a" — adjust labelDx/labelDy/labelSegment or set labelAt.\n label rect: [73, 109, 30, 14]\n node "a" rect: [42, 93, 92, 52]\n Suggested fix: set labelAt [88, 159] (below); or set labelAt [88, 85] (above)',+ subject: { diagramType: 'workflow' }, evidence: {}, supportedFixes: [],+};++test('rejected layout receipt retains complete fixed-v1 geometry and authored label coordinates', () => {+ const document = rejectedLabelWorkflow();+ const original = clone(document);+ for (const collection of [document.lanes, document.nodes, document.edges]) {+ collection.forEach(Object.freeze);+ Object.freeze(collection);+ }+ Object.freeze(document);+ const result = compileWorkflow({ workflow: document });+ assert.equal(result.ok, false);+ assert.equal(result.svg, undefined);+ assert.deepEqual(result.diagnostics, [rejectedLabelDiagnostic]);+ assert.equal(result.receipt.ok, false);+ assert.deepEqual(result.receipt.diagnostics, result.diagnostics);+ assert.equal(result.receipt.nodes.length, 2);+ assert.deepEqual(result.receipt.nodes[0], {+ id: 'a', lane: 'main', col: 0, x: 42, y: 93, width: 92, height: 52,+ });+ assert.deepEqual(result.receipt.edges, [{+ id: 'ab', from: 'a', to: 'b', points: [[134, 119], [254, 119]],+ }]);+ assert.deepEqual(result.receipt.labels, [{+ edge: 'ab', label: 'send', x: 88, y: 119, width: 30, height: 14,+ }]);+ assert.deepEqual(document, original);+ assert.equal(compileWorkflow({ workflow: oneLaneWorkflow([]) }).ok, true);+ assert.deepEqual(compileWorkflow({ workflow: document }).receipt, result.receipt);+});++test('rejected layout CLI receipt preserves failure diagnostics and writes no HTML', (t) => {+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-rejected-layout-'));+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));+ const input = path.join(directory, 'workflow.json');+ const document = rejectedLabelWorkflow();+ document.meta.output = 'must-not-write.html';+ const original = JSON.stringify(document);+ fs.writeFileSync(input, original);+ const cli = fileURLToPath(new URL('../archify/bin/archify.mjs', import.meta.url));+ for (const flags of [['--layout-json'], ['--layout-json', '--json']]) {+ const result = spawnSync(process.execPath, [cli, 'validate', 'workflow', input, ...flags], {+ encoding: 'utf8', cwd: directory,+ });+ assert.equal(result.status, 1, result.stdout + result.stderr);+ assert.equal(result.stderr, '');+ const receipt = JSON.parse(result.stdout);+ assert.equal(receipt.ok, false);+ assert.deepEqual(receipt.diagnostics, [rejectedLabelDiagnostic]);+ assert.equal(receipt.nodes.length, 2);+ assert.equal(receipt.edges.length, 1);+ assert.deepEqual(receipt.labels[0], {+ edge: 'ab', label: 'send', x: 88, y: 119, width: 30, height: 14,+ });+ assert.equal(fs.readFileSync(input, 'utf8'), original);+ assert.deepEqual(fs.readdirSync(directory), ['workflow.json']);+ }+});++test('rejected layout receipt retains the attempted readable-v2 frame and measured required frame', () => {+ const document = oneLaneWorkflow([{ id: 'ab', from: 'a', to: 'b', label: 'send' }]);+ document.meta.viewBox = [700, 300];+ document.nodes[1].col = 5;+ document.nodes[0].width = 200;+ document.nodes[1].width = 200;+ const result = compileWorkflow({ workflow: document, qualityProfile: 'standard' });+ assert.equal(result.ok, false);+ assert.equal(result.svg, undefined);+ assert.deepEqual(result.diagnostics.map(({ code }) => code), ['workflow/viewbox-capacity']);+ assert.equal(result.receipt.ok, false);+ assert.deepEqual(result.receipt.viewBox, document.meta.viewBox);+ assert.deepEqual(result.receipt.requiredViewBox, result.diagnostics[0].evidence.requiredViewBox);+ assert.ok(result.receipt.requiredViewBox[0] > result.receipt.viewBox[0]);+ assert.equal(result.receipt.nodes.length, document.nodes.length);+ assert.equal(result.receipt.edges.length, document.edges.length);+ assert.equal(result.receipt.labels.length, 1);+ assertOrthogonal(result.receipt.edges[0].points);+});++test('early causal failures retain diagnostic-only receipts after a complete rejected layout', () => {+ compileWorkflow({ workflow: rejectedLabelWorkflow() });+ for (const document of [+ { ...oneLaneWorkflow([]), semanticChecks: { allowedRoots: ['missing'] } },+ oneLaneWorkflow([{ id: 'unknown', from: 'a', to: 'missing' }]),+ { ...rejectedLabelWorkflow(), nodes: [+ { id: 'a', lane: 'main', col: 1, type: 'backend', label: 'A' },+ { id: 'b', lane: 'main', col: 2, type: 'backend', label: 'B' },+ ] },+ ]) {+ const result = compileWorkflow({ workflow: document });+ assert.equal(result.ok, false);+ assert.deepEqual(result.receipt, { contract: result.receipt.contract, diagnostics: result.diagnostics });+ }+});+++test('rejected layout receipt belongs to the selected best route-order attempt', (t) => {+ // The first plan crosses; retrying the later edge trades it for one shared+ // corridor. Equal error counts retain the first result, not the last routes.+ const document = workflow({+ lanes: [0, 1, 2, 3, 4].map((index) => ({ id: `l${index}`, label: `L${index}` })),+ nodes: [+ ['n3', 'l2', 3, 140], ['n5', 'l0', 3, 140],+ ['n6', 'l2', 4, 140], ['n7', 'l0', 4, 140],+ ['n8', 'l1', 5, 150], ['n9', 'l0', 5, 140],+ ['n11', 'l3', 4, 140], ['n12', 'l3', 5, 150],+ ].map(([id, lane, col, width]) => ({ id, lane, col, width, type: 'backend', label: id })),+ edges: [+ ['e05', 'n5', 'n6'], ['e06', 'n6', 'n7'], ['e07', 'n7', 'n6'],+ ['e08', 'n6', 'n8'], ['e10', 'n9', 'n3'], ['e13', 'n11', 'n6'],+ ].map(([id, from, to]) => ({ id, from, to })),+ });+ document.meta.quality_profile = 'showcase';+ const original = clone(document);+ const result = compileWorkflow({ workflow: document });+ assert.equal(result.ok, false);+ assert.equal(result.receipt.ok, false);+ assert.deepEqual(result.diagnostics.map(({ code }) => code), ['composition/proper-crossing']);+ const [diagnostic] = result.diagnostics;+ assert.equal(diagnostic.subject.id, 'e07');+ assert.equal(diagnostic.evidence.otherRelationship.id, 'e10');+ assert.equal(result.receipt.nodes.length, document.nodes.length);+ assert.equal(result.receipt.edges.length, document.edges.length);+ // Recompute the reported crossing from the returned segments. The final+ // retry's routes do not contain this crossing, so a mixed receipt fails.+ const first = result.receipt.edges.find(({ id }) => id === diagnostic.subject.id).points;+ const other = result.receipt.edges.find(({ id }) => id === diagnostic.evidence.otherRelationship.id).points;+ const i = diagnostic.evidence.segmentIndex;+ const j = diagnostic.evidence.otherSegmentIndex;+ assert.equal(first[i][1], first[i + 1][1]);+ assert.equal(other[j][0], other[j + 1][0]);+ const crossing = [other[j][0], first[i][1]];+ assert.deepEqual(crossing, diagnostic.evidence.point);+ assert.ok(crossing[0] > Math.min(first[i][0], first[i + 1][0])+ && crossing[0] < Math.max(first[i][0], first[i + 1][0]));+ assert.ok(crossing[1] > Math.min(other[j][1], other[j + 1][1])+ && crossing[1] < Math.max(other[j][1], other[j + 1][1]));+ assert.deepEqual(document, original);++ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-selected-workflow-attempt-'));+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));+ const input = path.join(directory, 'workflow.json');+ const inputBytes = JSON.stringify(document);+ fs.writeFileSync(input, inputBytes);+ const cli = fileURLToPath(new URL('../archify/bin/archify.mjs', import.meta.url));+ const failures = [[], ['--layout-json']].map((flags) => {+ const validation = spawnSync(process.execPath, [+ cli, 'validate', 'workflow', input, '--quality', 'showcase', '--json', ...flags,+ ], { encoding: 'utf8', cwd: directory });+ assert.equal(validation.status, 1, validation.stdout + validation.stderr);+ assert.equal(validation.stderr, '');+ const failure = JSON.parse(validation.stdout);+ assert.equal(failure.ok, false);+ assert.equal(fs.readFileSync(input, 'utf8'), inputBytes);+ assert.deepEqual(fs.readdirSync(directory), ['workflow.json']);+ return failure;+ });+ // Both public views must describe the selected routes. Discarded attempts+ // cannot contribute a repair target absent from the returned layout.+ assert.deepEqual(failures[1].diagnostics, result.diagnostics);+ assert.deepEqual(failures[0].diagnostics, failures[1].diagnostics);+});+++test('rejected fixed-v1 label overflow reports its footprint without changing the attempted canvas', () => {+ const document = rejectedLabelWorkflow();+ document.edges[0].labelAt = [760, 220];+ const result = compileWorkflow({ workflow: document });+ assert.equal(result.ok, false);+ assert.equal(result.svg, undefined);+ assert.equal(result.receipt.ok, false);+ assert.equal(result.receipt.viewBox[0], 720);+ // 760px anchor + half the 30px mask + the existing 16px canvas margin.+ assert.equal(result.receipt.requiredViewBox[0], 791);+ assert.deepEqual(result.receipt.labels[0], {+ edge: 'ab', label: 'send', x: 760, y: 220, width: 30, height: 14,+ });+ assert.equal(result.diagnostics[0].code, 'layout/constraint');+ assert.match(result.diagnostics[0].message, /composition\/label-canvas-containment.*right edge by 55px/);+});diff --git a/test/workflow-compiler.test.mjs b/test/workflow-compiler.test.mjsindex 3b80c847..7c17cb9f 100644--- a/test/workflow-compiler.test.mjs+++ b/test/workflow-compiler.test.mjs@@ -27,7 +27,8 @@ function sha256(value) {}// #199 intentionally changes only text positions inside fixed-v1 nodes.-// Pin every other SVG byte to the pre-fix baseline, including labels, fonts,+// Compatibility digests also include the approved ordinary lane-heading ink.+// Pin every other SVG byte, including labels, fonts,// node bounds, icon shapes, edges, ports, viewBox and accessibility metadata.function withoutNodeTextPositions(svg) {// Default motion adds presentation hooks; keep the original geometry digest.@@ -328,7 +329,7 @@ test('fixed-v1 preserves baseline SVG except repaired node text positions', () =assert.equal(result.receipt.contract, 'fixed-v1');assert.equal(sha256(withoutNodeTextPositions(result.svg)),- 'e64795a4521e8568718981bf053c6e8f4e0cf714e27f70f0087d1850ae1fe633',+ '92b23cf7eadf0420afe7a9e7f11e29f08ed69cd4be4450656ab6e54d43ccee92',);});@@ -345,7 +346,7 @@ test('fixed-v1 compiler preserves the exact 700x400 compatibility geometry', ()assert.deepEqual(svgViewBox(result.svg), [0, 0, 700, 400]);assert.equal(sha256(withoutNodeTextPositions(result.svg)),- '79ac3e30f9e81263f9c7941339a6fe684f3a33dd2ac3ce4f7281a03fa2ee1c6b',+ '26529a40e65f18d246e9129af0e57aca09cc3561539dc0cdac3e38310c248cea','the clearance repair must not move or reserialize legacy geometry outside node text',);});@@ -358,9 +359,10 @@ test('readable-v2 separates approval branches in the checked-in workflow exampleassert.equal(// approval-denied and approved-tool keep separate trunks. Neighbouring// columns now keep a 32px route corridor, which widens the canvas by 12px,- // and tags keep their 7px preferred size.+ // and tags keep their 7px preferred size. The digest includes the approved+ // ordinary lane-heading ink.sha256(result.svg.replace(/ data-(?:composition-routing|edge-role|layout-contract)="[^"]*"/g, '')),- '09ece2904db9a525bd5990f896ab6f335b48cd7617beb6a47868874a17e94774',+ '23257ef301e6ac7385010960d531b55416361883ac0c87f7b3ed8f5f62294d24',);});diff --git a/test/workflow-counterflow-spacing.test.mjs b/test/workflow-counterflow-spacing.test.mjsnew file mode 100644index 00000000..e25b7204--- /dev/null+++ b/test/workflow-counterflow-spacing.test.mjs@@ -0,0 +1,151 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { compileWorkflow } from '../archify/renderers/workflow/workflow-compiler.mjs';++function libraryApproval() {+ return {+ schema_version: 2, diagram_type: 'workflow',+ meta: { title: 'Library approval routing', output: 'library.html', quality_profile: 'showcase' },+ lanes: [{ id: 'desk', label: 'Approval desk' }, { id: 'review', label: 'Book review' }, { id: 'delivery', label: 'Delivery' }],+ nodes: [+ { id: 'special', lane: 'desk', col: 2, type: 'backend', label: 'Special review', yOffset: 100, width: 136 },+ { id: 'regular', lane: 'desk', col: 2, type: 'backend', label: 'Regular review' },+ { id: 'queue', lane: 'desk', col: 3, type: 'backend', label: 'Lending queue', width: 132 },+ { id: 'issue', lane: 'delivery', col: 3, type: 'backend', label: 'Issue book' },+ { id: 'inspection', lane: 'review', col: 4, type: 'backend', label: 'Inspection' },+ { id: 'shelf', lane: 'delivery', col: 5, type: 'backend', label: 'Shelf record', yOffset: 100 },+ { id: 'request', lane: 'desk', col: 1, type: 'backend', label: 'Request' },+ ],+ edges: [+ { id: 'release', from: 'queue', to: 'issue', label: 'release book', fromSide: 'bottom', toSide: 'top' },+ { id: 'special-queue', from: 'special', to: 'queue', label: 'reviewed', role: 'branch' },+ { id: 'regular-queue', from: 'regular', to: 'queue' },+ { id: 'a-shelf', from: 'inspection', to: 'shelf', label: 'record checked book', fromSide: 'bottom', toSide: 'top' },+ { id: 'a-special', from: 'request', to: 'special', label: 'special review', role: 'branch' },+ { id: 'a-regular', from: 'request', to: 'regular', label: 'regular' },+ ],+ };+}++const route = (result, id) => result.receipt.edges.find((edge) => edge.id === id).points;+const routeLength = (points) => points.slice(1).reduce((total, point, index) => total+ + Math.hypot(point[0] - points[index][0], point[1] - points[index][1]), 0);++function parallelWitness({ overlap = 56, gap = 3.5, sameDirection = false, split = false } = {}) {+ const track = 214 + gap;+ const low = 209 - overlap;+ const via = sameDirection+ ? [[454, low], [track, low], [track, 209], [454, 209]]+ : [[454, 209], [track, 209],+ ...(split ? [[track, 209 - overlap / 3], [track, 209 - 2 * overlap / 3]] : []),+ [track, low], [454, low]];+ return {+ schema_version: 2, diagram_type: 'workflow',+ meta: { title: 'Parallel return controls', output: 'parallel.html', quality_profile: 'showcase', legend: { mode: 'hidden' } },+ lanes: [{ id: 'top', label: 'Top' }, { id: 'bottom', label: 'Bottom' }],+ nodes: [+ { id: 'a', lane: 'top', col: 1, type: 'backend', label: 'A' },+ { id: 'b', lane: 'bottom', col: 1, type: 'backend', label: 'B' },+ { id: 'c', lane: 'bottom', col: 3, type: 'backend', label: 'C' },+ { id: 'd', lane: 'top', col: 3, type: 'backend', label: 'D' },+ ],+ edges: [+ { id: 'z-auto', from: 'a', to: 'b', fromSide: 'bottom', toSide: 'top' },+ { id: 'a-witness', from: sameDirection ? 'd' : 'c', to: sameDirection ? 'c' : 'd',+ fromSide: sameDirection ? 'bottom' : 'top', toSide: sameDirection ? 'top' : 'bottom', via },+ ],+ };+}++function longOppositeVerticalNeighbours(left, right) {+ const hits = [];+ for (let a = 1; a < left.length; a += 1) {+ for (let b = 1; b < right.length; b += 1) {+ if (left[a][0] !== left[a - 1][0] || right[b][0] !== right[b - 1][0]) continue;+ if ((left[a][1] - left[a - 1][1]) * (right[b][1] - right[b - 1][1]) >= 0) continue;+ const overlap = Math.min(Math.max(left[a][1], left[a - 1][1]), Math.max(right[b][1], right[b - 1][1]))+ - Math.max(Math.min(left[a][1], left[a - 1][1]), Math.min(right[b][1], right[b - 1][1]));+ const gap = Math.abs(left[a][0] - right[b][0]);+ if (overlap > 24 && gap < 8) hits.push({ overlap, gap });+ }+ }+ return hits;+}++test('automatic workflow routes separate long opposite-direction neighbours while preserving authored sides', () => {+ for (const qualityProfile of ['standard', 'showcase']) {+ const workflow = libraryApproval();+ const before = JSON.stringify(workflow);+ const result = compileWorkflow({ workflow, qualityProfile });+ assert.equal(result.ok, true, JSON.stringify(result.diagnostics));+ assert.deepEqual(result.receipt.diagnostics, []);+ assert.deepEqual(longOppositeVerticalNeighbours(route(result, 'special-queue'), route(result, 'release')), []);+ assert.equal(JSON.stringify(workflow), before);+ const release = route(result, 'release');+ const source = result.receipt.nodes.find(({ id }) => id === 'queue');+ const target = result.receipt.nodes.find(({ id }) => id === 'issue');+ assert.equal(release[0][1], source.y + source.height);+ assert.ok(release[1][1] > release[0][1]);+ assert.equal(release.at(-1)[1], target.y);+ assert.ok(release.at(-2)[1] < target.y);+ assert.equal(result.receipt.nodes.length, workflow.nodes.length);+ assert.deepEqual(result.receipt.edges.map(({ id, from, to }) => [id, from, to]).sort(), workflow.edges.map(({ id, from, to }) => [id, from, to]).sort());+ for (const node of workflow.nodes) assert.ok(result.svg.includes(`>${node.label}</text>`), node.label);+ for (const edge of workflow.edges.filter(({ label }) => label)) assert.ok(result.svg.includes(`>${edge.label}</text>`), edge.label);+ }+});++test('counterflow route preference remains deterministic after repeated compilation and input reordering', () => {+ const workflow = libraryApproval();+ const first = compileWorkflow({ workflow });+ assert.equal(first.ok, true, JSON.stringify(first.diagnostics));+ assert.deepEqual(compileWorkflow({ workflow }), first);+ workflow.nodes.reverse();+ workflow.edges.reverse();+ assert.deepEqual(compileWorkflow({ workflow }), first);+});++test('a side-constrained automatic route can avoid the earlier branch when edge IDs reverse their order', () => {+ const workflow = libraryApproval();+ workflow.edges.find(({ id }) => id === 'release').id = 'zz-release';+ const before = JSON.stringify(workflow);+ const result = compileWorkflow({ workflow });+ assert.equal(result.ok, true, JSON.stringify(result.diagnostics));+ assert.deepEqual(longOppositeVerticalNeighbours(route(result, 'special-queue'), route(result, 'zz-release')), []);+ const release = route(result, 'zz-release');+ const source = result.receipt.nodes.find(({ id }) => id === 'queue');+ const target = result.receipt.nodes.find(({ id }) => id === 'issue');+ assert.equal(release[0][1], source.y + source.height);+ assert.ok(release[1][1] > release[0][1]);+ assert.equal(release.at(-1)[1], target.y);+ assert.ok(release.at(-2)[1] < target.y);+ assert.equal(JSON.stringify(workflow), before);+});++test('same-direction, short opposite runs and the outer spacing boundary retain compact routes', () => {+ for (const options of [{ sameDirection: true }, { overlap: 24 }, { gap: 8 }]) {+ const workflow = parallelWitness(options);+ const before = JSON.stringify(workflow);+ const result = compileWorkflow({ workflow });+ assert.equal(result.ok, true, JSON.stringify(result.diagnostics));+ assert.ok(routeLength(route(result, 'z-auto')) <= 80, 'a clear 72px route should stay compact');+ assert.deepEqual(route(result, 'a-witness').slice(1, -1), workflow.edges[1].via);+ assert.equal(JSON.stringify(workflow), before);+ }+});++test('long opposite runs stay visible to routing across redundant authored waypoints', () => {+ let unsplit;+ for (const split of [false, true]) {+ const workflow = parallelWitness({ split });+ const before = JSON.stringify(workflow);+ const result = compileWorkflow({ workflow });+ assert.equal(result.ok, true, JSON.stringify(result.diagnostics));+ assert.deepEqual(route(result, 'a-witness').slice(1, -1), workflow.edges[1].via);+ const witnessRun = [[217.5, 209], [217.5, 153]];+ assert.deepEqual(longOppositeVerticalNeighbours(route(result, 'z-auto'), witnessRun), []);+ if (split) assert.deepEqual(route(result, 'z-auto'), unsplit);+ else unsplit = route(result, 'z-auto');+ assert.equal(JSON.stringify(workflow), before);+ }+});diff --git a/test/workflow-edge-label-contrast-browser.test.mjs b/test/workflow-edge-label-contrast-browser.test.mjsnew file mode 100644index 00000000..787d8acc--- /dev/null+++ b/test/workflow-edge-label-contrast-browser.test.mjs@@ -0,0 +1,189 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { execFileSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { ChromeVisualBrowser, findChrome } from '../archify/bin/visual-check.mjs';++const cli = fileURLToPath(new URL('../archify/bin/archify.mjs', import.meta.url));++test('workflow default labels and lane headings remain readable without recoloring semantic ink', async (t) => {+ if (!Object.hasOwn(process.env, 'ARCHIFY_CHROME')) return t.skip('Set ARCHIFY_CHROME for real browser checks');+ const chrome = findChrome();+ assert.ok(chrome, 'The configured browser regression requires Chrome');+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-workflow-label-contrast-'));+ t.after(() => fs.rmSync(scratch, { recursive: true, force: true }));+ const input = path.join(scratch, 'workflow.json');+ const artifact = path.join(scratch, 'workflow.html');+ const variants = [undefined, 'default', 'emphasis', 'security', 'dashed'];+ fs.writeFileSync(input, JSON.stringify({+ schema_version: 2, diagram_type: 'workflow',+ meta: { title: 'Workflow label contrast', output: 'workflow.html', quality_profile: 'standard' },+ lanes: [+ { id: 'work', label: 'Work' },+ { id: 'normal', label: 'Normal', variant: 'normal' },+ { id: 'exception', label: 'Exception', variant: 'exception' },+ ],+ nodes: [...Array.from({ length: 6 }, (_, col) => ({+ id: `n${col}`, lane: 'work', col, type: 'backend', label: `Step ${col + 1}`,+ })),+ { id: 'normal-node', lane: 'normal', col: 0, type: 'backend', label: 'Normal node' },+ { id: 'exception-node', lane: 'exception', col: 0, type: 'security', label: 'Exception node' },+ ],+ edges: variants.map((variant, index) => ({+ id: `e${index}`, from: `n${index}`, to: `n${index + 1}`, label: `L${index}`,+ ...(variant ? { variant } : {}),+ })),+ }));+ execFileSync(process.execPath, [cli, 'render', 'workflow', input, artifact]);+ const browser = new ChromeVisualBrowser(chrome);+ t.after(() => browser.close());+ const session = await browser.sessionPromise;+ for (const theme of ['light', 'dark']) {+ await t.test(`${theme} Full-detail labels and normal lane headings meet classic contrast`, async () => {+ await browser.inspect({ artifactPath: artifact, width: 1440, height: 1100, theme });+ const evaluated = await browser.cdp.send('Runtime.evaluate', {+ awaitPromise: true, returnByValue: true,+ expression: `(async () => {+ await document.fonts.ready;+ Archify.view.reveal([...document.querySelectorAll('[data-node-id]')].map(node => node.dataset.nodeId), { instant: true, maxScale: 1 });+ const panel = document.querySelector('.diagram-container');+ await Promise.all(panel.getAnimations({ subtree: true }).map(animation => animation.finished.catch(() => {})));+ const rgba = value => {+ const parts = value.match(/[\\d.]+/g).map(Number);+ return [...parts.slice(0, 3), parts[3] ?? 1];+ };+ const luminance = rgb => rgb.slice(0, 3).map(c => {+ c /= 255;+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;+ }).reduce((sum, c, i) => sum + c * [0.2126, 0.7152, 0.0722][i], 0);+ const over = (foreground, background, alpha = foreground[3]) =>+ foreground.slice(0, 3).map((c, i) => c * alpha + background[i] * (1 - alpha));+ const contrast = (foreground, background) => {+ const a = luminance(foreground), b = luminance(background);+ return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);+ };+ const surface = getComputedStyle(panel), body = getComputedStyle(document.body);+ const dotColors = surface.backgroundImage.match(/rgba?\\([^)]*\\)/g) || [];+ const dot = dotColors.length === 2 ? rgba(dotColors[0]) : null;+ const beneathPanel = [];+ for (let node = panel.parentElement; node && node !== document.body; node = node.parentElement) {+ const style = getComputedStyle(node);+ beneathPanel.push({ color: style.backgroundColor, image: style.backgroundImage, opacity: style.opacity });+ }+ const panelBackground = over(rgba(surface.backgroundColor), rgba(body.backgroundColor));+ // A peak CSS dot covers the panel before the translucent SVG lane.+ // This bounds the declared gradient colors, not sampled glyph pixels.+ const dotBackground = dot ? over(dot, panelBackground) : null;+ const lanes = [...panel.querySelectorAll('[data-composition-frame-kind="lane"]')].map(frame => {+ let text = frame.nextElementSibling;+ const exceptionFrame = text.matches('[data-composition-frame-kind="exception-lane"]') ? text : null;+ if (exceptionFrame) text = text.nextElementSibling;+ const ink = getComputedStyle(text), plate = getComputedStyle(frame), foreground = rgba(ink.fill);+ const laneFill = rgba(plate.fill), laneAlpha = laneFill[3] * Number(plate.fillOpacity);+ const flat = over(laneFill, panelBackground, laneAlpha);+ const peak = dotBackground && over(laneFill, dotBackground, laneAlpha);+ const inkAlpha = foreground[3] * Number(ink.fillOpacity);+ const opacity = [];+ for (let node = text; node; node = node.parentElement) opacity.push(Number(getComputedStyle(node).opacity));+ return { label: text.textContent, fill: ink.fill, fontSize: ink.fontSize, fontWeight: ink.fontWeight,+ visibility: ink.visibility, display: ink.display, opacity, laneOpacity: Number(plate.opacity),+ flatBackground: flat, dotPeakBackground: peak,+ flatRatio: contrast(over(foreground, flat, inkAlpha), flat),+ dotPeakRatio: peak && contrast(over(foreground, peak, inkAlpha), peak),+ exceptionStroke: exceptionFrame && getComputedStyle(exceptionFrame).stroke,+ exceptionClass: exceptionFrame && text.getAttribute('class') };+ });+ const edges = Array.from({ length: 5 }, (_, index) => {+ const route = document.querySelector('path[data-edge-id="e' + index + '"]');+ const group = document.querySelector('g[data-edge-id="e' + index + '"]');+ const text = group.querySelector('text'), mask = group.querySelector('rect.c-mask');+ const ink = getComputedStyle(text), plate = getComputedStyle(mask);+ const foreground = rgba(ink.fill), background = rgba(plate.fill);+ const alpha = foreground[3] * Number(ink.fillOpacity);+ const rendered = foreground.slice(0, 3).map((c, i) => c * alpha + background[i] * (1 - alpha));+ const a = luminance(rendered), b = luminance(background);+ const opacity = [];+ for (let node = text; node; node = node.parentElement) opacity.push(Number(getComputedStyle(node).opacity));+ const marker = route.getAttribute('marker-end').match(/#([^)]*)/)[1];+ return { index, label: text.textContent, labelClass: text.getAttribute('class'),+ fill: ink.fill, fontSize: ink.fontSize, visibility: ink.visibility, display: ink.display, opacity,+ maskAlpha: background[3] * Number(plate.fillOpacity) * Number(plate.opacity),+ pathClass: route.getAttribute('class'), stroke: getComputedStyle(route).stroke,+ markerFill: getComputedStyle(document.getElementById(marker).querySelector('polygon')).fill,+ foreground: rendered, background: background.slice(0, 3),+ ratio: (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05) };+ });+ return { theme: document.documentElement.dataset.theme, preset: document.documentElement.dataset.preset,+ motion: document.documentElement.dataset.motion,+ detail: panel.dataset.detailLevel, scale: Archify.view.state().scale, edges, lanes, beneathPanel,+ surface: { image: surface.backgroundImage,+ bodyImage: body.backgroundImage, bodyAlpha: rgba(body.backgroundColor)[3], dotColors,+ dotEndAlpha: dotColors.length === 2 ? rgba(dotColors[1])[3] : null,+ svgBackground: getComputedStyle(panel.querySelector('svg')).backgroundColor,+ svgImage: getComputedStyle(panel.querySelector('svg')).backgroundImage,+ gridStrokes: [...panel.querySelectorAll('.c-grid')].map(grid => getComputedStyle(grid).stroke) } };+ })()`,+ }, session);+ assert.equal(evaluated.exceptionDetails, undefined, evaluated.exceptionDetails?.exception?.description);+ const observed = evaluated.result.value;+ assert.equal(observed.theme, theme);+ assert.equal(observed.preset, 'classic');+ assert.equal(observed.motion, 'still');+ assert.equal(observed.detail, 'full');+ assert.equal(observed.scale, 1);+ assert.equal(observed.surface.bodyImage, 'none', 'the classic body has a flat opaque base');+ assert.equal(observed.surface.bodyAlpha, 1);+ assert.equal(observed.surface.svgBackground, 'rgba(0, 0, 0, 0)');+ assert.equal(observed.surface.svgImage, 'none');+ assert.ok(observed.beneathPanel.every(surface => surface.color === 'rgba(0, 0, 0, 0)'+ && surface.image === 'none' && Number(surface.opacity) === 1), 'no intervening ancestor surface changes the backdrop');+ assert.match(observed.surface.image, /^radial-gradient\([^()]*rgba?\([^)]*\)[^()]*rgba?\([^)]*\)[^()]*\)(?:,\s*none)?$/,+ 'the peak model requires a single radial gradient with no extra image layer');+ assert.equal(observed.surface.dotColors.length, 2, 'model the actual two-stop CSS dot rule');+ assert.equal(observed.surface.dotEndAlpha, 0, 'the dot blends to a transparent endpoint');+ assert.ok(observed.surface.gridStrokes.every(stroke => stroke === 'rgba(0, 0, 0, 0)'), 'classic SVG grid adds no visible ink');+ assert.deepEqual(observed.lanes.map(lane => lane.label), ['01 / Work', '02 / Normal', 'EX / Exception']);+ for (const lane of observed.lanes) {+ assert.equal(lane.fontSize, '10px');+ assert.equal(lane.fontWeight, '600');+ assert.ok(lane.opacity.every(value => value === 1));+ assert.equal(lane.laneOpacity, 1);+ assert.notEqual(lane.visibility, 'hidden');+ assert.notEqual(lane.display, 'none');+ }+ assert.equal(observed.lanes[2].exceptionClass, 't-security');+ assert.equal(observed.lanes[2].fill, observed.lanes[2].exceptionStroke, 'EX heading retains its semantic frame ink');+ assert.equal(observed.lanes[0].fill, observed.lanes[1].fill, 'default and explicit normal headings share their ink');+ for (const lane of observed.lanes.slice(0, 2)) {+ t.diagnostic(`${theme} ${lane.label}: flat ${lane.flatRatio.toFixed(6)}:1, CSS dot peak ${lane.dotPeakRatio.toFixed(6)}:1; fill ${lane.fill}; flat background ${lane.flatBackground}; dot peak background ${lane.dotPeakBackground}`);+ }+ for (const edge of observed.edges) {+ const variant = variants[edge.index] || 'default';+ assert.equal(edge.label, `L${edge.index}`);+ assert.equal(edge.fontSize, '8px');+ assert.ok(edge.opacity.every(value => value === 1), 'measure visible text through opaque ancestors');+ assert.notEqual(edge.visibility, 'hidden');+ assert.notEqual(edge.display, 'none');+ assert.equal(edge.maskAlpha, 1, 'the existing opaque plate is the actual text background');+ assert.equal(edge.pathClass, `a-${variant}`);+ assert.equal(edge.markerFill, edge.stroke, 'arrowheads retain the connector color');+ if (edge.index < 2) {+ assert.ok(Number.isFinite(edge.ratio), 'the measured contrast is finite');+ assert.equal(edge.stroke, theme === 'light' ? 'rgb(148, 163, 184)' : 'rgb(100, 116, 139)', 'default connectors retain their existing ink');+ t.diagnostic(`${theme} ${edge.index === 0 ? 'fallback' : 'default'} label: ${edge.ratio.toFixed(3)}:1; foreground ${edge.foreground}; background ${edge.background}`);+ } else {+ assert.equal(edge.labelClass, `t-edge-${variant}`);+ assert.equal(edge.fill, edge.stroke, 'colored labels retain the semantic connector color');+ }+ }+ assert.ok(observed.edges.slice(0, 2).every(edge => edge.ratio >= 4.5),+ `default/fallback labels must have at least 4.5:1 contrast: ${JSON.stringify(observed.edges.slice(0, 2))}`);+ assert.ok(observed.lanes.slice(0, 2).every(lane => Number.isFinite(lane.flatRatio)+ && Number.isFinite(lane.dotPeakRatio) && lane.flatRatio >= 4.5 && lane.dotPeakRatio >= 4.5),+ `classic normal headings must have at least 4.5:1 flat and CSS dot peak contrast: ${JSON.stringify(observed.lanes.slice(0, 2))}`);+ });+ }+});