From 5e568f9924e05f7252fd2599e51329691b2e829d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 12:54:00 +1100 Subject: [PATCH 1/3] Rename to dx-workflow with frontend and backend skills; review frontend code (0.5.0) - Plugin ui-workflow -> dx-workflow (plugins/dx-workflow, marketplace, package, CI template DX_WORKFLOW_REF, stop gate DX_WORKFLOW_GATE). - Skills building-consistent-ui -> frontend, building-reliable-backend -> backend; lane kinds ui/api -> frontend/backend, template lanes renamed. - UI stays inside frontend (design.md, tokens, ui-look, design-review). - New frontend code-review.md: state, requests and races, forms, security, accessibility in code, performance, backend contract, tests. The frontend brief points the reviewer at design review then code review, one file. - Drop 0.1 compatibility (.ui-verify migration, UI_VERIFY_RUN_DIR) and the upgrade notes. - ADR 0005. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014d2MvQ5v7FCph37jwFCC7i --- .claude-plugin/marketplace.json | 8 +- .github/workflows/test.yml | 4 +- NOTICE.md | 14 +-- README.md | 85 +++++++------------ ...hecks-out-of-reach-and-bound-to-content.md | 4 +- docs/adr/0005-dx-workflow-frontend-backend.md | 31 +++++++ .../cases/check-then-insert-signup/case.json | 2 +- evals/cases/clean-pagination-clamp/case.json | 2 +- evals/cases/clean-rename-with-tests/case.json | 2 +- evals/cases/idor-order-lookup/case.json | 2 +- evals/cases/swallowed-payment-error/case.json | 2 +- evals/run.mjs | 4 +- package.json | 4 +- .../.claude-plugin/plugin.json | 9 +- .../hooks/hooks.json | 0 .../scripts/check-raw-styles.mjs | 0 .../scripts/find-tools.mjs | 0 .../scripts/lib/checklist.mjs | 2 +- .../scripts/lib/negative.mjs | 0 .../scripts/lib/verify-config.mjs | 16 ++-- .../scripts/make-evidence.mjs | 4 +- .../scripts/review-brief.mjs | 17 ++-- .../scripts/run-verify.mjs | 50 ++--------- .../scripts/stamp.mjs | 2 +- .../scripts/stop-gate.mjs | 18 +--- .../scripts/turn-start.mjs | 0 .../shared/acceptance.md | 2 +- .../{workflow => dx-workflow}/shared/ctl.md | 2 +- .../shared/ratchet.md | 2 +- .../shared/verify-ci.yml | 14 +-- .../shared/verify.config.json | 4 +- .../skills/backend}/SKILL.md | 10 +-- .../skills/backend}/build.md | 2 +- .../skills/backend}/code-review.md | 8 +- .../skills/backend}/setup.md | 10 +-- .../skills/backend}/templates/backend.md | 0 .../skills/backend}/verify.md | 6 +- .../skills/frontend}/SKILL.md | 11 ++- .../skills/frontend}/build.md | 0 .../skills/frontend/code-review.md | 52 ++++++++++++ .../skills/frontend}/design-review.md | 16 +++- .../skills/frontend}/setup.md | 7 +- .../skills/frontend}/templates/design.md | 0 .../skills/frontend}/templates/ui-look.e2e.ts | 2 +- .../skills/frontend}/templates/ui-pages.json | 0 .../skills/frontend}/verify.md | 12 +-- test/evals.test.mjs | 4 +- test/helpers.mjs | 14 +-- test/make-evidence.test.mjs | 6 +- test/review-brief.test.mjs | 41 +++++---- test/run-verify.test.mjs | 18 ++-- test/stamp-ci.test.mjs | 14 +-- test/stop-gate.test.mjs | 8 +- test/verify-config.test.mjs | 8 +- vendor.lock.json | 20 ++--- 55 files changed, 304 insertions(+), 271 deletions(-) create mode 100644 docs/adr/0005-dx-workflow-frontend-backend.md rename plugins/{workflow => dx-workflow}/.claude-plugin/plugin.json (50%) rename plugins/{workflow => dx-workflow}/hooks/hooks.json (100%) rename plugins/{workflow => dx-workflow}/scripts/check-raw-styles.mjs (100%) rename plugins/{workflow => dx-workflow}/scripts/find-tools.mjs (100%) rename plugins/{workflow => dx-workflow}/scripts/lib/checklist.mjs (99%) rename plugins/{workflow => dx-workflow}/scripts/lib/negative.mjs (100%) rename plugins/{workflow => dx-workflow}/scripts/lib/verify-config.mjs (96%) rename plugins/{workflow => dx-workflow}/scripts/make-evidence.mjs (98%) rename plugins/{workflow => dx-workflow}/scripts/review-brief.mjs (92%) rename plugins/{workflow => dx-workflow}/scripts/run-verify.mjs (76%) rename plugins/{workflow => dx-workflow}/scripts/stamp.mjs (99%) rename plugins/{workflow => dx-workflow}/scripts/stop-gate.mjs (86%) rename plugins/{workflow => dx-workflow}/scripts/turn-start.mjs (100%) rename plugins/{workflow => dx-workflow}/shared/acceptance.md (99%) rename plugins/{workflow => dx-workflow}/shared/ctl.md (98%) rename plugins/{workflow => dx-workflow}/shared/ratchet.md (99%) rename plugins/{workflow => dx-workflow}/shared/verify-ci.yml (78%) rename plugins/{workflow => dx-workflow}/shared/verify.config.json (98%) rename plugins/{workflow/skills/building-reliable-backend => dx-workflow/skills/backend}/SKILL.md (90%) rename plugins/{workflow/skills/building-reliable-backend => dx-workflow/skills/backend}/build.md (97%) rename plugins/{workflow/skills/building-reliable-backend => dx-workflow/skills/backend}/code-review.md (96%) rename plugins/{workflow/skills/building-reliable-backend => dx-workflow/skills/backend}/setup.md (93%) rename plugins/{workflow/skills/building-reliable-backend => dx-workflow/skills/backend}/templates/backend.md (100%) rename plugins/{workflow/skills/building-reliable-backend => dx-workflow/skills/backend}/verify.md (95%) rename plugins/{workflow/skills/building-consistent-ui => dx-workflow/skills/frontend}/SKILL.md (89%) rename plugins/{workflow/skills/building-consistent-ui => dx-workflow/skills/frontend}/build.md (100%) create mode 100644 plugins/dx-workflow/skills/frontend/code-review.md rename plugins/{workflow/skills/building-consistent-ui => dx-workflow/skills/frontend}/design-review.md (91%) rename plugins/{workflow/skills/building-consistent-ui => dx-workflow/skills/frontend}/setup.md (95%) rename plugins/{workflow/skills/building-consistent-ui => dx-workflow/skills/frontend}/templates/design.md (100%) rename plugins/{workflow/skills/building-consistent-ui => dx-workflow/skills/frontend}/templates/ui-look.e2e.ts (93%) rename plugins/{workflow/skills/building-consistent-ui => dx-workflow/skills/frontend}/templates/ui-pages.json (100%) rename plugins/{workflow/skills/building-consistent-ui => dx-workflow/skills/frontend}/verify.md (93%) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 8a008c1..9764233 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -1,13 +1,13 @@ { - "name": "ui-workflow", + "name": "dx-workflow", "owner": { "name": "davidxiaodev" }, "plugins": [ { - "name": "ui-workflow", - "source": "./plugins/workflow", - "description": "Acceptance first, one design and one backend contract, enforced verification per lane (ui, api) with independent review and evidence." + "name": "dx-workflow", + "source": "./plugins/dx-workflow", + "description": "Acceptance first, one design and one backend contract, enforced verification per lane (frontend, backend) with independent review and evidence." } ] } diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 3e94eff..e242ddc 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -24,10 +24,10 @@ jobs: node-version: ${{ matrix.node }} - name: Syntax check every script run: | - for f in plugins/workflow/scripts/*.mjs plugins/workflow/scripts/lib/*.mjs; do node --check "$f"; done + for f in plugins/dx-workflow/scripts/*.mjs plugins/dx-workflow/scripts/lib/*.mjs; do node --check "$f"; done - name: Hooks and plugin manifests are valid JSON run: | - for f in plugins/workflow/hooks/hooks.json plugins/workflow/.claude-plugin/plugin.json .claude-plugin/marketplace.json plugins/workflow/shared/verify.config.json; do + for f in plugins/dx-workflow/hooks/hooks.json plugins/dx-workflow/.claude-plugin/plugin.json .claude-plugin/marketplace.json plugins/dx-workflow/shared/verify.config.json; do node -e "JSON.parse(require('fs').readFileSync(process.argv[1], 'utf8'))" "$f" || { echo "invalid JSON: $f"; exit 1; } done - run: npm test diff --git a/NOTICE.md b/NOTICE.md index aaa2c0d..752f1ff 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -1,23 +1,23 @@ # Notices -ui-workflow is MIT licensed (see LICENSE). It calls, but does not include, these tools: +dx-workflow is MIT licensed (see LICENSE). It calls, but does not include, these tools: taste-skill (MIT, Leonxlnx), ui-ux-pro-max (MIT, nextlevelbuilder), baoyu-design (mixed licence, JimLiu; optional and never bundled). Adapted text: -- `skills/building-consistent-ui/verify.md` and `shared/ctl.md` (formerly `functional-verify.md`) +- `skills/frontend/verify.md` and `shared/ctl.md` (formerly `functional-verify.md`) adapt pstack's `create-verification-skill`, its visual-parity playbook and its practice of - independent review; `skills/building-reliable-backend/code-review.md` adapts pstack's + independent review; `skills/backend/code-review.md` adapts pstack's `blast-radius`. pstack: MIT License, Copyright (c) 2026 Lauren Tan, https://github.com/cursor/plugins/tree/main/pstack -- `skills/building-consistent-ui/build.md` adapts the UI branch of `prototype`, and - `skills/building-reliable-backend/build.md` and `code-review.md` adapt `tdd` and `code-review`, from +- `skills/frontend/build.md` adapts the UI branch of `prototype`, and + `skills/backend/build.md` and `code-review.md` adapt `tdd` and `code-review`, from mattpocock/skills, MIT License, https://github.com/mattpocock/skills -- `skills/building-consistent-ui/design-review.md` adapts the `design-review` command from +- `skills/frontend/design-review.md` adapts the `design-review` command from interface-design, MIT License, Copyright (c) 2026 Damola Akinleye, https://github.com/Dammyjay93/interface-design -- `skills/building-reliable-backend/code-review.md`, `verify.md` and `build.md` adapt the `/review` +- `skills/backend/code-review.md`, `verify.md` and `build.md` adapt the `/review` checklist and specialists and the `/verify` rules from gstack, MIT License, Copyright (c) 2026 Garry Tan, https://github.com/garrytan/gstack diff --git a/README.md b/README.md index d198cd1..0ac4371 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -# ui-workflow +# dx-workflow 仓库:`davidxiaodev/workflow`。 @@ -9,16 +9,17 @@ ## 整套流程 -前端(ui)和后端(api)走同一套流程,只是每一步用的约定、检查和评审方式不同。项目里每一块界面或服务叫一个 **lane**。 +前端(frontend:用户直接接触的客户端;目前支持 Web,React Native / Expo 移动端在下一个版本)和后端(backend)走同一套流程,只是每一步用的约定、检查和评审方式不同。 +项目里每一个客户端或服务叫一个 **lane**,一个仓库可以有多条,比如 `web`、`app`、`api`,各自标明 `kind` 是 `frontend` 还是 `backend`。 -| 步骤 | 做什么 | ui lane | api lane | +| 步骤 | 做什么 | frontend lane | backend lane | | --- | --- | --- | --- | | 0 准备 | 每个项目一次:写约定、接检查、加 lint 护栏、标出 `sensitive` 路径 | `docs/design.md` + token 文件 | `docs/backend.md` + 契约文件(OpenAPI 等)+ 迁移目录 | | 1 澄清 | 只在大改动时:先追问需求、边界、失败时怎么办 | 同左 | 同左 | | 2 验收标准 | 写 `.verify/acceptance.md`:可观察的结果,每条写明用什么证明;逐项过一遍异常情况清单;可选写明怎么回滚、能否撤回 | 无效输入、键盘、慢请求、双击提交、390 宽…… | 边界值、越权、重复请求、并发写、下游失败…… | | 3 实现 | 按约定做 | 需要时出 3 个结构不同的原型 | 先改契约,再按验收标准一条条先写测试后写实现 | | 4 机器检查 | `run-verify.mjs` 按 lane 跑,只认真实退出码,遇到第一个失败就停 | 样式、类型、截图 + 可访问性、用户路径 | 类型、单元、真实数据库的集成测试、**负向检查**、契约、迁移、用户路径 | -| 5 独立评审 | `review-brief.mjs` 写 brief,交给没参与实现的子代理;逐条标记验收标准和触发的清单项;最多 3 轮 | `design-review.md` 看截图 | `code-review.md` 看 diff,按专项逐一检查,并跑一遍证明关键事实 | +| 5 独立评审 | `review-brief.mjs` 写 brief,交给没参与实现的子代理;逐条标记验收标准和触发的清单项;最多 3 轮 | `design-review.md` 看截图,再用前端版 `code-review.md` 看代码(状态、请求竞态、错误态、XSS、可访问性) | `code-review.md` 看 diff,按专项逐一检查,并跑一遍证明关键事实 | | 6 证据和分档 | `make-evidence.mjs` 生成证据包:验收标准和机器检查分开写,算合并分档,写明能否撤回、影响范围、怎么回滚 | 前后对比截图、录屏 | 检查日志、负向检查结果、契约与迁移改动 | | 7 沉淀 | 评审的 Blocker、回滚、你的纠正,按 `shared/ratchet.md` 变成检查或清单项 | 同左 | 同左 | @@ -83,7 +84,7 @@ lint 规则、类型或约束 > 由 diff 触发的清单项 > 写进约定文件 ```markdown ## C1 A retried create does not create twice - when: diff `/router\.post|@Post\(/` or path `src/**/handlers/create*.ts` -- lanes: api +- lanes: backend - check: POST the same body twice with the same Idempotency-Key; one row, the same id both times. - source: incident 2026-09-14, PR #311 ``` @@ -95,7 +96,7 @@ lint 规则、类型或约束 > 由 diff 触发的清单项 > 写进约定文件 没有全部标记,或者证据包不是当前内容的,第一次结束会被拦下。仍未通过就结束时,AI 必须写明"未验证" (钩子只拦一次,避免无限循环)。只聊天、没改内容的一轮不会被拦。 -`UI_WORKFLOW_GATE`:`enforce`(默认,拦截)、`observe`(只记录本来会拦什么,用来先看误报)、`off`(关闭)。 +`DX_WORKFLOW_GATE`:`enforce`(默认,拦截)、`observe`(只记录本来会拦什么,用来先看误报)、`off`(关闭)。 每次判断都追加到 `.verify/gate.log`,`ratchet.md` 建议每周看一次。 **提交盖章**(可选):`node /scripts/stamp.mjs --install` 装一个 `prepare-commit-msg` 钩子。每个改了 lane 文件的提交带上 @@ -108,7 +109,7 @@ git log --format='%h %s%n %(trailers:key=Verified,valueonly)' origin/main.. ## CI -把 `plugins/workflow/shared/verify-ci.yml` 复制到项目的 `.github/workflows/verify.yml`,填上安装依赖和启动服务的步骤。 +把 `plugins/dx-workflow/shared/verify-ci.yml` 复制到项目的 `.github/workflows/verify.yml`,填上安装依赖和启动服务的步骤。 每个 PR 都会用基线分支的配置在 PR 内容上重跑全部检查,按检查结果和改动范围算出分档(`make-evidence --checks-only`), 写进 job summary;未就绪时 status 为红,可以在分支保护里设为必过。日志和截图作为 artifact 保存。 @@ -119,12 +120,9 @@ CI 里目前不跑独立评审,分档会标明"checks only"。评审放进 CI ```bash /plugin marketplace add davidxiaodev/workflow -/plugin install ui-workflow@ui-workflow +/plugin install dx-workflow@dx-workflow ``` -仓库已从 `davidxiaodev/ui-workflow` 改名为 `davidxiaodev/workflow`,插件名和 marketplace 名仍是 `ui-workflow`。 -之前用旧名字加过 marketplace 的,GitHub 会跳转,但建议 `/plugin marketplace remove ui-workflow` 后用新名字重新加。 - 可选但推荐(插件会自动找到它们,见 `vendor.lock.json` 里锁定的版本): ```bash @@ -138,8 +136,8 @@ baoyu-design 是可选的看图调色工具,只在项目仓库外用(它含 ## 在一个项目里开始 -- 前端:对 Claude 说"用 building-consistent-ui 给这个项目建立设计约定"。 -- 后端:对 Claude 说"用 building-reliable-backend 给这个项目建立后端约定和检查"。 +- 前端:对 Claude 说"用 dx-workflow 的 frontend 技能给这个项目建立设计约定和检查"。 +- 后端:对 Claude 说"用 dx-workflow 的 backend 技能给这个项目建立后端约定和检查"。 两者都会写约定文件、接好 `.verify/config.json`、加 lint 护栏、建一个空的 `docs/checklist.md`、和你一起填 `sensitive` 路径; 没有可脚本化的用户路径时生成 `ctl` 控制命令;最后用 `run-verify.mjs --config working` 在未改动的代码上跑一遍全部检查 @@ -147,31 +145,12 @@ baoyu-design 是可选的看图调色工具,只在项目仓库外用(它含 接着可以做的:装提交盖章钩子、接 CI 模板。 -### 从 0.3 升级 - -- 评审改为先跑 `review-brief.mjs` 生成 brief(`verify.md` 里写了命令)。延后的 Should-fix 写进 `.verify/deferred-.md`。 -- 评审模板多了 `## Checklist` 和 `Pre-existing`;清单项不成立(`- [ ]`)会挡住收尾检查。 -- 可选:在 lane 配置里填 `sensitive`,建 `docs/checklist.md`(空的就行),装提交盖章钩子,接 CI 模板。 -- `run-verify` 现在遇到第一个失败的检查就停下这条 lane,要跑完全部用 `--keep-going`。检查顺序请按从快到慢排。 - -### 从 0.2 升级 - -- 评审文件要在标题下多写一行 `Tree: `,没有这一行收尾检查不放行(`review-brief.mjs` 的 brief 会写明)。 -- 检查改为从基线提交读配置。如果 `.verify/config.json` 还没合进默认分支,先用 `run-verify.mjs --config working`。 -- Stop 钩子现在也会检查这一轮里已经提交的改动。 -- 没有 remote 的仓库,基线就是当前提交,请设置 `VERIFY_BASE`。 - -### 从 0.1 升级 - -0.1 用的是 `.ui-verify/`。在项目里运行 `node /scripts/run-verify.mjs --migrate`,它会把目录改成 `.verify/`、 -把检查放进 `ui` lane,并列出需要手动做的几步(`.gitignore`、写第一份 `acceptance.md`)。没迁移之前,Stop 钩子会提示迁移。 - ## 环境变量 | 变量 | 作用 | | --- | --- | | `VERIFY_BASE` | 基线提交(默认:和 `origin/HEAD`、`origin/main`、`origin/master` 的 merge-base,都没有就是 `HEAD`) | -| `UI_WORKFLOW_GATE` | Stop 钩子:`enforce`(默认)、`observe`、`off` | +| `DX_WORKFLOW_GATE` | Stop 钩子:`enforce`(默认)、`observe`、`off` | ## 文件 @@ -179,30 +158,30 @@ baoyu-design 是可选的看图调色工具,只在项目仓库外用(它含 | 路径 | 作用 | | --- | --- | -| `plugins/workflow/skills/building-consistent-ui/` | 前端:`SKILL.md`(入口)、`setup.md`、`build.md`、`verify.md`、`design-review.md`(截图评审)、`templates/`(design.md、截图测试、页面清单) | -| `plugins/workflow/skills/building-reliable-backend/` | 后端:`SKILL.md`(入口)、`setup.md`、`build.md`、`verify.md`、`code-review.md`(代码评审)、`templates/backend.md` | -| `plugins/workflow/shared/acceptance.md` | 怎么写验收标准、异常情况清单、评审怎么标记 | -| `plugins/workflow/shared/ctl.md` | 生成项目的控制命令(读写分开),以及 `verify-` skill 和用户路径 | -| `plugins/workflow/shared/ratchet.md` | 把犯过的错变成检查:分类、准入、单独提交、清理;清单格式 | -| `plugins/workflow/shared/verify.config.json` | `.verify/config.json` 模板(ui 和 api 两条 lane) | -| `plugins/workflow/shared/verify-ci.yml` | 项目用的 CI 模板 | +| `plugins/dx-workflow/skills/frontend/` | 前端:`SKILL.md`(入口)、`setup.md`、`build.md`、`verify.md`、`design-review.md`(截图评审)、`code-review.md`(前端代码评审)、`templates/`(design.md、截图测试、页面清单) | +| `plugins/dx-workflow/skills/backend/` | 后端:`SKILL.md`(入口)、`setup.md`、`build.md`、`verify.md`、`code-review.md`(代码评审)、`templates/backend.md` | +| `plugins/dx-workflow/shared/acceptance.md` | 怎么写验收标准、异常情况清单、评审怎么标记 | +| `plugins/dx-workflow/shared/ctl.md` | 生成项目的控制命令(读写分开),以及 `verify-` skill 和用户路径 | +| `plugins/dx-workflow/shared/ratchet.md` | 把犯过的错变成检查:分类、准入、单独提交、清理;清单格式 | +| `plugins/dx-workflow/shared/verify.config.json` | `.verify/config.json` 模板(frontend 和 backend 两条 lane) | +| `plugins/dx-workflow/shared/verify-ci.yml` | 项目用的 CI 模板 | **脚本和钩子** | 路径 | 作用 | | --- | --- | -| `plugins/workflow/hooks/hooks.json` | 注册 UserPromptSubmit 和 Stop 两个钩子 | -| `plugins/workflow/scripts/run-verify.mjs` | 按 lane 跑检查(含负向检查),记录退出码和内容哈希;`--config working`、`--keep-going`、`--restore`、`--migrate` | -| `plugins/workflow/scripts/review-brief.mjs` | 写评审 brief:内容哈希、深度、触发的清单项、轮次 | -| `plugins/workflow/scripts/make-evidence.mjs` | 生成证据包和合并分档;`--pr` 输出 PR 描述,`--checks-only --exit-code` 给 CI 用 | -| `plugins/workflow/scripts/stop-gate.mjs` | Stop 钩子 | -| `plugins/workflow/scripts/turn-start.mjs` | UserPromptSubmit 钩子:记录这一轮开始时的内容哈希和插件位置 | -| `plugins/workflow/scripts/stamp.mjs` | 提交盖章;`--install` 装 git 钩子 | -| `plugins/workflow/scripts/check-raw-styles.mjs` | 找出写死的颜色、Tailwind 色板类、任意值 | -| `plugins/workflow/scripts/find-tools.mjs` | 找到已安装的 taste-skill、ui-ux-pro-max、baoyu-design | -| `plugins/workflow/scripts/lib/verify-config.mjs` | 读配置(从基线提交)、算改动范围和内容哈希、找出"改了检查本身"的改动 | -| `plugins/workflow/scripts/lib/checklist.mjs` | 解析 `docs/checklist.md`,按 diff 选出触发的条目 | -| `plugins/workflow/scripts/lib/negative.mjs` | 负向检查 | +| `plugins/dx-workflow/hooks/hooks.json` | 注册 UserPromptSubmit 和 Stop 两个钩子 | +| `plugins/dx-workflow/scripts/run-verify.mjs` | 按 lane 跑检查(含负向检查),记录退出码和内容哈希;`--config working`、`--keep-going`、`--restore` | +| `plugins/dx-workflow/scripts/review-brief.mjs` | 写评审 brief:内容哈希、深度、触发的清单项、轮次 | +| `plugins/dx-workflow/scripts/make-evidence.mjs` | 生成证据包和合并分档;`--pr` 输出 PR 描述,`--checks-only --exit-code` 给 CI 用 | +| `plugins/dx-workflow/scripts/stop-gate.mjs` | Stop 钩子 | +| `plugins/dx-workflow/scripts/turn-start.mjs` | UserPromptSubmit 钩子:记录这一轮开始时的内容哈希和插件位置 | +| `plugins/dx-workflow/scripts/stamp.mjs` | 提交盖章;`--install` 装 git 钩子 | +| `plugins/dx-workflow/scripts/check-raw-styles.mjs` | 找出写死的颜色、Tailwind 色板类、任意值 | +| `plugins/dx-workflow/scripts/find-tools.mjs` | 找到已安装的 taste-skill、ui-ux-pro-max、baoyu-design | +| `plugins/dx-workflow/scripts/lib/verify-config.mjs` | 读配置(从基线提交)、算改动范围和内容哈希、找出"改了检查本身"的改动 | +| `plugins/dx-workflow/scripts/lib/checklist.mjs` | 解析 `docs/checklist.md`,按 diff 选出触发的条目 | +| `plugins/dx-workflow/scripts/lib/negative.mjs` | 负向检查 | **本仓库** @@ -220,7 +199,7 @@ npm test # node evals/run.mjs all --reviewer "claude -p --permission-mode acceptEdits" # 改 code-review.md、brief 或换模型之前先跑,和 evals/results/ 里上一次比 ``` -发版:改 `plugins/workflow/.claude-plugin/plugin.json` 的版本,合并后打同名 tag(如 `v0.4.0`),CI 模板按 tag 锁定插件版本。 +发版:改 `plugins/dx-workflow/.claude-plugin/plugin.json` 的版本,合并后打同名 tag(如 `v0.5.0`),CI 模板按 tag 锁定插件版本。 升级第三方工具:一次只升一个,读它的改动,在两个项目上各跑一次 `run-verify.mjs`,结果没变差再改 `vendor.lock.json` 里的 commit。 diff --git a/docs/adr/0003-checks-out-of-reach-and-bound-to-content.md b/docs/adr/0003-checks-out-of-reach-and-bound-to-content.md index 2de92ef..b048200 100644 --- a/docs/adr/0003-checks-out-of-reach-and-bound-to-content.md +++ b/docs/adr/0003-checks-out-of-reach-and-bound-to-content.md @@ -34,7 +34,7 @@ modify its own checks, and a review applies to one specific commit. - **The change is everything since the base**, commits on the branch included, deletions included. A UserPromptSubmit hook records the tree when a turn starts, so the Stop gate checks only turns that changed content. -- **Gate modes.** `UI_WORKFLOW_GATE=enforce|observe|off`; every decision goes to `.verify/gate.log`. +- **Gate modes.** `DX_WORKFLOW_GATE=enforce|observe|off`; every decision goes to `.verify/gate.log`. - **The scripts have tests** (`test/`, `npm test`) and CI, because they are the judge. ## Consequences @@ -44,4 +44,4 @@ committed edit to the config becomes the base; set `VERIFY_BASE` there. Setting written before 0.3 lack `Tree:` and must be redone. Hashing the tree costs one `git add -A` into a temporary index per run and per stop. The guard patterns are a starting list and will need project additions and pruning. Everything here still runs on the agent's machine, where the agent -can set `UI_WORKFLOW_GATE=off`; the authority for merges belongs in CI, which is the next step. +can set `DX_WORKFLOW_GATE=off`; the authority for merges belongs in CI, which is the next step. diff --git a/docs/adr/0005-dx-workflow-frontend-backend.md b/docs/adr/0005-dx-workflow-frontend-backend.md new file mode 100644 index 0000000..d859b3f --- /dev/null +++ b/docs/adr/0005-dx-workflow-frontend-backend.md @@ -0,0 +1,31 @@ +# 5. dx-workflow, with frontend and backend + +Date: 2026-11-18 · Status: accepted + +## Context + +The plugin was called `ui-workflow` and its halves `building-consistent-ui` and +`building-reliable-backend`, with lanes `ui` and `api`. It had outgrown the name: half of it is +backend, and most of it is verification, review and the ratchet. The front half was named for the +look, but a front end is also state, requests and accessibility in code, and nobody reviewed that +code: the frontend reviewer only judged screenshots. "UI" also suggested web only, while the front +end includes mobile clients. + +## Decision + +- The plugin is `dx-workflow`; its skills are `frontend` and `backend` (shown as + `dx-workflow:frontend`, `dx-workflow:backend`). Lane kinds are `frontend` and `backend`; lanes are + named per app or service (`web`, `app`, `api`) with a `kind`. +- UI stays inside frontend: `docs/design.md`, tokens, the look screenshots and `design-review.md` + keep their names. It is not a lane of its own, because the same files are both look and logic. +- The frontend review is the design review plus a frontend `code-review.md` (state, requests and + races, forms, security, accessibility in code, performance, the backend contract, tests), in one + review file. +- No compatibility with earlier names: the 0.1 `.ui-verify/` migration, `UI_VERIFY_RUN_DIR` and the + upgrade notes are gone. The Stop gate variable is `DX_WORKFLOW_GATE`. + +## Consequences + +Projects set up before this rename key their config by `ui`/`api` and must rename lanes or add +`kind`. Mobile (React Native / Expo) support is the next change: platform defaults for lane files, +token checks, screenshots, journeys and review lenses. diff --git a/evals/cases/check-then-insert-signup/case.json b/evals/cases/check-then-insert-signup/case.json index 6202a3b..4bdcec6 100644 --- a/evals/cases/check-then-insert-signup/case.json +++ b/evals/cases/check-then-insert-signup/case.json @@ -1,5 +1,5 @@ { - "lane": "api", + "lane": "backend", "kind": "bug", "request": "Sign-up must never create two accounts for the same email.", "acceptance": [ diff --git a/evals/cases/clean-pagination-clamp/case.json b/evals/cases/clean-pagination-clamp/case.json index afabea7..62b7fd1 100644 --- a/evals/cases/clean-pagination-clamp/case.json +++ b/evals/cases/clean-pagination-clamp/case.json @@ -1,5 +1,5 @@ { - "lane": "api", + "lane": "backend", "kind": "clean", "request": "Cap the page size of GET /products at 100 and default it to 20.", "acceptance": [ diff --git a/evals/cases/clean-rename-with-tests/case.json b/evals/cases/clean-rename-with-tests/case.json index 1f90338..68bb1f7 100644 --- a/evals/cases/clean-rename-with-tests/case.json +++ b/evals/cases/clean-rename-with-tests/case.json @@ -1,5 +1,5 @@ { - "lane": "api", + "lane": "backend", "kind": "clean", "request": "Rename calcTotal to orderTotal everywhere; no behaviour change.", "acceptance": [ diff --git a/evals/cases/idor-order-lookup/case.json b/evals/cases/idor-order-lookup/case.json index 4c54f8d..b57ae9c 100644 --- a/evals/cases/idor-order-lookup/case.json +++ b/evals/cases/idor-order-lookup/case.json @@ -1,5 +1,5 @@ { - "lane": "api", + "lane": "backend", "kind": "bug", "request": "Add GET /orders/:id so a signed-in customer can see one of their orders.", "acceptance": [ diff --git a/evals/cases/swallowed-payment-error/case.json b/evals/cases/swallowed-payment-error/case.json index d515400..404ec70 100644 --- a/evals/cases/swallowed-payment-error/case.json +++ b/evals/cases/swallowed-payment-error/case.json @@ -1,5 +1,5 @@ { - "lane": "api", + "lane": "backend", "kind": "bug", "request": "Charge the card when an order is placed; the customer must see an error if the charge fails.", "acceptance": [ diff --git a/evals/run.mjs b/evals/run.mjs index 6172aa9..29251a7 100644 --- a/evals/run.mjs +++ b/evals/run.mjs @@ -2,7 +2,7 @@ // Reviewer evals: does code-review.md find known bugs, and does it leave clean changes alone? // // node evals/run.mjs prepare [--out ] build the case as a project, run the checks, write the brief -// node evals/run.mjs score score the .verify/review-api.md a reviewer wrote there +// node evals/run.mjs score score the .verify/review-backend.md a reviewer wrote there // node evals/run.mjs all [--reviewer ""] [--case ] // // `all` prepares every case; with --reviewer it runs the command in each project with the brief on @@ -21,7 +21,7 @@ import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; const HERE = dirname(fileURLToPath(import.meta.url)); -const SCRIPTS = resolve(HERE, "../plugins/workflow/scripts"); +const SCRIPTS = resolve(HERE, "../plugins/dx-workflow/scripts"); const CASES = join(HERE, "cases"); const GIT_ENV = { GIT_AUTHOR_NAME: "eval", GIT_AUTHOR_EMAIL: "eval@example.com", GIT_COMMITTER_NAME: "eval", GIT_COMMITTER_EMAIL: "eval@example.com", GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1" }; const TESTS = "for f in test/*.test.mjs; do node \"$f\" || exit 1; done"; diff --git a/package.json b/package.json index c00e169..ed84fba 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,8 @@ { - "name": "ui-workflow-dev", + "name": "dx-workflow-dev", "private": true, "type": "module", - "description": "Tests for the ui-workflow plugin's scripts. The plugin itself has no dependencies.", + "description": "Tests for the dx-workflow plugin's scripts. The plugin itself has no dependencies.", "engines": { "node": ">=20" }, diff --git a/plugins/workflow/.claude-plugin/plugin.json b/plugins/dx-workflow/.claude-plugin/plugin.json similarity index 50% rename from plugins/workflow/.claude-plugin/plugin.json rename to plugins/dx-workflow/.claude-plugin/plugin.json index 55b85fd..ad2b25b 100644 --- a/plugins/workflow/.claude-plugin/plugin.json +++ b/plugins/dx-workflow/.claude-plugin/plugin.json @@ -1,16 +1,15 @@ { - "name": "ui-workflow", - "version": "0.4.0", - "description": "Front-end and back-end changes you can trust: acceptance criteria first, a design contract and a backend contract, checks per lane (ui, api) including a negative check, independent review, an evidence pack with a computed merge tier, and a Stop gate. Checks are read from the base commit, runs and reviews are bound to a content hash, and changes to the checks themselves are tier 3.", + "name": "dx-workflow", + "version": "0.5.0", + "description": "Front-end and back-end changes you can trust: acceptance criteria first, a design contract and a backend contract, checks per lane (frontend, backend) including a negative check, independent review, an evidence pack with a computed merge tier, and a Stop gate. Checks are read from the base commit, runs and reviews are bound to a content hash, and changes to the checks themselves are tier 3.", "author": { "name": "davidxiaodev" }, "license": "MIT", "keywords": [ "design-system", - "ui", + "frontend", "backend", - "api", "verification", "acceptance", "code-review", diff --git a/plugins/workflow/hooks/hooks.json b/plugins/dx-workflow/hooks/hooks.json similarity index 100% rename from plugins/workflow/hooks/hooks.json rename to plugins/dx-workflow/hooks/hooks.json diff --git a/plugins/workflow/scripts/check-raw-styles.mjs b/plugins/dx-workflow/scripts/check-raw-styles.mjs similarity index 100% rename from plugins/workflow/scripts/check-raw-styles.mjs rename to plugins/dx-workflow/scripts/check-raw-styles.mjs diff --git a/plugins/workflow/scripts/find-tools.mjs b/plugins/dx-workflow/scripts/find-tools.mjs similarity index 100% rename from plugins/workflow/scripts/find-tools.mjs rename to plugins/dx-workflow/scripts/find-tools.mjs diff --git a/plugins/workflow/scripts/lib/checklist.mjs b/plugins/dx-workflow/scripts/lib/checklist.mjs similarity index 99% rename from plugins/workflow/scripts/lib/checklist.mjs rename to plugins/dx-workflow/scripts/lib/checklist.mjs index cd9b7bc..68e8f8c 100644 --- a/plugins/workflow/scripts/lib/checklist.mjs +++ b/plugins/dx-workflow/scripts/lib/checklist.mjs @@ -5,7 +5,7 @@ // // ## C3 Old saved sessions still load // - when: path `src/session/**` or diff `/schemaVersion|MessageType/` -// - lanes: api +// - lanes: backend // - check: load a transcript written by the previous release; new fields need a default. // - source: incident 2026-10-02, PR #412 // diff --git a/plugins/workflow/scripts/lib/negative.mjs b/plugins/dx-workflow/scripts/lib/negative.mjs similarity index 100% rename from plugins/workflow/scripts/lib/negative.mjs rename to plugins/dx-workflow/scripts/lib/negative.mjs diff --git a/plugins/workflow/scripts/lib/verify-config.mjs b/plugins/dx-workflow/scripts/lib/verify-config.mjs similarity index 96% rename from plugins/workflow/scripts/lib/verify-config.mjs rename to plugins/dx-workflow/scripts/lib/verify-config.mjs index 876a420..b2156b5 100644 --- a/plugins/workflow/scripts/lib/verify-config.mjs +++ b/plugins/dx-workflow/scripts/lib/verify-config.mjs @@ -1,6 +1,6 @@ // Shared by run-verify, stop-gate and make-evidence: reads .verify/config.json, matches files to // lanes, and lists what changed. A lane is one surface with its own files, checks and reviewer -// ("ui" uses design-review.md, "api" uses code-review.md). +// (kind "frontend" uses design-review.md, kind "backend" uses code-review.md). import { execFileSync } from "node:child_process"; import { copyFileSync, existsSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync } from "node:fs"; import { tmpdir } from "node:os"; @@ -9,8 +9,8 @@ import { isAbsolute, join } from "node:path"; export const VERIFY_DIR = ".verify"; // Paths a lane ignores unless its config says otherwise: test code and verification output. -const UI_FILES = ["**/*.{tsx,jsx,vue,svelte,html,css,scss}"]; -const UI_IGNORE = [ +const FRONTEND_FILES = ["**/*.{tsx,jsx,vue,svelte,html,css,scss}"]; +const FRONTEND_IGNORE = [ "**/e2e/**", "**/test/**", "**/tests/**", @@ -54,8 +54,8 @@ export function loadConfig(root, { source = "base", base } = {}) { ...lane, name, kind, - files: lane.files ?? (kind === "ui" ? UI_FILES : []), - ignore: [...(lane.ignore ?? (kind === "ui" ? UI_IGNORE : [])), `${VERIFY_DIR}/**`], + files: lane.files ?? (kind === "frontend" ? FRONTEND_FILES : []), + ignore: [...(lane.ignore ?? (kind === "frontend" ? FRONTEND_IGNORE : [])), `${VERIFY_DIR}/**`], checks: lane.checks ?? [], }; }); @@ -80,17 +80,13 @@ function normalizeJson(text) { } } -export function legacyConfigExists(root) { - return existsSync(join(root, ".ui-verify", "config.json")) && !existsSync(join(root, VERIFY_DIR, "config.json")); -} - /** True when the file belongs to the lane: matches one of its files globs and none of its ignore globs. */ export function inLane(lane, file) { return matchAny(lane.files, file) && !matchAny(lane.ignore, file); } export function contractPaths(lane) { - const own = lane.kind === "ui" ? ["docs/design.md"] : lane.kind === "api" ? ["docs/backend.md"] : []; + const own = lane.kind === "frontend" ? ["docs/design.md"] : lane.kind === "backend" ? ["docs/backend.md"] : []; return [...own, ...(lane.tokens ?? []), ...(lane.contract ?? []), ...(lane.migrations ?? [])]; } diff --git a/plugins/workflow/scripts/make-evidence.mjs b/plugins/dx-workflow/scripts/make-evidence.mjs similarity index 98% rename from plugins/workflow/scripts/make-evidence.mjs rename to plugins/dx-workflow/scripts/make-evidence.mjs index 003741e..78f0c61 100644 --- a/plugins/workflow/scripts/make-evidence.mjs +++ b/plugins/dx-workflow/scripts/make-evidence.mjs @@ -158,8 +158,8 @@ const blast = reach.length ? `wide: ${reach.join(", ")}` : `contained: ${touched const revert = field("Revert") ?? (migrationChanges.length ? "revert the commit and run the down migration first; check what data the up migration already changed" : "revert the commit"); const danger = [`- Door: ${door}`, `- Blast radius: ${blast}`, `- How to revert: ${revert}`]; -// Screenshots from the ui lanes' run folders. -const uiDirs = [...new Set(lanes.filter((l) => l.kind === "ui").map((l) => last.lanes[l.name]?.runDir).filter(Boolean))]; +// Screenshots from the frontend lanes' run folders. +const uiDirs = [...new Set(lanes.filter((l) => l.kind === "frontend").map((l) => last.lanes[l.name]?.runDir).filter(Boolean))]; const snapshots = walk(root, (d) => !/node_modules|\.git$|\.next$|\.verify$/.test(d)).filter((f) => /-snapshots[\\/].+\.png$/.test(f)); const pages = new Map(); for (const dir of uiDirs) { diff --git a/plugins/workflow/scripts/review-brief.mjs b/plugins/dx-workflow/scripts/review-brief.mjs similarity index 92% rename from plugins/workflow/scripts/review-brief.mjs rename to plugins/dx-workflow/scripts/review-brief.mjs index 2841e09..18b86bb 100644 --- a/plugins/workflow/scripts/review-brief.mjs +++ b/plugins/dx-workflow/scripts/review-brief.mjs @@ -3,8 +3,8 @@ // what to read, the tree under review, how deep to go, the checklist items this diff triggers, and, // from the second round on, the previous round's findings and only the diff since then. // -// node review-brief.mjs --lane api --request "" [--root ] -// node review-brief.mjs --lane ui --request "…" --scope "" --baselines "" +// node review-brief.mjs --lane backend --request "" [--root ] +// node review-brief.mjs --lane frontend --request "…" --scope "" --baselines "" // // Prints the brief (pass it verbatim to a fresh subagent) and saves it to .verify/brief-.md. // Exit 0 with a brief; 3 when three rounds ran without approval (stop and hand the findings to the @@ -112,17 +112,20 @@ if (round > MAX_ROUNDS) { const deferredPath = join(cfg.dir, `deferred-${lane.name}.md`); const deferred = existsSync(deferredPath) ? readFileSync(deferredPath, "utf8").trim() : ""; -const guide = join(PLUGIN, "skills", lane.kind === "ui" ? "building-consistent-ui/design-review.md" : "building-reliable-backend/code-review.md"); -const contractDoc = lane.kind === "ui" ? "docs/design.md" : "docs/backend.md"; +const guides = + lane.kind === "frontend" + ? `${join(PLUGIN, "skills/frontend/design-review.md")} for the screenshots, then ${join(PLUGIN, "skills/frontend/code-review.md")} for the code (one review file, one Findings list)` + : join(PLUGIN, "skills/backend/code-review.md"); +const contractDoc = lane.kind === "frontend" ? "docs/design.md" : "docs/backend.md"; const out = []; -out.push(`Review lane ${lane.name}, round ${round} of at most ${MAX_ROUNDS}. Follow ${guide} exactly. You did not build this change.`, ""); +out.push(`Review lane ${lane.name}, round ${round} of at most ${MAX_ROUNDS}. Follow ${guides} exactly. You did not build this change.`, ""); out.push(`The user asked for: ${request}`, ""); if (opt("scope")) out.push(`Scope: ${opt("scope")}`); if (opt("baselines")) out.push(`Baselines updated in this change (copy into the review): ${opt("baselines")}`); if (opt("scope") || opt("baselines")) out.push(""); -out.push("## Read", `- ${contractDoc}, .verify/acceptance.md, .verify/last-run.json (lanes.${lane.name}: checks, notes, logs${lane.kind === "ui" ? ", runDir screenshots" : ""})`); -if (lane.kind === "ui") out.push("- the ui-look page list (ui-pages.json) for the pages in scope"); +out.push("## Read", `- ${contractDoc}, .verify/acceptance.md, .verify/last-run.json (lanes.${lane.name}: checks, notes, logs${lane.kind === "frontend" ? ", runDir screenshots" : ""})`); +if (lane.kind === "frontend") out.push("- the ui-look page list (ui-pages.json) for the pages in scope"); out.push(`- the change: \`git diff ${short(cfg.base)}\` (${lanePaths.length} file(s) in this lane, ${size} changed lines)`); const newFiles = lanePaths.filter((p) => untracked.has(p)); if (newFiles.length) out.push(`- new files not yet in git, so not in that diff (read them whole): ${newFiles.join(", ")}`); diff --git a/plugins/workflow/scripts/run-verify.mjs b/plugins/dx-workflow/scripts/run-verify.mjs similarity index 76% rename from plugins/workflow/scripts/run-verify.mjs rename to plugins/dx-workflow/scripts/run-verify.mjs index abe9b38..9bcdaae 100644 --- a/plugins/workflow/scripts/run-verify.mjs +++ b/plugins/dx-workflow/scripts/run-verify.mjs @@ -2,20 +2,19 @@ // Runs the project's checks from .verify/config.json, lane by lane, and records the outcome in // .verify/last-run.json from real exit codes only, so the Stop gate can trust it. // -// node run-verify.mjs [--lane ui,api] [--only name,name] [--root ] +// node run-verify.mjs [--lane frontend,backend] [--only name,name] [--root ] // [--config base|working] [--base ] [--keep-going] // // A lane stops at its first failing check (cheap checks first: order them in config.json from // fastest to slowest); the rest are recorded as skipped. --keep-going runs every check anyway. // node run-verify.mjs --restore put back files a crashed negative check left reverted -// node run-verify.mjs --migrate move a 0.1 .ui-verify/ setup to .verify/ (lane "ui") // // config.json: -// { "lanes": { "api": { "files": ["services/api/**"], "checks": [ +// { "lanes": { "backend": { "files": ["services/api/**"], "checks": [ // { "name": "unit", "run": "pnpm test", "cwd": "services/api", "timeoutMin": 20 }, // { "name": "negative", "negative": { "test": "pnpm --dir services/api test" } } ] } } } // A check with "negative" instead of "run" is the built-in negative check (lib/negative.mjs). -// Each check gets VERIFY_RUN_DIR (and UI_VERIFY_RUN_DIR, the 0.1 name) and VERIFY_LANE. +// Each check gets VERIFY_RUN_DIR and VERIFY_LANE. // // The checks come from .verify/config.json as it is on the base commit (the merge-base with the // default branch, or --base / VERIFY_BASE), so a change cannot edit the checks that judge it. @@ -27,10 +26,10 @@ // trusting file times. // Exit 0 = every check passed, 1 = a check failed, 2 = no config or nothing to run. import { spawnSync } from "node:child_process"; -import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { backupExists, restore, runNegative } from "./lib/negative.mjs"; -import { legacyConfigExists, loadConfig, readJson, resolveBase, treeHash, VERIFY_DIR } from "./lib/verify-config.mjs"; +import { loadConfig, readJson, resolveBase, treeHash, VERIFY_DIR } from "./lib/verify-config.mjs"; const args = process.argv.slice(2); const opt = (name) => { @@ -39,8 +38,6 @@ const opt = (name) => { }; const root = resolve(opt("root") ?? process.cwd()); -if (args.includes("--migrate")) process.exit(migrate()); - const configSource = opt("config") ?? "base"; if (!["base", "working"].includes(configSource)) { console.error('run-verify: --config takes "base" or "working".'); @@ -48,11 +45,7 @@ if (!["base", "working"].includes(configSource)) { } const cfg = loadConfig(root, { source: configSource, base: opt("base") ? resolveBase(root, opt("base")) : undefined }); if (!cfg) { - console.error( - legacyConfigExists(root) - ? "run-verify: this project still uses .ui-verify/ (ui-workflow 0.1). Run run-verify.mjs --migrate first." - : `run-verify: no ${join(root, VERIFY_DIR, "config.json")}. Create it from the plugin's shared/verify.config.json.`, - ); + console.error(`run-verify: no ${join(root, VERIFY_DIR, "config.json")}. Create it from the plugin's shared/verify.config.json.`); process.exit(2); } @@ -115,7 +108,7 @@ for (const lane of lanes) { continue; } const cwd = resolve(root, check.cwd ?? "."); - const env = { ...process.env, VERIFY_RUN_DIR: runDir, UI_VERIFY_RUN_DIR: runDir, VERIFY_LANE: lane.name }; + const env = { ...process.env, VERIFY_RUN_DIR: runDir, VERIFY_LANE: lane.name }; const timeoutMs = (check.timeoutMin ?? 20) * 60_000; const t0 = Date.now(); process.stdout.write(`run-verify: ${lane.name}/${check.name} … `); @@ -175,32 +168,3 @@ console.log(`\nrun-verify: logs and evidence in ${runDir}`); if (anyFailed) console.log("Read the failing logs before changing anything. Never weaken a test or a check to get green."); if (only) console.log("A run with --only is recorded as partial and does not satisfy the Stop gate."); process.exit(anyFailed ? 1 : 0); - -function migrate() { - const oldDir = join(root, ".ui-verify"); - const newDir = join(root, VERIFY_DIR); - if (!existsSync(join(oldDir, "config.json"))) { - console.error("run-verify --migrate: no .ui-verify/config.json here."); - return 2; - } - if (existsSync(join(newDir, "config.json"))) { - console.error("run-verify --migrate: .verify/config.json already exists; nothing moved."); - return 2; - } - const old = JSON.parse(readFileSync(join(oldDir, "config.json"), "utf8")); - renameSync(oldDir, newDir); - const { checks = [], tokens, shared, ...rest } = old; - const config = { ...rest, lanes: { ui: { ...(tokens ? { tokens } : {}), ...(shared ? { shared } : {}), checks } } }; - writeFileSync(join(newDir, "config.json"), JSON.stringify(config, null, 2) + "\n"); - if (existsSync(join(newDir, "review.md"))) renameSync(join(newDir, "review.md"), join(newDir, "review-ui.md")); - console.log( - [ - 'run-verify --migrate: moved .ui-verify/ to .verify/ and its checks into lane "ui"; review.md is now review-ui.md.', - "Still to do by hand:", - "- .gitignore: replace .ui-verify/runs/ with the two lines `.verify/*` and `!.verify/config.json`.", - "- Commands in config.json that write to $UI_VERIFY_RUN_DIR keep working; new ones use $VERIFY_RUN_DIR.", - "- Write .verify/acceptance.md for the next change (/shared/acceptance.md).", - ].join("\n"), - ); - return 0; -} diff --git a/plugins/workflow/scripts/stamp.mjs b/plugins/dx-workflow/scripts/stamp.mjs similarity index 99% rename from plugins/workflow/scripts/stamp.mjs rename to plugins/dx-workflow/scripts/stamp.mjs index 5a999aa..ce77ca9 100644 --- a/plugins/workflow/scripts/stamp.mjs +++ b/plugins/dx-workflow/scripts/stamp.mjs @@ -64,7 +64,7 @@ function install() { const hooksDir = gitLines(root, ["rev-parse", "--git-path", "hooks"])[0]; const dir = isAbsolute(hooksDir) ? hooksDir : join(root, hooksDir); const hook = join(dir, "prepare-commit-msg"); - const marker = "# ui-workflow stamp"; + const marker = "# dx-workflow stamp"; if (existsSync(hook)) { const text = readFileSync(hook, "utf8"); if (text.includes(marker)) { diff --git a/plugins/workflow/scripts/stop-gate.mjs b/plugins/dx-workflow/scripts/stop-gate.mjs similarity index 86% rename from plugins/workflow/scripts/stop-gate.mjs rename to plugins/dx-workflow/scripts/stop-gate.mjs index 4311ec0..15be270 100644 --- a/plugins/workflow/scripts/stop-gate.mjs +++ b/plugins/dx-workflow/scripts/stop-gate.mjs @@ -1,6 +1,6 @@ #!/usr/bin/env node // Claude Code Stop hook. In a project with .verify/config.json it blocks the end of a turn that -// changed files of a lane (ui, api, …) when that lane is not verified for exactly the content on +// changed files of a lane (frontend, backend, …) when that lane is not verified for exactly the content on // disk now: // - its last run-verify did not pass, or ran on a different tree (content hash, not file times); // - its independent review is missing, open, not approved, or names a different tree; @@ -11,7 +11,7 @@ // turn that only talked is not stopped. // // It blocks once per stop (stop_hook_active lets the second attempt through, so a turn cannot loop -// forever). UI_WORKFLOW_GATE: "enforce" (default) blocks; "observe" only logs what it would have +// forever). DX_WORKFLOW_GATE: "enforce" (default) blocks; "observe" only logs what it would have // blocked; "off" does nothing. Every decision is appended to .verify/gate.log. import { appendFileSync, existsSync, readFileSync, statSync } from "node:fs"; import { join } from "node:path"; @@ -21,29 +21,19 @@ import { changedSince, gitRoot, inLane, - legacyConfigExists, loadConfig, OPEN_LINE, readJson, treeHash, - workingChanges, } from "./lib/verify-config.mjs"; -const mode = (process.env.UI_WORKFLOW_GATE ?? "enforce").toLowerCase(); +const mode = (process.env.DX_WORKFLOW_GATE ?? "enforce").toLowerCase(); const input = readStdin(); if (mode === "off") process.exit(0); const root = gitRoot(input.cwd ?? process.cwd()); if (!root) process.exit(0); -if (legacyConfigExists(root)) { - const ui = workingChanges(root).filter((f) => /\.(tsx|jsx|vue|svelte|html|css|scss)$/.test(f)); - if (ui.length && !input.stop_hook_active) { - block([`UI files changed (${preview(ui)}) in a project still set up for ui-workflow 0.1 (.ui-verify/).`, "Run `node /scripts/run-verify.mjs --migrate`, follow what it prints, then verify as the skill says."]); - } - process.exit(0); -} - const cfg = loadConfig(root); if (!cfg) process.exit(0); @@ -123,7 +113,7 @@ log("block", problems); block([ "Changes are not verified:", ...problems.map((p) => `- ${p}`), - "Follow the lane's skill (ui: building-consistent-ui verify.md; api: building-reliable-backend verify.md): run run-verify.mjs, get an independent review written to .verify/review-.md that names the run's tree and accounts for every acceptance criterion, then run make-evidence.mjs.", + "Follow the lane's skill (ui: frontend verify.md; api: backend verify.md): run run-verify.mjs, get an independent review written to .verify/review-.md that names the run's tree and accounts for every acceptance criterion, then run make-evidence.mjs.", "If you cannot verify (no browser, no database, server will not start), say so plainly to the user instead of claiming the work is done.", ]); diff --git a/plugins/workflow/scripts/turn-start.mjs b/plugins/dx-workflow/scripts/turn-start.mjs similarity index 100% rename from plugins/workflow/scripts/turn-start.mjs rename to plugins/dx-workflow/scripts/turn-start.mjs diff --git a/plugins/workflow/shared/acceptance.md b/plugins/dx-workflow/shared/acceptance.md similarity index 99% rename from plugins/workflow/shared/acceptance.md rename to plugins/dx-workflow/shared/acceptance.md index dcf58a0..258e596 100644 --- a/plugins/workflow/shared/acceptance.md +++ b/plugins/dx-workflow/shared/acceptance.md @@ -61,7 +61,7 @@ to prevent. ```markdown # Acceptance: Request: -Lanes: +Lanes: Revert: Door: " when it cannot be undone (an email sent, a third party called); migrations and contracts are detected> diff --git a/plugins/workflow/shared/ctl.md b/plugins/dx-workflow/shared/ctl.md similarity index 98% rename from plugins/workflow/shared/ctl.md rename to plugins/dx-workflow/shared/ctl.md index 840b482..36989ac 100644 --- a/plugins/workflow/shared/ctl.md +++ b/plugins/dx-workflow/shared/ctl.md @@ -4,7 +4,7 @@ Use this when the project has no scripted way to start the app, put it in a know a user or caller does, and look at the result (no e2e suite, no API journeys, or ones that skip the paths you change). The output is a small control CLI in the repo, a project skill that teaches it, journeys that use it, and a `functional` check per lane in `.verify/config.json`. Both lanes use the -same `ctl`: the ui lane drives screens, the api lane drives requests, and both read the same data. +same `ctl`: the frontend lane drives screens, the backend lane drives requests, and both read the same data. You write it for the next agent, who will read it cold, mid-task. diff --git a/plugins/workflow/shared/ratchet.md b/plugins/dx-workflow/shared/ratchet.md similarity index 99% rename from plugins/workflow/shared/ratchet.md rename to plugins/dx-workflow/shared/ratchet.md index 509632d..ae89ec4 100644 --- a/plugins/workflow/shared/ratchet.md +++ b/plugins/dx-workflow/shared/ratchet.md @@ -61,7 +61,7 @@ Items the reviewer checks when their trigger matches the diff. Add with evidence ## C1 A retried create does not create twice - when: diff `/router\.post|@Post\(|app\.post/` or path `src/**/handlers/create*.ts` -- lanes: api +- lanes: backend - check: POST the same body twice with the same Idempotency-Key; one row, the same id both times. - source: incident 2026-09-14 (double orders), PR #311 diff --git a/plugins/workflow/shared/verify-ci.yml b/plugins/dx-workflow/shared/verify-ci.yml similarity index 78% rename from plugins/workflow/shared/verify-ci.yml rename to plugins/dx-workflow/shared/verify-ci.yml index 03b4998..76cf675 100644 --- a/plugins/workflow/shared/verify-ci.yml +++ b/plugins/dx-workflow/shared/verify-ci.yml @@ -1,4 +1,4 @@ -# Copy to .github/workflows/verify.yml in a project that uses ui-workflow. +# Copy to .github/workflows/verify.yml in a project that uses dx-workflow. # # On every pull request it reruns the lanes' checks from the base branch's .verify/config.json on # the PR's head, and computes the merge tier from the checks and what changed (contracts, sensitive @@ -25,7 +25,7 @@ jobs: timeout-minutes: 60 env: # Pin the plugin to a release tag or commit; upgrade it in its own pull request. - UI_WORKFLOW_REF: v0.4.0 + DX_WORKFLOW_REF: v0.5.0 VERIFY_BASE: origin/${{ github.base_ref }} steps: - uses: actions/checkout@v4 @@ -34,10 +34,10 @@ jobs: - uses: actions/setup-node@v4 with: node-version: 22 - - name: Get ui-workflow + - name: Get dx-workflow run: | - git clone --quiet --depth 1 --branch "$UI_WORKFLOW_REF" https://github.com/davidxiaodev/workflow "$RUNNER_TEMP/ui-workflow" - echo "UI_WORKFLOW=$RUNNER_TEMP/ui-workflow/plugins/workflow" >> "$GITHUB_ENV" + git clone --quiet --depth 1 --branch "$DX_WORKFLOW_REF" https://github.com/davidxiaodev/workflow "$RUNNER_TEMP/dx-workflow" + echo "DX_WORKFLOW=$RUNNER_TEMP/dx-workflow/plugins/dx-workflow" >> "$GITHUB_ENV" # >>> project setup: install dependencies, start the services the checks need - name: Install @@ -45,10 +45,10 @@ jobs: # <<< project setup - name: Run the checks (from the base branch's config) - run: node "$UI_WORKFLOW/scripts/run-verify.mjs" --keep-going + run: node "$DX_WORKFLOW/scripts/run-verify.mjs" --keep-going - name: Merge tier if: always() - run: node "$UI_WORKFLOW/scripts/make-evidence.mjs" --checks-only --exit-code >> "$GITHUB_STEP_SUMMARY" + run: node "$DX_WORKFLOW/scripts/make-evidence.mjs" --checks-only --exit-code >> "$GITHUB_STEP_SUMMARY" - name: Keep logs and screenshots if: always() uses: actions/upload-artifact@v4 diff --git a/plugins/workflow/shared/verify.config.json b/plugins/dx-workflow/shared/verify.config.json similarity index 98% rename from plugins/workflow/shared/verify.config.json rename to plugins/dx-workflow/shared/verify.config.json index b4aac35..fa9a61d 100644 --- a/plugins/workflow/shared/verify.config.json +++ b/plugins/dx-workflow/shared/verify.config.json @@ -2,7 +2,7 @@ "guard": [], "tests": ["**/test/**", "**/tests/**", "**/__tests__/**", "**/e2e/**", "**/journeys/**", "**/*.{test,spec,e2e}.*", "**/*_test.*", "**/test_*.py", "**/*-snapshots/**"], "lanes": { - "ui": { + "frontend": { "files": ["/**/*.{tsx,jsx,vue,svelte,html,css,scss}"], "tokens": [""], "shared": [""], @@ -15,7 +15,7 @@ { "name": "inspect", "run": "node --out \"$VERIFY_RUN_DIR/inspect\" <--app for app screens>" } ] }, - "api": { + "backend": { "files": ["/**", "/**", ""], "contract": [""], "migrations": ["/**"], diff --git a/plugins/workflow/skills/building-reliable-backend/SKILL.md b/plugins/dx-workflow/skills/backend/SKILL.md similarity index 90% rename from plugins/workflow/skills/building-reliable-backend/SKILL.md rename to plugins/dx-workflow/skills/backend/SKILL.md index 471245c..9a2efaa 100644 --- a/plugins/workflow/skills/building-reliable-backend/SKILL.md +++ b/plugins/dx-workflow/skills/backend/SKILL.md @@ -1,5 +1,5 @@ --- -name: building-reliable-backend +name: backend description: Use when building, changing, reviewing or debugging server-side code - HTTP, GraphQL or RPC endpoints, database schema and migrations, background jobs, queues, webhooks, auth and permissions; when setting up a project's backend checks; or when asked whether a backend change is safe to merge. --- @@ -8,7 +8,7 @@ description: Use when building, changing, reviewing or debugging server-side cod ## Overview A backend change is done when what a caller can observe was decided before building, the code was -built test first at agreed seams, `run-verify.mjs` passed for the `api` lane (including a negative +built test first at agreed seams, `run-verify.mjs` passed for the `backend` lane (including a negative check proving the tests can fail), a reviewer who did not write it marked every acceptance criterion from evidence, and the evidence pack says how much a person must look before merging. @@ -19,12 +19,12 @@ the contract. `` is this skill's folder; `` is two levels up (it | Project state | Read | | --- | --- | -| No `docs/backend.md` or no `api` lane in `.verify/config.json` | `setup.md`, then come back | +| No `docs/backend.md` or no `backend` lane in `.verify/config.json` | `setup.md`, then come back | | Any change | `/shared/acceptance.md` first: write `.verify/acceptance.md` | | Building or changing endpoints, jobs, schema | `build.md`, then `verify.md` | | Asked only to review a change | `verify.md` (dispatch), then `code-review.md` | | No scripted way to start the app and drive requests | `/shared/ctl.md` | -| The change also touches screens | the `building-consistent-ui` skill for the ui lane; both lanes must pass | +| The change also touches screens | the `frontend` skill for the frontend lane; both lanes must pass | | A review found a Blocker, a change was reverted, or the user corrected you | `/shared/ratchet.md`: make it a check | ## Contract changes @@ -52,7 +52,7 @@ non-breaking way unless they choose the break. It is tier 3 either way. ## Done means `run-verify.mjs` printed `pass` for every lane the change touched, on the content now on disk; -`.verify/review-api.md` (written by a fresh reviewer from the `review-brief.mjs` brief, with +`.verify/review-backend.md` (written by a fresh reviewer from the `review-brief.mjs` brief, with `code-review.md`) names that same tree, has no open line, marks every acceptance id and every triggered checklist item, and says `Verdict: approved`; `make-evidence.mjs` wrote the evidence pack after it, for the same tree; diff --git a/plugins/workflow/skills/building-reliable-backend/build.md b/plugins/dx-workflow/skills/backend/build.md similarity index 97% rename from plugins/workflow/skills/building-reliable-backend/build.md rename to plugins/dx-workflow/skills/backend/build.md index 6ba7c12..1cb87bf 100644 --- a/plugins/workflow/skills/building-reliable-backend/build.md +++ b/plugins/dx-workflow/skills/backend/build.md @@ -28,7 +28,7 @@ handling the duplicate, or an atomic `UPDATE … WHERE state = old`), never check-then-insert. Errors use the format in `docs/backend.md`; never swallow an exception or return success on failure; log with the request id, never secrets or personal data. -8. Run the lane's fast checks while you work (`run-verify.mjs --lane api --only types,unit`), then go to `verify.md`. +8. Run the lane's fast checks while you work (`run-verify.mjs --lane backend --only types,unit`), then go to `verify.md`. Debugging a failure on the way: reproduce it in one focused test, find the cause, fix the cause, keep the test. Two fixes that did not hold mean you have not found the cause; stop guessing and trace it. diff --git a/plugins/workflow/skills/building-reliable-backend/code-review.md b/plugins/dx-workflow/skills/backend/code-review.md similarity index 96% rename from plugins/workflow/skills/building-reliable-backend/code-review.md rename to plugins/dx-workflow/skills/backend/code-review.md index 3122429..ddec60c 100644 --- a/plugins/workflow/skills/building-reliable-backend/code-review.md +++ b/plugins/dx-workflow/skills/backend/code-review.md @@ -8,7 +8,7 @@ acceptance marks and a verdict; fix nothing. - `.verify/acceptance.md` and the user's request from your brief. If they disagree, that is a Blocker. - `docs/backend.md`: the project's own decisions. Judge against them, not a generic ideal. -- The diff from the base ref, and `.verify/last-run.json` → `lanes.api`: which checks ran, their +- The diff from the base ref, and `.verify/last-run.json` → `lanes.backend`: which checks ran, their notes, their logs. A check missing from the run is "not checked", never "passed". ## 2. Acceptance: verify each criterion yourself @@ -60,12 +60,12 @@ A bug in code the diff did not touch is `Pre-existing`: report it, it does not b is one instance of a class lists every instance. Drop what you cannot tie to a concrete failure (input → wrong output, crash, leak, lost row); that is taste. Drop what docs/backend.md decided and what tooling already enforces. A few findings you are sure of beat a long list; say how sure you are when you are not. -## 5. Write `.verify/review-api.md` +## 5. Write `.verify/review-backend.md` ```markdown -# Review +# Review Reviewer: -Tree: +Tree: Scope: ..; ## Acceptance diff --git a/plugins/workflow/skills/building-reliable-backend/setup.md b/plugins/dx-workflow/skills/backend/setup.md similarity index 93% rename from plugins/workflow/skills/building-reliable-backend/setup.md rename to plugins/dx-workflow/skills/backend/setup.md index 206fd50..2847e9f 100644 --- a/plugins/workflow/skills/building-reliable-backend/setup.md +++ b/plugins/dx-workflow/skills/backend/setup.md @@ -1,7 +1,7 @@ # Setup: a backend contract and checks for this project Do this once per project, or once per service when a repo has several (each gets its own lane, -`api-`, with `"kind": "api"`). The output is `docs/backend.md`, a contract file, the `api` +`backend-`, with `"kind": "backend"`). The output is `docs/backend.md`, a contract file, the `backend` lane in `.verify/config.json`, and `ctl`. The user decides policy; you find what exists and write it down. ## 1. Inventory @@ -21,7 +21,7 @@ From the repo, then the user for what the repo cannot tell you: Copy `/templates/backend.md` and fill every section from the inventory. Where the repo has no policy yet, propose one with your reason and let the user agree; mark unconfirmed choices "chosen by agent". Add one line to `CLAUDE.md` (create it if missing; also `AGENTS.md` if present): -"Before any backend work read docs/backend.md and use the building-reliable-backend skill." +"Before any backend work read docs/backend.md and use the backend skill." ## 3. The contract file @@ -74,8 +74,8 @@ skill, and API journeys that call the running app and check the rows. ## 7. Wire `.verify/config.json` 1. The project must be a git repository (the Stop gate and the negative check read git). Ask before `git init`. -2. If `.verify/config.json` exists (the ui lane is set up), add the `api` lane from - `/shared/verify.config.json`; else copy that file and delete the `ui` lane. +2. If `.verify/config.json` exists (the frontend lane is set up), add the `backend` lane from + `/shared/verify.config.json`; else copy that file and delete the `frontend` lane. 3. `files`: everything a backend change touches, tests included (`/**`, the migrations folder, the contract file). `contract` and `migrations`: their paths (a change there is tier 3). `shared`: modules many endpoints depend on (auth, db access, money) (a change there is tier 2). @@ -83,7 +83,7 @@ skill, and API journeys that call the running app and check the rows. never invent one. `negative.test` runs the lane's unit and integration tests in one command, from the repo root. Set top-level `tests` if this repo's test files live elsewhere. 5. `.gitignore`: `.verify/*` and `!.verify/config.json`. -6. Run `node /scripts/run-verify.mjs --lane api --config working`. Every check must pass on +6. Run `node /scripts/run-verify.mjs --lane backend --config working`. Every check must pass on the unchanged code; fix the setup, or tell the user which check is red before any change and why. (`--config working` because the checks are not on the default branch yet. Once they are, every run reads them from the base commit, so a later change cannot edit the checks that judge it; a change diff --git a/plugins/workflow/skills/building-reliable-backend/templates/backend.md b/plugins/dx-workflow/skills/backend/templates/backend.md similarity index 100% rename from plugins/workflow/skills/building-reliable-backend/templates/backend.md rename to plugins/dx-workflow/skills/backend/templates/backend.md diff --git a/plugins/workflow/skills/building-reliable-backend/verify.md b/plugins/dx-workflow/skills/backend/verify.md similarity index 95% rename from plugins/workflow/skills/building-reliable-backend/verify.md rename to plugins/dx-workflow/skills/backend/verify.md index 6a40e5e..20792ca 100644 --- a/plugins/workflow/skills/building-reliable-backend/verify.md +++ b/plugins/dx-workflow/skills/backend/verify.md @@ -2,7 +2,7 @@ ## Run the checks -`node /scripts/run-verify.mjs --lane api` (or without `--lane` to run every lane) runs the +`node /scripts/run-verify.mjs --lane backend` (or without `--lane` to run every lane) runs the lane's checks from `.verify/config.json` and records the result from real exit codes. | Check | Passes when | @@ -41,7 +41,7 @@ contract; propose them to the user. The agent that built the change does not review it. Write the brief with ```bash -node /scripts/review-brief.mjs --lane api --request "" +node /scripts/review-brief.mjs --lane backend --request "" ``` and dispatch a fresh subagent (a different model when one is available) with exactly its output, @@ -49,7 +49,7 @@ and nothing about how the change was made. The brief names the tree under review the change (quick, standard, or deep for contracts, migrations, sensitive paths and changed checks, where Blockers must survive an attempt to disprove them), lists the `docs/checklist.md` items the diff triggers, and from the second round on gives the reviewer the previous findings and only the diff -since then. Put deferred Should-fixes, one per line with the reason, in `.verify/deferred-api.md` +since then. Put deferred Should-fixes, one per line with the reason, in `.verify/deferred-backend.md` before writing the brief. Then: diff --git a/plugins/workflow/skills/building-consistent-ui/SKILL.md b/plugins/dx-workflow/skills/frontend/SKILL.md similarity index 89% rename from plugins/workflow/skills/building-consistent-ui/SKILL.md rename to plugins/dx-workflow/skills/frontend/SKILL.md index b43b33e..685b0e6 100644 --- a/plugins/workflow/skills/building-consistent-ui/SKILL.md +++ b/plugins/dx-workflow/skills/frontend/SKILL.md @@ -1,5 +1,5 @@ --- -name: building-consistent-ui +name: frontend description: Use when building, restyling or reviewing any user-facing screen, page, storefront, dashboard or component; when starting a project's design system or tokens; when a user says the UI looks generic, ugly, unprofessional or inconsistent, or asks for one page or module to look different from the rest. --- @@ -21,11 +21,10 @@ Third-party design skills are tools this workflow calls; they never override the | Any change | `/shared/acceptance.md` first: write `.verify/acceptance.md` | | Request: one page/module should look different from `docs/design.md` | "Style change requests" below | | Building or changing a screen | `build.md`, then `verify.md` | -| Asked only to review or check UI | `verify.md`, then `design-review.md` | +| Asked only to review or check UI | `verify.md`, then `design-review.md` and `code-review.md` | | No scripted way to start the app and drive its journeys | `/shared/ctl.md` | -| The change also touches endpoints, jobs or schema | the `building-reliable-backend` skill for the api lane; both lanes must pass | +| The change also touches endpoints, jobs or schema | the `backend` skill for the backend lane; both lanes must pass | | A review found a Blocker, a change was reverted, or the user corrected you | `/shared/ratchet.md`: make it a check | -| Project still has `.ui-verify/` (0.1) | `node /scripts/run-verify.mjs --migrate`, then follow what it prints | ## Style change requests @@ -74,8 +73,8 @@ A tool missing: say which, continue with this skill's own checks, never pretend ## Done means `run-verify.mjs` printed `pass` for every lane the change touched, on the content now on disk; -`.verify/review-ui.md` (written by a fresh reviewer from the `review-brief.mjs` brief, with -`design-review.md`) names that same tree, has no open line, marks every acceptance id from +`.verify/review-frontend.md` (written by a fresh reviewer from the `review-brief.mjs` brief, with +`design-review.md` and `code-review.md`) names that same tree, has no open line, marks every acceptance id from `.verify/acceptance.md` and every triggered checklist item, and says `Verdict: approved`; `make-evidence.mjs` wrote the evidence pack after it, for the same tree; and your final message starts with the evidence path and the merge tier, then lists the follow-ups, the criteria not checked and what could not be checked. diff --git a/plugins/workflow/skills/building-consistent-ui/build.md b/plugins/dx-workflow/skills/frontend/build.md similarity index 100% rename from plugins/workflow/skills/building-consistent-ui/build.md rename to plugins/dx-workflow/skills/frontend/build.md diff --git a/plugins/dx-workflow/skills/frontend/code-review.md b/plugins/dx-workflow/skills/frontend/code-review.md new file mode 100644 index 0000000..a624b4d --- /dev/null +++ b/plugins/dx-workflow/skills/frontend/code-review.md @@ -0,0 +1,52 @@ +# Code review: the frontend change's code + +`design-review.md` judges what the user sees. This judges what the screenshots cannot show: state +that goes stale, requests that race, errors that vanish, content that becomes markup, a control a +keyboard cannot reach. Do it in the same review, after the screenshots; its findings go into the +same `## Findings` list of `.verify/review-frontend.md` (or `review-.md`), tagged with the lens. +Fix nothing. + +## 1. Read + +- The diff from the base ref (the brief gives the command, and lists new files the diff does not show). +- `.verify/acceptance.md`: for each criterion the screenshots cannot prove (a request sent once, a + retry, input kept after an error), find the test or journey that does, and open it. A criterion + proved only by a screenshot of the happy state is at most "met (seen, not exercised)". +- The negative check in `.verify/last-run.json` when the lane runs one: changed tests must fail + without the change. +- The backend contract (OpenAPI, GraphQL schema, generated client) when the change calls the API. + +## 2. Lenses + +Run each lens whose subject is in the diff; list the others once as "not applicable". Cite +`file:line`. + +| Lens | Look for | +| --- | --- | +| State | state that copies props or server data and goes stale; values derived in an effect instead of during render; effects with missing or wrong dependencies; stale closures in handlers, timers and subscriptions; state set after unmount; two sources of truth for one value (URL and component state, cache and local copy) | +| Data and requests | loading, empty and error states all handled for every request in the diff; out-of-order responses (a slow earlier request overwriting a later one: abort it or ignore it); a mutation sendable twice (button not disabled while pending, no idempotency key where the backend takes one); cache not invalidated or updated after a mutation; optimistic updates without rollback; pagination or filters lost on navigation | +| Forms and input | server errors not shown next to the field or not at all; input lost after a failed submit; validation only on the client for a rule the server also enforces differently; submit on Enter missing or doubled | +| Security | user or server content rendered as HTML (`dangerouslySetInnerHTML`, `v-html`, `innerHTML`) without sanitising; tokens or personal data in `localStorage` or logs; secrets in the client bundle (any env var with a public prefix such as `NEXT_PUBLIC_`, `VITE_`, `EXPO_PUBLIC_` that is not meant to be public); redirects to a URL taken from the query string; authorisation decided only by hiding a button | +| Accessibility in code | clickable `div`/`span` without role, focus and key handling; inputs without a label; focus not moved into a dialog or back after it closes; route changes that leave focus behind; async status (saved, failed) not announced (`aria-live`); images without `alt`, decorative ones without empty `alt` | +| Performance | list items without stable keys (index keys on lists that reorder); heavy work in render; long lists without virtualisation; a whole library imported for one function; images without size, causing layout shift | +| Contract with the backend | hand-written types that drift from the contract; a new error code or status not handled; fields assumed present that the contract marks optional; a request shape the contract does not accept | +| Tests | tests that assert implementation details (internal state, call counts on mocks of the module under test) instead of what the user sees; mocked network that returns shapes the real API does not; a criterion with no test; a test deleted, skipped or loosened | +| Standards | breaches of `docs/design.md`'s code rules and the repo's conventions (cite the rule); then only clear smells | + +Name the one fact the riskiest part depends on ("the request is aborted when the filter changes", +"the button is disabled while the mutation is pending") and prove it: run the test, drive it with +`ctl` or the journey, or throttle the network in the browser and watch. Say whether you proved it, +pointed at the line, or only believe it. + +## 3. Severity + +Same scale as `design-review.md`. A Blocker here is a wrong result the user can hit: data shown for +the wrong item, a double charge or double submit, content injected as markup, a lost input, a flow a +keyboard or screen reader cannot finish, a criterion not met. Every finding names the concrete +failure (the steps or input → what goes wrong); drop what you cannot tie to one. A problem in code +this change did not touch is `Pre-existing`. + +Add under `## Safety fact` in the review: ` · `. + +Adapted from the backend `code-review.md` in this plugin, gstack's `/review` (Garry Tan, MIT) and +mattpocock/skills `code-review` (MIT). diff --git a/plugins/workflow/skills/building-consistent-ui/design-review.md b/plugins/dx-workflow/skills/frontend/design-review.md similarity index 91% rename from plugins/workflow/skills/building-consistent-ui/design-review.md rename to plugins/dx-workflow/skills/frontend/design-review.md index 24c0ec0..1897e31 100644 --- a/plugins/workflow/skills/building-consistent-ui/design-review.md +++ b/plugins/dx-workflow/skills/frontend/design-review.md @@ -2,7 +2,9 @@ The question is not "does it render" but "would a design lead put their name on this, and does it look like the rest of this product?" Review the screenshots from the last run, against -`docs/design.md`. Report findings and a verdict; fix only after the review is written. +`docs/design.md`. Then review the code with `code-review.md` (state, requests, security, +accessibility in code): the screenshots cannot show those. Report findings and a verdict; fix only +after the review is written. ## 1. Scope and intent @@ -15,7 +17,7 @@ it look like the rest of this product?" Review the screenshots from the last run - Intent: read `docs/design.md` (direction, page patterns, what may vary). You judge against the product's own decisions, not a generic ideal. A dense back-office table is not failing for being dense. -- Evidence: the run folder named in `.verify/last-run.json` (`lanes.ui.runDir`). Approval needs a 390 and +- Evidence: the run folder named in `.verify/last-run.json` (`lanes.frontend.runDir`). Approval needs a 390 and a 1280 screenshot of every page in scope. Check each image's real pixel width first: a file whose width differs from its name, or a framework overlay in the shot, means the capture setup is wrong; fix it (setup.md, step 6.3) and rerun before judging layout. @@ -75,12 +77,12 @@ Drop false positives: If you cannot say how a finding costs the user or makes the screen look generated, it is taste. A few high-conviction findings beat a long list. -## 5. Write `.verify/review-ui.md` +## 5. Write `.verify/review-frontend.md` ```markdown # Review Reviewer: -Tree: +Tree: Scope: Focal point: : ; … @@ -95,6 +97,7 @@ Focal point: : ; … ## Findings - [ ] Blocker · · : → → +- [ ] Blocker · · : → → - [ ] Should-fix · … - [-] Should-fix · … (follow-up, deferred: ) - Pre-existing · · @@ -104,6 +107,11 @@ Focal point: : ; … ## Consistency - Group at 390: : +## Safety fact + · + +Code lenses not applicable: + Baselines updated: Not checked: Verdict: diff --git a/plugins/workflow/skills/building-consistent-ui/setup.md b/plugins/dx-workflow/skills/frontend/setup.md similarity index 95% rename from plugins/workflow/skills/building-consistent-ui/setup.md rename to plugins/dx-workflow/skills/frontend/setup.md index ae699e4..ced15ba 100644 --- a/plugins/workflow/skills/building-consistent-ui/setup.md +++ b/plugins/dx-workflow/skills/frontend/setup.md @@ -51,7 +51,7 @@ states, tables, navigation). Copy the numbers into design.md's UX rules. Ignore 1. Copy `/templates/design.md` to `docs/design.md` and fill every section. Map the dealt palette onto the token roles; put the values in the token file, not in design.md. 2. Add one line to `CLAUDE.md` (create it if missing; also `AGENTS.md` if the project has one): - "Before any UI work read docs/design.md and use the building-consistent-ui skill." + "Before any UI work read docs/design.md and use the frontend skill." 3. Optional, recommended when the user is not a designer: import the token file with baoyu-design's `claude-design-system` (from a code repository) into a sibling folder such as `../-designs/`, never inside the repo. The user tunes @@ -78,8 +78,9 @@ states, tables, navigation). Copy the numbers into design.md's UX rules. Ignore at a fixture module in the repo (`src/fixtures/.ts`). List any clock, random or live value under `mask` in `ui-pages.json`. 5. Copy `/shared/verify.config.json` to `.verify/config.json` (or, when it exists because the - api lane is set up, add its `ui` lane). Delete the `api` lane until the backend is set up with the - building-reliable-backend skill. Set the ui lane's `files` to the web app's UI source, `tokens` to + backend lane is set up, add its `frontend` lane; several apps get one lane each, e.g. `web` and + `admin`, with `"kind": "frontend"`). Delete the `backend` lane until the backend is set up with the + backend skill. Set the frontend lane's `files` to the web app's UI source, `tokens` to the token file (`docs/design.md` is always included), and `shared` to the folders of parts many pages use; the merge tier reads both. Fill each check with the project's real command. Optional checks the project may want: property tests for pure helpers such as money or date formatting, and diff --git a/plugins/workflow/skills/building-consistent-ui/templates/design.md b/plugins/dx-workflow/skills/frontend/templates/design.md similarity index 100% rename from plugins/workflow/skills/building-consistent-ui/templates/design.md rename to plugins/dx-workflow/skills/frontend/templates/design.md diff --git a/plugins/workflow/skills/building-consistent-ui/templates/ui-look.e2e.ts b/plugins/dx-workflow/skills/frontend/templates/ui-look.e2e.ts similarity index 93% rename from plugins/workflow/skills/building-consistent-ui/templates/ui-look.e2e.ts rename to plugins/dx-workflow/skills/frontend/templates/ui-look.e2e.ts index 5570a6e..15dce4f 100644 --- a/plugins/workflow/skills/building-consistent-ui/templates/ui-look.e2e.ts +++ b/plugins/dx-workflow/skills/frontend/templates/ui-look.e2e.ts @@ -12,7 +12,7 @@ interface UiPage { const pages: UiPage[] = JSON.parse(readFileSync(join(process.cwd(), "e2e", "ui-look", "ui-pages.json"), "utf8")); const widths = [390, 768, 1280]; -const evidenceDir = process.env.VERIFY_RUN_DIR ?? process.env.UI_VERIFY_RUN_DIR ?? "test-results/ui-look"; +const evidenceDir = process.env.VERIFY_RUN_DIR ?? "test-results/ui-look"; for (const uiPage of pages) { for (const width of widths) { diff --git a/plugins/workflow/skills/building-consistent-ui/templates/ui-pages.json b/plugins/dx-workflow/skills/frontend/templates/ui-pages.json similarity index 100% rename from plugins/workflow/skills/building-consistent-ui/templates/ui-pages.json rename to plugins/dx-workflow/skills/frontend/templates/ui-pages.json diff --git a/plugins/workflow/skills/building-consistent-ui/verify.md b/plugins/dx-workflow/skills/frontend/verify.md similarity index 93% rename from plugins/workflow/skills/building-consistent-ui/verify.md rename to plugins/dx-workflow/skills/frontend/verify.md index ed347b1..c67f79b 100644 --- a/plugins/workflow/skills/building-consistent-ui/verify.md +++ b/plugins/dx-workflow/skills/frontend/verify.md @@ -2,9 +2,9 @@ ## Run the checks -`node /scripts/run-verify.mjs --lane ui` runs the ui lane's checks in `.verify/config.json` +`node /scripts/run-verify.mjs --lane frontend` runs the frontend lane's checks in `.verify/config.json` (without `--lane`, every lane) and records the result from real exit codes. Logs and screenshots land -in the printed run folder. When the change also touched the api lane, both lanes must pass. +in the printed run folder. When the change also touched the backend lane, both lanes must pass. | Check | Passes when | | --- | --- | @@ -28,7 +28,7 @@ baseline once they agree. Then run `run-verify.mjs` in full. The agent that built the change does not review it. Write the brief with ```bash -node /scripts/review-brief.mjs --lane ui --request "" \ +node /scripts/review-brief.mjs --lane frontend --request "" \ --scope "" \ --baselines "" ``` @@ -37,7 +37,7 @@ and dispatch a fresh subagent (a different model when one is available) with exa and nothing about how the change was made. The brief names the tree under review, sets the depth, lists the `docs/checklist.md` items the diff triggers, and from the second round on gives the reviewer the previous findings and only the diff since then. Put deferred Should-fixes, one per line -with the reason, in `.verify/deferred-ui.md` before writing the brief. +with the reason, in `.verify/deferred-frontend.md` before writing the brief. Then: @@ -52,10 +52,10 @@ Then: 5. After an approved review, go through `/shared/ratchet.md` for every Blocker: a visual mistake that a script could catch (a raw colour, a missing state page, a clipped label) becomes a check, not a reminder. -6. No subagent tool here: review it yourself with `design-review.md` and write +6. No subagent tool here: review it yourself with `design-review.md` and `code-review.md` and write "Reviewer: same agent, no independent review available" under the title, and tell the user. -The Stop gate blocks your first attempt to stop until the run and `.verify/review-ui.md` both name +The Stop gate blocks your first attempt to stop until the run and `.verify/review-frontend.md` both name the tree now on disk (a content hash, not file times), the review has no open `- [ ]` line, accounts for every acceptance id, and says `Verdict: approved`. It lets the second attempt through so a turn cannot loop forever; ending that way means your final message must say the UI is not verified. diff --git a/test/evals.test.mjs b/test/evals.test.mjs index c621163..600a3ee 100644 --- a/test/evals.test.mjs +++ b/test/evals.test.mjs @@ -23,7 +23,7 @@ describe("reviewer evals", () => { const bug = prepare("idor-order-lookup"); dirs.push(dirname(bug.root)); const c = loadCase("idor-order-lookup"); - const review = (line) => writeFileSync(join(bug.root, ".verify/review-api.md"), `# Review\nTree: abcdef1234567\n\n## Findings\n${line}\n\nVerdict: changes required\n`); + const review = (line) => writeFileSync(join(bug.root, ".verify/review-backend.md"), `# Review\nTree: abcdef1234567\n\n## Findings\n${line}\n\nVerdict: changes required\n`); review("- [ ] Blocker · src/routes.mjs:6 · Auth: orders.get is not scoped to req.user, so another customer's order is returned → GET /orders/2 as c1 → filter by customerId"); assert.deepEqual({ found: score(bug.root, c).found, severity: score(bug.root, c).severity }, { found: true, severity: "Blocker" }); review("- [ ] Should-fix · src/routes.mjs:1 · security could be better"); @@ -31,7 +31,7 @@ describe("reviewer evals", () => { const clean = prepare("clean-rename-with-tests"); dirs.push(dirname(clean.root)); - writeFileSync(join(clean.root, ".verify/review-api.md"), "# Review\nTree: abcdef1234567\n\n## Findings\n- [ ] Blocker · src/total.mjs:1 · rename breaks callers\n\nVerdict: changes required\n"); + writeFileSync(join(clean.root, ".verify/review-backend.md"), "# Review\nTree: abcdef1234567\n\n## Findings\n- [ ] Blocker · src/total.mjs:1 · rename breaks callers\n\nVerdict: changes required\n"); const s = score(clean.root, loadCase("clean-rename-with-tests")); assert.equal(s.falsePositives, 1); assert.equal(s.approved, false); diff --git a/test/helpers.mjs b/test/helpers.mjs index 76e03fe..9526d98 100644 --- a/test/helpers.mjs +++ b/test/helpers.mjs @@ -1,12 +1,12 @@ // Fixture projects for the script tests: a bare "origin" with a main branch, and a clone on a -// feature branch. The project has one api lane whose unit test is a plain node script. +// feature branch. The project has one backend lane whose unit test is a plain node script. import { execFileSync, spawnSync } from "node:child_process"; import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; -export const SCRIPTS = resolve(dirname(fileURLToPath(import.meta.url)), "../plugins/workflow/scripts"); +export const SCRIPTS = resolve(dirname(fileURLToPath(import.meta.url)), "../plugins/dx-workflow/scripts"); const GIT_ENV = { GIT_AUTHOR_NAME: "test", @@ -19,7 +19,7 @@ const GIT_ENV = { export const CONFIG = { lanes: { - api: { + backend: { files: ["src/**", "test/**"], checks: [ { name: "unit", run: "node test/run.mjs" }, @@ -79,7 +79,7 @@ export function node(script, args = [], { cwd, input, env = {} } = {}) { cwd, input: input === undefined ? "" : typeof input === "string" ? input : JSON.stringify(input), encoding: "utf8", - env: { ...process.env, ...GIT_ENV, VERIFY_BASE: "", UI_WORKFLOW_GATE: "", ...env }, + env: { ...process.env, ...GIT_ENV, VERIFY_BASE: "", DX_WORKFLOW_GATE: "", ...env }, }); return { code: r.status, stdout: r.stdout, stderr: r.stderr }; } @@ -105,10 +105,10 @@ export function verify(root, { runArgs = [], reviewTree } = {}) { const last = JSON.parse(read(root, ".verify/last-run.json")); write(root, { ".verify/acceptance.md": "# Acceptance: sub\n## Criteria\n- A1 sub(5, 3) returns 2 · proof: test/run.mjs\n", - ".verify/review-api.md": [ - `# Review ${last.lanes.api.runDir}`, + ".verify/review-backend.md": [ + `# Review ${last.lanes.backend.runDir}`, "Reviewer: test", - `Tree: ${reviewTree ?? last.lanes.api.tree}`, + `Tree: ${reviewTree ?? last.lanes.backend.tree}`, "", "## Acceptance", "- [x] A1 met · test/run.mjs passed", diff --git a/test/make-evidence.test.mjs b/test/make-evidence.test.mjs index fb83fbe..e463b48 100644 --- a/test/make-evidence.test.mjs +++ b/test/make-evidence.test.mjs @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { rmSync } from "node:fs"; import { join } from "node:path"; import { after, describe, it } from "node:test"; -import { treeHash } from "../plugins/workflow/scripts/lib/verify-config.mjs"; +import { treeHash } from "../plugins/dx-workflow/scripts/lib/verify-config.mjs"; import { addFeature, cleanup, CONFIG, evidenceText, git, makeProject, node, read, tierOf, verify, write } from "./helpers.mjs"; const roots = []; @@ -23,7 +23,7 @@ describe("make-evidence merge tier", () => { }); it("counts commits already pushed on the branch as part of the change", () => { - const root = project({ config: { ...CONFIG, lanes: { api: { ...CONFIG.lanes.api, contract: ["openapi.yaml"] } } }, files: { "openapi.yaml": "v1\n" } }); + const root = project({ config: { ...CONFIG, lanes: { backend: { ...CONFIG.lanes.backend, contract: ["openapi.yaml"] } } }, files: { "openapi.yaml": "v1\n" } }); addFeature(root); write(root, { "openapi.yaml": "v2\n" }); git(root, "add", "-A"); @@ -65,7 +65,7 @@ describe("make-evidence merge tier", () => { addFeature(root); verify(root, { reviewTree: "0123456789ab" }); assert.equal(tierOf(root), "not ready"); - assert.match(evidenceText(root), /verified a different tree than the one on disk \(review api\)/); + assert.match(evidenceText(root), /verified a different tree than the one on disk \(review backend\)/); }); it("prints a PR body with the check changes and the tree", () => { diff --git a/test/review-brief.test.mjs b/test/review-brief.test.mjs index 4d8eecc..f2ba8ec 100644 --- a/test/review-brief.test.mjs +++ b/test/review-brief.test.mjs @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { existsSync } from "node:fs"; import { join } from "node:path"; import { after, describe, it } from "node:test"; -import { matchChecklist, parseChecklist } from "../plugins/workflow/scripts/lib/checklist.mjs"; +import { matchChecklist, parseChecklist } from "../plugins/dx-workflow/scripts/lib/checklist.mjs"; import { addFeature, cleanup, CONFIG, gate, makeProject, node, read, verify, write } from "./helpers.mjs"; const roots = []; @@ -12,13 +12,13 @@ const project = (opts) => { return r; }; after(() => roots.forEach(cleanup)); -const brief = (root, extra = []) => node("review-brief.mjs", ["--lane", "api", "--request", "add sub", ...extra], { cwd: root }); +const brief = (root, extra = []) => node("review-brief.mjs", ["--lane", "backend", "--request", "add sub", ...extra], { cwd: root }); const CHECKLIST = `# Reliability checklist ## C1 Subtraction never goes negative for money - when: diff \`/\\bsub\\b/\` or path \`src/money/**\` -- lanes: api +- lanes: backend - check: sub(1, 2) on amounts returns an error, not -1. - source: incident 2026-09-01 @@ -37,17 +37,17 @@ describe("checklist", () => { assert.deepEqual(items.map((i) => i.id), ["C1", "C2", "C3"]); assert.deepEqual(items[0].paths, ["src/money/**"]); assert.equal(items[0].patterns.length, 1); - assert.deepEqual(items[0].lanes, ["api"]); + assert.deepEqual(items[0].lanes, ["backend"]); assert.match(items[2].errors.join(), /unreadable trigger/); }); it("matches by changed path or changed line, and by lane", () => { const items = parseChecklist(CHECKLIST); const hit = (paths, lines, lane) => matchChecklist(items, { paths, lines, lane }).map((i) => i.id); - assert.deepEqual(hit(["src/session/a.ts"], [], "api"), ["C2"]); - assert.deepEqual(hit(["src/x.ts"], ["+export const sub = 1"], "api"), ["C1"]); - assert.deepEqual(hit(["src/x.ts"], ["+export const sub = 1"], "ui"), []); - assert.deepEqual(hit(["src/x.ts"], ["+subtle"], "api"), []); + assert.deepEqual(hit(["src/session/a.ts"], [], "backend"), ["C2"]); + assert.deepEqual(hit(["src/x.ts"], ["+export const sub = 1"], "backend"), ["C1"]); + assert.deepEqual(hit(["src/x.ts"], ["+export const sub = 1"], "frontend"), []); + assert.deepEqual(hit(["src/x.ts"], ["+subtle"], "backend"), []); }); }); @@ -69,13 +69,24 @@ describe("review-brief", () => { assert.match(r.stdout, /- C1 Subtraction never goes negative/); assert.doesNotMatch(r.stdout, /C2 Sessions/); assert.match(r.stdout, /C3: unreadable trigger/); - assert.match(r.stdout, /building-reliable-backend\/code-review\.md/); + assert.match(r.stdout, /backend\/code-review\.md/); assert.doesNotMatch(r.stdout, //); - assert.ok(existsSync(join(root, ".verify/brief-api.md"))); + assert.ok(existsSync(join(root, ".verify/brief-backend.md"))); + }); + + it("gives a frontend lane both the design review and the frontend code review", () => { + const root = project({ config: { lanes: { web: { kind: "frontend", files: ["src/**", "test/**"], checks: [{ name: "unit", run: "node test/run.mjs" }] } } } }); + addFeature(root); + node("run-verify.mjs", [], { cwd: root }); + const r = node("review-brief.mjs", ["--lane", "web", "--request", "add sub", "--scope", "home at 390"], { cwd: root }); + assert.equal(r.code, 0, r.stderr); + assert.match(r.stdout, /skills\/frontend\/design-review\.md for the screenshots, then .*skills\/frontend\/code-review\.md for the code/); + assert.match(r.stdout, /docs\/design\.md/); + assert.match(r.stdout, /Scope: home at 390/); }); it("goes deep on sensitive paths and asks to disprove Blockers", () => { - const root = project({ config: { ...CONFIG, lanes: { api: { ...CONFIG.lanes.api, sensitive: ["src/math.mjs"] } } } }); + const root = project({ config: { ...CONFIG, lanes: { backend: { ...CONFIG.lanes.backend, sensitive: ["src/math.mjs"] } } } }); addFeature(root); node("run-verify.mjs", [], { cwd: root }); const r = brief(root); @@ -106,13 +117,13 @@ describe("review-brief", () => { assert.match(r.stdout, /- \[ \] Blocker · src\/math\.mjs:1 · wrong/); } const last = JSON.parse(read(root, ".verify/last-run.json")); - write(root, { ".verify/review-api.md": `# Review\nTree: ${last.lanes.api.tree}\n\n## Findings\n- [ ] Blocker · src/math.mjs:1 · wrong\n\nVerdict: changes required\n` }); + write(root, { ".verify/review-backend.md": `# Review\nTree: ${last.lanes.backend.tree}\n\n## Findings\n- [ ] Blocker · src/math.mjs:1 · wrong\n\nVerdict: changes required\n` }); } write(root, { "src/math.mjs": read(root, "src/math.mjs") + "// round 4\n" }); node("run-verify.mjs", [], { cwd: root }); const r4 = brief(root); assert.equal(r4.code, 3); - assert.match(r4.stderr, /3 review rounds of lane api ended without approval/); + assert.match(r4.stderr, /3 review rounds of lane backend ended without approval/); }); it("restarts the round count for a new change (new acceptance)", () => { @@ -122,7 +133,7 @@ describe("review-brief", () => { node("run-verify.mjs", [], { cwd: root }); brief(root); const last = JSON.parse(read(root, ".verify/last-run.json")); - write(root, { ".verify/review-api.md": `Tree: ${last.lanes.api.tree}\nVerdict: changes required\n`, "src/math.mjs": read(root, "src/math.mjs") + "//x\n" }); + write(root, { ".verify/review-backend.md": `Tree: ${last.lanes.backend.tree}\nVerdict: changes required\n`, "src/math.mjs": read(root, "src/math.mjs") + "//x\n" }); node("run-verify.mjs", [], { cwd: root }); assert.match(brief(root).stdout, /round 2/); write(root, { ".verify/acceptance.md": "- A1 another change\n", "src/math.mjs": read(root, "src/math.mjs") + "//y\n" }); @@ -136,7 +147,7 @@ describe("pre-existing findings", () => { const root = project(); addFeature(root); verify(root); - write(root, { ".verify/review-api.md": read(root, ".verify/review-api.md").replace("- Note · none", "- Pre-existing · src/db.mjs:3 · unbounded query") }); + write(root, { ".verify/review-backend.md": read(root, ".verify/review-backend.md").replace("- Note · none", "- Pre-existing · src/db.mjs:3 · unbounded query") }); node("make-evidence.mjs", [], { cwd: root }); assert.equal(gate(root), null); }); diff --git a/test/run-verify.test.mjs b/test/run-verify.test.mjs index 6dfd804..9f967b8 100644 --- a/test/run-verify.test.mjs +++ b/test/run-verify.test.mjs @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import { existsSync } from "node:fs"; import { join } from "node:path"; import { after, describe, it } from "node:test"; -import { treeHash } from "../plugins/workflow/scripts/lib/verify-config.mjs"; +import { treeHash } from "../plugins/dx-workflow/scripts/lib/verify-config.mjs"; import { addFeature, cleanup, makeProject, node, read, write } from "./helpers.mjs"; const roots = []; @@ -21,16 +21,16 @@ describe("run-verify", () => { const r = node("run-verify.mjs", [], { cwd: root }); assert.equal(r.code, 0, r.stdout + r.stderr); const last = lastRun(root); - assert.equal(last.lanes.api.result, "pass"); - assert.equal(last.lanes.api.tree, treeHash(root)); + assert.equal(last.lanes.backend.result, "pass"); + assert.equal(last.lanes.backend.tree, treeHash(root)); assert.equal(last.config.source, "base"); - assert.match(last.lanes.api.checks.find((c) => c.name === "negative").note, /tests failed without the change/); + assert.match(last.lanes.backend.checks.find((c) => c.name === "negative").note, /tests failed without the change/); }); it("runs the base's checks when the change removes them from the working config", () => { const root = project(); write(root, { - ".verify/config.json": JSON.stringify({ lanes: { api: { files: ["src/**"], checks: [{ name: "unit", run: "node -e 0" }] } } }), + ".verify/config.json": JSON.stringify({ lanes: { backend: { files: ["src/**"], checks: [{ name: "unit", run: "node -e 0" }] } } }), "src/math.mjs": "export const add = (a, b) => a - b;\n", }); const r = node("run-verify.mjs", [], { cwd: root }); @@ -43,12 +43,12 @@ describe("run-verify", () => { it("fails a run whose checks wrote to the source", () => { const root = project({ - config: { lanes: { api: { files: ["src/**"], checks: [{ name: "format", run: "node -e \"require('fs').appendFileSync('src/math.mjs', '\\n')\"" }] } } }, + config: { lanes: { backend: { files: ["src/**"], checks: [{ name: "format", run: "node -e \"require('fs').appendFileSync('src/math.mjs', '\\n')\"" }] } } }, }); const r = node("run-verify.mjs", [], { cwd: root }); assert.equal(r.code, 1); assert.match(r.stdout, /files changed while the checks ran/); - assert.equal(lastRun(root).lanes.api.result, "fail"); + assert.equal(lastRun(root).lanes.backend.result, "fail"); }); it("refuses to run while a crashed negative check left a backup, and restores it", () => { @@ -70,7 +70,7 @@ describe("negative check", () => { }); const r = node("run-verify.mjs", ["--only", "negative"], { cwd: root }); assert.equal(r.code, 1); - assert.match(lastRun(root).lanes.api.checks[0].note, /do not test it/); + assert.match(lastRun(root).lanes.backend.checks[0].note, /do not test it/); }); it("puts the source back after reverting it, binary files included", () => { @@ -87,7 +87,7 @@ describe("negative check", () => { const root = project(); write(root, { "src/math.mjs": "export const add = (a, b) => b + a;\n" }); node("run-verify.mjs", ["--only", "negative"], { cwd: root }); - assert.match(lastRun(root).lanes.api.checks[0].note, /no test changed/); + assert.match(lastRun(root).lanes.backend.checks[0].note, /no test changed/); }); }); diff --git a/test/stamp-ci.test.mjs b/test/stamp-ci.test.mjs index 6d02e29..218916a 100644 --- a/test/stamp-ci.test.mjs +++ b/test/stamp-ci.test.mjs @@ -15,13 +15,13 @@ const stamp = (root) => node("stamp.mjs", [], { cwd: root }).stdout.trim(); describe("run-verify fail-fast", () => { it("skips the rest of a lane after a failure, unless --keep-going", () => { - const root = project({ config: { lanes: { api: { files: ["src/**"], checks: [{ name: "a", run: "node -e process.exit(1)" }, { name: "b", run: "node -e 0" }] } } } }); + const root = project({ config: { lanes: { backend: { files: ["src/**"], checks: [{ name: "a", run: "node -e process.exit(1)" }, { name: "b", run: "node -e 0" }] } } } }); write(root, { "src/x.mjs": "1\n" }); node("run-verify.mjs", [], { cwd: root }); - let checks = JSON.parse(read(root, ".verify/last-run.json")).lanes.api.checks; + let checks = JSON.parse(read(root, ".verify/last-run.json")).lanes.backend.checks; assert.equal(checks[1].skipped, true); node("run-verify.mjs", ["--keep-going"], { cwd: root }); - checks = JSON.parse(read(root, ".verify/last-run.json")).lanes.api.checks; + checks = JSON.parse(read(root, ".verify/last-run.json")).lanes.backend.checks; assert.equal(checks[1].exitCode, 0); }); }); @@ -34,7 +34,7 @@ describe("commit stamp", () => { assert.equal(stamp(root), "Verified: none (no evidence pack)"); verify(root); git(root, "add", "-A"); - assert.match(stamp(root), /^Verified: tree=[0-9a-f]{12} tier=1 lanes=api:pass$/); + assert.match(stamp(root), /^Verified: tree=[0-9a-f]{12} tier=1 lanes=backend:pass$/); write(root, { "src/math.mjs": read(root, "src/math.mjs") + "// staged later\n" }); git(root, "add", "src/math.mjs"); assert.equal(stamp(root), "Verified: none (the commit differs from the verified content)"); @@ -54,14 +54,14 @@ describe("commit stamp", () => { git(root, "add", "-A"); git(root, "commit", "-q", "-m", "add sub", "-m", "Co-Authored-By: x "); const msg = git(root, "log", "-1", "--format=%B"); - assert.match(msg, /Co-Authored-By: x \nVerified: tree=[0-9a-f]{12} tier=1 lanes=api:pass/); + assert.match(msg, /Co-Authored-By: x \nVerified: tree=[0-9a-f]{12} tier=1 lanes=backend:pass/); assert.equal(node("stamp.mjs", ["--install"], { cwd: root }).code, 0, "second install is a no-op"); }); }); describe("make-evidence extras", () => { it("tier 3 for a sensitive path, with merge danger", () => { - const root = project({ config: { ...CONFIG, lanes: { api: { ...CONFIG.lanes.api, sensitive: ["src/math.mjs"] } } } }); + const root = project({ config: { ...CONFIG, lanes: { backend: { ...CONFIG.lanes.backend, sensitive: ["src/math.mjs"] } } } }); addFeature(root); verify(root); assert.equal(tierOf(root), "3"); @@ -73,7 +73,7 @@ describe("make-evidence extras", () => { }); it("one-way door for a migration, and the acceptance's own revert note", () => { - const root = project({ config: { ...CONFIG, lanes: { api: { ...CONFIG.lanes.api, files: ["src/**", "test/**", "migrations/**"], migrations: ["migrations/**"] } } } }); + const root = project({ config: { ...CONFIG, lanes: { backend: { ...CONFIG.lanes.backend, files: ["src/**", "test/**", "migrations/**"], migrations: ["migrations/**"] } } } }); addFeature(root); write(root, { "migrations/002.sql": "alter table t add column c int;\n" }); verify(root); diff --git a/test/stop-gate.test.mjs b/test/stop-gate.test.mjs index 95e505b..22bc26d 100644 --- a/test/stop-gate.test.mjs +++ b/test/stop-gate.test.mjs @@ -58,7 +58,7 @@ describe("stop gate", () => { addFeature(root); verify(root, { reviewTree: "0123456789ab" }); assert.match(gate(root).reason, /its review is of tree 0123456789ab/); - write(root, { ".verify/review-api.md": read(root, ".verify/review-api.md").replace(/^Tree:.*\n/m, "") }); + write(root, { ".verify/review-backend.md": read(root, ".verify/review-backend.md").replace(/^Tree:.*\n/m, "") }); assert.match(gate(root).reason, /has no "Tree:" line/); }); @@ -95,16 +95,16 @@ describe("stop gate", () => { it("only logs in observe mode, and does nothing when off", () => { const root = project(); addFeature(root); - assert.equal(gate(root, {}, { UI_WORKFLOW_GATE: "observe" }), null); + assert.equal(gate(root, {}, { DX_WORKFLOW_GATE: "observe" }), null); assert.equal(gateLog(root).at(-1).decision, "would-block"); - assert.equal(gate(root, {}, { UI_WORKFLOW_GATE: "off" }), null); + assert.equal(gate(root, {}, { DX_WORKFLOW_GATE: "off" }), null); assert.equal(gateLog(root).length, 1); }); it("does not accept a weakened working config as the lane definition", () => { const root = project(); addFeature(root); - write(root, { ".verify/config.json": JSON.stringify({ lanes: { api: { files: ["nothing/**"], checks: [] } } }) }); + write(root, { ".verify/config.json": JSON.stringify({ lanes: { backend: { files: ["nothing/**"], checks: [] } } }) }); assert.equal(gate(root).decision, "block"); }); }); diff --git a/test/verify-config.test.mjs b/test/verify-config.test.mjs index 1fcc29f..e986773 100644 --- a/test/verify-config.test.mjs +++ b/test/verify-config.test.mjs @@ -3,7 +3,7 @@ import { execFileSync } from "node:child_process"; import { rmSync } from "node:fs"; import { join } from "node:path"; import { after, describe, it } from "node:test"; -import { changedSince, globToRegExp, guardChanges, loadConfig, treeHash } from "../plugins/workflow/scripts/lib/verify-config.mjs"; +import { changedSince, globToRegExp, guardChanges, loadConfig, treeHash } from "../plugins/dx-workflow/scripts/lib/verify-config.mjs"; import { cleanup, CONFIG, git, makeProject, write } from "./helpers.mjs"; const roots = []; @@ -91,7 +91,7 @@ describe("treeHash and racy edits", () => { describe("loadConfig", () => { it("reads the base commit's config, and says when the working copy differs", () => { const root = project(); - write(root, { ".verify/config.json": JSON.stringify({ lanes: { api: { files: ["src/**"], checks: [] } } }) }); + write(root, { ".verify/config.json": JSON.stringify({ lanes: { backend: { files: ["src/**"], checks: [] } } }) }); const cfg = loadConfig(root); assert.equal(cfg.source, "base"); assert.equal(cfg.workingDiffers, true); @@ -109,7 +109,7 @@ describe("loadConfig", () => { git(root, "fetch", "-q", "origin"); const cfg = loadConfig(root); assert.equal(cfg.source, "working"); - assert.deepEqual(cfg.lanes.map((l) => l.name), ["api"]); + assert.deepEqual(cfg.lanes.map((l) => l.name), ["backend"]); }); }); @@ -125,7 +125,7 @@ describe("guardChanges", () => { it("flags the config, deleted tests and skipped tests as tier 3", () => { const root = project(); write(root, { - ".verify/config.json": JSON.stringify({ ...CONFIG, lanes: { api: { ...CONFIG.lanes.api, checks: [] } } }), + ".verify/config.json": JSON.stringify({ ...CONFIG, lanes: { backend: { ...CONFIG.lanes.backend, checks: [] } } }), "test/run.mjs": "it.skip('adds', () => {});\n", "playwright.config.ts": "export default {};\n", }); diff --git a/vendor.lock.json b/vendor.lock.json index ae35816..0af34fe 100644 --- a/vendor.lock.json +++ b/vendor.lock.json @@ -1,5 +1,5 @@ { - "note": "Third-party tools ui-workflow calls or adapted from. Upgrade one at a time: read its diff, rerun run-verify on two projects, then bump the commit here.", + "note": "Third-party tools dx-workflow calls or adapted from. Upgrade one at a time: read its diff, rerun run-verify on two projects, then bump the commit here.", "called": { "taste-skill": { "repo": "https://github.com/Leonxlnx/taste-skill", @@ -38,7 +38,7 @@ "commit": "4dd1d05818d19792e7cd6e818f1667f95f7e1dbe", "license": "MIT, Copyright (c) 2026 Lauren Tan", "into": [ - "skills/building-consistent-ui/verify.md", + "skills/frontend/verify.md", "shared/ctl.md (was functional-verify.md)" ] }, @@ -47,9 +47,9 @@ "commit": "4ae2317ddb22b046e26455e4f9c9b3aaaf62212d", "license": "MIT", "into": [ - "skills/building-consistent-ui/build.md", - "skills/building-reliable-backend/build.md (tdd)", - "skills/building-reliable-backend/code-review.md (two axes: acceptance and standards)" + "skills/frontend/build.md", + "skills/backend/build.md (tdd)", + "skills/backend/code-review.md (two axes: acceptance and standards)" ] }, "interface-design": { @@ -57,7 +57,7 @@ "commit": "2f9be3206855bcb2d1d0af262c8bae25cba6658d", "license": "MIT, Copyright (c) 2026 Damola Akinleye", "into": [ - "skills/building-consistent-ui/design-review.md" + "skills/frontend/design-review.md" ] }, "pstack-blast-radius": { @@ -65,7 +65,7 @@ "commit": "6b0300214a09fd6029cfb7077043125758cd1fd2", "license": "MIT, Copyright (c) 2026 Lauren Tan", "into": [ - "skills/building-reliable-backend/code-review.md (Safety fact)" + "skills/backend/code-review.md (Safety fact)" ] }, "gstack": { @@ -73,9 +73,9 @@ "commit": "de5cb247e0ce319a2f7725d589e5c952c6d7761e", "license": "MIT, Copyright (c) 2026 Garry Tan", "into": [ - "skills/building-reliable-backend/code-review.md (review checklist and specialists)", - "skills/building-reliable-backend/verify.md (reading red results, never weaken a check)", - "skills/building-reliable-backend/build.md (data-migration rules)" + "skills/backend/code-review.md (review checklist and specialists)", + "skills/backend/verify.md (reading red results, never weaken a check)", + "skills/backend/build.md (data-migration rules)" ] } } From 45ac72a43fdc203aba01f2ee3812348f5896e864 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 13:09:16 +1100 Subject: [PATCH 2/3] Frontend covers React Native / Expo - Lane "platform": "react-native": default files (app code, app.json, app.config, eas.json, ios/, android/, assets/) and "native" globs. - rn-look.mjs: screenshots on iOS simulators and Android emulators via one Maestro flow per device and variant (default, dark, large-text), fixed status bar, compared with baselines named --- .png so the evidence pack pairs them; diff images and report.md. --update, --dry-run, --compare-only. - lib/png.mjs: dependency-free PNG decode, compare with masks, diff image. - check-raw-styles --platform react-native: colour literals in *Color keys and props, font literals, --spacing-scale for padding/margin/gap. - Native changes (native globs, a new react-native-*/expo-* module in package.json) are merge tier 3, a one-way door, and a deep review. - run-verify: "ci": false skips a check in CI (simulators) without tripping fail-fast. - mobile.md (setup, build, verify, over-the-air updates), templates rn-look.json and maestro-journey.yaml, an RN lane in the config template, mobile adverse cases, design and code review lenses. - rn-look script and screens.json are guard files. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014d2MvQ5v7FCph37jwFCC7i --- README.md | 26 +- docs/adr/0005-dx-workflow-frontend-backend.md | 11 +- .../dx-workflow/.claude-plugin/plugin.json | 5 +- .../dx-workflow/scripts/check-raw-styles.mjs | 40 ++- plugins/dx-workflow/scripts/lib/png.mjs | 162 +++++++++++ .../dx-workflow/scripts/lib/verify-config.mjs | 14 +- plugins/dx-workflow/scripts/make-evidence.mjs | 15 + plugins/dx-workflow/scripts/review-brief.mjs | 2 + plugins/dx-workflow/scripts/rn-look.mjs | 207 ++++++++++++++ plugins/dx-workflow/scripts/run-verify.mjs | 7 +- plugins/dx-workflow/shared/acceptance.md | 10 + plugins/dx-workflow/shared/verify.config.json | 18 ++ plugins/dx-workflow/skills/frontend/SKILL.md | 5 +- plugins/dx-workflow/skills/frontend/build.md | 3 + .../skills/frontend/code-review.md | 1 + .../skills/frontend/design-review.md | 1 + plugins/dx-workflow/skills/frontend/mobile.md | 80 ++++++ plugins/dx-workflow/skills/frontend/setup.md | 3 + .../frontend/templates/maestro-journey.yaml | 19 ++ .../skills/frontend/templates/rn-look.json | 22 ++ plugins/dx-workflow/skills/frontend/verify.md | 4 + test/helpers.mjs | 8 +- test/mobile.test.mjs | 258 ++++++++++++++++++ 23 files changed, 899 insertions(+), 22 deletions(-) create mode 100644 plugins/dx-workflow/scripts/lib/png.mjs create mode 100644 plugins/dx-workflow/scripts/rn-look.mjs create mode 100644 plugins/dx-workflow/skills/frontend/mobile.md create mode 100644 plugins/dx-workflow/skills/frontend/templates/maestro-journey.yaml create mode 100644 plugins/dx-workflow/skills/frontend/templates/rn-look.json create mode 100644 test/mobile.test.mjs diff --git a/README.md b/README.md index 0ac4371..a376353 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ ## 整套流程 -前端(frontend:用户直接接触的客户端;目前支持 Web,React Native / Expo 移动端在下一个版本)和后端(backend)走同一套流程,只是每一步用的约定、检查和评审方式不同。 +前端(frontend:用户直接接触的客户端,Web 和 React Native / Expo 移动端)和后端(backend)走同一套流程,只是每一步用的约定、检查和评审方式不同。 项目里每一个客户端或服务叫一个 **lane**,一个仓库可以有多条,比如 `web`、`app`、`api`,各自标明 `kind` 是 `frontend` 还是 `backend`。 | 步骤 | 做什么 | frontend lane | backend lane | @@ -18,7 +18,7 @@ | 1 澄清 | 只在大改动时:先追问需求、边界、失败时怎么办 | 同左 | 同左 | | 2 验收标准 | 写 `.verify/acceptance.md`:可观察的结果,每条写明用什么证明;逐项过一遍异常情况清单;可选写明怎么回滚、能否撤回 | 无效输入、键盘、慢请求、双击提交、390 宽…… | 边界值、越权、重复请求、并发写、下游失败…… | | 3 实现 | 按约定做 | 需要时出 3 个结构不同的原型 | 先改契约,再按验收标准一条条先写测试后写实现 | -| 4 机器检查 | `run-verify.mjs` 按 lane 跑,只认真实退出码,遇到第一个失败就停 | 样式、类型、截图 + 可访问性、用户路径 | 类型、单元、真实数据库的集成测试、**负向检查**、契约、迁移、用户路径 | +| 4 机器检查 | `run-verify.mjs` 按 lane 跑,只认真实退出码,遇到第一个失败就停 | 样式、类型、截图 + 可访问性、用户路径(Web 用 Playwright;移动端用模拟器截图 `rn-look.mjs` 和 Maestro) | 类型、单元、真实数据库的集成测试、**负向检查**、契约、迁移、用户路径 | | 5 独立评审 | `review-brief.mjs` 写 brief,交给没参与实现的子代理;逐条标记验收标准和触发的清单项;最多 3 轮 | `design-review.md` 看截图,再用前端版 `code-review.md` 看代码(状态、请求竞态、错误态、XSS、可访问性) | `code-review.md` 看 diff,按专项逐一检查,并跑一遍证明关键事实 | | 6 证据和分档 | `make-evidence.mjs` 生成证据包:验收标准和机器检查分开写,算合并分档,写明能否撤回、影响范围、怎么回滚 | 前后对比截图、录屏 | 检查日志、负向检查结果、契约与迁移改动 | | 7 沉淀 | 评审的 Blocker、回滚、你的纠正,按 `shared/ratchet.md` 变成检查或清单项 | 同左 | 同左 | @@ -26,6 +26,20 @@ 改动大小决定流程轻重:改文案、改颜色这类小改动不用追问,验收标准写 1 到 3 条,评审走 quick; 新流程、接口或数据契约变更、迁移、鉴权才走完整流程,评审走 deep。 +**移动端(React Native / Expo)**:lane 写 `"kind": "frontend", "platform": "react-native"`,默认覆盖全部 JS/TS 代码和 +`app.json`、`ios/`、`android/` 等原生配置。和 Web 的区别: + +- 截图用 `rn-look.mjs`:在 iOS 模拟器和 Android 模拟器上,用 Maestro 按深链接打开每个页面,固定状态栏, + 分默认、暗色、大字号三种各截一张,和基线逐像素比较(内置 PNG 比较,不需要依赖),差异图和报告进证据包; +- 样式检查加 `--platform react-native`:样式和属性里写死的颜色、字号字体、不在间距刻度上的数值; +- 用户路径用 Maestro flow(用 testID 定位); +- 原生改动(`app.json`、`ios/`、`android/`、`package.json` 新增原生模块)只能随新的商店版本发出,旧版本用户会一直用旧原生代码, + 所以固定 3 档、标为不可撤回,评审走 deep; +- 验收标准和评审多一组移动端情况:大字号、最小机型、暗色、断网、切后台、权限被拒、Android 返回键、键盘遮挡、读屏、旧版本 App。 +- 模拟器在 CI 里需要 macOS 或模拟器 runner;跑不了的检查标 `"ci": false`,只在本地跑,CI 里记为未运行。 + +详见 `skills/frontend/mobile.md`。 + **负向检查**:把这条 lane 里的源码改动退回到基线、保留新测试,再跑一遍测试,测试必须失败。 测试在没有实现时也能通过,说明它没测到这次改动。 @@ -37,7 +51,7 @@ | --- | --- | --- | | 1 | 检查全过、评审通过、验收标准全部满足,且没有下面的情况 | 扫一眼证据包即可合并 | | 2 | 改了截图基线或共享模块(`shared`);有验收标准"未验证";改了源码却没改测试;代码里新增了 `@ts-ignore`、`eslint-disable`、`noqa` 这类关掉检查的注释,或者加了重试 | 你要看前后对比和标出来的部分 | -| 3 | 改了设计约定、后端约定、接口契约或迁移;改了 `sensitive` 路径;**改了检查本身**(见下) | 你确认之后才能合并 | +| 3 | 改了设计约定、后端约定、接口契约或迁移;改了 `sensitive` 路径;移动端的原生改动;**改了检查本身**(见下) | 你确认之后才能合并 | | 未就绪 | 检查失败、评审未通过、有验收标准未满足或没被评审;运行或评审对应的不是当前磁盘上的内容 | 不合并 | 证据包和 PR 描述里还有一节"合并风险":能否撤回(有迁移是单向的,改了接口契约对已接入的调用方也是单向的)、 @@ -158,7 +172,7 @@ baoyu-design 是可选的看图调色工具,只在项目仓库外用(它含 | 路径 | 作用 | | --- | --- | -| `plugins/dx-workflow/skills/frontend/` | 前端:`SKILL.md`(入口)、`setup.md`、`build.md`、`verify.md`、`design-review.md`(截图评审)、`code-review.md`(前端代码评审)、`templates/`(design.md、截图测试、页面清单) | +| `plugins/dx-workflow/skills/frontend/` | 前端:`SKILL.md`(入口)、`setup.md`、`build.md`、`verify.md`、`mobile.md`(React Native / Expo)、`design-review.md`(截图评审)、`code-review.md`(前端代码评审)、`templates/`(design.md、Web 截图测试、页面清单、`rn-look.json`、Maestro journey) | | `plugins/dx-workflow/skills/backend/` | 后端:`SKILL.md`(入口)、`setup.md`、`build.md`、`verify.md`、`code-review.md`(代码评审)、`templates/backend.md` | | `plugins/dx-workflow/shared/acceptance.md` | 怎么写验收标准、异常情况清单、评审怎么标记 | | `plugins/dx-workflow/shared/ctl.md` | 生成项目的控制命令(读写分开),以及 `verify-` skill 和用户路径 | @@ -177,7 +191,9 @@ baoyu-design 是可选的看图调色工具,只在项目仓库外用(它含 | `plugins/dx-workflow/scripts/stop-gate.mjs` | Stop 钩子 | | `plugins/dx-workflow/scripts/turn-start.mjs` | UserPromptSubmit 钩子:记录这一轮开始时的内容哈希和插件位置 | | `plugins/dx-workflow/scripts/stamp.mjs` | 提交盖章;`--install` 装 git 钩子 | -| `plugins/dx-workflow/scripts/check-raw-styles.mjs` | 找出写死的颜色、Tailwind 色板类、任意值 | +| `plugins/dx-workflow/scripts/check-raw-styles.mjs` | 找出写死的颜色、Tailwind 色板类、任意值;`--platform react-native` 加查 RN 样式 | +| `plugins/dx-workflow/scripts/rn-look.mjs` | 移动端截图:模拟器 + Maestro,按设备和默认/暗色/大字号比较基线 | +| `plugins/dx-workflow/scripts/lib/png.mjs` | 无依赖的 PNG 解码、比较和差异图 | | `plugins/dx-workflow/scripts/find-tools.mjs` | 找到已安装的 taste-skill、ui-ux-pro-max、baoyu-design | | `plugins/dx-workflow/scripts/lib/verify-config.mjs` | 读配置(从基线提交)、算改动范围和内容哈希、找出"改了检查本身"的改动 | | `plugins/dx-workflow/scripts/lib/checklist.mjs` | 解析 `docs/checklist.md`,按 diff 选出触发的条目 | diff --git a/docs/adr/0005-dx-workflow-frontend-backend.md b/docs/adr/0005-dx-workflow-frontend-backend.md index d859b3f..e1b3aa6 100644 --- a/docs/adr/0005-dx-workflow-frontend-backend.md +++ b/docs/adr/0005-dx-workflow-frontend-backend.md @@ -21,11 +21,18 @@ end includes mobile clients. - The frontend review is the design review plus a frontend `code-review.md` (state, requests and races, forms, security, accessibility in code, performance, the backend contract, tests), in one review file. +- Mobile is frontend: a lane with `"platform": "react-native"` (React Native, Expo) gets default + files, `rn-look.mjs` screenshots (simulators through Maestro; default, dark and large-text + variants; a dependency-free PNG diff), a React Native mode of `check-raw-styles.mjs`, Maestro + journeys, mobile review lenses and adverse cases. Native changes (`native` globs, or a new native + module in `package.json`) are merge tier 3 and a one-way door, because they ship only in a store + build. Checks that need a simulator can be `"ci": false`. - No compatibility with earlier names: the 0.1 `.ui-verify/` migration, `UI_VERIFY_RUN_DIR` and the upgrade notes are gone. The Stop gate variable is `DX_WORKFLOW_GATE`. ## Consequences Projects set up before this rename key their config by `ui`/`api` and must rename lanes or add -`kind`. Mobile (React Native / Expo) support is the next change: platform defaults for lane files, -token checks, screenshots, journeys and review lenses. +`kind`. Only React Native / Expo is covered among mobile stacks; native iOS, Android and Flutter +would each need their own defaults, screenshot tool and lenses. `rn-look.mjs` is tested with +recorded screenshots and a dry run, not against a live simulator in CI. diff --git a/plugins/dx-workflow/.claude-plugin/plugin.json b/plugins/dx-workflow/.claude-plugin/plugin.json index ad2b25b..6429bad 100644 --- a/plugins/dx-workflow/.claude-plugin/plugin.json +++ b/plugins/dx-workflow/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "dx-workflow", "version": "0.5.0", - "description": "Front-end and back-end changes you can trust: acceptance criteria first, a design contract and a backend contract, checks per lane (frontend, backend) including a negative check, independent review, an evidence pack with a computed merge tier, and a Stop gate. Checks are read from the base commit, runs and reviews are bound to a content hash, and changes to the checks themselves are tier 3.", + "description": "Front-end and back-end changes you can trust: acceptance criteria first, a design contract and a backend contract, checks per lane (frontend on the web or React Native / Expo, backend) including a negative check, independent review, an evidence pack with a computed merge tier, and a Stop gate. Checks are read from the base commit, runs and reviews are bound to a content hash, and changes to the checks themselves are tier 3.", "author": { "name": "davidxiaodev" }, @@ -14,6 +14,9 @@ "acceptance", "code-review", "playwright", + "react-native", + "expo", + "maestro", "tokens", "migrations" ] diff --git a/plugins/dx-workflow/scripts/check-raw-styles.mjs b/plugins/dx-workflow/scripts/check-raw-styles.mjs index 08142fe..5edbd10 100644 --- a/plugins/dx-workflow/scripts/check-raw-styles.mjs +++ b/plugins/dx-workflow/scripts/check-raw-styles.mjs @@ -3,9 +3,16 @@ // arbitrary values (p-[13px], bg-[#fff]) and literal colours in style objects. // // node check-raw-styles.mjs ... [--tokens ]... [--allow ]... [--json] +// [--platform web|react-native] [--spacing-scale 0,4,8,12,16,24,32] +// +// --platform react-native (React Native, Expo; NativeWind classes are checked as on the web) adds: +// colour literals in any *Color / color style key or prop (StyleSheet and JSX: color="#fff", +// placeholderTextColor="gray"), and fontSize / fontFamily / lineHeight literals. --spacing-scale also +// flags padding, margin and gap numbers that are not on the scale. // // Token files (where raw values belong) are skipped: globals.css, variables.css, tailwind.config.*, -// plus every --tokens path. Exit 0 = clean, 1 = findings, 2 = usage error. +// theme / tokens / colors / typography / spacing .ts|.js|.json, plus every --tokens path. +// Exit 0 = clean, 1 = findings, 2 = usage error. import { readdirSync, readFileSync, statSync } from "node:fs"; import { extname, join, relative, resolve, basename } from "node:path"; @@ -14,23 +21,28 @@ const roots = []; const tokens = []; const allow = []; let asJson = false; +let platform = "web"; +let spacingScale = null; for (let i = 0; i < args.length; i++) { const a = args[i]; if (a === "--tokens") tokens.push(resolve(args[++i] ?? "")); else if (a === "--allow") allow.push(args[++i] ?? ""); else if (a === "--json") asJson = true; + else if (a === "--platform") platform = args[++i] ?? ""; + else if (a === "--spacing-scale") spacingScale = new Set((args[++i] ?? "").split(",").map((n) => Number(n.trim()))); else if (a === "-h" || a === "--help") usage(0); else roots.push(a); } -if (roots.length === 0) usage(2); +if (roots.length === 0 || !["web", "react-native"].includes(platform)) usage(2); const EXTS = new Set([".tsx", ".jsx", ".ts", ".js", ".vue", ".svelte", ".html", ".css", ".scss"]); const SKIP_DIRS = new Set(["node_modules", ".git", ".next", "dist", "build", "out", ".turbo", "coverage", ".expo", "ios", "android"]); -const TOKEN_NAMES = [/^globals\.css$/, /^variables\.css$/, /^tailwind\.config\.[cm]?[jt]s$/, /^tokens?\.(css|json|ts)$/]; +const TOKEN_NAMES = [/^globals\.css$/, /^variables\.css$/, /^tailwind\.config\.[cm]?[jt]s$/, /^(?:tokens?|theme|colou?rs|typography|spacing)\.(?:css|json|[cm]?[jt]s)$/]; +const NAMED = "white|black|red|green|blue|yellow|orange|purple|pink|gray|grey|silver|navy|teal|maroon|olive|lime|aqua|fuchsia"; const PALETTE = "slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose"; const UTIL = "bg|text|border|ring|fill|stroke|from|to|via|outline|decoration|shadow|divide|placeholder|accent|caret"; -const RULES = [ +const WEB_RULES = [ { id: "palette-class", re: new RegExp(`(? or theme.text.body); one-off sizes break the type scale and Dynamic Type.", + }, +]; +const SPACING = /\b(?:padding|margin)(?:Top|Bottom|Left|Right|Horizontal|Vertical|Start|End)?\s*:\s*(-?\d+(?:\.\d+)?)\b|\b(?:gap|rowGap|columnGap)\s*:\s*(\d+(?:\.\d+)?)\b/g; + +const RULES = platform === "react-native" ? [...WEB_RULES.filter((r) => r.id !== "literal-colour"), ...RN_RULES] : WEB_RULES; +if (spacingScale) RULES.push({ id: "off-scale-spacing", re: SPACING, fix: `Use the spacing scale (${[...spacingScale].join(", ")}) or a theme spacing value.` }); + const findings = []; for (const r of roots) walk(resolve(r)); @@ -97,6 +126,7 @@ function walk(p) { for (const m of text.matchAll(rule.re)) { if (text[m.index + m[0].length] === ":") continue; if (rule.id === "arbitrary-value" && isAllowedArbitrary(m[0])) continue; + if (rule.id === "off-scale-spacing" && spacingScale.has(Math.abs(Number(m[1] ?? m[2])))) continue; findings.push({ rule: rule.id, file: rel, line: i + 1, match: m[0] }); } } @@ -117,6 +147,6 @@ function isAllowedArbitrary(token) { } function usage(code) { - console.error("usage: node check-raw-styles.mjs ... [--tokens ]... [--allow ]... [--json]"); + console.error("usage: node check-raw-styles.mjs ... [--tokens ]... [--allow ]... [--json] [--platform web|react-native] [--spacing-scale 0,4,8,…]"); process.exit(code); } diff --git a/plugins/dx-workflow/scripts/lib/png.mjs b/plugins/dx-workflow/scripts/lib/png.mjs new file mode 100644 index 0000000..0e78ec7 --- /dev/null +++ b/plugins/dx-workflow/scripts/lib/png.mjs @@ -0,0 +1,162 @@ +// Just enough PNG to compare screenshots without dependencies: decode 8-bit, non-interlaced images +// (greyscale, RGB, palette, with or without alpha), compare two of them, and write a diff image. +import { deflateSync, inflateSync } from "node:zlib"; + +const SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]); + +/** Decodes a PNG into { width, height, data } with data as RGBA bytes. */ +export function decodePng(buf) { + if (!buf.subarray(0, 8).equals(SIGNATURE)) throw new Error("not a PNG"); + let pos = 8; + let width = 0; + let height = 0; + let depth = 0; + let type = 0; + let interlace = 0; + let palette = null; + let trns = null; + const idat = []; + while (pos < buf.length) { + const len = buf.readUInt32BE(pos); + const kind = buf.toString("latin1", pos + 4, pos + 8); + const body = buf.subarray(pos + 8, pos + 8 + len); + pos += 12 + len; + if (kind === "IHDR") { + width = body.readUInt32BE(0); + height = body.readUInt32BE(4); + depth = body[8]; + type = body[9]; + interlace = body[12]; + } else if (kind === "PLTE") palette = body; + else if (kind === "tRNS") trns = body; + else if (kind === "IDAT") idat.push(body); + else if (kind === "IEND") break; + } + if (depth !== 8) throw new Error(`PNG bit depth ${depth} is not supported (8 only)`); + if (interlace) throw new Error("interlaced PNG is not supported"); + const channels = { 0: 1, 2: 3, 3: 1, 4: 2, 6: 4 }[type]; + if (!channels) throw new Error(`PNG colour type ${type} is not supported`); + const raw = inflateSync(Buffer.concat(idat)); + const stride = width * channels; + const pixels = Buffer.alloc(stride * height); + for (let y = 0; y < height; y++) { + const filter = raw[y * (stride + 1)]; + const line = raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1)); + const out = pixels.subarray(y * stride, (y + 1) * stride); + const prev = y ? pixels.subarray((y - 1) * stride, y * stride) : null; + for (let x = 0; x < stride; x++) { + const a = x >= channels ? out[x - channels] : 0; + const b = prev ? prev[x] : 0; + const c = prev && x >= channels ? prev[x - channels] : 0; + let v = line[x]; + if (filter === 1) v += a; + else if (filter === 2) v += b; + else if (filter === 3) v += (a + b) >> 1; + else if (filter === 4) { + const p = a + b - c; + const pa = Math.abs(p - a); + const pb = Math.abs(p - b); + const pc = Math.abs(p - c); + v += pa <= pb && pa <= pc ? a : pb <= pc ? b : c; + } else if (filter !== 0) throw new Error(`bad PNG filter ${filter}`); + out[x] = v & 255; + } + } + const data = Buffer.alloc(width * height * 4); + for (let i = 0; i < width * height; i++) { + const s = i * channels; + const d = i * 4; + if (type === 6) pixels.copy(data, d, s, s + 4); + else if (type === 2) { + data[d] = pixels[s]; + data[d + 1] = pixels[s + 1]; + data[d + 2] = pixels[s + 2]; + data[d + 3] = 255; + } else if (type === 0 || type === 4) { + data[d] = data[d + 1] = data[d + 2] = pixels[s]; + data[d + 3] = type === 4 ? pixels[s + 1] : 255; + } else { + const idx = pixels[s]; + data[d] = palette[idx * 3]; + data[d + 1] = palette[idx * 3 + 1]; + data[d + 2] = palette[idx * 3 + 2]; + data[d + 3] = trns && idx < trns.length ? trns[idx] : 255; + } + } + return { width, height, data }; +} + +/** Encodes RGBA bytes as a PNG. */ +export function encodePng({ width, height, data }) { + const stride = width * 4; + const raw = Buffer.alloc((stride + 1) * height); + for (let y = 0; y < height; y++) data.copy(raw, y * (stride + 1) + 1, y * stride, (y + 1) * stride); + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(width, 0); + ihdr.writeUInt32BE(height, 4); + ihdr[8] = 8; + ihdr[9] = 6; + return Buffer.concat([SIGNATURE, chunk("IHDR", ihdr), chunk("IDAT", deflateSync(raw)), chunk("IEND", Buffer.alloc(0))]); +} + +/** + * Compares two decoded images. A pixel differs when any channel differs by more than `threshold` + * (0–255). `mask` is a list of [x, y, w, h] rectangles as fractions of the image (0–1) to ignore, + * such as a clock. Returns { sameSize, diffPixels, ratio, diff } where diff is an RGBA image: the + * expected image faded, differing pixels in red, masked areas in blue. + */ +export function comparePng(expected, actual, { threshold = 16, mask = [] } = {}) { + if (expected.width !== actual.width || expected.height !== actual.height) { + return { sameSize: false, diffPixels: null, ratio: 1, diff: null }; + } + const { width, height } = expected; + const rects = mask.map(([x, y, w, h]) => [Math.floor(x * width), Math.floor(y * height), Math.ceil((x + w) * width), Math.ceil((y + h) * height)]); + const diff = Buffer.alloc(width * height * 4); + let diffPixels = 0; + let counted = 0; + for (let y = 0; y < height; y++) { + for (let x = 0; x < width; x++) { + const i = (y * width + x) * 4; + if (rects.some(([x0, y0, x1, y1]) => x >= x0 && x < x1 && y >= y0 && y < y1)) { + diff.set([80, 120, 255, 255], i); + continue; + } + counted++; + const d = Math.max( + Math.abs(expected.data[i] - actual.data[i]), + Math.abs(expected.data[i + 1] - actual.data[i + 1]), + Math.abs(expected.data[i + 2] - actual.data[i + 2]), + Math.abs(expected.data[i + 3] - actual.data[i + 3]), + ); + if (d > threshold) { + diffPixels++; + diff.set([255, 0, 0, 255], i); + } else { + const g = 255 - Math.round((255 - (expected.data[i] * 0.3 + expected.data[i + 1] * 0.59 + expected.data[i + 2] * 0.11)) * 0.25); + diff.set([g, g, g, 255], i); + } + } + } + return { sameSize: true, diffPixels, ratio: counted ? diffPixels / counted : 0, diff: { width, height, data: diff } }; +} + +function chunk(kind, body) { + const len = Buffer.alloc(4); + len.writeUInt32BE(body.length); + const head = Buffer.from(kind, "latin1"); + const crc = Buffer.alloc(4); + crc.writeUInt32BE(crc32(Buffer.concat([head, body])) >>> 0); + return Buffer.concat([len, head, body, crc]); +} + +const CRC_TABLE = Array.from({ length: 256 }, (_, n) => { + let c = n; + for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; + return c >>> 0; +}); + +function crc32(buf) { + let c = 0xffffffff; + for (const b of buf) c = CRC_TABLE[(c ^ b) & 255] ^ (c >>> 8); + return c ^ 0xffffffff; +} diff --git a/plugins/dx-workflow/scripts/lib/verify-config.mjs b/plugins/dx-workflow/scripts/lib/verify-config.mjs index b2156b5..69399f3 100644 --- a/plugins/dx-workflow/scripts/lib/verify-config.mjs +++ b/plugins/dx-workflow/scripts/lib/verify-config.mjs @@ -10,6 +10,9 @@ export const VERIFY_DIR = ".verify"; // Paths a lane ignores unless its config says otherwise: test code and verification output. const FRONTEND_FILES = ["**/*.{tsx,jsx,vue,svelte,html,css,scss}"]; +// React Native / Expo: all app code is UI code, and native config ships with the store build. +const RN_FILES = ["**/*.{ts,tsx,js,jsx}", "app.json", "app.config.{js,ts}", "eas.json", "ios/**", "android/**", "assets/**"]; +const RN_NATIVE = ["app.json", "app.config.{js,ts}", "eas.json", "ios/**", "android/**"]; const FRONTEND_IGNORE = [ "**/e2e/**", "**/test/**", @@ -50,12 +53,16 @@ export function loadConfig(root, { source = "base", base } = {}) { const config = JSON.parse(text); const lanes = Object.entries(config.lanes ?? {}).map(([name, lane]) => { const kind = lane.kind ?? name; + const platform = kind === "frontend" ? (lane.platform ?? "web") : null; + const rn = platform === "react-native"; return { ...lane, name, kind, - files: lane.files ?? (kind === "frontend" ? FRONTEND_FILES : []), - ignore: [...(lane.ignore ?? (kind === "frontend" ? FRONTEND_IGNORE : [])), `${VERIFY_DIR}/**`], + platform, + files: lane.files ?? (kind === "frontend" ? (rn ? RN_FILES : FRONTEND_FILES) : []), + ignore: [...(lane.ignore ?? (kind === "frontend" ? [...FRONTEND_IGNORE, ...(rn ? ["**/.maestro/**", "**/node_modules/**"] : [])] : [])), `${VERIFY_DIR}/**`], + native: lane.native ?? (rn ? RN_NATIVE : []), checks: lane.checks ?? [], }; }); @@ -235,6 +242,9 @@ export const DEFAULT_GUARD = [ "**/conftest.py", "**/.golangci.y*ml", "**/scripts/ui/check-raw-styles.mjs", + "**/scripts/ui/rn-look.mjs", + "**/scripts/ui/lib/png.mjs", + "**/e2e/rn-look/screens.json", "**/e2e/ui-look/**/*.{ts,js,json}", ]; diff --git a/plugins/dx-workflow/scripts/make-evidence.mjs b/plugins/dx-workflow/scripts/make-evidence.mjs index 78f0c61..0d44cf2 100644 --- a/plugins/dx-workflow/scripts/make-evidence.mjs +++ b/plugins/dx-workflow/scripts/make-evidence.mjs @@ -25,6 +25,7 @@ import { acceptanceLines, changedSince, contractPaths, + gitLines, guardChanges, inLane, loadConfig, @@ -97,6 +98,16 @@ const contractChanges = touched.filter((f) => lanes.some((l) => isUnder(f, contr const baselineChanges = touched.filter((f) => /-snapshots\/.+\.png$/.test(f)); const sharedChanges = touched.filter((f) => lanes.some((l) => isUnder(f, l.shared ?? []))); const sensitiveChanges = touched.filter((f) => lanes.some((l) => isUnder(f, l.sensitive ?? []))); +// Native changes of a React Native / Expo app ship only in a new store build: native config and +// folders (lane "native"), and a package.json that gains a native module. +const nativeChanges = touched.filter((f) => lanes.some((l) => isUnder(f, l.native ?? []))); +if (lanes.some((l) => l.platform === "react-native")) { + for (const f of touched.filter((t) => /(^|\/)package\.json$/.test(t) && !nativeChanges.includes(t))) { + const added = gitLines(root, ["diff", "--unified=0", cfg.base ?? "HEAD", "--", f]).filter((l) => /^\+\s*"(?:react-native-|@react-native|expo-|@expo\/)[^"]*"\s*:/.test(l)); + const untracked = !added.length && !gitLines(root, ["ls-files", "--", f]).length && /"(?:react-native-|@react-native|expo-|@expo\/)[^"]*"\s*:/.test(readFileSync(join(root, f), "utf8")); + if (added.length || untracked) nativeChanges.push(`${f} (native dependency: ${added.map((l) => l.match(/"([^"]+)"/)[1]).join(", ") || "new file"})`); + } +} const negativeSkips = lanes.flatMap((l) => (last.lanes[l.name]?.checks ?? []).filter((c) => /no test changed/.test(c.note ?? "")).map((c) => `${l.name}/${c.name}`)); const notChecked = criteria.filter((c) => c.status === "not checked").map((c) => c.id); @@ -118,6 +129,7 @@ const why2 = [ const why3 = [ contractChanges.length && "a contract changed (design, API, data or migrations)", sensitiveChanges.length && `a sensitive path changed (${sensitiveChanges.join(", ")})`, + nativeChanges.length && `a native change needs a new store build (${nativeChanges.join(", ")})`, guard3.length && `the checks themselves changed (${[...new Set(guard3.map((g) => `${g.path}: ${g.why}`))].join("; ")})`, ].filter(Boolean); const notReady = [ @@ -145,11 +157,14 @@ const field = (name) => { }; const door = migrationChanges.length ? `one-way: a migration changes stored data (${migrationChanges.join(", ")})` + : nativeChanges.length + ? "one-way: a native change ships only in a new store build, and users keep the old build until they update; JavaScript sent over the air must keep working with both" : apiContractChanges.length ? `one-way for callers already using the new contract (${apiContractChanges.join(", ")})` : field("Door") ?? "two-way: reverting the commit restores the previous behaviour"; const reach = [ sensitiveChanges.length && `sensitive paths (${sensitiveChanges.length})`, + nativeChanges.length && `native code or config (${nativeChanges.length})`, contractChanges.length && `contracts (${contractChanges.length})`, sharedChanges.length && `shared parts (${sharedChanges.length})`, guarded.length && `the checks (${guarded.length})`, diff --git a/plugins/dx-workflow/scripts/review-brief.mjs b/plugins/dx-workflow/scripts/review-brief.mjs index 18b86bb..ccffc0d 100644 --- a/plugins/dx-workflow/scripts/review-brief.mjs +++ b/plugins/dx-workflow/scripts/review-brief.mjs @@ -63,9 +63,11 @@ const guarded = guardChanges(cfg, changedSince(root, cfg.base)); const contract = changes.filter((c) => matchAny(contractPaths(lane), c.path)).map((c) => c.path); const sensitive = changes.filter((c) => matchAny(lane.sensitive ?? [], c.path)).map((c) => c.path); const shared = changes.filter((c) => matchAny(lane.shared ?? [], c.path)).map((c) => c.path); +const native = changes.filter((c) => matchAny(lane.native ?? [], c.path)).map((c) => c.path); const reasons3 = [ contract.length && `contract: ${contract.join(", ")}`, sensitive.length && `sensitive: ${sensitive.join(", ")}`, + native.length && `native (needs a store build): ${native.join(", ")}`, guarded.some((g) => g.tier === 3) && `checks changed: ${guarded.filter((g) => g.tier === 3).map((g) => g.path).join(", ")}`, ].filter(Boolean); const depth = reasons3.length || size > 400 ? "deep" : size <= 30 && !shared.length ? "quick" : "standard"; diff --git a/plugins/dx-workflow/scripts/rn-look.mjs b/plugins/dx-workflow/scripts/rn-look.mjs new file mode 100644 index 0000000..ab7937b --- /dev/null +++ b/plugins/dx-workflow/scripts/rn-look.mjs @@ -0,0 +1,207 @@ +#!/usr/bin/env node +// Screenshots of a React Native / Expo app on simulators and emulators, compared with baselines. +// The mobile counterpart of the web look check (Playwright toHaveScreenshot). +// +// node rn-look.mjs [--config e2e/rn-look/screens.json] [--platform ios|android] [--update] +// [--dry-run] [--compare-only] [--out ] +// +// For each device and variant (default, dark, large-text) it fixes the status bar, sets the +// appearance and text size, opens every screen by deep link with one Maestro flow, takes a +// screenshot, and compares it with e2e/rn-look/look-snapshots/---.png. +// Screenshots, diff images and report.md go to $VERIFY_RUN_DIR/rn-look// (or test-results/rn-look). +// +// --update accept the new screenshots as baselines (review them first; a baseline change is merge tier 2) +// --dry-run print the commands and files it would use, run nothing +// --compare-only skip capturing; compare screenshots already in the output folder +// +// Exit 0 = every screen matches, 1 = differences or missing baselines, 2 = setup error. +// Needs: maestro on PATH; for iOS, Xcode (xcrun simctl); for Android, adb with the emulator running. +// The app must already be installed on the devices (a development build; `install` in the config +// runs a command per platform first). +import { spawnSync } from "node:child_process"; +import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname, join, relative, resolve } from "node:path"; +import { comparePng, decodePng, encodePng } from "./lib/png.mjs"; + +const args = process.argv.slice(2); +const opt = (name) => { + const i = args.indexOf(`--${name}`); + return i === -1 ? undefined : args[i + 1]; +}; +const flag = (name) => args.includes(`--${name}`); + +const configPath = resolve(opt("config") ?? "e2e/rn-look/screens.json"); +if (!existsSync(configPath)) fail(`rn-look: no ${configPath}. Copy the plugin's skills/frontend/templates/rn-look.json there and fill it in.`); +const config = JSON.parse(readFileSync(configPath, "utf8")); +const baselines = resolve(config.baselines ?? "e2e/rn-look/look-snapshots"); // relative to where the check runs +const outDir = resolve(opt("out") ?? (process.env.VERIFY_RUN_DIR ? join(process.env.VERIFY_RUN_DIR, "rn-look") : "test-results/rn-look")); +const variants = config.variants ?? ["default", "dark", "large-text"]; +const onlyPlatform = opt("platform"); +const devices = (config.devices ?? []).filter((d) => !onlyPlatform || d.platform === onlyPlatform); +const dry = flag("dry-run"); +const threshold = config.threshold ?? 16; +const maxDiffRatio = config.maxDiffRatio ?? 0.001; + +for (const k of ["appId", "screens"]) if (!config[k]) fail(`rn-look: ${configPath} needs "${k}".`); +if (!devices.length) fail("rn-look: no devices (devices: [{ platform, name or serial, width }])."); +for (const d of devices) { + if (!["ios", "android"].includes(d.platform)) fail(`rn-look: device platform must be ios or android, not ${d.platform}.`); + if (!d.width) fail(`rn-look: device ${d.name ?? d.serial} needs "width" (the screen width in points or dp, used in file names).`); +} + +const shots = []; +for (const device of devices) { + for (const variant of variants) { + for (const screen of config.screens) { + const name = `${screen.name}-${variant}-${device.platform}-${device.width}`; + shots.push({ device, variant, screen, name, file: join(outDir, screen.group ?? "screens", `${name}.png`), baseline: join(baselines, `${name}.png`) }); + } + } +} + +if (!flag("compare-only")) capture(); +if (dry) { + for (const s of shots) console.log(`would compare ${rel(s.file)} with ${rel(s.baseline)}`); + process.exit(0); +} +process.exit(compare()); + +function capture() { + const run = (cmd, argv, { ignoreFail = false } = {}) => { + console.log(`$ ${[cmd, ...argv].map(q).join(" ")}`); + if (dry) return ""; + const r = spawnSync(cmd, argv, { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }); + if (r.error) fail(`rn-look: cannot run ${cmd} (${r.error.code}); is it installed and on PATH?`); + if (r.status !== 0 && !ignoreFail) fail(`rn-look: ${cmd} ${argv.join(" ")} failed:\n${r.stderr || r.stdout}`); + return r.stdout; + }; + for (const platform of ["ios", "android"]) { + if (config.install?.[platform] && devices.some((d) => d.platform === platform)) run("sh", ["-c", config.install[platform]]); + } + for (const device of devices) { + const id = device.platform === "ios" ? iosDevice(device, run) : device.serial ?? "emulator-5554"; + statusBar(device.platform, id, run); + for (const variant of variants) { + setVariant(device.platform, id, variant, run); + const mine = shots.filter((s) => s.device === device && s.variant === variant); + for (const s of mine) mkdirSync(dirname(s.file), { recursive: true }); + const flow = join(outDir, "flows", `${device.platform}-${device.width}-${variant}.yaml`); + mkdirSync(dirname(flow), { recursive: true }); + writeFileSync(flow, flowYaml(mine)); + run("maestro", ["--device", id, "test", flow]); + } + setVariant(device.platform, id, "default", run); + } +} + +function flowYaml(list) { + const lines = [`appId: ${config.appId}`, "---", "- launchApp"]; + for (const s of list) { + lines.push(`- openLink: ${JSON.stringify(s.screen.link)}`); + if (s.screen.waitFor) lines.push("- extendedWaitUntil:", ` visible: ${JSON.stringify(s.screen.waitFor)}`, ` timeout: ${config.timeoutMs ?? 20000}`); + lines.push("- waitForAnimationToEnd", `- takeScreenshot: ${JSON.stringify(s.file.replace(/\.png$/, ""))}`); + } + return lines.join("\n") + "\n"; +} + +function iosDevice(device, run) { + if (device.udid) return device.udid; + if (dry) return ``; + const list = JSON.parse(run("xcrun", ["simctl", "list", "devices", "available", "-j"])); + const all = Object.values(list.devices).flat(); + const found = all.find((d) => d.name === device.name); + if (!found) fail(`rn-look: no available simulator named "${device.name}". xcrun simctl list devices available`); + run("xcrun", ["simctl", "boot", found.udid], { ignoreFail: true }); + run("xcrun", ["simctl", "bootstatus", found.udid, "-b"]); + return found.udid; +} + +function statusBar(platform, id, run) { + if (platform === "ios") { + run("xcrun", ["simctl", "status_bar", id, "override", "--time", "9:41", "--batteryState", "charged", "--batteryLevel", "100", "--wifiBars", "3", "--cellularBars", "4"]); + return; + } + const demo = (...extra) => run("adb", ["-s", id, "shell", "am", "broadcast", "-a", "com.android.systemui.demo", ...extra]); + run("adb", ["-s", id, "shell", "settings", "put", "global", "sysui_demo_allowed", "1"]); + demo("-e", "command", "enter"); + demo("-e", "command", "clock", "-e", "hhmm", "0941"); + demo("-e", "command", "battery", "-e", "level", "100", "-e", "plugged", "false"); + demo("-e", "command", "network", "-e", "wifi", "show", "-e", "level", "4"); + demo("-e", "command", "notifications", "-e", "visible", "false"); +} + +function setVariant(platform, id, variant, run) { + const dark = variant === "dark"; + const large = variant === "large-text"; + if (platform === "ios") { + run("xcrun", ["simctl", "ui", id, "appearance", dark ? "dark" : "light"]); + run("xcrun", ["simctl", "ui", id, "content_size", large ? "accessibility-extra-large" : "large"]); + } else { + run("adb", ["-s", id, "shell", "cmd", "uimode", "night", dark ? "yes" : "no"]); + run("adb", ["-s", id, "shell", "settings", "put", "system", "font_scale", large ? "1.5" : "1.0"]); + } +} + +function compare() { + const rows = []; + let failed = 0; + for (const s of shots) { + if (!existsSync(s.file)) { + rows.push({ s, result: "missing screenshot" }); + failed++; + continue; + } + if (flag("update")) { + mkdirSync(dirname(s.baseline), { recursive: true }); + copyFileSync(s.file, s.baseline); + rows.push({ s, result: "baseline updated" }); + continue; + } + if (!existsSync(s.baseline)) { + rows.push({ s, result: "no baseline (review the screenshot, then --update)" }); + failed++; + continue; + } + const c = comparePng(decodePng(readFileSync(s.baseline)), decodePng(readFileSync(s.file)), { threshold, mask: s.screen.mask ?? [] }); + if (!c.sameSize) { + rows.push({ s, result: "different size from the baseline" }); + failed++; + continue; + } + const ok = c.ratio <= (s.screen.maxDiffRatio ?? maxDiffRatio); + let diffFile = null; + if (!ok) { + diffFile = s.file.replace(/\.png$/, ".diff.png"); // not "-.png", so the evidence pack does not take it for a screen + writeFileSync(diffFile, encodePng(c.diff)); + failed++; + } + rows.push({ s, result: ok ? "match" : `differs: ${(c.ratio * 100).toFixed(3)}% of pixels`, diffFile }); + } + const report = [ + "# rn-look", + "", + "| Screen | Variant | Device | Result | Diff |", + "| --- | --- | --- | --- | --- |", + ...rows.map(({ s, result, diffFile }) => `| ${s.screen.name} | ${s.variant} | ${s.device.platform} ${s.device.name ?? s.device.serial ?? ""} (${s.device.width}) | ${result} | ${diffFile ? rel(diffFile) : ""} |`), + "", + ].join("\n"); + mkdirSync(outDir, { recursive: true }); + writeFileSync(join(outDir, "report.md"), report); + for (const { s, result } of rows) if (result !== "match") console.log(`rn-look: ${s.name}: ${result}`); + console.log(`rn-look: ${rows.length - failed}/${rows.length} match · ${rel(join(outDir, "report.md"))}`); + return failed ? 1 : 0; +} + +function rel(p) { + return relative(process.cwd(), p) || p; +} + +function q(s) { + return /^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, "'\\''")}'`; +} + +function fail(message) { + console.error(message); + process.exit(2); +} + diff --git a/plugins/dx-workflow/scripts/run-verify.mjs b/plugins/dx-workflow/scripts/run-verify.mjs index 9bcdaae..830152b 100644 --- a/plugins/dx-workflow/scripts/run-verify.mjs +++ b/plugins/dx-workflow/scripts/run-verify.mjs @@ -102,7 +102,12 @@ for (const lane of lanes) { const laneStarted = new Date().toISOString(); const results = []; for (const check of checks) { - if (!args.includes("--keep-going") && results.some((r) => r.exitCode !== 0)) { + if (process.env.CI && check.ci === false) { + console.log(`run-verify: ${lane.name}/${check.name} … skipped in CI ("ci": false; it needs a simulator, a device or a local service)`); + results.push({ name: check.name, run: check.run ?? "built-in negative check", exitCode: null, skipped: true, seconds: 0, log: null, note: 'not run in CI ("ci": false)' }); + continue; + } + if (!args.includes("--keep-going") && results.some((r) => r.exitCode !== 0 && !r.skipped)) { console.log(`run-verify: ${lane.name}/${check.name} … skipped (an earlier check failed; --keep-going runs it)`); results.push({ name: check.name, run: check.run ?? "built-in negative check", exitCode: null, skipped: true, seconds: 0, log: null, note: "skipped after an earlier failure" }); continue; diff --git a/plugins/dx-workflow/shared/acceptance.md b/plugins/dx-workflow/shared/acceptance.md index 258e596..10bb374 100644 --- a/plugins/dx-workflow/shared/acceptance.md +++ b/plugins/dx-workflow/shared/acceptance.md @@ -46,6 +46,16 @@ to prevent. - 390px wide; long words and translations; dark mode if the product has one - signed out, no permission, expired session +**Mobile (React Native / Expo)** + +- large system text size; smallest supported phone; dark mode +- offline or slow network: the failure is shown, retry works, input is kept +- backgrounded and resumed mid-flow; killed and reopened from a deep link or notification +- a permission denied (camera, location, notifications) +- Android back on every screen; the keyboard never covers the focused field +- VoiceOver / TalkBack can finish the flow +- an older app build still in use (over-the-air JavaScript, the API it calls) + **API and data** - boundaries: zero, one, maximum, just past maximum; empty and missing fields; wrong types diff --git a/plugins/dx-workflow/shared/verify.config.json b/plugins/dx-workflow/shared/verify.config.json index fa9a61d..52e753e 100644 --- a/plugins/dx-workflow/shared/verify.config.json +++ b/plugins/dx-workflow/shared/verify.config.json @@ -15,6 +15,24 @@ { "name": "inspect", "run": "node --out \"$VERIFY_RUN_DIR/inspect\" <--app for app screens>" } ] }, + "app": { + "kind": "frontend", + "platform": "react-native", + "files": ["/**/*.{ts,tsx,js,jsx}", "/app.json", "/app.config.{js,ts}", "/eas.json", "/ios/**", "/android/**", "/assets/**"], + "native": ["/app.json", "/app.config.{js,ts}", "/eas.json", "/ios/**", "/android/**"], + "tokens": [""], + "shared": [""], + "sensitive": [""], + "checks": [ + { "name": "raw-styles", "run": "node scripts/ui/check-raw-styles.mjs --platform react-native --spacing-scale <0,4,8,12,16,24,32>" }, + { "name": "types", "run": "npx tsc --noEmit", "cwd": "" }, + { "name": "lint", "run": "npx expo lint", "cwd": "" }, + { "name": "unit", "run": "npx jest --ci", "cwd": "" }, + { "name": "negative", "negative": { "test": "npx jest --ci" } }, + { "name": "functional", "run": "maestro test -e VERIFY_RUN_DIR=\"$VERIFY_RUN_DIR\" .maestro/journeys", "cwd": "", "timeoutMin": 30, "ci": false }, + { "name": "look", "run": "node scripts/ui/rn-look.mjs --config e2e/rn-look/screens.json", "cwd": "", "timeoutMin": 45, "ci": false } + ] + }, "backend": { "files": ["/**", "/**", ""], "contract": [""], diff --git a/plugins/dx-workflow/skills/frontend/SKILL.md b/plugins/dx-workflow/skills/frontend/SKILL.md index 685b0e6..9fe3bd4 100644 --- a/plugins/dx-workflow/skills/frontend/SKILL.md +++ b/plugins/dx-workflow/skills/frontend/SKILL.md @@ -1,9 +1,9 @@ --- name: frontend -description: Use when building, restyling or reviewing any user-facing screen, page, storefront, dashboard or component; when starting a project's design system or tokens; when a user says the UI looks generic, ugly, unprofessional or inconsistent, or asks for one page or module to look different from the rest. +description: Use when building, restyling or reviewing any user-facing screen, page, storefront, dashboard or component, on the web or in a React Native / Expo app; when starting a project's design system or tokens; when a user says the UI looks generic, ugly, unprofessional or inconsistent, or asks for one page or module to look different from the rest. --- -# Building consistent UI +# Frontend: consistent UI, on the web and on phones ## Overview @@ -18,6 +18,7 @@ Third-party design skills are tools this workflow calls; they never override the | Project state | Read | | --- | --- | | No `docs/design.md` | `setup.md`, then come back | +| The app is React Native or Expo (a lane with `"platform": "react-native"`) | `mobile.md` alongside every file below | | Any change | `/shared/acceptance.md` first: write `.verify/acceptance.md` | | Request: one page/module should look different from `docs/design.md` | "Style change requests" below | | Building or changing a screen | `build.md`, then `verify.md` | diff --git a/plugins/dx-workflow/skills/frontend/build.md b/plugins/dx-workflow/skills/frontend/build.md index 59e09c8..1c4c3d0 100644 --- a/plugins/dx-workflow/skills/frontend/build.md +++ b/plugins/dx-workflow/skills/frontend/build.md @@ -1,5 +1,8 @@ # Build: changing a screen +In a React Native / Expo app, also follow `mobile.md` "Build" (safe areas, keyboard, Android back, +large text, native changes) and its mobile adverse cases. + 0. No `.verify/acceptance.md` for this change yet: write it with `/shared/acceptance.md`, going through the UI adverse cases (invalid input, keyboard, slow and failed requests, double submit, 390px, no permission). Each criterion names its proof: a page and state in diff --git a/plugins/dx-workflow/skills/frontend/code-review.md b/plugins/dx-workflow/skills/frontend/code-review.md index a624b4d..0c282c3 100644 --- a/plugins/dx-workflow/skills/frontend/code-review.md +++ b/plugins/dx-workflow/skills/frontend/code-review.md @@ -30,6 +30,7 @@ Run each lens whose subject is in the diff; list the others once as "not applica | Accessibility in code | clickable `div`/`span` without role, focus and key handling; inputs without a label; focus not moved into a dialog or back after it closes; route changes that leave focus behind; async status (saved, failed) not announced (`aria-live`); images without `alt`, decorative ones without empty `alt` | | Performance | list items without stable keys (index keys on lists that reorder); heavy work in render; long lists without virtualisation; a whole library imported for one function; images without size, causing layout shift | | Contract with the backend | hand-written types that drift from the contract; a new error code or status not handled; fields assumed present that the contract marks optional; a request shape the contract does not accept | +| Mobile (React Native) | missing safe-area handling; forms without keyboard avoidance; Android back not handled or leaving a half-done flow; listeners, timers and subscriptions not removed (AppState, Keyboard, event emitters); work that breaks when the app is backgrounded mid-request; `FlatList` without `keyExtractor` or with inline heavy `renderItem`; images without size or caching; touchables without `accessibilityRole`/`accessibilityLabel`; `allowFontScaling={false}` or fixed-height text; a native module or permission added without the store-build note; JavaScript that calls a native API older builds lack | | Tests | tests that assert implementation details (internal state, call counts on mocks of the module under test) instead of what the user sees; mocked network that returns shapes the real API does not; a criterion with no test; a test deleted, skipped or loosened | | Standards | breaches of `docs/design.md`'s code rules and the repo's conventions (cite the rule); then only clear smells | diff --git a/plugins/dx-workflow/skills/frontend/design-review.md b/plugins/dx-workflow/skills/frontend/design-review.md index 1897e31..03495aa 100644 --- a/plugins/dx-workflow/skills/frontend/design-review.md +++ b/plugins/dx-workflow/skills/frontend/design-review.md @@ -49,6 +49,7 @@ For each lens ask: did someone decide, or did it default? | E. States and polish | Empty, loading, error, disabled, focus present; 44px touch targets; text not clipped or wrapping badly at 390 | | F. Structure and content | Shared parts reused, no hand-rolled control where a part exists, no tokens bypassed; every visible string tells one coherent story | | G. Consistency | Put every page of the same group side by side at one width: same header, spacing, type roles, parts. Content may differ; style may not | +| H. Mobile (React Native) | Safe areas (notch, home indicator, status bar never overlapped); the large-text variant: nothing clipped, overlapping or truncated that the user needs; touch targets 44 pt / 48 dp; dark variant uses the theme, no stray light surfaces; iOS and Android differ only where design.md says; the smallest phone does not cram, the largest does not stretch | Three quick tests while you look: diff --git a/plugins/dx-workflow/skills/frontend/mobile.md b/plugins/dx-workflow/skills/frontend/mobile.md new file mode 100644 index 0000000..3268ae1 --- /dev/null +++ b/plugins/dx-workflow/skills/frontend/mobile.md @@ -0,0 +1,80 @@ +# Mobile: React Native and Expo + +The frontend workflow is the same on a phone: one design contract, acceptance first, checks that +exit for real, screenshots a fresh reviewer judges, code a fresh reviewer reads. What changes is how +the app is driven and photographed, what a phone adds to "done", and that native changes ship only +in a store build. Read this alongside `setup.md`, `build.md` and `verify.md`; where they say +Playwright, the web or 390 px, use what this file says instead. + +## Setup (once per app) + +1. **The lane.** In `.verify/config.json` copy the `app` lane from + `/shared/verify.config.json`: `"kind": "frontend"`, `"platform": "react-native"`. Fill + `files` and `native` with the app's folder. `native` lists what only a store build can ship + (`app.json`, `app.config.*`, `eas.json`, `ios/`, `android/`); a change there, or a new native + module in `package.json`, is merge tier 3 and a one-way door. A web app in the same repo is a + second lane (`web`). +2. **The contract.** `docs/design.md` as `setup.md` writes it, with the token file being the theme + (`src/theme.ts`, or the NativeWind/Tailwind config). Add a "Mobile" section: type scale in points + and how it scales with the system text size (which text may grow, the largest size you support), + touch targets (44 pt iOS, 48 dp Android), safe areas, what differs between iOS and Android on + purpose (navigation, sheets, haptics), dark mode. +3. **Raw styles.** `check-raw-styles.mjs --platform react-native --spacing-scale `: + colour literals in style keys and props, font literals, off-scale spacing. Copy the script into + `scripts/ui/` as on the web. +4. **Accessibility lint.** `eslint-plugin-react-native-a11y` in the project's lint config: labels and + roles on touchables, no `accessible={false}` on interactive views. +5. **Every screen reachable by link, with fixed data.** The look check and the journeys open screens + by deep link (expo-router routes are links already). Give each state a link: `?fixture=empty`, + `?fixture=error`, a signed-in fixture user. Fixtures live in the repo; no clock, random or live + value on screen, or mask it. +6. **testIDs** on every control a journey taps or asserts. Text selectors break when copy changes. +7. **Screenshots.** Copy `/templates/rn-look.json` to `e2e/rn-look/screens.json`, `/scripts/rn-look.mjs` to `scripts/ui/rn-look.mjs` and + `/scripts/lib/png.mjs` to `scripts/ui/lib/png.mjs` (the first imports the second). Devices: the + smallest phone you support and the largest (375 and 440 on iOS), plus one Android. Variants: + default, dark, large-text. Run it once with `--update`, look at every image, commit the baselines. +8. **Journeys.** Maestro flows in `.maestro/journeys/`, one per acceptance-level user journey, + from `/templates/maestro-journey.yaml`. `ctl` (`/shared/ctl.md`) starts Metro and + the backend, seeds data, and opens the app. +9. **CI.** Simulators need macOS (iOS) or an emulator runner (Android). Either run the `look` and + `functional` checks on such a runner, or mark them `"ci": false`: they then run locally only, + and a CI run lists them as not run. + +## Build + +- Use the theme for every colour, text style and space; ``-style components over raw + `fontSize`. +- Respect the safe area on every screen (`SafeAreaView` or insets), the keyboard on every form + (`KeyboardAvoidingView` or a scroll view that moves the focused field into view), and Android's + back button and gesture on every screen that is not the root. +- Text must survive the large-text variant: no fixed heights on text containers, no + `numberOfLines` that hides content the user needs, `allowFontScaling` left on. +- Touchables: 44 pt / 48 dp, `accessibilityRole`, `accessibilityLabel` when the content is an icon, + `accessibilityState` for selected or disabled. +- Platform differences go through `Platform.select` or `.ios.tsx`/`.android.tsx` files, and only + where `docs/design.md` says they differ. +- A native change (a new module, a permission, `app.json`): say so to the user before building; + it needs a new store build, and users on the old build keep the old native code. + +## Verify + +`run-verify.mjs` runs the lane as everywhere. The look check is `rn-look.mjs`; it writes screenshots +named `---.png`, which the evidence pack shows next to the +baselines. A baseline change is merge tier 2: review the images before `--update`. + +What a phone adds to acceptance (`/shared/acceptance.md`, Mobile): + +- large text (the large-text variant), dark mode, the smallest supported phone; +- offline and slow network: the request fails, the screen says so, the user can retry, input is kept; +- the app goes to the background and comes back mid-flow; it is killed and reopened on a deep link; +- a permission is denied (camera, location, notifications) and the screen still works; +- Android back on every screen of the flow; the keyboard never covers the focused field; +- VoiceOver / TalkBack can finish the flow (at least by reading the labels and roles in code). + +## Over-the-air updates + +With `expo-updates` (EAS Update), JavaScript ships to installed builds without a store release. A +JavaScript change must therefore keep working on every build still in use: do not call a native +module the oldest supported build lacks, and keep `runtimeVersion` honest (a native change bumps +it). The backend contract has the same constraint: old app builds live for months, so the API must +keep answering them (`docs/backend.md`, Clients). diff --git a/plugins/dx-workflow/skills/frontend/setup.md b/plugins/dx-workflow/skills/frontend/setup.md index ced15ba..0c73397 100644 --- a/plugins/dx-workflow/skills/frontend/setup.md +++ b/plugins/dx-workflow/skills/frontend/setup.md @@ -1,5 +1,8 @@ # Setup: a design contract for this project +For a React Native or Expo app, follow `mobile.md` "Setup" for the lane, raw styles, screenshots and +journeys; the design contract steps below apply as they are. + Do this once per project. The output is `docs/design.md`, one token file, and the checks. The user makes the taste decisions; you prepare them and write them down. diff --git a/plugins/dx-workflow/skills/frontend/templates/maestro-journey.yaml b/plugins/dx-workflow/skills/frontend/templates/maestro-journey.yaml new file mode 100644 index 0000000..fc7fbba --- /dev/null +++ b/plugins/dx-workflow/skills/frontend/templates/maestro-journey.yaml @@ -0,0 +1,19 @@ +# One user journey: the acceptance criterion it proves, in the user's steps, ending in what they see. +# Save as .maestro/journeys/.yaml; run with `maestro test -e VERIFY_RUN_DIR="$VERIFY_RUN_DIR" .maestro/journeys`. +appId: +name: +--- +- launchApp: + clearState: true +- startRecording: ${VERIFY_RUN_DIR}/ # VERIFY_RUN_DIR is passed in with -e (the check in .verify/config.json) +- openLink: "://sign-in?fixture=user" +- tapOn: + id: "add-item" # testID on the control; text selectors break with copy changes +- inputText: "Milk" +- tapOn: + id: "save" +- assertVisible: + id: "item-0" + text: "Milk" +- assertNotVisible: "Something went wrong" +- stopRecording diff --git a/plugins/dx-workflow/skills/frontend/templates/rn-look.json b/plugins/dx-workflow/skills/frontend/templates/rn-look.json new file mode 100644 index 0000000..2043425 --- /dev/null +++ b/plugins/dx-workflow/skills/frontend/templates/rn-look.json @@ -0,0 +1,22 @@ +{ + "appId": "", + "baselines": "e2e/rn-look/look-snapshots", + "install": { + "ios": "", + "android": "" + }, + "devices": [ + { "platform": "ios", "name": "iPhone SE (3rd generation)", "width": 375 }, + { "platform": "ios", "name": "iPhone 16 Pro Max", "width": 440 }, + { "platform": "android", "serial": "emulator-5554", "width": 412 } + ], + "variants": ["default", "dark", "large-text"], + "threshold": 16, + "maxDiffRatio": 0.001, + "timeoutMs": 20000, + "screens": [ + { "name": "home", "group": "tabs", "link": "://home", "waitFor": "" }, + { "name": "home-empty", "group": "tabs", "link": "://home?fixture=empty", "waitFor": "<…>" }, + { "name": "settings", "group": "tabs", "link": "://settings", "waitFor": "<…>", "mask": [[0.6, 0.1, 0.4, 0.05]] } + ] +} diff --git a/plugins/dx-workflow/skills/frontend/verify.md b/plugins/dx-workflow/skills/frontend/verify.md index c67f79b..7bde153 100644 --- a/plugins/dx-workflow/skills/frontend/verify.md +++ b/plugins/dx-workflow/skills/frontend/verify.md @@ -1,5 +1,9 @@ # Verify: prove the screen is right +In a React Native / Expo lane the look check is `rn-look.mjs` (simulators, default, dark and +large-text variants) and the journeys are Maestro flows; read `mobile.md` "Verify" for what a phone +adds. Use `--lane ` with the lane's name (`app`, `web`, …). + ## Run the checks `node /scripts/run-verify.mjs --lane frontend` runs the frontend lane's checks in `.verify/config.json` diff --git a/test/helpers.mjs b/test/helpers.mjs index 9526d98..158c2be 100644 --- a/test/helpers.mjs +++ b/test/helpers.mjs @@ -100,15 +100,15 @@ export function addFeature(root) { } /** Everything the gate asks for: a passing run, acceptance, an approved review naming the run's tree, evidence. */ -export function verify(root, { runArgs = [], reviewTree } = {}) { +export function verify(root, { runArgs = [], reviewTree, lane = "backend" } = {}) { const run = node("run-verify.mjs", runArgs, { cwd: root }); const last = JSON.parse(read(root, ".verify/last-run.json")); write(root, { ".verify/acceptance.md": "# Acceptance: sub\n## Criteria\n- A1 sub(5, 3) returns 2 · proof: test/run.mjs\n", - ".verify/review-backend.md": [ - `# Review ${last.lanes.backend.runDir}`, + [`.verify/review-${lane}.md`]: [ + `# Review ${last.lanes[lane].runDir}`, "Reviewer: test", - `Tree: ${reviewTree ?? last.lanes.backend.tree}`, + `Tree: ${reviewTree ?? last.lanes[lane].tree}`, "", "## Acceptance", "- [x] A1 met · test/run.mjs passed", diff --git a/test/mobile.test.mjs b/test/mobile.test.mjs new file mode 100644 index 0000000..4f48d45 --- /dev/null +++ b/test/mobile.test.mjs @@ -0,0 +1,258 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { after, describe, it } from "node:test"; +import { deflateSync } from "node:zlib"; +import { loadConfig } from "../plugins/dx-workflow/scripts/lib/verify-config.mjs"; +import { comparePng, decodePng, encodePng } from "../plugins/dx-workflow/scripts/lib/png.mjs"; +import { cleanup, evidenceText, makeProject, node, read, SCRIPTS, tierOf, verify, write } from "./helpers.mjs"; + +const roots = []; +const temps = []; +const project = (opts) => { + const r = makeProject(opts); + roots.push(r); + return r; +}; +const tmp = () => { + const d = mkdtempSync(join(tmpdir(), "dxm-")); + temps.push(d); + return d; +}; +after(() => { + roots.forEach(cleanup); + temps.forEach((d) => rmSync(d, { recursive: true, force: true })); +}); + +const RN = { + lanes: { + app: { + kind: "frontend", + platform: "react-native", + checks: [ + { name: "unit", run: "node test/run.mjs" }, + { name: "look", run: "node -e process.exit(1)", ci: false }, + { name: "after", run: "node -e 0" }, + ], + }, + }, +}; + +function image(width, height, fill) { + const data = Buffer.alloc(width * height * 4); + for (let i = 0; i < width * height; i++) data.set(fill(i % width, Math.floor(i / width)), i * 4); + return { width, height, data }; +} + +// A PNG with colour type 2 (RGB) and every scanline filter, to exercise the decoder beyond what encodePng writes. +function rgbPngWithFilters(img) { + const { width, height, data } = img; + const bpp = 3; + const stride = width * bpp; + const rows = []; + for (let y = 0; y < height; y++) { + const row = Buffer.alloc(stride); + for (let x = 0; x < width; x++) for (let c = 0; c < 3; c++) row[x * 3 + c] = data[(y * width + x) * 4 + c]; + rows.push(row); + } + const out = []; + for (let y = 0; y < height; y++) { + const f = y % 5; + const cur = rows[y]; + const prev = y ? rows[y - 1] : Buffer.alloc(stride); + const line = Buffer.alloc(stride + 1); + line[0] = f; + for (let x = 0; x < stride; x++) { + const a = x >= bpp ? cur[x - bpp] : 0; + const b = prev[x]; + const c = x >= bpp ? prev[x - bpp] : 0; + const p = a + b - c; + const pred = [0, a, b, (a + b) >> 1, Math.abs(p - a) <= Math.abs(p - b) && Math.abs(p - a) <= Math.abs(p - c) ? a : Math.abs(p - b) <= Math.abs(p - c) ? b : c][f]; + line[x + 1] = (cur[x] - pred) & 255; + } + out.push(line); + } + const sig = encodePng({ width: 1, height: 1, data: Buffer.alloc(4) }).subarray(0, 8); + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(width, 0); + ihdr.writeUInt32BE(height, 4); + ihdr[8] = 8; + ihdr[9] = 2; + const chunk = (kind, body) => { + const len = Buffer.alloc(4); + len.writeUInt32BE(body.length); + const head = Buffer.from(kind, "latin1"); + const crc = Buffer.alloc(4); // decodePng does not check CRCs + return Buffer.concat([len, head, body, crc]); + }; + return Buffer.concat([sig, chunk("IHDR", ihdr), chunk("IDAT", deflateSync(Buffer.concat(out))), chunk("IEND", Buffer.alloc(0))]); +} + +describe("png", () => { + const img = image(23, 17, (x, y) => [(x * 11) & 255, (y * 15) & 255, (x * y) & 255, 255]); + + it("round-trips RGBA and decodes RGB with every filter", () => { + assert.deepEqual(decodePng(encodePng(img)).data, img.data); + assert.deepEqual(decodePng(rgbPngWithFilters(img)).data, img.data); + }); + + it("compares: identical, changed pixels, masked areas, size mismatch", () => { + assert.equal(comparePng(img, img).ratio, 0); + const changed = { ...img, data: Buffer.from(img.data) }; + for (let x = 0; x < 5; x++) changed.data.set([255, 255, 255, 255], x * 4); // 5 pixels in the top row + const c = comparePng(img, changed); + assert.equal(c.diffPixels, 5); + assert.ok(c.ratio > 0.01); + assert.equal(comparePng(img, changed, { mask: [[0, 0, 1, 0.1]] }).diffPixels, 0); + assert.equal(comparePng(img, image(10, 10, () => [0, 0, 0, 255])).sameSize, false); + }); +}); + +describe("rn-look", () => { + function setup() { + const dir = tmp(); + mkdirSync(join(dir, "e2e/rn-look"), { recursive: true }); + const config = { + appId: "com.example.app", + devices: [{ platform: "ios", name: "iPhone SE (3rd generation)", width: 375 }], + variants: ["default", "dark"], + screens: [ + { name: "home", group: "tabs", link: "app://home", waitFor: "Home" }, + { name: "settings", group: "tabs", link: "app://settings", waitFor: "Settings", mask: [[0, 0, 1, 0.2]] }, + ], + }; + writeFileSync(join(dir, "e2e/rn-look/screens.json"), JSON.stringify(config)); + const out = join(dir, "out"); + const shot = (name, img) => { + mkdirSync(join(out, "tabs"), { recursive: true }); + writeFileSync(join(out, "tabs", `${name}.png`), encodePng(img)); + }; + const run = (...extra) => spawnSync(process.execPath, [join(SCRIPTS, "rn-look.mjs"), "--out", out, ...extra], { cwd: dir, encoding: "utf8" }); + return { dir, out, shot, run }; + } + const base = image(20, 40, (x, y) => [x * 10, y * 5, 100, 255]); + + it("plans simulator setup and one Maestro flow per device and variant in a dry run", () => { + const { run, out } = setup(); + const r = run("--dry-run"); + assert.equal(r.status, 0, r.stderr); + assert.match(r.stdout, /xcrun simctl status_bar .* override --time 9:41/); + assert.match(r.stdout, /xcrun simctl ui .* appearance dark/); + assert.match(r.stdout, /maestro --device .* test .*ios-375-dark\.yaml/); + assert.match(r.stdout, /would compare .*tabs\/home-dark-ios-375\.png with .*look-snapshots\/home-dark-ios-375\.png/); + const flow = readFileSync(join(out, "flows", "ios-375-default.yaml"), "utf8"); + assert.match(flow, /appId: com\.example\.app\n---\n- launchApp\n- openLink: "app:\/\/home"/); + assert.match(flow, /takeScreenshot: ".*tabs\/home-default-ios-375"/); + }); + + it("fails without baselines, accepts them with --update, then matches, flags a change, and honours masks", () => { + const { dir, out, shot, run } = setup(); + for (const v of ["default", "dark"]) for (const s of ["home", "settings"]) shot(`${s}-${v}-ios-375`, base); + let r = run("--compare-only"); + assert.equal(r.status, 1); + assert.match(r.stdout, /no baseline/); + assert.equal(run("--compare-only", "--update").status, 0); + assert.ok(existsSync(join(dir, "e2e/rn-look/look-snapshots/home-dark-ios-375.png"))); + assert.equal(run("--compare-only").status, 0); + + const moved = image(20, 40, (x, y) => (y < 4 ? [255, 255, 255, 255] : [x * 10, y * 5, 100, 255])); // top 10% changed + shot("home-default-ios-375", moved); + shot("settings-default-ios-375", moved); // inside the settings mask + r = run("--compare-only"); + assert.equal(r.status, 1); + assert.match(r.stdout, /home-default-ios-375: differs/); + assert.doesNotMatch(r.stdout, /settings-default-ios-375/); + assert.ok(existsSync(join(out, "tabs", "home-default-ios-375.diff.png"))); + assert.match(readFileSync(join(out, "report.md"), "utf8"), /\| home \| default \| ios iPhone SE \(3rd generation\) \(375\) \| differs/); + }); +}); + +describe("check-raw-styles --platform react-native", () => { + it("flags colour props, font literals and off-scale spacing, and skips the theme file", () => { + const dir = tmp(); + mkdirSync(join(dir, "src")); + writeFileSync( + join(dir, "src/Card.tsx"), + [ + "const s = StyleSheet.create({", + " card: { backgroundColor: '#fff', padding: 13, margin: 16, borderColor: theme.colors.border },", + " title: { fontSize: 18, fontFamily: 'Inter-Bold', color: theme.colors.text },", + "});", + 'export const C = () => ;', + ].join("\n"), + ); + writeFileSync(join(dir, "src/theme.ts"), 'export const colors = { primary: "#0a7", text: "black" };\n'); + const r = spawnSync(process.execPath, [join(SCRIPTS, "check-raw-styles.mjs"), "src", "--platform", "react-native", "--spacing-scale", "0,4,8,12,16,24", "--json"], { cwd: dir, encoding: "utf8" }); + assert.equal(r.status, 1); + const got = JSON.parse(r.stdout).findings.map((f) => `${f.rule} ${f.line} ${f.match}`); + assert.deepEqual(got.sort(), [ + "off-scale-spacing 2 padding: 13", + "rn-font-literal 3 fontFamily: 'Inter-Bold", + "rn-font-literal 3 fontSize: 18", + "rn-literal-colour 2 backgroundColor: '#fff", + 'rn-literal-colour 5 placeholderTextColor="gray', + ]); + }); +}); + +describe("react-native lanes", () => { + it("default to app code plus native config, and mark native paths", () => { + const root = project({ config: { lanes: { app: { kind: "frontend", platform: "react-native", checks: [] }, web: { kind: "frontend", checks: [] } } } }); + const [app, web] = loadConfig(root).lanes; + assert.equal(app.platform, "react-native"); + assert.ok(app.files.includes("**/*.{ts,tsx,js,jsx}") && app.files.includes("ios/**")); + assert.ok(app.native.includes("app.json")); + assert.equal(web.platform, "web"); + assert.deepEqual(web.native, []); + }); + + it("skip ci:false checks in CI without stopping the lane, and run them locally", () => { + const root = project({ config: RN }); + write(root, { "src/math.mjs": read(root, "src/math.mjs") + "// x\n" }); + let r = node("run-verify.mjs", [], { cwd: root, env: { CI: "true" } }); + assert.equal(r.code, 0, r.stdout); + const checks = JSON.parse(read(root, ".verify/last-run.json")).lanes.app.checks; + assert.deepEqual(checks.map((c) => [c.name, c.skipped ?? false, c.exitCode]), [["unit", false, 0], ["look", true, null], ["after", false, 0]]); + r = node("run-verify.mjs", [], { cwd: root }); + assert.equal(r.code, 1, "locally the look check runs (and fails here)"); + }); + + const rnProject = (files = {}) => + project({ + config: { lanes: { app: { kind: "frontend", platform: "react-native", files: ["src/**", "test/**", "app.json", "package.json"], checks: [{ name: "unit", run: "node test/run.mjs" }] } } }, + files: { "app.json": '{ "expo": { "name": "a" } }\n', "package.json": '{\n "dependencies": {\n "react-native": "0.76.0"\n }\n}\n', ...files }, + }); + + it("tier 3 and a one-way door for app.json", () => { + const root = rnProject(); + write(root, { "app.json": '{ "expo": { "name": "a", "scheme": "a" } }\n', "src/math.mjs": read(root, "src/math.mjs") + "// x\n" }); + verify(root, { lane: "app" }); + assert.equal(tierOf(root), "3"); + const ev = evidenceText(root); + assert.match(ev, /a native change needs a new store build \(app\.json\)/); + assert.match(ev, /- Door: one-way: a native change ships only in a new store build/); + }); + + it("tier 3 for a new native module, not for a JavaScript-only dependency", () => { + const root = rnProject(); + write(root, { "package.json": '{\n "dependencies": {\n "lodash": "4.17.21",\n "react-native": "0.76.0"\n }\n}\n' }); + verify(root, { lane: "app" }); + assert.notEqual(tierOf(root), "3"); + write(root, { "package.json": '{\n "dependencies": {\n "expo-camera": "16.0.0",\n "lodash": "4.17.21",\n "react-native": "0.76.0"\n }\n}\n' }); + verify(root, { lane: "app" }); + assert.equal(tierOf(root), "3"); + assert.match(evidenceText(root), /package\.json \(native dependency: expo-camera\)/); + }); + + it("send a native change to a deep review", () => { + const root = rnProject(); + write(root, { "app.json": '{ "expo": { "name": "b" } }\n' }); + node("run-verify.mjs", [], { cwd: root }); + const r = node("review-brief.mjs", ["--lane", "app", "--request", "rename"], { cwd: root }); + assert.equal(r.code, 0, r.stderr); + assert.match(r.stdout, /## Depth: deep \(native \(needs a store build\): app\.json\)/); + assert.match(r.stdout, /frontend\/design-review\.md for the screenshots/); + }); +}); From 7613fa2cf284aaaee938ccad56fafcc187ff64da Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 13:11:43 +1100 Subject: [PATCH 3/3] Tests: clear CI by default so GitHub Actions' CI=true does not leak into local-run cases Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014d2MvQ5v7FCph37jwFCC7i --- test/helpers.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/helpers.mjs b/test/helpers.mjs index 158c2be..b866ce2 100644 --- a/test/helpers.mjs +++ b/test/helpers.mjs @@ -79,7 +79,7 @@ export function node(script, args = [], { cwd, input, env = {} } = {}) { cwd, input: input === undefined ? "" : typeof input === "string" ? input : JSON.stringify(input), encoding: "utf8", - env: { ...process.env, ...GIT_ENV, VERIFY_BASE: "", DX_WORKFLOW_GATE: "", ...env }, + env: { ...process.env, ...GIT_ENV, VERIFY_BASE: "", DX_WORKFLOW_GATE: "", CI: "", ...env }, // tests set CI themselves; GitHub Actions sets it everywhere }); return { code: r.status, stdout: r.stdout, stderr: r.stderr }; }