name: 'CI: Grind changed tests'

on:
  pull_request:
    paths:
      - 'packages/frontend/editor-ui/**/*.test.ts'

concurrency:
  group: grind-${{ github.event.pull_request.number || github.ref }}
  cancel-in-progress: true

jobs:
  grind:
    name: Grind changed editor-ui tests
    runs-on: ${{ vars.RUNNER_PROVIDER == 'github' && 'ubuntu-latest' || 'blacksmith-2vcpu-ubuntu-2204' }}
    # Non-blocking: a failure here surfaces in the PR Checks tab as a soft
    # signal but never gates merge. Remove `continue-on-error` once we have
    # confidence the grind has a low false-positive rate.
    continue-on-error: true
    timeout-minutes: 20
    permissions:
      contents: read
      pull-requests: write
    steps:
      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
        with:
          # Required so `git diff origin/<base>...HEAD` can find the
          # merge-base between the PR branch and the base ref. The script
          # also runs its own shallow `git fetch origin <base>` but the
          # symmetric-difference diff needs both sides of history present.
          fetch-depth: 0

      - name: Setup Node.js
        uses: ./.github/actions/setup-nodejs
        with:
          build-command: ''

      - name: Install .github/scripts dependencies
        run: pnpm install --frozen-lockfile --dir ./.github/scripts --ignore-workspace

      - name: Grind changed test files
        id: grind
        env:
          BASE_REF: ${{ github.base_ref }}
        run: |
          node .github/scripts/grind-changed-tests.mjs \
            --base "origin/${BASE_REF}" \
            --glob 'packages/frontend/editor-ui/**/*.test.ts' \
            --n 50 \
            --budget-seconds 900 \
            --out grind-comment.md

      - name: Post sticky PR comment
        if: steps.grind.outputs.files-count != '0'
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          PR_NUMBER: ${{ github.event.pull_request.number }}
        run: |
          node .github/scripts/post-grind-comment.mjs \
            --body grind-comment.md \
            --pr "$PR_NUMBER"
