Skip to content

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

fix: preserve validation and memory bounds in compile optimizations

sunsunsun720619c848ce
diff --git a/archify.zip b/archify.zip
index 07d5c840..8138d150 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 b993eb51..9937a9d5 100644
--- a/archify/renderers/shared/cli.mjs
+++ b/archify/renderers/shared/cli.mjs
@@ -19,6 +19,7 @@ import {
verifyAtomicOutput,
} from './atomic-output.mjs';
import { resolveLocale, translateMessage } from './i18n.mjs';
+import { prepareDiagramBrandMarks } from './brand-marks.mjs';
const outputPathGuards = new Map();
let renderCandidateSequence = 0;
@@ -85,30 +86,9 @@ export function loadDiagram({ rendererDir, diagramType, defaultExample, argv = p
// Brand URL capture is the only asynchronous authoring step. Typed renderers
// opt into it through this wrapper without changing loadDiagram's long-lived
// synchronous safety contract.
-// Brand resolution walks the element collection and returns immediately when no
-// element names a mark, so a document without one never needs the brand tables.
-const BRAND_COLLECTIONS = {
- architecture: 'components',
- workflow: 'nodes',
- sequence: 'participants',
- dataflow: 'nodes',
- lifecycle: 'states',
-};
-
-function declaresBrandMark(diagramType, diagram) {
- const collection = BRAND_COLLECTIONS[diagramType];
- const elements = collection && Array.isArray(diagram?.[collection]) ? diagram[collection] : [];
- // Same skip condition as the preparer, so a mark it would report as unknown
- // still reaches it.
- return elements.some((element) => Boolean(element?.brand));
-}
-
export async function loadDiagramWithBrandMarks(options) {
const loaded = loadDiagram(options);
- if (declaresBrandMark(options.diagramType, loaded.diagram)) {
- const { prepareDiagramBrandMarks } = await import('./brand-marks.mjs');
- await prepareDiagramBrandMarks(options.diagramType, loaded.diagram);
- }
+ await prepareDiagramBrandMarks(options.diagramType, loaded.diagram);
return loaded;
}
diff --git a/archify/renderers/shared/geometry.mjs b/archify/renderers/shared/geometry.mjs
index 6231b9e1..7d5331e6 100644
--- a/archify/renderers/shared/geometry.mjs
+++ b/archify/renderers/shared/geometry.mjs
@@ -1271,10 +1271,9 @@ function segmentPosition(index, segmentCount) {
// Normalizing a route is pure, and the same route array is normalized again by
// every predicate that inspects it. Keyed by the array itself, so a rebuilt
-// route simply gets a new entry. Cached results are frozen: every reader gets
-// the same read-only array, and an in-place edit cannot leave a stale entry
-// behind. The point array it contains is produced once per render and read
-// only.
+// route simply gets a new entry. The result's outer array is frozen. Callers
+// must also treat input arrays and their coordinate pairs as immutable, since
+// edits in place cannot invalidate this identity-based cache.
const NORMALIZED_ROUTE_POINTS = new WeakMap();
// Assembling a route from an anchor, corridor points and an anchor is the same
@@ -1330,18 +1329,14 @@ function pointRectDistance(point, rect) {
function pointSegmentDistanceXY(px, py, start, end) {
const dx = end[0] - start[0];
const dy = end[1] - start[1];
- if (dx === 0 && dy === 0) return Math.hypot(px - start[0], py - start[1]);
- const t = Math.max(0, Math.min(1, ((px - start[0]) * dx + (py - start[1]) * dy) / (dx * dx + dy * dy)));
+ const lengthSquared = dx * dx + dy * dy;
+ if (lengthSquared <= 0.0000001) return Math.hypot(px - start[0], py - start[1]);
+ const t = Math.max(0, Math.min(1, ((px - start[0]) * dx + (py - start[1]) * dy) / lengthSquared));
return Math.hypot(px - (start[0] + t * dx), py - (start[1] + t * dy));
}
function pointSegmentDistance(point, start, end) {
- const dx = end[0] - start[0];
- const dy = end[1] - start[1];
- const lengthSquared = dx * dx + dy * dy;
- if (lengthSquared <= 0.0000001) return Math.hypot(point[0] - start[0], point[1] - start[1]);
- const projection = Math.max(0, Math.min(1, ((point[0] - start[0]) * dx + (point[1] - start[1]) * dy) / lengthSquared));
- return Math.hypot(point[0] - (start[0] + projection * dx), point[1] - (start[1] + projection * dy));
+ return pointSegmentDistanceXY(point[0], point[1], start, end);
}
function collinearForward(a, b, c) {
diff --git a/archify/renderers/shared/repository-evidence.mjs b/archify/renderers/shared/repository-evidence.mjs
index d11acd9b..33898c0c 100644
--- a/archify/renderers/shared/repository-evidence.mjs
+++ b/archify/renderers/shared/repository-evidence.mjs
@@ -1,12 +1,13 @@
import { spawnSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
-import { throwDiagnosticError } from './diagnostics.mjs';
+import { throwDiagnosticError, withDiagnosticRecordingSuppressed } from './diagnostics.mjs';
import { sameEntry } from './path-semantics.mjs';
import { parseRepositoryRemote, redactRepositoryRemote, repositorySourceHref } from './repository-location.mjs';
const FULL_SHA_RE = /^[a-f0-9]{40}$/i;
const CONTROL_CHARACTER_RE = /[\u0000-\u001f\u007f]/;
+const MAX_SOURCE_BYTES = 16 * 1024 * 1024;
function evidenceFailure(code, message, { subject = {}, evidence = {}, supportedFixes = [] } = {}) {
throwDiagnosticError(message, [{
@@ -23,7 +24,7 @@ function runGit(repoRoot, args) {
// 固定 SHA 的来源必须读取原始对象,不能使用本地 replacement refs 的替换内容。
const result = spawnSync('git', ['--no-replace-objects', '-C', repoRoot, ...args], {
encoding: 'utf8',
- maxBuffer: 16 * 1024 * 1024,
+ maxBuffer: MAX_SOURCE_BYTES,
});
if (result.error) evidenceFailure('repository-evidence/git-unavailable', `Could not run Git: ${result.error.message}`, {
evidence: { reason: result.error.message },
@@ -32,12 +33,26 @@ function runGit(repoRoot, args) {
return result;
}
-// One `git cat-file --batch` session answers every object the document cites;
-// the alternative was two processes per citation (type, then content), which on
-// a sixty-citation document dominated the whole render.
-function prefetchBlobs(repoRoot, objects) {
+// Check types in one session, then read only blobs whose cited lines need
+// verification. Path-only references never require loading the file contents.
+function prefetchBlobs(repoRoot, objectNeedsContent) {
+ const blobs = readBatchObjects(repoRoot, [...objectNeedsContent.keys()], false);
+ if (!blobs) return null;
+ const readable = [...objectNeedsContent].filter(([object, needsContent]) => {
+ const blob = blobs.get(object);
+ return needsContent && blob?.type === 'blob' && blob.size <= MAX_SOURCE_BYTES;
+ }).map(([object]) => object);
+ const contents = readBatchObjects(repoRoot, readable, true);
+ if (contents) for (const [object, blob] of contents) blobs.set(object, blob);
+ // Failed or oversized reads fall back in source order to the original
+ // per-file path, preserving its size limit and diagnostic behavior.
+ return blobs;
+}
+
+function readBatchObjects(repoRoot, objects, includeContent) {
if (!objects.length) return new Map();
- const result = spawnSync('git', ['--no-replace-objects', '-C', repoRoot, 'cat-file', '--batch'], {
+ const mode = includeContent ? '--batch' : '--batch-check';
+ const result = spawnSync('git', ['--no-replace-objects', '-C', repoRoot, 'cat-file', mode], {
input: objects.join('\n') + '\n',
maxBuffer: 64 * 1024 * 1024,
});
@@ -56,9 +71,14 @@ function prefetchBlobs(repoRoot, objects) {
}
const parts = header.split(' ');
const size = Number(parts[2]);
- if (parts.length !== 3 || !Number.isFinite(size) || cursor + size > buffer.length) return null;
- blobs.set(object, { type: parts[1], content: buffer.toString('utf8', cursor, cursor + size) });
- cursor += size + 1;
+ if (parts.length !== 3 || !Number.isSafeInteger(size) || size < 0) return null;
+ const blob = { type: parts[1], size };
+ if (includeContent) {
+ if (cursor + size >= buffer.length || buffer[cursor + size] !== 0x0a) return null;
+ blob.content = buffer.toString('utf8', cursor, cursor + size);
+ cursor += size + 1;
+ }
+ blobs.set(object, blob);
}
return blobs;
}
@@ -221,21 +241,22 @@ export function verifyRepositoryEvidence(diagramType, diagram, repoRootInput) {
// The batch is an optimization only: every path, line-range, file and line
// check still runs in source order in the verification loop below, so a
// citation the batch cannot answer for never reorders the first diagnostic.
- const citedObjects = [];
+ const citedObjects = new Map();
for (const [nodeIndex, node] of authoredNodes.entries()) {
if (!Array.isArray(node.sources) || node.sources.length === 0) continue;
for (const [sourceIndex, authored] of node.sources.entries()) {
const at = `/${collection}/${nodeIndex}/sources/${sourceIndex}`;
let sourcePath;
try {
- sourcePath = verifiedSourcePath(authored.path, `${at}/path`);
+ sourcePath = withDiagnosticRecordingSuppressed(() => verifiedSourcePath(authored.path, `${at}/path`));
} catch {
continue;
}
- citedObjects.push(`${revision}:${sourcePath}`);
+ const object = `${revision}:${sourcePath}`;
+ citedObjects.set(object, citedObjects.get(object) || Boolean(authored.line));
}
}
- const prefetchedBlobs = prefetchBlobs(realRoot, [...new Set(citedObjects)]);
+ const prefetchedBlobs = prefetchBlobs(realRoot, citedObjects);
const nodes = Object.create(null);
let referenceCount = 0;
@@ -285,7 +306,7 @@ export function verifyRepositoryEvidence(diagramType, diagram, repoRootInput) {
});
}
if (source.line) {
- const content = prefetched && !prefetched.missing
+ const content = prefetched && Object.hasOwn(prefetched, 'content')
? { status: 0, stdout: prefetched.content }
: runGit(realRoot, ['show', object]);
if (content.status !== 0) evidenceFailure('repository-evidence/file-unreadable', `${where} could not be read at revision ${revision}.`, {
diff --git a/archify/renderers/shared/utils.mjs b/archify/renderers/shared/utils.mjs
index 49678023..72a6598e 100644
--- a/archify/renderers/shared/utils.mjs
+++ b/archify/renderers/shared/utils.mjs
@@ -229,6 +229,8 @@ const VARIATION_SELECTOR_EMOJI = 0xfe0f;
// Width measurement is pure and the same labels are measured many times per
// compile, so the unit count is memoized by its input string.
const TEXT_UNITS_CACHE = new Map();
+const MAX_TEXT_UNITS_CACHE_ENTRIES = 4096;
+const MAX_CACHED_TEXT_LENGTH = 1024;
export function textUnits(text) {
const cacheKey = String(text ?? '');
@@ -243,6 +245,12 @@ export function textUnits(text) {
if (next === VARIATION_SELECTOR_EMOJI) units += 2;
else units += FULLWIDTH_RE.test(chars[i]) ? 2 : 1;
}
- TEXT_UNITS_CACHE.set(cacheKey, units);
+ // Keep repeated in-process compiles bounded, including unusually long labels.
+ if (cacheKey.length <= MAX_CACHED_TEXT_LENGTH) {
+ if (TEXT_UNITS_CACHE.size >= MAX_TEXT_UNITS_CACHE_ENTRIES) {
+ TEXT_UNITS_CACHE.delete(TEXT_UNITS_CACHE.keys().next().value);
+ }
+ TEXT_UNITS_CACHE.set(cacheKey, units);
+ }
return units;
}
diff --git a/archify/test/geometry.test.mjs b/archify/test/geometry.test.mjs
index 53c229ee..ac48df2c 100644
--- a/archify/test/geometry.test.mjs
+++ b/archify/test/geometry.test.mjs
@@ -171,6 +171,14 @@ test('label-route clearance locks tangent, sub-threshold, boundary, and reversed
}
});
+test('near-zero segments preserve the existing label clearance threshold', () => {
+ const q = 100 - 3.999899999 / Math.sqrt(2);
+ const segment = { start: [q - 0.0001, q + 0.0001], end: [q + 0.0001, q - 0.0001] };
+ const box = rect(100, 100, 20, 20);
+ assert.ok(segmentRectClearance(segment, box) + 0.0001 >= 4);
+ assert.ok(segmentRectClearance({ start: segment.end, end: segment.start }, box) + 0.0001 >= 4);
+});
+
test('collectLabelRouteClearance exempts only the owning relationship at an exact threshold', () => {
const owner = { id: 'owner', from: 'a', to: 'b' };
const sharedSource = { id: 'other', from: 'a', to: 'c' };
diff --git a/archify/test/repository-evidence.test.mjs b/archify/test/repository-evidence.test.mjs
index adf12cd2..b41677f3 100644
--- a/archify/test/repository-evidence.test.mjs
+++ b/archify/test/repository-evidence.test.mjs
@@ -57,6 +57,46 @@ function evidencePayload(html) {
return JSON.parse(match[1]);
}
+test('evidence prefetch preserves the first source diagnostic in JSON output', (t) => {
+ const data = fixture();
+ t.after(() => fs.rmSync(data.root, { recursive: true, force: true }));
+ data.diagram.components[0].sources = [{ path: 'src/missing.js' }, { path: '../escape' }];
+ fs.writeFileSync(data.input, JSON.stringify(data.diagram));
+ const result = run(['validate', 'architecture', data.input, '--repo-root', data.root, '--json']);
+ assert.equal(result.status, 1);
+ const report = JSON.parse(result.stdout);
+ assert.deepEqual(report.diagnostics.map(({ code, subject }) => [code, subject.path]), [
+ ['repository-evidence/file-missing', '/components/0/sources/0/path'],
+ ]);
+});
+
+test('path-only evidence verifies types without reading blob contents', (t) => {
+ const data = fixture();
+ t.after(() => fs.rmSync(data.root, { recursive: true, force: true }));
+ data.diagram.components[0].sources = [{ path: 'src/router.js' }, { path: 'src/store.js' }];
+ fs.writeFileSync(data.input, JSON.stringify(data.diagram));
+ const trace = path.join(data.root, 'git.trace');
+ const result = spawnSync(process.execPath, [cli, 'validate', 'architecture', data.input, '--repo-root', data.root, '--json'], {
+ cwd: skillRoot, encoding: 'utf8', env: { ...process.env, GIT_TRACE: trace },
+ });
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ assert.doesNotMatch(fs.readFileSync(trace, 'utf8'), /cat-file --batch(?:\s|$)|\bshow\s/);
+});
+
+test('line evidence retains the per-file read limit after batch prefetch', (t) => {
+ const data = fixture();
+ t.after(() => fs.rmSync(data.root, { recursive: true, force: true }));
+ fs.writeFileSync(path.join(data.root, 'large.txt'), Buffer.alloc(17 * 1024 * 1024, 'x'));
+ git(data.root, 'add', 'large.txt');
+ git(data.root, 'commit', '-m', 'large source');
+ data.diagram.meta.repository.revision = git(data.root, 'rev-parse', 'HEAD');
+ data.diagram.components[0].sources = [{ path: 'large.txt', line: 1 }];
+ fs.writeFileSync(data.input, JSON.stringify(data.diagram));
+ const result = run(['validate', 'architecture', data.input, '--repo-root', data.root, '--json']);
+ assert.equal(result.status, 1, result.stdout);
+ assert.equal(JSON.parse(result.stdout).diagnostics[0].code, 'repository-evidence/git-unavailable');
+});
+
test('repository root accepts a different spelling of the same physical Git top-level', (t) => {
const data = fixture();
const alias = `${data.root}-alias`;