Skip to content

feat(core): DiffViewer moves to Core #109815

feat(core): DiffViewer moves to Core

feat(core): DiffViewer moves to Core #109815

Workflow file for this run

# Copyright (c) Meta Platforms, Inc. and affiliates.
# Review signal — deterministic labels that route reviews and gate auto-merge.
#
# On PR open/update this workflow inspects the changed file paths (never the
# code itself) and the PR author, then applies up to two labels:
#
# needs:code-review — HIGH-RISK code areas: a new package, a new
# component/module (in core — NOT lab, which is the
# canary staging area), any runtime change under
# core/src, or public API surface, NOT confined to
# low-risk areas (themes, templates, sandbox, storybook,
# docsite). Requests review from CODEOWNERS. ENGOWNERS
# self-serve code. A DESIGNOWNER author also self-serves
# an existing-file Core diff only when the trusted-base
# classifier proves every runtime line appearance-only
# and no other code reason applies.
#
# needs:design-review — DESIGN-AFFECTING changes anywhere: StyleX styling,
# theme/token files, or a template's .tsx. Keyed on
# visual signals only — NOT docs and NOT "a new dir
# appeared" (styleless modules don't count). NOT
# area-gated — a theme/template edit is where design
# lives. Requests review from DESIGNOWNERS. Skipped when
# the author is a DESIGNOWNER (design self-serves design).
# Besides the path signals, the DIFF CONTENT is scored
# by .github/scripts/lib/classify-visual.js (#3667) —
# most component styling here is an inline stylex.create
# edit in a .tsx, which no path pattern can see.
#
# The CODE label DISABLES auto-merge so the PR can't merge unattended (the
# design label is advisory and does not). Both are cleared when an entitled
# owner approves (code → CODEOWNER; design → DESIGNOWNER
# or CODEOWNER). For an author with write or admin permission, the review
# app named in vars.REVIEW_APP also clears the code gate with its latest
# approval on the exact head. Code detection is path-based and deterministic; design adds a
# content-based diff score (deterministic too — same diff, same score).
#
# HARD GATE (code review only): this emits a "review-required" COMMIT STATUS.
# When code review is needed it's set to `pending`, which blocks a required
# status context AND renders as a neutral yellow "waiting" dot (not a red
# failure), so a PR awaiting review doesn't add red noise to the queue. An
# entitled owner's code approval flips it to `success`. Keep "review-required"
# a REQUIRED status check in branch protection: it blocks non-admin merges even
# for internal contributors who have write access.
#
# Design review is ADVISORY: a design-affecting change is labeled
# needs:design-review and design owners are requested, but it does NOT block
# the merge. All contributor (non-owner) PRs require code review; engineering
# owners self-serve code, and design owners self-serve only classifier-proven
# appearance-only Core runtime changes.
#
# Uses pull_request_target so it can label / request reviewers / disable
# auto-merge on fork PRs. An engineering owner's owner command
# (`/approve-spec`, `/revoke-spec`, an issue_comment in the base context) also
# runs it, so the command re-evaluates the code half on a fork PR whose review
# event GitHub held for approval. It reads the PR file list, diff text, changed Core
# base/head source bytes, and the base/head bytes of each changed file that holds a
# CSS-named line (the classifier's style-context test) as inert API data. The approval helper comes from the
# trusted workflow SHA; the visual classifier comes from the PR base ref. It reads
# eng/design owner lists from repository VARIABLES (vars.ENGOWNERS /
# vars.DESIGNOWNERS) — no checkout and no execution of PR-controlled code.
# Do not add checkout or build steps to the flag job.
#
# ONE REVIEW GATE (spec:AST-030 FR15): "review-required" carries code review and
# the spec half the spec-owner job decides (DEC-14) from the trusted default branch.
name: Review signal
on:
pull_request_target:
branches: ['main']
types: [opened, synchronize, reopened, ready_for_review, converted_to_draft]
pull_request_review:
types: [submitted, dismissed]
# Owner commands for the spec-owner job, which also run the flag job so the
# command re-evaluates both halves of the gate (a fork's review event can be
# held for approval). The job-level filters skip every other comment before a
# runner starts.
issue_comment:
types: [created]
# Manual re-trigger. The App only auto-runs on the PR events above, so if it
# ever misses one (e.g. the workflow was added after a PR was opened, leaving
# the required "review-required" check stuck as Expected/pending), this is the
# recovery lever. Leave `pr` blank to re-flag EVERY open, non-draft PR
# (backfill); pass a number to re-flag just that one. A backfill too large for
# one job splits with `batch` k/n (PRs whose number mod n is k-1).
workflow_dispatch:
inputs:
pr:
description: 'PR number to re-flag (blank = every open, non-draft PR)'
required: false
type: string
batch:
description: 'With a blank pr: re-flag only PRs whose number mod n is k-1 (k/n, e.g. 2/4)'
required: false
type: string
permissions: {}
env:
CODE_LABEL: 'needs:code-review'
DESIGN_LABEL: 'needs:design-review'
COMMUNITY_LABEL: 'community'
REVIEW_LABEL: needs:spec-owner-review
jobs:
# ---------------------------------------------------------------------------
# Detect signals from changed paths + author; label, request reviewers, gate.
# ---------------------------------------------------------------------------
flag:
if: >-
github.event_name == 'pull_request_target'
|| github.event_name == 'workflow_dispatch'
|| (github.event_name == 'issue_comment'
&& github.event.issue.pull_request != null
&& (startsWith(github.event.comment.body, '/approve-spec')
|| startsWith(github.event.comment.body, '/revoke-spec')))
name: Flag review signals
runs-on: ubuntu-slim
# Per PR (run-scoped for backfill-all). Only this job cancels: a cancelled
# spec-owner reconcile could leave its head without a terminal status. An
# owner-command run is run-scoped too, so a comment never cancels a pull
# request event's run (which may be the only writer of a new head's gate).
concurrency:
group: review-signal-${{ github.event_name == 'issue_comment' && format('command-{0}', github.run_id) || github.event.pull_request.number || github.event.inputs.pr || github.run_id }}
cancel-in-progress: true
permissions:
pull-requests: write
contents: read
statuses: write
checks: write
steps:
- name: Detect signals and route
uses: actions/github-script@v9
env:
ENG_OWNERS: ${{ vars.ENGOWNERS }}
DESIGN_OWNERS: ${{ vars.DESIGNOWNERS }}
REVIEW_APP: ${{ vars.REVIEW_APP }}
with:
# api.github.com 503s intermittently; an unretried one used to leave a
# PR with no review-required status at all, blocked forever on
# "Expected — waiting for status" (#5149, #5152).
retries: 3
script: |
// Wait out the repository's shared API rate limit, with the helper
// read from this workflow's own trusted commit (no checkout). The
// raw file host spends none of that budget; the API is the fallback.
{
const helperPath = '.github/scripts/lib/rate-limit-backoff.cjs';
let helperSource;
try {
const response = await fetch(`https://raw.githubusercontent.com/${context.repo.owner}/${context.repo.repo}/${context.sha}/${helperPath}`);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
helperSource = await response.text();
} catch {
const {data: helper} = await github.rest.repos.getContent({...context.repo, ref: context.sha, path: helperPath});
helperSource = Buffer.from(helper.content, 'base64').toString('utf8');
}
const helperModule = {exports: {}};
new Function('module', 'exports', 'require', helperSource)(
helperModule, helperModule.exports,
() => { throw new Error('rate-limit-backoff.cjs must stay dependency-free'); },
);
helperModule.exports.installRateLimitBackoff({github, core});
}
const { owner, repo } = context.repo;
const CODE = process.env.CODE_LABEL;
const DESIGN = process.env.DESIGN_LABEL;
const COMMUNITY = process.env.COMMUNITY_LABEL;
// Owner handles from a repository variable. An empty or unset
// list throws: it is a configuration error, never "no owners"
// (see flagOne).
function parseHandles(text) {
return ((text || '').match(/@?[A-Za-z0-9-]+/g) || [])
.map((h) => h.replace(/^@/, '').toLowerCase());
}
function ownersFromVar(name) {
const handles = parseHandles(process.env[name]);
if (!handles.length) {
throw new Error(`Owner variable ${name} is empty or unset — refusing to bucket authors from an empty list.`);
}
return handles;
}
// Resolve which PR(s) to flag. On a PR event we get the payload PR.
// On manual dispatch we take the `pr` input (one PR), or re-flag
// every open PR when it's blank (backfill / mass recovery).
let prs;
if (context.eventName === 'workflow_dispatch') {
const num = (context.payload.inputs.pr || '').trim();
if (num) {
const { data } = await github.rest.pulls.get({
owner, repo, pull_number: Number(num),
});
prs = [data];
} else {
const open = await github.paginate(github.rest.pulls.list, {
owner, repo, state: 'open', per_page: 100,
});
// A draft is re-flagged when it becomes ready
// (ready_for_review), so a backfill skips it.
const ready = open.filter(listed => !listed.draft);
// A shard keys on the PR number, so it stays the same set
// while PRs open and close between dispatches.
const batch = (context.payload.inputs.batch || '').trim();
prs = ready;
if (batch) {
const match = /^(\d+)\/(\d+)$/.exec(batch);
const [k, n] = match ? [Number(match[1]), Number(match[2])] : [0, 0];
if (!(n >= 1 && k >= 1 && k <= n)) {
core.setFailed(`batch must be k/n with 1 <= k <= n; got "${batch}".`);
return;
}
prs = ready.filter(listed => listed.number % n === k - 1);
}
core.info(
`Backfill${batch ? ` ${batch}` : ''}: re-flagging ${prs.length} of ` +
`${open.length} open PR(s); ${open.length - ready.length} draft(s) skipped.`,
);
}
} else if (context.eventName === 'issue_comment') {
// An engineering owner's owner command re-evaluates the code
// half from the PR's reviews: GitHub can hold a fork's
// pull_request_review run for approval, so the approval alone
// may never reach the gate. Anyone else's command changes
// nothing here.
const commenter = (context.payload.comment?.user?.login || '').toLowerCase();
if (!ownersFromVar('ENG_OWNERS').includes(commenter)) {
core.info(`@${commenter} is not an engineering owner; the code half is unchanged.`);
return;
}
const { data } = await github.rest.pulls.get({
owner, repo, pull_number: context.payload.issue.number,
});
prs = [data];
} else {
prs = [context.payload.pull_request];
}
let hadError = false;
const isBackfill = prs.length > 1 ||
(context.eventName === 'workflow_dispatch' &&
!(context.payload.inputs.pr || '').trim());
for (const [index, listed] of prs.entries()) {
if (isBackfill) {
// A backfill makes several calls per PR on the job token's
// hourly budget. Stop with headroom left for PR events
// (reading /rate_limit costs nothing).
const {data: limits} = await github.rest.rateLimit.get();
const {remaining, limit, reset} = limits.resources.core;
if (remaining < Math.min(1500, Math.floor(limit / 3))) {
core.setFailed(
`Backfill stopped before PR #${listed.number} (${prs.length - index} left): ` +
`${remaining} of ${limit} API requests remain until ` +
`${new Date(reset * 1000).toISOString()}; re-run after the reset.`,
);
return;
}
}
try {
// The list endpoint omits changed_files, which the file check
// below needs, so a backfill reads each PR in full.
const pr = listed.changed_files == null
? (await github.rest.pulls.get({
owner, repo, pull_number: listed.number,
})).data
: listed;
await flagOne(pr);
} catch (e) {
hadError = true;
core.warning(`Failed to flag PR #${listed.number}: ${e.message}`);
}
}
if (hadError) core.setFailed('One or more PRs failed to flag; see warnings.');
// ================= per-PR detection + routing =================
async function flagOne(pr) {
const author = pr.user.login.toLowerCase();
// Bots (Dependabot, github-actions, etc.) are our own automation,
// not community contributors, and their PRs (dep bumps, chores) are
// mechanical and CI-gated. Exempt them from both the review gates
// and the community label entirely.
const authorIsBot = pr.user.type === 'Bot' || /\[bot\]$/.test(author);
// --- Owner sets come from repo VARIABLES (vars.ENGOWNERS /
// vars.DESIGNOWNERS), passed in as env above. No file read, no
// content API — so there is nothing to 502 on. CODEOWNERS is NOT
// read here: it is GitHub-native and auto-requests its reviewers on
// every PR regardless of branch protection, which covers code
// review for contributor and design-owner PRs. These lists are
// CRITICAL: an empty/unset value would mis-bucket a real owner as a
// community contributor and wrongly gate them. So treat an empty
// owner list as a configuration error and THROW — the caller's
// per-PR try/catch then skips this PR, LEAVES ITS GATE UNTOUCHED
// (never a false success), and fails the run visibly. An unreadable
// owner list is never "no owners".
const engOwners = ownersFromVar('ENG_OWNERS');
const designOwners = ownersFromVar('DESIGN_OWNERS');
const authorIsEng = engOwners.includes(author);
const authorIsDesign = designOwners.includes(author);
// Match the trusted workflow version: an older PR base can predate
// this helper even though the running workflow requires it.
const { data: reviewDecisionFile } = await github.rest.repos.getContent({
owner, repo, ref: context.sha,
path: '.github/scripts/review-signal-decision.cjs',
});
const reviewDecisionSource = Buffer.from(
reviewDecisionFile.content,
'base64',
).toString('utf8');
const reviewDecisionModule = { exports: {} };
new Function('module', 'exports', 'require', reviewDecisionSource)(
reviewDecisionModule,
reviewDecisionModule.exports,
() => { throw new Error('review-signal-decision.cjs must stay dependency-free'); },
);
const reviewDecision = reviewDecisionModule.exports;
// One review gate (DEC-14): code review leads; success needs both.
async function publishReviewGate(codeGated, codeDescription) {
// Write, then read the spec half once more: the spec-owner job
// writes its half before it reads this one, so one of the two
// always sees the other's latest write.
let gate = null;
for (let pass = 0; pass < 2; pass++) {
let statuses = [];
try {
statuses = await github.paginate(github.rest.repos.listCommitStatusesForRef, {
owner, repo, ref: pr.head.sha, per_page: 100,
});
} catch (e) {
core.warning(`Could not read the spec decision: ${e.message}`);
}
const next = reviewDecision.composeReviewGate({
codeGated,
codeDescription,
spec: reviewDecision.readSpecGate(statuses),
});
if (gate && next.state === gate.state && next.description === gate.description) break;
gate = next;
await github.rest.repos.createCommitStatus({
owner, repo, sha: pr.head.sha,
context: 'review-required',
state: gate.state,
description: gate.description,
target_url: gate.target_url,
});
}
return gate;
}
// Bot PRs: no gate, no community label. Set the check to success so
// a required "review-required" doesn't block them, drop any stray
// gate/community labels, and stop. A pull request the review app
// opens instead waits for a trainer pass (spec:AST-030 FR15).
if (authorIsBot) {
core.info(`@${author} is a bot — exempt from review gates.`);
const current = pr.labels.map((l) => l.name);
for (const name of [CODE, DESIGN, COMMUNITY]) {
if (current.includes(name)) {
try {
await github.rest.issues.removeLabel({
owner, repo, issue_number: pr.number, name,
});
} catch (e) {
core.warning(`Could not remove ${name}: ${e.message}`);
}
}
}
if (reviewDecision.needsTrainerPass({author, reviewApp: process.env.REVIEW_APP})) {
let passed = false;
try {
const reviews = await github.paginate(github.rest.pulls.listReviews, {
owner, repo, pull_number: pr.number, per_page: 100,
});
const headPushedAt = await reviewDecision.readHeadPushedAt({
github, owner, repo, sha: pr.head.sha,
});
passed = reviewDecision.trainerPassed({reviews, headSha: pr.head.sha, headPushedAt, engOwners});
} catch (e) {
core.warning(`Could not read exact-head reviews; the trainer pass stays pending: ${e.message}`);
}
core.info(`@${author} is the review app — trainer pass ${passed ? 'given' : 'pending'}.`);
await publishReviewGate(
!passed,
passed
? reviewDecision.OWNER_CLEARED_TEXT
: reviewDecision.TRAINER_WAITING_TEXT,
);
return;
}
await publishReviewGate(false, 'Automated (bot) PR — exempt from code review.');
return;
}
// --- Changed files, at the event's head. ---
// The status and its diff always describe the event's head: the
// compare of the event's base and head SHAs names that head's
// files, while the pull request's own lists can already show a
// newer push. A compare names at most COMPARE_FILES files, so a
// larger pull request reads its file list and then confirms that
// the pull request still points at the event's head.
const COMPARE_FILES = 300;
const basehead = `${pr.base.sha}...${pr.head.sha}`;
let allFiles;
if (pr.changed_files <= COMPARE_FILES) {
const { data: compared } =
await github.rest.repos.compareCommitsWithBasehead({
owner, repo, basehead,
});
allFiles = compared.files ?? [];
} else {
allFiles = await github.paginate(github.rest.pulls.listFiles, {
owner, repo, pull_number: pr.number, per_page: 100,
});
const { data: current } = await github.rest.pulls.get({
owner, repo, pull_number: pr.number,
});
if (current.head.sha !== pr.head.sha) {
core.info(
`PR #${pr.number} moved from ${pr.head.sha} to ${current.head.sha} while its files were read; the run for the newer head decides.`,
);
return;
}
}
if (allFiles.length !== pr.changed_files) {
throw new Error(
`GitHub returned ${allFiles.length} of ${pr.changed_files} changed files; refusing to classify an incomplete PR.`,
);
}
// A change is excluded as a safe-space change only when both its
// current and previous path are safe. This keeps unsafe→safe and
// Core→safe renames visible and fail-closed.
const {files, hasSafeBoundaryRename, paths} =
reviewDecision.classifyReviewSignalPaths(allFiles);
const isSafeSpace = reviewDecision.isSafeSpace;
// Two DIFFERENT categories — do not conflate them:
//
// SAFE SPACES — experimentation / staging. Exempt from BOTH gates.
// No review of any kind is expected here.
// lab, sandbox, storybook. A rename is safe only when both the
// previous and current paths are safe.
//
// DESIGN SPACES — where design work lives. Exempt from the CODE
// gate (low-risk for code), but they TRIGGER the DESIGN gate.
// themes, templates, docsite.
//
// Both are low-risk for the CODE gate, so the code gate ignores
// their union; only the design gate cares about the distinction.
const isDesignSpace = (p) =>
/^packages\/themes\//.test(p) ||
/^packages\/cli\/templates\//.test(p) ||
/^apps\/docsite\//.test(p);
// Code gate ignores both categories.
const isCodeExempt = (p) => isSafeSpace(p) || isDesignSpace(p);
const consideredCode = paths.filter((p) => !isCodeExempt(p));
// A "source barrel" is packages/<pkg>/src/**/index.ts(x). We do NOT
// hardcode which packages are component libraries — any package's
// src barrel counts, so new packages are covered automatically.
// Safe/design spaces and lab are already excluded above.
const isSrcBarrel = (p) =>
/^packages\/[^/]+\/src\/(.+\/)?index\.tsx?$/.test(p);
// A NEW component/module is a newly-added top-level src dir barrel.
const isNewComponentBarrel = (p) =>
/^packages\/[^/]+\/src\/[^/]+\/index\.tsx?$/.test(p) &&
!isCodeExempt(p);
// Any RUNTIME change under core/src (incl. styling .tsx) is
// higher-blast-radius than a leaf change — core is what everything
// composites over, so a change there warrants review even when it's
// styling-only. Docs/tests/stories are excluded (they don't gate).
const isCoreRuntime = (p) =>
/^packages\/core\/src\/.+\.tsx?$/.test(p) &&
!/\.test\.tsx?$/.test(p) &&
!/\.doc\.mjs$/.test(p) &&
!/\.stories\.tsx?$/.test(p);
// ============ HIGH-RISK CODE ============
const codeReasons = [];
if (hasSafeBoundaryRename) {
codeReasons.push('safe-space boundary rename');
}
const newPackage = files.some(
(f) => f.status === 'added' &&
/^packages\/[^/]+\/package\.json$/.test(f.filename),
);
if (newPackage) codeReasons.push('new package');
const newComponent = files.some(
(f) => f.status === 'added' && isNewComponentBarrel(f.filename),
);
if (newComponent) codeReasons.push('new component/module');
const apiSurface = consideredCode.some(
(p) => isSrcBarrel(p) || /^packages\/[^/]+\/package\.json$/.test(p),
);
if (apiSurface && !newPackage && !newComponent) {
codeReasons.push('public API surface change');
}
const coreChange = paths.some(isCoreRuntime);
// ============ DESIGN-AFFECTING ============
// DESIGN SPACES trigger this gate; SAFE SPACES never do (both
// defined above). Keyed on visual signals, NOT on "a new dir
// appeared" (that caught infra like i18n) and NOT on docs
// (.doc.mjs / .md / content).
// - Component StyleX — visual changes to shipped components,
// anywhere except a safe space.
// - themes / templates — design spaces (themes src, template .tsx).
// - docsite — a published design surface, but only its VISUAL dirs
// (app/, components/, themes/); blog/markdown content, lib/data
// plumbing, generated output, and tests are skipped.
const isDocsiteVisual = (p) =>
/^apps\/docsite\/src\/(app|components|themes)\/.+\.(tsx|stylex\.ts)$/.test(p) &&
!/\.test\.tsx?$/.test(p);
const designReasons = [];
if (paths.some((p) => /\.stylex\.tsx?$/.test(p) && !isSafeSpace(p))) designReasons.push('StyleX styles');
if (paths.some((p) => /^packages\/themes\/.+\/src\/.+\.tsx?$/.test(p))) designReasons.push('theme/token change');
if (paths.some((p) => /^packages\/cli\/templates\/.+\.tsx$/.test(p))) designReasons.push('template change');
if (paths.some(isDocsiteVisual)) designReasons.push('docsite visual change');
// Content-based visual signal (#3667). The classifier also proves
// the narrower appearance-only exception for DESIGNOWNER authors.
// It and the diff both come from the API: trusted BASE-ref source,
// inert PR diff text. Any fetch or parse failure keeps the exception
// false, so Core runtime changes continue to require engineering.
// A diff of more files than a compare names is never classified,
// so the exception stays false.
let visualClassification = null;
if (
(coreChange || designReasons.length === 0) &&
pr.changed_files <= COMPARE_FILES
) {
try {
const { data: libFile } = await github.rest.repos.getContent({
owner, repo, ref: pr.base.sha,
path: '.github/scripts/lib/classify-visual.js',
});
const libSrc = Buffer.from(libFile.content, 'base64').toString('utf8');
const mod = { exports: {} };
new Function('module', 'exports', 'require', libSrc)(
mod, mod.exports,
() => { throw new Error('classify-visual.js must stay dependency-free'); },
);
const { data: diff } = await github.request(
'GET /repos/{owner}/{repo}/compare/{basehead}',
{ owner, repo, basehead,
headers: { accept: 'application/vnd.github.diff' } },
);
const sources = {};
const coreRuntimeFiles = files.filter((file) =>
isCoreRuntime(file.filename) ||
(file.previous_filename && isCoreRuntime(file.previous_filename)),
);
async function readSource(fullName, ref, filePath) {
const [sourceOwner, sourceRepo] = fullName.split('/');
const { data } = await github.rest.repos.getContent({
owner: sourceOwner,
repo: sourceRepo,
ref,
path: filePath,
});
if (Array.isArray(data) || data.type !== 'file' || !data.content) {
throw new Error(`Could not read source bytes for ${filePath}.`);
}
return Buffer.from(data.content, 'base64').toString('utf8');
}
// The source bytes only prove the appearance-only exception
// a design owner may self-serve; an engineering owner
// self-serves every code change, so their pull requests skip
// these reads (two per changed Core file).
for (const file of authorIsEng ? [] : coreRuntimeFiles) {
const previousPath = file.previous_filename || file.filename;
if (file.status !== 'modified' || previousPath !== file.filename) {
continue;
}
const [baseSource, headSource] = await Promise.all([
readSource(
pr.base.repo.full_name,
pr.base.sha,
previousPath,
),
readSource(
pr.head.repo.full_name,
pr.head.sha,
file.filename,
),
]);
sources[file.filename] = {base: baseSource, head: headSource};
}
// A CSS-named key scores only in a style context of its file
// at its own revision (the classifier's styleContextLines),
// so read each file that holds one, at each side it changed.
// A file that cannot be read keeps scoring as a style edit.
const styleSources = {};
// A classifier from a base older than the style-context test
// has no styleContextPaths; it then counts as it did.
const needed =
typeof mod.exports.styleContextPaths === 'function'
? mod.exports.styleContextPaths(String(diff), {ignorePath: isSafeSpace})
: {};
for (const [filePath, sides] of Object.entries(needed)) {
styleSources[filePath] = {};
for (const [side, repoName, ref] of [
['base', pr.base.repo.full_name, pr.base.sha],
['head', pr.head.repo.full_name, pr.head.sha],
]) {
if (!sides[side]) continue;
try {
styleSources[filePath][side] = await readSource(repoName, ref, filePath);
} catch (e) {
core.info(`No ${side} bytes for ${filePath}: ${e.message}`);
}
}
}
visualClassification = mod.exports.classifyVisualDiff(String(diff), {
ignorePath: isSafeSpace,
sources,
styleSources,
});
core.info(`visual content score: ${visualClassification.score} (${visualClassification.bucket}); appearanceOnly=${visualClassification.appearanceOnly}`);
if (
designReasons.length === 0 &&
(visualClassification.bucket === 'visual' ||
visualClassification.bucket === 'likely-visual')
) {
designReasons.push(
`visual diff content (score ${visualClassification.score})`,
);
}
} catch (e) {
core.warning(`Content-based visual classification failed closed: ${e.message}`);
}
}
const appearanceOnly = visualClassification?.appearanceOnly === true;
if (coreChange && !codeReasons.includes('new component/module')) {
codeReasons.push(appearanceOnly ? 'core visual change' : 'core change');
}
// ALL contributor (non-owner) PRs require code review. The narrow
// appearance-only exception below is available only to a DESIGNOWNER;
// external contributors stay in the normal contribution flow.
const authorIsOwner = authorIsEng || authorIsDesign;
if (!authorIsOwner) codeReasons.push('community contribution');
const onlyCoreVisualChange =
codeReasons.length === 1 && codeReasons[0] === 'core visual change';
const designOwnerAppearanceSelfServe =
authorIsDesign && appearanceOnly && onlyCoreVisualChange;
// Eng owners self-serve all code. Design owners self-serve only the
// classifier-proven appearance-only Core case above.
const codeHighRisk =
codeReasons.length > 0 &&
!authorIsEng &&
!designOwnerAppearanceSelfServe;
// Design owners self-serve design — no design tag for them.
const designAffecting = designReasons.length > 0 && !authorIsDesign;
core.info(`author=@${author} eng=${authorIsEng} design=${authorIsDesign}`);
core.info(`code: ${codeHighRisk} (${codeReasons.join(', ') || '-'})`);
core.info(`design: ${designAffecting} (${designReasons.join(', ') || '-'})`);
// --- Resolve approvals by reading reviews (fork-safe). ---
// The clear job runs on pull_request_review, but that event does NOT
// reliably dispatch a workflow run for FORK PRs — so a fork
// contributor's gate would never clear via that path. Instead, read
// the PR's reviews here (this job runs on pull_request_target and
// workflow_dispatch, both of which work for forks) and treat a gate
// as satisfied when an entitled owner has approved:
// code gate → an ENGOWNER approval, or — for an author with
// write or admin permission — the review app's
// (vars.REVIEW_APP) latest verdict, when it approves
// design gate → a DESIGNOWNER approval
// Only reviews whose commit_id equals this current PR head count.
// Within that head, each reviewer's latest APPROVED /
// CHANGES_REQUESTED / DISMISSED state wins. An H1 approval can never
// clear H2 for either engineering or design.
//
// The author's permission is read live at every evaluation. An unset
// REVIEW_APP or a failed read leaves the app's reviews without effect
// (fail closed to the engineering-owner path).
const reviewApp = reviewDecision.normalizeReviewApp(process.env.REVIEW_APP);
let authorHasWrite = false;
if (reviewApp && codeHighRisk) {
try {
const { data: permission } =
await github.rest.repos.getCollaboratorPermissionLevel({
owner, repo, username: pr.user.login,
});
authorHasWrite = reviewDecision.hasWritePermission(permission);
} catch (e) {
core.warning(`Could not read author permission; review-app approval does not apply: ${e.message}`);
}
}
let codeApproved = false;
let codeApprovedBy = null;
let designApproved = false;
try {
const reviews = await github.paginate(github.rest.pulls.listReviews, {
owner, repo, pull_number: pr.number, per_page: 100,
});
const headPushedAt = await reviewDecision.readHeadPushedAt({
github, owner, repo, sha: pr.head.sha,
});
({codeApproved, codeApprovedBy, designApproved} =
reviewDecision.resolveReviewApprovals({
reviews,
headSha: pr.head.sha,
headPushedAt,
engOwners,
designOwners,
reviewApp,
authorHasWrite,
}));
} catch (e) {
core.warning(`Could not resolve exact-head reviews: ${e.message}`);
}
// Effective gate = detected gate minus what an entitled owner
// already approved.
const codeGated = codeHighRisk && !codeApproved;
const designGated = designAffecting && !designApproved;
core.info(`approvals: code=${codeApproved} (${codeApprovedBy || '-'}, authorHasWrite=${authorHasWrite}) design=${designApproved} → codeGated=${codeGated} designGated=${designGated}`);
// --- Apply labels. ---
const current = pr.labels.map((l) => l.name);
const toAdd = [];
if (codeGated && !current.includes(CODE)) toAdd.push(CODE);
if (designGated && !current.includes(DESIGN)) {
// An owner who removed the advisory design label after this exact
// head arrived has seen it: a later event at the same head (ready
// for review, a reopen) does not add it back. A newer head, or a
// timeline or status list that cannot be read, adds it as before.
// The run that brings a head to this pull request (opened,
// synchronize) adds the label as before: a commit status belongs
// to the commit, so a head another pull request already gated
// would read as arriving before an owner's removal made here at
// the old head. When this run reaches the add, the add is a later
// label event, which ends that removal for later events at the
// head. When a later event cancels this run (the per-pull-request
// cancel group) or the run fails first, that removal still holds
// the label off at this head until the next push.
const bringsHead =
context.eventName === 'pull_request_target' &&
['opened', 'synchronize'].includes(context.payload.action);
let removedAtHead = false;
let removedBy = null;
if (!bringsHead) {
try {
const events = await github.paginate(
github.rest.issues.listEventsForTimeline,
{owner, repo, issue_number: pr.number, per_page: 100},
);
const headStatuses = await github.paginate(
github.rest.repos.listCommitStatusesForRef,
{owner, repo, ref: pr.head.sha, per_page: 100},
);
({removedAtHead, by: removedBy} =
reviewDecision.ownerRemovedLabelAtHead({
events,
headStatuses,
label: DESIGN,
owners: [...engOwners, ...designOwners],
headSha: pr.head.sha,
}));
} catch (e) {
core.warning(`Could not read the timeline or the head's statuses; ${DESIGN} is added: ${e.message}`);
}
}
if (removedAtHead) {
const why = `#${pr.number}: ${DESIGN} not added back: @${removedBy} removed it at this head (${pr.head.sha.slice(0, 8)}).`;
core.info(why);
try {
if (core.summary) await core.summary.addRaw(`${why}\n`).write();
} catch (e) {
core.warning(`Could not write the job summary: ${e.message}`);
}
} else {
toAdd.push(DESIGN);
}
}
// A quiet "community" marker on PRs authored by someone who is not
// on the eng or design team, so the contribution queue is filterable
// (label:community) separately from the review gates. Absence = team.
// (authorIsOwner is defined above.)
if (!authorIsOwner && !current.includes(COMMUNITY)) toAdd.push(COMMUNITY);
if (toAdd.length) {
await github.rest.issues.addLabels({
owner, repo, issue_number: pr.number, labels: toAdd,
});
}
// Keep it accurate: if an owner's PR somehow carries it (e.g. author
// was added to an owners file after opening), drop it.
if (authorIsOwner && current.includes(COMMUNITY)) {
try {
await github.rest.issues.removeLabel({
owner, repo, issue_number: pr.number, name: COMMUNITY,
});
} catch (e) {
core.warning(`Could not remove ${COMMUNITY}: ${e.message}`);
}
}
// Remove gate labels an entitled owner has already approved away
// (fork-safe clearing — the pull_request_review clear job doesn't
// fire for forks, so we reconcile here from the reviews we read).
async function dropLabel(name) {
try {
await github.rest.issues.removeLabel({
owner, repo, issue_number: pr.number, name,
});
core.info(`Cleared ${name} (approved).`);
} catch (e) {
core.warning(`Could not remove ${name}: ${e.message}`);
}
}
if (!codeGated && current.includes(CODE)) await dropLabel(CODE);
if (!designGated && current.includes(DESIGN)) await dropLabel(DESIGN);
// --- Request reviewers (can't request the author; ignore 422s). ---
// Code review is left to GitHub-native CODEOWNERS auto-request (it
// requests the codeowners on every PR regardless of branch
// protection). We only add DESIGN owners, and only when a design
// gate actually fires — so design owners aren't pinged on every PR.
async function requestReviewers(handles) {
const reviewers = [...new Set(handles)].filter((h) => h !== author);
if (!reviewers.length) return;
try {
await github.rest.pulls.requestReviewers({
owner, repo, pull_number: pr.number, reviewers,
});
} catch (e) {
core.warning(`requestReviewers(${reviewers.join(',')}) failed: ${e.message}`);
}
}
if (designGated) await requestReviewers(designOwners);
// --- Only the CODE gate blocks. Design review is advisory:
// it labels + requests design owners (above) but does NOT
// disable auto-merge or block the merge. ---
if (codeGated && pr.auto_merge) {
try {
await github.graphql(
`mutation ($id: ID!) {
disablePullRequestAutoMerge(input: { pullRequestId: $id }) {
pullRequest { number }
}
}`,
{ id: pr.node_id },
);
core.info('Disabled auto-merge (code review required).');
} catch (e) {
core.warning(`Could not disable auto-merge: ${e.message}`);
}
}
// No explanatory comment is posted here on purpose. The label and
// status are the mechanical signals; reviews provide judgment
// separately rather than through a static workflow comment.
// --- The blocking gate: a "review-required" COMMIT STATUS. ---
// We use a commit STATUS (not a check run) for two reasons:
// 1. Branch protection here requires the "review-required" context
// as a status context ("Expected — Waiting for status to be
// reported"), which only a commit status satisfies — a check
// run of the same name does not clear it.
// 2. A pending status renders as a neutral YELLOW dot ("waiting"),
// not a red failure like a check run's action_required — so a
// PR awaiting review doesn't add red noise to the queue.
// Only the CODE gate drives it (design is advisory). pending blocks
// (branch protection passes only success); an owner's code approval
// flips it to success.
const gateReasons = codeGated ? codeReasons : [];
// Never swallow a failure here: the status IS the gate, so a PR
// whose POST failed is blocked on a status that will never arrive.
// Throwing marks the run red and lets the per-PR catch continue a
// backfill; re-run the workflow to retry.
const gateDescription = codeGated
? `Waiting on code review: ${gateReasons.join(', ')}`.slice(0, 140)
: codeHighRisk && codeApprovedBy === 'review-app'
? 'Cleared by review-app approval for a write-access author.'
: codeHighRisk && codeApproved
? 'Cleared by code-owner approval.'
: 'No code review required.';
const gate = await publishReviewGate(codeGated, gateDescription);
core.info(`review-required status: ${gate.state}`);
// Neutralize any stale "review-required" CHECK RUN left over from the
// pre-status gate. Such a leftover (conclusion action_required) drags
// the status rollup to FAILURE even though we now gate via a commit
// status — so once the status is set, clear the old check-run.
try {
const { data } = await github.rest.checks.listForRef({
owner, repo, ref: pr.head.sha, check_name: 'review-required', per_page: 100,
});
for (const cr of data.check_runs) {
if (cr.conclusion && cr.conclusion !== 'success' && cr.conclusion !== 'neutral') {
await github.rest.checks.update({
owner, repo, check_run_id: cr.id,
conclusion: 'neutral',
output: { title: 'Superseded by review-required status', summary: 'The gate is now a review-required commit status; see that context.' },
});
core.info(`Neutralized stale review-required check-run ${cr.id}.`);
}
}
} catch (e) {
core.warning(`Could not neutralize stale check-run: ${e.message}`);
}
} // end flagOne
# Anchor the clear/restore chain for every review state that can change the
# effective exact-head engineering approval.
review-anchor:
if: >-
github.event_name == 'pull_request_review' &&
contains(fromJSON('["approved","changes_requested","dismissed"]'), github.event.review.state)
name: Anchor review-clear chain
runs-on: ubuntu-slim
permissions: {}
steps:
- name: Note review state change
run: echo "Review state changed; review-clear will reconcile the code gate."
# Spec owner gate: reconcile the spec half for one pull request.
spec-owner:
# Fork reviews (read-only tokens) are skipped; owners use the command. The
# reconciler orders concurrent runs itself: no concurrency group.
if: >-
(github.event_name != 'pull_request_review' ||
github.event.pull_request.head.repo.full_name == github.repository) &&
(github.event_name != 'issue_comment' ||
(github.event.issue.pull_request != null &&
(startsWith(github.event.comment.body, '/approve-spec') ||
startsWith(github.event.comment.body, '/revoke-spec')))) &&
(github.event_name != 'workflow_dispatch' || github.event.inputs.pr != '')
name: Spec owner gate
runs-on: ubuntu-slim
permissions:
contents: read
pull-requests: write
issues: write
statuses: write
steps:
# Every privileged event checks out the trusted default branch. Never
# execute the PR merge ref or PR-controlled helpers with write permissions.
- uses: actions/checkout@v7
with:
ref: ${{ github.event.repository.default_branch }}
- name: Reconcile owner gate
uses: actions/github-script@v9
with:
retries: 3
script: |
// Wait out the repository's shared API rate limit (lib/rate-limit-backoff.cjs).
require(require('node:path').join(process.env.GITHUB_WORKSPACE, '.github/scripts/lib/rate-limit-backoff.cjs'))
.installRateLimitBackoff({github, core});
const path = require('node:path');
const {reconcileSpecOwnerGate} = require(path.join(
process.env.GITHUB_WORKSPACE,
'.github/scripts/spec-owner-reconcile.cjs',
));
await reconcileSpecOwnerGate({github, context, core});