-
Notifications
You must be signed in to change notification settings - Fork 395
Expand file tree
/
Copy pathtest-claude-create-pull-request.lock.yml
More file actions
641 lines (625 loc) · 30.1 KB
/
test-claude-create-pull-request.lock.yml
File metadata and controls
641 lines (625 loc) · 30.1 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
# This file was automatically generated by gh-aw. DO NOT EDIT.
# To update this file, edit the corresponding .md file and run:
# gh aw compile
name: "Test Claude Create Pull Request"
on:
workflow_dispatch: null
permissions: {}
concurrency:
group: "gh-aw-${{ github.workflow }}"
run-name: "Test Claude Create Pull Request"
jobs:
test-claude-create-pull-request:
runs-on: ubuntu-latest
permissions:
contents: read
issues: read
pull-requests: read
discussions: read
deployments: read
models: read
outputs:
output: ${{ steps.collect_output.outputs.output }}
steps:
- name: Checkout repository
uses: actions/checkout@v5
- name: Setup agent output
id: setup_agent_output
uses: actions/github-script@v7
with:
script: |
function main() {
const fs = require('fs');
const crypto = require('crypto');
// Generate a random filename for the output file
const randomId = crypto.randomBytes(8).toString('hex');
const outputFile = `/tmp/aw_output_${randomId}.txt`;
// Ensure the /tmp directory exists and create empty output file
fs.mkdirSync('/tmp', { recursive: true });
fs.writeFileSync(outputFile, '', { mode: 0o644 });
// Verify the file was created and is writable
if (!fs.existsSync(outputFile)) {
throw new Error(`Failed to create output file: ${outputFile}`);
}
// Set the environment variable for subsequent steps
core.exportVariable('GITHUB_AW_OUTPUT', outputFile);
console.log('Created agentic output file:', outputFile);
// Also set as step output for reference
core.setOutput('output_file', outputFile);
}
main();
- name: Setup MCPs
run: |
mkdir -p /tmp/mcp-config
cat > /tmp/mcp-config/mcp-servers.json << 'EOF'
{
"mcpServers": {
"github": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-e",
"GITHUB_PERSONAL_ACCESS_TOKEN",
"ghcr.io/github/github-mcp-server:sha-45e90ae"
],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "${{ secrets.GITHUB_TOKEN }}"
}
}
}
}
EOF
- name: Create prompt
env:
GITHUB_AW_OUTPUT: ${{ env.GITHUB_AW_OUTPUT }}
run: |
mkdir -p /tmp/aw-prompts
cat > /tmp/aw-prompts/prompt.txt << 'EOF'
Add a file "TEST.md" with content "Hello, World!"
Create a pull request with title "Hello" and body "World"
Add a haiku about GitHub Actions and AI to the PR body.
---
## Pull Request Creation
To create a pull request on GitHub, do NOT attempt to use MCP tools and do NOT attempt to use `gh` or the GitHub API. Instead, write to the title and issue body of the pull request description to "${{ env.GITHUB_AW_OUTPUT }}", where the first line of the file is the title of the issue, and the rest of the file is the body of the issue, in markdown.
Instead:
1. Make any file changes directly in the working directory, making the changes and additions you want, but leaving the changes uncommitted and unstaged.
2. Write a PR title and description to ${{ env.GITHUB_AW_OUTPUT }}, where the first line of the file is the title of the pull request, and the rest of the file is the body of the pull request, in markdown.
EOF
- name: Print prompt to step summary
run: |
echo "## Generated Prompt" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo '``````markdown' >> $GITHUB_STEP_SUMMARY
cat /tmp/aw-prompts/prompt.txt >> $GITHUB_STEP_SUMMARY
echo '``````' >> $GITHUB_STEP_SUMMARY
- name: Generate agentic run info
uses: actions/github-script@v7
with:
script: |
const fs = require('fs');
const awInfo = {
engine_id: "claude",
engine_name: "Claude Code",
model: "",
version: "",
workflow_name: "Test Claude Create Pull Request",
experimental: false,
supports_tools_whitelist: true,
supports_http_transport: true,
run_id: context.runId,
run_number: context.runNumber,
run_attempt: process.env.GITHUB_RUN_ATTEMPT,
repository: context.repo.owner + '/' + context.repo.repo,
ref: context.ref,
sha: context.sha,
actor: context.actor,
event_name: context.eventName,
created_at: new Date().toISOString()
};
// Write to /tmp directory to avoid inclusion in PR
const tmpPath = '/tmp/aw_info.json';
fs.writeFileSync(tmpPath, JSON.stringify(awInfo, null, 2));
console.log('Generated aw_info.json at:', tmpPath);
console.log(JSON.stringify(awInfo, null, 2));
- name: Upload agentic run info
if: always()
uses: actions/upload-artifact@v4
with:
name: aw_info.json
path: /tmp/aw_info.json
if-no-files-found: warn
- name: Execute Claude Code Action
id: agentic_execution
uses: anthropics/claude-code-base-action@v0.0.56
with:
# Allowed tools (sorted):
# - Glob
# - Grep
# - LS
# - NotebookRead
# - Read
# - Task
# - mcp__github__download_workflow_run_artifact
# - mcp__github__get_code_scanning_alert
# - mcp__github__get_commit
# - mcp__github__get_dependabot_alert
# - mcp__github__get_discussion
# - mcp__github__get_discussion_comments
# - mcp__github__get_file_contents
# - mcp__github__get_issue
# - mcp__github__get_issue_comments
# - mcp__github__get_job_logs
# - mcp__github__get_me
# - mcp__github__get_notification_details
# - mcp__github__get_pull_request
# - mcp__github__get_pull_request_comments
# - mcp__github__get_pull_request_diff
# - mcp__github__get_pull_request_files
# - mcp__github__get_pull_request_reviews
# - mcp__github__get_pull_request_status
# - mcp__github__get_secret_scanning_alert
# - mcp__github__get_tag
# - mcp__github__get_workflow_run
# - mcp__github__get_workflow_run_logs
# - mcp__github__get_workflow_run_usage
# - mcp__github__list_branches
# - mcp__github__list_code_scanning_alerts
# - mcp__github__list_commits
# - mcp__github__list_dependabot_alerts
# - mcp__github__list_discussion_categories
# - mcp__github__list_discussions
# - mcp__github__list_issues
# - mcp__github__list_notifications
# - mcp__github__list_pull_requests
# - mcp__github__list_secret_scanning_alerts
# - mcp__github__list_tags
# - mcp__github__list_workflow_jobs
# - mcp__github__list_workflow_run_artifacts
# - mcp__github__list_workflow_runs
# - mcp__github__list_workflows
# - mcp__github__search_code
# - mcp__github__search_issues
# - mcp__github__search_orgs
# - mcp__github__search_pull_requests
# - mcp__github__search_repositories
# - mcp__github__search_users
allowed_tools: "Glob,Grep,LS,NotebookRead,Read,Task,mcp__github__download_workflow_run_artifact,mcp__github__get_code_scanning_alert,mcp__github__get_commit,mcp__github__get_dependabot_alert,mcp__github__get_discussion,mcp__github__get_discussion_comments,mcp__github__get_file_contents,mcp__github__get_issue,mcp__github__get_issue_comments,mcp__github__get_job_logs,mcp__github__get_me,mcp__github__get_notification_details,mcp__github__get_pull_request,mcp__github__get_pull_request_comments,mcp__github__get_pull_request_diff,mcp__github__get_pull_request_files,mcp__github__get_pull_request_reviews,mcp__github__get_pull_request_status,mcp__github__get_secret_scanning_alert,mcp__github__get_tag,mcp__github__get_workflow_run,mcp__github__get_workflow_run_logs,mcp__github__get_workflow_run_usage,mcp__github__list_branches,mcp__github__list_code_scanning_alerts,mcp__github__list_commits,mcp__github__list_dependabot_alerts,mcp__github__list_discussion_categories,mcp__github__list_discussions,mcp__github__list_issues,mcp__github__list_notifications,mcp__github__list_pull_requests,mcp__github__list_secret_scanning_alerts,mcp__github__list_tags,mcp__github__list_workflow_jobs,mcp__github__list_workflow_run_artifacts,mcp__github__list_workflow_runs,mcp__github__list_workflows,mcp__github__search_code,mcp__github__search_issues,mcp__github__search_orgs,mcp__github__search_pull_requests,mcp__github__search_repositories,mcp__github__search_users"
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
claude_env: |
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GITHUB_AW_OUTPUT: ${{ env.GITHUB_AW_OUTPUT }}
mcp_config: /tmp/mcp-config/mcp-servers.json
prompt_file: /tmp/aw-prompts/prompt.txt
timeout_minutes: 5
env:
GITHUB_AW_OUTPUT: ${{ env.GITHUB_AW_OUTPUT }}
- name: Capture Agentic Action logs
if: always()
run: |
# Copy the detailed execution file from Agentic Action if available
if [ -n "${{ steps.agentic_execution.outputs.execution_file }}" ] && [ -f "${{ steps.agentic_execution.outputs.execution_file }}" ]; then
cp ${{ steps.agentic_execution.outputs.execution_file }} /tmp/test-claude-create-pull-request.log
else
echo "No execution file output found from Agentic Action" >> /tmp/test-claude-create-pull-request.log
fi
# Ensure log file exists
touch /tmp/test-claude-create-pull-request.log
- name: Check if workflow-complete.txt exists, if so upload it
id: check_file
run: |
if [ -f workflow-complete.txt ]; then
echo "File exists"
echo "upload=true" >> $GITHUB_OUTPUT
else
echo "File does not exist"
echo "upload=false" >> $GITHUB_OUTPUT
fi
- name: Upload workflow-complete.txt
if: steps.check_file.outputs.upload == 'true'
uses: actions/upload-artifact@v4
with:
name: workflow-complete
path: workflow-complete.txt
- name: Collect agent output
id: collect_output
uses: actions/github-script@v7
with:
script: |
/**
* Sanitizes content for safe output in GitHub Actions
* @param {string} content - The content to sanitize
* @returns {string} The sanitized content
*/
function sanitizeContent(content) {
if (!content || typeof content !== 'string') {
return '';
}
// Read allowed domains from environment variable
const allowedDomainsEnv = process.env.GITHUB_AW_ALLOWED_DOMAINS;
const defaultAllowedDomains = [
'github.com',
'github.io',
'githubusercontent.com',
'githubassets.com',
'github.dev',
'codespaces.new'
];
const allowedDomains = allowedDomainsEnv
? allowedDomainsEnv.split(',').map(d => d.trim()).filter(d => d)
: defaultAllowedDomains;
let sanitized = content;
// Neutralize @mentions to prevent unintended notifications
sanitized = neutralizeMentions(sanitized);
// Remove control characters (except newlines and tabs)
sanitized = sanitized.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '');
// XML character escaping
sanitized = sanitized
.replace(/&/g, '&') // Must be first to avoid double-escaping
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
// URI filtering - replace non-https protocols with "(redacted)"
// Step 1: Temporarily mark HTTPS URLs to protect them
sanitized = sanitizeUrlProtocols(sanitized);
// Domain filtering for HTTPS URIs
// Match https:// URIs and check if domain is in allowlist
sanitized = sanitizeUrlDomains(sanitized);
// Limit total length to prevent DoS (0.5MB max)
const maxLength = 524288;
if (sanitized.length > maxLength) {
sanitized = sanitized.substring(0, maxLength) + '\n[Content truncated due to length]';
}
// Limit number of lines to prevent log flooding (65k max)
const lines = sanitized.split('\n');
const maxLines = 65000;
if (lines.length > maxLines) {
sanitized = lines.slice(0, maxLines).join('\n') + '\n[Content truncated due to line count]';
}
// Remove ANSI escape sequences
sanitized = sanitized.replace(/\x1b\[[0-9;]*[mGKH]/g, '');
// Neutralize common bot trigger phrases
sanitized = neutralizeBotTriggers(sanitized);
// Trim excessive whitespace
return sanitized.trim();
/**
* Remove unknown domains
* @param {string} s - The string to process
* @returns {string} The string with unknown domains redacted
*/
function sanitizeUrlDomains(s) {
s = s.replace(/\bhttps:\/\/([^\/\s\])}'"<>&\x00-\x1f]+)/gi, (match, domain) => {
// Extract the hostname part (before first slash, colon, or other delimiter)
const hostname = domain.split(/[\/:\?#]/)[0].toLowerCase();
// Check if this domain or any parent domain is in the allowlist
const isAllowed = allowedDomains.some(allowedDomain => {
const normalizedAllowed = allowedDomain.toLowerCase();
return hostname === normalizedAllowed || hostname.endsWith('.' + normalizedAllowed);
});
return isAllowed ? match : '(redacted)';
});
return s;
}
/**
* Remove unknown protocols except https
* @param {string} s - The string to process
* @returns {string} The string with non-https protocols redacted
*/
function sanitizeUrlProtocols(s) {
// Match both protocol:// and protocol: patterns
// This covers URLs like https://example.com, javascript:alert(), mailto:user@domain.com, etc.
return s.replace(/\b(\w+):(?:\/\/)?[^\s\])}'"<>&\x00-\x1f]+/gi, (match, protocol) => {
// Allow https (case insensitive), redact everything else
return protocol.toLowerCase() === 'https' ? match : '(redacted)';
});
}
/**
* Neutralizes @mentions by wrapping them in backticks
* @param {string} s - The string to process
* @returns {string} The string with neutralized mentions
*/
function neutralizeMentions(s) {
// Replace @name or @org/team outside code with `@name`
return s.replace(/(^|[^\w`])@([A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?(?:\/[A-Za-z0-9._-]+)?)/g,
(_m, p1, p2) => `${p1}\`@${p2}\``);
}
/**
* Neutralizes bot trigger phrases by wrapping them in backticks
* @param {string} s - The string to process
* @returns {string} The string with neutralized bot triggers
*/
function neutralizeBotTriggers(s) {
// Neutralize common bot trigger phrases like "fixes #123", "closes #asdfs", etc.
return s.replace(/\b(fixes?|closes?|resolves?|fix|close|resolve)\s+#(\w+)/gi,
(match, action, ref) => `\`${action} #${ref}\``);
}
}
async function main() {
const fs = require("fs");
const outputFile = process.env.GITHUB_AW_OUTPUT;
if (!outputFile) {
console.log('GITHUB_AW_OUTPUT not set, no output to collect');
core.setOutput('output', '');
return;
}
if (!fs.existsSync(outputFile)) {
console.log('Output file does not exist:', outputFile);
core.setOutput('output', '');
return;
}
const outputContent = fs.readFileSync(outputFile, 'utf8');
if (outputContent.trim() === '') {
console.log('Output file is empty');
core.setOutput('output', '');
} else {
const sanitizedContent = sanitizeContent(outputContent);
console.log('Collected agentic output (sanitized):', sanitizedContent.substring(0, 200) + (sanitizedContent.length > 200 ? '...' : ''));
core.setOutput('output', sanitizedContent);
}
}
await main();
- name: Print agent output to step summary
env:
GITHUB_AW_OUTPUT: ${{ env.GITHUB_AW_OUTPUT }}
run: |
echo "## Agent Output" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo '``````markdown' >> $GITHUB_STEP_SUMMARY
cat ${{ env.GITHUB_AW_OUTPUT }} >> $GITHUB_STEP_SUMMARY
echo '``````' >> $GITHUB_STEP_SUMMARY
- name: Upload agentic output file
if: always() && steps.collect_output.outputs.output != ''
uses: actions/upload-artifact@v4
with:
name: aw_output.txt
path: ${{ env.GITHUB_AW_OUTPUT }}
if-no-files-found: warn
- name: Upload engine output files
if: always()
uses: actions/upload-artifact@v4
with:
name: agent_outputs
path: |
output.txt
if-no-files-found: ignore
- name: Upload agent logs
if: always()
uses: actions/upload-artifact@v4
with:
name: test-claude-create-pull-request.log
path: /tmp/test-claude-create-pull-request.log
if-no-files-found: warn
- name: Generate git patch
if: always()
run: |
# Check current git status
echo "Current git status:"
git status
# Get the initial commit SHA from the base branch of the pull request
if [ "$GITHUB_EVENT_NAME" = "pull_request" ] || [ "$GITHUB_EVENT_NAME" = "pull_request_review_comment" ]; then
INITIAL_SHA="$GITHUB_BASE_REF"
else
INITIAL_SHA="$GITHUB_SHA"
fi
echo "Base commit SHA: $INITIAL_SHA"
# Configure git user for GitHub Actions
git config --global user.email "action@github.com"
git config --global user.name "GitHub Action"
# Stage any unstaged files
git add -A || true
# Check if there are staged files to commit
if ! git diff --cached --quiet; then
echo "Staged files found, committing them..."
git commit -m "[agent] staged files" || true
echo "Staged files committed"
else
echo "No staged files to commit"
fi
# Check updated git status
echo "Updated git status after committing staged files:"
git status
# Show compact diff information between initial commit and HEAD (committed changes only)
echo '## Git diff' >> $GITHUB_STEP_SUMMARY
echo '' >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
git diff --name-only "$INITIAL_SHA"..HEAD >> $GITHUB_STEP_SUMMARY || true
echo '```' >> $GITHUB_STEP_SUMMARY
echo '' >> $GITHUB_STEP_SUMMARY
# Check if there are any committed changes since the initial commit
if git diff --quiet "$INITIAL_SHA" HEAD; then
echo "No committed changes detected since initial commit"
echo "Skipping patch generation - no committed changes to create patch from"
else
echo "Committed changes detected, generating patch..."
# Generate patch from initial commit to HEAD (committed changes only)
git format-patch "$INITIAL_SHA"..HEAD --stdout > /tmp/aw.patch || echo "Failed to generate patch" > /tmp/aw.patch
echo "Patch file created at /tmp/aw.patch"
ls -la /tmp/aw.patch
# Show the first 50 lines of the patch for review
echo '## Git Patch' >> $GITHUB_STEP_SUMMARY
echo '' >> $GITHUB_STEP_SUMMARY
echo '```diff' >> $GITHUB_STEP_SUMMARY
head -50 /tmp/aw.patch >> $GITHUB_STEP_SUMMARY || echo "Could not display patch contents" >> $GITHUB_STEP_SUMMARY
echo '...' >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
echo '' >> $GITHUB_STEP_SUMMARY
fi
- name: Upload git patch
if: always()
uses: actions/upload-artifact@v4
with:
name: aw.patch
path: /tmp/aw.patch
if-no-files-found: ignore
create_pull_request:
needs: test-claude-create-pull-request
runs-on: ubuntu-latest
permissions:
contents: write
issues: write
pull-requests: write
timeout-minutes: 10
outputs:
branch_name: ${{ steps.create_pull_request.outputs.branch_name }}
pull_request_number: ${{ steps.create_pull_request.outputs.pull_request_number }}
pull_request_url: ${{ steps.create_pull_request.outputs.pull_request_url }}
steps:
- name: Download patch artifact
uses: actions/download-artifact@v4
with:
name: aw.patch
path: /tmp/
- name: Checkout repository
uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Create Pull Request
id: create_pull_request
uses: actions/github-script@v7
env:
GITHUB_AW_AGENT_OUTPUT: ${{ needs.test-claude-create-pull-request.outputs.output }}
GITHUB_AW_WORKFLOW_ID: "test-claude-create-pull-request"
GITHUB_AW_BASE_BRANCH: ${{ github.ref_name }}
GITHUB_AW_PR_TITLE_PREFIX: "[claude-test] "
GITHUB_AW_PR_LABELS: "claude,automation,bot"
GITHUB_AW_PR_DRAFT: "true"
with:
script: |
/** @type {typeof import("fs")} */
const fs = require("fs");
/** @type {typeof import("crypto")} */
const crypto = require("crypto");
const { execSync } = require("child_process");
async function main() {
// Environment validation - fail early if required variables are missing
const workflowId = process.env.GITHUB_AW_WORKFLOW_ID;
if (!workflowId) {
throw new Error('GITHUB_AW_WORKFLOW_ID environment variable is required');
}
const baseBranch = process.env.GITHUB_AW_BASE_BRANCH;
if (!baseBranch) {
throw new Error('GITHUB_AW_BASE_BRANCH environment variable is required');
}
const outputContent = process.env.GITHUB_AW_AGENT_OUTPUT || "";
if (outputContent.trim() === '') {
console.log('Agent output content is empty');
}
// Check if patch file exists and has valid content
if (!fs.existsSync('/tmp/aw.patch')) {
throw new Error('No patch file found - cannot create pull request without changes');
}
const patchContent = fs.readFileSync('/tmp/aw.patch', 'utf8');
if (!patchContent || !patchContent.trim() || patchContent.includes('Failed to generate patch')) {
throw new Error('Patch file is empty or contains error message - cannot create pull request without changes');
}
console.log('Agent output content length:', outputContent.length);
console.log('Patch content validation passed');
// Parse the output to extract title and body
const lines = outputContent.split('\n');
let title = '';
let bodyLines = [];
let foundTitle = false;
for (let i = 0; i < lines.length; i++) {
const line = lines[i].trim();
// Skip empty lines until we find the title
if (!foundTitle && line === '') {
continue;
}
// First non-empty line becomes the title
if (!foundTitle && line !== '') {
// Remove markdown heading syntax if present
title = line.replace(/^#+\s*/, '').trim();
foundTitle = true;
continue;
}
// Everything else goes into the body
if (foundTitle) {
bodyLines.push(lines[i]); // Keep original formatting
}
}
// If no title was found, use a default
if (!title) {
title = 'Agent Output';
}
// Apply title prefix if provided via environment variable
const titlePrefix = process.env.GITHUB_AW_PR_TITLE_PREFIX;
if (titlePrefix && !title.startsWith(titlePrefix)) {
title = titlePrefix + title;
}
// Add AI disclaimer with run id, run htmlurl
const runId = context.runId;
const runUrl = context.payload.repository
? `${context.payload.repository.html_url}/actions/runs/${runId}`
: `https://github.com/actions/runs/${runId}`;
bodyLines.push(``, ``, `> Generated by Agentic Workflow Run [${runId}](${runUrl})`, '');
// Prepare the body content
const body = bodyLines.join('\n').trim();
// Parse labels from environment variable (comma-separated string)
const labelsEnv = process.env.GITHUB_AW_PR_LABELS;
const labels = labelsEnv ? labelsEnv.split(',').map(/** @param {string} label */ label => label.trim()).filter(/** @param {string} label */ label => label) : [];
// Parse draft setting from environment variable (defaults to true)
const draftEnv = process.env.GITHUB_AW_PR_DRAFT;
const draft = draftEnv ? draftEnv.toLowerCase() === 'true' : true;
console.log('Creating pull request with title:', title);
console.log('Labels:', labels);
console.log('Draft:', draft);
console.log('Body length:', body.length);
// Generate unique branch name using cryptographic random hex
const randomHex = crypto.randomBytes(8).toString('hex');
const branchName = `${workflowId}/${randomHex}`;
console.log('Generated branch name:', branchName);
console.log('Base branch:', baseBranch);
// Create a new branch using git CLI
// Configure git (required for commits)
execSync('git config --global user.email "action@github.com"', { stdio: 'inherit' });
execSync('git config --global user.name "GitHub Action"', { stdio: 'inherit' });
// Create and checkout new branch
execSync(`git checkout -b ${branchName}`, { stdio: 'inherit' });
console.log('Created and checked out branch:', branchName);
// Apply the patch using git CLI
console.log('Applying patch...');
// Apply the patch using git apply
execSync('git apply /tmp/aw.patch', { stdio: 'inherit' });
console.log('Patch applied successfully');
// Commit and push the changes
execSync('git add .', { stdio: 'inherit' });
execSync(`git commit -m "Add agent output: ${title}"`, { stdio: 'inherit' });
execSync(`git push origin ${branchName}`, { stdio: 'inherit' });
console.log('Changes committed and pushed');
// Create the pull request
const { data: pullRequest } = await github.rest.pulls.create({
owner: context.repo.owner,
repo: context.repo.repo,
title: title,
body: body,
head: branchName,
base: baseBranch,
draft: draft
});
console.log('Created pull request #' + pullRequest.number + ': ' + pullRequest.html_url);
// Add labels if specified
if (labels.length > 0) {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: pullRequest.number,
labels: labels
});
console.log('Added labels to pull request:', labels);
}
// Set output for other jobs to use
core.setOutput('pull_request_number', pullRequest.number);
core.setOutput('pull_request_url', pullRequest.html_url);
core.setOutput('branch_name', branchName);
// Write summary to GitHub Actions summary
await core.summary
.addRaw(`
## Pull Request
- **Pull Request**: [#${pullRequest.number}](${pullRequest.html_url})
- **Branch**: \`${branchName}\`
- **Base Branch**: \`${baseBranch}\`
`).write();
}
await main();