mirror of
https://github.com/anthropics/claude-code-action.git
synced 2026-01-23 15:04:13 +08:00
Compare commits
39 Commits
ashwin/tes
...
ashwin/ver
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6147037db9 | ||
|
|
194fca8b05 | ||
|
|
0f913a6e0e | ||
|
|
68b7ca379c | ||
|
|
900322ca88 | ||
|
|
8f0a7fe9d3 | ||
|
|
db36412854 | ||
|
|
f05d669d5f | ||
|
|
e89411bb6f | ||
|
|
02e9ed3181 | ||
|
|
78b07473f5 | ||
|
|
f562ed53e2 | ||
|
|
a1507aefdc | ||
|
|
ae66eb6a64 | ||
|
|
432c7cc889 | ||
|
|
0b138d9d49 | ||
|
|
c34e066a3b | ||
|
|
449c6791bd | ||
|
|
2b67ac084b | ||
|
|
76de8a48fc | ||
|
|
a80505bbfb | ||
|
|
af23644a50 | ||
|
|
98e6a902bf | ||
|
|
8b2bd6d04f | ||
|
|
4f4f43f044 | ||
|
|
8a5d751740 | ||
|
|
bc423b47f5 | ||
|
|
6d5c92076b | ||
|
|
fec554fc7c | ||
|
|
59ca6e42d9 | ||
|
|
7afc848186 | ||
|
|
6debac392b | ||
|
|
55fb6a96d0 | ||
|
|
15db2b3c79 | ||
|
|
188d526721 | ||
|
|
a519840051 | ||
|
|
85287e957d | ||
|
|
c6a07895d7 | ||
|
|
0c5d54472f |
2
.github/workflows/claude.yml
vendored
2
.github/workflows/claude.yml
vendored
@@ -36,4 +36,4 @@ jobs:
|
|||||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||||
allowed_tools: "Bash(bun install),Bash(bun test:*),Bash(bun run format),Bash(bun typecheck)"
|
allowed_tools: "Bash(bun install),Bash(bun test:*),Bash(bun run format),Bash(bun typecheck)"
|
||||||
custom_instructions: "You have also been granted tools for editing files and running bun commands (install, run, test, typecheck) for testing your changes: bun install, bun test, bun run format, bun typecheck."
|
custom_instructions: "You have also been granted tools for editing files and running bun commands (install, run, test, typecheck) for testing your changes: bun install, bun test, bun run format, bun typecheck."
|
||||||
model: "claude-opus-4-20250514"
|
model: "claude-opus-4-1-20250805"
|
||||||
|
|||||||
2
.github/workflows/issue-triage.yml
vendored
2
.github/workflows/issue-triage.yml
vendored
@@ -104,3 +104,5 @@ jobs:
|
|||||||
mcp_config: /tmp/mcp-config/mcp-servers.json
|
mcp_config: /tmp/mcp-config/mcp-servers.json
|
||||||
timeout_minutes: "5"
|
timeout_minutes: "5"
|
||||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
|||||||
13
README.md
13
README.md
@@ -14,6 +14,19 @@ A general-purpose [Claude Code](https://claude.ai/code) action for GitHub PRs an
|
|||||||
- 📋 **Progress Tracking**: Visual progress indicators with checkboxes that dynamically update as Claude completes tasks
|
- 📋 **Progress Tracking**: Visual progress indicators with checkboxes that dynamically update as Claude completes tasks
|
||||||
- 🏃 **Runs on Your Infrastructure**: The action executes entirely on your own GitHub runner (Anthropic API calls go to your chosen provider)
|
- 🏃 **Runs on Your Infrastructure**: The action executes entirely on your own GitHub runner (Anthropic API calls go to your chosen provider)
|
||||||
|
|
||||||
|
## ⚠️ **BREAKING CHANGES COMING IN v1.0** ⚠️
|
||||||
|
|
||||||
|
**We're planning a major update that will significantly change how this action works.** The new version will:
|
||||||
|
|
||||||
|
- ✨ Automatically select the appropriate mode (no more `mode` input)
|
||||||
|
- 🔧 Simplify configuration with unified `prompt` and `claude_args`
|
||||||
|
- 🚀 Align more closely with the Claude Code SDK capabilities
|
||||||
|
- 💥 Remove multiple inputs like `direct_prompt`, `custom_instructions`, and others
|
||||||
|
|
||||||
|
**[→ Read the full v1.0 roadmap and provide feedback](https://github.com/anthropics/claude-code-action/discussions/428)**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Quickstart
|
## Quickstart
|
||||||
|
|
||||||
The easiest way to set up this action is through [Claude Code](https://claude.ai/code) in the terminal. Just open `claude` and run `/install-github-app`.
|
The easiest way to set up this action is through [Claude Code](https://claude.ai/code) in the terminal. Just open `claude` and run `/install-github-app`.
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ Thank you for trying out the beta of our GitHub Action! This document outlines o
|
|||||||
- **Support for workflow_dispatch and repository_dispatch events** - Dispatch Claude on events triggered via API from other workflows or from other services
|
- **Support for workflow_dispatch and repository_dispatch events** - Dispatch Claude on events triggered via API from other workflows or from other services
|
||||||
- **Ability to disable commit signing** - Option to turn off GPG signing for environments where it's not required. This will enable Claude to use normal `git` bash commands for committing. This will likely become the default behavior once added.
|
- **Ability to disable commit signing** - Option to turn off GPG signing for environments where it's not required. This will enable Claude to use normal `git` bash commands for committing. This will likely become the default behavior once added.
|
||||||
- **Better code review behavior** - Support inline comments on specific lines, provide higher quality reviews with more actionable feedback
|
- **Better code review behavior** - Support inline comments on specific lines, provide higher quality reviews with more actionable feedback
|
||||||
- **Support triggering @claude from bot users** - Allow automation and bot accounts to invoke Claude
|
- ~**Support triggering @claude from bot users** - Allow automation and bot accounts to invoke Claude~
|
||||||
- **Customizable base prompts** - Full control over Claude's initial context with template variables like `$PR_COMMENTS`, `$PR_FILES`, etc. Users can replace our default prompt entirely while still accessing key contextual data
|
- **Customizable base prompts** - Full control over Claude's initial context with template variables like `$PR_COMMENTS`, `$PR_FILES`, etc. Users can replace our default prompt entirely while still accessing key contextual data
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
12
action.yml
12
action.yml
@@ -23,6 +23,10 @@ inputs:
|
|||||||
description: "The prefix to use for Claude branches (defaults to 'claude/', use 'claude-' for dash format)"
|
description: "The prefix to use for Claude branches (defaults to 'claude/', use 'claude-' for dash format)"
|
||||||
required: false
|
required: false
|
||||||
default: "claude/"
|
default: "claude/"
|
||||||
|
allowed_bots:
|
||||||
|
description: "Comma-separated list of allowed bot usernames, or '*' to allow all bots. Empty string (default) allows no bots."
|
||||||
|
required: false
|
||||||
|
default: ""
|
||||||
|
|
||||||
# Mode configuration
|
# Mode configuration
|
||||||
mode:
|
mode:
|
||||||
@@ -156,11 +160,13 @@ runs:
|
|||||||
OVERRIDE_PROMPT: ${{ inputs.override_prompt }}
|
OVERRIDE_PROMPT: ${{ inputs.override_prompt }}
|
||||||
MCP_CONFIG: ${{ inputs.mcp_config }}
|
MCP_CONFIG: ${{ inputs.mcp_config }}
|
||||||
OVERRIDE_GITHUB_TOKEN: ${{ inputs.github_token }}
|
OVERRIDE_GITHUB_TOKEN: ${{ inputs.github_token }}
|
||||||
|
ALLOWED_BOTS: ${{ inputs.allowed_bots }}
|
||||||
GITHUB_RUN_ID: ${{ github.run_id }}
|
GITHUB_RUN_ID: ${{ github.run_id }}
|
||||||
USE_STICKY_COMMENT: ${{ inputs.use_sticky_comment }}
|
USE_STICKY_COMMENT: ${{ inputs.use_sticky_comment }}
|
||||||
DEFAULT_WORKFLOW_TOKEN: ${{ github.token }}
|
DEFAULT_WORKFLOW_TOKEN: ${{ github.token }}
|
||||||
ADDITIONAL_PERMISSIONS: ${{ inputs.additional_permissions }}
|
ADDITIONAL_PERMISSIONS: ${{ inputs.additional_permissions }}
|
||||||
USE_COMMIT_SIGNING: ${{ inputs.use_commit_signing }}
|
USE_COMMIT_SIGNING: ${{ inputs.use_commit_signing }}
|
||||||
|
ALL_INPUTS: ${{ toJson(inputs) }}
|
||||||
|
|
||||||
- name: Install Base Action Dependencies
|
- name: Install Base Action Dependencies
|
||||||
if: steps.prepare.outputs.contains_trigger == 'true'
|
if: steps.prepare.outputs.contains_trigger == 'true'
|
||||||
@@ -172,7 +178,8 @@ runs:
|
|||||||
echo "Base-action dependencies installed"
|
echo "Base-action dependencies installed"
|
||||||
cd -
|
cd -
|
||||||
# Install Claude Code globally
|
# Install Claude Code globally
|
||||||
bun install -g @anthropic-ai/claude-code@1.0.68
|
curl -fsSL https://claude.ai/install.sh | bash -s 1.0.85
|
||||||
|
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
|
||||||
|
|
||||||
- name: Setup Network Restrictions
|
- name: Setup Network Restrictions
|
||||||
if: steps.prepare.outputs.contains_trigger == 'true' && inputs.experimental_allowed_domains != ''
|
if: steps.prepare.outputs.contains_trigger == 'true' && inputs.experimental_allowed_domains != ''
|
||||||
@@ -206,6 +213,7 @@ runs:
|
|||||||
INPUT_CLAUDE_ENV: ${{ inputs.claude_env }}
|
INPUT_CLAUDE_ENV: ${{ inputs.claude_env }}
|
||||||
INPUT_FALLBACK_MODEL: ${{ inputs.fallback_model }}
|
INPUT_FALLBACK_MODEL: ${{ inputs.fallback_model }}
|
||||||
INPUT_EXPERIMENTAL_SLASH_COMMANDS_DIR: ${{ github.action_path }}/slash-commands
|
INPUT_EXPERIMENTAL_SLASH_COMMANDS_DIR: ${{ github.action_path }}/slash-commands
|
||||||
|
INPUT_ACTION_INPUTS_PRESENT: ${{ steps.prepare.outputs.action_inputs_present }}
|
||||||
|
|
||||||
# Model configuration
|
# Model configuration
|
||||||
ANTHROPIC_MODEL: ${{ inputs.model || inputs.anthropic_model }}
|
ANTHROPIC_MODEL: ${{ inputs.model || inputs.anthropic_model }}
|
||||||
@@ -280,7 +288,7 @@ runs:
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
- name: Revoke app token
|
- name: Revoke app token
|
||||||
if: always() && inputs.github_token == ''
|
if: always() && inputs.github_token == '' && steps.prepare.outputs.skipped_due_to_workflow_validation_mismatch != 'true'
|
||||||
shell: bash
|
shell: bash
|
||||||
run: |
|
run: |
|
||||||
curl -L \
|
curl -L \
|
||||||
|
|||||||
@@ -69,7 +69,7 @@ Add the following to your workflow file:
|
|||||||
uses: anthropics/claude-code-base-action@beta
|
uses: anthropics/claude-code-base-action@beta
|
||||||
with:
|
with:
|
||||||
prompt: "Review and fix TypeScript errors"
|
prompt: "Review and fix TypeScript errors"
|
||||||
model: "claude-opus-4-20250514"
|
model: "claude-opus-4-1-20250805"
|
||||||
fallback_model: "claude-sonnet-4-20250514"
|
fallback_model: "claude-sonnet-4-20250514"
|
||||||
allowed_tools: "Bash(git:*),View,GlobTool,GrepTool,BatchTool"
|
allowed_tools: "Bash(git:*),View,GlobTool,GrepTool,BatchTool"
|
||||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||||
@@ -217,7 +217,7 @@ Provide the settings configuration directly as a JSON string:
|
|||||||
prompt: "Your prompt here"
|
prompt: "Your prompt here"
|
||||||
settings: |
|
settings: |
|
||||||
{
|
{
|
||||||
"model": "claude-opus-4-20250514",
|
"model": "claude-opus-4-1-20250805",
|
||||||
"env": {
|
"env": {
|
||||||
"DEBUG": "true",
|
"DEBUG": "true",
|
||||||
"API_URL": "https://api.example.com"
|
"API_URL": "https://api.example.com"
|
||||||
|
|||||||
@@ -118,7 +118,7 @@ runs:
|
|||||||
|
|
||||||
- name: Install Claude Code
|
- name: Install Claude Code
|
||||||
shell: bash
|
shell: bash
|
||||||
run: bun install -g @anthropic-ai/claude-code@1.0.68
|
run: curl -fsSL https://claude.ai/install.sh | bash -s 1.0.85
|
||||||
|
|
||||||
- name: Run Claude Code Action
|
- name: Run Claude Code Action
|
||||||
shell: bash
|
shell: bash
|
||||||
|
|||||||
@@ -110,6 +110,10 @@ export function prepareRunConfig(
|
|||||||
// Parse custom environment variables
|
// Parse custom environment variables
|
||||||
const customEnv = parseCustomEnvVars(options.claudeEnv);
|
const customEnv = parseCustomEnvVars(options.claudeEnv);
|
||||||
|
|
||||||
|
if (process.env.INPUT_ACTION_INPUTS_PRESENT) {
|
||||||
|
customEnv.GITHUB_ACTION_INPUTS = process.env.INPUT_ACTION_INPUTS_PRESENT;
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
claudeArgs,
|
claudeArgs,
|
||||||
promptPath,
|
promptPath,
|
||||||
@@ -142,9 +146,11 @@ export async function runClaude(promptPath: string, options: ClaudeOptions) {
|
|||||||
console.log(`Prompt file size: ${promptSize} bytes`);
|
console.log(`Prompt file size: ${promptSize} bytes`);
|
||||||
|
|
||||||
// Log custom environment variables if any
|
// Log custom environment variables if any
|
||||||
if (Object.keys(config.env).length > 0) {
|
const customEnvKeys = Object.keys(config.env).filter(
|
||||||
const envKeys = Object.keys(config.env).join(", ");
|
(key) => key !== "CLAUDE_ACTION_INPUTS_PRESENT",
|
||||||
console.log(`Custom environment variables: ${envKeys}`);
|
);
|
||||||
|
if (customEnvKeys.length > 0) {
|
||||||
|
console.log(`Custom environment variables: ${customEnvKeys.join(", ")}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Output to console
|
// Output to console
|
||||||
|
|||||||
@@ -134,7 +134,7 @@ describe("setupClaudeCodeSettings", () => {
|
|||||||
// Then, add new settings
|
// Then, add new settings
|
||||||
const newSettings = JSON.stringify({
|
const newSettings = JSON.stringify({
|
||||||
newKey: "newValue",
|
newKey: "newValue",
|
||||||
model: "claude-opus-4-20250514",
|
model: "claude-opus-4-1-20250805",
|
||||||
});
|
});
|
||||||
|
|
||||||
await setupClaudeCodeSettings(newSettings, testHomeDir);
|
await setupClaudeCodeSettings(newSettings, testHomeDir);
|
||||||
@@ -145,7 +145,7 @@ describe("setupClaudeCodeSettings", () => {
|
|||||||
expect(settings.enableAllProjectMcpServers).toBe(true);
|
expect(settings.enableAllProjectMcpServers).toBe(true);
|
||||||
expect(settings.existingKey).toBe("existingValue");
|
expect(settings.existingKey).toBe("existingValue");
|
||||||
expect(settings.newKey).toBe("newValue");
|
expect(settings.newKey).toBe("newValue");
|
||||||
expect(settings.model).toBe("claude-opus-4-20250514");
|
expect(settings.model).toBe("claude-opus-4-1-20250805");
|
||||||
});
|
});
|
||||||
|
|
||||||
test("should copy slash commands to .claude directory when path provided", async () => {
|
test("should copy slash commands to .claude directory when path provided", async () => {
|
||||||
|
|||||||
@@ -207,15 +207,8 @@ Claude does **not** have access to execute arbitrary Bash commands by default. I
|
|||||||
```yaml
|
```yaml
|
||||||
- uses: anthropics/claude-code-action@beta
|
- uses: anthropics/claude-code-action@beta
|
||||||
with:
|
with:
|
||||||
allowed_tools: |
|
allowed_tools: "Bash(npm install),Bash(npm run test),Edit,Replace,NotebookEditCell"
|
||||||
Bash(npm install)
|
disallowed_tools: "TaskOutput,KillTask"
|
||||||
Bash(npm run test)
|
|
||||||
Edit
|
|
||||||
Replace
|
|
||||||
NotebookEditCell
|
|
||||||
disallowed_tools: |
|
|
||||||
TaskOutput
|
|
||||||
KillTask
|
|
||||||
# ... other inputs
|
# ... other inputs
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -252,7 +245,7 @@ You can provide Claude Code settings to customize behavior such as model selecti
|
|||||||
with:
|
with:
|
||||||
settings: |
|
settings: |
|
||||||
{
|
{
|
||||||
"model": "claude-opus-4-20250514",
|
"model": "claude-opus-4-1-20250805",
|
||||||
"env": {
|
"env": {
|
||||||
"DEBUG": "true",
|
"DEBUG": "true",
|
||||||
"API_URL": "https://api.example.com"
|
"API_URL": "https://api.example.com"
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
## Access Control
|
## Access Control
|
||||||
|
|
||||||
- **Repository Access**: The action can only be triggered by users with write access to the repository
|
- **Repository Access**: The action can only be triggered by users with write access to the repository
|
||||||
- **No Bot Triggers**: GitHub Apps and bots cannot trigger this action
|
- **Bot User Control**: By default, GitHub Apps and bots cannot trigger this action for security reasons. Use the `allowed_bots` parameter to enable specific bots or all bots
|
||||||
- **Token Permissions**: The GitHub app receives only a short-lived token scoped specifically to the repository it's operating in
|
- **Token Permissions**: The GitHub app receives only a short-lived token scoped specifically to the repository it's operating in
|
||||||
- **No Cross-Repository Access**: Each action invocation is limited to the repository where it was triggered
|
- **No Cross-Repository Access**: Each action invocation is limited to the repository where it was triggered
|
||||||
- **Limited Scope**: The token cannot access other repositories or perform actions beyond the configured permissions
|
- **Limited Scope**: The token cannot access other repositories or perform actions beyond the configured permissions
|
||||||
|
|||||||
@@ -42,6 +42,8 @@ jobs:
|
|||||||
# Optional: grant additional permissions (requires corresponding GitHub token permissions)
|
# Optional: grant additional permissions (requires corresponding GitHub token permissions)
|
||||||
# additional_permissions: |
|
# additional_permissions: |
|
||||||
# actions: read
|
# actions: read
|
||||||
|
# Optional: allow bot users to trigger the action
|
||||||
|
# allowed_bots: "dependabot[bot],renovate[bot]"
|
||||||
```
|
```
|
||||||
|
|
||||||
## Inputs
|
## Inputs
|
||||||
@@ -76,6 +78,7 @@ jobs:
|
|||||||
| `additional_permissions` | Additional permissions to enable. Currently supports 'actions: read' for viewing workflow results | No | "" |
|
| `additional_permissions` | Additional permissions to enable. Currently supports 'actions: read' for viewing workflow results | No | "" |
|
||||||
| `experimental_allowed_domains` | Restrict network access to these domains only (newline-separated). | No | "" |
|
| `experimental_allowed_domains` | Restrict network access to these domains only (newline-separated). | No | "" |
|
||||||
| `use_commit_signing` | Enable commit signing using GitHub's commit signature verification. When false, Claude uses standard git commands | No | `false` |
|
| `use_commit_signing` | Enable commit signing using GitHub's commit signature verification. When false, Claude uses standard git commands | No | `false` |
|
||||||
|
| `allowed_bots` | Comma-separated list of allowed bot usernames, or '\*' to allow all bots. Empty string (default) allows no bots | No | "" |
|
||||||
|
|
||||||
\*Required when using direct Anthropic API (default and when not using Bedrock or Vertex)
|
\*Required when using direct Anthropic API (default and when not using Bedrock or Vertex)
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
name: Claude PR Assistant
|
name: Claude Code
|
||||||
|
|
||||||
on:
|
on:
|
||||||
issue_comment:
|
issue_comment:
|
||||||
@@ -11,38 +11,53 @@ on:
|
|||||||
types: [submitted]
|
types: [submitted]
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
claude-code-action:
|
claude:
|
||||||
if: |
|
if: |
|
||||||
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
|
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
|
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
|
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
|
||||||
(github.event_name == 'issues' && contains(github.event.issue.body, '@claude'))
|
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: write
|
||||||
pull-requests: read
|
pull-requests: write
|
||||||
issues: read
|
issues: write
|
||||||
id-token: write
|
id-token: write
|
||||||
|
actions: read # Required for Claude to read CI results on PRs
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
fetch-depth: 1
|
fetch-depth: 1
|
||||||
|
|
||||||
- name: Run Claude PR Action
|
- name: Run Claude Code
|
||||||
|
id: claude
|
||||||
uses: anthropics/claude-code-action@beta
|
uses: anthropics/claude-code-action@beta
|
||||||
with:
|
with:
|
||||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||||
# Or use OAuth token instead:
|
|
||||||
# claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
# This is an optional setting that allows Claude to read CI results on PRs
|
||||||
timeout_minutes: "60"
|
additional_permissions: |
|
||||||
# mode: tag # Default: responds to @claude mentions
|
actions: read
|
||||||
# Optional: Restrict network access to specific domains only
|
|
||||||
# experimental_allowed_domains: |
|
# Optional: Specify model (defaults to Claude Sonnet 4, uncomment for Claude Opus 4.1)
|
||||||
# .anthropic.com
|
# model: "claude-opus-4-1-20250805"
|
||||||
# .github.com
|
|
||||||
# api.github.com
|
# Optional: Customize the trigger phrase (default: @claude)
|
||||||
# .githubusercontent.com
|
# trigger_phrase: "/claude"
|
||||||
# bun.sh
|
|
||||||
# registry.npmjs.org
|
# Optional: Trigger when specific user is assigned to an issue
|
||||||
# .blob.core.windows.net
|
# assignee_trigger: "claude-bot"
|
||||||
|
|
||||||
|
# Optional: Allow Claude to run specific commands
|
||||||
|
# allowed_tools: "Bash(npm install),Bash(npm run build),Bash(npm run test:*),Bash(npm run lint:*)"
|
||||||
|
|
||||||
|
# Optional: Add custom instructions for Claude to customize its behavior for your project
|
||||||
|
# custom_instructions: |
|
||||||
|
# Follow our coding standards
|
||||||
|
# Ensure all new code has tests
|
||||||
|
# Use TypeScript for new files
|
||||||
|
|
||||||
|
# Optional: Custom environment variables for Claude
|
||||||
|
# claude_env: |
|
||||||
|
# NODE_ENV: test
|
||||||
|
|||||||
@@ -6,8 +6,8 @@ echo "Installing git hooks..."
|
|||||||
# Make sure hooks directory exists
|
# Make sure hooks directory exists
|
||||||
mkdir -p .git/hooks
|
mkdir -p .git/hooks
|
||||||
|
|
||||||
# Install pre-push hook
|
# Install pre-commit hook
|
||||||
cp scripts/pre-push .git/hooks/pre-push
|
cp scripts/pre-commit .git/hooks/pre-commit
|
||||||
chmod +x .git/hooks/pre-push
|
chmod +x .git/hooks/pre-commit
|
||||||
|
|
||||||
echo "Git hooks installed successfully!"
|
echo "Git hooks installed successfully!"
|
||||||
@@ -60,8 +60,6 @@ export function buildAllowedToolsString(
|
|||||||
"Bash(git diff:*)",
|
"Bash(git diff:*)",
|
||||||
"Bash(git log:*)",
|
"Bash(git log:*)",
|
||||||
"Bash(git rm:*)",
|
"Bash(git rm:*)",
|
||||||
"Bash(git config user.name:*)",
|
|
||||||
"Bash(git config user.email:*)",
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -838,7 +836,7 @@ export async function createPrompt(
|
|||||||
modeContext.claudeBranch,
|
modeContext.claudeBranch,
|
||||||
);
|
);
|
||||||
|
|
||||||
await mkdir(`${process.env.RUNNER_TEMP}/claude-prompts`, {
|
await mkdir(`${process.env.RUNNER_TEMP || "/tmp"}/claude-prompts`, {
|
||||||
recursive: true,
|
recursive: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -857,7 +855,7 @@ export async function createPrompt(
|
|||||||
|
|
||||||
// Write the prompt file
|
// Write the prompt file
|
||||||
await writeFile(
|
await writeFile(
|
||||||
`${process.env.RUNNER_TEMP}/claude-prompts/claude-prompt.txt`,
|
`${process.env.RUNNER_TEMP || "/tmp"}/claude-prompts/claude-prompt.txt`,
|
||||||
promptContent,
|
promptContent,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
59
src/entrypoints/collect-inputs.ts
Normal file
59
src/entrypoints/collect-inputs.ts
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
import * as core from "@actions/core";
|
||||||
|
|
||||||
|
export function collectActionInputsPresence(): void {
|
||||||
|
const inputDefaults: Record<string, string> = {
|
||||||
|
trigger_phrase: "@claude",
|
||||||
|
assignee_trigger: "",
|
||||||
|
label_trigger: "claude",
|
||||||
|
base_branch: "",
|
||||||
|
branch_prefix: "claude/",
|
||||||
|
allowed_bots: "",
|
||||||
|
mode: "tag",
|
||||||
|
model: "",
|
||||||
|
anthropic_model: "",
|
||||||
|
fallback_model: "",
|
||||||
|
allowed_tools: "",
|
||||||
|
disallowed_tools: "",
|
||||||
|
custom_instructions: "",
|
||||||
|
direct_prompt: "",
|
||||||
|
override_prompt: "",
|
||||||
|
mcp_config: "",
|
||||||
|
additional_permissions: "",
|
||||||
|
claude_env: "",
|
||||||
|
settings: "",
|
||||||
|
anthropic_api_key: "",
|
||||||
|
claude_code_oauth_token: "",
|
||||||
|
github_token: "",
|
||||||
|
max_turns: "",
|
||||||
|
use_sticky_comment: "false",
|
||||||
|
use_commit_signing: "false",
|
||||||
|
experimental_allowed_domains: "",
|
||||||
|
};
|
||||||
|
|
||||||
|
const allInputsJson = process.env.ALL_INPUTS;
|
||||||
|
if (!allInputsJson) {
|
||||||
|
console.log("ALL_INPUTS environment variable not found");
|
||||||
|
core.setOutput("action_inputs_present", JSON.stringify({}));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let allInputs: Record<string, string>;
|
||||||
|
try {
|
||||||
|
allInputs = JSON.parse(allInputsJson);
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Failed to parse ALL_INPUTS JSON:", e);
|
||||||
|
core.setOutput("action_inputs_present", JSON.stringify({}));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const presentInputs: Record<string, boolean> = {};
|
||||||
|
|
||||||
|
for (const [name, defaultValue] of Object.entries(inputDefaults)) {
|
||||||
|
const actualValue = allInputs[name] || "";
|
||||||
|
|
||||||
|
const isSet = actualValue !== defaultValue;
|
||||||
|
presentInputs[name] = isSet;
|
||||||
|
}
|
||||||
|
|
||||||
|
core.setOutput("action_inputs_present", JSON.stringify(presentInputs));
|
||||||
|
}
|
||||||
@@ -13,9 +13,12 @@ import { parseGitHubContext, isEntityContext } from "../github/context";
|
|||||||
import { getMode, isValidMode, DEFAULT_MODE } from "../modes/registry";
|
import { getMode, isValidMode, DEFAULT_MODE } from "../modes/registry";
|
||||||
import type { ModeName } from "../modes/types";
|
import type { ModeName } from "../modes/types";
|
||||||
import { prepare } from "../prepare";
|
import { prepare } from "../prepare";
|
||||||
|
import { collectActionInputsPresence } from "./collect-inputs";
|
||||||
|
|
||||||
async function run() {
|
async function run() {
|
||||||
try {
|
try {
|
||||||
|
collectActionInputsPresence();
|
||||||
|
|
||||||
// Step 1: Get mode first to determine authentication method
|
// Step 1: Get mode first to determine authentication method
|
||||||
const modeInput = process.env.MODE || DEFAULT_MODE;
|
const modeInput = process.env.MODE || DEFAULT_MODE;
|
||||||
|
|
||||||
|
|||||||
@@ -77,6 +77,7 @@ type BaseContext = {
|
|||||||
useStickyComment: boolean;
|
useStickyComment: boolean;
|
||||||
additionalPermissions: Map<string, string>;
|
additionalPermissions: Map<string, string>;
|
||||||
useCommitSigning: boolean;
|
useCommitSigning: boolean;
|
||||||
|
allowedBots: string;
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -136,6 +137,7 @@ export function parseGitHubContext(): GitHubContext {
|
|||||||
process.env.ADDITIONAL_PERMISSIONS ?? "",
|
process.env.ADDITIONAL_PERMISSIONS ?? "",
|
||||||
),
|
),
|
||||||
useCommitSigning: process.env.USE_COMMIT_SIGNING === "true",
|
useCommitSigning: process.env.USE_COMMIT_SIGNING === "true",
|
||||||
|
allowedBots: process.env.ALLOWED_BOTS ?? "",
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ export async function configureGitAuth(
|
|||||||
if (user) {
|
if (user) {
|
||||||
const botName = user.login;
|
const botName = user.login;
|
||||||
const botId = user.id;
|
const botId = user.id;
|
||||||
console.log(`Setting git user as ${botName} (id: ${botId})...`);
|
console.log(`Setting git user as ${botName}...`);
|
||||||
await $`git config user.name "${botName}"`;
|
await $`git config user.name "${botName}"`;
|
||||||
await $`git config user.email "${botId}+${botName}@${noreplyDomain}"`;
|
await $`git config user.email "${botId}+${botName}@${noreplyDomain}"`;
|
||||||
console.log(`✓ Set git user as ${botName}`);
|
console.log(`✓ Set git user as ${botName}`);
|
||||||
|
|||||||
@@ -31,8 +31,30 @@ async function exchangeForAppToken(oidcToken: string): Promise<string> {
|
|||||||
const responseJson = (await response.json()) as {
|
const responseJson = (await response.json()) as {
|
||||||
error?: {
|
error?: {
|
||||||
message?: string;
|
message?: string;
|
||||||
|
details?: {
|
||||||
|
error_code?: string;
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
type?: string;
|
||||||
|
message?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Check for specific workflow validation error codes that should skip the action
|
||||||
|
const errorCode = responseJson.error?.details?.error_code;
|
||||||
|
|
||||||
|
if (errorCode === "workflow_not_found_on_default_branch") {
|
||||||
|
const message =
|
||||||
|
responseJson.message ??
|
||||||
|
responseJson.error?.message ??
|
||||||
|
"Workflow validation failed";
|
||||||
|
core.warning(`Skipping action due to workflow validation: ${message}`);
|
||||||
|
console.log(
|
||||||
|
"Action skipped due to workflow validation error. This is expected when adding Claude Code workflows to new repositories or on PRs with workflow changes. If you're seeing this, your workflow will begin working once you merge your PR.",
|
||||||
|
);
|
||||||
|
core.setOutput("skipped_due_to_workflow_validation_mismatch", "true");
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
console.error(
|
console.error(
|
||||||
`App token exchange failed: ${response.status} ${response.statusText} - ${responseJson?.error?.message ?? "Unknown error"}`,
|
`App token exchange failed: ${response.status} ${response.statusText} - ${responseJson?.error?.message ?? "Unknown error"}`,
|
||||||
);
|
);
|
||||||
@@ -77,8 +99,9 @@ export async function setupGitHubToken(): Promise<string> {
|
|||||||
core.setOutput("GITHUB_TOKEN", appToken);
|
core.setOutput("GITHUB_TOKEN", appToken);
|
||||||
return appToken;
|
return appToken;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
// Only set failed if we get here - workflow validation errors will exit(0) before this
|
||||||
core.setFailed(
|
core.setFailed(
|
||||||
`Failed to setup GitHub token: ${error}.\n\nIf you instead wish to use this action with a custom GitHub token or custom GitHub app, provide a \`github_token\` in the \`uses\` section of the app in your workflow yml file.`,
|
`Failed to setup GitHub token: ${error}\n\nIf you instead wish to use this action with a custom GitHub token or custom GitHub app, provide a \`github_token\` in the \`uses\` section of the app in your workflow yml file.`,
|
||||||
);
|
);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,11 +3,17 @@ import path from "path";
|
|||||||
import type { Octokits } from "../api/client";
|
import type { Octokits } from "../api/client";
|
||||||
import { GITHUB_SERVER_URL } from "../api/config";
|
import { GITHUB_SERVER_URL } from "../api/config";
|
||||||
|
|
||||||
|
const escapedUrl = GITHUB_SERVER_URL.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||||
const IMAGE_REGEX = new RegExp(
|
const IMAGE_REGEX = new RegExp(
|
||||||
`!\\[[^\\]]*\\]\\((${GITHUB_SERVER_URL.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\/user-attachments\\/assets\\/[^)]+)\\)`,
|
`!\\[[^\\]]*\\]\\((${escapedUrl}\\/user-attachments\\/assets\\/[^)]+)\\)`,
|
||||||
"g",
|
"g",
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const HTML_IMG_REGEX = new RegExp(
|
||||||
|
`<img[^>]+src=["']([^"']*${escapedUrl}\\/user-attachments\\/assets\\/[^"']+)["'][^>]*>`,
|
||||||
|
"gi",
|
||||||
|
);
|
||||||
|
|
||||||
type IssueComment = {
|
type IssueComment = {
|
||||||
type: "issue_comment";
|
type: "issue_comment";
|
||||||
id: string;
|
id: string;
|
||||||
@@ -63,8 +69,16 @@ export async function downloadCommentImages(
|
|||||||
}> = [];
|
}> = [];
|
||||||
|
|
||||||
for (const comment of comments) {
|
for (const comment of comments) {
|
||||||
const imageMatches = [...comment.body.matchAll(IMAGE_REGEX)];
|
// Extract URLs from Markdown format
|
||||||
const urls = imageMatches.map((match) => match[1] as string);
|
const markdownMatches = [...comment.body.matchAll(IMAGE_REGEX)];
|
||||||
|
const markdownUrls = markdownMatches.map((match) => match[1] as string);
|
||||||
|
|
||||||
|
// Extract URLs from HTML format
|
||||||
|
const htmlMatches = [...comment.body.matchAll(HTML_IMG_REGEX)];
|
||||||
|
const htmlUrls = htmlMatches.map((match) => match[1] as string);
|
||||||
|
|
||||||
|
// Combine and deduplicate URLs
|
||||||
|
const urls = [...new Set([...markdownUrls, ...htmlUrls])];
|
||||||
|
|
||||||
if (urls.length > 0) {
|
if (urls.length > 0) {
|
||||||
commentsWithImages.push({ comment, urls });
|
commentsWithImages.push({ comment, urls });
|
||||||
|
|||||||
@@ -58,6 +58,41 @@ export function sanitizeContent(content: string): string {
|
|||||||
content = stripMarkdownLinkTitles(content);
|
content = stripMarkdownLinkTitles(content);
|
||||||
content = stripHiddenAttributes(content);
|
content = stripHiddenAttributes(content);
|
||||||
content = normalizeHtmlEntities(content);
|
content = normalizeHtmlEntities(content);
|
||||||
|
content = redactGitHubTokens(content);
|
||||||
|
return content;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function redactGitHubTokens(content: string): string {
|
||||||
|
// GitHub Personal Access Tokens (classic): ghp_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX (40 chars)
|
||||||
|
content = content.replace(
|
||||||
|
/\bghp_[A-Za-z0-9]{36}\b/g,
|
||||||
|
"[REDACTED_GITHUB_TOKEN]",
|
||||||
|
);
|
||||||
|
|
||||||
|
// GitHub OAuth tokens: gho_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX (40 chars)
|
||||||
|
content = content.replace(
|
||||||
|
/\bgho_[A-Za-z0-9]{36}\b/g,
|
||||||
|
"[REDACTED_GITHUB_TOKEN]",
|
||||||
|
);
|
||||||
|
|
||||||
|
// GitHub installation tokens: ghs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX (40 chars)
|
||||||
|
content = content.replace(
|
||||||
|
/\bghs_[A-Za-z0-9]{36}\b/g,
|
||||||
|
"[REDACTED_GITHUB_TOKEN]",
|
||||||
|
);
|
||||||
|
|
||||||
|
// GitHub refresh tokens: ghr_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX (40 chars)
|
||||||
|
content = content.replace(
|
||||||
|
/\bghr_[A-Za-z0-9]{36}\b/g,
|
||||||
|
"[REDACTED_GITHUB_TOKEN]",
|
||||||
|
);
|
||||||
|
|
||||||
|
// GitHub fine-grained personal access tokens: github_pat_XXXXXXXXXX (up to 255 chars)
|
||||||
|
content = content.replace(
|
||||||
|
/\bgithub_pat_[A-Za-z0-9_]{11,221}\b/g,
|
||||||
|
"[REDACTED_GITHUB_TOKEN]",
|
||||||
|
);
|
||||||
|
|
||||||
return content;
|
return content;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -21,9 +21,42 @@ export async function checkHumanActor(
|
|||||||
|
|
||||||
console.log(`Actor type: ${actorType}`);
|
console.log(`Actor type: ${actorType}`);
|
||||||
|
|
||||||
|
// Check bot permissions if actor is not a User
|
||||||
if (actorType !== "User") {
|
if (actorType !== "User") {
|
||||||
|
const allowedBots = githubContext.inputs.allowedBots;
|
||||||
|
|
||||||
|
// Check if all bots are allowed
|
||||||
|
if (allowedBots.trim() === "*") {
|
||||||
|
console.log(
|
||||||
|
`All bots are allowed, skipping human actor check for: ${githubContext.actor}`,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse allowed bots list
|
||||||
|
const allowedBotsList = allowedBots
|
||||||
|
.split(",")
|
||||||
|
.map((bot) =>
|
||||||
|
bot
|
||||||
|
.trim()
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/\[bot\]$/, ""),
|
||||||
|
)
|
||||||
|
.filter((bot) => bot.length > 0);
|
||||||
|
|
||||||
|
const botName = githubContext.actor.toLowerCase().replace(/\[bot\]$/, "");
|
||||||
|
|
||||||
|
// Check if specific bot is allowed
|
||||||
|
if (allowedBotsList.includes(botName)) {
|
||||||
|
console.log(
|
||||||
|
`Bot ${botName} is in allowed list, skipping human actor check`,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Bot not allowed
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Workflow initiated by non-human actor: ${githubContext.actor} (type: ${actorType}).`,
|
`Workflow initiated by non-human actor: ${botName} (type: ${actorType}). Add bot to allowed_bots list or use '*' to allow all bots.`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,6 +17,12 @@ export async function checkWritePermissions(
|
|||||||
try {
|
try {
|
||||||
core.info(`Checking permissions for actor: ${actor}`);
|
core.info(`Checking permissions for actor: ${actor}`);
|
||||||
|
|
||||||
|
// Check if the actor is a GitHub App (bot user)
|
||||||
|
if (actor.endsWith("[bot]")) {
|
||||||
|
core.info(`Actor is a GitHub App: ${actor}`);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
// Check permissions directly using the permission endpoint
|
// Check permissions directly using the permission endpoint
|
||||||
const response = await octokit.repos.getCollaboratorPermissionLevel({
|
const response = await octokit.repos.getCollaboratorPermissionLevel({
|
||||||
owner: repository.owner,
|
owner: repository.owner,
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { z } from "zod";
|
|||||||
import { GITHUB_API_URL } from "../github/api/config";
|
import { GITHUB_API_URL } from "../github/api/config";
|
||||||
import { Octokit } from "@octokit/rest";
|
import { Octokit } from "@octokit/rest";
|
||||||
import { updateClaudeComment } from "../github/operations/comments/update-claude-comment";
|
import { updateClaudeComment } from "../github/operations/comments/update-claude-comment";
|
||||||
|
import { sanitizeContent } from "../github/utils/sanitizer";
|
||||||
|
|
||||||
// Get repository information from environment variables
|
// Get repository information from environment variables
|
||||||
const REPO_OWNER = process.env.REPO_OWNER;
|
const REPO_OWNER = process.env.REPO_OWNER;
|
||||||
@@ -54,11 +55,13 @@ server.tool(
|
|||||||
const isPullRequestReviewComment =
|
const isPullRequestReviewComment =
|
||||||
eventName === "pull_request_review_comment";
|
eventName === "pull_request_review_comment";
|
||||||
|
|
||||||
|
const sanitizedBody = sanitizeContent(body);
|
||||||
|
|
||||||
const result = await updateClaudeComment(octokit, {
|
const result = await updateClaudeComment(octokit, {
|
||||||
owner,
|
owner,
|
||||||
repo,
|
repo,
|
||||||
commentId,
|
commentId,
|
||||||
body,
|
body: sanitizedBody,
|
||||||
isPullRequestReviewComment,
|
isPullRequestReviewComment,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -3,8 +3,9 @@
|
|||||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||||
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { readFile } from "fs/promises";
|
import { readFile, stat } from "fs/promises";
|
||||||
import { join } from "path";
|
import { join } from "path";
|
||||||
|
import { constants } from "fs";
|
||||||
import fetch from "node-fetch";
|
import fetch from "node-fetch";
|
||||||
import { GITHUB_API_URL } from "../github/api/config";
|
import { GITHUB_API_URL } from "../github/api/config";
|
||||||
import { retryWithBackoff } from "../utils/retry";
|
import { retryWithBackoff } from "../utils/retry";
|
||||||
@@ -162,6 +163,34 @@ async function getOrCreateBranchRef(
|
|||||||
return baseSha;
|
return baseSha;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Get the appropriate Git file mode for a file
|
||||||
|
async function getFileMode(filePath: string): Promise<string> {
|
||||||
|
try {
|
||||||
|
const fileStat = await stat(filePath);
|
||||||
|
if (fileStat.isFile()) {
|
||||||
|
// Check if execute bit is set for user
|
||||||
|
if (fileStat.mode & constants.S_IXUSR) {
|
||||||
|
return "100755"; // Executable file
|
||||||
|
} else {
|
||||||
|
return "100644"; // Regular file
|
||||||
|
}
|
||||||
|
} else if (fileStat.isDirectory()) {
|
||||||
|
return "040000"; // Directory (tree)
|
||||||
|
} else if (fileStat.isSymbolicLink()) {
|
||||||
|
return "120000"; // Symbolic link
|
||||||
|
} else {
|
||||||
|
// Fallback for unknown file types
|
||||||
|
return "100644";
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
// If we can't stat the file, default to regular file
|
||||||
|
console.warn(
|
||||||
|
`Could not determine file mode for ${filePath}, using default: ${error}`,
|
||||||
|
);
|
||||||
|
return "100644";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Commit files tool
|
// Commit files tool
|
||||||
server.tool(
|
server.tool(
|
||||||
"commit_files",
|
"commit_files",
|
||||||
@@ -223,6 +252,9 @@ server.tool(
|
|||||||
? filePath
|
? filePath
|
||||||
: join(REPO_DIR, filePath);
|
: join(REPO_DIR, filePath);
|
||||||
|
|
||||||
|
// Get the proper file mode based on file permissions
|
||||||
|
const fileMode = await getFileMode(fullPath);
|
||||||
|
|
||||||
// Check if file is binary (images, etc.)
|
// Check if file is binary (images, etc.)
|
||||||
const isBinaryFile =
|
const isBinaryFile =
|
||||||
/\.(png|jpg|jpeg|gif|webp|ico|pdf|zip|tar|gz|exe|bin|woff|woff2|ttf|eot)$/i.test(
|
/\.(png|jpg|jpeg|gif|webp|ico|pdf|zip|tar|gz|exe|bin|woff|woff2|ttf|eot)$/i.test(
|
||||||
@@ -261,7 +293,7 @@ server.tool(
|
|||||||
// Return tree entry with blob SHA
|
// Return tree entry with blob SHA
|
||||||
return {
|
return {
|
||||||
path: filePath,
|
path: filePath,
|
||||||
mode: "100644",
|
mode: fileMode,
|
||||||
type: "blob",
|
type: "blob",
|
||||||
sha: blobData.sha,
|
sha: blobData.sha,
|
||||||
};
|
};
|
||||||
@@ -270,7 +302,7 @@ server.tool(
|
|||||||
const content = await readFile(fullPath, "utf-8");
|
const content = await readFile(fullPath, "utf-8");
|
||||||
return {
|
return {
|
||||||
path: filePath,
|
path: filePath,
|
||||||
mode: "100644",
|
mode: fileMode,
|
||||||
type: "blob",
|
type: "blob",
|
||||||
content: content,
|
content: content,
|
||||||
};
|
};
|
||||||
@@ -335,6 +367,7 @@ server.tool(
|
|||||||
// We're seeing intermittent 403 "Resource not accessible by integration" errors
|
// We're seeing intermittent 403 "Resource not accessible by integration" errors
|
||||||
// on certain repos when updating git references. These appear to be transient
|
// on certain repos when updating git references. These appear to be transient
|
||||||
// GitHub API issues that succeed on retry.
|
// GitHub API issues that succeed on retry.
|
||||||
|
let lastErrorDetails: any = null;
|
||||||
await retryWithBackoff(
|
await retryWithBackoff(
|
||||||
async () => {
|
async () => {
|
||||||
const updateRefResponse = await fetch(updateRefUrl, {
|
const updateRefResponse = await fetch(updateRefUrl, {
|
||||||
@@ -353,17 +386,48 @@ server.tool(
|
|||||||
|
|
||||||
if (!updateRefResponse.ok) {
|
if (!updateRefResponse.ok) {
|
||||||
const errorText = await updateRefResponse.text();
|
const errorText = await updateRefResponse.text();
|
||||||
|
let errorJson: any = {};
|
||||||
|
try {
|
||||||
|
errorJson = JSON.parse(errorText);
|
||||||
|
} catch {
|
||||||
|
// If not JSON, use the text as-is
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collect debugging information
|
||||||
|
const debugInfo = {
|
||||||
|
status: updateRefResponse.status,
|
||||||
|
statusText: updateRefResponse.statusText,
|
||||||
|
headers: Object.fromEntries(updateRefResponse.headers.entries()),
|
||||||
|
errorBody: errorJson || errorText,
|
||||||
|
context: {
|
||||||
|
repository: `${owner}/${repo}`,
|
||||||
|
branch: branch,
|
||||||
|
baseBranch: process.env.BASE_BRANCH,
|
||||||
|
targetSha: newCommitData.sha,
|
||||||
|
parentSha: baseSha,
|
||||||
|
isGitHubAction: !!process.env.GITHUB_ACTIONS,
|
||||||
|
eventName: process.env.GITHUB_EVENT_NAME,
|
||||||
|
isPR: process.env.IS_PR,
|
||||||
|
tokenLength: githubToken?.length || 0,
|
||||||
|
tokenPrefix: githubToken?.substring(0, 10) + "...",
|
||||||
|
apiUrl: updateRefUrl,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
lastErrorDetails = debugInfo;
|
||||||
|
|
||||||
const error = new Error(
|
const error = new Error(
|
||||||
`Failed to update reference: ${updateRefResponse.status} - ${errorText}`,
|
`Failed to update reference: ${updateRefResponse.status} - ${errorText}\n\nDebug Info: ${JSON.stringify(debugInfo, null, 2)}`,
|
||||||
);
|
);
|
||||||
|
|
||||||
// Only retry on 403 errors - these are the intermittent failures we're targeting
|
// Only retry on 403 errors - these are the intermittent failures we're targeting
|
||||||
if (updateRefResponse.status === 403) {
|
if (updateRefResponse.status === 403) {
|
||||||
|
console.error("403 Error encountered (will retry):", debugInfo);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
// For non-403 errors, fail immediately without retry
|
// For non-403 errors, fail immediately without retry
|
||||||
console.error("Non-retryable error:", updateRefResponse.status);
|
console.error("Non-retryable error:", debugInfo);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -373,7 +437,23 @@ server.tool(
|
|||||||
maxDelayMs: 5000, // Max 5 seconds delay
|
maxDelayMs: 5000, // Max 5 seconds delay
|
||||||
backoffFactor: 2, // Double the delay each time
|
backoffFactor: 2, // Double the delay each time
|
||||||
},
|
},
|
||||||
);
|
).catch((error) => {
|
||||||
|
// If all retries failed, enhance the error message with collected details
|
||||||
|
if (lastErrorDetails) {
|
||||||
|
throw new Error(
|
||||||
|
`All retry attempts failed for ref update.\n\n` +
|
||||||
|
`Final error: ${error.message}\n\n` +
|
||||||
|
`Debugging hints:\n` +
|
||||||
|
`- Check if branch '${branch}' is protected and the GitHub App has bypass permissions\n` +
|
||||||
|
`- Verify the token has 'contents:write' permission for ${owner}/${repo}\n` +
|
||||||
|
`- Check for concurrent operations updating the same branch\n` +
|
||||||
|
`- Token appears to be: ${lastErrorDetails.context.tokenPrefix}\n` +
|
||||||
|
`- This may be a transient GitHub API issue if it works on retry\n\n` +
|
||||||
|
`Full debug details: ${JSON.stringify(lastErrorDetails, null, 2)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
});
|
||||||
|
|
||||||
const simplifiedResult = {
|
const simplifiedResult = {
|
||||||
commit: {
|
commit: {
|
||||||
@@ -541,6 +621,7 @@ server.tool(
|
|||||||
// We're seeing intermittent 403 "Resource not accessible by integration" errors
|
// We're seeing intermittent 403 "Resource not accessible by integration" errors
|
||||||
// on certain repos when updating git references. These appear to be transient
|
// on certain repos when updating git references. These appear to be transient
|
||||||
// GitHub API issues that succeed on retry.
|
// GitHub API issues that succeed on retry.
|
||||||
|
let lastErrorDetails: any = null;
|
||||||
await retryWithBackoff(
|
await retryWithBackoff(
|
||||||
async () => {
|
async () => {
|
||||||
const updateRefResponse = await fetch(updateRefUrl, {
|
const updateRefResponse = await fetch(updateRefUrl, {
|
||||||
@@ -559,18 +640,52 @@ server.tool(
|
|||||||
|
|
||||||
if (!updateRefResponse.ok) {
|
if (!updateRefResponse.ok) {
|
||||||
const errorText = await updateRefResponse.text();
|
const errorText = await updateRefResponse.text();
|
||||||
|
let errorJson: any = {};
|
||||||
|
try {
|
||||||
|
errorJson = JSON.parse(errorText);
|
||||||
|
} catch {
|
||||||
|
// If not JSON, use the text as-is
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collect debugging information
|
||||||
|
const debugInfo = {
|
||||||
|
status: updateRefResponse.status,
|
||||||
|
statusText: updateRefResponse.statusText,
|
||||||
|
headers: Object.fromEntries(updateRefResponse.headers.entries()),
|
||||||
|
errorBody: errorJson || errorText,
|
||||||
|
context: {
|
||||||
|
operation: "delete_files",
|
||||||
|
repository: `${owner}/${repo}`,
|
||||||
|
branch: branch,
|
||||||
|
baseBranch: process.env.BASE_BRANCH,
|
||||||
|
targetSha: newCommitData.sha,
|
||||||
|
parentSha: baseSha,
|
||||||
|
isGitHubAction: !!process.env.GITHUB_ACTIONS,
|
||||||
|
eventName: process.env.GITHUB_EVENT_NAME,
|
||||||
|
isPR: process.env.IS_PR,
|
||||||
|
tokenLength: githubToken?.length || 0,
|
||||||
|
tokenPrefix: githubToken?.substring(0, 10) + "...",
|
||||||
|
apiUrl: updateRefUrl,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
lastErrorDetails = debugInfo;
|
||||||
|
|
||||||
const error = new Error(
|
const error = new Error(
|
||||||
`Failed to update reference: ${updateRefResponse.status} - ${errorText}`,
|
`Failed to update reference: ${updateRefResponse.status} - ${errorText}\n\nDebug Info: ${JSON.stringify(debugInfo, null, 2)}`,
|
||||||
);
|
);
|
||||||
|
|
||||||
// Only retry on 403 errors - these are the intermittent failures we're targeting
|
// Only retry on 403 errors - these are the intermittent failures we're targeting
|
||||||
if (updateRefResponse.status === 403) {
|
if (updateRefResponse.status === 403) {
|
||||||
console.log("Received 403 error, will retry...");
|
console.error(
|
||||||
|
"403 Error encountered during delete (will retry):",
|
||||||
|
debugInfo,
|
||||||
|
);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
// For non-403 errors, fail immediately without retry
|
// For non-403 errors, fail immediately without retry
|
||||||
console.error("Non-retryable error:", updateRefResponse.status);
|
console.error("Non-retryable error during delete:", debugInfo);
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -580,7 +695,23 @@ server.tool(
|
|||||||
maxDelayMs: 5000, // Max 5 seconds delay
|
maxDelayMs: 5000, // Max 5 seconds delay
|
||||||
backoffFactor: 2, // Double the delay each time
|
backoffFactor: 2, // Double the delay each time
|
||||||
},
|
},
|
||||||
);
|
).catch((error) => {
|
||||||
|
// If all retries failed, enhance the error message with collected details
|
||||||
|
if (lastErrorDetails) {
|
||||||
|
throw new Error(
|
||||||
|
`All retry attempts failed for ref update during file deletion.\n\n` +
|
||||||
|
`Final error: ${error.message}\n\n` +
|
||||||
|
`Debugging hints:\n` +
|
||||||
|
`- Check if branch '${branch}' is protected and the GitHub App has bypass permissions\n` +
|
||||||
|
`- Verify the token has 'contents:write' permission for ${owner}/${repo}\n` +
|
||||||
|
`- Check for concurrent operations updating the same branch\n` +
|
||||||
|
`- Token appears to be: ${lastErrorDetails.context.tokenPrefix}\n` +
|
||||||
|
`- This may be a transient GitHub API issue if it works on retry\n\n` +
|
||||||
|
`Full debug details: ${JSON.stringify(lastErrorDetails, null, 2)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
});
|
||||||
|
|
||||||
const simplifiedResult = {
|
const simplifiedResult = {
|
||||||
commit: {
|
commit: {
|
||||||
|
|||||||
184
src/mcp/github-inline-comment-server.ts
Normal file
184
src/mcp/github-inline-comment-server.ts
Normal file
@@ -0,0 +1,184 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||||
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { createOctokit } from "../github/api/client";
|
||||||
|
import { sanitizeContent } from "../github/utils/sanitizer";
|
||||||
|
|
||||||
|
// Get repository and PR information from environment variables
|
||||||
|
const REPO_OWNER = process.env.REPO_OWNER;
|
||||||
|
const REPO_NAME = process.env.REPO_NAME;
|
||||||
|
const PR_NUMBER = process.env.PR_NUMBER;
|
||||||
|
|
||||||
|
if (!REPO_OWNER || !REPO_NAME || !PR_NUMBER) {
|
||||||
|
console.error(
|
||||||
|
"Error: REPO_OWNER, REPO_NAME, and PR_NUMBER environment variables are required",
|
||||||
|
);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// GitHub Inline Comment MCP Server - Provides inline PR comment functionality
|
||||||
|
// Provides an inline comment tool without exposing full PR review capabilities, so that
|
||||||
|
// Claude can't accidentally approve a PR
|
||||||
|
const server = new McpServer({
|
||||||
|
name: "GitHub Inline Comment Server",
|
||||||
|
version: "0.0.1",
|
||||||
|
});
|
||||||
|
|
||||||
|
server.tool(
|
||||||
|
"create_inline_comment",
|
||||||
|
"Create an inline comment on a specific line or lines in a PR file",
|
||||||
|
{
|
||||||
|
path: z
|
||||||
|
.string()
|
||||||
|
.describe("The file path to comment on (e.g., 'src/index.js')"),
|
||||||
|
body: z
|
||||||
|
.string()
|
||||||
|
.describe(
|
||||||
|
"The comment text (supports markdown and GitHub code suggestion blocks). " +
|
||||||
|
"For code suggestions, use: ```suggestion\\nreplacement code\\n```. " +
|
||||||
|
"IMPORTANT: The suggestion block will REPLACE the ENTIRE line range (single line or startLine to line). " +
|
||||||
|
"Ensure the replacement is syntactically complete and valid - it must work as a drop-in replacement for the selected lines.",
|
||||||
|
),
|
||||||
|
line: z
|
||||||
|
.number()
|
||||||
|
.nonnegative()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
"Line number for single-line comments (required if startLine is not provided)",
|
||||||
|
),
|
||||||
|
startLine: z
|
||||||
|
.number()
|
||||||
|
.nonnegative()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
"Start line for multi-line comments (use with line parameter for the end line)",
|
||||||
|
),
|
||||||
|
side: z
|
||||||
|
.enum(["LEFT", "RIGHT"])
|
||||||
|
.optional()
|
||||||
|
.default("RIGHT")
|
||||||
|
.describe(
|
||||||
|
"Side of the diff to comment on: LEFT (old code) or RIGHT (new code)",
|
||||||
|
),
|
||||||
|
commit_id: z
|
||||||
|
.string()
|
||||||
|
.optional()
|
||||||
|
.describe(
|
||||||
|
"Specific commit SHA to comment on (defaults to latest commit)",
|
||||||
|
),
|
||||||
|
},
|
||||||
|
async ({ path, body, line, startLine, side, commit_id }) => {
|
||||||
|
try {
|
||||||
|
const githubToken = process.env.GITHUB_TOKEN;
|
||||||
|
|
||||||
|
if (!githubToken) {
|
||||||
|
throw new Error("GITHUB_TOKEN environment variable is required");
|
||||||
|
}
|
||||||
|
|
||||||
|
const owner = REPO_OWNER;
|
||||||
|
const repo = REPO_NAME;
|
||||||
|
const pull_number = parseInt(PR_NUMBER, 10);
|
||||||
|
|
||||||
|
const octokit = createOctokit(githubToken).rest;
|
||||||
|
|
||||||
|
// Sanitize the comment body to remove any potential GitHub tokens
|
||||||
|
const sanitizedBody = sanitizeContent(body);
|
||||||
|
|
||||||
|
// Validate that either line or both startLine and line are provided
|
||||||
|
if (!line && !startLine) {
|
||||||
|
throw new Error(
|
||||||
|
"Either 'line' for single-line comments or both 'startLine' and 'line' for multi-line comments must be provided",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// If only line is provided, it's a single-line comment
|
||||||
|
// If both startLine and line are provided, it's a multi-line comment
|
||||||
|
const isSingleLine = !startLine;
|
||||||
|
|
||||||
|
const pr = await octokit.pulls.get({
|
||||||
|
owner,
|
||||||
|
repo,
|
||||||
|
pull_number,
|
||||||
|
});
|
||||||
|
|
||||||
|
const params: Parameters<
|
||||||
|
typeof octokit.rest.pulls.createReviewComment
|
||||||
|
>[0] = {
|
||||||
|
owner,
|
||||||
|
repo,
|
||||||
|
pull_number,
|
||||||
|
body: sanitizedBody,
|
||||||
|
path,
|
||||||
|
side: side || "RIGHT",
|
||||||
|
commit_id: commit_id || pr.data.head.sha,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (isSingleLine) {
|
||||||
|
// Single-line comment
|
||||||
|
params.line = line;
|
||||||
|
} else {
|
||||||
|
// Multi-line comment
|
||||||
|
params.start_line = startLine;
|
||||||
|
params.start_side = side || "RIGHT";
|
||||||
|
params.line = line;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await octokit.rest.pulls.createReviewComment(params);
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
type: "text",
|
||||||
|
text: JSON.stringify(
|
||||||
|
{
|
||||||
|
success: true,
|
||||||
|
comment_id: result.data.id,
|
||||||
|
html_url: result.data.html_url,
|
||||||
|
path: result.data.path,
|
||||||
|
line: result.data.line || result.data.original_line,
|
||||||
|
message: `Inline comment created successfully on ${path}${isSingleLine ? ` at line ${line}` : ` from line ${startLine} to ${line}`}`,
|
||||||
|
},
|
||||||
|
null,
|
||||||
|
2,
|
||||||
|
),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
const errorMessage =
|
||||||
|
error instanceof Error ? error.message : String(error);
|
||||||
|
|
||||||
|
// Provide more helpful error messages for common issues
|
||||||
|
let helpMessage = "";
|
||||||
|
if (errorMessage.includes("Validation Failed")) {
|
||||||
|
helpMessage =
|
||||||
|
"\n\nThis usually means the line number doesn't exist in the diff or the file path is incorrect. Make sure you're commenting on lines that are part of the PR's changes.";
|
||||||
|
} else if (errorMessage.includes("Not Found")) {
|
||||||
|
helpMessage =
|
||||||
|
"\n\nThis usually means the PR number, repository, or file path is incorrect.";
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: [
|
||||||
|
{
|
||||||
|
type: "text",
|
||||||
|
text: `Error creating inline comment: ${errorMessage}${helpMessage}`,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
error: errorMessage,
|
||||||
|
isError: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
async function runServer() {
|
||||||
|
const transport = new StdioServerTransport();
|
||||||
|
await server.connect(transport);
|
||||||
|
process.on("exit", () => {
|
||||||
|
server.close();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
runServer().catch(console.error);
|
||||||
@@ -111,6 +111,24 @@ export async function prepareMcpConfig(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Include inline comment server for experimental review mode
|
||||||
|
if (context.inputs.mode === "experimental-review" && context.isPR) {
|
||||||
|
baseMcpConfig.mcpServers.github_inline_comment = {
|
||||||
|
command: "bun",
|
||||||
|
args: [
|
||||||
|
"run",
|
||||||
|
`${process.env.GITHUB_ACTION_PATH}/src/mcp/github-inline-comment-server.ts`,
|
||||||
|
],
|
||||||
|
env: {
|
||||||
|
GITHUB_TOKEN: githubToken,
|
||||||
|
REPO_OWNER: owner,
|
||||||
|
REPO_NAME: repo,
|
||||||
|
PR_NUMBER: context.entityNumber?.toString() || "",
|
||||||
|
GITHUB_API_URL: GITHUB_API_URL,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Only add CI server if we have actions:read permission and we're in a PR context
|
// Only add CI server if we have actions:read permission and we're in a PR context
|
||||||
const hasActionsReadPermission =
|
const hasActionsReadPermission =
|
||||||
context.inputs.additionalPermissions.get("actions") === "read";
|
context.inputs.additionalPermissions.get("actions") === "read";
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import * as core from "@actions/core";
|
import * as core from "@actions/core";
|
||||||
|
import { mkdir, writeFile } from "fs/promises";
|
||||||
import type { Mode, ModeOptions, ModeResult } from "../types";
|
import type { Mode, ModeOptions, ModeResult } from "../types";
|
||||||
import { isAutomationContext } from "../../github/context";
|
import { isAutomationContext } from "../../github/context";
|
||||||
import type { PreparedContext } from "../../create-prompt/types";
|
import type { PreparedContext } from "../../create-prompt/types";
|
||||||
@@ -42,7 +43,23 @@ export const agentMode: Mode = {
|
|||||||
async prepare({ context }: ModeOptions): Promise<ModeResult> {
|
async prepare({ context }: ModeOptions): Promise<ModeResult> {
|
||||||
// Agent mode handles automation events (workflow_dispatch, schedule) only
|
// Agent mode handles automation events (workflow_dispatch, schedule) only
|
||||||
|
|
||||||
// Agent mode doesn't need to create prompt files here - handled by createPrompt
|
// TODO: handle by createPrompt (similar to tag and review modes)
|
||||||
|
// Create prompt directory
|
||||||
|
await mkdir(`${process.env.RUNNER_TEMP || "/tmp"}/claude-prompts`, {
|
||||||
|
recursive: true,
|
||||||
|
});
|
||||||
|
// Write the prompt file - the base action requires a prompt_file parameter,
|
||||||
|
// so we must create this file even though agent mode typically uses
|
||||||
|
// override_prompt or direct_prompt. If neither is provided, we write
|
||||||
|
// a minimal prompt with just the repository information.
|
||||||
|
const promptContent =
|
||||||
|
context.inputs.overridePrompt ||
|
||||||
|
context.inputs.directPrompt ||
|
||||||
|
`Repository: ${context.repository.owner}/${context.repository.repo}`;
|
||||||
|
await writeFile(
|
||||||
|
`${process.env.RUNNER_TEMP || "/tmp"}/claude-prompts/claude-prompt.txt`,
|
||||||
|
promptContent,
|
||||||
|
);
|
||||||
|
|
||||||
// Export tool environment variables for agent mode
|
// Export tool environment variables for agent mode
|
||||||
const baseTools = [
|
const baseTools = [
|
||||||
@@ -63,9 +80,8 @@ export const agentMode: Mode = {
|
|||||||
...context.inputs.disallowedTools,
|
...context.inputs.disallowedTools,
|
||||||
];
|
];
|
||||||
|
|
||||||
// Export as INPUT_ prefixed variables for the base action
|
core.exportVariable("ALLOWED_TOOLS", allowedTools.join(","));
|
||||||
core.exportVariable("INPUT_ALLOWED_TOOLS", allowedTools.join(","));
|
core.exportVariable("DISALLOWED_TOOLS", disallowedTools.join(","));
|
||||||
core.exportVariable("INPUT_DISALLOWED_TOOLS", disallowedTools.join(","));
|
|
||||||
|
|
||||||
// Agent mode uses a minimal MCP configuration
|
// Agent mode uses a minimal MCP configuration
|
||||||
// We don't need comment servers or PR-specific tools for automation
|
// We don't need comment servers or PR-specific tools for automation
|
||||||
|
|||||||
@@ -60,20 +60,8 @@ export const reviewMode: Mode = {
|
|||||||
|
|
||||||
getAllowedTools() {
|
getAllowedTools() {
|
||||||
return [
|
return [
|
||||||
// Context tools - to know who the current user is
|
"Bash(gh issue comment:*)",
|
||||||
"mcp__github__get_me",
|
"mcp__github_inline_comment__create_inline_comment",
|
||||||
// Core review tools
|
|
||||||
"mcp__github__create_pending_pull_request_review",
|
|
||||||
"mcp__github__add_comment_to_pending_review",
|
|
||||||
"mcp__github__submit_pending_pull_request_review",
|
|
||||||
"mcp__github__delete_pending_pull_request_review",
|
|
||||||
"mcp__github__create_and_submit_pull_request_review",
|
|
||||||
// Comment tools
|
|
||||||
"mcp__github__add_issue_comment",
|
|
||||||
// PR information tools
|
|
||||||
"mcp__github__get_pull_request",
|
|
||||||
"mcp__github__get_pull_request_reviews",
|
|
||||||
"mcp__github__get_pull_request_status",
|
|
||||||
];
|
];
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -115,6 +103,9 @@ export const reviewMode: Mode = {
|
|||||||
? formatBody(contextData.body, imageUrlMap)
|
? formatBody(contextData.body, imageUrlMap)
|
||||||
: "No description provided";
|
: "No description provided";
|
||||||
|
|
||||||
|
// Using a variable for code blocks to avoid escaping backticks in the template string
|
||||||
|
const codeBlock = "```";
|
||||||
|
|
||||||
return `You are Claude, an AI assistant specialized in code reviews for GitHub pull requests. You are operating in REVIEW MODE, which means you should focus on providing thorough code review feedback using GitHub MCP tools for inline comments and suggestions.
|
return `You are Claude, an AI assistant specialized in code reviews for GitHub pull requests. You are operating in REVIEW MODE, which means you should focus on providing thorough code review feedback using GitHub MCP tools for inline comments and suggestions.
|
||||||
|
|
||||||
<formatted_context>
|
<formatted_context>
|
||||||
@@ -163,68 +154,50 @@ REVIEW MODE WORKFLOW:
|
|||||||
|
|
||||||
1. First, understand the PR context:
|
1. First, understand the PR context:
|
||||||
- You are reviewing PR #${eventData.isPR && eventData.prNumber ? eventData.prNumber : "[PR number]"} in ${context.repository}
|
- You are reviewing PR #${eventData.isPR && eventData.prNumber ? eventData.prNumber : "[PR number]"} in ${context.repository}
|
||||||
- Use mcp__github__get_pull_request to get PR metadata
|
|
||||||
- Use the Read, Grep, and Glob tools to examine the modified files directly from disk
|
- Use the Read, Grep, and Glob tools to examine the modified files directly from disk
|
||||||
- This provides the full context and latest state of the code
|
- This provides the full context and latest state of the code
|
||||||
- Look at the changed_files section above to see which files were modified
|
- Look at the changed_files section above to see which files were modified
|
||||||
|
|
||||||
2. Create a pending review:
|
2. Create review comments using GitHub MCP tools:
|
||||||
- Use mcp__github__create_pending_pull_request_review to start your review
|
- Use Bash(gh issue comment:*) for general PR-level comments
|
||||||
- This allows you to batch comments before submitting
|
- Use mcp__github_inline_comment__create_inline_comment for line-specific feedback (strongly preferred)
|
||||||
|
|
||||||
3. Add inline comments:
|
3. When creating inline comments with suggestions:
|
||||||
- Use mcp__github__add_comment_to_pending_review for each issue or suggestion
|
CRITICAL: GitHub's suggestion blocks REPLACE the ENTIRE line range you select
|
||||||
- Parameters:
|
- For single-line comments: Use 'line' parameter only
|
||||||
* path: The file path (e.g., "src/index.js")
|
- For multi-line comments: Use both 'startLine' and 'line' parameters
|
||||||
* line: Line number for single-line comments
|
- The 'body' parameter should contain your comment and/or suggestion block
|
||||||
* startLine & line: For multi-line comments (startLine is the first line, line is the last)
|
|
||||||
* side: "LEFT" (old code) or "RIGHT" (new code)
|
|
||||||
* subjectType: "line" for line-level comments
|
|
||||||
* body: Your comment text
|
|
||||||
|
|
||||||
- When to use multi-line comments:
|
How to write code suggestions correctly:
|
||||||
* When replacing multiple consecutive lines
|
a) To remove a line (e.g., removing console.log on line 22):
|
||||||
* When the fix requires changes across several lines
|
- Set line: 22
|
||||||
* Example: To replace lines 19-20, use startLine: 19, line: 20
|
- Body: ${codeBlock}suggestion
|
||||||
|
${codeBlock}
|
||||||
|
(Empty suggestion block removes the line)
|
||||||
|
|
||||||
- For code suggestions, use this EXACT format in the body:
|
b) To modify a single line (e.g., fixing line 22):
|
||||||
\`\`\`suggestion
|
- Set line: 22
|
||||||
corrected code here
|
- Body: ${codeBlock}suggestion
|
||||||
\`\`\`
|
await this.emailInput.fill(email);
|
||||||
|
${codeBlock}
|
||||||
|
|
||||||
CRITICAL: GitHub suggestion blocks must ONLY contain the replacement for the specific line(s) being commented on:
|
c) To replace multiple lines (e.g., lines 21-23):
|
||||||
- For single-line comments: Replace ONLY that line
|
- Set startLine: 21, line: 23
|
||||||
- For multi-line comments: Replace ONLY the lines in the range
|
- Body must include ALL lines being replaced:
|
||||||
- Do NOT include surrounding context or function signatures
|
${codeBlock}suggestion
|
||||||
- Do NOT suggest changes that span beyond the commented lines
|
async typeEmail(email: string): Promise<void> {
|
||||||
|
await this.emailInput.fill(email);
|
||||||
|
}
|
||||||
|
${codeBlock}
|
||||||
|
|
||||||
Example for line 19 \`var name = user.name;\`:
|
COMMON MISTAKE TO AVOID:
|
||||||
WRONG:
|
Never duplicate code in suggestions. For example, DON'T do this:
|
||||||
\\\`\\\`\\\`suggestion
|
${codeBlock}suggestion
|
||||||
function processUser(user) {
|
async typeEmail(email: string): Promise<void> {
|
||||||
if (!user) throw new Error('Invalid user');
|
async typeEmail(email: string): Promise<void> { // WRONG: Duplicate signature!
|
||||||
const name = user.name;
|
await this.emailInput.fill(email);
|
||||||
\\\`\\\`\\\`
|
}
|
||||||
|
${codeBlock}
|
||||||
CORRECT:
|
|
||||||
\\\`\\\`\\\`suggestion
|
|
||||||
const name = user.name;
|
|
||||||
\\\`\\\`\\\`
|
|
||||||
|
|
||||||
For validation suggestions, comment on the function declaration line or create separate comments for each concern.
|
|
||||||
|
|
||||||
4. Submit your review:
|
|
||||||
- Use mcp__github__submit_pending_pull_request_review
|
|
||||||
- Parameters:
|
|
||||||
* event: "COMMENT" (general feedback), "REQUEST_CHANGES" (issues found), or "APPROVE" (if appropriate)
|
|
||||||
* body: Write a comprehensive review summary that includes:
|
|
||||||
- Overview of what was reviewed (files, scope, focus areas)
|
|
||||||
- Summary of all issues found (with counts by severity if applicable)
|
|
||||||
- Key recommendations and action items
|
|
||||||
- Highlights of good practices observed
|
|
||||||
- Overall assessment and recommendation
|
|
||||||
- The body should be detailed and informative since it's the main review content
|
|
||||||
- Structure the body with clear sections using markdown headers
|
|
||||||
|
|
||||||
REVIEW GUIDELINES:
|
REVIEW GUIDELINES:
|
||||||
|
|
||||||
@@ -238,13 +211,11 @@ REVIEW GUIDELINES:
|
|||||||
|
|
||||||
- Provide:
|
- Provide:
|
||||||
* Specific, actionable feedback
|
* Specific, actionable feedback
|
||||||
* Code suggestions when possible (following GitHub's format exactly)
|
* Code suggestions using the exact format described above
|
||||||
* Clear explanations of issues
|
* Clear explanations of issues found
|
||||||
* Constructive criticism
|
* Constructive criticism with solutions
|
||||||
* Recognition of good practices
|
* Recognition of good practices
|
||||||
* For complex changes that require multiple modifications:
|
* For complex changes: Create separate inline comments for each logical change
|
||||||
- Create separate comments for each logical change
|
|
||||||
- Or explain the full solution in text without a suggestion block
|
|
||||||
|
|
||||||
- Communication:
|
- Communication:
|
||||||
* All feedback goes through GitHub's review system
|
* All feedback goes through GitHub's review system
|
||||||
@@ -326,9 +297,8 @@ This ensures users get value from the review even before checking individual inl
|
|||||||
...context.inputs.disallowedTools,
|
...context.inputs.disallowedTools,
|
||||||
];
|
];
|
||||||
|
|
||||||
// Export as INPUT_ prefixed variables for the base action
|
core.exportVariable("ALLOWED_TOOLS", allowedTools.join(","));
|
||||||
core.exportVariable("INPUT_ALLOWED_TOOLS", allowedTools.join(","));
|
core.exportVariable("DISALLOWED_TOOLS", disallowedTools.join(","));
|
||||||
core.exportVariable("INPUT_DISALLOWED_TOOLS", disallowedTools.join(","));
|
|
||||||
|
|
||||||
const additionalMcpConfig = process.env.MCP_CONFIG || "";
|
const additionalMcpConfig = process.env.MCP_CONFIG || "";
|
||||||
const mcpConfig = await prepareMcpConfig({
|
const mcpConfig = await prepareMcpConfig({
|
||||||
|
|||||||
96
test/actor.test.ts
Normal file
96
test/actor.test.ts
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
#!/usr/bin/env bun
|
||||||
|
|
||||||
|
import { describe, test, expect } from "bun:test";
|
||||||
|
import { checkHumanActor } from "../src/github/validation/actor";
|
||||||
|
import type { Octokit } from "@octokit/rest";
|
||||||
|
import { createMockContext } from "./mockContext";
|
||||||
|
|
||||||
|
function createMockOctokit(userType: string): Octokit {
|
||||||
|
return {
|
||||||
|
users: {
|
||||||
|
getByUsername: async () => ({
|
||||||
|
data: {
|
||||||
|
type: userType,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
} as unknown as Octokit;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("checkHumanActor", () => {
|
||||||
|
test("should pass for human actor", async () => {
|
||||||
|
const mockOctokit = createMockOctokit("User");
|
||||||
|
const context = createMockContext();
|
||||||
|
context.actor = "human-user";
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
checkHumanActor(mockOctokit, context),
|
||||||
|
).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should throw error for bot actor when not allowed", async () => {
|
||||||
|
const mockOctokit = createMockOctokit("Bot");
|
||||||
|
const context = createMockContext();
|
||||||
|
context.actor = "test-bot[bot]";
|
||||||
|
context.inputs.allowedBots = "";
|
||||||
|
|
||||||
|
await expect(checkHumanActor(mockOctokit, context)).rejects.toThrow(
|
||||||
|
"Workflow initiated by non-human actor: test-bot (type: Bot). Add bot to allowed_bots list or use '*' to allow all bots.",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should pass for bot actor when all bots allowed", async () => {
|
||||||
|
const mockOctokit = createMockOctokit("Bot");
|
||||||
|
const context = createMockContext();
|
||||||
|
context.actor = "test-bot[bot]";
|
||||||
|
context.inputs.allowedBots = "*";
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
checkHumanActor(mockOctokit, context),
|
||||||
|
).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should pass for specific bot when in allowed list", async () => {
|
||||||
|
const mockOctokit = createMockOctokit("Bot");
|
||||||
|
const context = createMockContext();
|
||||||
|
context.actor = "dependabot[bot]";
|
||||||
|
context.inputs.allowedBots = "dependabot[bot],renovate[bot]";
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
checkHumanActor(mockOctokit, context),
|
||||||
|
).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should pass for specific bot when in allowed list (without [bot])", async () => {
|
||||||
|
const mockOctokit = createMockOctokit("Bot");
|
||||||
|
const context = createMockContext();
|
||||||
|
context.actor = "dependabot[bot]";
|
||||||
|
context.inputs.allowedBots = "dependabot,renovate";
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
checkHumanActor(mockOctokit, context),
|
||||||
|
).resolves.toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should throw error for bot not in allowed list", async () => {
|
||||||
|
const mockOctokit = createMockOctokit("Bot");
|
||||||
|
const context = createMockContext();
|
||||||
|
context.actor = "other-bot[bot]";
|
||||||
|
context.inputs.allowedBots = "dependabot[bot],renovate[bot]";
|
||||||
|
|
||||||
|
await expect(checkHumanActor(mockOctokit, context)).rejects.toThrow(
|
||||||
|
"Workflow initiated by non-human actor: other-bot (type: Bot). Add bot to allowed_bots list or use '*' to allow all bots.",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should throw error for bot not in allowed list (without [bot])", async () => {
|
||||||
|
const mockOctokit = createMockOctokit("Bot");
|
||||||
|
const context = createMockContext();
|
||||||
|
context.actor = "other-bot[bot]";
|
||||||
|
context.inputs.allowedBots = "dependabot,renovate";
|
||||||
|
|
||||||
|
await expect(checkHumanActor(mockOctokit, context)).rejects.toThrow(
|
||||||
|
"Workflow initiated by non-human actor: other-bot (type: Bot). Add bot to allowed_bots list or use '*' to allow all bots.",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1041,8 +1041,6 @@ describe("buildAllowedToolsString", () => {
|
|||||||
expect(result).toContain("Bash(git diff:*)");
|
expect(result).toContain("Bash(git diff:*)");
|
||||||
expect(result).toContain("Bash(git log:*)");
|
expect(result).toContain("Bash(git log:*)");
|
||||||
expect(result).toContain("Bash(git rm:*)");
|
expect(result).toContain("Bash(git rm:*)");
|
||||||
expect(result).toContain("Bash(git config user.name:*)");
|
|
||||||
expect(result).toContain("Bash(git config user.email:*)");
|
|
||||||
|
|
||||||
// Comment tool from minimal server should be included
|
// Comment tool from minimal server should be included
|
||||||
expect(result).toContain("mcp__github_comment__update_claude_comment");
|
expect(result).toContain("mcp__github_comment__update_claude_comment");
|
||||||
|
|||||||
@@ -662,4 +662,255 @@ describe("downloadCommentImages", () => {
|
|||||||
);
|
);
|
||||||
expect(result.get(imageUrl2)).toBeUndefined();
|
expect(result.get(imageUrl2)).toBeUndefined();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("should detect and download images from HTML img tags", async () => {
|
||||||
|
const mockOctokit = createMockOctokit();
|
||||||
|
const imageUrl =
|
||||||
|
"https://github.com/user-attachments/assets/html-image.png";
|
||||||
|
const signedUrl =
|
||||||
|
"https://private-user-images.githubusercontent.com/html.png?jwt=token";
|
||||||
|
|
||||||
|
// Mock octokit response
|
||||||
|
// @ts-expect-error Mock implementation doesn't match full type signature
|
||||||
|
mockOctokit.rest.issues.getComment = jest.fn().mockResolvedValue({
|
||||||
|
data: {
|
||||||
|
body_html: `<img src="${signedUrl}">`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Mock fetch for image download
|
||||||
|
const mockArrayBuffer = new ArrayBuffer(8);
|
||||||
|
fetchSpy = spyOn(global, "fetch").mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
arrayBuffer: async () => mockArrayBuffer,
|
||||||
|
} as Response);
|
||||||
|
|
||||||
|
const comments: CommentWithImages[] = [
|
||||||
|
{
|
||||||
|
type: "issue_comment",
|
||||||
|
id: "777",
|
||||||
|
body: `Here's an HTML image: <img src="${imageUrl}" alt="test">`,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = await downloadCommentImages(
|
||||||
|
mockOctokit,
|
||||||
|
"owner",
|
||||||
|
"repo",
|
||||||
|
comments,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(mockOctokit.rest.issues.getComment).toHaveBeenCalledWith({
|
||||||
|
owner: "owner",
|
||||||
|
repo: "repo",
|
||||||
|
comment_id: 777,
|
||||||
|
mediaType: { format: "full+json" },
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(fetchSpy).toHaveBeenCalledWith(signedUrl);
|
||||||
|
expect(fsWriteFileSpy).toHaveBeenCalledWith(
|
||||||
|
"/tmp/github-images/image-1704067200000-0.png",
|
||||||
|
Buffer.from(mockArrayBuffer),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result.size).toBe(1);
|
||||||
|
expect(result.get(imageUrl)).toBe(
|
||||||
|
"/tmp/github-images/image-1704067200000-0.png",
|
||||||
|
);
|
||||||
|
expect(consoleLogSpy).toHaveBeenCalledWith(
|
||||||
|
"Found 1 image(s) in issue_comment 777",
|
||||||
|
);
|
||||||
|
expect(consoleLogSpy).toHaveBeenCalledWith(`Downloading ${imageUrl}...`);
|
||||||
|
expect(consoleLogSpy).toHaveBeenCalledWith(
|
||||||
|
"✓ Saved: /tmp/github-images/image-1704067200000-0.png",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should handle HTML img tags with different quote styles", async () => {
|
||||||
|
const mockOctokit = createMockOctokit();
|
||||||
|
const imageUrl1 =
|
||||||
|
"https://github.com/user-attachments/assets/single-quote.jpg";
|
||||||
|
const imageUrl2 =
|
||||||
|
"https://github.com/user-attachments/assets/double-quote.png";
|
||||||
|
const signedUrl1 =
|
||||||
|
"https://private-user-images.githubusercontent.com/single.jpg?jwt=token1";
|
||||||
|
const signedUrl2 =
|
||||||
|
"https://private-user-images.githubusercontent.com/double.png?jwt=token2";
|
||||||
|
|
||||||
|
// @ts-expect-error Mock implementation doesn't match full type signature
|
||||||
|
mockOctokit.rest.issues.getComment = jest.fn().mockResolvedValue({
|
||||||
|
data: {
|
||||||
|
body_html: `<img src="${signedUrl1}"><img src="${signedUrl2}">`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
fetchSpy = spyOn(global, "fetch").mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
arrayBuffer: async () => new ArrayBuffer(8),
|
||||||
|
} as Response);
|
||||||
|
|
||||||
|
const comments: CommentWithImages[] = [
|
||||||
|
{
|
||||||
|
type: "issue_comment",
|
||||||
|
id: "888",
|
||||||
|
body: `Single quote: <img src='${imageUrl1}' alt="test"> and double quote: <img src="${imageUrl2}" alt="test">`,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = await downloadCommentImages(
|
||||||
|
mockOctokit,
|
||||||
|
"owner",
|
||||||
|
"repo",
|
||||||
|
comments,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(fetchSpy).toHaveBeenCalledTimes(2);
|
||||||
|
expect(result.size).toBe(2);
|
||||||
|
expect(result.get(imageUrl1)).toBe(
|
||||||
|
"/tmp/github-images/image-1704067200000-0.jpg",
|
||||||
|
);
|
||||||
|
expect(result.get(imageUrl2)).toBe(
|
||||||
|
"/tmp/github-images/image-1704067200000-1.png",
|
||||||
|
);
|
||||||
|
expect(consoleLogSpy).toHaveBeenCalledWith(
|
||||||
|
"Found 2 image(s) in issue_comment 888",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should handle mixed Markdown and HTML images", async () => {
|
||||||
|
const mockOctokit = createMockOctokit();
|
||||||
|
const markdownUrl =
|
||||||
|
"https://github.com/user-attachments/assets/markdown.png";
|
||||||
|
const htmlUrl = "https://github.com/user-attachments/assets/html.jpg";
|
||||||
|
const signedUrl1 =
|
||||||
|
"https://private-user-images.githubusercontent.com/md.png?jwt=token1";
|
||||||
|
const signedUrl2 =
|
||||||
|
"https://private-user-images.githubusercontent.com/html.jpg?jwt=token2";
|
||||||
|
|
||||||
|
// @ts-expect-error Mock implementation doesn't match full type signature
|
||||||
|
mockOctokit.rest.issues.getComment = jest.fn().mockResolvedValue({
|
||||||
|
data: {
|
||||||
|
body_html: `<img src="${signedUrl1}"><img src="${signedUrl2}">`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
fetchSpy = spyOn(global, "fetch").mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
arrayBuffer: async () => new ArrayBuffer(8),
|
||||||
|
} as Response);
|
||||||
|
|
||||||
|
const comments: CommentWithImages[] = [
|
||||||
|
{
|
||||||
|
type: "issue_comment",
|
||||||
|
id: "999",
|
||||||
|
body: `Markdown:  and HTML: <img src="${htmlUrl}" alt="test">`,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = await downloadCommentImages(
|
||||||
|
mockOctokit,
|
||||||
|
"owner",
|
||||||
|
"repo",
|
||||||
|
comments,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(fetchSpy).toHaveBeenCalledTimes(2);
|
||||||
|
expect(result.size).toBe(2);
|
||||||
|
expect(result.get(markdownUrl)).toBe(
|
||||||
|
"/tmp/github-images/image-1704067200000-0.png",
|
||||||
|
);
|
||||||
|
expect(result.get(htmlUrl)).toBe(
|
||||||
|
"/tmp/github-images/image-1704067200000-1.jpg",
|
||||||
|
);
|
||||||
|
expect(consoleLogSpy).toHaveBeenCalledWith(
|
||||||
|
"Found 2 image(s) in issue_comment 999",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should deduplicate identical URLs from Markdown and HTML", async () => {
|
||||||
|
const mockOctokit = createMockOctokit();
|
||||||
|
const imageUrl = "https://github.com/user-attachments/assets/duplicate.png";
|
||||||
|
const signedUrl =
|
||||||
|
"https://private-user-images.githubusercontent.com/dup.png?jwt=token";
|
||||||
|
|
||||||
|
// @ts-expect-error Mock implementation doesn't match full type signature
|
||||||
|
mockOctokit.rest.issues.getComment = jest.fn().mockResolvedValue({
|
||||||
|
data: {
|
||||||
|
body_html: `<img src="${signedUrl}">`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
fetchSpy = spyOn(global, "fetch").mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
arrayBuffer: async () => new ArrayBuffer(8),
|
||||||
|
} as Response);
|
||||||
|
|
||||||
|
const comments: CommentWithImages[] = [
|
||||||
|
{
|
||||||
|
type: "issue_comment",
|
||||||
|
id: "1000",
|
||||||
|
body: `Same image twice:  and <img src="${imageUrl}" alt="test">`,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = await downloadCommentImages(
|
||||||
|
mockOctokit,
|
||||||
|
"owner",
|
||||||
|
"repo",
|
||||||
|
comments,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(fetchSpy).toHaveBeenCalledTimes(1); // Only downloaded once
|
||||||
|
expect(result.size).toBe(1);
|
||||||
|
expect(result.get(imageUrl)).toBe(
|
||||||
|
"/tmp/github-images/image-1704067200000-0.png",
|
||||||
|
);
|
||||||
|
expect(consoleLogSpy).toHaveBeenCalledWith(
|
||||||
|
"Found 1 image(s) in issue_comment 1000",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("should handle HTML img tags with additional attributes", async () => {
|
||||||
|
const mockOctokit = createMockOctokit();
|
||||||
|
const imageUrl =
|
||||||
|
"https://github.com/user-attachments/assets/complex-tag.webp";
|
||||||
|
const signedUrl =
|
||||||
|
"https://private-user-images.githubusercontent.com/complex.webp?jwt=token";
|
||||||
|
|
||||||
|
// @ts-expect-error Mock implementation doesn't match full type signature
|
||||||
|
mockOctokit.rest.issues.getComment = jest.fn().mockResolvedValue({
|
||||||
|
data: {
|
||||||
|
body_html: `<img src="${signedUrl}">`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
fetchSpy = spyOn(global, "fetch").mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
arrayBuffer: async () => new ArrayBuffer(8),
|
||||||
|
} as Response);
|
||||||
|
|
||||||
|
const comments: CommentWithImages[] = [
|
||||||
|
{
|
||||||
|
type: "issue_comment",
|
||||||
|
id: "1001",
|
||||||
|
body: `Complex tag: <img class="image" src="${imageUrl}" alt="test image" width="100" height="200">`,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = await downloadCommentImages(
|
||||||
|
mockOctokit,
|
||||||
|
"owner",
|
||||||
|
"repo",
|
||||||
|
comments,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(fetchSpy).toHaveBeenCalledTimes(1);
|
||||||
|
expect(result.size).toBe(1);
|
||||||
|
expect(result.get(imageUrl)).toBe(
|
||||||
|
"/tmp/github-images/image-1704067200000-0.webp",
|
||||||
|
);
|
||||||
|
expect(consoleLogSpy).toHaveBeenCalledWith(
|
||||||
|
"Found 1 image(s) in issue_comment 1001",
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ describe("prepareMcpConfig", () => {
|
|||||||
useStickyComment: false,
|
useStickyComment: false,
|
||||||
additionalPermissions: new Map(),
|
additionalPermissions: new Map(),
|
||||||
useCommitSigning: false,
|
useCommitSigning: false,
|
||||||
|
allowedBots: "",
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ const defaultInputs = {
|
|||||||
useStickyComment: false,
|
useStickyComment: false,
|
||||||
additionalPermissions: new Map<string, string>(),
|
additionalPermissions: new Map<string, string>(),
|
||||||
useCommitSigning: false,
|
useCommitSigning: false,
|
||||||
|
allowedBots: "",
|
||||||
};
|
};
|
||||||
|
|
||||||
const defaultRepository = {
|
const defaultRepository = {
|
||||||
|
|||||||
@@ -1,15 +1,29 @@
|
|||||||
import { describe, test, expect, beforeEach } from "bun:test";
|
import { describe, test, expect, beforeEach, afterEach, spyOn } from "bun:test";
|
||||||
import { agentMode } from "../../src/modes/agent";
|
import { agentMode } from "../../src/modes/agent";
|
||||||
import type { GitHubContext } from "../../src/github/context";
|
import type { GitHubContext } from "../../src/github/context";
|
||||||
import { createMockContext, createMockAutomationContext } from "../mockContext";
|
import { createMockContext, createMockAutomationContext } from "../mockContext";
|
||||||
|
import * as core from "@actions/core";
|
||||||
|
|
||||||
describe("Agent Mode", () => {
|
describe("Agent Mode", () => {
|
||||||
let mockContext: GitHubContext;
|
let mockContext: GitHubContext;
|
||||||
|
let exportVariableSpy: any;
|
||||||
|
let setOutputSpy: any;
|
||||||
|
|
||||||
beforeEach(() => {
|
beforeEach(() => {
|
||||||
mockContext = createMockAutomationContext({
|
mockContext = createMockAutomationContext({
|
||||||
eventName: "workflow_dispatch",
|
eventName: "workflow_dispatch",
|
||||||
});
|
});
|
||||||
|
exportVariableSpy = spyOn(core, "exportVariable").mockImplementation(
|
||||||
|
() => {},
|
||||||
|
);
|
||||||
|
setOutputSpy = spyOn(core, "setOutput").mockImplementation(() => {});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
exportVariableSpy?.mockClear();
|
||||||
|
setOutputSpy?.mockClear();
|
||||||
|
exportVariableSpy?.mockRestore();
|
||||||
|
setOutputSpy?.mockRestore();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("agent mode has correct properties", () => {
|
test("agent mode has correct properties", () => {
|
||||||
@@ -56,4 +70,67 @@ describe("Agent Mode", () => {
|
|||||||
expect(agentMode.shouldTrigger(context)).toBe(false);
|
expect(agentMode.shouldTrigger(context)).toBe(false);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("prepare method sets up tools environment variables correctly", async () => {
|
||||||
|
// Clear any previous calls before this test
|
||||||
|
exportVariableSpy.mockClear();
|
||||||
|
setOutputSpy.mockClear();
|
||||||
|
|
||||||
|
const contextWithCustomTools = createMockAutomationContext({
|
||||||
|
eventName: "workflow_dispatch",
|
||||||
|
});
|
||||||
|
contextWithCustomTools.inputs.allowedTools = ["CustomTool1", "CustomTool2"];
|
||||||
|
contextWithCustomTools.inputs.disallowedTools = ["BadTool"];
|
||||||
|
|
||||||
|
const mockOctokit = {} as any;
|
||||||
|
const result = await agentMode.prepare({
|
||||||
|
context: contextWithCustomTools,
|
||||||
|
octokit: mockOctokit,
|
||||||
|
githubToken: "test-token",
|
||||||
|
});
|
||||||
|
|
||||||
|
// Verify that both ALLOWED_TOOLS and DISALLOWED_TOOLS are set
|
||||||
|
expect(exportVariableSpy).toHaveBeenCalledWith(
|
||||||
|
"ALLOWED_TOOLS",
|
||||||
|
"Edit,MultiEdit,Glob,Grep,LS,Read,Write,CustomTool1,CustomTool2",
|
||||||
|
);
|
||||||
|
expect(exportVariableSpy).toHaveBeenCalledWith(
|
||||||
|
"DISALLOWED_TOOLS",
|
||||||
|
"WebSearch,WebFetch,BadTool",
|
||||||
|
);
|
||||||
|
|
||||||
|
// Verify MCP config is set
|
||||||
|
expect(setOutputSpy).toHaveBeenCalledWith("mcp_config", expect.any(String));
|
||||||
|
|
||||||
|
// Verify return structure
|
||||||
|
expect(result).toEqual({
|
||||||
|
commentId: undefined,
|
||||||
|
branchInfo: {
|
||||||
|
baseBranch: "",
|
||||||
|
currentBranch: "",
|
||||||
|
claudeBranch: undefined,
|
||||||
|
},
|
||||||
|
mcpConfig: expect.any(String),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("prepare method creates prompt file with correct content", async () => {
|
||||||
|
const contextWithPrompts = createMockAutomationContext({
|
||||||
|
eventName: "workflow_dispatch",
|
||||||
|
});
|
||||||
|
contextWithPrompts.inputs.overridePrompt = "Custom override prompt";
|
||||||
|
contextWithPrompts.inputs.directPrompt =
|
||||||
|
"Direct prompt (should be ignored)";
|
||||||
|
|
||||||
|
const mockOctokit = {} as any;
|
||||||
|
await agentMode.prepare({
|
||||||
|
context: contextWithPrompts,
|
||||||
|
octokit: mockOctokit,
|
||||||
|
githubToken: "test-token",
|
||||||
|
});
|
||||||
|
|
||||||
|
// Note: We can't easily test file creation in this unit test,
|
||||||
|
// but we can verify the method completes without errors
|
||||||
|
expect(setOutputSpy).toHaveBeenCalledWith("mcp_config", expect.any(String));
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -73,6 +73,7 @@ describe("checkWritePermissions", () => {
|
|||||||
useStickyComment: false,
|
useStickyComment: false,
|
||||||
additionalPermissions: new Map(),
|
additionalPermissions: new Map(),
|
||||||
useCommitSigning: false,
|
useCommitSigning: false,
|
||||||
|
allowedBots: "",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -126,6 +127,16 @@ describe("checkWritePermissions", () => {
|
|||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("should return true for bot user", async () => {
|
||||||
|
const mockOctokit = createMockOctokit("none");
|
||||||
|
const context = createContext();
|
||||||
|
context.actor = "test-bot[bot]";
|
||||||
|
|
||||||
|
const result = await checkWritePermissions(mockOctokit, context);
|
||||||
|
|
||||||
|
expect(result).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
test("should throw error when permission check fails", async () => {
|
test("should throw error when permission check fails", async () => {
|
||||||
const error = new Error("API error");
|
const error = new Error("API error");
|
||||||
const mockOctokit = {
|
const mockOctokit = {
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
normalizeHtmlEntities,
|
normalizeHtmlEntities,
|
||||||
sanitizeContent,
|
sanitizeContent,
|
||||||
stripHtmlComments,
|
stripHtmlComments,
|
||||||
|
redactGitHubTokens,
|
||||||
} from "../src/github/utils/sanitizer";
|
} from "../src/github/utils/sanitizer";
|
||||||
|
|
||||||
describe("stripInvisibleCharacters", () => {
|
describe("stripInvisibleCharacters", () => {
|
||||||
@@ -242,6 +243,109 @@ describe("sanitizeContent", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("redactGitHubTokens", () => {
|
||||||
|
it("should redact personal access tokens (ghp_)", () => {
|
||||||
|
const token = "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";
|
||||||
|
expect(redactGitHubTokens(`Token: ${token}`)).toBe(
|
||||||
|
"Token: [REDACTED_GITHUB_TOKEN]",
|
||||||
|
);
|
||||||
|
expect(redactGitHubTokens(`Here's a token: ${token} in text`)).toBe(
|
||||||
|
"Here's a token: [REDACTED_GITHUB_TOKEN] in text",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should redact OAuth tokens (gho_)", () => {
|
||||||
|
const token = "gho_16C7e42F292c6912E7710c838347Ae178B4a";
|
||||||
|
expect(redactGitHubTokens(`OAuth: ${token}`)).toBe(
|
||||||
|
"OAuth: [REDACTED_GITHUB_TOKEN]",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should redact installation tokens (ghs_)", () => {
|
||||||
|
const token = "ghs_xz7yzju2SZjGPa0dUNMAx0SH4xDOCS31LXQW";
|
||||||
|
expect(redactGitHubTokens(`Install token: ${token}`)).toBe(
|
||||||
|
"Install token: [REDACTED_GITHUB_TOKEN]",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should redact refresh tokens (ghr_)", () => {
|
||||||
|
const token = "ghr_1B4a2e77838347a253e56d7b5253e7d11667";
|
||||||
|
expect(redactGitHubTokens(`Refresh: ${token}`)).toBe(
|
||||||
|
"Refresh: [REDACTED_GITHUB_TOKEN]",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should redact fine-grained tokens (github_pat_)", () => {
|
||||||
|
const token =
|
||||||
|
"github_pat_11ABCDEFG0example5of9_2nVwvsylpmOLboQwTPTLewDcE621dQ0AAaBBCCDDEEFFHH";
|
||||||
|
expect(redactGitHubTokens(`Fine-grained: ${token}`)).toBe(
|
||||||
|
"Fine-grained: [REDACTED_GITHUB_TOKEN]",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should handle tokens in code blocks", () => {
|
||||||
|
const content = `\`\`\`bash
|
||||||
|
export GITHUB_TOKEN=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
|
||||||
|
\`\`\``;
|
||||||
|
const expected = `\`\`\`bash
|
||||||
|
export GITHUB_TOKEN=[REDACTED_GITHUB_TOKEN]
|
||||||
|
\`\`\``;
|
||||||
|
expect(redactGitHubTokens(content)).toBe(expected);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should handle multiple tokens in one text", () => {
|
||||||
|
const content =
|
||||||
|
"Token 1: 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 and token 2: gho_16C7e42F292c6912E7710c838347Ae178B4a";
|
||||||
|
expect(redactGitHubTokens(content)).toBe(
|
||||||
|
"Token 1: [REDACTED_GITHUB_TOKEN] and token 2: [REDACTED_GITHUB_TOKEN]",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should handle tokens in URLs", () => {
|
||||||
|
const content =
|
||||||
|
"https://api.github.com/user?access_token=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";
|
||||||
|
expect(redactGitHubTokens(content)).toBe(
|
||||||
|
"https://api.github.com/user?access_token=[REDACTED_GITHUB_TOKEN]",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should not redact partial matches or invalid tokens", () => {
|
||||||
|
const content =
|
||||||
|
"This is not a token: ghp_short or gho_toolong1234567890123456789012345678901234567890";
|
||||||
|
expect(redactGitHubTokens(content)).toBe(content);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should preserve normal text", () => {
|
||||||
|
const content = "Normal text with no tokens";
|
||||||
|
expect(redactGitHubTokens(content)).toBe(content);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("should handle edge cases", () => {
|
||||||
|
expect(redactGitHubTokens("")).toBe("");
|
||||||
|
expect(redactGitHubTokens("ghp_")).toBe("ghp_");
|
||||||
|
expect(redactGitHubTokens("github_pat_short")).toBe("github_pat_short");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("sanitizeContent with token redaction", () => {
|
||||||
|
it("should redact tokens as part of full sanitization", () => {
|
||||||
|
const content = `
|
||||||
|
<!-- Hidden comment with token: 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 -->
|
||||||
|
Here's some text with a token: gho_16C7e42F292c6912E7710c838347Ae178B4a
|
||||||
|
And invisible chars: test\u200Btoken
|
||||||
|
`;
|
||||||
|
|
||||||
|
const sanitized = sanitizeContent(content);
|
||||||
|
|
||||||
|
expect(sanitized).not.toContain("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");
|
||||||
|
expect(sanitized).not.toContain("gho_16C7e42F292c6912E7710c838347Ae178B4a");
|
||||||
|
expect(sanitized).not.toContain("<!-- Hidden comment");
|
||||||
|
expect(sanitized).not.toContain("\u200B");
|
||||||
|
expect(sanitized).toContain("[REDACTED_GITHUB_TOKEN]");
|
||||||
|
expect(sanitized).toContain("Here's some text with a token:");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("stripHtmlComments (legacy)", () => {
|
describe("stripHtmlComments (legacy)", () => {
|
||||||
it("should remove HTML comments", () => {
|
it("should remove HTML comments", () => {
|
||||||
expect(stripHtmlComments("Hello <!-- example -->World")).toBe(
|
expect(stripHtmlComments("Hello <!-- example -->World")).toBe(
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ describe("checkContainsTrigger", () => {
|
|||||||
useStickyComment: false,
|
useStickyComment: false,
|
||||||
additionalPermissions: new Map(),
|
additionalPermissions: new Map(),
|
||||||
useCommitSigning: false,
|
useCommitSigning: false,
|
||||||
|
allowedBots: "",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
expect(checkContainsTrigger(context)).toBe(true);
|
expect(checkContainsTrigger(context)).toBe(true);
|
||||||
@@ -74,6 +75,7 @@ describe("checkContainsTrigger", () => {
|
|||||||
useStickyComment: false,
|
useStickyComment: false,
|
||||||
additionalPermissions: new Map(),
|
additionalPermissions: new Map(),
|
||||||
useCommitSigning: false,
|
useCommitSigning: false,
|
||||||
|
allowedBots: "",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
expect(checkContainsTrigger(context)).toBe(false);
|
expect(checkContainsTrigger(context)).toBe(false);
|
||||||
@@ -291,6 +293,7 @@ describe("checkContainsTrigger", () => {
|
|||||||
useStickyComment: false,
|
useStickyComment: false,
|
||||||
additionalPermissions: new Map(),
|
additionalPermissions: new Map(),
|
||||||
useCommitSigning: false,
|
useCommitSigning: false,
|
||||||
|
allowedBots: "",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
expect(checkContainsTrigger(context)).toBe(true);
|
expect(checkContainsTrigger(context)).toBe(true);
|
||||||
@@ -325,6 +328,7 @@ describe("checkContainsTrigger", () => {
|
|||||||
useStickyComment: false,
|
useStickyComment: false,
|
||||||
additionalPermissions: new Map(),
|
additionalPermissions: new Map(),
|
||||||
useCommitSigning: false,
|
useCommitSigning: false,
|
||||||
|
allowedBots: "",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
expect(checkContainsTrigger(context)).toBe(true);
|
expect(checkContainsTrigger(context)).toBe(true);
|
||||||
@@ -359,6 +363,7 @@ describe("checkContainsTrigger", () => {
|
|||||||
useStickyComment: false,
|
useStickyComment: false,
|
||||||
additionalPermissions: new Map(),
|
additionalPermissions: new Map(),
|
||||||
useCommitSigning: false,
|
useCommitSigning: false,
|
||||||
|
allowedBots: "",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
expect(checkContainsTrigger(context)).toBe(false);
|
expect(checkContainsTrigger(context)).toBe(false);
|
||||||
|
|||||||
Reference in New Issue
Block a user