Skip to content

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

fix(compare): validate captured input snapshots (#404)

逺坂凛30fd4632b41e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bd03a391..9fd3fb91 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@ All notable changes are documented here. Format loosely follows [Keep a Changelo
> Development identity: `v2.17.0-dev.1`. Not a stable release.
### Fixed
+- **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 --git a/archify.zip b/archify.zip
index 5902a52a..a44866db 100644
Binary files a/archify.zip and b/archify.zip differ
diff --git a/archify/bin/archify.mjs b/archify/bin/archify.mjs
index 5828c43f..07ad91ba 100755
--- a/archify/bin/archify.mjs
+++ b/archify/bin/archify.mjs
@@ -576,6 +576,8 @@ async function commandCompare(args) {
const headCandidate = path.join(stagingDirectory, 'head.html');
const rawBaseCandidate = path.join(stagingDirectory, 'base.raw.html');
const rawHeadCandidate = path.join(stagingDirectory, 'head.raw.html');
+ const rawBaseInput = path.join(stagingDirectory, 'base.snapshot.json');
+ const rawHeadInput = path.join(stagingDirectory, 'head.snapshot.json');
const canonicalBaseInput = path.join(stagingDirectory, 'base.architecture.json');
const canonicalHeadInput = path.join(stagingDirectory, 'head.architecture.json');
const htmlCandidate = path.join(stagingDirectory, path.basename(outputPath));
@@ -584,8 +586,31 @@ async function commandCompare(args) {
try {
let baseResult;
let headResult;
+ for (const { side, snapshotPath, buffer } of [
+ { side: 'base', snapshotPath: rawBaseInput, buffer: baseBuffer },
+ { side: 'head', snapshotPath: rawHeadInput, buffer: headBuffer },
+ ]) {
+ try {
+ fs.writeFileSync(snapshotPath, buffer, { flag: 'wx' });
+ } catch (error) {
+ const message = `Could not freeze ${side} compare snapshot: ${error.message}`;
+ reportCompareFailure({
+ json: options.json,
+ stage: 'prepare',
+ error: message,
+ code: 'delta/freeze-snapshot',
+ details: {
+ side,
+ ...(error?.code ? { systemCode: error.code } : {}),
+ reason: error.message,
+ supportedFixes: ['choose a writable compare output directory on the target filesystem'],
+ },
+ });
+ return;
+ }
+ }
try {
- renderValidatedArchitecture(basePath, rawBaseCandidate, qualityArgs.quality, repoArgs.repoRoot);
+ renderValidatedArchitecture(rawBaseInput, rawBaseCandidate, qualityArgs.quality, repoArgs.repoRoot);
} catch (error) {
const diagnosticEntry = error.diagnostics?.[0];
reportCompareFailure({
@@ -599,7 +624,7 @@ async function commandCompare(args) {
return;
}
try {
- renderValidatedArchitecture(headPath, rawHeadCandidate, qualityArgs.quality, repoArgs.repoRoot);
+ renderValidatedArchitecture(rawHeadInput, rawHeadCandidate, qualityArgs.quality, repoArgs.repoRoot);
} catch (error) {
const diagnosticEntry = error.diagnostics?.[0];
reportCompareFailure({
diff --git a/archify/scripts/check-render-output.mjs b/archify/scripts/check-render-output.mjs
index d59a69f4..f7149687 100644
--- a/archify/scripts/check-render-output.mjs
+++ b/archify/scripts/check-render-output.mjs
@@ -855,8 +855,8 @@ function collectNonFiniteAttrs(svg) {
continue;
}
const parent = stack[stack.length - 1];
- const inSvg = element === 'svg' || !parent
- || (parent.inSvg && !SVG_HTML_INTEGRATION_POINTS.has(parent.element));
+ const inSvg = element === 'svg'
+ || Boolean(parent?.inSvg && !SVG_HTML_INTEGRATION_POINTS.has(parent.element));
if (inSvg) {
for (const [name, value] of attrEntries(match[0])) {
if (!isNumericAttr(element, name) || !NON_FINITE_TOKEN.test(decodeNumericReferences(value))) continue;
diff --git a/archify/test/architecture-delta.test.mjs b/archify/test/architecture-delta.test.mjs
index 7f35bca3..cf7cf255 100644
--- a/archify/test/architecture-delta.test.mjs
+++ b/archify/test/architecture-delta.test.mjs
@@ -5,6 +5,7 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
+import { createHash } from 'node:crypto';
import {
ArchitectureDeltaError,
architectureDeltaChangeRows,
@@ -593,3 +594,101 @@ test('compare commit preflights both targets before replacing a trusted pair', (
assert.equal(failure.diagnostics[0].code, 'delta/commit-target');
assert.equal(failure.diagnostics[0].evidence.targetType, 'directory');
});
+
+for (const side of ['base', 'head']) {
+ for (const initiallyValid of [true, false]) {
+ test(`compare validates captured ${side} bytes when the original becomes ${initiallyValid ? 'invalid' : 'valid'}`, () => {
+ const caseRoot = fs.mkdtempSync(path.join(tmp, 'snapshot-'));
+ const input = path.join(caseRoot, `${side}.json`);
+ const output = path.join(caseRoot, 'delta.html');
+ const receiptPath = path.join(caseRoot, 'delta.receipt.json');
+ const valid = read(side === 'base' ? baseFixture : headFixture);
+ const invalid = { ...valid, unknown_top_level_fact: true };
+ const captured = Buffer.from(JSON.stringify(initiallyValid ? valid : invalid));
+ const replacement = JSON.stringify(initiallyValid ? invalid : valid);
+ fs.writeFileSync(input, captured);
+ fs.writeFileSync(output, 'trusted html');
+ fs.writeFileSync(receiptPath, 'trusted receipt');
+ const preload = path.join(caseRoot, 'replace-after-read.cjs');
+ // 在首次读取返回时替换原文件,避免依赖定时竞争或平台专用 FIFO。
+ fs.writeFileSync(preload, `
+ const fs = require('node:fs');
+ const originalRead = fs.readFileSync;
+ fs.readFileSync = function(file, ...args) {
+ const bytes = originalRead.call(this, file, ...args);
+ if (file === ${JSON.stringify(input)}) {
+ fs.readFileSync = originalRead;
+ fs.writeFileSync(file, ${JSON.stringify(replacement)});
+ }
+ return bytes;
+ };
+ `);
+ const result = spawnSync(process.execPath, [
+ '--require', preload, cli, 'compare', 'architecture',
+ side === 'base' ? input : baseFixture,
+ side === 'head' ? input : headFixture, output, '--json',
+ ], { cwd: skillRoot, encoding: 'utf8', timeout: 30000 });
+ assert.ifError(result.error);
+ assert.equal(fs.readFileSync(input, 'utf8'), replacement);
+ const receipt = JSON.parse(result.stdout);
+ if (initiallyValid) {
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ assert.equal(receipt.ok, true);
+ assert.equal(receipt[side].rawSha256, createHash('sha256').update(captured).digest('hex'));
+ assert.equal(receipt[side].bytes, captured.byteLength);
+ assert.deepEqual(read(receiptPath), receipt);
+ } else {
+ assert.notEqual(result.status, 0);
+ assert.equal(receipt.ok, false);
+ assert.equal(receipt.diagnostics[0].code, 'schema/additionalProperties');
+ assert.equal(receipt.diagnostics[0].subject.side, side);
+ assert.equal(fs.readFileSync(output, 'utf8'), 'trusted html');
+ assert.equal(fs.readFileSync(receiptPath, 'utf8'), 'trusted receipt');
+ }
+ assert.equal(fs.readdirSync(caseRoot).some(name => name.startsWith('.archify-compare-')), false);
+ });
+ }
+}
+
+for (const side of ['base', 'head']) {
+ test(`compare reports a ${side} snapshot write failure as a preparation error`, () => {
+ const caseRoot = fs.mkdtempSync(path.join(tmp, 'snapshot-write-'));
+ const output = path.join(caseRoot, 'delta.html');
+ const receiptPath = path.join(caseRoot, 'delta.receipt.json');
+ fs.writeFileSync(output, 'trusted html');
+ fs.writeFileSync(receiptPath, 'trusted receipt');
+ const preload = path.join(caseRoot, 'fail-snapshot-write.cjs');
+ fs.writeFileSync(preload, `
+ const fs = require('node:fs');
+ const originalWrite = fs.writeFileSync;
+ fs.writeFileSync = function(file, ...args) {
+ if (String(file).endsWith(${JSON.stringify(`${side}.snapshot.json`)})) {
+ const error = new Error('simulated snapshot write failure');
+ error.code = 'ENOSPC';
+ throw error;
+ }
+ return originalWrite.call(this, file, ...args);
+ };
+ `);
+
+ const result = spawnSync(process.execPath, [
+ '--require', preload, cli, 'compare', 'architecture',
+ baseFixture, headFixture, output, '--json',
+ ], { cwd: skillRoot, encoding: 'utf8', timeout: 30000 });
+
+ assert.ifError(result.error);
+ assert.notEqual(result.status, 0);
+ const failure = JSON.parse(result.stdout);
+ assert.equal(failure.stage, 'prepare');
+ assert.equal(failure.diagnostics[0].code, 'delta/freeze-snapshot');
+ assert.equal(failure.diagnostics[0].subject.side, side);
+ assert.equal(failure.diagnostics[0].evidence.systemCode, 'ENOSPC');
+ assert.match(failure.diagnostics[0].evidence.reason, /simulated snapshot write failure/);
+ assert.deepEqual(failure.diagnostics[0].supportedFixes, [
+ 'choose a writable compare output directory on the target filesystem',
+ ]);
+ assert.equal(fs.readFileSync(output, 'utf8'), 'trusted html');
+ assert.equal(fs.readFileSync(receiptPath, 'utf8'), 'trusted receipt');
+ assert.equal(fs.readdirSync(caseRoot).some(name => name.startsWith('.archify-compare-')), false);
+ });
+}
diff --git a/archify/test/render-output-checks.test.mjs b/archify/test/render-output-checks.test.mjs
index 55033122..7b02ba37 100644
--- a/archify/test/render-output-checks.test.mjs
+++ b/archify/test/render-output-checks.test.mjs
@@ -434,6 +434,19 @@ test('render output check: endpoint stubs from 8px pass while cramped interior t
process.on('exit', () => fs.rmSync(tmp, { recursive: true, force: true }));
+for (const position of ['before', 'after']) {
+ test(`render output check: finite_svg ignores HTML numeric attributes ${position} SVG`, () => {
+ const htmlPath = path.join(tmp, `finite-html-${position}.html`);
+ const html = '<div x="NaN" width="Infinity"><input width="NaN"><br></div>';
+ const svg = '<svg viewBox="0 0 240 160"><rect x="10" y="10" width="20" height="20"/></svg>';
+ fs.writeFileSync(htmlPath, `<!doctype html><html><body>${position === 'before' ? html + svg : svg + html}</body></html>`);
+ const result = JSON.parse(execFileSync('node', [checker, htmlPath], { encoding: 'utf8' }));
+ const check = result.checks.find(item => item.name === 'finite_svg');
+ assert.equal(check.ok, true);
+ assert.deepEqual(check.details, []);
+ });
+}
+
test('render output check: finite_svg ignores comments and CDATA but still checks real elements', () => {
const { result } = checkHtml('finite-non-elements', `
<!-- <rect x="NaN"/> -->
diff --git a/docs/authoring-cookbook.zh-CN.md b/docs/authoring-cookbook.zh-CN.md
index c9969c13..f9a24988 100644
--- a/docs/authoring-cookbook.zh-CN.md
+++ b/docs/authoring-cookbook.zh-CN.md
@@ -95,6 +95,8 @@ node bin/archify.mjs compare architecture base.json head.json \
architecture-delta.html --quality showcase --json
```
+`compare` 首次读取两份输入后,会使用捕获的原始字节进行校验、计算回执哈希并生成差异;之后原文件的变化不会影响本次比较。非法原始字段仍会在规范化之前被拒绝。
+
## 6. 检查最终文件
确定性校验不会在真实浏览器中运行 Viewer。如果环境有 Chrome 或 Chromium,请对刚刚交付的 HTML 收集自动化浏览器证据: