# When Theseus finishes generating a guide for a pull request, Claude Code reads the guide and fixes what it
# flags on the pull request's branch. Copy this file to .github/workflows/ on your default branch:
# GitHub only runs repository_dispatch workflows from there. Setup and safety notes: README.md.
name: Theseus fix (Claude Code)

on:
  repository_dispatch:
    # Theseus sends `theseus.<event type>`; add other types your integration subscribes to.
    types: [theseus.guide.ready]

# One job at a time per pull request; a newer event waits rather than racing the running fix.
concurrency:
  group: theseus-pr-${{ github.event.client_payload.changeset.number }}
  cancel-in-progress: false

permissions:
  contents: write
  pull-requests: read

env:
  # Fix commits a pull request may receive from this workflow before it stops.
  MAX_FIX_CYCLES: '3'
  EVENT_ID: ${{ github.event.client_payload.event_id }}
  PR_NUMBER: ${{ github.event.client_payload.changeset.number }}
  HEAD_SHA: ${{ github.event.client_payload.guide.head_sha }}
  GUIDE_URL: ${{ github.event.client_payload.url }}
  DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}

jobs:
  fix:
    runs-on: ubuntu-latest
    timeout-minutes: 30
    steps:
      # Theseus delivers at least once and retries under the same event ID; act on each ID once.
      - name: Drop duplicate events
        id: seen
        uses: actions/cache/restore@v4
        with:
          path: .theseus-event
          key: theseus-event-${{ github.event.client_payload.event_id }}
          lookup-only: true

      - name: Check the pull request
        id: pr
        if: steps.seen.outputs.cache-hit != 'true'
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          pr=$(curl -fsSL -H "Authorization: Bearer $GH_TOKEN" -H 'Accept: application/vnd.github+json' \
            "$GITHUB_API_URL/repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER")
          # Fork branches never run with this repository's secrets.
          if [ "$(jq -r .head.repo.full_name <<<"$pr")" != "$GITHUB_REPOSITORY" ]; then
            echo "::notice::Pull request #$PR_NUMBER comes from a fork; skipping."; exit 0
          fi
          if [ "$(jq -r .state <<<"$pr")" != open ]; then
            echo "::notice::Pull request #$PR_NUMBER is not open; skipping."; exit 0
          fi
          # The guide describes one commit; a newer push gets its own event.
          if [ "$(jq -r .head.sha <<<"$pr")" != "$HEAD_SHA" ]; then
            echo "::notice::Pull request #$PR_NUMBER moved past $HEAD_SHA; skipping."; exit 0
          fi
          echo "branch=$(jq -r .head.ref <<<"$pr")" >> "$GITHUB_OUTPUT"

      # No credential stays in .git/config while the agent reads pull request text: the fetch and
      # the push below each pass a token for that one command.
      - uses: actions/checkout@v4
        if: steps.pr.outputs.branch
        with:
          fetch-depth: 0
          persist-credentials: false

      # repository_dispatch checks out the default branch; switch to the head commit the guide describes.
      - name: Check out the pull request head
        id: head
        if: steps.pr.outputs.branch
        env:
          BRANCH: ${{ steps.pr.outputs.branch }}
          GH_TOKEN: ${{ github.token }}
        run: |
          auth="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$GH_TOKEN" | base64 -w0)"
          git -c "http.https://github.com/.extraheader=$auth" \
            fetch --no-tags origin "+refs/pull/$PR_NUMBER/head:refs/remotes/theseus/head"
          test "$(git rev-parse refs/remotes/theseus/head)" = "$HEAD_SHA"
          git checkout -B "$BRANCH" refs/remotes/theseus/head
          cycles=$(git log --format="%(trailers:key=Theseus-Fix-Cycle,valueonly)" "origin/$DEFAULT_BRANCH..HEAD" | grep -c . || true)
          if [ "$cycles" -ge "$MAX_FIX_CYCLES" ]; then
            echo "::notice::#$PR_NUMBER already has $cycles Theseus fix commits; stopping."; exit 0
          fi
          echo "run=true" >> "$GITHUB_OUTPUT"
          # The agent may write to .git/; the push refuses a configuration it changed. A step output
          # is kept by the runner, out of the agent's reach.
          echo "config=$(git config --local --list | sha256sum | cut -c1-64)" >> "$GITHUB_OUTPUT"

      # The agent edits the working tree only; the next step commits and pushes.
      - name: Fix what the guide flags
        id: agent
        if: steps.head.outputs.run
        uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: |
            Theseus generated a guide for pull request #${{ env.PR_NUMBER }} at commit ${{ env.HEAD_SHA }}.
            The guide is at ${{ env.GUIDE_URL }}. Read it through the Theseus API with the
            THESEUS_TOKEN environment variable when it is set.
            Fix problems the guide flags in this pull request's changes: failing rollout steps,
            unanswered open questions you can answer from the code, and claims the code contradicts.
            Edit files only. Do not commit, push, or claim anything is resolved. If nothing needs
            fixing, change nothing.
          claude_args: --max-turns 30
        env:
          THESEUS_TOKEN: ${{ secrets.THESEUS_TOKEN }}

      # Pushes made with the workflow's own GITHUB_TOKEN start no workflow runs, so a fix commit
      # would get no CI. A THESEUS_PUSH_TOKEN secret (a fine-grained token with contents: write on
      # this repository only) makes the fix run the pull request's checks.
      - name: Push the fix
        if: steps.head.outputs.run
        env:
          BRANCH: ${{ steps.pr.outputs.branch }}
          PUSH_TOKEN: ${{ secrets.THESEUS_PUSH_TOKEN || github.token }}
          CONFIG: ${{ steps.head.outputs.config }}
        run: |
          # Hooks, an fsmonitor or a proxy the agent configured could see the token: refuse them.
          if [ "$(git config --local --list | sha256sum | cut -c1-64)" != "$CONFIG" ]; then
            echo "::error::The agent changed .git/config; not pushing."; exit 1
          fi
          safe=(git -c core.hooksPath=/dev/null -c core.fsmonitor=false)
          if "${safe[@]}" diff --quiet && [ -z "$("${safe[@]}" ls-files --others --exclude-standard)" ]; then
            echo "::notice::Nothing to fix."; exit 0
          fi
          "${safe[@]}" add -A
          # An agent's fix never changes .github/: that would let pull request text rewrite CI. A
          # pathspec sees renames' sources and paths git would print quoted.
          if ! "${safe[@]}" diff --cached --no-renames --quiet -- .github; then
            echo "::error::The fix changes .github/; not pushing it."; exit 1
          fi
          "${safe[@]}" -c user.name='theseus-fix[bot]' -c user.email='theseus-fix@users.noreply.github.com' \
            commit --no-verify -m "Address the Theseus guide for #$PR_NUMBER" -m "Theseus-Fix-Cycle: $EVENT_ID"
          auth="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$PUSH_TOKEN" | base64 -w0)"
          "${safe[@]}" -c "http.https://github.com/.extraheader=$auth" \
            push --no-verify origin "HEAD:refs/heads/$BRANCH"

      - name: Remember the event
        if: steps.seen.outputs.cache-hit != 'true'
        run: mkdir -p .theseus-event && echo "$EVENT_ID" > .theseus-event/id
      - uses: actions/cache/save@v4
        if: steps.seen.outputs.cache-hit != 'true'
        with:
          path: .theseus-event
          key: theseus-event-${{ github.event.client_payload.event_id }}
