diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..ce45370 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,8 @@ +# Generated from REVIEW.md › High-risk paths: `node scripts/risk-tier.mjs codeowners > .github/CODEOWNERS`. +# test/risk-tier.test.mjs fails when the two differ. GitHub requests Tom's review +# from it. It enforces nothing: GitHub's code-owner rule needs at least one +# required approval, which would put Tom on every PR, so Risk tier is the gate. +# Rows that count only when a file is deleted (the tests) can't be said here. +/.github/** @tomdebres +/scripts/risk-tier.mjs @tomdebres +/scripts/publish-check.mjs @tomdebres diff --git a/.github/high-risk-paths.md b/.github/high-risk-paths.md new file mode 100644 index 0000000..417604a --- /dev/null +++ b/.github/high-risk-paths.md @@ -0,0 +1,17 @@ +# High-risk paths + +A pull request that touches one of these, or that comes from outside, needs +the maintainer's approval of its head commit before it can merge: the "Risk +tier" check (`scripts/risk-tier.mjs`) reads this table, and +`.github/CODEOWNERS` is generated from it (`node scripts/risk-tier.mjs +codeowners > .github/CODEOWNERS`). Globs are from the repo root; "deleted" rows +count only when a file is deleted or renamed away. + + +| Path | Counts | Why | +|---|---|---| +| `.github/**` | any | CI, review, Risk tier, Publish check, CODEOWNERS and this table: the gates themselves. | +| `scripts/risk-tier.mjs` | any | The matcher Risk tier runs. | +| `scripts/publish-check.mjs` | any | What keeps private details out of this public repo. | +| `test/**` | deleted | A deleted test is a weaker spec. | + diff --git a/.github/workflows/claude-code-review.yml b/.github/workflows/claude-code-review.yml index 554913a..5db7ac4 100644 --- a/.github/workflows/claude-code-review.yml +++ b/.github/workflows/claude-code-review.yml @@ -4,11 +4,9 @@ name: Claude Code Review # keeps the rounds (round 1 the whole diff, later rounds the new commits, three # at most) and decides the check: red only for an open Important finding or the # round cap. Every other failure (token, outage, timeout, turn limit) passes -# with a warning, so an outage never blocks every merge. -# -# devkit's own reviewer (devkit a7a7482, itself bodyops's), copied from heerr -# with only the repo name in the prompt changed; scripts/review-round.mjs and -# test/review-round.test.mjs are devkit's, verbatim. +# with a warning, so an outage never blocks every merge. A fork's +# scripts/review-scope.mjs, if it has one, tells upstream's part of an upstream +# merge from the fork's: a bug in upstream's own code is Upstream, never red. on: pull_request: types: @@ -44,6 +42,32 @@ jobs: continue-on-error: true with: node-version: '22' + # A public repo keeps REVIEW.md in its private notes repo, -notes + # (devkit PLAN.md › Public repos), read with the NOTES_KEY secret, a + # read-only deploy key there. Only REVIEW.md is kept, and the rest goes + # before the review starts, so nothing else of the notes can reach a + # public comment. A fork's PR gets no secret, and no review either. + - name: Notes key + id: notes + continue-on-error: true + env: + KEY: ${{ secrets.NOTES_KEY }} + run: '[ -z "$KEY" ] || echo "repo=${GITHUB_REPOSITORY}-notes" >> "$GITHUB_OUTPUT"' + - name: Private notes + if: steps.notes.outputs.repo + continue-on-error: true + uses: actions/checkout@v4 + with: + repository: ${{ steps.notes.outputs.repo }} + ssh-key: ${{ secrets.NOTES_KEY }} + path: .notes + persist-credentials: false + - name: REVIEW.md from the notes + if: steps.notes.outputs.repo + continue-on-error: true + run: | + if [ ! -e REVIEW.md ] && [ -f .notes/REVIEW.md ]; then cp .notes/REVIEW.md REVIEW.md; fi + rm -rf .notes - name: Plan the round id: plan continue-on-error: true @@ -58,7 +82,7 @@ jobs: claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} github_token: ${{ github.token }} prompt: | - You are the bug reviewer for nockmark pull request #${{ github.event.pull_request.number }}. Report bugs only. + You are the bug reviewer for ${{ github.event.repository.name }} pull request #${{ github.event.pull_request.number }}. Report bugs only. 1. Read REVIEW.md first. "What failure looks like here" is what to look for in this repo; "Findings" is how to tag. 2. The scope of this round is at the end. Review only that; anything else in the PR is context. @@ -68,13 +92,14 @@ jobs: - Important: in code this PR adds or changes, and it would reach a user, the data or a ship: wrong behaviour, a crash, lost or corrupted data, a security hole, or a REVIEW.md rule broken. - Nit: a real bug, but minor or unlikely. - Pre-existing: a bug in code this PR didn't change. Never Important. + - Upstream: only on a PR the scope below says merges the repo's upstream: a bug in upstream's own changes. Listed, never blocks. Git then checks every Important and Upstream finding against the scope, so put each where its cause is. 6. Don't post comments or reviews yourself. Answer only with the JSON the output schema asks for: file is repo-relative, line is in the PR head's version, title is one line, detail is the failing scenario in a sentence or two. List each earlier finding's id under resolved or still_open. ${{ steps.plan.outputs.context }} claude_args: | --max-turns 30 --allowedTools "Read,Grep,Glob,Bash(git diff:*),Bash(git log:*),Bash(git show:*)" - --json-schema '{"type":"object","properties":{"summary":{"type":"string"},"findings":{"type":"array","items":{"type":"object","properties":{"severity":{"type":"string","enum":["Important","Nit","Pre-existing"]},"file":{"type":"string"},"line":{"type":"integer"},"title":{"type":"string"},"detail":{"type":"string"}},"required":["severity","file","title","detail"]}},"resolved":{"type":"array","items":{"type":"string"}},"still_open":{"type":"array","items":{"type":"string"}}},"required":["summary","findings","resolved","still_open"]}' + --json-schema '{"type":"object","properties":{"summary":{"type":"string"},"findings":{"type":"array","items":{"type":"object","properties":{"severity":{"type":"string","enum":["Important","Nit","Pre-existing","Upstream"]},"file":{"type":"string"},"line":{"type":"integer"},"title":{"type":"string"},"detail":{"type":"string"}},"required":["severity","file","title","detail"]}},"resolved":{"type":"array","items":{"type":"string"}},"still_open":{"type":"array","items":{"type":"string"}}},"required":["summary","findings","resolved","still_open"]}' - name: Verdict if: ${{ !cancelled() }} env: diff --git a/.github/workflows/publish-check.yml b/.github/workflows/publish-check.yml new file mode 100644 index 0000000..429eddb --- /dev/null +++ b/.github/workflows/publish-check.yml @@ -0,0 +1,47 @@ +name: Publish check + +# A public repo carries no agent working docs, personal emails in commit +# metadata, secrets, or self-hosted runners: scripts/publish-check.mjs checks the +# tree and the new commits of each PR and of each push to main (a web merge or +# edit included). From devkit's templates/publish-check.yml (kit-install +# --public). Its personal patterns are private, so here it runs without them; +# the pre-push hook on Tom's Mac (devkit bin/notes-link) runs it with them. +# Read-only: it checks out and reads, and runs nothing from the PR but the +# script, which a PR from outside can't merge without Tom (Risk tier). +on: + pull_request: + push: + branches: [main] + +concurrency: + group: publish-check-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + publish-check: + # Branch protection requires this check by its name: change both together. + name: Publish check + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + fetch-depth: 0 + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: '22' + - name: Check + env: + BASE: ${{ github.event.pull_request.base.sha || github.event.before }} + HEAD: ${{ github.event.pull_request.head.sha || github.sha }} + run: | + case "$BASE" in + ''|0000000000000000000000000000000000000000) range="" ;; + *) range="--range $BASE..$HEAD" ;; + esac + node scripts/publish-check.mjs --no-personal $range . diff --git a/.github/workflows/risk-tier-review.yml b/.github/workflows/risk-tier-review.yml new file mode 100644 index 0000000..10b4fd3 --- /dev/null +++ b/.github/workflows/risk-tier-review.yml @@ -0,0 +1,46 @@ +name: Risk tier on review + +# A review can be Tom's approval (or its dismissal), but the "Risk tier" check +# is risk-tier.yml's pull_request_target run. A red Risk tier from one run +# blocks the merge whatever another run says, so a review reports none of its +# own: Tom's approval once passed in its own run while the earlier red stayed +# (devkit PLAN.md › Agent identity). This reruns the newest Risk tier run on the +# head commit, once it has finished, when its conclusion disagrees with the +# verdict now. The rerun decides with main's code as always; this job's own +# result is no verdict. pull_request_review has no _target variant, so this +# file is the PR's copy, but the script is main's. From devkit's +# templates/risk-tier-review.yml. +on: + pull_request_review: + types: + - submitted + - dismissed + +concurrency: + group: risk-tier-review-${{ github.event.pull_request.number }} + cancel-in-progress: true + +permissions: + actions: write + contents: read + pull-requests: read + issues: read + +jobs: + rerun: + name: Rerun Risk tier + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: '22' + - name: Rerun if the review changed the verdict + env: + GH_TOKEN: ${{ github.token }} + PR: ${{ github.event.pull_request.number }} + run: node scripts/risk-tier.mjs rerun --repo "$GITHUB_REPOSITORY" --pr "$PR" diff --git a/.github/workflows/risk-tier.yml b/.github/workflows/risk-tier.yml new file mode 100644 index 0000000..7d4e07a --- /dev/null +++ b/.github/workflows/risk-tier.yml @@ -0,0 +1,49 @@ +name: Risk tier + +# Fails while a PR touches a high-risk path (REVIEW.md › High-risk paths) +# without Tom's approving review of its head commit, which GitHub requests from +# him (CODEOWNERS). From devkit's templates/risk-tier.yml. +# pull_request_target runs main's copy of this workflow, and the checkout is +# main whatever the PR's base, so REVIEW.md and scripts/risk-tier.mjs are main's +# too and a PR can't loosen its own gate. Nothing from the PR is checked out or +# run: the changed files come from the API. "edited" covers a PR retargeted +# onto main. A review doesn't run this: risk-tier-review.yml reruns this run +# instead, as a second "Risk tier" of its own couldn't clear this one's red. +# The PR that adds this file isn't gated by it: main has no copy to run yet. +on: + pull_request_target: + types: + - opened + - synchronize + - reopened + - edited + - ready_for_review + +concurrency: + group: risk-tier-${{ github.event.pull_request.number }} + cancel-in-progress: true + +permissions: + contents: read + pull-requests: write + issues: write + +jobs: + risk-tier: + # Branch protection requires this check by its name: change both together. + name: Risk tier + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + - uses: actions/setup-node@v4 + with: + node-version: '22' + - name: Check + env: + GH_TOKEN: ${{ github.token }} + PR: ${{ github.event.pull_request.number }} + run: node scripts/risk-tier.mjs check --repo "$GITHUB_REPOSITORY" --pr "$PR" diff --git a/scripts/publish-check.mjs b/scripts/publish-check.mjs new file mode 100755 index 0000000..681a74d --- /dev/null +++ b/scripts/publish-check.mjs @@ -0,0 +1,515 @@ +#!/usr/bin/env node +// publish-check: is this fit to be public? From devkit's +// templates/publish-check.mjs (kit-install --public puts it in scripts/): +// change it there, not here. +// +// publish-check [--range .. | --tree-only] [--github ] +// [--patterns | --no-personal] [--secrets-env ] +// [--summary] +// +// is a checkout (its working tree, the history of every ref and +// every commit's metadata), a bare repo (HEAD's tree stands for the working +// tree), a plain directory (its files only), or owner/name on GitHub, which is +// mirror-cloned to a temp dir (every ref GitHub keeps, pull requests' heads +// included) and implies --github. --range checks only those commits (CI, a +// pre-push hook); --tree-only only the files. +// +// What it looks for: +// agent-file agent working docs (CLAUDE.md, AGENTS.md, HANDOVER.md, +// DECISIONS.md, REVIEW.md, PLAN.md, .claude/, .orca, session +// notes, …) at any depth, in the tree or ever in history +// personal:.. | --tree-only] [--github ] [--patterns | --no-personal] [--secrets-env ] [--summary] '); + process.exit(2); +} + +function parseArgs(argv) { + const o = { range: null, treeOnly: false, github: null, patterns: process.env.PUBLISH_PATTERNS || null, personal: true, + secretsEnv: process.env.PUBLISH_SECRETS_ENV || null, summary: false, target: null }; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + const val = () => { const v = argv[++i]; if (v === undefined || v.startsWith('--')) usage(`${a} needs a value`); return v; }; + if (a === '--range') o.range = val(); + else if (a === '--tree-only') o.treeOnly = true; + else if (a === '--github') o.github = val(); + else if (a === '--patterns') o.patterns = val(); + else if (a === '--no-personal') o.personal = false; + else if (a === '--secrets-env') o.secretsEnv = val(); + else if (a === '--summary') o.summary = true; + else if (a.startsWith('-')) usage(`unknown option ${a}`); + else if (o.target) usage('one repo or directory'); + else o.target = a; + } + if (!o.target) usage(); + if (o.range && o.treeOnly) usage('--range or --tree-only, not both'); + if (o.range && !/^[^\s.][^\s]*\.\.[^\s.][^\s]*$/.test(o.range)) usage('--range is ..'); + if (o.github && !/^[\w.-]+\/[\w.-]+$/.test(o.github)) usage('--github is owner/name'); + return o; +} + +export function check(o) { + const findings = []; + const seen = new Set(); + const add = (kind, where, key = `${kind}|${where}`) => { + if (!seen.has(key)) { seen.add(key); findings.push({ kind, where }); } + }; + const notes = []; + + let rules = []; + if (o.personal) { + if (!o.patterns) throw Object.assign(new Error('no patterns file: pass --patterns (or set PUBLISH_PATTERNS), or --no-personal'), { code: 2 }); + if (!existsSync(o.patterns)) throw Object.assign(new Error(`no patterns file at ${o.patterns}: build it, or pass --no-personal`), { code: 2 }); + rules = parsePatterns(readFileSync(o.patterns, 'utf8')); + if (!rules.length) throw Object.assign(new Error(`${o.patterns} has no patterns`), { code: 2 }); + } + const personal = rules; + if (o.secretsEnv) { + if (existsSync(o.secretsEnv)) rules = rules.concat(parseSecretsEnv(readFileSync(o.secretsEnv, 'utf8'))); + else notes.push(`no secrets file at ${o.secretsEnv}: its values weren't looked for`); + } + + // The target: a GitHub repo is cloned with every ref it keeps. + let dir = o.target; + let temp = null; + let github = o.github; + if (!existsSync(dir) && /^[\w.-]+\/[\w.-]+$/.test(dir)) { + temp = mkdtempSync(join(tmpdir(), 'publish-check-')); + const r = spawnSync('git', ['clone', '--quiet', '--mirror', `https://github.com/${dir}.git`, join(temp, 'repo.git')], { encoding: 'utf8' }); + if (r.status !== 0) { rmSync(temp, { recursive: true, force: true }); throw Object.assign(new Error(`can't clone ${dir}: ${r.stderr.trim().split('\n')[0]}`), { code: 2 }); } + github ??= dir; + dir = join(temp, 'repo.git'); + } + if (!existsSync(dir) || !statSync(dir).isDirectory()) throw Object.assign(new Error(`${o.target} isn't a directory or owner/name`), { code: 2 }); + dir = realpathSync(dir); + + try { + const inGit = spawnSync('git', ['-C', dir, 'rev-parse', '--is-bare-repository'], { encoding: 'utf8' }); + const isGit = inGit.status === 0 && (inGit.stdout.trim() === 'true' || + realpathSync(gitText(dir, ['rev-parse', '--show-toplevel']).trim()) === dir); + const bare = isGit && inGit.stdout.trim() === 'true'; + const hasHead = isGit && spawnSync('git', ['-C', dir, 'rev-parse', '--verify', '--quiet', 'HEAD^{commit}']).status === 0; + // Refs with commits, whatever HEAD is: an orphan branch checked out, or a + // bare repo whose HEAD names a missing branch, still has every other ref. + const hasRefs = isGit && (hasHead || gitText(dir, ['for-each-ref', '--count=1', '--format=x', '--exclude=refs/stash']).trim() !== ''); + if (o.range && !isGit) throw Object.assign(new Error('--range needs a git repo'), { code: 2 }); + + // gitleaks for secrets when it's there; built-in rules otherwise, and for a + // bare repo's tree alone, which gitleaks has no way to read. + const gl = spawnSync(GITLEAKS, ['version'], { encoding: 'utf8' }); + const gitleaks = gl.status === 0 && !(bare && o.treeOnly); + if (!gitleaks) rules = rules.concat(SECRET_RULES); + const contentRules = rules; + const treeKeys = new Set(); // personal or secret hits the tree has: history reports only the rest + + // ---- the tree + const files = []; // [path, () => Buffer] + if (!isGit) { + const walk = (rel) => { + for (const e of readdirSync(join(dir, rel), { withFileTypes: true })) { + const p = rel ? `${rel}/${e.name}` : e.name; + if (e.name === '.git' && !rel) continue; + if (e.isDirectory()) walk(p); + else if (e.isFile()) files.push([p, () => readFileSync(join(dir, p)), statSync(join(dir, p)).size]); + else if (e.isSymbolicLink()) files.push([p, null, 0]); + } + }; + walk(''); + } else if (!bare) { + const list = gitText(dir, ['ls-files', '-z', '--cached', '--others', '--exclude-standard']).split('\0').filter(Boolean); + for (const p of [...new Set(list)]) { + const st = lstatSync(join(dir, p), { throwIfNoEntry: false }); + if (!st) continue; // deleted in the tree, not yet committed + files.push([p, st.isFile() ? () => readFileSync(join(dir, p)) : null, st.isFile() ? st.size : 0]); + } + } else if (hasHead) { + const ls = gitText(dir, ['ls-tree', '-r', '-z', '--long', 'HEAD']).split('\0').filter(Boolean); + const ids = []; + for (const row of ls) { + const [meta, p] = row.split('\t'); + const [, type, id, size] = meta.trim().split(/\s+/); + if (type !== 'blob') continue; + files.push([p, id, Number(size)]); + if (Number(size) <= MAX_BLOB) ids.push({ id, size: Number(size) }); + } + const content = new Map(blobs(dir, ids)); + for (const f of files) { const id = f[1]; f[1] = content.has(id) ? () => content.get(id) : null; } + } + for (const [p, read, size] of files) { + if (isAgentPath(p)) add('agent-file', p); + if (!read || size > MAX_BLOB) continue; + const buf = read(); + if (isBinary(buf)) continue; + const text = buf.toString('utf8'); + for (const h of scanText(text, contentRules)) { + treeKeys.add(`${h.rule.label}|${p}|${hash(h.text)}`); + add(`${h.rule.kind}:${h.rule.label}`, `${p}:${h.line}`); + } + if (/^\.github\/workflows\/[^/]+\.ya?ml$/.test(p)) { + text.split('\n').forEach((t, i) => { + if (/^\s*#/.test(t)) return; + if (/\bself-hosted\b/.test(t)) add('workflow', `${p}:${i + 1} runs on a self-hosted runner`); + }); + } + } + // gitleaks reads the files of a plain directory, or a checkout's when only + // the tree is asked for (ignored files never leave the machine). Otherwise + // its history scan below covers what's committed, and a finding whose + // secret the tree still has counts as a tree finding. + const readers = new Map(files.map(([p, read]) => [p, read])); + if (gitleaks && (!isGit || (o.treeOnly && !bare))) { + for (const f of runGitleaks(['dir', dir])) { + const file = f.File.startsWith(`${dir}/`) ? f.File.slice(dir.length + 1) : f.File; + if (isGit && !readers.has(file)) continue; + add(`secret:${f.RuleID}`, `${file}:${f.StartLine}`); + } + } + + // ---- history and metadata + let commits = 0; + if (isGit && !o.treeOnly && hasRefs) { + const revs = o.range ? [o.range] : ['--exclude=refs/stash', '--all']; + commits = Number(gitText(dir, ['rev-list', '--count', ...revs]).trim()); + + // Agent files ever added, with the first commit that added each. + const added = new Map(); + let at = ''; + for (const row of gitText(dir, ['log', '--reverse', '--format=@%h', '--abbrev=7', '--name-only', '--diff-filter=A', '--no-renames', ...revs]).split('\n')) { + if (row.startsWith('@')) at = row.slice(1, 8); + else if (row && !added.has(row)) added.set(row, at); + } + const inTree = new Set(files.map(([p]) => p)); + for (const [p, sha] of added) if (isAgentPath(p) && !inTree.has(p)) add('agent-file', `history ${p} (added in ${sha})`); + + // Every blob the commits reach, read once; a hit names the first commit + // that introduced the blob. + const objs = gitText(dir, ['rev-list', '--objects', ...revs]).split('\n').filter(Boolean); + const pathOf = new Map(); + for (const row of objs) { const i = row.indexOf(' '); if (i > 0) pathOf.set(row.slice(0, i), row.slice(i + 1)); } + const checkIn = [...pathOf.keys()].join('\n') + '\n'; + const sizes = gitRun(dir, ['cat-file', '--batch-check=%(objectname) %(objecttype) %(objectsize)'], { input: checkIn, encoding: 'utf8' }); + const want = []; + for (const row of sizes.split('\n')) { + const [id, type, size] = row.split(' '); + if (type === 'blob' && Number(size) <= MAX_BLOB) want.push({ id, size: Number(size) }); + } + const firstIn = new Map(); + for (const row of gitText(dir, ['log', '--reverse', '--format=@%h', '--raw', '--no-abbrev', '--no-renames', '--diff-merges=first-parent', ...revs]).split('\n')) { + if (row.startsWith('@')) { at = row.slice(1, 8); continue; } + const m = row.match(/^:\d+ \d+ [0-9a-f]+ ([0-9a-f]+) [A-Z]/); + if (m && !firstIn.has(m[1])) firstIn.set(m[1], at); + } + for (const [id, buf] of blobs(dir, want)) { + if (isBinary(buf)) continue; + const p = pathOf.get(id); + for (const h of scanText(buf.toString('utf8'), contentRules)) { + const key = `${h.rule.label}|${p}|${hash(h.text)}`; + if (treeKeys.has(key)) continue; + add(`${h.rule.kind}:${h.rule.label}`, `history ${p}:${h.line} (in ${firstIn.get(id) ?? 'a merge'})`, key); + } + } + + // Messages, names and addresses. Each address that isn't noreply gets a + // number, so its commits can be counted without printing it. + const addrs = new Map(); + const log = gitText(dir, ['log', '--abbrev=7', '--format=%h%x00%an%x00%ae%x00%cn%x00%ce%x00%B%x1e', ...revs]); + for (const rec of log.split('\x1e')) { + const [sha, an, ae, cn, ce, body] = rec.replace(/^\n/, '').split('\0'); + if (!sha) continue; + for (const [role, name, email] of [['author', an, ae], ['committer', cn, ce]]) { + for (const h of scanText(name, personal)) add(`personal:${h.rule.label}`, `${sha} ${role} name`); + if (isNoreply(email)) continue; + if (!addrs.has(email.toLowerCase())) addrs.set(email.toLowerCase(), addrs.size + 1); + const label = scanText(email, personal)[0]?.rule.label; + add('email', `${sha} ${role}: address ${addrs.get(email.toLowerCase())}${label ? ` (${label})` : ''}, not GitHub's noreply`); + } + for (const h of scanText(body ?? '', contentRules)) add(`${h.rule.kind}:${h.rule.label}`, `${sha} message:${h.line}`); + } + + // Annotated tags: every one, or with --range the tag a push names as its + // right side. Their tagger and message are as public as a commit's. + const tagRows = o.range + ? (gitText(dir, ['cat-file', '-t', o.range.split('..')[1]]).trim() === 'tag' ? [o.range.split('..')[1]] : []) + : gitText(dir, ['for-each-ref', '--format=%(objectname) %(objecttype)', 'refs/tags']).split('\n').filter((l) => l.endsWith(' tag')).map((l) => l.split(' ')[0]); + for (const id of tagRows) { + const raw = gitText(dir, ['cat-file', 'tag', id]); + const head = raw.slice(0, raw.indexOf('\n\n') >= 0 ? raw.indexOf('\n\n') : raw.length); + const msg = raw.indexOf('\n\n') >= 0 ? raw.slice(raw.indexOf('\n\n') + 2) : ''; + const name = head.match(/^tag (.*)$/m)?.[1] ?? id.slice(0, 7); + const tagger = head.match(/^tagger (.*?) <([^>]*)>/m); + if (tagger) { + for (const h of scanText(tagger[1], personal)) add(`personal:${h.rule.label}`, `tag ${name} tagger name`); + if (!isNoreply(tagger[2])) { + if (!addrs.has(tagger[2].toLowerCase())) addrs.set(tagger[2].toLowerCase(), addrs.size + 1); + const label = scanText(tagger[2], personal)[0]?.rule.label; + add('email', `tag ${name} tagger: address ${addrs.get(tagger[2].toLowerCase())}${label ? ` (${label})` : ''}, not GitHub's noreply`); + } + } + for (const h of scanText(msg, contentRules)) add(`${h.rule.kind}:${h.rule.label}`, `tag ${name} message:${h.line}`); + } + + if (gitleaks) { + for (const f of runGitleaks(['git', dir, `--log-opts=${revs.join(' ')}`])) { + const read = readers.get(f.File); + const now = read && f.Secret ? read().toString('utf8').split('\n').findIndex((l) => l.includes(f.Secret)) : -1; + if (now >= 0) add(`secret:${f.RuleID}`, `${f.File}:${now + 1}`); + else add(`secret:${f.RuleID}`, `history ${f.File}:${f.StartLine} (in ${String(f.Commit).slice(0, 7)})`, `secret|${f.RuleID}|${f.File}|${hash(f.Secret ?? '')}`); + } + } + } + + // ---- GitHub: issues, pull requests, comments, reviews, releases + let gh = 0; + if (github) gh = scanGitHub(github, contentRules, add); + + return { findings, notes, commits, files: files.length, gitleaks, github: gh }; + } finally { + if (temp) rmSync(temp, { recursive: true, force: true }); + } +} + +// gitleaks' findings. Its report holds the raw secret, in a private temp dir +// removed straight after: the value is only compared and hashed, never printed. +function runGitleaks(args) { + const tmp = mkdtempSync(join(tmpdir(), 'publish-check-gl-')); + try { + const report = join(tmp, 'report.json'); + const r = spawnSync(GITLEAKS, [...args, '--no-banner', '--log-level', 'error', '--exit-code', '0', + '--report-format', 'json', '--report-path', report], { encoding: 'utf8', maxBuffer: BUF }); + if (r.status !== 0 || !existsSync(report)) throw Object.assign(new Error(`gitleaks ${args[0]} failed: ${String(r.stderr).trim().split('\n')[0]}`), { code: 2 }); + return JSON.parse(readFileSync(report, 'utf8') || '[]'); + } finally { + rmSync(tmp, { recursive: true, force: true }); + } +} + +function ghJSON(path) { + const r = spawnSync('gh', ['api', '--paginate', '--slurp', path], { encoding: 'utf8', maxBuffer: BUF }); + if (r.status !== 0) throw Object.assign(new Error(`gh api ${path.split('?')[0]}: ${String(r.stderr).trim().split('\n')[0]}`), { code: 2 }); + return JSON.parse(r.stdout).flat(); +} + +function scanGitHub(repo, rules, add) { + let n = 0; + const scan = (text, where) => { n++; for (const h of scanText(text ?? '', rules)) add(`${h.rule.kind}:${h.rule.label}`, `github ${where}:${h.line}`); }; + const meta = ghJSON(`repos/${repo}`)[0] ?? {}; + scan([meta.description, meta.homepage].filter(Boolean).join('\n'), 'description'); + const issues = ghJSON(`repos/${repo}/issues?state=all&per_page=100`); + for (const i of issues) { + const kind = i.pull_request ? 'pr' : 'issue'; + scan(i.title, `${kind} #${i.number} title`); + scan(i.body, `${kind} #${i.number} body`); + if (i.pull_request) for (const r of ghJSON(`repos/${repo}/pulls/${i.number}/reviews?per_page=100`)) scan(r.body, `pr #${i.number} review ${r.id}`); + } + for (const c of ghJSON(`repos/${repo}/issues/comments?per_page=100`)) scan(c.body, `comment ${c.id} on #${c.issue_url?.split('/').pop()}`); + for (const c of ghJSON(`repos/${repo}/pulls/comments?per_page=100`)) scan(c.body, `review comment ${c.id} on #${c.pull_request_url?.split('/').pop()}`); + for (const r of ghJSON(`repos/${repo}/releases?per_page=100`)) { scan(r.name, `release ${r.tag_name} name`); scan(r.body, `release ${r.tag_name} body`); } + return n; +} + +function main(argv) { + const o = parseArgs(argv); + let r; + try { + r = check(o); + } catch (e) { + console.error(`publish-check: ${e.message}`); + return e.code ?? 2; + } + const counts = {}; + for (const f of r.findings) counts[f.kind.split(':')[0]] = (counts[f.kind.split(':')[0]] ?? 0) + 1; + if (!o.summary) for (const f of r.findings) console.log(`${f.kind}\t${f.where}`); + for (const n of r.notes) console.error(`publish-check: note: ${n}`); + const scope = [`${r.files} files`, o.treeOnly ? null : `${r.commits} commits`, r.github ? `${r.github} GitHub texts` : null, + r.gitleaks ? 'secrets by gitleaks' : 'secrets by built-in rules', o.personal ? 'personal patterns' : 'no personal patterns'].filter(Boolean).join(', '); + if (!r.findings.length) { console.log(`publish-check: clean (${scope})`); return 0; } + const byKind = Object.entries(counts).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${k} ${v}`).join(', '); + console.log(`publish-check: ${r.findings.length} findings: ${byKind} (${scope})`); + return 1; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) process.exit(main(process.argv.slice(2))); diff --git a/scripts/review-round.mjs b/scripts/review-round.mjs index ca02739..65b1d8d 100644 --- a/scripts/review-round.mjs +++ b/scripts/review-round.mjs @@ -16,15 +16,21 @@ // or the cap. Anything // else going wrong (token, outage, timeout, a malformed answer) passes with a // warning, so an outage never blocks every merge. -import { appendFileSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'; +// +// A fork can add scripts/review-scope.mjs, its own: on a PR that merges its +// upstream, scope() tells upstream's part from the fork's with git, and +// classify() then sets each finding's severity by where it is. A bug in +// upstream's own code is Upstream: listed, never red. Without a scope, nothing +// is upstream's, and an Upstream finding counts as Important. +import { appendFileSync, existsSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'; import { execFileSync } from 'node:child_process'; import path from 'node:path'; -import { fileURLToPath } from 'node:url'; +import { fileURLToPath, pathToFileURL } from 'node:url'; export const CAP = 3; export const BOT = 'github-actions[bot]'; export const CAP_LABEL = 'review-cap'; -const SEVERITIES = ['Important', 'Nit', 'Pre-existing']; +const SEVERITIES = ['Important', 'Nit', 'Pre-existing', 'Upstream']; const MARK = //g; // The newest state the reviewer itself wrote. @@ -88,6 +94,7 @@ export function context(p, head) { for (const c of p.commits) out.push(`- ${c}`); out.push('The rest of the PR (`git diff origin/main...HEAD`) was reviewed already: read it for context only.'); } + if (p.scope?.context) out.push('', p.scope.context); if (p.open.length) { out.push('', 'Important findings still open from earlier rounds. For each id, say "resolved" if the current code fixes it (or it was wrong), "still_open" if not:'); for (const f of p.open) out.push(`- ${f.id}: ${where(f)}: ${f.title}`); @@ -96,10 +103,24 @@ export function context(p, head) { } const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`; + +// Upstream is a severity only the scope can grant: where it ran, its classify +// decides; anywhere else, or if it fails, Upstream counts as Important. +export function bySource(findings, scope, classify) { + const strict = () => findings.map((f) => (f.severity === 'Upstream' ? { ...f, severity: 'Important' } : f)); + if (!scope || !classify) return { findings: strict() }; + try { + const out = classify(findings, scope); + if (Array.isArray(out) && out.length === findings.length) return { findings: out }; + return { findings: strict(), warning: 'the review scope gave back a different list: Upstream counts as Important' }; + } catch (e) { + return { findings: strict(), warning: `the review scope failed (${String(e.message).split('\n')[0]}): Upstream counts as Important` }; + } +} const bullet = (f) => `- **${where(f)}**: ${f.title}${f.detail ? `. ${f.detail}` : ''}`; // The verdict, the comment and the labels, from the plan and Claude's answer. -export function report({ plan: p, outcome, output, head }) { +export function report({ plan: p, outcome, output, head, classify }) { const done = (code, body, state, extra = {}) => ({ code, body: body && state ? `${body}\n\n${marker(state)}` : body, ...extra }); const keep = { round: p.round, reviewed: head, open: p.open, verdict: verdictOf(p.open) }; @@ -125,7 +146,8 @@ export function report({ plan: p, outcome, output, head }) { 'Passing open, so an outage doesn\'t block every merge. The next push reviews again.', null, { warning: `review skipped: ${why}` }); } - const findings = answer.findings.filter((f) => SEVERITIES.includes(f.severity) && f.title); + const scoped = bySource(answer.findings.filter((f) => SEVERITIES.includes(f.severity) && f.title), p.scope, classify); + const findings = scoped.findings; const resolved = new Set(answer.resolved); const fixed = p.open.filter((f) => resolved.has(f.id)); const still = p.open.filter((f) => !resolved.has(f.id)); @@ -133,8 +155,9 @@ export function report({ plan: p, outcome, output, head }) { .map((f, i) => ({ id: `r${p.round}-${i + 1}`, file: f.file, line: f.line ?? null, title: f.title })); const open = [...still, ...fresh]; const nits = findings.filter((f) => f.severity === 'Nit'), old = findings.filter((f) => f.severity === 'Pre-existing'); + const theirs = findings.filter((f) => f.severity === 'Upstream'); - const verdict = verdictOf(open, nits.length); + const verdict = verdictOf(open, nits.length, theirs.length); const body = [`**Claude review, round ${ofCap(p.round)}** on \`${head.slice(0, 7)}\`: ${sentence(open)}`]; if (answer.summary) body.push('', answer.summary); const section = (title, items, fmt = bullet) => { if (items.length) body.push('', `### ${title}`, ...items.map(fmt)); }; @@ -143,14 +166,15 @@ export function report({ plan: p, outcome, output, head }) { section('Fixed since the last round', fixed, (f) => `- ${f.id} **${where(f)}**: ${f.title}`); section('Nit (never blocks)', nits); section('Pre-existing (already on main; never blocks)', old); + section('Upstream (in upstream\'s own changes; upstream\'s to fix, never blocks)', theirs); if (open.length && p.round >= CAP) { body.push('', `Round ${ofCap(p.round)}: if another push still leaves these open, the round cap stops this PR. If the approach is fighting the reviewer, rethink it now.`); } - return done(open.length ? 1 : 0, body.join('\n'), { round: p.round, reviewed: head, open, verdict }); + return done(open.length ? 1 : 0, body.join('\n'), { round: p.round, reviewed: head, open, verdict }, scoped.warning ? { warning: scoped.warning } : {}); } -function verdictOf(open, nits = 0) { - const n = nits ? `, ${plural(nits, 'Nit')}` : ''; +function verdictOf(open, nits = 0, theirs = 0) { + const n = (nits ? `, ${plural(nits, 'Nit')}` : '') + (theirs ? `, ${theirs} Upstream` : ''); return open.length ? `${plural(open.length, 'open Important finding')}${n}` : `no open Important findings${n}`; } const sentence = (open) => (open.length @@ -163,13 +187,16 @@ const gh = (...args) => execFileSync('gh', args, { encoding: 'utf8', stdio: ['ig const git = (...args) => execFileSync('git', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }); const jsonLines = (text) => text.split('\n').filter(Boolean).map((l) => JSON.parse(l)); const planFile = () => path.join(env.RUNNER_TEMP ?? '/tmp', 'review-plan.json'); +// The repo's scope, if it has one (REVIEW_SCOPE names another file, for tests). +const scopeFile = () => env.REVIEW_SCOPE ?? path.join(path.dirname(fileURLToPath(import.meta.url)), 'review-scope.mjs'); +const loadScope = async () => (existsSync(scopeFile()) ? import(pathToFileURL(path.resolve(scopeFile())).href) : null); const output = (name, value) => { if (!env.GITHUB_OUTPUT) return; const eof = `EOF_${Math.random().toString(36).slice(2)}`; appendFileSync(env.GITHUB_OUTPUT, `${name}<<${eof}\n${value}\n${eof}\n`); }; -function cliPlan() { +async function cliPlan() { const { GITHUB_REPOSITORY: repo, PR: pr, HEAD_SHA: head } = env; const comments = jsonLines(gh('api', '--paginate', `repos/${repo}/issues/${pr}/comments`, '--jq', '.[] | {user: .user.login, body}')); const labels = JSON.parse(gh('api', `repos/${repo}/pulls/${pr}`)).labels.map((l) => l.name); @@ -178,19 +205,37 @@ function cliPlan() { ? sinceReviewed(git, { reviewed: state.reviewed, head, base: 'refs/remotes/origin/main' }) : null; const p = plan({ state, labels, head, commits }); + if (p.mode === 'review') { + // A scope that fails leaves nothing upstream's: the strict side. + try { + const hook = await loadScope(); + p.scope = hook ? hook.scope({ git, head, base: 'refs/remotes/origin/main' }) : null; + } catch (e) { + console.log(`::warning::the review scope failed: ${String(e.message).split('\n')[0]}; nothing counts as upstream's`); + p.scope = null; + } + } writeFileSync(planFile(), JSON.stringify(p)); output('mode', p.mode); output('context', p.mode === 'review' ? context(p, head) : ''); console.log(`round ${p.round}: ${p.mode}${p.commits ? ` (${plural(p.commits.length, 'new commit')})` : ''}`); } -function cliReport() { +async function cliReport() { const { GITHUB_REPOSITORY: repo, PR: pr, HEAD_SHA: head } = env; if (env.PLAN_OUTCOME !== 'success') { console.log(`::warning::review skipped: planning the round ${env.PLAN_OUTCOME || 'did not run'}; passing open`); return 0; } - const r = report({ plan: JSON.parse(readFileSync(planFile(), 'utf8')), outcome: env.CLAUDE_OUTCOME, output: env.FINDINGS, head }); + const p = JSON.parse(readFileSync(planFile(), 'utf8')); + let classify = null; + if (p.scope) { + try { + const hook = await loadScope(); + if (hook) classify = (findings, scope) => hook.classify(findings, scope, { git, head }); + } catch { /* no classify: Upstream counts as Important */ } + } + const r = report({ plan: p, outcome: env.CLAUDE_OUTCOME, output: env.FINDINGS, head, classify }); // The verdict is decided; failing to post it doesn't change it. try { if (r.body) { @@ -211,7 +256,7 @@ const invoked = process.argv[1] && realpathSync(process.argv[1]) === realpathSyn if (invoked) { const cmd = process.argv[2]; try { - if (cmd === 'plan') { cliPlan(); process.exitCode = 0; } else if (cmd === 'report') process.exitCode = cliReport(); + if (cmd === 'plan') { await cliPlan(); process.exitCode = 0; } else if (cmd === 'report') process.exitCode = await cliReport(); else { console.error('usage: review-round.mjs plan | report'); process.exitCode = 2; } } catch (e) { // Never 1: that is reserved for findings. diff --git a/scripts/risk-tier.mjs b/scripts/risk-tier.mjs new file mode 100755 index 0000000..c0b2f87 --- /dev/null +++ b/scripts/risk-tier.mjs @@ -0,0 +1,276 @@ +#!/usr/bin/env node +// Risk tier: which high-risk paths (REVIEW.md › High-risk paths) a change +// touches, and whether Tom has approved it. From devkit's +// templates/risk-tier.mjs (kit-install --risk-tier): change it there, not here. +// +// node scripts/risk-tier.mjs match < name-status # `git diff --name-status -M` output +// node scripts/risk-tier.mjs check --repo --pr +// node scripts/risk-tier.mjs rerun --repo --pr +// node scripts/risk-tier.mjs codeowners # what .github/CODEOWNERS must say +// +// `match` prints one line per matched path, "\t", and nothing for an +// ordinary change, for a land script to tell Tom before he's asked. `check` is +// the "Risk tier" job: it fails when the PR touches a high-risk path and Tom +// hasn't approved its head commit with a review (GitHub requests it from +// CODEOWNERS). The workflow runs it from main's checkout, so the table and this +// file are main's, never the PR's. `rerun` is what a review does +// (risk-tier-review.yml): it reruns the PR's newest Risk tier run when the +// review has changed the verdict. +// +// The table is REVIEW.md's, or in a public repo, which keeps no REVIEW.md, +// .github/high-risk-paths.md's (devkit PLAN.md › Public repos). On a public +// repo every pull request from anyone but Tom and the bot, or from a fork, +// needs Tom's approval of its head too, whatever it touches: an outside PR +// never merges on green alone. +import { existsSync, readFileSync, appendFileSync, realpathSync } from 'node:fs'; +import { execFileSync } from 'node:child_process'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +export const NEEDS_TOM = 'needs-tom'; +export const APPROVER = 'tomdebres'; +export const TRUSTED = [APPROVER, 'tomdebres-agent']; +// A public repo's own table first: its REVIEW.md, if any, is a link into the +// private notes, which CI never sees. +export const TABLES = ['.github/high-risk-paths.md', 'REVIEW.md']; +const START = ''; +const END = ''; + +// Root-relative globs: `*` and `?` stay inside one directory, `**` crosses any +// number, and `**/` may be none at all. +export function globToRegExp(glob) { + if (!glob || glob.startsWith('/') || glob.includes('\\')) throw new Error(`not a root-relative glob: ${glob}`); + let re = ''; + for (let i = 0; i < glob.length; i++) { + const c = glob[i]; + if (c === '*' && glob[i + 1] === '*') { + if (glob[i + 2] === '/') { re += '(?:.*/)?'; i += 2; } else { re += '.*'; i += 1; } + } else if (c === '*') re += '[^/]*'; + else if (c === '?') re += '[^/]'; + else re += c.replace(/[.+^${}()|[\]]/g, '\\$&'); + } + return new RegExp(`^${re}$`); +} + +// The table between the markers: | `glob` | any or deleted | why |. +export function parseRules(markdown) { + const start = markdown.indexOf(START), end = markdown.indexOf(END); + if (start < 0 || end < start) throw new Error(`no ${START} … ${END} block`); + const rules = []; + for (const row of markdown.slice(start + START.length, end).split('\n').map((l) => l.trim())) { + if (!row) continue; + const cells = row.replace(/^\||\|$/g, '').split('|').map((c) => c.trim()); + if (!row.startsWith('|') || cells.length !== 3) throw new Error(`not a three-column row: ${row}`); + if (cells[0] === 'Path' || /^-+$/.test(cells[0])) continue; + const glob = cells[0].replace(/^`(.*)`$/, '$1'); + if (cells[1] !== 'any' && cells[1] !== 'deleted') throw new Error(`"${cells[1]}" is not any or deleted: ${row}`); + if (!cells[2]) throw new Error(`no reason given: ${row}`); + rules.push({ glob, counts: cells[1], why: cells[2], re: globToRegExp(glob) }); + } + if (!rules.length) throw new Error('the high-risk table is empty'); + return rules; +} + +const STATUS = { A: 'added', M: 'modified', D: 'removed', R: 'renamed', C: 'copied', T: 'changed' }; + +// `git diff --name-status -M`: "M\tpath", "R097\told\tnew". +export function fromNameStatus(text) { + return text.split('\n').filter(Boolean).map((line) => { + const [code, a, b] = line.split('\t'); + const status = STATUS[code[0]] ?? 'modified'; + return b === undefined ? { path: a, status } : { path: b, previous: a, status }; + }); +} + +// GitHub's pulls//files entries. +export const fromPullFiles = (files) => + files.map((f) => ({ path: f.filename, status: f.status, ...(f.previous_filename ? { previous: f.previous_filename } : {}) })); + +// Every high-risk path a change touches, once, with the first rule's reason. +// A rename touches the old path too, and for a "deleted" row it is the old path +// that is gone. +export function match(rules, changes) { + const hits = new Map(); + const hit = (label, rule) => { if (!hits.has(label)) hits.set(label, { path: label, why: rule.why }); }; + for (const c of changes) { + for (const rule of rules) { + if (rule.counts === 'any') { + for (const p of [c.path, c.previous].filter(Boolean)) if (rule.re.test(p)) hit(p, rule); + } else if (c.status === 'removed' && rule.re.test(c.path)) { + hit(`${c.path} (deleted)`, rule); + } else if (c.status === 'renamed' && rule.re.test(c.previous)) { + hit(`${c.previous} (renamed to ${c.path})`, rule); + } + } + } + return [...hits.values()]; +} + +// Tom's latest verdict on the head commit, if he gave one there. +function reviewApproves(reviews, headSha) { + const verdicts = reviews.filter((r) => r.user === APPROVER && r.commit_id === headSha && + (r.state === 'APPROVED' || r.state === 'CHANGES_REQUESTED')); + return verdicts.at(-1)?.state === 'APPROVED'; +} + +// Why a pull request on a public repo is an outsider's, or null: its author +// isn't Tom or the bot, or its head is in another repo (a fork). A private +// repo has no outsiders. +export function outsider(info) { + if (info?.base?.repo?.private !== false) return null; + const login = info.user?.login; + if (!TRUSTED.includes(login)) return `opened by ${login ?? 'an unknown account'}`; + if (info.head?.repo?.full_name !== info.base.repo.full_name) return `from ${info.head?.repo?.full_name ?? 'a deleted fork'}`; + return null; +} + +export function decide({ matches, reviews, headSha, outside = null }) { + if (!matches.length && !outside) return { pass: true, why: 'no high-risk paths' }; + const head = headSha.slice(0, 7); + if (reviewApproves(reviews, headSha)) return { pass: true, why: `approved: review by ${APPROVER} on ${head}` }; + return { pass: false, why: `needs Tom: an approving review by ${APPROVER} on ${head}` }; +} + +// A review reports no Risk tier of its own. A red Risk tier from one run blocks +// the merge whatever a later run says: Tom's approval once passed in its own +// run and the earlier red stayed (devkit PLAN.md › Agent identity). So the +// verdict stays with the pull_request_target runs, and a review reruns the +// newest of them on the head once it has finished, if its conclusion disagrees +// with the verdict now. +export function staleRun(runs, pass) { + const run = runs.filter((r) => r.event === 'pull_request_target').sort((a, b) => a.id - b.id).at(-1); + if (!run) return { action: 'none', why: 'no Risk tier run on the head commit yet' }; + if (run.status !== 'completed') return { action: 'wait', run, why: `run ${run.id} is ${run.status}` }; + if ((run.conclusion === 'success') === pass) return { action: 'none', run, why: `run ${run.id} already says ${run.conclusion}` }; + return { action: 'rerun', run, why: `run ${run.id} says ${run.conclusion}, the verdict now is ${pass ? 'pass' : 'fail'}` }; +} + +// CODEOWNERS can't say "only when deleted", so those rows stay with Risk tier. +export function codeowners(rules) { + const lines = [ + '# Generated from REVIEW.md › High-risk paths: `node scripts/risk-tier.mjs codeowners > .github/CODEOWNERS`.', + '# test/risk-tier.test.mjs fails when the two differ. GitHub requests Tom\'s review', + '# from it. It enforces nothing: GitHub\'s code-owner rule needs at least one', + '# required approval, which would put Tom on every PR, so Risk tier is the gate.', + '# Rows that count only when a file is deleted (the tests) can\'t be said here.', + ]; + for (const r of rules.filter((r) => r.counts === 'any')) { + lines.push(`${r.glob.startsWith('**/') ? r.glob.slice(3) : `/${r.glob}`} @${APPROVER}`); + } + return `${lines.join('\n')}\n`; +} + +const ROOT = path.resolve(import.meta.dirname, '..'); + +// The first of TABLES that holds the table: { file, text }. +export function readTable(root) { + for (const file of TABLES) { + const p = path.join(root, file); + if (!existsSync(p)) continue; + const text = readFileSync(p, 'utf8'); + if (text.includes(START)) return { file, text }; + } + throw new Error(`no ${START} table in ${TABLES.join(' or ')}`); +} +const readRules = () => parseRules(readTable(ROOT).text); +const gh = (...args) => execFileSync('gh', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'inherit'] }); +const jsonLines = (text) => text.split('\n').filter(Boolean).map((l) => JSON.parse(l)); +const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); + +function needPr({ repo, pr }, cmd) { + if (!repo || !/^\d+$/.test(pr ?? '')) throw new Error(`${cmd} needs --repo --pr `); +} + +// The PR as Risk tier sees it: its head, labels, files and reviews. +function readPr(repo, pr) { + const rules = readRules(); + const info = JSON.parse(gh('api', `repos/${repo}/pulls/${pr}`)); + const files = jsonLines(gh('api', '--paginate', `repos/${repo}/pulls/${pr}/files`, + '--jq', '.[] | {filename, status, previous_filename}')); + const reviews = jsonLines(gh('api', '--paginate', `repos/${repo}/pulls/${pr}/reviews`, + '--jq', '.[] | {user: .user.login, state, commit_id}')); + return { + state: info.state, headSha: info.head.sha, labels: info.labels.map((l) => l.name), + files, reviews, matches: match(rules, fromPullFiles(files)), outside: outsider(info), + }; +} + +function check(args) { + needPr(args, 'check'); + const { repo, pr } = args; + const { headSha, labels, files, reviews, matches, outside } = readPr(repo, pr); + const verdict = decide({ matches, reviews, headSha, outside }); + const out = []; + out.push(matches.length + ? `Risk tier: ${matches.length} high-risk path${matches.length === 1 ? '' : 's'} (${readTable(ROOT).file})` + : `Risk tier: no high-risk paths in ${files.length} changed file${files.length === 1 ? '' : 's'}`); + for (const m of matches) out.push(` ${m.path}: ${m.why}`); + if (outside) out.push(` an outside pull request (${outside}): it never merges without Tom`); + out.push(verdict.pass ? `pass: ${verdict.why}` : `FAIL: ${verdict.why}`); + // A land script may label a high-risk PR needs-tom; Tom's approval answers + // it. Only housekeeping, so a failure here doesn't touch the verdict. + if (verdict.pass && (matches.length || outside) && labels.includes(NEEDS_TOM)) { + try { + gh('api', '-X', 'DELETE', `repos/${repo}/issues/${pr}/labels/${NEEDS_TOM}`); + out.push(`${NEEDS_TOM} removed`); + } catch { + out.push(`${NEEDS_TOM} left on: GitHub refused to remove it`); + } + } + console.log(out.join('\n')); + if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, `\`\`\`\n${out.join('\n')}\n\`\`\`\n`); + return verdict.pass ? 0 : 1; +} + +// After a review: rerun the newest Risk tier run on the head if the review has +// changed the verdict. One still running may have read the PR before the +// review, so it is waited for first. Its own exit is not a verdict: 0 when the +// run agrees or has been rerun, 1 when it couldn't get that far. +function rerun(args) { + needPr(args, 'rerun'); + const { repo, pr } = args; + const poll = Number(process.env.RISK_TIER_POLL_MS ?? 10_000); + const until = Date.now() + Number(process.env.RISK_TIER_WAIT_MS ?? 600_000); + const runs = (sha) => jsonLines(gh('api', `repos/${repo}/actions/workflows/risk-tier.yml/runs?head_sha=${sha}&event=pull_request_target&per_page=100`, + '--jq', '.workflow_runs[] | {id, event, status, conclusion}')); + for (;;) { + const p = readPr(repo, pr); + if (p.state !== 'open') { console.log(`Risk tier: #${pr} is ${p.state}, nothing to rerun`); return 0; } + const verdict = decide(p); + const next = staleRun(runs(p.headSha), verdict.pass); + if (next.action === 'wait' && Date.now() < until) { sleep(poll); continue; } + if (next.action === 'wait') { console.log(`Risk tier on ${p.headSha.slice(0, 7)}: ${next.why} still; not rerun`); return 1; } + if (next.action === 'rerun') gh('api', '-X', 'POST', `repos/${repo}/actions/runs/${next.run.id}/rerun`); + console.log(`Risk tier on ${p.headSha.slice(0, 7)}: ${verdict.pass ? 'pass' : 'fail'} (${verdict.why}); ${next.why}${next.action === 'rerun' ? ': rerun' : ''}`); + return 0; + } +} + +function main(argv) { + const [cmd, ...rest] = argv; + const args = {}; + for (let i = 0; i < rest.length; i += 2) { + if (!rest[i].startsWith('--') || rest[i + 1] === undefined) throw new Error(`bad argument: ${rest[i]}`); + args[rest[i].slice(2)] = rest[i + 1]; + } + if (cmd === 'match') { + for (const m of match(readRules(), fromNameStatus(readFileSync(0, 'utf8')))) console.log(`${m.path}\t${m.why}`); + return 0; + } + if (cmd === 'codeowners') { process.stdout.write(codeowners(readRules())); return 0; } + if (cmd === 'check') return check(args); + if (cmd === 'rerun') return rerun(args); + console.error('usage: risk-tier.mjs match < name-status | check --repo --pr | rerun --repo --pr | codeowners'); + return 2; +} + +// Compared as real paths: node resolves symlinks in a module's own URL, and +// macOS's TMPDIR is under /var, a symlink to /private/var. +if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url))) { + try { + process.exitCode = main(process.argv.slice(2)); + } catch (e) { + console.error(`risk-tier: ${e.message}`); + process.exitCode = 2; + } +} diff --git a/test/review-round.test.mjs b/test/review-round.test.mjs index cfd4665..4a624a1 100644 --- a/test/review-round.test.mjs +++ b/test/review-round.test.mjs @@ -7,7 +7,7 @@ import { execFileSync, spawnSync } from 'node:child_process'; import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync } from 'node:fs'; import { tmpdir } from 'node:os'; import path from 'node:path'; -import { BOT, CAP, context, latestState, marker, plan, report, sinceReviewed } from '../scripts/review-round.mjs'; +import { BOT, CAP, bySource, context, latestState, marker, plan, report, sinceReviewed } from '../scripts/review-round.mjs'; const SCRIPT = path.resolve(import.meta.dirname, '../scripts/review-round.mjs'); const HEAD = 'c'.repeat(40); @@ -161,6 +161,39 @@ test('after round 3: "round cap reached: rethink the approach", the label, red, assert.equal(report({ plan: { mode: 'capped', round: 4, open: [] }, outcome: 'skipped', head: HEAD }).code, 1); }); +test('Upstream is granted only by the repo\'s scope: without one, or when it fails, Upstream counts as Important', () => { + const ups = finding({ severity: 'Upstream', file: 'up/Player.java' }); + const mine = finding({ file: 'fork/Flavour.java' }); + const scope = { context: 'An upstream merge.' }; + const theirs = (fs) => fs.map((f) => ({ ...f, severity: f.file.startsWith('up/') ? 'Upstream' : 'Important' })); + assert.deepEqual(bySource([ups, mine], null, theirs).findings.map((f) => f.severity), ['Important', 'Important']); + assert.deepEqual(bySource([ups, mine], scope, null).findings.map((f) => f.severity), ['Important', 'Important']); + assert.deepEqual(bySource([finding({ file: 'up/Player.java' }), mine], scope, theirs).findings.map((f) => f.severity), ['Upstream', 'Important']); + let r = bySource([ups], scope, () => { throw new Error('git broke\nmore'); }); + assert.equal(r.findings[0].severity, 'Important'); + assert.match(r.warning, /^the review scope failed \(git broke\): Upstream counts as Important$/); + r = bySource([ups], scope, () => []); + assert.equal(r.findings[0].severity, 'Important'); + assert.match(r.warning, /different list/); + + // In a round: the scope's context goes in the prompt, Upstream is listed and never red. + const p = { mode: 'review', round: 1, open: [], commits: null, scope }; + assert.match(context(p, HEAD), /^Review the whole PR: .*\n\nAn upstream merge\.$/m); + r = report({ plan: p, outcome: 'success', output: answer({ findings: [finding({ file: 'up/Player.java', title: 'skips on UP' })] }), head: HEAD, classify: theirs }); + assert.equal(r.code, 0); + assert.match(r.body, /: no open Important findings\.$/m); + assert.match(r.body, /^### Upstream \(in upstream's own changes; upstream's to fix, never blocks\)\n- \*\*up\/Player\.java:12\*\*: skips on UP/m); + assert.deepEqual(latestState([{ user: BOT, body: r.body }]), { round: 1, reviewed: HEAD, open: [], verdict: 'no open Important findings, 1 Upstream' }); + // The model calling a fork bug Upstream doesn't make it so. + r = report({ plan: p, outcome: 'success', output: answer({ findings: [finding({ severity: 'Upstream' })] }), head: HEAD, classify: theirs }); + assert.equal(r.code, 1); + assert.match(r.body, /^### Important\n- \*\*src\/feed\.mjs:12\*\*/m); + // No scope (not an upstream merge): an Upstream finding is Important. + r = report({ plan: { ...p, scope: null }, outcome: 'success', output: answer({ findings: [finding({ severity: 'Upstream', file: 'up/Player.java' })] }), head: HEAD }); + assert.equal(r.code, 1); + assert.doesNotMatch(r.body, /### Upstream/); +}); + test('the same head, or a rebase with nothing new, keeps the last verdict without a review', () => { assert.equal(report({ plan: { mode: 'same', round: 1, open: [open1] }, head: HEAD }).code, 1); assert.equal(report({ plan: { mode: 'same', round: 1, open: [] }, head: HEAD }).code, 0); @@ -171,7 +204,7 @@ test('the same head, or a rebase with nothing new, keeps the last verdict withou }); // The two workflow steps against a stub gh. -function cli(t, comments = []) { +function cli(t, comments = [], scope = null) { const dir = mkdtempSync(path.join(tmpdir(), 'review-cli-')); t.after(() => rmSync(dir, { recursive: true, force: true })); mkdirSync(path.join(dir, 'bin')); @@ -188,8 +221,10 @@ esac `); chmodSync(path.join(dir, 'bin/gh'), 0o755); writeFileSync(path.join(dir, 'out'), ''); + // The repo's own scope, if any, is never the one under test: a stub, or none. + if (scope) writeFileSync(path.join(dir, 'scope.mjs'), scope); const base = { ...process.env, PATH: `${dir}/bin:${process.env.PATH}`, STUB: dir, RUNNER_TEMP: dir, GITHUB_OUTPUT: path.join(dir, 'out'), - GITHUB_REPOSITORY: 'tomdebres/devkit', PR: '12', HEAD_SHA: HEAD }; + GITHUB_REPOSITORY: 'tomdebres/devkit', PR: '12', HEAD_SHA: HEAD, REVIEW_SCOPE: path.join(dir, 'scope.mjs') }; const step = (cmd, env = {}) => { const r = spawnSync('node', [SCRIPT, cmd], { env: { ...base, ...env }, encoding: 'utf8' }); return { code: r.status, out: r.stdout + r.stderr }; @@ -234,3 +269,24 @@ test('the same head is not reviewed twice: plan says "same" and the verdict stan assert.equal(step('report', { PLAN_OUTCOME: 'success', CLAUDE_OUTCOME: 'skipped' }).code, 1); assert.equal(read('posted.md'), ''); }); + +test('a repo\'s scope: plan puts its context in the prompt, report lets it set Upstream; a scope that throws leaves nothing upstream\'s', (t) => { + const SCOPE = `export const scope = ({ head }) => ({ context: 'Upstream merge of 1.1: up/ is upstream\\'s.', head }); +export const classify = (fs, s, { head }) => fs.map((f) => ({ ...f, severity: f.file.startsWith('up/') && s.head === head ? 'Upstream' : 'Important' })); +`; + let { step, read } = cli(t, [], SCOPE); + assert.equal(step('plan').code, 0); + assert.match(read('out'), /Review the whole PR[^\n]*\n\nUpstream merge of 1\.1: up\/ is upstream's\./); + let r = step('report', { PLAN_OUTCOME: 'success', CLAUDE_OUTCOME: 'success', FINDINGS: answer({ findings: [finding({ file: 'up/Player.java' })] }) }); + assert.equal(r.code, 0, r.out); + assert.match(read('posted.md'), /^### Upstream /m); + r = step('report', { PLAN_OUTCOME: 'success', CLAUDE_OUTCOME: 'success', FINDINGS: answer({ findings: [finding({ severity: 'Upstream', file: 'fork/Flavour.java' })] }) }); + assert.equal(r.code, 1, r.out); + + ({ step, read } = cli(t, [], 'export const scope = () => { throw new Error("no upstream"); };\nexport const classify = (fs) => fs;\n')); + r = step('plan'); + assert.equal(r.code, 0, r.out); + assert.match(r.out, /^::warning::the review scope failed: no upstream; nothing counts as upstream's$/m); + r = step('report', { PLAN_OUTCOME: 'success', CLAUDE_OUTCOME: 'success', FINDINGS: answer({ findings: [finding({ severity: 'Upstream', file: 'up/Player.java' })] }) }); + assert.equal(r.code, 1, r.out); +}); diff --git a/test/risk-tier.test.mjs b/test/risk-tier.test.mjs new file mode 100644 index 0000000..f4d590a --- /dev/null +++ b/test/risk-tier.test.mjs @@ -0,0 +1,390 @@ +// Risk tier (scripts/risk-tier.mjs), from devkit's templates/risk-tier.test.mjs +// (kit-install --risk-tier): change it there, not here. First this repo's own +// setup: its high-risk table (REVIEW.md, or .github/high-risk-paths.md in a +// public repo), the CODEOWNERS made from it and the +// two workflows. Then the script against a fixed table: which paths it matches, +// the verdict, and the "Risk tier" job and a review's rerun end to end against +// a stub gh on PATH. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { execFileSync, spawnSync } from 'node:child_process'; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import path from 'node:path'; +import { + APPROVER, codeowners, decide, fromNameStatus, fromPullFiles, globToRegExp, match, outsider, parseRules, readTable, staleRun, +} from '../scripts/risk-tier.mjs'; + +const ROOT = path.resolve(import.meta.dirname, '..'); +const SCRIPT = path.join(ROOT, 'scripts/risk-tier.mjs'); +const HEAD = 'a'.repeat(40), OLD = 'b'.repeat(40); +const REPO = 'owner/repo'; + +// ---- this repo --------------------------------------------------------------- + +const table = readTable(ROOT); +const ours = parseRules(table.text); + +test('the high-risk table is there, every row with a reason', () => { + for (const r of ours) assert.ok(r.why.length > 20, `${r.glob}: "${r.why}"`); +}); + +test('every row names files that exist: a rename can\'t quietly drop a path off the list', () => { + const files = execFileSync('git', ['ls-files', '--cached', '--others', '--exclude-standard'], { cwd: ROOT, encoding: 'utf8' }) + .split('\n').filter(Boolean); + for (const r of ours) { + assert.ok(files.some((f) => r.re.test(f)), `${r.glob} matches no file in the repo`); + } +}); + +test('the gate guards itself: its table, script, workflows and CODEOWNERS are high-risk', () => { + for (const p of [table.file, 'scripts/risk-tier.mjs', '.github/workflows/risk-tier.yml', + '.github/workflows/risk-tier-review.yml', '.github/CODEOWNERS']) { + assert.ok(ours.some((r) => r.counts === 'any' && r.re.test(p)), `${p} isn't on the list`); + } +}); + +test('.github/CODEOWNERS is what the table generates', () => { + assert.equal(readFileSync(path.join(ROOT, '.github/CODEOWNERS'), 'utf8'), codeowners(ours), + 'regenerate: node scripts/risk-tier.mjs codeowners > .github/CODEOWNERS'); +}); + +test('the workflow runs main\'s code for any base, and reruns when the base changes', () => { + const yml = readFileSync(path.join(ROOT, '.github/workflows/risk-tier.yml'), 'utf8'); + assert.match(yml, /^ {2}pull_request_target:$/m); + assert.match(yml, /^ {4}name: Risk tier$/m); + assert.match(yml, /^ {10}ref: \$\{\{ github\.event\.repository\.default_branch \}\}$/m); + assert.doesNotMatch(yml, /base\.ref|head\.ref|head\.sha|refs\/pull/); + const types = yml.slice(yml.indexOf('pull_request_target:'), yml.indexOf('concurrency:')); + for (const t of ['opened', 'synchronize', 'reopened', 'edited', 'ready_for_review']) assert.match(types, new RegExp(`- ${t}$`, 'm')); + // Labels decide nothing, so they start no run. + assert.doesNotMatch(types, /labeled/); +}); + +test('a review reports no Risk tier of its own; its workflow reruns main\'s instead', () => { + const dir = path.join(ROOT, '.github/workflows'); + const tier = readFileSync(path.join(dir, 'risk-tier.yml'), 'utf8'); + assert.doesNotMatch(tier, /^ {2}pull_request_review:/m); + const yml = readFileSync(path.join(dir, 'risk-tier-review.yml'), 'utf8'); + assert.match(yml, /^ {2}pull_request_review:\n {4}types:\n {6}- submitted\n {6}- dismissed\n/m); + assert.match(yml, /^ {2}actions: write$/m); + assert.match(yml, /^ {10}ref: \$\{\{ github\.event\.repository\.default_branch \}\}$/m); + assert.match(yml, /node scripts\/risk-tier\.mjs rerun --repo "\$GITHUB_REPOSITORY" --pr "\$PR"$/m); + assert.match(yml, /group: risk-tier-review-/); + // No other job may answer for the required check. + for (const f of readdirSync(dir).filter((f) => /\.ya?ml$/.test(f) && f !== 'risk-tier.yml')) { + assert.doesNotMatch(readFileSync(path.join(dir, f), 'utf8'), /^\s*name: Risk tier\s*$/m, f); + } +}); + +// ---- the script, against a fixed table --------------------------------------- + +const TABLE = `# Review + + +| Path | Counts | Why | +|---|---|---| +| \`src/auth.mjs\` | any | Who the caller is. | +| \`schema.sql\` | any | The live database's shape. | +| \`**/*.entitlements\` | any | What the signed app may do. | +| \`.github/**\` | any | The gates themselves. | +| \`REVIEW.md\` | any | This list. | +| \`test/**\` | deleted | A deleted test is a weaker spec. | +| \`ios/*Tests/**\` | deleted | A deleted iOS test is a weaker spec. | + +`; +const rules = parseRules(TABLE); +const touched = (...lines) => match(rules, fromNameStatus(lines.join('\n'))); +const paths = (...lines) => touched(...lines).map((m) => m.path); + +// A copy of the script beside the fixed table, as a checkout would hold them. +function fixture(t, table = 'REVIEW.md') { + const dir = mkdtempSync(path.join(tmpdir(), 'risk-tier-')); + t.after(() => rmSync(dir, { recursive: true, force: true })); + mkdirSync(path.join(dir, 'repo/scripts'), { recursive: true }); + mkdirSync(path.join(dir, 'repo/.github'), { recursive: true }); + writeFileSync(path.join(dir, 'repo/scripts/risk-tier.mjs'), readFileSync(SCRIPT)); + writeFileSync(path.join(dir, 'repo', table), TABLE); + return { dir, script: path.join(dir, 'repo/scripts/risk-tier.mjs') }; +} + +test('a table that is not three columns of any/deleted with a reason is refused', () => { + const block = (rows) => `\n| Path | Counts | Why |\n|---|---|---|\n${rows}\n`; + assert.equal(parseRules(block('| `a.txt` | any | Because it matters. |')).length, 1); + assert.throws(() => parseRules('no table'), /no /); + assert.throws(() => parseRules(block('| `a.txt` | any |')), /three-column/); + assert.throws(() => parseRules(block('| `a.txt` | sometimes | Because. |')), /not any or deleted/); + assert.throws(() => parseRules(block('| `a.txt` | any | |')), /no reason/); + assert.throws(() => parseRules(block('| `/a.txt` | any | Because. |')), /root-relative/); + assert.throws(() => parseRules(block('')), /empty/); +}); + +test('globs: * stays in one directory, ** crosses any number, **/ may be none', () => { + const yes = (g, p) => assert.ok(globToRegExp(g).test(p), `${g} ~ ${p}`); + const no = (g, p) => assert.ok(!globToRegExp(g).test(p), `${g} !~ ${p}`); + yes('schema.sql', 'schema.sql'); no('schema.sql', 'test/schema.sql'); no('schema.sql', 'schema.sqlx'); + yes('.github/**', '.github/workflows/ci.yml'); yes('.github/**', '.github/CODEOWNERS'); no('.github/**', 'x.github/a'); + yes('**/*.entitlements', 'ios/Watch/Watch.entitlements'); yes('**/*.entitlements', 'a.entitlements'); + no('**/*.entitlements', 'ios/a.entitlements.bak'); + yes('ios/*Tests/**', 'ios/AppTests/DayTests.swift'); yes('ios/*Tests/**', 'ios/AppUITests/a/b.swift'); + no('ios/*Tests/**', 'ios/App/Tests/x.swift'); no('src/?.mjs', 'src/ab.mjs'); yes('src/?.mjs', 'src/a.mjs'); + yes('scripts/run-*.sh', 'scripts/run-a.sh'); no('scripts/run-*.sh', 'scripts/sub/run-a.sh'); +}); + +test('an ordinary change matches nothing; a high-risk one is listed with its reason', () => { + assert.deepEqual(touched('M\tsrc/server.mjs', 'A\tsrc/new.mjs', 'M\tios/App/TodayView.swift', 'M\tREADME.md'), []); + const [m] = touched('M\tsrc/server.mjs', 'M\tschema.sql'); + assert.equal(m.path, 'schema.sql'); + assert.match(m.why, /live database/); + assert.deepEqual(paths('M\tios/Widgets/Widgets.entitlements', 'M\t.github/workflows/ci.yml'), + ['ios/Widgets/Widgets.entitlements', '.github/workflows/ci.yml']); + // Once per path, however many rows match it. + assert.deepEqual(paths('M\tschema.sql', 'M\tschema.sql'), ['schema.sql']); +}); + +test('tests count only when deleted or renamed away; adding or editing one is ordinary', () => { + assert.deepEqual(paths('A\ttest/new.test.mjs', 'M\ttest/auth.test.mjs', 'M\tios/AppTests/DayTests.swift'), []); + assert.deepEqual(paths('D\ttest/auth.test.mjs'), ['test/auth.test.mjs (deleted)']); + assert.deepEqual(paths('D\tios/AppUITests/SmokeUITests.swift'), ['ios/AppUITests/SmokeUITests.swift (deleted)']); + assert.deepEqual(paths('R100\ttest/auth.test.mjs\tdocs/auth.test.mjs'), ['test/auth.test.mjs (renamed to docs/auth.test.mjs)']); +}); + +test('a high-risk file renamed away still counts, by its old path', () => { + assert.deepEqual(paths('R095\tsrc/auth.mjs\tsrc/who.mjs'), ['src/auth.mjs']); + assert.deepEqual(paths('R100\tsrc/a.mjs\tsrc/auth.mjs'), ['src/auth.mjs']); +}); + +test('GitHub\'s file list reads the same as git\'s', () => { + const files = [ + { filename: 'src/server.mjs', status: 'modified' }, + { filename: 'test/x.test.mjs', status: 'removed' }, + { filename: 'src/who.mjs', status: 'renamed', previous_filename: 'src/auth.mjs' }, + ]; + assert.deepEqual(match(rules, fromPullFiles(files)).map((m) => m.path), ['test/x.test.mjs (deleted)', 'src/auth.mjs']); +}); + +test('the verdict: a high-risk path needs Tom\'s review of the head; an ordinary path passes', () => { + const matches = touched('M\tschema.sql'); + assert.deepEqual(decide({ matches, reviews: [], headSha: HEAD }), { pass: false, why: `needs Tom: an approving review by ${APPROVER} on aaaaaaa` }); + assert.deepEqual(decide({ matches, reviews: [{ user: APPROVER, state: 'APPROVED', commit_id: HEAD }], headSha: HEAD }), + { pass: true, why: `approved: review by ${APPROVER} on aaaaaaa` }); + assert.deepEqual(decide({ matches: [], reviews: [], headSha: HEAD }), { pass: true, why: 'no high-risk paths' }); +}); + +test('on a public repo an outsider\'s PR needs Tom\'s review of the head, whatever it touches', () => { + const repo = (priv) => ({ full_name: REPO, private: priv }); + const pr = (login, head = REPO, priv = false) => ({ user: { login }, base: { repo: repo(priv) }, head: { repo: head && { full_name: head } } }); + assert.equal(outsider(pr('tomdebres-agent')), null); + assert.equal(outsider(pr(APPROVER)), null); + assert.equal(outsider(pr('someone')), 'opened by someone'); + assert.equal(outsider(pr('dependabot[bot]')), 'opened by dependabot[bot]'); + assert.equal(outsider(pr('tomdebres-agent', 'someone/repo')), 'from someone/repo'); + assert.equal(outsider(pr('tomdebres-agent', null)), 'from a deleted fork'); + // A private repo, or a PR GitHub didn't describe, has no outsiders. + assert.equal(outsider(pr('someone', 'someone/repo', true)), null); + assert.equal(outsider({ head: { sha: HEAD } }), null); + const outside = 'opened by someone'; + assert.deepEqual(decide({ matches: [], reviews: [], headSha: HEAD, outside }), { pass: false, why: `needs Tom: an approving review by ${APPROVER} on aaaaaaa` }); + assert.equal(decide({ matches: [], reviews: [{ user: APPROVER, state: 'APPROVED', commit_id: HEAD }], headSha: HEAD, outside }).pass, true); + assert.equal(decide({ matches: [], reviews: [{ user: APPROVER, state: 'APPROVED', commit_id: OLD }], headSha: HEAD, outside }).pass, false); +}); + +test('a review approves only from the approver, on the head commit, as the latest verdict there', () => { + const matches = touched('M\tschema.sql'); + const r = (o) => ({ user: APPROVER, state: 'APPROVED', commit_id: HEAD, ...o }); + const pass = (...reviews) => decide({ matches, reviews, headSha: HEAD }).pass; + assert.equal(pass(r()), true); + assert.equal(pass(r({ commit_id: OLD })), false); + assert.equal(pass(r({ user: 'tomdebres-agent' })), false); + assert.equal(pass(r({ state: 'DISMISSED' })), false); + assert.equal(pass(r({ state: 'COMMENTED' })), false); + assert.equal(pass(r(), r({ state: 'CHANGES_REQUESTED' })), false); + assert.equal(pass(r({ state: 'CHANGES_REQUESTED' }), r()), true); + assert.equal(pass(r(), r({ state: 'COMMENTED' })), true); +}); + +test('CODEOWNERS names the approver on every "any" row and leaves the deleted-only rows to Risk tier', () => { + const generated = codeowners(rules); + assert.match(generated, new RegExp(`^/schema\\.sql @${APPROVER}$`, 'm')); + assert.match(generated, new RegExp(`^\\*\\.entitlements @${APPROVER}$`, 'm')); + assert.match(generated, new RegExp(`^/\\.github/\\*\\* @${APPROVER}$`, 'm')); + assert.doesNotMatch(generated, /^\/?test\//m); + assert.doesNotMatch(generated, /Tests/); +}); + +// The job as GitHub runs it: gh answers from files, and logs every call. +// `runs` is what each successive look at the Risk tier runs finds; the last +// answer repeats. +function job(t, { files, labels = [], reviews = [], state = 'open', runs = [[]], cmd = 'check', refuse = false, pr = {}, table = 'REVIEW.md' }) { + const { dir, script } = fixture(t, table); + mkdirSync(path.join(dir, 'bin')); + const lines = (rows) => rows.map((x) => JSON.stringify(x)).join('\n'); + writeFileSync(path.join(dir, 'pr.json'), JSON.stringify({ state, labels: labels.map((name) => ({ name })), ...pr, head: { sha: HEAD, ...pr.head } })); + writeFileSync(path.join(dir, 'files.jsonl'), lines(files)); + writeFileSync(path.join(dir, 'reviews.jsonl'), lines(reviews)); + runs.forEach((r, i) => writeFileSync(path.join(dir, `runs-${i + 1}.jsonl`), lines(r))); + if (refuse) writeFileSync(path.join(dir, 'refuse'), ''); + writeFileSync(path.join(dir, 'bin/gh'), String.raw`#!/bin/bash +echo "gh $*" >> "$STUB/calls" +case "$*" in + "api repos/${REPO}/actions/workflows/risk-tier.yml/runs?head_sha=${HEAD}&event=pull_request_target&per_page=100 "*) + n=$(( $(cat "$STUB/looks" 2>/dev/null || echo 0) + 1 )); echo "$n" > "$STUB/looks" + while [ ! -f "$STUB/runs-$n.jsonl" ]; do n=$((n - 1)); done + cat "$STUB/runs-$n.jsonl" ;; + *"pulls/12/files"*) cat "$STUB/files.jsonl" ;; + *"pulls/12/reviews"*) cat "$STUB/reviews.jsonl" ;; + "api repos/${REPO}/pulls/12") cat "$STUB/pr.json" ;; + "api -X "*) if [ -f "$STUB/refuse" ]; then echo "gh: HTTP 403" >&2; exit 1; fi ;; + *) echo "unexpected: $*" >&2; exit 1 ;; +esac +`); + chmodSync(path.join(dir, 'bin/gh'), 0o755); + return (...extra) => { + const env = { + ...process.env, PATH: `${dir}/bin:${process.env.PATH}`, STUB: dir, GITHUB_STEP_SUMMARY: path.join(dir, 'summary'), + RISK_TIER_POLL_MS: '1', RISK_TIER_WAIT_MS: '2000', + }; + const r = spawnSync('node', [script, cmd, '--repo', REPO, '--pr', '12', ...extra], { env, encoding: 'utf8' }); + const read = (f) => (existsSync(path.join(dir, f)) ? readFileSync(path.join(dir, f), 'utf8') : ''); + return { code: r.status, out: r.stdout + r.stderr, calls: read('calls'), summary: read('summary') }; + }; +} +const approved = [{ user: APPROVER, state: 'APPROVED', commit_id: HEAD }]; + +test('the job fails on a high-risk path without approval, and lists what it matched', (t) => { + const run = job(t, { files: [{ filename: 'schema.sql', status: 'modified' }, { filename: 'src/server.mjs', status: 'modified' }] }); + const { code, out, summary } = run(); + assert.equal(code, 1, out); + assert.match(out, /^Risk tier: 1 high-risk path \(REVIEW\.md\)$/m); + assert.match(out, /^ {2}schema\.sql: The live database's shape/m); + assert.match(out, /^FAIL: needs Tom: /m); + assert.match(summary, /schema\.sql/); +}); + +test('the job passes on Tom\'s review of the head, and takes needs-tom off; an ordinary PR passes as it is', (t) => { + const files = [{ filename: 'src/auth.mjs', status: 'modified' }]; + let r = job(t, { files, reviews: approved, labels: ['needs-tom'] })(); + assert.equal(r.code, 0, r.out); + assert.match(r.out, new RegExp(`^pass: approved: review by ${APPROVER} on aaaaaaa\\nneeds-tom removed$`, 'm')); + assert.match(r.calls, /^gh api -X DELETE repos\/owner\/repo\/issues\/12\/labels\/needs-tom$/m); + // Taking the label off is housekeeping: GitHub refusing it changes no verdict. + r = job(t, { files, reviews: approved, labels: ['needs-tom'], refuse: true })(); + assert.equal(r.code, 0, r.out); + assert.match(r.out, /^needs-tom left on: GitHub refused to remove it$/m); + + r = job(t, { files: [{ filename: 'src/server.mjs', status: 'modified' }, { filename: 'test/x.test.mjs', status: 'added' }] })(); + assert.equal(r.code, 0, r.out); + assert.match(r.out, /^Risk tier: no high-risk paths in 2 changed files$/m); + assert.doesNotMatch(r.calls, /-X/); +}); + +test('a label passes nothing, and nor does an approval of an earlier commit', (t) => { + const files = [{ filename: 'REVIEW.md', status: 'modified' }]; + const r = job(t, { files, labels: ['tom-approved', 'needs-tom'] })(); + assert.equal(r.code, 1, r.out); + assert.match(r.out, new RegExp(`^FAIL: needs Tom: an approving review by ${APPROVER} on aaaaaaa$`, 'm')); + assert.doesNotMatch(r.calls, /-X/); + const old = job(t, { files, reviews: [{ user: APPROVER, state: 'APPROVED', commit_id: OLD }] })(); + assert.equal(old.code, 1, old.out); +}); + +test('a public checkout reads its own table even beside a REVIEW.md with one (a link into the notes)', (t) => { + const { dir } = fixture(t, '.github/high-risk-paths.md'); + writeFileSync(path.join(dir, 'repo/REVIEW.md'), TABLE.replace('schema.sql', 'notes-only.sql')); + assert.equal(readTable(path.join(dir, 'repo')).file, '.github/high-risk-paths.md'); + rmSync(path.join(dir, 'repo/.github/high-risk-paths.md')); + assert.equal(readTable(path.join(dir, 'repo')).file, 'REVIEW.md'); +}); + +test('a public repo\'s table is .github/high-risk-paths.md, and an outsider\'s ordinary PR fails until Tom approves it', (t) => { + const files = [{ filename: 'src/server.mjs', status: 'modified' }]; + const pr = { user: { login: 'someone' }, base: { repo: { full_name: REPO, private: false } }, head: { repo: { full_name: 'someone/repo' } } }; + let r = job(t, { files, pr, table: '.github/high-risk-paths.md' })(); + assert.equal(r.code, 1, r.out); + assert.match(r.out, /^ {2}an outside pull request \(opened by someone\): it never merges without Tom$/m); + assert.match(r.out, /^FAIL: needs Tom: /m); + r = job(t, { files: [{ filename: 'schema.sql', status: 'modified' }], pr, table: '.github/high-risk-paths.md' })(); + assert.match(r.out, /^Risk tier: 1 high-risk path \(\.github\/high-risk-paths\.md\)$/m); + r = job(t, { files, pr, reviews: approved, table: '.github/high-risk-paths.md' })(); + assert.equal(r.code, 0, r.out); + // The bot's own PR on the same public repo is ordinary. + r = job(t, { files, pr: { ...pr, user: { login: 'tomdebres-agent' }, head: { repo: { full_name: REPO } } }, table: '.github/high-risk-paths.md' })(); + assert.equal(r.code, 0, r.out); + assert.match(r.out, /^pass: no high-risk paths$/m); +}); + +const run = (id, conclusion, { status = 'completed', event = 'pull_request_target' } = {}) => ({ id, event, status, conclusion }); + +test('which run a review reruns: the newest pull_request_target one, finished, when it disagrees', () => { + assert.equal(staleRun([], true).action, 'none'); + // Tom approved after a red: rerun that run, not the cancelled older one, and + // never a run from another event. + const runs = [run(1, 'cancelled'), run(2, 'failure'), run(3, 'success', { event: 'pull_request_review' })]; + assert.deepEqual([staleRun(runs, true).action, staleRun(runs, true).run.id], ['rerun', 2]); + assert.equal(staleRun(runs, false).action, 'none'); + // A dismissed approval turns a green run red. + assert.equal(staleRun([run(2, 'success')], false).action, 'rerun'); + assert.equal(staleRun([run(2, 'success')], true).action, 'none'); + // A run still going may have read the PR before the review: wait for it. + assert.equal(staleRun([run(2, 'failure'), run(4, null, { status: 'in_progress' })], true).action, 'wait'); + assert.equal(staleRun([run(4, null, { status: 'queued' })], false).action, 'wait'); +}); + +test('Tom\'s approving review reruns the red Risk tier run, with nobody rerunning it', (t) => { + const files = [{ filename: 'REVIEW.md', status: 'modified' }]; + const r = job(t, { files, reviews: approved, cmd: 'rerun', runs: [[run(40280097664, 'cancelled'), run(40280100259, 'failure')]] })(); + assert.equal(r.code, 0, r.out); + assert.match(r.calls, /^gh api -X POST repos\/owner\/repo\/actions\/runs\/40280100259\/rerun$/m); + assert.equal(r.calls.match(/-X POST/g).length, 1); + assert.match(r.out, new RegExp(`^Risk tier on aaaaaaa: pass \\(approved: review by ${APPROVER} on aaaaaaa\\); run 40280100259 says failure, the verdict now is pass: rerun$`, 'm')); +}); + +test('a review that changes nothing reruns nothing; one mid-run waits for it to finish', (t) => { + const files = [{ filename: 'REVIEW.md', status: 'modified' }]; + // A comment, not an approval: the red stands. + let r = job(t, { files, reviews: [{ user: APPROVER, state: 'COMMENTED', commit_id: HEAD }], cmd: 'rerun', runs: [[run(7, 'failure')]] })(); + assert.equal(r.code, 0, r.out); + assert.doesNotMatch(r.calls, /-X/); + assert.match(r.out, /run 7 already says failure$/m); + // An ordinary PR passed already. + r = job(t, { files: [{ filename: 'src/server.mjs', status: 'modified' }], cmd: 'rerun', runs: [[run(7, 'success')]] })(); + assert.equal(r.code, 0, r.out); + assert.doesNotMatch(r.calls, /-X/); + // A run that read the PR before Tom's review landed, and ends red. + r = job(t, { files, reviews: approved, cmd: 'rerun', runs: [[run(8, null, { status: 'in_progress' })], [run(8, null, { status: 'in_progress' })], [run(8, 'failure')]] })(); + assert.equal(r.code, 0, r.out); + assert.match(r.calls, /^gh api -X POST repos\/owner\/repo\/actions\/runs\/8\/rerun$/m); + assert.equal(r.calls.match(/actions\/workflows/g).length, 3); + // One that never finishes: no rerun, and the job says so. + r = job(t, { files, reviews: approved, cmd: 'rerun', runs: [[run(9, null, { status: 'queued' })]] })(); + assert.equal(r.code, 1, r.out); + assert.doesNotMatch(r.calls, /-X/); + assert.match(r.out, /run 9 is queued still; not rerun$/m); + // A merged PR has nothing left to gate. + r = job(t, { files, reviews: approved, state: 'closed', cmd: 'rerun', runs: [[run(7, 'failure')]] })(); + assert.equal(r.code, 0, r.out); + assert.doesNotMatch(r.calls, /actions|-X/); + assert.equal(job(t, { files, cmd: 'rerun' })('--pr', 'x').code, 2); +}); + +test('the job fails closed when GitHub can\'t be read, and on bad arguments', (t) => { + const r0 = job(t, { files: [] }); + // The stub answers only for #12; for #13 it fails as gh does on a 404. + const r = r0('--pr', '13'); + assert.equal(r.code, 2, r.out); + assert.match(r.out, /^risk-tier: Command failed: gh api repos\/owner\/repo\/pulls\/13/m); + assert.equal(r0('--pr').code, 2); + assert.equal(r0('--pr', 'twelve').code, 2); + assert.equal(spawnSync('node', [SCRIPT, 'nonsense'], { encoding: 'utf8' }).status, 2); +}); + +test('match reads git\'s name-status on stdin and prints path and reason, from a copy reached through a symlink', (t) => { + const { dir, script } = fixture(t); + const out = execFileSync('node', [script, 'match'], { input: 'M\tsrc/server.mjs\nD\ttest/a.test.mjs\nM\tschema.sql\n', encoding: 'utf8' }); + assert.deepEqual(out.trim().split('\n').map((l) => l.split('\t')[0]), ['test/a.test.mjs (deleted)', 'schema.sql']); + assert.equal(execFileSync('node', [script, 'match'], { input: 'M\tsrc/server.mjs\n', encoding: 'utf8' }), ''); + // A land script may run main's copy through a link to its checkout. + symlinkSync(path.join(dir, 'repo'), path.join(dir, 'link')); + const linked = execFileSync('node', [path.join(dir, 'link/scripts/risk-tier.mjs'), 'match'], { input: 'M\tschema.sql\n', encoding: 'utf8' }); + assert.match(linked, /^schema\.sql\t/); +}); diff --git a/verify b/verify index fe3d1c3..edb0590 100755 --- a/verify +++ b/verify @@ -112,6 +112,10 @@ sys.exit(bad)' "${html[@]}" # The reviewer's bookkeeping (devkit's, verbatim). Node is on the runner and the Mac. step 'reviewer rounds (node --test test/review-round.test.mjs)' \ node --test test/review-round.test.mjs +# Risk tier's matcher, its table (.github/high-risk-paths.md) and CODEOWNERS +# (devkit's, verbatim). +step 'risk tier (node --test test/risk-tier.test.mjs)' \ + node --test test/risk-tier.test.mjs if [ "$mode" = full ]; then # ---- full only: slow, or needs something shared -------------------------