Skip to content

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

fix(renderer): isolate compiler imports from CLI diagnostics

Wang Zhenhuan72deba7f3f49
diff --git a/archify.zip b/archify.zip
index a44866db..bbd10522 100644
Binary files a/archify.zip and b/archify.zip differ
diff --git a/archify/renderers/shared/cli.mjs b/archify/renderers/shared/cli.mjs
index 32f66726..df7ee65d 100644
--- a/archify/renderers/shared/cli.mjs
+++ b/archify/renderers/shared/cli.mjs
@@ -9,14 +9,15 @@ import { resolveOutputPath } from './output-path.mjs';
import { prepareDiagramBrandMarks } from './brand-marks.mjs';
import { resolveLocale, translateMessage } from './i18n.mjs';
-installRendererDiagnosticBoundary();
-
const outputPathGuards = new Map();
// Common CLI head: node render-<type>.mjs [input.json] [output.html]
// Keep this synchronous because callers also use it to establish the guarded
// output path before testing a last-moment filesystem alias change.
export function loadDiagram({ rendererDir, diagramType, defaultExample, argv = process.argv }) {
+ // Compilers also import this module for SVG helpers. Only CLI execution
+ // should install a process-level handler, before reading or validating input.
+ installRendererDiagnosticBoundary();
const skillRoot = path.resolve(rendererDir, '../..');
const inputPath = path.resolve(argv[2] || path.join(skillRoot, 'examples', defaultExample));
const diagram = JSON.parse(fs.readFileSync(inputPath, 'utf8'));
diff --git a/archify/test/renderer-import-isolation.test.mjs b/archify/test/renderer-import-isolation.test.mjs
new file mode 100644
index 00000000..904e4c43
--- /dev/null
+++ b/archify/test/renderer-import-isolation.test.mjs
@@ -0,0 +1,99 @@
+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 compilerUrl = new URL('../renderers/workflow/workflow-compiler.mjs', import.meta.url).href;
+const skillRoot = fileURLToPath(new URL('../', import.meta.url));
+
+function workspace(t) {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-import-isolation-'));
+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
+ return directory;
+}
+
+function run(args, cwd, format) {
+ const env = { ...process.env, ARCHIFY_DIAGNOSTIC_FORMAT: format === 'json' ? 'json' : '' };
+ delete env.ARCHIFY_QUALITY_PROFILE;
+ return spawnSync(process.execPath, args, { cwd, env, encoding: 'utf8', timeout: 15000 });
+}
+
+for (const format of ['human', 'json']) {
+ test(`workflow compiler import preserves host state outside the repository (${format})`, t => {
+ const cwd = workspace(t);
+ const script = `
+ import assert from 'node:assert/strict';
+ const events = ['uncaughtException', 'unhandledRejection'];
+ for (const event of events) process.on(event, () => {});
+ const listeners = events.map(event => process.rawListeners(event));
+ const argv = [...process.argv];
+ const env = { ...process.env };
+ process.exitCode = 23;
+ await import(process.argv[1]);
+ for (const [index, event] of events.entries()) {
+ assert.deepEqual(process.rawListeners(event), listeners[index], event);
+ }
+ assert.deepEqual(process.argv, argv);
+ assert.deepEqual({ ...process.env }, env);
+ assert.equal(process.exitCode, 23);
+ process.stdout.write('import complete');
+ `;
+ const child = run(['--input-type=module', '--eval', script, compilerUrl], cwd, format);
+ assert.equal(child.status, 23, child.stderr || child.error?.message);
+ assert.equal(child.stdout, 'import complete');
+ assert.equal(child.stderr, '');
+ assert.deepEqual(fs.readdirSync(cwd), []);
+ });
+
+ test(`failed workflow compilation leaves a later exception to the host (${format})`, t => {
+ const cwd = workspace(t);
+ const script = `
+ import assert from 'node:assert/strict';
+ process.once('uncaughtException', error => {
+ process.stdout.write(error.message);
+ process.exitCode = 23;
+ });
+ const { compileWorkflow } = await import(process.argv[1]);
+ const result = compileWorkflow({ workflow: {} });
+ assert.equal(result.ok, false);
+ assert.ok(result.diagnostics.length > 0);
+ setImmediate(() => { throw new Error('host-owned failure'); });
+ `;
+ const child = run(['--input-type=module', '--eval', script, compilerUrl], cwd, format);
+ assert.equal(child.status, 23, child.stderr || child.error?.message);
+ assert.equal(child.stdout, 'host-owned failure');
+ assert.equal(child.stderr, '');
+ assert.deepEqual(fs.readdirSync(cwd), []);
+ });
+}
+
+// All five entrypoints use the shared loader. Moving its diagnostic boundary
+// must still classify failures that happen before a diagram can be compiled.
+for (const type of ['architecture', 'workflow', 'sequence', 'dataflow', 'lifecycle']) {
+ test(`${type} CLI installs JSON diagnostics before reading and validating input`, t => {
+ const cwd = workspace(t);
+ const output = path.join(cwd, 'diagram.html');
+ fs.writeFileSync(output, 'previous artifact');
+ const renderer = path.join(skillRoot, 'renderers', type, `render-${type}.mjs`);
+ for (const [name, contents, code] of [
+ ['missing', null, 'input/read'],
+ ['malformed', '{"broken":', 'input/json-parse'],
+ ['schema', '{}', 'schema/required'],
+ ]) {
+ const input = path.join(cwd, `${name}.json`);
+ if (contents !== null) fs.writeFileSync(input, contents);
+ const child = run([renderer, input, output], cwd, 'json');
+ assert.equal(child.status, 1, child.stderr || child.error?.message);
+ assert.equal(child.stdout, '');
+ const receipt = JSON.parse(child.stderr);
+ assert.equal(receipt.ok, false);
+ assert.equal(receipt.source, 'renderer');
+ assert.ok(receipt.diagnostics.length > 0);
+ assert.ok(receipt.diagnostics.every(entry => entry.code === code), child.stderr);
+ assert.equal(fs.readFileSync(output, 'utf8'), 'previous artifact');
+ }
+ });
+}
diff --git a/archify/test/workflow-compiler-call-contract.test.mjs b/archify/test/workflow-compiler-call-contract.test.mjs
new file mode 100644
index 00000000..d0a6f318
--- /dev/null
+++ b/archify/test/workflow-compiler-call-contract.test.mjs
@@ -0,0 +1,82 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+
+import { compileWorkflow } from '../renderers/workflow/workflow-compiler.mjs';
+
+function workflow(version, locale = 'en') {
+ return {
+ schema_version: version,
+ diagram_type: 'workflow',
+ meta: { title: `Workflow ${version}`, locale, quality_profile: 'standard', legend: { mode: 'hidden' } },
+ lanes: [{ id: 'main', label: 'Main' }],
+ nodes: [
+ { id: 'a', lane: 'main', col: 0, type: 'frontend', label: 'Input' },
+ { id: 'b', lane: 'main', col: 3, type: 'backend', label: 'Output' },
+ ],
+ edges: [{ id: 'ab', from: 'a', to: 'b', label: 'request' }],
+ };
+}
+
+function deepFreeze(value) {
+ if (value && typeof value === 'object') {
+ for (const child of Object.values(value)) deepFreeze(child);
+ Object.freeze(value);
+ }
+ return value;
+}
+
+for (const version of [1, 2]) {
+ test(`workflow v${version}: A/B/A compilation preserves frozen inputs and earlier results`, () => {
+ const input = workflow(version);
+ const before = structuredClone(input);
+ deepFreeze(input);
+ const first = compileWorkflow({ workflow: input, qualityProfile: 'showcase' });
+ assert.equal(first.ok, true, JSON.stringify(first.diagnostics));
+ const snapshot = structuredClone(first);
+ deepFreeze(first);
+
+ const other = workflow(version === 1 ? 2 : 1, 'zh-CN');
+ other.meta.title = 'Another workflow';
+ other.nodes[1].col = 4;
+ const different = compileWorkflow({ workflow: deepFreeze(other), qualityProfile: 'standard' });
+ assert.equal(different.ok, true, JSON.stringify(different.diagnostics));
+ assert.notEqual(different.svg, first.svg);
+ assert.notEqual(different.receipt.contract, first.receipt.contract);
+ assert.match(different.svg, /lang="zh-CN"/);
+ assert.match(different.svg, /data-quality-profile="standard"/);
+
+ const repeated = compileWorkflow({ workflow: input, qualityProfile: 'showcase' });
+ assert.deepEqual(repeated, snapshot);
+ assert.deepEqual(first, snapshot);
+ assert.deepEqual(input, before);
+ assert.match(repeated.svg, /lang="en"/);
+ assert.match(repeated.svg, /data-quality-profile="showcase"/);
+ });
+
+ test(`workflow v${version}: failure/success calls retain independent result diagnostics`, () => {
+ const input = deepFreeze(workflow(version));
+ const expected = compileWorkflow({ workflow: input, qualityProfile: 'standard' });
+ assert.equal(expected.ok, true, JSON.stringify(expected.diagnostics));
+
+ const schemaFailure = compileWorkflow({ workflow: deepFreeze({}) });
+ assert.equal(schemaFailure.ok, false);
+ assert.ok(schemaFailure.diagnostics.length > 0);
+ assert.ok(schemaFailure.diagnostics.every(entry => entry.code === 'schema/required'));
+ assert.equal(schemaFailure.svg, undefined);
+ const snapshot = structuredClone(schemaFailure);
+ deepFreeze(schemaFailure);
+ assert.deepEqual(compileWorkflow({ workflow: input, qualityProfile: 'standard' }), expected);
+
+ const invalid = workflow(version);
+ invalid.semanticChecks = { requiredEdges: [{ from: 'b', to: 'a' }] };
+ const semanticFailure = compileWorkflow({ workflow: deepFreeze(invalid), qualityProfile: 'standard' });
+ assert.equal(semanticFailure.ok, false);
+ assert.deepEqual(semanticFailure.diagnostics.map(entry => entry.code), ['workflow/required-edge']);
+ assert.deepEqual(semanticFailure.receipt.diagnostics, semanticFailure.diagnostics);
+ assert.equal(semanticFailure.svg, undefined);
+ assert.deepEqual(compileWorkflow({ workflow: input, qualityProfile: 'standard' }), expected);
+ assert.deepEqual(compileWorkflow({ workflow: {} }), snapshot);
+ assert.deepEqual(schemaFailure, snapshot);
+ assert.deepEqual(expected.receipt.diagnostics, []);
+ });
+}