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 dev into PR 456 and fix HTML head boundary detection
sunsunsunde9268f6c213
diff --cc CHANGELOG.mdindex 87ab77f6,1d9fae2b..fd6ed421--- a/CHANGELOG.md+++ b/CHANGELOG.md@@@ -4,10 -4,20 +4,22 @@@ All notable changes are documented here## [Unreleased]+ ### Improved reading++ - Showcase sequence message names use larger primary type and matching label plates; real browser readability checks now include message labels.+> Development identity: `v2.17.0-dev.1`. Not a stable release.+ ### Added+ - **Hermes Agent community opt-in.** `integrations/hermes-agent` is a Skill-only directory plugin: it registers the existing Node Archify `SKILL.md` for Hermes. The documented install is `hermes skills install skills-sh/tt-a1i/archify/archify -y` (published GitHub Skill). A checkout symlink remains the local-dev path. Hermes still runs `node bin/archify.mjs`. This is not an official Nous product and is not an agent-switcher target.+ - **GitHub Copilot agent-switcher target.** The Start page agent switcher, README EN/ZH quick start, and landing copy add `github-copilot` alongside `cursor`, `codex`, `claude-code`, and `opencode`. It installs the same checked Skill and zero-dependency renderers via `npx skills add tt-a1i/archify --skill archify --agent github-copilot ...`; no vendor-specific fork, renderer, or schema behavior was added.+ - **Repository evidence for every diagram type (#59).** `meta.repository` and node `sources` are now accepted by Workflow, Sequence, Data Flow, and Lifecycle as well as Architecture, and `--repo-root` reaches `render`, `validate`, `deliver`, and `preview` for all five. Each mode authors sources on its own node collection (`components`, `nodes`, `participants`, `states`) while verification is unchanged: Git top level, origin match, commit, blob, path containment, and line bounds all still have to hold, GitHub, Gitee, and `link_mode: "local-only"` repositories behave identically in every mode, and the verified payload stays keyed by node id. Architecture output is unchanged and the `repository-evidence/type-unsupported` diagnostic is removed as unreachable.+### Fixed+- **Escaped brand icon URLs (#454).** Favicon discovery decodes basic named and numeric HTML character references once before URL resolution, preserving percent escapes and the existing network and digest checks.++- **Brand HTML head boundaries.** Favicon capture ignores apparent head endings inside comments, raw text and quoted attributes while retaining bounded, streaming head reads.+ - **Conservative VS15 text-width estimates.** Text-presentation selectors retain the base character's estimated width instead of forcing every sequence to one unit. This prevents wide labels, including CJK text whose font ignores VS15, from passing layout checks at half their estimated width. Actual glyph widths remain font-dependent; some text-presentation labels may now need more space. VS16 emoji estimates and text without selectors are unchanged.+ - **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 配置。diff --cc archify.zipindex b712767f,c9aaf761..5a3d7633Binary files differdiff --cc archify/references/brand-marks.mdindex dcfad1ea,55411787..1c127493--- a/archify/references/brand-marks.md+++ b/archify/references/brand-marks.md@@@ -48,12 -48,6 +48,16 @@@ does; `brand` explains whose product iURL or silently assign a visually similar company.Known-brand URLs resolve to the bundled vector instead of using the network.+For discovered icon `href` attributes, capture decodes the basic named references+`amp`, `quot`, `apos`, `lt`, `gt` (and their defined uppercase aliases), plus+decimal and hexadecimal numeric references, once before URL resolution. Thus+`/icon.png?v=1&size=32` requests `/icon.png?v=1&size=32`. URL percent escapes+remain intact; nested escapes are not decoded recursively. This bounded decoder+does not add a general HTML parser or support every named HTML entity.++HTML reads stop at an explicit head ending outside comments, raw-text elements++and quoted attributes, including when those tokens span network chunks. The++256 KiB head limit and capture deadline still apply; a larger body after the++head is not read for icon discovery.Unknown URL capture accepts only bounded raster image formats, blockscredentials, nonstandard public ports, and private or link-local destinations,uses bounded concurrency and one total deadline, and returns the captureddiff --cc archify/renderers/shared/brand-marks.mjsindex 44451027,9b0cf868..0b4a7678--- a/archify/renderers/shared/brand-marks.mjs+++ b/archify/renderers/shared/brand-marks.mjs@@@ -269,6 -269,42 +269,83 @@@ async function readLimited(response, mareturn Buffer.concat(chunks, total);}+ // Read only the bounded head, independent of network chunk boundaries. Scan+ // bytes once so many tiny chunks cannot cause repeated concatenation/rescanning.++// This is a boundary scanner, not a DOM parser: comments, quoted attributes and++// raw-text elements must not turn a literal </head> into an early stop.+ async function readHtmlHead(response, maximum) {+ const chunks = response.body && typeof response.body[Symbol.asyncIterator] === 'function'+ ? response.body : [await readLimited(response, maximum)];+ const buffer = Buffer.alloc(maximum);- const closing = Buffer.from('</head');+ let total = 0;++ let tagStart = -1;++ let quote = 0;++ let comment = false;++ let rawClosing = '';+ let matched = 0;+ for await (const value of chunks) {+ const chunk = Buffer.from(value);+ const length = Math.min(chunk.length, maximum - total);+ chunk.copy(buffer, total, 0, length);+ for (let offset = 0; offset < length; offset++) {+ const byte = chunk[offset];- if (matched === closing.length) {- if (byte === 0x3e) {++ const position = total + offset;++ if (comment) {++ if (byte === 0x3e && buffer[position - 1] === 0x2d && buffer[position - 2] === 0x2d) comment = false;++ continue;++ }++ if (rawClosing) {++ const lower = byte >= 65 && byte <= 90 ? byte + 32 : byte;++ if (matched === rawClosing.length && [9, 10, 12, 13, 32, 47, 62].includes(byte)) {++ tagStart = position - matched;++ rawClosing = '';++ matched = 0;++ } else {++ matched = lower === rawClosing.charCodeAt(matched) ? matched + 1 : (byte === 0x3c ? 1 : 0);++ continue;++ }++ }++ if (tagStart < 0) {++ if (byte === 0x3c) tagStart = position;++ continue;++ }++ if (position === tagStart + 1 && !((byte >= 65 && byte <= 90) || (byte >= 97 && byte <= 122) || [33, 47, 63].includes(byte))) {++ tagStart = byte === 0x3c ? position : -1;++ continue;++ }++ if (position === tagStart + 3 && buffer[tagStart + 1] === 0x21 && buffer[tagStart + 2] === 0x2d && byte === 0x2d) {++ comment = true;++ tagStart = -1;++ continue;++ }++ if (quote) {++ if (byte === quote) quote = 0;++ continue;++ }++ if (byte === 0x22 || byte === 0x27) {++ quote = byte;++ continue;++ }++ if (byte === 0x3e) {++ const tag = buffer.toString('utf8', tagStart, position + 1);++ if (/^<\/head[\t\n\f\r ]*>$/i.test(tag)) {+ response.body?.destroy?.();- return buffer.toString('utf8', 0, total + offset + 1);++ return buffer.toString('utf8', 0, position + 1);+ }- if (byte === 9 || byte === 10 || byte === 12 || byte === 13 || byte === 32) continue;- matched = byte === 0x3c ? 1 : 0;- } else {- const lower = byte >= 65 && byte <= 90 ? byte + 32 : byte;- matched = lower === closing[matched] ? matched + 1 : (byte === 0x3c ? 1 : 0);++ const raw = /^<(script|style|title|textarea|xmp|iframe|noembed|noframes)(?=[\t\n\f\r />])/i.exec(tag);++ if (raw) rawClosing = `</${raw[1].toLowerCase()}`;++ tagStart = -1;+ }+ }+ total += length;+ if (chunk.length > length) {+ response.body?.destroy?.();+ throw new Error('brand asset is too large');+ }+ }+ return buffer.toString('utf8', 0, total);+ }+function attribute(tag, name) {const match = tag.match(new RegExp(`\\b${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i'));return match ? (match[1] ?? match[2] ?? match[3] ?? '') : '';diff --cc archify/test/brand-href-entities.test.mjsindex 40487b1a,00000000..1cd90c01mode 100644,000000..100644--- a/archify/test/brand-href-entities.test.mjs+++ b/archify/test/brand-href-entities.test.mjs@@@ -1,125 -1,0 +1,173 @@@+import assert from 'node:assert/strict';+import { spawn } from 'node:child_process';+import { createHash } from 'node:crypto';+import fs from 'node:fs';+import http from 'node:http';+import os from 'node:os';+import path from 'node:path';+import test from 'node:test';+import { fileURLToPath } from 'node:url';++const skillRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const cli = path.join(skillRoot, 'bin/archify.mjs');+const icon = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=', 'base64');+const digest = createHash('sha256').update(icon).digest('hex');+const cases = [+ ['named ampersand', '/mark.png?a=1&b=2', '/mark.png?a=1&b=2'],+ ['uppercase ampersand', '/mark.png?a=1&b=2', '/mark.png?a=1&b=2'],+ ['decimal ampersand', '/mark.png?a=1&b=2', '/mark.png?a=1&b=2'],+ ['hexadecimal ampersand', '/mark.png?a=1&b=2', '/mark.png?a=1&b=2'],+ ['basic named references', '/mark.png?q="'<>', '/mark.png?q="\'<>'],+ ['percent escapes', '/mark.png?q=%26amp%3B%2F&v=%2526', '/mark.png?q=%26amp%3B%2F&v=%2526'],+ ['one decoding pass', '/mark.png?a=1&amp;b=2', '/mark.png?a=1&b=2'],+ ['literal query ampersands', '/mark.png?a=1&b=2&token=plain', '/mark.png?a=1&b=2&token=plain'],+ ['ambiguous unterminated names', '/mark.png?a=1&=2&x=3&=4', '/mark.png?a=1&=2&x=3&=4'],+ ['Unicode numeric references', '/mark.png?q=🚀😀', '/mark.png?q=🚀😀'],+ ['invalid numeric code points', '/mark.png?q=���', '/mark.png?q=���'],+ ['unterminated numeric reference', '/mark.png?a=1&b=2', '/mark.png?a=1&b=2'],+ ['legacy numeric C1 mapping', '/mark.png?q=€', '/mark.png?q=€'],+ ['attribute named-reference boundaries', '/mark.png?q=&!&apos!&bogus;&AmP;', '/mark.png?q=&!&apos!&bogus;&AmP;'],+];++function run(args) {+ return new Promise((resolve, reject) => {+ const child = spawn(process.execPath, [cli, ...args], {+ cwd: skillRoot,+ env: { ...process.env, ARCHIFY_BRAND_ALLOW_PRIVATE: '1' },+ stdio: ['ignore', 'pipe', 'pipe'],+ timeout: 15000,+ });+ let stdout = '';+ let stderr = '';+ child.stdout.setEncoding('utf8').on('data', (chunk) => { stdout += chunk; });+ child.stderr.setEncoding('utf8').on('data', (chunk) => { stderr += chunk; });+ child.once('error', reject);+ child.once('close', (status) => resolve({ status, stdout, stderr }));+ });+}+- async function fixture(t, href, decoded) {++async function fixture(t, href, decoded, chunks) {+ const requests = [];+ let expected;- const server = http.createServer((request, response) => {++ const server = http.createServer(async (request, response) => {+ requests.push(request.url);+ if (request.url === '/studio') {+ response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });- response.end(`<html><title>Entity fixture</title><link rel="icon" href="${href}"></html>`);++ if (chunks) {++ for (const chunk of chunks) {++ if (response.destroyed) return;++ response.write(chunk);++ await new Promise((resolve) => setTimeout(resolve, 2));++ }++ response.end();++ } else {++ response.end(`<html><title>Entity fixture</title><link rel="icon" href="${href}"></html>`);++ }+ } else if (expected && request.url === expected.pathname + expected.search) {+ response.writeHead(200, { 'content-type': 'image/png' });+ response.end(icon);+ } else {+ // A wrong query and the fallback must never accidentally yield the right digest.+ response.writeHead(404);+ response.end('no icon at this URL');+ }+ });+ await new Promise((resolve, reject) => {+ server.once('error', reject);+ server.listen(0, '127.0.0.1', resolve);+ });+ t.after(() => new Promise((resolve) => {+ server.closeAllConnections?.();+ server.close(resolve);+ }));+ const url = `http://127.0.0.1:${server.address().port}/studio`;+ if (decoded) expected = new URL(decoded, url);+ return { url, requests, expected };+}++async function capture(data) {+ const result = await run(['brands', 'capture', data.url, '--json']);+ assert.deepEqual(data.requests, ['/studio', data.expected.pathname + data.expected.search], 'request the decoded href exactly once');+ assert.equal(result.status, 0, result.stderr || result.stdout);+ const receipt = JSON.parse(result.stdout);+ assert.equal(receipt.ok, true);+ assert.deepEqual(receipt.brand, { url: data.url, sha256: digest });+ assert.equal(receipt.evidence.status, 'captured');+ assert.equal(receipt.evidence.sha256, digest);+ return receipt.brand;+}++for (const [name, href, decoded] of cases) {+ test(`brands capture resolves ${name} in icon href`, { timeout: 20000 }, async (t) => {+ await capture(await fixture(t, href, decoded));+ });+}+- test('captured entity URL is fetched identically for pinned validation and rendering', { timeout: 45000 }, async (t) => {- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-brand-href-'));- t.after(() => fs.rmSync(root, { recursive: true, force: true }));- const data = await fixture(t, '/mark.png?v=1&size=32', '/mark.png?v=1&size=32');- const brand = await capture(data);- const diagram = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples/web-app.architecture.json'), 'utf8'));- diagram.components[0].brand = brand;- const input = path.join(root, 'diagram.json');- const output = path.join(root, 'diagram.html');- fs.writeFileSync(input, JSON.stringify(diagram));- for (const command of ['validate', 'render']) {- data.requests.length = 0;- const args = [command, 'architecture', input, ...(command === 'render' ? [output] : ['--json'])];- const result = await run(args);- assert.equal(result.status, 0, result.stderr || result.stdout);- assert.deepEqual(data.requests, ['/studio', data.expected.pathname + data.expected.search]);- }- const html = fs.readFileSync(output, 'utf8');- assert.match(html, /data-brand-status="captured"/);- assert.ok(html.includes(`data-brand-sha256="${digest}"`));- assert.ok(html.includes(`data:image/png;base64,${icon.toString('base64')}`));++const diagramTypes = [++ ['architecture', 'web-app.architecture.json', 'components'],++ ['workflow', 'agent-tool-call.workflow.json', 'nodes'],++ ['sequence', 'cache-miss-request.sequence.json', 'participants'],++ ['dataflow', 'product-analytics.dataflow.json', 'nodes'],++ ['lifecycle', 'agent-run.lifecycle.json', 'states'],++];++for (const [type, example, collection] of diagramTypes) {++ test(`captured entity URL is fetched identically for pinned ${type} validation and rendering`, { timeout: 45000 }, async (t) => {++ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-brand-href-'));++ t.after(() => fs.rmSync(root, { recursive: true, force: true }));++ const data = await fixture(t, null, '/mark.png?v=1&size=32', [++ '<head><!-- </head> --><script>const tag = "</head>";</script>',++ '<link rel="icon" href="/mark.png?v=1&am',++ 'p;size=32"></he', 'ad><body>',++ ]);++ const brand = await capture(data);++ const diagram = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples', example), 'utf8'));++ diagram[collection][0].brand = brand;++ const input = path.join(root, 'diagram.json');++ const output = path.join(root, 'diagram.html');++ fs.writeFileSync(input, JSON.stringify(diagram));++ for (const command of ['validate', 'render']) {++ data.requests.length = 0;++ const args = [command, type, input, ...(command === 'render' ? [output] : ['--json'])];++ const result = await run(args);++ assert.equal(result.status, 0, result.stderr || result.stdout);++ assert.deepEqual(data.requests, ['/studio', data.expected.pathname + data.expected.search]);++ }++ const html = fs.readFileSync(output, 'utf8');++ assert.match(html, /data-brand-status="captured"/);++ assert.ok(html.includes(`data-brand-sha256="${digest}"`));++ assert.ok(html.includes(`data:image/png;base64,${icon.toString('base64')}`));++ });++}++++for (const [name, prefix] of [++ ['comment', '<!-- example </head> -->'],++ ['script', '<script>const tag = "</head>"; if (1 < 2) {}</script>'],++ ['style', '<style>p::after { content: "</head>"; }</style>'],++ ['title', '<title>Literal </head> example</title>'],++ ['quoted attribute', '<meta name="example" content="prefix > </head>">'],++ ['single quoted attribute', "<meta name='example' content='prefix > </head>'>"],++ ['raw end tag prefix', '<script>"</scripture></head>";</script>'],++ ['self-closing script flag', '<script/>"</head>";</script>'],++ ['mixed case and spacing', '<ScRiPt data-example=">">"</head>";</sCrIpT \n>'],++]) {++ test(`capture ignores a head ending inside ${name} across response chunks`, async (t) => {++ const html = `<head>${prefix}<link rel='icon' href='/mark.png?a=1&b=2'></HEAD \n>`;++ // Split every token (including the entity) and append a body above the cap:++ // success requires both context-aware scanning and early cancellation.++ const data = await fixture(t, null, '/mark.png?a=1&b=2', [...html, 'x'.repeat(300 * 1024)]);++ await capture(data);++ });++}++++test('capture decodes an unquoted href split across chunks', async (t) => {++ await capture(await fixture(t, null, '/mark.png?a=1&b=2', [++ '<head><link rel=icon href=/mark.png?a=1&am', 'p;b=2></head>',++ ]));+});++test('entity-decoded non-HTTP icon URLs are not fetched', { timeout: 20000 }, async (t) => {+ const data = await fixture(t, 'javascript:alert(1)');+ const result = await run(['brands', 'capture', data.url, '--json']);+ assert.notEqual(result.status, 0);+ assert.deepEqual(data.requests, ['/studio', '/favicon.ico']);+});