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
perf(ci): shard full regression and remove redundant test work (#803)
tt-a1i0c5550a6e5c7
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 3a5f7106..5d6623f4 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -61,13 +61,43 @@ jobs:if: steps.classify.outputs.scope == 'docs'run: node --test test/readme-showcase.test.mjs+ full-regression:+ needs: scope+ if: needs.scope.outputs.scope == 'full'+ runs-on: ubuntu-latest+ strategy:+ fail-fast: false+ matrix:+ shard: [1, 2]+ steps:+ - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0+ - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0+ with:+ node-version: 22+ cache: npm+ cache-dependency-path: |+ package-lock.json+ archify/package-lock.json+ - name: Install regression dependencies+ run: npm ci && npm --prefix archify ci+ # Reuse a shard's installed runtime instead of bootstrapping after all+ # shards finish. These checks still run exactly once in complete CI.+ - name: Generated outputs and representative goldens+ if: matrix.shard == 2+ run: npm run test:generated+ - name: Verify community Hermes adapter+ if: matrix.shard == 2+ run: node --test integrations/hermes-agent/test/plugin-contract.test.mjs+ - name: Run a complete regression shard+ run: node scripts/run-tests.mjs --shard=${{ matrix.shard }}/2+test:needs: scopeif: always() && !cancelled()runs-on: ubuntu-lateststrategy:matrix:- node-version: [18, 20, 22, 24]+ node-version: [18, 20, 24]steps:# Keep every required matrix check present; fail closed if classification/checks fail.- name: Require successful scope checks@@ -91,27 +121,60 @@ jobs:- name: Install renderer dependenciesif: needs.scope.outputs.scope != 'docs'run: npm ci && npm --prefix archify ci- - name: Complete regression suite on canonical Node- if: needs.scope.outputs.scope == 'full' && matrix.node-version == 22- run: npm run test:full- - name: Core public CLI contracts- if: needs.scope.outputs.scope == 'core' && matrix.node-version == 22- run: npm test- name: Supported Node runtime compatibility- if: needs.scope.outputs.scope != 'docs' && matrix.node-version != 22+ if: needs.scope.outputs.scope != 'docs'run: npm run test:compat++ canonical-test:+ name: test (22)+ needs: [scope, full-regression]+ if: always() && !cancelled()+ runs-on: ubuntu-latest+ steps:+ # Keep every required matrix check present; fail closed if classification/checks fail.+ - name: Require successful scope checks+ env:+ SCOPE_RESULT: ${{ needs.scope.result }}+ CI_SCOPE: ${{ needs.scope.outputs.scope }}+ shell: bash+ run: |+ test "$SCOPE_RESULT" = success+ case "$CI_SCOPE" in docs|core|full) ;; *) exit 1 ;; esac+ - name: Require complete regression shards+ env:+ CI_SCOPE: ${{ needs.scope.outputs.scope }}+ REGRESSION_RESULT: ${{ needs.full-regression.result }}+ shell: bash+ run: |+ case "$CI_SCOPE:$REGRESSION_RESULT" in+ full:success|core:skipped|docs:skipped) ;;+ *) exit 1 ;;+ esac+ - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0+ if: needs.scope.outputs.scope == 'core'+ - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0+ if: needs.scope.outputs.scope == 'core'+ with:+ node-version: 22+ cache: npm+ cache-dependency-path: |+ package-lock.json+ archify/package-lock.json+ - name: Install renderer dependencies+ if: needs.scope.outputs.scope == 'core'+ run: npm ci && npm --prefix archify ci+ - name: Core public CLI contracts+ if: needs.scope.outputs.scope == 'core'+ run: npm test- name: Generated outputs and representative goldens- if: needs.scope.outputs.scope != 'full' && needs.scope.outputs.generated == 'true' && matrix.node-version == 22+ if: needs.scope.outputs.scope == 'core' && needs.scope.outputs.generated == 'true'run: npm run test:generated- name: Changed tests and owned regression suites- if: needs.scope.outputs.scope == 'core' && matrix.node-version == 22+ if: needs.scope.outputs.scope == 'core'run: npm run test:affectedenv:CI_TEST_OWNERS: ${{ needs.scope.outputs.owners }}CI_CHANGED_TESTS: ${{ needs.scope.outputs.changedTests }}- - name: Verify community Hermes adapter- if: needs.scope.outputs.scope == 'full' && matrix.node-version == 22- run: node --test integrations/hermes-agent/test/plugin-contract.test.mjsbrowser-regression:needs: scope@@ -454,7 +517,7 @@ jobs:run: scripts/windows-path-fixtures.ps1 -NodeVersion '${{ matrix.node-version }}'- name: Verify maintained Windows path contractsif: needs.scope.outputs.windows == 'true'- run: node scripts/run-windows-path-tests.mjs+ run: node scripts/run-windows-path-tests.mjs ${{ matrix.node-version == 24 && '--smoke' || '' }}env:ARCHIFY_REQUIRE_WINDOWS_8DOT3: '1'ARCHIFY_REQUIRE_WINDOWS_REAL_PATHS: '1'@@ -465,7 +528,7 @@ jobs:deploy-pages:if: github.event_name == 'push' && github.ref == 'refs/heads/main'- needs: [test, webm-artifact, zip-freshness, published-update-manifest, package-smoke, windows-test-portability, website]+ needs: [test, canonical-test, webm-artifact, zip-freshness, published-update-manifest, package-smoke, windows-test-portability, website]runs-on: ubuntu-latestconcurrency:group: github-pages@@ -514,7 +577,7 @@ jobs:# Disable Git-connected automatic deployments so they cannot bypass these gates.deploy-cloudflare:if: github.event_name == 'push' && github.ref == 'refs/heads/main' && vars.CLOUDFLARE_PAGES_PROJECT != ''- needs: [test, webm-artifact, zip-freshness, published-update-manifest, package-smoke, windows-test-portability, website]+ needs: [test, canonical-test, webm-artifact, zip-freshness, published-update-manifest, package-smoke, windows-test-portability, website]runs-on: ubuntu-latestconcurrency:group: cloudflare-pagesdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 140fd01f..1acbd331 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -26,7 +26,7 @@ jobs:shell: pwshrun: scripts/windows-path-fixtures.ps1 -NodeVersion '${{ matrix.node-version }}'- name: Verify maintained Windows path contracts- run: node scripts/run-windows-path-tests.mjs+ run: node scripts/run-windows-path-tests.mjs ${{ matrix.node-version == 24 && '--smoke' || '' }}env:ARCHIFY_REQUIRE_WINDOWS_8DOT3: '1'ARCHIFY_REQUIRE_WINDOWS_REAL_PATHS: '1'diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 6d7e8256..7085b43b 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -143,6 +143,24 @@ their responsibility is affected and in complete verification. The separatebrowser, WebM, Windows, and package gates retain their distinct claims. Do notrepeat an unchanged complete run locally just because CI is also running it.+For full CI, Node 22 runs every discovered test file across two independent+machines using `node scripts/run-tests.mjs --shard=1/2` and `--shard=2/2`.+One shard also runs generated checks and the Hermes adapter contract once,+using the same installed dependencies. The existing `test (22)` check requires+both shards to succeed without reinstalling dependencies afterward. Other scopes do not+start these shards. Node 18, 20 and 24 compatibility checks start after scope+classification, without waiting for the complete regression shards.+`--list --shard=1/2` shows the selected files; shards cannot+be combined with explicit files or test-name filtering. Locally and in tagged+releases, `npm run test:full` still runs the complete inventory without sharding.++The Windows Node 22 lane owns the complete filesystem and fault-injection+matrices. Node 24 runs the core CLI smoke instead of repeating those matrices.+Both lanes, including tagged releases, still run the controlled case-sensitive+NTFS, UNC, extended-path, and 8.3-path scenarios. Use+`node scripts/run-windows-path-tests.mjs --list` (or `--smoke --list`) to inspect+the selected groups without running tests or creating Windows fixtures.+The test runners accept `--concurrency=N` to tune the number of simultaneoustest files on Node 18.19+, for example `npm run test:focus -- test/geometry.test.mjs --concurrency=4`. Headlessrepository and compatibility runs default to the available CPU count, cappeddiff --git a/scripts/browser-test-inventory.mjs b/scripts/browser-test-inventory.mjsindex d0f7dda6..76836bfa 100644--- a/scripts/browser-test-inventory.mjs+++ b/scripts/browser-test-inventory.mjs@@ -13,7 +13,7 @@ export const browserTestFiles = ['compact-header-clearance.test.mjs','architecture-reading-size-browser.test.mjs','export-cleanup-browser.test.mjs',- 'i18n.test.mjs',+ 'i18n-browser.test.mjs','offline-font-browser.test.mjs','viewer-chrome-layout.test.mjs','semantic-radar.test.mjs',@@ -29,7 +29,7 @@ export const browserTestFiles = ['export-browser.test.mjs','sequence-note-export-browser.test.mjs','viewer-identifiers-browser.test.mjs',- 'repository-evidence.test.mjs',+ 'repository-evidence-browser.test.mjs','repository-evidence-types-browser.test.mjs','tree-branches-browser.test.mjs','class-motion-browser.test.mjs',diff --git a/scripts/package-smoke.mjs b/scripts/package-smoke.mjsindex 617636f2..846c93f9 100644--- a/scripts/package-smoke.mjs+++ b/scripts/package-smoke.mjs@@ -7,6 +7,7 @@ import path from 'node:path';import { fileURLToPath, pathToFileURL } from 'node:url';import { assertThirdPartyNotices } from './third-party-notices-contract.mjs';+import { verifyPackagedUpdateChecker } from './package-update-smoke.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));const repoRoot = path.resolve(__dirname, '..');@@ -132,67 +133,7 @@ try {throw new Error('packaged skill-release.json does not match the package release identity');}- const updateCheck = spawnSync(process.execPath, [updateChecker], {- cwd: skillRoot,- encoding: 'utf8',- env: { ...process.env, ARCHIFY_UPDATE_CHECK_DISABLED: '1' },- });- if (updateCheck.status !== 0) {- throw new Error(`packaged update checker failed with ${updateCheck.status}\n${updateCheck.stderr}`);- }- let updateReceipt;- try {- updateReceipt = JSON.parse(updateCheck.stdout);- } catch {- throw new Error('packaged update checker did not return valid JSON');- }- if (updateReceipt.status !== 'silent' || updateReceipt.reason !== 'disabled') {- throw new Error('packaged update checker did not honor the local disable switch');- }-- const checker = await import(pathToFileURL(updateChecker).href);- const versionCore = /^(\d+)\.(\d+)\.(\d+)/.exec(packageJson.version);- if (!versionCore) throw new Error('package version cannot produce an update-check smoke candidate');- const candidateVersion = `${versionCore[1]}.${versionCore[2]}.${BigInt(versionCore[3]) + 1n}`;- const candidate = {- schemaVersion: 1,- skillId: 'archify',- channel: 'stable',- version: candidateVersion,- publishedAt: '2026-08-28T00:00:00Z',- source: {- repository: 'https://github.com/tt-a1i/archify',- ref: `v${candidateVersion}`,- treeSha: 'a'.repeat(40),- },- artifact: { sha256: 'b'.repeat(64) },- summary: 'Package smoke candidate.',- releaseNotes: `https://github.com/tt-a1i/archify/releases/tag/v${candidateVersion}`,- severity: 'normal',- };- const notifierCache = path.join(scratch, 'update-cache');- const notifierReceipt = await checker.checkForUpdate({- cacheDirectory: notifierCache,- fetchImpl: async () => new Response(JSON.stringify(candidate), {- status: 200,- headers: { 'content-type': 'application/json', etag: '"package-smoke"' },- }),- now: () => Date.parse('2026-08-28T00:00:00Z'),- random: () => 0.5,- });- if (notifierReceipt.status !== 'update_available') {- throw new Error(`packaged update checker did not return an update candidate: ${JSON.stringify(notifierReceipt)}`);- }- const notifierSnooze = await checker.setUpdatePreference({- releasePath: path.join(skillRoot, 'skill-release.json'),- cacheDirectory: notifierCache,- eventKey: notifierReceipt.eventKey,- mode: 'snooze',- now: () => Date.parse('2026-08-28T00:00:01Z'),- });- if (notifierSnooze.status !== 'snoozed') {- throw new Error('packaged update checker did not persist an explicit snooze');- }+ await verifyPackagedUpdateChecker(skillRoot, path.join(scratch, 'update-cache'));const skill = fs.readFileSync(path.join(skillRoot, 'SKILL.md'), 'utf8');const skillReferences = [...skill.matchAll(@@ -412,8 +353,17 @@ try {const inferredBridgeHtml = path.join(scratch, 'inferred-bridge.html');fs.writeFileSync(inferredBridgePath, JSON.stringify(inferredBridge));run(['render', 'architecture', inferredBridgePath, inferredBridgeHtml]);+ run(['check', inferredBridgeHtml]);const inferredBridgeArtifact = fs.readFileSync(inferredBridgeHtml, 'utf8');- if (!inferredBridgeArtifact.includes('data-composition-points="700,130;184,130;184,330;160,330"')) {+ const bridgePoints = inferredBridgeArtifact.match(/data-edge-id="terminal-return"[^>]*data-composition-points="([^"]+)"/)?.[1]+ .split(';').map(point => point.split(',').map(Number));+ // Automatic bend positions may improve; attachment and side normals must hold.+ if (!bridgePoints || bridgePoints.length < 2+ || !bridgePoints.every(point => point.length === 2 && point.every(Number.isFinite))+ || bridgePoints[0][0] !== 700 || bridgePoints[0][1] !== 130+ || bridgePoints[1][1] !== 130 || bridgePoints[1][0] >= 700+ || bridgePoints.at(-1)[0] !== 160 || bridgePoints.at(-1)[1] !== 330+ || bridgePoints.at(-2)[1] !== 330 || bridgePoints.at(-2)[0] <= 160) {throw new Error('packaged skill did not preserve inferred endpoint normals with a side-aware bridge');}diff --git a/scripts/package-update-smoke.mjs b/scripts/package-update-smoke.mjsnew file mode 100644index 00000000..8c996552--- /dev/null+++ b/scripts/package-update-smoke.mjs@@ -0,0 +1,73 @@+import { spawnSync } from 'node:child_process';+import fs from 'node:fs';+import path from 'node:path';+import { pathToFileURL } from 'node:url';++// Exercise the update code from the actual clean package. Keeping this gate+// separate lets notifier edge cases reuse it without replaying every renderer.+export async function verifyPackagedUpdateChecker(skillRoot, cacheDirectory) {+ const updateChecker = path.join(skillRoot, 'scripts', 'check-update.mjs');+ const packageJson = JSON.parse(fs.readFileSync(path.join(skillRoot, 'package.json'), 'utf8'));+ const updateCheck = spawnSync(process.execPath, [updateChecker], {+ cwd: skillRoot,+ encoding: 'utf8',+ env: { ...process.env, ARCHIFY_UPDATE_CHECK_DISABLED: '1' },+ });+ if (updateCheck.status !== 0) {+ throw new Error(`packaged update checker failed with ${updateCheck.status}\n${updateCheck.stderr}`);+ }+ let updateReceipt;+ try {+ updateReceipt = JSON.parse(updateCheck.stdout);+ } catch {+ throw new Error('packaged update checker did not return valid JSON');+ }+ if (updateReceipt.status !== 'silent' || updateReceipt.reason !== 'disabled') {+ throw new Error('packaged update checker did not honor the local disable switch');+ }++ const checker = await import(pathToFileURL(updateChecker).href);+ const versionCore = /^(\d+)\.(\d+)\.(\d+)/.exec(packageJson.version);+ if (!versionCore) throw new Error('package version cannot produce an update-check smoke candidate');+ const candidateVersion = `${versionCore[1]}.${versionCore[2]}.${BigInt(versionCore[3]) + 1n}`;+ const candidate = {+ schemaVersion: 1,+ skillId: 'archify',+ channel: 'stable',+ version: candidateVersion,+ publishedAt: '2026-08-28T00:00:00Z',+ source: {+ repository: 'https://github.com/tt-a1i/archify',+ ref: `v${candidateVersion}`,+ treeSha: 'a'.repeat(40),+ },+ artifact: { sha256: 'b'.repeat(64) },+ summary: 'Package smoke candidate.',+ releaseNotes: `https://github.com/tt-a1i/archify/releases/tag/v${candidateVersion}`,+ severity: 'normal',+ };+ const notifierReceipt = await checker.checkForUpdate({+ cacheDirectory,+ fetchImpl: async () => new Response(JSON.stringify(candidate), {+ status: 200,+ headers: { 'content-type': 'application/json', etag: '"package-smoke"' },+ }),+ now: () => Date.parse('2026-08-28T00:00:00Z'),+ random: () => 0.5,+ });+ if (notifierReceipt.status !== 'update_available') {+ throw new Error(`packaged update checker did not return an update candidate: ${JSON.stringify(notifierReceipt)}`);+ }+ const notifierSnooze = await checker.setUpdatePreference({+ releasePath: path.join(skillRoot, 'skill-release.json'),+ cacheDirectory,+ eventKey: notifierReceipt.eventKey,+ mode: 'snooze',+ now: () => Date.parse('2026-08-28T00:00:01Z'),+ });+ if (notifierSnooze.status !== 'snoozed') {+ throw new Error('packaged update checker did not persist an explicit snooze');+ }++ return { candidateVersion, notifierReceipt };+}diff --git a/scripts/run-browser-tests.mjs b/scripts/run-browser-tests.mjsindex ab34c71a..d033958e 100644--- a/scripts/run-browser-tests.mjs+++ b/scripts/run-browser-tests.mjs@@ -1,6 +1,8 @@#!/usr/bin/env nodeimport { spawnSync } from 'node:child_process';+import fs from 'node:fs';+import os from 'node:os';import path from 'node:path';import { fileURLToPath } from 'node:url';import { findChrome } from '../archify/bin/visual-check.mjs';@@ -11,34 +13,10 @@ import { browserTestFiles as testFiles } from './browser-test-inventory.mjs';const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');let options;-let shard;try {if (new Set(testFiles).size !== testFiles.length) throw new Error('Browser inventory contains duplicate files');- const runnerArguments = [];- for (const argument of process.argv.slice(2)) {- if (argument.startsWith('--shard')) {- if (shard) throw new Error('--shard may be specified only once');- const match = /^--shard=([1-9]\d*)\/([1-9]\d*)$/.exec(argument);- if (!match) throw new Error('Use --shard=<index>/<count> with positive integers');- const index = Number(match[1]);- const count = Number(match[2]);- if (!Number.isSafeInteger(index) || !Number.isSafeInteger(count) || index > count) {- throw new Error('--shard index must be a safe integer within the shard count');- }- if (count > testFiles.length) throw new Error('--shard count would create empty browser shards');- shard = { index, count };- } else {- runnerArguments.push(argument);- }- }- if (shard && runnerArguments.some(argument => !argument.startsWith('--') || argument.startsWith('--test-name-pattern='))) {- throw new Error('--shard cannot be combined with explicit files or a test-name selection');- }- const inventory = shard- ? testFiles.filter((_, index) => index % shard.count === shard.index - 1)- : testFiles;- options = testRunnerOptions(runnerArguments, {- repoRoot, testFiles: inventory.map(file => path.join('test', file)),+ options = testRunnerOptions(process.argv.slice(2), {+ repoRoot, testFiles: testFiles.map(file => path.join('test', file)), allowShards: true,});} catch (error) {console.error(error.message);@@ -55,12 +33,20 @@ if (!chrome) {process.exit(1);}-console.error(`Browser tests: ${options.files.length} files, concurrency ${options.concurrency}${shard ? `, shard ${shard.index}/${shard.count}` : ''}`);-const result = spawnSync(process.execPath, options.args, {- cwd: repoRoot,- env: { ...process.env, ARCHIFY_CHROME: chrome },- stdio: 'inherit',-});+console.error(`Browser tests: ${options.files.length} files, concurrency ${options.concurrency}${options.shard ? `, shard ${options.shard.index}/${options.shard.count}` : ''}`);+// Browser fixtures also deliver artifacts and check for updates. Give each+// invocation its own cache, just like the ordinary repository test runner.+const updateCache = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'archify-browser-update-')));+let result;+try {+ result = spawnSync(process.execPath, options.args, {+ cwd: repoRoot,+ env: { ...process.env, ARCHIFY_CHROME: chrome, ARCHIFY_UPDATE_CACHE_DIRECTORY: updateCache },+ stdio: 'inherit',+ });+} finally {+ fs.rmSync(updateCache, { recursive: true, force: true });+}if (result.error) throw result.error;if (result.signal) console.error(`browser test runner terminated by ${result.signal}`);process.exitCode = result.signal ? 1 : (result.status ?? 1);diff --git a/scripts/run-tests.mjs b/scripts/run-tests.mjsindex 8c51dc61..bd9e1439 100644--- a/scripts/run-tests.mjs+++ b/scripts/run-tests.mjs@@ -20,7 +20,7 @@ try {// ceiling when a full run explicitly enables browser cases.const parallelism = os.availableParallelism?.() ?? os.cpus().length;const defaultConcurrency = process.env.ARCHIFY_CHROME ? 2 : Math.max(1, Math.min(4, parallelism));- options = testRunnerOptions(process.argv.slice(2), { repoRoot, testFiles, allowRequireFiles: true, defaultConcurrency });+ options = testRunnerOptions(process.argv.slice(2), { repoRoot, testFiles, allowRequireFiles: true, defaultConcurrency, allowShards: true });} catch (error) {console.error(error.message);process.exit(1);@@ -29,7 +29,7 @@ if (options.list) {console.log(options.files.join('\n'));process.exit(0);}-console.error(`Repository tests: ${options.files.length} files, concurrency ${options.concurrency}`);+console.error(`Repository tests: ${options.files.length} files, concurrency ${options.concurrency}${options.shard ? `, shard ${options.shard.index}/${options.shard.count}` : ''}`);// Delivery commands check for updates; keep that state out of the user's cache.const updateCache = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'archify-test-update-')));diff --git a/scripts/run-windows-path-tests.mjs b/scripts/run-windows-path-tests.mjsindex 32561376..c3ed5231 100644--- a/scripts/run-windows-path-tests.mjs+++ b/scripts/run-windows-path-tests.mjs@@ -16,6 +16,10 @@ import { stageCleanSkill } from './stage-clean-skill.mjs';const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');const skillRoot = path.join(repoRoot, 'archify');const cli = path.join(skillRoot, 'bin', 'archify.mjs');+const options = process.argv.slice(2);+for (const option of options) {+ if (!['--smoke', '--list'].includes(option)) throw new Error(`Unknown Windows test option: ${option}`);+}function commandFailure(label, result) {return [@@ -595,7 +599,11 @@ const portabilityPattern = ['doctor identifies an incomplete installation',].join('|');-const groups = [+// Both lanes exercise controlled NTFS/UNC/8.3 paths below. Only the canonical+// lane repeats the detailed fault matrices; the other runs public CLI contracts.+const groups = options.includes('--smoke') ? [+ ['--test', '--test-concurrency=1', 'test/core-smoke.test.mjs'],+] : [['--test', '--test-concurrency=1', ...fullSuites],['--test',@@ -605,20 +613,24 @@ const groups = [],];-await runControlledWindowsPathE2E();+if (options.includes('--list')) {+ console.log(JSON.stringify({ controlledPaths: true, groups }));+} else {+ await runControlledWindowsPathE2E();-for (const args of groups) {- const result = spawnSync(process.execPath, args, {- cwd: repoRoot,- stdio: 'inherit',- });- if (result.error) throw result.error;- if (result.signal) {- process.stderr.write(`Windows path test runner terminated by ${result.signal}\n`);- process.exitCode = 1;- break;- }- if (result.status !== 0) {- process.exitCode = result.status ?? 1;+ for (const args of groups) {+ const result = spawnSync(process.execPath, args, {+ cwd: repoRoot,+ stdio: 'inherit',+ });+ if (result.error) throw result.error;+ if (result.signal) {+ process.stderr.write(`Windows path test runner terminated by ${result.signal}\n`);+ process.exitCode = 1;+ break;+ }+ if (result.status !== 0) {+ process.exitCode = result.status ?? 1;+ }}}diff --git a/scripts/test-runner-options.mjs b/scripts/test-runner-options.mjsindex 2a9a6cdc..4b48dd90 100644--- a/scripts/test-runner-options.mjs+++ b/scripts/test-runner-options.mjs@@ -1,12 +1,13 @@import path from 'node:path';// Both runners accept exact files, never infer coverage from changed sources.-export function testRunnerOptions(argv, { repoRoot, testFiles, allowRequireFiles = false, defaultConcurrency = 2 }) {+export function testRunnerOptions(argv, { repoRoot, testFiles, allowRequireFiles = false, defaultConcurrency = 2, allowShards = false }) {let concurrency = defaultConcurrency;let explicitConcurrency = false;let list = false;let requireFiles = false;let namePattern;+ let shard;const selected = [];const knownFiles = new Map(testFiles.map(file => [path.resolve(repoRoot, file), file]));for (const argument of argv) {@@ -14,6 +15,18 @@ export function testRunnerOptions(argv, { repoRoot, testFiles, allowRequireFileslist = true;} else if (argument === '--require-files' && allowRequireFiles) {requireFiles = true;+ } else if (argument.startsWith('--shard') && allowShards) {+ if (shard) throw new Error('--shard may be specified only once');+ const match = /^--shard=([1-9]\d*)\/([1-9]\d*)$/.exec(argument);+ if (!match) throw new Error('Use --shard=<index>/<count> with positive integers');+ const index = Number(match[1]);+ const count = Number(match[2]);+ if (!Number.isSafeInteger(index) || !Number.isSafeInteger(count) || index > count) {+ throw new Error('--shard index must be a safe integer within the shard count');+ }+ if (count > testFiles.length) throw new Error('--shard count would create empty test shards');+ if (knownFiles.size !== testFiles.length) throw new Error('Test inventory contains duplicate files');+ shard = { index, count };} else if (argument.startsWith('--concurrency=')) {const value = argument.slice('--concurrency='.length);if (!/^[1-9]\d*$/.test(value) || !Number.isSafeInteger(Number(value))) {@@ -31,13 +44,16 @@ export function testRunnerOptions(argv, { repoRoot, testFiles, allowRequireFiles}namePattern = value;} else if (argument.startsWith('-')) {- throw new Error(`Unknown test runner option: ${argument}. Use --list, --concurrency=N or --test-name-pattern=<regex>`);+ throw new Error(`Unknown test runner option: ${argument}. Use --list, --concurrency=N, --test-name-pattern=<regex>${allowShards ? ' or --shard=index/count' : ''}`);} else {const file = knownFiles.get(path.resolve(repoRoot, argument));if (!file) throw new Error(`File is not in this runner's test inventory: ${argument}`);if (!selected.includes(file)) selected.push(file);}}+ if (shard && (selected.length || namePattern !== undefined)) {+ throw new Error('--shard cannot be combined with explicit files or a test-name selection');+ }if (requireFiles && selected.length === 0) {throw new Error('Focused tests require at least one explicit test file');}@@ -50,10 +66,12 @@ export function testRunnerOptions(argv, { repoRoot, testFiles, allowRequireFilesif (namePattern !== undefined && !supportsNamePattern) {throw new Error('--test-name-pattern requires Node 18.11 or newer');}- const files = selected.length ? selected : testFiles;+ const files = shard+ ? testFiles.filter((_, index) => index % shard.count === shard.index - 1)+ : selected.length ? selected : testFiles;const args = ['--test'];if (supportsConcurrency) args.push(`--test-concurrency=${concurrency}`);if (namePattern !== undefined) args.push(`--test-name-pattern=${namePattern}`);args.push(...files);- return { files, args, list, concurrency: supportsConcurrency ? concurrency : 'Node default' };+ return { files, args, list, shard, concurrency: supportsConcurrency ? concurrency : 'Node default' };}diff --git a/test/browser-gate.test.mjs b/test/browser-gate.test.mjsindex a03ce646..59f72a3d 100644--- a/test/browser-gate.test.mjs+++ b/test/browser-gate.test.mjs@@ -32,23 +32,36 @@ test('browser gate rejects an unavailable explicit browser instead of skipping',function interceptedRun(t, outcome, args = []) {const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-browser-gate-'));t.after(() => fs.rmSync(directory, { recursive: true, force: true }));+ const userCache = path.join(directory, 'user-cache');+ fs.mkdirSync(userCache);+ fs.writeFileSync(path.join(userCache, 'preserved'), 'existing cache');const preload = path.join(directory, 'capture-runner.cjs');fs.writeFileSync(preload, `const childProcess = require('node:child_process');childProcess.spawnSync = (command, args, options) => {- console.log(JSON.stringify({ command, args, cwd: options.cwd, chrome: options.env.ARCHIFY_CHROME }));+ const updateCache = options.env.ARCHIFY_UPDATE_CACHE_DIRECTORY;+ require('node:fs').writeFileSync(require('node:path').join(updateCache, 'fixture-update'), 'test receipt');+ console.log(JSON.stringify({ command, args, cwd: options.cwd, chrome: options.env.ARCHIFY_CHROME, updateCache }));return ${JSON.stringify(outcome)};};require('node:module').syncBuiltinESMExports();`);- return spawnSync(process.execPath, ['--require', preload, runner, ...args], {+ const result = spawnSync(process.execPath, ['--require', preload, runner, ...args], {cwd: directory,encoding: 'utf8',- env: { ...process.env, ARCHIFY_CHROME: process.execPath },+ env: { ...process.env, ARCHIFY_CHROME: process.execPath, ARCHIFY_UPDATE_CACHE_DIRECTORY: userCache },});+ assert.equal(fs.readFileSync(path.join(userCache, 'preserved'), 'utf8'), 'existing cache');+ assert.deepEqual(fs.readdirSync(userCache), ['preserved']);+ if (result.stdout.startsWith('{')) {+ const call = JSON.parse(result.stdout);+ assert.notEqual(call.updateCache, userCache, 'the browser gate must isolate update state');+ assert.equal(fs.existsSync(call.updateCache), false, 'temporary cache must be cleaned on success, failure and child termination');+ }+ return result;}-test('browser gate includes dedicated and mixed browser suites and enables them', (t) => {+test('browser gate includes every browser suite without repeating ordinary Node suites', (t) => {const result = interceptedRun(t, { status: 0, signal: null });assert.equal(result.status, 0, result.stderr);const call = JSON.parse(result.stdout);@@ -65,13 +78,16 @@ test('browser gate includes dedicated and mixed browser suites and enables them'for (const file of files) assert.ok(fs.existsSync(path.join(repoRoot, file)), file);const required = [...fs.readdirSync(path.join(skillRoot, '..', 'test')).filter((file) => file.endsWith('-browser.test.mjs')),- 'sequence-header-clearance.test.mjs', 'repository-evidence.test.mjs', 'i18n.test.mjs', 'semantic-radar.test.mjs', 'viewer-chrome-layout.test.mjs',+ 'sequence-header-clearance.test.mjs', 'semantic-radar.test.mjs', 'viewer-chrome-layout.test.mjs',];for (const file of required) assert.ok(files.includes(path.join('test', file)), `${file} must run in the browser gate`);+ for (const file of ['i18n.test.mjs', 'repository-evidence.test.mjs']) {+ assert.ok(!files.includes(path.join('test', file)), `${file} belongs to the ordinary Node gate`);+ }});-test('browser gate focuses maintained mixed suites and supports explicit concurrency', (t) => {- const files = ['test/i18n.test.mjs', 'test/desktop-reader-browser.test.mjs'];+test('browser gate focuses maintained browser suites and supports explicit concurrency', (t) => {+ const files = ['test/i18n-browser.test.mjs', 'test/desktop-reader-browser.test.mjs'];const result = interceptedRun(t, { status: 0 }, [files[0], path.join(repoRoot, files[1]),...(supportsConcurrency ? ['--concurrency=1'] : [])]);assert.equal(result.status, 0, result.stderr);@@ -81,7 +97,7 @@ test('browser gate focuses maintained mixed suites and supports explicit concurr});test('browser gate forwards a validated test name pattern', (t) => {- const result = interceptedRun(t, { status: 0 }, ['test/i18n.test.mjs', '--test-name-pattern=locale.*日本語']);+ const result = interceptedRun(t, { status: 0 }, ['test/i18n-browser.test.mjs', '--test-name-pattern=locale.*日本語']);if (!supportsNamePattern) {assert.equal(result.status, 1);assert.equal(result.stdout, '');@@ -91,7 +107,7 @@ test('browser gate forwards a validated test name pattern', (t) => {assert.equal(result.status, 0, result.stderr);assert.deepEqual(JSON.parse(result.stdout).args, ['--test', ...(supportsConcurrency ? ['--test-concurrency=2'] : []),- '--test-name-pattern=locale.*日本語', 'test/i18n.test.mjs',+ '--test-name-pattern=locale.*日本語', 'test/i18n-browser.test.mjs',]);});@@ -115,7 +131,7 @@ test('browser inventory can be listed without Chrome or child execution', (t) =>});test('selected browser execution still requires Chrome', () => {- const result = spawnSync(process.execPath, [runner, 'test/i18n.test.mjs'], {+ const result = spawnSync(process.execPath, [runner, 'test/i18n-browser.test.mjs'], {encoding: 'utf8', env: { ...process.env, ARCHIFY_CHROME: '' },});assert.equal(result.status, 1, result.stderr);@@ -161,7 +177,7 @@ test('browser shards are deterministic, nonempty, disjoint and cover the full maassert.equal(shards.flat().length, full.length);assert.deepEqual(shards.flat().sort(), [...full].sort());const owner = file => shards.findIndex(files => files.includes(`test/${file}`));- assert.notEqual(owner('desktop-reader-browser.test.mjs'), owner('i18n.test.mjs'));+ assert.notEqual(owner('desktop-reader-browser.test.mjs'), owner('i18n-browser.test.mjs'));assert.notEqual(owner('viewer-chrome-layout.test.mjs'), owner('reader-layout-browser.test.mjs'));});@@ -184,7 +200,7 @@ test('browser shards reject invalid, duplicate, empty or partially selected cove['--shard'], ['--shard=0/2'], ['--shard=1/0'], ['--shard=3/2'],['--shard=01/2'], ['--shard=1/2.0'], ['--shard=1/999'],['--shard=1/9007199254740992'], ['--shard=1/2', '--shard=2/2'],- ['--shard=1/2', 'test/i18n.test.mjs'],+ ['--shard=1/2', 'test/i18n-browser.test.mjs'],['--shard=1/2', '--test-name-pattern=locale'],]) {const result = interceptedRun(t, { status: 0 }, args);diff --git a/test/ci-scope.test.mjs b/test/ci-scope.test.mjsindex abd14973..ccf00cd8 100644--- a/test/ci-scope.test.mjs+++ b/test/ci-scope.test.mjs@@ -158,7 +158,7 @@ test('real Git comparison retains rename source ownership and detects added test});test('required jobs fail when classification fails or returns an unknown scope', () => {- for (const name of ['test', 'browser-regression', 'webm-decode', 'zip-freshness', 'published-update-manifest', 'package-smoke', 'windows-test-portability']) {+ for (const name of ['test', 'canonical-test', 'browser-regression', 'webm-decode', 'zip-freshness', 'published-update-manifest', 'package-smoke', 'windows-test-portability']) {const step = workflow.jobs[name].steps.find(step => step.name === 'Require successful scope checks');assert.ok(step, name);for (const [result, scope, status] of [['success', 'core', 0], ['success', 'full', 0], ['failure', 'core', 1], ['success', '', 1], ['success', 'unknown', 1]]) {@@ -170,3 +170,19 @@ test('required jobs fail when classification fails or returns an unknown scope',assert.ok(fetch.run.includes('--depth=1') && fetch.run.includes('--no-tags'));assert.equal(fetch.if, "github.event_name == 'pull_request'");});++test('canonical Node cannot pass full CI with failed, cancelled or skipped regression shards', () => {+ const step = workflow.jobs['canonical-test'].steps.find(step => step.name === 'Require complete regression shards');+ assert.equal(step.if, undefined, 'every canonical check must validate its complete regression dependency');+ assert.equal(step.env.REGRESSION_RESULT, '${{ needs.full-regression.result }}');+ assert.equal(step.env.CI_SCOPE, '${{ needs.scope.outputs.scope }}');+ for (const scope of ['full', 'core', 'docs', '', 'unknown']) {+ for (const result of ['success', 'failure', 'cancelled', 'skipped', '']) {+ const expected = scope === 'full' ? result === 'success' : ['core', 'docs'].includes(scope) && result === 'skipped';+ const run = spawnSync('bash', ['-e', '-c', step.run], {+ env: { ...process.env, CI_SCOPE: scope, REGRESSION_RESULT: result },+ });+ assert.equal(run.status, expected ? 0 : 1, `${scope}/${result}`);+ }+ }+});diff --git a/test/clean-skill-staging.test.mjs b/test/clean-skill-staging.test.mjsindex 466e8cb3..5a03a272 100644--- a/test/clean-skill-staging.test.mjs+++ b/test/clean-skill-staging.test.mjs@@ -91,6 +91,34 @@ test('clean staging rejects a packaged notice that diverges from the repository}});+test('clean staging rejects untracked required release inputs before creating output', () => {+ const root = repositoryFixture();+ const destination = path.join(root, 'staged-skill');+ try {+ git(root, ['add', '.']);+ for (const relative of [+ 'THIRD_PARTY_NOTICES.md',+ 'archify/LICENSE',+ 'archify/THIRD_PARTY_NOTICES.md',+ 'archify/skill-release.json',+ 'archify/scripts/check-update.mjs',+ 'archify/scripts/update-contract.mjs',+ 'archify/renderers/shared/generated-validators.mjs',+ ]) {+ git(root, ['rm', '--cached', '-f', relative]);+ assert.throws(() => stageCleanSkill({ repoRoot: root, destination }), error => {+ assert.ok(error.message.includes(relative), error.message);+ assert.match(error.message, /not tracked by Git/);+ return true;+ });+ assert.equal(fs.existsSync(destination), false, relative);+ git(root, ['add', relative]);+ }+ } finally {+ fs.rmSync(root, { recursive: true, force: true });+ }+});+test('clean staging requires shared path runtimes only when packaged code imports them', () => {const root = repositoryFixture();const destination = path.join(root, 'staged-skill');diff --git a/test/compatibility-gate.test.mjs b/test/compatibility-gate.test.mjsindex b8d20414..6ea2ee0b 100644--- a/test/compatibility-gate.test.mjs+++ b/test/compatibility-gate.test.mjs@@ -22,10 +22,33 @@ test('generated checks have one explicit entrypoint separate from core feedback'});test('all maintained Node check names remain and publication uses exhaustive verification', () => {- assert.deepEqual(ci.jobs.test.strategy.matrix['node-version'], [18, 20, 22, 24]);+ assert.deepEqual(ci.jobs.test.strategy.matrix['node-version'], [18, 20, 24]);assert.equal(ci.jobs.test.name, undefined);- const full = ci.jobs.test.steps.find(step => step.run === 'npm run test:full');- assert.ok(full && full.if.includes("scope == 'full'") && full.if.includes('== 22'));+ assert.equal(ci.jobs.test.needs, 'scope', 'short compatibility checks must not wait for complete regression');+ const canonical = ci.jobs['canonical-test'];+ assert.equal(canonical.name, 'test (22)');+ assert.deepEqual(canonical.needs, ['scope', 'full-regression']);+ assert.ok(canonical.steps.some(step => step.with?.['node-version'] === 22));+ const full = ci.jobs['full-regression'];+ assert.equal(full.if, "needs.scope.outputs.scope == 'full'");+ assert.equal(full.strategy['fail-fast'], false);+ assert.deepEqual(full.strategy.matrix.shard, [1, 2]);+ assert.ok(full.steps.some(step => step.with?.['node-version'] === 22));+ assert.ok(full.steps.some(step => step.run === 'node scripts/run-tests.mjs --shard=${{ matrix.shard }}/2'));+ const generated = full.steps.find(step => step.run === 'npm run test:generated');+ assert.equal(generated.if, 'matrix.shard == 2', 'complete generated checks run once inside a regression shard');+ const hermes = full.steps.find(step => step.run === 'node --test integrations/hermes-agent/test/plugin-contract.test.mjs');+ assert.equal(hermes.if, 'matrix.shard == 2');+ assert.equal(full.steps.filter(step => step.run === 'npm run test:generated').length, 1);+ const coreGenerated = canonical.steps.find(step => step.run === 'npm run test:generated');+ assert.equal(coreGenerated.if, "needs.scope.outputs.scope == 'core' && needs.scope.outputs.generated == 'true'");+ for (const step of canonical.steps.filter(step => step.uses || step.name === 'Install renderer dependencies')) {+ assert.equal(step.if, "needs.scope.outputs.scope == 'core'", 'full aggregation must not bootstrap another runtime');+ }+ for (const name of ['deploy-pages', 'deploy-cloudflare']) {+ assert.ok(ci.jobs[name].needs.includes('test'));+ assert.ok(ci.jobs[name].needs.includes('canonical-test'));+ }assert.ok(ci.jobs.test.steps.some(step => step.run === 'npm run test:compat'));assert.ok(release.jobs.release.steps.some(step => step.run === 'npm run test:full'));assert.ok(!release.jobs.release.steps.some(step => step.run === 'npm test'));diff --git a/test/core-smoke.test.mjs b/test/core-smoke.test.mjsindex 3769fa8c..0c3cacf3 100644--- a/test/core-smoke.test.mjs+++ b/test/core-smoke.test.mjs@@ -78,7 +78,8 @@ function assertDiagnostic(receipt, code) {}test('core smoke: public CLI diagrams, compatibility and delivery safety', async (t) => {- const workspace = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'archify-core-')));+ // Resolve Windows 8.3 temp aliases using the same native path semantics as delivery.+ const workspace = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), 'archify-core-')));t.after(() => fs.rmSync(workspace, { recursive: true, force: true }));const runtimeTmp = path.join(workspace, 'runtime-temp');fs.mkdirSync(runtimeTmp);diff --git a/test/delivery-update.test.mjs b/test/delivery-update.test.mjsindex 1c859459..4184c1e1 100644--- a/test/delivery-update.test.mjs+++ b/test/delivery-update.test.mjs@@ -84,21 +84,33 @@ test('service deadline kills a blocked child and leaves no later result', asyncassert.deepEqual(fs.readdirSync(root).sort(), ['blocker.mjs', 'skill-release.json']);});-test('a slow network records its failed check before the deadline and backs off', async (t) => {+test('a network timeout persists failure backoff for subsequent checks and deliveries', async (t) => {const testFixture = fixture(t);const calls = path.join(testFixture.root, 'fetch-calls');+ const fetchImpl = (_url, { signal }) => {+ fs.appendFileSync(calls, 'x');+ return new Promise((_resolve, reject) => signal.addEventListener('abort', () => reject(signal.reason), { once: true }));+ };+ // Exercise the real network abort and persistence without assuming that a+ // child can start, abort its request and publish under a 600ms CPU/I/O budget.+ // The separate blocked-child test retains the service's hard deadline.+ const first = await checkForUpdate({ ...testFixture, fetchImpl, timeoutMs: 25 });+ assert.equal(first.reason, 'check-failed');+ const second = await checkForUpdate({ ...testFixture, fetchImpl, timeoutMs: 25 });+ assert.equal(second.status, 'silent');+ assert.equal(second.reason, 'cache-valid');+ assert.equal(fs.readFileSync(calls, 'utf8'), 'x');const preload = path.join(testFixture.root, 'slow-fetch.mjs');fs.writeFileSync(preload, `import fs from 'node:fs';-globalThis.fetch = (_url, { signal }) => {+globalThis.fetch = () => {fs.appendFileSync(${JSON.stringify(calls)}, 'x');- return new Promise((_resolve, reject) => signal.addEventListener('abort', () => reject(signal.reason)));+ throw new Error('a recorded failure must back off before another delivery fetch');};`);const slowEnv = { ...env(testFixture), NODE_OPTIONS: `--import=${pathToFileURL(preload).href}` };- const first = await startDeliveryUpdateCheck({ env: slowEnv, deadlineMs: 600 });- assert.equal(first.reason, 'check-failed');- const second = await startDeliveryUpdateCheck({ env: slowEnv, deadlineMs: 600 });- assert.equal(second.status, 'unavailable');+ const delivered = await startDeliveryUpdateCheck({ env: slowEnv });+ assert.equal(delivered.status, 'unavailable');+ assert.equal(delivered.reason, 'cache-valid');assert.equal(fs.readFileSync(calls, 'utf8'), 'x');});diff --git a/test/export-browser.test.mjs b/test/export-browser.test.mjsindex 620099c6..17bd7ca8 100644--- a/test/export-browser.test.mjs+++ b/test/export-browser.test.mjs@@ -396,8 +396,11 @@ test('Export preserves menu, clipboard, semantic cards and recording lifecycles'});await t.test('recording constructor/error/empty failures clean up and public run disables WebM', async () => {+ await load();+ let previousTracks = 0;+ // Consecutive failures must release their own resources without a page+ // reload doing the cleanup for them. Keep the unsupported startup separate.for (const fault of ['constructor','error','empty']) {- await load();await run(`window.MediaRecorder=class {static isTypeSupported(){return true;}constructor(){if(${JSON.stringify(fault)}==='constructor')throw new Error('recorder constructor');this.state='inactive';this.mimeType='video/webm';}@@ -405,7 +408,11 @@ test('Export preserves menu, clipboard, semantic cards and recording lifecycles'requestData(){} stop(){this.state='inactive';this.onstop();}};`);assert.equal(await run('Archify.motion.recordWebm({duration:250,fps:10}).then(()=>false,()=>true)'),true);- const state=await record('webm-'+fault);assert.ok(state.urls.every(u=>u.revoked));assert.ok(state.tracks.length>0);assert.ok(state.tracks.every(s=>s==='ended'));+ const state=await record('webm-'+fault);+ assert.ok(state.urls.every(u=>u.revoked));+ assert.ok(state.tracks.length>previousTracks, `${fault}: the attempt must acquire its own stream`);+ assert.ok(state.tracks.every(s=>s==='ended'));+ previousTracks = state.tracks.length;}await load({extra:'&fault=unsupported'});await run(`Archify.exportMenu.run('webm')`);diff --git a/test/geometry.test.mjs b/test/geometry.test.mjsindex c9f83aba..c87d85c1 100644--- a/test/geometry.test.mjs+++ b/test/geometry.test.mjs@@ -7,6 +7,7 @@import { test } from 'node:test';import assert from 'node:assert/strict';+import { readFileSync } from 'node:fs';import {rectsOverlap,segmentIntersectsRect,@@ -953,6 +954,23 @@ test('unknown semantic sigils fail closed to a neutral role stamp', () => {assert.match(sigil, /scale\(1\)/);});+test('every authored icon has SVG geometry while keeping its node tone and placement', () => {+ const icons = JSON.parse(readFileSync(new URL('../archify/schemas/common.schema.json', import.meta.url), 'utf8')).$defs.nodeIcon.enum;+ for (const icon of icons) {+ const svg = renderSemanticSigil('frontend', { x: 12, y: 18, icon });+ if (icon === 'none') {+ assert.equal(svg, '', 'hidden icons must not reserve SVG content');+ } else {+ assert.match(svg, new RegExp(`data-semantic-sigil="${icon}"`), icon);+ assert.match(svg, /<(?:path|circle|ellipse|rect)\b/, `${icon}: accepted icons need visible geometry`);+ assert.match(svg, /aria-hidden="true"/);+ assert.match(svg, /class="semantic-sigil s-frontend"/, `${icon}: icon override must not change the node's tone`);+ assert.match(svg, /transform="translate\(12 18\) scale\(0\.6875\)"/);+ assert.doesNotMatch(svg, /#[0-9a-f]{3,8}|rgba?\(/i, `${icon}: colors must follow the theme`);+ }+ }+});+test('suggestLabelObstacleFix includes rects and labelAt/labelDy hints', () => {const labelRect = { x: 100, y: 180, width: 48, height: 14, label: '写入' };const obstacle = { id: 'memtool', x: 30, y: 130, width: 230, height: 58 };diff --git a/test/helpers/i18n-fixture.mjs b/test/helpers/i18n-fixture.mjsnew file mode 100644index 00000000..54460d9e--- /dev/null+++ b/test/helpers/i18n-fixture.mjs@@ -0,0 +1,185 @@+import assert from 'node:assert/strict';+import { spawnSync } from 'node:child_process';+import { createHash } from 'node:crypto';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { after } from 'node:test';+import { fileURLToPath } from 'node:url';++export const skillRoot = fileURLToPath(new URL('../../archify/', import.meta.url));+export const cli = path.join(skillRoot, 'bin/archify.mjs');+export const ES_TRANSLATIONS = JSON.parse(fs.readFileSync(path.join(skillRoot, 'locales/es.json'), 'utf8'));++// locales/ holds the package-owned catalogs that meta.locale selects through+// locales/manifest.json. examples/locales/fr.partial.json is the genericity+// proof — an unbundled language, deliberately partial to also exercise the+// coverage/fallback contract.+export const KO_TRANSLATIONS = JSON.parse(fs.readFileSync(path.join(skillRoot, 'locales/ko.json'), 'utf8'));+export const FR_PARTIAL_TRANSLATIONS = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples/locales/fr.partial.json'), 'utf8'));+export const MANIFEST = JSON.parse(fs.readFileSync(path.join(skillRoot, 'locales/manifest.json'), 'utf8'));++export const EXAMPLES = {+ architecture: 'web-app.architecture.json',+ workflow: 'agent-tool-call.workflow.json',+ sequence: 'cache-miss-request.sequence.json',+ dataflow: 'product-analytics.dataflow.json',+ lifecycle: 'agent-run.lifecycle.json',+};++export function example(type) {+ return JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples', EXAMPLES[type]), 'utf8'));+}++const AUTHORED_TEXT_KEYS = new Set([+ 'title',+ 'subtitle',+ 'label',+ 'sublabel',+ 'tag',+ 'note',+ 'context',+ 'responsibility',+ 'classification',+ 'step',+]);++export function authoredExample(type, locale) {+ const document = example(type);+ const authored = [];+ let authoredIndex = 0;+ const nextAuthoredText = () => {+ authoredIndex += 1;+ const value = locale === 'zh-CN'+ ? `文案${String(authoredIndex).padStart(2, '0')}`+ : locale === 'ko'+ ? `문구${String(authoredIndex).padStart(2, '0')}`+ : `Copy${String(authoredIndex).padStart(2, '0')}`;+ authored.push(value);+ return value;+ };+ const rewrite = (value, path = []) => {+ if (Array.isArray(value)) {+ value.forEach((item, index) => rewrite(item, [...path, index]));+ return;+ }+ if (!value || typeof value !== 'object') return;+ for (const [key, child] of Object.entries(value)) {+ if (typeof child === 'string' && AUTHORED_TEXT_KEYS.has(key)) {+ value[key] = nextAuthoredText();+ } else if (key === 'items' && path.includes('cards') && Array.isArray(child)) {+ value[key] = child.map((item) => (typeof item === 'string' ? nextAuthoredText() : item));+ } else {+ rewrite(child, [...path, key]);+ }+ }+ };++ rewrite(document);+ document.meta.locale = locale;+ if (locale === 'ko') document.meta.translations = KO_TRANSLATIONS;+ if (!document.meta.subtitle) document.meta.subtitle = nextAuthoredText();+ return { document, authored };+}++export function localeDocument(type, meta) {+ const document = example(type);+ delete document.meta.subtitle;+ Object.assign(document.meta, meta);+ return document;+}++// Each suite owns its files; sharing fixture code never shares rendered output.+export function createLocaleFixture() {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-i18n-'));+ after(() => fs.rmSync(tmp, { recursive: true, force: true }));+ let sequence = 0;++ function run(type, document, command = 'render') {+ const id = sequence++;+ const input = path.join(tmp, `${id}-${type}.json`);+ const output = path.join(tmp, `${id}-${type}.html`);+ fs.writeFileSync(input, JSON.stringify(document));+ const args = command === 'render'+ ? [cli, 'render', type, input, output]+ : [cli, 'validate', type, input, '--json'];+ const result = spawnSync(process.execPath, args, { cwd: skillRoot, encoding: 'utf8' });+ return {+ ...result,+ output,+ html: result.status === 0 && command === 'render' ? fs.readFileSync(output, 'utf8') : '',+ };+ }++ function deliverKoreanFixture() {+ const fixture = path.join(skillRoot, '..', 'test', 'fixtures/korean-locale.architecture.json');+ const source = JSON.parse(fs.readFileSync(fixture, 'utf8'));+ assert.equal(source.meta.locale, 'ko');+ assert.match(source.meta.title, /[가-힣]/);++ const validate = spawnSync(process.execPath, [cli, 'validate', 'architecture', fixture, '--json'], {+ cwd: skillRoot,+ encoding: 'utf8',+ });+ assert.equal(validate.status, 0, validate.stderr || validate.stdout);+ const validation = JSON.parse(validate.stdout);+ assert.equal(validation.ok, true);+ assert.equal(validation.command, 'validate');++ const artifact = path.join(tmp, 'korean-locale-fixture.html');+ const deliver = spawnSync(+ process.execPath,+ [cli, 'deliver', 'architecture', fixture, artifact, '--quality', 'showcase', '--json'],+ { cwd: skillRoot, encoding: 'utf8' },+ );+ assert.equal(deliver.status, 0, deliver.stderr || deliver.stdout);+ const delivery = JSON.parse(deliver.stdout);+ assert.equal(delivery.ok, true);+ assert.equal(delivery.command, 'deliver');+ assert.equal(delivery.type, 'architecture');+ assert.match(delivery.artifact.sha256, /^[a-f0-9]{64}$/);+ assert.equal(delivery.artifact.bytes, fs.statSync(artifact).size);+ assert.equal(delivery.artifact.sha256, createHash('sha256').update(fs.readFileSync(artifact)).digest('hex'));+ return { fixture, artifact, delivery };+ }++ function deliverJapaneseFixture() {+ const fixture = path.join(skillRoot, '..', 'test', 'fixtures/japanese-locale.architecture.json');+ const source = JSON.parse(fs.readFileSync(fixture, 'utf8'));+ assert.equal(source.meta.locale, 'ja');+ assert.match(source.meta.title, /[-ヿ一-鿿]/);++ const validate = spawnSync(process.execPath, [cli, 'validate', 'architecture', fixture, '--json'], {+ cwd: skillRoot,+ encoding: 'utf8',+ });+ assert.equal(validate.status, 0, validate.stderr || validate.stdout);+ const validation = JSON.parse(validate.stdout);+ assert.equal(validation.ok, true);+ assert.equal(validation.command, 'validate');++ const artifact = path.join(tmp, 'japanese-locale-fixture.html');+ const deliver = spawnSync(+ process.execPath,+ [cli, 'deliver', 'architecture', fixture, artifact, '--quality', 'showcase', '--json'],+ { cwd: skillRoot, encoding: 'utf8' },+ );+ assert.equal(deliver.status, 0, deliver.stderr || deliver.stdout);+ const delivery = JSON.parse(deliver.stdout);+ assert.equal(delivery.ok, true);+ assert.equal(delivery.command, 'deliver');+ assert.equal(delivery.type, 'architecture');+ assert.match(delivery.artifact.sha256, /^[a-f0-9]{64}$/);+ assert.equal(delivery.artifact.bytes, fs.statSync(artifact).size);+ assert.equal(delivery.artifact.sha256, createHash('sha256').update(fs.readFileSync(artifact)).digest('hex'));+ return { fixture, artifact, delivery };+ }++ function cliJson(args) {+ const result = spawnSync(process.execPath, [cli, ...args], { cwd: tmp, encoding: 'utf8' });+ assert.equal(result.status, 0, result.stderr || result.stdout);+ return JSON.parse(result.stdout);+ }++ return { tmp, run, deliverKoreanFixture, deliverJapaneseFixture, cliJson };+}diff --git a/test/helpers/repository-evidence-fixture.mjs b/test/helpers/repository-evidence-fixture.mjsnew file mode 100644index 00000000..59f3ba76--- /dev/null+++ b/test/helpers/repository-evidence-fixture.mjs@@ -0,0 +1,53 @@+import assert from 'node:assert/strict';+import { execFileSync, spawnSync } from 'node:child_process';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++export const skillRoot = fileURLToPath(new URL('../../archify/', import.meta.url));+export const cli = path.join(skillRoot, 'bin', 'archify.mjs');++export function git(repo, ...args) {+ return execFileSync('git', ['-C', repo, ...args], { encoding: 'utf8' }).trim();+}++export function fixture() {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-evidence-repo-'));+ fs.mkdirSync(path.join(root, 'src'), { recursive: true });+ fs.writeFileSync(path.join(root, 'src', 'router.js'), 'export function route(input) {\n return input.kind;\n}\n');+ fs.writeFileSync(path.join(root, 'src', 'store.js'), 'export const store = new Map();\n');+ git(root, 'init');+ git(root, 'config', 'user.name', 'Archify Tests');+ git(root, 'config', 'user.email', '[email protected]');+ git(root, 'remote', 'add', 'origin', '[email protected]:example/evidence-repo.git');+ git(root, 'add', '.');+ git(root, 'commit', '-m', 'fixture');+ const revision = git(root, 'rev-parse', 'HEAD');++ const diagram = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples', 'web-app.architecture.json'), 'utf8'));+ diagram.meta.repository = {+ url: 'https://github.com/example/evidence-repo',+ revision,+ };+ diagram.components[0].sources = [+ { path: 'src/router.js', line: 1, end_line: 3, label: 'Request router' },+ { path: 'src/store.js', line: 1 },+ ];+ const input = path.join(root, 'diagram.architecture.json');+ fs.writeFileSync(input, JSON.stringify(diagram, null, 2));+ return { root, revision, diagram, input };+}++export function run(args) {+ return spawnSync(process.execPath, [cli, ...args], {+ cwd: skillRoot,+ encoding: 'utf8',+ });+}++export function evidencePayload(html) {+ const match = html.match(/<script id="archify-source-evidence-data" type="application\/json">([\s\S]*?)<\/script>/);+ assert.ok(match, 'verified evidence payload missing');+ return JSON.parse(match[1]);+}diff --git a/test/i18n-browser.test.mjs b/test/i18n-browser.test.mjsnew file mode 100644index 00000000..d90137f4--- /dev/null+++ b/test/i18n-browser.test.mjs@@ -0,0 +1,304 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { spawnSync } from 'node:child_process';+import fs from 'node:fs';+import path from 'node:path';+import { pathToFileURL } from 'node:url';+import { ChromeVisualBrowser, findChrome, runVisualCheck } from '../archify/bin/visual-check.mjs';+import {+ skillRoot, cli, EXAMPLES, example, localeDocument, FR_PARTIAL_TRANSLATIONS, createLocaleFixture,+} from './helpers/i18n-fixture.mjs';++const chromePath = process.env.ARCHIFY_CHROME ? findChrome() : null;+const { tmp, run, deliverKoreanFixture, deliverJapaneseFixture, cliJson } = createLocaleFixture();++async function evaluate(browser, sessionId, expression, awaitPromise = false) {+ const response = await browser.cdp.send('Runtime.evaluate', {+ expression,+ returnByValue: true,+ awaitPromise,+ }, sessionId);+ if (response.exceptionDetails) {+ throw new Error(response.exceptionDetails.exception?.description+ || response.exceptionDetails.text+ || 'browser evaluation failed');+ }+ return response.result?.value;+}++async function loadArtifact(browser, artifactPath) {+ const sessionId = await browser.sessionPromise;+ await browser.cdp.send('Emulation.setDeviceMetricsOverride', {+ width: 1440,+ height: 900,+ deviceScaleFactor: 1,+ mobile: false,+ }, sessionId);+ const loaded = browser.cdp.waitFor('Page.loadEventFired', sessionId);+ const navigation = await browser.cdp.send('Page.navigate', {+ url: pathToFileURL(artifactPath).href,+ }, sessionId);+ if (navigation.errorText) throw new Error(`Chrome navigation failed: ${navigation.errorText}`);+ await loaded;+ await evaluate(browser, sessionId, `new Promise(function (resolve) {+ requestAnimationFrame(function () { requestAnimationFrame(function () { resolve(true); }); });+ })`, true);+ return sessionId;+}++test('visual-check binds the delivered Korean fixture to viewport and theme receipts', {+ skip: chromePath ? false : 'Set ARCHIFY_CHROME to collect artifact-bound visual-check evidence for the Korean fixture.',+}, () => {+ const { artifact, delivery } = deliverKoreanFixture();+ const visual = spawnSync(process.execPath, [cli, 'visual-check', artifact, '--json'], {+ cwd: skillRoot,+ encoding: 'utf8',+ env: { ...process.env, ARCHIFY_CHROME: chromePath },+ });+ assert.ok([0, 1].includes(visual.status), visual.stderr || visual.stdout);+ const receipt = JSON.parse(visual.stdout);+ assert.equal(receipt.command, 'visual-check');+ assert.equal(receipt.visualReview, 'pending');+ assert.equal(receipt.chrome.status, 'available');+ assert.equal(receipt.readability.status, 'pass');+ assert.equal(receipt.viewerChrome.status, 'pass');+ assert.equal(receipt.captures.status, 'pass');+ assert.equal(receipt.artifact.sha256, delivery.artifact.sha256);+ assert.equal(receipt.artifact.bytes, delivery.artifact.bytes);+ assert.equal(+ receipt.containment.viewports.every((viewport) => viewport.overflowX === false),+ true,+ 'Korean fixture introduced horizontal overflow',+ );+});++test('visual-check binds the delivered Japanese fixture to viewport and theme receipts', {+ skip: chromePath ? false : 'Set ARCHIFY_CHROME to collect artifact-bound visual-check evidence for the Japanese fixture.',+}, () => {+ const { artifact, delivery } = deliverJapaneseFixture();+ const visual = spawnSync(process.execPath, [cli, 'visual-check', artifact, '--json'], {+ cwd: skillRoot,+ encoding: 'utf8',+ env: { ...process.env, ARCHIFY_CHROME: chromePath },+ });+ assert.ok([0, 1].includes(visual.status), visual.stderr || visual.stdout);+ const receipt = JSON.parse(visual.stdout);+ assert.equal(receipt.command, 'visual-check');+ assert.equal(receipt.visualReview, 'pending');+ assert.equal(receipt.chrome.status, 'available');+ assert.equal(receipt.readability.status, 'pass');+ assert.equal(receipt.viewerChrome.status, 'pass');+ assert.equal(receipt.captures.status, 'pass');+ assert.equal(receipt.artifact.sha256, delivery.artifact.sha256);+ assert.equal(receipt.artifact.bytes, delivery.artifact.bytes);+ assert.equal(+ receipt.containment.viewports.every((viewport) => viewport.overflowX === false),+ true,+ 'Japanese fixture introduced horizontal overflow',+ );+});++test('a passing finalize keeps locale warnings in its receipt', {+ skip: chromePath ? false : 'Set ARCHIFY_CHROME to run finalize with its browser gate.',+}, () => {+ const input = path.join(tmp, 'finalize-fr.json');+ fs.writeFileSync(input, JSON.stringify(localeDocument('architecture', { locale: 'fr', translations: FR_PARTIAL_TRANSLATIONS })));+ const summary = cliJson(['finalize', 'architecture', input, path.join(tmp, 'finalize-fr.html'), '--quality', 'showcase', '--json']);+ assert.equal(summary.ok, true);+ assert.equal(summary.status, 'pass');+ assert.deepEqual(summary.diagnostics.map((entry) => entry.code), ['i18n/translation-coverage']);+ const full = JSON.parse(fs.readFileSync(summary.evidence.receipt, 'utf8'));+ assert.deepEqual(full.diagnostics.map((entry) => entry.code), ['i18n/translation-coverage']);+});++const BROWSER_LOCALES = {+ 'zh-CN': {+ title: (type) => `浏览器本地化-${type}`,+ toolbarLabel: '图表视图控制',+ finder: { hidden: false, title: '查找节点', searchLabel: '搜索图表节点' },+ route: { hidden: false, title: '点击路径的起点', label: '清除已追踪路径' },+ exportLabel: '导出图表',+ exportMenuLabel: '导出',+ exportMenuText: /复制图表/,+ presetBadges: {+ 'signal-flow': { header: '信号流', plate: 'none' },+ blueprint: { header: '蓝图 / 修订 01', plate: '' },+ editorial: { header: '编辑风格 / 现场笔记', plate: 'ARCHIFY / 图版 04' },+ },+ shareCardFailure: '无法为分享卡片创建二维画布上下文',+ },+ es: {+ title: (type) => `Localización del navegador-${type}`,+ toolbarLabel: 'Controles de vista del diagrama',+ finder: { hidden: false, title: 'Buscar un nodo', searchLabel: 'Buscar nodos del diagrama' },+ route: { hidden: false, title: 'Haz clic donde empieza la ruta', label: 'Borrar la ruta trazada' },+ exportLabel: 'Exportar diagrama',+ exportMenuLabel: 'Exportar',+ exportMenuText: /Copiar diagrama/,+ presetBadges: {+ 'signal-flow': { header: 'FLUJO DE SEÑAL', plate: 'none' },+ blueprint: { header: 'PLANO / REV 01', plate: '' },+ editorial: { header: 'EDITORIAL / NOTA DE CAMPO', plate: 'ARCHIFY / LÁMINA 04' },+ },+ shareCardFailure: 'Contexto de lienzo 2D no disponible para Tarjeta para compartir',+ },+ ko: {+ title: (type) => `브라우저 로케일-${type}`,+ toolbarLabel: '다이어그램 보기 제어',+ finder: { hidden: false, title: '노드 찾기', searchLabel: '다이어그램 노드 검색' },+ route: { hidden: false, title: '시작 노드 선택', label: '추적된 경로 지우기' },+ exportLabel: '다이어그램 내보내기',+ exportMenuLabel: '내보내기',+ exportMenuText: /다이어그램 복사/,+ presetBadges: {+ 'signal-flow': { header: '시그널 플로우', plate: 'none' },+ blueprint: { header: '블루프린트 / 개정 01', plate: '' },+ editorial: { header: '에디토리얼 / 현장 노트', plate: 'ARCHIFY / 도판 04' },+ },+ shareCardFailure: '공유 카드에 2D 캔버스 컨텍스트를 만들 수 없습니다',+ },++};++async function assertLocalizedViewer(browser, locale, expected) {+ for (const type of Object.keys(EXAMPLES)) {+ const document = example(type);+ document.meta.locale = locale;+ const authoredTitle = expected.title(type);+ document.meta.title = authoredTitle;+ const result = run(type, document);+ assert.equal(result.status, 0, `${locale}/${type}: ${result.stderr || result.stdout}`);++ const sessionId = await loadArtifact(browser, result.output);+ const state = await evaluate(browser, sessionId, `(function () {+ var finderButton = document.getElementById('btn-node-finder');+ var routeButton = document.getElementById('btn-route-probe');+ var exportButton = document.getElementById('btn-export');+ finderButton.click();+ var finder = {+ hidden: document.getElementById('node-finder').hidden,+ title: document.getElementById('node-finder-title').textContent.trim(),+ searchLabel: document.getElementById('node-finder-input').getAttribute('aria-label')+ };+ document.getElementById('node-finder-close').click();+ routeButton.click();+ var route = {+ hidden: document.getElementById('route-probe').hidden,+ title: document.getElementById('route-probe-title').textContent.trim(),+ label: routeButton.getAttribute('aria-label')+ };+ routeButton.click();+ exportButton.click();+ var exportMenu = document.getElementById('export-menu');+ function pseudoContent(selector) {+ var content = getComputedStyle(document.querySelector(selector), '::after').content || '';+ return content.replace(/^["']|["']$/g, '');+ }+ var presetBadges = {};+ ['signal-flow', 'blueprint', 'editorial'].forEach(function (preset) {+ document.documentElement.setAttribute('data-preset', preset);+ presetBadges[preset] = {+ header: pseudoContent('.header-row'),+ plate: pseudoContent('.diagram-container')+ };+ });+ return {+ htmlLang: document.documentElement.lang,+ svgLang: document.querySelector('.diagram-container svg').getAttribute('lang'),+ heading: (document.querySelector('h1') || {}).textContent,+ toolbarLabel: document.querySelector('.diagram-nav').getAttribute('aria-label'),+ finder: finder,+ route: route,+ exportMenuOpen: exportMenu.classList.contains('open'),+ exportLabel: exportButton.getAttribute('aria-label'),+ exportMenuLabel: exportMenu.getAttribute('aria-label'),+ exportMenuText: exportMenu.textContent,+ presetBadges: presetBadges+ };+ })()`);++ assert.equal(state.htmlLang, locale, `${locale}/${type}`);+ assert.equal(state.svgLang, locale, `${locale}/${type}`);+ // Authored copy stays verbatim while the surrounding chrome localizes.+ assert.equal(state.heading, authoredTitle, `${locale}/${type}: authored heading changed`);+ assert.equal(state.toolbarLabel, expected.toolbarLabel, `${locale}/${type}`);+ assert.deepEqual(state.finder, expected.finder, `${locale}/${type}`);+ assert.deepEqual(state.route, expected.route, `${locale}/${type}`);+ assert.equal(state.exportMenuOpen, true, `${locale}/${type}`);+ assert.equal(state.exportLabel, expected.exportLabel, `${locale}/${type}`);+ assert.equal(state.exportMenuLabel, expected.exportMenuLabel, `${locale}/${type}`);+ assert.match(state.exportMenuText, expected.exportMenuText, `${locale}/${type}`);+ assert.deepEqual(state.presetBadges, expected.presetBadges, `${locale}/${type}`);++ const shareCardFailure = await evaluate(browser, sessionId, `(async function () {+ var originalGetContext = HTMLCanvasElement.prototype.getContext;+ HTMLCanvasElement.prototype.getContext = function () { return null; };+ try {+ var edge = document.querySelector('.diagram-container svg [data-edge-from][data-edge-to]');+ Archify.routeProbe.begin({ source: edge.getAttribute('data-edge-from'), focusNode: false });+ Archify.routeProbe.choose(edge.getAttribute('data-edge-to'), { updateUrl: false });+ await Archify.exportMenu.shareCard({ variant: 'route' });+ return { rejected: false, message: '' };+ } catch (error) {+ return { rejected: true, message: String(error && error.message || error) };+ } finally {+ HTMLCanvasElement.prototype.getContext = originalGetContext;+ }+ })()`, true);+ assert.deepEqual(shareCardFailure, {+ rejected: true,+ message: expected.shareCardFailure,+ }, `${locale}/${type}`);++ // Keep every locale/type's real viewport, theme, font and capture checks.+ // The delivered fixtures above retain the public visual-check CLI receipt+ // contract; this matrix calls the same checker without another CLI process.+ // Its default factory still creates a fresh Chrome profile for each artifact.+ const visual = await runVisualCheck({ artifactPath: result.output, chromePath });+ assert.ok([0, 1].includes(visual.exitCode), `${locale}/${type}: ${JSON.stringify(visual.receipt)}`);+ const receipt = visual.receipt;+ assert.equal(receipt.visualReview, 'pending', `${locale}/${type}`);+ assert.equal(receipt.chrome.status, 'available', `${locale}/${type}`);+ assert.equal(receipt.readability.status, 'pass', `${locale}/${type}`);+ assert.equal(receipt.viewerChrome.status, 'pass', `${locale}/${type}`);+ assert.equal(receipt.captures.status, 'pass', `${locale}/${type}`);+ assert.equal(+ receipt.containment.viewports.every((viewport) => viewport.overflowX === false),+ true,+ `${locale}/${type}: localized Viewer introduced horizontal overflow`,+ );+ }+}++test('real Chrome keeps zh-CN Finder, Route, Export, and accessibility UI localized in all five modes', {+ skip: chromePath ? false : 'Set ARCHIFY_CHROME to run the real browser localization regression.',+}, async () => {+ const browser = new ChromeVisualBrowser(chromePath);+ try {+ await assertLocalizedViewer(browser, 'zh-CN', BROWSER_LOCALES['zh-CN']);+ } finally {+ await browser.close();+ }+});++test('real Chrome keeps es Finder, Route, Export, and accessibility UI localized in all five modes', {+ skip: chromePath ? false : 'Set ARCHIFY_CHROME to run the real browser localization regression.',+}, async () => {+ const browser = new ChromeVisualBrowser(chromePath);+ try {+ await assertLocalizedViewer(browser, 'es', BROWSER_LOCALES.es);+ } finally {+ await browser.close();+ }+});++test('real Chrome keeps ko Finder, Route, Export, and accessibility UI localized in all five modes', {+ skip: chromePath ? false : 'Set ARCHIFY_CHROME to run the real browser localization regression.',+}, async () => {+ const browser = new ChromeVisualBrowser(chromePath);+ try {+ await assertLocalizedViewer(browser, 'ko', BROWSER_LOCALES.ko);+ } finally {+ await browser.close();+ }+});diff --git a/test/i18n.test.mjs b/test/i18n.test.mjsindex a5f1c524..13c2cc5d 100644--- a/test/i18n.test.mjs+++ b/test/i18n.test.mjs@@ -1,154 +1,31 @@import { test } from 'node:test';import assert from 'node:assert/strict';import { spawnSync } from 'node:child_process';-import { createHash } from 'node:crypto';import fs from 'node:fs';import os from 'node:os';import path from 'node:path';-import { fileURLToPath, pathToFileURL } from 'node:url';--import { ChromeVisualBrowser, findChrome } from '../archify/bin/visual-check.mjs';+import { validateSchema } from '../archify/renderers/shared/validator.mjs';+import {+ skillRoot, ES_TRANSLATIONS, KO_TRANSLATIONS, FR_PARTIAL_TRANSLATIONS,+ MANIFEST, EXAMPLES, example, authoredExample, localeDocument, createLocaleFixture,+} from './helpers/i18n-fixture.mjs';import {SUPPORTED_LOCALES,bundledLocaleFor,catalogKeys,resolveCatalog,+ resolveLocale,+ viewerCatalog,+ localizeTemplate,translateCount,translateMessage,registerLocale,validateTranslations,} from '../archify/renderers/shared/i18n.mjs';-const __dirname = path.dirname(fileURLToPath(import.meta.url));-const skillRoot = path.resolve(__dirname, '..', 'archify');-const cli = path.join(skillRoot, 'bin/archify.mjs');const templatePath = path.join(skillRoot, 'assets/template.html');-const ES_TRANSLATIONS = JSON.parse(fs.readFileSync(path.join(skillRoot, 'locales/es.json'), 'utf8'));-const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-i18n-'));-const chromePath = process.env.ARCHIFY_CHROME ? findChrome() : null;-let sequence = 0;--// locales/ holds the package-owned catalogs that meta.locale selects through-// locales/manifest.json. examples/locales/fr.partial.json is the genericity-// proof — an unbundled language, deliberately partial to also exercise the-// coverage/fallback contract.-const KO_TRANSLATIONS = JSON.parse(fs.readFileSync(path.join(skillRoot, 'locales/ko.json'), 'utf8'));-const FR_PARTIAL_TRANSLATIONS = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples/locales/fr.partial.json'), 'utf8'));-const MANIFEST = JSON.parse(fs.readFileSync(path.join(skillRoot, 'locales/manifest.json'), 'utf8'));--const EXAMPLES = {- architecture: 'web-app.architecture.json',- workflow: 'agent-tool-call.workflow.json',- sequence: 'cache-miss-request.sequence.json',- dataflow: 'product-analytics.dataflow.json',- lifecycle: 'agent-run.lifecycle.json',-};--function example(type) {- return JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples', EXAMPLES[type]), 'utf8'));-}--const AUTHORED_TEXT_KEYS = new Set([- 'title',- 'subtitle',- 'label',- 'sublabel',- 'tag',- 'note',- 'context',- 'responsibility',- 'classification',- 'step',-]);--function authoredExample(type, locale) {- const document = example(type);- const authored = [];- let authoredIndex = 0;- const nextAuthoredText = () => {- authoredIndex += 1;- const value = locale === 'zh-CN'- ? `文案${String(authoredIndex).padStart(2, '0')}`- : locale === 'ko'- ? `문구${String(authoredIndex).padStart(2, '0')}`- : `Copy${String(authoredIndex).padStart(2, '0')}`;- authored.push(value);- return value;- };- const rewrite = (value, path = []) => {- if (Array.isArray(value)) {- value.forEach((item, index) => rewrite(item, [...path, index]));- return;- }- if (!value || typeof value !== 'object') return;- for (const [key, child] of Object.entries(value)) {- if (typeof child === 'string' && AUTHORED_TEXT_KEYS.has(key)) {- value[key] = nextAuthoredText();- } else if (key === 'items' && path.includes('cards') && Array.isArray(child)) {- value[key] = child.map((item) => (typeof item === 'string' ? nextAuthoredText() : item));- } else {- rewrite(child, [...path, key]);- }- }- };-- rewrite(document);- document.meta.locale = locale;- if (locale === 'ko') document.meta.translations = KO_TRANSLATIONS;- if (!document.meta.subtitle) document.meta.subtitle = nextAuthoredText();- return { document, authored };-}--function run(type, document, command = 'render') {- const id = sequence++;- const input = path.join(tmp, `${id}-${type}.json`);- const output = path.join(tmp, `${id}-${type}.html`);- fs.writeFileSync(input, JSON.stringify(document));- const args = command === 'render'- ? [cli, 'render', type, input, output]- : [cli, 'validate', type, input, '--json'];- const result = spawnSync(process.execPath, args, { cwd: skillRoot, encoding: 'utf8' });- return {- ...result,- output,- html: result.status === 0 && command === 'render' ? fs.readFileSync(output, 'utf8') : '',- };-}--async function evaluate(browser, sessionId, expression, awaitPromise = false) {- const response = await browser.cdp.send('Runtime.evaluate', {- expression,- returnByValue: true,- awaitPromise,- }, sessionId);- if (response.exceptionDetails) {- throw new Error(response.exceptionDetails.exception?.description- || response.exceptionDetails.text- || 'browser evaluation failed');- }- return response.result?.value;-}--async function loadArtifact(browser, artifactPath) {- const sessionId = await browser.sessionPromise;- await browser.cdp.send('Emulation.setDeviceMetricsOverride', {- width: 1440,- height: 900,- deviceScaleFactor: 1,- mobile: false,- }, sessionId);- const loaded = browser.cdp.waitFor('Page.loadEventFired', sessionId);- const navigation = await browser.cdp.send('Page.navigate', {- url: pathToFileURL(artifactPath).href,- }, sessionId);- if (navigation.errorText) throw new Error(`Chrome navigation failed: ${navigation.errorText}`);- await loaded;- await evaluate(browser, sessionId, `new Promise(function (resolve) {- requestAnimationFrame(function () { requestAnimationFrame(function () { resolve(true); }); });- })`, true);- return sessionId;-}+const { tmp, run, deliverKoreanFixture, deliverJapaneseFixture, cliJson } = createLocaleFixture();test('zh-CN localizes renderer-owned output across all five modes without translating authored content', () => {assert.deepEqual(SUPPORTED_LOCALES, ['en', 'zh-CN', 'zh-TW', 'es', 'ko']);@@ -173,54 +50,6 @@ test('zh-CN localizes renderer-owned output across all five modes without transl}});-test('supplied es catalog localizes renderer-owned output across all five modes without translating authored content', () => {- assert.equal(validateTranslations(ES_TRANSLATIONS).coverage, 1);- for (const type of Object.keys(EXAMPLES)) {- const document = example(type);- const authoredTitle = document.meta.title;- document.meta.locale = 'es';- document.meta.translations = ES_TRANSLATIONS;- delete document.meta.subtitle;-- const result = run(type, document);- assert.equal(result.status, 0, `${type}: ${result.stderr || result.stdout}`);- assert.match(result.html, /^<!DOCTYPE html>\n<html lang="es"/);- assert.match(result.html, /<svg\b[^>]*\blang="es"/);- assert.ok(result.html.includes(`<title>${authoredTitle} · Diagrama</title>`), `${type}: authored title changed`);- assert.ok(result.html.includes(`<h1>${authoredTitle}</h1>`), `${type}: authored heading changed`);- assert.match(result.html, /<text\b[^>]*>Leyenda<\/text>/);- assert.match(result.html, /aria-label="Enfocar/);- assert.match(result.html, /<desc id="archify-diagram-description">Un diagrama de /);- assert.match(result.html, /"locale":"es"/);- assert.match(result.html, />Exportar diagrama</);- assert.doesNotMatch(result.html, /\{\{i18n:/);- assert.doesNotMatch(result.stderr, /has no bundled catalog/, `${type}: es unexpectedly fell back to English`);- }-});--test('ko localizes renderer-owned output across all five modes via meta.translations, without translating authored content', () => {- for (const type of Object.keys(EXAMPLES)) {- const document = example(type);- const authoredTitle = document.meta.title;- document.meta.locale = 'ko';- document.meta.translations = KO_TRANSLATIONS;- delete document.meta.subtitle;-- const result = run(type, document);- assert.equal(result.status, 0, `${type}: ${result.stderr || result.stdout}`);- assert.match(result.html, /^<!DOCTYPE html>\n<html lang="ko"/);- assert.match(result.html, /<svg\b[^>]*\blang="ko"/);- assert.ok(result.html.includes(`<title>${authoredTitle} 다이어그램</title>`), `${type}: authored title changed`);- assert.ok(result.html.includes(`<h1>${authoredTitle}</h1>`), `${type}: authored heading changed`);- assert.match(result.html, /<text\b[^>]*>범례<\/text>/);- assert.match(result.html, /aria-label="[^"]*포커스/);- assert.match(result.html, new RegExp(`<desc id="archify-diagram-description">Archify로 생성한`));- assert.match(result.html, /"locale":"ko"/);- assert.match(result.html, />다이어그램 내보내기</);- assert.doesNotMatch(result.html, /\{\{i18n:/);- }-});-test('explicit en, zh-CN, and ko preserve complete authored field inventories across all five modes', () => {for (const type of Object.keys(EXAMPLES)) {const english = authoredExample(type, 'en');@@ -286,38 +115,6 @@ test('omitted locale preserves non-English authored content and the English View}});-function deliverKoreanFixture() {- const fixture = path.join(skillRoot, '..', 'test', 'fixtures/korean-locale.architecture.json');- const source = JSON.parse(fs.readFileSync(fixture, 'utf8'));- assert.equal(source.meta.locale, 'ko');- assert.match(source.meta.title, /[가-힣]/);-- const validate = spawnSync(process.execPath, [cli, 'validate', 'architecture', fixture, '--json'], {- cwd: skillRoot,- encoding: 'utf8',- });- assert.equal(validate.status, 0, validate.stderr || validate.stdout);- const validation = JSON.parse(validate.stdout);- assert.equal(validation.ok, true);- assert.equal(validation.command, 'validate');-- const artifact = path.join(tmp, 'korean-locale-fixture.html');- const deliver = spawnSync(- process.execPath,- [cli, 'deliver', 'architecture', fixture, artifact, '--quality', 'showcase', '--json'],- { cwd: skillRoot, encoding: 'utf8' },- );- assert.equal(deliver.status, 0, deliver.stderr || deliver.stdout);- const delivery = JSON.parse(deliver.stdout);- assert.equal(delivery.ok, true);- assert.equal(delivery.command, 'deliver');- assert.equal(delivery.type, 'architecture');- assert.match(delivery.artifact.sha256, /^[a-f0-9]{64}$/);- assert.equal(delivery.artifact.bytes, fs.statSync(artifact).size);- assert.equal(delivery.artifact.sha256, createHash('sha256').update(fs.readFileSync(artifact)).digest('hex'));- return { fixture, artifact, delivery };-}-test('checked-in Korean fixture validates and delivers a ko architecture artifact', () => {const { artifact, delivery } = deliverKoreanFixture();const html = fs.readFileSync(artifact, 'utf8');@@ -332,32 +129,6 @@ test('checked-in Korean fixture validates and delivers a ko architecture artifacassert.match(delivery.artifact.sha256, /^[a-f0-9]{64}$/);});-test('visual-check binds the delivered Korean fixture to viewport and theme receipts', {- skip: chromePath ? false : 'Set ARCHIFY_CHROME to collect artifact-bound visual-check evidence for the Korean fixture.',-}, () => {- const { artifact, delivery } = deliverKoreanFixture();- const visual = spawnSync(process.execPath, [cli, 'visual-check', artifact, '--json'], {- cwd: skillRoot,- encoding: 'utf8',- env: { ...process.env, ARCHIFY_CHROME: chromePath },- });- assert.ok([0, 1].includes(visual.status), visual.stderr || visual.stdout);- const receipt = JSON.parse(visual.stdout);- assert.equal(receipt.command, 'visual-check');- assert.equal(receipt.visualReview, 'pending');- assert.equal(receipt.chrome.status, 'available');- assert.equal(receipt.readability.status, 'pass');- assert.equal(receipt.viewerChrome.status, 'pass');- assert.equal(receipt.captures.status, 'pass');- assert.equal(receipt.artifact.sha256, delivery.artifact.sha256);- assert.equal(receipt.artifact.bytes, delivery.artifact.bytes);- assert.equal(- receipt.containment.viewports.every((viewport) => viewport.overflowX === false),- true,- 'Korean fixture introduced horizontal overflow',- );-});-// examples/locales/ko.json proved the mechanism for renderer-owned Viewer// chrome; this fixture proves the other half of "complete" language support// that predates this PR (issue #458: "the renderer never translates@@ -365,38 +136,6 @@ test('visual-check binds the delivered Korean fixture to viewport and theme rece// directly in the target language, with meta.locale/meta.translations// localizing only the fixed chrome around it. Japanese is a second,// independent worked example of that same end-to-end pattern.-function deliverJapaneseFixture() {- const fixture = path.join(skillRoot, '..', 'test', 'fixtures/japanese-locale.architecture.json');- const source = JSON.parse(fs.readFileSync(fixture, 'utf8'));- assert.equal(source.meta.locale, 'ja');- assert.match(source.meta.title, /[-ヿ一-鿿]/);-- const validate = spawnSync(process.execPath, [cli, 'validate', 'architecture', fixture, '--json'], {- cwd: skillRoot,- encoding: 'utf8',- });- assert.equal(validate.status, 0, validate.stderr || validate.stdout);- const validation = JSON.parse(validate.stdout);- assert.equal(validation.ok, true);- assert.equal(validation.command, 'validate');-- const artifact = path.join(tmp, 'japanese-locale-fixture.html');- const deliver = spawnSync(- process.execPath,- [cli, 'deliver', 'architecture', fixture, artifact, '--quality', 'showcase', '--json'],- { cwd: skillRoot, encoding: 'utf8' },- );- assert.equal(deliver.status, 0, deliver.stderr || deliver.stdout);- const delivery = JSON.parse(deliver.stdout);- assert.equal(delivery.ok, true);- assert.equal(delivery.command, 'deliver');- assert.equal(delivery.type, 'architecture');- assert.match(delivery.artifact.sha256, /^[a-f0-9]{64}$/);- assert.equal(delivery.artifact.bytes, fs.statSync(artifact).size);- assert.equal(delivery.artifact.sha256, createHash('sha256').update(fs.readFileSync(artifact)).digest('hex'));- return { fixture, artifact, delivery };-}-test('checked-in Japanese fixture validates and delivers a fully-authored ja architecture artifact', () => {const { artifact, delivery } = deliverJapaneseFixture();const html = fs.readFileSync(artifact, 'utf8');@@ -416,43 +155,24 @@ test('checked-in Japanese fixture validates and delivers a fully-authored ja arcassert.match(delivery.artifact.sha256, /^[a-f0-9]{64}$/);});-test('visual-check binds the delivered Japanese fixture to viewport and theme receipts', {- skip: chromePath ? false : 'Set ARCHIFY_CHROME to collect artifact-bound visual-check evidence for the Japanese fixture.',-}, () => {- const { artifact, delivery } = deliverJapaneseFixture();- const visual = spawnSync(process.execPath, [cli, 'visual-check', artifact, '--json'], {- cwd: skillRoot,- encoding: 'utf8',- env: { ...process.env, ARCHIFY_CHROME: chromePath },- });- assert.ok([0, 1].includes(visual.status), visual.stderr || visual.stdout);- const receipt = JSON.parse(visual.stdout);- assert.equal(receipt.command, 'visual-check');- assert.equal(receipt.visualReview, 'pending');- assert.equal(receipt.chrome.status, 'available');- assert.equal(receipt.readability.status, 'pass');- assert.equal(receipt.viewerChrome.status, 'pass');- assert.equal(receipt.captures.status, 'pass');- assert.equal(receipt.artifact.sha256, delivery.artifact.sha256);- assert.equal(receipt.artifact.bytes, delivery.artifact.bytes);- assert.equal(- receipt.containment.viewports.every((viewport) => viewport.overflowX === false),- true,- 'Japanese fixture introduced horizontal overflow',- );-});-test('malformed locale tags fail schema validation in every mode', () => {- for (const locale of ['123', 'x', 'en_US', 'a'.repeat(40)]) {- for (const type of Object.keys(EXAMPLES)) {- const document = example(type);- document.meta.locale = locale;- const result = run(type, document, 'validate');- assert.notEqual(result.status, 0, `${type}: malformed locale ${locale} unexpectedly passed`);- const payload = JSON.parse(result.stdout);- assert.equal(payload.ok, false);- assert.ok(payload.diagnostics.some((entry) => entry.subject?.path === '/meta/locale'), `${type}: ${locale}`);+ const invalidLocales = ['123', 'x', 'en_US', 'a'.repeat(40)];+ for (const [index, type] of Object.keys(EXAMPLES).entries()) {+ for (const locale of invalidLocales) {+ const document = localeDocument(type, { locale });+ // The shared validator owns the complete tag matrix. Every type still+ // exercises the public CLI's structured rejection below.+ assert.throws(() => validateSchema(type, document), (error) => {+ assert.ok(error.archifyDiagnostics.some((entry) => entry.subject?.path === '/meta/locale'), `${type}: ${locale}`);+ return true;+ });}+ const locale = invalidLocales[index % invalidLocales.length];+ const result = run(type, localeDocument(type, { locale }), 'validate');+ assert.notEqual(result.status, 0, `${type}: malformed locale ${locale} unexpectedly passed`);+ const payload = JSON.parse(result.stdout);+ assert.equal(payload.ok, false);+ assert.ok(payload.diagnostics.some((entry) => entry.subject?.path === '/meta/locale'), `${type}: ${locale}`);}});@@ -460,7 +180,11 @@ test('a well-formed but unregistered locale passes validation, falls back to Eng// Region and script variants are distinct tags: none collapses onto a// bundled catalog without explicit data.for (const locale of ['fr', 'zh-HK', 'zh-Hant', 'es-MX', 'ko-KR']) {- for (const type of Object.keys(EXAMPLES)) {+ // Locale resolution and diagnostics are shared through loadDiagram.+ // Check every tag through architecture, and every renderer with fr;+ // repeating the cross-product does not exercise another fallback path.+ const types = locale === 'fr' ? Object.keys(EXAMPLES) : ['architecture'];+ for (const type of types) {const document = example(type);document.meta.locale = locale;const validated = run(type, document, 'validate');@@ -533,19 +257,19 @@ function embeddedMessages(html) {return JSON.parse(embedded[1]);}-function localeDocument(type, meta) {- const document = example(type);- delete document.meta.subtitle;- Object.assign(document.meta, meta);- return document;-}-test('bundled es and ko render from meta.locale alone in all five modes, identical to supplying the full catalog', () => {const cases = {- es: { catalog: ES_TRANSLATIONS, legend: 'Leyenda', focus: 'Enfocar', exportLabel: 'Exportar diagrama' },- ko: { catalog: KO_TRANSLATIONS, legend: '범례', focus: '포커스', exportLabel: '다이어그램 내보내기' },+ es: {+ catalog: ES_TRANSLATIONS, legend: 'Leyenda', focus: 'Enfocar', exportLabel: 'Exportar diagrama',+ titleSuffix: ' · Diagrama', description: /<desc id="archify-diagram-description">Un diagrama de /,+ },+ ko: {+ catalog: KO_TRANSLATIONS, legend: '범례', focus: '포커스', exportLabel: '다이어그램 내보내기',+ titleSuffix: ' 다이어그램', description: /<desc id="archify-diagram-description">Archify로 생성한/,+ },};for (const [locale, expected] of Object.entries(cases)) {+ assert.equal(validateTranslations(expected.catalog).coverage, 1);for (const type of Object.keys(EXAMPLES)) {const localeOnly = run(type, localeDocument(type, { locale }));assert.equal(localeOnly.status, 0, `${type}/${locale}: ${localeOnly.stderr || localeOnly.stdout}`);@@ -563,7 +287,15 @@ test('bundled es and ko render from meta.locale alone in all five modes, identicconst supplied = run(type, localeDocument(type, { locale, translations: expected.catalog }));assert.equal(supplied.status, 0, `${type}/${locale}: ${supplied.stderr || supplied.stdout}`);+ assert.equal(supplied.stderr, '', `${type}/${locale}: a complete supplied catalog should not warn`);assert.equal(supplied.html, localeOnly.html, `${type}/${locale}: supplied catalog changed existing wording`);+ // These were separate supplied-catalog renders of the same documents.+ // Keep their authored-content and accessible-description assertions here.+ const authoredTitle = example(type).meta.title;+ assert.ok(supplied.html.includes(`<title>${authoredTitle}${expected.titleSuffix}</title>`), `${type}/${locale}: authored title changed`);+ assert.ok(supplied.html.includes(`<h1>${authoredTitle}</h1>`), `${type}/${locale}: authored heading changed`);+ assert.match(supplied.html, expected.description);+ assert.doesNotMatch(supplied.html, /\{\{i18n:/);}}});@@ -574,22 +306,54 @@ test('a partial override replaces only its keys and keeps the rest of the selectes: { message: 'Cerrar panel', legend: 'Leyenda' },ko: { message: '패널 닫기', legend: '범례' },};+ // Every renderer registers its document through the shared CLI and embeds+ // that catalog through applyTemplate. Cover the rule matrix once, then+ // prove each renderer's wiring with a real one-key override.for (const [locale, expected] of Object.entries(overrides)) {- for (const type of Object.keys(EXAMPLES)) {- const result = run(type, localeDocument(type, { locale, translations: { 'viewer.common.close': expected.message } }));- assert.equal(result.status, 0, `${type}/${locale}: ${result.stderr || result.stdout}`);- assert.equal(result.stderr, '', `${type}/${locale}: a valid one-key override over a complete catalog is not a coverage gap`);- assert.match(result.html, new RegExp(`^<!DOCTYPE html>\\n<html lang="${locale}"`));- assert.match(result.html, new RegExp(`<text\\b[^>]*>${expected.legend}</text>`), `${type}/${locale}: rest of the language was lost`);- const runtime = embeddedMessages(result.html);- assert.equal(runtime.messages['viewer.common.close'], expected.message);- assert.equal(runtime.messages['viewer.common.copyLink'], translateMessage(locale, 'viewer.common.copyLink'));- }+ const bundled = resolveCatalog(locale).messages;+ const resolved = resolveCatalog(locale, { 'viewer.common.close': expected.message });+ assert.deepEqual(resolved.messages, { ...bundled, 'viewer.common.close': expected.message });+ assert.equal(resolved.messages['legend.title'], expected.legend);+ assert.deepEqual(resolved.report.fallbackKeys, []);+ assert.equal(resolved.report.override.appliedKeys, 1);+ }+ const locales = Object.keys(overrides);+ for (const [index, type] of Object.keys(EXAMPLES).entries()) {+ const locale = locales[index % locales.length];+ const expected = overrides[locale];+ const result = run(type, localeDocument(type, { locale, translations: { 'viewer.common.close': expected.message } }));+ assert.equal(result.status, 0, `${type}/${locale}: ${result.stderr || result.stdout}`);+ assert.equal(result.stderr, '', `${type}/${locale}: a valid one-key override over a complete catalog is not a coverage gap`);+ assert.match(result.html, new RegExp(`^<!DOCTYPE html>\\n<html lang="${locale}"`));+ assert.match(result.html, new RegExp(`<text\\b[^>]*>${expected.legend}</text>`), `${type}/${locale}: rest of the language was lost`);+ const runtime = embeddedMessages(result.html);+ assert.equal(runtime.messages['viewer.common.close'], expected.message);+ assert.equal(runtime.messages['viewer.common.copyLink'], translateMessage(locale, 'viewer.common.copyLink'));}});test('empty translations and equivalent tag casing select the same bundled catalog', () => {- for (const type of Object.keys(EXAMPLES)) {+ const chinese = resolveCatalog('zh-CN');+ const koreanCatalog = resolveCatalog('ko');+ assert.deepEqual(resolveCatalog('ko', {}).messages, koreanCatalog.messages);+ assert.deepEqual(resolveCatalog('ko', {}).report, koreanCatalog.report);+ const overrides = { 'viewer.common.close': '关闭面板', 'viewer.export.diagram': '导出此图' };+ for (const locale of ['zh-cn', 'zh-cN', 'ZH-cn']) {+ assert.deepEqual(resolveCatalog(locale).messages, chinese.messages);+ assert.equal(resolveCatalog(locale).report.resolvedLocale, 'zh-CN');+ try {+ registerLocale(locale, overrides);+ for (const lookup of [locale, 'zh-CN', 'ZH-cn']) {+ assert.equal(resolveLocale(lookup), 'zh-CN');+ assert.equal(translateMessage(lookup, 'viewer.common.close'), overrides['viewer.common.close']);+ assert.equal(viewerCatalog(lookup)['viewer.common.close'], overrides['viewer.common.close']);+ assert.equal(localizeTemplate('{{i18n:viewer.export.diagram}}', lookup), '导出此图');+ }+ } finally {+ registerLocale(locale);+ }+ }+ for (const [index, type] of Object.keys(EXAMPLES).entries()) {const reference = run(type, localeDocument(type, { locale: 'zh-CN' }));assert.equal(reference.status, 0, reference.stderr);const lowered = run(type, localeDocument(type, { locale: 'zh-cn' }));@@ -597,27 +361,24 @@ test('empty translations and equivalent tag casing select the same bundled catalassert.equal(lowered.stderr, '');assert.equal(lowered.html, reference.html, `${type}: zh-cn should select the zh-CN catalog and canonical lang`);- const korean = run(type, localeDocument(type, { locale: 'ko' }));- const empty = run(type, localeDocument(type, { locale: 'ko', translations: {} }));- assert.equal(empty.status, 0, empty.stderr);- assert.equal(empty.stderr, '');- assert.equal(empty.html, korean.html, `${type}: {} is not an override`);- }- // An override under an equivalent-case tag reaches every lookup path: SVG- // copy, the HTML template, and the embedded Viewer catalog.- for (const locale of ['zh-cn', 'zh-cN']) {- for (const type of Object.keys(EXAMPLES)) {- const result = run(type, localeDocument(type, {- locale,- translations: { 'viewer.common.close': '关闭面板', 'viewer.export.diagram': '导出此图' },- }));- assert.equal(result.status, 0, result.stderr);- assert.match(result.html, /^<!DOCTYPE html>\n<html lang="zh-CN"/);- const runtime = embeddedMessages(result.html);- assert.equal(runtime.locale, 'zh-CN');- assert.equal(runtime.messages['viewer.common.close'], '关闭面板', `${type}/${locale}: embedded Viewer override lost`);- assert.ok(result.html.includes('>导出此图<'), `${type}/${locale}: template override lost`);+ // The shared empty-override rule also has a real renderer witness.+ if (type === 'architecture') {+ const korean = run(type, localeDocument(type, { locale: 'ko' }));+ const empty = run(type, localeDocument(type, { locale: 'ko', translations: {} }));+ assert.equal(korean.status, 0, korean.stderr);+ assert.equal(empty.status, 0, empty.stderr);+ assert.equal(empty.stderr, '');+ assert.equal(empty.html, korean.html, '{} is not an override');}+ const locale = index % 2 ? 'zh-cN' : 'zh-cn';+ const result = run(type, localeDocument(type, { locale, translations: overrides }));+ assert.equal(result.status, 0, result.stderr);+ assert.equal(result.stderr, '');+ assert.match(result.html, /^<!DOCTYPE html>\n<html lang="zh-CN"/);+ const runtime = embeddedMessages(result.html);+ assert.equal(runtime.locale, 'zh-CN');+ assert.equal(runtime.messages['viewer.common.close'], '关闭面板', `${type}/${locale}: embedded Viewer override lost`);+ assert.ok(result.html.includes('>导出此图<'), `${type}/${locale}: template override lost`);}assert.equal(bundledLocaleFor('ZH-cn'), 'zh-CN');assert.equal(bundledLocaleFor('zh-Hant'), null);@@ -697,12 +458,6 @@ test('a document override never mutates the reusable bundled catalog', () => {assert.equal(translateMessage('es', 'viewer.common.close'), before, 'a later document without overrides reuses the bundled catalog');});-function cliJson(args) {- const result = spawnSync(process.execPath, [cli, ...args], { cwd: tmp, encoding: 'utf8' });- assert.equal(result.status, 0, result.stderr || result.stdout);- return JSON.parse(result.stdout);-}-test('validate and deliver receipts carry locale warnings as structured diagnostics without failing', () => {const input = path.join(tmp, 'receipt-fr.json');fs.writeFileSync(input, JSON.stringify(localeDocument('architecture', {@@ -730,19 +485,6 @@ test('validate and deliver receipts carry locale warnings as structured diagnostassert.equal(cliJson(['deliver', 'architecture', clean, path.join(tmp, 'receipt-ko.html'), '--json']).diagnostics, undefined);});-test('a passing finalize keeps locale warnings in its receipt', {- skip: chromePath ? false : 'Set ARCHIFY_CHROME to run finalize with its browser gate.',-}, () => {- const input = path.join(tmp, 'finalize-fr.json');- fs.writeFileSync(input, JSON.stringify(localeDocument('architecture', { locale: 'fr', translations: FR_PARTIAL_TRANSLATIONS })));- const summary = cliJson(['finalize', 'architecture', input, path.join(tmp, 'finalize-fr.html'), '--quality', 'showcase', '--json']);- assert.equal(summary.ok, true);- assert.equal(summary.status, 'pass');- assert.deepEqual(summary.diagnostics.map((entry) => entry.code), ['i18n/translation-coverage']);- const full = JSON.parse(fs.readFileSync(summary.evidence.receipt, 'utf8'));- assert.deepEqual(full.diagnostics.map((entry) => entry.code), ['i18n/translation-coverage']);-});-test('the manifest enrolls exactly the bundled catalogs, and each is complete', () => {assert.deepEqual(MANIFEST.catalogs.map(({ locale }) => locale), SUPPORTED_LOCALES);const files = fs.readdirSync(path.join(skillRoot, 'locales')).filter((file) => file.endsWith('.json') && file !== 'manifest.json').sort();@@ -790,297 +532,6 @@ test('enrolling a catalog is a data-only change and works from an unrelated work}});-const BROWSER_LOCALES = {- 'zh-CN': {- title: (type) => `浏览器本地化-${type}`,- toolbarLabel: '图表视图控制',- finder: { hidden: false, title: '查找节点', searchLabel: '搜索图表节点' },- route: { hidden: false, title: '点击路径的起点', label: '清除已追踪路径' },- exportLabel: '导出图表',- exportMenuLabel: '导出',- exportMenuText: /复制图表/,- presetBadges: {- 'signal-flow': { header: '信号流', plate: 'none' },- blueprint: { header: '蓝图 / 修订 01', plate: '' },- editorial: { header: '编辑风格 / 现场笔记', plate: 'ARCHIFY / 图版 04' },- },- shareCardFailure: '无法为分享卡片创建二维画布上下文',- },- es: {- title: (type) => `Localización del navegador-${type}`,- toolbarLabel: 'Controles de vista del diagrama',- finder: { hidden: false, title: 'Buscar un nodo', searchLabel: 'Buscar nodos del diagrama' },- route: { hidden: false, title: 'Haz clic donde empieza la ruta', label: 'Borrar la ruta trazada' },- exportLabel: 'Exportar diagrama',- exportMenuLabel: 'Exportar',- exportMenuText: /Copiar diagrama/,- presetBadges: {- 'signal-flow': { header: 'FLUJO DE SEÑAL', plate: 'none' },- blueprint: { header: 'PLANO / REV 01', plate: '' },- editorial: { header: 'EDITORIAL / NOTA DE CAMPO', plate: 'ARCHIFY / LÁMINA 04' },- },- shareCardFailure: 'Contexto de lienzo 2D no disponible para Tarjeta para compartir',- },-};--async function assertLocalizedViewer(browser, locale, expected) {- for (const type of Object.keys(EXAMPLES)) {- const document = example(type);- document.meta.locale = locale;- const authoredTitle = expected.title(type);- document.meta.title = authoredTitle;- const result = run(type, document);- assert.equal(result.status, 0, `${locale}/${type}: ${result.stderr || result.stdout}`);-- const sessionId = await loadArtifact(browser, result.output);- const state = await evaluate(browser, sessionId, `(function () {- var finderButton = document.getElementById('btn-node-finder');- var routeButton = document.getElementById('btn-route-probe');- var exportButton = document.getElementById('btn-export');- finderButton.click();- var finder = {- hidden: document.getElementById('node-finder').hidden,- title: document.getElementById('node-finder-title').textContent.trim(),- searchLabel: document.getElementById('node-finder-input').getAttribute('aria-label')- };- document.getElementById('node-finder-close').click();- routeButton.click();- var route = {- hidden: document.getElementById('route-probe').hidden,- title: document.getElementById('route-probe-title').textContent.trim(),- label: routeButton.getAttribute('aria-label')- };- routeButton.click();- exportButton.click();- var exportMenu = document.getElementById('export-menu');- function pseudoContent(selector) {- var content = getComputedStyle(document.querySelector(selector), '::after').content || '';- return content.replace(/^["']|["']$/g, '');- }- var presetBadges = {};- ['signal-flow', 'blueprint', 'editorial'].forEach(function (preset) {- document.documentElement.setAttribute('data-preset', preset);- presetBadges[preset] = {- header: pseudoContent('.header-row'),- plate: pseudoContent('.diagram-container')- };- });- return {- htmlLang: document.documentElement.lang,- svgLang: document.querySelector('.diagram-container svg').getAttribute('lang'),- heading: (document.querySelector('h1') || {}).textContent,- toolbarLabel: document.querySelector('.diagram-nav').getAttribute('aria-label'),- finder: finder,- route: route,- exportMenuOpen: exportMenu.classList.contains('open'),- exportLabel: exportButton.getAttribute('aria-label'),- exportMenuLabel: exportMenu.getAttribute('aria-label'),- exportMenuText: exportMenu.textContent,- presetBadges: presetBadges- };- })()`);-- assert.equal(state.htmlLang, locale, `${locale}/${type}`);- assert.equal(state.svgLang, locale, `${locale}/${type}`);- // Authored copy stays verbatim while the surrounding chrome localizes.- assert.equal(state.heading, authoredTitle, `${locale}/${type}: authored heading changed`);- assert.equal(state.toolbarLabel, expected.toolbarLabel, `${locale}/${type}`);- assert.deepEqual(state.finder, expected.finder, `${locale}/${type}`);- assert.deepEqual(state.route, expected.route, `${locale}/${type}`);- assert.equal(state.exportMenuOpen, true, `${locale}/${type}`);- assert.equal(state.exportLabel, expected.exportLabel, `${locale}/${type}`);- assert.equal(state.exportMenuLabel, expected.exportMenuLabel, `${locale}/${type}`);- assert.match(state.exportMenuText, expected.exportMenuText, `${locale}/${type}`);- assert.deepEqual(state.presetBadges, expected.presetBadges, `${locale}/${type}`);-- const shareCardFailure = await evaluate(browser, sessionId, `(async function () {- var originalGetContext = HTMLCanvasElement.prototype.getContext;- HTMLCanvasElement.prototype.getContext = function () { return null; };- try {- var edge = document.querySelector('.diagram-container svg [data-edge-from][data-edge-to]');- Archify.routeProbe.begin({ source: edge.getAttribute('data-edge-from'), focusNode: false });- Archify.routeProbe.choose(edge.getAttribute('data-edge-to'), { updateUrl: false });- await Archify.exportMenu.shareCard({ variant: 'route' });- return { rejected: false, message: '' };- } catch (error) {- return { rejected: true, message: String(error && error.message || error) };- } finally {- HTMLCanvasElement.prototype.getContext = originalGetContext;- }- })()`, true);- assert.deepEqual(shareCardFailure, {- rejected: true,- message: expected.shareCardFailure,- }, `${locale}/${type}`);-- // Representative visual pass: longer localized labels must not overflow.- const visual = spawnSync(process.execPath, [cli, 'visual-check', result.output, '--json'], {- cwd: skillRoot,- encoding: 'utf8',- env: { ...process.env, ARCHIFY_CHROME: chromePath },- });- assert.ok([0, 1].includes(visual.status), `${locale}/${type}: ${visual.stderr || visual.stdout}`);- const receipt = JSON.parse(visual.stdout);- assert.equal(receipt.visualReview, 'pending', `${locale}/${type}`);- assert.equal(receipt.chrome.status, 'available', `${locale}/${type}`);- assert.equal(receipt.readability.status, 'pass', `${locale}/${type}`);- assert.equal(receipt.viewerChrome.status, 'pass', `${locale}/${type}`);- assert.equal(receipt.captures.status, 'pass', `${locale}/${type}`);- assert.equal(- receipt.containment.viewports.every((viewport) => viewport.overflowX === false),- true,- `${locale}/${type}: localized Viewer introduced horizontal overflow`,- );- }-}--test('real Chrome keeps zh-CN Finder, Route, Export, and accessibility UI localized in all five modes', {- skip: chromePath ? false : 'Set ARCHIFY_CHROME to run the real browser localization regression.',-}, async () => {- const browser = new ChromeVisualBrowser(chromePath);- try {- await assertLocalizedViewer(browser, 'zh-CN', BROWSER_LOCALES['zh-CN']);- } finally {- await browser.close();- }-});--test('real Chrome keeps es Finder, Route, Export, and accessibility UI localized in all five modes', {- skip: chromePath ? false : 'Set ARCHIFY_CHROME to run the real browser localization regression.',-}, async () => {- const browser = new ChromeVisualBrowser(chromePath);- try {- await assertLocalizedViewer(browser, 'es', BROWSER_LOCALES.es);- } finally {- await browser.close();- }-});--test('real Chrome keeps ko Finder, Route, Export, and accessibility UI localized in all five modes', {- skip: chromePath ? false : 'Set ARCHIFY_CHROME to run the real browser localization regression.',-}, async () => {- const browser = new ChromeVisualBrowser(chromePath);- try {- for (const type of Object.keys(EXAMPLES)) {- const document = example(type);- document.meta.locale = 'ko';- document.meta.title = `브라우저 로케일-${type}`;- const result = run(type, document);- assert.equal(result.status, 0, `${type}: ${result.stderr || result.stdout}`);-- const sessionId = await loadArtifact(browser, result.output);- const state = await evaluate(browser, sessionId, `(function () {- var finderButton = document.getElementById('btn-node-finder');- var routeButton = document.getElementById('btn-route-probe');- var exportButton = document.getElementById('btn-export');- finderButton.click();- var finder = {- hidden: document.getElementById('node-finder').hidden,- title: document.getElementById('node-finder-title').textContent.trim(),- searchLabel: document.getElementById('node-finder-input').getAttribute('aria-label')- };- document.getElementById('node-finder-close').click();- routeButton.click();- var route = {- hidden: document.getElementById('route-probe').hidden,- title: document.getElementById('route-probe-title').textContent.trim(),- label: routeButton.getAttribute('aria-label')- };- routeButton.click();- exportButton.click();- var exportMenu = document.getElementById('export-menu');- function pseudoContent(selector) {- var content = getComputedStyle(document.querySelector(selector), '::after').content || '';- return content.replace(/^["']|["']$/g, '');- }- var presetBadges = {};- ['signal-flow', 'blueprint', 'editorial'].forEach(function (preset) {- document.documentElement.setAttribute('data-preset', preset);- presetBadges[preset] = {- header: pseudoContent('.header-row'),- plate: pseudoContent('.diagram-container')- };- });- return {- htmlLang: document.documentElement.lang,- svgLang: document.querySelector('.diagram-container svg').getAttribute('lang'),- toolbarLabel: document.querySelector('.diagram-nav').getAttribute('aria-label'),- finder: finder,- route: route,- exportMenuOpen: exportMenu.classList.contains('open'),- exportLabel: exportButton.getAttribute('aria-label'),- exportMenuLabel: exportMenu.getAttribute('aria-label'),- exportMenuText: exportMenu.textContent,- presetBadges: presetBadges- };- })()`);-- assert.equal(state.htmlLang, 'ko', type);- assert.equal(state.svgLang, 'ko', type);- assert.equal(state.toolbarLabel, '다이어그램 보기 제어', type);- assert.deepEqual(state.finder, {- hidden: false,- title: '노드 찾기',- searchLabel: '다이어그램 노드 검색',- }, type);- assert.deepEqual(state.route, {- hidden: false,- title: '시작 노드 선택',- label: '추적된 경로 지우기',- }, type);- assert.equal(state.exportMenuOpen, true, type);- assert.equal(state.exportLabel, '다이어그램 내보내기', type);- assert.equal(state.exportMenuLabel, '내보내기', type);- assert.match(state.exportMenuText, /다이어그램 복사/, type);- assert.deepEqual(state.presetBadges, {- 'signal-flow': { header: '시그널 플로우', plate: 'none' },- blueprint: { header: '블루프린트 / 개정 01', plate: '' },- editorial: { header: '에디토리얼 / 현장 노트', plate: 'ARCHIFY / 도판 04' },- }, type);-- const shareCardFailure = await evaluate(browser, sessionId, `(async function () {- var originalGetContext = HTMLCanvasElement.prototype.getContext;- HTMLCanvasElement.prototype.getContext = function () { return null; };- try {- var edge = document.querySelector('.diagram-container svg [data-edge-from][data-edge-to]');- Archify.routeProbe.begin({ source: edge.getAttribute('data-edge-from'), focusNode: false });- Archify.routeProbe.choose(edge.getAttribute('data-edge-to'), { updateUrl: false });- await Archify.exportMenu.shareCard({ variant: 'route' });- return { rejected: false, message: '' };- } catch (error) {- return { rejected: true, message: String(error && error.message || error) };- } finally {- HTMLCanvasElement.prototype.getContext = originalGetContext;- }- })()`, true);- assert.deepEqual(shareCardFailure, {- rejected: true,- message: '공유 카드에 2D 캔버스 컨텍스트를 만들 수 없습니다',- }, type);-- const visual = spawnSync(process.execPath, [cli, 'visual-check', result.output, '--json'], {- cwd: skillRoot,- encoding: 'utf8',- env: { ...process.env, ARCHIFY_CHROME: chromePath },- });- assert.ok([0, 1].includes(visual.status), `${type}: ${visual.stderr || visual.stdout}`);- const receipt = JSON.parse(visual.stdout);- assert.equal(receipt.visualReview, 'pending', type);- assert.equal(receipt.chrome.status, 'available', type);- assert.equal(receipt.readability.status, 'pass', type);- assert.equal(receipt.viewerChrome.status, 'pass', type);- assert.equal(receipt.captures.status, 'pass', type);- assert.equal(- receipt.containment.viewports.every((viewport) => viewport.overflowX === false),- true,- `${type}: localized Viewer introduced horizontal overflow`,- );- }- } finally {- await browser.close();- }-});-test('every Viewer message reference resolves through the shared catalog', () => {const template = fs.readFileSync(templatePath, 'utf8');const keys = new Set(catalogKeys());diff --git a/test/layout-rules.test.mjs b/test/layout-rules.test.mjsindex 18052aca..d6c1a13a 100644--- a/test/layout-rules.test.mjs+++ b/test/layout-rules.test.mjs@@ -18,7 +18,7 @@ import os from 'node:os';import path from 'node:path';import { fileURLToPath } from 'node:url';import { minimumReadableSourceTextPx } from '../archify/renderers/shared/desktop-readability.mjs';-import { segmentRectClearanceWithin } from '../archify/renderers/shared/geometry.mjs';+import { segmentRectClearanceWithin, segmentIntersectsRect } from '../archify/renderers/shared/geometry.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));const skillRoot = path.resolve(__dirname, '..', 'archify');@@ -1537,12 +1537,30 @@ function autoRoutePassThroughDocument(connection) {};}+function assertAutomaticRoute(html, from, to, obstacles = []) {+ const encoded = html.match(/data-composition-points="([^"]+)"/)?.[1];+ assert.ok(encoded, 'expected a rendered route');+ const points = encoded.split(';').map(point => point.split(',').map(Number));+ assert.ok(points.length >= 2 && points.every(point => point.length === 2 && point.every(Number.isFinite)));+ assert.deepEqual(points[0], from, 'route must attach to its source port');+ assert.deepEqual(points.at(-1), to, 'route must attach to its target port');+ for (let i = 1; i < points.length; i++) {+ const start = points[i - 1];+ const end = points[i];+ assert.ok((start[0] === end[0]) !== (start[1] === end[1]), 'route segments must be nonzero and orthogonal');+ for (const obstacle of obstacles) {+ assert.equal(segmentIntersectsRect({ start, end }, obstacle), false, 'route must avoid unrelated nodes');+ }+ }+ return points;+}+test('architecture: default auto route selects a safe orthogonal candidate around an unrelated component', () => {const d = autoRoutePassThroughDocument({ from: 'api', to: 'queue', variant: 'dashed' });const { code, stderr, outPath } = render('architecture', d);assert.equal(code, 0, stderr);const html = fs.readFileSync(outPath, 'utf8');- assert.match(html, /data-composition-points="560,318;856,318;856,160;880,160"/);+ assertAutomaticRoute(html, [560, 318], [880, 160], [{ x: 645, y: 130, width: 130, height: 60 }]);});test('architecture: aligned automatic endpoints still route around an unrelated component', () => {@@ -1581,7 +1599,11 @@ test('architecture: auto route enters explicit top and bottom ports perpendiculaconst { code, stderr, outPath } = render('architecture', d);assert.equal(code, 0, stderr);const html = fs.readFileSync(outPath, 'utf8');- assert.match(html, /data-composition-points="350,160;350,200;150,200;150,240"/);+ const points = assertAutomaticRoute(html, [350, 160], [150, 240]);+ assert.equal(points[1][0], 350, 'leave the bottom port vertically');+ assert.ok(points[1][1] > 160, 'leave downward');+ assert.equal(points.at(-2)[0], 150, 'enter the top port vertically');+ assert.ok(points.at(-2)[1] < 240, 'enter from above');});test('architecture: auto route preserves inferred side normals when the primary dogleg is blocked', () => {@@ -1602,8 +1624,14 @@ test('architecture: auto route preserves inferred side normals when the primaryconst { code, stderr, outPath } = render('architecture', d);assert.equal(code, 0, stderr);const html = fs.readFileSync(outPath, 'utf8');- assert.match(html, /data-composition-points="700,130;184,130;184,330;160,330"/);- assert.doesNotMatch(html, /data-composition-points="700,130;700,230;160,230;160,330"/);+ const points = assertAutomaticRoute(html, [700, 130], [160, 330], [+ { x: 220, y: 300, width: 120, height: 60 },+ { x: 400, y: 300, width: 120, height: 60 },+ ]);+ assert.equal(points[1][1], 130, 'leave the inferred left port horizontally');+ assert.ok(points[1][0] < 700, 'leave leftward');+ assert.equal(points.at(-2)[1], 330, 'enter the inferred right port horizontally');+ assert.ok(points.at(-2)[0] > 160, 'enter from the right');});test('architecture: auto route finds a multi-bend path when both side-safe doglegs are blocked', () => {diff --git a/test/node-icons.test.mjs b/test/node-icons.test.mjsindex abbb1944..49792294 100644--- a/test/node-icons.test.mjs+++ b/test/node-icons.test.mjs@@ -32,8 +32,10 @@ for (const [mode, [example, collection, index = 0]] of Object.entries(cases)) {const sigil = /<g aria-hidden="true" data-semantic-sigil="[^"]+"[^>]*>[\s\S]*?<\/g>/;const old = baseline.match(sigil)?.[0];assert.ok(old);- const icons = JSON.parse(fs.readFileSync(path.join(root, 'schemas/common.schema.json'))).$defs.nodeIcon.enum;- for (const icon of icons) {+ // geometry.test.mjs covers the full shared icon catalog. Every renderer+ // still proves override/hiding, unchanged non-icon output, brand+ // coexistence and schema rejection through its real entrypoint.+ for (const icon of ['calendar', 'none']) {spec[collection][index].icon = icon;const html = render();if (icon === 'none') {diff --git a/test/reader-layout-browser.test.mjs b/test/reader-layout-browser.test.mjsindex 9f67d6ae..6a7840c8 100644--- a/test/reader-layout-browser.test.mjs+++ b/test/reader-layout-browser.test.mjs@@ -959,7 +959,8 @@ test('Reader Layout preserves final-artifact behavior across its ownership boundassert.deepEqual(fontGate, { beforeReady: false, afterReady: true });await stable();assert.equal((await snapshot('delayed-fonts-and-content')).active, true);- await load(wide);+ // The pending-frame budget belongs to the shared waiter, not a second+ // diagram fixture. Reuse the now-settled real page and its original fonts.const result = await evaluate(`(async function () {var original = document.fonts;var release;diff --git a/test/release-package-gates.test.mjs b/test/release-package-gates.test.mjsindex fda3958d..a937008b 100644--- a/test/release-package-gates.test.mjs+++ b/test/release-package-gates.test.mjs@@ -5,8 +5,10 @@ import fs from 'node:fs';import os from 'node:os';import path from 'node:path';import { fileURLToPath, pathToFileURL } from 'node:url';+import { parse } from 'yaml';import { stageCleanSkill } from '../scripts/stage-clean-skill.mjs';+import { verifyPackagedUpdateChecker } from '../scripts/package-update-smoke.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));const repoRoot = path.resolve(__dirname, '..');@@ -220,7 +222,11 @@ test('GitHub Pages deploys the verified website artifact only after every reposiconst job = workflowJob(workflow, 'deploy-pages');assert.match(workflow, /push:\n branches: \[main, dev\]/);assert.match(job, /if: github\.event_name == 'push' && github\.ref == 'refs\/heads\/main'/);- assert.match(job, /needs: \[test, webm-artifact, zip-freshness, published-update-manifest, package-smoke, windows-test-portability, website\]/);+ const jobs = parse(workflow).jobs;+ const dependencies = jobs['deploy-pages'].needs;+ for (const gate of ['test', 'canonical-test', 'webm-artifact', 'zip-freshness', 'published-update-manifest', 'package-smoke', 'windows-test-portability', 'website']) {+ assert.ok(dependencies.includes(gate), `Pages deployment must require ${gate}`);+ }assert.match(job, /pages: write/);assert.match(job, /id-token: write/);assert.match(job, /repos\/\$\{GITHUB_REPOSITORY\}\/git\/ref\/heads\/main/);@@ -271,8 +277,7 @@ test('GitHub Pages deploys the verified website artifact only after every reposiassert.match(media, /needs: \[scope, browser-regression, webm-decode\]/);assert.match(media, /test "\$BROWSER_RESULT" = success/);assert.match(media, /test "\$WEBM_RESULT" = success/);- const renderer = workflowJob(workflow, 'test');- assert.match(renderer, /Verify community Hermes adapter/);+ assert.ok(jobs['canonical-test'].needs.includes('full-regression'), 'Pages must wait for the complete regression and adapter checks');const packageSmoke = workflowJob(workflow, 'package-smoke');assert.match(packageSmoke, /Verify delivery-lock ownership with real subprocesses/);assert.match(packageSmoke, /Verify macOS opener stays behind delivery-lock release/);@@ -337,15 +342,6 @@ test('package smoke rejects every dependency or repository-only artifact', () =>}});-test('package smoke verifies the embedded notifier identity and local disable switch', () => {- const source = fs.readFileSync(path.join(repoRoot, 'scripts', 'package-smoke.mjs'), 'utf8');- assert.match(source, /scripts', 'check-update\.mjs/);- assert.match(source, /scripts', 'update-contract\.mjs/);- assert.match(source, /skill-release\.json/);- assert.match(source, /ARCHIFY_UPDATE_CHECK_DISABLED: '1'/);- assert.match(source, /reason !== 'disabled'/);-});-test('package smoke rejects a missing or modified distribution license', () => {const packageSmoke = path.join(repoRoot, 'scripts', 'package-smoke.mjs');const fixture = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-package-license-gate-'));@@ -428,7 +424,7 @@ test('package smoke rejects missing, modified, or incomplete third-party notices}});-test('package smoke increments an arbitrary-precision SemVer patch without Number coercion', () => {+test('package smoke increments an arbitrary-precision SemVer patch without Number coercion', async () => {const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-package-bigint-version-'));const skillRoot = path.join(scratch, 'archify');try {@@ -444,34 +440,16 @@ test('package smoke increments an arbitrary-precision SemVer patch without Numbefs.writeFileSync(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`);fs.writeFileSync(releasePath, `${JSON.stringify(release, null, 2)}\n`);- const smoke = spawnSync(process.execPath, [path.join(repoRoot, 'scripts/package-smoke.mjs'), skillRoot], {- cwd: repoRoot,- encoding: 'utf8',- });- assert.equal(smoke.status, 0, smoke.stderr || smoke.stdout);+ // The ordinary archive smoke owns renderer/distribution coverage. This+ // version edge case needs only its real packaged notifier gate.+ const smoke = await verifyPackagedUpdateChecker(skillRoot, path.join(scratch, 'update-cache'));+ assert.equal(smoke.candidateVersion, '2.16.9007199254740994');+ assert.equal(smoke.notifierReceipt.status, 'update_available');} finally {fs.rmSync(scratch, { recursive: true, force: true });}});-test('archive build refuses to silently omit required release files', () => {- const buildSource = fs.readFileSync(path.join(repoRoot, 'scripts', 'build-zip.sh'), 'utf8');- const stageSource = fs.readFileSync(path.join(repoRoot, 'scripts', 'stage-clean-skill.mjs'), 'utf8');- assert.match(buildSource, /stage-clean-skill\.mjs/);- assert.match(stageSource, /archify\/LICENSE/);- assert.match(stageSource, /archify\/THIRD_PARTY_NOTICES\.md/);- assert.match(stageSource, /archify\/skill-release\.json/);- assert.match(stageSource, /archify\/renderers\/shared\/path-semantics\.mjs/);- assert.match(stageSource, /archify\/renderers\/shared\/portable-path\.mjs/);- assert.match(stageSource, /archify\/renderers\/shared\/output-path\.mjs/);- assert.match(stageSource, /archify\/renderers\/shared\/atomic-output\.mjs/);- assert.match(stageSource, /archify\/scripts\/check-update\.mjs/);- assert.match(stageSource, /archify\/scripts\/update-contract\.mjs/);- assert.match(stageSource, /git', \['ls-files', '--stage', '-z'/);- assert.match(stageSource, /required package input is not tracked by Git/);- assert.match(stageSource, /required repository input is not tracked by Git/);-});-test('clean package staging rejects non-portable tracked names and entry collisions before copying', () => {const cases = [{@@ -556,29 +534,6 @@ test('archive build rejects unsafe native output paths before creating files', (}});-test('archive output grammar is owned by the shared native-path validator', () => {- const buildSource = fs.readFileSync(path.join(repoRoot, 'scripts', 'build-zip.sh'), 'utf8');- const writerSource = fs.readFileSync(- path.join(repoRoot, 'scripts', 'write-deterministic-zip.mjs'),- 'utf8',- );- assert.doesNotMatch(buildSource, /windows_(?:drive|current|device|extended|dot|unc)/);- assert.match(writerSource, /import \{ validateNativeOutputPath \} from/);- assert.equal(writerSource.match(/kind: 'file'/gu)?.length, 2);- assert.ok(- writerSource.indexOf('validateNativeOutputPath(') < writerSource.indexOf('path.resolve(outputArg)'),- 'the raw output spelling must be validated before it is normalized or any archive write begins',- );- const validationOnly = buildSource.indexOf('--validate-output "$out"');- const nodeMajorGate = buildSource.indexOf('node_version=');- assert.notEqual(validationOnly, -1, 'the archive build must invoke the writer path-only validation mode');- assert.notEqual(nodeMajorGate, -1, 'the archive build must retain its canonical Node-major gate');- assert.ok(- validationOnly < nodeMajorGate,- 'raw output validation must run before the canonical Node-major gate',- );-});-test('archive build keeps unsafe-path diagnostics ahead of the canonical Node gate', {skip: process.platform === 'win32' ? 'the POSIX node shim is unnecessary on the real Windows Node 24 lane' : false,}, () => {@@ -657,15 +612,14 @@ canonicalZipTest('package smoke rejects every dependency metadata field in a buibundleDependencies: ['bundle-alias'],};+ const packagePath = path.join(builtPackage, 'package.json');+ const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8'));+ // These failures stop at metadata validation, before running the package.+ // Start each case from the pristine manifest without copying the whole ZIP.for (const [field, value] of Object.entries(dependencyFields)) {- const caseRoot = path.join(fixture, field);- fs.cpSync(builtPackage, caseRoot, { recursive: true });- const packagePath = path.join(caseRoot, 'package.json');- const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8'));- packageJson[field] = value;- fs.writeFileSync(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`);-- const result = spawnSync(process.execPath, [path.join(repoRoot, 'scripts', 'package-smoke.mjs'), caseRoot], {+ fs.writeFileSync(packagePath, `${JSON.stringify({ ...packageJson, [field]: value }, null, 2)}\n`);++ const result = spawnSync(process.execPath, [path.join(repoRoot, 'scripts', 'package-smoke.mjs'), builtPackage], {encoding: 'utf8',});assert.notEqual(result.status, 0, `${field} must fail package smoke`);@@ -1533,18 +1487,45 @@ test('CI tests the declared Node floor plus every maintained current lane', () =.split(',').map((version) => Number(version.trim()));assert.ok(versions, 'test job must declare an explicit Node version matrix');- for (const version of [18, 20, 22, 24]) {+ for (const version of [18, 20, 24]) {assert.ok(versions.includes(version), `test matrix must cover Node ${version}`);}+ const canonicalJob = workflowJob(workflow, 'canonical-test');+ assert.match(canonicalJob, /name: test \(22\)/);+ assert.match(canonicalJob, /node-version:\s*22/);const packageSmokeJob = workflowJob(workflow, 'package-smoke');assert.match(packageSmokeJob, /os:\s*\[ubuntu-latest, macos-latest, windows-latest\]/);assert.match(packageSmokeJob, /node-version:\s*22/);});-test('CI and tagged releases share the maintained Windows path contract on Node 22 and 24', () => {+test('CI and tagged releases keep real Windows paths on both Nodes and detailed matrices on canonical Node', () => {const runnerPath = path.join(repoRoot, 'scripts', 'run-windows-path-tests.mjs');const runner = fs.readFileSync(runnerPath, 'utf8');+ const list = (...options) => {+ const result = spawnSync(process.execPath, [runnerPath, '--list', ...options], {+ cwd: os.tmpdir(), encoding: 'utf8', timeout: 10_000,+ });+ assert.equal(result.status, 0, result.stderr);+ return JSON.parse(result.stdout);+ };+ const complete = list();+ const smoke = list('--smoke');+ assert.equal(complete.controlledPaths, true);+ assert.equal(smoke.controlledPaths, true);+ assert.deepEqual(smoke.groups.flat().filter(arg => arg.endsWith('.test.mjs')),+ ['test/core-smoke.test.mjs'], 'The compatibility profile selects only core product coverage.');+ const invalid = spawnSync(process.execPath, [runnerPath, '--list', '--smkoe'], { encoding: 'utf8', timeout: 10_000 });+ assert.notEqual(invalid.status, 0, 'A misspelled profile must not silently reduce coverage.');+ if (process.platform !== 'win32') {+ const wrongHost = spawnSync(process.execPath, [runnerPath, '--smoke'], {+ encoding: 'utf8', timeout: 10_000,+ env: { ...process.env, ARCHIFY_REQUIRE_WINDOWS_REAL_PATHS: '1' },+ });+ assert.notEqual(wrongHost.status, 0);+ assert.match(wrongHost.stderr, /ARCHIFY_REQUIRE_WINDOWS_REAL_PATHS=1 requires Windows/,+ 'The smoke profile must still enter the required real-path gate.');+ }const fullSuites = ['test/release-package-gates.test.mjs','test/copy-site-assets.test.mjs',@@ -1563,7 +1544,7 @@ test('CI and tagged releases share the maintained Windows path contract on Node'test/atomic-output-recovery.test.mjs',];for (const suite of fullSuites) {- assert.ok(runner.includes(`'${suite}'`), `shared runner must execute ${suite}`);+ assert.ok(complete.groups.flat().includes(suite), `canonical runner must execute ${suite}`);}for (const fixture of ['test/checkout-line-endings.test.mjs',@@ -1693,6 +1674,8 @@ test('CI and tagged releases share the maintained Windows path contract on Nodeassert.match(job, /node-version:\s*\$\{\{ matrix\.node-version \}\}/);assert.match(job, /npm ci --ignore-scripts/);assert.match(job, /node scripts\/run-windows-path-tests\.mjs/);+ assert.ok(job.includes("matrix.node-version == 24 && '--smoke' || ''"),+ `${label} must select smoke only for Node 24; Node 22 retains the complete matrices`);assert.match(job, label === 'CI'? /name: Provision controlled Windows path fixtures\n\s+if: needs\.scope\.outputs\.windows == 'true'\n\s+shell: pwsh/: /name: Provision controlled Windows path fixtures\n\s+shell: pwsh/);diff --git a/test/repository-evidence-browser.test.mjs b/test/repository-evidence-browser.test.mjsnew file mode 100644index 00000000..85e56b73--- /dev/null+++ b/test/repository-evidence-browser.test.mjs@@ -0,0 +1,206 @@+import assert from 'node:assert/strict';+import fs from 'node:fs';+import path from 'node:path';+import test from 'node:test';+import { ChromeVisualBrowser, findChrome } from '../archify/bin/visual-check.mjs';+import { git, fixture, run } from './helpers/repository-evidence-fixture.mjs';++test('browser renders local-only sources as searchable text and web sources as links', {+ skip: process.env.ARCHIFY_CHROME ? false : 'Set ARCHIFY_CHROME to run evidence browser checks.',+ timeout: 60000,+}, async () => {+ const data = fixture();+ const browser = new ChromeVisualBrowser(findChrome());+ try {+ for (const mode of ['github', 'gitee', 'gitlab', 'local-only']) {+ const local = mode === 'local-only';+ const url = local ? 'http://git.internal/Team/repo' : `https://${mode}.com/example/evidence-repo`;+ data.diagram.meta.repository = { url, revision: data.revision, ...(local ? { link_mode: mode } : {}) };+ git(data.root, 'remote', 'set-url', 'origin', url);+ fs.writeFileSync(data.input, JSON.stringify(data.diagram));+ const artifactPath = path.join(data.root, `${mode}.html`);+ const result = run(['deliver', 'architecture', data.input, artifactPath, '--repo-root', data.root, '--json']);+ assert.equal(result.status, 0, result.stderr || result.stdout);+ for (const theme of ['light', 'dark']) {+ await browser.inspect({ artifactPath, width: 1440, height: 900, theme });+ const sessionId = await browser.sessionPromise;+ const response = await browser.cdp.send('Runtime.evaluate', {+ expression: `(() => {+ document.querySelector('[data-node-id="users"]').dispatchEvent(new MouseEvent('click', { bubbles: true }));+ const panel = document.getElementById('focus-evidence');+ const rows = [...panel.querySelectorAll('.semantic-passport-source')];+ const input = document.getElementById('node-finder-input');+ input.value = 'src/router.js';+ input.dispatchEvent(new Event('input', { bubbles: true }));+ return {+ visible: !panel.hidden,+ links: rows.filter(row => row.tagName === 'A').map(row => row.getAttribute('href')),+ paths: rows.map(row => row.querySelector('small').textContent),+ locations: rows.map(row => row.querySelector('code').textContent),+ repositoryHref: document.getElementById('focus-repository').getAttribute('href'),+ scope: panel.title,+ badges: document.querySelectorAll('[data-source-evidence-beacon]').length,+ sourceCount: document.querySelector('[data-node-id="users"]').getAttribute('data-source-evidence-count'),+ sourceAria: document.querySelector('[data-node-id="users"]').getAttribute('aria-label'),+ invalidLinks: [...panel.querySelectorAll('a[href]')].some(a => /undefined|javascript:/.test(a.getAttribute('href'))),+ search: document.getElementById('node-finder-results').textContent+ };+ })()`, returnByValue: true,+ }, sessionId);+ assert.equal(response.exceptionDetails, undefined);+ const observed = response.result.value;+ assert.equal(observed.visible, true);+ assert.equal(observed.badges, 0);+ assert.equal(observed.sourceCount, '2');+ assert.match(observed.sourceAria, /2 verified source references/);+ assert.equal(observed.invalidLinks, false);+ assert.deepEqual(observed.paths, ['src/router.js', 'src/store.js']);+ assert.match(observed.scope, /local Git/);+ assert.match(observed.search, /Users/);+ assert.equal(observed.links.length, local ? 0 : 2);+ assert.equal(observed.locations[0], local ? 'L1–3' : 'L1–3 ↗');+ assert.equal(observed.repositoryHref, local ? null : `${url}/${mode === 'gitlab' ? '-/' : ''}tree/${data.revision}`);+ }+ }+ } finally { await browser.close(); }+});++test('browser announces verified source counts without visual marks and restores canonical export labels', {+ skip: process.env.ARCHIFY_CHROME ? false : 'Set ARCHIFY_CHROME to run evidence browser checks.',+ timeout: 30000,+}, async (t) => {+ const data = fixture();+ t.after(() => fs.rmSync(data.root, { recursive: true, force: true }));+ data.diagram.meta.locale = 'zh-CN';+ fs.writeFileSync(data.input, JSON.stringify(data.diagram));+ const artifactPath = path.join(data.root, 'source-aria.html');+ const delivered = run(['deliver', 'architecture', data.input, artifactPath, '--repo-root', data.root, '--json']);+ assert.equal(delivered.status, 0, delivered.stderr || delivered.stdout);+ const html = fs.readFileSync(artifactPath, 'utf8');+ const initialization = html.match(/Archify\.sourceEvidence = \(function \(\) \{[\s\S]*?\}\)\(\);/)?.[0];+ assert.ok(initialization);+ const browser = new ChromeVisualBrowser(findChrome());+ try {+ await browser.inspect({ artifactPath, width: 1440, height: 900, theme: 'light' });+ const sessionId = await browser.sessionPromise;+ async function accessibleNodeName() {+ const remote = await browser.cdp.send('Runtime.evaluate', {+ expression: `document.querySelector('[data-node-id="users"]')`,+ }, sessionId);+ const tree = await browser.cdp.send('Accessibility.getPartialAXTree', {+ objectId: remote.result.objectId, fetchRelatives: false,+ }, sessionId);+ const name = tree.nodes.find(node => !node.ignored)?.name?.value;+ assert.equal(typeof name, 'string', JSON.stringify(tree));+ return name;+ }+ assert.match(await accessibleNodeName(), /2 个已验证来源引用/);+ const response = await browser.cdp.send('Runtime.evaluate', {+ expression: `(async () => {+ const reinitialize = () => { ${initialization} };+ const svg = document.querySelector('.diagram-container > svg');+ const node = svg.querySelector('[data-node-id="users"]');+ const element = document.getElementById('archify-source-evidence-data');+ const payload = JSON.parse(element.textContent);+ const originalSources = payload.nodes.users.slice();+ const authoredLabel = node.getAttribute('data-source-evidence-original-label');+ const geometry = [...svg.querySelectorAll('rect,path,line,polyline,text')].map(el => el.outerHTML).join('');+ const initial = node.getAttribute('aria-label');+ reinitialize();+ const repeated = node.getAttribute('aria-label');+ const noVisualMarks = !svg.querySelector('[data-source-evidence-beacon], .source-evidence-beacon');+ const geometryPreserved = geometry === [...svg.querySelectorAll('rect,path,line,polyline,text')].map(el => el.outerHTML).join('');+ Archify.focus.set('users', { toggle: false });+ const passportLinks = document.querySelectorAll('#focus-evidence a[href]').length;+ const before = svg.outerHTML;+ const originalCreate = URL.createObjectURL;+ let exportedBlob;+ URL.createObjectURL = function(blob) {+ if (blob.type.startsWith('image/svg+xml')) exportedBlob = blob;+ return originalCreate.call(URL, blob);+ };+ let exportPreservesLive;+ try {+ const pending = Archify.exportMenu.run('svg');+ exportPreservesLive = before === svg.outerHTML;+ await pending;+ } finally { URL.createObjectURL = originalCreate; }+ const exported = new DOMParser().parseFromString(await exportedBlob.text(), 'image/svg+xml');+ const exportedLabel = exported.querySelector('[data-node-id="users"]').getAttribute('aria-label');+ const exportClean = !exported.querySelector('[data-source-evidence-count], [data-source-evidence-original-label], [data-reader-legend-corner], [data-source-evidence-beacon]');+ // The download anchor can clear Focus through its existing outside-click+ // behavior. Reopen via the public interface to verify sources survive.+ Archify.focus.set('users', { toggle: false });+ const passportLinksAfter = document.querySelectorAll('#focus-evidence a[href]').length;+ payload.nodes.users = [];+ element.textContent = JSON.stringify(payload);+ reinitialize();+ const zeroRestored = node.getAttribute('aria-label') === authoredLabel && !node.hasAttribute('data-source-evidence-count');+ const results = [];+ for (const label of [null, '', 'Authored focus label']) {+ node.removeAttribute('data-source-evidence-count');+ node.removeAttribute('data-source-evidence-original-label');+ if (label === null) node.removeAttribute('aria-label'); else node.setAttribute('aria-label', label);+ payload.nodes.users = [originalSources[0]];+ payload.verified = true;+ element.textContent = JSON.stringify(payload);+ reinitialize();+ const once = node.getAttribute('aria-label');+ reinitialize();+ const twice = node.getAttribute('aria-label');+ let labelBlob;+ URL.createObjectURL = function(blob) {+ if (blob.type.startsWith('image/svg+xml')) labelBlob = blob;+ return originalCreate.call(URL, blob);+ };+ try { await Archify.exportMenu.run('svg'); }+ finally { URL.createObjectURL = originalCreate; }+ const exportedNode = new DOMParser().parseFromString(await labelBlob.text(), 'image/svg+xml').querySelector('[data-node-id="users"]');+ payload.nodes.users = [];+ element.textContent = JSON.stringify(payload);+ reinitialize();+ const zeroRestored = node.getAttribute('aria-label');+ payload.nodes.users = [originalSources[0]];+ element.textContent = JSON.stringify(payload);+ reinitialize();+ payload.verified = false;+ element.textContent = JSON.stringify(payload);+ reinitialize();+ results.push({ once, twice, zeroRestored, exportedLabel: exportedNode.getAttribute('aria-label'), restored: node.getAttribute('aria-label'), count: node.getAttribute('data-source-evidence-count') });+ }+ return { initial, repeated, noVisualMarks, geometryPreserved, authoredLabel, exportedLabel,+ exportClean, exportPreservesLive, passportLinks, passportLinksAfter,+ zeroRestored, results };+ })()`, returnByValue: true, awaitPromise: true,+ }, sessionId);+ assert.equal(response.exceptionDetails, undefined);+ const observed = response.result.value;+ assert.match(observed.initial, /2 个已验证来源引用/);+ assert.equal(observed.repeated, observed.initial);+ for (const key of ['noVisualMarks', 'geometryPreserved', 'exportClean', 'exportPreservesLive', 'zeroRestored']) assert.equal(observed[key], true, key);+ assert.equal(observed.exportedLabel, observed.authoredLabel);+ assert.equal(observed.passportLinks, 3);+ assert.equal(observed.passportLinksAfter, 3);+ for (const [index, result] of observed.results.entries()) {+ assert.match(result.once, /1 个已验证来源引用/);+ assert.equal(result.twice, result.once);+ assert.equal(result.restored, [null, '', 'Authored focus label'][index]);+ assert.equal(result.zeroRestored, [null, '', 'Authored focus label'][index]);+ assert.equal(result.exportedLabel, [null, '', 'Authored focus label'][index]);+ assert.equal(result.count, null);+ }+ const restored = await browser.cdp.send('Runtime.evaluate', {+ expression: `(() => {+ const element = document.getElementById('archify-source-evidence-data');+ const payload = JSON.parse(element.textContent);+ payload.verified = true;+ element.textContent = JSON.stringify(payload);+ ${initialization}+ return document.querySelector('[data-node-id="users"]').getAttribute('aria-labelledby');+ })()`, returnByValue: true,+ }, sessionId);+ assert.equal(restored.exceptionDetails, undefined);+ assert.equal(restored.result.value, null, 'node has no competing aria-labelledby');+ assert.equal(await accessibleNodeName(), 'Authored focus label, 1 个已验证来源引用');+ } finally { await browser.close(); }+});diff --git a/test/repository-evidence-types.test.mjs b/test/repository-evidence-types.test.mjsindex 995a9518..153057db 100644--- a/test/repository-evidence-types.test.mjs+++ b/test/repository-evidence-types.test.mjs@@ -6,6 +6,7 @@ import path from 'node:path';import test, { after } from 'node:test';import { fileURLToPath } from 'node:url';import { startPreview } from '../archify/bin/preview.mjs';+import { validateSchema } from '../archify/renderers/shared/validator.mjs';const here = path.dirname(fileURLToPath(import.meta.url));const skillRoot = path.resolve(here, '..', 'archify');@@ -95,7 +96,91 @@ function fixture(t, { type, collection, example, first }) {return { root, revision, diagram, node, input, write };}-for (const shape of TYPES) {+// All renderers enter the same repository verifier through loadDiagram. Keep+// the full rejection matrix once; the type loop below owns each mode's wiring.+test('shared repository evidence rejects invalid roots, revisions, paths and lines without replacing output', (t) => {+ const shape = TYPES.find(({ type }) => type === 'architecture');+ const { type } = shape;+ const data = fixture(t, shape);+ const output = path.join(data.root, `must-stay.${type}.html`);+ fs.writeFileSync(output, 'trusted previous artifact');+ const deliver = (...args) => {+ const result = run(['deliver', type, data.input, output, ...args, '--json']);+ assert.equal(fs.readFileSync(output, 'utf8'), 'trusted previous artifact');+ return result;+ };++ // No --repo-root at all.+ let result = deliver();+ assert.equal(result.status, 1);+ assert.match(JSON.parse(result.stdout).error, /Pass --repo-root/);++ // Not the Git top-level directory.+ result = deliver('--repo-root', path.join(data.root, 'src'));+ assert.equal(result.status, 1);+ assert.match(JSON.parse(result.stdout).error, /must be the Git top-level directory/);++ // Origin does not match the authored repository.+ git(data.root, 'remote', 'set-url', 'origin', 'https://github.com/example/other-repo.git');+ result = deliver('--repo-root', data.root);+ assert.equal(result.status, 1);+ assert.match(JSON.parse(result.stdout).error, /does not match/);+ git(data.root, 'remote', 'set-url', 'origin', '[email protected]:example/evidence-repo.git');++ // Commit does not exist locally.+ const pinned = data.diagram.meta.repository.revision;+ data.diagram.meta.repository.revision = '0'.repeat(40);+ data.write();+ result = deliver('--repo-root', data.root);+ assert.equal(result.status, 1);+ assert.match(JSON.parse(result.stdout).error, /is not available in the local repository/);+ data.diagram.meta.repository.revision = pinned;++ // Path escape.+ data.node.sources = [{ path: '../outside.js' }];+ data.write();+ result = deliver('--repo-root', data.root);+ assert.equal(result.status, 1);+ assert.match(JSON.parse(result.stdout).error, /must stay inside the repository/);++ // Non-POSIX / control-character path.+ data.node.sources = [{ path: 'src/router.js\n' }];+ data.write();+ result = deliver('--repo-root', data.root);+ assert.equal(result.status, 1);+ assert.match(JSON.parse(result.stdout).error, /repo-relative POSIX path/);++ // Blob does not exist at the pinned revision.+ data.node.sources = [{ path: 'src/missing.js' }];+ data.write();+ result = deliver('--repo-root', data.root);+ assert.equal(result.status, 1);+ assert.match(JSON.parse(result.stdout).error, /does not identify a file/);++ // Line range beyond the pinned blob.+ data.node.sources = [{ path: 'src/router.js', line: 4 }];+ data.write();+ result = deliver('--repo-root', data.root);+ assert.equal(result.status, 1);+ assert.match(JSON.parse(result.stdout).error, /has 3 lines/);++ // Inverted line range.+ data.node.sources = [{ path: 'src/router.js', line: 3, end_line: 2 }];+ data.write();+ result = deliver('--repo-root', data.root);+ assert.equal(result.status, 1);+ assert.match(JSON.parse(result.stdout).error, /must be greater than or equal to line/);++ // end_line without line.+ data.node.sources = [{ path: 'src/router.js', end_line: 2 }];+ data.write();+ result = deliver('--repo-root', data.root);+ assert.equal(result.status, 1);+ assert.match(JSON.parse(result.stdout).error, /requires line/);++});++for (const [typeIndex, shape] of TYPES.entries()) {const { type, collection, first } = shape;test(`${type} repository evidence is revision-verified, receipt-backed, and keyed by node id`, (t) => {@@ -132,83 +217,6 @@ for (const shape of TYPES) {assert.doesNotMatch(svg, /src\/router\.js|github\.com\/example\/evidence-repo|source-evidence/);});- test(`${type} repository evidence applies every architecture verification`, (t) => {- const data = fixture(t, shape);- const output = path.join(data.root, `must-stay.${type}.html`);- fs.writeFileSync(output, 'trusted previous artifact');- const deliver = (...args) => run(['deliver', type, data.input, output, ...args, '--json']);-- // No --repo-root at all.- let result = deliver();- assert.equal(result.status, 1);- assert.match(JSON.parse(result.stdout).error, /Pass --repo-root/);-- // Not the Git top-level directory.- result = deliver('--repo-root', path.join(data.root, 'src'));- assert.equal(result.status, 1);- assert.match(JSON.parse(result.stdout).error, /must be the Git top-level directory/);-- // Origin does not match the authored repository.- git(data.root, 'remote', 'set-url', 'origin', 'https://github.com/example/other-repo.git');- result = deliver('--repo-root', data.root);- assert.equal(result.status, 1);- assert.match(JSON.parse(result.stdout).error, /does not match/);- git(data.root, 'remote', 'set-url', 'origin', '[email protected]:example/evidence-repo.git');-- // Commit does not exist locally.- const pinned = data.diagram.meta.repository.revision;- data.diagram.meta.repository.revision = '0'.repeat(40);- data.write();- result = deliver('--repo-root', data.root);- assert.equal(result.status, 1);- assert.match(JSON.parse(result.stdout).error, /is not available in the local repository/);- data.diagram.meta.repository.revision = pinned;-- // Path escape.- data.node.sources = [{ path: '../outside.js' }];- data.write();- result = deliver('--repo-root', data.root);- assert.equal(result.status, 1);- assert.match(JSON.parse(result.stdout).error, /must stay inside the repository/);-- // Non-POSIX / control-character path.- data.node.sources = [{ path: 'src/router.js\n' }];- data.write();- result = deliver('--repo-root', data.root);- assert.equal(result.status, 1);- assert.match(JSON.parse(result.stdout).error, /repo-relative POSIX path/);-- // Blob does not exist at the pinned revision.- data.node.sources = [{ path: 'src/missing.js' }];- data.write();- result = deliver('--repo-root', data.root);- assert.equal(result.status, 1);- assert.match(JSON.parse(result.stdout).error, /does not identify a file/);-- // Line range beyond the pinned blob.- data.node.sources = [{ path: 'src/router.js', line: 4 }];- data.write();- result = deliver('--repo-root', data.root);- assert.equal(result.status, 1);- assert.match(JSON.parse(result.stdout).error, /has 3 lines/);-- // Inverted line range.- data.node.sources = [{ path: 'src/router.js', line: 3, end_line: 2 }];- data.write();- result = deliver('--repo-root', data.root);- assert.equal(result.status, 1);- assert.match(JSON.parse(result.stdout).error, /must be greater than or equal to line/);-- // end_line without line.- data.node.sources = [{ path: 'src/router.js', end_line: 2 }];- data.write();- result = deliver('--repo-root', data.root);- assert.equal(result.status, 1);- assert.match(JSON.parse(result.stdout).error, /requires line/);-- assert.equal(fs.readFileSync(output, 'utf8'), 'trusted previous artifact');- });-test(`${type} duplicate evidence node IDs cannot replace a trusted artifact`, (t) => {const data = fixture(t, shape);const duplicate = structuredClone(data.node);@@ -246,52 +254,60 @@ for (const shape of TYPES) {assert.equal(fs.readFileSync(output, 'utf8'), 'trusted previous artifact');});- test(`${type} repository evidence honors Gitee and GitLab links and local-only mode`, (t) => {+ // GitHub integration is checked above for every type. The full provider,+ // origin and rejection matrix lives in repository-evidence.test.mjs, using+ // the same verifier. Each type also proves one alternate configuration is+ // threaded through its schema, delivery receipt and embedded payload.+ test(`${type} repository evidence preserves alternate provider settings`, (t) => {const data = fixture(t, shape);const output = path.join(data.root, `provider.${type}.html`);-- data.diagram.meta.repository = { url: 'https://gitee.com/example/evidence-repo', revision: data.revision, provider: 'gitee' };- data.write();- git(data.root, 'remote', 'set-url', 'origin', '[email protected]:example/evidence-repo.git');- let result = run(['deliver', type, data.input, output, '--repo-root', data.root, '--json']);- assert.equal(result.status, 0, result.stderr || result.stdout);- let evidence = evidencePayload(fs.readFileSync(output, 'utf8'));- assert.equal(evidence.repository.href, `https://gitee.com/example/evidence-repo/tree/${data.revision}`);- assert.equal(evidence.nodes[first][0].href, `https://gitee.com/example/evidence-repo/blob/${data.revision}/src/router.js#L1-3`);-- data.diagram.meta.repository.provider = 'github';- data.write();- result = run(['validate', type, data.input, '--repo-root', data.root, '--json']);- assert.equal(result.status, 1);- assert.ok(JSON.parse(result.stdout).diagnostics.some((entry) => entry.code === 'repository-evidence/provider-invalid'));-- data.diagram.meta.repository = { url: 'https://gitlab.com/example/platform/evidence-repo', revision: data.revision };- data.write();- git(data.root, 'remote', 'set-url', 'origin', '[email protected]:example/platform/evidence-repo.git');- result = run(['deliver', type, data.input, output, '--repo-root', data.root, '--json']);- assert.equal(result.status, 0, result.stderr || result.stdout);- evidence = evidencePayload(fs.readFileSync(output, 'utf8'));- assert.equal(evidence.repository.href, `https://gitlab.com/example/platform/evidence-repo/-/tree/${data.revision}`);- assert.equal(evidence.nodes[first][0].href, `https://gitlab.com/example/platform/evidence-repo/-/blob/${data.revision}/src/router.js#L1-3`);-- data.diagram.meta.repository = { url: 'http://git.internal:3000/Platform/evidence-repo', revision: data.revision, link_mode: 'local-only' };+ const providers = [+ {+ repository: { url: 'https://gitee.com/example/evidence-repo', provider: 'gitee' },+ origin: '[email protected]:example/evidence-repo.git',+ tree: `https://gitee.com/example/evidence-repo/tree/${data.revision}`,+ source: `https://gitee.com/example/evidence-repo/blob/${data.revision}/src/router.js#L1-3`,+ },+ {+ repository: { url: 'https://gitlab.com/example/platform/evidence-repo' },+ origin: '[email protected]:example/platform/evidence-repo.git',+ tree: `https://gitlab.com/example/platform/evidence-repo/-/tree/${data.revision}`,+ source: `https://gitlab.com/example/platform/evidence-repo/-/blob/${data.revision}/src/router.js#L1-3`,+ },+ {+ repository: { url: 'http://git.internal:3000/Platform/evidence-repo', link_mode: 'local-only' },+ origin: 'http://git.internal:3000/Platform/evidence-repo',+ },+ ];+ const provider = providers[typeIndex % providers.length];+ data.diagram.meta.repository = { ...provider.repository, revision: data.revision };data.write();- git(data.root, 'remote', 'set-url', 'origin', 'http://git.internal:3000/Platform/evidence-repo');- result = run(['deliver', type, data.input, output, '--repo-root', data.root, '--json']);+ git(data.root, 'remote', 'set-url', 'origin', provider.origin);+ const result = run(['deliver', type, data.input, output, '--repo-root', data.root, '--json']);assert.equal(result.status, 0, result.stderr || result.stdout);- assert.equal(JSON.parse(result.stdout).evidence.linkMode, 'local-only');- evidence = evidencePayload(fs.readFileSync(output, 'utf8'));- assert.equal(evidence.repository.linkMode, 'local-only');- assert.equal(evidence.repository.href, undefined);+ const receipt = JSON.parse(result.stdout);+ assert.equal(receipt.evidence.verified, true);+ assert.equal(receipt.evidence.references, 2);+ const evidence = evidencePayload(fs.readFileSync(output, 'utf8'));+ assert.equal(evidence.verified, true);+ assert.deepEqual(Object.keys(evidence.nodes), [first]);assert.equal(evidence.nodes[first].length, 2);- assert.ok(evidence.nodes[first].every((source) => !Object.hasOwn(source, 'href')));+ assert.equal(evidence.repository.href, provider.tree);+ assert.equal(evidence.nodes[first][0].href, provider.source);+ if (provider.repository.link_mode === 'local-only') {+ assert.equal(receipt.evidence.linkMode, 'local-only');+ assert.equal(evidence.repository.linkMode, 'local-only');+ assert.ok(evidence.nodes[first].every((source) => !Object.hasOwn(source, 'href')));+ }});- test(`${type} evidence diagnostics point at its own node collection`, (t) => {+ test(`${type} failed evidence delivery identifies its node collection and preserves output`, (t) => {const data = fixture(t, shape);data.node.sources = [{ path: 'src/missing.js' }];data.write();- const result = run(['validate', type, data.input, '--repo-root', data.root, '--json']);+ const output = path.join(data.root, 'trusted.html');+ fs.writeFileSync(output, 'trusted previous artifact');+ const result = run(['deliver', type, data.input, output, '--repo-root', data.root, '--json']);assert.equal(result.status, 1);const receipt = JSON.parse(result.stdout);const diagnostic = receipt.diagnostics.find((entry) => entry.code === 'repository-evidence/file-missing');@@ -300,26 +316,40 @@ for (const shape of TYPES) {assert.equal(diagnostic.subject.nodeId, first);assert.equal(diagnostic.evidence.sourcePath, 'src/missing.js');assert.ok(diagnostic.supportedFixes.length);+ assert.equal(fs.readFileSync(output, 'utf8'), 'trusted previous artifact');});test(`${type} sources stay bounded by the shared schema shape`, (t) => {- const data = fixture(t, shape);- data.node.sources = [- { path: 'src/router.js' },- { path: 'src/router.js' },- { path: 'src/router.js' },- { path: 'src/router.js' },- ];- data.write();- let result = run(['validate', type, data.input, '--repo-root', data.root]);- assert.equal(result.status, 1);- assert.match(result.stderr, /must NOT have more than 3 items/);-- data.node.sources = [{ path: 'src/router.js', branch: 'main' }];- data.write();- result = run(['validate', type, data.input, '--repo-root', data.root]);- assert.equal(result.status, 1);- assert.match(result.stderr, /must NOT have additional properties/);+ // These failures occur before Git verification. Exercise each generated+ // type validator directly; one CLI witness retains exit/diagnostic wiring.+ const diagram = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples', shape.example), 'utf8'));+ const nodeIndex = diagram[collection].findIndex(node => node.id === first);+ const node = diagram[collection][nodeIndex];+ diagram.meta.repository = { url: 'https://github.com/example/evidence-repo', revision: 'a'.repeat(40) };+ node.sources = [{ path: 'src/router.js' }];+ assert.doesNotThrow(() => validateSchema(type, diagram));+ const cliData = type === 'architecture' ? fixture(t, shape) : null;+ for (const [sources, pattern, code, sourceSuffix] of [+ [Array.from({ length: 4 }, () => ({ path: 'src/router.js' })), /must NOT have more than 3 items/, 'schema/maxItems', ''],+ [[{ path: 'src/router.js', branch: 'main' }], /must NOT have additional properties/, 'schema/additionalProperties', '/0'],+ ]) {+ node.sources = sources;+ assert.throws(() => validateSchema(type, diagram), (error) => {+ assert.match(error.message, pattern);+ const diagnostic = error.archifyDiagnostics.find(entry => entry.code === code);+ assert.ok(diagnostic, `${type}: missing ${code}`);+ assert.equal(diagnostic.subject.diagramType, type);+ assert.equal(diagnostic.subject.path, `/${collection}/${nodeIndex}/sources${sourceSuffix}`);+ return true;+ });+ if (cliData) {+ cliData.node.sources = sources;+ cliData.write();+ const result = run(['validate', type, cliData.input, '--repo-root', cliData.root]);+ assert.equal(result.status, 1);+ assert.match(result.stderr, pattern);+ }+ }});test(`${type} node sources require pinned repository metadata`, (t) => {@@ -354,17 +384,6 @@ test('--repo-root is accepted for every diagram type', () => {}});-test('repository evidence no longer rejects any supported diagram type', () => {- const rejected = run(['validate', 'lifecycle', path.join(skillRoot, 'examples', 'agent-run.lifecycle.json'), '--repo-root', '.']);- assert.equal(rejected.status, 0, rejected.stderr);- assert.doesNotMatch(rejected.stderr, /architecture diagrams only/);- assert.doesNotMatch(- fs.readFileSync(path.join(skillRoot, 'renderers', 'shared', 'repository-evidence.mjs'), 'utf8'),- /type-unsupported/,- 'the type-unsupported diagnostic is unreachable and must be removed deliberately',- );-});-test('ordinary typed artifacts still carry no repository evidence', (t) => {for (const { type, example } of TYPES) {const output = path.join(temporaryDirectory(t, 'archify-no-evidence-types-'), `${type}.html`);diff --git a/test/repository-evidence.test.mjs b/test/repository-evidence.test.mjsindex 1e7511e0..72f181be 100644--- a/test/repository-evidence.test.mjs+++ b/test/repository-evidence.test.mjs@@ -1,60 +1,37 @@import assert from 'node:assert/strict';-import { execFileSync, spawnSync } from 'node:child_process';+import { spawnSync } from 'node:child_process';import fs from 'node:fs';import os from 'node:os';import path from 'node:path';import test from 'node:test';-import { fileURLToPath } from 'node:url';import { startPreview } from '../archify/bin/preview.mjs';-import { ChromeVisualBrowser, findChrome } from '../archify/bin/visual-check.mjs';import { verifyRepositoryEvidence } from '../archify/renderers/shared/repository-evidence.mjs';--const here = path.dirname(fileURLToPath(import.meta.url));-const skillRoot = path.resolve(here, '..', 'archify');-const cli = path.join(skillRoot, 'bin', 'archify.mjs');--function git(repo, ...args) {- return execFileSync('git', ['-C', repo, ...args], { encoding: 'utf8' }).trim();-}--function fixture() {- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-evidence-repo-'));- fs.mkdirSync(path.join(root, 'src'), { recursive: true });- fs.writeFileSync(path.join(root, 'src', 'router.js'), 'export function route(input) {\n return input.kind;\n}\n');- fs.writeFileSync(path.join(root, 'src', 'store.js'), 'export const store = new Map();\n');- git(root, 'init');- git(root, 'config', 'user.name', 'Archify Tests');- git(root, 'config', 'user.email', '[email protected]');- git(root, 'remote', 'add', 'origin', '[email protected]:example/evidence-repo.git');- git(root, 'add', '.');- git(root, 'commit', '-m', 'fixture');- const revision = git(root, 'rev-parse', 'HEAD');-- const diagram = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples', 'web-app.architecture.json'), 'utf8'));- diagram.meta.repository = {- url: 'https://github.com/example/evidence-repo',- revision,- };- diagram.components[0].sources = [- { path: 'src/router.js', line: 1, end_line: 3, label: 'Request router' },- { path: 'src/store.js', line: 1 },- ];- const input = path.join(root, 'diagram.architecture.json');- fs.writeFileSync(input, JSON.stringify(diagram, null, 2));- return { root, revision, diagram, input };-}--function run(args) {- return spawnSync(process.execPath, [cli, ...args], {- cwd: skillRoot,- encoding: 'utf8',- });-}--function evidencePayload(html) {- const match = html.match(/<script id="archify-source-evidence-data" type="application\/json">([\s\S]*?)<\/script>/);- assert.ok(match, 'verified evidence payload missing');- return JSON.parse(match[1]);+import { skillRoot, cli, git, fixture, run, evidencePayload } from './helpers/repository-evidence-fixture.mjs';++// Address variants exercise the same real Git verifier. Keep representative+// CLI paths to prove that the verified payload reaches HTML and delivery receipts,+// instead of rendering the same diagram again for every spelling of its origin.+function verifyRemoteEvidence(data, output, { cli: throughCli = false, command = 'deliver' } = {}) {+ if (!throughCli) {+ const evidence = verifyRepositoryEvidence('architecture', data.diagram, data.root);+ assert.equal(evidence.verified, true);+ return evidence;+ }+ fs.writeFileSync(data.input, JSON.stringify(data.diagram));+ const args = [command, 'architecture', data.input, output, '--repo-root', data.root];+ if (command === 'deliver') args.push('--json');+ const result = run(args);+ assert.equal(result.status, 0, `${data.diagram.meta.repository.url}: ${result.stderr || result.stdout}`);+ const html = fs.readFileSync(output, 'utf8');+ const evidence = evidencePayload(html);+ assert.equal(evidence.verified, true);+ assert.doesNotMatch(html, /SYNTHETIC_TOKEN|not-a-real-token/);+ if (command === 'deliver') {+ const receipt = JSON.parse(result.stdout);+ assert.equal(receipt.evidence.verified, true);+ assert.equal(receipt.evidence.linkMode, evidence.repository.linkMode);+ }+ return evidence;}test('evidence prefetch preserves the first source diagnostic in JSON output', (t) => {@@ -194,28 +171,28 @@ test('repository root fails closed when physical identity is indeterminate', (t));});-test('Gitee evidence generates provider-specific revision and line links', () => {+test('Gitee evidence generates provider-specific revision and line links', (t) => {const data = fixture();+ t.after(() => fs.rmSync(data.root, { recursive: true, force: true }));data.diagram.meta.repository.url = 'https://gitee.com/example/evidence-repo';fs.writeFileSync(data.input, JSON.stringify(data.diagram));const output = path.join(data.root, 'gitee.html');- for (const remote of [+ for (const [index, remote] of ['https://gitee.com/example/evidence-repo.git/','[email protected]:example/evidence-repo.git','ssh://[email protected]/example/evidence-repo.git',- ]) {+ ].entries()) {git(data.root, 'remote', 'set-url', 'origin', remote);- const result = run(['deliver', 'architecture', data.input, output, '--repo-root', data.root, '--json']);- assert.equal(result.status, 0, result.stderr || result.stdout);- const evidence = evidencePayload(fs.readFileSync(output, 'utf8'));+ const evidence = verifyRemoteEvidence(data, output, { cli: index === 0 });assert.equal(evidence.repository.href, `https://gitee.com/example/evidence-repo/tree/${data.revision}`);assert.equal(evidence.nodes.users[0].href, `https://gitee.com/example/evidence-repo/blob/${data.revision}/src/router.js#L1-3`);assert.equal(evidence.nodes.users[1].href, `https://gitee.com/example/evidence-repo/blob/${data.revision}/src/store.js#L1`);}});-test('GitLab evidence links nested groups and accepts SSH, HTTPS, suffix and case variants', () => {+test('GitLab evidence links nested groups and accepts SSH, HTTPS, suffix and case variants', (t) => {const data = fixture();+ t.after(() => fs.rmSync(data.root, { recursive: true, force: true }));fs.mkdirSync(path.join(data.root, 'docs'));fs.writeFileSync(path.join(data.root, 'docs', 'guide.md'), '# Guide\n\nRoute requests.\n');git(data.root, 'add', '.');@@ -227,18 +204,15 @@ test('GitLab evidence links nested groups and accepts SSH, HTTPS, suffix and casfs.writeFileSync(data.input, JSON.stringify(data.diagram));const output = path.join(data.root, 'gitlab.html');const base = 'https://gitlab.com/example/platform/evidence-repo';- for (const remote of [+ for (const [index, remote] of ['https://gitlab.com/example/platform/evidence-repo.git/','https://oauth2:[email protected]/example/platform/evidence-repo.git','[email protected]:example/platform/evidence-repo.git','ssh://[email protected]/example/platform/evidence-repo','[email protected]:Example/Platform/evidence-repo.git',- ]) {+ ].entries()) {git(data.root, 'remote', 'set-url', 'origin', remote);- const result = run(['deliver', 'architecture', data.input, output, '--repo-root', data.root, '--json']);- assert.equal(result.status, 0, `${remote}: ${result.stderr || result.stdout}`);- assert.equal(JSON.parse(result.stdout).evidence.linkMode, undefined);- const evidence = evidencePayload(fs.readFileSync(output, 'utf8'));+ const evidence = verifyRemoteEvidence(data, output, { cli: index === 1 || index === 2 });assert.equal(evidence.repository.href, `${base}/-/tree/${revision}`);assert.deepEqual(evidence.nodes.users.map((source) => source.href), [`${base}/-/blob/${revision}/src/router.js#L1-3`,@@ -251,17 +225,16 @@ test('GitLab evidence links nested groups and accepts SSH, HTTPS, suffix and cas}});-test('self-managed GitLab links require an explicit provider and keep endpoint identity', () => {+test('self-managed GitLab links require an explicit provider and keep endpoint identity', (t) => {const data = fixture();+ t.after(() => fs.rmSync(data.root, { recursive: true, force: true }));const url = 'https://git.example.internal/Platform/Services/evidence-repo';const output = path.join(data.root, 'self-managed.html');- for (const remote of [url, '[email protected]:Platform/Services/evidence-repo.git']) {+ for (const [index, remote] of [url, '[email protected]:Platform/Services/evidence-repo.git'].entries()) {data.diagram.meta.repository = { url, revision: data.revision, provider: 'gitlab' };fs.writeFileSync(data.input, JSON.stringify(data.diagram));git(data.root, 'remote', 'set-url', 'origin', remote);- const result = run(['deliver', 'architecture', data.input, output, '--repo-root', data.root, '--json']);- assert.equal(result.status, 0, `${remote}: ${result.stderr || result.stdout}`);- const evidence = evidencePayload(fs.readFileSync(output, 'utf8'));+ const evidence = verifyRemoteEvidence(data, output, { cli: index === 0 });assert.equal(evidence.repository.href, `${url}/-/tree/${data.revision}`);assert.equal(evidence.nodes.users[0].href, `${url}/-/blob/${data.revision}/src/router.js#L1-3`);}@@ -307,10 +280,11 @@ test('local-only evidence verifies HTTP self-hosted origins without generating lassert.ok(evidence.nodes.users.every((source) => !Object.hasOwn(source, 'href')));});-test('local-only supports nested HTTPS and Git SSH identities with bounded port equivalence', () => {+test('local-only supports nested HTTPS and Git SSH identities with bounded port equivalence', (t) => {const data = fixture();+ t.after(() => fs.rmSync(data.root, { recursive: true, force: true }));const output = path.join(data.root, 'portable.html');- for (const [url, remote] of [+ for (const [index, [url, remote]] of [['https://git.internal/Platform/Services/repo.git', 'https://git.internal:443/Platform/Services/repo.git'],['ssh://[email protected]/Platform/Services/repo', 'ssh://[email protected]:22/Platform/Services/repo'],['ssh://[email protected]:2222/Platform/repo.git', 'ssh://[email protected]:2222/Platform/repo.git'],@@ -320,15 +294,13 @@ test('local-only supports nested HTTPS and Git SSH identities with bounded port['https://git.internal/Platform/repo.git', 'https://user:[email protected]/Platform/repo.git'],['[email protected]:Platform/repo%41', '[email protected]:Platform/repo%41'],['ssh://[email protected]/Platform/repo%41', 'ssh://[email protected]/Platform/repoA'],- ]) {+ ].entries()) {data.diagram.meta.repository = { url, revision: data.revision, link_mode: 'local-only' };fs.writeFileSync(data.input, JSON.stringify(data.diagram));git(data.root, 'remote', 'set-url', 'origin', remote);- const result = run(['render', 'architecture', data.input, output, '--repo-root', data.root]);- assert.equal(result.status, 0, `${url}: ${result.stderr}`);- const html = fs.readFileSync(output, 'utf8');- assert.doesNotMatch(html, /SYNTHETIC_TOKEN/);- assert.equal(evidencePayload(html).repository.href, undefined);+ const evidence = verifyRemoteEvidence(data, output, { cli: index === 1 || index === 5, command: 'render' });+ assert.doesNotMatch(JSON.stringify(evidence), /SYNTHETIC_TOKEN/);+ assert.equal(evidence.repository.href, undefined);}});@@ -499,219 +471,21 @@ test('local-only preview and compare publish only revision-verified evidence', {} finally { await preview.stop(); }});-test('browser renders local-only sources as searchable text and web sources as links', {- skip: process.env.ARCHIFY_CHROME ? false : 'Set ARCHIFY_CHROME to run evidence browser checks.',- timeout: 60000,-}, async () => {- const data = fixture();- const browser = new ChromeVisualBrowser(findChrome());- try {- for (const mode of ['github', 'gitee', 'gitlab', 'local-only']) {- const local = mode === 'local-only';- const url = local ? 'http://git.internal/Team/repo' : `https://${mode}.com/example/evidence-repo`;- data.diagram.meta.repository = { url, revision: data.revision, ...(local ? { link_mode: mode } : {}) };- git(data.root, 'remote', 'set-url', 'origin', url);- fs.writeFileSync(data.input, JSON.stringify(data.diagram));- const artifactPath = path.join(data.root, `${mode}.html`);- const result = run(['deliver', 'architecture', data.input, artifactPath, '--repo-root', data.root, '--json']);- assert.equal(result.status, 0, result.stderr || result.stdout);- for (const theme of ['light', 'dark']) {- await browser.inspect({ artifactPath, width: 1440, height: 900, theme });- const sessionId = await browser.sessionPromise;- const response = await browser.cdp.send('Runtime.evaluate', {- expression: `(() => {- document.querySelector('[data-node-id="users"]').dispatchEvent(new MouseEvent('click', { bubbles: true }));- const panel = document.getElementById('focus-evidence');- const rows = [...panel.querySelectorAll('.semantic-passport-source')];- const input = document.getElementById('node-finder-input');- input.value = 'src/router.js';- input.dispatchEvent(new Event('input', { bubbles: true }));- return {- visible: !panel.hidden,- links: rows.filter(row => row.tagName === 'A').map(row => row.getAttribute('href')),- paths: rows.map(row => row.querySelector('small').textContent),- locations: rows.map(row => row.querySelector('code').textContent),- repositoryHref: document.getElementById('focus-repository').getAttribute('href'),- scope: panel.title,- badges: document.querySelectorAll('[data-source-evidence-beacon]').length,- sourceCount: document.querySelector('[data-node-id="users"]').getAttribute('data-source-evidence-count'),- sourceAria: document.querySelector('[data-node-id="users"]').getAttribute('aria-label'),- invalidLinks: [...panel.querySelectorAll('a[href]')].some(a => /undefined|javascript:/.test(a.getAttribute('href'))),- search: document.getElementById('node-finder-results').textContent- };- })()`, returnByValue: true,- }, sessionId);- assert.equal(response.exceptionDetails, undefined);- const observed = response.result.value;- assert.equal(observed.visible, true);- assert.equal(observed.badges, 0);- assert.equal(observed.sourceCount, '2');- assert.match(observed.sourceAria, /2 verified source references/);- assert.equal(observed.invalidLinks, false);- assert.deepEqual(observed.paths, ['src/router.js', 'src/store.js']);- assert.match(observed.scope, /local Git/);- assert.match(observed.search, /Users/);- assert.equal(observed.links.length, local ? 0 : 2);- assert.equal(observed.locations[0], local ? 'L1–3' : 'L1–3 ↗');- assert.equal(observed.repositoryHref, local ? null : `${url}/${mode === 'gitlab' ? '-/' : ''}tree/${data.revision}`);- }- }- } finally { await browser.close(); }-});--test('browser announces verified source counts without visual marks and restores canonical export labels', {- skip: process.env.ARCHIFY_CHROME ? false : 'Set ARCHIFY_CHROME to run evidence browser checks.',- timeout: 30000,-}, async (t) => {+test('repository evidence accepts canonical HTTPS and common SSH remotes', (t) => {const data = fixture();t.after(() => fs.rmSync(data.root, { recursive: true, force: true }));- data.diagram.meta.locale = 'zh-CN';- fs.writeFileSync(data.input, JSON.stringify(data.diagram));- const artifactPath = path.join(data.root, 'source-aria.html');- const delivered = run(['deliver', 'architecture', data.input, artifactPath, '--repo-root', data.root, '--json']);- assert.equal(delivered.status, 0, delivered.stderr || delivered.stdout);- const html = fs.readFileSync(artifactPath, 'utf8');- const initialization = html.match(/Archify\.sourceEvidence = \(function \(\) \{[\s\S]*?\}\)\(\);/)?.[0];- assert.ok(initialization);- const browser = new ChromeVisualBrowser(findChrome());- try {- await browser.inspect({ artifactPath, width: 1440, height: 900, theme: 'light' });- const sessionId = await browser.sessionPromise;- async function accessibleNodeName() {- const remote = await browser.cdp.send('Runtime.evaluate', {- expression: `document.querySelector('[data-node-id="users"]')`,- }, sessionId);- const tree = await browser.cdp.send('Accessibility.getPartialAXTree', {- objectId: remote.result.objectId, fetchRelatives: false,- }, sessionId);- const name = tree.nodes.find(node => !node.ignored)?.name?.value;- assert.equal(typeof name, 'string', JSON.stringify(tree));- return name;- }- assert.match(await accessibleNodeName(), /2 个已验证来源引用/);- const response = await browser.cdp.send('Runtime.evaluate', {- expression: `(async () => {- const reinitialize = () => { ${initialization} };- const svg = document.querySelector('.diagram-container > svg');- const node = svg.querySelector('[data-node-id="users"]');- const element = document.getElementById('archify-source-evidence-data');- const payload = JSON.parse(element.textContent);- const originalSources = payload.nodes.users.slice();- const authoredLabel = node.getAttribute('data-source-evidence-original-label');- const geometry = [...svg.querySelectorAll('rect,path,line,polyline,text')].map(el => el.outerHTML).join('');- const initial = node.getAttribute('aria-label');- reinitialize();- const repeated = node.getAttribute('aria-label');- const noVisualMarks = !svg.querySelector('[data-source-evidence-beacon], .source-evidence-beacon');- const geometryPreserved = geometry === [...svg.querySelectorAll('rect,path,line,polyline,text')].map(el => el.outerHTML).join('');- Archify.focus.set('users', { toggle: false });- const passportLinks = document.querySelectorAll('#focus-evidence a[href]').length;- const before = svg.outerHTML;- const originalCreate = URL.createObjectURL;- let exportedBlob;- URL.createObjectURL = function(blob) {- if (blob.type.startsWith('image/svg+xml')) exportedBlob = blob;- return originalCreate.call(URL, blob);- };- let exportPreservesLive;- try {- const pending = Archify.exportMenu.run('svg');- exportPreservesLive = before === svg.outerHTML;- await pending;- } finally { URL.createObjectURL = originalCreate; }- const exported = new DOMParser().parseFromString(await exportedBlob.text(), 'image/svg+xml');- const exportedLabel = exported.querySelector('[data-node-id="users"]').getAttribute('aria-label');- const exportClean = !exported.querySelector('[data-source-evidence-count], [data-source-evidence-original-label], [data-reader-legend-corner], [data-source-evidence-beacon]');- // The download anchor can clear Focus through its existing outside-click- // behavior. Reopen via the public interface to verify sources survive.- Archify.focus.set('users', { toggle: false });- const passportLinksAfter = document.querySelectorAll('#focus-evidence a[href]').length;- payload.nodes.users = [];- element.textContent = JSON.stringify(payload);- reinitialize();- const zeroRestored = node.getAttribute('aria-label') === authoredLabel && !node.hasAttribute('data-source-evidence-count');- const results = [];- for (const label of [null, '', 'Authored focus label']) {- node.removeAttribute('data-source-evidence-count');- node.removeAttribute('data-source-evidence-original-label');- if (label === null) node.removeAttribute('aria-label'); else node.setAttribute('aria-label', label);- payload.nodes.users = [originalSources[0]];- payload.verified = true;- element.textContent = JSON.stringify(payload);- reinitialize();- const once = node.getAttribute('aria-label');- reinitialize();- const twice = node.getAttribute('aria-label');- let labelBlob;- URL.createObjectURL = function(blob) {- if (blob.type.startsWith('image/svg+xml')) labelBlob = blob;- return originalCreate.call(URL, blob);- };- try { await Archify.exportMenu.run('svg'); }- finally { URL.createObjectURL = originalCreate; }- const exportedNode = new DOMParser().parseFromString(await labelBlob.text(), 'image/svg+xml').querySelector('[data-node-id="users"]');- payload.nodes.users = [];- element.textContent = JSON.stringify(payload);- reinitialize();- const zeroRestored = node.getAttribute('aria-label');- payload.nodes.users = [originalSources[0]];- element.textContent = JSON.stringify(payload);- reinitialize();- payload.verified = false;- element.textContent = JSON.stringify(payload);- reinitialize();- results.push({ once, twice, zeroRestored, exportedLabel: exportedNode.getAttribute('aria-label'), restored: node.getAttribute('aria-label'), count: node.getAttribute('data-source-evidence-count') });- }- return { initial, repeated, noVisualMarks, geometryPreserved, authoredLabel, exportedLabel,- exportClean, exportPreservesLive, passportLinks, passportLinksAfter,- zeroRestored, results };- })()`, returnByValue: true, awaitPromise: true,- }, sessionId);- assert.equal(response.exceptionDetails, undefined);- const observed = response.result.value;- assert.match(observed.initial, /2 个已验证来源引用/);- assert.equal(observed.repeated, observed.initial);- for (const key of ['noVisualMarks', 'geometryPreserved', 'exportClean', 'exportPreservesLive', 'zeroRestored']) assert.equal(observed[key], true, key);- assert.equal(observed.exportedLabel, observed.authoredLabel);- assert.equal(observed.passportLinks, 3);- assert.equal(observed.passportLinksAfter, 3);- for (const [index, result] of observed.results.entries()) {- assert.match(result.once, /1 个已验证来源引用/);- assert.equal(result.twice, result.once);- assert.equal(result.restored, [null, '', 'Authored focus label'][index]);- assert.equal(result.zeroRestored, [null, '', 'Authored focus label'][index]);- assert.equal(result.exportedLabel, [null, '', 'Authored focus label'][index]);- assert.equal(result.count, null);- }- const restored = await browser.cdp.send('Runtime.evaluate', {- expression: `(() => {- const element = document.getElementById('archify-source-evidence-data');- const payload = JSON.parse(element.textContent);- payload.verified = true;- element.textContent = JSON.stringify(payload);- ${initialization}- return document.querySelector('[data-node-id="users"]').getAttribute('aria-labelledby');- })()`, returnByValue: true,- }, sessionId);- assert.equal(restored.exceptionDetails, undefined);- assert.equal(restored.result.value, null, 'node has no competing aria-labelledby');- assert.equal(await accessibleNodeName(), 'Authored focus label, 1 个已验证来源引用');- } finally { await browser.close(); }-});--test('repository evidence accepts canonical HTTPS and common SSH remotes', () => {- const data = fixture();const output = path.join(data.root, 'remote-form.html');- for (const remote of [+ for (const [index, remote] of ['https://github.com/example/evidence-repo.git/','https://x-access-token:[email protected]/example/evidence-repo.git','https://oauth2:[email protected]/example/evidence-repo','[email protected]:example/evidence-repo.git','ssh://[email protected]/example/evidence-repo.git',- ]) {+ ].entries()) {git(data.root, 'remote', 'set-url', 'origin', remote);- const result = run(['deliver', 'architecture', data.input, output, '--repo-root', data.root, '--json']);- assert.equal(result.status, 0, `${remote}: ${result.stderr || result.stdout}`);+ const evidence = verifyRemoteEvidence(data, output, { cli: index === 1 || index === 3 });+ assert.equal(evidence.repository.href, `https://github.com/example/evidence-repo/tree/${data.revision}`);+ assert.equal(evidence.nodes.users[0].href, `https://github.com/example/evidence-repo/blob/${data.revision}/src/router.js#L1-L3`);}});diff --git a/test/repository-test-runner.test.mjs b/test/repository-test-runner.test.mjsindex b69f8b25..1b4753ff 100644--- a/test/repository-test-runner.test.mjs+++ b/test/repository-test-runner.test.mjs@@ -126,6 +126,46 @@ test('focus alias requires files and invalid options never launch a child', (t)}});+test('repository shards execute exactly their listed inventory and together cover every suite once', (t) => {+ const full = interceptedRun(t, ['--list']).stdout.trim().split('\n');+ for (const count of [2, 3]) {+ const shards = [];+ for (let index = 1; index <= count; index++) {+ const argument = `--shard=${index}/${count}`;+ const listed = interceptedRun(t, ['--list', argument]);+ assert.equal(listed.status, 0, listed.stderr);+ assert.equal(listed.stderr, '');+ const files = listed.stdout.trim().split('\n');+ assert.ok(files.length > 0);+ const executed = interceptedRun(t, [argument]);+ assert.equal(executed.status, 0, executed.stderr);+ assert.deepEqual(JSON.parse(executed.stdout).args.filter(arg => !arg.startsWith('--')), files);+ assert.ok(executed.stderr.includes(`shard ${index}/${count}`));+ shards.push(...files);+ }+ assert.equal(new Set(shards).size, shards.length, 'no test may execute in two shards');+ assert.deepEqual(shards.sort(), full, 'new and existing suites must all be dispatched');+ }+});++test('repository shards reject invalid or partial coverage before launching tests', (t) => {+ const count = fs.readdirSync(path.join(repoRoot, 'test')).filter(file => file.endsWith('.test.mjs')).length;+ for (const args of [+ ['--shard'], ['--shard=0/2'], ['--shard=1/0'], ['--shard=3/2'],+ ['--shard=01/2'], ['--shard=1/2.0'], [`--shard=1/${count + 1}`],+ ['--shard=1/9007199254740992'], ['--shard=1/2', '--shard=2/2'],+ ['--shard=1/2', 'test/cli.test.mjs'], ['--shard=1/2', '--test-name-pattern=validate'],+ ['--shard=1/2', '--require-files'],+ ]) {+ const result = interceptedRun(t, args);+ assert.equal(result.status, 1, `${args}: ${result.stderr}`);+ assert.equal(result.stdout, '', 'an invalid shard must never execute a partial green run');+ }+ const failed = interceptedRun(t, ['--shard=2/2'], { status: 7 });+ assert.equal(failed.status, 7, failed.stderr);+ assert.equal(fs.existsSync(JSON.parse(failed.stdout).cache), false);+});+for (const outcome of [{ status: 7 }, { status: null, signal: 'SIGTERM' }, { error: { message: 'spawn failed' } }]) {test(`repository runner cleans cache and propagates child failure (${outcome.signal || outcome.status || 'error'})`, (t) => {const result = interceptedRun(t, ['test/repository-test-runner.test.mjs'], outcome);diff --git a/test/skill-installation.test.mjs b/test/skill-installation.test.mjsindex f4879431..b099bfda 100644--- a/test/skill-installation.test.mjs+++ b/test/skill-installation.test.mjs@@ -15,7 +15,8 @@ const skillsPackage = require.resolve('skills/package.json');const skillsCli = path.join(path.dirname(skillsPackage), 'bin', 'cli.mjs');const [major, minor] = process.versions.node.split('.').map(Number);// Archify supports Node 18+, while this external installer's own minimum is 22.20.-// CI's Node 22 and 24 lanes exercise the real CLI; metadata tests run on all lanes.+// Canonical Node 22 regression lanes exercise the real installer. Other Node+// compatibility lanes run Archify's core smoke, not this installer matrix.const installerSkip = major > 22 || (major === 22 && minor >= 20)? false : 'skills 1.7.0 requires Node >=22.20.0';