Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.
HTML agent-skillsai-agentsarchitecture-diagramclaude-codeclaude-skillscodexcoding-agentsdeepseek-harnessdeveloper-toolsdiagramsdiagrams-as-codedsh-pluginflowchartllmmermaidopencodesequence-diagramsoftware-architecturesystem-designvisualization
feat: add bounded visual evidence checks
tt-a1i6c03124ab82a
diff --git a/archify.zip b/archify.zipindex 7550b57a..c445a55b 100644Binary files a/archify.zip and b/archify.zip differdiff --git a/archify/SKILL.md b/archify/SKILL.mdindex 3d66674f..c6a2eba4 100644--- a/archify/SKILL.md+++ b/archify/SKILL.md@@ -68,7 +68,9 @@ Read Mermaid for topology and meaning, then author fresh Archify JSON; do not me- Match every reader-facing authored string to the language of the user's request, or the conversation's dominant language when the request is language-neutral. Apply it consistently to titles/subtitles, node/edge/boundary/lane/group text, guided-view labels/notes, legend label overrides, and card titles/items; use another language or bilingual copy only when the user asks.- Preserve exact product names, code identifiers, commands, protocols, API paths, and environment names. They may remain English inside localized copy, but never justify leaving the surrounding explanatory prose in another language.- Component types are `frontend`, `backend`, `database`, `cloud`, `security`, `messagebus`, and `external`; variants are `default`, `emphasis`, `security`, and `dashed`.-- Spacing means clear gap, not center distance. For a relationship label, clear gap must exceed its measured mask width; otherwise omit the label or move it deliberately.+- Relationship labels are semantic data. When one collides, move the label, adjust the route or spacing, then shorten the wording while preserving meaning. Only delete a label when both endpoints fully imply the relationship and it contains no protocol, action, direction, synchronous/asynchronous behavior, or cross-boundary mechanism; explain why the deleted label is redundant. Never delete a meaningful label merely to pass `showcase`.+- Omit `meta.engineering_profile` by default. Region, cluster, and security boundary wording do not by themselves enable it. Enable `deployment-ownership` only when the user explicitly asks for a production deployment topology, ownership handoff, or fail-closed deployment review and the source facts are known. Once enabled, must not remove the engineering profile merely to pass validation; repair the facts or report the diagnostics truthfully.+- Spacing means clear gap, not center distance. For a relationship label, clear gap must exceed its measured mask width; use the label-preserving repair order before considering deletion.- Automatic routes own their endpoint sides. A side is a direction contract: the first and final segment must leave/enter perpendicular to that side.- Automatic Port Spread is a default renderer behavior for architecture, workflow, data-flow, and lifecycle. It skips single relationships and explicit `via`, `channelX`, `channelY`, `labelAt`, or non-`auto` routes. Near parallel ports use an outside bridge so automatic routing cannot create a sub-8px segment or sub-16px interior turn. Architecture separately keeps unobstructed facing automatic ports (`left`/`right` or `top`/`bottom`) on one shared axis when their offset is under 16px and both ports retain corner clearance. If exactly one endpoint was spread, only the unshared endpoint may move onto that axis; if both endpoints were spread, keep the outside bridge so competing ports remain distinct.- Never accept an edge crossing an unrelated opaque node, an ambiguous shared corridor, or a relationship label masking another route.@@ -79,6 +81,14 @@ Read `references/authoring-contract.md` only when you need field enums, spacingUse `validate` during repair and `deliver` once for final acceptance. Delivery freezes the exact specification bytes into a private same-directory snapshot, renders and checks that snapshot, atomically commits the HTML, and reports SHA-256 plus byte counts for both specification and artifact.+After delivery, collect bounded desktop evidence without modifying or rerendering the trusted HTML:++```bash+node bin/archify.mjs visual-check <output.html> --json+```++`visual-check` measures containment at 1440×900, 1600×1000, 1920×1080, and 2048×1320; captures light/dark screenshots at the smallest and largest sizes; and writes a relative-path contact sheet plus JSON sidecars beside the artifact. Its automated receipt always reports `visualReview: "pending"`: screenshots are evidence for inspection, never an automatic polish claim. Exit 0 means containment and captures passed, 1 means overflow or capture failure, and 2 means Chrome/Chromium was unavailable and the receipt is `skipped`. The command never changes the delivered HTML.+Add `--open` only when the user wants an immediate local preview. For an active desktop authoring loop, the optional command is:```bashdiff --git a/archify/bin/archify.mjs b/archify/bin/archify.mjsindex f0e6d08f..1475b430 100755--- a/archify/bin/archify.mjs+++ b/archify/bin/archify.mjs@@ -21,6 +21,7 @@ function usage() {archify validate <type> <input.json> [--json] [--layout-json] [--quality standard|showcase] [--repo-root path]archify inspect <type> <input.json>archify check <output.html>+ archify visual-check <output.html> [--json]archify guide [scenario or question] [--json] [--lang en|zh]archify examplesarchify doctor@@ -1155,6 +1156,56 @@ function commandCheck(args) {if (result.status !== 0) exitFrom(result);}+async function commandVisualCheck(args) {+ const json = args.includes('--json');+ const knownOptions = new Set(['--json']);+ const unknown = args.filter((arg) => arg.startsWith('--') && !knownOptions.has(arg));+ if (unknown.length) fail(`Unknown visual-check option "${unknown[0]}".`, 1);+ const positional = args.filter((arg) => !knownOptions.has(arg));+ if (positional.length !== 1) fail(usage(), 1);++ let runVisualCheck;+ try {+ ({ runVisualCheck } = await import('./visual-check.mjs'));+ } catch (error) {+ fail(`Could not load visual-check: ${error.message}`, 1);+ }++ let result;+ try {+ result = await runVisualCheck({ artifactPath: positional[0] });+ } catch (error) {+ if (json) {+ console.log(JSON.stringify({+ schemaVersion: 1,+ ok: false,+ command: 'visual-check',+ status: 'fail',+ visualReview: 'pending',+ artifact: { path: path.resolve(positional[0]) },+ error: error.message,+ }, null, 2));+ } else {+ console.error(`visual-check failed: ${error.message}`);+ }+ process.exitCode = 1;+ return;+ }++ if (json) {+ console.log(JSON.stringify(result.receipt, null, 2));+ } else {+ console.log(`visual-check ${result.receipt.status}: ${result.receipt.artifact.path}`);+ console.log(`containment ${result.receipt.containment.status}; captures ${result.receipt.captures.status}; visual review pending`);+ console.log(`receipt ${path.join(path.dirname(result.receipt.artifact.path), result.receipt.sidecars.receipt)}`);+ if (result.receipt.captures.contactSheet) {+ console.log(`contact sheet ${path.join(path.dirname(result.receipt.artifact.path), result.receipt.captures.contactSheet)}`);+ }+ if (result.receipt.error) console.error(result.receipt.error);+ }+ process.exitCode = result.exitCode;+}+function commandExamples() {const result = runNode([path.join(skillRoot, 'scripts/render-examples.mjs')], { cwd: skillRoot });if (result.status !== 0) exitFrom(result);@@ -1191,6 +1242,13 @@ async function commandDoctor() {missing: fs.existsSync(previewRuntime) ? 0 : 1,});+ const visualCheckRuntime = path.join(skillRoot, 'bin/visual-check.mjs');+ checks.push({+ label: 'Visual-check runtime',+ ok: fs.existsSync(visualCheckRuntime),+ missing: fs.existsSync(visualCheckRuntime) ? 0 : 1,+ });+const outputPathRuntime = path.join(skillRoot, 'renderers/shared/output-path.mjs');checks.push({label: 'Output path safety runtime',@@ -1505,6 +1563,9 @@ switch (command) {case 'check':commandCheck(args);break;+ case 'visual-check':+ await commandVisualCheck(args);+ break;case 'guide':await commandGuide(args);break;diff --git a/archify/bin/visual-check.mjs b/archify/bin/visual-check.mjsnew file mode 100644index 00000000..97b59cfb--- /dev/null+++ b/archify/bin/visual-check.mjs@@ -0,0 +1,531 @@+import { spawn } from 'node:child_process';+import { createHash } from 'node:crypto';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { pathToFileURL } from 'node:url';++export const VISUAL_CHECK_VIEWPORTS = Object.freeze([+ Object.freeze({ width: 1440, height: 900 }),+ Object.freeze({ width: 1600, height: 1000 }),+ Object.freeze({ width: 1920, height: 1080 }),+ Object.freeze({ width: 2048, height: 1320 }),+]);++const CAPTURE_VIEWPORTS = Object.freeze([+ Object.freeze({ width: 1440, height: 900 }),+ Object.freeze({ width: 2048, height: 1320 }),+]);+const THEMES = Object.freeze(['light', 'dark']);+const EXIT = Object.freeze({ pass: 0, fail: 1, skipped: 2 });++function sha256(buffer) {+ return createHash('sha256').update(buffer).digest('hex');+}++function htmlEscape(value) {+ return String(value).replace(/[&<>"']/g, (char) => ({+ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''',+ })[char]);+}++function safeUnlink(file) {+ try {+ fs.rmSync(file, { force: true });+ } catch {+ // A stale optional sidecar must never make the delivered HTML mutable.+ }+}++function writeAtomic(file, contents) {+ const temporary = `${file}.tmp-${process.pid}`;+ try {+ fs.writeFileSync(temporary, contents, { flag: 'w' });+ fs.renameSync(temporary, file);+ } finally {+ safeUnlink(temporary);+ }+}++function screenshotKey(width, height, theme) {+ return `${width}x${height}:${theme}`;+}++export function sidecarPaths(artifactPath) {+ const artifact = path.resolve(artifactPath);+ const stem = artifact.replace(/\.html?$/i, '');+ const base = `${stem}.visual-check`;+ const screenshots = CAPTURE_VIEWPORTS.flatMap(({ width, height }) => THEMES.map((theme) => ({+ width,+ height,+ theme,+ path: `${base}.${width}x${height}.${theme}.png`,+ })));+ return {+ base,+ receipt: `${base}.json`,+ contactSheet: `${base}.html`,+ screenshots,+ };+}++function cleanupCaptureSidecars(paths) {+ safeUnlink(paths.contactSheet);+ for (const screenshot of paths.screenshots) safeUnlink(screenshot.path);+}++function executable(file, platform = process.platform) {+ if (!file) return null;+ try {+ fs.accessSync(file, platform === 'win32' ? fs.constants.F_OK : fs.constants.X_OK);+ return path.resolve(file);+ } catch {+ return null;+ }+}++function findOnPath(command, env, platform) {+ const directories = String(env.PATH || '').split(path.delimiter).filter(Boolean);+ const extensions = platform === 'win32'+ ? String(env.PATHEXT || '.EXE;.CMD;.BAT;.COM').split(';').filter(Boolean)+ : [''];+ for (const directory of directories) {+ for (const extension of extensions) {+ const candidate = path.join(directory, `${command}${extension}`);+ const resolved = executable(candidate, platform);+ if (resolved) return resolved;+ }+ }+ return null;+}++export function findChrome({ env = process.env, platform = process.platform } = {}) {+ if (Object.prototype.hasOwnProperty.call(env, 'ARCHIFY_CHROME')) {+ return executable(env.ARCHIFY_CHROME, platform);+ }++ const fixed = [];+ const commands = [];+ if (platform === 'darwin') {+ fixed.push(+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',+ '/Applications/Chromium.app/Contents/MacOS/Chromium',+ );+ } else if (platform === 'win32') {+ for (const root of [env.PROGRAMFILES, env['PROGRAMFILES(X86)'], env.LOCALAPPDATA].filter(Boolean)) {+ fixed.push(+ path.join(root, 'Google', 'Chrome', 'Application', 'chrome.exe'),+ path.join(root, 'Chromium', 'Application', 'chrome.exe'),+ );+ }+ } else {+ commands.push('google-chrome', 'google-chrome-stable', 'chromium', 'chromium-browser');+ }++ for (const candidate of fixed) {+ const resolved = executable(candidate, platform);+ if (resolved) return resolved;+ }+ for (const command of commands) {+ const resolved = findOnPath(command, env, platform);+ if (resolved) return resolved;+ }+ return null;+}++class PipeCdp {+ constructor(child) {+ this.child = child;+ this.nextId = 1;+ this.buffer = '';+ this.pending = new Map();+ this.waiters = [];+ child.stdio[4].setEncoding('utf8');+ child.stdio[4].on('data', (chunk) => this.consume(chunk));+ child.once('error', (error) => this.failAll(error));+ child.once('exit', (code) => this.failAll(new Error(`Chrome exited before visual-check completed (${code})`)));+ }++ consume(chunk) {+ this.buffer += chunk;+ let boundary;+ while ((boundary = this.buffer.indexOf('\0')) >= 0) {+ const raw = this.buffer.slice(0, boundary);+ this.buffer = this.buffer.slice(boundary + 1);+ if (!raw) continue;+ let message;+ try {+ message = JSON.parse(raw);+ } catch (error) {+ this.failAll(new Error(`Chrome DevTools returned invalid JSON: ${error.message}`));+ continue;+ }+ if (message.id) {+ const pending = this.pending.get(message.id);+ if (!pending) continue;+ clearTimeout(pending.timer);+ this.pending.delete(message.id);+ if (message.error) pending.reject(new Error(`${pending.method}: ${message.error.message}`));+ else pending.resolve(message.result || {});+ continue;+ }+ for (const waiter of [...this.waiters]) {+ if (waiter.method !== message.method) continue;+ if (waiter.sessionId && waiter.sessionId !== message.sessionId) continue;+ clearTimeout(waiter.timer);+ this.waiters.splice(this.waiters.indexOf(waiter), 1);+ waiter.resolve(message.params || {});+ }+ }+ }++ send(method, params = {}, sessionId = undefined, timeoutMs = 15000) {+ const id = this.nextId++;+ const message = { id, method, params };+ if (sessionId) message.sessionId = sessionId;+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => {+ this.pending.delete(id);+ reject(new Error(`${method}: timed out after ${timeoutMs}ms`));+ }, timeoutMs);+ this.pending.set(id, { method, resolve, reject, timer });+ this.child.stdio[3].write(`${JSON.stringify(message)}\0`);+ });+ }++ waitFor(method, sessionId, timeoutMs = 15000) {+ return new Promise((resolve, reject) => {+ const waiter = { method, sessionId, resolve, reject, timer: null };+ waiter.timer = setTimeout(() => {+ this.waiters.splice(this.waiters.indexOf(waiter), 1);+ reject(new Error(`${method}: event timed out after ${timeoutMs}ms`));+ }, timeoutMs);+ this.waiters.push(waiter);+ });+ }++ failAll(error) {+ for (const pending of this.pending.values()) {+ clearTimeout(pending.timer);+ pending.reject(error);+ }+ for (const waiter of this.waiters) {+ clearTimeout(waiter.timer);+ waiter.reject(error);+ }+ this.pending.clear();+ this.waiters = [];+ }+}++async function evaluate(cdp, sessionId, expression, awaitPromise = false) {+ const response = await cdp.send('Runtime.evaluate', {+ expression,+ awaitPromise,+ returnByValue: true,+ }, sessionId);+ if (response.exceptionDetails) {+ throw new Error(response.exceptionDetails.exception?.description+ || response.exceptionDetails.text+ || 'Runtime.evaluate failed');+ }+ return response.result?.value;+}++class ChromeVisualBrowser {+ constructor(chromePath) {+ this.profileRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-visual-check-profile-'));+ const args = [+ '--headless=new',+ '--remote-debugging-pipe',+ '--disable-gpu',+ '--hide-scrollbars',+ '--disable-background-networking',+ '--disable-component-update',+ '--disable-default-apps',+ '--disable-sync',+ '--metrics-recording-only',+ '--no-first-run',+ '--no-default-browser-check',+ '--disable-background-timer-throttling',+ '--disable-backgrounding-occluded-windows',+ '--disable-renderer-backgrounding',+ '--force-device-scale-factor=1',+ `--user-data-dir=${this.profileRoot}`,+ 'about:blank',+ ];+ if (typeof process.getuid === 'function' && process.getuid() === 0) args.unshift('--no-sandbox');+ this.child = spawn(chromePath, args, { stdio: ['ignore', 'ignore', 'pipe', 'pipe', 'pipe'] });+ this.stderr = '';+ this.child.stderr.setEncoding('utf8');+ this.child.stderr.on('data', (chunk) => {+ this.stderr = `${this.stderr}${chunk}`.slice(-8000);+ });+ this.cdp = new PipeCdp(this.child);+ this.sessionPromise = this.attach();+ }++ async attach() {+ const targets = await this.cdp.send('Target.getTargets');+ let target = targets.targetInfos?.find((item) => item.type === 'page');+ if (!target) {+ const created = await this.cdp.send('Target.createTarget', { url: 'about:blank' });+ target = { targetId: created.targetId };+ }+ const attached = await this.cdp.send('Target.attachToTarget', {+ targetId: target.targetId,+ flatten: true,+ });+ await this.cdp.send('Page.enable', {}, attached.sessionId);+ await this.cdp.send('Runtime.enable', {}, attached.sessionId);+ return attached.sessionId;+ }++ async inspect({ artifactPath, width, height, theme, screenshotPath }) {+ const sessionId = await this.sessionPromise;+ await this.cdp.send('Emulation.setDeviceMetricsOverride', {+ width,+ height,+ deviceScaleFactor: 1,+ mobile: false,+ }, sessionId);++ const url = new URL(pathToFileURL(artifactPath).href);+ url.searchParams.set('theme', theme);+ const loaded = this.cdp.waitFor('Page.loadEventFired', sessionId);+ const navigation = await this.cdp.send('Page.navigate', { url: url.href }, sessionId);+ if (navigation.errorText) throw new Error(`Chrome navigation failed: ${navigation.errorText}`);+ await loaded;+ await evaluate(this.cdp, sessionId, `new Promise(function (resolve) {+ document.documentElement.setAttribute('data-motion', 'still');+ var panel = document.querySelector('.diagram-container');+ if (panel) panel.setAttribute('data-detail-level', 'read');+ requestAnimationFrame(function () { requestAnimationFrame(resolve); });+ })`, true);++ const metrics = await evaluate(this.cdp, sessionId, `({+ innerWidth: window.innerWidth,+ innerHeight: window.innerHeight,+ scrollWidth: Math.ceil(document.documentElement.scrollWidth),+ scrollHeight: Math.ceil(document.documentElement.scrollHeight),+ resolvedTheme: document.documentElement.getAttribute('data-theme') || ''+ })`);+ if (!metrics || !Number.isFinite(metrics.scrollWidth) || !Number.isFinite(metrics.scrollHeight)) {+ throw new Error('Chrome returned incomplete containment metrics.');+ }++ if (screenshotPath) {+ const capture = await this.cdp.send('Page.captureScreenshot', {+ format: 'png',+ fromSurface: true,+ captureBeyondViewport: false,+ }, sessionId, 20000);+ if (!capture.data) throw new Error('Chrome returned an empty screenshot.');+ fs.writeFileSync(screenshotPath, Buffer.from(capture.data, 'base64'));+ }+ return metrics;+ }++ async close() {+ this.cdp.failAll(new Error('visual-check finished'));+ if (this.child.exitCode === null && this.child.signalCode === null) {+ this.child.kill('SIGTERM');+ await new Promise((resolve) => {+ const timer = setTimeout(() => {+ if (this.child.exitCode === null && this.child.signalCode === null) this.child.kill('SIGKILL');+ resolve();+ }, 1500);+ this.child.once('exit', () => {+ clearTimeout(timer);+ resolve();+ });+ });+ }+ try {+ fs.rmSync(this.profileRoot, { recursive: true, force: true });+ } catch {+ // Chrome may briefly retain profile files on Windows; evidence is done.+ }+ }+}++function observation({ width, height, theme, metrics }) {+ const innerWidth = Number(metrics.innerWidth);+ const innerHeight = Number(metrics.innerHeight);+ const scrollWidth = Number(metrics.scrollWidth);+ const scrollHeight = Number(metrics.scrollHeight);+ const overflowX = scrollWidth > innerWidth;+ const overflowY = scrollHeight > innerHeight;+ return {+ width,+ height,+ theme,+ innerWidth,+ innerHeight,+ scrollWidth,+ scrollHeight,+ overflowX,+ overflowY,+ ok: !overflowX && !overflowY,+ resolvedTheme: metrics.resolvedTheme || theme,+ };+}++function contactSheetHtml({ artifactPath, receipt, screenshots }) {+ const cards = screenshots.map((entry) => `+ <figure>+ <img src="${htmlEscape(entry.file)}" alt="${htmlEscape(`${entry.theme} ${entry.width} by ${entry.height}`)}">+ <figcaption><strong>${htmlEscape(entry.theme.toUpperCase())}</strong> · ${entry.width}×${entry.height} · containment ${entry.ok ? 'pass' : 'fail'}</figcaption>+ </figure>`).join('');+ return `<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1">+<title>Archify visual-check · ${htmlEscape(path.basename(artifactPath))}</title>+<style>+*{box-sizing:border-box}body{margin:0;padding:24px;background:#e9eef5;color:#172033;font:14px/1.5 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}header{max-width:1500px;margin:0 auto 18px}h1{margin:0 0 6px;font-size:20px}p{margin:0;color:#526176}.grid{max-width:1500px;margin:auto;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}figure{margin:0;padding:10px;background:white;border:1px solid #c9d4e3;border-radius:12px;box-shadow:0 10px 30px rgba(15,23,42,.08)}img{display:block;width:100%;height:auto;border:1px solid #e2e8f0}figcaption{padding:9px 4px 2px;color:#526176}@media(max-width:900px){.grid{grid-template-columns:1fr}}+</style>+</head>+<body>+<header><h1>Archify visual-check</h1><p>${htmlEscape(path.basename(artifactPath))} · automated containment ${htmlEscape(receipt.containment.status)} · visual review pending</p></header>+<main class="grid">${cards}+</main>+</body>+</html>+`;+}++function baseReceipt({ artifactPath, artifact, outputs, chrome }) {+ return {+ schemaVersion: 1,+ ok: false,+ command: 'visual-check',+ status: 'fail',+ visualReview: 'pending',+ artifact: {+ path: artifactPath,+ sha256: sha256(artifact),+ bytes: artifact.byteLength,+ },+ state: { detail: 'read', motion: 'still' },+ chrome,+ containment: { status: 'fail', viewports: [] },+ captures: { status: 'fail', screenshots: [], contactSheet: null },+ sidecars: {+ receipt: path.basename(outputs.receipt),+ contactSheet: path.basename(outputs.contactSheet),+ },+ };+}++function persistReceipt(outputs, receipt) {+ writeAtomic(outputs.receipt, `${JSON.stringify(receipt, null, 2)}\n`);+}++export async function runVisualCheck({+ artifactPath,+ chromePath,+ resolveChrome = findChrome,+ browserFactory = async (resolvedChrome) => new ChromeVisualBrowser(resolvedChrome),+} = {}) {+ if (!artifactPath) throw new Error('visual-check requires one delivered HTML artifact.');+ const artifact = path.resolve(artifactPath);+ if (!/\.html?$/i.test(artifact)) throw new Error('visual-check requires an .html artifact.');+ const artifactBytes = fs.readFileSync(artifact);+ const outputs = sidecarPaths(artifact);+ cleanupCaptureSidecars(outputs);+ safeUnlink(outputs.receipt);++ const resolvedChrome = chromePath || resolveChrome();+ const receipt = baseReceipt({+ artifactPath: artifact,+ artifact: artifactBytes,+ outputs,+ chrome: resolvedChrome+ ? { status: 'available', executable: resolvedChrome }+ : { status: 'unavailable', executable: null },+ });++ if (!resolvedChrome) {+ receipt.status = 'skipped';+ receipt.containment.status = 'skipped';+ receipt.captures.status = 'skipped';+ receipt.error = 'Chrome or Chromium is unavailable. Set ARCHIFY_CHROME to its executable path.';+ persistReceipt(outputs, receipt);+ return { exitCode: EXIT.skipped, receipt };+ }++ let browser;+ try {+ browser = await browserFactory(resolvedChrome);+ const observations = new Map();+ const screenshotsByKey = new Map(outputs.screenshots.map((entry) => [+ screenshotKey(entry.width, entry.height, entry.theme),+ entry,+ ]));++ for (const viewport of VISUAL_CHECK_VIEWPORTS) {+ const key = screenshotKey(viewport.width, viewport.height, 'light');+ const screenshot = screenshotsByKey.get(key);+ const metrics = await browser.inspect({+ artifactPath: artifact,+ ...viewport,+ theme: 'light',+ ...(screenshot ? { screenshotPath: screenshot.path } : {}),+ });+ observations.set(key, observation({ ...viewport, theme: 'light', metrics }));+ }+ for (const viewport of CAPTURE_VIEWPORTS) {+ const key = screenshotKey(viewport.width, viewport.height, 'dark');+ const screenshot = screenshotsByKey.get(key);+ const metrics = await browser.inspect({+ artifactPath: artifact,+ ...viewport,+ theme: 'dark',+ screenshotPath: screenshot.path,+ });+ observations.set(key, observation({ ...viewport, theme: 'dark', metrics }));+ }++ const afterBytes = fs.readFileSync(artifact);+ if (sha256(afterBytes) !== receipt.artifact.sha256 || afterBytes.byteLength !== receipt.artifact.bytes) {+ throw new Error('The delivered artifact changed while visual-check was running.');+ }++ receipt.containment.viewports = VISUAL_CHECK_VIEWPORTS.map(({ width, height }) => (+ observations.get(screenshotKey(width, height, 'light'))+ ));+ receipt.captures.screenshots = outputs.screenshots.map((entry) => ({+ ...observations.get(screenshotKey(entry.width, entry.height, entry.theme)),+ file: path.basename(entry.path),+ }));+ const allObservations = [...observations.values()];+ const containmentPass = allObservations.every((entry) => entry.ok);+ receipt.containment.status = containmentPass ? 'pass' : 'fail';+ receipt.captures.status = 'pass';+ receipt.captures.contactSheet = path.basename(outputs.contactSheet);+ receipt.status = containmentPass ? 'pass' : 'fail';+ receipt.ok = containmentPass;+ writeAtomic(outputs.contactSheet, contactSheetHtml({+ artifactPath: artifact,+ receipt,+ screenshots: receipt.captures.screenshots,+ }));+ persistReceipt(outputs, receipt);+ return { exitCode: containmentPass ? EXIT.pass : EXIT.fail, receipt };+ } catch (error) {+ cleanupCaptureSidecars(outputs);+ receipt.status = 'fail';+ receipt.ok = false;+ receipt.error = error.message;+ receipt.containment.status = 'fail';+ receipt.captures.status = 'fail';+ receipt.captures.screenshots = [];+ receipt.captures.contactSheet = null;+ persistReceipt(outputs, receipt);+ return { exitCode: EXIT.fail, receipt };+ } finally {+ if (browser?.close) await browser.close();+ }+}diff --git a/archify/references/authoring-contract.md b/archify/references/authoring-contract.mdindex 32f1712b..9b2b3005 100644--- a/archify/references/authoring-contract.md+++ b/archify/references/authoring-contract.md@@ -54,6 +54,16 @@ independent viewer state: switching Light / Dark must preserve the currentpreset. Author `signal-flow`, `blueprint`, or `editorial` only when the userexplicitly requests that visual style.+## Engineering profile default++Omit `meta.engineering_profile` for an ordinary system architecture. Region,+cluster, and security boundary wording do not by themselves enable an+engineering profile. Enable `deployment-ownership` only when the user+explicitly asks for a production deployment topology, ownership handoff, or+fail-closed deployment review and the source facts are known. Once enabled,+do not remove the engineering profile merely to pass validation; repair the+authored facts or report the diagnostics truthfully.+## Title hierarchyUse one concise title and let the diagram carry the explanation. Omit@@ -84,7 +94,14 @@ label mask width ≈ 6.5px × ASCII units + 13pxCJK characters count as two units```-If the gap is too small, prefer an unlabeled obvious edge. Otherwise increase the clear gap or apply a diagnosed `labelAt`, `labelDx`/`labelDy`, or `labelSegment`. Never guess several geometry controls at once.+Relationship labels are semantic data. If the gap is too small, move the label,+adjust the route or spacing, then shorten the wording while preserving meaning.+Only delete a label when both endpoints fully imply the relationship and it+contains no protocol, action, direction, synchronous/asynchronous behavior, or+cross-boundary mechanism. Explain why a deleted label is redundant. Never+delete a meaningful label merely to pass `showcase`. Apply a diagnosed+`labelAt`, `labelDx`/`labelDy`, or `labelSegment` before guessing several+geometry controls at once.### Repair orderdiff --git a/archify/references/delivery-contract.md b/archify/references/delivery-contract.mdindex cf4874c5..655794b4 100644--- a/archify/references/delivery-contract.md+++ b/archify/references/delivery-contract.md@@ -12,6 +12,28 @@ Deliver reads the specification once, writes those exact bytes to a private sameThe deterministic receipt proves byte identity and automated checks. Never claim that the deterministic receipt includes visual review.+## Automated visual evidence++After delivery, inspect the exact trusted HTML without rerendering or modifying+it:++```bash+node bin/archify.mjs visual-check <output.html> --json+```++The zero-dependency command uses Chrome/Chromium through the DevTools pipe. It+measures light-theme containment at 1440×900, 1600×1000, 1920×1080, and+2048×1320, then captures light/dark screenshots at 1440×900 and 2048×1320. It+writes four PNG sidecars, one relative-path HTML contact sheet, and one JSON+receipt beside the artifact. The receipt binds the source artifact SHA-256 and+byte count, records READ plus Still runtime state, and always reports+`visualReview: "pending"`; automated evidence cannot claim perceptual review.++Exit 0 means every containment measurement and capture passed. Exit 1 means an+overflow or capture failure. Exit 2 means Chrome/Chromium was unavailable and+the receipt status is `skipped`. Failed or skipped capture runs remove stale+image/contact-sheet sidecars rather than presenting prior evidence as current.+## Optional openingAdd `--open` only when the user wants an immediate local preview. It runs after that atomic commit, uses one argument-array OS opener with a five-second bound, and records `open.status`. Keep it off for CI, unattended agents, and non-interactive environments. Failure or unsupported opening does not invalidate delivery; its status proves only whether the local opener invocation succeeded.diff --git a/archify/test/authoring-safety-contract.test.mjs b/archify/test/authoring-safety-contract.test.mjsnew file mode 100644index 00000000..3acc7e8b--- /dev/null+++ b/archify/test/authoring-safety-contract.test.mjs@@ -0,0 +1,43 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import fs from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const skillRoot = path.resolve(__dirname, '..');+const skill = fs.readFileSync(path.join(skillRoot, 'SKILL.md'), 'utf8');+const authoringContract = fs.readFileSync(+ path.join(skillRoot, 'references', 'authoring-contract.md'),+ 'utf8',+);++test('relationship labels remain semantic data and deletion is an auditable last resort', () => {+ for (const [name, source] of [['SKILL.md', skill], ['authoring contract', authoringContract]]) {+ assert.match(source, /Relationship labels are semantic data/i, name);+ assert.match(source, /move the label[\s\S]*adjust the route or spacing[\s\S]*shorten/i, name);+ assert.match(source, /protocol[\s\S]*action[\s\S]*direction[\s\S]*synchronous[\s\S]*asynchronous[\s\S]*cross-boundary mechanism/i, name);+ assert.match(source, /Never\s+delete[\s\S]*merely to pass `?showcase`?/i, name);+ assert.match(source, /explain why[\s\S]*redundant/i, name);+ }+});++test('deployment ownership stays explicit, fact-backed, and cannot be removed to pass', () => {+ assert.match(skill, /Omit `meta\.engineering_profile` by default/);+ assert.match(skill, /Region.*cluster.*security boundar.*do not.*enable/i);+ assert.match(skill, /production deployment topology.*ownership.*fail-closed deployment review/i);+ assert.match(skill, /must not remove.*engineering profile.*pass validation/i);+});++test('visual-check stays a pending sidecar receipt instead of a polish claim', () => {+ const deliveryContract = fs.readFileSync(+ path.join(skillRoot, 'references', 'delivery-contract.md'),+ 'utf8',+ );+ for (const [name, source] of [['SKILL.md', skill], ['delivery contract', deliveryContract]]) {+ assert.match(source, /visual-check <output\.html> --json/, name);+ assert.match(source, /1440×900[\s\S]*1600×1000[\s\S]*1920×1080[\s\S]*2048×1320/, name);+ assert.match(source, /visualReview: "pending"/, name);+ assert.match(source, /never changes.*delivered|without (?:rerendering or )?modifying/i, name);+ }+});diff --git a/archify/test/cli.test.mjs b/archify/test/cli.test.mjsindex a76ae566..c0fcc8b8 100644--- a/archify/test/cli.test.mjs+++ b/archify/test/cli.test.mjs@@ -75,6 +75,7 @@ test('cli: help lists commands and diagram types', () => {assert.match(result.stdout, /archify compare architecture <base\.json> <head\.json>/);assert.match(result.stdout, /archify deliver <type>/);assert.match(result.stdout, /archify preview <type>/);+ assert.match(result.stdout, /archify visual-check <output\.html>/);assert.match(result.stdout, /--open/);assert.match(result.stdout, /archify guide \[scenario or question\]/);assert.match(result.stdout, /archify doctor/);@@ -229,6 +230,22 @@ test('cli: render writes a diagram html file', () => {assert.match(fs.readFileSync(out, 'utf8'), /Agent Tool Call Workflow/);});+test('cli: visual-check returns a skipped receipt with exit 2 when Chrome is unavailable', () => {+ const out = path.join(tmp, 'visual-check-skipped.html');+ fs.writeFileSync(out, '<!doctype html><html><body>delivered</body></html>');+ const missingChrome = path.join(tmp, 'missing-chrome');+ const result = run(['visual-check', out, '--json'], {+ env: { ...process.env, ARCHIFY_CHROME: missingChrome },+ });++ assert.equal(result.status, 2, result.stderr);+ const receipt = JSON.parse(result.stdout);+ assert.equal(receipt.status, 'skipped');+ assert.equal(receipt.visualReview, 'pending');+ assert.equal(receipt.chrome.status, 'unavailable');+ assert.equal(fs.existsSync(out.replace(/\.html$/, '.visual-check.json')), true);+});+test('cli: deliver atomically writes a checked artifact and structured receipt', () => {const out = path.join(tmp, 'delivered-workflow.html');const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');diff --git a/archify/test/visual-check.test.mjs b/archify/test/visual-check.test.mjsnew file mode 100644index 00000000..209ee461--- /dev/null+++ b/archify/test/visual-check.test.mjs@@ -0,0 +1,149 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { createHash } from 'node:crypto';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++import {+ VISUAL_CHECK_VIEWPORTS,+ runVisualCheck,+ sidecarPaths,+} from '../bin/visual-check.mjs';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const skillRoot = path.resolve(__dirname, '..');+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-visual-check-'));+const png = Buffer.from('89504e470d0a1a0a', 'hex');++function artifact(name = 'diagram.html') {+ const file = path.join(tmp, name);+ fs.writeFileSync(file, '<!doctype html><html><body>checked artifact</body></html>');+ return file;+}++function sha256(file) {+ return createHash('sha256').update(fs.readFileSync(file)).digest('hex');+}++function fakeBrowser({ overflowAt, screenshotFailure } = {}) {+ const calls = [];+ return {+ calls,+ async inspect({ width, height, theme, screenshotPath }) {+ calls.push({ width, height, theme, screenshotPath });+ if (screenshotPath && screenshotFailure?.({ width, height, theme })) {+ throw new Error('synthetic screenshot failure');+ }+ if (screenshotPath) fs.writeFileSync(screenshotPath, png);+ const overflow = overflowAt?.({ width, height, theme }) || false;+ return {+ innerWidth: width,+ innerHeight: height,+ scrollWidth: width + (overflow ? 1 : 0),+ scrollHeight: height,+ resolvedTheme: theme,+ };+ },+ async close() {},+ };+}++test('visual-check records four containment viewports and four endpoint theme captures', async () => {+ const input = artifact('passing.html');+ const before = sha256(input);+ const browser = fakeBrowser();+ const result = await runVisualCheck({+ artifactPath: input,+ chromePath: '/fake/chrome',+ browserFactory: async () => browser,+ });++ assert.equal(result.exitCode, 0);+ assert.equal(result.receipt.status, 'pass');+ assert.equal(result.receipt.visualReview, 'pending');+ assert.equal(result.receipt.containment.viewports.length, VISUAL_CHECK_VIEWPORTS.length);+ assert.equal(result.receipt.containment.viewports.every((entry) => entry.ok), true);+ assert.deepEqual(+ result.receipt.captures.screenshots.map(({ width, height, theme }) => [width, height, theme]),+ [+ [1440, 900, 'light'],+ [1440, 900, 'dark'],+ [2048, 1320, 'light'],+ [2048, 1320, 'dark'],+ ],+ );+ assert.equal(result.receipt.artifact.sha256, before);+ assert.equal(sha256(input), before, 'visual-check mutated the delivered artifact');++ const outputs = sidecarPaths(input);+ assert.equal(fs.existsSync(outputs.receipt), true);+ assert.equal(fs.existsSync(outputs.contactSheet), true);+ assert.equal(outputs.screenshots.every((entry) => fs.existsSync(entry.path)), true);+ const contactSheet = fs.readFileSync(outputs.contactSheet, 'utf8');+ for (const screenshot of outputs.screenshots) {+ assert.match(contactSheet, new RegExp(path.basename(screenshot.path).replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));+ assert.doesNotMatch(contactSheet, new RegExp(screenshot.path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));+ }+});++test('visual-check returns 1 and preserves evidence when any viewport overflows', async () => {+ const input = artifact('overflow.html');+ const result = await runVisualCheck({+ artifactPath: input,+ chromePath: '/fake/chrome',+ browserFactory: async () => fakeBrowser({+ overflowAt: ({ width, theme }) => width === 1600 && theme === 'light',+ }),+ });++ assert.equal(result.exitCode, 1);+ assert.equal(result.receipt.status, 'fail');+ assert.equal(result.receipt.containment.status, 'fail');+ assert.deepEqual(+ result.receipt.containment.viewports.filter((entry) => !entry.ok).map((entry) => [entry.width, entry.height]),+ [[1600, 1000]],+ );+ assert.equal(fs.existsSync(sidecarPaths(input).contactSheet), true);+});++test('visual-check returns 1 and removes misleading capture sidecars on screenshot failure', async () => {+ const input = artifact('capture-failure.html');+ const outputs = sidecarPaths(input);+ fs.writeFileSync(outputs.contactSheet, 'stale');+ for (const screenshot of outputs.screenshots) fs.writeFileSync(screenshot.path, png);++ const result = await runVisualCheck({+ artifactPath: input,+ chromePath: '/fake/chrome',+ browserFactory: async () => fakeBrowser({+ screenshotFailure: ({ theme }) => theme === 'dark',+ }),+ });++ assert.equal(result.exitCode, 1);+ assert.equal(result.receipt.status, 'fail');+ assert.equal(result.receipt.captures.status, 'fail');+ assert.match(result.receipt.error, /synthetic screenshot failure/);+ assert.equal(fs.existsSync(outputs.contactSheet), false);+ assert.equal(outputs.screenshots.some((entry) => fs.existsSync(entry.path)), false);+ assert.equal(fs.existsSync(outputs.receipt), true);+});++test('visual-check returns 2 with a truthful skipped receipt when Chrome is unavailable', async () => {+ const input = artifact('no-chrome.html');+ const result = await runVisualCheck({+ artifactPath: input,+ resolveChrome: () => null,+ });++ assert.equal(result.exitCode, 2);+ assert.equal(result.receipt.status, 'skipped');+ assert.equal(result.receipt.containment.status, 'skipped');+ assert.equal(result.receipt.captures.status, 'skipped');+ assert.equal(result.receipt.visualReview, 'pending');+ assert.equal(fs.existsSync(sidecarPaths(input).receipt), true);+});++process.on('exit', () => fs.rmSync(tmp, { recursive: true, force: true }));diff --git a/scripts/package-smoke.mjs b/scripts/package-smoke.mjsindex c72af653..1aacecb4 100644--- a/scripts/package-smoke.mjs+++ b/scripts/package-smoke.mjs@@ -136,6 +136,16 @@ try {throw new Error('packaged workflow delivery did not return a passing receipt');}+ const visualSkipped = JSON.parse(runExpectFailure([+ 'visual-check', delivered.output, '--json',+ ], {+ env: { ...process.env, ARCHIFY_CHROME: path.join(scratch, 'missing-chrome') },+ }));+ if (visualSkipped.status !== 'skipped' || visualSkipped.visualReview !== 'pending'+ || visualSkipped.chrome?.status !== 'unavailable') {+ throw new Error('packaged visual-check did not return the expected Chrome-unavailable receipt');+ }+const emptyPath = path.join(scratch, 'empty-path');fs.mkdirSync(emptyPath);const openReceipt = JSON.parse(run([