name: Auto Fix CI Failures

on:
  workflow_run:
    workflows: ["CI - Type Check, Format & Lint"]
    types:
      - completed

permissions:
  contents: write
  pull-requests: write
  actions: read
  issues: write
  id-token: write

jobs:
  auto-fix:
    if: |
      github.event.workflow_run.conclusion == 'failure' &&
      github.event.workflow_run.pull_requests[0]
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v5
        with:
          ref: ${{ github.event.workflow_run.head_branch }}
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Setup Bun
        uses: oven-sh/setup-bun@v2

      - name: Install dependencies
        run: bun install

      - name: Setup git identity
        run: |
          git config --global user.email "claude[bot]@users.noreply.github.com"
          git config --global user.name "claude[bot]"

      - name: Get CI failure details
        id: failure_details
        uses: actions/github-script@v7
        with:
          script: |
            const run = await github.rest.actions.getWorkflowRun({
              owner: context.repo.owner,
              repo: context.repo.repo,
              run_id: ${{ github.event.workflow_run.id }}
            });

            const jobs = await github.rest.actions.listJobsForWorkflowRun({
              owner: context.repo.owner,
              repo: context.repo.repo,
              run_id: ${{ github.event.workflow_run.id }}
            });

            const failedJobs = jobs.data.jobs.filter(job => job.conclusion === 'failure');

            return {
              runUrl: run.data.html_url,
              failedJobs: failedJobs.map(j => ({ name: j.name, id: j.id }))
            };

      - name: Fix CI failures with Claude
        uses: anthropics/claude-code-action@v1
        with:
          prompt: |
            Failed CI Run: ${{ fromJSON(steps.failure_details.outputs.result).runUrl }}
            Failed Jobs: ${{ join(fromJSON(steps.failure_details.outputs.result).failedJobs.*.name, ', ') }}
            PR Number: ${{ github.event.workflow_run.pull_requests[0].number }}
            Branch: ${{ github.event.workflow_run.head_branch }}
            Repository: ${{ github.repository }}

            Check supermemory for similar past CI failures and fixes.

            Fix the CI failures. Common fixes:
            - Biome lint errors: Run `bun run format-lint` or `biome check --fix .`
            - Type errors: Run `bun run check-types` and fix reported issues
            - Test failures: Debug and fix the failing tests

            After fixing, commit the changes and push directly to the branch `${{ github.event.workflow_run.head_branch }}`.
            Do NOT create a new PR — the fixes should be pushed to the existing PR branch.

            Save the fix pattern to supermemory for future reference.

          claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
          claude_args: |
            --max-turns 20
            --model claude-opus-4-5-20251101
            --allowedTools "Read,Write,Edit,Glob,Grep,Bash(*),WebSearch,WebFetch,Task,mcp__supermemory,mcp__github"
            --mcp-config '{
              "mcpServers": {
                "supermemory": {
                  "type": "http",
                  "url": "https://mcp.supermemory.ai/mcp",
                  "headers": {
                    "Authorization": "Bearer ${{ secrets.SUPERMEMORY_API_KEY }}"
                  }
                }
              }
            }'
