Skip to content

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

Merge dev test tooling migration into new diagram types

tt-a1ic82719ed9259
diff --cc test/class-motion-browser.test.mjs
index 9db7e155,00000000..fb603beb
mode 100644,000000..100644
--- a/test/class-motion-browser.test.mjs
+++ b/test/class-motion-browser.test.mjs
@@@ -1,95 -1,0 +1,95 @@@
+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 { findChrome } from '../bin/visual-check.mjs';
++import { findChrome } from '../archify/bin/visual-check.mjs';
+import { desktopBrowser } from './helpers/desktop-browser.mjs';
+
- const skillRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
++const skillRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'archify');
+const chrome = process.env.ARCHIFY_CHROME ? findChrome() : null;
+
+test('class: hierarchy bus motion follows from-to while retaining aligned visual dashes', {
+ skip: chrome ? false : 'Set ARCHIFY_CHROME to run class motion browser checks.',
+}, async (t) => {
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-class-motion-'));
+ t.after(() => fs.rmSync(scratch, { recursive: true, force: true }));
+ const diagram = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples/payments.class.json'), 'utf8'));
+ diagram.meta.animation = 'trace';
+ const input = path.join(scratch, 'payments.class.json');
+ const output = path.join(scratch, 'payments.html');
+ fs.writeFileSync(input, JSON.stringify(diagram));
+ execFileSync(process.execPath, [path.join(skillRoot, 'renderers/class/render-class.mjs'), input, output]);
+ const browser = desktopBrowser(chrome);
+ t.after(() => browser.close());
+ const session = await browser.sessionPromise;
+ const send = (method, params = {}) => browser.cdp.send(method, params, session);
+ const run = async (expression) => {
+ const result = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
+ assert.equal(result.exceptionDetails, undefined, result.exceptionDetails?.exception?.description);
+ return result.result?.value;
+ };
+ await send('Emulation.setDeviceMetricsOverride', { width: 1440, height: 900, deviceScaleFactor: 1, mobile: false });
+ await send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-reduced-motion', value: 'no-preference' }] });
+ await send('Page.addScriptToEvaluateOnNewDocument', { source: `try { localStorage.removeItem('archify-motion'); } catch (_) {}` });
+ const loaded = browser.cdp.waitFor('Page.loadEventFired', session);
+ await send('Page.navigate', { url: pathToFileURL(output).href });
+ await loaded;
+ await run('document.fonts.ready');
+ await run('Archify.viewerChromeLayout.whenStable()');
+ const result = await run(`(() => {
+ const edge = document.querySelector('path[data-edge-id="card_implements"]');
+ const visual = edge.getAttribute('d'), semantic = edge.getAttribute('data-motion-path');
+ const endpoints = pathData => {
+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); path.setAttribute('d', pathData);
+ const first = path.getPointAtLength(0), last = path.getPointAtLength(path.getTotalLength());
+ return [[first.x, first.y], [last.x, last.y]];
+ };
+ const token = Archify.flowTokens.create(edge, edge);
+ Archify.focus.inspectRelationshipById('card_implements', { toggle: false });
+ const pulse = document.querySelector('.relationship-flow-pulse').getAttribute('d');
+ const animatedToken = document.querySelector('.relationship-flow-token animateMotion').getAttribute('path');
+ Archify.focus.clear();
+ Archify.intentTrace.show('card_gateway');
+ const intent = document.querySelector('.intent-trace-flow').getAttribute('d');
+ Archify.intentTrace.clear();
+ Archify.semanticLens.select('class');
+ const lens = [...document.querySelectorAll('.semantic-lens-flow')].some(path => path.getAttribute('d') === semantic);
+ Archify.semanticLens.clear();
+ Archify.routeProbe.begin(); Archify.routeProbe.choose('card_gateway'); Archify.routeProbe.choose('payment_gateway');
+ const route = document.querySelector('.route-probe-flow').getAttribute('d');
+ Archify.routeProbe.selectJourneyIndex(1);
+ const journey = document.querySelector('.route-journey-flow').getAttribute('d');
+ return { visual, semantic, visualEnds: endpoints(visual), semanticEnds: endpoints(semantic),
+ token: token.querySelector('animateMotion').getAttribute('path'), pulse, animatedToken, intent, lens, route, journey,
+ original: edge.getAttribute('d'), marker: edge.getAttribute('marker-start') };
+ })()`);
+ assert.notEqual(result.visual, result.semantic);
+ assert.deepEqual(result.visualEnds, [...result.semanticEnds].reverse());
+ for (const mode of ['token', 'animatedToken', 'pulse', 'intent', 'route', 'journey']) assert.equal(result[mode], result.semantic, mode);
+ assert.equal(result.lens, true);
+ assert.equal(result.original, result.visual);
+ assert.equal(result.marker, 'url(#cl-triangle-start)');
+ const recording = await run(`(async () => {
+ Archify.routeProbe.clear();
+ const original = SVGGeometryElement.prototype.getPointAtLength;
+ const samples = [];
+ SVGGeometryElement.prototype.getPointAtLength = function (distance) {
+ const point = original.call(this, distance);
+ if (this.getAttribute('data-edge-id') === 'card_implements') samples.push({ d: this.getAttribute('d'), x: point.x, y: point.y });
+ return point;
+ };
+ try {
+ const blob = await Archify.motion.recordWebm({ duration: 250, fps: 10 });
+ return { type: blob.type, size: blob.size, samples };
+ } finally { SVGGeometryElement.prototype.getPointAtLength = original; }
+ })()`);
+ assert.match(recording.type, /^video\/webm/);
+ assert.ok(recording.size > 0);
+ assert.ok(recording.samples.length > 1);
+ assert.ok(recording.samples.every((sample) => sample.d === result.semantic));
+ assert.deepEqual([recording.samples[0].x, recording.samples[0].y], result.semanticEnds[0]);
+ assert.deepEqual([recording.samples.at(-1).x, recording.samples.at(-1).y], result.semanticEnds[1]);
+});
diff --cc test/class-rendering.test.mjs
index d9d849a1,00000000..965188b4
mode 100644,000000..100644
--- a/test/class-rendering.test.mjs
+++ b/test/class-rendering.test.mjs
@@@ -1,209 -1,0 +1,209 @@@
+import { test } from 'node:test';
+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 { fileURLToPath } from 'node:url';
+
- import { textUnits } from '../renderers/shared/utils.mjs';
- import { bandedLayout, resolveEntityPos } from '../renderers/erd/grid.mjs';
++import { textUnits } from '../archify/renderers/shared/utils.mjs';
++import { bandedLayout, resolveEntityPos } from '../archify/renderers/erd/grid.mjs';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
- const skillRoot = path.resolve(__dirname, '..');
++const skillRoot = path.resolve(__dirname, '..', 'archify');
+const renderer = path.join(skillRoot, 'renderers', 'class', 'render-class.mjs');
+const checker = path.join(skillRoot, 'scripts', 'check-render-output.mjs');
+const small = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples', 'payments.class.json'), 'utf8'));
+const large = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples', 'payment-processors.class.json'), 'utf8'));
+
+const clone = (value) => JSON.parse(JSON.stringify(value));
+
+function render(diagram) {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-class-'));
+ const input = path.join(directory, 'candidate.class.json');
+ const output = path.join(directory, 'candidate.html');
+ fs.writeFileSync(input, JSON.stringify(diagram));
+ const result = spawnSync(process.execPath, [renderer, input, output], { cwd: directory, encoding: 'utf8' });
+ const html = result.status === 0 ? fs.readFileSync(output, 'utf8') : '';
+ return { ...result, output, html, svg: html.match(/<svg\b[\s\S]*?<\/svg>/i)?.[0] ?? '' };
+}
+
+function attrs(tag) {
+ return Object.fromEntries([...tag.matchAll(/([a-zA-Z-]+)="([^"]*)"/g)].map((match) => [match[1], match[2]]));
+}
+
+function relationshipPaths(svg) {
+ return [...svg.matchAll(/<path [^>]*data-class-relationship="[^"]+"[^>]*\/>/g)]
+ .map((match) => attrs(match[0]))
+ .filter((attributes) => attributes['data-edge-from']);
+}
+
+function typeBoxes(svg) {
+ const boxes = new Map();
+ for (const match of svg.matchAll(/data-node-id="([a-z_]+)"[\s\S]{0,600}?<rect x="([\d.]+)" y="([\d.]+)" width="([\d.]+)" height="([\d.]+)" rx="6" class="c-[a-z]+ cl-type"/g)) {
+ boxes.set(match[1], { x: +match[2], y: +match[3], width: +match[4], height: +match[5] });
+ }
+ return boxes;
+}
+
+for (const [name, diagram] of [['small', small], ['large', large]]) {
+ test(`class: ${name} example renders and passes the showcase artifact checks`, () => {
+ const result = render(diagram);
+ assert.equal(result.status, 0, result.stderr);
+ const check = spawnSync(process.execPath, [checker, result.output], { encoding: 'utf8' });
+ const receipt = JSON.parse(check.stdout);
+ assert.equal(receipt.ok, true, JSON.stringify(receipt.checks.filter((entry) => !entry.ok)));
+ assert.equal(receipt.composition.summary.errors, 0);
+ assert.equal(receipt.composition.summary.warnings, 0);
+ });
+}
+
+test('class: each relationship kind draws its own line and marker', () => {
+ const { svg, status, stderr } = render(large);
+ assert.equal(status, 0, stderr);
+ const byKind = {};
+ for (const path of relationshipPaths(svg)) (byKind[path['data-class-relationship']] ||= []).push(path);
+ const one = (kind) => byKind[kind][0];
+ assert.match(one('dependency').class, /\bcl-dashed\b/);
+ assert.equal(one('dependency')['marker-end'], 'url(#cl-open)');
+ assert.doesNotMatch(one('association').class, /\bcl-dashed\b/);
+ assert.equal(one('association')['marker-end'], 'url(#cl-open)');
+ assert.equal(one('composition')['marker-start'], 'url(#cl-diamond-filled)');
+ assert.equal(one('aggregation')['marker-start'], 'url(#cl-diamond-hollow)');
+ // Realization is dashed with a triangle; inheritance is solid with a triangle.
+ for (const path of byKind.realization) {
+ assert.match(path.class, /\bcl-dashed\b/);
+ assert.match(path['marker-end'] || path['marker-start'], /cl-triangle/);
+ }
+ for (const path of byKind.inheritance) {
+ assert.doesNotMatch(path.class, /\bcl-dashed\b/);
+ assert.match(path['marker-end'] || path['marker-start'], /cl-triangle/);
+ }
+});
+
+test('class: implementations of one supertype share a hierarchy bus and a single triangle point', () => {
+ const { svg } = render(small);
+ const boxes = typeBoxes(svg);
+ const gateway = boxes.get('payment_gateway');
+ const realizations = relationshipPaths(svg).filter((path) => path['data-class-relationship'] === 'realization');
+ assert.equal(realizations.length, 2);
+ const tips = new Set(realizations.map((path) => path['data-composition-points'].split(';').at(-1)));
+ assert.deepEqual([...tips], [`${gateway.x + gateway.width / 2},${gateway.y + gateway.height}`]);
+ for (const path of realizations) {
+ assert.equal(path['data-class-bus'], 'payment_gateway');
+ // Drawn from the supertype so the shared dashed trunk keeps one phase.
+ assert.match(path.d, new RegExp(`^M ${gateway.x + gateway.width / 2} ${gateway.y + gateway.height} `));
+ assert.equal(path['marker-start'], 'url(#cl-triangle-start)');
+ }
+ assert.match(svg, /<marker id="cl-triangle-start"[^>]*orient="auto-start-reverse"/);
+ // `col: 1.5` centres the supertype over its two subtypes, so the bus is symmetric.
+ const centre = (box) => box.x + box.width / 2;
+ assert.ok(Math.abs(centre(gateway) - (centre(boxes.get('card_gateway')) + centre(boxes.get('wallet_gateway'))) / 2) < 0.5);
+});
+
+test('class: half columns remain placeable without occupied integer neighbours', () => {
+ const grid = { origin: [100, 40], gapX: 128, gapY: 84, entityW: 180 };
+ for (const col of [0.5, 1.5, 3.5]) {
+ const entity = { row: 0, col, width: 180, height: 60 };
+ const bands = bandedLayout([entity], grid);
+ assert.deepEqual(resolveEntityPos(entity, grid, bands), [Math.max(100, 100 + 128 * col - 90), 40]);
+ }
+ const diagram = clone(small);
+ diagram.types = [{ id: 'person', label: 'Person', kind: 'interface', row: 0, col: 0.5, width: 300 }];
+ diagram.relationships = [];
+ const result = render(diagram);
+ assert.equal(result.status, 0, result.stderr);
+ assert.doesNotMatch(result.svg, /NaN|Infinity/);
+ const box = typeBoxes(result.svg).get('person');
+ assert.ok(box.x >= 0, 'half-column box must stay inside the canvas');
+ const check = spawnSync(process.execPath, [checker, result.output], { encoding: 'utf8' });
+ assert.equal(JSON.parse(check.stdout).ok, true, check.stdout);
+});
+
+test('class: shared grid preserves integer-column positions for ERD callers', () => {
+ const grid = { origin: [32, 40], gapX: 56, gapY: 44, entityW: 240 };
+ const entities = [{ row: 0, col: 0, width: 240, height: 60 }, { row: 0, col: 2, width: 120, height: 60 }];
+ const bands = bandedLayout(entities, grid);
+ assert.deepEqual(entities.map((entity) => resolveEntityPos(entity, grid, bands)), [[32, 40], [384, 40]]);
+});
+
+test('class: long members wrap inside the box instead of being truncated', () => {
+ const { svg, status, stderr } = render(large);
+ assert.equal(status, 0, stderr);
+ const boxes = typeBoxes(svg);
+ const processor = boxes.get('payment_processor');
+ const block = svg.slice(svg.indexOf('data-node-id="payment_processor"'), svg.indexOf('data-node-id="order"'));
+ // Annotations are tspans inside the line; the line's text is what is read.
+ const lines = [...block.matchAll(/<text data-detail="context" data-class-member="methods"[^>]* x="([\d.]+)"[^>]*>(.*?)<\/text>/g)]
+ .map((line) => Object.assign([...line], { 2: line[2].replace(/<[^>]+>/g, '') }));
+ assert.ok(lines.some((line) => /data-class-continuation/.test(line[0])), 'expected a wrapped continuation line');
+ const joined = lines.map((line) => line[2]).join('').replace(/&gt;/g, '>').replace(/&lt;/g, '<');
+ for (const method of large.types.find((type) => type.id === 'payment_processor').methods) {
+ assert.ok(joined.replace(/\s+/g, '').includes(`${method.name}(${method.parameters}):${method.returns}`.replace(/\s+/g, '')), method.name);
+ }
+ for (const line of lines) {
+ const right = Number(line[1]) + textUnits(line[2]) * 11 * 0.6;
+ assert.ok(right <= processor.x + processor.width - 11, `"${line[2]}" overruns its box`);
+ }
+});
+
+function failure(mutate) {
+ const diagram = clone(small);
+ mutate(diagram);
+ const result = render(diagram);
+ assert.notEqual(result.status, 0, 'renderer accepted an invalid diagram');
+ return result.stderr;
+}
+
+test('class: realization must run from a non-interface to an interface', () => {
+ const stderr = failure((d) => { d.relationships.find((r) => r.id === 'card_implements').to = 'order'; });
+ assert.match(stderr, /class\/realization-target/);
+});
+
+test('class: inheritance across the interface boundary is rejected', () => {
+ const stderr = failure((d) => { d.relationships.find((r) => r.id === 'card_implements').kind = 'inheritance'; });
+ assert.match(stderr, /class\/inheritance-kind/);
+});
+
+test('class: an inheritance cycle is rejected', () => {
+ const stderr = failure((d) => {
+ d.relationships.push(
+ { from: 'card_gateway', to: 'wallet_gateway', kind: 'inheritance' },
+ { from: 'wallet_gateway', to: 'card_gateway', kind: 'inheritance', fromSide: 'top', toSide: 'top' },
+ );
+ });
+ assert.match(stderr, /class\/inheritance-cycle/);
+});
+
+test('class: interfaces accept instance property contracts and static constants', () => {
+ const diagram = clone(small);
+ diagram.types.find((type) => type.id === 'payment_gateway').attributes = [
+ { name: 'name', type: 'string' },
+ { name: 'VERSION', type: 'string', static: true },
+ ];
+ const { status, stderr, svg } = render(diagram);
+ assert.equal(status, 0, stderr);
+ const text = svg.replace(/<[^>]+>/g, '');
+ assert.match(text, /name: string/);
+ assert.match(text, /VERSION: string/);
+});
+
+test('class: duplicate interface properties remain invalid', () => {
+ const stderr = failure((diagram) => {
+ diagram.types.find((type) => type.id === 'payment_gateway').attributes = [
+ { name: 'name', type: 'string' },
+ { name: 'name', type: 'string' },
+ ];
+ });
+ assert.match(stderr, /declares attribute "name" twice/);
+});
+
+test('class: an authored width too narrow for the title is reported, not clipped', () => {
+ const stderr = failure((d) => { d.types.find((t) => t.id === 'payment_gateway').width = 120; });
+ assert.match(stderr, /class\/title-text-capacity/);
+});
+
+test('class: unknown endpoints and self-relationships are rejected', () => {
+ assert.match(failure((d) => { d.relationships[0].to = 'missing'; }), /unknown type "missing"/);
+ assert.match(failure((d) => { d.relationships[0].to = d.relationships[0].from; }), /to itself/);
+});
diff --cc test/timeline-rendering.test.mjs
index 77035954,00000000..6ae0c832
mode 100644,000000..100644
--- a/test/timeline-rendering.test.mjs
+++ b/test/timeline-rendering.test.mjs
@@@ -1,159 -1,0 +1,159 @@@
+import { test } from 'node:test';
+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 { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
- const skillRoot = path.resolve(__dirname, '..');
++const skillRoot = path.resolve(__dirname, '..', 'archify');
+const renderer = path.join(skillRoot, 'renderers', 'timeline', 'render-timeline.mjs');
+const checker = path.join(skillRoot, 'scripts', 'check-render-output.mjs');
+const small = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples', 'payment-incident.timeline.json'), 'utf8'));
+const large = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples', 'archify-dev-activity.timeline.json'), 'utf8'));
+const clone = (value) => JSON.parse(JSON.stringify(value));
+
+function run(diagram, extra = []) {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-timeline-'));
+ const input = path.join(directory, 'candidate.timeline.json');
+ const output = path.join(directory, 'candidate.html');
+ fs.writeFileSync(input, JSON.stringify(diagram));
+ return { ...spawnSync(process.execPath, [renderer, input, output, ...extra], { cwd: directory, encoding: 'utf8' }), output };
+}
+function layoutOf(diagram) {
+ const result = run(diagram, ['--layout-json']);
+ assert.equal(result.status, 0, result.stderr);
+ return JSON.parse(result.stdout);
+}
+const overlap = (a, b) => a.left < b.left + b.width && b.left < a.left + a.width && a.top < b.top + b.height && b.top < a.top + a.height;
+
+test('timeline: both examples render and pass the showcase artifact checks', () => {
+ for (const diagram of [small, large]) {
+ const result = run(diagram);
+ assert.equal(result.status, 0, result.stderr);
+ const receipt = JSON.parse(spawnSync(process.execPath, [checker, result.output], { encoding: 'utf8' }).stdout);
+ assert.equal(receipt.ok, true, JSON.stringify(receipt.checks.filter((entry) => !entry.ok)));
+ assert.equal(receipt.composition.summary.errors, 0);
+ }
+});
+
+test('timeline: position is linear in time on one shared axis across lanes', () => {
+ const report = layoutOf(small);
+ assert.equal(report.breaks.length, 0);
+ const [a, b, c] = report.events;
+ // 10:00, 10:05, 10:10 in different lanes: equal time steps are equal x steps.
+ assert.ok(Math.abs((b.x - a.x) - (c.x - b.x)) < 0.02);
+ assert.notEqual(a.lane, b.lane);
+ // Every tick sits at its own timestamp on the same scale.
+ for (const tick of report.ticks) {
+ assert.ok(Math.abs(tick.x - (a.x + (tick.t - a.t) * report.scalePxPerMinute / 60000)) < 0.05);
+ }
+});
+
+test('timeline: events are drawn in chronological order whatever the authored order', () => {
+ const diagram = clone(small);
+ diagram.events.reverse();
+ const report = layoutOf(diagram);
+ const times = report.events.map((event) => event.t);
+ assert.deepEqual(times, [...times].sort((x, y) => x - y));
+ assert.ok(report.events.every((event, index, all) => !index || event.x >= all[index - 1].x));
+});
+
+test('timeline: offsets are honoured, so the same instant in two offsets aligns', () => {
+ const diagram = clone(small);
+ diagram.events.push({ id: 'same_instant', at: '2026-10-01T07:35:00+05:30', title: 'Same instant as the alert', lane: 'release' });
+ const report = layoutOf(diagram);
+ const alert = report.events.find((event) => event.id === 'alert');
+ const same = report.events.find((event) => event.id === 'same_instant');
+ assert.equal(same.t, alert.t);
+ assert.equal(same.x, alert.x);
+});
+
+test('timeline: long quiet periods become disclosed breaks, proportional inside each segment', () => {
+ const report = layoutOf(large);
+ assert.ok(report.breaks.length >= 1);
+ for (const gap of report.breaks) assert.ok(gap.x1 - gap.x0 >= 56);
+ const result = run(large);
+ const svg = fs.readFileSync(result.output, 'utf8').match(/<svg\b[\s\S]*?<\/svg>/)[0];
+ assert.equal((svg.match(/data-timeline-break=""/g) || []).length, report.breaks.length);
+ assert.match(svg, /quiet period\(s\) compressed/);
+ assert.match(svg, /data-timeline-evidence="observed"/);
+ // Without breaks the axis is one proportional segment.
+ const flat = clone(large);
+ flat.layout = { breaks: 'none' };
+ assert.equal(layoutOf(flat).breaks.length, 0);
+});
+
+test('timeline: simultaneous and close events stack instead of overprinting', () => {
+ const diagram = clone(small);
+ diagram.events.push(
+ { id: 'page_1', at: '2026-10-01T10:05:00+08:00', title: 'Page primary on-call', lane: 'monitoring' },
+ { id: 'page_2', at: '2026-10-01T10:05:20+08:00', title: 'Page secondary on-call', lane: 'monitoring' },
+ );
+ const report = layoutOf(diagram);
+ const cards = report.events;
+ for (const card of cards) for (const other of cards) if (card.id < other.id) assert.ok(!overlap(card, other), `${card.id} overlaps ${other.id}`);
+ assert.equal(report.events.find((event) => event.id === 'page_1').x, report.events.find((event) => event.id === 'alert').x);
+});
+
+function failure(mutate) {
+ const diagram = clone(small);
+ mutate(diagram);
+ const result = run(diagram);
+ assert.notEqual(result.status, 0, 'renderer accepted invalid input');
+ return result.stderr;
+}
+
+test('timeline: ambiguous or invalid time input is refused', () => {
+ assert.match(failure((d) => { d.events[0].at = '2026-10-01T10:00:00'; }), /\/events\/0\/at/);
+ assert.match(failure((d) => { d.events[0].at = '2026-02-30T25:00:00Z'; }), /timeline\/invalid-timestamp/);
+ assert.match(failure((d) => { d.meta.timezone = 'Mars/Olympus'; }), /timeline\/invalid-timezone/);
+ assert.match(failure((d) => { d.events[0].lane = 'billing'; }), /timeline\/unknown-lane/);
+ assert.match(failure((d) => { delete d.meta.evidence; }), /evidence/);
+});
+
+test('timeline: invalid calendar dates are rejected before Date.parse can normalize them', () => {
+ for (const at of ['2026-02-30T10:00:00Z', '2025-02-29T10:00:00+05:30', '2100-02-29T10:00:00Z', '2026-04-31T10:00:00-04:00']) {
+ assert.match(failure((diagram) => { diagram.events[0].at = at; }), /timeline\/invalid-timestamp/);
+ }
+ for (const at of ['2024-02-29T10:00:00+05:30', '2000-02-29T10:00:00Z']) {
+ const diagram = clone(small);
+ diagram.events[0].at = at;
+ const event = layoutOf(diagram).events.find((entry) => entry.id === diagram.events[0].id);
+ assert.equal(event.t, Date.parse(at));
+ }
+});
+
+function crowdedBreaksDiagram() {
+ const diagram = clone(small);
+ diagram.layout = { width: 480, breaks: 'auto' };
+ const start = Date.parse('2026-01-01T00:00:00Z');
+ // Nine short bursts separated by eight eligible quiet periods. Their labels
+ // and segment floors previously exhausted a 480px axis and set scale to 0.
+ diagram.events = Array.from({ length: 18 }, (_, index) => ({
+ id: `event_${index}`,
+ at: new Date(start + Math.floor(index / 2) * (35 * 60 * 60000) + (index % 2) * 10 * 60000).toISOString(),
+ title: `Event ${index}`,
+ lane: 'release',
+ }));
+ return diagram;
+}
+
+test('timeline: automatic breaks leave room for proportional time on a narrow axis', () => {
+ const report = layoutOf(crowdedBreaksDiagram());
+ assert.ok(report.breaks.length > 0, 'eligible quiet periods still compress');
+ assert.ok(report.scalePxPerMinute > 0, 'distinct instants must retain a positive scale');
+ assert.ok(report.events.every((event, index, all) => !index || event.x > all[index - 1].x), 'distinct instants must not collapse to one x');
+ for (const segment of report.segments) {
+ assert.ok(segment.x0 <= segment.x1);
+ assert.ok(segment.x1 <= report.viewBox[0] - 28 - 72, 'segments stay within the authored axis');
+ }
+ for (const gap of report.breaks) assert.ok(gap.x1 <= report.viewBox[0] - 28 - 72, 'breaks stay within the authored axis');
+ const result = run(crowdedBreaksDiagram());
+ assert.equal(result.status, 0, result.stderr);
+ const html = fs.readFileSync(result.output, 'utf8');
+ assert.equal((html.match(/data-timeline-break=""/g) || []).length, report.breaks.length);
+ const receipt = JSON.parse(spawnSync(process.execPath, [checker, result.output], { encoding: 'utf8' }).stdout);
+ assert.equal(receipt.ok, true, JSON.stringify(receipt.checks.filter((entry) => !entry.ok)));
+});
diff --cc test/tree-branches-browser.test.mjs
index f2a64cec,00000000..3cdaa104
mode 100644,000000..100644
--- a/test/tree-branches-browser.test.mjs
+++ b/test/tree-branches-browser.test.mjs
@@@ -1,178 -1,0 +1,178 @@@
+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';
++import { ChromeVisualBrowser, findChrome } from '../archify/bin/visual-check.mjs';
+
- const skillRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
++const skillRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'archify');
+const chromeConfigured = Object.prototype.hasOwnProperty.call(process.env, 'ARCHIFY_CHROME');
+const chrome = chromeConfigured ? findChrome() : null;
+if (chromeConfigured && !chrome) {
+ throw new Error(`ARCHIFY_CHROME does not resolve to an executable browser: ${process.env.ARCHIFY_CHROME}`);
+}
+
+test('Tree branches collapse in place, follow the keyboard, reveal selections, and export complete', {
+ skip: chrome ? false : 'Set ARCHIFY_CHROME to run real-browser tree checks.',
+}, async (t) => {
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-tree-browser-'));
+ t.after(() => fs.rmSync(scratch, { recursive: true, force: true }));
+ // Verified evidence on a root, branch and leaf exercises the shared beacon
+ // installer against both hidden stack decorations and actual node cards.
+ const git = (...args) => execFileSync('git', ['-C', scratch, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+ fs.writeFileSync(path.join(scratch, 'source.js'), 'export const source = true;\n');
+ git('init');
+ git('config', 'user.name', 'Archify Tests');
+ git('config', 'user.email', '[email protected]');
+ git('add', 'source.js');
+ git('commit', '-m', 'source fixture');
+ git('remote', 'add', 'origin', 'https://github.com/example/evidence-repo');
+ const render = (example, name) => {
+ const output = path.join(scratch, name);
+ const diagram = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples', example), 'utf8'));
+ diagram.meta.repository = { url: 'https://github.com/example/evidence-repo', revision: git('rev-parse', 'HEAD') };
+ diagram.nodes.forEach((node) => { node.sources = [{ path: 'source.js', line: 1 }]; });
+ const input = path.join(scratch, name + '.json');
+ fs.writeFileSync(input, JSON.stringify(diagram));
+ execFileSync(process.execPath, [path.join(skillRoot, 'bin/archify.mjs'), 'render', 'tree', input, output, '--repo-root', scratch]);
+ return output;
+ };
+ const small = render('payment-platform.tree.json', 'small.html');
+ const large = render('archify-repository.tree.json', 'large.html');
+ // Private export hook in this disposable copy only, as in export-cleanup-browser.
+ const html = fs.readFileSync(small, 'utf8');
+ const hooked = html.replace(' function download(blob, filename) {',
+ ' window.treeExportTest = { serialize: serializeSvg, clean: cleanExportClone };\n function download(blob, filename) {');
+ assert.notEqual(hooked, html, 'export hook anchor');
+ fs.writeFileSync(small, hooked);
+
+ const browser = new ChromeVisualBrowser(chrome);
+ t.after(() => browser.close());
+ const session = await browser.sessionPromise;
+ const send = (method, params = {}) => browser.cdp.send(method, params, session);
+ await send('Emulation.setFocusEmulationEnabled', { enabled: true });
+ async function run(expression) {
+ const result = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
+ assert.equal(result.exceptionDetails, undefined, result.exceptionDetails?.exception?.description);
+ return result.result?.value;
+ }
+ let loadCount = 0;
+ async function load(file, hash = '', theme = 'light') {
+ await send('Emulation.setDeviceMetricsOverride', { width: 1440, height: 900, deviceScaleFactor: 1, mobile: false });
+ const loaded = browser.cdp.waitFor('Page.loadEventFired', session);
+ await send('Page.navigate', { url: pathToFileURL(file).href + '?theme=' + theme + '&load=' + ++loadCount + hash });
+ await loaded;
+ await run('document.fonts.ready');
+ await run('Archify.viewerChromeLayout.whenStable()');
+ }
+ async function key(name, code, windowsVirtualKeyCode) {
+ await send('Input.dispatchKeyEvent', { type: 'keyDown', key: name, code, windowsVirtualKeyCode });
+ await send('Input.dispatchKeyEvent', { type: 'keyUp', key: name, code, windowsVirtualKeyCode });
+ }
+ const box = (id) => `(() => { const r = document.querySelector('[data-node-id="${id}"] > rect.c-mask').getBoundingClientRect(); return [Math.round(r.x), Math.round(r.y)]; })()`;
+
+ await load(small);
+ assert.equal(await run('Archify.treeBranches.active'), true);
+ async function checkBeacons() {
+ assert.deepEqual(await run(`(() => ['platform', 'payments', 'card_payment'].map(id => {
+ const node = document.querySelector('[data-node-id="' + id + '"]');
+ const beacon = node.querySelector('[data-source-evidence-beacon]');
+ const card = node.querySelector('rect.c-mask').getBoundingClientRect();
+ const box = beacon && beacon.getBoundingClientRect();
+ const texts = [...node.querySelectorAll('text:not(.source-evidence-beacon text)')];
+ texts.forEach(text => {
+ text.style.setProperty('display', 'inline', 'important');
+ text.style.setProperty('opacity', '1', 'important');
+ });
+ const textCollisions = texts.filter(text => {
+ const other = text.getBoundingClientRect();
+ return box && box.left < other.right && other.left < box.right && box.top < other.bottom && other.top < box.bottom;
+ }).map(text => text.textContent);
+ return { id, exists: !!beacon, onCard: !!box && box.x >= card.x && box.x + box.width <= card.x + card.width
+ && box.y >= card.y && box.y + box.height <= card.y + card.height, textCollisions };
+ }))()`), ['platform', 'payments', 'card_payment'].map(id => ({ id, exists: true, onCard: true, textCollisions: [] })));
+ }
+ await checkBeacons();
+ const before = await run(box('operations'));
+ const started = await run('performance.now()');
+ await run(`document.querySelector('[data-tree-toggle="payments"]').dispatchEvent(new MouseEvent('click', { bubbles: true }))`);
+ const elapsed = (await run('performance.now()')) - started;
+ const collapsed = await run(`(() => ({
+ hidden: [...document.querySelectorAll('[data-node-id][data-tree-hidden]')].map((n) => n.getAttribute('data-node-id')),
+ hiddenEdges: document.querySelectorAll('[data-edge-to][data-tree-hidden]').length,
+ expanded: document.querySelector('[data-tree-toggle="payments"]').getAttribute('aria-expanded'),
+ label: document.querySelector('[data-tree-toggle="payments"]').getAttribute('aria-label'),
+ stacked: document.querySelector('[data-node-id="payments"]').hasAttribute('data-tree-collapsed'),
+ expandAll: getComputedStyle(document.querySelector('[data-tree-expand-all]')).display,
+ }))()`);
+ assert.deepEqual(collapsed.hidden, ['card_payment', 'wallet_payment']);
+ assert.equal(collapsed.hiddenEdges, 2);
+ assert.equal(collapsed.expanded, 'false');
+ assert.equal(collapsed.label, 'Expand Payments (2 hidden)');
+ assert.equal(collapsed.stacked, true);
+ assert.notEqual(collapsed.expandAll, 'none');
+ // Collapsing never moves what stays visible.
+ assert.deepEqual(await run(box('operations')), before);
+ assert.ok(elapsed < 50, `collapse took ${elapsed}ms`);
+
+ // Keyboard: Enter on the toggle restores the branch and keeps focus there;
+ // ArrowLeft on a branch node collapses it, ArrowRight expands it.
+ await run(`document.querySelector('[data-tree-toggle="payments"]').focus()`);
+ await key('Enter', 'Enter', 13);
+ assert.deepEqual(await run('Archify.treeBranches.collapsedIds()'), []);
+ assert.equal(await run(`document.activeElement.getAttribute('data-tree-toggle')`), 'payments');
+ await run(`document.querySelector('[data-node-id="orders"]').focus()`);
+ await key('ArrowLeft', 'ArrowLeft', 37);
+ assert.deepEqual(await run('Archify.treeBranches.collapsedIds()'), ['orders']);
+ await key('ArrowRight', 'ArrowRight', 39);
+ assert.deepEqual(await run('Archify.treeBranches.collapsedIds()'), []);
+
+ // A selection through the shared focus path reveals a hidden node.
+ await run(`Archify.treeBranches.collapse('platform')`);
+ assert.equal(await run(`document.querySelector('[data-node-id="refunds"]').hasAttribute('data-tree-hidden')`), true);
+ await run(`Archify.focus.set('refunds')`);
+ assert.deepEqual(await run('Archify.treeBranches.collapsedIds()'), []);
+ assert.equal(await run(`document.querySelector('[data-node-id="refunds"]').hasAttribute('data-tree-hidden')`), false);
+
+ // Export is always the complete hierarchy, and the live view keeps its state.
+ await run(`Archify.treeBranches.collapse('operations'); Archify.treeBranches.collapse('platform')`);
+ const exported = await run(`(() => {
+ const clone = document.querySelector('.diagram-container > svg').cloneNode(true);
+ const clean = treeExportTest.clean(clone);
+ return { clean, hidden: clone.querySelectorAll('[data-tree-hidden], [data-tree-collapsed]').length,
+ any: clone.hasAttribute('data-tree-any-collapsed'),
+ collapsedToggles: clone.querySelectorAll('[data-tree-toggle][aria-expanded="false"]').length,
+ nodes: clone.querySelectorAll('[data-node-id]').length };
+ })()`);
+ assert.deepEqual(exported, { clean: true, hidden: 0, any: false, collapsedToggles: 0, nodes: 10 });
+ assert.deepEqual((await run('Archify.treeBranches.collapsedIds()')).sort(), ['operations', 'platform']);
+
+ // Expand all restores the authored hierarchy.
+ await run(`document.querySelector('[data-tree-expand-all]').dispatchEvent(new MouseEvent('click', { bubbles: true }))`);
+ assert.deepEqual(await run('Archify.treeBranches.collapsedIds()'), []);
+ assert.equal(await run(`document.querySelectorAll('[data-tree-hidden]').length`), 0);
+
+ // An authored collapsed branch starts collapsed in the Viewer.
+ await load(large);
+ assert.deepEqual(await run('Archify.treeBranches.collapsedIds()'), ['viewer']);
+ assert.equal(await run(`document.querySelector('[data-node-id="v_tree"]').hasAttribute('data-tree-hidden')`), true);
+
+ // Initial shared links reveal the authored collapsed ancestors before focus
+ // measures the node. Hash updates use an internal setter, as do multi-selects.
+ await load(large, '#focus=v_tree');
+ assert.deepEqual(await run('Archify.treeBranches.collapsedIds()'), []);
+ assert.equal(await run('Archify.focus.active()'), 'v_tree');
+ assert.equal(await run(`document.querySelector('[data-node-id="v_tree"]').getBoundingClientRect().width > 0`), true);
+ assert.equal(await run(`document.getElementById('focus-chip').hidden`), false);
+ await run(`Archify.treeBranches.collapse('viewer'); location.hash = 'focus=v_focus'`);
+ await run(`new Promise(resolve => setTimeout(resolve, 50))`);
+ assert.equal(await run('Archify.focus.active()'), 'v_focus');
+ assert.deepEqual(await run('Archify.treeBranches.collapsedIds()'), []);
+ await run(`Archify.treeBranches.collapse('viewer'); Archify.focus.setMany(['v_tree', 'v_focus'])`);
+ assert.deepEqual(await run('Archify.treeBranches.collapsedIds()'), []);
+
+ await load(small, '', 'dark');
+ await checkBeacons();
+});
diff --cc test/tree-rendering.test.mjs
index 58a72b93,00000000..dc85abd4
mode 100644,000000..100644
--- a/test/tree-rendering.test.mjs
+++ b/test/tree-rendering.test.mjs
@@@ -1,149 -1,0 +1,149 @@@
+import { test } from 'node:test';
+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 { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
- const skillRoot = path.resolve(__dirname, '..');
++const skillRoot = path.resolve(__dirname, '..', 'archify');
+const renderer = path.join(skillRoot, 'renderers', 'tree', 'render-tree.mjs');
+const checker = path.join(skillRoot, 'scripts', 'check-render-output.mjs');
+const small = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples', 'payment-platform.tree.json'), 'utf8'));
+const large = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples', 'archify-repository.tree.json'), 'utf8'));
+const clone = (value) => JSON.parse(JSON.stringify(value));
+
+function run(diagram, extra = []) {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-tree-'));
+ const input = path.join(directory, 'candidate.tree.json');
+ const output = path.join(directory, 'candidate.html');
+ fs.writeFileSync(input, JSON.stringify(diagram));
+ const result = spawnSync(process.execPath, [renderer, input, output, ...extra], { cwd: directory, encoding: 'utf8' });
+ return { ...result, output };
+}
+
+const layoutOf = (diagram) => {
+ const result = run(diagram, ['--layout-json']);
+ assert.equal(result.status, 0, result.stderr);
+ return JSON.parse(result.stdout);
+};
+
+const overlap = (a, b) => a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height;
+
+for (const [name, diagram] of [['small', small], ['large', large]]) {
+ test(`tree: ${name} example renders and passes the showcase artifact checks`, () => {
+ const result = run(diagram);
+ assert.equal(result.status, 0, result.stderr);
+ const receipt = JSON.parse(spawnSync(process.execPath, [checker, result.output], { encoding: 'utf8' }).stdout);
+ assert.equal(receipt.ok, true, JSON.stringify(receipt.checks.filter((entry) => !entry.ok)));
+ assert.equal(receipt.composition.summary.errors, 0);
+ assert.equal(receipt.composition.summary.warnings, 0);
+ });
+
+ test(`tree: ${name} layout keeps generations aligned and nodes apart`, () => {
+ const report = layoutOf(diagram);
+ const byId = new Map(report.nodes.map((node) => [node.id, node]));
+ const down = report.direction === 'down';
+ for (const node of report.nodes) {
+ for (const other of report.nodes) if (node.id < other.id) assert.ok(!overlap(node, other), `${node.id} overlaps ${other.id}`);
+ if (!node.parent) continue;
+ const parent = byId.get(node.parent);
+ assert.equal(node.depth, parent.depth + 1);
+ // Children lie strictly past their parent along the depth axis.
+ assert.ok(down ? node.y >= parent.y + parent.height : node.x >= parent.x + parent.width, `${node.id} is not beyond ${parent.id}`);
+ }
+ // One generation shares one band edge: a row centre going down, a column
+ // start going right. A stacked leaf list hangs below its parent instead.
+ const bands = new Map();
+ for (const node of report.nodes) {
+ if (node.stacked) continue;
+ const key = down ? Math.round(node.y + node.height / 2) : node.x;
+ (bands.get(node.depth) || bands.set(node.depth, new Set()).get(node.depth)).add(key);
+ }
+ for (const [depth, keys] of bands) assert.equal(keys.size, 1, `generation ${depth} is not aligned`);
+ // Every link starts at its parent and ends at its child.
+ for (const edge of report.edges) {
+ const [start, end] = [edge.points[0], edge.points.at(-1)];
+ const parent = byId.get(edge.from);
+ const child = byId.get(edge.to);
+ if (down) {
+ assert.equal(start[1], parent.y + parent.height);
+ assert.ok(start[0] > parent.x && start[0] < parent.x + parent.width, `${edge.from} link leaves its own bottom edge`);
+ } else assert.deepEqual(start, [parent.x + parent.width, parent.y + parent.height / 2]);
+ assert.deepEqual(end, down && !child.stacked ? [child.x + child.width / 2, child.y] : [child.x, child.y + child.height / 2]);
+ }
+ });
+}
+
+test('tree: an unbalanced tree places a parent over its own children only', () => {
+ const report = layoutOf(small);
+ const byId = new Map(report.nodes.map((node) => [node.id, node]));
+ const center = (node) => node.x + node.width / 2;
+ for (const parent of ['orders', 'payments', 'operations']) {
+ const children = report.nodes.filter((node) => node.parent === parent);
+ const expected = (center(children[0]) + center(children.at(-1))) / 2;
+ assert.ok(Math.abs(center(byId.get(parent)) - expected) <= 1, parent);
+ }
+});
+
+test('tree: three or more sibling leaves going down become one stacked list', () => {
+ const report = layoutOf(large);
+ const children = (id) => report.nodes.filter((node) => node.parent === id);
+ const scripts = children('scripts');
+ assert.ok(scripts.length >= 3 && scripts.every((node) => node.stacked));
+ // One column, one width, in authored order.
+ assert.equal(new Set(scripts.map((node) => node.x)).size, 1);
+ assert.equal(new Set(scripts.map((node) => node.width)).size, 1);
+ for (let index = 1; index < scripts.length; index += 1) assert.ok(scripts[index].y >= scripts[index - 1].y + scripts[index - 1].height);
+ // Two leaves and every branch stay in the row layout.
+ assert.ok(layoutOf(small).nodes.every((node) => !node.stacked));
+ assert.ok(!report.nodes.find((node) => node.id === 'r_shared').stacked);
+});
+
+test('tree: every descendant and link carries its ancestors, and toggles count what they hide', () => {
+ const result = run(small);
+ const html = fs.readFileSync(result.output, 'utf8');
+ assert.match(html, /data-node-id="card_payment"[^>]*data-tree-ancestors="payments platform"/);
+ assert.match(html, /data-edge-from="payments" data-edge-to="card_payment"[^>]*data-tree-ancestors="payments platform"/);
+ assert.match(html, /data-tree-toggle="platform" data-tree-count="9"/);
+ assert.match(html, /data-tree-toggle="payments" data-tree-count="2"[^>]*aria-expanded="true" aria-label="Collapse Payments \(2 below\)"/);
+ assert.doesNotMatch(html, /data-tree-toggle="card_payment"/);
+});
+
+test('tree: authored collapsed state is a Viewer default, not a removal from the SVG', () => {
+ const result = run(large);
+ const html = fs.readFileSync(result.output, 'utf8');
+ assert.match(html, /data-tree-toggle="viewer"[^>]*data-tree-initially-collapsed=""/);
+ assert.match(html, /data-node-id="v_tree"/);
+ assert.doesNotMatch(html.match(/<svg\b[\s\S]*?<\/svg>/)[0], /data-tree-hidden=""/);
+});
+
+test('tree: long labels wrap between words instead of overflowing', () => {
+ const diagram = clone(small);
+ diagram.nodes.find((node) => node.id === 'refunds').label = 'Refund handling for partially captured multi-currency orders';
+ const report = layoutOf(diagram);
+ const node = report.nodes.find((entry) => entry.id === 'refunds');
+ assert.ok(node.lines > 1);
+ assert.ok(node.width <= 220);
+});
+
+function failure(mutate) {
+ const diagram = clone(small);
+ mutate(diagram);
+ const result = run(diagram);
+ assert.notEqual(result.status, 0, 'renderer accepted an invalid tree');
+ return result.stderr;
+}
+
+test('tree: structural errors are refused instead of inventing a hierarchy', () => {
+ assert.match(failure((d) => { d.nodes[4].parent = 'missing'; }), /tree\/missing-parent/);
+ assert.match(failure((d) => { delete d.nodes[1].parent; }), /tree\/root-count/);
+ assert.match(failure((d) => { d.nodes[0].parent = 'orders'; }), /tree\/root-count/);
+ const cycle = failure((d) => {
+ d.nodes.find((node) => node.id === 'orders').parent = 'create_order';
+ });
+ assert.match(cycle, /tree\/cycle/);
+ assert.match(cycle, /"orders" -> "create_order" -> "orders"|"create_order" -> "orders" -> "create_order"/);
+ assert.match(failure((d) => { d.nodes[5].id = d.nodes[4].id; }), /tree\/duplicate-id/);
+});
diff --cc test/waterfall-rendering.test.mjs
index a167f0df,00000000..e70fe438
mode 100644,000000..100644
--- a/test/waterfall-rendering.test.mjs
+++ b/test/waterfall-rendering.test.mjs
@@@ -1,98 -1,0 +1,98 @@@
+import { test } from 'node:test';
+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 { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
- const skillRoot = path.resolve(__dirname, '..');
++const skillRoot = path.resolve(__dirname, '..', 'archify');
+const renderer = path.join(skillRoot, 'renderers', 'waterfall', 'render-waterfall.mjs');
+const checker = path.join(skillRoot, 'scripts', 'check-render-output.mjs');
+const small = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples', 'checkout-request.waterfall.json'), 'utf8'));
+const large = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples', 'example-rebuild.waterfall.json'), 'utf8'));
+const clone = (value) => JSON.parse(JSON.stringify(value));
+
+function run(diagram, extra = []) {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-waterfall-'));
+ const input = path.join(directory, 'candidate.waterfall.json');
+ const output = path.join(directory, 'candidate.html');
+ fs.writeFileSync(input, JSON.stringify(diagram));
+ return { ...spawnSync(process.execPath, [renderer, input, output, ...extra], { cwd: directory, encoding: 'utf8' }), output };
+}
+function layoutOf(diagram) {
+ const result = run(diagram, ['--layout-json']);
+ assert.equal(result.status, 0, result.stderr);
+ return JSON.parse(result.stdout);
+}
+
+test('waterfall: both examples render and pass the showcase artifact checks', () => {
+ for (const diagram of [small, large]) {
+ const result = run(diagram);
+ assert.equal(result.status, 0, result.stderr);
+ const receipt = JSON.parse(spawnSync(process.execPath, [checker, result.output], { encoding: 'utf8' }).stdout);
+ assert.equal(receipt.ok, true, JSON.stringify(receipt.checks.filter((entry) => !entry.ok)));
+ assert.equal(receipt.composition.summary.errors, 0);
+ }
+});
+
+test('waterfall: bar geometry is exactly the recorded timing on one axis', () => {
+ const report = layoutOf(small);
+ assert.equal(report.wall, 1200);
+ const x = (t) => report.axis.x0 + t * report.pxPerUnit;
+ for (const row of report.rows) {
+ const span = small.spans.find((candidate) => candidate.id === row.id);
+ const end = span.end ?? span.start + span.duration;
+ assert.ok(Math.abs(row.x0 - x(span.start)) < 0.01, `${row.id} start`);
+ assert.ok(Math.abs(row.x1 - x(end)) < 0.01, `${row.id} end`);
+ }
+ // Concurrent siblings overlap; the request bar spans the whole wall clock.
+ const rows = Object.fromEntries(report.rows.map((row) => [row.id, row]));
+ assert.ok(rows.discount.x0 === rows.inventory.x0 && rows.discount.x1 < rows.inventory.x1);
+ assert.equal(rows.request.x1 - rows.request.x0, report.axis.x1 - report.axis.x0);
+ // Children follow their parent, depth-first by start time.
+ assert.deepEqual(report.rows.map((row) => row.id), ['request', 'auth', 'inventory', 'discount', 'payment', 'save']);
+});
+
+test('waterfall: percentages name their denominator and are never summed into the parent', () => {
+ const html = fs.readFileSync(run(small).output, 'utf8');
+ assert.match(html, /data-node-id="payment"[^>]*aria-label="[^"]*400–1,050 ms · 650 ms · 54% of 1,200 ms wall-clock/);
+ assert.match(html, /data-waterfall-total="1200"[^>]*>Wall-clock 1,200 ms/);
+ assert.match(html, /data-waterfall-evidence="illustrative"/);
+});
+
+test('waterfall: a short operation keeps its duration label beside the bar', () => {
+ const diagram = clone(small);
+ diagram.spans.push({ id: 'cache', name: 'Read cache', start: 400, duration: 4, parent: 'payment' });
+ const row = layoutOf(diagram).rows.find((entry) => entry.id === 'cache');
+ assert.equal(row.label, '4 ms');
+ assert.notEqual(row.placement, 'inside');
+});
+
+test('waterfall: an incomplete span is an open lower bound, not a measured duration', () => {
+ const diagram = clone(small);
+ diagram.spans.push({ id: 'webhook', name: 'Await webhook', start: 1100, parent: 'request', status: 'incomplete' });
+ const report = layoutOf(diagram);
+ const row = report.rows.find((entry) => entry.id === 'webhook');
+ assert.equal(row.open, true);
+ assert.equal(row.end, report.wall);
+ assert.equal(row.label, 'incomplete, ≥ 100 ms');
+});
+
+function failure(mutate) {
+ const diagram = clone(small);
+ mutate(diagram);
+ const result = run(diagram);
+ assert.notEqual(result.status, 0, 'renderer accepted invalid timing');
+ return result.stderr;
+}
+
+test('waterfall: invalid timing and parent cycles are refused', () => {
+ assert.match(failure((d) => { d.spans[1].end = -5; delete d.spans[1].duration; }), /\/spans\/1\/end/);
+ assert.match(failure((d) => { d.spans[0].end = 900; d.spans[0].start = 1000; }), /waterfall\/invalid-timing/);
+ assert.match(failure((d) => { d.spans[1].end = 500; }), /disagree/);
+ assert.match(failure((d) => { delete d.spans[1].duration; }), /must be marked status "incomplete"/);
+ assert.match(failure((d) => { d.spans[1].parent = 'missing'; }), /waterfall\/missing-parent/);
+ assert.match(failure((d) => { d.spans[0].parent = 'auth'; }), /waterfall\/cycle/);
+});
diff --cc viewer/README.md
index a8e8477d,73402856..68804352
--- a/viewer/README.md
+++ b/viewer/README.md
@@@ -19,18 -18,7 +19,18 @@@ sources live outside the packaged `arch
From `archify/`, run `npm run generate:viewer` after editing any source.
`npm run check:viewer` verifies freshness without writing; `npm test` includes
-that check. Assembly inserts JavaScript fragments verbatim at fixed markers.
+that check. Shared Viewer changes also require rebuilding the checked-in
+Checkout comparison from its tracked snapshots. From the repository root, run:
+
+```sh
+node archify/bin/archify.mjs compare architecture archify/examples/checkout-platform.base.architecture.json archify/examples/checkout-platform.head.architecture.json examples/checkout-platform-delta.html --receipt examples/checkout-platform-delta.receipt.json --quality showcase --json
+```
+
- `archify/test/architecture-delta.test.mjs` verifies those artifact and receipt
++`test/architecture-delta.test.mjs` verifies those artifact and receipt
+bytes. Rebuild other affected examples and distribution outputs according to
+[Contributing](../CONTRIBUTING.md#packages-and-generated-artifacts).
+
+Assembly inserts JavaScript fragments verbatim at fixed markers.
The CSS fragment is authored at column zero and reindented four spaces when it
is inserted into the shell's `<style>` block; this preserves the delivered
template bytes while keeping the standalone source easy to edit.