name: "Huggy PR Agent"
description: "Repository-aware inline PR reviews, 1-click suggestions, /describe, /improve, /ask, and test-gated @huggy auto-fixes."
author: "Binh Duc Nguyen"
branding:
  icon: "git-pull-request"
  color: "yellow"

inputs:
  mode:
    description: "What to run: 'auto' (review on pull_request, slash/@huggy/@pi commands on comments), 'review', or 'comment'."
    required: false
    default: "auto"
  api_key:
    description: "API key for the chosen model provider (e.g. OpenCode Go, OpenRouter, Anthropic, OpenAI). Optional when using Google Vertex AI (`gcp_project`)."
    required: false
    default: ""
  api_key_env:
    description: "Environment variable name Pi reads for `api_key`."
    required: false
    default: "OPENCODE_API_KEY"
  gcp_project:
    description: "Google Cloud project ID when using `google-vertex/*` models (sets `GOOGLE_CLOUD_PROJECT`; auto-detected when `gcp_credentials_json` is provided)."
    required: false
    default: ""
  gcp_location:
    description: "Google Cloud region or 'global' when using `google-vertex/*` models (sets `GOOGLE_CLOUD_LOCATION`)."
    required: false
    default: "global"
  gcp_credentials_json:
    description: "Google Cloud Service Account JSON key for `google-vertex/*` models (omit when using Workload Identity Federation)."
    required: false
    default: ""
  model:
    description: "Primary / Lead Pi model identifier (`provider/model`). Reviews the highest-risk bundle and runs the Judge pass."
    required: false
    default: "opencode-go/deepseek-v4.1-flash"
  wingman_model:
    description: "Optional Wingman Pi model identifier (`provider/model`) for parallel non-lead bundles (e.g. `google-vertex/gemini-4-argon`). Must be reachable with the same credentials configured for `model` (`api_key`/`api_key_env` or Vertex `gcp_*`). Defaults to `model` when empty."
    required: false
    default: ""
  fallback_model:
    description: "Emergency fallback model identifier tried only after `model` or `wingman_model` fails (error, non-zero exit, missing verdict, or timeout)."
    required: false
    default: "opencode-go/glm-5.3-flash"
  thinking:
    description: "Thinking level (`off`, `minimal`, `low`, `medium`, `high`)."
    required: false
    default: "high"
  pi_version:
    description: "Version or dist-tag of @earendil-works/pi-coding-agent to install."
    required: false
    default: "latest"
  review_tools:
    description: "Comma-separated Pi tools enabled during read-only PR reviews."
    required: false
    default: "read,grep,find,ls"
  review_timeout_minutes:
    description: "Review timeout budget in minutes, or 'auto' to scale dynamically with PR size (18m to 50m)."
    required: false
    default: "auto"
  fix_timeout_minutes:
    description: "Per-attempt timeout in minutes for interactive @pi / /fix commands."
    required: false
    default: "25"
  max_parallel_bundles:
    description: "Maximum parallel Pi workers when reviewing large multi-bundle PRs."
    required: false
    default: "3"
  judge_pass:
    description: "Run an independent tool-free fact-checker pass to drop hallucinated or duplicate findings."
    required: false
    default: "true"
  review_profile:
    description: "Noise profile: 'chill' (posts High/Medium inline and collapses Low nitpicks in the summary) or 'assertive' (posts all findings inline)."
    required: false
    default: "chill"
  review_depth:
    description: "Review pass strategy: 'standard' (single pass per bundle) or 'deep' (parallel Logic+Security specialist lenses merged via Judge)."
    required: false
    default: "standard"
  skip_bots:
    description: "Skip automatic pull_request reviews when the PR author is a bot (e.g. Renovate, Dependabot)."
    required: false
    default: "true"
  skip_drafts:
    description: "Skip automatic pull_request reviews while the PR is in draft state."
    required: false
    default: "false"
  rubric_file:
    description: "Context file read from the base branch as the review/fix rubric (falls back to CLAUDE.md if absent)."
    required: false
    default: "AGENTS.md"
  extra_instructions:
    description: "Optional extra instructions appended to the prompt."
    required: false
    default: ""
  setup_cmd:
    description: "Shell command run in a secret-free step before a @pi fix (e.g. 'corepack enable pnpm && pnpm install --frozen-lockfile')."
    required: false
    default: ""
  verify_cmd:
    description: "Shell command run after a @pi / /fix edit before committing and pushing (e.g. 'pnpm typecheck && pnpm lint && pnpm test')."
    required: false
    default: ""
  guarded_paths:
    description: "Space-separated paths that a @pi / /fix run is not allowed to stage or push."
    required: false
    default: ".github .woodpecker Dockerfile docker-entrypoint.sh package.json pnpm-lock.yaml pnpm-workspace.yaml Cargo.lock go.mod go.sum migrations"
  github_token:
    description: "GitHub token used to post reviews/comments and push @pi fixes."
    required: false
    default: ${{ github.token }}

runs:
  using: "composite"
  steps:
    # -------------------------------------------------------------------------
    # SHARED CACHE FOR PI CLI
    # -------------------------------------------------------------------------
    - name: Resolve concrete Pi CLI version
      id: pi_ver
      shell: bash
      env:
        PI_VERSION: ${{ inputs.pi_version }}
      run: |
        set -euo pipefail
        resolved=$(curl -fsSL --max-time 5 "https://registry.npmjs.org/@earendil-works/pi-coding-agent/$PI_VERSION" 2>/dev/null | jq -r '.version // empty' || true)
        [ -n "$resolved" ] || resolved=$(npm view "@earendil-works/pi-coding-agent@$PI_VERSION" version 2>/dev/null || printf '%s' "$PI_VERSION")
        echo "version=$resolved" >> "$GITHUB_OUTPUT"

    - name: Cache Pi CLI installation
      uses: actions/cache@v4
      with:
        path: ~/.pi-cli
        key: pi-cli-v2-${{ runner.os }}-${{ runner.arch }}-${{ steps.pi_ver.outputs.version }}

    # -------------------------------------------------------------------------
    # AUTOMATIC PR REVIEW (pull_request event)
    # -------------------------------------------------------------------------
    - name: Check whether PR review should run
      id: gate_review
      if: (inputs.mode == 'review') || (inputs.mode == 'auto' && github.event_name == 'pull_request')
      shell: bash
      env:
        SKIP_BOTS: ${{ inputs.skip_bots }}
        SKIP_DRAFTS: ${{ inputs.skip_drafts }}
        PR_USER_TYPE: ${{ github.event.pull_request.user.type }}
        PR_USER_LOGIN: ${{ github.event.pull_request.user.login }}
        PR_DRAFT: ${{ github.event.pull_request.draft }}
      run: |
        set -euo pipefail
        if [ "$SKIP_BOTS" = "true" ] && { [ "$PR_USER_TYPE" = "Bot" ] || [[ "$PR_USER_LOGIN" == *"[bot]" ]]; }; then
          echo "Skipping automatic review for bot PR author ($PR_USER_LOGIN)."
          echo "go=false" >> "$GITHUB_OUTPUT"
          exit 0
        fi
        if [ "$SKIP_DRAFTS" = "true" ] && [ "$PR_DRAFT" = "true" ]; then
          echo "Skipping automatic review for draft PR."
          echo "go=false" >> "$GITHUB_OUTPUT"
          exit 0
        fi
        echo "go=true" >> "$GITHUB_OUTPUT"

    - name: Checkout PR head ref (review)
      if: steps.gate_review.outputs.go == 'true'
      uses: actions/checkout@v4
      with:
        ref: ${{ github.event.pull_request.head.sha }}
        fetch-depth: 100
        persist-credentials: false
        token: ${{ inputs.github_token }}

    - name: Resolve base branch, rubric and review context
      if: steps.gate_review.outputs.go == 'true'
      shell: bash
      env:
        GH_TOKEN: ${{ inputs.github_token }}
        SERVER: ${{ github.server_url }}
        REPO: ${{ github.repository }}
        TARGET: ${{ github.event.pull_request.base.ref }}
        PR: ${{ github.event.pull_request.number }}
        RUBRIC_FILE: ${{ inputs.rubric_file }}
        EXTRA_INSTRUCTIONS: ${{ inputs.extra_instructions }}
        ACTION_PATH: ${{ github.action_path }}
      run: |
        set -euo pipefail
        rm -rf "$RUNNER_TEMP/pi-action"
        mkdir -p "$RUNNER_TEMP/pi-action"
        cp -R "$ACTION_PATH/scripts" "$ACTION_PATH/prompts" "$RUNNER_TEMP/pi-action/"

        git_basic=$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 | tr -d '\r\n')
        git -c "http.$SERVER/.extraheader=AUTHORIZATION: basic $git_basic" \
          fetch --no-tags --depth=100 "$SERVER/$REPO.git" \
          "+refs/heads/$TARGET:refs/heads/base-tip"
        mb=$(git merge-base base-tip HEAD 2>/dev/null || true)
        if [ -z "$mb" ]; then
          shallow_flag=""
          [ -f "$(git rev-parse --git-dir)/shallow" ] && shallow_flag="--unshallow"
          git -c "http.$SERVER/.extraheader=AUTHORIZATION: basic $git_basic" \
            fetch --no-tags $shallow_flag "$SERVER/$REPO.git" \
            "+refs/pull/$PR/head:refs/remotes/pr-head" "+refs/heads/$TARGET:refs/heads/base-tip"
          mb=$(git merge-base base-tip HEAD 2>/dev/null || true)
          if [ -z "$mb" ]; then
            echo "no merge base between $TARGET and HEAD; refusing to review an inverted diff" >&2
            exit 1
          fi
        fi
        git branch -f base "$mb"
        echo "base = $(git rev-parse --short base) (tip = $(git rev-parse --short base-tip), head = $(git rev-parse --short HEAD))"

        if git cat-file -e "base-tip:$RUBRIC_FILE" 2>/dev/null; then
          git show "base-tip:$RUBRIC_FILE" > "$RUNNER_TEMP/rubric.md"
        elif git cat-file -e "base-tip:CLAUDE.md" 2>/dev/null; then
          git show "base-tip:CLAUDE.md" > "$RUNNER_TEMP/rubric.md"
        else
          : > "$RUNNER_TEMP/rubric.md"
        fi

        if git cat-file -e "base-tip:.github/pi-review-prompt.md" 2>/dev/null; then
          git show "base-tip:.github/pi-review-prompt.md" > "$RUNNER_TEMP/brief-template.md"
        else
          cp "$RUNNER_TEMP/pi-action/prompts/review.md" "$RUNNER_TEMP/brief-template.md"
        fi
        if [ -n "$EXTRA_INSTRUCTIONS" ]; then
          printf '\n\nAdditional repository instructions:\n%s\n' "$EXTRA_INSTRUCTIONS" >> "$RUNNER_TEMP/brief-template.md"
        fi

        GIT_ATTR_SOURCE=base-tip git -c core.quotePath=false diff base HEAD > "$RUNNER_TEMP/diff.patch"
        python3 "$RUNNER_TEMP/pi-action/scripts/fetch_pr_context.py" "$RUNNER_TEMP/pr-context.md" "$RUNNER_TEMP/diff.patch"
        python3 "$RUNNER_TEMP/pi-action/scripts/post_progress.py"
        # Scrub checkout token from .git/config and FETCH_HEAD before the Pi step runs
        git config --local --unset-all "http.$SERVER/.extraheader" 2>/dev/null || true
        rm -f .git/FETCH_HEAD

    - name: Run Pi (bundle finders)
      if: steps.gate_review.outputs.go == 'true'
      shell: bash
      env:
        PI_API_KEY: ${{ inputs.api_key }}
        PI_API_KEY_ENV: ${{ inputs.api_key_env }}
        PI_GCP_PROJECT: ${{ inputs.gcp_project }}
        PI_GCP_LOCATION: ${{ inputs.gcp_location }}
        PI_GCP_CREDENTIALS_JSON: ${{ inputs.gcp_credentials_json }}
        PI_MODEL: ${{ inputs.model }}
        PI_WINGMAN_MODEL: ${{ inputs.wingman_model }}
        PI_FALLBACK_MODEL: ${{ inputs.fallback_model }}
        PI_THINKING: ${{ inputs.thinking }}
        PI_VERSION: ${{ inputs.pi_version }}
        PI_REVIEW_TOOLS: ${{ inputs.review_tools }}
        PI_REVIEW_TIMEOUT_MINUTES: ${{ inputs.review_timeout_minutes }}
        PI_MAX_PARALLEL_BUNDLES: ${{ inputs.max_parallel_bundles }}
        PI_JUDGE_PASS: ${{ inputs.judge_pass }}
        PI_REVIEW_DEPTH: ${{ inputs.review_depth }}
      run: |
        set -euo pipefail
        # shellcheck disable=SC1091
        source "$RUNNER_TEMP/pi-action/scripts/ensure_tools.sh"
        python3 "$RUNNER_TEMP/pi-action/scripts/run_review.py" --phase find

    - name: Update progress banner to Judge pass
      if: steps.gate_review.outputs.go == 'true'
      shell: bash
      env:
        GH_TOKEN: ${{ inputs.github_token }}
        REPO: ${{ github.repository }}
        PR: ${{ github.event.pull_request.number }}
      run: |
        set -euo pipefail
        python3 "$RUNNER_TEMP/pi-action/scripts/post_progress.py" judge

    - name: Run Pi (precision judge)
      id: judge
      if: steps.gate_review.outputs.go == 'true'
      continue-on-error: true
      shell: bash
      env:
        PI_API_KEY: ${{ inputs.api_key }}
        PI_API_KEY_ENV: ${{ inputs.api_key_env }}
        PI_GCP_PROJECT: ${{ inputs.gcp_project }}
        PI_GCP_LOCATION: ${{ inputs.gcp_location }}
        PI_GCP_CREDENTIALS_JSON: ${{ inputs.gcp_credentials_json }}
        PI_MODEL: ${{ inputs.model }}
        PI_WINGMAN_MODEL: ${{ inputs.wingman_model }}
        PI_FALLBACK_MODEL: ${{ inputs.fallback_model }}
        PI_THINKING: ${{ inputs.thinking }}
        PI_VERSION: ${{ inputs.pi_version }}
        PI_JUDGE_PASS: ${{ inputs.judge_pass }}
      run: |
        set -euo pipefail
        # shellcheck disable=SC1091
        source "$RUNNER_TEMP/pi-action/scripts/ensure_tools.sh"
        python3 "$RUNNER_TEMP/pi-action/scripts/run_review.py" --phase judge

    - name: Publish inline review and sticky summary
      if: steps.gate_review.outputs.go == 'true'
      shell: bash
      env:
        GH_TOKEN: ${{ inputs.github_token }}
        REPO: ${{ github.repository }}
        PR: ${{ github.event.pull_request.number }}
        HEAD_SHA: ${{ github.event.pull_request.head.sha }}
        PI_REVIEW_PROFILE: ${{ inputs.review_profile }}
        JUDGE_OUTCOME: ${{ steps.judge.outcome }}
      run: |
        set -euo pipefail
        if [ "${JUDGE_OUTCOME:-}" = "failure" ] && [ -f review.md ]; then
          python3 -c '
        p = open("review.md", encoding="utf-8").read()
        note = "\n> ⚠️ **Judge pass interrupted:** publishing unverified finder candidates from `--phase find`.\n"
        lines = p.splitlines()
        insert_at = 0
        for i, ln in enumerate(lines):
            if ln.startswith("**Effort:**") or ln.startswith("**Verdict:**"):
                insert_at = i + 1
        lines.insert(insert_at, note)
        open("review.md", "w", encoding="utf-8").write("\n".join(lines) + "\n")
        '
        fi
        GIT_ATTR_SOURCE=base-tip git -c core.quotePath=false diff base HEAD > "$RUNNER_TEMP/diff.patch"
        python3 "$RUNNER_TEMP/pi-action/scripts/post_review.py"

    - name: Replace a stale verdict when review fails
      if: failure() && steps.gate_review.outputs.go == 'true'
      shell: bash
      env:
        GH_TOKEN: ${{ inputs.github_token }}
        REPO: ${{ github.repository }}
        PR: ${{ github.event.pull_request.number }}
      run: |
        set -euo pipefail
        auth="Authorization: Bearer $GH_TOKEN"
        api="https://api.github.com/repos/$REPO/issues"
        comments=$(curl -fsSL -H "$auth" "$api/$PR/comments?per_page=100")
        existing=$(printf '%s' "$comments" | jq -r 'first(.[] | select(.body | startswith("<!-- pi-review")) | .id) // empty')
        marker=$(printf '%s' "$comments" | jq -r 'first(.[] | select(.body | startswith("<!-- pi-review")) | (.body | split("\n")[0])) // "<!-- pi-review -->"')
        icon="https://raw.githubusercontent.com/tripplen23/huggy-pr-agent/v1/assets/huggy-icon.svg"
        body=$(printf '%s\n## <img src="%s" width="24" height="24" align="absmiddle" alt="Huggy" /> Review by Huggy\n\nThis run did not finish, so any verdict above is from an older commit. The log says why: %s/%s/actions/runs/%s' \
          "$marker" "$icon" "${{ github.server_url }}" "$REPO" "${{ github.run_id }}")
        payload=$(jq -n --arg b "$body" '{body: $b}')
        if [ -n "$existing" ]; then
          curl -fsSL -X PATCH -H "$auth" -H "Content-Type: application/json" \
            "$api/comments/$existing" -d "$payload" > /dev/null
        fi

    # -------------------------------------------------------------------------
    # INTERACTIVE PR COMMANDS (/review, /describe, /improve, /ask, /fix, @pi)
    # -------------------------------------------------------------------------
    - name: Parse command and check out PR branch
      id: prepare
      if: (inputs.mode == 'fix' || inputs.mode == 'comment') || (inputs.mode == 'auto' && (github.event_name == 'issue_comment' || github.event_name == 'pull_request_review_comment'))
      shell: bash
      env:
        GH_TOKEN: ${{ inputs.github_token }}
        SERVER: ${{ github.server_url }}
        REPO: ${{ github.repository }}
        PR: ${{ github.event.issue.number || github.event.pull_request.number }}
        COMMENT_BODY: ${{ github.event.comment.body }}
        COMMENT_ID: ${{ github.event.comment.id }}
        COMMENT_USER: ${{ github.event.comment.user.login }}
        COMMENT_USER_TYPE: ${{ github.event.comment.user.type }}
        COMMENT_ASSOC: ${{ github.event.comment.author_association }}
        COMMENT_PATH: ${{ github.event.comment.path || '' }}
        COMMENT_LINE: ${{ github.event.comment.line || github.event.comment.original_line || '' }}
        COMMENT_START_LINE: ${{ github.event.comment.start_line || github.event.comment.original_start_line || '' }}
        COMMENT_DIFF_HUNK: ${{ github.event.comment.diff_hunk || '' }}
        THREAD: ${{ github.event_name == 'pull_request_review_comment' && 'yes' || '' }}
        ACTION_PATH: ${{ github.action_path }}
      run: |
        set -euo pipefail
        rm -rf "$RUNNER_TEMP/pi-action"
        mkdir -p "$RUNNER_TEMP/pi-action"
        cp -R "$ACTION_PATH/scripts" "$ACTION_PATH/prompts" "$RUNNER_TEMP/pi-action/"

        python3 "$RUNNER_TEMP/pi-action/scripts/prepare_command.py" authorize
        grep -qx "go=true" "$GITHUB_OUTPUT" || exit 0
        cmd=$(sed -n 's/^cmd=//p' "$GITHUB_OUTPUT" | tail -n 1)

        api="https://api.github.com/repos/$REPO"
        auth="Authorization: Bearer $GH_TOKEN"

        if [ -n "$THREAD" ]; then
          react="$api/pulls/comments/$COMMENT_ID/reactions"
        else
          react="$api/issues/comments/$COMMENT_ID/reactions"
        fi
        curl -fsSL -X POST -H "$auth" -H "Content-Type: application/json" \
          "$react" -d '{"content":"eyes"}' > /dev/null \
          || echo "could not add reaction (cosmetic); carrying on."

        read -r branch base cross < <(curl -fsSL -H "$auth" "$api/pulls/$PR" \
          | jq -r '"\(.head.ref) \(.base.ref) \(.head.repo.full_name != .base.repo.full_name)"')
        : "${branch:?could not read the PR branch}"
        blocked_img='<img src="https://raw.githubusercontent.com/tripplen23/huggy-pr-agent/v1/assets/huggy-blocked.svg" width="160" alt="Huggy stopped on a guarded boundary" />'
        if [ "$cross" = "true" ] && [ "$cmd" = "fix" ]; then
          curl -fsSL -X POST -H "$auth" -H "Content-Type: application/json" \
            "$api/issues/$PR/comments" -d "$(jq -n --arg b "$blocked_img"$'\n\n'"I cannot push to a fork branch with this token. Run \`pi\` on the branch locally, or open the PR from a branch in this repo." '{body: $b}')" > /dev/null
          echo "go=false" >> "$GITHUB_OUTPUT"
          exit 0
        fi
        git_basic=$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 | tr -d '\r\n')
        if [ "$cmd" = "fix" ] && ! git -c "http.$SERVER/.extraheader=AUTHORIZATION: basic $git_basic" ls-remote --exit-code "$SERVER/$REPO.git" "refs/heads/$branch" > /dev/null 2>&1; then
          if [ -n "$THREAD" ]; then reply_url="$api/pulls/$PR/comments/$COMMENT_ID/replies"; else reply_url="$api/issues/$PR/comments"; fi
          curl -fsSL -X POST -H "$auth" -H "Content-Type: application/json" \
            "$reply_url" -d "$(jq -n --arg b "$blocked_img"$'\n\n'"Branch \`$branch\` has been deleted on GitHub, so new commits cannot be pushed to this PR yet. Click **Restore branch** on the PR (or push \`$branch\` again), then re-run \`@huggy\`." '{body: $b}')" > /dev/null
          echo "go=false" >> "$GITHUB_OUTPUT"
          exit 0
        fi

        git init -q .
        git -c "http.$SERVER/.extraheader=AUTHORIZATION: basic $git_basic" \
          fetch -q --no-tags "$SERVER/$REPO.git" \
          "+refs/pull/$PR/head:refs/heads/pr-head" "+refs/heads/$base:refs/heads/base-tip"
        git checkout -q pr-head
        mb=$(git merge-base base-tip pr-head 2>/dev/null || git rev-parse base-tip)
        git branch -f base "$mb"

        GIT_ATTR_SOURCE=base-tip git -c core.quotePath=false diff base HEAD > "$RUNNER_TEMP/diff.patch"
        python3 "$RUNNER_TEMP/pi-action/scripts/fetch_pr_context.py" "$RUNNER_TEMP/pr-context.md" "$RUNNER_TEMP/diff.patch"
        THREAD="${THREAD:-}" python3 "$RUNNER_TEMP/pi-action/scripts/prepare_command.py" build-request "$RUNNER_TEMP/fix-request.md"
        if [ -f "$RUNNER_TEMP/fix-tasks.json" ] && [ "$(jq 'length' "$RUNNER_TEMP/fix-tasks.json" 2>/dev/null || echo 1)" = "0" ]; then
          git config --local --unset-all "http.$SERVER/.extraheader" 2>/dev/null || true
          rm -f .git/FETCH_HEAD
          exit 0
        fi
        if [ "$cmd" = "review" ]; then
          python3 "$RUNNER_TEMP/pi-action/scripts/post_progress.py"
        else
          CMD="$cmd" python3 "$RUNNER_TEMP/pi-action/scripts/post_progress.py" command-start
        fi
        # Scrub any checkout credentials from .git/config and FETCH_HEAD before running Pi
        git config --local --unset-all "http.$SERVER/.extraheader" 2>/dev/null || true
        rm -f .git/FETCH_HEAD

    # Runs in its own step with neither GH_TOKEN nor PI_API_KEY in env, so
    # dependency lifecycle scripts (`postinstall`) from the PR branch cannot read
    # or exfiltrate any secret.
    - name: Set up project dependencies for fix
      if: steps.prepare.outputs.go == 'true' && steps.prepare.outputs.already_handled != 'true' && steps.prepare.outputs.cmd == 'fix' && inputs.setup_cmd != ''
      shell: bash
      env:
        SETUP_CMD: ${{ inputs.setup_cmd }}
      run: |
        set -euo pipefail
        eval "$SETUP_CMD"

    - name: Run Pi (command)
      id: fix
      if: steps.prepare.outputs.go == 'true' && steps.prepare.outputs.already_handled != 'true'
      shell: bash
      env:
        PI_API_KEY: ${{ inputs.api_key }}
        PI_API_KEY_ENV: ${{ inputs.api_key_env }}
        PI_GCP_PROJECT: ${{ inputs.gcp_project }}
        PI_GCP_LOCATION: ${{ inputs.gcp_location }}
        PI_GCP_CREDENTIALS_JSON: ${{ inputs.gcp_credentials_json }}
        PI_MODEL: ${{ inputs.model }}
        PI_WINGMAN_MODEL: ${{ inputs.wingman_model }}
        PI_FALLBACK_MODEL: ${{ inputs.fallback_model }}
        PI_THINKING: ${{ inputs.thinking }}
        PI_VERSION: ${{ inputs.pi_version }}
        PI_REVIEW_TOOLS: ${{ inputs.review_tools }}
        PI_REVIEW_TIMEOUT_MINUTES: ${{ inputs.review_timeout_minutes }}
        PI_FIX_TIMEOUT_MINUTES: ${{ inputs.fix_timeout_minutes }}
        PI_MAX_PARALLEL_BUNDLES: ${{ inputs.max_parallel_bundles }}
        PI_JUDGE_PASS: ${{ inputs.judge_pass }}
        PI_REVIEW_DEPTH: ${{ steps.prepare.outputs.review_depth || inputs.review_depth }}
        RUBRIC_FILE: ${{ inputs.rubric_file }}
        EXTRA_INSTRUCTIONS: ${{ inputs.extra_instructions }}
        COMMENT_BODY: ${{ github.event.comment.body }}
        COMMENT_ID: ${{ github.event.comment.id }}
        CMD: ${{ steps.prepare.outputs.cmd }}
      run: |
        set -euo pipefail
        # shellcheck disable=SC1091
        source "$RUNNER_TEMP/pi-action/scripts/ensure_tools.sh"

        if git cat-file -e "base-tip:$RUBRIC_FILE" 2>/dev/null; then
          git show "base-tip:$RUBRIC_FILE" > "$RUNNER_TEMP/rubric.md"
        elif git cat-file -e "base-tip:CLAUDE.md" 2>/dev/null; then
          git show "base-tip:CLAUDE.md" > "$RUNNER_TEMP/rubric.md"
        else
          : > "$RUNNER_TEMP/rubric.md"
        fi

        if [ "$CMD" = "review" ]; then
          if git cat-file -e "base-tip:.github/pi-review-prompt.md" 2>/dev/null; then
            git show "base-tip:.github/pi-review-prompt.md" > "$RUNNER_TEMP/brief-template.md"
          else
            cp "$RUNNER_TEMP/pi-action/prompts/review.md" "$RUNNER_TEMP/brief-template.md"
          fi
          if [ -n "$EXTRA_INSTRUCTIONS" ]; then
            printf '\n\nAdditional repository instructions:\n%s\n' "$EXTRA_INSTRUCTIONS" >> "$RUNNER_TEMP/brief-template.md"
          fi
          python3 "$RUNNER_TEMP/pi-action/scripts/run_review.py"
          cp review.md "$RUNNER_TEMP/reply.md"
          echo "changed=false" >> "$GITHUB_OUTPUT"
          exit 0
        fi

        if [ "$CMD" = "fix" ]; then
          python3 "$RUNNER_TEMP/pi-action/scripts/run_fix.py" run
          exit 0
        fi

        if [ -f "$RUNNER_TEMP/fix-request.md" ]; then
          cp "$RUNNER_TEMP/fix-request.md" .pi-fix-request.md
        else
          printf '%s\n' "$COMMENT_BODY" > .pi-fix-request.md
        fi

        case "$CMD" in
          describe) cp "$RUNNER_TEMP/pi-action/prompts/describe.md" "$RUNNER_TEMP/brief.md" ;;
          improve)  cp "$RUNNER_TEMP/pi-action/prompts/improve.md" "$RUNNER_TEMP/brief.md" ;;
          ask)      cp "$RUNNER_TEMP/pi-action/prompts/ask.md" "$RUNNER_TEMP/brief.md" ;;
          fix)
            if git cat-file -e "base:.github/pi-fix-prompt.md" 2>/dev/null; then
              git show "base:.github/pi-fix-prompt.md" > "$RUNNER_TEMP/brief.md"
            else
              cp "$RUNNER_TEMP/pi-action/prompts/fix.md" "$RUNNER_TEMP/brief.md"
            fi
            ;;
        esac
        if [ -n "$EXTRA_INSTRUCTIONS" ]; then
          printf '\n\nAdditional repository instructions:\n%s\n' "$EXTRA_INSTRUCTIONS" >> "$RUNNER_TEMP/brief.md"
        fi
        if [ -s "$RUNNER_TEMP/pr-context.md" ]; then
          printf '\n\n' >> "$RUNNER_TEMP/brief.md"
          cat "$RUNNER_TEMP/pr-context.md" >> "$RUNNER_TEMP/brief.md"
        fi

        sys_args=()
        if [ -s "$RUNNER_TEMP/rubric.md" ]; then
          sys_args=(--append-system-prompt "$RUNNER_TEMP/rubric.md")
        fi

        tools="read,grep,find,ls,bash"
        if [ "$CMD" = "fix" ]; then
          tools="read,grep,find,ls,bash,edit,write"
        fi

        timeout_sec=$(( ${PI_FIX_TIMEOUT_MINUTES:-25} * 60 ))
        run_ok=0
        for candidate in "$PI_MODEL" "$PI_MODEL" "${PI_FALLBACK_MODEL:-}"; do
          [ -n "$candidate" ] || continue
          echo "Running $CMD with model: $candidate (thinking: $PI_THINKING, timeout: ${timeout_sec}s)"
          if perl -e 'alarm shift; exec @ARGV' "$timeout_sec" pi --print \
            --model "$candidate" \
            --thinking "$PI_THINKING" \
            --tools "$tools" \
            --no-extensions --no-mcp --no-skills \
            --no-context-files \
            --no-approve --no-session \
            "${sys_args[@]}" < "$RUNNER_TEMP/brief.md" | tee .pi-fix-reply.md && [ -s .pi-fix-reply.md ]; then
            run_ok=1
            break
          fi
          echo "Model $candidate failed or was overloaded (429/5xx); backing off 20s before retry/fallback..." >&2
          sleep 20
        done
        [ "$run_ok" -eq 1 ] || { echo "All model attempts failed" >&2; exit 1; }

        python3 - <<'PY'
        import os, sys
        sys.path.insert(0, os.path.join(os.environ["RUNNER_TEMP"], "pi-action", "scripts"))
        import run_review
        raw = open(".pi-fix-reply.md", encoding="utf-8", errors="replace").read()
        clean = run_review.redact_secret(raw, os.environ.get("PI_API_KEY") or "")
        open(os.path.join(os.environ["RUNNER_TEMP"], "reply.md"), "w", encoding="utf-8").write(clean)
        PY
        cp "$RUNNER_TEMP/reply.md" review.md
        rm -f .pi-fix-reply.md .pi-fix-request.md
        if [ "$CMD" = "fix" ] && [ -n "$(git status --porcelain)" ]; then
          echo "changed=true" >> "$GITHUB_OUTPUT"
        else
          echo "changed=false" >> "$GITHUB_OUTPUT"
        fi

    - name: Update progress banner to verification test gate
      if: steps.fix.outputs.changed == 'true' && inputs.verify_cmd != ''
      shell: bash
      env:
        GH_TOKEN: ${{ inputs.github_token }}
        REPO: ${{ github.repository }}
        PR: ${{ github.event.issue.number || github.event.pull_request.number }}
        PROGRESS_COMMENT_ID: ${{ steps.prepare.outputs.progress_comment_id }}
        PROGRESS_COMMENT_KIND: ${{ steps.prepare.outputs.progress_comment_kind }}
      run: |
        set -euo pipefail
        python3 "$RUNNER_TEMP/pi-action/scripts/post_progress.py" command-testing

    - name: Verify fix
      id: verify1
      if: steps.fix.outputs.changed == 'true' && inputs.verify_cmd != ''
      shell: bash
      env:
        VERIFY_CMD: ${{ inputs.verify_cmd }}
      run: |
        set +e
        eval "$VERIFY_CMD" > >(tee "$RUNNER_TEMP/verify-out.log") 2>&1
        rc=$?
        set -e
        if [ "$rc" -eq 0 ]; then
          echo "ok=true" >> "$GITHUB_OUTPUT"
        else
          echo "ok=false" >> "$GITHUB_OUTPUT"
        fi

    - name: Repair verification failure (if needed)
      if: steps.fix.outputs.changed == 'true' && inputs.verify_cmd != '' && steps.verify1.outputs.ok == 'false'
      shell: bash
      env:
        PI_API_KEY: ${{ inputs.api_key }}
        PI_API_KEY_ENV: ${{ inputs.api_key_env }}
        PI_GCP_PROJECT: ${{ inputs.gcp_project }}
        PI_GCP_LOCATION: ${{ inputs.gcp_location }}
        PI_GCP_CREDENTIALS_JSON: ${{ inputs.gcp_credentials_json }}
        PI_MODEL: ${{ inputs.model }}
        PI_FALLBACK_MODEL: ${{ inputs.fallback_model }}
        PI_VERSION: ${{ inputs.pi_version }}
      run: |
        set -euo pipefail
        # shellcheck disable=SC1091
        source "$RUNNER_TEMP/pi-action/scripts/ensure_tools.sh"
        python3 "$RUNNER_TEMP/pi-action/scripts/run_fix.py" repair "$RUNNER_TEMP/verify-out.log"

    - name: Re-verify repaired fix
      if: steps.fix.outputs.changed == 'true' && inputs.verify_cmd != '' && steps.verify1.outputs.ok == 'false'
      shell: bash
      env:
        VERIFY_CMD: ${{ inputs.verify_cmd }}
      run: |
        set -euo pipefail
        eval "$VERIFY_CMD"

    - name: Publish command result
      if: success() && steps.prepare.outputs.go == 'true' && steps.prepare.outputs.already_handled != 'true'
      shell: bash
      env:
        GH_TOKEN: ${{ inputs.github_token }}
        REPO: ${{ github.repository }}
        PR: ${{ github.event.issue.number || github.event.pull_request.number }}
        COMMENT_ID: ${{ github.event.comment.id }}
        THREAD: ${{ github.event_name == 'pull_request_review_comment' && 'yes' || '' }}
        CMD: ${{ steps.prepare.outputs.cmd }}
        FIX_CHANGED: ${{ steps.fix.outputs.changed }}
        PROGRESS_COMMENT_ID: ${{ steps.prepare.outputs.progress_comment_id }}
        PROGRESS_COMMENT_KIND: ${{ steps.prepare.outputs.progress_comment_kind }}
        PI_REVIEW_PROFILE: ${{ inputs.review_profile }}
        GUARDED_PATHS: ${{ inputs.guarded_paths }}
      run: |
        set -euo pipefail
        if [ "$CMD" = "fix" ]; then
          python3 "$RUNNER_TEMP/pi-action/scripts/run_fix.py" publish
          exit 0
        fi
        api="https://api.github.com/repos/$REPO"
        auth="Authorization: Bearer $GH_TOKEN"
        reply=$(cat "$RUNNER_TEMP/reply.md")

        if [ -n "$THREAD" ]; then
          post="$api/pulls/$PR/comments/$COMMENT_ID/replies"
        else
          post="$api/issues/$PR/comments"
        fi
        answer() {
          local payload
          payload=$(jq -n --arg b "$1" '{body: $b}')
          if [ -n "${PROGRESS_COMMENT_ID:-}" ]; then
            local patch_url="$api/issues/comments/$PROGRESS_COMMENT_ID"
            [ "${PROGRESS_COMMENT_KIND:-}" = "pull" ] && patch_url="$api/pulls/comments/$PROGRESS_COMMENT_ID"
            if curl -fsSL -X PATCH -H "$auth" -H "Content-Type: application/json" "$patch_url" -d "$payload" > /dev/null 2>&1; then
              return 0
            fi
          fi
          curl -fsSL -X POST -H "$auth" -H "Content-Type: application/json" "$post" -d "$payload" > /dev/null
        }
        cleanup_progress_comment() {
          if [ -n "${PROGRESS_COMMENT_ID:-}" ]; then
            local del_url="$api/issues/comments/$PROGRESS_COMMENT_ID"
            [ "${PROGRESS_COMMENT_KIND:-}" = "pull" ] && del_url="$api/pulls/comments/$PROGRESS_COMMENT_ID"
            curl -fsSL -X DELETE -H "$auth" "$del_url" > /dev/null 2>&1 || true
          fi
        }

        if [ "$CMD" = "review" ] || [ "$CMD" = "improve" ]; then
          cleanup_progress_comment
          export HEAD_SHA="$(git rev-parse HEAD)"
          GIT_ATTR_SOURCE=base-tip git -c core.quotePath=false diff base HEAD > "$RUNNER_TEMP/diff.patch"
          python3 "$RUNNER_TEMP/pi-action/scripts/post_review.py"
          exit 0
        fi

        if [ "$CMD" = "describe" ]; then
          python3 - <<'PY'
        import json, os, sys, urllib.request
        sys.path.insert(0, os.path.join(os.environ["RUNNER_TEMP"], "pi-action", "scripts"))
        import post_review
        repo, pr, token = os.environ["REPO"], os.environ["PR"], os.environ["GH_TOKEN"]
        url = f"https://api.github.com/repos/{repo}/pulls/{pr}"
        headers = {"Authorization": f"Bearer {token}", "Accept": "application/vnd.github+json", "Content-Type": "application/json", "User-Agent": "pi-pr-agent"}
        with urllib.request.urlopen(urllib.request.Request(url, headers=headers), timeout=30) as r:
            existing = (json.loads(r.read().decode("utf-8")) or {}).get("body") or ""
        reply = open(os.path.join(os.environ["RUNNER_TEMP"], "reply.md"), encoding="utf-8").read()
        merged = post_review.merge_pr_description(existing, reply)
        req = urllib.request.Request(url, data=json.dumps({"body": merged}).encode("utf-8"), headers=headers, method="PATCH")
        urllib.request.urlopen(req, timeout=30).read()
        PY
          answer "$(printf 'Updated the PR description:\n\n%s' "$reply")"
          exit 0
        fi

        if [ "$CMD" = "ask" ]; then
          answer "$reply"
          exit 0
        fi

    - name: Report when command fails
      if: (failure() || cancelled()) && steps.prepare.outputs.go == 'true' && steps.prepare.outputs.already_handled != 'true'
      shell: bash
      env:
        GH_TOKEN: ${{ inputs.github_token }}
        REPO: ${{ github.repository }}
        PR: ${{ github.event.issue.number || github.event.pull_request.number }}
        COMMENT_ID: ${{ github.event.comment.id }}
        THREAD: ${{ github.event_name == 'pull_request_review_comment' && 'yes' || '' }}
        CMD: ${{ steps.prepare.outputs.cmd }}
        PROGRESS_COMMENT_ID: ${{ steps.prepare.outputs.progress_comment_id }}
        PROGRESS_COMMENT_KIND: ${{ steps.prepare.outputs.progress_comment_kind }}
        RUN: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
      run: |
        set -euo pipefail
        if [ "$CMD" = "fix" ]; then
          python3 "$RUNNER_TEMP/pi-action/scripts/run_fix.py" fail
          exit 0
        fi
        api="https://api.github.com/repos/$REPO"
        auth="Authorization: Bearer $GH_TOKEN"
        if [ "$CMD" = "review" ]; then
          comments=$(curl -fsSL -H "$auth" "$api/issues/$PR/comments?per_page=100" || echo '[]')
          existing=$(printf '%s' "$comments" | jq -r 'first(.[] | select(.body | startswith("<!-- pi-review")) | .id) // empty')
          marker=$(printf '%s' "$comments" | jq -r 'first(.[] | select(.body | startswith("<!-- pi-review")) | (.body | split("\n")[0])) // "<!-- pi-review -->"')
          if [ -n "$existing" ]; then
            icon="https://raw.githubusercontent.com/tripplen23/huggy-pr-agent/v1/assets/huggy-icon.svg"
            payload=$(jq -n --arg m "$marker" --arg ic "$icon" --arg run "$RUN" \
              '{body: ($m + "\n## <img src=\"" + $ic + "\" width=\"24\" height=\"24\" align=\"absmiddle\" alt=\"Huggy\" /> Review by Huggy\n\nThis `/review` run did not finish, so any verdict above is from an older commit. The log says why: " + $run)}')
            curl -fsSL -X PATCH -H "$auth" -H "Content-Type: application/json" \
              "$api/issues/comments/$existing" -d "$payload" > /dev/null || true
          fi
        fi
        fail_payload=$(jq -n --arg b "Huggy did not finish this one: a step failed, so nothing was pushed past the checks. The log says which: $RUN" '{body: $b}')
        if [ -n "${PROGRESS_COMMENT_ID:-}" ]; then
          patch_url="$api/issues/comments/$PROGRESS_COMMENT_ID"
          [ "${PROGRESS_COMMENT_KIND:-}" = "pull" ] && patch_url="$api/pulls/comments/$PROGRESS_COMMENT_ID"
          prog_body=$(curl -fsSL -H "$auth" "$patch_url" | jq -r '.body // ""' 2>/dev/null || true)
          case "$prog_body" in
            "<!-- huggy-cmd-progress -->"*)
              if curl -fsSL -X PATCH -H "$auth" -H "Content-Type: application/json" "$patch_url" -d "$fail_payload" > /dev/null 2>&1; then
                exit 0
              fi
              ;;
            ?*)
              # Progress comment was already replaced with a specific refusal message; preserve it!
              exit 0
              ;;
          esac
        fi
        if [ -n "$THREAD" ]; then
          post="$api/pulls/$PR/comments/$COMMENT_ID/replies"
        else
          post="$api/issues/$PR/comments"
        fi
        curl -fsSL -X POST -H "$auth" -H "Content-Type: application/json" \
          "$post" -d "$fail_payload" > /dev/null
