From 7bd58e8058b4b9da649af9675bbe33a2963ea1d6 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 09:21:36 +1100 Subject: [PATCH 1/2] Keep checks out of the change's reach and bind verification to content (0.3.0) - Read .verify/config.json from the base commit; --config working to opt in. - Changes to the checks themselves (config, test/lint/CI config, deleted tests, skipped or loosened tests) are merge tier 3; silenced checks tier 2. - run-verify records a working-tree hash; reviews name it on a Tree: line; the Stop gate and make-evidence accept only the tree now on disk. A check that rewrites source fails the run. - Measure the change from the merge-base: commits on the branch and deletions count (fixes the gate skipping committed work and make-evidence dropping pushed commits). - UserPromptSubmit hook records the tree at turn start so talk-only turns pass; gate modes enforce/observe/off with .verify/gate.log. - Negative check is binary-safe and shares base resolution. - Tests for the scripts (node:test, fixture repos) and CI. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014d2MvQ5v7FCph37jwFCC7i --- .github/workflows/test.yml | 29 +++ README.md | 38 +++- ...hecks-out-of-reach-and-bound-to-content.md | 47 ++++ package.json | 12 ++ plugins/workflow/.claude-plugin/plugin.json | 4 +- plugins/workflow/hooks/hooks.json | 11 + plugins/workflow/scripts/lib/negative.mjs | 36 +--- .../workflow/scripts/lib/verify-config.mjs | 204 +++++++++++++++++- plugins/workflow/scripts/make-evidence.mjs | 58 +++-- plugins/workflow/scripts/run-verify.mjs | 56 ++++- plugins/workflow/scripts/stop-gate.mjs | 92 ++++++-- plugins/workflow/scripts/turn-start.mjs | 23 ++ plugins/workflow/shared/verify.config.json | 1 + .../building-consistent-ui/design-review.md | 1 + .../skills/building-consistent-ui/setup.md | 9 +- .../skills/building-consistent-ui/verify.md | 15 +- .../building-reliable-backend/code-review.md | 1 + .../skills/building-reliable-backend/setup.md | 7 +- .../building-reliable-backend/verify.md | 12 +- test/helpers.mjs | 135 ++++++++++++ test/make-evidence.test.mjs | 79 +++++++ test/run-verify.test.mjs | 93 ++++++++ test/stop-gate.test.mjs | 110 ++++++++++ test/verify-config.test.mjs | 117 ++++++++++ 24 files changed, 1089 insertions(+), 101 deletions(-) create mode 100644 .github/workflows/test.yml create mode 100644 docs/adr/0003-checks-out-of-reach-and-bound-to-content.md create mode 100644 package.json create mode 100644 plugins/workflow/scripts/turn-start.mjs create mode 100644 test/helpers.mjs create mode 100644 test/make-evidence.test.mjs create mode 100644 test/run-verify.test.mjs create mode 100644 test/stop-gate.test.mjs create mode 100644 test/verify-config.test.mjs diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml new file mode 100644 index 0000000..bb8446f --- /dev/null +++ b/.github/workflows/test.yml @@ -0,0 +1,29 @@ +name: test + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + scripts: + name: scripts (node ${{ matrix.node }}, ${{ matrix.os }}) + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest] + node: [20, 22] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + 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 + - 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 node -e "JSON.parse(require('fs').readFileSync('$f','utf8'))" || { echo "invalid JSON: $f"; exit 1; }; done + - run: npm test diff --git a/README.md b/README.md index b974e9a..dd387bf 100644 --- a/README.md +++ b/README.md @@ -28,12 +28,30 @@ | --- | --- | --- | | 1 | 检查全过、评审通过、验收标准全部满足,且没有下面的情况 | 扫一眼证据包即可合并 | | 2 | 改了截图基线或共享模块;有验收标准"未验证";改了源码却没改测试 | 你要看前后对比和标出来的部分 | -| 3 | 改了设计约定、后端约定、接口契约或迁移 | 你确认之后才能合并 | -| 未就绪 | 检查失败、评审未通过、有验收标准未满足或没被评审 | 不合并 | +| 3 | 改了设计约定、后端约定、接口契约或迁移;或者**改了检查本身**(见下) | 你确认之后才能合并 | +| 未就绪 | 检查失败、评审未通过、有验收标准未满足或没被评审;或者运行、评审对应的不是当前磁盘上的内容 | 不合并 | -**收尾检查**:Stop 钩子。有 lane 的文件被改了,但这条 lane 的 `run-verify` 没通过、独立评审缺失、过期或未通过, -验收标准没有全部在评审里标记,或者证据包比评审旧,第一次结束会被拦下;仍未通过就结束时,AI 必须写明"未验证" -(钩子只拦一次,避免无限循环)。关闭:环境变量 `UI_WORKFLOW_GATE=off`。 +另外,代码里新增了 `@ts-ignore`、`eslint-disable`、`noqa` 这类"关掉检查"的注释,或者加了重试,至少是 2 档。 + +**改动不能改判它的检查**:检查一律从基线提交(和默认分支的 merge-base,可用 `VERIFY_BASE` 指定)上的 +`.verify/config.json` 读取,工作区里改过的配置不生效。确实要改检查的改动(接新检查、调整 lane)用 +`run-verify.mjs --config working` 跑,但这类改动固定是 3 档。算作"改了检查本身"的有:`.verify/config.json`; +测试、lint、类型和 CI 的配置(`playwright.config.*`、`eslint.config.*`、`tsconfig*.json`、`.github/workflows/**`、 +`.claude/settings.json` 等,完整清单见 `scripts/lib/verify-config.mjs` 的 `DEFAULT_GUARD`,项目可以在配置的 `guard` +里追加);删掉的测试文件;测试里新增的 `.skip`、`.only`、`xit`、`@pytest.mark.skip`,以及截图对比的 `threshold`、 +`maxDiffPixels`、`mask`。 + +**按内容认,不按时间认**:`run-verify` 记录工作区内容的哈希(`tree`,不含 `.verify/` 和被 `.gitignore` 忽略的文件), +评审在标题下写 `Tree: <这个哈希>`,证据包也写上它。收尾检查和分档只认哈希对得上的运行和评审;`touch`、`checkout` +或者评审之后再改文件,都骗不过去。运行期间如果有检查改写了源码(比如格式化工具开了写入模式),这次运行直接判失败。 + +**收尾检查**:Stop 钩子。这一轮改动了某条 lane 的文件(和基线提交相比,已提交、未提交、删除都算;内容和这一轮开始时 +不同,由 UserPromptSubmit 钩子记录),而这条 lane 的 `run-verify` 没通过或对应的不是当前内容,独立评审缺失、未通过 +或对应的不是当前内容,验收标准没有全部在评审里标记,或者证据包不是当前内容的,第一次结束会被拦下;仍未通过就结束时, +AI 必须写明"未验证"(钩子只拦一次,避免无限循环)。只聊天、没改内容的一轮不会被拦。 + +`UI_WORKFLOW_GATE`:`enforce`(默认,拦截)、`observe`(只记录本来会拦什么,用来先看误报)、`off`(关闭)。 +每次判断都追加到 `.verify/gate.log`。 ## 安装 @@ -61,6 +79,13 @@ baoyu-design 是可选的看图调色工具,只在项目仓库外用(它含 两者都会写约定文件、接好 `.verify/config.json`,没有可脚本化的用户路径时生成 `ctl` 控制命令,最后在未改动的代码上跑一遍全部检查。 之后正常让 Claude 改代码即可。 +### 从 0.2 升级 + +- 评审文件要在标题下多写一行 `Tree: `,没有这一行收尾检查不放行。 + 按新的 `verify.md` 派评审即可,brief 里已经写了。 +- 检查改为从基线提交读配置。如果 `.verify/config.json` 还没合进默认分支,先用 `run-verify.mjs --config working`。 +- Stop 钩子现在也会检查这一轮里已经提交的改动。 + ### 从 0.1 升级 0.1 用的是 `.ui-verify/`。在项目里运行 `node /scripts/run-verify.mjs --migrate`,它会把目录改成 `.verify/`、 @@ -78,6 +103,9 @@ baoyu-design 是可选的看图调色工具,只在项目仓库外用(它含 | `plugins/workflow/scripts/run-verify.mjs` | 按 lane 跑检查(含内置负向检查),按真实退出码记录;`--restore`、`--migrate` | | `plugins/workflow/scripts/make-evidence.mjs` | 生成证据包:合并分档、验收标准、机器检查、前后对比截图、录屏;`--pr` 输出 PR 描述 | | `plugins/workflow/scripts/stop-gate.mjs` | Stop 钩子 | +| `plugins/workflow/scripts/turn-start.mjs` | UserPromptSubmit 钩子:记录这一轮开始时的内容哈希 | +| `plugins/workflow/scripts/lib/verify-config.mjs` | 读配置(从基线提交)、算改动范围和内容哈希、找出"改了检查本身"的改动 | +| `test/` | 这些脚本自己的测试:`npm test`(Node 20+,无依赖),CI 见 `.github/workflows/test.yml` | | `plugins/workflow/scripts/check-raw-styles.mjs` | 找出写死的颜色、Tailwind 色板类、任意值 | | `plugins/workflow/scripts/find-tools.mjs` | 找到已安装的 taste-skill、ui-ux-pro-max、baoyu-design | | `docs/adr/` | 关键取舍的决策记录 | 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 new file mode 100644 index 0000000..2de92ef --- /dev/null +++ b/docs/adr/0003-checks-out-of-reach-and-bound-to-content.md @@ -0,0 +1,47 @@ +# 3. Checks are out of the change's reach, and verification is bound to content + +Date: 2026-11-18 · Status: accepted + +## Context + +Three holes let an agent's change pass verification it should not: + +- The change could edit its own judge. `run-verify`, the Stop gate and the merge tier all read + `.verify/config.json` from the working tree, and `make-evidence` left `.verify/` out of the change, + so deleting a check or narrowing a lane's `files` left the tier at 1. Deleted files were invisible + too (`workingChanges` drops them), so deleting a test raised nothing. +- Freshness was decided by file times. "Review newer than run, run newer than the files" breaks on + `touch`, `checkout` and `rebase`, and says nothing about what content a review saw. +- The change was measured against the wrong thing. The Stop gate looked only at uncommitted files, + so committing during a turn skipped it; `make-evidence` diffed against the upstream branch, so + pushed commits stopped counting. + +The Claude Code team's verification write-up states the rule plainly: a change must not be able to +modify its own checks, and a review applies to one specific commit. + +## Decision + +- **Base config.** The checks come from `.verify/config.json` on the base commit (merge-base with the + default branch, or `VERIFY_BASE`). `run-verify --config working` uses the working copy, for a + change that sets up or extends the checks. +- **Guarded changes.** A change to a guard file (`DEFAULT_GUARD` in `lib/verify-config.mjs`, plus the + config's `guard`), a deleted test, or a test gaining a skip, focus, threshold or mask is merge tier + 3. A line anywhere that silences a type or lint check, or adds retries, is tier 2. +- **Content hash.** `run-verify` records a hash of the working tree (a `git write-tree` of a copy of + the index after `add -A`, without `.verify/` and ignored files). Reviews name it on a `Tree:` line, + the evidence pack prints it, and the Stop gate and the tier accept only runs and reviews of the tree + now on disk. A check that changes the tree while it runs fails the run. +- **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`. +- **The scripts have tests** (`test/`, `npm test`) and CI, because they are the judge. + +## Consequences + +A repository with no remote has no default branch to measure from, so the base is `HEAD` and a +committed edit to the config becomes the base; set `VERIFY_BASE` there. Setting up checks on a branch needs `--config working` until they reach the default branch. Reviews +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. diff --git a/package.json b/package.json new file mode 100644 index 0000000..c00e169 --- /dev/null +++ b/package.json @@ -0,0 +1,12 @@ +{ + "name": "ui-workflow-dev", + "private": true, + "type": "module", + "description": "Tests for the ui-workflow plugin's scripts. The plugin itself has no dependencies.", + "engines": { + "node": ">=20" + }, + "scripts": { + "test": "node --test test/*.test.mjs" + } +} diff --git a/plugins/workflow/.claude-plugin/plugin.json b/plugins/workflow/.claude-plugin/plugin.json index 12618c1..65ab9a0 100644 --- a/plugins/workflow/.claude-plugin/plugin.json +++ b/plugins/workflow/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "ui-workflow", - "version": "0.2.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.", + "version": "0.3.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.", "author": { "name": "davidxiaodev" }, diff --git a/plugins/workflow/hooks/hooks.json b/plugins/workflow/hooks/hooks.json index ee6a91f..6709e59 100644 --- a/plugins/workflow/hooks/hooks.json +++ b/plugins/workflow/hooks/hooks.json @@ -1,5 +1,16 @@ { "hooks": { + "UserPromptSubmit": [ + { + "hooks": [ + { + "type": "command", + "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/turn-start.mjs\"", + "timeout": 15 + } + ] + } + ], "Stop": [ { "hooks": [ diff --git a/plugins/workflow/scripts/lib/negative.mjs b/plugins/workflow/scripts/lib/negative.mjs index 84477c6..83b5d80 100644 --- a/plugins/workflow/scripts/lib/negative.mjs +++ b/plugins/workflow/scripts/lib/negative.mjs @@ -5,10 +5,10 @@ // // It edits the working tree in place, so it backs every file up first, restores in a finally block, // and refuses to start while an older backup exists (a crashed run): `run-verify.mjs --restore`. -import { execFileSync, spawnSync } from "node:child_process"; +import { spawnSync } from "node:child_process"; import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, unlinkSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; -import { gitLines, inLane, matchAny } from "./verify-config.mjs"; +import { changedSince, gitShow, inLane, matchAny, resolveBase } from "./verify-config.mjs"; const BACKUP = "negative-backup"; @@ -45,7 +45,7 @@ export function runNegative({ root, dir, lane, tests, spec, timeoutMs, env }) { }; } - const base = resolveBase(root, spec.base); + const base = spec.base ? resolveBase(root, spec.base) : resolveBase(root); if (!base) return { exitCode: 2, note: "no base commit to compare with (no commits yet?)", log: "" }; const changed = changedSince(root, base).filter((c) => inLane(lane, c.path)); const isTest = (p) => matchAny(spec.tests ?? tests, p); @@ -87,7 +87,7 @@ export function runNegative({ root, dir, lane, tests, spec, timeoutMs, env }) { } manifest.files.push({ path: s.path, existed }); writeFileSync(join(backupDir, "manifest.json"), JSON.stringify(manifest, null, 2)); - const old = baseContent(root, base, s.path); + const old = gitShow(root, base, s.path, { buffer: true }); if (old === null) { if (existed) unlinkSync(target); } else { @@ -113,31 +113,3 @@ export function runNegative({ root, dir, lane, tests, spec, timeoutMs, env }) { log: log.join("\n"), }; } - -function resolveBase(root, wanted) { - const candidates = wanted ? [wanted] : ["origin/HEAD", "origin/main", "origin/master"]; - for (const ref of candidates) { - const mb = gitLines(root, ["merge-base", "HEAD", ref])[0]; - if (mb) return mb; - } - return gitLines(root, ["rev-parse", "HEAD"])[0] ?? null; -} - -/** Files that differ between base and the working tree, including untracked ones. */ -function changedSince(root, base) { - const out = new Map(); - for (const line of gitLines(root, ["diff", "--name-status", "--no-renames", base])) { - const [status, path] = line.split("\t"); - out.set(path, { path, status }); - } - for (const path of gitLines(root, ["ls-files", "--others", "--exclude-standard"])) out.set(path, { path, status: "A" }); - return [...out.values()]; -} - -function baseContent(root, base, path) { - try { - return execFileSync("git", ["show", `${base}:${path}`], { cwd: root, maxBuffer: 64 << 20, stdio: ["ignore", "pipe", "ignore"] }); - } catch { - return null; - } -} diff --git a/plugins/workflow/scripts/lib/verify-config.mjs b/plugins/workflow/scripts/lib/verify-config.mjs index ccbf1b4..bdc3cb4 100644 --- a/plugins/workflow/scripts/lib/verify-config.mjs +++ b/plugins/workflow/scripts/lib/verify-config.mjs @@ -2,8 +2,9 @@ // 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). import { execFileSync } from "node:child_process"; -import { existsSync, readFileSync } from "node:fs"; -import { join } from "node:path"; +import { copyFileSync, existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { isAbsolute, join } from "node:path"; export const VERIFY_DIR = ".verify"; @@ -28,11 +29,25 @@ export const DEFAULT_TESTS = [ "**/*-snapshots/**", ]; -/** Returns { root, dir, config, lanes: [{ name, kind, files, ignore, ... }] } or null when the project has no config. */ -export function loadConfig(root) { - const path = join(root, VERIFY_DIR, "config.json"); - if (!existsSync(path)) return null; - const config = JSON.parse(readFileSync(path, "utf8")); +export const CONFIG_PATH = `${VERIFY_DIR}/config.json`; + +/** + * Returns { root, dir, config, lanes, tests, source, base, workingDiffers } or null when the project has no config. + * + * The config is read from the base commit (the merge-base with the default branch) when it exists + * there, because a change must not be able to edit the checks that judge it. `source: "working"` + * reads the working copy instead (run-verify --config working, for a change that sets up or extends + * the checks); such a change is a guarded change and lands in merge tier 3 anyway. + */ +export function loadConfig(root, { source = "base", base } = {}) { + const workingPath = join(root, CONFIG_PATH); + const workingText = existsSync(workingPath) ? readFileSync(workingPath, "utf8") : null; + const baseRef = base ?? resolveBase(root); + const baseText = baseRef ? gitShow(root, baseRef, CONFIG_PATH) : null; + const useBase = source !== "working" && baseText !== null; + const text = useBase ? baseText : workingText; + if (text === null) return null; + const config = JSON.parse(text); const lanes = Object.entries(config.lanes ?? {}).map(([name, lane]) => { const kind = lane.kind ?? name; return { @@ -44,7 +59,25 @@ export function loadConfig(root) { checks: lane.checks ?? [], }; }); - return { root, dir: join(root, VERIFY_DIR), config, lanes, tests: config.tests ?? DEFAULT_TESTS }; + return { + root, + dir: join(root, VERIFY_DIR), + config, + lanes, + tests: config.tests ?? DEFAULT_TESTS, + guard: [...DEFAULT_GUARD, ...(config.guard ?? [])], + source: useBase ? "base" : "working", + base: baseRef, + workingDiffers: workingText !== null && baseText !== null && normalizeJson(workingText) !== normalizeJson(baseText), + }; +} + +function normalizeJson(text) { + try { + return JSON.stringify(JSON.parse(text)); + } catch { + return text; + } } export function legacyConfigExists(root) { @@ -98,6 +131,161 @@ export function workingChanges(root) { .filter((f) => existsSync(join(root, f))); } +/** The commit a change is measured against: VERIFY_BASE, else the merge-base with the default branch, else HEAD. */ +export function resolveBase(root, wanted = process.env.VERIFY_BASE) { + const candidates = wanted ? [wanted] : ["origin/HEAD", "origin/main", "origin/master"]; + for (const ref of candidates) { + const mb = gitLines(root, ["merge-base", "HEAD", ref])[0]; + if (mb) return mb; + } + return gitLines(root, ["rev-parse", "--verify", "HEAD"])[0] ?? null; +} + +/** + * Every file that differs between the base commit and the working tree: committed on this branch, + * staged, unstaged or untracked, deletions included. [{ path, status }] with status A, M or D. + */ +export function changedSince(root, base = resolveBase(root)) { + const out = new Map(); + if (base) { + for (const line of gitLines(root, ["diff", "--name-status", "--no-renames", base])) { + const [status, path] = line.split("\t"); + out.set(path, { path, status: status[0] }); + } + } + for (const path of gitLines(root, ["ls-files", "--others", "--exclude-standard"])) out.set(path, { path, status: "A" }); + return [...out.values()]; +} + +/** + * A hash of the working tree's content (tracked and untracked files, deletions, not .gitignored + * files, not .verify/). A run, a review and an evidence pack record it; when the content changes, so + * does the hash, whatever the file times say. Uses a copy of the real index so unchanged files are + * not re-read. + */ +export function treeHash(root) { + const tmp = mkdtempSync(join(tmpdir(), "verify-index-")); + const index = join(tmp, "index"); + try { + const realIndex = gitLines(root, ["rev-parse", "--git-path", "index"])[0]; + const realPath = realIndex && (isAbsolute(realIndex) ? realIndex : join(root, realIndex)); + const env = { ...process.env, GIT_INDEX_FILE: index }; + if (realPath && existsSync(realPath)) copyFileSync(realPath, index); + else execFileSync("git", ["read-tree", "--empty"], { cwd: root, env, stdio: "ignore" }); + execFileSync("git", ["add", "-A", "--", ".", `:(exclude)${VERIFY_DIR}`], { cwd: root, env, stdio: "ignore" }); + execFileSync("git", ["rm", "-r", "--cached", "--quiet", "--ignore-unmatch", "--", VERIFY_DIR], { cwd: root, env, stdio: "ignore" }); + return execFileSync("git", ["write-tree"], { cwd: root, env, encoding: "utf8" }).trim(); + } catch { + return null; + } finally { + rmSync(tmp, { recursive: true, force: true }); + } +} + +// Files that define how a change is judged. A change to one of them is a change to the checks +// themselves, so it is never verified by those checks alone: it lands in merge tier 3. +export const DEFAULT_GUARD = [ + CONFIG_PATH, + ".claude/settings.json", + ".claude/settings.local.json", + ".claude/hooks/**", + ".github/workflows/**", + ".github/CODEOWNERS", + ".husky/**", + "**/.pre-commit-config.yaml", + "**/playwright.config.*", + "**/vitest.config.*", + "**/vitest.workspace.*", + "**/jest.config.*", + "**/cypress.config.*", + "**/eslint.config.*", + "**/.eslintrc*", + "**/biome.json", + "**/biome.jsonc", + "**/tsconfig*.json", + "**/.stylelintrc*", + "**/pytest.ini", + "**/conftest.py", + "**/.golangci.y*ml", + "**/scripts/ui/check-raw-styles.mjs", + "**/e2e/ui-look/**/*.{ts,js,json}", +]; + +// Lines in a test file that switch a test off, focus a run on a few tests, or loosen a visual +// comparison: tier 3. Lines anywhere that silence a type or lint check, or retry and wait longer: +// tier 2, because they are common and often fine, but a person should see them. +const WEAKENING_TESTS = [ + [/\b(?:it|test|describe|context|suite)\.(?:skip|only|todo|fixme)\s*\(/, "skips or focuses tests"], + [/\b(?:xit|xdescribe|xtest|fit|fdescribe)\s*\(/, "skips or focuses tests"], + [/@pytest\.mark\.(?:skip|skipif|xfail)\b|@unittest\.skip|pytest\.skip\(/, "skips tests"], + [/\bt\.Skip(?:Now|f)?\(|#\[ignore\]/, "skips tests"], + [/\b(?:maxDiffPixels|maxDiffPixelRatio|threshold)\s*:/, "loosens a screenshot comparison"], + [/\bmask\s*:\s*\[/, "masks part of a screenshot"], +]; +const SILENCING = [ + [/@ts-(?:ignore|nocheck|expect-error)\b|eslint-disable|biome-ignore|#\s*type:\s*ignore|#\s*noqa\b|\/\/\s*nolint\b/, "silences a type or lint check"], + [/\b(?:retries|retry)\s*[:=(]\s*\d/, "adds retries"], +]; + +/** + * Changes that weaken or redefine the checks. [{ path, why, tier }] + * - tier 3: a guard file changed or was deleted, a test file was deleted, or a test file gained a + * line that skips, focuses or loosens a check; + * - tier 2: any changed file gained a line that silences a type or lint check, or adds retries. + */ +export function guardChanges(cfg, changes = changedSince(cfg.root, cfg.base)) { + const out = []; + const isTest = (p) => matchAny(cfg.tests, p); + const isGuard = (p) => matchAny(cfg.guard, p); + for (const c of changes) { + if (isGuard(c.path)) out.push({ path: c.path, why: c.status === "D" ? "check file deleted" : "check or tool config changed", tier: 3 }); + else if (c.status === "D" && isTest(c.path)) out.push({ path: c.path, why: "test file deleted", tier: 3 }); + } + const added = addedLinesByFile(cfg.root, cfg.base); + for (const c of changes.filter((c) => c.status !== "D" && !isGuard(c.path) && !c.path.startsWith(`${VERIFY_DIR}/`))) { + const lines = added.get(c.path) ?? readLines(join(cfg.root, c.path)); + const rules = [...(isTest(c.path) ? WEAKENING_TESTS.map((r) => [...r, 3]) : []), ...SILENCING.map((r) => [...r, 2])]; + const seen = new Set(); + for (const [re, why, tier] of rules) { + if (seen.has(why) || !lines.some((l) => re.test(l))) continue; + seen.add(why); + out.push({ path: c.path, why: `${isTest(c.path) ? "a test" : "the code"} ${why}`, tier }); + } + } + return out; +} + +/** Lines added since base, per tracked file, from one diff. Untracked files are not in it. */ +function addedLinesByFile(root, base) { + const out = new Map(); + if (!base) return out; + let current = null; + for (const line of gitLines(root, ["diff", "--unified=0", "--no-renames", "--no-color", base])) { + if (line.startsWith("+++ ")) { + current = line === "+++ /dev/null" ? null : line.slice(6); + if (current && !out.has(current)) out.set(current, []); + } else if (current && line.startsWith("+")) out.get(current).push(line.slice(1)); + } + return out; +} + +function readLines(file) { + try { + return readFileSync(file, "utf8").split("\n"); + } catch { + return []; + } +} + +/** A file's content at a commit (a string, or a Buffer with { buffer: true }), or null when it does not exist there. */ +export function gitShow(root, ref, path, { buffer = false } = {}) { + try { + return execFileSync("git", ["show", `${ref}:${path}`], { cwd: root, ...(buffer ? {} : { encoding: "utf8" }), maxBuffer: 64 << 20, stdio: ["ignore", "pipe", "ignore"] }); + } catch { + return null; + } +} + export function gitLines(root, argv) { try { return execFileSync("git", argv, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }) diff --git a/plugins/workflow/scripts/make-evidence.mjs b/plugins/workflow/scripts/make-evidence.mjs index 186fcee..1984aca 100644 --- a/plugins/workflow/scripts/make-evidence.mjs +++ b/plugins/workflow/scripts/make-evidence.mjs @@ -7,6 +7,12 @@ // node make-evidence.mjs [--root ] [--pr] // // --pr also prints a pull request body (text only) to stdout. +// +// "The change" is everything that differs from the base commit (the merge-base with the default +// branch, or VERIFY_BASE): commits on this branch, staged, unstaged and untracked files, deletions. +// The pack names the working tree's hash; it is ready only when every lane's run and review name +// that same tree. Guarded changes (the checks themselves, deleted tests, skipped or loosened tests) +// raise the tier: lib/verify-config.mjs guardChanges. // Exit 0 always unless the inputs are missing (2). import { execFileSync } from "node:child_process"; import { copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; @@ -14,14 +20,15 @@ import { basename, dirname, join, relative, resolve } from "node:path"; import { acceptanceIds, acceptanceLines, + changedSince, contractPaths, - gitLines, + guardChanges, inLane, loadConfig, matchAny, OPEN_LINE, readJson, - workingChanges, + treeHash, } from "./lib/verify-config.mjs"; const args = process.argv.slice(2); @@ -37,10 +44,14 @@ if (!cfg || !last?.lanes) { const runDir = last.runDir; const rel = (f) => relative(runDir, f).split("\\").join("/"); -// What this change touched: uncommitted work plus commits not yet on the upstream or default branch. -const committed = gitLines(root, ["diff", "--name-only", "HEAD@{upstream}...HEAD"]); -const sinceDefault = committed.length ? [] : gitLines(root, ["diff", "--name-only", "origin/HEAD...HEAD"]); -const touched = [...new Set([...workingChanges(root), ...committed, ...sinceDefault])].filter((f) => !f.startsWith(".verify/")); +// What this change touched, measured from the base commit, deletions included. +const allChanges = changedSince(root, cfg.base); +const changes = allChanges.filter((c) => !c.path.startsWith(".verify/")); +const touched = changes.map((c) => c.path); +const guarded = guardChanges(cfg, allChanges); // .verify/config.json is a guard file + +const current = treeHash(root); +const short = (h) => (h ? h.slice(0, 12) : "none"); let lanes = cfg.lanes.filter((l) => touched.some((f) => inLane(l, f))); if (lanes.length === 0) lanes = cfg.lanes.filter((l) => last.lanes[l.name]); @@ -56,6 +67,7 @@ const reviews = lanes.map((lane) => { text, verdict: /^Verdict:\s*(.+)$/im.exec(text)?.[1].trim() ?? "missing", reviewer: /^Reviewer:\s*(.+)$/im.exec(text)?.[1].trim() ?? "not stated", + tree: /^Tree:\s*([0-9a-f]{7,40})\b/im.exec(text)?.[1] ?? null, notChecked: /^Not checked:\s*(.+)$/im.exec(text)?.[1].trim() ?? "not stated", open: lines.filter(OPEN_LINE), deferred: lines.filter((l) => /^\s*-\s*\[-\]/.test(l) && !acceptanceLines(text).includes(l)), @@ -83,25 +95,40 @@ const negativeSkips = lanes.flatMap((l) => (last.lanes[l.name]?.checks ?? []).fi const notChecked = criteria.filter((c) => c.status === "not checked").map((c) => c.id); const lanesReady = lanes.every((l) => last.lanes[l.name]?.result === "pass"); +const staleRuns = lanes.filter((l) => !current || last.lanes[l.name]?.tree !== current).map((l) => l.name); +const staleReviews = reviews.filter((r) => !current || !r.tree || !current.startsWith(r.tree)).map((r) => r.lane.name); const reviewsReady = reviews.every((r) => /^approved\b/i.test(r.verdict) && r.open.length === 0); +const sameTree = staleRuns.length === 0 && staleReviews.length === 0; +const guard3 = guarded.filter((g) => g.tier === 3); +const guard2 = guarded.filter((g) => g.tier === 2); const acceptanceReady = criteria.length > 0 && criteria.every((c) => c.status === "met" || c.status === "not checked"); const why2 = [ baselineChanges.length && "screenshot baselines changed", sharedChanges.length && "shared parts changed", notChecked.length && `acceptance not checked: ${notChecked.join(", ")}`, negativeSkips.length && `source changed with no test change (${negativeSkips.join(", ")})`, + guard2.length && `checks silenced or retried (${[...new Set(guard2.map((g) => g.path))].join(", ")})`, +].filter(Boolean); +const why3 = [ + contractChanges.length && "a contract changed (design, API, data or migrations)", + guard3.length && `the checks themselves changed (${[...new Set(guard3.map((g) => `${g.path}: ${g.why}`))].join("; ")})`, +].filter(Boolean); +const notReady = [ + !lanesReady && "a lane's checks did not pass", + !reviewsReady && "a review is not approved or has open lines", + !acceptanceReady && "an acceptance criterion is not met or not reviewed", + !sameTree && `verified a different tree than the one on disk (${[...staleRuns.map((n) => `run ${n}`), ...staleReviews.map((n) => `review ${n}`)].join(", ")})`, ].filter(Boolean); -const tier = !(lanesReady && reviewsReady && acceptanceReady) - ? { id: "not ready", rule: "Checks, reviews or acceptance did not pass. Do not merge." } - : contractChanges.length - ? { id: "3", rule: "A contract changed (design, API, data or migrations). The owner must confirm before merge." } +const tier = notReady.length + ? { id: "not ready", rule: `${notReady.join("; ")}. Do not merge.` } + : why3.length + ? { id: "3", rule: `${why3.join("; ")}. The owner must confirm before merge.` } : why2.length ? { id: "2", rule: `Look before merge: ${why2.join("; ")}.` } : { id: "1", rule: "Verified and contained. A glance at this page is enough to merge." }; // 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))]; -const changedNow = workingChanges(root); 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) { @@ -125,9 +152,12 @@ for (const f of [acceptancePath, ...reviews.map((r) => r.path)]) if (existsSync( const md = []; md.push(`# Evidence: ${basename(runDir)}`, ""); md.push(`**Merge tier: ${tier.id}.** ${tier.rule}`, ""); +md.push(`Tree: ${current ?? "unknown"}`, `Base: ${cfg.base ?? "none"}`, ""); md.push(`- Lanes: ${lanes.map((l) => l.name).join(", ") || "none"}`); for (const r of reviews) md.push(`- Review ${r.lane.name}: ${r.verdict}, by ${r.reviewer}; ${r.open.length} open, ${r.deferred.length} deferred`); md.push(`- Contract changes: ${list(contractChanges)}`); +md.push(`- Check changes: ${guarded.length ? guarded.map((g) => `${g.path} (${g.why}, tier ${g.tier})`).join(", ") : "none"}`); +md.push(`- Checks read from: ${last.config?.source ?? "working"} config${last.config?.differsFromBase ? " (the working .verify/config.json differs from base)" : ""}`); md.push(`- Baselines changed: ${list(baselineChanges)}`); md.push(`- Shared parts changed: ${list(sharedChanges)}`); for (const r of reviews) md.push(`- Not checked (${r.lane.name}): ${r.notChecked}`); @@ -185,7 +215,9 @@ if (wantPr) { "### Checks", ...lanes.map((l) => `- ${l.name}: ${last.lanes[l.name]?.result ?? "not run"}; review: ${reviews.find((r) => r.lane === l)?.verdict} (${reviews.find((r) => r.lane === l)?.reviewer})`), `- Contract changes: ${list(contractChanges)}`, + `- Check changes: ${guarded.length ? guarded.map((g) => `${g.path} (${g.why})`).join(", ") : "none"}`, `- Baselines changed: ${list(baselineChanges)}`, + `- Verified tree: \`${short(current)}\` against base \`${short(cfg.base)}\``, ...(pages.size ? [`- Pages verified: ${[...pages.values()].map((p) => `${p.name} (${p.widths.map((w) => w.width).join("/")})`).join(", ")}`] : []), `- Deferred follow-ups: ${deferred.length ? "" : "none"}`, ...deferred, @@ -203,11 +235,11 @@ function beforeImage(name, width) { const out = join(runDir, "before", basename(match)); mkdirSync(dirname(out), { recursive: true }); try { - const bytes = execFileSync("git", ["show", `HEAD:${relPath}`], { cwd: root, maxBuffer: 64 << 20, stdio: ["ignore", "pipe", "ignore"] }); + const bytes = execFileSync("git", ["show", `${cfg.base ?? "HEAD"}:${relPath}`], { cwd: root, maxBuffer: 64 << 20, stdio: ["ignore", "pipe", "ignore"] }); writeFileSync(out, bytes); return out; } catch { - if (!changedNow.includes(relPath)) { + if (!touched.includes(relPath)) { copyFileSync(match, out); return out; } diff --git a/plugins/workflow/scripts/run-verify.mjs b/plugins/workflow/scripts/run-verify.mjs index 450027e..02fd391 100644 --- a/plugins/workflow/scripts/run-verify.mjs +++ b/plugins/workflow/scripts/run-verify.mjs @@ -3,6 +3,7 @@ // .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 ] +// [--config base|working] [--base ] // 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") // @@ -12,12 +13,21 @@ // { "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. +// +// 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. +// --config working uses the working copy: for a change that sets up or extends the checks. That +// change is a guarded change (merge tier 3) either way. +// +// The run records a hash of the working tree (lib/verify-config.mjs treeHash). The Stop gate and +// make-evidence compare it with the tree now and with the one each review names, instead of +// 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 { join, resolve } from "node:path"; import { backupExists, restore, runNegative } from "./lib/negative.mjs"; -import { legacyConfigExists, loadConfig, readJson, VERIFY_DIR } from "./lib/verify-config.mjs"; +import { legacyConfigExists, loadConfig, readJson, resolveBase, treeHash, VERIFY_DIR } from "./lib/verify-config.mjs"; const args = process.argv.slice(2); const opt = (name) => { @@ -28,7 +38,12 @@ const root = resolve(opt("root") ?? process.cwd()); if (args.includes("--migrate")) process.exit(migrate()); -const cfg = loadConfig(root); +const configSource = opt("config") ?? "base"; +if (!["base", "working"].includes(configSource)) { + console.error('run-verify: --config takes "base" or "working".'); + process.exit(2); +} +const cfg = loadConfig(root, { source: configSource, base: opt("base") ? resolveBase(root, opt("base")) : undefined }); if (!cfg) { console.error( legacyConfigExists(root) @@ -61,12 +76,28 @@ if (lanes.every((l) => l.checks.filter((c) => !only || only.includes(c.name)).le process.exit(2); } +if (cfg.workingDiffers && cfg.source === "base") { + console.log( + "run-verify: .verify/config.json differs from the base commit; running the base's checks. For a change that sets up or extends the checks, rerun with --config working (the change is merge tier 3 either way).", + ); +} +if (cfg.source === "working" && configSource === "base") console.log("run-verify: no .verify/config.json on the base commit; using the working copy."); + +const treeBefore = treeHash(root); const startedAt = new Date(); const runDir = join(cfg.dir, "runs", startedAt.toISOString().replace(/[:.]/g, "-")); mkdirSync(runDir, { recursive: true }); const previous = readJson(join(cfg.dir, "last-run.json")); -const record = { runDir, finishedAt: null, lanes: { ...(previous?.lanes ?? {}) } }; +const record = { + runDir, + finishedAt: null, + tree: null, + base: cfg.base, + config: { source: cfg.source, differsFromBase: cfg.workingDiffers }, + lanes: { ...(previous?.lanes ?? {}) }, +}; +const ranLanes = []; let anyFailed = false; for (const lane of lanes) { @@ -105,11 +136,30 @@ for (const lane of lanes) { finishedAt: new Date().toISOString(), result: failed.length ? "fail" : only ? "partial" : "pass", runDir, + tree: null, + config: cfg.source, checks: results, }; + ranLanes.push(lane.name); console.log(`run-verify: lane ${lane.name}: ${record.lanes[lane.name].result}${failed.length ? ` (failed: ${failed.map((f) => f.name).join(", ")})` : ""}`); } +// The tree the checks saw. A check that wrote to tracked or untracked source files (a formatter in +// write mode, a code generator) makes the run unusable: what passed is not what is on disk. +const treeAfter = treeHash(root); +record.tree = treeAfter; +for (const name of ranLanes) { + record.lanes[name].tree = treeAfter; + if (treeBefore !== treeAfter) { + record.lanes[name].result = "fail"; + record.lanes[name].note = "files changed while the checks ran; a check writes to the source (run formatters in check mode)"; + } +} +if (treeBefore !== treeAfter) { + anyFailed = true; + console.log("run-verify: files changed while the checks ran, so the result does not describe what is on disk. Run formatters and generators in check mode, then rerun."); +} + record.finishedAt = new Date().toISOString(); writeFileSync(join(cfg.dir, "last-run.json"), JSON.stringify(record, null, 2) + "\n"); diff --git a/plugins/workflow/scripts/stop-gate.mjs b/plugins/workflow/scripts/stop-gate.mjs index b3d1b71..4311ec0 100644 --- a/plugins/workflow/scripts/stop-gate.mjs +++ b/plugins/workflow/scripts/stop-gate.mjs @@ -1,52 +1,71 @@ #!/usr/bin/env node -// Claude Code Stop hook. In a project with .verify/config.json it blocks the end of a turn when -// files of a lane (ui, api, …) changed and that lane is not verified: its last run-verify did not -// pass after the change, its independent review is missing, stale, open or not approved, the -// acceptance criteria are missing or not all accounted for in a review, or the evidence pack is -// older than the reviews. It blocks once per stop (stop_hook_active lets the second attempt through, -// so a turn cannot loop forever). Set UI_WORKFLOW_GATE=off to disable it. -import { existsSync, readFileSync, statSync } from "node:fs"; +// 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 +// 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; +// - the acceptance criteria are missing or not all accounted for in a review; +// - the evidence pack is missing, names a different tree, or is older than a review. +// "Changed" means: the files differ from the base commit (committed on this branch or not, deletions +// included), and the tree differs from the one recorded when the turn started (turn-start.mjs), so a +// 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 +// 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"; import { acceptanceIds, acceptanceLines, + 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 input = readStdin(); -if (process.env.UI_WORKFLOW_GATE === "off" || input.stop_hook_active) process.exit(0); +if (mode === "off") process.exit(0); const root = gitRoot(input.cwd ?? process.cwd()); if (!root) process.exit(0); -const changed = workingChanges(root); if (legacyConfigExists(root)) { - const ui = changed.filter((f) => /\.(tsx|jsx|vue|svelte|html|css|scss)$/.test(f)); - if (ui.length) 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."]); + 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); +const changes = changedSince(root, cfg.base); const required = cfg.lanes - .map((lane) => ({ lane, files: changed.filter((f) => inLane(lane, f)) })) + .map((lane) => ({ lane, files: changes.filter((c) => inLane(lane, c.path)).map((c) => c.path) })) .filter((x) => x.files.length); if (required.length === 0) process.exit(0); +const current = treeHash(root); +const turn = readJson(join(cfg.dir, "turn.json")); +if (current && turn?.tree === current) process.exit(0); // this turn changed nothing + const last = readJson(join(cfg.dir, "last-run.json")); const problems = []; const reviewTimes = []; const coveredIds = new Set(); +const short = (h) => (h ? h.slice(0, 12) : "none"); + +if (!current) problems.push("could not hash the working tree (git failed); verification cannot be matched to the content."); for (const { lane, files } of required) { - const newest = Math.max(...files.map((f) => statSync(join(root, f)).mtimeMs)); const run = last?.lanes?.[lane.name]; const reviewPath = join(cfg.dir, `review-${lane.name}.md`); const label = `lane ${lane.name} (${preview(files)})`; @@ -54,17 +73,17 @@ for (const { lane, files } of required) { problems.push(`${label}: run-verify has not run this lane.`); continue; } - const finished = Date.parse(run.finishedAt); if (run.result !== "pass") problems.push(`${label}: the last run-verify result is "${run.result}", not "pass".`); - if (finished < newest) problems.push(`${label}: files changed after the last run-verify.`); + if (run.tree !== current) problems.push(`${label}: files changed since the last run-verify (it checked tree ${short(run.tree)}, the tree is now ${short(current)}).`); if (!existsSync(reviewPath)) { problems.push(`${label}: .verify/review-${lane.name}.md is missing (independent review).`); continue; } const review = readFileSync(reviewPath, "utf8"); - const reviewTime = statSync(reviewPath).mtimeMs; - reviewTimes.push(reviewTime); - if (reviewTime < finished) problems.push(`${label}: its review is older than the last run-verify.`); + reviewTimes.push(statSync(reviewPath).mtimeMs); + const reviewed = reviewTree(review); + if (!reviewed) problems.push(`${label}: its review has no "Tree:" line naming the tree it reviewed (lanes.${lane.name}.tree in last-run.json).`); + else if (current && !current.startsWith(reviewed)) problems.push(`${label}: its review is of tree ${short(reviewed)}, not the current tree ${short(current)}.`); const open = review.split("\n").filter(OPEN_LINE); if (open.length) problems.push(`${label}: its review still has ${open.length} open or failing line(s).`); if (!/^Verdict:\s*approved\b/im.test(review)) problems.push(`${label}: its review does not say "Verdict: approved".`); @@ -82,16 +101,47 @@ else { const evidencePath = last?.runDir ? join(last.runDir, "evidence.md") : ""; if (!evidencePath || !existsSync(evidencePath)) problems.push("the evidence pack is missing: run make-evidence.mjs after the reviews."); -else if (reviewTimes.some((t) => statSync(evidencePath).mtimeMs < t)) problems.push("the evidence pack is older than a review: run make-evidence.mjs again."); +else { + const evidenceTree = /^Tree:\s*([0-9a-f]+)/im.exec(readFileSync(evidencePath, "utf8"))?.[1]; + if (evidenceTree !== current) problems.push("the evidence pack is of another tree: run make-evidence.mjs again."); + if (reviewTimes.some((t) => statSync(evidencePath).mtimeMs < t)) problems.push("the evidence pack is older than a review: run make-evidence.mjs again."); +} -if (problems.length === 0) process.exit(0); +if (problems.length === 0) { + log("pass", []); + process.exit(0); +} +if (input.stop_hook_active) { + log("let-through-unverified", problems); + process.exit(0); +} +if (mode === "observe") { + log("would-block", problems); + process.exit(0); +} +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 accounts for every acceptance criterion, then run make-evidence.mjs.", + "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.", "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.", ]); +function reviewTree(text) { + return /^Tree:\s*([0-9a-f]{7,40})\b/im.exec(text)?.[1] ?? null; +} + +function log(decision, list) { + try { + appendFileSync( + join(cfg.dir, "gate.log"), + JSON.stringify({ at: new Date().toISOString(), mode, decision, tree: current, session: input.session_id ?? null, problems: list }) + "\n", + ); + } catch { + // logging never decides anything + } +} + function block(lines) { process.stdout.write(JSON.stringify({ decision: "block", reason: lines.join("\n") }) + "\n"); process.exit(0); diff --git a/plugins/workflow/scripts/turn-start.mjs b/plugins/workflow/scripts/turn-start.mjs new file mode 100644 index 0000000..f0c3de0 --- /dev/null +++ b/plugins/workflow/scripts/turn-start.mjs @@ -0,0 +1,23 @@ +#!/usr/bin/env node +// Claude Code UserPromptSubmit hook. Records the working tree's hash when a turn starts +// (.verify/turn.json), so the Stop gate checks a turn only when it changed the content, committed or +// not, and leaves turns that only talked alone. Does nothing in a project without .verify/. +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { gitRoot, treeHash, VERIFY_DIR } from "./lib/verify-config.mjs"; + +let input = {}; +try { + const raw = readFileSync(0, "utf8"); + input = raw.trim() ? JSON.parse(raw) : {}; +} catch { + input = {}; +} +const root = gitRoot(input.cwd ?? process.cwd()); +if (!root || !existsSync(join(root, VERIFY_DIR))) process.exit(0); +const tree = treeHash(root); +if (tree) { + mkdirSync(join(root, VERIFY_DIR), { recursive: true }); + writeFileSync(join(root, VERIFY_DIR, "turn.json"), JSON.stringify({ tree, startedAt: new Date().toISOString(), session: input.session_id ?? null }) + "\n"); +} +process.exit(0); diff --git a/plugins/workflow/shared/verify.config.json b/plugins/workflow/shared/verify.config.json index b8efb67..43402dc 100644 --- a/plugins/workflow/shared/verify.config.json +++ b/plugins/workflow/shared/verify.config.json @@ -1,4 +1,5 @@ { + "guard": [], "tests": ["**/test/**", "**/tests/**", "**/__tests__/**", "**/e2e/**", "**/journeys/**", "**/*.{test,spec,e2e}.*", "**/*_test.*", "**/test_*.py", "**/*-snapshots/**"], "lanes": { "ui": { diff --git a/plugins/workflow/skills/building-consistent-ui/design-review.md b/plugins/workflow/skills/building-consistent-ui/design-review.md index 200f970..5ac01ca 100644 --- a/plugins/workflow/skills/building-consistent-ui/design-review.md +++ b/plugins/workflow/skills/building-consistent-ui/design-review.md @@ -79,6 +79,7 @@ high-conviction findings beat a long list. ```markdown # Review Reviewer: +Tree: Scope: Focal point: : ; … diff --git a/plugins/workflow/skills/building-consistent-ui/setup.md b/plugins/workflow/skills/building-consistent-ui/setup.md index b0dec2f..14eac69 100644 --- a/plugins/workflow/skills/building-consistent-ui/setup.md +++ b/plugins/workflow/skills/building-consistent-ui/setup.md @@ -60,7 +60,7 @@ states, tables, navigation). Copy the numbers into design.md's UX rules. Ignore ## 6. Wire the checks -1. The project must be a git repository (the Stop gate reads `git status` and is off without one). +1. The project must be a git repository (the Stop gate reads git and is off without one). If it is not, ask the user before running `git init`. 2. Copy `/scripts/check-raw-styles.mjs` to `scripts/ui/` in the project. In its check command pass `--allow ` (shadcn's `components/ui`): that folder is where @@ -100,8 +100,11 @@ states, tables, navigation). Copy the numbers into design.md's UX rules. Ignore first page you build creates its baseline the same way (verify.md, New pages). Write the OS or container used in design.md's Baselines line; Playwright adds it to snapshot names (`-linux`, `-darwin`), so later updates must run there too. -9. If pages exist, run `node /scripts/run-verify.mjs` and follow `verify.md` once end to - end. If none exist, the first build does this. +9. If pages exist, run `node /scripts/run-verify.mjs --config working` and follow `verify.md` + once end to end. If none exist, the first build does this. (`--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 to the checks themselves runs with + `--config working` and is merge tier 3.) ## Asking a user who is not a designer diff --git a/plugins/workflow/skills/building-consistent-ui/verify.md b/plugins/workflow/skills/building-consistent-ui/verify.md index 9e5914b..bed72aa 100644 --- a/plugins/workflow/skills/building-consistent-ui/verify.md +++ b/plugins/workflow/skills/building-consistent-ui/verify.md @@ -36,8 +36,8 @@ The user asked for: . Scope: . Deferred Should-fixes (record as "- [-]" follow-ups if still present): . Baselines updated in this change (copy into the review): . -Write .verify/review-ui.md as design-review.md step 5 shows, with "Reviewer: " under -the title. Do not edit any other file. Reply with the verdict and the Blocker lines. +Write .verify/review-ui.md as design-review.md step 5 shows, with "Reviewer: " and +"Tree: " under the title. Do not edit any other file. Reply with the verdict and the Blocker lines. ``` Then: @@ -53,8 +53,9 @@ Then: 5. No subagent tool here: review it yourself with `design-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 `.verify/review-ui.md` is newer than the run, -has no open `- [ ]` line, accounts for every acceptance id, and says `Verdict: approved`. It lets the second attempt through so a turn +The Stop gate blocks your first attempt to stop until the run and `.verify/review-ui.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. ## Evidence pack and merge tier @@ -67,9 +68,9 @@ findings and what was not checked. The Stop gate requires it and requires it new | Tier | When | Who must look | | --- | --- | --- | | 1 | checks pass, review approved, every criterion met, nothing below | a glance at evidence.md is enough to merge | -| 2 | baselines updated, a shared part changed (`shared` in config), or a criterion "not checked" | the user looks at every before/after pair and the unchecked criteria | -| 3 | `docs/design.md` or a token file changed (`tokens` in config), or an api contract or migration | the user confirms the contract change before merge | -| not ready | checks failed, review not approved, a criterion not met or not reviewed | nobody merges | +| 2 | baselines updated, a shared part changed (`shared` in config), a criterion "not checked", or a check silenced in the code (`@ts-ignore`, `eslint-disable`) | the user looks at every before/after pair and the unchecked criteria | +| 3 | `docs/design.md` or a token file changed (`tokens` in config), or an api contract or migration; or the checks themselves changed: `.verify/config.json`, `playwright.config.*`, the look tests, lint or CI config, a deleted test, a test that skips, masks or loosens a comparison | the user confirms before merge | +| not ready | checks failed, review not approved, a criterion not met or not reviewed, or the run or the review is of a different tree than the one on disk | nobody merges | The tier is computed, never chosen. When you open a pull request, put the `--pr` output at the top of its body, and attach the screenshots and recordings (or link the CI artifact of the run folder). diff --git a/plugins/workflow/skills/building-reliable-backend/code-review.md b/plugins/workflow/skills/building-reliable-backend/code-review.md index a935cb4..a888d41 100644 --- a/plugins/workflow/skills/building-reliable-backend/code-review.md +++ b/plugins/workflow/skills/building-reliable-backend/code-review.md @@ -65,6 +65,7 @@ touch. A few findings you are sure of beat a long list; say how sure you are whe ```markdown # Review Reviewer: +Tree: Scope: ..; ## Acceptance diff --git a/plugins/workflow/skills/building-reliable-backend/setup.md b/plugins/workflow/skills/building-reliable-backend/setup.md index 9ef1dd1..8887a40 100644 --- a/plugins/workflow/skills/building-reliable-backend/setup.md +++ b/plugins/workflow/skills/building-reliable-backend/setup.md @@ -65,5 +65,8 @@ 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`. Every check must pass on the unchanged - code; fix the setup, or tell the user which check is red before any change and why. +6. Run `node /scripts/run-verify.mjs --lane api --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 + to the checks themselves runs with `--config working` and is merge tier 3.) diff --git a/plugins/workflow/skills/building-reliable-backend/verify.md b/plugins/workflow/skills/building-reliable-backend/verify.md index 4c38860..ccc62ea 100644 --- a/plugins/workflow/skills/building-reliable-backend/verify.md +++ b/plugins/workflow/skills/building-reliable-backend/verify.md @@ -47,7 +47,8 @@ Read: docs/backend.md, .verify/acceptance.md, .verify/last-run.json (lanes.api), (git diff ), and the logs it names. The user asked for: . Deferred findings from earlier rounds (record as "- [-]" if still present): . -Write .verify/review-api.md as code-review.md shows, with "Reviewer: " under the title. +Write .verify/review-api.md as code-review.md shows, with "Reviewer: " and +"Tree: " under the title. Do not edit any other file. Reply with the verdict and the Blocker lines. ``` @@ -70,9 +71,10 @@ After the review, `node /scripts/make-evidence.mjs` (add `--pr` for a pu | Tier | When | Who must look | | --- | --- | --- | | 1 | checks pass, review approved, every criterion met, nothing below | a glance at evidence.md | -| 2 | a shared module changed, a criterion "not checked", source changed with no test change, baselines updated | the user reads the evidence and the flagged parts of the diff | -| 3 | `docs/backend.md`, the contract file or a migration changed | the user confirms before merge | -| not ready | a check failed, the review is not approved, a criterion not met or not reviewed | nobody merges | +| 2 | a shared module changed, a criterion "not checked", source changed with no test change, baselines updated, a check silenced in the code (`@ts-ignore`, `eslint-disable`, `noqa`) or retries added | the user reads the evidence and the flagged parts of the diff | +| 3 | `docs/backend.md`, the contract file or a migration changed; or the checks themselves changed: `.verify/config.json`, a test, lint or CI config, a deleted test, a test that skips, focuses or loosens a check | the user confirms before merge | +| not ready | a check failed, the review is not approved, a criterion not met or not reviewed, or the run or the review is of a different tree than the one on disk | nobody merges | -The tier is computed, never chosen. Your final message is at least two lines: the evidence.md path and +The tier is computed, never chosen. The checks come from `.verify/config.json` on the base commit; +a change that edits them reruns with `--config working`, and is tier 3 either way. Your final message is at least two lines: the evidence.md path and the tier, then deferred follow-ups, criteria not checked, and checks that could not run (or "none"). diff --git a/test/helpers.mjs b/test/helpers.mjs new file mode 100644 index 0000000..76e03fe --- /dev/null +++ b/test/helpers.mjs @@ -0,0 +1,135 @@ +// 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. +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"); + +const GIT_ENV = { + GIT_AUTHOR_NAME: "test", + GIT_AUTHOR_EMAIL: "test@example.com", + GIT_COMMITTER_NAME: "test", + GIT_COMMITTER_EMAIL: "test@example.com", + GIT_CONFIG_NOSYSTEM: "1", + GIT_CONFIG_GLOBAL: "/dev/null", +}; + +export const CONFIG = { + lanes: { + api: { + files: ["src/**", "test/**"], + checks: [ + { name: "unit", run: "node test/run.mjs" }, + { name: "negative", negative: { test: "node test/run.mjs" } }, + ], + }, + }, +}; + +export function git(cwd, ...args) { + return execFileSync("git", args, { cwd, encoding: "utf8", env: { ...process.env, ...GIT_ENV }, stdio: ["ignore", "pipe", "pipe"] }).trim(); +} + +/** A project committed on origin/main, checked out on branch "feature". Returns its path. */ +export function makeProject({ config = CONFIG, files = {} } = {}) { + const base = mkdtempSync(join(tmpdir(), "uiwf-")); + const origin = join(base, "origin.git"); + const root = join(base, "project"); + git(base, "init", "-q", "--bare", "-b", "main", origin); + mkdirSync(root); + git(root, "init", "-q", "-b", "main"); + write(root, { + ".gitignore": ".verify/*\n!.verify/config.json\nnode_modules/\n", + ".verify/config.json": JSON.stringify(config, null, 2), + "src/math.mjs": "export const add = (a, b) => a + b;\n", + "test/run.mjs": 'import { add } from "../src/math.mjs";\nif (add(2, 2) !== 4) { console.error("add broken"); process.exit(1); }\nconsole.log("ok");\n', + "test/other.test.mjs": "// another test file\n", + ...files, + }); + git(root, "add", "-A"); + git(root, "commit", "-q", "-m", "base"); + git(root, "remote", "add", "origin", origin); + git(root, "push", "-q", "origin", "main"); + git(root, "remote", "set-head", "origin", "main"); + git(root, "checkout", "-q", "-b", "feature"); + return root; +} + +export function cleanup(root) { + rmSync(dirname(root), { recursive: true, force: true }); +} + +export function write(root, files) { + for (const [path, content] of Object.entries(files)) { + const p = join(root, path); + mkdirSync(dirname(p), { recursive: true }); + writeFileSync(p, content); + } +} + +export function read(root, path) { + return readFileSync(join(root, path), "utf8"); +} + +export function node(script, args = [], { cwd, input, env = {} } = {}) { + const r = spawnSync(process.execPath, [join(SCRIPTS, script), ...args], { + cwd, + input: input === undefined ? "" : typeof input === "string" ? input : JSON.stringify(input), + encoding: "utf8", + env: { ...process.env, ...GIT_ENV, VERIFY_BASE: "", UI_WORKFLOW_GATE: "", ...env }, + }); + return { code: r.status, stdout: r.stdout, stderr: r.stderr }; +} + +/** Runs the Stop gate; returns the parsed block decision or null when it let the turn end. */ +export function gate(root, input = {}, env = {}) { + const r = node("stop-gate.mjs", [], { cwd: root, input: { cwd: root, ...input }, env }); + return r.stdout.trim() ? JSON.parse(r.stdout) : null; +} + +/** Feature change that adds behaviour plus a test that only passes with it. */ +export function addFeature(root) { + write(root, { + "src/math.mjs": "export const add = (a, b) => a + b;\nexport const sub = (a, b) => a - b;\n", + "test/run.mjs": + 'import * as m from "../src/math.mjs";\nif (m.add(2, 2) !== 4) { console.error("add broken"); process.exit(1); }\nif (typeof m.sub !== "function" || m.sub(5, 3) !== 2) { console.error("sub broken"); process.exit(1); }\nconsole.log("ok");\n', + }); +} + +/** Everything the gate asks for: a passing run, acceptance, an approved review naming the run's tree, evidence. */ +export function verify(root, { runArgs = [], reviewTree } = {}) { + 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-api.md": [ + `# Review ${last.lanes.api.runDir}`, + "Reviewer: test", + `Tree: ${reviewTree ?? last.lanes.api.tree}`, + "", + "## Acceptance", + "- [x] A1 met · test/run.mjs passed", + "", + "## Findings", + "- Note · none", + "", + "Verdict: approved", + "", + ].join("\n"), + }); + const evidence = node("make-evidence.mjs", [], { cwd: root }); + return { run, evidence, last }; +} + +export function tierOf(root) { + const last = JSON.parse(read(root, ".verify/last-run.json")); + return /\*\*Merge tier: ([^.*]+)\.\*\*/.exec(readFileSync(join(last.runDir, "evidence.md"), "utf8"))?.[1]; +} + +export function evidenceText(root) { + const last = JSON.parse(read(root, ".verify/last-run.json")); + return readFileSync(join(last.runDir, "evidence.md"), "utf8"); +} diff --git a/test/make-evidence.test.mjs b/test/make-evidence.test.mjs new file mode 100644 index 0000000..fb83fbe --- /dev/null +++ b/test/make-evidence.test.mjs @@ -0,0 +1,79 @@ +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 { addFeature, cleanup, CONFIG, evidenceText, git, makeProject, node, read, tierOf, verify, write } from "./helpers.mjs"; + +const roots = []; +const project = (opts) => { + const r = makeProject(opts); + roots.push(r); + return r; +}; +after(() => roots.forEach(cleanup)); + +describe("make-evidence merge tier", () => { + it("tier 1 for a verified, contained change, naming the tree", () => { + const root = project(); + addFeature(root); + verify(root); + assert.equal(tierOf(root), "1"); + assert.match(evidenceText(root), new RegExp(`^Tree: ${treeHash(root)}$`, "m")); + }); + + 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" } }); + addFeature(root); + write(root, { "openapi.yaml": "v2\n" }); + git(root, "add", "-A"); + git(root, "commit", "-q", "-m", "feature"); + git(root, "push", "-q", "-u", "origin", "feature"); + verify(root); + assert.equal(tierOf(root), "3"); + assert.match(evidenceText(root), /Contract changes: `openapi.yaml`/); + }); + + it("tier 3 when the checks themselves changed", () => { + const root = project(); + addFeature(root); + write(root, { ".verify/config.json": JSON.stringify({ ...CONFIG, tests: ["test/**"] }) }); + verify(root, { runArgs: ["--config", "working"] }); + assert.equal(tierOf(root), "3"); + assert.match(evidenceText(root), /the checks themselves changed \(\.verify\/config\.json/); + }); + + it("tier 3 when a test file was deleted", () => { + const root = project(); + addFeature(root); + rmSync(join(root, "test/other.test.mjs")); + verify(root); + assert.equal(tierOf(root), "3"); + assert.match(evidenceText(root), /test\/other\.test\.mjs: test file deleted/); + }); + + it("tier 2 when the code silences a check", () => { + const root = project(); + addFeature(root); + write(root, { "src/math.mjs": "// @ts-expect-error\n" + read(root, "src/math.mjs") }); + verify(root); + assert.equal(tierOf(root), "2"); + }); + + it("not ready when the review is of another tree", () => { + const root = project(); + 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\)/); + }); + + it("prints a PR body with the check changes and the tree", () => { + const root = project(); + addFeature(root); + verify(root); + const pr = node("make-evidence.mjs", ["--pr"], { cwd: root }); + assert.match(pr.stdout, /Check changes: none/); + assert.match(pr.stdout, /Verified tree: `[0-9a-f]{12}`/); + }); +}); diff --git a/test/run-verify.test.mjs b/test/run-verify.test.mjs new file mode 100644 index 0000000..6dfd804 --- /dev/null +++ b/test/run-verify.test.mjs @@ -0,0 +1,93 @@ +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 { addFeature, cleanup, makeProject, node, read, write } from "./helpers.mjs"; + +const roots = []; +const project = (opts) => { + const r = makeProject(opts); + roots.push(r); + return r; +}; +after(() => roots.forEach(cleanup)); +const lastRun = (root) => JSON.parse(read(root, ".verify/last-run.json")); + +describe("run-verify", () => { + it("records a pass with the tree it checked and where the config came from", () => { + const root = project(); + addFeature(root); + 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.config.source, "base"); + assert.match(last.lanes.api.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" }] } } }), + "src/math.mjs": "export const add = (a, b) => a - b;\n", + }); + const r = node("run-verify.mjs", [], { cwd: root }); + assert.equal(r.code, 1, r.stdout); + assert.match(r.stdout, /differs from the base commit; running the base's checks/); + const wk = node("run-verify.mjs", ["--config", "working"], { cwd: root }); + assert.equal(wk.code, 0, wk.stdout); + assert.equal(lastRun(root).config.source, "working"); + }); + + 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')\"" }] } } }, + }); + 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"); + }); + + it("refuses to run while a crashed negative check left a backup, and restores it", () => { + const root = project(); + write(root, { ".verify/negative-backup/manifest.json": JSON.stringify({ files: [{ path: "src/math.mjs", existed: true }] }), ".verify/negative-backup/files/src/math.mjs": "export const add = (a, b) => a + b; // original\n", "src/math.mjs": "reverted\n" }); + assert.equal(node("run-verify.mjs", [], { cwd: root }).code, 2); + assert.equal(node("run-verify.mjs", ["--restore"], { cwd: root }).code, 0); + assert.match(read(root, "src/math.mjs"), /original/); + assert.equal(existsSync(join(root, ".verify/negative-backup")), false); + }); +}); + +describe("negative check", () => { + it("fails when the changed tests pass without the source change", () => { + const root = project(); + write(root, { + "src/math.mjs": "export const add = (a, b) => a + b;\nexport const sub = (a, b) => a - b;\n", + "test/run.mjs": read(root, "test/run.mjs") + "// touched\n", + }); + 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/); + }); + + it("puts the source back after reverting it, binary files included", () => { + const root = project({ files: { "src/logo.bin": Buffer.from([0, 255, 1, 254, 128]) } }); + addFeature(root); + write(root, { "src/logo.bin": Buffer.from([9, 200, 0, 7]) }); + const before = treeHash(root); + const r = node("run-verify.mjs", ["--only", "negative"], { cwd: root }); + assert.equal(r.code, 0, r.stdout); + assert.equal(treeHash(root), before); + }); + + it("only reports a source change that came with no test change", () => { + 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/); + }); +}); + diff --git a/test/stop-gate.test.mjs b/test/stop-gate.test.mjs new file mode 100644 index 0000000..95e505b --- /dev/null +++ b/test/stop-gate.test.mjs @@ -0,0 +1,110 @@ +import assert from "node:assert/strict"; +import { rmSync } from "node:fs"; +import { join } from "node:path"; +import { after, describe, it } from "node:test"; +import { addFeature, cleanup, gate, git, makeProject, node, read, verify, write } from "./helpers.mjs"; + +const roots = []; +const project = (opts) => { + const r = makeProject(opts); + roots.push(r); + return r; +}; +after(() => roots.forEach(cleanup)); +const gateLog = (root) => + read(root, ".verify/gate.log") + .trim() + .split("\n") + .map((l) => JSON.parse(l)); + +describe("stop gate", () => { + it("lets a turn end when no lane file changed", () => { + const root = project(); + write(root, { "README.md": "docs\n" }); + assert.equal(gate(root), null); + }); + + it("blocks an unverified lane change", () => { + const root = project(); + addFeature(root); + const d = gate(root); + assert.equal(d.decision, "block"); + assert.match(d.reason, /run-verify has not run this lane/); + }); + + it("lets a fully verified change end, and blocks again after an edit", () => { + const root = project(); + addFeature(root); + const { run, evidence } = verify(root); + assert.equal(run.code, 0, run.stdout); + assert.equal(evidence.code, 0, evidence.stderr); + assert.equal(gate(root), null); + write(root, { "src/math.mjs": read(root, "src/math.mjs") + "// later edit\n" }); + const d = gate(root); + assert.match(d.reason, /files changed since the last run-verify/); + assert.match(d.reason, /its review is of tree/); + }); + + it("does not trust file times: touching nothing but re-saving the same content still passes", () => { + const root = project(); + addFeature(root); + verify(root); + write(root, { "src/math.mjs": read(root, "src/math.mjs") }); + assert.equal(gate(root), null); + }); + + it("blocks a review that names another tree or none", () => { + const root = project(); + 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, "") }); + assert.match(gate(root).reason, /has no "Tree:" line/); + }); + + it("still checks a change that was committed during the turn", () => { + const root = project(); + addFeature(root); + git(root, "add", "-A"); + git(root, "commit", "-q", "-m", "feature"); + assert.equal(gate(root).decision, "block"); + }); + + it("checks a deleted lane file", () => { + const root = project(); + rmSync(join(root, "test/other.test.mjs")); + assert.equal(gate(root).decision, "block"); + }); + + it("leaves a turn alone that changed nothing since it started", () => { + const root = project(); + addFeature(root); + node("turn-start.mjs", [], { cwd: root, input: { cwd: root } }); + assert.equal(gate(root), null); + write(root, { "src/math.mjs": read(root, "src/math.mjs") + "// edit in this turn\n" }); + assert.equal(gate(root).decision, "block"); + }); + + it("lets the second stop through and logs it", () => { + const root = project(); + addFeature(root); + assert.equal(gate(root, { stop_hook_active: true }), null); + assert.equal(gateLog(root).at(-1).decision, "let-through-unverified"); + }); + + 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(gateLog(root).at(-1).decision, "would-block"); + assert.equal(gate(root, {}, { UI_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: [] } } }) }); + assert.equal(gate(root).decision, "block"); + }); +}); diff --git a/test/verify-config.test.mjs b/test/verify-config.test.mjs new file mode 100644 index 0000000..fabe771 --- /dev/null +++ b/test/verify-config.test.mjs @@ -0,0 +1,117 @@ +import assert from "node:assert/strict"; +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 { cleanup, CONFIG, git, makeProject, write } from "./helpers.mjs"; + +const roots = []; +const project = (opts) => { + const r = makeProject(opts); + roots.push(r); + return r; +}; +after(() => roots.forEach(cleanup)); + +describe("globToRegExp", () => { + it("matches any depth, one segment and alternatives", () => { + assert.ok(globToRegExp("src/**").test("src/a/b.ts")); + assert.ok(globToRegExp("**/*.{ts,tsx}").test("a/b/c.tsx")); + assert.ok(!globToRegExp("src/*.ts").test("src/a/b.ts")); + assert.ok(globToRegExp(".verify/config.json").test(".verify/config.json")); + }); +}); + +describe("changedSince", () => { + it("sees commits on the branch, untracked files and deletions", () => { + const root = project(); + write(root, { "src/committed.mjs": "1\n" }); + git(root, "add", "-A"); + git(root, "commit", "-q", "-m", "on branch"); + write(root, { "src/untracked.mjs": "1\n" }); + rmSync(join(root, "test/other.test.mjs")); + const byPath = Object.fromEntries(changedSince(root).map((c) => [c.path, c.status])); + assert.equal(byPath["src/committed.mjs"], "A"); + assert.equal(byPath["src/untracked.mjs"], "A"); + assert.equal(byPath["test/other.test.mjs"], "D"); + }); +}); + +describe("treeHash", () => { + it("changes with content and deletions, not with .verify/ or ignored files", () => { + const root = project(); + const t0 = treeHash(root); + assert.match(t0, /^[0-9a-f]{40}$/); + assert.equal(treeHash(root), t0); + write(root, { ".verify/last-run.json": "{}", "node_modules/x.js": "1" }); + assert.equal(treeHash(root), t0, ".verify and ignored files do not count"); + write(root, { "src/math.mjs": "export const add = (a, b) => b + a;\n" }); + const t1 = treeHash(root); + assert.notEqual(t1, t0); + rmSync(join(root, "test/other.test.mjs")); + assert.notEqual(treeHash(root), t1); + assert.equal(git(root, "status", "--porcelain").includes("A "), false, "the real index is untouched"); + }); +}); + +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: [] } } }) }); + const cfg = loadConfig(root); + assert.equal(cfg.source, "base"); + assert.equal(cfg.workingDiffers, true); + assert.equal(cfg.lanes[0].checks.length, 2); + const working = loadConfig(root, { source: "working" }); + assert.equal(working.source, "working"); + assert.equal(working.lanes[0].checks.length, 0); + }); + + it("uses the working copy when the base has no config", () => { + const root = project(); + git(root, "rm", "-q", "--cached", ".verify/config.json"); + git(root, "commit", "-q", "-m", "drop config"); + git(root, "push", "-q", "origin", "feature:main", "--force"); + git(root, "fetch", "-q", "origin"); + const cfg = loadConfig(root); + assert.equal(cfg.source, "working"); + assert.deepEqual(cfg.lanes.map((l) => l.name), ["api"]); + }); +}); + +describe("guardChanges", () => { + const guards = (root) => guardChanges(loadConfig(root)).map((g) => `${g.tier} ${g.path}: ${g.why}`); + + it("is empty for an ordinary change with a new test", () => { + const root = project(); + write(root, { "src/math.mjs": "export const add = (a, b) => a + b + 0;\n", "test/new.test.mjs": "await page.waitFor({ timeout: 5000 });\n" }); + assert.deepEqual(guards(root), []); + }); + + 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: [] } } }), + "test/run.mjs": "it.skip('adds', () => {});\n", + "playwright.config.ts": "export default {};\n", + }); + rmSync(join(root, "test/other.test.mjs")); + const g = guards(root); + assert.ok(g.includes("3 .verify/config.json: check or tool config changed"), g.join("\n")); + assert.ok(g.includes("3 test/other.test.mjs: test file deleted"), g.join("\n")); + assert.ok(g.includes("3 test/run.mjs: a test skips or focuses tests"), g.join("\n")); + assert.ok(g.includes("3 playwright.config.ts: check or tool config changed"), g.join("\n")); + }); + + it("flags silenced checks in source as tier 2", () => { + const root = project(); + write(root, { "src/math.mjs": "// @ts-ignore\nexport const add = (a, b) => a + b;\n" }); + assert.deepEqual(guards(root), ["2 src/math.mjs: the code silences a type or lint check"]); + }); + + it("looks only at added lines of files that existed on the base", () => { + const root = project({ files: { "src/legacy.mjs": "// eslint-disable-next-line\nexport const x = 1;\n" } }); + write(root, { "src/legacy.mjs": "// eslint-disable-next-line\nexport const x = 2;\n" }); + assert.deepEqual(guards(root), []); + }); +}); From 4d21da2a67db9a35de5174b85bda526532f6bb15 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 18 Nov 2026 09:34:20 +1100 Subject: [PATCH 2/2] Fix test workflow: quote run steps as block scalars Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014d2MvQ5v7FCph37jwFCC7i --- .github/workflows/test.yml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index bb8446f..3e94eff 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -23,7 +23,11 @@ jobs: with: 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 + run: | + for f in plugins/workflow/scripts/*.mjs plugins/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 node -e "JSON.parse(require('fs').readFileSync('$f','utf8'))" || { echo "invalid JSON: $f"; exit 1; }; done + 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 + node -e "JSON.parse(require('fs').readFileSync(process.argv[1], 'utf8'))" "$f" || { echo "invalid JSON: $f"; exit 1; } + done - run: npm test