forked from Al-does/metta
-
Notifications
You must be signed in to change notification settings - Fork 0
765 lines (666 loc) · 34.6 KB
/
claude.yml
File metadata and controls
765 lines (666 loc) · 34.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
name: "Claude Assistant"
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
pull_request_review:
types: [submitted]
discussion_comment:
types: [created]
permissions:
contents: write
pull-requests: write
issues: write
discussions: write
id-token: write
actions: write
env:
CLAUDE_MODEL: "claude-sonnet-4-20250514"
jobs:
claude-response:
if: contains(github.event.comment.body, '@claude')
runs-on: ubuntu-latest
outputs:
action: ${{ steps.check_action.outputs.action }}
review_types: ${{ steps.check_action.outputs.review_types }}
comment_id: ${{ steps.context_info.outputs.comment_id }}
comment_type: ${{ steps.context_info.outputs.comment_type }}
pr_number: ${{ steps.context_info.outputs.pr_number }}
steps:
- name: Extract Context Information
id: context_info
run: |
echo "=== EXTRACTING CONTEXT INFO ==="
# Determine comment type and extract relevant IDs
if [[ "${{ github.event_name }}" == "issue_comment" ]]; then
echo "comment_type=issue" >> $GITHUB_OUTPUT
echo "comment_id=${{ github.event.issue.number }}" >> $GITHUB_OUTPUT
if [[ "${{ !!github.event.issue.pull_request }}" == "true" ]]; then
echo "is_pr=true" >> $GITHUB_OUTPUT
echo "pr_number=${{ github.event.issue.number }}" >> $GITHUB_OUTPUT
else
echo "is_pr=false" >> $GITHUB_OUTPUT
fi
elif [[ "${{ github.event_name }}" == "pull_request_review_comment" ]] || [[ "${{ github.event_name }}" == "pull_request_review" ]]; then
echo "comment_type=pr_review" >> $GITHUB_OUTPUT
echo "comment_id=${{ github.event.pull_request.number }}" >> $GITHUB_OUTPUT
echo "pr_number=${{ github.event.pull_request.number }}" >> $GITHUB_OUTPUT
echo "is_pr=true" >> $GITHUB_OUTPUT
elif [[ "${{ github.event_name }}" == "discussion_comment" ]]; then
echo "comment_type=discussion" >> $GITHUB_OUTPUT
echo "comment_id=${{ github.event.discussion.number }}" >> $GITHUB_OUTPUT
echo "is_pr=false" >> $GITHUB_OUTPUT
elif [[ "${{ github.event_name }}" == "commit_comment" ]]; then
echo "comment_type=commit" >> $GITHUB_OUTPUT
echo "comment_id=${{ github.event.comment.commit_id }}" >> $GITHUB_OUTPUT
echo "is_pr=false" >> $GITHUB_OUTPUT
else
echo "comment_type=unknown" >> $GITHUB_OUTPUT
echo "comment_id=none" >> $GITHUB_OUTPUT
echo "is_pr=false" >> $GITHUB_OUTPUT
fi
echo "==========================="
- name: Debug - Workflow Context
run: |
echo "=== WORKFLOW DEBUG INFO ==="
echo "Event: ${{ github.event_name }}"
echo "Action: ${{ github.event.action }}"
echo "Comment Type: ${{ steps.context_info.outputs.comment_type }}"
echo "Comment ID: ${{ steps.context_info.outputs.comment_id }}"
echo "Is PR: ${{ steps.context_info.outputs.is_pr }}"
echo "PR Number: ${{ steps.context_info.outputs.pr_number }}"
echo "Comment Body: ${{ github.event.comment.body }}"
echo "Comment Author: ${{ github.event.comment.user.login }}"
echo "Repository: ${{ github.repository }}"
echo "==========================="
- name: Check for action type
id: check_action
run: |
echo "=== ACTION DETECTION DEBUG ==="
echo "Full comment: ${{ github.event.comment.body }}"
IS_PR="${{ steps.context_info.outputs.is_pr }}"
# Check for review commands first (must be on a PR)
if [[ "$IS_PR" == "true" ]]; then
if echo "${{ github.event.comment.body }}" | grep -q "@claude review"; then
echo "✅ Detected: Review request"
echo "action=review" >> $GITHUB_OUTPUT
echo "fetch_depth=0" >> $GITHUB_OUTPUT
# Extract review types from the comment
REVIEW_ARGS=$(echo "${{ github.event.comment.body }}" | sed -n 's/.*@claude review\s*\([^@]*\).*/\1/p' | head -1)
echo "Review arguments: '$REVIEW_ARGS'"
# Parse the review types
REVIEW_TYPES=""
# Check for special keywords first
if echo "$REVIEW_ARGS" | grep -qw "all"; then
echo "✅ Detected: All reviews requested"
REVIEW_TYPES="readme,comments,types,einops"
else
# Parse comma-separated list
PARSED_TYPES=$(echo "$REVIEW_ARGS" | sed 's/[\[\]]//g' | tr ',' '\n' | sed 's/^[[:space:]]*//;s/[[:space:]]*$//' | grep -E '^(readme|comments|types|einops)$' | tr '\n' ',' | sed 's/,$//')
if [ -z "$PARSED_TYPES" ]; then
echo "⚠️ No valid review types found, defaulting to all"
REVIEW_TYPES="readme,comments,types,einops"
else
REVIEW_TYPES="$PARSED_TYPES"
fi
fi
echo "review_types=$REVIEW_TYPES" >> $GITHUB_OUTPUT
echo "✅ Review types to run: $REVIEW_TYPES"
elif echo "${{ github.event.comment.body }}" | grep -q "@claude open-pr"; then
echo "✅ Detected: PR creation request"
echo "action=create_pr" >> $GITHUB_OUTPUT
echo "fetch_depth=0" >> $GITHUB_OUTPUT
else
echo "✅ Detected: Regular comment request"
echo "action=comment" >> $GITHUB_OUTPUT
echo "fetch_depth=1" >> $GITHUB_OUTPUT
fi
else
# Not on a PR, check for open-pr or default to comment
if echo "${{ github.event.comment.body }}" | grep -q "@claude open-pr"; then
echo "✅ Detected: PR creation request"
echo "action=create_pr" >> $GITHUB_OUTPUT
echo "fetch_depth=0" >> $GITHUB_OUTPUT
else
echo "✅ Detected: Regular comment request"
echo "action=comment" >> $GITHUB_OUTPUT
echo "fetch_depth=1" >> $GITHUB_OUTPUT
fi
fi
echo "=============================="
# Post acknowledgment for review requests
- name: Post Review Acknowledgment
if: steps.check_action.outputs.action == 'review' && steps.context_info.outputs.comment_type == 'issue'
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const reviewTypes = '${{ steps.check_action.outputs.review_types }}'.split(',');
await github.rest.issues.createComment({
issue_number: ${{ steps.context_info.outputs.comment_id }},
owner: context.repo.owner,
repo: context.repo.repo,
body: `🔍 **Starting Claude review...**\n\nI'll analyze:\n${reviewTypes.map(t => `- ${t.charAt(0).toUpperCase() + t.slice(1)}`).join('\n')}\n\nThis may take a few minutes. You can check the progress in the [Actions tab](${{ github.server_url }}/${{ github.repository }}/actions).`
});
# Only checkout and run Claude if not a review action
- name: Checkout repository
if: contains(fromJson('["comment", "create_pr"]'), steps.check_action.outputs.action)
uses: actions/checkout@v4
with:
fetch-depth: ${{ steps.check_action.outputs.fetch_depth == '0' && 0 || 1 }}
token: ${{ secrets.GITHUB_TOKEN }}
- name: Configure Git
if: steps.check_action.outputs.action == 'create_pr'
run: |
git config --global user.name "Claude Assistant"
git config --global user.email "claude-assistant@users.noreply.github.com"
- name: Debug - Check Secrets
if: contains(fromJson('["comment", "create_pr"]'), steps.check_action.outputs.action)
run: |
echo "=== SECRETS DEBUG ==="
if [ -n "${{ secrets.ANTHROPIC_API_KEY }}" ]; then
echo "✅ ANTHROPIC_API_KEY is set"
else
echo "❌ ANTHROPIC_API_KEY is missing!"
fi
echo "=================="
# Regular Claude responses for comments/questions
- name: Claude Comment Response
if: steps.check_action.outputs.action == 'comment'
uses: anthropics/claude-code-action@beta
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
model: ${{ env.CLAUDE_MODEL }}
timeout_minutes: 30
allowed_tools: "Bash(git status),Bash(git log --oneline -10),Bash(git show),Bash(git diff *),Bash(git branch -a),Bash(ruff check *),Bash(python -m *),Bash(./tools/*),View,GlobTool,GrepTool"
custom_instructions: |
Follow the project's coding standards defined in CLAUDE.md.
Provide helpful analysis and suggestions for code improvements.
Focus on code review, explanations, and suggestions rather than making changes.
You have access to ruff for linting Python code if needed.
# Determine target branch and generate new branch name
- name: Determine branches
if: steps.check_action.outputs.action == 'create_pr'
id: branches
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
let targetBranch = 'main'; // fallback
let contextInfo = '';
const commentType = '${{ steps.context_info.outputs.comment_type }}';
const commentId = '${{ steps.context_info.outputs.comment_id }}';
const prNumber = '${{ steps.context_info.outputs.pr_number }}';
// Determine target branch based on comment type
if (commentType === 'issue' && prNumber) {
// Comment on a PR
console.log("Comment made on PR, fetching PR details...");
const prResponse = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: parseInt(prNumber)
});
targetBranch = prResponse.data.head.ref;
contextInfo = `PR #${prNumber} (${targetBranch})`;
console.log(`Will target PR branch: ${targetBranch}`);
} else if (commentType === 'pr_review') {
// PR review comment
console.log("PR review comment, fetching PR details...");
const prResponse = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: parseInt(prNumber)
});
targetBranch = prResponse.data.head.ref;
contextInfo = `PR #${prNumber} review (${targetBranch})`;
console.log(`Will target PR branch: ${targetBranch}`);
} else {
// For issues, discussions, commits, or unknown - use default branch
const repoResponse = await github.rest.repos.get({
owner: context.repo.owner,
repo: context.repo.repo
});
targetBranch = repoResponse.data.default_branch;
if (commentType === 'issue') {
contextInfo = `issue #${commentId} (${targetBranch})`;
} else if (commentType === 'discussion') {
contextInfo = `discussion #${commentId} (${targetBranch})`;
} else if (commentType === 'commit') {
contextInfo = `commit ${commentId.substring(0, 7)} (${targetBranch})`;
} else {
contextInfo = `${commentType} comment (${targetBranch})`;
}
console.log(`Will target default branch: ${targetBranch}`);
}
// Generate unique branch name
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
const identifier = commentId === 'none' ? 'direct' : commentId;
const newBranch = `claude/auto-${identifier}-${timestamp}`;
console.log(`New branch: ${newBranch} -> ${targetBranch}`);
// Set outputs
core.setOutput('target_branch', targetBranch);
core.setOutput('new_branch', newBranch);
core.setOutput('context_info', contextInfo);
return {
targetBranch,
newBranch,
contextInfo
};
# Pre-create the branch before Claude runs
- name: Setup branch for Claude
if: steps.check_action.outputs.action == 'create_pr'
run: |
echo "=== SETTING UP BRANCH FOR CLAUDE ==="
# Fetch all remote branches
git fetch origin
# Checkout and update the target branch
git checkout ${{ steps.branches.outputs.target_branch }}
git pull origin ${{ steps.branches.outputs.target_branch }}
# Create and checkout the new branch
git checkout -b ${{ steps.branches.outputs.new_branch }}
echo "✅ Created branch: $(git branch --show-current)"
echo "✅ Ready for Claude to make changes"
- name: Prepare MCP Configuration
if: steps.check_action.outputs.action == 'create_pr'
id: mcp_config
run: |
echo "=== PREPARING MCP CONFIGURATION ==="
# Debug available paths
echo "GITHUB_WORKSPACE: $GITHUB_WORKSPACE"
echo "GITHUB_ACTION_PATH: ${GITHUB_ACTION_PATH:-'NOT SET'}"
echo "Current directory: $(pwd)"
# Find the claude-code-action path
CLAUDE_ACTION_PATH="/home/runner/work/_actions/anthropics/claude-code-action/beta"
if [ -d "$CLAUDE_ACTION_PATH" ]; then
echo "✅ Found Claude action at: $CLAUDE_ACTION_PATH"
else
echo "⚠️ Claude action not found at expected path, checking alternatives..."
find /home/runner/work/_actions -name "github-file-ops-server.ts" -type f 2>/dev/null || true
fi
# Construct the MCP config
MCP_CONFIG=$(cat <<EOF
{
"mcpServers": {
"github_file_ops": {
"command": "bun",
"args": [
"run",
"${CLAUDE_ACTION_PATH}/src/mcp/github-file-ops-server.ts"
],
"env": {
"GITHUB_TOKEN": "${{ secrets.GITHUB_TOKEN }}",
"REPO_OWNER": "${{ github.repository_owner }}",
"REPO_NAME": "${{ github.event.repository.name }}",
"BRANCH_NAME": "${{ steps.branches.outputs.new_branch }}",
"REPO_DIR": "${{ github.workspace }}",
"CLAUDE_COMMENT_ID": "${{ github.event.comment.id }}",
"GITHUB_EVENT_NAME": "workflow_dispatch",
"IS_PR": "false",
"GITHUB_API_URL": "${{ github.api_url }}",
"DEBUG": "github-file-ops:*"
}
}
}
}
EOF
)
# Log the config for debugging
echo "=== MCP CONFIGURATION ==="
echo "$MCP_CONFIG" | jq '.' || echo "$MCP_CONFIG"
echo "========================="
# Validate critical values
echo "=== VALIDATING CONFIG ==="
echo "Branch name: ${{ steps.branches.outputs.new_branch }}"
echo "Repo: ${{ github.repository_owner }}/${{ github.event.repository.name }}"
echo "Comment ID: ${{ github.event.comment.id }}"
# Save config as output (need to escape newlines)
MCP_CONFIG_ESCAPED=$(echo "$MCP_CONFIG" | jq -c '.')
echo "config=$MCP_CONFIG_ESCAPED" >> $GITHUB_OUTPUT
# Claude PR creation with MCP tools instead of bash
- name: Claude PR Creation
if: steps.check_action.outputs.action == 'create_pr'
uses: anthropics/claude-code-action@beta
id: claude_pr
continue-on-error: true
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
model: ${{ env.CLAUDE_MODEL }}
timeout_minutes: 45
mcp_config: ${{ steps.mcp_config.outputs.config }}
direct_prompt: |
CRITICAL FIRST STEP - BRANCH SWITCHING:
The Claude action may have automatically checked out the wrong branch.
YOUR VERY FIRST ACTION MUST BE to switch to the correct branch.
🚨 STEP 1 - MANDATORY FIRST ACTION 🚨
Use this bash command IMMEDIATELY as your first tool call:
Bash(git checkout ${{ steps.branches.outputs.new_branch }})
This will ensure you're on the correct branch: ${{ steps.branches.outputs.new_branch }}
CONTEXT:
- Working directory: ${{ github.workspace }}
- Branch you MUST work on: ${{ steps.branches.outputs.new_branch }}
- Target branch for eventual PR: ${{ steps.branches.outputs.target_branch }}
- Request from: ${{ steps.branches.outputs.context_info }}
YOUR TASK: "${{ github.event.comment.body }}"
WORKFLOW INSTRUCTIONS:
1. FIRST: Run `Bash(git checkout ${{ steps.branches.outputs.new_branch }})` to switch to the correct branch
2. SECOND: Verify you're on the correct branch with `Bash(git branch --show-current)`
3. THIRD: Check for project standards:
- Look for CLAUDE.md file and follow any coding standards defined there
- Check for .prettierrc, .eslintrc, pyproject.toml, or similar config files
4. FOURTH: Make all the requested code changes using Edit/Replace tools
5. FIFTH: Run quality checks if available:
- Check for test commands in package.json, Makefile, or similar
- Run linters/formatters if configured (e.g., prettier, eslint, black, ruff)
- Only proceed if no errors, or document any issues you can't resolve
6. FINALLY: Commit your changes using ONE of these methods:
Option A (preferred): Use the MCP tool:
mcp__github_file_ops__commit_files
Option B (if MCP fails): Use bash commands:
Bash(git add -A)
Bash(git commit -m "feat: implement requested changes from ${{ steps.branches.outputs.context_info }}")
Use a descriptive commit message like:
"feat: implement requested changes from ${{ steps.branches.outputs.context_info }}"
CRITICAL REMINDERS:
- IMPORTANT: Never modify files in .github/workflows/ directory. If asked to modify workflow files, explain that this is restricted for security.
- You MUST switch to branch ${{ steps.branches.outputs.new_branch }} before making ANY changes
- If mcp__github_file_ops__commit_files fails with 404, use the bash git commands instead
- Do NOT push or create a PR - the workflow handles that
- All your changes should be on ${{ steps.branches.outputs.new_branch }}, NOT on ${{ steps.branches.outputs.target_branch }}
- If tests fail, try to fix the issues before committing, or clearly document what's failing
TROUBLESHOOTING:
- If you get "permission denied" for bash commands, report this in your response
- If MCP tools fail with 404 errors, use the bash git fallback commands
- If tests or linters fail, attempt to fix issues or document them clearly
- Always verify you're on the correct branch before and after making changes
allowed_tools: "Edit,Replace,View,GlobTool,GrepTool,Read,Write,mcp__github_file_ops__commit_files,mcp__github__update_issue_comment,Bash(git checkout*),Bash(git branch*),Bash(git status),Bash(git add*),Bash(git commit*),Bash(git log*)"
- name: Fix git state after Claude
if: steps.check_action.outputs.action == 'create_pr' && steps.claude_pr.outcome == 'success'
id: fix_git_state
run: |
echo "=== FIXING GIT STATE ==="
# Ensure we're on the correct branch
CURRENT_BRANCH=$(git branch --show-current)
echo "Current branch: $CURRENT_BRANCH"
if [ "$CURRENT_BRANCH" != "${{ steps.branches.outputs.new_branch }}" ]; then
echo "⚠️ Not on expected branch, switching to ${{ steps.branches.outputs.new_branch }}"
git checkout ${{ steps.branches.outputs.new_branch }}
fi
# Clean up any debug/output files that shouldn't be committed
echo "=== CLEANING UP EXTRA FILES ==="
# Remove common debug/output files if they exist
for file in output.txt output.log debug.txt claude-debug.txt .claude-session*; do
if [ -f "$file" ]; then
echo "Removing debug file: $file"
rm -f "$file"
fi
done
# Check git status to see what files were added/modified
echo "=== GIT STATUS AFTER CLEANUP ==="
git status --short
# Check for uncommitted changes
if ! git diff --quiet || ! git diff --cached --quiet; then
echo "⚠️ Found uncommitted changes, committing them..."
git add -A
git commit -m "feat: implement requested changes from ${{ steps.branches.outputs.context_info }}"
echo "✅ Changes committed"
fi
# Check if there are commits to push
COMMIT_COUNT=$(git rev-list --count origin/${{ steps.branches.outputs.target_branch }}..HEAD 2>/dev/null || echo "0")
echo "commit_count=$COMMIT_COUNT" >> $GITHUB_OUTPUT
if [ "$COMMIT_COUNT" -gt "0" ]; then
echo "✅ Found $COMMIT_COUNT commits to push"
echo "has_commits=true" >> $GITHUB_OUTPUT
else
echo "❌ No commits found"
echo "has_commits=false" >> $GITHUB_OUTPUT
fi
# Debug git state after fix
- name: Debug git state after fix
if: steps.check_action.outputs.action == 'create_pr' && steps.claude_pr.outcome == 'success'
run: |
echo "=== GIT STATE AFTER FIX ==="
echo "Current branch: $(git branch --show-current)"
echo ""
echo "Git status:"
git status --short
echo ""
echo "Commits on current branch not on target:"
git log --oneline origin/${{ steps.branches.outputs.target_branch }}..HEAD || echo "No commits"
echo ""
echo "All local branches:"
git branch -vv
echo "============================"
# Push the branch after ensuring commits exist
- name: Push branch if needed
if: steps.check_action.outputs.action == 'create_pr' && steps.fix_git_state.outputs.has_commits == 'true'
id: push_branch
run: |
echo "=== PUSHING BRANCH ==="
# Push the branch
git push -u origin ${{ steps.branches.outputs.new_branch }}
echo "✅ Branch pushed successfully"
echo "branch_pushed=true" >> $GITHUB_OUTPUT
# Create PR only if branch was pushed successfully
- name: Create Pull Request
if: steps.check_action.outputs.action == 'create_pr' && steps.push_branch.outputs.branch_pushed == 'true'
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
try {
console.log("=== CREATING PULL REQUEST ===");
const targetBranch = "${{ steps.branches.outputs.target_branch }}";
const newBranch = "${{ steps.branches.outputs.new_branch }}";
const contextInfo = "${{ steps.branches.outputs.context_info }}";
const commitCount = "${{ steps.fix_git_state.outputs.commit_count }}";
const commentType = "${{ steps.context_info.outputs.comment_type }}";
console.log(`Creating PR: ${newBranch} -> ${targetBranch}`);
console.log(`Context: ${contextInfo}`);
// Get latest commit for PR title
const { execSync } = require('child_process');
const latestCommit = execSync('git log -1 --pretty=format:"%s"', { encoding: 'utf-8' }).trim();
const prTitle = latestCommit.length > 50
? `${latestCommit.substring(0, 47)}...`
: latestCommit;
// Use context.payload to safely access the comment body
const commentBody = context.payload.comment?.body || 'No description provided';
// Create the PR targeting the original branch
const prResponse = await github.rest.pulls.create({
owner: context.repo.owner,
repo: context.repo.repo,
title: prTitle,
head: newBranch,
base: targetBranch,
body: [
"🤖 **Automated PR created by Claude**",
"",
"**Original request:**",
...commentBody.split('\n').map(line => '> ' + line.trim()),
"",
"**Context:** This PR addresses the request from " + contextInfo,
"**Target:** This PR will merge into " + targetBranch + (targetBranch === 'main' ? '' : ' (not main)'),
"",
"**Changes made:**",
"- " + commitCount + " commit(s) with: " + latestCommit,
"",
"**Branch flow:** " + newBranch + " → " + targetBranch,
"",
"---",
"*This PR was automatically created by Claude Code Assistant.*"
].join('\n')
});
console.log(`✅ Created PR #${prResponse.data.number}: ${prResponse.data.html_url}`);
// Post success comment based on comment type
const commentId = '${{ steps.context_info.outputs.comment_id }}';
const successMessage = [
"🚀 **PR Created Successfully!**",
"",
"I've implemented your request and created PR #" + prResponse.data.number + ":",
prResponse.data.html_url,
"",
"**Branch flow:** " + newBranch + " → " + targetBranch,
"**Commits:** " + commitCount,
"**Changes:** " + latestCommit,
"",
targetBranch !== 'main'
? "This PR targets the feature branch " + targetBranch + " for iterative development! 🔄"
: "This PR is ready for review! 🎉"
].join('\n');
// Post comment based on original comment source
if (commentType === 'issue' || (commentType === 'pr_review' && '${{ steps.context_info.outputs.pr_number }}')) {
await github.rest.issues.createComment({
issue_number: parseInt(commentId),
owner: context.repo.owner,
repo: context.repo.repo,
body: successMessage
});
} else if (commentType === 'discussion') {
// For discussions, we can't easily post back, so log the URL
console.log("PR created from discussion comment. Users should check the PR directly.");
} else if (commentType === 'commit') {
// For commit comments, we also can't easily post back
console.log("PR created from commit comment. Users should check the PR directly.");
}
} catch (error) {
console.error('Error creating PR:', error);
const errorMessage = [
"❌ **Failed to create PR**",
"",
"Error: " + error.message,
"",
"**Debug info:**",
"- New branch: ${{ steps.branches.outputs.new_branch }}",
"- Target branch: ${{ steps.branches.outputs.target_branch }}",
"- Branch pushed: ${{ steps.push_branch.outputs.branch_pushed }}",
"- Has commits: ${{ steps.fix_git_state.outputs.has_commits }}",
"- Commit count: ${{ steps.fix_git_state.outputs.commit_count }}",
"",
"Please check the Actions logs for more details."
].join('\n');
// Try to post error message where possible
const commentType = '${{ steps.context_info.outputs.comment_type }}';
const commentId = '${{ steps.context_info.outputs.comment_id }}';
if (commentType === 'issue' || commentType === 'pr_review') {
await github.rest.issues.createComment({
issue_number: parseInt(commentId),
owner: context.repo.owner,
repo: context.repo.repo,
body: errorMessage
});
}
}
# Handle case where Claude didn't complete the workflow
- name: Handle workflow failure
if: steps.check_action.outputs.action == 'create_pr' && (steps.push_branch.outputs.branch_pushed != 'true' || steps.fix_git_state.outputs.has_commits != 'true')
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
let reason = "Unknown issue";
if ("${{ steps.fix_git_state.outputs.has_commits }}" !== 'true') {
reason = "No changes were committed";
} else if ("${{ steps.push_branch.outputs.branch_pushed }}" !== 'true') {
reason = "Failed to push the branch";
}
const errorMessage = [
"⚠️ **Unable to create PR**",
"",
`**Reason:** ${reason}`,
"",
"**Debug info:**",
`- Expected branch: \`${{ steps.branches.outputs.new_branch }}\``,
`- Target branch: \`${{ steps.branches.outputs.target_branch }}\``,
`- Has commits: ${{ steps.fix_git_state.outputs.has_commits }}`,
`- Branch pushed: ${{ steps.push_branch.outputs.branch_pushed }}`,
`- Claude execution: ${{ steps.claude_pr.outcome }}`,
"",
"**Possible solutions:**",
"- Try a simpler, more specific request",
"- Check if the changes conflict with existing code",
"- Ensure Claude used mcp__github_file_ops__commit_files to commit",
"",
"You can view the full execution logs in the Actions tab for more details."
].join('\n');
// Try to post message based on comment type
const commentType = '${{ steps.context_info.outputs.comment_type }}';
const commentId = '${{ steps.context_info.outputs.comment_id }}';
if ((commentType === 'issue' || commentType === 'pr_review') && commentId !== 'none') {
await github.rest.issues.createComment({
issue_number: parseInt(commentId),
owner: context.repo.owner,
repo: context.repo.repo,
body: errorMessage
});
}
# Add help message for unrecognized commands on PRs
- name: Post Help Message
if: steps.check_action.outputs.action == 'comment' && steps.context_info.outputs.is_pr == 'true'
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
// Check if the comment might have been trying to use a review command
const comment = "${{ github.event.comment.body }}".toLowerCase();
const commentId = '${{ steps.context_info.outputs.comment_id }}';
if (comment.includes('review') && commentId !== 'none') {
await github.rest.issues.createComment({
issue_number: parseInt(commentId),
owner: context.repo.owner,
repo: context.repo.repo,
body: [
"💡 **Claude Review Commands Available**",
"",
"I noticed you mentioned 'review'. Here's how to use review commands:",
"",
"**Syntax:** `@claude review <types>`",
"",
"**Examples:**",
"- `@claude review all` - Run all review types",
"- `@claude review einops` - Check for einops optimization opportunities",
"- `@claude review comments, types` - Review comments and type annotations",
"- `@claude review readme, einops, comments` - Run multiple specific reviews",
"",
"**Available review types:**",
"- `readme` - Verify README accuracy",
"- `comments` - Review code comments and docstrings",
"- `types` - Check type annotations",
"- `einops` - Suggest einops optimizations",
"- `all` - Run all review types",
"",
"You can also:",
"- `@claude open-pr` - Create a new PR with changes",
"- `@claude [question]` - Ask me anything about the code",
"",
"*Note: Review commands only work on pull requests.*"
].join('\n')
});
}
- name: Final Debug Summary
if: always()
run: |
echo "=== FINAL WORKFLOW SUMMARY ==="
echo "Action type: ${{ steps.check_action.outputs.action }}"
echo "Comment type: ${{ steps.context_info.outputs.comment_type }}"
echo "Comment ID: ${{ steps.context_info.outputs.comment_id }}"
echo "New branch: ${{ steps.branches.outputs.new_branch }}"
echo "Target branch: ${{ steps.branches.outputs.target_branch }}"
echo "Context: ${{ steps.branches.outputs.context_info }}"
echo "Branch pushed: ${{ steps.push_branch.outputs.branch_pushed }}"
echo "Has commits: ${{ steps.fix_git_state.outputs.has_commits }}"
echo "Commit count: ${{ steps.fix_git_state.outputs.commit_count }}"
echo "Claude outcome: ${{ steps.claude_pr.outcome }}"
echo "Workflow status: ${{ job.status }}"
echo "=============================="
# Call the orchestrator workflow as a job when review is requested
run-orchestrator:
needs: claude-response
if: needs.claude-response.outputs.action == 'review'
uses: ./.github/workflows/claude-review-orchestrator.yml
secrets: inherit
with:
pr_number: ${{ needs.claude-response.outputs.pr_number }}
run_readme: ${{ contains(needs.claude-response.outputs.review_types, 'readme') }}
run_comments: ${{ contains(needs.claude-response.outputs.review_types, 'comments') }}
run_types: ${{ contains(needs.claude-response.outputs.review_types, 'types') }}
run_einops: ${{ contains(needs.claude-response.outputs.review_types, 'einops') }}