From c9cba447309979a0fbf7e93a99a5f25cca7983ee Mon Sep 17 00:00:00 2001 From: babycoder-dev Date: Wed, 7 Oct 2026 14:22:56 +0800 Subject: [PATCH 1/2] feat(ci): make the UI fidelity A-class gate an executable check MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A1/A2/A4 were described as machine-checkable in docs/development-workflow.md §7 but had no script and no CI step, so in practice they were self-attestation. Adds scripts/check-ui-fidelity.mjs (pure filesystem walk, no subprocess, sandbox-safe), a pnpm fidelity script, the verify chain and a CI step, plus docs/agent-workflow.md as the single source of truth for agent collaboration infrastructure. --- .github/workflows/ci.yml | 1 + docs/agent-workflow.md | 93 ++++++++++++++ docs/development-workflow.md | 3 +- docs/doc-index.md | 7 +- package.json | 3 +- scripts/check-ui-fidelity.mjs | 235 ++++++++++++++++++++++++++++++++++ 6 files changed, 339 insertions(+), 3 deletions(-) create mode 100644 docs/agent-workflow.md create mode 100644 scripts/check-ui-fidelity.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 15c55b7..8c01cdf 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -41,6 +41,7 @@ jobs: NODE_ENV: production PLATFORM_BOOTSTRAP_ADMIN_PASSWORD: ci-admin-password - run: pnpm lint + - run: pnpm fidelity - run: pnpm typecheck - run: pnpm test - run: pnpm test:db diff --git a/docs/agent-workflow.md b/docs/agent-workflow.md new file mode 100644 index 0000000..19f155d --- /dev/null +++ b/docs/agent-workflow.md @@ -0,0 +1,93 @@ +# Agent 协作与研发基建 + +状态:2026-10-05 立项(P0 进行中)| 定位:本仓「人 + 编码代理如何协作」的单一事实源。 +权威性低于 `docs/constitution.md` / ADR / RFC,高于任务包;只写**怎么做**,不重复**做什么**。 + +## 0. 为什么有这份文档 + +项目由「人 + 多个编码代理」推进(Claude Code / Codex / DeepSeek Harness)。相关约定此前散落在 +`.claude/`、`docs/ai-handoff.md`、`docs/development-workflow.md` §6/§7 与各 `CLAUDE.md` 里, +且**手工维护的状态文档已被证明会漂移**:`docs/ai-handoff.md` 停在 M3.5(最新提交写 `9c887bd`), +而项目当时已走到 M9 合并完成——漂移约 4.5 个月,期间无人察觉。 + +本文件吸收 DeepSeek Harness(DSH)的机制形态,把这些约定收敛到**可执行的守卫**上,并为长任务、 +技能、编排三类协作能力定下承载物与引入顺序。 + +## 1. 第一原则 + +1. **承诺必须落到会红的检查上**;文档只做指针,不做守卫。写不出命令的「已完成」不算完成。 +2. **一行日志不是证据**。2026-10-05 实测教训:`@nx/enforce-module-boundaries` 会偶发打印 + `No cached ProjectGraph is available. The rule will be skipped.`,但同一次运行**照样抓出越界依赖** + (`pnpm -r` / `nx run-many` / `pnpm --filter` 三条路径实测均 exit 1)。据此断言「守卫失效」是错的—— + 判断执法强度只能靠**故意违规的负向验证**,不能靠日志措辞。 +3. **自证是最弱的一环**。凡规则声称「可静态/机器核验」,就必须有对应的脚本与 CI 步骤。 + +## 2. 门禁清单(可执行物 → 谁跑) + +| 守卫 | 承载物 | 何时跑 | +| --- | --- | --- | +| UI 还原度 A 类(A1 零 hex / A2 零 emoji / A4 只引 token) | `scripts/check-ui-fidelity.mjs`(`pnpm fidelity`) | 本地 `pnpm verify` + CI | +| 模块边界 | eslint `@nx/enforce-module-boundaries`(三条 lint 路径实测生效)+ `.claude/hooks/guard-module-boundary.mjs`(写入期即时反馈) | lint / CI / 编辑时 | +| 交付门禁 | `pnpm verify`;涉 DB 加 `verify:full`,涉部署加 `docker:build` | 每次交付 | +| 证据纪律 | PR 模板 + `docs/verification-log.md` 条目形状 | PR | +| 设计还原度 B 类(人工并排比对,覆盖交互态) | 不可机器化,定稿前人工做 | 评审 | + +A 类规则的**边界**(未覆盖项,改动时需一并决策):A3(关键文案逐字一致)由 `*.spec.tsx` 断言承担; +A4 只覆盖 `padding|margin|gap|border-radius|box-shadow|font|font-size`,`letter-spacing` / +`line-height` / `transform` 的取值口径待定;TSX 内联样式不在扫描范围内。 + +## 3. 方言与挂载:一份实现、多入口 + +现状与目标:hook 逻辑一律放 `scripts/hooks/*.mjs`(方言无关、纯 Node、**不 spawn 子进程**), +各工具的配置只负责**挂载**: + +| 方言 | 挂载点 | 现状 | +| --- | --- | --- | +| Claude Code | `.claude/settings.json` → hooks | 已挂 4 个 | +| Codex | `.codex/` 等价配置 | **待补(P0)** | +| DSH | 仓库内配置 | **待补(P0)** | + +约定:hook 异常一律放行,绝不阻塞会话;唯一例外是**真边界违规**,用 `ask` 交人定夺,不硬拒 +(避免误报把工作流卡死)。 + +现有 4 个 hook 的职责:`guard-module-boundary`(写入期边界)、`format-on-edit`(prettier + eslint --fix)、 +`load-progress`(SessionStart 注入进度快照)、`remind-on-stop`(结束前提醒门禁与文档沉淀)。 + +## 4. 长任务与状态:替代手工 handoff + +- **进度单一事实源** = `docs/foundation-progress.md`;会话启动由 `load-progress.mjs` 抽「总览 / 当前下一步 / + 当前阻塞项」注入上下文。动态内容走 hook,**不写进 `CLAUDE.md`**(后者只留稳定指针与坑)。 +- **`docs/ai-handoff.md` 废弃**(P1):手工维护的会话状态已被证明必然漂移,其职责由「进度注入 + git 历史」 + 承担。 +- **长任务纪律**(借鉴 DSH goal,P1):phase = `active | paused | blocked | complete`;`blocked` 仅当 + **同一阻塞连续 ≥ 3 轮**且能给出具体阻塞条件时才允许,否则继续推进或在对话中问人;**resume / fork 后 + 不自复活**,必须由人显式恢复。承载物:`docs/goal/.md` + `scripts/goal.mjs`(校验非法转移与阈值)。 + +## 5. 技能(Skills) + +- 布局 `.agents/skills//SKILL.md`;frontmatter 必填 `name` + `description`,可选 `whenToUse`; + 正文按需加载,目录只索引 frontmatter。 +- 只放**可复用的操作手册**,不放规则(规则在 constitution / ADR / RFC)。首批(P1):任务包模板、 + 还原度门禁流程、数据库迁移纪律。 + +## 6. 多代理编排(Workflow) + +- **出现真实 fan-out 需求才引入**(例:多文件审计 + 逐候选独立复核),且**只做一个用例,不建通用引擎** + (沿 ADR-0005「不建引擎」原则)。 +- 若照搬 DSH 语义:pipeline 阶段间**无栅栏**,某阶段失败只把该 item 丢成 `null` 并跳过后续阶段; + 而**编排脚本自身的误用(参数错、超 schema)应 fail-fast 终止整个脚本**,不得静默降级。 +- 承载物:`workflows/*.mjs` 或直接复用 CI matrix(P1 决策)。 + +## 7. 明确不做(不搬清单) + +- DSH 的**沙箱真实强制**(受限令牌 / ACL / 每工作区 SID):需要隔离或并行时,改由**容器或 CI runner** 承担边界。 +- DSH 的 **subagent 运行时**:与进程模型强耦合,搬出去只会变成负担。 +- 为文档体系**再写总纲**:本文件即收口点,新增机制写进本节表格,不新开顶层文档。 + +## 8. 落地顺序 + +- **P0 · 承诺变守卫**:A 类门禁脚本化(✅ 已落地)→ 方言统一(补齐 Codex / DSH 挂载)→ 证据门禁 + (PR 模板 + verification-log 条目形状校验)。 +- **P1 · 长任务与协作**:goal 纪律 + 废弃 `ai-handoff.md` → 首批 skills → 一个真实 workflow 用例。 +- **P2 · 文档治理**:`docs/` 顶层 7 篇不在 `doc-index` 管辖内的文档逐一定性(纳入 / 归档 / 删除); + `iteration-roadmap.md`(自标已过时)归档。 diff --git a/docs/development-workflow.md b/docs/development-workflow.md index b15cfa0..db0856c 100644 --- a/docs/development-workflow.md +++ b/docs/development-workflow.md @@ -124,7 +124,8 @@ AI 每完成一个可交付片段,应执行或说明以下结果: 组件库 Modal 的还原 follow-up 见 `docs/design/ui-fidelity-gap-modal.md`(登记于 `docs/foundation-progress.md` §7.2)。 设计真源在 `docs/design/ui-handoff/`(只读基准,勿改)。 -- **A 类 · 实现方交付前必须自证(可静态/机器核验):** +- **A 类 · 已脚本化(会红的检查):** `pnpm fidelity` → `scripts/check-ui-fidelity.mjs` 覆盖 A1/A2/A4, + 已接入 `pnpm verify` 与 CI。下列条目即该脚本的规则来源;改规则必须同步脚本与本节。 - A1 零硬编码 hex:`apps/**/src` 与 `packages/ui/src` 的颜色只引 `var(--*)`;唯一允许出现 hex 的是 `packages/ui/src/styles/tokens.css`(token 唯一真源)。 - A2 零 emoji 当图标:图标一律用线性 SVG(`@work/ui` 的 `Icon`),不得用 emoji/首字母占位。 diff --git a/docs/doc-index.md b/docs/doc-index.md index 7a96a81..cca2a82 100644 --- a/docs/doc-index.md +++ b/docs/doc-index.md @@ -13,7 +13,7 @@ 5. `docs/product-requirements.md`:业务产品需求的单一事实源(要什么、给谁、边界),各 RFC 据此落地。 6. `docs/rfc/*.md`:某个阶段或重大能力的落地规格。 7. `docs/architecture.md`:当前目标架构说明。 -8. `docs/module-contract.md`、`docs/platform-core.md`、`docs/im-foundation.md` 等专题文档。 +8. `docs/module-contract.md`、`docs/platform-core.md`、`docs/im-foundation.md`、`docs/agent-workflow.md` 等专题文档。 9. `docs/tasks/*.md`:单切片任务包,自包含、可执行、可验收;不定义新规则,权威性低于 RFC 与专题文档。 10. `docs/runbooks/*.md`:可重跑的操作手册(部署、smoke、迁移演练等),自包含、可执行;不定义新规则。 11. `docs/research/*.md`:开源深评 spike 报告,支撑对应里程碑 RFC 的决策输入;不定义新规则,权威性同任务包。 @@ -165,6 +165,7 @@ docs/research/README.md 与该里程碑对应 spike 报告 | `docs/security-baseline.md` | 安全基线和强制要求 | 认证、授权、审计、密钥、部署安全变化 | | `docs/deployment.md` | 部署说明 | Docker、环境变量、部署流程变化 | | `docs/development-workflow.md` | 开发流程 | Git、测试、代码审查流程变化 | +| `docs/agent-workflow.md` | Agent 协作与研发基建 | 代理协作机制、门禁、长任务约定变化 | | `docs/runbooks/*.md` | 可重跑操作手册 | 每个 runbook 主题首次落地时 | | `docs/research/*.md` | 开源深评 spike 报告 | 每个大组件 RFC 前置 spike 完成时 | | `docs/verification-log.md` | 验证记录 | 每个重要交付点后追加 | @@ -268,6 +269,10 @@ RFC: M1 Platform Core 持久化的 schema、迁移、seed、session、测试方 agent-runtime/teable-anatomy 已产出,LLM spike 已取消) - vNext 首个 spike 任务包:`docs/tasks/vnext-spike-openim-deployment.md`(OpenIM 部署裁剪 评估,M13 前置;产出 `docs/research/openim-deployment-evaluation.md`) +- Agent 协作与研发基建约定:`docs/agent-workflow.md`(第一原则「承诺必须落到会红的检查上」; + 门禁清单 + A 类还原度脚本 `scripts/check-ui-fidelity.mjs`(`pnpm fidelity`,已接入 `pnpm verify` + 与 CI);方言挂载、长任务 goal 纪律、skills 与 workflow 承载物、不搬清单、P0/P1/P2 落地顺序。 + 2026-10-05 立项,P0 首项已落地) 后续建议补充: diff --git a/package.json b/package.json index d2aad9f..531d478 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,8 @@ "test:watch": "vitest --config vitest.config.mts", "test:e2e": "vitest run --config vitest.e2e.config.mts apps/platform-api/src/platform-api.e2e-spec.ts apps/gateway-api/src/forms-files-gateway.e2e-spec.ts apps/gateway-api/src/files-upload.e2e-spec.ts apps/gateway-api/src/forms-definition.e2e-spec.ts apps/gateway-api/src/people-aggregation.e2e-spec.ts apps/gateway-api/src/notification.e2e-spec.ts apps/gateway-api/src/notification-stream.e2e-spec.ts apps/gateway-api/src/scheduler.e2e-spec.ts apps/gateway-api/src/presence-status-types.e2e-spec.ts apps/gateway-api/src/presence-registration-forms.e2e-spec.ts apps/gateway-api/src/presence-board-realtime.e2e-spec.ts", "test:e2e:postgres": "vitest run --config vitest.e2e.config.mts apps/platform-api/src/platform-api.postgres.e2e-spec.ts apps/gateway-api/src/presence.e2e-spec.ts apps/gateway-api/src/files-upload.postgres.e2e-spec.ts", - "verify": "pnpm lint && pnpm typecheck && pnpm test && pnpm test:e2e && pnpm build", + "fidelity": "node scripts/check-ui-fidelity.mjs", + "verify": "pnpm lint && pnpm fidelity && pnpm typecheck && pnpm test && pnpm test:e2e && pnpm build", "verify:full": "pnpm verify && pnpm test:db && pnpm test:e2e:postgres", "build": "pnpm -r --if-present build", "docker:build": "docker compose -f infra/docker-compose.prod.yml build", diff --git a/scripts/check-ui-fidelity.mjs b/scripts/check-ui-fidelity.mjs new file mode 100644 index 0000000..f738796 --- /dev/null +++ b/scripts/check-ui-fidelity.mjs @@ -0,0 +1,235 @@ +#!/usr/bin/env node +// UI 设计还原度门禁 · A 类(可机器核验部分) +// +// 把 docs/development-workflow.md §7 里"A 类 · 实现方交付前必须自证"的条目 +// 变成**会红的检查**,而不是靠实现方(人或代理)宣称。规则出处见该节与 +// docs/tasks/ui-foundation-fidelity.md §2。 +// +// 覆盖(当前): +// A1 零硬编码 hex:UI 源码里的颜色只能引 var(--*),唯一允许出现 hex 的位置是 +// packages/ui/src/styles/tokens.css(token 唯一真源)。 +// A2 零 emoji 当图标:图标一律用线性 SVG(@work/ui 的 Icon),不得用 emoji 占位。 +// A4 只引 token:间距/圆角/阴影/字体(padding|margin|gap|border-radius|box-shadow| +// font|font-size)不得写裸 px/rem/em 字面量,须引 token 变量 +// (--sp-*、--r-*、--shadow-*、--font*)。 +// +// 不在本脚本范围(有意):A3(关键文案逐字一致)由 *.spec.tsx 的断言承担; +// B 类人工抽查不可机器化;letter-spacing / line-height / transform 等属性暂不在 +// A4 列表内(其取值口径待定,见 docs/agent-workflow.md 的 follow-up)。 +// +// 设计取舍:纯文件系统遍历,**不 spawn 子进程**(不调用 git/eslint),因此 +// 在受限沙箱与 CI 里行为一致,也不受工作区 git 状态影响。 +// +// 用法:node scripts/check-ui-fidelity.mjs [--verbose] +// 退出码:0 = 通过;1 = 有违规。 + +import { readFileSync, readdirSync, statSync } from 'node:fs'; +import path from 'node:path'; + +const REPO = path.resolve(import.meta.dirname, '..'); +const VERBOSE = process.argv.includes('--verbose'); + +// 唯一允许出现 hex 的位置(token 真源)。 +const HEX_ALLOWED = ['packages/ui/src/styles/tokens.css']; + +const SKIP_DIRS = new Set([ + 'node_modules', + 'dist', + 'build', + 'coverage', + '.git', + '.nx', + '.turbo', + '.vite', + 'worktrees', +]); + +const EXTENSIONS = new Set(['.css', '.ts', '.tsx', '.html']); + +// A2 例外:这几个字符是文本勾叉(常用于日志/注释),不是"emoji 当图标"。 +const EMOJI_ALLOWED = new Set(['\u2713', '\u2714', '\u2717', '\u2718']); + +const EMOJI_RE = + /[\u{1F000}-\u{1FAFF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}\u{2B00}-\u{2BFF}\u{FE0F}]/gu; + +const HEX_RE = /#[0-9a-fA-F]{3,8}\b/g; + +// A4 覆盖的属性 → 说明用的人类可读分组。 +const TOKEN_ONLY_PROPS = [ + [/^(padding|margin)(-top|-right|-bottom|-left)?$/, '间距'], + [/^(row-)?gap$/, '间距'], + [/^column-gap$/, '间距'], + [/^border-radius$/, '圆角'], + [/^border-(top|bottom)-(left|right)-radius$/, '圆角'], + [/^box-shadow$/, '阴影'], + [/^font$/, '字体'], + [/^font-family$/, '字体'], + [/^font-size$/, '字体'], +]; +const LENGTH_RE = /\b\d*\.?\d+(px|rem|em)\b/; + +/** A 类扫描范围:apps 下各 app 的 src、modules 下各模块的 web/src、packages/ui/src。 */ +function inScope(rel) { + if (rel.startsWith('packages/ui/src/')) return true; + if (/^apps\/[^/]+\/src\//.test(rel)) return true; + if (/^modules\/[^/]+\/web\/src\//.test(rel)) return true; + return false; +} + +function walk(dir, out = []) { + let entries; + try { + entries = readdirSync(dir, { withFileTypes: true }); + } catch { + return out; + } + for (const entry of entries) { + if (entry.isDirectory()) { + if (SKIP_DIRS.has(entry.name)) continue; + walk(path.join(dir, entry.name), out); + continue; + } + if (!entry.isFile()) continue; + const abs = path.join(dir, entry.name); + if (!EXTENSIONS.has(path.extname(entry.name).toLowerCase())) continue; + out.push(abs); + } + return out; +} + +/** 收集扫描根:三个范围各自的父目录,避免整仓遍历。 */ +function scanRoots() { + const roots = []; + const appsDir = path.join(REPO, 'apps'); + for (const name of readdirSync(appsDir, { withFileTypes: true })) { + if (name.isDirectory() && !SKIP_DIRS.has(name.name)) { + const src = path.join(appsDir, name.name, 'src'); + if (isDir(src)) roots.push(src); + } + } + const modulesDir = path.join(REPO, 'modules'); + for (const name of readdirSync(modulesDir, { withFileTypes: true })) { + if (name.isDirectory() && !SKIP_DIRS.has(name.name)) { + const src = path.join(modulesDir, name.name, 'web', 'src'); + if (isDir(src)) roots.push(src); + } + } + const uiSrc = path.join(REPO, 'packages', 'ui', 'src'); + if (isDir(uiSrc)) roots.push(uiSrc); + return roots; +} + +function isDir(p) { + try { + return statSync(p).isDirectory(); + } catch { + return false; + } +} + +const violations = []; +function report(rel, line, col, rule, message, snippet) { + violations.push({ rel, line, col, rule, message, snippet }); +} + +/** 逐行扫描,返回 [lineNumber, lineText]。 */ +function* lines(text) { + const parts = text.split(/\r?\n/); + for (let i = 0; i < parts.length; i++) yield [i + 1, parts[i]]; +} + +function checkA1(rel, lineNo, line) { + if (HEX_ALLOWED.includes(rel)) return; + for (const match of line.matchAll(HEX_RE)) { + report( + rel, + lineNo, + match.index + 1, + 'A1', + `硬编码颜色 ${match[0]};颜色只能引 var(--*),token 真源是 packages/ui/src/styles/tokens.css`, + line.trim(), + ); + } +} + +function checkA2(rel, lineNo, line) { + for (const match of line.matchAll(EMOJI_RE)) { + if (EMOJI_ALLOWED.has(match[0])) continue; + report( + rel, + lineNo, + match.index + 1, + 'A2', + `出现 emoji「${match[0]}」;图标必须用 @work/ui 的线性 Icon,不得用 emoji 占位`, + line.trim(), + ); + } +} + +/** A4 只作用于 CSS 声明行(`prop: value;`)。 */ +function checkA4(rel, lineNo, line) { + if (rel.endsWith('tokens.css')) return; + const decl = /^\s*([a-z-]+)\s*:\s*([^;{]+);/i.exec(line); + if (!decl) return; + const [, prop, value] = decl; + const group = TOKEN_ONLY_PROPS.find(([re]) => re.test(prop.toLowerCase())); + if (!group) return; + const literal = LENGTH_RE.exec(value); + if (!literal) return; + report( + rel, + lineNo, + line.indexOf(value) + 1, + 'A4', + `${group[1]}属性 ${prop} 写了裸长度 ${literal[0]};须引 token(--sp-*/--r-*/--shadow-*/--font*)`, + line.trim(), + ); +} + +const roots = scanRoots(); +const files = []; +for (const root of roots) walk(root, files); + +let scanned = 0; +for (const abs of files) { + const rel = path.relative(REPO, abs).split(path.sep).join('/'); + if (!inScope(rel)) continue; + let text; + try { + text = readFileSync(abs, 'utf8'); + } catch { + continue; + } + scanned++; + for (const [lineNo, line] of lines(text)) { + checkA1(rel, lineNo, line); + checkA2(rel, lineNo, line); + if (rel.endsWith('.css')) checkA4(rel, lineNo, line); + } +} + +if (VERBOSE) { + console.log(`扫描 ${scanned} 个文件(A 类范围:apps/*/src、modules/*/web/src、packages/ui/src)`); +} + +if (violations.length === 0) { + console.log(`UI 还原度 A 类门禁:通过(${scanned} 个文件,A1/A2/A4 均无违规)`); + process.exit(0); +} + +for (const v of violations) { + console.log(`${v.rel}:${v.line}:${v.col} [${v.rule}] ${v.message}`); + if (VERBOSE) console.log(` ${v.snippet}`); +} + +const byRule = violations.reduce((acc, v) => { + acc[v.rule] = (acc[v.rule] || 0) + 1; + return acc; +}, {}); +console.log( + `UI 还原度 A 类门禁:失败,${violations.length} 处违规(${Object.entries(byRule) + .map(([rule, n]) => `${rule}=${n}`) + .join(' ')})`, +); +console.log('规则与边界见 docs/development-workflow.md §7;设计真源见 docs/design/ui-handoff/。'); +process.exit(1); From 44ce70cb338d44927c060e319bbdf0b6ba25c67c Mon Sep 17 00:00:00 2001 From: babycoder-dev Date: Wed, 7 Oct 2026 14:37:00 +0800 Subject: [PATCH 2/2] fix(ci): cover every CSS length unit in the A4 fidelity rule Codex (PR #41, P2) showed the rule only recognised px/rem/em, so font-size:3vw, padding:5% and margin:2ch bypassed the token-only rule. The unit list now covers all CSS lengths and percentages with the zero-value allowance kept, the declaration parser no longer assumes one declaration per line (the regression spec caught that), the rules moved to scripts/lib/ui-fidelity-rules.mjs and are covered by scripts/lib/ui-fidelity-rules.spec.mjs collected via vitest. --- docs/agent-workflow.md | 8 +- scripts/check-ui-fidelity.mjs | 163 +++++-------------------- scripts/lib/ui-fidelity-rules.mjs | 113 +++++++++++++++++ scripts/lib/ui-fidelity-rules.spec.mjs | 90 ++++++++++++++ vitest.config.mts | 8 +- 5 files changed, 247 insertions(+), 135 deletions(-) create mode 100644 scripts/lib/ui-fidelity-rules.mjs create mode 100644 scripts/lib/ui-fidelity-rules.spec.mjs diff --git a/docs/agent-workflow.md b/docs/agent-workflow.md index 19f155d..f36a56b 100644 --- a/docs/agent-workflow.md +++ b/docs/agent-workflow.md @@ -33,8 +33,12 @@ | 设计还原度 B 类(人工并排比对,覆盖交互态) | 不可机器化,定稿前人工做 | 评审 | A 类规则的**边界**(未覆盖项,改动时需一并决策):A3(关键文案逐字一致)由 `*.spec.tsx` 断言承担; -A4 只覆盖 `padding|margin|gap|border-radius|box-shadow|font|font-size`,`letter-spacing` / -`line-height` / `transform` 的取值口径待定;TSX 内联样式不在扫描范围内。 +A4 只覆盖 `padding|margin|gap|border-radius|box-shadow|font|font-size`(**单位覆盖全部 CSS 长度与百分比, +含 vw/vh/ch/%,零值 `0` / `0px` / `0%` 豁免**),`letter-spacing` / `line-height` / `transform` 的取值口径 +待定;TSX 内联样式不在扫描范围内。 +规则本身有回归测试:`scripts/lib/ui-fidelity-rules.spec.mjs`(由 `vitest.config.mts` 的 +`scripts/**/*.spec.mjs` 收集)——**门禁自身也要有守卫**,否则规则会像 2026-10-07 那样被静默削弱 +(当时 A4 只认 px/rem/em,`font-size:3vw` 这类裸值可直接绕过)。 ## 3. 方言与挂载:一份实现、多入口 diff --git a/scripts/check-ui-fidelity.mjs b/scripts/check-ui-fidelity.mjs index f738796..2049d00 100644 --- a/scripts/check-ui-fidelity.mjs +++ b/scripts/check-ui-fidelity.mjs @@ -1,37 +1,29 @@ #!/usr/bin/env node -// UI 设计还原度门禁 · A 类(可机器核验部分) +// UI 设计还原度门禁 · A 类(可机器核验部分)— CLI // -// 把 docs/development-workflow.md §7 里"A 类 · 实现方交付前必须自证"的条目 -// 变成**会红的检查**,而不是靠实现方(人或代理)宣称。规则出处见该节与 -// docs/tasks/ui-foundation-fidelity.md §2。 +// 把 docs/development-workflow.md §7 里「A 类 · 实现方交付前必须自证」的条目 +// 变成**会红的检查**,而不是靠实现方(人或代理)宣称。 // -// 覆盖(当前): -// A1 零硬编码 hex:UI 源码里的颜色只能引 var(--*),唯一允许出现 hex 的位置是 -// packages/ui/src/styles/tokens.css(token 唯一真源)。 -// A2 零 emoji 当图标:图标一律用线性 SVG(@work/ui 的 Icon),不得用 emoji 占位。 -// A4 只引 token:间距/圆角/阴影/字体(padding|margin|gap|border-radius|box-shadow| -// font|font-size)不得写裸 px/rem/em 字面量,须引 token 变量 -// (--sp-*、--r-*、--shadow-*、--font*)。 +// 规则实现见 scripts/lib/ui-fidelity-rules.mjs(纯函数,可单测);本文件只负责 +// 遍历文件、打印违规、给退出码。 // -// 不在本脚本范围(有意):A3(关键文案逐字一致)由 *.spec.tsx 的断言承担; -// B 类人工抽查不可机器化;letter-spacing / line-height / transform 等属性暂不在 -// A4 列表内(其取值口径待定,见 docs/agent-workflow.md 的 follow-up)。 +// 覆盖:A1 零硬编码 hex / A2 零 emoji 当图标 / A4 间距·圆角·阴影·字体只引 token。 +// 不在范围(有意):A3 由 *.spec.tsx 的断言承担;B 类人工抽查不可机器化; +// letter-spacing / line-height / transform 与 TSX 内联样式不在 A4 内。 // -// 设计取舍:纯文件系统遍历,**不 spawn 子进程**(不调用 git/eslint),因此 -// 在受限沙箱与 CI 里行为一致,也不受工作区 git 状态影响。 +// 设计取舍:纯文件系统遍历,**不 spawn 子进程**(不调用 git/eslint),因此在受限 +// 沙箱、CI 与不同开发机上行为一致,也不受工作区 git 状态影响。 // // 用法:node scripts/check-ui-fidelity.mjs [--verbose] // 退出码:0 = 通过;1 = 有违规。 import { readFileSync, readdirSync, statSync } from 'node:fs'; import path from 'node:path'; +import { inScope, lintText } from './lib/ui-fidelity-rules.mjs'; const REPO = path.resolve(import.meta.dirname, '..'); const VERBOSE = process.argv.includes('--verbose'); -// 唯一允许出现 hex 的位置(token 真源)。 -const HEX_ALLOWED = ['packages/ui/src/styles/tokens.css']; - const SKIP_DIRS = new Set([ 'node_modules', 'dist', @@ -46,34 +38,12 @@ const SKIP_DIRS = new Set([ const EXTENSIONS = new Set(['.css', '.ts', '.tsx', '.html']); -// A2 例外:这几个字符是文本勾叉(常用于日志/注释),不是"emoji 当图标"。 -const EMOJI_ALLOWED = new Set(['\u2713', '\u2714', '\u2717', '\u2718']); - -const EMOJI_RE = - /[\u{1F000}-\u{1FAFF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}\u{2B00}-\u{2BFF}\u{FE0F}]/gu; - -const HEX_RE = /#[0-9a-fA-F]{3,8}\b/g; - -// A4 覆盖的属性 → 说明用的人类可读分组。 -const TOKEN_ONLY_PROPS = [ - [/^(padding|margin)(-top|-right|-bottom|-left)?$/, '间距'], - [/^(row-)?gap$/, '间距'], - [/^column-gap$/, '间距'], - [/^border-radius$/, '圆角'], - [/^border-(top|bottom)-(left|right)-radius$/, '圆角'], - [/^box-shadow$/, '阴影'], - [/^font$/, '字体'], - [/^font-family$/, '字体'], - [/^font-size$/, '字体'], -]; -const LENGTH_RE = /\b\d*\.?\d+(px|rem|em)\b/; - -/** A 类扫描范围:apps 下各 app 的 src、modules 下各模块的 web/src、packages/ui/src。 */ -function inScope(rel) { - if (rel.startsWith('packages/ui/src/')) return true; - if (/^apps\/[^/]+\/src\//.test(rel)) return true; - if (/^modules\/[^/]+\/web\/src\//.test(rel)) return true; - return false; +function isDir(p) { + try { + return statSync(p).isDirectory(); + } catch { + return false; + } } function walk(dir, out = []) { @@ -90,27 +60,26 @@ function walk(dir, out = []) { continue; } if (!entry.isFile()) continue; - const abs = path.join(dir, entry.name); if (!EXTENSIONS.has(path.extname(entry.name).toLowerCase())) continue; - out.push(abs); + out.push(path.join(dir, entry.name)); } return out; } -/** 收集扫描根:三个范围各自的父目录,避免整仓遍历。 */ +/** 收集扫描根,避免整仓遍历(node_modules 等一律不进)。 */ function scanRoots() { const roots = []; const appsDir = path.join(REPO, 'apps'); - for (const name of readdirSync(appsDir, { withFileTypes: true })) { - if (name.isDirectory() && !SKIP_DIRS.has(name.name)) { - const src = path.join(appsDir, name.name, 'src'); + for (const entry of readdirSync(appsDir, { withFileTypes: true })) { + if (entry.isDirectory() && !SKIP_DIRS.has(entry.name)) { + const src = path.join(appsDir, entry.name, 'src'); if (isDir(src)) roots.push(src); } } const modulesDir = path.join(REPO, 'modules'); - for (const name of readdirSync(modulesDir, { withFileTypes: true })) { - if (name.isDirectory() && !SKIP_DIRS.has(name.name)) { - const src = path.join(modulesDir, name.name, 'web', 'src'); + for (const entry of readdirSync(modulesDir, { withFileTypes: true })) { + if (entry.isDirectory() && !SKIP_DIRS.has(entry.name)) { + const src = path.join(modulesDir, entry.name, 'web', 'src'); if (isDir(src)) roots.push(src); } } @@ -119,77 +88,10 @@ function scanRoots() { return roots; } -function isDir(p) { - try { - return statSync(p).isDirectory(); - } catch { - return false; - } -} - -const violations = []; -function report(rel, line, col, rule, message, snippet) { - violations.push({ rel, line, col, rule, message, snippet }); -} - -/** 逐行扫描,返回 [lineNumber, lineText]。 */ -function* lines(text) { - const parts = text.split(/\r?\n/); - for (let i = 0; i < parts.length; i++) yield [i + 1, parts[i]]; -} - -function checkA1(rel, lineNo, line) { - if (HEX_ALLOWED.includes(rel)) return; - for (const match of line.matchAll(HEX_RE)) { - report( - rel, - lineNo, - match.index + 1, - 'A1', - `硬编码颜色 ${match[0]};颜色只能引 var(--*),token 真源是 packages/ui/src/styles/tokens.css`, - line.trim(), - ); - } -} - -function checkA2(rel, lineNo, line) { - for (const match of line.matchAll(EMOJI_RE)) { - if (EMOJI_ALLOWED.has(match[0])) continue; - report( - rel, - lineNo, - match.index + 1, - 'A2', - `出现 emoji「${match[0]}」;图标必须用 @work/ui 的线性 Icon,不得用 emoji 占位`, - line.trim(), - ); - } -} - -/** A4 只作用于 CSS 声明行(`prop: value;`)。 */ -function checkA4(rel, lineNo, line) { - if (rel.endsWith('tokens.css')) return; - const decl = /^\s*([a-z-]+)\s*:\s*([^;{]+);/i.exec(line); - if (!decl) return; - const [, prop, value] = decl; - const group = TOKEN_ONLY_PROPS.find(([re]) => re.test(prop.toLowerCase())); - if (!group) return; - const literal = LENGTH_RE.exec(value); - if (!literal) return; - report( - rel, - lineNo, - line.indexOf(value) + 1, - 'A4', - `${group[1]}属性 ${prop} 写了裸长度 ${literal[0]};须引 token(--sp-*/--r-*/--shadow-*/--font*)`, - line.trim(), - ); -} - -const roots = scanRoots(); const files = []; -for (const root of roots) walk(root, files); +for (const root of scanRoots()) walk(root, files); +const violations = []; let scanned = 0; for (const abs of files) { const rel = path.relative(REPO, abs).split(path.sep).join('/'); @@ -201,15 +103,13 @@ for (const abs of files) { continue; } scanned++; - for (const [lineNo, line] of lines(text)) { - checkA1(rel, lineNo, line); - checkA2(rel, lineNo, line); - if (rel.endsWith('.css')) checkA4(rel, lineNo, line); - } + violations.push(...lintText(rel, text)); } if (VERBOSE) { - console.log(`扫描 ${scanned} 个文件(A 类范围:apps/*/src、modules/*/web/src、packages/ui/src)`); + console.log( + `扫描 ${scanned} 个文件(A 类范围:apps 各 app 的 src、modules 各模块的 web/src、packages/ui/src)`, + ); } if (violations.length === 0) { @@ -219,7 +119,6 @@ if (violations.length === 0) { for (const v of violations) { console.log(`${v.rel}:${v.line}:${v.col} [${v.rule}] ${v.message}`); - if (VERBOSE) console.log(` ${v.snippet}`); } const byRule = violations.reduce((acc, v) => { diff --git a/scripts/lib/ui-fidelity-rules.mjs b/scripts/lib/ui-fidelity-rules.mjs new file mode 100644 index 0000000..16a02eb --- /dev/null +++ b/scripts/lib/ui-fidelity-rules.mjs @@ -0,0 +1,113 @@ +// UI 设计还原度门禁 · A 类规则(纯函数,无 I/O) +// +// 规则出处:docs/development-workflow.md §7「A 类」与 docs/agent-workflow.md §2。 +// 单独成模块是为了让规则本身可被单测覆盖——门禁自身也要有守卫 +// (见 scripts/lib/ui-fidelity-rules.spec.mjs;vitest.config.mts 已收集该目录)。 + +/** 唯一允许出现 hex 的位置(token 真源)。 */ +export const HEX_ALLOWED = ['packages/ui/src/styles/tokens.css']; + +/** A2 例外:文本勾叉(常用于日志/注释),不算「emoji 当图标」。 */ +const EMOJI_ALLOWED = new Set(['\u2713', '\u2714', '\u2717', '\u2718']); + +const EMOJI_RE = + /[\u{1F000}-\u{1FAFF}\u{2600}-\u{26FF}\u{2700}-\u{27BF}\u{2B00}-\u{2BFF}\u{FE0F}]/gu; + +const HEX_RE = /#[0-9a-fA-F]{3,8}\b/g; + +/** A4 覆盖的属性 → 人类可读分组。 */ +export const TOKEN_ONLY_PROPS = [ + [/^(padding|margin)(-top|-right|-bottom|-left)?$/, '间距'], + [/^(row-)?gap$/, '间距'], + [/^column-gap$/, '间距'], + [/^border-radius$/, '圆角'], + [/^border-(top|bottom)-(left|right)-radius$/, '圆角'], + [/^box-shadow$/, '阴影'], + [/^font$/, '字体'], + [/^font-family$/, '字体'], + [/^font-size$/, '字体'], +]; + +// 覆盖全部 CSS 长度/百分比单位:只认 px/rem/em 会让 vw / vh / ch / % 之类的裸值绕过规则。 +const LENGTH_TOKEN_RE = + /(-?\d*\.?\d+)(px|rem|em|ex|ch|cap|ic|lh|rlh|vw|vh|vi|vb|vmin|vmax|cm|mm|q|in|pc|pt|%)/gi; + +function push(out, rel, line, col, rule, message) { + out.push({ rel, line, col, rule, message }); +} + +function checkA1(rel, lineNo, line, out) { + if (HEX_ALLOWED.includes(rel)) return; + for (const match of line.matchAll(HEX_RE)) { + push( + out, + rel, + lineNo, + match.index + 1, + 'A1', + `硬编码颜色 ${match[0]};颜色只能引 var(--*),token 真源是 packages/ui/src/styles/tokens.css`, + ); + } +} + +function checkA2(rel, lineNo, line, out) { + for (const match of line.matchAll(EMOJI_RE)) { + if (EMOJI_ALLOWED.has(match[0])) continue; + push( + out, + rel, + lineNo, + match.index + 1, + 'A2', + `出现 emoji「${match[0]}」;图标必须用 @work/ui 的线性 Icon,不得用 emoji 占位`, + ); + } +} + +/** A4 只作用于 CSS 声明(`prop: value`);零值(0 / 0px / 0%)豁免。 */ +function checkA4(rel, lineNo, line, out) { + if (rel.endsWith('tokens.css')) return; + // 把 { } 视作分隔符后按 ; 切块,这样「一行一个声明」与「整条规则写在一行」都能解析 + // (早先版本把正则锚在行首,`.a { padding: 13px; }` 会被整条漏掉)。 + for (const chunk of line.replace(/[{}]/g, ';').split(';')) { + const decl = /^\s*([a-z-]+)\s*:\s*(.+?)\s*$/.exec(chunk); + if (!decl) continue; + const [, prop, value] = decl; + const group = TOKEN_ONLY_PROPS.find(([re]) => re.test(prop.toLowerCase())); + if (!group) continue; + for (const match of value.matchAll(LENGTH_TOKEN_RE)) { + if (Number(match[1]) === 0) continue; + push( + out, + rel, + lineNo, + Math.max(1, line.indexOf(value) + 1), + 'A4', + `${group[1]}属性 ${prop} 写了裸值 ${match[0]};须引 token(--sp-*、--r-*、--shadow-*、--font*)`, + ); + return; // 每行只报一次,避免刷屏 + } + } +} + +/** 对单个文件内容执行 A1/A2/A4,返回违规数组。 */ +export function lintText(rel, text) { + const out = []; + const lines = text.split(/\r?\n/); + for (let i = 0; i < lines.length; i++) { + const lineNo = i + 1; + const line = lines[i]; + checkA1(rel, lineNo, line, out); + checkA2(rel, lineNo, line, out); + if (rel.endsWith('.css')) checkA4(rel, lineNo, line, out); + } + return out; +} + +/** A 类扫描范围:apps 下各 app 的 src、modules 下各模块的 web/src、packages/ui/src。 */ +export function inScope(rel) { + if (rel.startsWith('packages/ui/src/')) return true; + if (/^apps\/[^/]+\/src\//.test(rel)) return true; + if (/^modules\/[^/]+\/web\/src\//.test(rel)) return true; + return false; +} diff --git a/scripts/lib/ui-fidelity-rules.spec.mjs b/scripts/lib/ui-fidelity-rules.spec.mjs new file mode 100644 index 0000000..f22d0da --- /dev/null +++ b/scripts/lib/ui-fidelity-rules.spec.mjs @@ -0,0 +1,90 @@ +// UI 还原度 A 类规则的回归测试。 +// +// 存在理由:门禁自身也要有守卫。2026-10-07 Codex 在 PR #41 上指出 A4 只认 px/rem/em, +// 于是 font-size:3vw / padding:5% / margin:2ch 这类裸值可绕过规则——那是一次**规则本身的 +// 覆盖缺口**,靠人工注入验证发现不了(当时我只测了 px)。本文件把每类单位的正/负样例固化。 +// +// 由 vitest.config.mts 的 scripts/**/*.spec.mjs 收集(node 环境)。 + +import { describe, expect, it } from 'vitest'; +import { inScope, lintText } from './ui-fidelity-rules.mjs'; + +const APP = 'apps/workbench-shell/src/styles.css'; +const MODULE = 'modules/presence/web/src/styles.css'; +const TOKENS = 'packages/ui/src/styles/tokens.css'; + +/** 取违规的 rule 列表,便于断言。 */ +const rules = (rel, text) => lintText(rel, text).map((v) => v.rule); + +describe('A1 零硬编码 hex', () => { + it('抓到 hex 颜色', () => { + expect(rules(APP, '.a { color: #ff0000; }')).toEqual(['A1']); + }); + + it('tokens.css 是唯一豁免', () => { + expect(rules(TOKENS, ':root { --danger: #f54a45; }')).toEqual([]); + }); + + it('放行 var() 引用', () => { + expect(rules(APP, '.a { color: var(--ink-1); }')).toEqual([]); + }); +}); + +describe('A2 零 emoji 当图标', () => { + it('抓到 emoji', () => { + expect(rules('modules/presence/web/src/pages/X.tsx', 'const icon = "🔔";')).toEqual(['A2']); + }); + + it('放行文本勾叉', () => { + expect(rules('modules/presence/web/src/pages/X.tsx', '// ✓ 已完成')).toEqual([]); + }); +}); + +describe('A4 只引 token', () => { + it.each([ + ['padding', 'padding: 13px;'], + ['margin', 'margin: 2ch;'], + ['gap', 'gap: 1.5rem;'], + ['font-size 视口单位', 'font-size: 3vw;'], + ['padding 百分比', 'padding: 5%;'], + ['border-radius 百分比', 'border-radius: 50%;'], + ['box-shadow 裸值', 'box-shadow: 0 1px 2px rgba(0,0,0,.2);'], + ])('抓到裸值:%s', (_label, decl) => { + expect(rules(APP, `.a { ${decl} }`)).toEqual(['A4']); + }); + + it.each([ + ['无单位零值', 'padding: 0;'], + ['带单位零值', 'padding: 0px;'], + ['零百分比', 'padding: 0%;'], + ['token 引用', 'padding: var(--sp-3);'], + ['calc 组合 token', 'gap: calc(var(--sp-4) - var(--border-width));'], + ['calc 除 token', 'padding: calc(var(--sp-1) / 2);'], + ['多值混合', 'padding: 0 var(--sp-2);'], + ])('放行:%s', (_label, decl) => { + expect(rules(APP, `.a { ${decl} }`)).toEqual([]); + }); + + it('不碰 A4 属性清单之外的属性', () => { + expect(rules(APP, '.a { width: 100%; transform: translateY(-1px); letter-spacing: -0.5px; }')).toEqual( + [], + ); + }); + + it('tokens.css 豁免(token 真源自身可以有裸值)', () => { + expect(rules(TOKENS, ':root { --badge-padding-y: 1px; }')).toEqual([]); + }); +}); + +describe('扫描范围', () => { + it.each([ + ['apps/*/src', APP, true], + ['modules/*/web/src', MODULE, true], + ['packages/ui/src', TOKENS, true], + ['modules/*/api/src', 'modules/presence/api/src/x.ts', false], + ['apps 构建产物', 'apps/workbench-shell/dist/x.css', false], + ['仓库脚本', 'scripts/check-ui-fidelity.mjs', false], + ])('%s', (_label, rel, expected) => { + expect(inScope(rel)).toBe(expected); + }); +}); diff --git a/vitest.config.mts b/vitest.config.mts index 76245c0..52a1338 100644 --- a/vitest.config.mts +++ b/vitest.config.mts @@ -6,7 +6,13 @@ export default defineConfig({ test: { globals: true, environment: 'node', - include: ['packages/**/*.spec.ts', 'modules/**/*.spec.ts', 'apps/**/*.spec.ts'], + include: [ + 'packages/**/*.spec.ts', + 'modules/**/*.spec.ts', + 'apps/**/*.spec.ts', + // 仓库级工具脚本的规则单测(scripts/lib/*.spec.mjs,node 环境) + 'scripts/**/*.spec.mjs', + ], exclude: ['**/*.e2e-spec.ts', '**/*.spec.tsx', '**/node_modules/**', '**/dist/**'], coverage: { provider: 'v8',