Skip to content

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

feat(check): report unused leading space as composition advice

tt-a1i6bbe2497ebfb
diff --git a/archify.zip b/archify.zip
index 1a515d1d..70049d81 100644
Binary files a/archify.zip and b/archify.zip differ
diff --git a/archify/bin/finalize.mjs b/archify/bin/finalize.mjs
index 9ab078f5..592c6974 100644
--- a/archify/bin/finalize.mjs
+++ b/archify/bin/finalize.mjs
@@ -552,6 +552,15 @@ export function compactFinalizeReceipt(receipt) {
} : {}),
};
}
+ const leadingSpace = receipt.stages?.check?.receipt?.composition?.leadingSpace;
+ if (receipt.ok && leadingSpace?.reviewSuggested === true) {
+ compact.layoutReviewRecommendation = {
+ action: 'inspect-leading-space',
+ evidence: leadingSpace,
+ reason: 'Measured content, including routes and labels, leaves a large empty area above the diagram. This is a composition suggestion, not a failed gate.',
+ repair: 'Check whether that leading space is intentional. If not, reposition the connected scene nearer the canvas origin while retaining room for its actual boundaries, labels and return routes. Preserve all meaning and user-fixed geometry, then rerun finalize. No screenshot is required.',
+ };
+ }
if (!receipt.ok && receipt.status === 'fail' && receipt.failedStage === 'validate') {
compact.nextAction = {
action: 'edit-in-place',
diff --git a/archify/references/delivery-contract.md b/archify/references/delivery-contract.md
index 3dcde663..a908089b 100644
--- a/archify/references/delivery-contract.md
+++ b/archify/references/delivery-contract.md
@@ -263,6 +263,14 @@ truncated and its shown subjects and evidence cannot identify a coherent local
repair, or when complete audit evidence was explicitly requested. The compact
receipt reports `visualReview: "not-requested"`; the automated gate does not create images or require a perceptual reviewer. A compact `visualReviewRecommendation` retains positive crossover and route-detour metrics from the strict check so the author can apply the review escalation below without reading the full receipt. A recommendation does not change the machine exit code or claim that review happened. Its `affectedRoutes` identifies crossing pairs and detours (up to eight of each, with a truncation flag); the full strict-check `composition.routeReview` retains all affected relationships. Use these IDs to trace the routes in the captured default viewport. Detours may include `directCorridorBlockers`, identifying nodes between aligned endpoints. These are geometric review clues, not new validation failures or inferred main-path semantics. For a blocked main path or several tangled routes, follow [Architecture layout repair](architecture-layout-repair.md) and reflow the connected scene before tuning individual sides or labels. Preserve every semantic fact; retain unrelated positions only when their surrounding composition is already accepted.
+For a measured automatic Architecture with a large unused leading area, the
+compact receipt may include `layoutReviewRecommendation`. Its
+`composition.leadingSpace` evidence accounts for nodes, boundary titles,
+routes and labels. Check whether that space is intentional; if not, reposition
+the connected scene while preserving meaning and user-fixed geometry, then
+finalize again. This suggestion changes no gate or exit status and requires
+no screenshot. A fixed canvas or uncertain measurement receives no suggestion.
+
A passing finalizer receipt is sufficient evidence for all four gates. Merely
naming the gates or requiring each one to pass does not require replaying their
standalone commands. Replay an individual command only when the request
diff --git a/archify/scripts/check-render-output.mjs b/archify/scripts/check-render-output.mjs
index a6d8920f..42a381bd 100644
--- a/archify/scripts/check-render-output.mjs
+++ b/archify/scripts/check-render-output.mjs
@@ -163,6 +163,10 @@ if (svgMatches.length === 1) {
routedRelations: routedRelationships.filter((entry) => entry.relation.independentPorts),
});
const relationshipLabels = collectRelationshipLabelMasks(beforeLegend, arrows);
+ const leadingSpace = collectArchitectureLeadingSpace({
+ svgAttrs, fragment: beforeLegend, nodeRects, frames: compositionFrames,
+ arrows, labels: relationshipLabels,
+ });
const labelClearanceThreshold = qualityProfile === 'showcase' ? 4 : 2;
const labelRouteMeasurements = collectLabelRouteClearance({
labels: relationshipLabels,
@@ -248,6 +252,7 @@ if (svgMatches.length === 1) {
}] : [];
}),
},
+ leadingSpace,
desktopReadability: desktopReadability.evidence,
issues: [
...containerBorderRuns.map((hit) => ({
@@ -677,6 +682,59 @@ function collectCompositionFrames(fragment) {
return frames;
}
+// Evidence for author review only. Automatic Architecture is identifiable by
+// its intrinsic Reader contract; authored canvases must retain their geometry.
+function collectArchitectureLeadingSpace({ svgAttrs, fragment, nodeRects, frames, arrows, labels }) {
+ const evidence = { measured: false, reviewSuggested: false };
+ if (svgAttrs['data-reader-fit'] !== 'intrinsic-height'
+ || svgAttrs['data-reader-primary-text'] !== '14'
+ || svgAttrs.transform
+ || [...fragment.matchAll(/<g\b[^>]*\btransform\s*=[^>]*>/gi)]
+ .some((match) => !/\bdata-semantic-sigil=/.test(match[0]))
+ || /<(?:path|line|rect|text)\b[^>]*\btransform\s*=/i.test(fragment)) return evidence;
+ const [originX, originY, width, height] = viewBoxRect(svgAttrs);
+ if (![originX, originY, width, height].every(Number.isFinite) || width <= 0 || height <= 0) return evidence;
+ const nodeCount = [...fragment.matchAll(/<g\b[^>]*\bdata-node-id=/gi)].length;
+ if (!nodeRects.length || nodeRects.length !== nodeCount) return evidence;
+ const semanticArrows = arrows.filter((arrow) => arrow.from && arrow.to);
+ if (semanticArrows.some((arrow) => !arrow.routePoints.length)) return evidence;
+
+ const occupied = nodeRects.map((node) => node.box[1]);
+ for (const frame of frames) {
+ const top = frame.shape === 'line'
+ ? Math.min(frame.start[1], frame.end[1]) : frame.y;
+ if (!Number.isFinite(top)) return evidence;
+ occupied.push(top);
+ }
+ // Boundary titles can protrude above their structural frame.
+ for (const match of fragment.matchAll(/<g\b[^>]*\bdata-graph-role="structural-frame-label"[^>]*>[\s\S]*?<rect\b[^>]*\bdata-graph-role="structural-frame-label-mask"[^>]*>/gi)) {
+ const rect = parseAttrs(match[0].match(/<rect\b[^>]*>/i)?.[0] || '');
+ const y = numberAttr(rect, 'y');
+ if (!Number.isFinite(y)) return evidence;
+ occupied.push(y);
+ }
+ for (const arrow of semanticArrows) {
+ for (const point of arrow.routePoints) occupied.push(point[1]);
+ }
+ for (const label of labels) occupied.push(label.rect.y);
+ if (!occupied.every(Number.isFinite)) return evidence;
+ const occupiedTop = Math.min(...occupied);
+ const gap = Math.max(0, occupiedTop - originY);
+ const heights = nodeRects.map((node) => node.box[3]).sort((a, b) => a - b);
+ const typicalNodeHeight = heights[Math.floor(heights.length / 2)];
+ const ratio = gap / height;
+ return {
+ measured: true,
+ emptyTopPx: Math.round(gap * 10) / 10,
+ emptyTopRatio: Math.round(ratio * 1000) / 1000,
+ occupiedTop: Math.round(occupiedTop * 10) / 10,
+ viewBoxTop: originY,
+ canvasHeight: height,
+ typicalNodeHeight,
+ reviewSuggested: gap > 2 * typicalNodeHeight && ratio > 0.2,
+ };
+}
+
function frameName(frame) {
return `${frame.kind || 'frame'} "${frame.id}"`;
}
diff --git a/archify/test/architecture-leading-space.test.mjs b/archify/test/architecture-leading-space.test.mjs
new file mode 100644
index 00000000..ae8f94f8
--- /dev/null
+++ b/archify/test/architecture-leading-space.test.mjs
@@ -0,0 +1,90 @@
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import test from 'node:test';
+import { fileURLToPath } from 'node:url';
+
+const root = fileURLToPath(new URL('../', import.meta.url));
+const cli = path.join(root, 'bin/archify.mjs');
+const checker = path.join(root, 'scripts/check-render-output.mjs');
+
+function run(args) {
+ const result = spawnSync(process.execPath, args, { encoding: 'utf8' });
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ return JSON.parse(result.stdout);
+}
+
+function fixture(t, changes = {}) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-leading-space-'));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ const source = path.join(dir, 'diagram.json');
+ const output = path.join(dir, 'diagram.html');
+ const diagram = {
+ schema_version: 1, diagram_type: 'architecture',
+ meta: { title: 'Leading space', quality_profile: 'standard', output: 'diagram.html', ...changes.meta },
+ components: [
+ { id: 'a', type: 'backend', label: 'A', pos: [40, 225], size: [120, 60] },
+ { id: 'b', type: 'backend', label: 'B', pos: [300, 225], size: [120, 60] },
+ ],
+ connections: changes.connections || [{ from: 'a', to: 'b', label: 'request' }],
+ ...(changes.boundaries ? { boundaries: changes.boundaries } : {}),
+ };
+ fs.writeFileSync(source, JSON.stringify(diagram));
+ const rendered = spawnSync(process.execPath, [cli, 'render', 'architecture', source, output], { encoding: 'utf8' });
+ assert.equal(rendered.status, 0, rendered.stdout + rendered.stderr);
+ return { source, output, read: () => run([checker, output]) };
+}
+
+test('automatic Architecture reports visible leading space as review evidence only', t => {
+ const { read } = fixture(t);
+ const report = read();
+ const space = report.composition.leadingSpace;
+ assert.equal(space.measured, true);
+ assert.equal(space.reviewSuggested, true);
+ assert.ok(space.emptyTopPx > 120);
+ assert.ok(space.emptyTopRatio > 0.2);
+ assert.ok(space.occupiedTop <= 225);
+ assert.deepEqual(report.composition.summary, { errors: 0, warnings: 0 });
+ assert.equal(report.composition.status, 'pass');
+ assert.equal(report.composition.issues.length, 0);
+});
+
+test('a top return route occupies the space before the first node', t => {
+ const { read } = fixture(t, { connections: [
+ { from: 'a', to: 'b', label: 'request' },
+ { from: 'b', to: 'a', fromSide: 'top', toSide: 'top', via: [[360, 72], [100, 72]], label: 'return' },
+ ] });
+ const space = read().composition.leadingSpace;
+ assert.equal(space.measured, true);
+ assert.ok(space.occupiedTop < 100);
+ assert.equal(space.reviewSuggested, false);
+});
+
+test('boundary frame and its title occupy the top region', t => {
+ const { read, output } = fixture(t);
+ let html = fs.readFileSync(output, 'utf8');
+ html = html.replace('<!-- Boundaries (behind everything) -->', `<!-- Boundaries (behind everything) -->
+ <rect data-graph-role="structural-frame" data-composition-frame-kind="region" data-composition-frame-id="0" x="20" y="30" width="420" height="280"/>
+ <g data-graph-role="structural-frame-label"><rect data-graph-role="structural-frame-label-mask" x="30" y="18" width="70" height="14"/></g>`);
+ fs.writeFileSync(output, html);
+ const space = read().composition.leadingSpace;
+ assert.equal(space.measured, true);
+ assert.ok(space.occupiedTop < 40);
+ assert.equal(space.reviewSuggested, false);
+});
+
+test('authored viewBox and transformed SVGs are not suggested for automatic review', t => {
+ const authored = fixture(t, { meta: { viewBox: [500, 400] } });
+ assert.equal(authored.read().composition.leadingSpace.reviewSuggested, false);
+ const automatic = fixture(t);
+ let html = fs.readFileSync(automatic.output, 'utf8');
+ html = html.replace('<svg viewBox=', '<svg transform="translate(0 1)" viewBox=');
+ fs.writeFileSync(automatic.output, html);
+ assert.equal(automatic.read().composition.leadingSpace.reviewSuggested, false);
+ html = html.replace('data-reader-primary-text="14"', 'data-reader-primary-text="12"');
+ html = html.replace('transform="translate(0 1)" ', '');
+ fs.writeFileSync(automatic.output, html);
+ assert.equal(automatic.read().composition.leadingSpace.reviewSuggested, false, 'other diagram modes do not qualify');
+});
diff --git a/archify/test/finalize.test.mjs b/archify/test/finalize.test.mjs
index 932d6450..d07de020 100644
--- a/archify/test/finalize.test.mjs
+++ b/archify/test/finalize.test.mjs
@@ -281,6 +281,27 @@ test('compact success retains route-quality review signals without claiming perc
assert.equal('visualReviewRecommendation' in uncomplicated, false);
});
+test('compact leading-space advice preserves successful gates and optional visual review', () => {
+ const leadingSpace = { occupiedTop: 181, emptyTopPx: 181, canvasHeight: 576,
+ emptyTopRatio: 181 / 576, reviewSuggested: true };
+ const receipt = { ok: true, status: 'pass', diagnostics: [], stages: {
+ check: { status: 'pass', receipt: { composition: { leadingSpace } } },
+ } };
+ const compact = compactFinalizeReceipt(receipt);
+ assert.equal(compact.status, 'pass');
+ assert.equal(compact.gates.check, 'pass');
+ assert.deepEqual(compact.diagnostics, []);
+ assert.equal(compact.visualReview, 'not-requested');
+ assert.equal(compact.layoutReviewRecommendation.action, 'inspect-leading-space');
+ assert.deepEqual(compact.layoutReviewRecommendation.evidence, leadingSpace);
+ assert.match(compact.layoutReviewRecommendation.repair, /user-fixed geometry/);
+ assert.match(compact.layoutReviewRecommendation.repair, /No screenshot is required/);
+ leadingSpace.reviewSuggested = false;
+ assert.equal('layoutReviewRecommendation' in compactFinalizeReceipt(receipt), false);
+ leadingSpace.reviewSuggested = true;
+ assert.equal('layoutReviewRecommendation' in compactFinalizeReceipt({ ...receipt, ok: false, status: 'fail' }), false);
+});
+
test('compact success bounds review context and preserves relationship identity', () => {
const crossings = Array.from({ length: 10 }, (_, index) => ({ left: { id: `edge-${index}` }, right: { id: 'hub' }, point: [index, 50] }));
const detours = [{ relationship: { id: 'return', from: 'worker', to: 'api' }, bends: 4, stretch: 1.5,