name: Auto-merge Controller

on:
  schedule:
    # Every 5 minutes — picks up newly green PRs without waiting for events
    - cron: "*/5 * * * *"
  pull_request:
    types: [opened, synchronize, labeled, ready_for_review]
  check_run:
    types: [completed]
  workflow_dispatch:

# Serialize across the whole repo. We never cancel an in-flight cycle —
# losing the audit trail is more dangerous than running back-to-back.
concurrency:
  group: auto-merge-${{ github.repository }}
  cancel-in-progress: false

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

jobs:
  auto-merge:
    name: auto-merge
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 1

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.12"

      - name: Show controller version
        run: |
          set -euo pipefail
          ls -l scripts/auto_merge_controller.py scripts/auto_merge_lock.py
          python3 -m py_compile scripts/auto_merge_controller.py scripts/auto_merge_lock.py
          echo "OK: controller compiled"

      - name: Run auto-merge controller
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          REPO: ${{ github.repository }}
          WORKSPACE_ROOT: ${{ github.workspace }}
        run: |
          set -euo pipefail
          python3 scripts/auto_merge_controller.py --repo "${REPO}" --verbose

      - name: Upload audit log
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: auto-merge-audit-${{ github.run_id }}
          path: |
            memory/logs/auto-merge-audit.jsonl
          if-no-files-found: ignore
          retention-days: 30
