Skip to content

ci: bring behind pull requests up to date automatically - #349

Merged
BenSheridanEdwards merged 5 commits into
mainfrom
ci/auto-update-behind-prs
Nov 10, 2026
Merged

BenSheridanEdwards merged 5 commits into
mainfrom
ci/auto-update-behind-prs

Conversation

@BenSheridanEdwards

@BenSheridanEdwards BenSheridanEdwards commented Nov 10, 2026 •

Copy link
Copy Markdown
Owner

Why does this feature exist?

Branch protection on main is strict, so a PR that falls behind main cannot merge. The maintainer ticked an enforcement sign-off on #345 after #347 merged, and the PR still could not merge because it was behind. The repository is user-owned, so GitHub's merge queue is not available. Updating by hand also broke the PR quality check: on #345 and #346 the body's - Head commit: (and on #346 - North Star commit:) no longer matched the head.

This PR keeps every open, ready PR current. When main moves, each behind PR has main merged in, its required checks run on the new head, its body stays valid, and an unchanged sign-off carries.

What changed?

About 70% of the 1,500 added lines are tests. The change is one idea: keep behind PRs current and keep every gate judging the updated head.

  • New workflow .github/workflows/update-behind-prs.yml runs scripts/update-behind-prs.mjs from main on every push to main, or by dispatch with a pr number. It needs contents: write, pull-requests: write and actions: write, and refuses any ref but the default branch.
    • For each open PR into main it calls planUpdate, which skips drafts, forks, bot PRs and other bases.
    • It merges main into a behind, mergeable PR with GitHub's update-branch (merge method). The update is pinned to the head the script judged.
    • It comments once on a conflicting PR ("needs a manual rebase"). It also comments once when main's new commits change .github/workflows/, because GITHUB_TOKEN may not push that change.
    • It keeps one comment and rewrites it when the reason changes. It removes the comment once the PR is current, however the PR got there.
    • The update is pinned to the head the script compared. A PR that is current but whose head has no run of a dispatched workflow, or no enforcement-approval status, gets its checks dispatched, so an update whose dispatches failed or came late is finished by the next run.
  • Checks on the new head: a GITHUB_TOKEN push starts no pull_request run, so the script dispatches ci.yml, codeql.yml, lighthouse.yml, visual.yml and pr-quality.yml on the PR branch, and enforcement-approval.yml on main with the PR number. Each gained a workflow_dispatch trigger. Their job names are the required check names, so no personal token or GitHub App is needed. pnpm gates:check now fails when a required-check workflow is missing from DISPATCHES or has no dispatch trigger.
  • Dispatched runs judge the branch against main:
    • The coverage gate and blast radius compare with origin/main.
    • lighthouse-scope.mjs runs audits in full outside pull_request; docs-only scope already did.
    • pr-quality.yml reads the title and body from the API, and on a dispatch it requires the open PR whose head is this branch. Both events take the base from the base branch's tip in the checkout, because GitHub refreshes base.sha lazily.
    • The enforcement script accepts inputs.pr.
  • PR body: validate-pr-body.mjs accepts a - Head commit: followed only by clean merges from main. A clean merge has two parents, the second in main, and a tree equal to git merge-tree of those parents. The North Star field is then read at that commit. A rebase, an ordinary commit, or a merge that also edits the PR still needs the body re-checked.
  • Dry run: node scripts/update-behind-prs.mjs --dry-run [<pr>] prints the plan for every open PR through read-only gh api calls.
  • ADR 0129 records the decision, why merge beats rebase, and the gaps. QUALITY_GATES.md, PR_QUALITY.md and docs/required-gates.md are updated.

Why #345's tick did not carry. The gate never recorded a tick on #345. Every enforcement-approval status on its pre-update head c3b27ac is failure, and no issue_comment gate run touched #345 after 9 November 18:33 UTC. The only tick on 10 November was on #346, at head 77d9f2b, at 10:58:25 UTC. Nine seconds later #346 was rebased onto main and force-pushed to 1bce1d8. Its guard fingerprint was identical (2bc7777…), but 77d9f2b was no longer a commit of the PR, so ADR 0122's carry rule correctly refused. For #345, the fingerprint before and after its update (7690f33…) is identical and c3b27ac stays in the PR, so a tick there would have carried. This is why the workflow merges and never rebases.

Behavioural Proof (with video and screenshots)

Not applicable: this change adds a CI workflow and gate scripts with no user-visible UI. Deterministic proof follows.

  • Video: Not applicable, no UI.
  • Screenshots: Not applicable, no UI.
  • Behaviour tests:
    • scripts/update-behind-prs.test.ts covers the selection logic: behind, draft, conflicting, up to date, workflow change, fork, bot and unknown mergeability. It also covers the shell: one notice per PR, rewritten when the reason changes and cleared once current; a head that moves during the read or the update; an asynchronous update; a head that never moves; a failed dispatch finished by the next run; and a dry run.
    • scripts/validate-pr-body.test.ts covers earlier heads, the North Star read at the named commit, and real-Git clean, edited, side-branch and ordinary commits.
    • scripts/enforcement-approval.test.ts covers a dispatched gate carrying the tick, and a bad inputs.pr.
    • scripts/required-gates.test.ts covers missing dispatch triggers and DISPATCHES entries.
    • scripts/lighthouse-scope.test.ts covers the dispatched full run.
  • E2E mapping: Not applicable, no user-visible behaviour changed. pnpm e2e still passes.
  • Live dry run against this repository (read-only, captured before this PR's own updates; feat(lint): add six policy rules mined from nine agent rebuilds #345 and feat(gates): fail the gate on Fallow, Playwright worker and runner warnings #346 are current now):
$ node scripts/update-behind-prs.mjs --dry-run
#346 is 1 commit(s) behind main: update
#345 is 1 commit(s) behind main: update
#335 is a draft: skip
#143 is a draft: skip

#343 and #344 target feat/todo-example-app, not main, so the workflow never lists them.

#345 main's validator   ✗ `- Head commit:` says c3b27ac…, but the PR head is 504cd7f1bd1a.
#345 this branch        PR body and title satisfy the quality contract.
#346 main's validator   ✗ Head commit 77d9f2b…  ✗ North Star commit 76be8d3…
#346 this branch        same two failures, correctly: #346 was rebased, so its own commits changed.

Verification Summary

  • Head commit: 18a4d30
  • PRDs checked: None: CI workflow and gate scripts only, no product behaviour
  • PRD impact: None
  • North Star commit: 5cd630f4ac19c6679a939b4361b85026cc8bd98d
  • Commands run (e.g. pnpm verify, pnpm e2e): pnpm verify, pnpm e2e, node scripts/required-gates.mjs --check, node scripts/update-behind-prs.mjs --dry-run, the validator on feat(lint): add six policy rules mined from nine agent rebuilds #345 and feat(gates): fail the gate on Fallow, Playwright worker and runner warnings #346 as above.
  • Results: pnpm verify passed in the pre-push hook (3023 Jest tests plus the integration and contract projects) and pnpm e2e passed (15 Playwright tests) on c2c401f. At 12:31 UTC the branch was rebased onto main after feat(lint): add six policy rules mined from nine agent rebuilds #345 merged; git range-diff shows this head's four commits identical to those at c2c401f, and this head is judged by its CI run. The rebase also took the ticked commit out of the PR, so the sign-off cannot carry (ADR 0122) and needs a fresh tick at this head. Locally the contract suite needs PACT_DIR set to a private directory, because another worktree left todos.add interactions in the shared default pact file; one earlier hook run failed on an unrelated scripts/bench/run.test.ts pnpm tarball-integrity retry and passed on rerun.
  • Definition of Done (.agents/project/PR_QUALITY.md) satisfied, or each gap named: satisfied, except the live gaps listed under known risks.
  • pnpm verify
  • pnpm e2e
  • Behaviour is covered by the E2E map when user-visible behaviour changed. Not applicable: no user-visible change.
  • Logic is unit-tested where logic changed.
  • Accessibility considered and verified for interactive/UI changes. Not applicable: no UI.
  • The diff follows .agents/project/ARCHITECTURE.md and CONVENTIONS.md; new decisions recorded as ADRs.
  • No gates were bypassed or weakened.
  • Known risks or skipped checks (with reason, risk, and rollback):
    • Not testable before merge. The push trigger and every dispatch need the workflows on main. GitHub only dispatches a workflow whose file on the default branch has workflow_dispatch. The first run after merge is the live proof. Watch the Update behind PRs run and the dispatched checks on the first updated PR.
    • First run comments on behind PRs. This PR changes seven workflow files. When it merges, every behind PR's incoming commits include workflow changes, so the first run comments asking for Update branch instead of updating. From then on, updates whose main commits leave workflows alone are automatic. Closing the gap needs a GitHub App installation token (Contents, Pull requests and Workflows: write) as a secret, which is a separate decision.
    • Branch protection does not require the tick. Live branch protection on main does not require the enforcement-approval status or Visual regression, though docs/required-gates.md lists both. A carried tick shows on the PR but does not gate merging until the settings match. This predates the PR; pnpm gates:protection reports the difference.
    • Cost. Dispatched runs do not get the docs-only or UI-scope savings, so each auto-update runs full CI, CodeQL, Lighthouse and visual.
    • Rollback. Revert this PR, or disable the "Update behind PRs" workflow in the Actions tab. The other dispatch triggers are inert without it.
    • Pre-commit. Hook steps are unchanged, so there are no new per-step timings.

PRD Behaviours to Review

  • None

PR Proof Law

  • I followed .agents/project/PR_QUALITY.md and .agents/skills/pr-quality-contract/SKILL.md; the PR quality check verifies the proof format.

🤖 Generated with Claude Code

@github-actions github-actions Bot added confidence: red A required gate is failing or pending, or evidence is unavailable. confidence: green Required gates, slice E2E/PRDs, unit line coverage and import blast radius passed. and removed confidence: red A required gate is failing or pending, or evidence is unavailable. confidence: green Required gates, slice E2E/PRDs, unit line coverage and import blast radius passed. labels Nov 10, 2026
BenSheridanEdwards and others added 4 commits November 10, 2026 12:31
On every push to main, update-behind-prs.yml merges main into each open,
ready, same-repo PR that is behind it and dispatches the PR's required
checks and the enforcement gate, because a GITHUB_TOKEN push starts no
pull_request run. Conflicting PRs get one comment. The PR body validator
accepts a head commit followed only by clean merges from main (ADR 0129).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Predict workflow-file refusals instead of trying, clear notices once a PR is
current, enforce DISPATCHES in gates:check, harden the pr-quality dispatch,
add a read-only dry run, and record why merge keeps the sign-off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Finish an update whose dispatches failed on the next run, pin the update to
the compared head, take the PR-quality base from the checkout, and rewrite
the one notice when its reason changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A current head with no enforcement-approval status gets its checks
dispatched again, and a one-PR dispatch of the updater uses its own
concurrency group so it never replaces a queued full run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot added confidence: red A required gate is failing or pending, or evidence is unavailable. confidence: green Required gates, slice E2E/PRDs, unit line coverage and import blast radius passed. and removed confidence: green Required gates, slice E2E/PRDs, unit line coverage and import blast radius passed. confidence: red A required gate is failing or pending, or evidence is unavailable. labels Nov 10, 2026
@github-actions

github-actions Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Enforcement sign-off

Ran at Tuesday, the 10th of November, at 4:48 pm on commit 791ea8a.

This PR changes gated enforcement or product intent, so it needs sign-off.

File What changed How it affects
.github/workflows/ci.yml Changes the step Blast-radius evidence (ADR 0068): run changed="$(git -c core.quotePath=false diff --name-only HEAD^1..."$HEAD_SHA")" → changed="$(git -c core.quotePath=false diff --name-only "$BASE"..."$HEAD_SHA")"; Changes the step Changed sources and slices have tests: run changed="$(git -c core.quotePath=false diff --name-only HEAD^1..."$HEAD_SHA")" … → changed="$(git -c core.quotePath=false diff --name-only "$BASE"..."$HEAD_SHA")"…; Changes workflow jobs.fallow.steps.env.BASE from not set to "${{ github.event_name == 'workflow_dispatch' && github.ref_name != github.event.repository.default_branch && format('origin/{0}', github.event.repository.default_branch) || 'HEAD^1' }}"; Changes workflow jobs.coverage.steps.env.BASE from not set to "${{ github.event_name == 'workflow_dispatch' && github.ref_name != github.event.repository.default_branch && format('origin/{0}', github.event.repository.default_branch) || 'HEAD^1' }}" The named jobs, steps, action versions and trigger settings above determine which checks execute
.github/workflows/codeql.yml Changes the workflow trigger or job definition The named jobs, steps, action versions and trigger settings above determine which checks execute
.github/workflows/enforcement-approval.yml Changes workflow jobs.approve.concurrency.group from "enforcement-approval-${{ github.event.pull_request.number || github.event.issue.number }}" to "enforcement-approval-${{ github.event.pull_request.number || github.event.issue.number || inputs.pr }}"; Changes workflow on.workflow_dispatch.inputs.pr.description from not set to "Pull request number to judge at its current head"; Changes workflow on.workflow_dispatch.inputs.pr.required from not set to "true" The named jobs, steps, action versions and trigger settings above determine which checks execute
.github/workflows/lighthouse.yml Changes workflow on from "pull_request" to not set The named jobs, steps, action versions and trigger settings above determine which checks execute
.github/workflows/pr-quality.yml Changes the step ./.github/actions/setup; Adds the step Read the pull request; Changes the step Validate; Changes workflow concurrency.group from "pr-quality-${{ github.event.pull_request.number }}" to "pr-quality-${{ github.event.pull_request.number || inputs.pr }}"; Changes workflow jobs.pr-body.steps.env.PR_TITLE from "${{ toJSON(github.event.pull_request.title) }}" to "${{ steps.pr.outputs.title }}"; Changes workflow jobs.pr-body.steps.env.PR_BODY from "${{ toJSON(github.event.pull_request.body) }}" to "${{ steps.pr.outputs.body }}"; Changes workflow jobs.pr-body.steps.env.PR_HEAD_SHA from "${{ github.event.pull_request.head.sha }}" to "${{ github.event.pull_request.head.sha || github.sha }}"; Changes workflow jobs.pr-body.steps.env.PR_BASE_SHA from "${{ github.event.pull_request.base.sha }}" to "${{ steps.pr.outputs.base-sha }}"; Changes workflow jobs.pr-body.steps.env.PR_HEAD_REF from "${{ toJSON(github.event.pull_request.head.ref) }}" to "${{ steps.pr.outputs.head-ref }}"; Changes workflow on.workflow_dispatch.inputs.pr.description from not set to "Pull request number whose head is this branch"; Changes workflow on.workflow_dispatch.inputs.pr.required from not set to "true"; Changes workflow permissions.pull-requests from not set to "read"; Changes workflow jobs.pr-body.steps.id from not set to "pr"; Changes workflow jobs.pr-body.steps.env.GH_TOKEN from not set to "${{ github.token }}"; Changes workflow jobs.pr-body.steps.env.REPO from not set to "${{ github.repository }}"; Changes workflow jobs.pr-body.steps.env.NUMBER from not set to "${{ github.event.pull_request.number || inputs.pr }}"; Changes workflow jobs.pr-body.steps.env.EVENT from not set to "${{ github.event_name }}" Changes the GitHub permissions available to the workflow; The named jobs, steps, action versions and trigger settings above determine which checks execute
.github/workflows/update-behind-prs.yml Adds this file; Changes workflow name from not set to "Update behind PRs"; Changes workflow on.push.branches from not set to "[main]"; Changes workflow on.workflow_dispatch.inputs.pr.description from not set to "Update only this pull request number; leave empty for every behind PR"; Changes workflow on.workflow_dispatch.inputs.pr.required from not set to "false"; Changes workflow on.workflow_dispatch.inputs.pr.default from not set to "''"; Changes workflow permissions from not set to "{}"; Changes workflow concurrency.group from not set to "update-behind-prs-${{ inputs.pr || 'all' }}"; Changes workflow concurrency.cancel-in-progress from not set to "false"; Changes workflow jobs.update.if from not set to "github.ref == format('refs/heads/{0}', github.event.repository.default_branch)"; Changes workflow jobs.update.runs-on from not set to "ubuntu-latest"; Changes workflow jobs.update.timeout-minutes from not set to "15"; Changes workflow jobs.update.permissions.contents from not set to "write"; Changes workflow jobs.update.permissions.pull-requests from not set to "write"; Changes workflow jobs.update.permissions.actions from not set to "write"; Changes workflow jobs.update.steps.with.persist-credentials from not set to "false"; Changes workflow jobs.update.steps.with.sparse-checkout from not set to "scripts/update-behind-prs.mjs"; Changes workflow jobs.update.steps.with.sparse-checkout-cone-mode from not set to "false"; Changes workflow jobs.update.steps.with.script from not set to "|" The revised condition changes when the named job or step runs; Changes the GitHub permissions available to the workflow; The named jobs, steps, action versions and trigger settings above determine which checks execute
.github/workflows/visual.yml Changes workflow on from "pull_request" to not set The named jobs, steps, action versions and trigger settings above determine which checks execute
scripts/enforcement-approval.mjs Rewrites the check run: definition "export async function run({ github, context, core }) {\\n const repo = context.repo;\\n const number = context.payload.pull_request?.number ?? context.payload.issue?.number;\\n const { data: pullRequest } = await github.rest.pulls.get({ ...repo, pull_number: number });\\n const head = pullRequest.head.sha;\\n\\n const { data: comparison } = await github.rest.repos.compareCommitsWithBasehead({\\n ...repo,\\n basehead: '${pullRequest.base.sha}...${head}',\\n });\\n\\n const mergeBase = comparison.merge_base_commit.sha;\\n\\n const files = await github.paginate(github.rest.pulls.listFiles, {\\n ...repo,\\n pull_number: number,\\n per_page: 100,\\n });\\n\\n const changes = await Promise.all(\\n guardedPaths(files).map(async (path) => ({\\n path,\\n before: await readFile(github, repo, path, mergeBase),\\n after: await readFile(github, repo, path, head),\\n })),\\n );\\n\\n const problems = [\\n ...(files.length >= LIST_FILES_LIMIT ? [TOO_MANY_FILES] : []),\\n ...enforcementProblems(changes),\\n ];\\n\\n const comments = await github.paginate(github.rest.issues.listComments, {\\n ...repo,\\n issue_number: number,\\n per_page: 100,\\n });\\n\\n const event = await gateEvent(github, context);\\n const existing = findSignoffComment(comments, event);\\n const fingerprint = guardFingerprint(changes);\\n const signedOff = await holdsSignOff({ github, repo, head, fingerprint });\\n const carry = await carryFor({\\n github,\\n repo,\\n number,\\n pullRequest,\\n changes,\\n comment: existing,\\n eligible: event.kind === 'pull' && problems.length > 0 && !signedOff,\\n listed: files.length,\\n });\\n\\n const plan = planApproval({\\n head,\\n problems,\\n comment: existing,\\n signedOff,\\n event,\\n carry,\\n fingerprint,\\n });\\n\\n await writeComment({\\n github,\\n repo,\\n number,\\n existing,\\n older: gateComments(comments).map((comment) => comment.id),\\n body: plan.commentBody,\\n repost: event.kind === 'pull',\\n });\\n\\n if (!plan.status) {\\n core.info('${STATUS_CONTEXT}: left as it is for ${head}');\\n\\n return;\\n }\\n\\n await github.rest.repos.createCommitStatus({\\n ...repo,\\n sha: head,\\n context: STATUS_CONTEXT,\\n state: plan.status.state,\\n description: plan.status.description,\\n });\\n core.info('${STATUS_CONTEXT}: ${plan.status.state} — ${plan.status.description}');\\n}" becomes "export async function run({ github, context, core }) {\\n const repo = context.repo;\\n const number = pullRequestNumber(context);\\n const { data: pullRequest } = await github.rest.pulls.get({ ...repo, pull_number: number });\\n const head = pullRequest.head.sha;\\n\\n const { data: comparison } = await github.rest.repos.compareCommitsWithBasehead({\\n ...repo,\\n basehead: '${pullRequest.base.sha}...${head}',\\n });\\n\\n const mergeBase = comparison.merge_base_commit.sha;\\n\\n const files = await github.paginate(github.rest.pulls.listFiles, {\\n ...repo,\\n pull_number: number,\\n per_page: 100,\\n });\\n\\n const changes = await Promise.all(\\n guardedPaths(files).map(async (path) => ({\\n path,\\n before: await readFile(github, repo, path, mergeBase),\\n after: await readFile(github, repo, path, head),\\n })),\\n );\\n\\n const problems = [\\n ...(files.length >= LIST_FILES_LIMIT ? [TOO_MANY_FILES] : []),\\n ...enforcementProblems(changes),\\n ];\\n\\n const comments = await github.paginate(github.rest.issues.listComments, {\\n ...repo,\\n issue_number: number,\\n per_page: 100,\\n });\\n\\n const event = await gateEvent(github, context);\\n const existing = findSignoffComment(comments, event);\\n const fingerprint = guardFingerprint(changes);\\n const signedOff = await holdsSignOff({ github, repo, head, fingerprint });\\n const carry = await carryFor({\\n github,\\n repo,\\n number,\\n pullRequest,\\n changes,\\n comment: existing,\\n eligible: event.kind === 'pull' && problems.length > 0 && !signedOff,\\n listed: files.length,\\n });\\n\\n const plan = planApproval({\\n head,\\n problems,\\n comment: existing,\\n signedOff,\\n event,\\n carry,\\n fingerprint,\\n });\\n\\n await writeComment({\\n github,\\n repo,\\n number,\\n existing,\\n older: gateComments(comments).map((comment) => comment.id),\\n body: plan.commentBody,\\n repost: event.kind === 'pull',\\n });\\n\\n if (!plan.status) {\\n core.info('${STATUS_CONTEXT}: left as it is for ${head}');\\n\\n return;\\n }\\n\\n await github.rest.repos.createCommitStatus({\\n ...repo,\\n sha: head,\\n context: STATUS_CONTEXT,\\n state: plan.status.state,\\n description: plan.status.description,\\n });\\n core.info('${STATUS_CONTEXT}: ${plan.status.state} — ${plan.status.description}');\\n}"; Adds the check pullRequestNumber: definition "" becomes "function pullRequestNumber(context) {\\n const fromEvent = context.payload.pull_request?.number ?? context.payload.issue?.number;\\n if (fromEvent !== undefined) return fromEvent;\\n const input = String(context.payload.inputs?.pr ?? '');\\n if (!/^[1-9]\\\\d*$/.test(input)) {\\n throw new Error(\\n 'The ${context.eventName} run names no pull request: inputs.pr is ${JSON.stringify(input)}.',\\n );\\n }\\n return Number(input);\\n}" The comment must explain the guarded change before the maintainer ticks; display text does not grant approval; These checks are unchanged: isApprover, isFreshTick, guardFingerprint, verifiedCarry, holdsSignOff (configured-user authorization, fresh ticks and identical guarded-content carry-over); Unchanged: only the configured GitHub User @BenSheridanEdwards can fresh-tick; identical guarded-content fingerprints keep approval across a new head, and changed guarded content clears it
scripts/enforcement-approval.test.ts Adds regression coverage: carries the tick when the update workflow dispatches the gate for the PR it updated, refuses a dispatch that does not name one pull request number The tooling gate must pass these approval and comment scenarios; a regression fails verification before a push or merge.

@BenSheridanEdwards: tick to approve.

  • Approve these enforcement changes at 791ea8a ticked by Ben Sheridan Edwards at Tuesday, the 10th of November, at 4:48 pm (@BenSheridanEdwards)

@github-actions github-actions Bot added confidence: red A required gate is failing or pending, or evidence is unavailable. confidence: green Required gates, slice E2E/PRDs, unit line coverage and import blast radius passed. and removed confidence: green Required gates, slice E2E/PRDs, unit line coverage and import blast radius passed. confidence: red A required gate is failing or pending, or evidence is unavailable. labels Nov 10, 2026
@BenSheridanEdwards
BenSheridanEdwards merged commit 5a27279 into main Nov 10, 2026
21 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

confidence: green Required gates, slice E2E/PRDs, unit line coverage and import blast radius passed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant