-
Notifications
You must be signed in to change notification settings - Fork 7
696 lines (612 loc) · 28.2 KB
/
Copy pathgemini-coder.yml
File metadata and controls
696 lines (612 loc) · 28.2 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
# .github/workflows/gemini-coder.yml
#
# AI-Powered Automated Code Generation and Patching
#
# Purpose:
# Uses the Gemini API to automatically generate code changes based on task descriptions.
# Creates pull requests with AI-generated patches, validates them, and provides detailed
# error reports for debugging patch application failures.
#
# Triggers:
# 1. Issue Label: When an issue is labeled with 'auto-code'
# 2. Manual: Via workflow_dispatch with custom task description
#
# Key Features:
# - Intelligent patch extraction from LLM markdown code blocks
# - Thorough patch validation with 3-way merge fallback
# - Secret scrubbing to prevent credential leakage in artifacts
# - Comprehensive error diagnostics with artifact uploads
# - Commitlint-compliant commit message generation
# - File state context (line counts, hashes) in prompts for accuracy
#
# Workflow Steps:
# 1. Parse task description from issue or manual input
# 2. Gather current file state and context for the AI
# 3. Call Gemini API to generate code changes as a unified diff
# 4. Extract diff from markdown code blocks if present
# 5. Validate patch format and test application with --check
# 6. Apply patch with 3-way merge if strict check fails
# 7. Run quality checks (linting, building)
# 8. Generate commitlint-compliant commit message
# 9. Create pull request with patch and metadata
# 10. Upload debug artifacts on failure for diagnostics
#
# Configuration:
# GEMINI_API_KEY - Required: Set in repository secrets
# ARI_PAT - Required: Personal access token for PR creation
# NEXTAUTH_URL, NEXTAUTH_SECRET - For build verification
#
# Error Handling:
# - Patches that don't apply cleanly are logged with diagnostics
# - Rejected hunks are uploaded as artifacts for manual review
# - LLM "conversational text" is filtered to extract valid diffs
# - All failures are non-blocking; workflow continues for reporting
name: Gemini Coder
on:
issues:
types: [labeled]
workflow_dispatch:
inputs:
task_description:
description: 'The detailed description of the coding task.'
required: true
target_files:
description: 'Comma-separated list of files for the AI to consider.'
required: false
agent_provider:
description: 'The AI agent to use (jules or gemini).'
required: true
default: 'gemini'
type: choice
options:
- jules
- gemini
branch_name:
description: 'Optional custom branch name.'
required: false
workflow_call:
inputs:
task_description:
description: 'The detailed description of the coding task.'
required: true
type: string
target_files:
description: 'Comma-separated list of files for the AI to consider.'
required: false
type: string
branch_name:
description: 'Optional custom branch name.'
required: false
type: string
permissions:
contents: write
pull-requests: write
issues: read
jobs:
ai-developer:
if: |
(github.event_name == 'workflow_dispatch' || github.event_name == 'workflow_call') ||
(vars.GEMINI_ENABLE_CODER != 'false' && github.event.label.name == 'auto-code')
runs-on: self-hosted
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
ref: ${{ (github.event.issue.pull_request || github.event.pull_request) && format('refs/pull/{0}/head', github.event.issue.number || github.event.pull_request.number) || github.sha }}
- name: Setup Python
uses: actions/setup-python@v7
with:
python-version: '3.10'
- name: 'Context Setup: Set Agent Provider'
id: set_provider
env:
EVENT_NAME: ${{ github.event_name }}
INPUT_PROVIDER: ${{ github.event.inputs.agent_provider }}
LABEL_NAME: ${{ github.event.label.name }}
run: |
if [ "$EVENT_NAME" == "workflow_dispatch" ]; then
echo "AGENT_PROVIDER=$INPUT_PROVIDER" >> $GITHUB_ENV
elif [[ "$LABEL_NAME" == "auto-code" ]]; then
echo "AGENT_PROVIDER=gemini" >> $GITHUB_ENV
fi
- name: 'Context Setup: Parse Issue Body'
if: github.event_name == 'issues'
id: parse_issue
env:
ISSUE_BODY: ${{ github.event.issue.body }}
run: |
printf "%s" "$ISSUE_BODY" > issue_body.txt
python3 .github/scripts/parse_issue.py issue_body.txt >> $GITHUB_OUTPUT
- name: 'Context Setup: Consolidate Inputs'
id: consolidate_inputs
env:
EVENT_NAME: ${{ github.event_name }}
TASK_DESC_PARSED: ${{ steps.parse_issue.outputs.task_description }}
TARGET_FILES_PARSED: ${{ steps.parse_issue.outputs.target_files }}
BRANCH_NAME_PARSED: ${{ steps.parse_issue.outputs.branch_name }}
TASK_DESC_INPUT: ${{ inputs.task_description || github.event.inputs.task_description }}
TARGET_FILES_INPUT: ${{ inputs.target_files || github.event.inputs.target_files }}
BRANCH_NAME_INPUT: ${{ inputs.branch_name || github.event.inputs.branch_name }}
ISSUE_TITLE: ${{ github.event.issue.title }}
ISSUE_NUMBER: ${{ github.event.issue.number }}
RUN_ID: ${{ github.run_id }}
run: |
EOF=$(dd if=/dev/urandom bs=15 count=1 status=none | base64)
# Store inputs in temp files to avoid env var exposure/injection
if [ "$EVENT_NAME" == "issues" ]; then
printf "%s" "$TASK_DESC_PARSED" > task_desc.txt
echo "FILES=$TARGET_FILES_PARSED" >> $GITHUB_ENV
echo "TITLE=$ISSUE_TITLE" >> $GITHUB_ENV
if [ -n "$BRANCH_NAME_PARSED" ]; then
echo "BRANCH=$BRANCH_NAME_PARSED" >> $GITHUB_ENV
else
BRANCH_SLUG=$(echo "$ISSUE_TITLE" | tr -cs 'a-zA-Z0-9' '-' | sed -e 's/--/-/g' -e 's/^-//' -e 's/-$//' | tr '[:upper:]' '[:lower:]')
echo "BRANCH=ai/${BRANCH_SLUG}-${ISSUE_NUMBER}" >> $GITHUB_ENV
fi
else
printf "%s" "$TASK_DESC_INPUT" > task_desc.txt
echo "FILES=$TARGET_FILES_INPUT" >> $GITHUB_ENV
TITLE_TEXT=$(echo "$TASK_DESC_INPUT" | head -c 50)
echo "TITLE=AI Task: $TITLE_TEXT" >> $GITHUB_ENV
if [ -n "$BRANCH_NAME_INPUT" ]; then
echo "BRANCH=$BRANCH_NAME_INPUT" >> $GITHUB_ENV
else
BRANCH_SLUG=$(echo "$TASK_DESC_INPUT" | tr -cs 'a-zA-Z0-9' '-' | sed -e 's/--/-/g' -e 's/^-//' -e 's/-$//' -e 's/^\(.\{30\}\).*$/\1/' | tr '[:upper:]' '[:lower:]')
echo "BRANCH=ai/${BRANCH_SLUG}-${RUN_ID}" >> $GITHUB_ENV
fi
fi
# Pass content via GITHUB_ENV for steps that need it, securely
# Use unique delimiter to prevent collision with file content
PROMPT_DELIMITER="GEMINI_PROMPT_$(date +%s%N | sha256sum | head -c 32)"
{
echo "PROMPT<<$PROMPT_DELIMITER"
cat task_desc.txt
echo "" # Ensure newline before delimiter
echo "$PROMPT_DELIMITER"
} >> $GITHUB_ENV
- name: 'Jules: Prepare Prompt'
if: env.AGENT_PROVIDER == 'jules'
run: |
echo "Invoking Jules Agent..."
# Create prompt file instead of relying solely on env var echoing
printf "Task: %s\n\nTarget Files:\n%s" "$PROMPT" "$FILES" > jules_prompt.txt
- name: 'Jules: Install Dependencies'
if: env.AGENT_PROVIDER == 'jules'
run: pip install requests
- name: 'Jules: Execute API Call'
if: env.AGENT_PROVIDER == 'jules'
env:
JULES_API_KEY: ${{ secrets.JULES_API_KEY }}
BRANCH: ${{ env.BRANCH }}
TITLE: ${{ env.TITLE }}
REPO_OWNER: ${{ github.repository_owner }}
REPO_NAME: ${{ github.event.repository.name }}
id: jules_session
run: |
# Read prompt from file to avoid CLI argument length limits or exposure
FULL_PROMPT=$(cat jules_prompt.txt)
python3 .github/scripts/jules_ops.py \
--prompt "$FULL_PROMPT" \
--branch "$BRANCH" \
--title "$TITLE" \
--owner "$REPO_OWNER" \
--repo-name "$REPO_NAME" >> $GITHUB_OUTPUT
- name: 'Jules: Create Tracking PR'
if: env.AGENT_PROVIDER == 'jules'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
BRANCH: ${{ env.BRANCH }}
TITLE: ${{ env.TITLE }}
PROMPT: ${{ env.PROMPT }}
SESSION_URL: ${{ steps.jules_session.outputs.session_url }}
run: |
set -euo pipefail
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
EXISTING_PR_URL=$(gh pr list --head "$BRANCH" --json url --limit 1 -q '.[0].url' || echo "")
(
cat <<EOF
A Jules session has been initiated to address this task.
**Task Details:**
EOF
echo "$PROMPT"
cat <<EOF
**Jules Session URL:**
[Follow the progress here]($SESSION_URL)
EOF
) > pr_body.md
if [ -n "$EXISTING_PR_URL" ]; then
echo "::notice::PR for branch '$BRANCH' already exists. Updating body: $EXISTING_PR_URL"
gh pr edit "$EXISTING_PR_URL" --body-file pr_body.md
else
echo "::notice::No PR found for branch '$BRANCH'. Creating a new one."
gh auth setup-git
DEFAULT_BRANCH=$(git remote show origin | grep 'HEAD branch' | cut -d' ' -f5)
git checkout $DEFAULT_BRANCH
git pull
git branch -D "$BRANCH" 2>/dev/null || true
git checkout -b "$BRANCH"
# Create an empty commit to establish the branch and enable PR creation.
git commit --allow-empty -m "chore: initiate jules session"
# Use --force to ensure the remote branch accurately reflects the latest automated state,
# effectively overwriting any previous partial or failed pushes.
git push --force -u origin "$BRANCH"
gh pr create \
--base $DEFAULT_BRANCH \
--head "$BRANCH" \
--title "$TITLE" \
--body-file pr_body.md
fi
# Clean up the temporary file
rm pr_body.md
- name: 'Gemini: Verify Client Exists'
if: env.AGENT_PROVIDER == 'gemini'
run: |
if [ ! -f scripts/gemini-client.ts ]; then
echo "Error: scripts/gemini-client.ts not found!"
exit 1
fi
echo "Gemini client script verified."
- name: 'Gemini: Prepare Prompt'
if: env.AGENT_PROVIDER == 'gemini'
env:
TASK_CONTENT: ${{ env.PROMPT }}
FILES_CONTENT: ${{ env.FILES }}
run: |
echo "Invoking Gemini Agent..."
# Include current file hashes to help with context
echo "File state information:" > file_state.txt
for file in $(echo "$FILES_CONTENT" | tr ',' '\n'); do
if [ -f "$file" ]; then
HASH=$(sha256sum "$file" 2>/dev/null | awk '{print $1}' | cut -c1-8)
LINES=$(wc -l < "$file" 2>/dev/null)
echo " $file: $LINES lines (hash: $HASH)" >> file_state.txt
fi
done
cat > prompt.txt << 'PROMPTEOF'
You are a code generation assistant. Your task is to generate code changes in unified diff format.
IMPORTANT: Output ONLY a valid unified diff that can be applied with `git apply`. Do not include any explanation, markdown, or extra text.
The diff must:
1. Start with "--- a/path/to/file" and "+++ b/path/to/file" headers
2. Include @@ hunk headers showing line numbers
3. Have proper context lines (unchanged lines prefixed with space)
4. Have additions prefixed with +
5. Have deletions prefixed with -
Task Description:
PROMPTEOF
echo "$TASK_CONTENT" >> prompt.txt
cat >> prompt.txt << 'PROMPTEOF'
Target Files (may be empty, infer from task):
PROMPTEOF
echo "$FILES_CONTENT" >> prompt.txt
# Include current file state for context
if [ -f file_state.txt ]; then
cat >> prompt.txt << 'PROMPTEOF'
Current File State (for context):
PROMPTEOF
cat file_state.txt >> prompt.txt
fi
cat >> prompt.txt << 'PROMPTEOF'
Generate the unified diff for the changes described above.
PROMPTEOF
- name: 'Gemini: Setup pnpm'
if: env.AGENT_PROVIDER == 'gemini'
uses: pnpm/action-setup@v4
- name: 'Gemini: Setup Node.js'
if: env.AGENT_PROVIDER == 'gemini'
uses: actions/setup-node@v6
with:
node-version: '20'
cache: 'pnpm'
- name: 'Gemini: Install Dependencies'
if: env.AGENT_PROVIDER == 'gemini'
run: pnpm install --frozen-lockfile
- name: 'Gemini: Run AI Code Generation'
if: env.AGENT_PROVIDER == 'gemini'
env:
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
CONTEXT_FILES: ${{ env.FILES }}
run: |
npx tsx scripts/gemini-client.ts \
--task-file "prompt.txt" \
--context "$CONTEXT_FILES" \
--output "patch.diff"
- name: 'Gemini: Apply Patch'
if: env.AGENT_PROVIDER == 'gemini'
env:
BRANCH: ${{ env.BRANCH }}
run: |
echo "::notice::Checking patch.diff..."
if [ ! -f patch.diff ]; then
echo "::error::patch.diff file not found. The gemini-client failed to generate a patch."
exit 1
fi
PATCH_SIZE=$(wc -c < patch.diff)
echo "::notice::Patch file size: $PATCH_SIZE bytes"
if [ $PATCH_SIZE -eq 0 ]; then
echo "::error::patch.diff is empty. The gemini-client did not generate any code changes."
echo "::notice::Possible causes:"
echo "::notice:: - The gemini-client failed to understand the task"
echo "::notice:: - The API response was incomplete or malformed"
exit 1
fi
# Step 1: Extract from markdown code block if present (do this FIRST)
FIRST_LINE=$(head -1 patch.diff)
if [[ "$FIRST_LINE" == *'```'* ]]; then
echo "::notice::Detected markdown code block, extracting diff..."
# Handles variations: ```diff, ``` diff, ```
sed -n '/^```/,/^```$/p' patch.diff | sed '1d;$d' > patch.diff.tmp
if [ -s patch.diff.tmp ]; then
mv patch.diff.tmp patch.diff
echo "::notice::✅ Extracted diff from markdown code block"
else
rm patch.diff.tmp 2>/dev/null
echo "::warning::Markdown extraction resulted in empty file, using original"
fi
fi
# Step 2: Enhanced conversational text filtering
# Remove common LLM preamble/postamble text while preserving the diff
# Set DISABLE_TEXT_FILTERING=true to skip this step
if [ "${DISABLE_TEXT_FILTERING:-false}" != "true" ]; then
echo "::notice::Filtering conversational text from patch..."
# Find the first diff header in the original content
DIFF_START=$(grep -n "^--- a/" patch.diff | head -1 | cut -d: -f1)
if [ -z "$DIFF_START" ]; then
echo "::notice::No diff header found. Patch may have conversational text before the diff."
else
echo "::notice::Found diff starting at line $DIFF_START, extracting..."
# Extract from first diff header to end, this removes all preamble safely
tail -n +$DIFF_START patch.diff > patch.diff.cleaned
if [ -s patch.diff.cleaned ]; then
mv patch.diff.cleaned patch.diff
echo "::notice::✅ Removed conversational text from patch"
else
echo "::warning::Cleaned patch is empty, using original"
rm patch.diff.cleaned 2>/dev/null
fi
fi
else
echo "::notice::Conversational text filtering disabled (DISABLE_TEXT_FILTERING=true)"
fi
# Validate patch format starts with --- a/
if ! head -1 patch.diff | grep -q "^--- a/"; then
echo "::error::Patch does not start with '--- a/' header"
echo "::notice::The patch is not in unified diff format. This usually means:"
echo "::notice:: - The gemini-client included explanation text before the diff"
echo "::notice:: - The output was not properly formatted as a diff"
echo "::notice::First 30 lines of patch.diff:"
head -30 patch.diff | sed 's/^/::notice:: /'
exit 1
fi
echo "::notice::✅ Patch validation passed. Validating patch can be applied..."
# Check if patch can be applied cleanly without actually applying it
if ! git apply --ignore-whitespace --check patch.diff 2>&1; then
APPLY_ERROR=$(git apply --ignore-whitespace --check patch.diff 2>&1)
echo "::error::Patch cannot be applied cleanly."
echo "::notice::Git apply validation failed:"
echo "$APPLY_ERROR" | sed 's/^/::notice:: /'
# Try 3-way merge attempt (might work even if strict check fails)
echo ""
echo "::notice::Attempting 3-way merge..."
if git apply --ignore-whitespace --3way patch.diff 2>&1; then
echo "::notice::✅ 3-way merge succeeded!"
else
echo "::notice::3-way merge also failed. Attempting detailed diagnostics..."
# Attempt to apply with --reject to show which hunks failed
echo "::notice::Applying with --reject to identify failing hunks..."
git apply --ignore-whitespace --reject patch.diff 2>&1 || true
# Collect rejected hunks for artifact upload
if find . -name "*.rej" -type f | grep -q .; then
echo "::notice::Found rejected hunks:"
find . -name "*.rej" -type f -exec echo " - {}" \;
fi
echo ""
echo "::notice::Debugging information:"
echo "::notice::Files in patch:"
grep "^--- a/" patch.diff | sed 's/^--- a\///;s/^/::notice:: /' || echo "::notice:: (unable to extract file list)"
echo ""
echo "::notice::Common causes and solutions:"
echo "::notice:: 1. File content has changed - Run gemini-coder again with fresh context"
echo "::notice:: 2. Line numbers are off - Check if files were recently modified"
echo "::notice:: 3. Whitespace issues - The patch may have different line endings"
echo ""
echo "::notice::To debug locally, try:"
echo "::notice:: git apply --reject patch.diff # Shows which hunks fail"
echo "::notice:: git diff # Compare current state with patch"
# Upload patch for manual review
echo ""
echo "::notice::Uploading patch for manual review..."
exit 1
fi
fi
echo "::notice::✅ Patch validation passed. Applying patch..."
git config user.name "AI Agent"
git config user.email "ai@agent.local"
# Apply patch to current branch (will be committed by create-pull-request action)
if ! git apply patch.diff; then
echo "::error::Failed to apply patch. This should not happen after validation passed."
exit 1
fi
echo "::notice::✅ Patch applied successfully"
- name: Upload Failed Hunks as Artifact
if: failure() && env.AGENT_PROVIDER == 'gemini'
uses: actions/upload-artifact@v7
with:
name: patch-artifacts-run-${{ github.run_id }}
path: |
patch.diff
prompt.txt
task_desc.txt
*.rej
if-no-files-found: warn
retention-days: 2
compression-level: 6
- name: Generate Patch Debug Report
if: failure() && env.AGENT_PROVIDER == 'gemini'
run: |
# Comprehensive secret scrubbing function
scrub_secrets() {
local content="$1"
# Scrub all known secret patterns and environment variables
echo "$content" | \
sed 's/ghp_[A-Za-z0-9_]\{36\}/***GITHUB_TOKEN***/g' | \
sed 's/github_pat_[A-Za-z0-9_]\{62\}/***GITHUB_PAT***/g' | \
sed 's/ghu_[A-Za-z0-9_]\{36\}/***GITHUB_USER_TOKEN***/g' | \
sed 's/ghs_[A-Za-z0-9_]\{36\}/***GITHUB_APP_TOKEN***/g' | \
sed 's/gho_[A-Za-z0-9_]\{36\}/***GITHUB_OAUTH_TOKEN***/g' | \
sed 's/[A-Za-z0-9_-]*API[_-]*KEY[=:][^ ]*/***REDACTED***/gi' | \
sed 's/[A-Za-z0-9_-]*SECRET[=:][^ ]*/***REDACTED***/gi' | \
sed 's/[A-Za-z0-9_-]*TOKEN[=:][^ ]*/***REDACTED***/gi' | \
sed 's/[A-Za-z0-9_-]*PASSWORD[=:][^ ]*/***REDACTED***/gi' | \
sed 's/NEXTAUTH_[A-Z_]*[=:][^ ]*/***REDACTED***/gi' | \
sed 's/GEMINI_[A-Z_]*[=:][^ ]*/***REDACTED***/gi' | \
sed 's/ARI_[A-Z_]*[=:][^ ]*/***REDACTED***/gi' | \
sed 's/Authorization:[^ ]*/***REDACTED***/gi'
}
{
echo "# Patch Failure Debug Report"
echo ""
echo "**Run ID**: ${{ github.run_id }}"
echo "**Branch**: ${{ env.BRANCH }}"
echo "**Title**: ${{ env.TITLE }}"
echo ""
echo "## Patch File"
echo '```diff'
# Scrub patch content and redact lines with sensitive keywords
head -100 patch.diff | \
sed 's/^.*\(secret\|token\|password\|api[_-]*key\|authorization\|bearer\).*/***LINE_REDACTED***/gi'
echo '```'
echo ""
echo "## Rejected Hunks"
if find . -name "*.rej" | grep -q .; then
find . -name "*.rej" -exec sh -c 'echo "### {}"; cat "{}" | sed "s/^.*\(secret\|token\|password\|api[_-]*key\|authorization\|bearer\).*/***LINE_REDACTED***/gi"' \;
else
echo "No rejected hunks found"
fi
echo ""
echo "## Task Description"
echo '```'
if [ -f task_desc.txt ]; then
scrub_secrets "$(cat task_desc.txt)"
else
echo "N/A"
fi
echo '```'
echo ""
echo "---"
echo "*This report has been scrubbed of sensitive information (secrets, tokens, API keys)*"
} > patch-debug-report.md
cat patch-debug-report.md
- name: Upload Debug Report
if: failure() && env.AGENT_PROVIDER == 'gemini'
uses: actions/upload-artifact@v7
with:
name: patch-debug-report-run-${{ github.run_id }}
path: patch-debug-report.md
retention-days: 2
- name: 'Gemini: Generate Build-Time Secrets'
if: env.AGENT_PROVIDER == 'gemini'
id: build-secrets
env:
NEXTAUTH_URL_SECRET: ${{ secrets.NEXTAUTH_URL }}
NEXTAUTH_SECRET_SECRET: ${{ secrets.NEXTAUTH_SECRET }}
run: |
# Generate unique build-time values for CI verification only
BUILD_ID=$(uuidgen || python3 -c "import uuid; print(uuid.uuid4())")
# Only use provided secrets, never use defaults
if [ -z "$NEXTAUTH_URL_SECRET" ]; then
echo "::warning::NEXTAUTH_URL secret not configured. Using generated build-time value."
echo "NEXTAUTH_URL=http://localhost:3000" >> $GITHUB_ENV
else
echo "NEXTAUTH_URL=$NEXTAUTH_URL_SECRET" >> $GITHUB_ENV
fi
if [ -z "$NEXTAUTH_SECRET_SECRET" ]; then
echo "::warning::NEXTAUTH_SECRET secret not configured. Generating build-time value."
echo "NEXTAUTH_SECRET=build-verification-$BUILD_ID" >> $GITHUB_ENV
else
echo "NEXTAUTH_SECRET=$NEXTAUTH_SECRET_SECRET" >> $GITHUB_ENV
fi
echo "::notice::Build-time secrets configured for verification phase"
- name: 'Gemini: Verify Changes'
if: env.AGENT_PROVIDER == 'gemini'
env:
NEXTAUTH_URL: ${{ env.NEXTAUTH_URL }}
NEXTAUTH_SECRET: ${{ env.NEXTAUTH_SECRET }}
run: |
echo "::notice::Building project..."
pnpm run build
echo "::notice::Running lint fixes..."
pnpm run lint --fix || echo "::warning::Lint fix encountered issues, continuing..."
- name: 'Gemini: Prepare Commit Message'
if: env.AGENT_PROVIDER == 'gemini'
run: |
# Build a commitlint-compliant message with intelligent scope extraction
# Format: feat(scope): lowercase description under 72 characters
# This ensures compliance with conventional commits while preserving context
TITLE="${{ env.TITLE }}"
# Generate commit message following conventional commits and commitlint rules
# Rules: lowercase subject, max 100 chars, must be lowercase (no sentence case)
TITLE_LOWER=$(echo "$TITLE" | tr '[:upper:]' '[:lower:]')
SCOPE="ai"
# If title already has a conventional commit format, use as-is (just lowercase)
if echo "$TITLE_LOWER" | grep -qE '^(feat|fix|chore|docs|style|refactor|perf|test)(\([^)]*\))?:[[:space:]]'; then
COMMIT_MESSAGE="$TITLE_LOWER"
else
# Add feat(ai): prefix if not already present
COMMIT_MESSAGE="feat($SCOPE): $TITLE_LOWER"
fi
# Trim whitespace
COMMIT_MESSAGE=$(echo "$COMMIT_MESSAGE" | xargs)
# Enforce commitlint subject-max-length: 100 chars
if [ ${#COMMIT_MESSAGE} -gt 100 ]; then
echo "::warning::Commit message exceeds 100 characters, truncating"
COMMIT_MESSAGE="${COMMIT_MESSAGE:0:97}..."
fi
echo "COMMIT_MESSAGE=$COMMIT_MESSAGE" >> $GITHUB_ENV
echo "::notice::Generated commit message: $COMMIT_MESSAGE (${#COMMIT_MESSAGE} chars)"
- name: 'Gemini: Create Pull Request'
if: env.AGENT_PROVIDER == 'gemini'
uses: peter-evans/create-pull-request@v6
with:
token: ${{ secrets.ARI_PAT }}
commit-message: ${{ env.COMMIT_MESSAGE }}
title: ${{ env.TITLE }}
body: |
Automated pull request created by the Gemini Coder agent.
**Task:**
${{ env.PROMPT }}
**Files Modified:**
${{ env.FILES }}
---
#### 🤖 [Gemini Manual Trigger Guide](${{ github.server_url }}/${{ github.repository }}/blob/leader/docs/workflows/MANUAL_TRIGGERS.md)
branch: ${{ env.BRANCH }}
base: leader
delete-branch: true
disabled-guidance:
if: |
vars.GEMINI_ENABLE_CODER == 'false' &&
github.event_name == 'issues' &&
github.event.action == 'labeled' &&
github.event.label.name == 'auto-code'
runs-on: ubuntu-latest
steps:
- name: Post Guidance Comment
uses: actions/github-script@v7
with:
script: |
const body = '### ℹ️ Gemini Coder Disabled\n\n' +
'Automatic code generation is currently disabled via `GEMINI_ENABLE_CODER`. To run it manually:\n\n' +
'**Via Comment:**\n```\n@gemini-coder <task description>\n```\n\n' +
'**Via GitHub Actions:**\n' +
'1. Go to [Actions → Gemini Coder](' + context.payload.repository.html_url + '/actions/workflows/gemini-coder.yml)\n' +
'2. Click "Run workflow"\n' +
'3. Enter task description and other details.\n\n' +
'**Via GitHub CLI:**\n```bash\ngh workflow run gemini-coder.yml -f task_description="..."\n```\n\n' +
'#### 🤖 [Gemini Manual Trigger Guide](' + context.payload.repository.html_url + '/blob/leader/docs/workflows/MANUAL_TRIGGERS.md)\n\n' +
'**To re-enable:** Set repository variable `GEMINI_ENABLE_CODER=true`';
github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: body
});