Skip to content

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

fix(check): preserve SVG subpaths with bounded path parsing

To3akaRin41a77f67e663
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 57a23725..a464d5ef 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,10 @@ All notable changes are documented here. Format loosely follows [Keep a Changelo
## [Unreleased]
+### Fixed
+
+- **SVG 路径检查(#641)。** 统一解析关系线和结构边界的 `M/L/H/V/Q/Z` 路径,正确保留子路径与闭合语义;截断参数、非法数值和不支持的命令现在有限失败并给出定位诊断,避免检查挂起、漏检或虚构跨子路径线段。普通有效产物的 9 项检查保持不变。
+
## [3.0.1] — 2026-09-28
### Changed
diff --git a/archify/bin/archify.mjs b/archify/bin/archify.mjs
index fa2066d9..83ae7e50 100755
--- a/archify/bin/archify.mjs
+++ b/archify/bin/archify.mjs
@@ -2632,6 +2632,16 @@ function checkerDiagnostics(checker) {
}
for (const check of checker?.checks || []) {
if (check.ok || COMPOSITION_CHECKS.has(check.name)) continue;
+ if (check.name === 'svg_path_data') {
+ const pathDiagnostics = (checker.diagnostics || []).filter(item => (
+ item?.severity === 'error'
+ && ['artifact/svg-path-malformed', 'artifact/svg-path-unsupported'].includes(item.code)
+ ));
+ if (pathDiagnostics.length) {
+ diagnostics.push(...pathDiagnostics.map(item => diagnostic(item)));
+ continue;
+ }
+ }
diagnostics.push(diagnostic({
code: `artifact/${check.name.replaceAll('_', '-')}`,
message: (check.details || []).find(Boolean) || `Final artifact failed ${check.name}.`,
diff --git a/archify/references/delivery-contract.md b/archify/references/delivery-contract.md
index 1cde6441..f9350a84 100644
--- a/archify/references/delivery-contract.md
+++ b/archify/references/delivery-contract.md
@@ -336,6 +336,21 @@ recovery journal, or delivery lock makes every checker fail before accepting
the preserved HTML; report the diagnostics and complete a successful recovery
delivery before collecting new browser evidence.
+静态 `check` 对受检关系线和结构边界的 SVG 路径使用同一解析结果,支持
+`M/L/H/V/Q/Z` 及其小写相对形式、重复参数和有限数值。每个 `M` 开始独立
+子路径,`Z` 只闭合当前子路径;子路径之间不会被拼接成图中不存在的线段。
+线段长度和伸长率按连续子路径测量,真实转弯数汇总到原关系;超预算关系
+只计一次,内部子路径断点不享有语义起终点的短共享线例外。
+这不是完整 SVG 命令集的支持承诺:`A/C/S/T` 返回
+`artifact/svg-path-unsupported`;缺少参数、非法数值等格式错误返回
+`artifact/svg-path-malformed`,检查以非零状态结束,不跳过坏路径或无限等待。
+路径失败时追加 `svg_path_data` 检查;普通有效产物仍保留原来的 9 项检查。
+诊断携带受检路径的 `pathIndex`、`role`、可用的关系/边界 `id`,以及解析位置
+`tokenOffset`、可用的 `command` 和 `reason`,用于定位并修复生成路径的来源。
+`pathIndex` 从 1 开始;`tokenOffset` 是数字字符引用解码后的 `d` 字符串中
+从 0 开始的 UTF-16 位置。注释、CDATA 和属性文本中的伪标签不参与检查。
+静态路径检查通过仍不代表浏览器或感知视觉验收通过。
+
The delivery interface exposes four separate claims:
1. `deliver` proves deterministic artifact checks and byte identity.
diff --git a/archify/renderers/shared/geometry.mjs b/archify/renderers/shared/geometry.mjs
index cd8882c7..de191dbb 100644
--- a/archify/renderers/shared/geometry.mjs
+++ b/archify/renderers/shared/geometry.mjs
@@ -719,6 +719,8 @@ export function collectAmbiguousCorridors({
relation,
relationIndex: Number.isInteger(entry.relationIndex) ? entry.relationIndex : fallbackIndex,
points,
+ ...(entry.sourceEndpoint === false ? { sourceEndpoint: false } : {}),
+ ...(entry.targetEndpoint === false ? { targetEndpoint: false } : {}),
};
}).filter(Boolean);
const hits = [];
@@ -773,9 +775,11 @@ function shortWorkflowTrunk(left, right, leftSegment, rightSegment, length) {
const width = (edge) => edge.width || (variant(edge) === 'emphasis' ? 1.8 : 1.4);
if (variant(a) !== variant(b) || width(a) !== width(b) || (a.role || '') !== (b.role || '')) return false;
const same = (p, q) => Math.abs(p[0] - q[0]) < 0.0001 && Math.abs(p[1] - q[1]) < 0.0001;
- const source = a.from === b.from && leftSegment === 0 && rightSegment === 0
+ const source = left.sourceEndpoint !== false && right.sourceEndpoint !== false
+ && a.from === b.from && leftSegment === 0 && rightSegment === 0
&& same(left.points[0], right.points[0]);
- const target = a.to === b.to && leftSegment === left.points.length - 2 && rightSegment === right.points.length - 2
+ const target = left.targetEndpoint !== false && right.targetEndpoint !== false
+ && a.to === b.to && leftSegment === left.points.length - 2 && rightSegment === right.points.length - 2
&& same(left.points.at(-1), right.points.at(-1));
if (!source && !target) return false;
const p = left.points[leftSegment], q = left.points[leftSegment + 1];
diff --git a/archify/renderers/shared/svg-path-analysis.mjs b/archify/renderers/shared/svg-path-analysis.mjs
new file mode 100644
index 00000000..e77c2b69
--- /dev/null
+++ b/archify/renderers/shared/svg-path-analysis.mjs
@@ -0,0 +1,135 @@
+// 仅分析静态检查器需要的路径子集,不作为通用 SVG 渲染器。
+const NUMBER = /[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/y;
+const COMMANDS = /^[MLHVQZACSTmlhvqzacst]$/;
+const ARITY = { M: 2, L: 2, H: 1, V: 1, Q: 4 };
+
+function failure(tokenOffset, reason, command, unsupported = false) {
+ return { ok: false, error: {
+ code: unsupported ? 'artifact/svg-path-unsupported' : 'artifact/svg-path-malformed',
+ tokenOffset, reason, ...(command ? { command } : {}),
+ } };
+}
+
+function tokenize(source) {
+ const tokens = [];
+ let offset = 0;
+ let comma = null;
+ while (offset < source.length) {
+ const character = source[offset];
+ if (/[ \t\r\n]/.test(character)) { offset += 1; continue; }
+ if (character === ',') {
+ if (comma !== null || tokens.at(-1)?.kind !== 'number') return failure(offset, 'unexpected comma');
+ comma = offset++;
+ continue;
+ }
+ if (COMMANDS.test(character)) {
+ if (comma !== null) return failure(comma, 'a comma must separate numbers');
+ tokens.push({ kind: 'command', value: character, offset: offset++ });
+ continue;
+ }
+ NUMBER.lastIndex = offset;
+ const number = NUMBER.exec(source);
+ if (!number) return failure(offset, 'expected a number or supported path command');
+ const value = Number(number[0]);
+ if (!Number.isFinite(value)) return failure(offset, 'coordinate is not finite');
+ tokens.push({ kind: 'number', value, offset });
+ offset = NUMBER.lastIndex;
+ comma = null;
+ }
+ return comma === null ? { ok: true, tokens } : failure(comma, 'trailing comma');
+}
+
+/** 每步消费一个命令或完整参数组;失败不返回部分几何。偏移基于传入的 d 字符串。 */
+export function analyzeSvgPath(source) {
+ if (typeof source !== 'string') return failure(0, 'path data must be a string');
+ const lexed = tokenize(source);
+ if (!lexed.ok) return lexed;
+ const { tokens } = lexed;
+ const subpaths = [];
+ let index = 0;
+ let command = null;
+ let commandOffset = 0;
+ let current = [0, 0];
+ let subpath;
+
+ function move(point) {
+ current = point;
+ subpath = { points: [point], segments: [], straightSegments: [], closed: false };
+ subpaths.push(subpath);
+ }
+ function line(point) {
+ const segment = { start: current, end: point };
+ subpath.segments.push(segment);
+ subpath.straightSegments.push(segment);
+ subpath.points.push(point);
+ current = point;
+ }
+
+ while (index < tokens.length) {
+ if (tokens[index].kind === 'command') {
+ command = tokens[index].value;
+ commandOffset = tokens[index++].offset;
+ } else if (!command) {
+ return failure(tokens[index].offset, 'a command is required after closepath');
+ }
+ const upper = command.toUpperCase();
+ if (!subpath && upper !== 'M') return failure(commandOffset, 'the first command must be moveto', command);
+ if (!Object.hasOwn(ARITY, upper) && upper !== 'Z') {
+ return failure(commandOffset, 'path command is not supported by artifact analysis', command, true);
+ }
+ if (upper === 'Z') {
+ line(subpath.points[0]);
+ subpath.closed = true;
+ command = null;
+ continue;
+ }
+ const parameters = [];
+ const parameterOffset = tokens[index]?.offset ?? source.length;
+ for (let count = 0; count < ARITY[upper]; count += 1) {
+ const token = tokens[index];
+ if (!token || token.kind !== 'number') {
+ return failure(token?.offset ?? source.length, `command ${command} requires ${ARITY[upper]} parameters`, command);
+ }
+ parameters.push(token.value);
+ index += 1;
+ }
+ const relative = command !== upper;
+ const point = (x, y) => relative ? [current[0] + x, current[1] + y] : [x, y];
+ let end;
+ let control;
+ if (upper === 'H') end = [relative ? current[0] + parameters[0] : parameters[0], current[1]];
+ else if (upper === 'V') end = [current[0], relative ? current[1] + parameters[0] : parameters[0]];
+ else if (upper === 'Q') {
+ control = point(parameters[0], parameters[1]);
+ end = point(parameters[2], parameters[3]);
+ } else end = point(parameters[0], parameters[1]);
+ if (![...end, ...(control || [])].every(Number.isFinite)) {
+ return failure(parameterOffset, 'computed coordinate is not finite', command);
+ }
+ if (upper === 'M') {
+ move(end);
+ // moveto 后的额外参数组是 lineto,不能变成额外子路径。
+ command = relative ? 'l' : 'L';
+ continue;
+ }
+ if (subpath.closed) move(current);
+ if (upper !== 'Q') { line(end); continue; }
+
+ const start = current;
+ const cross = (control[0] - start[0]) * (end[1] - start[1]) - (control[1] - start[1]) * (end[0] - start[0]);
+ if (Math.abs(cross) <= 1e-9) subpath.straightSegments.push({ start, end });
+ // 保留既有八步 Q 采样;非共线曲线不冒充结构框的直线边界。
+ for (let step = 1; step <= 8; step += 1) {
+ const amount = step / 8;
+ const remaining = 1 - amount;
+ const next = [0, 1].map(axis => remaining * remaining * start[axis]
+ + 2 * remaining * amount * control[axis] + amount * amount * end[axis]);
+ if (!next.every(Number.isFinite)) return failure(parameterOffset, 'sampled coordinate is not finite', command);
+ subpath.segments.push({ start: current, end: next });
+ subpath.points.push(next);
+ current = next;
+ }
+ current = end;
+ }
+ return { ok: true, subpaths };
+}
diff --git a/archify/scripts/check-render-output.mjs b/archify/scripts/check-render-output.mjs
index ae6e741a..345a9133 100644
--- a/archify/scripts/check-render-output.mjs
+++ b/archify/scripts/check-render-output.mjs
@@ -1,9 +1,10 @@
#!/usr/bin/env node
import fs from 'node:fs';
+import { analyzeSvgPath } from '../renderers/shared/svg-path-analysis.mjs';
import { createHash } from 'node:crypto';
import path from 'node:path';
-import { collectAmbiguousCorridors, collectArrowheadCollisions, collectBorderRuns, collectLabelCanvasOverflow, collectLabelRouteClearance, collectRouteRhythmIssues, describeLabelCanvasOverflow, formatRect, forwardCollinearAnalysisSegments, minimumLabelRouteClearance, routeBudgetMetrics } from '../renderers/shared/geometry.mjs';
+import { collectAmbiguousCorridors, collectArrowheadCollisions, collectBorderRuns, collectLabelCanvasOverflow, collectLabelRouteClearance, collectRouteRhythmIssues, describeLabelCanvasOverflow, formatRect, forwardCollinearAnalysisSegments, minimumLabelRouteClearance, normalizeRoutePoints, routeBudgetMetrics } from '../renderers/shared/geometry.mjs';
import {
DESKTOP_READABILITY_VIEWPORT,
DESKTOP_READER_DIAGRAM_WIDTH,
@@ -39,6 +40,8 @@ try {
}
const checks = [];
+const pathDiagnostics = [];
+const pathAnalyses = new Map();
let composition = {
schemaVersion: 1,
profile: 'standard',
@@ -150,22 +153,23 @@ if (svgMatches.length === 1) {
frames: compositionFrames,
});
const routedRelationships = arrows
- .filter((arrow) => arrow.from && arrow.to && arrow.routePoints.length)
+ .filter((arrow) => arrow.from && arrow.to && arrow.routeSubpaths.some(points => points.length > 1))
.map((arrow) => ({ relation: arrow, relationIndex: arrow.index, points: arrow.routePoints }));
const nodeRects = svgAttrs.transform ? [] : collectUntransformedNodeRects(beforeLegend);
- const routeMetrics = routeBudgetMetrics({ routedRelations: routedRelationships });
+ const routeMetrics = subpathBudgetMetrics(routedRelationships);
// Architecture marks only one of its two Reader fits with its type.
const crowdedSides = svgAttrs['data-diagram-type'] === 'architecture' || svgAttrs['data-reader-primary-text'] === '14'
? crowdedNodeSides(arrows, nodeRects) : [];
- const routeRhythmIssues = collectRouteRhythmIssues({ routedRelations: routedRelationships });
- const ambiguousCorridors = collectAmbiguousCorridors({
+ const routeRhythmIssues = subpathRhythmIssues(routedRelationships);
+ const ambiguousCorridors = subpathCorridors({
routedRelations: routedRelationships,
includeSharedEndpoints: (left, right) => workflowV2 || (left.independentPorts && right.independentPorts),
allowShortWorkflowTrunks: workflowV2,
includeSharedEndpointCounterflow: (left, right) => left.automaticWorkflowRoute && right.automaticWorkflowRoute,
});
const arrowheadCollisions = collectArrowheadCollisions({
- routedRelations: routedRelationships.filter((entry) => workflowV2 || entry.relation.independentPorts),
+ routedRelations: routedRelationships.filter((entry) => workflowV2 || entry.relation.independentPorts)
+ .flatMap(entry => routeParts(entry).filter(part => part.targetEndpoint)),
allowShortWorkflowTrunks: workflowV2,
});
const relationshipLabels = collectRelationshipLabelMasks(beforeLegend, arrows);
@@ -175,12 +179,12 @@ if (svgMatches.length === 1) {
});
const sequenceColumnSpace = collectSequenceColumnSpace({ svgAttrs, fragment: beforeLegend, nodeRects, arrows });
const labelClearanceThreshold = qualityProfile === 'showcase' ? 4 : 2;
- const labelRouteMeasurements = collectLabelRouteClearance({
+ const labelRouteMeasurements = subpathLabelClearance({
labels: relationshipLabels,
routedRelations: arrows.map((arrow) => ({ relation: arrow, relationIndex: arrow.index, points: arrow.routePoints })),
threshold: Number.MAX_VALUE,
});
- const labelRouteClearance = collectLabelRouteClearance({
+ const labelRouteClearance = subpathLabelClearance({
labels: relationshipLabels,
routedRelations: arrows.map((arrow) => ({ relation: arrow, relationIndex: arrow.index, points: arrow.routePoints })),
threshold: labelClearanceThreshold,
@@ -254,7 +258,7 @@ if (svgMatches.length === 1) {
}),
...(crowdedSides.length ? { crowdedSides } : {}),
detours: routedRelationships.flatMap((entry) => {
- const metrics = routeBudgetMetrics({ routedRelations: [entry] });
+ const metrics = subpathBudgetMetrics([entry]);
const blockers = directCorridorBlockers(entry.relation, nodeRects);
return metrics.routesOverSuggestedBends || metrics.routesOverSuggestedStretch ? [{
relationship: relationshipRecord(entry.relation),
@@ -428,18 +432,26 @@ if (svgMatches.length === 1) {
}
}
+if (pathDiagnostics.length) addCheck('svg_path_data', false, pathDiagnostics.map(item => item.message));
+
const ok = checks.every((check) => check.ok) && composition.status !== 'fail';
-console.log(JSON.stringify({ ok, file: htmlPath, artifact, checks, composition }, null, 2));
+console.log(JSON.stringify({ ok, file: htmlPath, artifact, checks, composition,
+ ...(pathDiagnostics.length ? { diagnostics: pathDiagnostics } : {}),
+}, null, 2));
// Let pending stdout writes drain: large receipts are asynchronous when piped.
process.exitCode = ok ? 0 : 1;
function collectArrows(fragment, useActualPoints = false) {
const arrows = [];
let index = 0;
+ let pathIndex = 0;
let previousTag = null;
let previousTagEnd = 0;
- for (const tag of fragment.matchAll(/<(path|line)\b[^>]*>/gi)) {
+ for (const tag of fragment.matchAll(SVG_TAG_TOKEN)) {
+ const name = tag[2]?.toLowerCase();
+ if (tag[1] || !['path', 'line'].includes(name)) continue;
+ if (name === 'path') pathIndex += 1;
const tagStart = tag.index;
const raw = tag[0];
const gap = previousTag ? fragment.slice(previousTagEnd, tagStart) : '';
@@ -448,8 +460,8 @@ function collectArrows(fragment, useActualPoints = false) {
&& previousTag.name === 'path'
&& previousTag.underlayAttrs;
previousTag = {
- name: tag[1].toLowerCase(),
- underlayAttrs: tag[1].toLowerCase() === 'path' && AUTOMATIC_CROSSOVER_UNDERLAY_TAG.test(raw)
+ name: name,
+ underlayAttrs: name === 'path' && AUTOMATIC_CROSSOVER_UNDERLAY_TAG.test(raw)
? parseAttrs(raw)
: null,
};
@@ -467,14 +479,20 @@ function collectArrows(fragment, useActualPoints = false) {
&& Number.isFinite(routeStrokeWidth)
&& Number.isFinite(underlayStrokeWidth)
&& underlayStrokeWidth >= routeStrokeWidth + 3;
- const segments = tag[1].toLowerCase() === 'line'
- ? lineSegments(attrs)
- : pathSegments(attrs.d || '');
- const borderSegments = tag[1].toLowerCase() === 'line'
- ? segments
- : straightPathSegments(attrs.d || '');
+ const line = name === 'line';
+ const parsed = line ? null : inspectedPath(attrs, tag.index, pathIndex, 'relationship');
+ const segments = line ? lineSegments(attrs) : parsed.subpaths.flatMap(part => part.segments);
+ const borderSegments = line ? segments : parsed.subpaths.flatMap(part => part.straightSegments);
+ const pointsOf = parts => parts.length ? [parts[0].start, ...parts.map(segment => segment.end)] : [];
+ let routeSubpaths = line ? [pointsOf(segments)]
+ : parsed.subpaths.map(part => pointsOf(part.straightSegments));
+ // Legacy single-path metadata remains supported. It cannot bridge actual moveto boundaries.
+ if (!useActualPoints && (line || parsed.subpaths.length === 1)) {
+ const authoredPoints = parseRoutePoints(attrs['data-composition-points']);
+ if (authoredPoints) routeSubpaths = [authoredPoints];
+ }
arrows.push({
- kind: tag[1].toLowerCase(),
+ kind: name,
index: index += 1,
raw,
// Trust route intent only for a semantic edge with one visible direct
@@ -482,7 +500,7 @@ function collectArrows(fragment, useActualPoints = false) {
authoredStraight: attrs['data-composition-route'] === 'straight'
&& Boolean(attrs['data-edge-from'] && attrs['data-edge-to'])
&& segments.length === 1 && borderSegments.length === 1
- && (tag[1].toLowerCase() === 'line' || /^\s*M\s+[-+\d.eE]+\s+[-+\d.eE]+\s+L\s+[-+\d.eE]+\s+[-+\d.eE]+\s*$/.test(attrs.d || '')),
+ && (name === 'line' || /^\s*M\s+[-+\d.eE]+\s+[-+\d.eE]+\s+L\s+[-+\d.eE]+\s+[-+\d.eE]+\s*$/.test(attrs.d || '')),
crossoverHalo: verifiedCrossoverHalo,
independentPorts: verifiedCrossoverHalo && attrs['data-composition-independent'] === 'true',
// Compatibility with first-round exports lacking a root layout contract.
@@ -494,9 +512,8 @@ function collectArrows(fragment, useActualPoints = false) {
role: attrs['data-edge-role'],
segments,
borderSegments,
- routePoints: (!useActualPoints && parseRoutePoints(attrs['data-composition-points'])) || (
- borderSegments.length ? [borderSegments[0].start, ...borderSegments.map((segment) => segment.end)] : []
- ),
+ routePoints: routeSubpaths.length === 1 ? routeSubpaths[0] : [],
+ routeSubpaths,
from: attrs['data-edge-from'] || attrs['data-composition-edge-from'],
to: attrs['data-edge-to'] || attrs['data-composition-edge-to'],
id: attrs['data-edge-id'] || attrs['data-composition-edge-id'],
@@ -509,6 +526,123 @@ function collectArrows(fragment, useActualPoints = false) {
return arrows;
}
+function inspectedPath(attrs, offset, pathIndex, role) {
+ if (pathAnalyses.has(offset)) return pathAnalyses.get(offset);
+ const result = analyzeSvgPath(decodeNumericReferences(attrs.d || ''));
+ if (result.ok) {
+ pathAnalyses.set(offset, result);
+ return result;
+ }
+ const { code, ...evidence } = result.error;
+ const id = attrs.id || attrs['data-edge-id'] || attrs['data-composition-frame-id'];
+ pathDiagnostics.push({
+ code,
+ severity: 'error',
+ message: `${role} path ${pathIndex}${id ? ` (${id})` : ''}: ${evidence.reason} at d offset ${evidence.tokenOffset}.`,
+ subject: { role, pathIndex, ...(id ? { id } : {}) },
+ evidence,
+ supportedFixes: [code === 'artifact/svg-path-unsupported'
+ ? 'regenerate the inspected relationship or frame using M/L/H/V/Q/Z commands'
+ : 'correct the path data at the reported offset or regenerate it from the original diagram'],
+ });
+ const invalid = { ok: false, subpaths: [] };
+ pathAnalyses.set(offset, invalid);
+ return invalid;
+}
+
+// Keep relationship identity separate from its disconnected drawing pieces.
+// Normalizing each piece also makes evidence segment indices stable across consumers.
+function routeParts(entry) {
+ const subpaths = entry.relation.routeSubpaths || [entry.points];
+ let segmentOffset = 0;
+ return subpaths.flatMap((points, subpathIndex) => {
+ const normalized = normalizeRoutePoints(points);
+ const part = { ...entry, points: normalized, segmentOffset,
+ sourceEndpoint: subpathIndex === 0, targetEndpoint: subpathIndex === subpaths.length - 1 };
+ segmentOffset += Math.max(0, normalized.length - 1);
+ return normalized.length > 1 ? [part] : [];
+ });
+}
+
+function subpathBudgetMetrics(entries) {
+ if (entries.every(entry => entry.relation.routeSubpaths.length <= 1)) {
+ return routeBudgetMetrics({ routedRelations: entries });
+ }
+ const total = routeBudgetMetrics({ routedRelations: [] });
+ for (const entry of entries) {
+ const parts = routeParts(entry);
+ const metrics = routeBudgetMetrics({ routedRelations: parts });
+ metrics.maxBends = parts.reduce((sum, part) => sum + Math.max(0, part.points.length - 2), 0);
+ // A relationship may exceed a budget in several pieces; count its identity once.
+ metrics.routesOverSuggestedBends = Number(metrics.maxBends > 2);
+ metrics.routesOverSuggestedStretch = Number(metrics.routesOverSuggestedStretch > 0);
+ for (const [key, value] of Object.entries(metrics)) {
+ if (key.startsWith('max')) total[key] = value == null ? total[key] : Math.max(total[key] ?? value, value);
+ else if (key.startsWith('min')) total[key] = value == null ? total[key] : Math.min(total[key] ?? value, value);
+ else total[key] += value;
+ }
+ }
+ return total;
+}
+
+function subpathRhythmIssues(entries) {
+ return entries.flatMap(entry => routeParts(entry).flatMap(part => (
+ collectRouteRhythmIssues({ routedRelations: [part] }).map(issue => ({
+ ...issue, segmentIndex: issue.segmentIndex + part.segmentOffset,
+ }))
+ )));
+}
+
+function subpathCorridors({ routedRelations, ...options }) {
+ if (routedRelations.every(entry => entry.relation.routeSubpaths.length <= 1)) {
+ return collectAmbiguousCorridors({ routedRelations, ...options });
+ }
+ const hits = [];
+ const parts = routedRelations.map(routeParts);
+ for (let left = 0; left < parts.length; left += 1) {
+ for (let right = left + 1; right < parts.length; right += 1) {
+ let longest;
+ for (const a of parts[left]) for (const b of parts[right]) {
+ const hit = collectAmbiguousCorridors({ routedRelations: [a, b], ...options })[0];
+ if (hit && (!longest || hit.overlapLength > longest.overlapLength + 0.0001)) {
+ longest = { ...hit, leftSegment: hit.leftSegment + a.segmentOffset,
+ rightSegment: hit.rightSegment + b.segmentOffset };
+ }
+ }
+ if (longest) hits.push(longest);
+ }
+ }
+ return hits;
+}
+
+function subpathLabelClearance({ routedRelations, labels, threshold }) {
+ if (routedRelations.every(entry => entry.relation.routeSubpaths.length <= 1)) {
+ return collectLabelRouteClearance({ routedRelations, labels, threshold });
+ }
+ // The shared helper deduplicates by relationship identity. Measure each piece
+ // independently, then preserve one nearest hit per label/relationship pair.
+ const hits = [];
+ const seen = new Set();
+ for (const entry of routedRelations) {
+ const relation = entry.relation;
+ const identity = relation.key !== undefined ? `key:${relation.key}`
+ : relation.id ? `id:${relation.from || ''}\0${relation.to || ''}\0${relation.id}` : `index:${entry.relationIndex}`;
+ if (seen.has(identity) || !routeParts(entry).length) continue;
+ seen.add(identity);
+ const nearest = new Map();
+ for (const part of routeParts(entry)) {
+ for (const hit of collectLabelRouteClearance({ routedRelations: [part], labels, threshold })) {
+ const current = nearest.get(hit.labelRelationIndex);
+ if (!current || hit.clearance < current.clearance) nearest.set(hit.labelRelationIndex, {
+ ...hit, segmentIndex: hit.segmentIndex + part.segmentOffset,
+ });
+ }
+ }
+ hits.push(...nearest.values());
+ }
+ return hits;
+}
+
function collectRelationshipLabelMasks(fragment, arrows) {
const labels = [];
for (const match of fragment.matchAll(/<g\b[^>]*\bdata-edge-(?:key|id|from)="[^"]*"[^>]*>[\s\S]*?<\/g>/gi)) {
@@ -580,7 +714,7 @@ function collectRelationshipCrossings(arrows, includeSharedEndpoints = false) {
...arrow,
// Readable-v2 routePoints come from the visible path, never its metadata.
// A straight-through via is not a visual endpoint; preserve real bends.
- segments: includeSharedEndpoints ? forwardCollinearAnalysisSegments(arrow.routePoints) : arrow.segments,
+ segments: includeSharedEndpoints ? arrow.routeSubpaths.flatMap(forwardCollinearAnalysisSegments) : arrow.segments,
}));
const crossings = [];
for (let leftIndex = 0; leftIndex < relationships.length; leftIndex += 1) {
@@ -702,12 +836,16 @@ function relationshipRecord(arrow) {
function collectCompositionFrames(fragment) {
const frames = [];
- for (const match of fragment.matchAll(/<(rect|path|line)\b[^>]*>/gi)) {
+ let pathIndex = 0;
+ for (const match of fragment.matchAll(SVG_TAG_TOKEN)) {
+ const name = match[2]?.toLowerCase();
+ if (match[1] || !['rect', 'path', 'line'].includes(name)) continue;
+ if (name === 'path') pathIndex += 1;
const attrs = parseAttrs(match[0]);
const kind = attrs['data-composition-frame-kind'];
if (!kind) continue;
const identity = attrs['data-composition-frame-id'] || frames.length;
- if (match[1].toLowerCase() === 'rect') {
+ if (name === 'rect') {
const frame = {
kind,
id: identity,
@@ -720,9 +858,9 @@ function collectCompositionFrames(fragment) {
if ([frame.x, frame.y, frame.width, frame.height].every(Number.isFinite)) frames.push(frame);
continue;
}
- const segments = match[1].toLowerCase() === 'line'
+ const segments = name === 'line'
? lineSegments(attrs)
- : pathSegments(attrs.d || '');
+ : inspectedPath(attrs, match.index, pathIndex, 'structural-frame').subpaths.flatMap(part => part.segments);
for (const [segmentIndex, segment] of segments.entries()) {
frames.push({
kind,
@@ -751,7 +889,7 @@ function collectArchitectureLeadingSpace({ svgAttrs, fragment, nodeRects, frames
const nodeCount = [...fragment.matchAll(/<g\b[^>]*\bdata-node-id=/gi)].length;
if (!nodeRects.length || nodeRects.length !== nodeCount) return evidence;
const semanticArrows = arrows.filter((arrow) => arrow.from && arrow.to);
- if (semanticArrows.some((arrow) => !arrow.routePoints.length)) return evidence;
+ if (semanticArrows.some((arrow) => !arrow.routeSubpaths.some(points => points.length))) return evidence;
const occupied = nodeRects.map((node) => node.box[1]);
for (const frame of frames) {
@@ -768,7 +906,7 @@ function collectArchitectureLeadingSpace({ svgAttrs, fragment, nodeRects, frames
occupied.push(y);
}
for (const arrow of semanticArrows) {
- for (const point of arrow.routePoints) occupied.push(point[1]);
+ for (const points of arrow.routeSubpaths) for (const point of points) occupied.push(point[1]);
}
for (const label of labels) occupied.push(label.rect.y);
if (!occupied.every(Number.isFinite)) return evidence;
@@ -820,10 +958,10 @@ function collectSequenceColumnSpace({ svgAttrs, fragment, nodeRects, arrows }) {
const nodeCount = [...fragment.matchAll(/<g\b[^>]*\bdata-node-id=/gi)].length;
if (!nodeRects.length || nodeCount !== nodeRects.length) return evidence;
const semanticArrows = arrows.filter((arrow) => arrow.from && arrow.to);
- if (semanticArrows.some((arrow) => !arrow.routePoints.length)) return evidence;
+ if (semanticArrows.some((arrow) => !arrow.routeSubpaths.some(points => points.length))) return evidence;
const rightEdges = nodeRects.map((node) => node.box[0] + node.box[2]);
for (const arrow of semanticArrows) {
- for (const point of arrow.routePoints) rightEdges.push(point[0]);
+ for (const points of arrow.routeSubpaths) for (const point of points) rightEdges.push(point[0]);
}
// Label plates, activations and segment titles also reserve horizontal room.
for (const match of fragment.matchAll(/<rect\b[^>]*>/gi)) {
@@ -878,88 +1016,6 @@ function lineSegments(attrs) {
return [{ start, end }];
}
-function pathSegments(d) {
- const points = pointsFromPath(d);
- const segments = [];
- for (let i = 1; i < points.length; i += 1) {
- segments.push({ start: points[i - 1], end: points[i] });
- }
- return segments;
-}
-
-// Border runs use exact visible primitives. Non-collinear Q curves are never
-// flattened into chords here: a tangent or sampled near-horizontal curve is
-// not a structural border run. A fully collinear Q remains a straight visible
-// primitive and is included.
-function straightPathSegments(d) {
- const tokens = d.match(/[MLHVQZmlhvqz]|[-+]?(?:\d*\.)?\d+(?:e[-+]?\d+)?/g) || [];
- const segments = [];
- let i = 0;
- let command = '';
- let current = [0, 0];
- let start = null;
- while (i < tokens.length) {
- if (isCommand(tokens[i])) command = tokens[i++];
- if (!command) break;
- const absolute = command === command.toUpperCase();
- switch (command.toUpperCase()) {
- case 'M':
- case 'L': {
- let first = true;
- while (i + 1 < tokens.length && !isCommand(tokens[i])) {
- const point = [Number.parseFloat(tokens[i++]), Number.parseFloat(tokens[i++])];
- if (!point.every(Number.isFinite)) break;
- const next = absolute ? point : [current[0] + point[0], current[1] + point[1]];
- if (command.toUpperCase() === 'L' || !first) segments.push({ start: current, end: next });
- current = next;
- if (!start) start = current;
- first = false;
- }
- break;
- }
- case 'H': {
- while (i < tokens.length && !isCommand(tokens[i])) {
- const value = Number.parseFloat(tokens[i++]);
- if (!Number.isFinite(value)) break;
- const next = [absolute ? value : current[0] + value, current[1]];
- segments.push({ start: current, end: next });
- current = next;
- }
- break;
- }
- case 'V': {
- while (i < tokens.length && !isCommand(tokens[i])) {
- const value = Number.parseFloat(tokens[i++]);
- if (!Number.isFinite(value)) break;
- const next = [current[0], absolute ? value : current[1] + value];
- segments.push({ start: current, end: next });
- current = next;
- }
- break;
- }
- case 'Q': {
- while (i + 3 < tokens.length && !isCommand(tokens[i])) {
- const values = [0, 0, 0, 0].map(() => Number.parseFloat(tokens[i++]));
- if (!values.every(Number.isFinite)) break;
- const control = absolute ? values.slice(0, 2) : [current[0] + values[0], current[1] + values[1]];
- const end = absolute ? values.slice(2, 4) : [current[0] + values[2], current[1] + values[3]];
- if (Math.abs(crossProduct(current, control, end)) <= 1e-9) segments.push({ start: current, end });
- current = end;
- }
- break;
- }
- case 'Z':
- if (start) segments.push({ start: current, end: start });
- current = start || current;
- command = '';
- break;
- default:
- return [];
- }
- }
- return segments.filter(({ start: a, end: b }) => isPoint(a) && isPoint(b));
-}
-
function diagonalStraightSegments(arrow) {
if (arrow.authoredStraight) return [];
return arrow.borderSegments.flatMap(({ start, end }, segmentIndex) => (
@@ -1155,88 +1211,6 @@ function estimatedTextWidth(text, fontSize) {
return Math.max(fontSize, units * fontSize);
}
-function pointsFromPath(d) {
- const tokens = d.match(/[MLHVQZmlhvqz]|[-+]?(?:\d*\.)?\d+(?:e[-+]?\d+)?/g) || [];
- const points = [];
- let i = 0;
- let command = '';
- let current = [0, 0];
- let start = null;
-
- while (i < tokens.length) {
- if (isCommand(tokens[i])) command = tokens[i++];
- if (!command) break;
-
- const absolute = command === command.toUpperCase();
- switch (command.toUpperCase()) {
- case 'M':
- case 'L': {
- while (i + 1 < tokens.length && !isCommand(tokens[i])) {
- const x = Number.parseFloat(tokens[i++]);
- const y = Number.parseFloat(tokens[i++]);
- if (!Number.isFinite(x) || !Number.isFinite(y)) break;
- current = absolute ? [x, y] : [current[0] + x, current[1] + y];
- points.push(current);
- if (!start) start = current;
- }
- break;
- }
- case 'H': {
- while (i < tokens.length && !isCommand(tokens[i])) {
- const x = Number.parseFloat(tokens[i++]);
- if (!Number.isFinite(x)) break;
- current = absolute ? [x, current[1]] : [current[0] + x, current[1]];
- points.push(current);
- }
- break;
- }
- case 'V': {
- while (i < tokens.length && !isCommand(tokens[i])) {
- const y = Number.parseFloat(tokens[i++]);
- if (!Number.isFinite(y)) break;
- current = absolute ? [current[0], y] : [current[0], current[1] + y];
- points.push(current);
- }
- break;
- }
- case 'Q': {
- while (i + 3 < tokens.length && !isCommand(tokens[i])) {
- const controlX = Number.parseFloat(tokens[i++]);
- const controlY = Number.parseFloat(tokens[i++]);
- const endX = Number.parseFloat(tokens[i++]);
- const endY = Number.parseFloat(tokens[i++]);
- if (![controlX, controlY, endX, endY].every(Number.isFinite)) break;
- const control = absolute
- ? [controlX, controlY]
- : [current[0] + controlX, current[1] + controlY];
- const end = absolute
- ? [endX, endY]
- : [current[0] + endX, current[1] + endY];
- const startPoint = current;
- for (let step = 1; step <= 8; step += 1) {
- const amount = step / 8;
- const remaining = 1 - amount;
- points.push([
- remaining * remaining * startPoint[0] + 2 * remaining * amount * control[0] + amount * amount * end[0],
- remaining * remaining * startPoint[1] + 2 * remaining * amount * control[1] + amount * amount * end[1],
- ]);
- }
- current = end;
- }
- break;
- }
- case 'Z': {
- if (start) points.push(start);
- break;
- }
- default:
- return [];
- }
- }
-
- return points.filter(isPoint);
-}
-
function properSegmentIntersection(a, b, c, d) {
const abC = crossProduct(a, b, c);
const abD = crossProduct(a, b, d);
@@ -1375,10 +1349,6 @@ function numberAttr(attrs, name) {
return Number.parseFloat(attrs[name]);
}
-function isCommand(token) {
- return /^[A-Za-z]$/.test(token);
-}
-
function isPoint(point) {
return Array.isArray(point) && point.length === 2 && point.every(Number.isFinite);
}
diff --git a/archify/test/svg-path-analysis.test.mjs b/archify/test/svg-path-analysis.test.mjs
new file mode 100644
index 00000000..8224636d
--- /dev/null
+++ b/archify/test/svg-path-analysis.test.mjs
@@ -0,0 +1,90 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { analyzeSvgPath } from '../renderers/shared/svg-path-analysis.mjs';
+
+function parsed(source) {
+ const result = analyzeSvgPath(source);
+ assert.equal(result.ok, true, JSON.stringify(result));
+ return result.subpaths;
+}
+
+test('empty data and move-only subpaths do not invent drawing segments', () => {
+ assert.deepEqual(parsed(' \n\t'), []);
+ const [first, second] = parsed('M20 20 M100 100');
+ assert.deepEqual(first.points, [[20, 20]]);
+ assert.deepEqual(second.points, [[100, 100]]);
+ assert.deepEqual(first.segments, []);
+ assert.deepEqual(second.straightSegments, []);
+});
+
+test('a move starts a separate subpath while subsequent pairs draw implicit lines', () => {
+ const [first, second] = parsed('M20 20 100 20 M100 100 200 100');
+ assert.deepEqual(first.segments, [{ start: [20, 20], end: [100, 20] }]);
+ assert.deepEqual(second.segments, [{ start: [100, 100], end: [200, 100] }]);
+ assert.deepEqual(first.straightSegments, first.segments);
+});
+
+test('relative repetitions and closepath restore the current subpath origin', () => {
+ const [first, second] = parsed('m10 20 30 0 h20 v10 l-20 0 z m100 0 20 0');
+ assert.deepEqual(first.points, [[10, 20], [40, 20], [60, 20], [60, 30], [40, 30], [10, 20]]);
+ assert.equal(first.closed, true);
+ assert.deepEqual(second.points, [[110, 20], [130, 20]]);
+ assert.equal(second.closed, false);
+});
+
+test('each closepath uses its own most recent move and can be followed by drawing', () => {
+ const paths = parsed('M20 20 H100 V60 H20 Z M160 20 H240 V60 H160 Z l0 40');
+ assert.deepEqual(paths[0].segments.at(-1), { start: [20, 60], end: [20, 20] });
+ assert.deepEqual(paths[1].segments.at(-1), { start: [160, 60], end: [160, 20] });
+ assert.deepEqual(paths[2].segments, [{ start: [160, 20], end: [160, 60] }]);
+});
+
+test('legal number spellings preserve coordinates instead of dropping exponent letters', () => {
+ const absolute = parsed('M100 20 V100');
+ assert.deepEqual(parsed('M1e2 2e1 V1e2'), absolute);
+ assert.deepEqual(parsed('M1E2 2E1 V1E2'), absolute);
+ assert.deepEqual(parsed('M+1e+2,+2E+1 V100.'), absolute);
+ assert.deepEqual(parsed('M.5-.5 l.5.5')[0].points, [[0.5, -0.5], [1, 0]]);
+});
+
+test('quadratic sampling and exact collinear primitives retain their separate meanings', () => {
+ const [curve] = parsed('M0 0 Q10 0 10 10 L20 10');
+ assert.equal(curve.segments.length, 9);
+ assert.deepEqual(curve.points[4], [7.5, 2.5]);
+ assert.deepEqual(curve.straightSegments, [{ start: [10, 10], end: [20, 10] }]);
+ assert.deepEqual(parsed('M0 0 q10 0 10 10 l10 0')[0], curve);
+ assert.deepEqual(parsed('M0 0 Q10 0 20 0')[0].straightSegments, [{ start: [0, 0], end: [20, 0] }]);
+});
+
+for (const source of [
+ 'M20', 'M20 20 Q30 30 40', 'M20 20 L', 'M20 20 Q',
+ 'M20 20 L30 Z', 'M20 20 Q30 30 L40 40', 'M20 20 Z30 40',
+ 'L20 20', 'Z', 'M,20 20', 'M20,,20', 'M20 20,', 'M20 20,L30 30',
+ 'M20 20 R30 30', 'M20 NaN', 'M20 Infinity', 'M20 1e', 'M20 1e+',
+ 'M20 1e999', 'M1e308 0 l1e308 0', 'M20 20;L30 30', 'M20\u00a020',
+]) {
+ test(`malformed data terminates with a source offset: ${JSON.stringify(source)}`, () => {
+ const result = analyzeSvgPath(source);
+ assert.equal(result.ok, false);
+ assert.equal(result.error.code, 'artifact/svg-path-malformed');
+ assert.ok(Number.isInteger(result.error.tokenOffset));
+ assert.ok(result.error.tokenOffset >= 0 && result.error.tokenOffset <= source.length);
+ assert.equal(typeof result.error.reason, 'string');
+ assert.equal(result.subpaths, undefined, '不把部分解析当作可信几何返回');
+ });
+}
+
+test('missing parameters point to the incomplete group or interrupting command', () => {
+ assert.equal(analyzeSvgPath('M20').error.tokenOffset, 3);
+ assert.equal(analyzeSvgPath('M20 L30 30').error.tokenOffset, 4);
+});
+
+for (const command of ['A', 'a', 'C', 'c', 'S', 's', 'T', 't']) {
+ test(`recognized unsupported command ${command} is not silently reinterpreted`, () => {
+ const result = analyzeSvgPath(`M20 20 ${command} 30 30 40 40 0 50 50`);
+ assert.equal(result.ok, false);
+ assert.equal(result.error.code, 'artifact/svg-path-unsupported');
+ assert.equal(result.error.command, command);
+ assert.equal(result.error.tokenOffset, 7);
+ });
+}
diff --git a/archify/test/svg-path-checker.test.mjs b/archify/test/svg-path-checker.test.mjs
new file mode 100644
index 00000000..440d06cf
--- /dev/null
+++ b/archify/test/svg-path-checker.test.mjs
@@ -0,0 +1,338 @@
+import assert from 'node:assert/strict';
+import { spawn, spawnSync } from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import { after, test } from 'node:test';
+
+const skillRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const checker = path.join(skillRoot, 'scripts/check-render-output.mjs');
+const cli = path.join(skillRoot, 'bin/archify.mjs');
+const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-svg-path-checker-'));
+const deadlineMs = process.platform === 'win32' ? 10000 : 3000;
+let sequence = 0;
+after(() => fs.rmSync(scratch, { recursive: true, force: true }));
+
+// 公共 CLI 会再启动 checker;超时必须结束我们自己的整棵进程树。
+function killTree(child) {
+ if (!child.pid) return;
+ if (process.platform === 'win32') {
+ const result = spawnSync('taskkill', ['/pid', String(child.pid), '/t', '/f'], {
+ encoding: 'utf8', windowsHide: true, timeout: 5000,
+ });
+ if (result.error) throw result.error;
+ if (result.status !== 0 && child.exitCode === null) {
+ throw new Error(`taskkill failed: ${result.stderr || result.stdout}`);
+ }
+ } else {
+ try { process.kill(-child.pid, 'SIGKILL'); }
+ catch (error) { if (error.code !== 'ESRCH') throw error; }
+ }
+}
+
+async function check(t, body, { publicCli = false, rootAttrs = '', profile = 'showcase' } = {}) {
+ const file = path.join(scratch, `${sequence++}.html`);
+ fs.writeFileSync(file, `<!doctype html><html><body><svg viewBox="0 0 400 250" data-quality-profile="${profile}" ${rootAttrs}>${body}</svg></body></html>`);
+ const args = publicCli ? [cli, 'check', file, '--json'] : [checker, file];
+ return execute(t, args, body);
+}
+
+async function execute(t, args, description) {
+ const child = spawn(process.execPath, args, {
+ detached: process.platform !== 'win32',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ env: { ...process.env, ARCHIFY_UPDATE_CHECK_DISABLED: '1' },
+ });
+ let stdout = '', stderr = '', timedOut = false, exited = false, spawnError, cleanupError;
+ child.stdout.on('data', chunk => { stdout += chunk; });
+ child.stderr.on('data', chunk => { stderr += chunk; });
+ child.once('error', error => { spawnError = error; });
+ const closed = new Promise(resolve => child.once('close', (code, signal) => {
+ exited = true;
+ resolve({ code, signal });
+ }));
+ const timer = setTimeout(() => {
+ timedOut = true;
+ try { killTree(child); } catch (error) { cleanupError = error; }
+ }, deadlineMs);
+ t.after(async () => {
+ clearTimeout(timer);
+ if (!exited) killTree(child);
+ await closed;
+ });
+ const result = await closed;
+ clearTimeout(timer);
+ assert.ifError(spawnError);
+ assert.ifError(cleanupError);
+ assert.equal(timedOut, false, `路径检查在 ${deadlineMs}ms 内未退出,已终止进程树:${description}`);
+ assert.equal(result.signal, null, stderr);
+ assert.ok(stdout.trim(), `路径检查必须返回 JSON 回执:${stderr}`);
+ return { ...result, receipt: JSON.parse(stdout), stderr };
+}
+
+function arrow(d, { id = 'route', from = 'a', to = 'b', extra = '' } = {}) {
+ return `<path id="${id}" data-edge-id="${id}" data-edge-from="${from}" data-edge-to="${to}" d="${d}" class="a-default" marker-end="url(#arrowhead)" ${extra}/>`;
+}
+
+const normalChecks = ['single_svg', 'finite_svg', 'orthogonal_arrows', 'label_route_clearance',
+ 'relationship_crossings', 'relationship_corridors', 'container_border_runs', 'route_rhythm', 'legend_clearance'];
+function assertPass(result) {
+ assert.equal(result.code, 0, JSON.stringify(result.receipt));
+ assert.equal(result.receipt.ok, true);
+ assert.deepEqual(result.receipt.checks.map(item => item.name), normalChecks, '正常产物仍保留原有九项检查');
+}
+function assertPathError(result, code, { role = 'relationship', pathIndex = 1, id = 'route' } = {}) {
+ assert.equal(result.code, 1, JSON.stringify(result.receipt));
+ assert.equal(result.receipt.ok, false);
+ assert.equal(result.receipt.checks.find(item => item.name === 'svg_path_data')?.ok, false);
+ const diagnostic = result.receipt.diagnostics?.find(item => item.code === code);
+ assert.ok(diagnostic, JSON.stringify(result.receipt));
+ assert.equal(diagnostic.subject.role, role);
+ assert.equal(diagnostic.subject.pathIndex, pathIndex);
+ assert.equal(diagnostic.subject.id, id);
+ assert.ok(Number.isInteger(diagnostic.evidence.tokenOffset) && diagnostic.evidence.tokenOffset >= 0);
+ assert.ok(diagnostic.evidence.reason);
+ assert.ok(diagnostic.supportedFixes.length > 0);
+}
+
+for (const d of [
+ 'M 20', 'M 20 20 Q 30 30 40', 'M 20 20 L 100', 'M 20 20 L 100 M 200 20',
+ 'M 20 NaN', 'M 20 20 L 1e999 30', 'M 20 20 X 100 20', 'M 20 20 Z 7', 'M20 20L40,,20',
+]) {
+ test(`缺失、未知或非有限路径数据以诊断结束:${d}`, async t => {
+ assertPathError(await check(t, arrow(d)), 'artifact/svg-path-malformed');
+ });
+}
+for (const d of ['M20 20A40 40 0 0 1 100 100', 'M20 20C40 20 60 20 100 20']) {
+ test(`合法但未支持的指令不能被当作其他指令继续读取:${d}`, async t => {
+ assertPathError(await check(t, arrow(d)), 'artifact/svg-path-unsupported');
+ });
+}
+
+test('公共 check CLI 有界返回路径诊断,不遗留其 checker 子进程', async t => {
+ const result = await check(t, arrow('M20 20Q40 40 80'), { publicCli: true });
+ assertPathError(result, 'artifact/svg-path-malformed');
+});
+
+test('路径诊断定位实际 path 元素并保留可修复的命令信息', async t => {
+ const decoration = '<path d="M0 0C1 1 2 2 3 3"/>';
+ const result = await check(t, decoration + arrow('M20 20A40 40 0 0 1 100 100'));
+ assertPathError(result, 'artifact/svg-path-unsupported', { pathIndex: 2 });
+ assert.equal(result.receipt.diagnostics.find(item => item.code === 'artifact/svg-path-unsupported').evidence.command, 'A');
+ assert.equal(result.receipt.diagnostics.find(item => item.code === 'artifact/svg-path-unsupported').evidence.tokenOffset, 6);
+});
+
+test('大小写指数、小数、隐式重复和相对坐标保留同一条实际直线', async t => {
+ const forms = ['M20 20L200 20', 'M2E1,2e1 2e2,2E1', 'm20 20h1.8e2',
+ 'M+20.0 +20.L2.0e2 20.', 'M20 20h80 100', 'M&#x20;20&#32;20H200'];
+ let metrics;
+ for (const d of forms) {
+ const result = await check(t, arrow(d));
+ assertPass(result);
+ const actual = result.receipt.composition.metrics;
+ if (!metrics) metrics = actual;
+ assert.equal(actual.properCrossings, 0);
+ assert.equal(actual.maxBends, 0);
+ assert.equal(actual.minSegmentPx, metrics.minSegmentPx);
+ }
+});
+
+test('正常二次曲线继续受检,不能为拒绝其他曲线而禁止已有 Q', async t => {
+ assertPass(await check(t, arrow('M20 20L80 20Q100 20 100 40L100 120')));
+ assertPass(await check(t, arrow('m20 20l60 0q20 0 20 20v80')));
+});
+
+const disconnected = 'M20 20L100 20M100 100L200 100';
+const acrossGap = arrow('M80 60L120 60', { id: 'other', from: 'c', to: 'd', extra: 'data-edge-key="1"' });
+for (const rootAttrs of ['', 'data-layout-contract="readable-v2"']) {
+ test(`多个 M 不产生虚构的交叉、转弯或遮挡:${rootAttrs || 'legacy'}`, async t => {
+ const label = '<g data-edge-key="1" data-edge-from="c" data-edge-to="d" data-edge-label="Gap label"><rect class="c-mask" x="90" y="50" width="20" height="20"/></g>';
+ const result = await check(t, arrow(disconnected) + acrossGap + label, { rootAttrs });
+ assertPass(result);
+ const metrics = result.receipt.composition.metrics;
+ assert.equal(metrics.properCrossings, 0);
+ assert.equal(metrics.labelRouteClearanceIssues, 0);
+ assert.equal(metrics.maxBends, 0);
+ assert.equal(metrics.microSegmentCount, 0);
+ });
+ test(`路径元数据不能跨越可见子路径断点:${rootAttrs || 'legacy'}`, async t => {
+ const metadata = 'data-composition-points="20,20;100,20;100,100;200,100"';
+ const result = await check(t, arrow(disconnected, { extra: metadata }) + acrossGap, { rootAttrs });
+ assertPass(result);
+ assert.equal(result.receipt.composition.metrics.maxBends, 0);
+ });
+ test(`真实连续路径交叉仍然失败:${rootAttrs || 'legacy'}`, async t => {
+ const result = await check(t, arrow('M20 20L100 20L100 100L200 100') + acrossGap, { rootAttrs });
+ assert.equal(result.code, 1);
+ assert.equal(result.receipt.checks.find(item => item.name === 'relationship_crossings').ok, false);
+ assert.deepEqual(result.receipt.composition.issues.find(item => item.code === 'composition/proper-crossing').point, [100, 60]);
+ });
+}
+
+test('Z 回到当前子路径起点,后续相对 m 不沿旧终点移动', async t => {
+ const d = 'M20 20H100V100H20Z m0 120h60';
+ const other = arrow('M10 180H30', { id: 'other', from: 'c', to: 'd' });
+ const result = await check(t, arrow(d) + other);
+ assertPass(result);
+ assert.equal(result.receipt.composition.metrics.properCrossings, 0);
+});
+
+test('每个新 M 都重置关闭点,两个正交闭合子路径不会出现对角线', async t => {
+ assertPass(await check(t, arrow('M20 20H100V60H20Z M160 20H240V60H160Z')));
+});
+
+test('关闭路径后继续的相对绘制使用关闭点,仍能发现真实交叉', async t => {
+ const body = arrow('M20 20H100V100H20Z m0 120h60')
+ + arrow('M60 130V150', { id: 'other', from: 'c', to: 'd' });
+ const result = await check(t, body);
+ assert.equal(result.code, 1);
+ assert.deepEqual(result.receipt.composition.issues.find(item => item.code === 'composition/proper-crossing').point, [60, 140]);
+});
+
+test('合法 metadata 不能使残缺路径绕过语法检查', async t => {
+ const result = await check(t, arrow('M20', { extra: 'data-composition-points="20,20;200,20"' }), {
+ rootAttrs: 'data-layout-contract="readable-v2"',
+ });
+ assertPathError(result, 'artifact/svg-path-malformed');
+});
+
+test('结构框的残缺路径返回独立定位,不在第二个解析入口挂起', async t => {
+ const frame = '<path id="outline" data-composition-frame-kind="group" data-composition-frame-id="group-a" d="M20 20Q40 40 80"/>';
+ assertPathError(await check(t, frame), 'artifact/svg-path-malformed', { role: 'structural-frame', id: 'outline' });
+});
+
+test('结构框子路径之间的空隙不产生边框重合,真实边框仍会失败', async t => {
+ const makeFrame = d => `<path data-composition-frame-kind="group" data-composition-frame-id="group-a" d="${d}"/>`;
+ const relation = arrow('M120 40H180');
+ assertPass(await check(t, makeFrame('M40 40H100 M200 40H280') + relation));
+ const crossing = await check(t, makeFrame('M40 40H280') + relation);
+ assert.equal(crossing.code, 1);
+ assert.equal(crossing.receipt.checks.find(item => item.name === 'container_border_runs').ok, false);
+});
+
+test('图标、品牌与普通装饰中的 A/C 不扩大检查器的路径范围', async t => {
+ const decorations = `<g data-node-icon="cloud"><path d="M0 0A4 4 0 0 1 8 0"/></g>
+ <g data-node-brand="example"><path d="M0 0C1 1 2 2 3 3"/></g>
+ <path class="a-default" d="M20 20A40 40 0 0 1 100 100"/>
+ <path marker-end="url(#arrowhead)" d="M20 20C40 20 60 20 100 20"/>`;
+ assertPass(await check(t, decorations + arrow('M20 20H200')));
+});
+
+
+test('多子路径的预算按连续片段测量,同一关系超预算只计一次', async t => {
+ const result = await check(t, arrow('M20 20H60V60H100V100 M160 20H200V60H240V100'));
+ assertPass(result);
+ assert.equal(result.receipt.composition.metrics.maxBends, 6);
+ assert.equal(result.receipt.composition.metrics.routesOverSuggestedBends, 1);
+});
+
+test('后续子路径仍参与标签遮挡,不能被关系 ID 去重丢弃', async t => {
+ const label = '<g data-edge-key="1" data-edge-from="c" data-edge-to="d" data-edge-label="Label"><rect class="c-mask" x="130" y="90" width="20" height="20"/></g>';
+ const result = await check(t, arrow('M20 20H60 M100 100H200')
+ + arrow('M90 200H210', { id: 'other', from: 'c', to: 'd', extra: 'data-edge-key="1"' }) + label);
+ assert.equal(result.code, 1);
+ const issue = result.receipt.composition.issues.find(item => item.code === 'composition/label-route-clearance');
+ assert.equal(issue.otherRelationship.id, 'route');
+ assert.equal(issue.segmentIndex, 1);
+});
+
+test('多子路径只以真实最后一段检测 marker-end,早期片段不产生虚假箭头相撞', async t => {
+ const result = await check(t, arrow('M20 20H100 M20 100H150', { from: 'a', to: 'end' })
+ + arrow('M20 21H100 M20 150H150', { id: 'other', from: 'b', to: 'end' }), {
+ rootAttrs: 'data-layout-contract="readable-v2"',
+ });
+ assertPass(result);
+ assert.equal(result.receipt.composition.metrics.arrowheadCollisions, 0);
+});
+
+for (const [name, left, right, from, to, passes] of [
+ ['实际 source', 'M20 20H40V60 M100 100H140', 'M20 20H40V0 M180 100H220', 'a', 'other-end', true],
+ ['内部 source', 'M20 20H60 M100 100H120V140', 'M20 60H60 M100 100H120V60', 'a', 'other-end', false],
+ ['实际 target', 'M20 20H60 M100 100H120', 'M20 60H60 M100 80V100H120', 'other-start', 'b', true],
+ ['内部 target', 'M100 100H120 M200 20H240', 'M100 80V100H120 M200 60H240', 'other-start', 'b', false],
+]) {
+ test(`workflow 短共享线例外使用 ${name} 而非任意子路径首尾`, async t => {
+ const result = await check(t, arrow(left) + arrow(right, { id: 'other', from, to }), {
+ rootAttrs: 'data-layout-contract="readable-v2"',
+ });
+ if (passes) assertPass(result);
+ else {
+ assert.equal(result.code, 1);
+ assert.equal(result.receipt.checks.find(item => item.name === 'relationship_corridors').ok, false);
+ assert.equal(result.receipt.composition.metrics.ambiguousCorridors, 1);
+ }
+ });
+}
+
+test('注释、CDATA 和属性文本中的伪路径不参与严格解析或路径编号', async t => {
+ const fake = '<path class="a-default" marker-end="url(#arrowhead)" d="M20 20X100 20"/>';
+ const frame = '<path data-composition-frame-kind="group" d="M20"/>';
+ const ignored = `<!-- ${fake}${frame} --> <![CDATA[${fake}${frame}]]><g data-example='${fake}${frame}'></g>`;
+ assertPass(await check(t, ignored + arrow('M20 20H200')));
+ assertPathError(await check(t, ignored + arrow('M20')), 'artifact/svg-path-malformed');
+});
+
+test('多子路径模式仍对同一关系的重复 SVG 片段只计算一次标签遮挡', async t => {
+ const duplicate = arrow('M20 100H200', { extra: 'data-edge-key="0"' });
+ const other = arrow('M90 200H210', { id: 'other', from: 'c', to: 'd', extra: 'data-edge-key="1"' });
+ const label = '<g data-edge-key="1" data-edge-from="c" data-edge-to="d" data-edge-label="Label"><rect class="c-mask" x="130" y="90" width="20" height="20"/></g>';
+ const trigger = arrow('M20 220H60 M100 220H200', { id: 'disjoint', from: 'e', to: 'f' });
+ const base = await check(t, duplicate + duplicate + other + label);
+ const multi = await check(t, duplicate + duplicate + other + label + trigger);
+ assert.equal(base.receipt.composition.metrics.labelRouteClearanceIssues, 1);
+ assert.equal(multi.receipt.composition.metrics.labelRouteClearanceIssues, 1);
+});
+
+test('每片段各两次转弯仍累计为原关系的四个真实转弯', async t => {
+ const result = await check(t, arrow('M20 20H100V60H180 M220 20H300V60H380'));
+ assertPass(result);
+ assert.equal(result.receipt.composition.metrics.maxBends, 4);
+ assert.equal(result.receipt.composition.metrics.routesOverSuggestedBends, 1);
+});
+
+test('deliver 保留路径诊断并且不覆盖此前存在的 HTML', async t => {
+ const output = path.join(scratch, 'previous.html');
+ const wrapper = path.join(scratch, 'broken-renderer.mjs');
+ const previous = Buffer.from('<!doctype html><p>previous trusted artifact</p>');
+ fs.writeFileSync(output, previous);
+ // 只在 renderer 成功写完后破坏其产物;交付、检查、回执与回滚均走生产入口。
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+import childProcess from 'node:child_process';
+import { syncBuiltinESMExports } from 'node:module';
+const original = childProcess.spawnSync;
+childProcess.spawnSync = (command, args, options) => {
+ const result = original(command, args, options);
+ if (String(args?.[0]).endsWith('render-architecture.mjs') && result.status === 0) {
+ const html = fs.readFileSync(args[2], 'utf8');
+ let replaced = false;
+ const broken = html.replace(/<path\\b[^>]*>/g, tag => {
+ if (replaced || !/class="[^"]*\\ba-(?:default|emphasis|security|dashed)\\b/.test(tag) || !tag.includes('marker-end=')) return tag;
+ replaced = true;
+ return tag.replace('<path ', '<path id="injected-path" ').replace(/\\bd="[^"]*"/, 'd="M20 20A40 40 0 0 1 100 100"');
+ });
+ if (!replaced) throw new Error('fixture did not find a rendered arrow');
+ fs.writeFileSync(args[2], broken);
+ }
+ return result;
+};
+syncBuiltinESMExports();
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'architecture',
+ ${JSON.stringify(path.join(skillRoot, 'examples/web-app.architecture.json'))}, ${JSON.stringify(output)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+ const result = await execute(t, [wrapper], 'deliver with an unsupported rendered path');
+ assert.equal(result.code, 1, JSON.stringify(result.receipt));
+ assert.equal(result.receipt.stage, 'check');
+ assert.equal(result.receipt.ok, false);
+ const issue = result.receipt.diagnostics.find(item => item.code === 'artifact/svg-path-unsupported');
+ assert.ok(issue, JSON.stringify(result.receipt));
+ assert.equal(issue.subject.id, 'injected-path');
+ assert.equal(issue.subject.role, 'relationship');
+ assert.ok(issue.subject.pathIndex >= 1);
+ assert.equal(issue.evidence.command, 'A');
+ assert.equal(issue.evidence.tokenOffset, 6);
+ assert.ok(issue.supportedFixes.length > 0);
+ assert.deepEqual(fs.readFileSync(output), previous);
+});