Elffuss BraidHub

kikocis/continue public

main ¡ 21.5 KiBRawPermalink
1name: "Continue PR Review"
2description: "Automated code review for pull requests using Continue CLI"
3author: "Continue Dev, Inc."
4
5inputs:
6 continue-api-key:
7 description: "API key for Continue service"
8 required: true
9 continue-org:
10 description: "Organization for Continue config"
11 required: true
12 continue-config:
13 description: 'Config path to use (e.g., "myorg/review-bot")'
14 required: true
15
16runs:
17 using: "composite"
18 steps:
19 - name: Checkout Repository
20 uses: actions/checkout@v4
21
22 - name: Check Authorization
23 shell: bash
24 env:
25 # Only move the dangerous check to env to prevent shell injection
26 HAS_TRIGGER_PHRASE: ${{ contains(github.event.comment.body, '@continue-review') }}
27 run: |
28 # Check if this action should run based on event type and user permissions
29 SHOULD_RUN="false"
30
31 if [ "${{ github.event_name }}" = "pull_request" ]; then
32 # Check if PR is a draft
33 if [ "${{ github.event.pull_request.draft }}" = "true" ]; then
34 echo "::notice::Skipping review - PR is a draft"
35 else
36 # Check PR author association
37 AUTHOR_ASSOC="${{ github.event.pull_request.author_association }}"
38 if [ "$AUTHOR_ASSOC" = "OWNER" ] || [ "$AUTHOR_ASSOC" = "MEMBER" ] || [ "$AUTHOR_ASSOC" = "COLLABORATOR" ]; then
39 SHOULD_RUN="true"
40 else
41 echo "::notice::Skipping review - PR author is not a team member (association: $AUTHOR_ASSOC)"
42 fi
43 fi
44 elif [ "${{ github.event_name }}" = "issue_comment" ]; then
45 # Check if it's a PR comment with the trigger phrase
46 if [ "${{ github.event.issue.pull_request }}" != "" ] && [ "$HAS_TRIGGER_PHRASE" = "true" ]; then
47 COMMENTER_ASSOC="${{ github.event.comment.author_association }}"
48 if [ "$COMMENTER_ASSOC" = "OWNER" ] || [ "$COMMENTER_ASSOC" = "MEMBER" ] || [ "$COMMENTER_ASSOC" = "COLLABORATOR" ]; then
49 SHOULD_RUN="true"
50 else
51 echo "::notice::Skipping review - Commenter is not a team member (association: $COMMENTER_ASSOC)"
52 fi
53 else
54 echo "::notice::Skipping review - Comment does not contain @continue-review trigger, or is not on a PR"
55 fi
56 else
57 echo "::notice::Skipping review - Unsupported event type: ${{ github.event_name }}"
58 fi
59
60 echo "SHOULD_RUN=$SHOULD_RUN" >> $GITHUB_ENV
61
62 - name: Setup Node.js
63 if: env.SHOULD_RUN == 'true'
64 uses: actions/setup-node@v4
65 with:
66 node-version: 20
67
68 - name: Install Continue CLI
69 if: env.SHOULD_RUN == 'true'
70 shell: bash
71 run: npm install -g @continuedev/cli@1.4.30
72
73 - name: Post Initial Comment
74 if: env.SHOULD_RUN == 'true'
75 id: initial-comment
76 uses: actions/github-script@v7
77 with:
78 script: |
79 const marker = '<!-- continue-agent-review -->';
80
81 // Get PR number based on event type
82 let prNumber;
83 if (context.eventName === 'pull_request') {
84 prNumber = context.payload.pull_request.number;
85 } else {
86 // For issue_comment event
87 prNumber = context.payload.issue.number;
88 }
89
90 // Check for existing comment
91 const { data: comments } = await github.rest.issues.listComments({
92 owner: context.repo.owner,
93 repo: context.repo.repo,
94 issue_number: prNumber,
95 per_page: 100
96 });
97
98 // Find existing Continue review comment
99 const existingComment = comments
100 .filter(c => c.body && c.body.includes(marker))
101 .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0];
102
103 // Get workflow run URL
104 const workflowRunUrl = `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;
105
106 // Create initial "review in progress" message
107 let initialMessage = `${marker}\n**🔄 Review In Progress**\n\n`;
108
109 if (context.eventName === 'issue_comment') {
110 initialMessage = `${marker}\n**🔄 Review In Progress**\n\n*Triggered by @${context.payload.comment.user.login}'s request*\n\n`;
111 }
112
113 initialMessage += `Continue AI is analyzing the code changes...\n\n`;
114 initialMessage += `📊 **Review Scope:**\n`;
115 initialMessage += `- Repository: ${context.repo.owner}/${context.repo.repo}\n`;
116 initialMessage += `- PR #${prNumber}\n\n`;
117 initialMessage += `⏱️ This typically takes 1-2 minutes.\n\n`;
118 initialMessage += `[View live progress →](${workflowRunUrl})\n\n`;
119 initialMessage += `---\n<!-- ${new Date().toISOString()} | Powered by Continue (https://continue.dev) -->`;
120
121 if (existingComment) {
122 // Check if comment is less than 1 hour old
123 const commentAge = Date.now() - new Date(existingComment.created_at).getTime();
124 const oneHour = 60 * 60 * 1000;
125
126 if (commentAge < oneHour) {
127 // Update existing comment if less than 1 hour old
128 await github.rest.issues.updateComment({
129 owner: context.repo.owner,
130 repo: context.repo.repo,
131 comment_id: existingComment.id,
132 body: initialMessage
133 });
134 console.log(`Updated existing comment ${existingComment.id} to show review in progress`);
135 core.setOutput('comment_id', existingComment.id);
136 } else {
137 // Create new comment if older than 1 hour (preserve history)
138 const { data: comment } = await github.rest.issues.createComment({
139 issue_number: prNumber,
140 owner: context.repo.owner,
141 repo: context.repo.repo,
142 body: initialMessage
143 });
144 console.log(`Created new comment ${comment.id} showing review in progress`);
145 core.setOutput('comment_id', comment.id);
146 }
147 } else {
148 // Create new comment
149 const { data: comment } = await github.rest.issues.createComment({
150 issue_number: prNumber,
151 owner: context.repo.owner,
152 repo: context.repo.repo,
153 body: initialMessage
154 });
155 console.log(`Created new comment ${comment.id} on PR #${prNumber}`);
156 core.setOutput('comment_id', comment.id);
157 }
158
159 - name: Build PR Review Prompt
160 if: env.SHOULD_RUN == 'true'
161 shell: bash
162 env:
163 GITHUB_TOKEN: ${{ github.token }}
164 run: |
165 # Get PR number based on event type
166 if [ "${{ github.event_name }}" = "pull_request" ]; then
167 PR_NUMBER="${{ github.event.number }}"
168 else
169 # For issue_comment event on a PR
170 PR_NUMBER="${{ github.event.issue.number }}"
171 fi
172
173 # Get PR diff
174 gh pr diff $PR_NUMBER > pr_diff.txt
175
176 # Get PR details
177 PR_TITLE=$(gh pr view $PR_NUMBER --json title -q .title)
178 PR_AUTHOR=$(gh pr view $PR_NUMBER --json author -q .author.login)
179 PR_BODY=$(gh pr view $PR_NUMBER --json body -q .body)
180 FILES_CHANGED=$(gh pr view $PR_NUMBER --json files -q '.files | length')
181
182 # Create review prompt
183 cat > review_prompt.txt << EOF
184 You are reviewing a pull request. Please provide helpful, context-aware feedback.
185
186 CONTEXT:
187 - Repository: ${{ github.repository }}
188 - PR #$PR_NUMBER: $PR_TITLE
189 - Files Changed: $FILES_CHANGED
190 - Author: $PR_AUTHOR
191
192 REVIEW APPROACH:
193 1. First, understand what this PR is trying to accomplish
194 2. Check if similar patterns exist elsewhere in the codebase
195 3. Focus on actual issues that affect functionality
196 4. Be constructive and suggest solutions when possible
197
198 FOCUS ON:
199 - Bugs that will cause failures or incorrect behavior
200 - Security vulnerabilities (exposed secrets, injection risks)
201 - Breaking changes that affect other parts of the system
202 - Performance issues with real impact (memory leaks, O(n²) algorithms)
203 - Missing tests for new features or bug fixes
204 - Missing documentation for APIs or complex logic
205
206 SKIP COMMENTING ON:
207 - Style and formatting (handled by linters)
208 - Alternative approaches unless current is broken
209 - Minor naming unless genuinely confusing
210 - Trivial documentation for self-explanatory code
211
212 Be specific with line numbers and explain why something is an issue.
213
214 PR Description: ${PR_BODY:-No description provided}
215
216 Code Changes:
217 EOF
218
219 # Add the diff
220 cat pr_diff.txt >> review_prompt.txt
221
222 cat >> review_prompt.txt << 'EOF'
223
224 Your Review:
225 Please provide constructive feedback on the code changes.
226 Focus on issues that matter for functionality, security, and maintainability.
227 If the code looks good overall, acknowledge that while noting any minor suggestions.
228 EOF
229
230 - name: Run Continue CLI Review
231 if: env.SHOULD_RUN == 'true'
232 shell: bash
233 env:
234 CONTINUE_API_KEY: ${{ inputs.continue-api-key }}
235 CONTINUE_ORG: ${{ inputs.continue-org }}
236 CONTINUE_CONFIG: ${{ inputs.continue-config }}
237 GITHUB_TOKEN: ${{ github.token }}
238 run: |
239 echo "Running Continue CLI with prompt:"
240 echo "=================================="
241 head -n 100 review_prompt.txt
242 echo "... [truncated] ..."
243 echo "=================================="
244 echo ""
245
246 # Validate API key
247 if [ -z "$CONTINUE_API_KEY" ]; then
248 echo "Warning: CONTINUE_API_KEY environment variable is not set"
249 # Create fallback review and continue
250 cat > code_review.md << 'EOF'
251 ## Code Review Summary
252
253 ⚠️ AI review skipped: CONTINUE_API_KEY not configured.
254
255 ### Configuration Required
256 - Please set the CONTINUE_API_KEY secret in repository settings
257 - Verify that the organization and config path are valid
258 EOF
259 echo "SKIP_CLI=true" >> $GITHUB_ENV
260 else
261 echo "SKIP_CLI=false" >> $GITHUB_ENV
262 fi
263
264 # Validate inputs to prevent command injection
265 if [[ ! "$CONTINUE_ORG" =~ ^[a-zA-Z0-9_-]+$ ]]; then
266 echo "Error: Invalid organization name. Must contain only alphanumeric characters, hyphens, and underscores."
267 exit 1
268 fi
269
270 if [[ ! "$CONTINUE_CONFIG" =~ ^[a-zA-Z0-9_/-]+$ ]]; then
271 echo "Error: Invalid config path. Must contain only alphanumeric characters, hyphens, underscores, and forward slashes."
272 exit 1
273 fi
274
275 # Test Continue CLI availability
276 if [ "$SKIP_CLI" != "true" ]; then
277 echo "Testing Continue CLI..."
278 if ! which cn > /dev/null 2>&1; then
279 echo "Warning: Continue CLI not found or not working"
280 cat > code_review.md << 'EOF'
281 ## Code Review Summary
282
283 ⚠️ AI review skipped: Continue CLI installation failed.
284
285 ### Troubleshooting
286 - Check that npm installation succeeded
287 - Verify @continuedev/cli package is available
288 EOF
289 echo "SKIP_CLI=true" >> $GITHUB_ENV
290 else
291 echo "Continue CLI found at: $(which cn)"
292 echo "Continue CLI version: $(cn --version 2>/dev/null || echo 'version check failed')"
293 fi
294 fi
295
296 # Run the CLI with validated config and error handling
297 if [ "$SKIP_CLI" != "true" ]; then
298 echo "Executing Continue CLI with config: $CONTINUE_ORG/$CONTINUE_CONFIG"
299
300 # Write prompt to temp file for headless mode
301 PROMPT_FILE="/tmp/continue-review-$RANDOM.txt"
302 cp review_prompt.txt "$PROMPT_FILE"
303 echo "Prompt file: $PROMPT_FILE"
304 echo "Prompt length: $(wc -c < "$PROMPT_FILE") characters"
305
306 # Use timeout to prevent hanging (360 seconds = 6 minutes)
307 echo "Executing command: cn --config $CONTINUE_ORG/$CONTINUE_CONFIG -p @$PROMPT_FILE --allow Bash"
308
309 if timeout 360 cn --config "$CONTINUE_ORG/$CONTINUE_CONFIG" -p "@$PROMPT_FILE" --allow Bash > code_review_raw.md 2>cli_error.log; then
310 echo "Continue CLI completed successfully"
311 echo "Raw output length: $(wc -c < code_review_raw.md) characters"
312
313 # Clean up ANSI codes if any
314 sed 's/\x1b\[[0-9;]*m//g' code_review_raw.md > code_review.md
315
316 echo "Cleaned output length: $(wc -c < code_review.md) characters"
317 echo "First 500 chars of output:"
318 head -c 500 code_review.md
319 echo ""
320
321 # Check if output is empty
322 if [ ! -s code_review.md ]; then
323 echo "Warning: Continue CLI returned empty output"
324 cat > code_review.md << 'EOF'
325 ## Code Review Summary
326
327 ⚠️ Continue CLI returned an empty response. Please check the configuration.
328 EOF
329 fi
330 else
331 echo "Error: Continue CLI command failed with exit code $?"
332 echo "CLI error log:"
333 cat cli_error.log
334
335 # Check for specific error patterns
336 if grep -q "not found\|ENOENT" cli_error.log 2>/dev/null; then
337 cat > code_review.md << 'EOF'
338 ## Code Review Summary
339
340 ⚠️ Continue CLI is not properly installed. Please ensure @continuedev/cli is installed globally.
341 EOF
342 elif grep -q "config\|assistant" cli_error.log 2>/dev/null; then
343 cat > code_review.md << 'EOF'
344 ## Code Review Summary
345
346 ⚠️ Continue configuration error. Please verify that the assistant exists in Continue Hub.
347 EOF
348 elif grep -q "api\|auth" cli_error.log 2>/dev/null; then
349 cat > code_review.md << 'EOF'
350 ## Code Review Summary
351
352 ⚠️ Continue API authentication failed. Please check your CONTINUE_API_KEY.
353 EOF
354 else
355 cat > code_review.md << 'EOF'
356 ## Code Review Summary
357
358 ⚠️ AI review failed. Please check the Continue API key and configuration.
359
360 ### Troubleshooting
361 - Verify the CONTINUE_API_KEY secret is set correctly
362 - Check that the organization and config path are valid
363 - Ensure the Continue service is accessible
364 EOF
365 fi
366 fi
367
368 # Clean up temp file
369 rm -f "$PROMPT_FILE"
370 else
371 echo "Review generation successfully completed"
372 fi
373
374 - name: Upload Review Results
375 if: env.SHOULD_RUN == 'true' && always()
376 uses: actions/upload-artifact@v4
377 with:
378 name: code-review-results
379 path: |
380 code_review.md
381 review_prompt.txt
382 pr_diff.txt
383 retention-days: 30
384
385 - name: Update Comment with Review
386 if: env.SHOULD_RUN == 'true' && always()
387 uses: actions/github-script@v7
388 with:
389 script: |
390 const fs = require('fs');
391
392 try {
393 let reviewContent = '';
394
395 if (fs.existsSync('code_review.md') && fs.statSync('code_review.md').size > 0) {
396 reviewContent = fs.readFileSync('code_review.md', 'utf8');
397 } else {
398 // Build direct link to workflow logs
399 const workflowRunUrl = `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;
400 reviewContent = `⚠️ AI review completed but no review output was generated.\n\n**Likely cause:** Expired CONTINUE_API_KEY or missing continuedev/review-bot assistant\n\n[📋 View workflow logs](${workflowRunUrl}) for details.`;
401 }
402
403 // Get PR number based on event type
404 let prNumber;
405 if (context.eventName === 'pull_request') {
406 prNumber = context.payload.pull_request.number;
407 } else {
408 // For issue_comment event
409 prNumber = context.payload.issue.number;
410 }
411
412 // Add a header if triggered by comment
413 if (context.eventName === 'issue_comment') {
414 reviewContent = `*Triggered by @${context.payload.comment.user.login}'s request*\n\n${reviewContent}`;
415 }
416
417 // Add footer with timestamp and branding
418 const timestamp = new Date().toISOString();
419 reviewContent += `\n\n---\n<!-- ${timestamp} | Powered by Continue (https://continue.dev) -->`;
420
421 // Look for existing review comment to update (sticky comment)
422 const marker = '<!-- continue-agent-review -->';
423
424 // Try to get comment_id from the initial comment step
425 const initialCommentId = '${{ steps.initial-comment.outputs.comment_id }}';
426
427 if (initialCommentId && initialCommentId !== '') {
428 // We have the comment ID from the initial step, use it directly
429 reviewContent = `${marker}\n**✅ Review Complete**\n\n${reviewContent}`;
430
431 try {
432 await github.rest.issues.updateComment({
433 owner: context.repo.owner,
434 repo: context.repo.repo,
435 comment_id: parseInt(initialCommentId),
436 body: reviewContent
437 });
438 console.log(`Updated comment ${initialCommentId} with review results`);
439 } catch (updateError) {
440 console.log(`Failed to update comment ${initialCommentId}, will search for it instead:`, updateError.message);
441
442 // Fallback: search for the comment
443 const { data: comments } = await github.rest.issues.listComments({
444 owner: context.repo.owner,
445 repo: context.repo.repo,
446 issue_number: prNumber,
447 per_page: 100
448 });
449
450 // Find existing Continue review comment
451 const existingComment = comments
452 .filter(c => c.body && c.body.includes(marker))
453 .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0];
454
455 if (existingComment) {
456 await github.rest.issues.updateComment({
457 owner: context.repo.owner,
458 repo: context.repo.repo,
459 comment_id: existingComment.id,
460 body: reviewContent
461 });
462 console.log(`Updated existing comment ${existingComment.id} via search`);
463 } else {
464 // Create new comment as last resort
465 await github.rest.issues.createComment({
466 issue_number: prNumber,
467 owner: context.repo.owner,
468 repo: context.repo.repo,
469 body: reviewContent
470 });
471 console.log(`Created new comment on PR #${prNumber} as fallback`);
472 }
473 }
474 } else {
475 // No initial comment ID, search for existing comment
476 const { data: comments } = await github.rest.issues.listComments({
477 owner: context.repo.owner,
478 repo: context.repo.repo,
479 issue_number: prNumber,
480 per_page: 100
481 });
482
483 // Find existing Continue review comment
484 const existingComment = comments
485 .filter(c => c.body && c.body.includes(marker))
486 .sort((a, b) => new Date(b.created_at).getTime() - new Date(a.created_at).getTime())[0];
487
488 // Add marker and review status
489 reviewContent = `${marker}\n**✅ Review Complete**\n\n${reviewContent}`;
490
491 if (existingComment) {
492 // Check if comment is less than 1 hour old
493 const commentAge = Date.now() - new Date(existingComment.created_at).getTime();
494 const oneHour = 60 * 60 * 1000;
495
496 if (commentAge < oneHour) {
497 // Update existing comment if less than 1 hour old
498 await github.rest.issues.updateComment({
499 owner: context.repo.owner,
500 repo: context.repo.repo,
501 comment_id: existingComment.id,
502 body: reviewContent
503 });
504 console.log(`Updated existing comment ${existingComment.id} (${Math.round(commentAge / 1000 / 60)} minutes old)`);
505 } else {
506 // Create new comment if older than 1 hour (preserve history)
507 await github.rest.issues.createComment({
508 issue_number: prNumber,
509 owner: context.repo.owner,
510 repo: context.repo.repo,
511 body: reviewContent
512 });
513 console.log(`Created new comment (existing comment was ${Math.round(commentAge / 1000 / 60)} minutes old)`);
514 }
515 } else {
516 // Create new comment
517 await github.rest.issues.createComment({
518 issue_number: prNumber,
519 owner: context.repo.owner,
520 repo: context.repo.repo,
521 body: reviewContent
522 });
523 console.log(`Created new comment on PR #${prNumber}`);
524 }
525 }
526 } catch (error) {
527 console.log('Failed to post comment:', error.message);
528 console.log('Error details:', error);
529 }
530
531branding:
532 icon: "code"
533 color: "blue"