Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Create workflow to automate Claude Code creating PR fixes (#62198)

Fraser66f5f5845de2
diff --git a/.github/workflows/claude-code-bug-fix.yml b/.github/workflows/claude-code-bug-fix.yml
new file mode 100644
index 00000000000..85ecdf865f2
--- /dev/null
+++ b/.github/workflows/claude-code-bug-fix.yml
@@ -0,0 +1,387 @@
+name: "Claude Code Bug Fix"
+
+on:
+ issues:
+ types:
+ - labeled
+ workflow_dispatch:
+ inputs:
+ issue_number:
+ description: "Issue number to fix"
+ required: true
+ type: string
+
+jobs:
+ check-employee-and-issue:
+ runs-on: ubuntu-latest
+ timeout-minutes: 2
+ permissions:
+ contents: read
+ issues: read
+ if: |
+ (github.event_name == 'issues' && github.event.label.name == 'Claude Bug Fix' && github.event.issue.state == 'open') ||
+ (github.event_name == 'workflow_dispatch')
+ outputs:
+ is_employee: ${{ steps.check_employee.outputs.is_employee }}
+ issue_number: ${{ steps.get_issue.outputs.issue_number }}
+ issue_data: ${{ steps.get_issue.outputs.issue_data }}
+ steps:
+ - name: Generate GitHub App Token
+ uses: actions/create-github-app-token@v1
+ id: app-token
+ with:
+ app-id: ${{ secrets.METABASE_BOT_APP_ID }}
+ private-key: ${{ secrets.METABASE_BOT_APP_PRIVATE_KEY }}
+
+ - name: Get issue data
+ id: get_issue
+ uses: actions/github-script@v7
+ with:
+ script: |
+ let issueNumber, issueData;
+
+ if (context.eventName === 'issues') {
+ // Original issue label event
+ issueNumber = context.payload.issue.number;
+ issueData = context.payload.issue;
+ } else if (context.eventName === 'workflow_dispatch') {
+ // Manual trigger with issue number input
+ issueNumber = parseInt('${{ github.event.inputs.issue_number }}');
+ const { data } = await github.rest.issues.get({
+ owner: context.repo.owner,
+ repo: context.repo.repo,
+ issue_number: issueNumber
+ });
+ issueData = data;
+ }
+
+ core.setOutput('issue_number', issueNumber);
+ core.setOutput('issue_data', JSON.stringify(issueData));
+
+ console.log(`Issue #${issueNumber}: ${issueData.title}`);
+ console.log(`Issue author: ${issueData.user.login}`);
+
+ - name: Check if issue creator is a Metabase employee
+ id: check_employee
+ uses: actions/github-script@v7
+ env:
+ ISSUE_DATA: ${{ steps.get_issue.outputs.issue_data }}
+ with:
+ github-token: ${{ steps.app-token.outputs.token }}
+ script: |
+ const issueData = JSON.parse(process.env.ISSUE_DATA);
+ const issueAuthor = issueData.user.login;
+
+ try {
+ // Check if user is a member of the metabase organization (including private members)
+ const { data: membership } = await github.rest.orgs.getMembershipForUser({
+ org: 'metabase',
+ username: issueAuthor
+ });
+
+ if (membership.state === 'active') {
+ console.log(`User ${issueAuthor} is an active member of the Metabase organization. Proceeding with bug fix automation.`);
+ core.setOutput('is_employee', 'true');
+ } else {
+ console.log(`User ${issueAuthor} is not an active member of the Metabase organization. Skipping bug fix automation.`);
+ core.setOutput('is_employee', 'false');
+ }
+ } catch (error) {
+ if (error.status === 404) {
+ console.log(`User ${issueAuthor} is not a member of the Metabase organization. Skipping bug fix automation.`);
+ } else {
+ console.error('Error checking organization membership:', error);
+ }
+ core.setOutput('is_employee', 'false');
+ }
+
+ auto-fix-bug:
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+ permissions:
+ contents: write
+ issues: write
+ pull-requests: write
+ id-token: write
+ needs: check-employee-and-issue
+ if: needs.check-employee-and-issue.outputs.is_employee == 'true'
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@v4
+ with:
+ fetch-depth: 0
+ token: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Set up git configuration
+ run: |
+ git config --global user.name "Claude Code[bot]"
+ git config --global user.email "[email protected]"
+
+ - name: Prepare dynamic issue info
+ id: prepare_issue_info
+ uses: actions/github-script@v7
+ env:
+ ISSUE_DATA: ${{ needs.check-employee-and-issue.outputs.issue_data }}
+ with:
+ script: |
+ const issueData = JSON.parse(process.env.ISSUE_DATA);
+ const issueNumber = '${{ needs.check-employee-and-issue.outputs.issue_number }}';
+
+ // Convert issue title to kebab case
+ const issueTitle = issueData.title || 'untitled';
+ const kebabTitle = issueTitle
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-+|-+$/g, '')
+ .replace(/-+/g, '-')
+ .substring(0, 50); // Limit length
+
+ // Create base branch name
+ const baseBranchName = `claude-fix/issue-${issueNumber}-${kebabTitle}`;
+ core.exportVariable('BASE_BRANCH_NAME', baseBranchName);
+
+ // Export issue info for the prompt
+ core.exportVariable('ISSUE_NUMBER', issueNumber);
+ core.exportVariable('ISSUE_TITLE', issueData.title);
+ core.exportVariable('ISSUE_AUTHOR', issueData.user.login);
+ core.exportVariable('ISSUE_CREATED', issueData.created_at);
+ core.exportVariable('ISSUE_BODY', issueData.body || 'No description provided');
+
+ - name: Determine branch strategy
+ run: |
+ # Use the base branch name (no counters)
+ BRANCH_NAME="${{ env.BASE_BRANCH_NAME }}"
+
+ # Check if this exact branch already exists
+ if git branch -r --list "origin/${BRANCH_NAME}" | grep -q .; then
+ echo "Branch already exists: $BRANCH_NAME"
+ echo "Will push to existing branch and skip PR creation"
+ echo "BRANCH_EXISTS=true" >> $GITHUB_ENV
+ else
+ echo "Creating new branch: $BRANCH_NAME"
+ echo "Will create new PR"
+ echo "BRANCH_EXISTS=false" >> $GITHUB_ENV
+ fi
+
+ # Export the branch name
+ echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV
+
+ - name: Prepare bug fix prompt
+ id: prepare_prompt
+ run: |
+ # Prepare the prompt for Claude
+ cat << 'EOF' >> $GITHUB_ENV
+ BUG_FIX_PROMPT<<PROMPT_END
+ You are helping to automatically fix a bug reported in GitHub issue #${{ env.ISSUE_NUMBER }}.
+
+ ## Bug Report Details
+ **Title:** ${{ env.ISSUE_TITLE }}
+ **Reporter:** ${{ env.ISSUE_AUTHOR }}
+ **Created:** ${{ env.ISSUE_CREATED }}
+
+ **Description:**
+ ${{ env.ISSUE_BODY }}
+
+ ## Instructions
+ 1. **Analyze the bug report** - Understand what the issue is describing
+ 2. **Search the codebase** - Use Grep and Glob tools to find relevant files
+ 3. **Implement a fix** - Follow existing code patterns and conventions
+ 4. **Test the fix** - Run appropriate tests using the commands in CLAUDE.md:
+ - JavaScript/TypeScript: `yarn test-unit path/to/file.unit.spec.js`
+ - Clojure: `clojure -X:dev:test :only namespace/test-name`
+ - Lint: `yarn lint-eslint-pure` for JS/TS, `./bin/mage kondo <file>` for Clojure
+ 5. **Verify the fix** - Ensure tests pass and code follows conventions
+
+ ## Important Guidelines
+ - Follow the development patterns in CLAUDE.md
+ - Write failing tests first, then fix them
+ - Work in small, testable increments
+ - Don't commit changes - leave that for the workflow
+ - IMPORTANT: Focus only on fixing the reported bug, don't make unrelated changes
+
+ ## Scratchpad Directory
+ A `.claude-scratchpad/` directory has been created for your temporary files:
+ - Use this directory for ALL temporary verification files. However, prefer using production test files rather than adhoc ones.
+ - Only modify actual production code in the main repository directories
+ - The scratchpad will be cleaned up automatically - nothing from it will be committed
+
+ ## If You Cannot Fix The Bug
+ If you determine that you cannot create a definitive fix, create a file called `FAILED_FIX_ANALYSIS.md` with:
+ 1. **Why No Fix** - Specific reason why you couldn't implement a fix
+ 2. **Tool Limitations** - If you needed additional tools/access that weren't available
+
+ Start by understanding the bug and then systematically work toward a solution.
+ PROMPT_END
+ EOF
+
+ - name: Create scratchpad directory for Claude
+ run: |
+ # Create a scratchpad directory for Claude to use for temporary files
+ mkdir -p .claude-scratchpad
+ echo "Scratchpad directory created for Claude's temporary verification files"
+
+ - name: Generate GitHub App Token for Claude
+ uses: actions/create-github-app-token@v1
+ id: claude-app-token
+ with:
+ app-id: ${{ secrets.METABASE_BOT_APP_ID }}
+ private-key: ${{ secrets.METABASE_BOT_APP_PRIVATE_KEY }}
+
+ - name: Generate Bug Fix with Claude Code
+ uses: anthropics/claude-code-action@beta
+ with:
+ mode: agent
+ anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
+ github_token: ${{ steps.claude-app-token.outputs.token }}
+ direct_prompt: ${{ env.BUG_FIX_PROMPT }}
+ timeout_minutes: "25"
+ allowed_tools: "Bash(yarn test-unit*),Bash(yarn lint-eslint-pure),Bash(./bin/mage*),Bash(clojure*),Bash(find*),Bash(ls*),Bash(grep*),Write,Read,Glob,Grep,Edit,MultiEdit"
+ disallowed_tools: "Bash(git commit*),Bash(git push*),Bash(gh*)"
+
+ - name: Clean up scratchpad directory
+ run: |
+ # Remove the scratchpad directory so its contents don't get committed
+ rm -rf .claude-scratchpad/
+ # Remove output file generated by Claude Code action
+ rm -f output.txt
+ echo "Scratchpad directory and action output files cleaned up"
+
+ - name: Check for changes and analysis
+ id: check_changes
+ run: |
+ # Check if Claude created an analysis file first and store its content
+ if [ -f "FAILED_FIX_ANALYSIS.md" ]; then
+ echo "has_analysis=true" >> $GITHUB_OUTPUT
+ echo "Analysis file found"
+ # Store analysis content in a GitHub output (base64 encoded to handle multiline)
+ ANALYSIS_CONTENT=$(base64 -w 0 FAILED_FIX_ANALYSIS.md)
+ echo "analysis_content=$ANALYSIS_CONTENT" >> $GITHUB_OUTPUT
+ # Remove analysis file so it doesn't count as a code change
+ rm -f FAILED_FIX_ANALYSIS.md
+ else
+ echo "has_analysis=false" >> $GITHUB_OUTPUT
+ echo "No analysis file found"
+ fi
+
+ # Now check for actual code changes (excluding analysis file)
+ if [ -n "$(git status --porcelain)" ]; then
+ echo "has_changes=true" >> $GITHUB_OUTPUT
+ echo "Changes detected:"
+ git status --short
+ else
+ echo "has_changes=false" >> $GITHUB_OUTPUT
+ echo "No changes made by Claude."
+ fi
+
+ - name: Get issue team labels and prepare reviewers
+ if: steps.check_changes.outputs.has_changes == 'true'
+ id: prepare_reviewers
+ uses: actions/github-script@v7
+ env:
+ ISSUE_DATA: ${{ needs.check-employee-and-issue.outputs.issue_data }}
+ with:
+ script: |
+ // Get existing team labels from the issue
+ const issueData = JSON.parse(process.env.ISSUE_DATA);
+ const issueLabels = issueData.labels.map(label => label.name);
+ const teamLabels = issueLabels.filter(label => label.startsWith('.Team/'));
+
+ console.log('Issue labels:', issueLabels);
+ console.log('Team labels found:', teamLabels);
+
+ // Add issue creator as reviewer
+ const issueCreator = issueData.user.login;
+
+ core.setOutput('team_labels', teamLabels.join(','));
+ core.setOutput('reviewers', issueCreator);
+
+ console.log('Reviewer:', issueCreator);
+
+ - name: Create Pull Request
+ if: steps.check_changes.outputs.has_changes == 'true'
+ uses: peter-evans/create-pull-request@v6
+ with:
+ token: ${{ secrets.GITHUB_TOKEN }}
+ branch: ${{ env.BRANCH_NAME }}
+ base: master
+ commit-message: |
+ Fix: ${{ env.ISSUE_TITLE }}
+
+ Fixes #${{ env.ISSUE_NUMBER }}
+
+ πŸ€– Generated with [Claude Code](https://claude.ai/code)
+
+ Co-Authored-By: Claude <[email protected]>
+ committer: "Claude Code[bot] <[email protected]>"
+ author: "Claude Code[bot] <[email protected]>"
+ title: "Fix: ${{ env.ISSUE_TITLE }}"
+ body: |
+ This PR automatically fixes the bug reported in #${{ env.ISSUE_NUMBER }}.
+
+ ## Bug Report
+ **Original Issue:** #${{ env.ISSUE_NUMBER }}
+ **Reporter:** @${{ env.ISSUE_AUTHOR }}
+ **Issue Title:** ${{ env.ISSUE_TITLE }}
+
+ ## Automated Fix
+ πŸ€– This fix was generated automatically by Claude Code based on the issue description.
+
+ **Please review carefully:**
+ - [ ] The fix addresses the reported issue
+ - [ ] Tests pass and code follows conventions
+ - [ ] No unrelated changes were introduced
+ - [ ] The solution is appropriate and maintainable
+
+ ## Next Steps
+ - Review the changes and test thoroughly
+ - If the fix looks good, approve and merge
+ - If issues are found, either fix them or close this PR
+
+ ---
+ Closes #${{ env.ISSUE_NUMBER }}
+
+ πŸ€– Generated with [Claude Code](https://claude.ai/code)
+
+ Co-Authored-By: Claude <[email protected]>
+ labels: |
+ ${{ steps.prepare_reviewers.outputs.team_labels }}
+ automated-fix
+ ci skip
+ reviewers: ${{ steps.prepare_reviewers.outputs.reviewers }}
+
+ - name: Log existing branch update
+ if: steps.check_changes.outputs.has_changes == 'true' && env.BRANCH_EXISTS == 'true'
+ uses: actions/github-script@v7
+ with:
+ script: |
+ console.log('πŸ”„ Updated existing branch: ${{ env.BRANCH_NAME }}');
+ console.log('The changes have been pushed to the existing PR for this issue.');
+
+ - name: Log analysis for no changes
+ if: steps.check_changes.outputs.has_changes == 'false'
+ uses: actions/github-script@v7
+ with:
+ script: |
+ console.log('πŸ€– No code changes were made by Claude.');
+
+ // Check if Claude provided a detailed analysis
+ if ('${{ steps.check_changes.outputs.has_analysis }}' === 'true') {
+ try {
+ // Decode the base64-encoded analysis content
+ const analysisBase64 = '${{ steps.check_changes.outputs.analysis_content }}';
+ const analysisContent = Buffer.from(analysisBase64, 'base64').toString('utf8');
+ console.log('πŸ“‹ Claude provided detailed analysis:');
+ console.log('='.repeat(50));
+ console.log(analysisContent);
+ console.log('='.repeat(50));
+ } catch (error) {
+ console.log('❌ Could not decode analysis content:', error);
+ }
+ } else {
+ console.log('ℹ️ No detailed analysis file was created by Claude.');
+ console.log('This could be because:');
+ console.log('- The issue requires more context or clarification');
+ console.log('- The fix is complex and requires human judgment');
+ console.log('- The issue is not a straightforward code bug');
+ console.log('- Claude couldn\'t locate the relevant code to modify');
+ }