Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(design-system): DS-10 绑定目标须为 dimension 叶 Token 且跟随审计 root
Kirozeng18873ea3156f
diff --git a/scripts/__tests__/hardcoded-color-audit.test.mjs b/scripts/__tests__/hardcoded-color-audit.test.mjsindex cae3dcce61..79eacea6d7 100644--- a/scripts/__tests__/hardcoded-color-audit.test.mjs+++ b/scripts/__tests__/hardcoded-color-audit.test.mjs@@ -189,6 +189,14 @@ test('worktree includes staged, unstaged and untracked source; commit mode exclufs.appendFileSync(path.join(temp,file), "const c = 'var(--x, #abc123)';\n");fs.writeFileSync(path.join(temp,renderer+'new.tsx'), "const style = { color: 'rgb(4,5,6)' };\n");fs.writeFileSync(path.join(temp,renderer+'plain.tsx'), "const label = 'RGB(1, 2, 3)';\n");+ // The isolated repo carries its own contract inputs: audit({root}) must+ // read and hash bindings and the DTCG source from root, not this checkout.+ const bindings = 'packages/design-tokens/src/desktop-bindings.json';+ const dtcg = 'packages/design-tokens/src/semantic/foundations.json';+ fs.mkdirSync(path.dirname(path.join(temp, bindings)), {recursive:true});+ fs.copyFileSync(path.join(root, bindings), path.join(temp, bindings));+ fs.mkdirSync(path.dirname(path.join(temp, dtcg)), {recursive:true});+ fs.copyFileSync(path.join(root, dtcg), path.join(temp, dtcg));const result = audit({root:temp,baseRef:commit,worktree:true});assert.equal(result.counts.unexpected,3);assert.deepEqual(result.findings.filter(f=>f.file===file).map(f=>f.line),[2,3]);@@ -197,6 +205,23 @@ test('worktree includes staged, unstaged and untracked source; commit mode excluassert.deepEqual(result.findings.filter(f=>f.file===renderer+'plain.tsx'),[]);assert.equal(audit({root:temp,baseRef:commit}).counts.unexpected,0);assert.equal(audit({root:temp,baseRef:commit,worktree:true}).candidateHash,result.candidateHash);+ // The isolated root's own bindings drive classification and fail-closed+ // validation — a custom valid source registers, and corruption introduced+ // between two audit calls must not be served from any stale copy.+ const localBindings = JSON.parse(fs.readFileSync(path.join(root, bindings), 'utf8'));+ localBindings.foundations.css['space-local'] = 'semantic.foundations.space-local';+ fs.writeFileSync(path.join(temp,bindings), JSON.stringify(localBindings));+ const localDtcg = JSON.parse(fs.readFileSync(path.join(root, dtcg), 'utf8'));+ localDtcg.semantic.foundations['space-local'] = { $type: 'dimension', $value: '{reference.foundations.space-4}' };+ fs.writeFileSync(path.join(temp,dtcg), JSON.stringify(localDtcg));+ fs.writeFileSync(path.join(temp,renderer+'LocalSpacing.tsx'), 'export const L = <div className="p-[var(--space-local)]" />;\n');+ const local = audit({root:temp,baseRef:commit,worktree:true});+ assert.equal(local.findings.find(f=>f.rule==='role-spacing')?.classification,'spacing-source-reference');+ fs.writeFileSync(path.join(temp,bindings),'{bad json');+ assert.throws(()=>audit({root:temp,baseRef:commit,worktree:true}));+ fs.copyFileSync(path.join(root, bindings), path.join(temp, bindings));+ fs.copyFileSync(path.join(root, dtcg), path.join(temp, dtcg));+ fs.rmSync(path.join(temp,renderer+'LocalSpacing.tsx'));// Execute the real CLI against this isolated candidate, then the actual CI// aggregation shell. A process failure must not turn into a green summary.for (const rel of ['hardcoded-color-audit.mjs', 'shared/hardcoded-color-match.mjs', 'shared/design-layer-report.mjs']) {@@ -204,12 +229,6 @@ test('worktree includes staged, unstaged and untracked source; commit mode exclufs.mkdirSync(path.dirname(target), {recursive:true});fs.copyFileSync(path.join(root, 'scripts', rel), target);}- const bindings = 'packages/design-tokens/src/desktop-bindings.json';- const dtcg = 'packages/design-tokens/src/semantic/foundations.json';- fs.mkdirSync(path.dirname(path.join(temp, bindings)), {recursive:true});- fs.copyFileSync(path.join(root, bindings), path.join(temp, bindings));- fs.mkdirSync(path.dirname(path.join(temp, dtcg)), {recursive:true});- fs.copyFileSync(path.join(root, dtcg), path.join(temp, dtcg));const cli = (...args) => spawnSync(process.execPath, ['scripts/hardcoded-color-audit.mjs', ...args], {cwd:temp,encoding:'utf8'});const failed = cli('--base-ref',commit,'--worktree','--json');assert.equal(failed.status,1,failed.stderr);@@ -252,6 +271,13 @@ test('worktree includes staged, unstaged and untracked source; commit mode exclufs.rmSync(path.join(temp,dtcg));assert.equal(cli('--base-ref',commit,'--worktree','--report').status,2);fs.copyFileSync(path.join(root, dtcg), path.join(temp, dtcg));+ // A target that exists as a key but is not a leaf dimension token — an+ // empty object or a group — never reaches generation output either.+ const leafless = JSON.parse(fs.readFileSync(path.join(root, dtcg), 'utf8'));+ leafless.semantic.foundations['space-4'] = {};+ fs.writeFileSync(path.join(temp,dtcg), JSON.stringify(leafless));+ assert.equal(cli('--base-ref',commit,'--worktree','--report').status,2);+ fs.copyFileSync(path.join(root, dtcg), path.join(temp, dtcg));fs.appendFileSync(path.join(temp,file), '\nconst spacing = "gap-x-[var(--space-4)]";\n');const reported = cli('--base-ref',commit,'--worktree','--report','--json');assert.equal(reported.status,0,reported.stderr);diff --git a/scripts/hardcoded-color-audit.mjs b/scripts/hardcoded-color-audit.mjsindex 8d5e08d509..47e6485b04 100644--- a/scripts/hardcoded-color-audit.mjs+++ b/scripts/hardcoded-color-audit.mjs@@ -8,7 +8,7 @@ import fs from 'node:fs';import path from 'node:path';import { fileURLToPath } from 'node:url';import { findBareColors, maskColorComments } from './shared/hardcoded-color-match.mjs';-import { reportDesignLayers, getSpacingVariables } from './shared/design-layer-report.mjs';+import { reportDesignLayers, readSpacingVariables } from './shared/design-layer-report.mjs';const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');const hash = (text) => createHash('sha256').update(text).digest('hex');@@ -120,7 +120,7 @@ export function addedLines(diff) {return lines;}-export function inspectFile(file, source, changed, exemptions) {+export function inspectFile(file, source, changed, exemptions, spacingVariables) {const starts = [0];for (let i = 0; i < source.length; i++) if (source[i] === '\n') starts.push(i + 1);const locate = index => {@@ -146,7 +146,7 @@ export function inspectFile(file, source, changed, exemptions) {suggestion: 'Desktop: find the matching role in themes/colors.ts and consume var(--role) / hsl(var(--role)); preserve local aliases. Mobile: use ThemeColors. If no role fits, request a design decision; do not guess a token.',}];});- const layers = scope === 'block' ? reportDesignLayers(file, clean, changed, locate) : [];+ const layers = scope === 'block' ? reportDesignLayers(file, clean, changed, locate, spacingVariables) : [];return [...colors, ...layers];}@@ -154,10 +154,10 @@ export function audit({ root = ROOT, baseRef = 'origin/main', headRef = 'HEAD',const resolve = ref => git(root, ['rev-parse', '--verify', '--end-of-options', `${ref}^{commit}`]).trim();const base = resolve(baseRef), head = resolve(headRef);const exemptions = readExemptions(root);- // Validate the spacing binding on every run: a docs- or colour-only diff- // never reaches the lazy read inside classifySpacing, and hashing alone- // would accept a corrupt contract as a clean exit.- getSpacingVariables();+ // Load and validate the spacing contract from the audited root on every+ // run: a docs- or colour-only diff never reaches the lazy read inside+ // classifySpacing, and hashing alone would accept a corrupt contract.+ const spacingVariables = readSpacingVariables(root);const range = worktree ? [base] : [base, head];const diffArgs = ['diff', '--no-ext-diff', '--no-textconv', '--no-renames'];const tracked = git(root, [...diffArgs, '--name-only', '-z', ...range, '--']).split('\0').filter(Boolean);@@ -180,14 +180,19 @@ export function audit({ root = ROOT, baseRef = 'origin/main', headRef = 'HEAD',const changed = untracked.includes(file) ? new Set(source.split('\n').map((_, i) => i + 1)): addedLines(git(root, [...diffArgs, '--unified=0', ...range, '--', file]));sources.push({ file, sha256: hash(source), addedLines: [...changed] });- try { findings.push(...inspectFile(file, source, changed, exemptions)); }+ try { findings.push(...inspectFile(file, source, changed, exemptions, spacingVariables)); }catch (error) { throw new Error(`${file}: ${error.message}`); }}- const scripts = ['scripts/hardcoded-color-audit.mjs', 'scripts/shared/hardcoded-color-match.mjs',- 'scripts/shared/design-layer-report.mjs', 'scripts/hardcoded-color-exemptions.json',- 'packages/design-tokens/src/desktop-bindings.json',+ // Code hashes bind the running scripts; input hashes bind the audited+ // root's contract inputs, so audit({root}) reports that checkout's inputs.+ const scriptFiles = ['scripts/hardcoded-color-audit.mjs', 'scripts/shared/hardcoded-color-match.mjs',+ 'scripts/shared/design-layer-report.mjs'];+ const inputFiles = ['scripts/hardcoded-color-exemptions.json', 'packages/design-tokens/src/desktop-bindings.json','packages/design-tokens/src/semantic/foundations.json'];- const scriptHashes = Object.fromEntries(scripts.map(f => [f, hash(fs.readFileSync(path.join(f === 'scripts/hardcoded-color-exemptions.json' ? root : ROOT, f)))]));+ const scriptHashes = Object.fromEntries([+ ...scriptFiles.map(f => [f, hash(fs.readFileSync(path.join(ROOT, f)))]),+ ...inputFiles.map(f => [f, hash(fs.readFileSync(path.join(root, f)))]),+ ]);const colors = findings.filter(f => f.rule === 'bare-color');return { schemaVersion: 1, base, head, candidate: worktree ? 'worktree (staged + unstaged + untracked)' : 'commit',scriptHashes, candidateHash: hash(JSON.stringify(sources)), sources,diff --git a/scripts/shared/design-layer-report.mjs b/scripts/shared/design-layer-report.mjsindex ebe4c118a2..34d26b5037 100644--- a/scripts/shared/design-layer-report.mjs+++ b/scripts/shared/design-layer-report.mjs@@ -1,38 +1,48 @@import { readFileSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';// Read the generation contract, not a second hand-maintained token allowlist.-// Exported so the audit can validate the binding on every invocation, not-// only when a spacing candidate reaches the lazy read below.-let spacingVariables;-export function getSpacingVariables() {- if (!spacingVariables) {- const { foundations } = JSON.parse(readFileSync(new URL('../../packages/design-tokens/src/desktop-bindings.json', import.meta.url), 'utf8'));- if (!foundations?.css || typeof foundations.css !== 'object' || Array.isArray(foundations.css)) {- throw new Error('Invalid desktop-bindings.json; expected foundations.css as a non-array mapping');- }- const bindings = Object.entries(foundations.css)- // Includes component spacing (space-input-lg), not only Tailwind's scale.- .filter(([, id]) => id.startsWith('semantic.foundations.space-'));- if (!bindings.length) {- throw new Error('Invalid desktop-bindings.json; foundations.css has no semantic.foundations.space-* entries');- }- // The prefix alone must not invent sources: every binding target has to- // exist as a token in the DTCG generation source the binding is built from.- const dtcg = JSON.parse(readFileSync(new URL('../../packages/design-tokens/src/semantic/foundations.json', import.meta.url), 'utf8'))?.semantic?.foundations;- if (!dtcg || typeof dtcg !== 'object' || Array.isArray(dtcg)) {- throw new Error('Invalid semantic/foundations.json; expected semantic.foundations DTCG tokens');- }- const unbound = bindings.filter(([, id]) => !dtcg[id.slice('semantic.foundations.'.length)]);- if (unbound.length) {- throw new Error(`Invalid desktop-bindings.json; spacing bindings without a DTCG token: ${unbound.map(([name]) => `--${name}`).join(', ')}`);- }- spacingVariables = new Set(bindings.map(([name]) => `--${name}`));+// readSpacingVariables(root) is fresh per call so audit({root}) always honours+// that checkout's bindings — including corruption introduced between calls;+// the cached default below only serves direct callers of this module.+const MODULE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');+export function readSpacingVariables(root) {+ const readJson = file => JSON.parse(readFileSync(path.join(root, 'packages/design-tokens/src', file), 'utf8'));+ const { foundations } = readJson('desktop-bindings.json');+ if (!foundations?.css || typeof foundations.css !== 'object' || Array.isArray(foundations.css)) {+ throw new Error('Invalid desktop-bindings.json; expected foundations.css as a non-array mapping');}- return spacingVariables;+ const bindings = Object.entries(foundations.css)+ // Includes component spacing (space-input-lg), not only Tailwind's scale.+ .filter(([, id]) => id.startsWith('semantic.foundations.space-'));+ if (!bindings.length) {+ throw new Error('Invalid desktop-bindings.json; foundations.css has no semantic.foundations.space-* entries');+ }+ // The prefix alone must not invent sources: every binding target has to+ // be a real dimension token in the DTCG generation source. A bare key, an+ // empty object or a group is not a token — the generator's flatten() only+ // emits leaves that carry $value (production.ts).+ const dtcg = readJson('semantic/foundations.json')?.semantic?.foundations;+ if (!dtcg || typeof dtcg !== 'object' || Array.isArray(dtcg)) {+ throw new Error('Invalid semantic/foundations.json; expected semantic.foundations DTCG tokens');+ }+ const unbound = bindings.filter(([, id]) => {+ const token = dtcg[id.slice('semantic.foundations.'.length)];+ return !token || typeof token !== 'object' || !('$value' in token) || token.$type !== 'dimension';+ });+ if (unbound.length) {+ throw new Error(`Invalid desktop-bindings.json; spacing bindings without a dimension DTCG token: ${unbound.map(([name]) => `--${name}`).join(', ')}`);+ }+ return new Set(bindings.map(([name]) => `--${name}`));+}+let moduleSpacing;+function getSpacingVariables() {+ moduleSpacing ??= readSpacingVariables(MODULE_ROOT);+ return moduleSpacing;}-function classifySpacing(value) {- const spacingVariables = getSpacingVariables();+function classifySpacing(value, spacingVariables = getSpacingVariables()) {const expression = value.slice(value.indexOf('[') + 1, -1);const direct = /^var\(\s*(--[\w-]+)\s*\)$/.exec(expression);if (direct && spacingVariables.has(direct[1])) {@@ -71,7 +81,7 @@ export function classifyDesignLayer({ member, layer, radius, evidence = false }): { classification: 'registered-value-violation', reason: `${member}: this visible layer requires ${expected} at all four corners (DESIGN §5).` };}-export function reportDesignLayers(file, source, changed, locate) {+export function reportDesignLayers(file, source, changed, locate, spacingVariables) {const findings = [];const patterns = /\brounded(?:-(?:\[[^\]\n]+\]|[\w-]+))?|\bborder(?:-radius|Radius)\s*:\s*[^;,}\n]+|\b(?:p[xytrblse]?|gap(?:-[xy])?)-\[[^\]\n]+\]/g;for (const match of source.matchAll(patterns)) {@@ -92,7 +102,7 @@ export function reportDesignLayers(file, source, changed, locate) {if (/^<kbd\s/.test(tag) && /\b(?:border|bg-)/.test(tag)) { member = 'keycap'; evidence = true; }const radius = /^rounded-\[([^\]]+)\]$/.exec(match[0])?.[1] ?? match[0].replace(/^rounded-/, '');const judgement = isRadius ? classifyDesignLayer({ member, layer, radius, evidence })- : classifySpacing(match[0]);+ : classifySpacing(match[0], spacingVariables);findings.push({ file, ...pos, rule: isRadius ? 'visible-layer-radius' : 'role-spacing',value: match[0], disposition: 'report', ...judgement,suggestion: isRadius