-
Notifications
You must be signed in to change notification settings - Fork 1
1437 lines (1257 loc) · 63.7 KB
/
claude.yml
File metadata and controls
1437 lines (1257 loc) · 63.7 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
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
name: Claude Code
on:
# Manual/programmatic trigger
workflow_dispatch:
inputs:
trigger_text:
description: 'Text to trigger Claude with (optional)'
required: true
type: string
default: '@claude'
actor:
description: 'Actor to trigger Claude'
required: true
type: string
default: 'david'
# PR related events
pull_request_target:
types: [opened, synchronize, reopened]
pull_request_review_comment:
types: [created]
pull_request_review:
types: [submitted]
# Issue related events (added)
issues:
types: [opened, assigned]
issue_comment:
types: [created]
# Concurrency control (one run per Issue/PR)
concurrency:
group: claude-${{ github.repository }}-${{ github.event.number || github.run_id }}
cancel-in-progress: false
jobs:
setup:
# Security-focused conditional execution (full support for Issues, PRs, and manual dispatch)
if: |
(
github.event_name == 'workflow_dispatch' &&
github.event.inputs.trigger_text != '' &&
github.event.inputs.actor != ''
) ||
(
github.event_name == 'pull_request_target' &&
(
github.event.pull_request.head.repo.full_name == github.repository ||
contains(fromJSON('["COLLABORATOR", "MEMBER", "OWNER"]'), github.event.pull_request.author_association)
) &&
contains(github.event.pull_request.body, '@claude')
) ||
(
github.event_name == 'issue_comment' &&
(
github.event.sender.login == github.repository_owner ||
contains(fromJSON('["COLLABORATOR", "MEMBER", "OWNER"]'), github.event.comment.author_association)
) &&
contains(github.event.comment.body, '@claude')
) ||
(
github.event_name == 'issues' &&
(
github.event.sender.login == github.repository_owner ||
contains(fromJSON('["COLLABORATOR", "MEMBER", "OWNER"]'), github.event.issue.author_association)
) &&
(
contains(github.event.issue.body, '@claude') ||
contains(github.event.issue.title, '@claude')
)
) ||
(
github.event_name == 'pull_request_review_comment' &&
(
github.event.sender.login == github.repository_owner ||
contains(fromJSON('["COLLABORATOR", "MEMBER", "OWNER"]'), github.event.comment.author_association)
) &&
contains(github.event.comment.body, '@claude')
) ||
(
github.event_name == 'pull_request_review' &&
(
github.event.sender.login == github.repository_owner ||
contains(fromJSON('["COLLABORATOR", "MEMBER", "OWNER"]'), github.event.review.author_association)
) &&
contains(github.event.review.body, '@claude')
)
runs-on: ubuntu-latest
timeout-minutes: 2
permissions:
# 📁 Content management (highest permissions)
contents: write
pull-requests: write
issues: write
discussions: write
# 🔧 Development & CI/CD management
actions: write
checks: write
statuses: write
pages: write
deployments: write
# 📦 Package & security management
packages: write
security-events: write
# 🎯 Project management
repository-projects: write
# 🆔 Authentication & token management
id-token: write
# Outputs
outputs:
should-continue: ${{ steps.should-continue.outputs.should-continue }}
issue-number: ${{ steps.context-info.outputs.issue-number }}
pr-number: ${{ steps.context-info.outputs.pr-number }}
head-ref: ${{ steps.context-info.outputs.head-ref }}
base-ref: ${{ steps.context-info.outputs.base-ref }}
head-sha: ${{ steps.context-info.outputs.head-sha }}
is-pr: ${{ steps.context-info.outputs.is-pr }}
trigger-text: ${{ steps.context-info.outputs.trigger-text }}
has-linked-pr: ${{ steps.context-info.outputs.has-linked-pr }}
status-comment-id: ${{ steps.find_comment.outputs.comment-id || steps.create_comment.outputs.comment-id }}
######################
# Setup steps
######################
steps:
# Verify user permissions from dispatch
- name: Check dispatch permissions
id: check_membership
if: github.event_name == 'workflow_dispatch'
uses: actions/github-script@v7
with:
script: |
const allowedUsersInput = '${{ secrets.ALLOWED_USERS }}'
// Skip if no allowed users configured
if (!allowedUsersInput || allowedUsersInput.trim() === '') {
console.log('No allowed users configured in secrets, allowing all')
core.setOutput('is_member', true)
return
}
// Parse the allowed users (comma-separated)
const allowedUsers = allowedUsersInput.split(',').map(u => u.trim()).filter(u => u)
if (allowedUsers.length === 0) {
console.log('Empty allowed users list, allowing all')
core.setOutput('is_member', true)
return
}
let actor
if (context.eventName === 'issue_comment') {
actor = context.payload.comment.user.login
} else if (context.eventName === 'pull_request_review_comment') {
actor = context.payload.comment.user.login
} else if (context.eventName === 'pull_request_review') {
actor = context.payload.review.user.login
} else if (context.eventName === 'issues') {
actor = context.payload.issue.user.login
}
console.log(`Checking permissions for user: ${actor}`)
console.log(`Allowed users: ${allowedUsers.join(', ')}`)
if (allowedUsers.includes(actor)) {
console.log(`User ${actor} is in the allowed list`)
core.setOutput('is_member', true)
return
}
// Get organization name from context
const orgName = context.repo.owner
console.log(`Organization: ${orgName}`)
// Fallback: Check if user has repository permissions
try {
const collaboration = await github.rest.repos.getCollaboratorPermissionLevel({
owner: context.repo.owner,
repo: context.repo.repo,
username: actor
})
const permission = collaboration.data.permission
console.log(`User ${actor} has permission level: ${permission}`)
// Allow if user has push access or higher (write, maintain, admin)
const allowed = ['write', 'maintain', 'admin'].includes(permission)
if (allowed) {
core.setOutput('is_member', true)
} else {
core.setFailed(`User ${actor} does not have permission to run this workflow`)
return
}
} catch (error) {
console.log(`Error checking permissions: ${error.message}`)
// Final fallback: Check if user is a public member of the organization
try {
const membership = await github.rest.orgs.getMembershipForUser({
org: orgName,
username: actor
})
const allowed = membership.data.state === 'active'
if (allowed) {
core.setOutput('is_member', true)
} else {
core.setFailed(`User ${actor} does not have permission to run this workflow`)
return
}
} catch (membershipError) {
console.log(`Error checking organization membership: ${membershipError.message}`)
core.setFailed(`User ${actor} does not have permission to run this workflow`)
return
}
}
# Collect information from the event
- name: Get Context Information
id: context-info
uses: actions/github-script@v7
with:
script: |
let issueNumber, prNumber, headRef, baseRef, headSha
let triggerText = ''
let hasLinkedPR = false
let isPR = false
if (context.eventName === 'workflow_dispatch') {
console.log('Workflow dispatch event')
console.log(context.payload)
triggerText = context.payload.inputs.trigger_text
// Automatically add @claude to the trigger text if it's not already there
if (!triggerText.includes('@claude')) {
triggerText = '@claude ' + triggerText
}
console.log(`Workflow dispatch #${issueNumber}: ${triggerText}`)
} else if (context.eventName === 'pull_request_target') {
// When a PR is created or updated
isPR = true
issueNumber = context.payload.pull_request.number
prNumber = context.payload.pull_request.number
headRef = context.payload.pull_request.head.ref
baseRef = context.payload.pull_request.base.ref
headSha = context.payload.pull_request.head.sha
triggerText = context.payload.pull_request.body
console.log(`PR #${prNumber}: ${baseRef} <- ${headRef} (${headSha})`)
} else if (context.eventName === 'issues') {
// When an Issue is created or assigned
isPR = false
issueNumber = context.payload.issue.number
triggerText = `${context.payload.issue.title} ${context.payload.issue.body}`
console.log(`Issue #${issueNumber} created`)
} else if (context.eventName === 'issue_comment') {
// Issue/PR comment
issueNumber = context.payload.issue.number
triggerText = context.payload.comment.body
if (context.payload.issue.pull_request) {
// Comment on a PR
isPR = true
try {
const pr = await github.rest.pulls.get({
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: issueNumber
})
prNumber = issueNumber
headRef = pr.data.head.ref
baseRef = pr.data.base.ref
headSha = pr.data.head.sha
console.log(`PR Comment #${prNumber}: ${baseRef} <- ${headRef}`)
} catch (error) {
console.error('Error fetching PR info:', error)
// In case of error, treat as a regular Issue
isPR = false
}
} else {
// Regular Issue comment - check for existing linked PRs
isPR = false
try {
// Get timeline events to find linked pull requests
const { data: timeline } = await github.rest.issues.listEventsForTimeline({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
per_page: 100,
headers: {
accept: 'application/vnd.github.mockingbird-preview+json'
}
})
console.log(`Timeline: ${JSON.stringify(timeline, null, 2)}`)
const linkedPRs = timeline
// filter out event.event is not cross-referenced
.filter(event => event.event === 'cross-referenced')
// filter out event.source?.issue?.pull_request is null
.filter(event => event.source?.issue?.pull_request?.url)
// return url and pr name, and the issue number and the body and the actor
.map(event => ({
issueNumber: event.source?.issue?.number,
actor: event.actor?.login,
url: event.source?.issue?.pull_request?.url,
title: event.source?.issue?.title,
body: event.source?.issue?.body,
}))
hasLinkedPR = linkedPRs.length > 0
console.log(`Linked PRs:`, linkedPRs)
console.log(`Issue Comment #${issueNumber}, already has linked PR: ${hasLinkedPR}`)
} catch (error) {
console.error('Error checking for linked PRs:', error)
}
}
} else if (context.eventName === 'pull_request_review_comment' || context.eventName === 'pull_request_review') {
// PR review related
isPR = true
issueNumber = context.payload.pull_request.number
prNumber = context.payload.pull_request.number
headRef = context.payload.pull_request.head.ref
baseRef = context.payload.pull_request.base.ref
headSha = context.payload.pull_request.head.sha
if (context.eventName === 'pull_request_review_comment') {
triggerText = context.payload.comment.body
} else {
triggerText = context.payload.review.body
}
console.log(`PR Review #${prNumber}: ${baseRef} <- ${headRef}`)
}
// Set outputs
core.setOutput('issue-number', issueNumber)
core.setOutput('pr-number', prNumber || '')
core.setOutput('head-ref', headRef || '')
core.setOutput('base-ref', baseRef || '')
core.setOutput('head-sha', headSha || '')
core.setOutput('is-pr', isPR)
core.setOutput('trigger-text', triggerText)
core.setOutput('has-linked-pr', hasLinkedPR)
console.log(`Final Context:`)
console.log(`Event: ${context.eventName}`)
console.log(`Issue #${issueNumber}`)
console.log(`isPR: ${isPR}`)
console.log(`Trigger Text: ${triggerText}`)
console.log(`Already has linked PR: ${hasLinkedPR}`)
- name: Validate Environment
run: |
echo "🔍 Runtime Environment Information"
echo "=================================="
echo "Event: ${{ github.event_name }}"
echo "Actor: ${{ github.actor }}"
echo "Repository: ${{ github.repository }}"
echo "Issue Number: ${{ steps.context-info.outputs.issue-number }}"
echo "Is PR: ${{ steps.context-info.outputs.is-pr }}"
echo "PR Number: ${{ steps.context-info.outputs.pr-number }}"
echo "Head Ref: ${{ steps.context-info.outputs.head-ref }}"
echo "Base Ref: ${{ steps.context-info.outputs.base-ref }}"
echo "Head SHA: ${{ steps.context-info.outputs.head-sha }}"
echo "Has Linked PR: ${{ steps.context-info.outputs.has-linked-pr }}"
echo "=================================="
# Check for secrets
if [ -z "${{ secrets.CLAUDE_CREDS_API_KEY }}" ]; then
echo "::error::CLAUDE_CREDS_API_KEY is not set"
exit 1
fi
if [ -z "${{ secrets.CLAUDE_CREDS_API }}" ]; then
echo "::error::CLAUDE_CREDS_API is not set"
exit 1
fi
echo "✅ Environment validation complete"
- name: Exit early if Issue already has linked PR
id: should-continue
run: |
IS_PR="${{ steps.context-info.outputs.is-pr }}"
HAS_LINKED_PR="${{ steps.context-info.outputs.has-linked-pr }}"
if [[ "$IS_PR" == "false" && "$HAS_LINKED_PR" == "true" ]]; then
echo "Issue already has linked PR. Will skip remaining steps."
echo "should-continue=false" >> $GITHUB_OUTPUT
else
echo "No linked PRs found or this is a PR. Continuing."
echo "should-continue=true" >> $GITHUB_OUTPUT
fi
- name: Debug issue number
if: github.event_name != 'workflow_dispatch'
run: echo "The issue number is ${{ steps.context-info.outputs.issue-number }}"
# Only add comment if it doesn't exist
- name: Find existing status comment
if: steps.should-continue.outputs.should-continue == 'true' && github.event_name != 'workflow_dispatch'
uses: peter-evans/find-comment@v3
id: find_comment # We'll check the output of this step
with:
issue-number: ${{ steps.context-info.outputs.issue-number }}
comment-author: 'github-actions[bot]'
body-includes: '<!-- claude-run-status -->'
- name: Create initial "in-progress" comment if it doesn't exist
# This step ONLY runs if the 'find-comment' step found nothing
if: steps.should-continue.outputs.should-continue == 'true' && steps.find_comment.outputs.comment-id == '' && github.event_name != 'workflow_dispatch'
uses: peter-evans/create-or-update-comment@v4
id: create_comment
with:
issue-number: ${{ steps.context-info.outputs.issue-number }}
body: |
Claude Code is running... ⏳
<!-- claude-run-status -->
#########################################################
# Claude Code
#########################################################
claude:
needs: setup
# Security-focused conditional execution (full support for Issues and PRs)
if: needs.setup.outputs.should-continue == 'true'
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
# 📁 Content management (highest permissions)
contents: write
pull-requests: write
issues: write
discussions: write
# 🔧 Development & CI/CD management
actions: write
checks: write
statuses: write
pages: write
deployments: write
# 📦 Package & security management
packages: write
security-events: write
# 🎯 Project management
repository-projects: write
# 🆔 Authentication & token management
id-token: write
steps:
- name: Checkout Repository
uses: actions/checkout@v4
with:
# Checkout the feature branch for PRs, or the default branch for Issues
ref: ${{ needs.setup.outputs.head-sha || github.ref }}
fetch-depth: ${{ needs.setup.outputs.is-pr == 'true' && 0 || 1 }}
token: ${{ secrets.GITHUB_TOKEN }}
- name: Validate Environment
run: |
echo "🔍 Runtime Environment Information"
echo "=================================="
echo "Event: ${{ github.event_name }}"
echo "Actor: ${{ github.actor }}"
echo "Repository: ${{ github.repository }}"
echo "Issue Number: ${{ needs.setup.outputs.issue-number }}"
echo "Is PR: ${{ needs.setup.outputs.is-pr }}"
echo "PR Number: ${{ needs.setup.outputs.pr-number }}"
echo "Head Ref: ${{ needs.setup.outputs.head-ref }}"
echo "Base Ref: ${{ needs.setup.outputs.base-ref }}"
echo "Head SHA: ${{ needs.setup.outputs.head-sha }}"
echo "Has Linked PR: ${{ needs.setup.outputs.has-linked-pr }}"
cat << EOF
Trigger Text: ${{ needs.setup.outputs.trigger-text }}
EOF
echo "=================================="
- name: Fetch Base Branch (PR only)
if: needs.setup.outputs.is-pr == 'true' && needs.setup.outputs.base-ref
run: |
echo "📥 Fetching base branch: ${{ needs.setup.outputs.base-ref }}"
git fetch origin ${{ needs.setup.outputs.base-ref }}:${{ needs.setup.outputs.base-ref }}
echo "📋 Changed files:"
git diff --name-only origin/${{ needs.setup.outputs.base-ref }}..HEAD || echo "Failed to get diff"
echo "📊 Change statistics:"
git diff --stat origin/${{ needs.setup.outputs.base-ref }}..HEAD || echo "Failed to get stats"
- name: Get Project Information
id: project-info
run: |
echo "📁 Collecting project information"
# Determine project type
project_type="unknown"
framework=""
if [ -f "package.json" ]; then
project_type="node"
echo "📦 Node.js project detected"
# Detect framework
if grep -q "next" package.json; then
framework="Next.js"
elif grep -q "react" package.json; then
framework="React"
elif grep -q "vue" package.json; then
framework="Vue.js"
elif grep -q "angular" package.json; then
framework="Angular"
elif grep -q "express" package.json; then
framework="Express"
fi
elif [ -f "requirements.txt" ] || [ -f "pyproject.toml" ]; then
project_type="python"
framework="Python"
echo "🐍 Python project detected"
elif [ -f "Cargo.toml" ]; then
project_type="rust"
framework="Rust"
echo "🦀 Rust project detected"
elif [ -f "go.mod" ]; then
project_type="go"
framework="Go"
echo "🐹 Go project detected"
elif [ -f "pom.xml" ] || [ -f "build.gradle" ]; then
project_type="java"
framework="Java"
echo "☕ Java project detected"
fi
echo "project-type=$project_type" >> $GITHUB_OUTPUT
echo "framework=$framework" >> $GITHUB_OUTPUT
# Estimate number of files
total_files=$(find . -type f \( -name "*.js" -o -name "*.ts" -o -name "*.jsx" -o -name "*.tsx" -o -name "*.py" -o -name "*.rs" -o -name "*.go" -o -name "*.java" \) | wc -l)
echo "total-files=$total_files" >> $GITHUB_OUTPUT
echo "📊 Project summary: $framework ($total_files files)"
- name: Setup Env
id: setup-env
uses: DavidWells/actions/get-claude-tokens@master
with:
api-key: ${{ secrets.CLAUDE_CREDS_API_KEY }}
api-endpoint: ${{ secrets.CLAUDE_CREDS_API }}
# - name: Run Claude PR Action
# uses: davidwells/claude-code-action@main
# with:
# use_oauth: true
# claude_access_token: ${{ steps.setup-env.outputs.access-token }}
# claude_refresh_token: ${{ steps.setup-env.outputs.refresh-token }}
# claude_expires_at: ${{ steps.setup-env.outputs.expires-at }}
# model: ${{ steps.setup-env.outputs.model || 'claude-sonnet-4-20250514' }}
# allowed_tools: ${{ steps.setup-env.outputs.allowed_tools || 'Bash,Edit,Read,Write,Glob,Grep,LS,MultiEdit,NotebookRead,NotebookEdit' }}
# timeout_minutes: "60"
- name: Run Claude Code
id: claude
uses: anthropics/claude-code-action@main
timeout-minutes: 20
continue-on-error: true
with:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
github_token: ${{ secrets.GITHUB_TOKEN }}
# GITHUB ACTIONS (Maximum Freedom):
settings: |
{
"permissions": {
"allowedTools": [
"Edit", "View", "Replace", "Write", "Create",
"BatchTool", "GlobTool", "GrepTool", "NotebookEditCell",
"Bash(git:*)", "Bash(npm:*)", "Bash(npx:*)", "Bash(yarn:*)",
"Bash(python:*)", "Bash(bun:*)", "Bash(pnpm:*)",
"Bash(docker:*)", "Bash(make:*)", "Bash(cargo:*)", "Bash(go:*)",
"Bash(ls:*)", "Bash(cat:*)", "Bash(echo:*)", "Bash(curl:*)",
"mcp__*"
],
"deny": [
"Bash(sudo:*)",
"Bash(rm -rf /)"
]
}
}
claude_args: |
--model sonnet --dangerously-skip-permissions
# If the workflow is triggered by a workflow_dispatch event, use the agent mode, otherwise use the tag mode
mode: ${{ github.event_name == 'workflow_dispatch' && 'agent' || 'tag' }}
# direct prompt from workflow_dispatch event
prompt: ${{ github.event_name == 'workflow_dispatch' && needs.setup.outputs.trigger-text || '' }}
# This is an optional setting that allows Claude to read CI results on PRs
additional_permissions: |
actions: read
env:
# Pass context information to Claude Code
GITHUB_CONTEXT_TYPE: ${{ needs.setup.outputs.is-pr == 'true' && 'PR' || 'ISSUE' }}
ISSUE_NUMBER: ${{ needs.setup.outputs.issue-number }}
PR_NUMBER: ${{ needs.setup.outputs.pr-number }}
BASE_BRANCH: ${{ needs.setup.outputs.base-ref }}
HEAD_BRANCH: ${{ needs.setup.outputs.head-ref }}
HEAD_SHA: ${{ needs.setup.outputs.head-sha }}
GITHUB_EVENT_NAME: ${{ github.event_name }}
TRIGGER_TEXT: ${{ needs.setup.outputs.trigger-text }}
PROJECT_TYPE: ${{ steps.project-info.outputs.project-type }}
PROJECT_FRAMEWORK: ${{ steps.project-info.outputs.framework }}
TOTAL_FILES: ${{ steps.project-info.outputs.total-files }}
GITHUB_ACTOR: ${{ github.actor }}
REPOSITORY_NAME: ${{ github.repository }}
# 🔑 Enhanced permission information
CLAUDE_PERMISSIONS_LEVEL: "ENHANCED"
REPO_ADMIN_MODE: "true"
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# 📊 Repository information
REPOSITORY_OWNER: ${{ github.repository_owner }}
REPOSITORY_DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
REPOSITORY_PRIVATE: ${{ github.event.repository.private }}
REPOSITORY_FORK: ${{ github.event.repository.fork }}
# 🎯 Execution context
WORKFLOW_RUN_ID: ${{ github.run_id }}
WORKFLOW_RUN_NUMBER: ${{ github.run_number }}
COMMIT_SHA: ${{ github.sha }}
REF_NAME: ${{ github.ref_name }}
# 🔧 Available feature flags
CAN_CREATE_RELEASES: "true"
CAN_MANAGE_LABELS: "true"
CAN_MANAGE_MILESTONES: "true"
CAN_MANAGE_PROJECTS: "true"
CAN_MANAGE_WIKI: "true"
CAN_MANAGE_PAGES: "true"
CAN_MANAGE_DEPLOYMENTS: "true"
CAN_MANAGE_SECURITY: "true"
CAN_MANAGE_PACKAGES: "true"
CAN_MANAGE_ACTIONS: "true"
- name: Run Advanced Repository Management
id: advanced-management
if: steps.claude.outcome == 'success' && needs.setup.outputs.issue-number
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const issueNumber = ${{ needs.setup.outputs.issue-number }};
const isPR = '${{ needs.setup.outputs.is-pr }}' === 'true';
const triggerText = (${{ toJSON(needs.setup.outputs.trigger-text) }} || '').toLowerCase();
const framework = '${{ steps.project-info.outputs.framework }}';
const hashSymbol = String.fromCharCode(35);
console.log('🚀 Starting advanced repository management...');
const managementResults = {
labels: [],
milestones: [],
projects: [],
releases: [],
security: [],
wiki: [],
pages: [],
actions: []
};
try {
// 1. 🏷️ Intelligent Label Management
console.log('📋 Running automatic label management...');
// Automatically create necessary labels
const requiredLabels = [
{ name: 'claude-code', color: '7B68EE', description: 'Items created or modified by Claude Code' },
{ name: 'auto-generated', color: '00D084', description: 'Automatically generated content' },
{ name: 'security-fix', color: 'FF4444', description: 'Security-related fixes' },
{ name: 'performance', color: 'FFA500', description: 'Performance improvements' },
{ name: 'technical-debt', color: '8B4513', description: 'Resolving technical debt' },
{ name: 'documentation', color: '0366D6', description: 'Documentation related' },
{ name: 'ci-cd', color: '28A745', description: 'CI/CD improvements' }
];
for (const label of requiredLabels) {
try {
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description
});
managementResults.labels.push(`✅ Created: ${label.name}`);
} catch (error) {
if (error.status === 422) {
managementResults.labels.push(`📋 Exists: ${label.name}`);
} else {
managementResults.labels.push(`❌ Error: ${label.name} - ${error.message}`);
}
}
}
// Automatically apply relevant labels
const autoLabels = ['claude-code', 'auto-generated'];
if (triggerText.includes('security')) {
autoLabels.push('security-fix');
}
if (triggerText.includes('performance')) {
autoLabels.push('performance');
}
if (triggerText.includes('technical debt')) {
autoLabels.push('technical-debt');
}
if (triggerText.includes('document')) {
autoLabels.push('documentation');
}
if (triggerText.includes('ci') || triggerText.includes('cd') || triggerText.includes('deploy')) {
autoLabels.push('ci-cd');
}
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: autoLabels
});
managementResults.labels.push(`🏷️ Applied: ${autoLabels.join(', ')}`);
// 2. 🎯 Automatic Milestone Management
console.log('🎯 Running milestone management...');
try {
// Create a milestone for the current year and month
const now = new Date();
const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const currentMilestone = `${now.getFullYear()}-${monthNames[now.getMonth()]}`;
try {
const milestone = await github.rest.issues.createMilestone({
owner: context.repo.owner,
repo: context.repo.repo,
title: currentMilestone,
description: `Tasks and improvements for ${currentMilestone}`,
due_on: new Date(now.getFullYear(), now.getMonth() + 1, 0).toISOString()
});
managementResults.milestones.push(`✅ Created: ${currentMilestone}`);
} catch (error) {
if (error.status === 422) {
managementResults.milestones.push(`📅 Exists: ${currentMilestone}`);
} else {
managementResults.milestones.push(`❌ Error: ${error.message}`);
}
}
} catch (error) {
managementResults.milestones.push(`❌ Milestone management error: ${error.message}`);
}
// 3. 📊 Project Board Management
console.log('📊 Running project management...');
try {
// Get projects for the repository
const projects = await github.rest.projects.listForRepo({
owner: context.repo.owner,
repo: context.repo.repo
});
if (projects.data.length > 0) {
const project = projects.data[0];
managementResults.projects.push(`📊 Project detected: ${project.name}`);
// Add a card to the To Do column
const columns = await github.rest.projects.listColumns({
project_id: project.id
});
const todoColumn = columns.data.find(col =>
col.name.toLowerCase().includes('todo') ||
col.name.toLowerCase().includes('backlog')
);
if (todoColumn) {
await github.rest.projects.createCard({
column_id: todoColumn.id,
content_id: context.payload.issue.id, // Use issue ID for content_id
content_type: 'Issue'
});
managementResults.projects.push(`📋 Card added: ${project.name}`);
}
} else {
managementResults.projects.push(`ℹ️ Project board not found`);
}
} catch (error) {
managementResults.projects.push(`❌ Project management error: ${error.message}`);
}
// 4. 🔒 Security Alert Handling
console.log('🔒 Running security check...');
try {
if (triggerText.includes('security') || triggerText.includes('vulnerability')) {
// Check for security alerts
try {
const vulnerabilities = await github.rest.secretScanning.listAlertsForRepo({
owner: context.repo.owner,
repo: context.repo.repo,
state: 'open'
});
managementResults.security.push(`🔍 Open security alerts: ${vulnerabilities.data.length}`);
if (vulnerabilities.data.length > 0) {
managementResults.security.push(`⚠️ Security alert confirmation required`);
}
} catch (error) {
managementResults.security.push(`ℹ️ Security alert check: Access restricted or feature disabled`);
}
} else {
managementResults.security.push(`ℹ️ Security check: Skipped`);
}
} catch (error) {
managementResults.security.push(`❌ Security check error: ${error.message}`);
}
// 5. 📚 Automatic Wiki Update
console.log('📚 Running Wiki management...');
try {
if (triggerText.includes('wiki') || triggerText.includes('document')) {
// Check if Wiki page exists
try {
const repoInfo = await github.rest.repos.get({
owner: context.repo.owner,
repo: context.repo.repo
});
if (repoInfo.data.has_wiki) {
managementResults.wiki.push(`📚 Wiki enabled: Updatable`);
// Actual Wiki update is performed by Claude Code
} else {
managementResults.wiki.push(`📚 Wiki disabled: Needs to be enabled in settings`);
}
} catch (error) {
managementResults.wiki.push(`❌ Wiki check error: ${error.message}`);
}
} else {
managementResults.wiki.push(`ℹ️ Wiki update: Skipped`);
}
} catch (error) {
managementResults.wiki.push(`❌ Wiki management error: ${error.message}`);
}
// 6. 🌐 GitHub Pages Management
console.log('🌐 Running GitHub Pages management...');
try {
if (triggerText.includes('pages') || triggerText.includes('deploy') || triggerText.includes('site')) {
try {
const pages = await github.rest.repos.getPages({
owner: context.repo.owner,
repo: context.repo.repo
});
managementResults.pages.push(`🌐 Pages enabled: ${pages.data.html_url}`);
// Trigger a Pages build
await github.rest.repos.requestPagesBuild({
owner: context.repo.owner,
repo: context.repo.repo
});
managementResults.pages.push(`🔄 Triggered Pages rebuild`);
} catch (error) {
if (error.status === 404) {
managementResults.pages.push(`🌐 Pages disabled: Needs to be enabled in settings`);
} else {
managementResults.pages.push(`❌ Pages management error: ${error.message}`);
}
}
} else {
managementResults.pages.push(`ℹ️ Pages management: Skipped`);
}
} catch (error) {
managementResults.pages.push(`❌ Pages management error: ${error.message}`);
}
// 7. ⚙️ Actions Workflow Management
console.log('⚙️ Running Actions management...');
try {
if (triggerText.includes('workflow') || triggerText.includes('action') || triggerText.includes('ci') || triggerText.includes('cd')) {
const workflows = await github.rest.actions.listRepoWorkflows({
owner: context.repo.owner,
repo: context.repo.repo
});
managementResults.actions.push(`⚙️ Number of workflows: ${workflows.data.total_count}`);
// Check for disabled workflows
const disabledWorkflows = workflows.data.workflows.filter(w => w.state === 'disabled_manually');
if (disabledWorkflows.length > 0) {
managementResults.actions.push(`⚠️ Disabled workflows: ${disabledWorkflows.length}`);
}
} else {
managementResults.actions.push(`ℹ️ Actions management: Skipped`);
}
} catch (error) {
managementResults.actions.push(`❌ Actions management error: ${error.message}`);
}
console.log('✅ Advanced repository management complete');
// Save results to output
core.setOutput('management-results', JSON.stringify(managementResults));
core.setOutput('management-success', 'true');
} catch (error) {
console.error('❌ Advanced repository management error:', error);
core.setOutput('management-error', error.message);
core.setOutput('management-success', 'false');
}
- name: Check for Changes and Prepare for PR
id: check-changes
if: steps.claude.outcome == 'success' && needs.setup.outputs.is-pr == 'false' && steps.claude.outputs.branch_name
run: |
set -e # Exit immediately if a command exits with a non-zero status.
BRANCH_NAME="${{ steps.claude.outputs.branch_name }}"
DEFAULT_BRANCH="origin/${{ github.event.repository.default_branch }}"
echo "--- 1. Checking if remote branch '${BRANCH_NAME}' exists ---"
# Use `git ls-remote` to check for the branch's existence. It exits with 0 if it exists, 2 if not.
if ! git ls-remote --exit-code --heads origin "${BRANCH_NAME}" >/dev/null 2>&1; then
echo "✅ Remote branch '${BRANCH_NAME}' not found. This indicates no code changes were committed."
echo "has-changes=false" >> $GITHUB_OUTPUT
echo "branch-exists=false" >> $GITHUB_OUTPUT
# Exit successfully as this is an expected outcome.
exit 0
fi
echo "✅ Remote branch found. Proceeding with original fetch and reset logic."
echo "branch-exists=true" >> $GITHUB_OUTPUT
echo "--- 2. DEBUG: Initial Git State ---"
echo "Current branch: $(git rev-parse --abbrev-ref HEAD)"
echo "Current commit: $(git log -1 --pretty=%h)"
echo "Workspace status:"
git status -s
echo "-----------------------------------"
echo "🚀 3. Fetching the specific branch pushed by Claude: '${BRANCH_NAME}'..."
git fetch origin "+refs/heads/${BRANCH_NAME}:refs/remotes/origin/${BRANCH_NAME}"
echo "--- 4. DEBUG: After Fetch ---"
echo "Remote commit for '${BRANCH_NAME}' is: $(git log origin/${BRANCH_NAME} -1 --pretty=%h)"
echo "-----------------------------"
echo "🔄 5. Forcibly resetting local branch to match the fetched remote state..."
git checkout "${BRANCH_NAME}"
git reset --hard "origin/${BRANCH_NAME}"
echo "--- 6. DEBUG: After Resetting Local Branch ---"
echo "Current branch is now: $(git rev-parse --abbrev-ref HEAD)"
echo "Current commit is now: $(git log -1 --pretty=%h)"
echo "Workspace status is now:"
git status -s
echo "---------------------------------------------"
BRANCH_RANGE="${DEFAULT_BRANCH}...${BRANCH_NAME}"
echo "🔍 7. Checking for changes in range: ${BRANCH_RANGE}..."
# Use the exit code of 'git diff --quiet' to check for changes.
if git diff --quiet $BRANCH_RANGE; then
echo "✅ No changes detected between branches. Setting has-changes=false."
echo "has-changes=false" >> $GITHUB_OUTPUT
else
echo "📝 Changes detected. Setting has-changes=true."
echo "has-changes=true" >> $GITHUB_OUTPUT
echo "---"
echo "📄 Changed files (compared to default branch):"
git diff --name-only $BRANCH_RANGE
echo "---"
echo "📊 Change statistics:"
git diff --stat $BRANCH_RANGE
fi
#########################################################
# IF we have changes, create or update a pull request