Skip to content

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

feat(readability): keep first drafts readable through a joint layout wait

tt-a1i4a999a360389
diff --git a/archify/assets/template.html b/archify/assets/template.html
index 21c1e089..28fe75fe 100644
--- a/archify/assets/template.html
+++ b/archify/assets/template.html
@@ -4,6 +4,7 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="archify 2.17.0-dev.1">
+ <meta name="archify-reader-contract" content="declared-wide-v1">
<title>[PROJECT NAME] Architecture Diagram</title>
<script>
// Resolve the theme before first paint so light-preference users don't
@@ -11202,6 +11203,8 @@ OTHER DEALINGS IN THE FONT SOFTWARE.
embed, presentation, print, and unmarked non-wide diagrams retain their own
established layout contracts.
============================================================ */
+ // Fixed script-private participants; the CLI sees only the joint wait below.
+ const archifyLayoutOwners = { reader: null, viewerChrome: null };
Archify.waitForStableLayout = function (options) {
options = options || {};
var maximumFrames = Math.max(1, Number(options.maximumFrames) || 240);
@@ -11287,9 +11290,13 @@ OTHER DEALINGS IN THE FONT SOFTWARE.
}
function minimumReadableScale() {
var sourceMinimum = null;
- Array.from(svg.querySelectorAll(
+ var selectors = [
'text[data-node-label], text[data-boundary-label], text[data-detail="context"]'
- )).forEach(function (text) {
+ ];
+ if (measuredHeightFit && ratio >= WIDE_RATIO && Number.isFinite(declaredMinimumText)) {
+ selectors.push('g[data-detail="context"][data-edge-from][data-edge-to] > text');
+ }
+ Array.from(svg.querySelectorAll(selectors.join(', '))).forEach(function (text) {
if (text.getAttribute('data-detail') === 'context' && !text.closest('[data-node-id]')) return;
var sourceFontPx = parseFloat(text.getAttribute('font-size') || '');
if (Number.isFinite(sourceFontPx)) {
@@ -11365,11 +11372,20 @@ OTHER DEALINGS IN THE FONT SOFTWARE.
var readableWidth = viewBox && viewBox.width > 0
? viewBox.width * minimumReadableScale() + chrome.diagramX
: MIN_READER_WIDTH;
- var minWidth = Math.min(
- measuredHeightFit && ratio < WIDE_RATIO ? readableWidth : MIN_READER_WIDTH,
- viewportCap
- );
var maxWidth = Math.min(MAX_READER_WIDTH, viewportCap);
+ var readableMinimumWidth = measuredHeightFit && ratio < WIDE_RATIO
+ ? readableWidth
+ : measuredHeightFit && ratio >= WIDE_RATIO && Number.isFinite(declaredMinimumText)
+ ? Math.max(MIN_READER_WIDTH, readableWidth)
+ : MIN_READER_WIDTH;
+ var minWidth;
+ if (measuredHeightFit && ratio < WIDE_RATIO) {
+ minWidth = Math.min(readableMinimumWidth, viewportCap);
+ } else if (measuredHeightFit && ratio >= WIDE_RATIO && Number.isFinite(declaredMinimumText)) {
+ minWidth = Math.min(readableMinimumWidth, maxWidth);
+ } else {
+ minWidth = Math.min(readableMinimumWidth, viewportCap);
+ }
var fixedHeight = chrome.bodyY + chrome.diagramY + SAFE_BOTTOM_GAP +
outerHeight(header) + outerHeight(guided) + outerHeight(cards);
var availableSvgHeight = Math.max(1, window.innerHeight - fixedHeight);
@@ -11405,14 +11421,16 @@ OTHER DEALINGS IN THE FONT SOFTWARE.
Math.round(diagramRect.height * 100) / 100
].join('|');
}
+ function layoutPending() { return Boolean(frame || settleFrame); }
function whenStable() {
return Archify.waitForStableLayout({
schedule: schedule,
- pending: function () { return Boolean(frame || settleFrame); },
+ pending: layoutPending,
snapshot: stableSnapshot,
timeoutMessage: 'Adaptive reader layout did not reach stable dimensions.'
});
}
+ archifyLayoutOwners.reader = { schedule: schedule, pending: layoutPending, snapshot: stableSnapshot };
window.addEventListener('resize', schedule, { passive: true });
window.addEventListener('load', schedule, { once: true });
@@ -11707,14 +11725,16 @@ OTHER DEALINGS IN THE FONT SOFTWARE.
lastReceipt ? lastReceipt.stageGap : ''
].join('|');
}
+ function layoutPending() { return Boolean(frame || settleFrame || probingBaseline); }
function whenStable() {
return Archify.waitForStableLayout({
schedule: schedule,
- pending: function () { return Boolean(frame || settleFrame || probingBaseline); },
+ pending: layoutPending,
snapshot: stableSnapshot,
timeoutMessage: 'Viewer chrome layout did not reach stable dimensions.'
});
}
+ archifyLayoutOwners.viewerChrome = { schedule: schedule, pending: layoutPending, snapshot: stableSnapshot };
window.addEventListener('resize', reprobe, { passive: true });
window.addEventListener('load', schedule, { once: true });
@@ -11750,6 +11770,49 @@ OTHER DEALINGS IN THE FONT SOFTWARE.
};
})();
+ Archify.layoutStability = {
+ whenStable: function () {
+ var reader = archifyLayoutOwners.reader;
+ var chrome = archifyLayoutOwners.viewerChrome;
+ if (!reader || !chrome) {
+ return Promise.reject(new Error('Joint layout owners are unavailable.'));
+ }
+ var observedFontsReady = document.fonts && document.fonts.ready;
+ var fontCyclePending = false;
+ var fontGeneration = 0;
+ function scheduleOwners() { reader.schedule(); chrome.schedule(); }
+ function fontsPending() {
+ var fonts = document.fonts;
+ var ready = fonts && fonts.ready;
+ if (ready && (ready !== observedFontsReady || (fonts.status === 'loading' && !fontCyclePending))) {
+ observedFontsReady = ready;
+ fontCyclePending = true;
+ var generation = ++fontGeneration;
+ ready.catch(function () {}).then(function () {
+ if (generation !== fontGeneration) return;
+ fontCyclePending = false;
+ scheduleOwners();
+ });
+ }
+ return fontCyclePending || Boolean(fonts && fonts.status === 'loading');
+ }
+ return Archify.waitForStableLayout({
+ maximumFrames: 960,
+ schedule: scheduleOwners,
+ pending: function () {
+ // Recapture readiness for font cycles that begin during sampling.
+ return fontsPending() || reader.pending() || chrome.pending();
+ },
+ snapshot: function () {
+ return JSON.stringify([
+ ['reader', reader.snapshot()],
+ ['viewerChrome', chrome.snapshot()]
+ ]);
+ },
+ timeoutMessage: 'Joint reader and viewer chrome layout did not reach stable dimensions.'
+ });
+ }
+ };
Archify.view = (function () {
var container = document.querySelector('.diagram-container');
var svg = container.querySelector('svg');
diff --git a/archify/bin/archify.mjs b/archify/bin/archify.mjs
index be1b6d8f..7296264e 100755
--- a/archify/bin/archify.mjs
+++ b/archify/bin/archify.mjs
@@ -2610,7 +2610,6 @@ const COMPOSITION_FIXES = {
'composition/container-border-run': ['route across the frame perpendicularly through a clear opening'],
'composition/label-route-clearance': ['adjust labelAt, labelDx, labelDy, labelSegment, message y, or the other relationship route'],
'composition/label-canvas-containment': ['adjust labelAt, labelDx, labelDy, or labelSegment so the label rect stays inside the viewBox, or enlarge meta.viewBox'],
- 'composition/desktop-readability': ['reduce the viewBox width, shorten node copy, widen affected nodes, or split the diagram so node context remains at least 6px at a 1440px desktop viewport'],
'composition/micro-segment': ['move the route/channel/via point so every visible segment is at least 8px'],
'composition/short-interior-segment': ['move the route/channel/via point so every interior turn has at least 16px'],
};
@@ -2626,7 +2625,7 @@ function checkerDiagnostics(checker) {
message: `Final artifact failed ${code}.`,
subject: relationship ? { relationship } : { check: 'composition', ...(nodeId ? { nodeId } : {}) },
evidence,
- supportedFixes: COMPOSITION_FIXES[code] || [],
+ supportedFixes: compositionFixes(issue),
}));
}
for (const check of checker?.checks || []) {
@@ -2647,6 +2646,27 @@ function checkerDiagnostics(checker) {
})];
}
+function compositionFixes(issue) {
+ if (issue.code !== 'composition/desktop-readability') return COMPOSITION_FIXES[issue.code] || [];
+ const sourceFontPx = Number(issue.sourceFontPx);
+ const actualBudgetPx = Number(issue.availableDiagramWidth);
+ const hardFloorPx = Number(issue.minimumProjectedFontPx);
+ const viewBoxWidth = Number(issue.viewBoxWidth);
+ const preserveIntent = 'Preserve the semantic text and any supplied coordinates, routes, sides, channels, and labels.';
+ const readerCap = issue.budgetBasis === 'recognized-declared-wide'
+ ? ` The declared Reader reports a ${issue.budgetLimit} limit and ${actualBudgetPx}px actual diagram budget; do not assume an uncapped viewport.`
+ : '';
+ if (![sourceFontPx, actualBudgetPx, hardFloorPx, viewBoxWidth].every(Number.isFinite)
+ || actualBudgetPx <= 0 || hardFloorPx <= 0 || viewBoxWidth <= 0) {
+ return [`${preserveIntent} Repair the measured source font, desktop budget, or complete viewBox width; position-only label controls do not change projected text size.`];
+ }
+ if (sourceFontPx < hardFloorPx) {
+ return [`${preserveIntent} The diagnosed ${sourceFontPx}px source text is below the ${hardFloorPx}px hard floor even at scale 1, so use a renderer-supported semantic text-size setting or renderer-level fix. Position-only label controls cannot repair its projection.${readerCap}`];
+ }
+ const maximumViewBoxWidth = Math.floor((sourceFontPx * actualBudgetPx) / hardFloorPx);
+ return [`${preserveIntent} Compactly reflow automatic spacing and empty corridors so the complete viewBox width is at most ${maximumViewBoxWidth}px (current ${viewBoxWidth}px; ${sourceFontPx}px source text at ${actualBudgetPx}px desktop budget). If supplied geometry fixes that width, use a renderer-supported semantic text-size setting or renderer-level fix instead. Position-only label controls cannot repair its projection.${readerCap}`];
+}
+
function formatDiagnostics(error, diagnostics = []) {
if (!diagnostics.length) return error;
return [
diff --git a/archify/bin/visual-check.mjs b/archify/bin/visual-check.mjs
index 61cf3fc9..8edff00b 100644
--- a/archify/bin/visual-check.mjs
+++ b/archify/bin/visual-check.mjs
@@ -52,6 +52,7 @@ const VISUAL_SIDECAR_SUFFIXES = Object.freeze([
)),
]);
const visualEvidenceOwnerships = new WeakSet();
+export const CHROME_STARTUP_TIMEOUT_MS = 90000;
function sha256(buffer) {
return createHash('sha256').update(buffer).digest('hex');
@@ -1368,13 +1369,16 @@ class PipeCdp {
failure(stage, error) {
const code = error?.code ? ` [${error.code}]` : '';
const details = this.failureDetails();
- return new Error([
+ const failure = new Error([
`Chrome DevTools ${stage} failed: ${error?.message || String(error)}${code}`,
details,
`Chrome transport: Node ${process.version}, libuv ${process.versions.uv}, ${process.platform}; pid=${this.child.pid ?? 'unavailable'}, exitCode=${this.child.exitCode}, signalCode=${this.child.signalCode}.`,
`Chrome read pipe: readable=${this.readPipe.readable}, ended=${this.readPipe.readableEnded}, destroyed=${this.readPipe.destroyed}, receivedBytes=${this.receivedBytes}, messages=${this.receivedMessages}, bufferedBytes=${Buffer.byteLength(this.buffer)}.`,
`Chrome write pipe: writable=${this.writePipe.writable}, ended=${this.writePipe.writableEnded}, destroyed=${this.writePipe.destroyed}, completedWrites=${this.completedWrites}, writtenBytes=${this.writtenBytes}, bufferedBytes=${this.writePipe.writableLength}.`,
].filter(Boolean).join('\n'));
+ if (error?.code) failure.code = error.code;
+ if (error?.method) failure.method = error.method;
+ return failure;
}
consume(chunk) {
@@ -1419,7 +1423,10 @@ class PipeCdp {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
this.pending.delete(id);
- reject(this.failure('command timeout', new Error(`${method}: timed out after ${timeoutMs}ms`)));
+ const error = new Error(`${method}: timed out after ${timeoutMs}ms`);
+ error.code = 'ERR_CHROME_CDP_TIMEOUT';
+ error.method = method;
+ reject(this.failure('protocol timeout', error));
}, timeoutMs);
this.pending.set(id, { method, resolve, reject, timer });
try {
@@ -1511,6 +1518,7 @@ export class ChromeVisualBrowser {
env = process.env,
getuid = typeof process.getuid === 'function' ? () => process.getuid() : null,
spawnImpl = spawn,
+ startupTimeoutMs = CHROME_STARTUP_TIMEOUT_MS,
} = {}) {
this.profileRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-visual-check-profile-'));
this.stderr = '';
@@ -1535,11 +1543,17 @@ export class ChromeVisualBrowser {
].filter(Boolean).join('\n');
},
});
+ this.startupTimeoutMs = startupTimeoutMs;
this.sessionPromise = this.attach();
}
async attach() {
- const targets = await this.cdp.send('Target.getTargets');
+ // Process launch can be delayed substantially on a busy desktop. Keep the
+ // longer allowance inside one gate invocation so an authoring agent does
+ // not turn startup jitter into repeated tool calls or candidate edits.
+ const targets = await this.cdp.send(
+ 'Target.getTargets', {}, undefined, this.startupTimeoutMs,
+ );
let target = targets.targetInfos?.find((item) => item.type === 'page');
if (!target) {
const created = await this.cdp.send('Target.createTarget', { url: 'about:blank' });
@@ -1580,6 +1594,9 @@ export class ChromeVisualBrowser {
var fontsReady = document.fonts && document.fonts.ready
? document.fonts.ready.catch(function () {})
: Promise.resolve();
+ if (window.Archify && Archify.layoutStability && typeof Archify.layoutStability.whenStable === 'function') {
+ return fontsReady.then(function () { return Archify.layoutStability.whenStable(); });
+ }
return fontsReady.then(function () {
if (window.Archify && Archify.readerLayout && typeof Archify.readerLayout.whenStable === 'function') {
return Archify.readerLayout.whenStable();
@@ -1617,22 +1634,40 @@ export class ChromeVisualBrowser {
var viewBoxWidth = viewBox ? viewBox.width : 0;
var scale = viewBoxWidth > 0 ? Math.min(1, diagramWidth / viewBoxWidth) : 0;
var minimum = null;
+ var minimumNonEdge = null;
+ var minimumEdge = null;
if (svg && scale > 0) {
- Array.from(svg.querySelectorAll('text[data-node-label], text[data-boundary-label], text[data-detail="context"], [data-edge-id] g[data-detail="context"] > text')).forEach(function (text) {
- var detail = text.closest('[data-edge-id]') ? 'message' : text.hasAttribute('data-node-label')
+ Array.from(svg.querySelectorAll('text[data-node-label], text[data-boundary-label], text[data-detail="context"], g[data-detail="context"] text')).forEach(function (text) {
+ if (text.getAttribute('data-detail') === 'fine' || text.closest('[data-detail="fine"]')) return;
+ var edge = text.closest('[data-edge-from][data-edge-to]');
+ var node = text.closest('[data-node-id]');
+ var context = text.getAttribute('data-detail') === 'context' || Boolean(text.closest('g[data-detail="context"]'));
+ var detail = text.hasAttribute('data-node-label')
? 'primary'
- : text.hasAttribute('data-boundary-label') ? 'boundary' : 'context';
- if (detail === 'context' && !text.closest('[data-node-id]')) return;
+ : text.hasAttribute('data-boundary-label') ? 'boundary'
+ : context && edge ? 'edge' : 'context';
+ if (detail === 'context' && !node) return;
var sourceFontPx = parseFloat(text.getAttribute('font-size') || '');
if (!Number.isFinite(sourceFontPx)) return;
var projectedFontPx = sourceFontPx * scale;
- if (!minimum || projectedFontPx < minimum.projectedFontPx) {
- minimum = {
- text: (text.textContent || '').trim(),
- detail: detail,
- sourceFontPx: sourceFontPx,
- projectedFontPx: projectedFontPx
- };
+ var entry = {
+ text: (text.textContent || '').trim(),
+ detail: detail,
+ owner: edge ? {
+ kind: 'edge',
+ id: edge.getAttribute('data-edge-id'),
+ from: edge.getAttribute('data-edge-from'),
+ to: edge.getAttribute('data-edge-to')
+ } : node ? { kind: 'node', id: node.getAttribute('data-node-id') }
+ : detail === 'boundary' ? { kind: 'boundary', id: null } : null,
+ sourceFontPx: sourceFontPx,
+ projectedFontPx: projectedFontPx
+ };
+ if (!minimum || projectedFontPx < minimum.projectedFontPx) minimum = entry;
+ if (detail === 'edge') {
+ if (!minimumEdge || projectedFontPx < minimumEdge.projectedFontPx) minimumEdge = entry;
+ } else if (!minimumNonEdge || projectedFontPx < minimumNonEdge.projectedFontPx) {
+ minimumNonEdge = entry;
}
});
}
@@ -1690,8 +1725,11 @@ export class ChromeVisualBrowser {
viewBoxWidth: viewBoxWidth,
workflowLanes: workflowLanes,
minimumProjectedNodeTextPx: minimum ? minimum.projectedFontPx : null,
+ minimumProjectedNonEdgeTextPx: minimumNonEdge ? minimumNonEdge.projectedFontPx : null,
+ minimumProjectedEdgeTextPx: minimumEdge ? minimumEdge.projectedFontPx : null,
minimumProjectedNodeText: minimum ? minimum.text : null,
minimumProjectedNodeTextDetail: minimum ? minimum.detail : null,
+ minimumProjectedNodeTextOwner: minimum ? minimum.owner : null,
hasLegend: Boolean(legendRect && legendRect.width && legendRect.height),
hasNavigationDock: Boolean(navigationDockRect && navigationDockRect.width && navigationDockRect.height),
legendDockIntersectionArea: stageDockIntersectionArea > 0
@@ -1755,6 +1793,12 @@ function observation({ width, height, theme, metrics }) {
const minimumProjectedNodeTextPx = metrics.minimumProjectedNodeTextPx == null
? null
: Number(metrics.minimumProjectedNodeTextPx);
+ const minimumProjectedNonEdgeTextPx = metrics.minimumProjectedNonEdgeTextPx == null
+ ? null
+ : Number(metrics.minimumProjectedNonEdgeTextPx);
+ const minimumProjectedEdgeTextPx = metrics.minimumProjectedEdgeTextPx == null
+ ? null
+ : Number(metrics.minimumProjectedEdgeTextPx);
const readabilityOk = minimumProjectedNodeTextPx == null
|| minimumProjectedNodeTextPx >= MIN_PROJECTED_NODE_TEXT_PX;
const readerLayout = metrics.readerLayout || null;
@@ -1806,8 +1850,11 @@ function observation({ width, height, theme, metrics }) {
viewBoxWidth: Number(metrics.viewBoxWidth) || null,
...(metrics.workflowLanes?.length ? { workflowLanes: metrics.workflowLanes } : {}),
minimumProjectedNodeTextPx,
+ minimumProjectedNonEdgeTextPx,
+ minimumProjectedEdgeTextPx,
minimumProjectedNodeText: metrics.minimumProjectedNodeText || null,
minimumProjectedNodeTextDetail: metrics.minimumProjectedNodeTextDetail || null,
+ minimumProjectedNodeTextOwner: metrics.minimumProjectedNodeTextOwner || null,
minimumRequiredNodeTextPx: MIN_PROJECTED_NODE_TEXT_PX,
readabilityOk,
hasLegend: Boolean(metrics.hasLegend),
@@ -1965,11 +2012,12 @@ function observationDiagnostics({ artifact, allObservations, readabilityObservat
evidence: {
text: entry.minimumProjectedNodeText,
detail: entry.minimumProjectedNodeTextDetail,
+ owner: entry.minimumProjectedNodeTextOwner,
minimumProjectedNodeTextPx: entry.minimumProjectedNodeTextPx,
minimumRequiredNodeTextPx: entry.minimumRequiredNodeTextPx,
},
supportedFixes: [
- `increase projected node text to at least ${entry.minimumRequiredNodeTextPx}px at ${entry.width}x${entry.height}, then rerun visual-check`,
+ `increase projected ${entry.minimumProjectedNodeTextOwner?.kind === 'edge' ? 'relationship label' : entry.minimumProjectedNodeTextOwner?.kind === 'boundary' ? 'boundary label' : 'node text'} to at least ${entry.minimumRequiredNodeTextPx}px at ${entry.width}x${entry.height}, then rerun visual-check`,
],
}));
}
@@ -2376,6 +2424,8 @@ export async function runVisualCheck({
}
return { exitCode: receipt.ok ? EXIT.pass : EXIT.fail, receipt };
} catch (error) {
+ const startupTimeout = error.code === 'ERR_CHROME_CDP_TIMEOUT'
+ && error.method === 'Target.getTargets';
receipt.status = 'fail';
receipt.ok = false;
receipt.error = error.message;
@@ -2387,11 +2437,18 @@ export async function runVisualCheck({
receipt.captures.contactSheet = null;
if (error.deliveryProvenance) receipt.provenance = error.deliveryProvenance.status;
receipt.diagnostics = error.archifyDiagnostics || [failureDiagnostic({
- code: 'viewer/visual-check-runtime',
- message: 'visual-check could not complete its Chrome inspection.',
+ code: startupTimeout ? 'viewer/chrome-startup-timeout' : 'viewer/visual-check-runtime',
+ message: startupTimeout
+ ? 'Chrome did not finish its initial DevTools handshake within the startup window.'
+ : 'visual-check could not complete its Chrome inspection.',
subject: { artifact },
evidence: { reason: error.message },
- supportedFixes: ['resolve the reported Chrome inspection error, then rerun visual-check'],
+ supportedFixes: startupTimeout
+ ? [
+ 'do not edit or simplify the artifact because this is a browser-startup failure',
+ `retry visual-check once after host load subsides; if it repeats, stop and report the environment failure`,
+ ]
+ : ['resolve the reported Chrome inspection error, then rerun visual-check'],
})];
return {
exitCode: EXIT.fail,
diff --git a/archify/renderers/shared/desktop-readability.mjs b/archify/renderers/shared/desktop-readability.mjs
index 1a4c249d..5576cf3e 100644
--- a/archify/renderers/shared/desktop-readability.mjs
+++ b/archify/renderers/shared/desktop-readability.mjs
@@ -3,6 +3,11 @@ export const DESKTOP_READER_MIN_WIDTH = 960;
export const DESKTOP_READER_HORIZONTAL_CHROME = 30;
export const DESKTOP_READER_DIAGRAM_WIDTH = DESKTOP_READER_MIN_WIDTH - DESKTOP_READER_HORIZONTAL_CHROME;
export const MIN_PROJECTED_NODE_TEXT_PX = 6;
+export const DECLARED_WIDE_READER_CONTRACT = 'declared-wide-v1';
+export const DECLARED_WIDE_READER_RATIO = 1.55;
+export const DECLARED_WIDE_READER_MAX_WIDTH = 1920;
+export const DECLARED_WIDE_REFERENCE_BODY_HORIZONTAL_PX = 64;
+export const DECLARED_WIDE_REFERENCE_DIAGRAM_HORIZONTAL_PX = 30;
export function projectedNodeTextPx(sourceFontPx, viewBoxWidth, diagramWidth = DESKTOP_READER_DIAGRAM_WIDTH) {
if (![sourceFontPx, viewBoxWidth, diagramWidth].every(Number.isFinite) || viewBoxWidth <= 0 || diagramWidth <= 0) {
@@ -24,3 +29,54 @@ export function minimumReadableSourceTextPx(
}
return minimumProjectedPx / Math.min(1, diagramWidth / viewBoxWidth);
}
+
+// This is deliberately separate from the legacy 930px projection. Architecture
+// boundary convergence depends on that legacy default, while only a recognized
+// v2 wide Reader may use this declared-width proof.
+export function declaredWideReadabilityBudget({
+ viewBoxWidth,
+ viewBoxHeight,
+ minimumSourceTextPx,
+ requestedMinimumTextPx,
+ viewportWidth = DESKTOP_READABILITY_VIEWPORT.width,
+ bodyHorizontalPx = DECLARED_WIDE_REFERENCE_BODY_HORIZONTAL_PX,
+ diagramHorizontalPx = DECLARED_WIDE_REFERENCE_DIAGRAM_HORIZONTAL_PX,
+ minimumReaderWidth = DESKTOP_READER_MIN_WIDTH,
+ maximumReaderWidth = DECLARED_WIDE_READER_MAX_WIDTH,
+} = {}) {
+ const values = [
+ viewBoxWidth, viewBoxHeight, minimumSourceTextPx, requestedMinimumTextPx,
+ viewportWidth, bodyHorizontalPx, diagramHorizontalPx, minimumReaderWidth, maximumReaderWidth,
+ ];
+ if (!values.every(Number.isFinite) || viewBoxWidth <= 0 || viewBoxHeight <= 0
+ || minimumSourceTextPx <= 0 || requestedMinimumTextPx <= 0 || viewportWidth <= 0
+ || bodyHorizontalPx < 0 || diagramHorizontalPx < 0 || minimumReaderWidth <= 0
+ || maximumReaderWidth < minimumReaderWidth || viewBoxWidth / viewBoxHeight < DECLARED_WIDE_READER_RATIO) {
+ return null;
+ }
+ const requestedTargetPx = Math.max(MIN_PROJECTED_NODE_TEXT_PX, requestedMinimumTextPx);
+ const requestedScale = Math.min(1, requestedTargetPx / minimumSourceTextPx);
+ const desiredReaderWidth = Math.max(minimumReaderWidth, viewBoxWidth * requestedScale + diagramHorizontalPx);
+ const viewportCap = Math.max(0, viewportWidth - bodyHorizontalPx);
+ const cap = Math.min(maximumReaderWidth, viewportCap);
+ const actualReaderWidth = Math.min(desiredReaderWidth, cap);
+ const guaranteedSvgWidth = Math.max(0, actualReaderWidth - diagramHorizontalPx);
+ const projectedMinimumTextPx = projectedNodeTextPx(minimumSourceTextPx, viewBoxWidth, guaranteedSvgWidth);
+ const limit = actualReaderWidth < desiredReaderWidth
+ ? (viewportCap <= maximumReaderWidth ? 'viewport-cap' : 'reader-cap')
+ : 'source-size';
+ return {
+ requestedTargetPx,
+ requestedScale,
+ desiredReaderWidth,
+ viewportCap,
+ maximumReaderWidth,
+ actualReaderWidth,
+ guaranteedSvgWidth,
+ projectedMinimumTextPx,
+ hardFloorPx: MIN_PROJECTED_NODE_TEXT_PX,
+ hardFloorMet: projectedMinimumTextPx >= MIN_PROJECTED_NODE_TEXT_PX,
+ requestedTargetMet: projectedMinimumTextPx >= requestedMinimumTextPx,
+ limit,
+ };
+}
diff --git a/archify/renderers/shared/geometry.mjs b/archify/renderers/shared/geometry.mjs
index ef33ae9f..b4fc9677 100644
--- a/archify/renderers/shared/geometry.mjs
+++ b/archify/renderers/shared/geometry.mjs
@@ -1345,48 +1345,65 @@ export function automaticPortRhythmBridge(
const toVector = PORT_OUTWARD_VECTOR[toSide];
if (!fromVector || !toVector) return null;
- const startStub = [
- start[0] + fromVector[0] * endpointStubPx,
- start[1] + fromVector[1] * endpointStubPx,
- ];
- const endStub = [
- end[0] + toVector[0] * endpointStubPx,
- end[1] + toVector[1] * endpointStubPx,
- ];
+ const opposedFacingGap = (
+ (fromSide === 'right' && toSide === 'left' && end[0] > start[0])
+ || (fromSide === 'left' && toSide === 'right' && start[0] > end[0])
+ ) ? Math.abs(end[0] - start[0]) : (
+ (fromSide === 'bottom' && toSide === 'top' && end[1] > start[1])
+ || (fromSide === 'top' && toSide === 'bottom' && start[1] > end[1])
+ ) ? Math.abs(end[1] - start[1]) : null;
+ const boundedStubPx = opposedFacingGap != null
+ && opposedFacingGap - endpointStubPx * 2 < interiorSegmentPx
+ ? Math.max(8, Math.min(endpointStubPx, (opposedFacingGap - interiorSegmentPx) / 2))
+ : null;
+ const stubDistances = [endpointStubPx];
+ if (boundedStubPx != null && boundedStubPx >= 8 && boundedStubPx !== endpointStubPx) {
+ stubDistances.push(boundedStubPx);
+ }
const candidates = [];
const verticalSides = new Set(['top', 'bottom']);
const horizontalSides = new Set(['left', 'right']);
- if (verticalSides.has(fromSide) && verticalSides.has(toSide)
- && Math.abs(start[0] - end[0]) < interiorSegmentPx) {
- for (const channelX of [
- Math.max(start[0], end[0]) + interiorSegmentPx,
- Math.min(start[0], end[0]) - interiorSegmentPx,
- ]) {
- candidates.push([
- start,
- startStub,
- [channelX, startStub[1]],
- [channelX, endStub[1]],
- endStub,
- end,
- ]);
+ for (const stubPx of stubDistances) {
+ const startStub = [
+ start[0] + fromVector[0] * stubPx,
+ start[1] + fromVector[1] * stubPx,
+ ];
+ const endStub = [
+ end[0] + toVector[0] * stubPx,
+ end[1] + toVector[1] * stubPx,
+ ];
+ if (verticalSides.has(fromSide) && verticalSides.has(toSide)
+ && Math.abs(start[0] - end[0]) < interiorSegmentPx) {
+ for (const channelX of [
+ Math.max(start[0], end[0]) + interiorSegmentPx,
+ Math.min(start[0], end[0]) - interiorSegmentPx,
+ ]) {
+ candidates.push([
+ start,
+ startStub,
+ [channelX, startStub[1]],
+ [channelX, endStub[1]],
+ endStub,
+ end,
+ ]);
+ }
}
- }
- if (horizontalSides.has(fromSide) && horizontalSides.has(toSide)
- && Math.abs(start[1] - end[1]) < interiorSegmentPx) {
- for (const channelY of [
- Math.max(start[1], end[1]) + interiorSegmentPx,
- Math.min(start[1], end[1]) - interiorSegmentPx,
- ]) {
- candidates.push([
- start,
- startStub,
- [startStub[0], channelY],
- [endStub[0], channelY],
- endStub,
- end,
- ]);
+ if (horizontalSides.has(fromSide) && horizontalSides.has(toSide)
+ && Math.abs(start[1] - end[1]) < interiorSegmentPx) {
+ for (const channelY of [
+ Math.max(start[1], end[1]) + interiorSegmentPx,
+ Math.min(start[1], end[1]) - interiorSegmentPx,
+ ]) {
+ candidates.push([
+ start,
+ startStub,
+ [startStub[0], channelY],
+ [endStub[0], channelY],
+ endStub,
+ end,
+ ]);
+ }
}
}
diff --git a/archify/scripts/check-render-output.mjs b/archify/scripts/check-render-output.mjs
index 68c76a70..0a125dd1 100644
--- a/archify/scripts/check-render-output.mjs
+++ b/archify/scripts/check-render-output.mjs
@@ -7,6 +7,8 @@ import { collectAmbiguousCorridors, collectBorderRuns, collectLabelCanvasOverflo
import {
DESKTOP_READABILITY_VIEWPORT,
DESKTOP_READER_DIAGRAM_WIDTH,
+ DECLARED_WIDE_READER_CONTRACT,
+ declaredWideReadabilityBudget,
MIN_PROJECTED_NODE_TEXT_PX,
projectedNodeTextPx,
} from '../renderers/shared/desktop-readability.mjs';
@@ -72,6 +74,7 @@ const AUTOMATIC_CROSSOVER_UNDERLAY_TAG = /<path\b[^>]*\bdata-graph-role="automat
const HTML_VOID_ELEMENTS = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr']);
const SVG_HTML_INTEGRATION_POINTS = new Set(['foreignobject', 'desc', 'title']);
const HTML_ATTRIBUTE = /([A-Za-z_:][\w:.-]*)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/g;
+const readerContract = readerContractFromHtml(html);
const NUMERIC_ATTRS = new Set([
'x', 'y', 'x1', 'y1', 'x2', 'y2', 'dx', 'dy', 'cx', 'cy', 'r', 'rx', 'ry', 'fx', 'fy',
'fr', 'width', 'height', 'd', 'points', 'pathlength', 'transform', 'viewbox', 'offset',
@@ -109,7 +112,8 @@ if (svgMatches.length === 1) {
addCheck('finite_svg', nonFiniteAttrs.length === 0, nonFiniteAttrs);
const legendStart = svg.indexOf('<!-- Legend -->');
const beforeLegend = legendStart >= 0 ? svg.slice(0, legendStart) : svg;
- const desktopReadabilityIssue = collectDesktopReadability(svgAttrs, beforeLegend);
+ const desktopReadability = collectDesktopReadability(svgAttrs, beforeLegend, readerContract);
+ const desktopReadabilityIssue = desktopReadability.issue;
const arrows = collectArrows(beforeLegend);
const diagonal = arrows.flatMap((arrow) => diagonalStraightSegments(arrow).map((segment) => ({ arrow, ...segment })));
addCheck(
@@ -197,10 +201,11 @@ if (svgMatches.length === 1) {
labelCanvasOverflowIssues: labelCanvasOverflow.length,
minLabelRouteClearance: minimumLabelRouteClearance(labelRouteMeasurements),
desktopReadabilityIssues: desktopReadabilityIssue ? 1 : 0,
- minProjectedNodeTextPx: desktopReadabilityIssue?.projectedFontPx ?? null,
+ minProjectedNodeTextPx: desktopReadability.evidence.minimumProjectedTextPx,
...roundedRouteMetrics(routeMetrics),
},
suggestedLimits: { bendsPerRelationship: 2, stretch: 1.35, segmentPx: 16, microSegmentPx: 8 },
+ desktopReadability: desktopReadability.evidence,
issues: [
...containerBorderRuns.map((hit) => ({
severity: qualityGatesEnforced ? 'error' : 'warning',
@@ -273,9 +278,15 @@ if (svgMatches.length === 1) {
severity: desktopReadabilityIsError ? 'error' : 'warning',
code: 'composition/desktop-readability',
...(desktopReadabilityIssue.nodeId ? { nodeId: desktopReadabilityIssue.nodeId } : {}),
+ owner: desktopReadabilityIssue.owner,
viewportWidth: DESKTOP_READABILITY_VIEWPORT.width,
viewportHeight: DESKTOP_READABILITY_VIEWPORT.height,
- availableDiagramWidth: DESKTOP_READER_DIAGRAM_WIDTH,
+ availableDiagramWidth: desktopReadability.evidence.availableDiagramWidth,
+ budgetBasis: desktopReadability.evidence.budgetBasis,
+ readerContract: desktopReadability.evidence.readerContract,
+ requestedTargetPx: desktopReadability.evidence.requestedTargetPx,
+ requestedTargetMet: desktopReadability.evidence.requestedTargetMet,
+ budgetLimit: desktopReadability.evidence.limit,
viewBoxWidth: desktopReadabilityIssue.viewBoxWidth,
scale: desktopReadabilityIssue.scale,
text: desktopReadabilityIssue.text,
@@ -728,48 +739,117 @@ function viewBoxSize(svgAttrs) {
return viewBoxRect(svgAttrs).slice(2);
}
-function collectDesktopReadability(svgAttrs, fragment) {
- const [viewBoxWidth] = viewBoxSize(svgAttrs);
- if (!Number.isFinite(viewBoxWidth) || viewBoxWidth <= 0) return null;
- const scale = Math.min(1, DESKTOP_READER_DIAGRAM_WIDTH / viewBoxWidth);
- let worst = null;
- const nodeOwners = [];
- // Walk groups alongside text so nested decoration retains the owning node,
- // without leaking that identity into a following boundary or loose label.
+function hasAttribute(attrs, name) {
+ return new RegExp('(?:^|\\s)' + name + '(?:\\s*=|\\s|$)', 'i').test(attrs);
+}
+
+function readerContractFromHtml(source) {
+ const markers = [...source.matchAll(/<meta\b[^>]*>/gi)]
+ .map((match) => parseAttrs(match[0]))
+ .filter((attrs) => attrs.name === 'archify-reader-contract');
+ return markers.length === 1 && markers[0].content === DECLARED_WIDE_READER_CONTRACT
+ ? DECLARED_WIDE_READER_CONTRACT
+ : null;
+}
+
+function collectDesktopReadability(svgAttrs, fragment, contract) {
+ const [viewBoxWidth, viewBoxHeight] = viewBoxSize(svgAttrs);
+ const requestedMinimumTextPx = Number.parseFloat(svgAttrs['data-reader-min-text'] || '');
+ const entries = [];
+ let invalidSemanticText = false;
+ const groups = [];
+ // Keep the complete ancestry, rather than a node-only stack: an edge can
+ // share its context group with its label or nest that group (Sequence).
for (const match of fragment.matchAll(/<!--[\s\S]*?(?:-->|$)|<!\[CDATA\[[\s\S]*?(?:\]\]>|$)|<text\b([^>]*)>([\s\S]*?)<\/text>|<g\b[^>]*>|<\/g\s*>/gi)) {
- // Comment and CDATA contents cannot open or close a real SVG group.
if (match[0].startsWith('<!')) continue;
if (match[1] === undefined) {
- if (/^<\/g/i.test(match[0])) nodeOwners.pop();
- else if (!/\/\s*>$/.test(match[0])) {
- const attrs = parseAttrs(match[0]);
- nodeOwners.push(attrs['data-node-id'] || nodeOwners.at(-1));
- }
+ if (/^<\/g/i.test(match[0])) groups.pop();
+ else if (!/\/\s*>$/.test(match[0])) groups.push(parseAttrs(match[0]));
continue;
}
- const primary = /\bdata-node-label(?:\s*=|\s|$)/i.test(match[1]);
- const boundary = /\bdata-boundary-label(?:\s*=|\s|$)/i.test(match[1]);
- const context = /\bdata-detail\s*=\s*"context"/i.test(match[1]);
- if (!primary && !boundary && !context) continue;
const attrs = parseAttrs(match[1]);
+ if (attrs['data-detail'] === 'fine' || groups.some((group) => group['data-detail'] === 'fine')) continue;
+ const primary = hasAttribute(match[1], 'data-node-label');
+ const boundary = hasAttribute(match[1], 'data-boundary-label');
+ const context = attrs['data-detail'] === 'context'
+ || groups.some((group) => group['data-detail'] === 'context');
+ const nodeOwner = [...groups].reverse().find((group) => group['data-node-id']);
+ const edgeOwner = [...groups].reverse().find((group) => group['data-edge-from'] && group['data-edge-to']);
+ const owner = primary
+ ? { kind: 'node', id: nodeOwner?.['data-node-id'] || null }
+ : boundary ? { kind: 'boundary', id: null }
+ : context && edgeOwner ? {
+ kind: 'edge', id: edgeOwner['data-edge-id'] || null,
+ from: edgeOwner['data-edge-from'], to: edgeOwner['data-edge-to'],
+ }
+ : context && nodeOwner ? { kind: 'node', id: nodeOwner['data-node-id'] }
+ : null;
+ // A context text with neither semantic owner is legend/fine/loose copy.
+ if (!owner) continue;
const fontSize = Number.parseFloat(attrs['font-size'] || '');
- if (!Number.isFinite(fontSize)) continue;
- const projected = projectedNodeTextPx(fontSize, viewBoxWidth);
- if (projected >= MIN_PROJECTED_NODE_TEXT_PX) continue;
- const candidate = {
- ...(nodeOwners.at(-1) ? { nodeId: nodeOwners.at(-1) } : {}),
- viewBoxWidth,
- scale,
+ if (!Number.isFinite(fontSize)) {
+ invalidSemanticText = true;
+ continue;
+ }
+ if (fontSize <= 0) invalidSemanticText = true;
+ entries.push({
+ ...(owner.kind === 'node' && owner.id ? { nodeId: owner.id } : {}),
+ owner,
text: stripTags(match[2]).trim(),
- detail: primary
- ? 'primary'
- : boundary ? 'boundary' : 'context',
+ detail: primary ? 'primary' : boundary ? 'boundary' : owner.kind === 'edge' ? 'edge' : 'context',
sourceFontPx: fontSize,
- projectedFontPx: projected,
- };
- if (!worst || candidate.projectedFontPx < worst.projectedFontPx) worst = candidate;
+ });
}
- return worst;
+ const minimumSourceTextPx = entries.length ? Math.min(...entries.map((entry) => entry.sourceFontPx)) : Number.NaN;
+ const eligible = contract === DECLARED_WIDE_READER_CONTRACT
+ && svgAttrs['data-reader-fit'] === 'intrinsic-height'
+ && Number.isFinite(requestedMinimumTextPx) && requestedMinimumTextPx > 0
+ && !invalidSemanticText && entries.length > 0;
+ const declared = eligible ? declaredWideReadabilityBudget({
+ viewBoxWidth,
+ viewBoxHeight,
+ minimumSourceTextPx,
+ requestedMinimumTextPx,
+ }) : null;
+ const availableDiagramWidth = declared?.guaranteedSvgWidth ?? DESKTOP_READER_DIAGRAM_WIDTH;
+ const budgetBasis = declared ? 'recognized-declared-wide' : 'legacy-930';
+ const scale = Number.isFinite(viewBoxWidth) && viewBoxWidth > 0
+ ? Math.min(1, availableDiagramWidth / viewBoxWidth) : Number.NaN;
+ const projected = entries.map((entry) => ({
+ ...entry,
+ viewBoxWidth,
+ scale,
+ projectedFontPx: projectedNodeTextPx(entry.sourceFontPx, viewBoxWidth, availableDiagramWidth),
+ }));
+ const worst = projected.reduce((current, entry) => (
+ !current || entry.projectedFontPx < current.projectedFontPx ? entry : current
+ ), null);
+ const projectedMinimumTextPx = Number.isFinite(worst?.projectedFontPx) ? worst.projectedFontPx : null;
+ const hardFloorMet = Number.isFinite(worst?.projectedFontPx)
+ ? worst.projectedFontPx >= MIN_PROJECTED_NODE_TEXT_PX : null;
+ const requestedTargetMet = worst && Number.isFinite(requestedMinimumTextPx)
+ ? worst.projectedFontPx >= requestedMinimumTextPx : null;
+ const evidence = {
+ budgetBasis,
+ readerContract: contract,
+ availableDiagramWidth,
+ actualBudgetPx: availableDiagramWidth,
+ ...(declared ? {
+ actualReaderWidth: declared.actualReaderWidth,
+ desiredReaderWidth: declared.desiredReaderWidth,
+ viewportCap: declared.viewportCap,
+ limit: declared.limit,
+ } : { limit: 'legacy' }),
+ requestedTargetPx: Number.isFinite(requestedMinimumTextPx) ? requestedMinimumTextPx : null,
+ requestedTargetMet,
+ hardFloorPx: MIN_PROJECTED_NODE_TEXT_PX,
+ hardFloorMet,
+ minimumOwner: worst?.owner || null,
+ minimumSourceTextPx: worst?.sourceFontPx ?? null,
+ minimumProjectedTextPx: projectedMinimumTextPx,
+ semanticTextCount: entries.length,
+ };
+ return { evidence, issue: worst && hardFloorMet === false ? worst : null };
}
function estimatedTextWidth(text, fontSize) {
diff --git a/archify/test/adaptive-reader-layout.test.mjs b/archify/test/adaptive-reader-layout.test.mjs
index 59b9ccef..a4178427 100644
--- a/archify/test/adaptive-reader-layout.test.mjs
+++ b/archify/test/adaptive-reader-layout.test.mjs
@@ -8,6 +8,9 @@ import {
DESKTOP_READER_DIAGRAM_WIDTH,
DESKTOP_READER_HORIZONTAL_CHROME,
DESKTOP_READER_MIN_WIDTH,
+ DECLARED_WIDE_READER_CONTRACT,
+ DECLARED_WIDE_READER_RATIO,
+ declaredWideReadabilityBudget,
MIN_PROJECTED_NODE_TEXT_PX,
minimumReadableSourceTextPx,
projectedNodeTextPx,
@@ -17,6 +20,7 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
const skillRoot = path.resolve(__dirname, '..');
const template = fs.readFileSync(path.join(skillRoot, 'assets', 'template.html'), 'utf8');
const skill = fs.readFileSync(path.join(skillRoot, 'SKILL.md'), 'utf8');
+const architectureRenderer = fs.readFileSync(path.join(skillRoot, 'renderers', 'architecture', 'render-architecture.mjs'), 'utf8');
const reader = template.slice(
template.indexOf('Adaptive Reader Shell'),
template.indexOf('Archify.view = (function ()'),
@@ -31,6 +35,7 @@ test('wide desktop diagrams use one height-budgeted reader shell instead of brea
assert.match(reader, /var availableSvgHeight = Math\.max\(1, window\.innerHeight - fixedHeight\)/);
assert.match(reader, /var desiredWidth = availableSvgHeight \* ratio \+ chrome\.diagramX/);
assert.match(reader, /html\.style\.setProperty\('--archify-reader-width', rounded \+ 'px'\)/);
+ assert.equal((template.match(/<meta name="archify-reader-contract" content="declared-wide-v1">/g) || []).length, 1);
});
test('compiler-measured intrinsic tall workflows reuse the height budget without widening eligibility', () => {
@@ -38,12 +43,25 @@ test('compiler-measured intrinsic tall workflows reuse the height budget without
assert.match(reader, /ratio >= WIDE_RATIO \|\| measuredHeightFit/);
assert.match(reader, /var MIN_PROJECTED_NODE_TEXT_PX = 6/);
assert.match(reader, /viewBox\.width \* minimumReadableScale\(\) \+ chrome\.diagramX/);
- assert.match(reader, /measuredHeightFit && ratio < WIDE_RATIO \? readableWidth : MIN_READER_WIDTH/);
+ assert.match(reader, /measuredHeightFit &&[\s\S]{0,100}ratio < WIDE_RATIO[\s\S]{0,120}readableWidth/);
assert.match(reader, /Math\.max\(Math\.ceil\(minWidth \|\| 0\), Math\.round\(width\)\)/);
assert.match(reader, /lastWidth > Math\.ceil\(minWidth\)/);
assert.doesNotMatch(reader, /function eligible\(\)[\s\S]{0,240}ratio > 0/);
});
+test('declared wide intrinsic readers include semantic edge labels in the readable floor', () => {
+ assert.match(reader, /g\[data-detail="context"\]\[data-edge-from\]\[data-edge-to\] > text/);
+ assert.match(reader, /measuredHeightFit && ratio >= WIDE_RATIO && Number\.isFinite\(declaredMinimumText\)/);
+ assert.match(reader, /measuredHeightFit && ratio < WIDE_RATIO[\s\S]{0,60}\? readableWidth/);
+ assert.match(reader, /Math\.max\(MIN_READER_WIDTH, readableWidth\)/);
+ assert.match(reader, /if \(measuredHeightFit && ratio < WIDE_RATIO\)[\s\S]{0,120}minWidth = Math\.min\(readableMinimumWidth, viewportCap\)/);
+ assert.match(reader, /else if \(measuredHeightFit && ratio >= WIDE_RATIO && Number\.isFinite\(declaredMinimumText\)\)[\s\S]{0,140}minWidth = Math\.min\(readableMinimumWidth, maxWidth\)/);
+ assert.match(reader, /var maxWidth = Math\.min\(MAX_READER_WIDTH, viewportCap\)/);
+ assert.match(reader, /ratio >= WIDE_RATIO && Number\.isFinite\(declaredMinimumText\)/);
+ assert.equal(DESKTOP_READER_MIN_WIDTH, 960);
+ assert.equal(MIN_PROJECTED_NODE_TEXT_PX, 6);
+});
+
test('desktop readability budget matches the minimum adaptive reader at 1440 by 900', () => {
assert.deepEqual(DESKTOP_READABILITY_VIEWPORT, { width: 1440, height: 900 });
assert.equal(DESKTOP_READER_MIN_WIDTH, 960);
@@ -65,6 +83,34 @@ test('desktop readability source floor is the inverse of the projected-size gate
assert.ok(Number.isNaN(minimumReadableSourceTextPx(0)));
});
+test('declared-wide budget is additive and reports a cap without changing the legacy 930px floor', () => {
+ assert.equal(DECLARED_WIDE_READER_CONTRACT, 'declared-wide-v1');
+ assert.equal(DECLARED_WIDE_READER_RATIO, 1.55);
+ const first = declaredWideReadabilityBudget({
+ viewBoxWidth: 1438,
+ viewBoxHeight: 800,
+ minimumSourceTextPx: 8,
+ requestedMinimumTextPx: 7.5,
+ });
+ assert.ok(first);
+ assert.equal(first.actualReaderWidth, 1376);
+ assert.equal(first.guaranteedSvgWidth, 1346);
+ assert.equal(first.limit, 'viewport-cap');
+ assert.ok(first.projectedMinimumTextPx >= MIN_PROJECTED_NODE_TEXT_PX);
+ assert.ok(first.projectedMinimumTextPx < 7.5, 'do not round 7.488px into a met 7.5px target');
+ assert.equal(first.requestedTargetMet, false);
+ assert.equal(DESKTOP_READER_DIAGRAM_WIDTH, 930);
+ assert.equal(declaredWideReadabilityBudget({
+ viewBoxWidth: 1000,
+ viewBoxHeight: 800,
+ minimumSourceTextPx: 8,
+ requestedMinimumTextPx: 7.5,
+ }), null, 'narrow diagrams remain on the legacy checker path');
+ assert.match(architectureRenderer, /minimumReadableSourceTextPx\(budgetViewBoxWidth\) \+ 1e-6/);
+ assert.match(architectureRenderer, /minimumReadableSourceTextPx\(finalViewBoxWidth\)/);
+ assert.doesNotMatch(architectureRenderer, /declaredWideReadabilityBudget/);
+});
+
test('adaptive width preserves canonical SVG geometry and yields to specialized viewer modes', () => {
assert.match(reader, /window\.innerWidth >= MIN_DESKTOP_WIDTH/);
assert.match(reader, /html\.getAttribute\('data-embed'\) !== 'true'/);
diff --git a/archify/test/desktop-reader-browser.test.mjs b/archify/test/desktop-reader-browser.test.mjs
index 0b0d5cd7..9b146e45 100644
--- a/archify/test/desktop-reader-browser.test.mjs
+++ b/archify/test/desktop-reader-browser.test.mjs
@@ -35,6 +35,44 @@ test('all packaged HTML examples pass the real visual-check desktop gate', {
}
});
+test('visual-check collects nested ID-less semantic edge text for every renderer family', {
+ skip: chromePath ? false : 'Set ARCHIFY_CHROME to run the real browser regression.',
+}, async () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-visual-edge-collector-'));
+ const cases = [
+ ['architecture', 'examples/web-app.architecture.json'],
+ ['workflow', 'examples/agent-tool-call.workflow.json'],
+ ['sequence', 'examples/cache-miss-request.sequence.json'],
+ ['dataflow', 'examples/event-stream.dataflow.json'],
+ ['lifecycle', 'examples/agent-run.lifecycle.json'],
+ ];
+ try {
+ for (const [index, [type, input]] of cases.entries()) {
+ const artifact = path.join(tmp, `${type}.html`);
+ execFileSync(process.execPath, [
+ path.join(skillRoot, 'bin', 'archify.mjs'), 'render', type,
+ path.join(skillRoot, input), artifact, '--quality', 'showcase',
+ ], { cwd: skillRoot, encoding: 'utf8' });
+ const edge = index % 2
+ ? `<g data-edge-from="collector-${type}" data-edge-to="reader-${type}"><g data-detail="context"><text x="1" y="1" font-size="5">nested semantic edge</text><text data-detail="fine" x="1" y="2" font-size="1">fine edge annotation</text></g></g>`
+ : `<g data-edge-from="collector-${type}" data-edge-to="reader-${type}" data-detail="context"><text x="1" y="1" font-size="5">same-group semantic edge</text><g data-detail="fine"><text x="1" y="2" font-size="1">fine nested annotation</text></g></g>`;
+ const injected = fs.readFileSync(artifact, 'utf8').replace('</svg>', `${edge}</svg>`);
+ fs.writeFileSync(artifact, injected);
+ const result = await runVisualCheck({ artifactPath: artifact, chromePath });
+ const desktop = result.receipt.readability.viewports.find(({ width, height }) => width === 1440 && height === 900);
+ assert.ok(desktop, `${type}: missing desktop observation`);
+ assert.equal(desktop.minimumProjectedNodeTextDetail, 'edge', `${type}: ${JSON.stringify(desktop)}`);
+ assert.match(desktop.minimumProjectedNodeText, /semantic edge/, `${type}: fine text must be excluded`);
+ assert.deepEqual(desktop.minimumProjectedNodeTextOwner, {
+ kind: 'edge', id: null, from: `collector-${type}`, to: `reader-${type}`,
+ }, `${type}: ${JSON.stringify(desktop)}`);
+ assert.equal(result.receipt.readability.status, 'fail', `${type}: injected 5px edge must be measured`);
+ }
+ } finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+});
+
const issue250TallGroup = {
schema_version: 2,
diagram_type: 'workflow',
@@ -94,6 +132,15 @@ test('production showcase is readable in the real 1440 by 900 adaptive reader',
'showcase',
], { cwd: skillRoot, encoding: 'utf8' });
+ const artifactSource = fs.readFileSync(artifact, 'utf8');
+ const svgRoot = artifactSource.match(/<svg\b[^>]*>/)?.[0];
+ assert.ok(svgRoot, 'production fixture must contain an SVG root');
+ // With 8px edge text across a 1376px SVG, the declared 7.5px floor
+ // requires a 1290px diagram plus 30px of Reader chrome.
+ assert.match(svgRoot, /viewBox="0 0 1376 728"/);
+ assert.match(svgRoot, /data-reader-fit="intrinsic-height"/);
+ assert.match(svgRoot, /data-reader-min-text="7\.5"/);
+
for (let attempt = 1; attempt <= 3; attempt += 1) {
const result = await runVisualCheck({ artifactPath: artifact, chromePath });
assert.equal(result.exitCode, 0, `attempt ${attempt}: ${JSON.stringify(result.receipt, null, 2)}`);
@@ -108,13 +155,25 @@ test('production showcase is readable in the real 1440 by 900 adaptive reader',
));
for (const observation of [desktop, darkDesktop]) {
assert.ok(observation);
- assert.equal(observation.readerWidth, 960);
- assert.equal(observation.diagramWidth, 930);
+ assert.equal(observation.readerWidth, 1320);
+ assert.ok(observation.readerWidth <= 1376);
+ assert.equal(observation.diagramWidth, 1290);
+ assert.equal(observation.viewBoxWidth, 1376);
+ assert.ok(Number.isFinite(observation.minimumProjectedNodeTextPx));
assert.ok(observation.minimumProjectedNodeTextPx >= MIN_PROJECTED_NODE_TEXT_PX);
- assert.equal(observation.minimumProjectedNodeTextDetail, 'boundary');
- assert.equal(observation.minimumProjectedNodeText, 'AWS eu-west-1 / disaster recovery');
+ assert.ok(observation.minimumProjectedNodeTextPx >= 7.5, JSON.stringify(observation));
+ assert.equal(typeof observation.minimumProjectedNodeText, 'string');
+ assert.ok(observation.minimumProjectedNodeText.trim().length > 0);
assert.equal(observation.readabilityOk, true);
- assert.equal(observation.scrollHeight, DESKTOP_READABILITY_VIEWPORT.height);
+ assert.equal(observation.overflowX, false, JSON.stringify(observation));
+ if (observation.overflowY) {
+ assert.equal(observation.verticalScrollAccepted, true, JSON.stringify(observation));
+ assert.equal(observation.readerLayout, 'adaptive', JSON.stringify(observation));
+ assert.equal(observation.readerOverflow, 'authored', JSON.stringify(observation));
+ assert.equal(observation.readerFit, 'intrinsic-height', JSON.stringify(observation));
+ } else {
+ assert.equal(observation.verticalScrollAccepted, false, JSON.stringify(observation));
+ }
}
}
} finally {
@@ -159,7 +218,14 @@ test('route-expanded intrinsic architecture fits every required desktop viewport
assert.equal(viewport.overflowX, false, JSON.stringify(viewport, null, 2));
assert.equal(viewport.overflowY, false, JSON.stringify(viewport, null, 2));
assert.equal(viewport.scrollHeight, viewport.height, JSON.stringify(viewport, null, 2));
- assert.ok(viewport.minimumProjectedNodeTextPx >= 7.5 - 0.01);
+ for (const [field, floor] of [
+ ['minimumProjectedNonEdgeTextPx', 7.5 - 0.01],
+ ['minimumProjectedEdgeTextPx', MIN_PROJECTED_NODE_TEXT_PX],
+ ['minimumProjectedNodeTextPx', MIN_PROJECTED_NODE_TEXT_PX],
+ ]) {
+ assert.ok(Number.isFinite(viewport[field]), field + ': ' + JSON.stringify(viewport, null, 2));
+ assert.ok(viewport[field] >= floor, field + ': ' + JSON.stringify(viewport, null, 2));
+ }
}
const desktop = result.receipt.containment.viewports.find(({ width, height }) => (
width === DESKTOP_READABILITY_VIEWPORT.width
@@ -211,7 +277,14 @@ test('extreme intrinsic architecture keeps readable page scroll below first-scre
let scrollViewportCount = 0;
for (const viewport of result.receipt.containment.viewports) {
assert.equal(viewport.overflowX, false, JSON.stringify(viewport, null, 2));
- assert.ok(viewport.minimumProjectedNodeTextPx >= 7.5 - 0.01);
+ for (const [field, floor] of [
+ ['minimumProjectedNonEdgeTextPx', 7.5 - 0.01],
+ ['minimumProjectedEdgeTextPx', MIN_PROJECTED_NODE_TEXT_PX],
+ ['minimumProjectedNodeTextPx', MIN_PROJECTED_NODE_TEXT_PX],
+ ]) {
+ assert.ok(Number.isFinite(viewport[field]), field + ': ' + JSON.stringify(viewport, null, 2));
+ assert.ok(viewport[field] >= floor, field + ': ' + JSON.stringify(viewport, null, 2));
+ }
if (viewport.overflowY) {
scrollViewportCount += 1;
assert.equal(viewport.verticalScrollAccepted, true, JSON.stringify(viewport, null, 2));
diff --git a/archify/test/fixtures/architecture-viewport/readable-scroll-worldscope.architecture.json b/archify/test/fixtures/architecture-viewport/readable-scroll-worldscope.architecture.json
index 2c25b295..6cc6b33e 100644
--- a/archify/test/fixtures/architecture-viewport/readable-scroll-worldscope.architecture.json
+++ b/archify/test/fixtures/architecture-viewport/readable-scroll-worldscope.architecture.json
@@ -119,6 +119,20 @@
170,
64
]
+ },
+ {
+ "id": "archive",
+ "type": "database",
+ "label": "历史证据归档",
+ "sublabel": "大体量离线资料",
+ "pos": [
+ 790,
+ 1056
+ ],
+ "size": [
+ 150,
+ 64
+ ]
}
],
"connections": [
@@ -168,11 +182,11 @@
"via": [
[
135,
- 1120
+ 610
],
[
485,
- 1120
+ 610
]
]
},
diff --git a/archify/test/fixtures/reader-readability/synthetic-wide.architecture.json b/archify/test/fixtures/reader-readability/synthetic-wide.architecture.json
new file mode 100644
index 00000000..15a10737
--- /dev/null
+++ b/archify/test/fixtures/reader-readability/synthetic-wide.architecture.json
@@ -0,0 +1,336 @@
+{
+ "schema_version": 1,
+ "diagram_type": "architecture",
+ "meta": {
+ "title": "Synthetic wide reader fixture",
+ "output": "synthetic-wide-reader.html",
+ "quality_profile": "showcase",
+ "views": [
+ {
+ "id": "admission",
+ "label": "Admission",
+ "focus": [
+ "caller",
+ "listener",
+ "handler",
+ "parser",
+ "coordinator",
+ "store",
+ "queue"
+ ],
+ "note": "Trace request admission through queued state."
+ },
+ {
+ "id": "execution",
+ "label": "Execution",
+ "focus": [
+ "coordinator",
+ "queue",
+ "scheduler",
+ "worker",
+ "formatter",
+ "store"
+ ],
+ "note": "Follow one queued item through worker completion."
+ },
+ {
+ "id": "polling",
+ "label": "Polling",
+ "focus": [
+ "caller",
+ "listener",
+ "handler",
+ "coordinator",
+ "store",
+ "scheduler"
+ ],
+ "note": "Follow polling across the process boundary."
+ }
+ ]
+ },
+ "components": [
+ {
+ "id": "caller",
+ "type": "external",
+ "label": "Client caller",
+ "sublabel": "external request",
+ "pos": [
+ 40,
+ 270
+ ],
+ "size": [
+ 160,
+ 78
+ ]
+ },
+ {
+ "id": "listener",
+ "type": "backend",
+ "label": "HTTP listener",
+ "sublabel": "request bridge",
+ "pos": [
+ 260,
+ 270
+ ],
+ "size": [
+ 170,
+ 78
+ ]
+ },
+ {
+ "id": "handler",
+ "type": "backend",
+ "label": "Request handler",
+ "sublabel": "route and validation",
+ "pos": [
+ 530,
+ 270
+ ],
+ "size": [
+ 180,
+ 84
+ ]
+ },
+ {
+ "id": "parser",
+ "type": "backend",
+ "label": "Input parser",
+ "sublabel": "structured payload",
+ "pos": [
+ 740,
+ 110
+ ],
+ "size": [
+ 180,
+ 78
+ ]
+ },
+ {
+ "id": "coordinator",
+ "type": "backend",
+ "label": "Work coordinator",
+ "sublabel": "admit and poll",
+ "pos": [
+ 740,
+ 300
+ ],
+ "size": [
+ 160,
+ 84
+ ]
+ },
+ {
+ "id": "store",
+ "type": "database",
+ "label": "State store",
+ "sublabel": "in-memory records",
+ "pos": [
+ 930,
+ 170
+ ],
+ "size": [
+ 170,
+ 82
+ ]
+ },
+ {
+ "id": "queue",
+ "type": "messagebus",
+ "label": "FIFO queue",
+ "sublabel": "in-memory ids",
+ "pos": [
+ 920,
+ 370
+ ],
+ "size": [
+ 170,
+ 82
+ ]
+ },
+ {
+ "id": "scheduler",
+ "type": "backend",
+ "label": "Tick scheduler",
+ "sublabel": "periodic worker tick",
+ "pos": [
+ 720,
+ 540
+ ],
+ "size": [
+ 180,
+ 78
+ ]
+ },
+ {
+ "id": "worker",
+ "type": "backend",
+ "label": "Work worker",
+ "sublabel": "queued to complete",
+ "pos": [
+ 1115,
+ 370
+ ],
+ "size": [
+ 165,
+ 84
+ ]
+ },
+ {
+ "id": "formatter",
+ "type": "backend",
+ "label": "Result formatter",
+ "sublabel": "text transform",
+ "pos": [
+ 1115,
+ 170
+ ],
+ "size": [
+ 165,
+ 78
+ ]
+ }
+ ],
+ "boundaries": [
+ {
+ "kind": "region",
+ "label": "Application process",
+ "wraps": [
+ "listener",
+ "handler",
+ "parser",
+ "coordinator",
+ "store",
+ "queue",
+ "scheduler",
+ "worker",
+ "formatter"
+ ],
+ "pad": 28
+ }
+ ],
+ "connections": [
+ {
+ "id": "client-request",
+ "from": "caller",
+ "to": "listener",
+ "label": "request",
+ "variant": "emphasis"
+ },
+ {
+ "id": "request-envelope",
+ "from": "listener",
+ "to": "handler",
+ "label": "method and body"
+ },
+ {
+ "id": "post-body",
+ "from": "handler",
+ "to": "parser",
+ "label": "parse payload"
+ },
+ {
+ "id": "validated-job",
+ "from": "parser",
+ "to": "coordinator",
+ "label": "validated work"
+ },
+ {
+ "id": "poll-request",
+ "from": "handler",
+ "to": "coordinator",
+ "label": "poll status"
+ },
+ {
+ "id": "state-admission",
+ "from": "coordinator",
+ "to": "store",
+ "label": "read or write state"
+ },
+ {
+ "id": "enqueue-id",
+ "from": "coordinator",
+ "to": "queue",
+ "label": "enqueue id",
+ "variant": "dashed"
+ },
+ {
+ "id": "coordinator-result",
+ "from": "coordinator",
+ "to": "handler",
+ "label": "status result"
+ },
+ {
+ "id": "json-response",
+ "from": "handler",
+ "to": "listener",
+ "label": "response body"
+ },
+ {
+ "id": "server-response",
+ "from": "listener",
+ "to": "caller",
+ "label": "HTTP response",
+ "variant": "emphasis"
+ },
+ {
+ "id": "timer-tick",
+ "from": "scheduler",
+ "to": "worker",
+ "label": "tick every interval",
+ "variant": "dashed"
+ },
+ {
+ "id": "dequeue-id",
+ "from": "queue",
+ "to": "worker",
+ "label": "dequeue next id"
+ },
+ {
+ "id": "worker-state",
+ "from": "worker",
+ "to": "store",
+ "label": "update state"
+ },
+ {
+ "id": "format-call",
+ "from": "worker",
+ "to": "formatter",
+ "label": "format text"
+ },
+ {
+ "id": "format-result",
+ "from": "formatter",
+ "to": "worker",
+ "label": "formatted result"
+ }
+ ],
+ "cards": [
+ {
+ "dot": "cyan",
+ "title": "Admission",
+ "items": [
+ "The handler validates a request before coordinator work.",
+ "Malformed input stops before state changes.",
+ "Repeated ids are rejected without a second enqueue."
+ ]
+ },
+ {
+ "dot": "emerald",
+ "title": "Execution",
+ "items": [
+ "Accepted work enters the FIFO queue.",
+ "The worker advances one item through completion.",
+ "Formatting runs before the completed result is stored."
+ ]
+ },
+ {
+ "dot": "violet",
+ "title": "Polling",
+ "items": [
+ "Polling reads a cloned record.",
+ "Missing ids return a not-found result.",
+ "The runtime keeps state inside one process."
+ ]
+ }
+ ]
+}
diff --git a/archify/test/geometry.test.mjs b/archify/test/geometry.test.mjs
index 9adb0892..cb2b5951 100644
--- a/archify/test/geometry.test.mjs
+++ b/archify/test/geometry.test.mjs
@@ -64,6 +64,39 @@ test('automaticPortRhythmBridge: near parallel ports use readable outside runs',
}), []);
});
+test('automaticPortRhythmBridge: opposed facing ports shrink only the rejected 24px stubs', () => {
+ const points = automaticPortRhythmBridge(
+ [430, 321],
+ [490, 335],
+ 'right',
+ 'left',
+ );
+
+ assert.deepEqual(points, [
+ [430, 321],
+ [452, 321],
+ [452, 351],
+ [468, 351],
+ [468, 335],
+ [490, 335],
+ ]);
+ assert.deepEqual(collectRouteRhythmIssues({
+ routedRelations: [{ relation: { id: 'opposed-facing' }, points }],
+ }), []);
+});
+
+test('automaticPortRhythmBridge: accepts no route when the collision callback rejects each candidate', () => {
+ const points = automaticPortRhythmBridge(
+ [430, 321],
+ [490, 335],
+ 'right',
+ 'left',
+ { accept: () => false },
+ );
+
+ assert.equal(points, null);
+});
+
test('rectsOverlap: separated rects do not overlap', () => {
assert.equal(rectsOverlap(rect(0, 0, 10, 10), rect(20, 0, 10, 10)), false);
});
diff --git a/archify/test/joint-layout-browser.test.mjs b/archify/test/joint-layout-browser.test.mjs
new file mode 100644
index 00000000..54e801da
--- /dev/null
+++ b/archify/test/joint-layout-browser.test.mjs
@@ -0,0 +1,507 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { execFileSync } from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import { ChromeVisualBrowser, findChrome, runVisualCheck } from '../bin/visual-check.mjs';
+
+const skillRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const configured = Object.prototype.hasOwnProperty.call(process.env, 'ARCHIFY_CHROME');
+const chrome = configured ? findChrome() : null;
+if (configured && !chrome) throw new Error(`ARCHIFY_CHROME is not executable: ${process.env.ARCHIFY_CHROME}`);
+
+// This observer deliberately has no access to either owner's receipt(),
+// measure(), stageRect(), or scheduler. In particular, a stale receipt cannot
+// repair the geometry before the first observation at joint resolution.
+const pageHelpers = `(() => {
+ const rounded = value => Math.round(value * 100) / 100;
+ const rect = element => {
+ if (!element) return null;
+ const box = element.getBoundingClientRect();
+ return ['left', 'top', 'right', 'bottom', 'width', 'height'].map(key => rounded(box[key]));
+ };
+ window.__jointRaw = () => {
+ const html = document.documentElement;
+ const panel = document.querySelector('.diagram-container');
+ const svg = panel.querySelector(':scope > svg');
+ const nav = panel.querySelector('.diagram-nav');
+ const stage = svg.getBoundingClientRect();
+ const dock = nav.getBoundingClientRect();
+ return {
+ boxes: ['.container', '.header', '.guided-views', '.cards', '.diagram-container',
+ '.diagram-container > svg', '.diagram-nav', '[data-legend]']
+ .map(selector => [selector, rect(document.querySelector(selector))]),
+ reserve: parseFloat(getComputedStyle(panel).getPropertyValue('--archify-nav-reserve')) || 0,
+ rail: panel.getAttribute('data-nav-stage-rail'), rootRail: html.getAttribute('data-nav-stage-rail'),
+ readerWidth: html.style.getPropertyValue('--archify-reader-width'),
+ reader: html.getAttribute('data-reader-layout'), overflow: html.getAttribute('data-reader-overflow'),
+ readerFit: svg.getAttribute('data-reader-fit'), theme: html.getAttribute('data-theme'), preset: html.getAttribute('data-preset'),
+ dimensions: [innerWidth, innerHeight, html.scrollWidth, html.scrollHeight, document.body.scrollWidth, document.body.scrollHeight],
+ viewBox: svg.getAttribute('viewBox'),
+ gap: rounded(dock.top - stage.bottom),
+ overlap: rounded(Math.max(0, Math.min(stage.right, dock.right) - Math.max(stage.left, dock.left)) *
+ Math.max(0, Math.min(stage.bottom, dock.bottom) - Math.max(stage.top, dock.top))),
+ fonts: document.fonts ? document.fonts.status : null,
+ payloads: Array.from(document.querySelectorAll('script[type="application/json"]'))
+ .map(element => [element.id, element.textContent]),
+ // Preserve complete live geometry for every within-state convergence
+ // comparison, including runtime legend hit areas and count badges.
+ semantic: Array.from(svg.querySelectorAll('[data-node-id], [data-edge-id], [data-legend]')).map(element => [
+ element.getAttribute('data-node-id') || element.getAttribute('data-edge-id') || 'legend',
+ [element, ...element.querySelectorAll('rect, path, line, circle, ellipse, polygon, polyline, text')].map(node =>
+ ['transform', 'd', 'x', 'y', 'x1', 'x2', 'y1', 'y2', 'cx', 'cy', 'r', 'rx', 'ry', 'width', 'height', 'points', 'font-size']
+ .map(attribute => node.getAttribute(attribute)))
+ ]),
+ // Cross-state preservation follows canonical export cleanup's exact
+ // runtime-legend boundary. Authored legend geometry remains included.
+ authoredSemantic: Array.from(svg.querySelectorAll('[data-node-id], [data-edge-id], [data-legend]')).map(element => [
+ element.getAttribute('data-node-id') || element.getAttribute('data-edge-id') || 'legend',
+ [element, ...element.querySelectorAll('rect, path, line, circle, ellipse, polygon, polyline, text')]
+ .filter(node => !node.closest('[data-legend-bridge-runtime]')).map(node =>
+ ['transform', 'd', 'x', 'y', 'x1', 'x2', 'y1', 'y2', 'cx', 'cy', 'r', 'rx', 'ry', 'width', 'height', 'points', 'font-size']
+ .map(attribute => node.getAttribute(attribute)))
+ ])
+ };
+ };
+ window.__jointFrames = count => new Promise(resolve => {
+ const step = () => { if (--count <= 0) resolve(); else requestAnimationFrame(step); };
+ requestAnimationFrame(step);
+ });
+ window.__jointOracle = immediate => new Promise((resolve, reject) => {
+ const expected = JSON.stringify(immediate);
+ let previous = '', equal = 0, sampled = 0, firstDeviation = null;
+ const sample = () => {
+ const raw = __jointRaw();
+ const current = JSON.stringify(raw);
+ sampled++;
+ if (current !== expected && !firstDeviation) firstDeviation = { sampledFrame: sampled, raw };
+ equal = current === previous ? equal + 1 : 0;
+ previous = current;
+ if (equal >= 8) return resolve({ raw, firstDeviation });
+ if (sampled >= 240) return reject(new Error('Independent eight-frame geometry oracle did not converge'));
+ requestAnimationFrame(sample);
+ };
+ requestAnimationFrame(sample);
+ });
+ window.__jointCompare = async immediate => {
+ // The read-only oracle runs BEFORE any extra readiness API. Otherwise
+ // legacy scheduling could repair a missed observer before it is noticed.
+ const observation = await __jointOracle(immediate);
+ await Archify.readerLayout.whenStable();
+ await Archify.viewerChromeLayout.whenStable();
+ await Archify.readerLayout.whenStable();
+ await Archify.viewerChromeLayout.whenStable();
+ const legacy = __jointRaw();
+ await Archify.layoutStability.whenStable();
+ const second = __jointRaw();
+ return { immediate, later: observation.raw, firstDeviation: observation.firstDeviation,
+ legacy, second, errors: window.__jointErrors || [] };
+ };
+})()`;
+
+const helperSetupAssertion = `
+ if (!['__jointRaw', '__jointFrames', '__jointOracle', '__jointCompare']
+ .every(name => typeof window[name] === 'function')) {
+ throw new Error('Joint layout test helper setup failed');
+ }
+`;
+
+// Wrap native observers only to count actual notifications. All original
+// callbacks, entries, observation options and native scheduling pass through.
+const observerCounters = `(() => {
+ window.__jointErrors = [];
+ addEventListener('error', event => __jointErrors.push(event.message));
+ addEventListener('unhandledrejection', event => __jointErrors.push(String(event.reason)));
+ window.__jointObservers = { resizeReader: 0, resizeChrome: 0, mutationReader: 0, mutationChrome: 0 };
+ const reader = element => element.matches && element.matches('.header, .guided-views, .cards');
+ const chrome = element => element.matches && element.matches('.diagram-nav, .diagram-container > svg, [data-legend]');
+ const Resize = window.ResizeObserver;
+ if (Resize) window.ResizeObserver = class extends Resize {
+ constructor(callback) { super((entries, observer) => {
+ if (entries.some(entry => reader(entry.target))) __jointObservers.resizeReader++;
+ if (entries.some(entry => chrome(entry.target))) __jointObservers.resizeChrome++;
+ callback(entries, observer);
+ }); }
+ };
+ const Mutation = window.MutationObserver;
+ if (Mutation) window.MutationObserver = class extends Mutation {
+ constructor(callback) { super((entries, observer) => {
+ if (entries.some(entry => reader(entry.target))) __jointObservers.mutationReader++;
+ if (entries.some(entry => chrome(entry.target) || entry.target === document.documentElement)) __jointObservers.mutationChrome++;
+ callback(entries, observer);
+ }); }
+ };
+})()`;
+
+test('one joint wait preserves real Reader/Chrome convergence at the CLI boundary', {
+ skip: chrome ? false : 'Set ARCHIFY_CHROME to run the real joint-layout browser regression.',
+}, async (t) => {
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-joint-layout-'));
+ const records = [];
+ const evidence = process.env.ARCHIFY_JOINT_LAYOUT_EVIDENCE;
+ if (evidence) fs.mkdirSync(evidence, { recursive: true });
+ let browser;
+ try {
+ function render(name, input, repoRoot) {
+ const file = path.join(scratch, `${name}.html`);
+ execFileSync(process.execPath, [path.join(skillRoot, 'bin/archify.mjs'),
+ 'render', 'architecture', path.resolve(skillRoot, input), file,
+ ...(repoRoot ? ['--repo-root', repoRoot] : [])], { stdio: 'pipe' });
+ return file;
+ }
+ // Use the existing evidence-browser fixture pattern so preservation covers
+ // a verified, nonempty source payload, not just an absent script element.
+ const repo = path.join(scratch, 'source-repo');
+ fs.mkdirSync(repo);
+ fs.writeFileSync(path.join(repo, 'source.js'), 'export function source() {\n return true;\n}\n');
+ const git = (...args) => execFileSync('git', ['-C', repo, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+ git('init');
+ git('add', 'source.js');
+ git('-c', 'user.name=Archify Tests', '-c', '[email protected]', '-c', 'commit.gpgsign=false', 'commit', '-m', 'source fixture');
+ git('remote', 'add', 'origin', 'https://github.com/example/evidence-repo');
+ const wideSource = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples/web-app.architecture.json'), 'utf8'));
+ wideSource.meta.repository = { url: 'https://github.com/example/evidence-repo', revision: git('rev-parse', 'HEAD') };
+ wideSource.components[0].sources = [{ path: 'source.js', line: 1, end_line: 3 }];
+ const wideInput = path.join(repo, 'wide.json');
+ fs.writeFileSync(wideInput, JSON.stringify(wideSource));
+ const wide = render('wide', wideInput, repo);
+ const intrinsic = render('intrinsic', 'test/fixtures/architecture-viewport/route-expanded-worldscope.architecture.json');
+ const pristine = new Map([wide, intrinsic].map(file => [file, fs.readFileSync(file, 'utf8')]));
+ function variant(name, base, { before = '', after = '' } = {}) {
+ let html = pristine.get(base);
+ const anchor = ' <script>\n var Archify = {};';
+ assert.ok(html.includes(anchor), 'Viewer fixture anchor');
+ if (before) html = html.replace(anchor, () => ` <script>${before}</script>\n${anchor}`);
+ if (after) html = html.replace('</body>', () => `<script>${after}</script>\n</body>`);
+ const file = path.join(scratch, `${name}.html`);
+ fs.writeFileSync(file, html);
+ return file;
+ }
+ browser = new ChromeVisualBrowser(chrome);
+ const session = await browser.sessionPromise;
+ const send = (method, params = {}) => browser.cdp.send(method, params, session);
+ const evaluate = async (expression, awaitPromise = false) => {
+ const result = await send('Runtime.evaluate', { expression, awaitPromise, returnByValue: true });
+ assert.equal(result.exceptionDetails, undefined, result.exceptionDetails?.exception?.description || result.exceptionDetails?.text);
+ return result.result?.value;
+ };
+ await send('Page.addScriptToEvaluateOnNewDocument', { source: `${observerCounters};\n${pageHelpers}` });
+ await browser.cdp.send('Browser.setDownloadBehavior', { behavior: 'deny' });
+ async function viewport(width = 1440, height = 900) {
+ await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false });
+ }
+ async function load(file = wide, { width = 1440, height = 900, theme = 'light' } = {}) {
+ await viewport(width, height);
+ await send('Emulation.setEmulatedMedia', { media: '', features: [{ name: 'prefers-reduced-motion', value: 'reduce' }] });
+ const loaded = browser.cdp.waitFor('Page.loadEventFired', session);
+ const navigation = await send('Page.navigate', { url: pathToFileURL(file).href + `?theme=${theme}` });
+ assert.equal(navigation.errorText, undefined);
+ await loaded;
+ await evaluate(helperSetupAssertion);
+ await evaluate(`document.documentElement.setAttribute('data-motion', 'still');
+ document.querySelector('.diagram-container').setAttribute('data-detail-level', 'read');`);
+ }
+ function compare(result, label) {
+ assert.deepEqual(result.errors, [], `${label}: Viewer errors`);
+ assert.equal(result.firstDeviation, null, `${label}: geometry changed after resolution: ${JSON.stringify(result.firstDeviation)}`);
+ for (const key of ['later', 'legacy', 'second']) {
+ assert.deepEqual(result.immediate, result[key], `${label}: joint resolution differs from ${key}`);
+ }
+ records.push({ label, ...result });
+ return result.immediate;
+ }
+ async function joint(label, setup = '') {
+ return compare(await evaluate(`(async () => {
+ ${setup}
+ await Archify.layoutStability.whenStable();
+ const immediate = __jointRaw();
+ return __jointCompare(immediate);
+ })()`, true), label);
+ }
+ function clearStage(raw, label) {
+ assert.ok(raw.reserve > 0, `${label}: reserve`);
+ assert.ok(raw.gap >= 9, `${label}: stage gap ${raw.gap}`);
+ assert.equal(raw.overlap, 0, `${label}: dock/stage overlap`);
+ assert.equal(raw.rail, 'true', label);
+ assert.equal(raw.rootRail, 'true', label);
+ assert.ok(raw.dimensions[2] <= raw.dimensions[0], `${label}: horizontal containment`);
+ }
+ function unchanged(before, after, label) {
+ for (const key of ['viewBox', 'authoredSemantic', 'payloads']) assert.deepEqual(after[key], before[key], `${label}: ${key}`);
+ }
+ function preservedState(raw) {
+ // Baseline resize also recomputes runtime legend decorations. Exclude
+ // only those live values from CROSS-state return equality; compare()
+ // above still checks every original raw field within each state.
+ const preserved = { ...raw };
+ delete preserved.semantic;
+ preserved.boxes = raw.boxes.filter(([selector]) => selector !== '[data-legend]');
+ return preserved;
+ }
+ async function canonicalExport() {
+ return evaluate(`(async () => {
+ const create = URL.createObjectURL;
+ const click = HTMLAnchorElement.prototype.click;
+ let svg;
+ URL.createObjectURL = function(blob) {
+ if (blob.type.startsWith('image/svg+xml')) svg = blob;
+ return create.call(URL, blob);
+ };
+ HTMLAnchorElement.prototype.click = function() {};
+ try {
+ await Archify.exportMenu.run('svg');
+ if (!svg) throw new Error('Canonical SVG export was not captured');
+ return { text: await svg.text(), canonical: document.documentElement.getAttribute('data-last-export-canonical') };
+ } finally { URL.createObjectURL = create; HTMLAnchorElement.prototype.click = click; }
+ })()`, true);
+ }
+
+ await t.test('CLI visits all six fresh states and captures immediate geometry before collecting metrics', async () => {
+ const instrumented = variant('cli', intrinsic, { after: `
+ ${helperSetupAssertion}
+ window.__jointCalls = { joint: 0, chrome: 0 };
+ const joint = Archify.layoutStability.whenStable;
+ const chrome = Archify.viewerChromeLayout.whenStable;
+ Archify.layoutStability.whenStable = function() {
+ __jointCalls.joint++;
+ return joint().then(result => { window.__jointAtResolution = __jointRaw(); return result; });
+ };
+ Archify.viewerChromeLayout.whenStable = function() { __jointCalls.chrome++; return chrome(); };
+ ` });
+ const states = [];
+ const result = await runVisualCheck({ artifactPath: instrumented, chromePath: chrome,
+ browserFactory: async () => ({
+ inspect: async options => {
+ const metrics = await browser.inspect(options);
+ assert.deepEqual(await evaluate('__jointCalls'), { joint: 1, chrome: 0 }, 'one CLI joint call; no legacy Chrome call');
+ const raw = compare(await evaluate('__jointCompare(__jointAtResolution)', true), `cli-${options.width}-${options.height}-${options.theme}`);
+ clearStage(raw, 'CLI');
+ assert.deepEqual(raw.dimensions.slice(0, 2), [options.width, options.height], 'actual raw viewport');
+ assert.deepEqual([metrics.innerWidth, metrics.innerHeight], [options.width, options.height], 'actual CLI metrics viewport');
+ assert.equal(raw.theme, options.theme);
+ assert.equal(raw.viewBox, '0 0 980 678');
+ assert.equal(raw.readerFit, 'intrinsic-height');
+ states.push([options.width, options.height, options.theme]);
+ return metrics;
+ },
+ // The suite owns one browser; the CLI wrapper owns no process.
+ close: async () => {},
+ }),
+ });
+ assert.equal(result.exitCode, 0, JSON.stringify(result.receipt));
+ assert.deepEqual(states, [[1440, 900, 'light'], [1600, 1000, 'light'], [1920, 1080, 'light'],
+ [2048, 1320, 'light'], [1440, 900, 'dark'], [2048, 1320, 'dark']]);
+ assert.deepEqual(result.receipt.containment.viewports.map(value => [value.width, value.height]), states.slice(0, 4).map(value => value.slice(0, 2)));
+ assert.deepEqual(result.receipt.readability.viewports.map(value => [value.width, value.height]), states.slice(0, 4).map(value => value.slice(0, 2)));
+ });
+
+ await t.test('native observer feedback converges through reserve and adaptive overflow without changing canonical SVG', async () => {
+ await load();
+ const before = await joint('feedback-before');
+ clearStage(before, 'feedback-before');
+ assert.equal(before.reader, 'adaptive');
+ const sourcePayload = before.payloads.find(([id]) => id === 'archify-source-evidence-data');
+ assert.ok(sourcePayload, 'fixture has embedded verified source evidence');
+ assert.equal(JSON.parse(sourcePayload[1]).verified, true);
+ const exportedBefore = await canonicalExport();
+ assert.equal(exportedBefore.canonical, 'true');
+ const after = await joint('feedback-after', `
+ Object.keys(__jointObservers).forEach(key => { __jointObservers[key] = 0; });
+ document.querySelector('.diagram-nav').style.height = '110px';
+ document.querySelector('.header').style.minHeight = '240px';
+ document.querySelector('.cards').insertAdjacentHTML('beforeend', '<div class="card" style="height:1200px">Late supporting content</div>');
+ document.documentElement.setAttribute('data-preset', 'blueprint');
+ `);
+ clearStage(after, 'feedback-after');
+ assert.equal(after.overflow, 'authored');
+ assert.ok(after.dimensions[3] > after.dimensions[1]);
+ assert.ok(after.reserve > before.reserve, 'nav resize adds reserve and schedules Reader');
+ assert.ok(parseFloat(after.readerWidth) <= parseFloat(before.readerWidth));
+ const counts = await evaluate('__jointObservers');
+ for (const [name, count] of Object.entries(counts)) assert.ok(count > 0, `native ${name}: ${JSON.stringify(counts)}`);
+ unchanged(before, after, 'observer feedback');
+ // Restore the visual preset before comparing complete canonical exports.
+ await joint('feedback-restored-preset', `document.documentElement.setAttribute('data-preset', ${JSON.stringify(before.preset)});`);
+ // Export is intentionally after every immediate/raw geometry assertion.
+ const exportedAfter = await canonicalExport();
+ assert.equal(exportedAfter.canonical, 'true');
+ assert.equal(exportedAfter.text, exportedBefore.text, 'Reader/Chrome changes preserve canonical SVG bytes');
+ });
+
+ await t.test('a deferred or rejected reader-only reprobe blocks joint resolution and coalesces', async () => {
+ for (const reject of [false, true]) {
+ await load();
+ const before = await joint(`probe-before-${reject}`);
+ const result = await evaluate(`(async () => {
+ const original = Archify.readerLayout.whenStable;
+ let release;
+ const gate = new Promise((resolve, reject) => { release = ${reject} ? () => reject(new Error('held reader probe')) : resolve; });
+ Archify.readerLayout.whenStable = () => gate;
+ try {
+ const first = Archify.viewerChromeLayout.reprobe();
+ const second = Archify.viewerChromeLayout.reprobe();
+ let resolved = false;
+ const waiting = Archify.layoutStability.whenStable().then(() => { resolved = true; return __jointRaw(); });
+ await __jointFrames(12);
+ const pending = { resolved, same: first === second,
+ reserve: document.querySelector('.diagram-container').style.getPropertyValue('--archify-nav-reserve') };
+ Archify.readerLayout.whenStable = original;
+ release();
+ const immediate = await waiting;
+ return { pending, probeResult: await first, comparisons: await __jointCompare(immediate) };
+ } finally { Archify.readerLayout.whenStable = original; release(); }
+ })()`, true);
+ assert.deepEqual(result.pending, { resolved: false, same: true, reserve: '' });
+ assert.equal(result.probeResult, true);
+ const after = compare(result.comparisons, `probe-after-${reject}`);
+ clearStage(after, 'probe return');
+ unchanged(before, after, 'probe');
+ }
+ });
+
+ await t.test('initial font readiness blocks the gate through changed nav and reader content', async () => {
+ const delayed = variant('initial-font-gate', wide, { before: `
+ window.__jointNativeFonts = document.fonts;
+ window.__jointFontGate = { status: 'loading', ready: new Promise(resolve => { window.__jointReleaseInitialFont = resolve; }) };
+ Object.defineProperty(document, 'fonts', { configurable: true, value: __jointFontGate });
+ ` });
+ await load(delayed);
+ const result = await evaluate(`(async () => {
+ let resolved = false;
+ const waiting = Archify.layoutStability.whenStable().then(() => { resolved = true; return __jointRaw(); });
+ document.querySelector('.diagram-nav').style.height = '100px';
+ document.querySelector('.cards').style.minHeight = '450px';
+ await __jointFrames(12);
+ const beforeReady = resolved;
+ __jointFontGate.status = 'loaded';
+ __jointReleaseInitialFont();
+ const immediate = await waiting;
+ const comparisons = await __jointCompare(immediate);
+ Object.defineProperty(document, 'fonts', { configurable: true, value: __jointNativeFonts });
+ return { beforeReady, comparisons };
+ })()`, true);
+ assert.equal(result.beforeReady, false);
+ clearStage(compare(result.comparisons, 'initial-font-ready'), 'initial-font-ready');
+ });
+
+ await t.test('a new native font cycle active during sampling cannot resolve before font/layout readiness', async () => {
+ await load();
+ const before = await joint('late-font-before');
+ // The final bundled face is the Latin subset, including the title text.
+ const encoded = [...pristine.get(wide).matchAll(/data:font\/woff2;base64,([A-Za-z0-9+/=]+)/g)].at(-1)?.[1];
+ assert.ok(encoded, 'use the artifact own bundled WOFF2 bytes');
+ await send('Fetch.enable', { patterns: [{ urlPattern: 'https://archify-joint-font.test/*', resourceType: 'Font', requestStage: 'Request' }] });
+ const requested = browser.cdp.waitFor('Fetch.requestPaused', session);
+ // Observe both outcomes immediately so a request timeout cannot become an
+ // unhandled rejection if a preceding page assertion fails.
+ const requestOutcome = requested.then(value => ({ value }), error => ({ error }));
+ try {
+ const held = await evaluate(`(async () => {
+ const run = window.__jointFontRun = { resolved: false };
+ run.ready = Archify.layoutStability.whenStable().then(() => {
+ run.resolved = true;
+ run.immediate = __jointRaw();
+ run.faceAtResolution = run.face.status;
+ return run.immediate;
+ });
+ await __jointFrames(1);
+ run.resolvedAtStart = run.resolved;
+ run.face = new FontFace('JointLateFont', 'url("https://archify-joint-font.test/native.woff2")');
+ document.fonts.add(run.face);
+ document.querySelector('.header h1').style.fontFamily = 'JointLateFont, monospace';
+ run.loaded = run.face.load().then(() => {
+ document.querySelector('.diagram-nav').style.height = '115px';
+ document.querySelector('.cards').style.minHeight = '390px';
+ });
+ // Register a handler immediately; the awaited copy below still fails.
+ run.loaded.catch(() => {});
+ await __jointFrames(12);
+ return { resolvedAtStart: run.resolvedAtStart, resolvedWhileLoading: run.resolved,
+ fonts: document.fonts.status, face: run.face.status };
+ })()`, true);
+ const outcome = await requestOutcome;
+ if (outcome.error) throw outcome.error;
+ assert.deepEqual(held, { resolvedAtStart: false, resolvedWhileLoading: false, fonts: 'loading', face: 'loading' });
+ await send('Fetch.fulfillRequest', { requestId: outcome.value.requestId, responseCode: 200,
+ responseHeaders: [{ name: 'Content-Type', value: 'font/woff2' }, { name: 'Access-Control-Allow-Origin', value: '*' }], body: encoded });
+ const result = await evaluate(`(async () => {
+ const run = __jointFontRun;
+ await run.loaded;
+ const immediate = await run.ready;
+ return { faceAtResolution: run.faceAtResolution, comparisons: await __jointCompare(immediate) };
+ })()`, true);
+ assert.equal(result.faceAtResolution, 'loaded');
+ const after = compare(result.comparisons, 'native-late-font');
+ assert.equal(after.fonts, 'loaded');
+ clearStage(after, 'native-late-font');
+ unchanged(before, after, 'native font');
+ } finally { await send('Fetch.disable'); }
+ });
+
+ await t.test('intrinsic-height overflow, resize bursts, and mode returns converge at baseline camera', async () => {
+ await load(intrinsic);
+ const before = await joint('intrinsic-before');
+ assert.equal(before.readerFit, 'intrinsic-height');
+ const exportedBefore = await canonicalExport();
+ assert.equal(exportedBefore.canonical, 'true');
+ const overflow = await joint('intrinsic-overflow', `document.querySelector('.cards').style.minHeight = '1200px';`);
+ assert.equal(overflow.overflow, 'authored');
+ clearStage(overflow, 'intrinsic overflow');
+ unchanged(before, overflow, 'intrinsic overflow');
+ await joint('intrinsic-content-restored', `document.querySelector('.cards').style.minHeight = '';`);
+ for (const mode of ['embed', 'present', 'print']) {
+ if (mode === 'print') {
+ await send('Emulation.setEmulatedMedia', { media: 'print' });
+ await evaluate(`dispatchEvent(new Event('beforeprint'))`);
+ } else await evaluate(mode === 'present' ? 'Archify.presentation.enter()'
+ : `document.documentElement.setAttribute('data-embed', 'true')`);
+ const entered = await joint(`${mode}-entered`);
+ assert.equal(entered.reader, null);
+ if (mode !== 'present') assert.equal(entered.reserve, 0);
+ if (mode === 'print') {
+ await send('Emulation.setEmulatedMedia', { media: '' });
+ await evaluate(`dispatchEvent(new Event('afterprint'))`);
+ } else await evaluate(mode === 'present' ? 'Archify.presentation.exit()'
+ : `document.documentElement.removeAttribute('data-embed')`);
+ const returned = await joint(`${mode}-returned`);
+ clearStage(returned, `${mode} return`);
+ unchanged(before, returned, `${mode} return`);
+ }
+ await viewport(1600, 1000);
+ const resized = await joint('resize-theme-burst', `
+ for (let i = 0; i < 20; i++) dispatchEvent(new Event('resize'));
+ document.documentElement.setAttribute('data-theme', 'dark');
+ `);
+ clearStage(resized, 'resize/theme burst');
+ assert.equal(resized.theme, 'dark');
+ unchanged(before, resized, 'resize/theme');
+ await viewport();
+ const restored = await joint('resize-theme-return', `document.documentElement.setAttribute('data-theme', 'light');`);
+ assert.deepEqual(preservedState(restored), preservedState(before), 'return to original authored and Viewer frame geometry');
+ const exportedAfter = await canonicalExport();
+ assert.equal(exportedAfter.canonical, 'true');
+ assert.equal(exportedAfter.text, exportedBefore.text, 'resize and mode returns preserve canonical SVG bytes');
+ });
+
+ await t.test('optional-observer fallback retains joint scheduling on viewport changes', async () => {
+ const fallback = variant('no-observers', wide, { before: 'window.ResizeObserver = undefined; window.MutationObserver = undefined;' });
+ await load(fallback);
+ const before = await joint('fallback-before');
+ await viewport(720, 900);
+ const mobile = await joint('fallback-mobile');
+ assert.equal(mobile.reader, null);
+ assert.equal(mobile.reserve, 0);
+ await viewport();
+ const after = await joint('fallback-return');
+ clearStage(after, 'fallback return');
+ assert.deepEqual(after, before);
+ });
+ for (const [file, original] of pristine) assert.equal(fs.readFileSync(file, 'utf8'), original, 'canonical artifact bytes remain untouched');
+ } finally {
+ if (evidence) fs.writeFileSync(path.join(evidence, 'joint-layout-observations.json'), `${JSON.stringify(records, null, 2)}\n`);
+ if (browser) await browser.close();
+ fs.rmSync(scratch, { recursive: true, force: true });
+ }
+});
diff --git a/archify/test/joint-layout-contract.test.mjs b/archify/test/joint-layout-contract.test.mjs
new file mode 100644
index 00000000..ae392c38
--- /dev/null
+++ b/archify/test/joint-layout-contract.test.mjs
@@ -0,0 +1,347 @@
+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 vm from 'node:vm';
+import { EventEmitter } from 'node:events';
+import { fileURLToPath } from 'node:url';
+import { ChromeVisualBrowser, runVisualCheck } from '../bin/visual-check.mjs';
+
+// Minimal 1x1 PNG so visual-check's capture path has bytes to persist.
+const PNG_STUB = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==';
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
+const template = fs.readFileSync(path.join(root, 'viewer/template.source.html'), 'utf8');
+const helper = template.slice(template.indexOf(' const archifyLayoutOwners ='), template.indexOf('/* ARCHIFY:READER_LAYOUT */'));
+const joint = template.slice(template.indexOf(' Archify.layoutStability ='), template.indexOf('/* ARCHIFY:CAMERA */'));
+
+function fixture({ readerPending = () => false, chromePending = () => false,
+ readerSnapshot = () => 'reader|original', chromeSnapshot = () => 'chrome|original', fonts } = {}) {
+ let frame = 0;
+ let nextId = 0;
+ const frames = [];
+ const scheduled = [];
+ const context = vm.createContext({
+ Archify: {},
+ document: { fonts: fonts || { status: 'loaded', ready: Promise.resolve() } },
+ requestAnimationFrame(callback) { frames.push(callback); return ++nextId; },
+ owners: {
+ reader: { schedule() { scheduled.push('reader'); }, pending: () => readerPending(frame), snapshot: () => readerSnapshot(frame) },
+ viewerChrome: { schedule() { scheduled.push('chrome'); }, pending: () => chromePending(frame), snapshot: () => chromeSnapshot(frame) },
+ },
+ });
+ vm.runInContext(helper + '\narchifyLayoutOwners.reader = owners.reader; archifyLayoutOwners.viewerChrome = owners.viewerChrome;\n' + joint, context);
+ const microtasks = async () => { for (let i = 0; i < 12; i++) await Promise.resolve(); };
+ async function tick(before = () => {}) {
+ await microtasks();
+ frame += 1;
+ before(frame);
+ const callbacks = frames.splice(0);
+ for (const callback of callbacks) callback(frame * (1000 / 60));
+ await microtasks();
+ }
+ async function settle(promise, { limit = 1000, before } = {}) {
+ let done = false;
+ let value;
+ let error;
+ promise.then(result => { done = true; value = result; }, reason => { done = true; error = reason; });
+ for (let i = 0; i < limit && !done; i++) await tick(before);
+ assert.ok(done, 'synthetic frame queue must settle within its explicit test budget');
+ return { value, error, frame };
+ }
+ return { context, scheduled, frames, tick, settle, get frame() { return frame; },
+ wait: () => context.Archify.layoutStability.whenStable(),
+ local: owner => context.Archify.waitForStableLayout(context.owners[owner]),
+ };
+}
+
+test('joint contract schedules both private owners and compares an unambiguous tuple for three equal comparisons', async () => {
+ const f = fixture();
+ const result = await f.settle(f.wait());
+ assert.ifError(result.error);
+ assert.deepEqual(f.scheduled, ['reader', 'chrome']);
+ assert.equal(result.value.sampledFrames, 4);
+ assert.deepEqual(JSON.parse(result.value.snapshot), [['reader', 'reader|original'], ['viewerChrome', 'chrome|original']]);
+ assert.deepEqual(Object.keys(f.context.Archify.layoutStability), ['whenStable']);
+ assert.equal(Object.hasOwn(f.context, 'archifyLayoutOwners'), false, 'descriptors must not become a window property');
+});
+
+for (const owner of ['reader', 'chrome']) {
+ test(`joint contract blocks ${owner}-only pending work and restarts all stable comparisons`, async () => {
+ const f = fixture({ [`${owner}Pending`]: frame => frame === 3 || frame === 4 });
+ const result = await f.settle(f.wait());
+ assert.ifError(result.error);
+ assert.equal(result.value.sampledFrames, 8);
+ });
+ test(`joint contract resets comparisons when only the ${owner} snapshot changes without pending work`, async () => {
+ const f = fixture({ [`${owner}Snapshot`]: frame => frame < 3 ? 'before' : 'after' });
+ const result = await f.settle(f.wait());
+ assert.ifError(result.error);
+ assert.equal(result.value.sampledFrames, 6);
+ });
+}
+
+test('joint sampling starts only after initial font readiness and handles an active later font cycle', async () => {
+ let release;
+ const fonts = { status: 'loading', ready: new Promise(resolve => { release = resolve; }) };
+ const f = fixture({ fonts });
+ const waiting = f.wait();
+ await f.tick();
+ await f.tick();
+ assert.deepEqual(f.scheduled, []);
+ fonts.status = 'loaded';
+ release();
+ let releaseLater;
+ const result = await f.settle(waiting, { before(frame) {
+ if (frame === 5) {
+ fonts.status = 'loading';
+ fonts.ready = new Promise(resolve => { releaseLater = resolve; });
+ }
+ if (frame === 12) fonts.status = 'loaded';
+ if (frame === 14) releaseLater();
+ } });
+ assert.ifError(result.error);
+ assert.ok(result.frame >= 18, 'current fonts.ready, not only its status, must finish before a new stable-frame streak');
+ assert.deepEqual(f.scheduled, ['reader', 'chrome', 'reader', 'chrome']);
+});
+
+test('joint pending keeps an in-flight baseline reprobe from passing even when frame handles would be idle', async () => {
+ const f = fixture({ chromePending: frame => frame < 12 });
+ const result = await f.settle(f.wait());
+ assert.ifError(result.error);
+ assert.equal(result.value.sampledFrames, 15);
+});
+
+test('budget policy A: joint non-convergence rejects at 960 while local defaults still reject at 240', async () => {
+ const combined = fixture({ readerPending: () => true });
+ const result = await combined.settle(combined.wait());
+ assert.match(result.error?.message || '', /Joint reader and viewer chrome layout did not reach stable dimensions/);
+ assert.equal(result.frame, 960);
+ for (const owner of ['reader', 'viewerChrome']) {
+ const local = fixture({ readerPending: () => true, chromePending: () => true });
+ const rejected = await local.settle(local.local(owner));
+ assert.match(rejected.error?.message || '', /did not reach stable dimensions/);
+ assert.equal(rejected.frame, 240, `${owner}: unchanged local default`);
+ }
+});
+
+test('budget policy A accepts the original staged case that legacy also accepts', async t => {
+ const options = { readerPending: frame => frame < 230, chromePending: frame => frame < 250 };
+ const combined = fixture(options);
+ const jointResult = await combined.settle(combined.wait());
+ assert.ifError(jointResult.error);
+ assert.equal(jointResult.frame, 253);
+
+ const original = fixture(options);
+ const legacy = original.local('reader')
+ .then(() => original.local('viewerChrome'))
+ .then(() => original.local('reader'))
+ .then(() => original.local('viewerChrome'));
+ const legacyResult = await original.settle(legacy);
+ assert.ifError(legacyResult.error);
+ assert.equal(legacyResult.frame, 261);
+ t.diagnostic('Disclosed policy change: one joint budget is 960; each legacy local budget remains 240. This staged case passes both, but the policies are not equivalent.');
+});
+
+test('budget policy A newly accepts single-owner work at frame 250 that legacy rejects at 240', async t => {
+ const options = { readerPending: frame => frame < 250 };
+ const combined = fixture(options);
+ const accepted = await combined.settle(combined.wait());
+ assert.ifError(accepted.error);
+ assert.equal(accepted.frame, 253);
+ const original = fixture(options);
+ const legacy = original.local('reader')
+ .then(() => original.local('viewerChrome'))
+ .then(() => original.local('reader'))
+ .then(() => original.local('viewerChrome'));
+ const rejected = await original.settle(legacy);
+ assert.match(rejected.error?.message || '', /did not reach stable dimensions/);
+ assert.equal(rejected.frame, 240);
+ assert.deepEqual(original.scheduled, ['reader'], 'legacy stops on its first owner failure');
+ t.diagnostic('New acceptance is intentional and explicit: joint accepts frame250 owner completion; original four-step policy rejects that first owner at frame240.');
+});
+
+test('late cross-owner feedback restarts the combined streak throughout the expanded budget', async () => {
+ const f = fixture({
+ readerPending: frame => frame < 230 || frame === 942 || frame === 943,
+ chromePending: frame => frame >= 232 && frame < 940,
+ readerSnapshot: frame => frame < 943 ? 'reader-before' : 'reader-after',
+ chromeSnapshot: frame => frame < 942 ? 'chrome-before' : 'chrome-after',
+ });
+ const result = await f.settle(f.wait());
+ assert.ifError(result.error);
+ assert.equal(result.frame, 947, 'late feedback from either owner must reset all three comparisons');
+ assert.deepEqual(JSON.parse(result.value.snapshot), [['reader', 'reader-after'], ['viewerChrome', 'chrome-after']]);
+});
+
+test('late owner work before the last comparison rejects at 960 instead of falsely passing', async () => {
+ const f = fixture({ readerPending: frame => frame >= 959, chromePending: frame => frame < 956 });
+ const result = await f.settle(f.wait());
+ assert.match(result.error?.message || '', /did not reach stable dimensions/);
+ assert.equal(result.frame, 960);
+});
+
+// Exercise the actual unchanged PipeCdp implementation and CLI inspection with
+// a fake transport/clock. No Chrome process and no real 15-second sleep needed.
+// Frame and wall-clock limits are independent: the CLI can time out before960.
+test('forever-pending joint inspection still fails at the unchanged 15000ms CDP boundary without fallback', async () => {
+ const visualSource = fs.readFileSync(path.join(root, 'archify/bin/visual-check.mjs'), 'utf8');
+ const pipeSource = visualSource.slice(visualSource.indexOf('class PipeCdp {'), visualSource.indexOf('export function chromeVisualBrowserArgs'));
+ const timers = new Map();
+ let nextTimer = 0;
+ let now = 0;
+ const clockContext = vm.createContext({
+ Buffer,
+ process,
+ setTimeout(callback, delay) { const id = ++nextTimer; timers.set(id, { callback, deadline: now + delay }); return id; },
+ clearTimeout(id) { timers.delete(id); },
+ });
+ const PipeCdp = vm.runInContext(pipeSource + '\nPipeCdp', clockContext);
+ const f = fixture({ readerPending: () => true });
+ const localCalls = [];
+ f.context.window = { Archify: f.context.Archify };
+ f.context.document.documentElement = { setAttribute() {} };
+ f.context.document.querySelector = () => null;
+ f.context.Archify.readerLayout = { whenStable() { localCalls.push('reader'); return Promise.resolve(); } };
+ f.context.Archify.viewerChromeLayout = { whenStable() { localCalls.push('chrome'); return Promise.resolve(); } };
+ const sent = [];
+ const read = new EventEmitter();
+ read.setEncoding = () => {};
+ const write = new EventEmitter();
+ write.write = (raw, callback) => {
+ const message = JSON.parse(raw.slice(0, -1));
+ sent.push(message);
+ queueMicrotask(() => {
+ const respond = result => read.emit('data', JSON.stringify({ id: message.id, result }) + '\0');
+ if (message.method === 'Runtime.evaluate') {
+ Promise.resolve().then(() => vm.runInContext(message.params.expression, f.context))
+ .then(value => respond({ result: { value } }), error => respond({ exceptionDetails: { exception: { description: error.message } } }));
+ } else {
+ respond({});
+ if (message.method === 'Page.navigate') read.emit('data', JSON.stringify({ method: 'Page.loadEventFired', sessionId: 'test-session', params: {} }) + '\0');
+ }
+ callback();
+ });
+ };
+ const child = new EventEmitter();
+ child.stdio = [null, null, null, write, read];
+ const browser = Object.create(ChromeVisualBrowser.prototype);
+ browser.sessionPromise = Promise.resolve('test-session');
+ browser.cdp = new PipeCdp(child);
+ let settled = false;
+ const outcome = browser.inspect({ artifactPath: '/tmp/forever-pending.html', width: 1440, height: 900, theme: 'light' })
+ .then(value => { settled = true; return { value }; }, error => { settled = true; return { error }; });
+ for (let i = 0; i < 50 && !sent.some(message => message.method === 'Runtime.evaluate'); i++) await Promise.resolve();
+ assert.equal(sent.filter(message => message.method === 'Runtime.evaluate').length, 1);
+ for (let frame = 0; frame < 899; frame++) await f.tick();
+ now = 14999;
+ assert.equal(settled, false);
+ assert.equal(timers.size, 1);
+ const [[timerId, { callback, deadline }]] = timers.entries();
+ assert.equal(deadline, 15000, 'real PipeCdp.send default, not a larger budget-derived timeout');
+ now = 15000;
+ timers.delete(timerId);
+ callback();
+ const result = await outcome;
+ assert.equal(result.error?.code, 'ERR_CHROME_CDP_TIMEOUT');
+ assert.equal(result.error?.method, 'Runtime.evaluate');
+ assert.match(result.error?.message || '', /timed out after 15000ms/);
+ assert.equal(f.frame, 899, 'CLI can reject before the 960-frame sampler ceiling');
+ assert.equal(browser.cdp.pending.size, 0);
+ assert.equal(timers.size, 0);
+ assert.deepEqual(localCalls, [], 'CDP failure cannot trigger a legacy recovery path');
+ assert.equal(sent.filter(message => message.method === 'Runtime.evaluate').length, 1, 'no metrics evaluation after timeout');
+});
+
+function inspection({ capability = true, rejectJoint = false, localMethods = true } = {}) {
+ const calls = [];
+ const states = [];
+ let current = {};
+ let rafCount = 0;
+ const Archify = {};
+ if (localMethods) {
+ Archify.readerLayout = { whenStable: async () => { calls.push('reader'); } };
+ Archify.viewerChromeLayout = { whenStable: async () => { calls.push('chrome'); } };
+ }
+ if (capability) Archify.layoutStability = { whenStable: async () => {
+ calls.push('joint');
+ if (rejectJoint) throw new Error('joint rejection fixture');
+ } };
+ const page = vm.createContext({
+ Archify, window: { Archify },
+ document: { documentElement: { setAttribute() {} }, querySelector: () => null,
+ fonts: { ready: Promise.resolve(), status: 'loaded' } },
+ requestAnimationFrame(callback) { rafCount++; queueMicrotask(callback); },
+ });
+ const browser = Object.create(ChromeVisualBrowser.prototype);
+ browser.sessionPromise = Promise.resolve('test-session');
+ browser.close = async () => {};
+ browser.cdp = {
+ waitFor: async () => ({}),
+ async send(method, params) {
+ if (method === 'Emulation.setDeviceMetricsOverride') current = { width: params.width, height: params.height };
+ if (method === 'Page.navigate') {
+ current.theme = new URL(params.url).searchParams.get('theme');
+ states.push({ ...current });
+ }
+ if (method === 'Runtime.evaluate' && params.awaitPromise) {
+ try {
+ await vm.runInContext(params.expression, page);
+ return { result: { value: null } };
+ } catch (error) {
+ return { exceptionDetails: { exception: { description: error.message } } };
+ }
+ }
+ if (method === 'Page.captureScreenshot') return { data: PNG_STUB };
+ if (method === 'Runtime.evaluate') return { result: { value: {
+ innerWidth: current.width, innerHeight: current.height, scrollWidth: current.width, scrollHeight: current.height,
+ resolvedTheme: current.theme, minimumProjectedNodeTextPx: 12, hasNavigationDock: false,
+ legendDockIntersectionArea: 0, dockStageIntersectionArea: 0, viewerChromeRequiredGap: 10,
+ } } };
+ return {};
+ },
+ };
+ return { browser, calls, states, get rafCount() { return rafCount; } };
+}
+
+test('CLI inspection calls the new capability once and propagates its rejection without legacy recovery', async () => {
+ const passing = inspection();
+ await passing.browser.inspect({ artifactPath: '/tmp/joint-contract.html', width: 1440, height: 900, theme: 'light' });
+ assert.deepEqual(passing.calls, ['joint']);
+ const failing = inspection({ rejectJoint: true });
+ await assert.rejects(failing.browser.inspect({ artifactPath: '/tmp/joint-contract.html', width: 1440, height: 900, theme: 'light' }), /joint rejection fixture/);
+ assert.deepEqual(failing.calls, ['joint']);
+});
+
+test('old artifacts keep the exact four local waits and no-layout artifacts keep the two-rAF fallback', async () => {
+ const legacy = inspection({ capability: false });
+ await legacy.browser.inspect({ artifactPath: '/tmp/joint-contract.html', width: 1440, height: 900, theme: 'light' });
+ assert.deepEqual(legacy.calls, ['reader', 'chrome', 'reader', 'chrome']);
+ assert.equal(legacy.rafCount, 0);
+ const absent = inspection({ capability: false, localMethods: false });
+ await absent.browser.inspect({ artifactPath: '/tmp/joint-contract.html', width: 1440, height: 900, theme: 'light' });
+ assert.equal(absent.rafCount, 2);
+});
+
+test('normal browser evidence retains all six inspections and receipt mappings with the joint capability', async () => {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-joint-contract-'));
+ try {
+ const artifactPath = path.join(directory, 'diagram.html');
+ fs.writeFileSync(artifactPath, '<!doctype html><title>joint fixture</title>');
+ const f = inspection();
+ const result = await runVisualCheck({ artifactPath, chromePath: '/fake/chrome', browserFactory: () => f.browser });
+ assert.equal(result.exitCode, 0);
+ assert.equal(result.receipt.ok, true);
+ assert.deepEqual(f.states, [
+ { width: 1440, height: 900, theme: 'light' }, { width: 1600, height: 1000, theme: 'light' },
+ { width: 1920, height: 1080, theme: 'light' }, { width: 2048, height: 1320, theme: 'light' },
+ { width: 1440, height: 900, theme: 'dark' }, { width: 2048, height: 1320, theme: 'dark' },
+ ]);
+ assert.deepEqual(f.calls, Array(6).fill('joint'));
+ assert.equal(result.receipt.containment.viewports.length, 4);
+ assert.equal(result.receipt.readability.viewports.length, 4);
+ } finally {
+ fs.rmSync(directory, { recursive: true, force: true });
+ }
+});
diff --git a/archify/test/layout-rules.test.mjs b/archify/test/layout-rules.test.mjs
index 72f6fa50..5881501a 100644
--- a/archify/test/layout-rules.test.mjs
+++ b/archify/test/layout-rules.test.mjs
@@ -1813,6 +1813,40 @@ test('architecture: route rhythm warns in standard and blocks a showcase micro s
assert.match(stderr, /wider corridor|move the component/);
});
+test('architecture: automatic reciprocal adjacent routes keep the showcase interior floor', () => {
+ const doc = {
+ schema_version: 1,
+ diagram_type: 'architecture',
+ meta: { title: 'Automatic adjacent request and response', quality_profile: 'showcase' },
+ components: [
+ { id: 'listener', type: 'backend', label: 'Node HTTP listener', pos: [260, 270], size: [170, 78] },
+ { id: 'handler', type: 'backend', label: 'HTTP request handler', pos: [490, 270], size: [180, 84] },
+ ],
+ connections: [
+ { id: 'request-envelope', from: 'listener', to: 'handler', label: 'method · path · body' },
+ { id: 'json-response', from: 'handler', to: 'listener', label: '401 / 400 / 404 / 409 / 202 / 200' },
+ ],
+ };
+ assert.ok(doc.connections.every((connection) => (
+ !('route' in connection) && !('via' in connection) && !('fromSide' in connection) && !('toSide' in connection)
+ )));
+
+ const { code, stderr, outPath } = render('architecture', doc);
+ assert.equal(code, 0, stderr);
+ const html = fs.readFileSync(outPath, 'utf8');
+ for (const id of ['request-envelope', 'json-response']) {
+ const encoded = html.match(new RegExp(
+ `data-edge-id="${id}" data-composition-points="([^"]+)"`,
+ ))?.[1];
+ assert.ok(encoded, `expected rendered composition points for ${id}`);
+ const points = encoded.split(';').map((point) => point.split(',').map(Number));
+ const interiorLengths = points.slice(1, -2).map((point, index) => (
+ Math.abs(point[0] - points[index + 2][0]) + Math.abs(point[1] - points[index + 2][1])
+ ));
+ assert.ok(interiorLengths.every((length) => length >= 16), `${id} has cramped interior: ${encoded}`);
+ }
+});
+
test('architecture: container border run is blocking in standard and showcase', () => {
for (const profile of ['standard', 'showcase']) {
const d = load('architecture');
diff --git a/archify/test/reader-layout-browser.test.mjs b/archify/test/reader-layout-browser.test.mjs
index 9ac63a88..bca06693 100644
--- a/archify/test/reader-layout-browser.test.mjs
+++ b/archify/test/reader-layout-browser.test.mjs
@@ -83,6 +83,7 @@ test('Reader Layout preserves final-artifact behavior across its ownership bound
width: html.style.getPropertyValue('--archify-reader-width'),
layout: html.getAttribute('data-reader-layout'), overflow: html.getAttribute('data-reader-overflow'),
wide: diagram.getAttribute('data-wide-diagram'), shape: html.getAttribute('data-diagram-shape'),
+ readerFit: svg.getAttribute('data-reader-fit'),
geometry: ['viewBox', 'width', 'height'].map(function (name) { return svg.getAttribute(name); }),
shellWidth: document.querySelector('.container').getBoundingClientRect().width,
scrollHeight: Math.max(html.scrollHeight, document.body.scrollHeight),
@@ -107,11 +108,16 @@ test('Reader Layout preserves final-artifact behavior across its ownership bound
assert.deepEqual(await evaluate('window.readerTestErrors'), [], 'Viewer initialization');
if (waitForLayout) await stable();
}
- function variant(name, { ratio, beforeViewer = '' } = {}) {
+ function variant(name, { ratio, undeclaredFit = false, beforeViewer = '' } = {}) {
let html = fs.readFileSync(artifacts.architecture, 'utf8');
if (ratio !== undefined) assert.match(html, /<svg\b[^>]*\bviewBox="[^"]+"/, 'Reader viewBox fixture anchor');
if (beforeViewer) assert.ok(html.includes(' <script>\n var Archify = {};'), 'Reader setup fixture anchor');
if (ratio !== undefined) html = html.replace(/(<svg\b[^>]*\bviewBox=")[^"]+(")/, (_, start, end) => `${start}0 0 ${ratio * 1000} 1000${end}`);
+ if (undeclaredFit) {
+ // Ratio-only cases must not inherit the compiler's independent
+ // intrinsic-height eligibility declaration from the source fixture.
+ html = html.replace(/<svg\b[^>]*>/, root => root.replace(' data-reader-fit="intrinsic-height"', ''));
+ }
if (beforeViewer) html = html.replace(' <script>\n var Archify = {};', () => ` <script>${beforeViewer}</script>\n <script>\n var Archify = {};`);
const file = path.join(scratch, `${name}.html`);
fs.writeFileSync(file, html);
@@ -170,9 +176,17 @@ test('Reader Layout preserves final-artifact behavior across its ownership bound
});
await t.test('ratio and desktop thresholds preserve shape while clearing temporary state', async () => {
+ await load(variant('intrinsic-ratio-1.549', { ratio: 1.549 }));
+ const intrinsic = await snapshot('intrinsic-ratio-1.549');
+ assert.equal(intrinsic.readerFit, 'intrinsic-height');
+ assert.equal(intrinsic.receipt.ratio, 1.549);
+ assert.equal(intrinsic.active, true, 'intrinsic-height remains eligible below the wide-ratio threshold');
+ assert.equal(intrinsic.wide, null);
+ assert.equal(intrinsic.shape, null);
for (const ratio of [1.549, 1.55, 1.551]) {
- await load(variant(`ratio-${ratio}`, { ratio }));
+ await load(variant(`ratio-${ratio}`, { ratio, undeclaredFit: true }));
const before = await snapshot(`ratio-${ratio}`);
+ assert.equal(before.readerFit, null, 'legacy ratio fixture declares no intrinsic fit');
assert.equal(before.active, ratio >= 1.55);
if (ratio < 1.55) inactive(before, false);
for (const width of [1023, 1024, 1025, 1023, 1440]) {
@@ -186,7 +200,7 @@ test('Reader Layout preserves final-artifact behavior across its ownership bound
}
});
- const wide = variant('wide', { ratio: 3 });
+ const wide = variant('wide', { ratio: 3, undeclaredFit: true });
await t.test('desktop budgets, extreme content and limited horizontal space preserve geometry', async () => {
for (const [width, height] of [[1440, 900], [1600, 1000], [1920, 1080], [2048, 1320]]) {
await load(wide, { width, height });
diff --git a/archify/test/reader-readability-maintained-browser.test.mjs b/archify/test/reader-readability-maintained-browser.test.mjs
new file mode 100644
index 00000000..386cb5cc
--- /dev/null
+++ b/archify/test/reader-readability-maintained-browser.test.mjs
@@ -0,0 +1,180 @@
+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 '../bin/visual-check.mjs';
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const chromeConfigured = Object.prototype.hasOwnProperty.call(process.env, 'ARCHIFY_CHROME');
+const chromePath = chromeConfigured ? findChrome() : null;
+if (chromeConfigured && !chromePath) {
+ throw new Error(`ARCHIFY_CHROME does not resolve to an executable browser: ${process.env.ARCHIFY_CHROME}`);
+}
+const fixtureJson = path.join(root, 'test/fixtures/reader-readability/synthetic-wide.architecture.json');
+
+test('declared wide synthetic reader preserves geometry and reaches edge/node readability', {
+ skip: chromePath ? false :
+ 'Set ARCHIFY_CHROME to run the maintained real browser regression.',
+}, async () => {
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-reader-readability-'));
+ const artifact = path.join(scratch, 'synthetic-wide.html');
+ try {
+ execFileSync(process.execPath, [
+ path.join(root, 'bin', 'archify.mjs'), 'deliver', 'architecture', fixtureJson, artifact,
+ '--quality', 'showcase',
+ ], { cwd: root, stdio: 'pipe' });
+ const artifactSource = fs.readFileSync(artifact, 'utf8');
+ const svgStart = artifactSource.indexOf('<svg');
+ const svgEnd = artifactSource.indexOf('</svg>', svgStart) + '</svg>'.length;
+ assert.ok(svgStart >= 0 && svgEnd > svgStart, 'generated artifact must contain a canonical SVG');
+ const canonicalSvg = artifactSource.slice(svgStart, svgEnd);
+ assert.match(canonicalSvg, /viewBox="0 0 1348 706"/);
+ const tallArtifact = path.join(scratch, 'synthetic-wide-tall.html');
+ // With the fixture's 9px minimum label, 2300x1600 yields 1946.67px of
+ // reader width, below the 1984px viewport reserve but above the 1920px
+ // new-wide cap. This keeps the explicit legacy-width guard meaningful.
+ fs.writeFileSync(tallArtifact, artifactSource.replace('viewBox="0 0 1348 706"', 'viewBox="0 0 2300 1600"'));
+
+ const browser = new ChromeVisualBrowser(chromePath);
+ try {
+ const session = await browser.sessionPromise;
+ const send = (method, params = {}) => browser.cdp.send(method, params, session);
+ const evaluate = async (expression, awaitPromise = false) => {
+ const result = await send('Runtime.evaluate', { expression, awaitPromise, returnByValue: true });
+ assert.equal(result.exceptionDetails, undefined, result.exceptionDetails?.exception?.description);
+ return result.result?.value;
+ };
+ await send('Browser.setDownloadBehavior', { behavior: 'deny' });
+ async function stable() {
+ await evaluate(`(async function () {
+ for (var i = 0; i < 2; i += 1) {
+ await Archify.readerLayout.whenStable();
+ await Archify.viewerChromeLayout.whenStable();
+ }
+ })()`, true);
+ }
+ async function load(width, height, theme = 'dark', query = '', print = false, file = artifact) {
+ await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false });
+ await send('Emulation.setEmulatedMedia', { media: print ? 'print' : '', features: [
+ { name: 'prefers-color-scheme', value: theme },
+ ] });
+ const loaded = browser.cdp.waitFor('Page.loadEventFired', session);
+ const result = await send('Page.navigate', { url: pathToFileURL(file).href + `?theme=${theme}${query}` });
+ assert.equal(result.errorText, undefined, result.errorText);
+ await loaded;
+ await evaluate(`(function () {
+ if (Archify.view && Archify.view.reset) Archify.view.reset();
+ if (Archify.motionGovernor && Archify.motionGovernor.setMode) {
+ Archify.motionGovernor.setMode('still');
+ }
+ })()`);
+ await stable();
+ }
+ async function snapshot() {
+ return evaluate(`(function () {
+ var html = document.documentElement;
+ var svg = document.querySelector('.diagram-container > svg');
+ var container = document.querySelector('.diagram-container');
+ var box = svg.viewBox.baseVal;
+ var width = svg.getBoundingClientRect().width;
+ function projected(text) {
+ return parseFloat(text.getAttribute('font-size')) * width / box.width;
+ }
+ var edge = Array.from(svg.querySelectorAll('g[data-detail="context"][data-edge-from][data-edge-to] > text'))
+ .map(projected);
+ var node = Array.from(svg.querySelectorAll(
+ 'text[data-node-label], text[data-boundary-label], text[data-detail="context"]'
+ )).filter(function (text) {
+ return text.getAttribute('data-detail') !== 'context' || text.closest('[data-node-id]');
+ }).map(projected);
+ var chrome = Archify.viewerChromeLayout.receipt();
+ var camera = Archify.view.state();
+ return {
+ active: Archify.readerLayout.active(), receipt: Archify.readerLayout.receipt(),
+ layout: html.getAttribute('data-reader-layout'), overflow: html.getAttribute('data-reader-overflow'),
+ readerFit: svg.getAttribute('data-reader-fit'), minText: svg.getAttribute('data-reader-min-text'),
+ geometry: ['viewBox', 'width', 'height'].map(function (name) { return svg.getAttribute(name); }),
+ edgeCount: edge.length, nodeCount: node.length,
+ edgeMinimum: edge.length ? Math.min.apply(Math, edge) : null,
+ nodeMinimum: node.length ? Math.min.apply(Math, node) : null,
+ edgeFinite: edge.length > 0 && edge.every(Number.isFinite),
+ nodeFinite: node.length > 0 && node.every(Number.isFinite),
+ overflowX: Math.max(html.scrollWidth, document.body.scrollWidth) > innerWidth,
+ overflowY: Math.max(html.scrollHeight, document.body.scrollHeight) > innerHeight + 1,
+ theme: html.getAttribute('data-theme'), motion: html.getAttribute('data-motion'),
+ motionMode: Archify.motionGovernor.mode(), detailLevel: container.getAttribute('data-detail-level'),
+ cameraScale: camera.scale, cameraMode: camera.mode,
+ viewPercent: document.querySelector('[data-view-percent]')?.textContent || null,
+ chromeStageIntersectionArea: chrome.stageIntersectionArea,
+ chromeIntersectionArea: chrome.intersectionArea,
+ innerWidth: innerWidth, innerHeight: innerHeight,
+ };
+ })()`);
+ }
+
+ const viewports = [[1440, 900], [1600, 1000], [1920, 1080], [2048, 1320]];
+ for (const [width, height] of viewports) {
+ for (const theme of width === 1440 ? ['dark', 'light'] : ['dark']) {
+ await load(width, height, theme);
+ const state = await snapshot();
+ assert.equal(state.active, true);
+ assert.equal(state.layout, 'adaptive');
+ assert.equal(state.readerFit, 'intrinsic-height');
+ assert.equal(state.minText, '7.5');
+ assert.equal(state.edgeCount, 15, JSON.stringify(state));
+ assert.ok(state.nodeCount > 0, JSON.stringify(state));
+ assert.equal(state.edgeFinite, true, JSON.stringify(state));
+ assert.equal(state.nodeFinite, true, JSON.stringify(state));
+ assert.ok(state.edgeMinimum >= 7.5 - 0.01, JSON.stringify(state));
+ assert.ok(state.nodeMinimum >= 7.5 - 0.01, JSON.stringify(state));
+ assert.equal(state.overflowX, false, JSON.stringify(state));
+ assert.equal(state.theme, theme, JSON.stringify(state));
+ assert.equal(state.motionMode, 'still', JSON.stringify(state));
+ if (state.motion !== null) assert.equal(state.motion, 'still', JSON.stringify(state));
+ assert.equal(state.detailLevel, 'read', JSON.stringify(state));
+ assert.equal(state.cameraScale, 1, JSON.stringify(state));
+ assert.equal(state.viewPercent, '100%', JSON.stringify(state));
+ assert.ok(Number.isFinite(state.chromeStageIntersectionArea));
+ assert.ok(Number.isFinite(state.chromeIntersectionArea));
+ assert.ok(state.chromeStageIntersectionArea <= 0, JSON.stringify(state));
+ assert.ok(state.chromeIntersectionArea <= 0, JSON.stringify(state));
+ assert.equal(state.geometry[0], '0 0 1348 706');
+ if (state.overflowY) assert.equal(state.overflow, 'authored', JSON.stringify(state));
+ if (width === 1440) assert.ok(state.receipt.width >= 1294, JSON.stringify(state));
+ await stable();
+ assert.deepEqual(await snapshot(), state, `${width}x${height} ${theme}: unstable reader`);
+ }
+ }
+
+ await load(1024, 900);
+ const physicallyCapped = await snapshot();
+ assert.equal(physicallyCapped.active, true);
+ assert.ok(physicallyCapped.receipt.width <= 1024, JSON.stringify(physicallyCapped));
+ assert.equal(physicallyCapped.edgeCount, 15, JSON.stringify(physicallyCapped));
+ assert.equal(physicallyCapped.edgeFinite, true, JSON.stringify(physicallyCapped));
+ assert.ok(physicallyCapped.edgeMinimum < 7.5, 'a physical width cap must report the unmet declaration');
+ assert.equal(physicallyCapped.overflowX, false, JSON.stringify(physicallyCapped));
+
+ await load(2048, 1320, 'dark', '', false, tallArtifact);
+ const legacyTall = await snapshot();
+ assert.equal(legacyTall.active, true);
+ assert.equal(legacyTall.geometry[0], '0 0 2300 1600');
+ assert.ok(legacyTall.receipt.width > 1920, JSON.stringify(legacyTall));
+ assert.ok(legacyTall.nodeMinimum >= 7.5 - 0.01, JSON.stringify(legacyTall));
+
+ await load(1440, 900, 'dark', '&embed=1');
+ assert.equal((await snapshot()).active, false, 'embed mode must bypass the adaptive reader');
+ await load(1440, 900, 'dark', '&present=1');
+ assert.equal((await snapshot()).active, false, 'presentation mode must bypass the adaptive reader');
+ await load(1440, 900, 'dark', '', true);
+ assert.equal((await snapshot()).active, false, 'print mode must bypass the adaptive reader');
+ } finally {
+ await browser.close();
+ }
+ } finally {
+ fs.rmSync(scratch, { recursive: true, force: true });
+ }
+});
diff --git a/archify/test/render-output-checks.test.mjs b/archify/test/render-output-checks.test.mjs
index d902f7d0..ecec6d7c 100644
--- a/archify/test/render-output-checks.test.mjs
+++ b/archify/test/render-output-checks.test.mjs
@@ -30,9 +30,9 @@ test('render output check: finite_svg preserves slashes in unquoted HTML attribu
}
});
-function checkHtml(name, svgBody, profile = 'standard', viewBox = '0 0 240 160') {
+function checkHtml(name, svgBody, profile = 'standard', viewBox = '0 0 240 160', head = '', svgAttributes = '') {
const htmlPath = path.join(tmp, `${name}.html`);
- fs.writeFileSync(htmlPath, `<!doctype html><html><body><svg viewBox="${viewBox}" data-quality-profile="${profile}">${svgBody}</svg></body></html>`);
+ fs.writeFileSync(htmlPath, `<!doctype html><html><head>${head}</head><body><svg viewBox="${viewBox}" data-quality-profile="${profile}"${svgAttributes}>${svgBody}</svg></body></html>`);
try {
const stdout = execFileSync('node', [checker, htmlPath], { encoding: 'utf8' });
return { code: 0, result: JSON.parse(stdout) };
@@ -114,6 +114,107 @@ test('render output check: includes semantic boundary labels in desktop readabil
assert.ok(issue?.projectedFontPx < issue?.minimumProjectedFontPx);
});
+test('render output check: recognized declared-wide Reader admits the hard floor but records an unmet 7.5 target', () => {
+ const { code, result } = checkHtml('recognized-declared-wide-edge', `
+ <g data-edge-from="listener" data-edge-to="handler" data-detail="context">
+ <text x="120" y="160" class="t-muted" font-size="8">method path body</text>
+ <text data-detail="fine" x="120" y="172" class="t-dim" font-size="1">fine annotation</text>
+ </g>
+ `, 'showcase', '0 0 1438 800', '<meta name="archify-reader-contract" content="declared-wide-v1">', ' data-reader-fit="intrinsic-height" data-reader-min-text="7.5"');
+
+ assert.equal(code, 0, JSON.stringify(result, null, 2));
+ assert.equal(result.composition.desktopReadability.budgetBasis, 'recognized-declared-wide');
+ assert.equal(result.composition.desktopReadability.availableDiagramWidth, 1346);
+ assert.equal(result.composition.desktopReadability.minimumOwner.kind, 'edge');
+ assert.equal(result.composition.desktopReadability.minimumOwner.id, null);
+ assert.equal(result.composition.desktopReadability.semanticTextCount, 1);
+ assert.equal(result.composition.desktopReadability.hardFloorMet, true);
+ assert.equal(result.composition.desktopReadability.requestedTargetPx, 7.5);
+ assert.equal(result.composition.desktopReadability.requestedTargetMet, false);
+ assert.ok(result.composition.desktopReadability.minimumProjectedTextPx < 7.5);
+});
+
+test('render output check: ordinary metadata preserves legacy readability and bare semantic markers', () => {
+ const { code, result } = checkHtml('ordinary-meta-legacy-primary', `
+ <g data-node-id="compact-node">
+ <text data-node-label x="160" y="126" class="t-primary" font-size="8">Compact node</text>
+ </g>
+ `, 'showcase', '0 0 1300 700', '<meta name="viewport" content="width=device-width">');
+ assert.notEqual(code, 0);
+ assert.equal(result.composition.desktopReadability.budgetBasis, 'legacy-930');
+ const issue = result.composition.issues.find((item) => item.code === 'composition/desktop-readability');
+ assert.equal(issue?.detail, 'primary');
+ assert.equal(issue?.owner.kind, 'node');
+});
+
+test('render output check: marker recognition is exact and old fit/min-only HTML keeps the 930px floor', () => {
+ const body = `
+ <g data-edge-from="listener" data-edge-to="handler" data-detail="context">
+ <text x="120" y="160" class="t-muted" font-size="8">method path body</text>
+ </g>
+ `;
+ const svgAttributes = ' data-reader-fit="intrinsic-height" data-reader-min-text="7.5"';
+ for (const [name, head, attributes] of [
+ ['old-fit-min-only', '', svgAttributes],
+ ['unknown-reader-contract', '<meta name="archify-reader-contract" content="declared-wide-v2">', svgAttributes],
+ ['duplicate-reader-contract', '<meta name="archify-reader-contract" content="declared-wide-v1"><meta name="archify-reader-contract" content="declared-wide-v1">', svgAttributes],
+ ['invalid-reader-minimum', '<meta name="archify-reader-contract" content="declared-wide-v1">', ' data-reader-fit="intrinsic-height" data-reader-min-text="NaN"'],
+ ['explicit-viewbox-geometry', '<meta name="archify-reader-contract" content="declared-wide-v1">', ' data-reader-min-text="7.5"'],
+ ]) {
+ const { code, result } = checkHtml(name, body, 'showcase', '0 0 1438 800', head, attributes);
+ assert.notEqual(code, 0, name);
+ assert.equal(result.composition.desktopReadability.budgetBasis, 'legacy-930', name);
+ assert.equal(result.composition.issues.find((item) => item.code === 'composition/desktop-readability')?.detail, 'edge', name);
+ }
+});
+
+test('render output check: an edge below 6 remains warning in standard and error in showcase', () => {
+ const body = `
+ <g data-edge-from="listener" data-edge-to="handler" data-detail="context">
+ <text x="120" y="160" class="t-muted" font-size="5">short semantic edge label</text>
+ </g>
+ `;
+ const head = '<meta name="archify-reader-contract" content="declared-wide-v1">';
+ const svgAttributes = ' data-reader-fit="intrinsic-height" data-reader-min-text="7.5"';
+ const standard = checkHtml('declared-wide-standard-edge', body, 'standard', '0 0 1438 800', head, svgAttributes);
+ const showcase = checkHtml('declared-wide-showcase-edge', body, 'showcase', '0 0 1438 800', head, svgAttributes);
+ assert.equal(standard.code, 0);
+ assert.equal(standard.result.composition.issues.find((item) => item.code === 'composition/desktop-readability')?.severity, 'warning');
+ assert.notEqual(showcase.code, 0);
+ assert.equal(showcase.result.composition.issues.find((item) => item.code === 'composition/desktop-readability')?.severity, 'error');
+});
+
+test('render output check: finite non-positive semantic text remains below the 6px floor', () => {
+ const contract = '<meta name="archify-reader-contract" content="declared-wide-v1">';
+ const attributes = ' data-reader-fit="intrinsic-height" data-reader-min-text="7.5"';
+ for (const [name, body] of [
+ ['zero-only', '<g data-edge-from="a" data-edge-to="b" data-detail="context"><text x="1" y="1" font-size="0">zero</text></g>'],
+ ['negative-only', '<g data-edge-from="a" data-edge-to="b" data-detail="context"><text x="1" y="1" font-size="-1">negative</text></g>'],
+ ['zero-with-normal', '<g data-edge-from="a" data-edge-to="b" data-detail="context"><text x="1" y="1" font-size="8">ordinary</text><text x="1" y="2" font-size="0">zero</text></g>'],
+ ]) {
+ const showcase = checkHtml(`${name}-showcase`, body, 'showcase', '0 0 1438 800', contract, attributes);
+ const standard = checkHtml(`${name}-standard`, body, 'standard', '0 0 1438 800', contract, attributes);
+ assert.notEqual(showcase.code, 0, name);
+ assert.equal(showcase.result.composition.desktopReadability.budgetBasis, 'legacy-930', name);
+ assert.equal(showcase.result.composition.issues.find((item) => item.code === 'composition/desktop-readability')?.severity, 'error', name);
+ assert.equal(standard.code, 0, name);
+ assert.equal(standard.result.composition.issues.find((item) => item.code === 'composition/desktop-readability')?.severity, 'warning', name);
+ }
+});
+
+test('render output check: fine detail on a context edge is excluded before ownership classification', () => {
+ const { code, result } = checkHtml('fine-context-edge', `
+ <g data-edge-from="a" data-edge-to="b" data-detail="context">
+ <text x="1" y="1" font-size="8">ordinary relationship label</text>
+ <g data-detail="fine"><text x="1" y="2" font-size="1">fine nested note</text></g>
+ </g>
+ `, 'showcase', '0 0 1438 800', '<meta name="archify-reader-contract" content="declared-wide-v1">', ' data-reader-fit="intrinsic-height" data-reader-min-text="7.5"');
+ assert.equal(code, 0, JSON.stringify(result, null, 2));
+ assert.equal(result.composition.desktopReadability.minimumOwner.kind, 'edge');
+ assert.equal(result.composition.desktopReadability.semanticTextCount, 1);
+ assert.ok(result.composition.desktopReadability.minimumProjectedTextPx >= 6);
+});
+
test('render output check: accepts orthogonal arrows away from legend', () => {
const { code, result } = checkHtml('clean', `
<path d="M 20 20 L 120 20 L 120 60" class="a-default" stroke-width="1.4" marker-end="url(#arrowhead)"/>
diff --git a/archify/test/repair-receipt.test.mjs b/archify/test/repair-receipt.test.mjs
index 3f0b2045..49723995 100644
--- a/archify/test/repair-receipt.test.mjs
+++ b/archify/test/repair-receipt.test.mjs
@@ -176,7 +176,10 @@ test('repair receipt: public validate reports borderline desktop readability wit
assert.ok(repair);
assert.deepEqual(repair.subject, { check: 'composition', nodeId: 'tool-runtime' });
assert.ok(repair.evidence.projectedFontPx < repair.evidence.minimumProjectedFontPx);
- assert.ok(repair.supportedFixes.some((fix) => fix.includes('reduce the viewBox width')));
+ const fix = repair.supportedFixes.join(' ');
+ assert.match(fix, /complete viewBox width is at most \d+px/);
+ assert.match(fix, /desktop budget/);
+ assert.doesNotMatch(fix, /labelAt|labelDx|labelDy|labelSegment/);
});
process.on('exit', () => fs.rmSync(tmp, { recursive: true, force: true }));
@@ -209,3 +212,30 @@ test('repair receipt: readability identifies the failing node despite repeated c
}
}
});
+
+test('repair receipt: edge readability advises a projection-changing reflow, not label positioning', () => {
+ const input = writeFixture('edge-readability.architecture.json', {
+ schema_version: 1,
+ diagram_type: 'architecture',
+ meta: { title: 'Edge readability', quality_profile: 'showcase', viewBox: [1438, 800] },
+ components: [
+ { id: 'listener', type: 'backend', label: 'Listener', pos: [120, 260], size: [180, 80] },
+ { id: 'handler', type: 'backend', label: 'Handler', pos: [760, 260], size: [180, 80] },
+ ],
+ connections: [{ id: 'request', from: 'listener', to: 'handler', label: 'method path body' }],
+ });
+ const result = run(['validate', 'architecture', input, '--quality', 'showcase', '--json']);
+ assert.equal(result.status, 1, result.stderr || result.stdout);
+ const repair = receipt(result).diagnostics.find((entry) => entry.code === 'composition/desktop-readability');
+ assert.ok(repair);
+ assert.equal(repair.evidence.owner.kind, 'edge');
+ assert.equal(repair.evidence.owner.id, 'request');
+ assert.equal(repair.evidence.sourceFontPx, 8);
+ assert.equal(repair.evidence.availableDiagramWidth, 930);
+ assert.equal(repair.evidence.viewBoxWidth, 1438);
+ const fix = repair.supportedFixes.join(' ');
+ assert.match(fix, /complete viewBox width is at most 1240px/);
+ assert.match(fix, /8px source text at 930px desktop budget/);
+ assert.match(fix, /Preserve the semantic text and any supplied coordinates, routes, sides, channels, and labels/);
+ assert.doesNotMatch(fix, /labelAt|labelDx|labelDy|labelSegment|reposition/i);
+});
diff --git a/archify/test/visual-check.test.mjs b/archify/test/visual-check.test.mjs
index d82fe7c7..ed7c70b8 100644
--- a/archify/test/visual-check.test.mjs
+++ b/archify/test/visual-check.test.mjs
@@ -10,6 +10,7 @@ import { PassThrough } from 'node:stream';
import { fileURLToPath, pathToFileURL } from 'node:url';
import {
+ CHROME_STARTUP_TIMEOUT_MS,
ChromeVisualBrowser,
VISUAL_CHECK_VIEWPORTS,
chromeVisualBrowserArgs,
@@ -2077,6 +2078,34 @@ test('visual-check restore rollback preserves a successor swapped at its public
assert.deepEqual(entryIdentity(outputs.contactSheet), successorIdentity);
});
+test('visual-check keeps slow Chrome startup inside one bounded gate invocation', async () => {
+ assert.equal(CHROME_STARTUP_TIMEOUT_MS, 90000);
+ const input = artifact('chrome-startup-timeout.html');
+ const child = fakeChromeChild();
+
+ const result = await runVisualCheck({
+ artifactPath: input,
+ chromePath: '/fake/chrome',
+ browserFactory: async () => new ChromeVisualBrowser('/fake/chrome', {
+ startupTimeoutMs: 5,
+ spawnImpl: () => child,
+ }),
+ });
+
+ assert.equal(result.exitCode, 1);
+ assert.equal(result.receipt.diagnostics[0]?.code, 'viewer/chrome-startup-timeout');
+ assert.match(result.receipt.error, /Target\.getTargets: timed out after 5ms/);
+ assert.match(result.receipt.error, /Chrome process: still running/);
+ assert.match(
+ result.receipt.diagnostics[0]?.supportedFixes?.join('\n') || '',
+ /do not edit or simplify the artifact/,
+ );
+ assert.match(
+ result.receipt.diagnostics[0]?.supportedFixes?.join('\n') || '',
+ /retry visual-check once.*stop and report the environment failure/,
+ );
+});
+
for (const scenario of [
{ name: 'backup unlink', fault: 'unlink' },
{ name: 'staging rmdir', fault: 'rmdir' },
diff --git a/scripts/run-browser-tests.mjs b/scripts/run-browser-tests.mjs
index ebf5c3a7..de38d10c 100644
--- a/scripts/run-browser-tests.mjs
+++ b/scripts/run-browser-tests.mjs
@@ -9,7 +9,9 @@ const skillRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..
// Shared by PR CI and tag releases. WebM decoding stays in test:webm.
const testFiles = [
'desktop-reader-browser.test.mjs',
+ 'reader-readability-maintained-browser.test.mjs',
'reader-layout-browser.test.mjs',
+ 'joint-layout-browser.test.mjs',
'sequence-header-clearance.test.mjs',
'lifecycle-rail-browser.test.mjs',
'export-cleanup-browser.test.mjs',
diff --git a/viewer/reader-layout.js b/viewer/reader-layout.js
index a8b60a5d..6e1ce08c 100644
--- a/viewer/reader-layout.js
+++ b/viewer/reader-layout.js
@@ -43,9 +43,13 @@
}
function minimumReadableScale() {
var sourceMinimum = null;
- Array.from(svg.querySelectorAll(
+ var selectors = [
'text[data-node-label], text[data-boundary-label], text[data-detail="context"]'
- )).forEach(function (text) {
+ ];
+ if (measuredHeightFit && ratio >= WIDE_RATIO && Number.isFinite(declaredMinimumText)) {
+ selectors.push('g[data-detail="context"][data-edge-from][data-edge-to] > text');
+ }
+ Array.from(svg.querySelectorAll(selectors.join(', '))).forEach(function (text) {
if (text.getAttribute('data-detail') === 'context' && !text.closest('[data-node-id]')) return;
var sourceFontPx = parseFloat(text.getAttribute('font-size') || '');
if (Number.isFinite(sourceFontPx)) {
@@ -121,11 +125,20 @@
var readableWidth = viewBox && viewBox.width > 0
? viewBox.width * minimumReadableScale() + chrome.diagramX
: MIN_READER_WIDTH;
- var minWidth = Math.min(
- measuredHeightFit && ratio < WIDE_RATIO ? readableWidth : MIN_READER_WIDTH,
- viewportCap
- );
var maxWidth = Math.min(MAX_READER_WIDTH, viewportCap);
+ var readableMinimumWidth = measuredHeightFit && ratio < WIDE_RATIO
+ ? readableWidth
+ : measuredHeightFit && ratio >= WIDE_RATIO && Number.isFinite(declaredMinimumText)
+ ? Math.max(MIN_READER_WIDTH, readableWidth)
+ : MIN_READER_WIDTH;
+ var minWidth;
+ if (measuredHeightFit && ratio < WIDE_RATIO) {
+ minWidth = Math.min(readableMinimumWidth, viewportCap);
+ } else if (measuredHeightFit && ratio >= WIDE_RATIO && Number.isFinite(declaredMinimumText)) {
+ minWidth = Math.min(readableMinimumWidth, maxWidth);
+ } else {
+ minWidth = Math.min(readableMinimumWidth, viewportCap);
+ }
var fixedHeight = chrome.bodyY + chrome.diagramY + SAFE_BOTTOM_GAP +
outerHeight(header) + outerHeight(guided) + outerHeight(cards);
var availableSvgHeight = Math.max(1, window.innerHeight - fixedHeight);
@@ -161,14 +174,16 @@
Math.round(diagramRect.height * 100) / 100
].join('|');
}
+ function layoutPending() { return Boolean(frame || settleFrame); }
function whenStable() {
return Archify.waitForStableLayout({
schedule: schedule,
- pending: function () { return Boolean(frame || settleFrame); },
+ pending: layoutPending,
snapshot: stableSnapshot,
timeoutMessage: 'Adaptive reader layout did not reach stable dimensions.'
});
}
+ archifyLayoutOwners.reader = { schedule: schedule, pending: layoutPending, snapshot: stableSnapshot };
window.addEventListener('resize', schedule, { passive: true });
window.addEventListener('load', schedule, { once: true });
diff --git a/viewer/template.source.html b/viewer/template.source.html
index d0dcf758..6dd79767 100644
--- a/viewer/template.source.html
+++ b/viewer/template.source.html
@@ -4,6 +4,7 @@
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="archify 2.17.0-dev.1">
+ <meta name="archify-reader-contract" content="declared-wide-v1">
<title>[PROJECT NAME] Architecture Diagram</title>
<script>
// Resolve the theme before first paint so light-preference users don't
@@ -1028,6 +1029,8 @@ OTHER DEALINGS IN THE FONT SOFTWARE.
embed, presentation, print, and unmarked non-wide diagrams retain their own
established layout contracts.
============================================================ */
+ // Fixed script-private participants; the CLI sees only the joint wait below.
+ const archifyLayoutOwners = { reader: null, viewerChrome: null };
Archify.waitForStableLayout = function (options) {
options = options || {};
var maximumFrames = Math.max(1, Number(options.maximumFrames) || 240);
@@ -1070,6 +1073,49 @@ OTHER DEALINGS IN THE FONT SOFTWARE.
/* ARCHIFY:READER_LAYOUT */
/* ARCHIFY:CHROME_LAYOUT */
+ Archify.layoutStability = {
+ whenStable: function () {
+ var reader = archifyLayoutOwners.reader;
+ var chrome = archifyLayoutOwners.viewerChrome;
+ if (!reader || !chrome) {
+ return Promise.reject(new Error('Joint layout owners are unavailable.'));
+ }
+ var observedFontsReady = document.fonts && document.fonts.ready;
+ var fontCyclePending = false;
+ var fontGeneration = 0;
+ function scheduleOwners() { reader.schedule(); chrome.schedule(); }
+ function fontsPending() {
+ var fonts = document.fonts;
+ var ready = fonts && fonts.ready;
+ if (ready && (ready !== observedFontsReady || (fonts.status === 'loading' && !fontCyclePending))) {
+ observedFontsReady = ready;
+ fontCyclePending = true;
+ var generation = ++fontGeneration;
+ ready.catch(function () {}).then(function () {
+ if (generation !== fontGeneration) return;
+ fontCyclePending = false;
+ scheduleOwners();
+ });
+ }
+ return fontCyclePending || Boolean(fonts && fonts.status === 'loading');
+ }
+ return Archify.waitForStableLayout({
+ maximumFrames: 960,
+ schedule: scheduleOwners,
+ pending: function () {
+ // Recapture readiness for font cycles that begin during sampling.
+ return fontsPending() || reader.pending() || chrome.pending();
+ },
+ snapshot: function () {
+ return JSON.stringify([
+ ['reader', reader.snapshot()],
+ ['viewerChrome', chrome.snapshot()]
+ ]);
+ },
+ timeoutMessage: 'Joint reader and viewer chrome layout did not reach stable dimensions.'
+ });
+ }
+ };
/* ARCHIFY:CAMERA */
/* ARCHIFY:RADAR */
diff --git a/viewer/viewer-chrome-layout.js b/viewer/viewer-chrome-layout.js
index c57fd26a..7c481313 100644
--- a/viewer/viewer-chrome-layout.js
+++ b/viewer/viewer-chrome-layout.js
@@ -267,14 +267,16 @@
lastReceipt ? lastReceipt.stageGap : ''
].join('|');
}
+ function layoutPending() { return Boolean(frame || settleFrame || probingBaseline); }
function whenStable() {
return Archify.waitForStableLayout({
schedule: schedule,
- pending: function () { return Boolean(frame || settleFrame || probingBaseline); },
+ pending: layoutPending,
snapshot: stableSnapshot,
timeoutMessage: 'Viewer chrome layout did not reach stable dimensions.'
});
}
+ archifyLayoutOwners.viewerChrome = { schedule: schedule, pending: layoutPending, snapshot: stableSnapshot };
window.addEventListener('resize', reprobe, { passive: true });
window.addEventListener('load', schedule, { once: true });