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
Merge remote-tracking branch 'origin/pr441' into codex/pr396-dev-integration
tt-a1iffdc6a0094dd
diff --cc CHANGELOG.mdindex 3ada7edd,1b841d01..aca2631b--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -7,7 -7,11 +7,12 @@@ All notable changes are documented here> Development identity: `v2.17.0-dev.1`. Not a stable release.### Fixed+- **Readable renderer failures.** `render` and direct renderer entry points format classified input, schema, layout, and output failures without Node stacks. Filesystem failures identify the failing operation instead of labelling output errors as unreadable input; successful artifact bytes and existing validation/delivery receipt formats remain unchanged.+ - **Architecture Delta baseline arrowheads (#433).** Removed and rerouted baseline relationships retain their marker definitions in the composed Delta SVG, preserving their authored direction alongside current relationships.+ - **Compare rollback recovery (#438).** If restoring a previous output fails, compare preserves its recovery directory and reports backup-to-target paths instead of deleting the remaining backups during cleanup.+ - **固定提交的来源校验 (#420)。** 校验忽略本地 Git replacement refs,始终读取指定提交的原始对象,避免替换后的文件或行范围造成误接受或误拒绝;保留原有来源链接、诊断与用户 Git 配置。+ - **导出的独立 SVG 声明 UTF-8 编码。** 架构图「下载 SVG」和架构对比(compare)导出的 SVG 文档现在以 `<?xml version="1.0" encoding="UTF-8"?>` 声明开头;缺少声明时,部分消费方不按 XML 规范默认 UTF-8 而猜测编码,导致中文等非 ASCII 文本乱码。+ - **Compare 输入快照一致性 (#400)。** 原始输入校验使用首次读取的字节快照,使其与回执哈希和差异计算保持一致;读取后原文件发生变化不会影响本次比较,非法原始字段仍会被拒绝。- **DSH plugin refresh.** Adapter 0.2.0 pins the current Archify development snapshot, includes the newer runtime and CLI fixes, and targets DSH 0.1.2-rc.1. Release metadata replaces the frozen 0.1.0 packaging source; the tarball uses the canonical clean-Skill stager and documents independent plugin upgrades.- **Machine-readable CLI argument failures (#330).** `validate --json` and `deliver --json` now keep invalid or missing option values, unknown options and diagram types, unsupported option combinations, and usage errors inside one versioned failure receipt on stdout. These failures use the `arguments` stage, stable diagnostic codes, and exit status 2, while human-mode stderr behavior remains unchanged.- **Complete artifact-check receipts (#311).** The checker now lets stdout drain before exiting, so large JSON receipts remain complete through pipes. Validation, delivery, and architecture comparison retain their original success/failure status without truncated-JSON errors.diff --cc archify.zipindex e3b54cfd,3fea2e1b..66ce9fd5Binary files differdiff --cc archify/renderers/shared/cli.mjsindex 6ddd7954,11b25fdb..1d18d068--- a/archify/renderers/shared/cli.mjs+++ b/archify/renderers/shared/cli.mjs@@@ -17,34 -15,12 +15,37 @@@ const outputPathGuards = new Map()// 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'));+ let input;+ try {+ input = fs.readFileSync(inputPath, 'utf8');+ } catch (error) {+ if (!isFilesystemError(error)) throw error;+ const message = `Input could not be read: ${error.message}`;+ throwDiagnosticError(message, [{+ code: 'input/read', message,+ subject: { input: inputPath },+ evidence: { systemCode: error.code, reason: error.message },+ supportedFixes: ['provide one readable JSON input file'],+ }]);+ }+ let diagram;+ try {+ diagram = JSON.parse(input);+ } catch (error) {+ if (!(error instanceof SyntaxError)) throw error;+ const message = `Input JSON could not be parsed: ${error.message}`;+ throwDiagnosticError(message, [{+ code: 'input/json-parse', message,+ subject: { input: inputPath },+ evidence: { reason: error.message },+ supportedFixes: ['repair the JSON syntax and run validation again'],+ }]);+ }validateSchema(diagramType, diagram);validateGuidedViews(diagramType, diagram);validateRelationshipIds(diagramType, diagram);diff --cc archify/renderers/shared/diagnostics.mjsindex abc39d2b,5d74de7d..0b267363--- a/archify/renderers/shared/diagnostics.mjs+++ b/archify/renderers/shared/diagnostics.mjs@@@ -94,38 -111,21 +94,50 @@@ function rendererFailure(error)};}+// Match the public CLI's text format without making its standalone doctor+// bootstrap depend on this renderer runtime being present.+function formatDiagnostics(error, diagnostics = []) {+ if (!diagnostics.length) return error;+ return [+ error,+ ...diagnostics.map((entry) => {+ const fix = entry.supportedFixes?.length ? ` Fix: ${entry.supportedFixes.join('; ')}.` : '';+ return `[${entry.code}] ${entry.message}${fix}`;+ }),+ ].join('\n');+}++ const readerSignal = new Int32Array(new SharedArrayBuffer(4));++ function waitForReader() {+ // Sleep instead of spinning on EAGAIN. A retry budget looks like a safeguard+ // and behaves like a truncation gate: a spinning loop burns thousands of+ // attempts in a few milliseconds, so a reader that is merely slow to start+ // exhausts it and loses the tail of the receipt. Waiting costs nothing while+ // the reader catches up, and a reader that goes away raises EPIPE, which the+ // caller already treats as a real write failure.+ Atomics.wait(readerSignal, 0, 0, 1);+ }+export function installRendererDiagnosticBoundary() {- if (!DIAGNOSTIC_MODE || globalThis[boundaryKey]) return;+ if (globalThis[boundaryKey]) return;globalThis[boundaryKey] = true;+ if (!DIAGNOSTIC_MODE) {+ process.once('uncaughtException', (error) => {+ // Only errors classified at their operation boundary are author-facing.+ // Preserve Node's debugging information for unexpected implementation errors.+ if (!error?.archifyDiagnostics?.length) {+ // The once-listener is already removed. Rethrow outside the exception+ // handler so Node retains its normal stack and exit code (not code 7).+ process.nextTick(() => { throw error; });+ return;+ }+ const payload = `${formatDiagnostics(error.message, error.archifyDiagnostics)}\n`;+ process.stderr.once('error', () => process.exit(1));+ process.stderr.write(payload, () => process.exit(1));+ });+ return;+ }process.on('uncaughtException', (error) => {const payload = `${JSON.stringify(rendererFailure(error))}\n`;try {diff --cc archify/test/render-failure-diagnostics.test.mjsindex af6e2234,00000000..3cea378fmode 100644,000000..100644--- a/archify/test/render-failure-diagnostics.test.mjs+++ b/archify/test/render-failure-diagnostics.test.mjs@@@ -1,185 -1,0 +1,187 @@@+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';+import vm from 'node:vm';++const skillRoot = fileURLToPath(new URL('../', import.meta.url));+const cli = path.join(skillRoot, 'bin/archify.mjs');++const diagnosticModule = new URL('../renderers/shared/diagnostics.mjs', import.meta.url).href;++const installBoundary = `import { installRendererDiagnosticBoundary } from ${JSON.stringify(diagnosticModule)}; installRendererDiagnosticBoundary();`;+const examples = {+ architecture: 'web-app.architecture.json',+ workflow: 'agent-tool-call.workflow.json',+ sequence: 'cache-miss-request.sequence.json',+ dataflow: 'product-analytics.dataflow.json',+ lifecycle: 'agent-run.lifecycle.json',+};++function workspace(t) {+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-render-diagnostics-'));+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));+ return directory;+}++function run(args, cwd, json = false) {+ return spawnSync(process.execPath, args, {+ cwd,+ encoding: 'utf8',+ env: { ...process.env, ARCHIFY_DIAGNOSTIC_FORMAT: json ? 'json' : '' },+ });+}++function assertHumanFailure(result, code) {+ assert.equal(result.status, 1, result.stdout || result.stderr);+ assert.equal(result.stdout, '');+ assert.ok(result.stderr.includes(`[${code}]`), result.stderr);+ assert.doesNotMatch(result.stderr, /\n\s+at\s|file:\/\/|Node\.js v/);+}++for (const [type, example] of Object.entries(examples)) {+ test(`render ${type}: input read/parse and output failures name the failing operation`, t => {+ const cwd = workspace(t);+ const input = path.join(skillRoot, 'examples', example);+ const output = path.join(cwd, 'diagram.html');+ const missing = run([cli, 'render', type, path.join(cwd, 'missing.json'), output], cwd);+ assertHumanFailure(missing, 'input/read');+ assert.match(missing.stderr, /Fix: provide one readable JSON input file/);++ const malformed = path.join(cwd, 'malformed.json');+ fs.writeFileSync(malformed, '{"broken":');+ assertHumanFailure(run([cli, 'render', type, malformed, output], cwd), 'input/json-parse');+ assert.equal(fs.existsSync(output), false);++ // Directory targets fail on both POSIX and Windows without relying on+ // permission bits (which a privileged test process may bypass).+ fs.mkdirSync(output);+ assertHumanFailure(run([cli, 'render', type, input, output], cwd), 'output/write');+ const renderer = path.join(skillRoot, 'renderers', type, `render-${type}.mjs`);+ const machine = run([renderer, input, output], cwd, true);+ assert.equal(machine.status, 1);+ assert.equal(machine.stdout, '');+ const failure = JSON.parse(machine.stderr);+ assert.equal(failure.diagnostics[0].code, 'output/write');+ assert.deepEqual(failure.diagnostics[0].subject, { output });+ assert.ok(failure.diagnostics[0].evidence.systemCode);+ assert.ok(failure.diagnostics[0].supportedFixes.length);+ assert.deepEqual(fs.readdirSync(output), []);++ const blockedParent = path.join(cwd, 'parent');+ fs.writeFileSync(blockedParent, 'preserved');+ assertHumanFailure(run([renderer, input, path.join(blockedParent, 'diagram.html')], cwd), 'output/write');+ assert.equal(fs.readFileSync(blockedParent, 'utf8'), 'preserved');+ });++ test(`render ${type}: successful direct and public rendering retain the output contract`, t => {+ const cwd = workspace(t);+ const input = path.join(skillRoot, 'examples', example);+ const output = path.join(cwd, 'diagram.html');+ const publicResult = run([cli, 'render', type, input, output], cwd);+ assert.equal(publicResult.status, 0, publicResult.stderr);+ assert.equal(publicResult.stdout, `${output}\n`);+ assert.equal(publicResult.stderr, '');+ const bytes = fs.readFileSync(output);+ const directResult = run([path.join(skillRoot, 'renderers', type, `render-${type}.mjs`), input, output], cwd);+ assert.equal(directResult.status, 0, directResult.stderr);+ assert.equal(directResult.stdout, `${output}\n`);+ assert.equal(directResult.stderr, '');+ assert.deepEqual(fs.readFileSync(output), bytes);+ });+}++test('render layout rejection exposes the existing diagnostic and preserves an existing artifact', t => {+ const cwd = workspace(t);+ const input = path.join(cwd, 'layout.json');+ const output = path.join(cwd, 'diagram.html');+ fs.writeFileSync(input, JSON.stringify({+ schema_version: 1,+ diagram_type: 'architecture',+ meta: { title: 'Wide label', quality_profile: 'standard', viewBox: [975, 395] },+ components: [{ id: 'node', type: 'security', label: '字'.repeat(40), pos: [40, 40], size: [88, 71] }],+ }));+ fs.writeFileSync(output, 'trusted artifact');+ const result = run([cli, 'render', 'architecture', input, output], cwd);+ assertHumanFailure(result, 'layout/constraint');+ assert.match(result.stderr, /shorten the label or widen size/);+ assert.equal(fs.readFileSync(output, 'utf8'), 'trusted artifact');+ for (const command of ['validate', 'deliver']) {+ const machine = run([cli, command, 'architecture', input, ...(command === 'deliver' ? [output] : []), '--json'], cwd);+ assert.equal(machine.status, 1);+ assert.equal(machine.stderr, '');+ const failure = JSON.parse(machine.stdout);+ assert.equal(failure.diagnostics[0].code, 'layout/constraint');+ assert.deepEqual(failure.diagnostics[0].subject, { diagramType: 'architecture' });+ }+ assert.equal(fs.readFileSync(output, 'utf8'), 'trusted artifact');+});++test('unexpected renderer exceptions keep native debugging information and are not relabelled as input errors', t => {+ const cwd = workspace(t);+ const helper = new URL('../renderers/shared/cli.mjs', import.meta.url).href;- const script = `import ${JSON.stringify(helper)}; throw Object.assign(new SyntaxError('implementation defect'), { code: 'EACCES' });`;++ const script = `${installBoundary} import ${JSON.stringify(helper)}; throw Object.assign(new SyntaxError('implementation defect'), { code: 'EACCES' });`;+ const human = run(['--input-type=module', '-e', script], cwd);+ assert.equal(human.status, 1);+ assert.match(human.stderr, /SyntaxError: implementation defect/);+ assert.match(human.stderr, /\n\s+at\s/);+ const machine = run(['--input-type=module', '-e', script], cwd, true);+ assert.equal(machine.status, 1);+ assert.equal(JSON.parse(machine.stderr).diagnostics[0].code, 'internal/unclassified');+});++test('a recorded layout diagnostic cannot hide a later unclassified exception', t => {+ const cwd = workspace(t);+ const helper = new URL('../renderers/shared/diagnostics.mjs', import.meta.url).href;+ const setup = `import { installRendererDiagnosticBoundary, recordDiagnostic, throwDiagnosticError } from ${JSON.stringify(helper)};+ installRendererDiagnosticBoundary();+ recordDiagnostic({ code: 'layout/constraint', message: 'earlier layout problem' });`;+ for (const failure of [+ `throw new TypeError('later implementation defect');`,+ `throwDiagnosticError('later implementation defect', []);`,+ ]) {+ const result = run(['--input-type=module', '-e', setup + failure], cwd, true);+ assert.equal(result.status, 1);+ const receipt = JSON.parse(result.stderr);+ assert.deepEqual(receipt.diagnostics.map(d => d.code), ['internal/unclassified']);+ assert.equal(receipt.diagnostics[0].message, 'later implementation defect');+ }+ const classified = run(['--input-type=module', '-e', setup + `throwDiagnosticError('layout rejected', [{ code: 'layout/constraint', message: 'final layout problem' }]);`], cwd, true);+ assert.equal(classified.status, 1);+ assert.deepEqual(JSON.parse(classified.stderr).diagnostics.map(d => d.message), ['earlier layout problem', 'final layout problem']);+});++test('invalid output arguments keep their implementation error instead of a filesystem repair', t => {+ const cwd = workspace(t);+ const helper = new URL('../renderers/shared/cli.mjs', import.meta.url).href;+ const templatePath = path.join(skillRoot, 'assets/template.html');- const script = `import fs from 'node:fs'; import { writeDiagram } from ${JSON.stringify(helper)};++ const script = `${installBoundary} import fs from 'node:fs'; import { writeDiagram } from ${JSON.stringify(helper)};+ writeDiagram({ outPath: undefined, template: fs.readFileSync(${JSON.stringify(templatePath)}, 'utf8'), diagramType: 'architecture', meta: { title: 'Test' }, svg: '', cards: [] });`;+ const human = run(['--input-type=module', '-e', script], cwd);+ assert.equal(human.status, 1);+ assert.match(human.stderr, /TypeError \[ERR_INVALID_ARG_TYPE\]/);+ assert.match(human.stderr, /\n\s+at\s/);+ assert.doesNotMatch(human.stderr, /output\/write|choose a writable/);+ const machine = run(['--input-type=module', '-e', script], cwd, true);+ assert.equal(machine.status, 1);+ assert.equal(JSON.parse(machine.stderr).diagnostics[0].code, 'internal/unclassified');+});++test('renderer and standalone CLI format the same diagnostics consistently', () => {+ // Evaluate only the pure formatter: importing the CLI would run its command+ // dispatch, and sharing its renderer import would break incomplete-install doctor.+ const formatters = [cli, path.join(skillRoot, 'renderers/shared/diagnostics.mjs')].map(file => {+ const source = fs.readFileSync(file, 'utf8');+ const start = source.indexOf('function formatDiagnostics(');+ assert.notEqual(start, -1);+ const end = source.indexOf('\n}', start) + 2;+ return vm.runInNewContext(`(${source.slice(start, end)})`);+ });+ for (const diagnostics of [[], [+ { code: 'layout/constraint', message: '标签过宽', supportedFixes: ['widen size', 'shorten label'] },+ { code: 'internal/unclassified', message: 'No repair available' },+ ]]) {+ assert.equal(formatters[0]('Render failed', diagnostics), formatters[1]('Render failed', diagnostics));+ }+});