Files
cindy/scripts/hardcoded-color-audit.mjs
Kirozeng 2afecd89e5 fix(design-system): DS-10 修准间距报告并交接维护 (#4427)
* fix(design-system): DS-10 修准间距报告并交接维护

从现有 desktop-bindings 识别真实间距来源,区分未知变量、
混合计算和裸值,补齐 gap-x/gap-y 与逻辑 padding 报告。
绑定报告输入 hash,补真实 CLI 正反例与异常退出码回归。

保持现有颜色阻断和生成保护,回填 DS-9 合并状态与
DS-10 验证、维护入口及尚未完成的验收边界。

Signed-off-by: kirozeng <kirozeng@gmail.com>

* fix(design-system): DS-10 审计每次调用先校验间距绑定

审查指出:diff 无间距候选(docs-only/纯颜色)时 classifySpacing
的惰性读取不执行,损坏的 desktop-bindings.json 只被哈希、
--report 退出 0,违反已文档化的 exit-2 契约。

getSpacingVariables 导出并增加 foundations.css 结构校验,
audit() 对每次调用先行解析,两种模式对损坏/缺失绑定均退出 2。
回归测试补无间距候选 + 损坏绑定断言,证据文档补记本轮边界。

Signed-off-by: Kirozeng <kirozeng@gmail.com>

* fix(design-system): DS-10 间距绑定校验拒绝数组与空映射

审查指出:foundations.css 为数组时 typeof 判定为 object 而放行,
{"foundations":{"css":[]}} 真实 CLI 退出 0;无 space-* 条目的映射
也会让全部间距报告退化为 unknown。校验改为要求非数组 mapping 且
过滤后至少一个 spacing 条目,两类输入均退出 2,健康输入不变,
回归测试补数组与无 spacing 条目断言。

Signed-off-by: Kirozeng <kirozeng@gmail.com>

* docs(design-system): DS-10 重跑 23 组回放绑定最终脚本

按证据文档自身的流程,在 52cee8764 树上重跑全部 23 组历史
回放:counts、candidateHash、expectedBlock 与原记录逐组一致,
仅两个被改脚本的 hash 与 baseline 更新,样本数值不变,
回放证据重新绑定修复后的最终实现。

Signed-off-by: Kirozeng <kirozeng@gmail.com>

* fix(design-system): DS-10 间距绑定目标须存在于 DTCG 源

审查指出:前缀正确但目标不存在的条目(space-typo)仍能通过
非空校验,docs-only 审计退出 0,且 p-[var(--space-typo)] 会被
标成 spacing-source-reference——单个拼写错误就能伪造生成来源。

校验改为逐条核对 space-* 绑定目标在
packages/design-tokens/src/semantic/foundations.json 的
semantic.foundations 下真实存在,不存在则退出 2 并指名缺失项;
DTCG 源缺失/损坏同样退出 2。该文件纳入审计 scriptHashes 输入,
回归测试补伪造目标与 DTCG 缺失断言。

Signed-off-by: Kirozeng <kirozeng@gmail.com>

* docs(design-system): DS-10 回放再生成并纳入 DTCG 源哈希

在 373d435a5 树上重跑全部 23 组历史回放:counts、
candidateHash、expectedBlock 仍与原记录逐组一致,baseline
与脚本哈希更新,scriptHashes 新增 semantic/foundations.json,
样本数值不变,证据绑定最终实现。

Signed-off-by: Kirozeng <kirozeng@gmail.com>

* fix(design-system): DS-10 绑定目标须为 dimension 叶 Token 且跟随审计 root

复审两点:键存在但为 {} 或分组对象时仍放行,而生成器 flatten()
只产出携带 $value 的叶子(production.ts),此类目标不会进入生成
输出;audit({root}) 审计隔离仓时绑定读取未跟随 root,隔离仓的
有效 --space-local 被标 unknown、损坏绑定被忽略。

校验改为要求目标是含 $value 且 $type 为 dimension 的叶 Token;
绑定读取改为 readSpacingVariables(root) 每次审计调用新鲜执行并
将集合下穿分类链,绑定/DTCG/豁免哈希改从 root 读取。回归测试
补 {} 叶、隔离仓有效来源与调用间损坏的断言。

Signed-off-by: Kirozeng <kirozeng@gmail.com>

* docs(design-system): DS-10 回放随叶校验修复再生成

在 18873ea31 树上重跑全部 23 组历史回放:counts、
candidateHash、expectedBlock 仍逐组一致,baseline 与两个
被改脚本的哈希更新,样本数值不变,证据绑定最终实现。

Signed-off-by: Kirozeng <kirozeng@gmail.com>

* fix(design-system): DS-10 显式识别 var() fallback 为混合间距

审查指出:已登记变量带不含数字的合法 fallback(如
p-[var(--space-4,initial)])时,/\d/ 判定不到,被归为纯
spacing-expression,审阅者会误以为整个表达式都来自已验证间距源。

mixed 判定改为显式识别 var() 的 fallback(名字后带逗号),
initial、auto、嵌套 var 一律归 mixed-spacing-expression;
无 fallback 的纯 calc 派生表达式保持 spacing-expression。

Signed-off-by: Kirozeng <kirozeng@gmail.com>

* docs(design-system): DS-10 回放随 fallback 识别修复再生成

在 bf95bf72a 树上重跑全部 23 组历史回放:counts、
candidateHash、expectedBlock 仍逐组一致,baseline 与报告脚本
哈希更新,样本数值不变,证据绑定最终实现。

Signed-off-by: Kirozeng <kirozeng@gmail.com>

* fix(design-system): DS-10 间距报告纳入任意 margin 与多值裸值

复审两点:Desktop renderer 新增 mt-[3px]、mx-[7px] 等任意
margin 时完全不匹配,同一 TAILWIND_SPACING 尺度的硬编码间距
整类漏报(仓内存量 69 处);多值任意值(如 p-[14px_16px])
被单值正则归入 unclassified-spacing,无法与真正解析不了的
动态表达式区分。

pattern 增加 m/mx/my/mt/mr/mb/ml/ms/me 进同一分类链;
literal 判定支持下划线分隔的裸值列表并逐项校验数字与单位,
calc(100%-4px) 等无 var 表达式保持 unclassified。

Signed-off-by: Kirozeng <kirozeng@gmail.com>

* docs(design-system): DS-10 回放随 margin 覆盖扩展再生成

在 12987f2c9 树上重跑全部 23 组历史回放:candidateHash、颜色
计数、unexpected 全部不变,report 无漂移(历史样本新增行无
任意 margin),baseline 与报告脚本哈希更新,证据绑定最终实现。

Signed-off-by: Kirozeng <kirozeng@gmail.com>

* fix(design-system): DS-10 间距报告纳入 space-x/y 任意值

复审指出:space-x-[…] 与 space-y-[…] 也是间距消费者,但
模式不匹配,新增 space-y-[4px] 或 space-x-[var(--space-4)]
不产生 role-spacing 报告(仓内 AtMentionPanel.tsx:490、
QuotaHoverCard.tsx:310 有真实用法)。

pattern 增加 space-[xy] 进同一分类链,suggestion 文案同步;
尺度类 space-x-2 与 space-y-reverse 仍不报。

Signed-off-by: Kirozeng <kirozeng@gmail.com>

* docs(design-system): DS-10 回放随 space-x/y 覆盖再生成

在 a4bad4e6a 树上重跑全部 23 组历史回放:candidateHash、颜色
计数、unexpected 全部不变,report 无漂移,baseline 与报告
脚本哈希更新,证据绑定最终实现。

Signed-off-by: Kirozeng <kirozeng@gmail.com>

* fix(design-system): DS-10 非 token 操作数归入混合间距

复审指出:已登记 token 与非数字来源组合(如
p-[calc(var(--space-4)_+_env(safe-area-inset-top))])时,
数字检测判不到,被归为纯 spacing-expression,而 env() 操作数
既非已验证引用也非字面量,审阅者失去区分。

mixed 判定改为残差检测:剥离已登记 var() 调用、calc 关键字
与纯操作符后,剩余任何内容(字面量、fallback、env()/min()
操作数)都归 mixed-spacing-expression;仅由已登记引用与
calc 操作符构成的表达式保持 spacing-expression,原有数字与
fallback 行为被残差检测完全覆盖。

Signed-off-by: Kirozeng <kirozeng@gmail.com>

* docs(design-system): DS-10 回放随残差检测修复再生成

在 4f0cbbc2 树上重跑全部 23 组历史回放:candidateHash、颜色
计数、unexpected 全部不变,report 无漂移,baseline 与报告
脚本哈希更新,证据绑定最终实现。

Signed-off-by: Kirozeng <kirozeng@gmail.com>

* fix(design-system): DS-10 裸间距单位按 CSS 维度语法识别

复审指出:p-[1lh]、mt-[2dvh]、gap-[1cqw]、p-[12PX] 被单位
白名单归入 unclassified-spacing,而排版门禁
(typographyDiscipline.test.ts)已明确认可 dvh/lh/cqw/pt 与
大写单位,且其原则就是数字开头的现代单位不得依赖单位枚举。

literal 判定改为数字加任意字母单位或 %(大小写不敏感),
单值与下划线多值同口径;env()/calc()/字号关键字等非数字
开头的表达式保持 unclassified-spacing。

Signed-off-by: Kirozeng <kirozeng@gmail.com>

* docs(design-system): DS-10 回放随维度语法识别修复再生成

在 f2b5b81e 树上重跑全部 23 组历史回放:candidateHash、颜色
计数、unexpected 全部不变,report 无漂移,baseline 与报告
脚本哈希更新,证据绑定最终实现。

Signed-off-by: Kirozeng <kirozeng@gmail.com>

---------

Signed-off-by: kirozeng <kirozeng@gmail.com>
Signed-off-by: Kirozeng <kirozeng@gmail.com>
2026-09-15 14:35:25 +07:00

231 lines
13 KiB
JavaScript

#!/usr/bin/env node
/** Added-line design audit. Report first, then block only the mature colour scope.
* Explicit refs are compared directly; --worktree includes staged, unstaged and
* untracked source files. No shell interpolation, index writes or commits. */
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
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, 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');
const EXTENSIONS = /\.(?:[cm]?[jt]sx?|css|html|md|json|svg)$/;
export function git(root, args) {
return execFileSync('git', args, { cwd: root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
}
/** Existing Mobile discipline continues independently; new diff blocking starts
* with Desktop renderer consumers. Other sources stay visible as report/allowed. */
export function colorScope(file) {
if (/\/(?:__tests__|__mocks__|fixtures)\/|\.(?:test|spec)\./.test(file)) return 'test';
if (file === 'apps/desktop/src/renderer/themes/colors.ts'
|| /^apps\/desktop\/src\/renderer\/themes\/builtin\/[^/]+\.ts$/.test(file)
|| file === 'apps/mobile/src/theme/tokens.ts') return 'source';
if (file.startsWith('apps/desktop/src/renderer/')
&& !/\/(?:assets|vendor)\//.test(file) && /\.(?:[cm]?[jt]sx?|css|html)$/.test(file)) return 'block';
return 'report';
}
export function readExemptions(root) {
const data = JSON.parse(fs.readFileSync(path.join(root, 'scripts/hardcoded-color-exemptions.json'), 'utf8'));
if (!Array.isArray(data) || data.some(e => !e.glob || !e.reason || !e.owner)) {
throw new Error('Invalid hardcoded-color-exemptions.json; expected glob/reason/owner');
}
for (const entry of data) {
if (entry.matches !== undefined && !Array.isArray(entry.matches)) throw new Error(`Invalid matches: ${entry.glob}`);
for (const rule of entry.matches ?? []) {
if (typeof rule.value !== 'string' || typeof rule.before !== 'string' || !rule.before || !entry.reviewDate) throw new Error(`Invalid narrow exemption: ${entry.glob}`);
if (rule.object !== undefined && !(typeof rule.object === 'string' ? rule.object
: Array.isArray(rule.object) && rule.object.length && rule.object.every(o => typeof o === 'string' && o))) {
throw new Error(`Invalid object binding: ${entry.glob}`);
}
new RegExp(rule.before);
}
}
return data;
}
/** Key path of the object literals enclosing index, outermost first — e.g.
* ['VARIANT_MAP', 'info'] for a colour inside `VARIANT_MAP = { info: { … } }`.
* Anonymous blocks (function bodies, call arguments, array literals) add no
* segment; string contents are skipped. Lexical, like the rest of this
* scanner: unbalanced braces inside regex literals can only fail closed
* (the binding stops matching and the hit is reported). */
export function objectPathAt(source, index) {
const stack = [];
let quote = '';
for (let i = 0; i < index; i++) {
const char = source[i];
if (quote) {
if (char === '\\') i++;
else if (char === quote) quote = '';
continue;
}
if (char === '"' || char === "'" || char === '`') { quote = char; continue; }
if (char === '{') {
const head = source.slice(Math.max(0, i - 200), i);
// `key: {` (optionally quoted), `NAME = {` and `NAME: Type = {`; the
// type annotation may not cross statement or block boundaries, and the
// 200-char window bounds how far back we look for the declared name.
const prop = /["']?([A-Za-z_$][\w$]*)["']?\s*:\s*$/.exec(head);
const decl = /([A-Za-z_$][\w$]*)\s*(?::[^;{}=]*)?=\s*$/.exec(head);
stack.push(prop ? prop[1] : decl ? decl[1] : null);
} else if (char === '}' && stack.length) stack.pop();
}
return stack.filter(Boolean);
}
export function approvedColor(file, source, hit, exemptions) {
let enclosing; // lazy: object key path at the hit, shared by every rule below
return exemptions.find(entry => {
const glob = new RegExp('^' + entry.glob.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*') + '$');
if (!glob.test(file)) return false;
// Old broad entries are historical records, never consumer-file bypasses.
return (entry.matches ?? []).some(rule => {
if (hit.value.toLowerCase().replace(/\s/g, '') !== rule.value.toLowerCase().replace(/\s/g, '')) return false;
if (!new RegExp(`(?:^|[^\\w-])(?:${rule.before})$`).test(source.slice(0, hit.index))) return false;
if (rule.selector) {
const open = source.lastIndexOf('{', hit.index);
const prevClose = source.lastIndexOf('}', open);
const normalize = value => value.replace(/'/g, '"').replace(/\s+/g, ' ').trim();
if (normalize(source.slice(prevClose + 1, open)) !== normalize(rule.selector)) return false;
}
// Bind the exception to the approved object (and variant/skin): the same
// value under the same property in any other object of the file stays a
// violation. Without this, a new object could reuse an approved colour.
if (rule.object) {
enclosing ??= objectPathAt(source, hit.index).join('.');
const objects = Array.isArray(rule.object) ? rule.object : [rule.object];
if (!objects.includes(enclosing)) return false;
}
return true;
});
});
}
export function addedLines(diff) {
const lines = new Set();
let current = null;
for (const line of diff.split('\n')) {
if (line.startsWith('@@')) {
const match = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(line);
if (!match) throw new Error('Malformed diff hunk');
current = Number(match[1]);
} else if (current !== null && line.startsWith('+')) lines.add(current++);
else if (current !== null && line.startsWith(' ')) current++;
}
return lines;
}
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 => {
let low = 0, high = starts.length;
while (low + 1 < high) { const mid = (low + high) >> 1; if (starts[mid] <= index) low = mid; else high = mid; }
return { line: low + 1, column: index - starts[low] + 1 };
};
const scope = colorScope(file);
const clean = maskColorComments(source);
const colors = findBareColors(source).flatMap(hit => {
const pos = locate(hit.index);
const end = locate(hit.end - 1).line;
const addedLine = [...changed].filter(line => line >= pos.line && line <= end).sort((a, b) => a - b)[0];
if (addedLine === undefined) return [];
const candidatePos = addedLine === pos.line ? pos : { line: addedLine, column: 1 };
const exemption = approvedColor(file, clean, hit, exemptions);
const disposition = exemption || scope === 'source' || scope === 'test' ? 'allowed' : scope;
return [{ file, ...candidatePos, literalStart: pos, rule: 'bare-color', value: hit.value, disposition,
reason: exemption?.reason ?? (scope === 'source' ? 'Governed colour source; existing theme guards still apply.'
: scope === 'test' ? 'Test/fixture colour, not a production consumer.'
: scope === 'report' ? 'Literal colour outside the newly blocking scope; inspect its role (documentation, asset, runtime or future UI scope), not automatically a violation.'
: 'Literal colour bypasses semantic Light/Dark theme roles (including literal fallbacks).'),
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, spacingVariables) : [];
return [...colors, ...layers];
}
export function audit({ root = ROOT, baseRef = 'origin/main', headRef = 'HEAD', worktree = false } = {}) {
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);
// 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);
const untracked = worktree ? git(root, ['ls-files', '--others', '--exclude-standard', '-z', '--', 'apps', 'packages', 'scripts', 'docs', '.github']).split('\0').filter(Boolean) : [];
const files = [...new Set([...tracked, ...untracked])].filter(f => EXTENSIONS.test(f)).sort();
const findings = [], sources = [];
for (const file of files) {
let source;
if (worktree) {
const absolute = path.join(root, ...file.split('/'));
if (!fs.existsSync(absolute)) continue; // deleted file
if (!fs.lstatSync(absolute).isFile()) throw new Error(`Not a regular source file: ${file}`);
source = fs.readFileSync(absolute, 'utf8');
} else {
const entry = git(root, ['ls-tree', head, '--', file]);
if (!entry) continue;
if (!/^100(?:644|755) blob /.test(entry)) continue; // symlink/gitlink is not source
source = git(root, ['show', `${head}:${file}`]);
}
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, spacingVariables)); }
catch (error) { throw new Error(`${file}: ${error.message}`); }
}
// 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([
...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,
counts: { raw: colors.length, allowed: colors.filter(f => f.disposition === 'allowed').length,
unexpected: colors.filter(f => f.disposition === 'block').length,
report: findings.filter(f => f.disposition === 'report').length }, findings };
}
export function main(args = process.argv.slice(2)) {
const options = {};
let report = false, json = false;
for (let i = 0; i < args.length; i++) {
if (args[i] === '--report') report = true;
else if (args[i] === '--json') json = true;
else if (args[i] === '--worktree') options.worktree = true;
else if (['--base-ref', '--head-ref'].includes(args[i])) {
if (!args[i + 1] || args[i + 1].startsWith('--')) throw new Error(`Missing value for ${args[i]}`);
options[args[i] === '--base-ref' ? 'baseRef' : 'headRef'] = args[++i];
} else throw new Error(`Unknown argument: ${args[i]}`);
}
if (options.worktree && options.headRef) throw new Error('--worktree and --head-ref are mutually exclusive');
const result = audit(options);
if (json) console.log(JSON.stringify(result, null, 2));
else {
console.log(`BASE ${result.base} HEAD ${result.head} ${result.candidate}\n${JSON.stringify(result.counts)}`);
for (const f of result.findings.filter(f => f.disposition !== 'allowed')) {
console.log(`${f.file}:${f.line}:${f.column} [${f.disposition}/${f.rule}] ${f.value}\n ${f.reason}\n ${f.suggestion}`);
}
}
return !report && result.counts.unexpected > 0 ? 1 : 0;
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
try { process.exitCode = main(); }
catch (error) { console.error(`[design-audit] ${error.message}`); process.exitCode = 2; }
}