Compare commits

..

1 Commits

Author SHA1 Message Date
Ashwin Bhat
53d451f987 chore: update claude-code-base-action to v0.0.10 2025-06-05 16:51:05 +00:00
26 changed files with 53 additions and 588 deletions

View File

@@ -29,4 +29,4 @@ jobs:
Be constructive and specific in your feedback. Give inline comments where applicable.
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
allowed_tools: "mcp__github__create_pending_pull_request_review,mcp__github__add_pull_request_review_comment_to_pending_review,mcp__github__submit_pending_pull_request_review,mcp__github__get_pull_request_diff"
allowed_tools: "mcp__github__add_pull_request_review_comment"

View File

@@ -32,7 +32,7 @@ jobs:
"--rm",
"-e",
"GITHUB_PERSONAL_ACCESS_TOKEN",
"ghcr.io/github/github-mcp-server:sha-6d69797"
"ghcr.io/github/github-mcp-server:sha-7aced2b"
],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "${{ secrets.GITHUB_TOKEN }}"

View File

@@ -1,138 +0,0 @@
name: Create Release
on:
workflow_dispatch:
inputs:
dry_run:
description: "Dry run (only show what would be created)"
required: false
type: boolean
default: false
jobs:
create-release:
runs-on: ubuntu-latest
permissions:
contents: write
outputs:
next_version: ${{ steps.next_version.outputs.next_version }}
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Get latest tag
id: get_latest_tag
run: |
# Get only version tags (v + number pattern)
latest_tag=$(git tag -l 'v[0-9]*' | sort -V | tail -1 || echo "v0.0.0")
if [ -z "$latest_tag" ]; then
latest_tag="v0.0.0"
fi
echo "latest_tag=$latest_tag" >> $GITHUB_OUTPUT
echo "Latest tag: $latest_tag"
- name: Calculate next version
id: next_version
run: |
latest_tag="${{ steps.get_latest_tag.outputs.latest_tag }}"
# Remove 'v' prefix and split by dots
version=${latest_tag#v}
IFS='.' read -ra VERSION_PARTS <<< "$version"
# Increment patch version
major=${VERSION_PARTS[0]:-0}
minor=${VERSION_PARTS[1]:-0}
patch=${VERSION_PARTS[2]:-0}
patch=$((patch + 1))
next_version="v${major}.${minor}.${patch}"
echo "next_version=$next_version" >> $GITHUB_OUTPUT
echo "Next version: $next_version"
- name: Display dry run info
if: ${{ inputs.dry_run }}
run: |
echo "🔍 DRY RUN MODE"
echo "Would create tag: ${{ steps.next_version.outputs.next_version }}"
echo "From commit: ${{ github.sha }}"
echo "Previous tag: ${{ steps.get_latest_tag.outputs.latest_tag }}"
- name: Create and push tag
if: ${{ !inputs.dry_run }}
run: |
next_version="${{ steps.next_version.outputs.next_version }}"
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git tag -a "$next_version" -m "Release $next_version"
git push origin "$next_version"
- name: Create Release
if: ${{ !inputs.dry_run }}
env:
GH_TOKEN: ${{ github.token }}
run: |
next_version="${{ steps.next_version.outputs.next_version }}"
gh release create "$next_version" \
--title "$next_version" \
--generate-notes \
--latest=false # We want to keep beta as the latest
update-beta-tag:
needs: create-release
if: ${{ !inputs.dry_run }}
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Update beta tag
run: |
# Get the latest version tag
VERSION=$(git tag -l 'v[0-9]*' | sort -V | tail -1)
# Update the beta tag to point to this release
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git tag -fa beta -m "Update beta tag to ${VERSION}"
git push origin beta --force
- name: Update beta release to be latest
env:
GH_TOKEN: ${{ github.token }}
run: |
# Update beta release to be marked as latest
gh release edit beta --latest
update-major-tag:
needs: create-release
if: ${{ !inputs.dry_run }}
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Update major version tag
run: |
next_version="${{ needs.create-release.outputs.next_version }}"
# Extract major version (e.g., v0 from v0.0.20)
major_version=$(echo "$next_version" | cut -d. -f1)
# Update the major version tag to point to this release
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git tag -fa "$major_version" -m "Update $major_version tag to $next_version"
git push origin "$major_version" --force
echo "Updated $major_version tag to point to $next_version"

View File

@@ -50,6 +50,20 @@ Thank you for your interest in contributing to Claude Code Action! This document
bun test
```
2. **Integration Tests** (using GitHub Actions locally):
```bash
./test-local.sh
```
This script:
- Installs `act` if not present (requires Homebrew on macOS)
- Runs the GitHub Action workflow locally using Docker
- Requires your `ANTHROPIC_API_KEY` to be set
On Apple Silicon Macs, the script automatically adds the `--container-architecture linux/amd64` flag to avoid compatibility issues.
## Pull Request Process
1. Create a new branch from `main`:
@@ -89,7 +103,13 @@ Thank you for your interest in contributing to Claude Code Action! This document
When modifying the action:
1. Test in a real GitHub Actions workflow by:
1. Test locally with the test script:
```bash
./test-local.sh
```
2. Test in a real GitHub Actions workflow by:
- Creating a test repository
- Using your branch as the action source:
```yaml

View File

@@ -70,8 +70,6 @@ jobs:
# NODE_ENV: test
# DEBUG: true
# API_URL: https://api.example.com
# Optional: limit the number of conversation turns
# max_turns: "5"
```
## Inputs
@@ -80,7 +78,6 @@ jobs:
| --------------------- | -------------------------------------------------------------------------------------------------------------------- | -------- | --------- |
| `anthropic_api_key` | Anthropic API key (required for direct API, not needed for Bedrock/Vertex) | No\* | - |
| `direct_prompt` | Direct prompt for Claude to execute automatically without needing a trigger (for automated workflows) | No | - |
| `max_turns` | Maximum number of conversation turns Claude can take (limits back-and-forth exchanges) | No | - |
| `timeout_minutes` | Timeout in minutes for execution | No | `30` |
| `github_token` | GitHub token for Claude to operate with. **Only include this if you're connecting a custom GitHub app of your own!** | No | - |
| `model` | Model to use (provider-specific format required for Bedrock/Vertex) | No | - |
@@ -149,40 +146,6 @@ For MCP servers that require sensitive information like API keys or tokens, use
# ... other inputs
```
#### Using Python MCP Servers with uv
For Python-based MCP servers managed with `uv`, you need to specify the directory containing your server:
```yaml
- uses: anthropics/claude-code-action@beta
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
mcp_config: |
{
"mcpServers": {
"my-python-server": {
"type": "stdio",
"command": "uv",
"args": [
"--directory",
"${{ github.workspace }}/path/to/server/",
"run",
"server_file.py"
]
}
}
}
allowed_tools: "my-python-server__<tool_name>" # Replace <tool_name> with your server's tool names
# ... other inputs
```
For example, if your Python MCP server is at `mcp_servers/weather.py`, you would use:
```yaml
"args":
["--directory", "${{ github.workspace }}/mcp_servers/", "run", "weather.py"]
```
**Important**:
- Always use GitHub Secrets (`${{ secrets.SECRET_NAME }}`) for sensitive values like API keys, tokens, or passwords. Never hardcode secrets directly in the workflow file.
@@ -348,24 +311,6 @@ You can pass custom environment variables to Claude Code execution using the `cl
The `claude_env` input accepts YAML format where each line defines a key-value pair. These environment variables will be available to Claude Code during execution, allowing it to run tests, build processes, or other commands that depend on specific environment configurations.
### Limiting Conversation Turns
You can use the `max_turns` parameter to limit the number of back-and-forth exchanges Claude can have during task execution. This is useful for:
- Controlling costs by preventing runaway conversations
- Setting time boundaries for automated workflows
- Ensuring predictable behavior in CI/CD pipelines
```yaml
- uses: anthropics/claude-code-action@beta
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
max_turns: "5" # Limit to 5 conversation turns
# ... other inputs
```
When the turn limit is reached, Claude will stop execution gracefully. Choose a value that gives Claude enough turns to complete typical tasks while preventing excessive usage.
### Custom Tools
By default, Claude only has access to:
@@ -381,15 +326,8 @@ Claude does **not** have access to execute arbitrary Bash commands by default. I
```yaml
- uses: anthropics/claude-code-action@beta
with:
allowed_tools: |
Bash(npm install)
Bash(npm run test)
Edit
Replace
NotebookEditCell
disallowed_tools: |
TaskOutput
KillTask
allowed_tools: "Bash(npm install),Bash(npm run test),Edit,Replace,NotebookEditCell"
disallowed_tools: "TaskOutput,KillTask"
# ... other inputs
```

View File

@@ -1,20 +0,0 @@
# Claude Code GitHub Action Roadmap
Thank you for trying out the beta of our GitHub Action! This document outlines our path to `v1.0`. Items are not necessarily in priority order.
## Path to 1.0
- **Ability to see GitHub Action CI results** - This will enable Claude to look at CI failures and make updates to PRs to fix test failures, lint errors, and the like.
- **Cross-repo support** - Enable Claude to work across multiple repositories in a single session
- **Ability to modify workflow files** - Let Claude update GitHub Actions workflows and other CI configuration files
- **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.
- **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
- **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
---
**Note:** This roadmap represents our current vision for reaching `v1.0` and is subject to change based on user feedback and development priorities.
We welcome feedback on these planned features! If you're interested in contributing to any of these features, please open an issue to discuss implementation details with us. We're also open to suggestions for new features not listed here.

View File

@@ -62,10 +62,6 @@ inputs:
required: false
default: "false"
max_turns:
description: "Maximum number of conversation turns"
required: false
default: ""
timeout_minutes:
description: "Timeout in minutes for execution"
required: false
@@ -87,20 +83,19 @@ runs:
- name: Install Dependencies
shell: bash
run: |
cd ${GITHUB_ACTION_PATH}
cd ${{ github.action_path }}
bun install
- name: Prepare action
id: prepare
shell: bash
run: |
bun run ${GITHUB_ACTION_PATH}/src/entrypoints/prepare.ts
bun run ${{ github.action_path }}/src/entrypoints/prepare.ts
env:
TRIGGER_PHRASE: ${{ inputs.trigger_phrase }}
ASSIGNEE_TRIGGER: ${{ inputs.assignee_trigger }}
BASE_BRANCH: ${{ inputs.base_branch }}
ALLOWED_TOOLS: ${{ inputs.allowed_tools }}
DISALLOWED_TOOLS: ${{ inputs.disallowed_tools }}
CUSTOM_INSTRUCTIONS: ${{ inputs.custom_instructions }}
DIRECT_PROMPT: ${{ inputs.direct_prompt }}
MCP_CONFIG: ${{ inputs.mcp_config }}
@@ -110,13 +105,12 @@ runs:
- name: Run Claude Code
id: claude-code
if: steps.prepare.outputs.contains_trigger == 'true'
uses: anthropics/claude-code-base-action@f382bd1ea00f26043eb461ebabebe0d850572a71 # v0.0.24
uses: anthropics/claude-code-base-action@9e4e150978667888ba2108a2ee63a79bf9cfbe06 # v0.0.10
with:
prompt_file: ${{ runner.temp }}/claude-prompts/claude-prompt.txt
prompt_file: /tmp/claude-prompts/claude-prompt.txt
allowed_tools: ${{ env.ALLOWED_TOOLS }}
disallowed_tools: ${{ env.DISALLOWED_TOOLS }}
timeout_minutes: ${{ inputs.timeout_minutes }}
max_turns: ${{ inputs.max_turns }}
model: ${{ inputs.model || inputs.anthropic_model }}
mcp_config: ${{ steps.prepare.outputs.mcp_config }}
use_bedrock: ${{ inputs.use_bedrock }}
@@ -153,7 +147,7 @@ runs:
if: steps.prepare.outputs.contains_trigger == 'true' && steps.prepare.outputs.claude_comment_id && always()
shell: bash
run: |
bun run ${GITHUB_ACTION_PATH}/src/entrypoints/update-comment-link.ts
bun run ${{ github.action_path }}/src/entrypoints/update-comment-link.ts
env:
REPOSITORY: ${{ github.repository }}
PR_NUMBER: ${{ github.event.issue.number || github.event.pull_request.number }}

View File

@@ -2,7 +2,7 @@
"lockfileVersion": 1,
"workspaces": {
"": {
"name": "@anthropic-ai/claude-code-action",
"name": "claude-pr-action",
"dependencies": {
"@actions/core": "^1.10.1",
"@actions/github": "^6.0.1",

View File

@@ -1,73 +0,0 @@
name: Claude Task Executor
on:
repository_dispatch:
types: [claude-task]
permissions:
contents: write
pull-requests: write
issues: write
id-token: write # Required for OIDC authentication
jobs:
execute-claude-task:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Execute Claude Task
uses: anthropics/claude-code-action@main
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
# Base branch for creating task branches
base_branch: main
# Optional: Custom instructions for Claude
custom_instructions: |
Follow the CLAUDE.md guidelines strictly.
Commit changes with descriptive messages.
# Optional: Tool restrictions
allowed_tools: |
file_editor
bash_command
github_comment
mcp__github__create_or_update_file
# Optional: Anthropic API configuration
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
# Or use AWS Bedrock
# aws_access_key: ${{ secrets.AWS_ACCESS_KEY_ID }}
# aws_secret_key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
# aws_region: us-east-1
# Or use Google Vertex AI
# google_credentials: ${{ secrets.GOOGLE_CREDENTIALS }}
# vertex_project: my-project
# vertex_location: us-central1
# Example: Triggering this workflow from another service
#
# curl -X POST \
# https://api.github.com/repos/owner/repo/dispatches \
# -H "Authorization: token $GITHUB_TOKEN" \
# -H "Accept: application/vnd.github.v3+json" \
# -d '{
# "event_type": "claude-task",
# "client_payload": {
# "description": "Analyze the codebase and create a comprehensive test suite for the authentication module",
# "progress_endpoint": "https://api.example.com/claude/progress",
# "correlation_id": "task-auth-tests-2024-01-17"
# }
# }'
#
# The progress_endpoint will receive POST requests with:
# {
# "repository": "owner/repo",
# "run_id": "123456789",
# "correlation_id": "task-auth-tests-2024-01-17",
# "status": "in_progress" | "completed" | "failed",
# "message": "Current progress description",
# "completed_tasks": ["task1", "task2"],
# "current_task": "Working on task3",
# "timestamp": "2024-01-17T12:00:00Z"
# }
#
# Authentication: Progress updates include a GitHub OIDC token in the Authorization header

View File

@@ -35,4 +35,4 @@ jobs:
Provide constructive feedback with specific suggestions for improvement.
Use inline comments to highlight specific areas of concern.
# allowed_tools: "mcp__github__create_pending_pull_request_review,mcp__github__add_pull_request_review_comment_to_pending_review,mcp__github__submit_pending_pull_request_review,mcp__github__get_pull_request_diff"
# allowed_tools: "mcp__github__add_pull_request_review_comment"

View File

@@ -1,5 +1,5 @@
{
"name": "@anthropic-ai/claude-code-action",
"name": "claude-pr-action",
"version": "1.0.0",
"private": true,
"scripts": {

View File

@@ -1,118 +0,0 @@
## Summary
Adds support for `repository_dispatch` events, enabling backend services to programmatically trigger Claude to perform tasks and receive progress updates via API.
## Architecture
```mermaid
sequenceDiagram
participant Backend as Backend Service
participant GH as GitHub
participant Action as Claude Action
participant Claude as Claude
participant MCP as Progress MCP Server
participant API as Progress API
Backend->>GH: POST /repos/{owner}/{repo}/dispatches
Note over Backend,GH: Payload includes:<br/>- description (task)<br/>- progress_endpoint<br/>- correlation_id
GH->>Action: Trigger workflow<br/>(repository_dispatch)
Action->>Action: Parse dispatch payload
Note over Action: Extract task description,<br/>endpoint, correlation_id
Action->>MCP: Install Progress Server
Note over MCP: Configure with:<br/>- PROGRESS_ENDPOINT<br/>- CORRELATION_ID<br/>- GITHUB_RUN_ID
Action->>Claude: Execute task with<br/>MCP tools available
loop Task Execution
Claude->>MCP: update_claude_progress()
MCP->>MCP: Get OIDC token
MCP->>API: POST progress update
Note over API: Payload includes:<br/>- correlation_id<br/>- status<br/>- message<br/>- completed_tasks
API->>Backend: Forward update
end
Claude->>Action: Task complete
Action->>GH: Commit changes
```
## Key Features
### 1. Repository Dispatch Support
- New event handler for `repository_dispatch` events
- Extracts task description, progress endpoint, and correlation ID from `client_payload`
- Bypasses GitHub UI interaction for fully programmatic operation
### 2. Progress Reporting MCP Server
- New MCP server (`progress-server.ts`) for sending progress updates
- OIDC authentication for secure API communication
- Includes correlation ID in all updates for request tracking
### 3. Simplified Dispatch Prompts
- Focused instructions for dispatch events (no PR/issue context)
- Clear directives: answer questions or implement changes
- Automatic progress updates at start and completion
## Implementation Details
### Triggering a Dispatch
```bash
curl -X POST \
https://api.github.com/repos/{owner}/{repo}/dispatches \
-H "Authorization: token $GITHUB_TOKEN" \
-H "Accept: application/vnd.github.v3+json" \
-d '{
"event_type": "claude-task",
"client_payload": {
"description": "Implement a new feature that...",
"progress_endpoint": "https://api.example.com/progress",
"correlation_id": "req-123-abc"
}
}'
```
### Progress Update Payload
```json
{
"repository": "owner/repo",
"run_id": "123456789",
"correlation_id": "req-123-abc",
"status": "in_progress",
"message": "Implementing feature...",
"completed_tasks": ["Setup environment", "Created base structure"],
"current_task": "Writing tests",
"timestamp": "2024-01-17T12:00:00Z"
}
```
## Security
- **OIDC Authentication**: All progress updates use GitHub OIDC tokens
- **Correlation IDs**: Included in request body (not URL) for security
- **Endpoint Validation**: Progress endpoint must be explicitly provided
- **No Credential Storage**: Tokens are generated per-request
## Testing
To test the repository_dispatch flow:
1. Configure workflow with `repository_dispatch` trigger
2. Send dispatch event with required payload
3. Monitor GitHub Actions logs for execution
4. Verify progress updates at configured endpoint
## Changes
- Added `repository_dispatch` event handling in `context.ts`
- Created new `progress-server.ts` MCP server
- Updated `isDispatch` flag across all event types
- Modified prompt generation for dispatch events
- Made `githubData` optional for dispatch workflows
- Added correlation ID support throughout the pipeline

View File

@@ -24,7 +24,6 @@ export type { CommonFields, PreparedContext } from "./types";
const BASE_ALLOWED_TOOLS = [
"Edit",
"MultiEdit",
"Glob",
"Grep",
"LS",
@@ -418,7 +417,6 @@ ${
}
<claude_comment_id>${context.claudeCommentId}</claude_comment_id>
<trigger_username>${context.triggerUsername ?? "Unknown"}</trigger_username>
<trigger_display_name>${githubData.triggerDisplayName ?? context.triggerUsername ?? "Unknown"}</trigger_display_name>
<trigger_phrase>${context.triggerPhrase}</trigger_phrase>
${
(eventData.eventName === "issue_comment" ||
@@ -504,14 +502,12 @@ ${context.directPrompt ? ` - DIRECT INSTRUCTION: A direct instruction was prov
? `
- Push directly using mcp__github_file_ops__commit_files to the existing branch (works for both new and existing files).
- Use mcp__github_file_ops__commit_files to commit files atomically in a single commit (supports single or multiple files).
- When pushing changes with this tool and the trigger user is not "Unknown", include a Co-authored-by trailer in the commit message.
- Use: "Co-authored-by: ${githubData.triggerDisplayName ?? context.triggerUsername} <${context.triggerUsername}@users.noreply.github.com>"`
- When pushing changes with this tool and TRIGGER_USERNAME is not "Unknown", include a "Co-authored-by: ${context.triggerUsername} <${context.triggerUsername}@users.noreply.github.com>" line in the commit message.`
: `
- You are already on the correct branch (${eventData.claudeBranch || "the PR branch"}). Do not create a new branch.
- Push changes directly to the current branch using mcp__github_file_ops__commit_files (works for both new and existing files)
- Use mcp__github_file_ops__commit_files to commit files atomically in a single commit (supports single or multiple files).
- When pushing changes and the trigger user is not "Unknown", include a Co-authored-by trailer in the commit message.
- Use: "Co-authored-by: ${githubData.triggerDisplayName ?? context.triggerUsername} <${context.triggerUsername}@users.noreply.github.com>"
- When pushing changes and TRIGGER_USERNAME is not "Unknown", include a "Co-authored-by: ${context.triggerUsername} <${context.triggerUsername}@users.noreply.github.com>" line in the commit message.
${
eventData.claudeBranch
? `- Provide a URL to create a PR manually in this format:
@@ -624,9 +620,7 @@ export async function createPrompt(
claudeBranch,
);
await mkdir(`${process.env.RUNNER_TEMP}/claude-prompts`, {
recursive: true,
});
await mkdir("/tmp/claude-prompts", { recursive: true });
// Generate the prompt
const promptContent = generatePrompt(preparedContext, githubData);
@@ -637,10 +631,7 @@ export async function createPrompt(
console.log("=======================");
// Write the prompt file
await writeFile(
`${process.env.RUNNER_TEMP}/claude-prompts/claude-prompt.txt`,
promptContent,
);
await writeFile("/tmp/claude-prompts/claude-prompt.txt", promptContent);
// Set allowed tools
const allAllowedTools = buildAllowedToolsString(

View File

@@ -59,7 +59,6 @@ async function run() {
repository: `${context.repository.owner}/${context.repository.repo}`,
prNumber: context.entityNumber.toString(),
isPR: context.isPR,
triggerUsername: context.actor,
});
// Step 8: Setup branch

View File

@@ -104,11 +104,3 @@ export const ISSUE_QUERY = `
}
}
`;
export const USER_QUERY = `
query($login: String!) {
user(login: $login) {
name
}
}
`;

View File

@@ -1,7 +1,6 @@
import * as github from "@actions/github";
import type {
IssuesEvent,
IssuesAssignedEvent,
IssueCommentEvent,
PullRequestEvent,
PullRequestReviewEvent,
@@ -53,8 +52,14 @@ export function parseGitHubContext(): ParsedGitHubContext {
inputs: {
triggerPhrase: process.env.TRIGGER_PHRASE ?? "@claude",
assigneeTrigger: process.env.ASSIGNEE_TRIGGER ?? "",
allowedTools: parseMultilineInput(process.env.ALLOWED_TOOLS ?? ""),
disallowedTools: parseMultilineInput(process.env.DISALLOWED_TOOLS ?? ""),
allowedTools: (process.env.ALLOWED_TOOLS ?? "")
.split(",")
.map((tool) => tool.trim())
.filter((tool) => tool.length > 0),
disallowedTools: (process.env.DISALLOWED_TOOLS ?? "")
.split(",")
.map((tool) => tool.trim())
.filter((tool) => tool.length > 0),
customInstructions: process.env.CUSTOM_INSTRUCTIONS ?? "",
directPrompt: process.env.DIRECT_PROMPT ?? "",
baseBranch: process.env.BASE_BRANCH,
@@ -111,14 +116,6 @@ export function parseGitHubContext(): ParsedGitHubContext {
}
}
export function parseMultilineInput(s: string): string[] {
return s
.split(/,|[\n\r]+/)
.map((tool) => tool.replace(/#.+$/, ""))
.map((tool) => tool.trim())
.filter((tool) => tool.length > 0);
}
export function isIssuesEvent(
context: ParsedGitHubContext,
): context is ParsedGitHubContext & { payload: IssuesEvent } {
@@ -148,9 +145,3 @@ export function isPullRequestReviewCommentEvent(
): context is ParsedGitHubContext & { payload: PullRequestReviewCommentEvent } {
return context.eventName === "pull_request_review_comment";
}
export function isIssuesAssignedEvent(
context: ParsedGitHubContext,
): context is ParsedGitHubContext & { payload: IssuesAssignedEvent } {
return isIssuesEvent(context) && context.eventAction === "assigned";
}

View File

@@ -1,6 +1,6 @@
import { execSync } from "child_process";
import type { Octokits } from "../api/client";
import { ISSUE_QUERY, PR_QUERY, USER_QUERY } from "../api/queries/github";
import { ISSUE_QUERY, PR_QUERY } from "../api/queries/github";
import type {
GitHubComment,
GitHubFile,
@@ -18,7 +18,6 @@ type FetchDataParams = {
repository: string;
prNumber: string;
isPR: boolean;
triggerUsername?: string;
};
export type GitHubFileWithSHA = GitHubFile & {
@@ -32,7 +31,6 @@ export type FetchDataResult = {
changedFilesWithSHA: GitHubFileWithSHA[];
reviewData: { nodes: GitHubReview[] } | null;
imageUrlMap: Map<string, string>;
triggerDisplayName?: string | null;
};
export async function fetchGitHubData({
@@ -40,7 +38,6 @@ export async function fetchGitHubData({
repository,
prNumber,
isPR,
triggerUsername,
}: FetchDataParams): Promise<FetchDataResult> {
const [owner, repo] = repository.split("/");
if (!owner || !repo) {
@@ -194,12 +191,6 @@ export async function fetchGitHubData({
allComments,
);
// Fetch trigger user display name if username is provided
let triggerDisplayName: string | null | undefined;
if (triggerUsername) {
triggerDisplayName = await fetchUserDisplayName(octokits, triggerUsername);
}
return {
contextData,
comments,
@@ -207,27 +198,5 @@ export async function fetchGitHubData({
changedFilesWithSHA,
reviewData,
imageUrlMap,
triggerDisplayName,
};
}
export type UserQueryResponse = {
user: {
name: string | null;
};
};
export async function fetchUserDisplayName(
octokits: Octokits,
login: string,
): Promise<string | null> {
try {
const result = await octokits.graphql<UserQueryResponse>(USER_QUERY, {
login,
});
return result.user.name;
} catch (error) {
console.warn(`Failed to fetch user display name for ${login}:`, error);
return null;
}
}

View File

@@ -45,16 +45,9 @@ export async function setupBranch(
const branchName = prData.headRefName;
// Determine optimal fetch depth based on PR commit count, with a minimum of 20
const commitCount = prData.commits.totalCount;
const fetchDepth = Math.max(commitCount, 20);
console.log(
`PR #${entityNumber}: ${commitCount} commits, using fetch depth ${fetchDepth}`,
);
// Execute git commands to checkout PR branch (dynamic depth based on PR size)
await $`git fetch origin --depth=${fetchDepth} ${branchName}`;
// Execute git commands to checkout PR branch (shallow fetch for performance)
// Fetch the branch with a depth of 20 to avoid fetching too much history, while still allowing for some context
await $`git fetch origin --depth=20 ${branchName}`;
await $`git checkout ${branchName}`;
console.log(`Successfully checked out PR branch for PR #${entityNumber}`);

View File

@@ -1,7 +1,6 @@
// Types for GitHub GraphQL query responses
export type GitHubAuthor = {
login: string;
name?: string;
};
export type GitHubComment = {

View File

@@ -3,7 +3,6 @@
import * as core from "@actions/core";
import {
isIssuesEvent,
isIssuesAssignedEvent,
isIssueCommentEvent,
isPullRequestEvent,
isPullRequestReviewEvent,
@@ -23,10 +22,10 @@ export function checkContainsTrigger(context: ParsedGitHubContext): boolean {
}
// Check for assignee trigger
if (isIssuesAssignedEvent(context)) {
if (isIssuesEvent(context) && context.eventAction === "assigned") {
// Remove @ symbol from assignee_trigger if present
let triggerUser = assigneeTrigger.replace(/^@/, "");
const assigneeUsername = context.payload.assignee?.login || "";
const assigneeUsername = context.payload.issue.assignee?.login || "";
if (triggerUser && assigneeUsername === triggerUser) {
console.log(`Issue assigned to trigger user '${triggerUser}'`);

View File

@@ -466,7 +466,6 @@ server.tool(
const octokit = new Octokit({
auth: githubToken,
baseUrl: GITHUB_API_URL,
});
const isPullRequestReviewComment =

View File

@@ -1,5 +1,4 @@
import * as core from "@actions/core";
import { GITHUB_API_URL } from "../github/api/config";
type PrepareConfigParams = {
githubToken: string;
@@ -47,7 +46,6 @@ export async function prepareMcpConfig(
...(claudeCommentId && { CLAUDE_COMMENT_ID: claudeCommentId }),
GITHUB_EVENT_NAME: process.env.GITHUB_EVENT_NAME || "",
IS_PR: process.env.IS_PR || "false",
GITHUB_API_URL: GITHUB_API_URL,
},
},
},
@@ -62,7 +60,7 @@ export async function prepareMcpConfig(
"--rm",
"-e",
"GITHUB_PERSONAL_ACCESS_TOKEN",
"ghcr.io/github/github-mcp-server:sha-6d69797", // https://github.com/github/github-mcp-server/releases/tag/v0.5.0
"ghcr.io/github/github-mcp-server:sha-e9f748f", // https://github.com/github/github-mcp-server/releases/tag/v0.4.0
],
env: {
GITHUB_PERSONAL_ACCESS_TOKEN: githubToken,

View File

@@ -316,7 +316,7 @@ describe("generatePrompt", () => {
expect(prompt).toContain("<trigger_username>johndoe</trigger_username>");
expect(prompt).toContain(
'Use: "Co-authored-by: johndoe <johndoe@users.noreply.github.com>"',
"Co-authored-by: johndoe <johndoe@users.noreply.github.com>",
);
});

View File

@@ -1,57 +0,0 @@
import { describe, it, expect } from "bun:test";
import { parseMultilineInput } from "../../src/github/context";
describe("parseMultilineInput", () => {
it("should parse a comma-separated string", () => {
const input = `Bash(bun install),Bash(bun test:*),Bash(bun typecheck)`;
const result = parseMultilineInput(input);
expect(result).toEqual([
"Bash(bun install)",
"Bash(bun test:*)",
"Bash(bun typecheck)",
]);
});
it("should parse multiline string", () => {
const input = `Bash(bun install)
Bash(bun test:*)
Bash(bun typecheck)`;
const result = parseMultilineInput(input);
expect(result).toEqual([
"Bash(bun install)",
"Bash(bun test:*)",
"Bash(bun typecheck)",
]);
});
it("should parse comma-separated multiline line", () => {
const input = `Bash(bun install),Bash(bun test:*)
Bash(bun typecheck)`;
const result = parseMultilineInput(input);
expect(result).toEqual([
"Bash(bun install)",
"Bash(bun test:*)",
"Bash(bun typecheck)",
]);
});
it("should ignore comments", () => {
const input = `Bash(bun install),
Bash(bun test:*) # For testing
# For type checking
Bash(bun typecheck)
`;
const result = parseMultilineInput(input);
expect(result).toEqual([
"Bash(bun install)",
"Bash(bun test:*)",
"Bash(bun typecheck)",
]);
});
it("should parse an empty string", () => {
const input = "";
const result = parseMultilineInput(input);
expect(result).toEqual([]);
});
});

View File

@@ -91,12 +91,6 @@ export const mockIssueAssignedContext: ParsedGitHubContext = {
actor: "admin-user",
payload: {
action: "assigned",
assignee: {
login: "claude-bot",
id: 11111,
avatar_url: "https://avatars.githubusercontent.com/u/11111",
html_url: "https://github.com/claude-bot",
},
issue: {
number: 123,
title: "Feature: Add dark mode support",

View File

@@ -87,11 +87,6 @@ describe("checkContainsTrigger", () => {
...mockIssueAssignedContext,
payload: {
...mockIssueAssignedContext.payload,
assignee: {
...(mockIssueAssignedContext.payload as IssuesAssignedEvent)
.assignee,
login: "otherUser",
},
issue: {
...(mockIssueAssignedContext.payload as IssuesAssignedEvent).issue,
assignee: {