name: Contribution Gate

on:
  pull_request_target:
    types:
      - opened
      - reopened
      - edited
  # Manual sweep over every open PR — e.g. after bulk-applying the
  # `open-for-contribution` label. Set `dry_run` to log decisions without
  # commenting or closing.
  workflow_dispatch:
    inputs:
      dry_run:
        description: "Evaluate and log decisions only; do not comment or close"
        type: boolean
        default: false

permissions:
  pull-requests: write
  issues: read
  contents: read

concurrency:
  # Per-PR for pull_request_target; unique per run for manual sweeps (which
  # carry no pull_request payload) so two sweeps never cancel each other.
  group: contribution-gate-${{ github.event.pull_request.number || github.run_id }}
  cancel-in-progress: true

jobs:
  gate-single:
    name: Contribution Gate
    runs-on: ubuntu-latest
    # Exempt maintainers/collaborators and bots. External contributors are gated.
    if: >
      github.event_name == 'pull_request_target' &&
      github.event.pull_request.author_association != 'OWNER' &&
      github.event.pull_request.author_association != 'MEMBER' &&
      github.event.pull_request.author_association != 'COLLABORATOR' &&
      github.event.pull_request.user.type != 'Bot'
    steps:
      # Checks out the base repo (default for pull_request_target), so the gate
      # runs trusted code from the base branch, never the untrusted PR head.
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
      - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
        with:
          bun-version-file: ".bun-version"
      - name: Evaluate contribution gate
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          GITHUB_REPOSITORY: ${{ github.repository }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
          PR_AUTHOR_ASSOCIATION: ${{ github.event.pull_request.author_association }}
          PR_AUTHOR_LOGIN: ${{ github.event.pull_request.user.login }}
          PR_AUTHOR_TYPE: ${{ github.event.pull_request.user.type }}
        run: bun .github/scripts/contribution-gate.ts

  gate-all:
    name: Contribution Gate (all open PRs)
    runs-on: ubuntu-latest
    if: github.event_name == 'workflow_dispatch'
    steps:
      # Base-branch checkout only — the sweep makes API calls and never runs
      # any PR's code.
      - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
      - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
        with:
          bun-version-file: ".bun-version"
      - name: Evaluate contribution gate across all open PRs
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          GITHUB_REPOSITORY: ${{ github.repository }}
          GATE_MODE: all
          DRY_RUN: ${{ inputs.dry_run || 'false' }}
        run: bun .github/scripts/contribution-gate.ts