mirror of
https://github.com/anthropics/claude-code-action.git
synced 2026-01-23 15:04:13 +08:00
Compare commits
16 Commits
testenvvar
...
km/add-mcp
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
340104d9cf | ||
|
|
9abdfa8a3a | ||
|
|
56179f5fc9 | ||
|
|
0e5fbc0d44 | ||
|
|
6c5d11c8c3 | ||
|
|
106183c4c0 | ||
|
|
7cc3cff20b | ||
|
|
b4cc5cd6c5 | ||
|
|
1b4ac7d7e0 | ||
|
|
1f6e3225b0 | ||
|
|
6672e9b357 | ||
|
|
950bdc01df | ||
|
|
15dd796e97 | ||
|
|
fd012347a2 | ||
|
|
5bdc533a52 | ||
|
|
d45539c118 |
2
.github/workflows/claude-review.yml
vendored
2
.github/workflows/claude-review.yml
vendored
@@ -30,4 +30,4 @@ jobs:
|
|||||||
|
|
||||||
Be constructive and specific in your feedback. Give inline comments where applicable.
|
Be constructive and specific in your feedback. Give inline comments where applicable.
|
||||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
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__create_pending_pull_request_review,mcp__github__add_comment_to_pending_review,mcp__github__submit_pending_pull_request_review,mcp__github__get_pull_request_diff"
|
||||||
|
|||||||
128
CLAUDE.md
128
CLAUDE.md
@@ -1,10 +1,11 @@
|
|||||||
# CLAUDE.md
|
# CLAUDE.md
|
||||||
|
|
||||||
This file provides guidance to Claude Code when working with code in this repository.
|
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||||
|
|
||||||
## Development Tools
|
## Development Tools
|
||||||
|
|
||||||
- Runtime: Bun 1.2.11
|
- Runtime: Bun 1.2.11
|
||||||
|
- TypeScript with strict configuration
|
||||||
|
|
||||||
## Common Development Tasks
|
## Common Development Tasks
|
||||||
|
|
||||||
@@ -17,42 +18,119 @@ bun test
|
|||||||
# Formatting
|
# Formatting
|
||||||
bun run format # Format code with prettier
|
bun run format # Format code with prettier
|
||||||
bun run format:check # Check code formatting
|
bun run format:check # Check code formatting
|
||||||
|
|
||||||
|
# Type checking
|
||||||
|
bun run typecheck # Run TypeScript type checker
|
||||||
```
|
```
|
||||||
|
|
||||||
## Architecture Overview
|
## Architecture Overview
|
||||||
|
|
||||||
This is a GitHub Action that enables Claude to interact with GitHub PRs and issues. The action:
|
This is a GitHub Action that enables Claude to interact with GitHub PRs and issues. The action operates in two main phases:
|
||||||
|
|
||||||
1. **Trigger Detection**: Uses `check-trigger.ts` to determine if Claude should respond based on comment/issue content
|
### Phase 1: Preparation (`src/entrypoints/prepare.ts`)
|
||||||
2. **Context Gathering**: Fetches GitHub data (PRs, issues, comments) via `github-data-fetcher.ts` and formats it using `github-data-formatter.ts`
|
|
||||||
3. **AI Integration**: Supports multiple Claude providers (Anthropic API, AWS Bedrock, Google Vertex AI)
|
|
||||||
4. **Prompt Creation**: Generates context-rich prompts using `create-prompt.ts`
|
|
||||||
5. **MCP Server Integration**: Installs and configures GitHub MCP server for extended functionality
|
|
||||||
|
|
||||||
### Key Components
|
1. **Authentication Setup**: Establishes GitHub token via OIDC or GitHub App
|
||||||
|
2. **Permission Validation**: Verifies actor has write permissions
|
||||||
|
3. **Trigger Detection**: Uses mode-specific logic to determine if Claude should respond
|
||||||
|
4. **Context Creation**: Prepares GitHub context and initial tracking comment
|
||||||
|
|
||||||
- **Trigger System**: Responds to `/claude` comments or issue assignments
|
### Phase 2: Execution (`base-action/`)
|
||||||
- **Authentication**: OIDC-based token exchange for secure GitHub interactions
|
|
||||||
- **Cloud Integration**: Supports direct Anthropic API, AWS Bedrock, and Google Vertex AI
|
The `base-action/` directory contains the core Claude Code execution logic, which serves a dual purpose:
|
||||||
- **GitHub Operations**: Creates branches, posts comments, and manages PRs/issues
|
|
||||||
|
- **Standalone Action**: Published separately as `@anthropic-ai/claude-code-base-action` for direct use
|
||||||
|
- **Inner Logic**: Used internally by this GitHub Action after preparation phase completes
|
||||||
|
|
||||||
|
Execution steps:
|
||||||
|
|
||||||
|
1. **MCP Server Setup**: Installs and configures GitHub MCP server for tool access
|
||||||
|
2. **Prompt Generation**: Creates context-rich prompts from GitHub data
|
||||||
|
3. **Claude Integration**: Executes via multiple providers (Anthropic API, AWS Bedrock, Google Vertex AI)
|
||||||
|
4. **Result Processing**: Updates comments and creates branches/PRs as needed
|
||||||
|
|
||||||
|
### Key Architectural Components
|
||||||
|
|
||||||
|
#### Mode System (`src/modes/`)
|
||||||
|
|
||||||
|
- **Tag Mode** (`tag/`): Responds to `@claude` mentions and issue assignments
|
||||||
|
- **Agent Mode** (`agent/`): Automated execution without trigger checking
|
||||||
|
- Extensible registry pattern in `modes/registry.ts`
|
||||||
|
|
||||||
|
#### GitHub Integration (`src/github/`)
|
||||||
|
|
||||||
|
- **Context Parsing** (`context.ts`): Unified GitHub event handling
|
||||||
|
- **Data Fetching** (`data/fetcher.ts`): Retrieves PR/issue data via GraphQL/REST
|
||||||
|
- **Data Formatting** (`data/formatter.ts`): Converts GitHub data to Claude-readable format
|
||||||
|
- **Branch Operations** (`operations/branch.ts`): Handles branch creation and cleanup
|
||||||
|
- **Comment Management** (`operations/comments/`): Creates and updates tracking comments
|
||||||
|
|
||||||
|
#### MCP Server Integration (`src/mcp/`)
|
||||||
|
|
||||||
|
- **GitHub Actions Server** (`github-actions-server.ts`): Workflow and CI access
|
||||||
|
- **GitHub Comment Server** (`github-comment-server.ts`): Comment operations
|
||||||
|
- **GitHub File Operations** (`github-file-ops-server.ts`): File system access
|
||||||
|
- Auto-installation and configuration in `install-mcp-server.ts`
|
||||||
|
|
||||||
|
#### Authentication & Security (`src/github/`)
|
||||||
|
|
||||||
|
- **Token Management** (`token.ts`): OIDC token exchange and GitHub App authentication
|
||||||
|
- **Permission Validation** (`validation/permissions.ts`): Write access verification
|
||||||
|
- **Actor Validation** (`validation/actor.ts`): Human vs bot detection
|
||||||
|
|
||||||
### Project Structure
|
### Project Structure
|
||||||
|
|
||||||
```
|
```
|
||||||
src/
|
src/
|
||||||
├── check-trigger.ts # Determines if Claude should respond
|
├── entrypoints/ # Action entry points
|
||||||
├── create-prompt.ts # Generates contextual prompts
|
│ ├── prepare.ts # Main preparation logic
|
||||||
├── github-data-fetcher.ts # Retrieves GitHub data
|
│ ├── update-comment-link.ts # Post-execution comment updates
|
||||||
├── github-data-formatter.ts # Formats GitHub data for prompts
|
│ └── format-turns.ts # Claude conversation formatting
|
||||||
├── install-mcp-server.ts # Sets up GitHub MCP server
|
├── github/ # GitHub integration layer
|
||||||
├── update-comment-with-link.ts # Updates comments with job links
|
│ ├── api/ # REST/GraphQL clients
|
||||||
└── types/
|
│ ├── data/ # Data fetching and formatting
|
||||||
└── github.ts # TypeScript types for GitHub data
|
│ ├── operations/ # Branch, comment, git operations
|
||||||
|
│ ├── validation/ # Permission and trigger validation
|
||||||
|
│ └── utils/ # Image downloading, sanitization
|
||||||
|
├── modes/ # Execution modes
|
||||||
|
│ ├── tag/ # @claude mention mode
|
||||||
|
│ ├── agent/ # Automation mode
|
||||||
|
│ └── registry.ts # Mode selection logic
|
||||||
|
├── mcp/ # MCP server implementations
|
||||||
|
├── prepare/ # Preparation orchestration
|
||||||
|
└── utils/ # Shared utilities
|
||||||
```
|
```
|
||||||
|
|
||||||
## Important Notes
|
## Important Implementation Notes
|
||||||
|
|
||||||
- Actions are triggered by `@claude` comments or issue assignment unless a different trigger_phrase is specified
|
### Authentication Flow
|
||||||
- The action creates branches for issues and pushes to PR branches directly
|
|
||||||
- All actions create OIDC tokens for secure authentication
|
- Uses GitHub OIDC token exchange for secure authentication
|
||||||
- Progress is tracked through dynamic comment updates with checkboxes
|
- Supports custom GitHub Apps via `APP_ID` and `APP_PRIVATE_KEY`
|
||||||
|
- Falls back to official Claude GitHub App if no custom app provided
|
||||||
|
|
||||||
|
### MCP Server Architecture
|
||||||
|
|
||||||
|
- Each MCP server has specific GitHub API access patterns
|
||||||
|
- Servers are auto-installed in `~/.claude/mcp/github-{type}-server/`
|
||||||
|
- Configuration merged with user-provided MCP config via `mcp_config` input
|
||||||
|
|
||||||
|
### Mode System Design
|
||||||
|
|
||||||
|
- Modes implement `Mode` interface with `shouldTrigger()` and `prepare()` methods
|
||||||
|
- Registry validates mode compatibility with GitHub event types
|
||||||
|
- Agent mode bypasses all trigger checking for automation scenarios
|
||||||
|
|
||||||
|
### Comment Threading
|
||||||
|
|
||||||
|
- Single tracking comment updated throughout execution
|
||||||
|
- Progress indicated via dynamic checkboxes
|
||||||
|
- Links to job runs and created branches/PRs
|
||||||
|
- Sticky comment option for consolidated PR comments
|
||||||
|
|
||||||
|
## Code Conventions
|
||||||
|
|
||||||
|
- Use Bun-specific TypeScript configuration with `moduleResolution: "bundler"`
|
||||||
|
- Strict TypeScript with `noUnusedLocals` and `noUnusedParameters` enabled
|
||||||
|
- Prefer explicit error handling with detailed error messages
|
||||||
|
- Use discriminated unions for GitHub context types
|
||||||
|
- Implement retry logic for GitHub API operations via `utils/retry.ts`
|
||||||
|
|||||||
85
README.md
85
README.md
@@ -167,36 +167,36 @@ jobs:
|
|||||||
|
|
||||||
## Inputs
|
## Inputs
|
||||||
|
|
||||||
| Input | Description | Required | Default |
|
| Input | Description | Required | Default |
|
||||||
| ------------------------------ | ---------------------------------------------------------------------------------------------------------------------- | -------- | --------- |
|
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- | -------- | --------- |
|
||||||
| `mode` | Execution mode: 'tag' (default - triggered by mentions/assignments), 'agent' (for automation with no trigger checking) | No | `tag` |
|
| `mode` | Execution mode: 'tag' (default - triggered by mentions/assignments), 'agent' (for automation), 'experimental-review' (for PR reviews) | No | `tag` |
|
||||||
| `anthropic_api_key` | Anthropic API key (required for direct API, not needed for Bedrock/Vertex) | No\* | - |
|
| `anthropic_api_key` | Anthropic API key (required for direct API, not needed for Bedrock/Vertex) | No\* | - |
|
||||||
| `claude_code_oauth_token` | Claude Code OAuth token (alternative to anthropic_api_key) | No\* | - |
|
| `claude_code_oauth_token` | Claude Code OAuth token (alternative to anthropic_api_key) | No\* | - |
|
||||||
| `direct_prompt` | Direct prompt for Claude to execute automatically without needing a trigger (for automated workflows) | No | - |
|
| `direct_prompt` | Direct prompt for Claude to execute automatically without needing a trigger (for automated workflows) | No | - |
|
||||||
| `override_prompt` | Complete replacement of Claude's prompt with custom template (supports variable substitution) | No | - |
|
| `override_prompt` | Complete replacement of Claude's prompt with custom template (supports variable substitution) | No | - |
|
||||||
| `base_branch` | The base branch to use for creating new branches (e.g., 'main', 'develop') | No | - |
|
| `base_branch` | The base branch to use for creating new branches (e.g., 'main', 'develop') | No | - |
|
||||||
| `max_turns` | Maximum number of conversation turns Claude can take (limits back-and-forth exchanges) | 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` |
|
| `timeout_minutes` | Timeout in minutes for execution | No | `30` |
|
||||||
| `use_sticky_comment` | Use just one comment to deliver PR comments (only applies for pull_request event workflows) | No | `false` |
|
| `use_sticky_comment` | Use just one comment to deliver PR comments (only applies for pull_request event workflows) | No | `false` |
|
||||||
| `github_token` | GitHub token for Claude to operate with. **Only include this if you're connecting a custom GitHub app of your own!** | No | - |
|
| `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 | - |
|
| `model` | Model to use (provider-specific format required for Bedrock/Vertex) | No | - |
|
||||||
| `fallback_model` | Enable automatic fallback to specified model when primary model is unavailable | No | - |
|
| `fallback_model` | Enable automatic fallback to specified model when primary model is unavailable | No | - |
|
||||||
| `anthropic_model` | **DEPRECATED**: Use `model` instead. Kept for backward compatibility. | No | - |
|
| `anthropic_model` | **DEPRECATED**: Use `model` instead. Kept for backward compatibility. | No | - |
|
||||||
| `use_bedrock` | Use Amazon Bedrock with OIDC authentication instead of direct Anthropic API | No | `false` |
|
| `use_bedrock` | Use Amazon Bedrock with OIDC authentication instead of direct Anthropic API | No | `false` |
|
||||||
| `use_vertex` | Use Google Vertex AI with OIDC authentication instead of direct Anthropic API | No | `false` |
|
| `use_vertex` | Use Google Vertex AI with OIDC authentication instead of direct Anthropic API | No | `false` |
|
||||||
| `allowed_tools` | Additional tools for Claude to use (the base GitHub tools will always be included) | No | "" |
|
| `allowed_tools` | Additional tools for Claude to use (the base GitHub tools will always be included) | No | "" |
|
||||||
| `disallowed_tools` | Tools that Claude should never use | No | "" |
|
| `disallowed_tools` | Tools that Claude should never use | No | "" |
|
||||||
| `custom_instructions` | Additional custom instructions to include in the prompt for Claude | No | "" |
|
| `custom_instructions` | Additional custom instructions to include in the prompt for Claude | No | "" |
|
||||||
| `mcp_config` | Additional MCP configuration (JSON string) that merges with the built-in GitHub MCP servers | No | "" |
|
| `mcp_config` | Additional MCP configuration (JSON string) that merges with the built-in GitHub MCP servers | No | "" |
|
||||||
| `assignee_trigger` | The assignee username that triggers the action (e.g. @claude). Only used for issue assignment | No | - |
|
| `assignee_trigger` | The assignee username that triggers the action (e.g. @claude). Only used for issue assignment | No | - |
|
||||||
| `label_trigger` | The label name that triggers the action when applied to an issue (e.g. "claude") | No | - |
|
| `label_trigger` | The label name that triggers the action when applied to an issue (e.g. "claude") | No | - |
|
||||||
| `trigger_phrase` | The trigger phrase to look for in comments, issue/PR bodies, and issue titles | No | `@claude` |
|
| `trigger_phrase` | The trigger phrase to look for in comments, issue/PR bodies, and issue titles | No | `@claude` |
|
||||||
| `branch_prefix` | The prefix to use for Claude branches (defaults to 'claude/', use 'claude-' for dash format) | No | `claude/` |
|
| `branch_prefix` | The prefix to use for Claude branches (defaults to 'claude/', use 'claude-' for dash format) | No | `claude/` |
|
||||||
| `claude_env` | Custom environment variables to pass to Claude Code execution (YAML format) | No | "" |
|
| `claude_env` | Custom environment variables to pass to Claude Code execution (YAML format) | No | "" |
|
||||||
| `settings` | Claude Code settings as JSON string or path to settings JSON file | No | "" |
|
| `settings` | Claude Code settings as JSON string or path to settings JSON file | No | "" |
|
||||||
| `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` |
|
||||||
|
|
||||||
\*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)
|
||||||
|
|
||||||
@@ -204,7 +204,7 @@ jobs:
|
|||||||
|
|
||||||
## Execution Modes
|
## Execution Modes
|
||||||
|
|
||||||
The action supports two execution modes, each optimized for different use cases:
|
The action supports three execution modes, each optimized for different use cases:
|
||||||
|
|
||||||
### Tag Mode (Default)
|
### Tag Mode (Default)
|
||||||
|
|
||||||
@@ -238,7 +238,28 @@ For automation and scheduled tasks without trigger checking.
|
|||||||
Check for outdated dependencies and create an issue if any are found.
|
Check for outdated dependencies and create an issue if any are found.
|
||||||
```
|
```
|
||||||
|
|
||||||
See [`examples/claude-modes.yml`](./examples/claude-modes.yml) for complete examples of each mode.
|
### Experimental Review Mode
|
||||||
|
|
||||||
|
> **EXPERIMENTAL**: This mode is under active development and may change significantly. Use with caution in production workflows.
|
||||||
|
|
||||||
|
Specialized mode for automated PR code reviews using GitHub's review API.
|
||||||
|
|
||||||
|
- **Triggers**: Automatically on PR events (opened, synchronize, reopened) when configured in workflow
|
||||||
|
- **Features**: Creates inline review comments with suggestions, batches feedback into a single review
|
||||||
|
- **Use case**: Automated code reviews, security scanning, best practices enforcement
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
- uses: anthropics/claude-code-action@beta
|
||||||
|
with:
|
||||||
|
mode: experimental-review
|
||||||
|
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||||
|
custom_instructions: |
|
||||||
|
Focus on security vulnerabilities, performance issues, and code quality.
|
||||||
|
```
|
||||||
|
|
||||||
|
Review mode automatically includes GitHub MCP tools for creating pending reviews and inline comments. See [`examples/claude-experimental-review-mode.yml`](./examples/claude-experimental-review-mode.yml) for a complete example.
|
||||||
|
|
||||||
|
See [`examples/claude-modes.yml`](./examples/claude-modes.yml) for complete examples of available modes.
|
||||||
|
|
||||||
### Using Custom MCP Configuration
|
### Using Custom MCP Configuration
|
||||||
|
|
||||||
|
|||||||
@@ -26,7 +26,7 @@ inputs:
|
|||||||
|
|
||||||
# Mode configuration
|
# Mode configuration
|
||||||
mode:
|
mode:
|
||||||
description: "Execution mode for the action. Valid modes: 'tag' (default - triggered by mentions/assignments), 'agent' (for automation with no trigger checking)"
|
description: "Execution mode for the action. Valid modes: 'tag' (default - triggered by mentions/assignments), 'agent' (for automation with no trigger checking), 'experimental-review' (experimental mode for code reviews with inline comments and suggestions)"
|
||||||
required: false
|
required: false
|
||||||
default: "tag"
|
default: "tag"
|
||||||
|
|
||||||
@@ -158,7 +158,7 @@ runs:
|
|||||||
OVERRIDE_GITHUB_TOKEN: ${{ inputs.github_token }}
|
OVERRIDE_GITHUB_TOKEN: ${{ inputs.github_token }}
|
||||||
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 }}
|
||||||
ACTIONS_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 }}
|
||||||
|
|
||||||
@@ -172,7 +172,7 @@ 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.63
|
bun install -g @anthropic-ai/claude-code@1.0.66
|
||||||
|
|
||||||
- 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 != ''
|
||||||
|
|||||||
@@ -115,7 +115,7 @@ runs:
|
|||||||
|
|
||||||
- name: Install Claude Code
|
- name: Install Claude Code
|
||||||
shell: bash
|
shell: bash
|
||||||
run: bun install -g @anthropic-ai/claude-code@1.0.63
|
run: bun install -g @anthropic-ai/claude-code@1.0.66
|
||||||
|
|
||||||
- name: Run Claude Code Action
|
- name: Run Claude Code Action
|
||||||
shell: bash
|
shell: bash
|
||||||
|
|||||||
@@ -35,4 +35,4 @@ jobs:
|
|||||||
|
|
||||||
Provide constructive feedback with specific suggestions for improvement.
|
Provide constructive feedback with specific suggestions for improvement.
|
||||||
Use inline comments to highlight specific areas of concern.
|
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__create_pending_pull_request_review,mcp__github__add_comment_to_pending_review,mcp__github__submit_pending_pull_request_review,mcp__github__get_pull_request_diff"
|
||||||
|
|||||||
45
examples/claude-experimental-review-mode.yml
Normal file
45
examples/claude-experimental-review-mode.yml
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
name: Claude Experimental Review Mode
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
types: [opened, synchronize]
|
||||||
|
issue_comment:
|
||||||
|
types: [created]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
code-review:
|
||||||
|
# Run on PR events, or when someone comments "@claude review" on a PR
|
||||||
|
if: |
|
||||||
|
github.event_name == 'pull_request' ||
|
||||||
|
(github.event_name == 'issue_comment' &&
|
||||||
|
github.event.issue.pull_request &&
|
||||||
|
contains(github.event.comment.body, '@claude review'))
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
pull-requests: write
|
||||||
|
issues: write
|
||||||
|
id-token: write
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0 # Full history for better diff analysis
|
||||||
|
|
||||||
|
- name: Code Review with Claude
|
||||||
|
uses: anthropics/claude-code-action@beta
|
||||||
|
with:
|
||||||
|
mode: experimental-review
|
||||||
|
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||||
|
# github_token not needed - uses default GITHUB_TOKEN for GitHub operations
|
||||||
|
timeout_minutes: "30"
|
||||||
|
custom_instructions: |
|
||||||
|
Focus on:
|
||||||
|
- Code quality and maintainability
|
||||||
|
- Security vulnerabilities
|
||||||
|
- Performance issues
|
||||||
|
- Best practices and design patterns
|
||||||
|
- Test coverage gaps
|
||||||
|
|
||||||
|
Be constructive and provide specific suggestions for improvements.
|
||||||
|
Use GitHub's suggestion format when proposing code changes.
|
||||||
@@ -530,6 +530,7 @@ export function generatePrompt(
|
|||||||
context: PreparedContext,
|
context: PreparedContext,
|
||||||
githubData: FetchDataResult,
|
githubData: FetchDataResult,
|
||||||
useCommitSigning: boolean,
|
useCommitSigning: boolean,
|
||||||
|
mode: Mode,
|
||||||
): string {
|
): string {
|
||||||
if (context.overridePrompt) {
|
if (context.overridePrompt) {
|
||||||
return substitutePromptVariables(
|
return substitutePromptVariables(
|
||||||
@@ -539,6 +540,19 @@ export function generatePrompt(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Use the mode's prompt generator
|
||||||
|
return mode.generatePrompt(context, githubData, useCommitSigning);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates the default prompt for tag mode
|
||||||
|
* @internal
|
||||||
|
*/
|
||||||
|
export function generateDefaultPrompt(
|
||||||
|
context: PreparedContext,
|
||||||
|
githubData: FetchDataResult,
|
||||||
|
useCommitSigning: boolean = false,
|
||||||
|
): string {
|
||||||
const {
|
const {
|
||||||
contextData,
|
contextData,
|
||||||
comments,
|
comments,
|
||||||
@@ -587,23 +601,28 @@ ${formattedBody}
|
|||||||
${formattedComments || "No comments"}
|
${formattedComments || "No comments"}
|
||||||
</comments>
|
</comments>
|
||||||
|
|
||||||
<review_comments>
|
${
|
||||||
${eventData.isPR ? formattedReviewComments || "No review comments" : ""}
|
eventData.isPR
|
||||||
</review_comments>
|
? `<review_comments>
|
||||||
|
${formattedReviewComments || "No review comments"}
|
||||||
|
</review_comments>`
|
||||||
|
: ""
|
||||||
|
}
|
||||||
|
|
||||||
<changed_files>
|
${
|
||||||
${eventData.isPR ? formattedChangedFiles || "No files changed" : ""}
|
eventData.isPR
|
||||||
</changed_files>${imagesInfo}
|
? `<changed_files>
|
||||||
|
${formattedChangedFiles || "No files changed"}
|
||||||
|
</changed_files>`
|
||||||
|
: ""
|
||||||
|
}${imagesInfo}
|
||||||
|
|
||||||
<event_type>${eventType}</event_type>
|
<event_type>${eventType}</event_type>
|
||||||
<is_pr>${eventData.isPR ? "true" : "false"}</is_pr>
|
<is_pr>${eventData.isPR ? "true" : "false"}</is_pr>
|
||||||
<trigger_context>${triggerContext}</trigger_context>
|
<trigger_context>${triggerContext}</trigger_context>
|
||||||
<repository>${context.repository}</repository>
|
<repository>${context.repository}</repository>
|
||||||
${
|
${eventData.isPR && eventData.prNumber ? `<pr_number>${eventData.prNumber}</pr_number>` : ""}
|
||||||
eventData.isPR
|
${!eventData.isPR && eventData.issueNumber ? `<issue_number>${eventData.issueNumber}</issue_number>` : ""}
|
||||||
? `<pr_number>${eventData.prNumber}</pr_number>`
|
|
||||||
: `<issue_number>${eventData.issueNumber ?? ""}</issue_number>`
|
|
||||||
}
|
|
||||||
<claude_comment_id>${context.claudeCommentId}</claude_comment_id>
|
<claude_comment_id>${context.claudeCommentId}</claude_comment_id>
|
||||||
<trigger_username>${context.triggerUsername ?? "Unknown"}</trigger_username>
|
<trigger_username>${context.triggerUsername ?? "Unknown"}</trigger_username>
|
||||||
<trigger_display_name>${githubData.triggerDisplayName ?? context.triggerUsername ?? "Unknown"}</trigger_display_name>
|
<trigger_display_name>${githubData.triggerDisplayName ?? context.triggerUsername ?? "Unknown"}</trigger_display_name>
|
||||||
@@ -805,7 +824,9 @@ export async function createPrompt(
|
|||||||
let claudeCommentId: string = "";
|
let claudeCommentId: string = "";
|
||||||
if (mode.name === "tag") {
|
if (mode.name === "tag") {
|
||||||
if (!modeContext.commentId) {
|
if (!modeContext.commentId) {
|
||||||
throw new Error("Tag mode requires a comment ID for prompt generation");
|
throw new Error(
|
||||||
|
`${mode.name} mode requires a comment ID for prompt generation`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
claudeCommentId = modeContext.commentId.toString();
|
claudeCommentId = modeContext.commentId.toString();
|
||||||
}
|
}
|
||||||
@@ -826,6 +847,7 @@ export async function createPrompt(
|
|||||||
preparedContext,
|
preparedContext,
|
||||||
githubData,
|
githubData,
|
||||||
context.inputs.useCommitSigning,
|
context.inputs.useCommitSigning,
|
||||||
|
mode,
|
||||||
);
|
);
|
||||||
|
|
||||||
// Log the final prompt to console
|
// Log the final prompt to console
|
||||||
|
|||||||
@@ -372,8 +372,12 @@ export function formatGroupedContent(groupedContent: GroupedContent[]): string {
|
|||||||
const usage = item.usage || {};
|
const usage = item.usage || {};
|
||||||
if (Object.keys(usage).length > 0) {
|
if (Object.keys(usage).length > 0) {
|
||||||
const inputTokens = usage.input_tokens || 0;
|
const inputTokens = usage.input_tokens || 0;
|
||||||
|
const cacheCreationTokens = usage.cache_creation_input_tokens || 0;
|
||||||
|
const cacheReadTokens = usage.cache_read_input_tokens || 0;
|
||||||
|
const totalInputTokens =
|
||||||
|
inputTokens + cacheCreationTokens + cacheReadTokens;
|
||||||
const outputTokens = usage.output_tokens || 0;
|
const outputTokens = usage.output_tokens || 0;
|
||||||
markdown += `*Token usage: ${inputTokens} input, ${outputTokens} output*\n\n`;
|
markdown += `*Token usage: ${totalInputTokens} input, ${outputTokens} output*\n\n`;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only add separator if this section had content
|
// Only add separator if this section had content
|
||||||
@@ -393,7 +397,7 @@ export function formatGroupedContent(groupedContent: GroupedContent[]): string {
|
|||||||
markdown += "---\n\n";
|
markdown += "---\n\n";
|
||||||
} else if (itemType === "final_result") {
|
} else if (itemType === "final_result") {
|
||||||
const data = item.data || {};
|
const data = item.data || {};
|
||||||
const cost = (data as any).cost_usd || 0;
|
const cost = (data as any).total_cost_usd || (data as any).cost_usd || 0;
|
||||||
const duration = (data as any).duration_ms || 0;
|
const duration = (data as any).duration_ms || 0;
|
||||||
const resultText = (data as any).result || "";
|
const resultText = (data as any).result || "";
|
||||||
|
|
||||||
|
|||||||
@@ -10,13 +10,37 @@ import { setupGitHubToken } from "../github/token";
|
|||||||
import { checkWritePermissions } from "../github/validation/permissions";
|
import { checkWritePermissions } from "../github/validation/permissions";
|
||||||
import { createOctokit } from "../github/api/client";
|
import { createOctokit } from "../github/api/client";
|
||||||
import { parseGitHubContext, isEntityContext } from "../github/context";
|
import { parseGitHubContext, isEntityContext } from "../github/context";
|
||||||
import { getMode } from "../modes/registry";
|
import { getMode, isValidMode, DEFAULT_MODE } from "../modes/registry";
|
||||||
|
import type { ModeName } from "../modes/types";
|
||||||
import { prepare } from "../prepare";
|
import { prepare } from "../prepare";
|
||||||
|
|
||||||
async function run() {
|
async function run() {
|
||||||
try {
|
try {
|
||||||
// Step 1: Setup GitHub token
|
// Step 1: Get mode first to determine authentication method
|
||||||
const githubToken = await setupGitHubToken();
|
const modeInput = process.env.MODE || DEFAULT_MODE;
|
||||||
|
|
||||||
|
// Validate mode input
|
||||||
|
if (!isValidMode(modeInput)) {
|
||||||
|
throw new Error(`Invalid mode: ${modeInput}`);
|
||||||
|
}
|
||||||
|
const validatedMode: ModeName = modeInput;
|
||||||
|
|
||||||
|
// Step 2: Setup GitHub token based on mode
|
||||||
|
let githubToken: string;
|
||||||
|
if (validatedMode === "experimental-review") {
|
||||||
|
// For experimental-review mode, use the default GitHub Action token
|
||||||
|
githubToken = process.env.DEFAULT_WORKFLOW_TOKEN || "";
|
||||||
|
if (!githubToken) {
|
||||||
|
throw new Error(
|
||||||
|
"DEFAULT_WORKFLOW_TOKEN not found for experimental-review mode",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
console.log("Using default GitHub Action token for review mode");
|
||||||
|
core.setOutput("GITHUB_TOKEN", githubToken);
|
||||||
|
} else {
|
||||||
|
// For other modes, use the existing token exchange
|
||||||
|
githubToken = await setupGitHubToken();
|
||||||
|
}
|
||||||
const octokit = createOctokit(githubToken);
|
const octokit = createOctokit(githubToken);
|
||||||
|
|
||||||
// Step 2: Parse GitHub context (once for all operations)
|
// Step 2: Parse GitHub context (once for all operations)
|
||||||
@@ -36,7 +60,7 @@ async function run() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Step 4: Get mode and check trigger conditions
|
// Step 4: Get mode and check trigger conditions
|
||||||
const mode = getMode(context.inputs.mode, context);
|
const mode = getMode(validatedMode, context);
|
||||||
const containsTrigger = mode.shouldTrigger(context);
|
const containsTrigger = mode.shouldTrigger(context);
|
||||||
|
|
||||||
// Set output for action.yml to check
|
// Set output for action.yml to check
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ export const PR_QUERY = `
|
|||||||
login
|
login
|
||||||
}
|
}
|
||||||
createdAt
|
createdAt
|
||||||
|
isMinimized
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
reviews(first: 100) {
|
reviews(first: 100) {
|
||||||
@@ -69,6 +70,7 @@ export const PR_QUERY = `
|
|||||||
login
|
login
|
||||||
}
|
}
|
||||||
createdAt
|
createdAt
|
||||||
|
isMinimized
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -98,6 +100,7 @@ export const ISSUE_QUERY = `
|
|||||||
login
|
login
|
||||||
}
|
}
|
||||||
createdAt
|
createdAt
|
||||||
|
isMinimized
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -134,7 +134,7 @@ export async function fetchGitHubData({
|
|||||||
|
|
||||||
// Prepare all comments for image processing
|
// Prepare all comments for image processing
|
||||||
const issueComments: CommentWithImages[] = comments
|
const issueComments: CommentWithImages[] = comments
|
||||||
.filter((c) => c.body)
|
.filter((c) => c.body && !c.isMinimized)
|
||||||
.map((c) => ({
|
.map((c) => ({
|
||||||
type: "issue_comment" as const,
|
type: "issue_comment" as const,
|
||||||
id: c.databaseId,
|
id: c.databaseId,
|
||||||
@@ -154,7 +154,7 @@ export async function fetchGitHubData({
|
|||||||
const reviewComments: CommentWithImages[] =
|
const reviewComments: CommentWithImages[] =
|
||||||
reviewData?.nodes
|
reviewData?.nodes
|
||||||
?.flatMap((r) => r.comments?.nodes ?? [])
|
?.flatMap((r) => r.comments?.nodes ?? [])
|
||||||
.filter((c) => c.body)
|
.filter((c) => c.body && !c.isMinimized)
|
||||||
.map((c) => ({
|
.map((c) => ({
|
||||||
type: "review_comment" as const,
|
type: "review_comment" as const,
|
||||||
id: c.databaseId,
|
id: c.databaseId,
|
||||||
|
|||||||
@@ -50,6 +50,7 @@ export function formatComments(
|
|||||||
imageUrlMap?: Map<string, string>,
|
imageUrlMap?: Map<string, string>,
|
||||||
): string {
|
): string {
|
||||||
return comments
|
return comments
|
||||||
|
.filter((comment) => !comment.isMinimized)
|
||||||
.map((comment) => {
|
.map((comment) => {
|
||||||
let body = comment.body;
|
let body = comment.body;
|
||||||
|
|
||||||
@@ -96,6 +97,7 @@ export function formatReviewComments(
|
|||||||
review.comments.nodes.length > 0
|
review.comments.nodes.length > 0
|
||||||
) {
|
) {
|
||||||
const comments = review.comments.nodes
|
const comments = review.comments.nodes
|
||||||
|
.filter((comment) => !comment.isMinimized)
|
||||||
.map((comment) => {
|
.map((comment) => {
|
||||||
let body = comment.body;
|
let body = comment.body;
|
||||||
|
|
||||||
@@ -110,7 +112,9 @@ export function formatReviewComments(
|
|||||||
return ` [Comment on ${comment.path}:${comment.line || "?"}]: ${body}`;
|
return ` [Comment on ${comment.path}:${comment.line || "?"}]: ${body}`;
|
||||||
})
|
})
|
||||||
.join("\n");
|
.join("\n");
|
||||||
reviewOutput += `\n${comments}`;
|
if (comments) {
|
||||||
|
reviewOutput += `\n${comments}`;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return reviewOutput;
|
return reviewOutput;
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ export type GitHubComment = {
|
|||||||
body: string;
|
body: string;
|
||||||
author: GitHubAuthor;
|
author: GitHubAuthor;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
|
isMinimized?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type GitHubReviewComment = GitHubComment & {
|
export type GitHubReviewComment = GitHubComment & {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import * as core from "@actions/core";
|
import * as core from "@actions/core";
|
||||||
import { GITHUB_API_URL } from "../github/api/config";
|
import { GITHUB_API_URL, GITHUB_SERVER_URL } from "../github/api/config";
|
||||||
import type { ParsedGitHubContext } from "../github/context";
|
import type { GitHubContext } from "../github/context";
|
||||||
|
import { isEntityContext } from "../github/context";
|
||||||
import { Octokit } from "@octokit/rest";
|
import { Octokit } from "@octokit/rest";
|
||||||
|
|
||||||
type PrepareConfigParams = {
|
type PrepareConfigParams = {
|
||||||
@@ -12,7 +13,7 @@ type PrepareConfigParams = {
|
|||||||
additionalMcpConfig?: string;
|
additionalMcpConfig?: string;
|
||||||
claudeCommentId?: string;
|
claudeCommentId?: string;
|
||||||
allowedTools: string[];
|
allowedTools: string[];
|
||||||
context: ParsedGitHubContext;
|
context: GitHubContext;
|
||||||
};
|
};
|
||||||
|
|
||||||
async function checkActionsReadPermission(
|
async function checkActionsReadPermission(
|
||||||
@@ -115,7 +116,7 @@ export async function prepareMcpConfig(
|
|||||||
const hasActionsReadPermission =
|
const hasActionsReadPermission =
|
||||||
context.inputs.additionalPermissions.get("actions") === "read";
|
context.inputs.additionalPermissions.get("actions") === "read";
|
||||||
|
|
||||||
if (context.isPR && hasActionsReadPermission) {
|
if (isEntityContext(context) && context.isPR && hasActionsReadPermission) {
|
||||||
// Verify the token actually has actions:read permission
|
// Verify the token actually has actions:read permission
|
||||||
const actuallyHasPermission = await checkActionsReadPermission(
|
const actuallyHasPermission = await checkActionsReadPermission(
|
||||||
process.env.ACTIONS_TOKEN || "",
|
process.env.ACTIONS_TOKEN || "",
|
||||||
@@ -141,7 +142,9 @@ export async function prepareMcpConfig(
|
|||||||
GITHUB_TOKEN: process.env.ACTIONS_TOKEN,
|
GITHUB_TOKEN: process.env.ACTIONS_TOKEN,
|
||||||
REPO_OWNER: owner,
|
REPO_OWNER: owner,
|
||||||
REPO_NAME: repo,
|
REPO_NAME: repo,
|
||||||
PR_NUMBER: context.entityNumber?.toString() || "",
|
PR_NUMBER: isEntityContext(context)
|
||||||
|
? context.entityNumber?.toString() || ""
|
||||||
|
: "",
|
||||||
RUNNER_TEMP: process.env.RUNNER_TEMP || "/tmp",
|
RUNNER_TEMP: process.env.RUNNER_TEMP || "/tmp",
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -156,10 +159,13 @@ export async function prepareMcpConfig(
|
|||||||
"--rm",
|
"--rm",
|
||||||
"-e",
|
"-e",
|
||||||
"GITHUB_PERSONAL_ACCESS_TOKEN",
|
"GITHUB_PERSONAL_ACCESS_TOKEN",
|
||||||
|
"-e",
|
||||||
|
"GITHUB_HOST",
|
||||||
"ghcr.io/github/github-mcp-server:sha-efef8ae", // https://github.com/github/github-mcp-server/releases/tag/v0.9.0
|
"ghcr.io/github/github-mcp-server:sha-efef8ae", // https://github.com/github/github-mcp-server/releases/tag/v0.9.0
|
||||||
],
|
],
|
||||||
env: {
|
env: {
|
||||||
GITHUB_PERSONAL_ACCESS_TOKEN: githubToken,
|
GITHUB_PERSONAL_ACCESS_TOKEN: githubToken,
|
||||||
|
GITHUB_HOST: GITHUB_SERVER_URL,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
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 { prepareMcpConfig } from "../../mcp/install-mcp-server";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Agent mode implementation.
|
* Agent mode implementation.
|
||||||
@@ -39,27 +40,10 @@ export const agentMode: Mode = {
|
|||||||
return false;
|
return false;
|
||||||
},
|
},
|
||||||
|
|
||||||
async prepare({ context }: ModeOptions): Promise<ModeResult> {
|
async prepare({ context, githubToken }: ModeOptions): Promise<ModeResult> {
|
||||||
// Agent mode handles automation events (workflow_dispatch, schedule) only
|
// Agent mode handles automation events (workflow_dispatch, schedule) only
|
||||||
|
|
||||||
// Create prompt directory
|
// Agent mode doesn't need to create prompt files here - handled by createPrompt
|
||||||
await mkdir(`${process.env.RUNNER_TEMP}/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}/claude-prompts/claude-prompt.txt`,
|
|
||||||
promptContent,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Export tool environment variables for agent mode
|
// Export tool environment variables for agent mode
|
||||||
const baseTools = [
|
const baseTools = [
|
||||||
@@ -80,29 +64,25 @@ export const agentMode: Mode = {
|
|||||||
...context.inputs.disallowedTools,
|
...context.inputs.disallowedTools,
|
||||||
];
|
];
|
||||||
|
|
||||||
core.exportVariable("ALLOWED_TOOLS", allowedTools.join(","));
|
// Export as INPUT_ prefixed variables for the base action
|
||||||
core.exportVariable("DISALLOWED_TOOLS", disallowedTools.join(","));
|
core.exportVariable("INPUT_ALLOWED_TOOLS", allowedTools.join(","));
|
||||||
|
core.exportVariable("INPUT_DISALLOWED_TOOLS", disallowedTools.join(","));
|
||||||
|
|
||||||
// Agent mode uses a minimal MCP configuration
|
// Get MCP configuration using the same setup as other modes
|
||||||
// We don't need comment servers or PR-specific tools for automation
|
|
||||||
const mcpConfig: any = {
|
|
||||||
mcpServers: {},
|
|
||||||
};
|
|
||||||
|
|
||||||
// Add user-provided additional MCP config if any
|
|
||||||
const additionalMcpConfig = process.env.MCP_CONFIG || "";
|
const additionalMcpConfig = process.env.MCP_CONFIG || "";
|
||||||
if (additionalMcpConfig.trim()) {
|
const mcpConfig = await prepareMcpConfig({
|
||||||
try {
|
githubToken,
|
||||||
const additional = JSON.parse(additionalMcpConfig);
|
owner: context.repository.owner,
|
||||||
if (additional && typeof additional === "object") {
|
repo: context.repository.repo,
|
||||||
Object.assign(mcpConfig, additional);
|
branch: "", // Agent mode doesn't use branches
|
||||||
}
|
baseBranch: "",
|
||||||
} catch (error) {
|
additionalMcpConfig,
|
||||||
core.warning(`Failed to parse additional MCP config: ${error}`);
|
claudeCommentId: undefined, // Agent mode doesn't track comments
|
||||||
}
|
allowedTools: [...baseTools, ...context.inputs.allowedTools],
|
||||||
}
|
context,
|
||||||
|
});
|
||||||
|
|
||||||
core.setOutput("mcp_config", JSON.stringify(mcpConfig));
|
core.setOutput("mcp_config", mcpConfig);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
commentId: undefined,
|
commentId: undefined,
|
||||||
@@ -111,7 +91,21 @@ export const agentMode: Mode = {
|
|||||||
currentBranch: "",
|
currentBranch: "",
|
||||||
claudeBranch: undefined,
|
claudeBranch: undefined,
|
||||||
},
|
},
|
||||||
mcpConfig: JSON.stringify(mcpConfig),
|
mcpConfig: mcpConfig,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
|
generatePrompt(context: PreparedContext): string {
|
||||||
|
// Agent mode uses override or direct prompt, no GitHub data needed
|
||||||
|
if (context.overridePrompt) {
|
||||||
|
return context.overridePrompt;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (context.directPrompt) {
|
||||||
|
return context.directPrompt;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Minimal fallback - repository is a string in PreparedContext
|
||||||
|
return `Repository: ${context.repository}`;
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -13,11 +13,12 @@
|
|||||||
import type { Mode, ModeName } from "./types";
|
import type { Mode, ModeName } from "./types";
|
||||||
import { tagMode } from "./tag";
|
import { tagMode } from "./tag";
|
||||||
import { agentMode } from "./agent";
|
import { agentMode } from "./agent";
|
||||||
|
import { reviewMode } from "./review";
|
||||||
import type { GitHubContext } from "../github/context";
|
import type { GitHubContext } from "../github/context";
|
||||||
import { isAutomationContext } from "../github/context";
|
import { isAutomationContext } from "../github/context";
|
||||||
|
|
||||||
export const DEFAULT_MODE = "tag" as const;
|
export const DEFAULT_MODE = "tag" as const;
|
||||||
export const VALID_MODES = ["tag", "agent"] as const;
|
export const VALID_MODES = ["tag", "agent", "experimental-review"] as const;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* All available modes.
|
* All available modes.
|
||||||
@@ -26,6 +27,7 @@ export const VALID_MODES = ["tag", "agent"] as const;
|
|||||||
const modes = {
|
const modes = {
|
||||||
tag: tagMode,
|
tag: tagMode,
|
||||||
agent: agentMode,
|
agent: agentMode,
|
||||||
|
"experimental-review": reviewMode,
|
||||||
} as const satisfies Record<ModeName, Mode>;
|
} as const satisfies Record<ModeName, Mode>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
352
src/modes/review/index.ts
Normal file
352
src/modes/review/index.ts
Normal file
@@ -0,0 +1,352 @@
|
|||||||
|
import * as core from "@actions/core";
|
||||||
|
import type { Mode, ModeOptions, ModeResult } from "../types";
|
||||||
|
import { checkContainsTrigger } from "../../github/validation/trigger";
|
||||||
|
import { prepareMcpConfig } from "../../mcp/install-mcp-server";
|
||||||
|
import { fetchGitHubData } from "../../github/data/fetcher";
|
||||||
|
import type { FetchDataResult } from "../../github/data/fetcher";
|
||||||
|
import { createPrompt } from "../../create-prompt";
|
||||||
|
import type { PreparedContext } from "../../create-prompt";
|
||||||
|
import { isEntityContext, isPullRequestEvent } from "../../github/context";
|
||||||
|
import {
|
||||||
|
formatContext,
|
||||||
|
formatBody,
|
||||||
|
formatComments,
|
||||||
|
formatReviewComments,
|
||||||
|
formatChangedFilesWithSHA,
|
||||||
|
} from "../../github/data/formatter";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Review mode implementation.
|
||||||
|
*
|
||||||
|
* Code review mode that uses the default GitHub Action token
|
||||||
|
* and focuses on providing inline comments and suggestions.
|
||||||
|
* Automatically includes GitHub MCP tools for review operations.
|
||||||
|
*/
|
||||||
|
export const reviewMode: Mode = {
|
||||||
|
name: "experimental-review",
|
||||||
|
description:
|
||||||
|
"Experimental code review mode for inline comments and suggestions",
|
||||||
|
|
||||||
|
shouldTrigger(context) {
|
||||||
|
if (!isEntityContext(context)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Review mode only works on PRs
|
||||||
|
if (!context.isPR) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// For pull_request events, only trigger on specific actions
|
||||||
|
if (isPullRequestEvent(context)) {
|
||||||
|
const allowedActions = ["opened", "synchronize", "reopened"];
|
||||||
|
const action = context.payload.action;
|
||||||
|
return allowedActions.includes(action);
|
||||||
|
}
|
||||||
|
|
||||||
|
// For other events (comments), check for trigger phrase
|
||||||
|
return checkContainsTrigger(context);
|
||||||
|
},
|
||||||
|
|
||||||
|
prepareContext(context, data) {
|
||||||
|
return {
|
||||||
|
mode: "experimental-review",
|
||||||
|
githubContext: context,
|
||||||
|
commentId: data?.commentId,
|
||||||
|
baseBranch: data?.baseBranch,
|
||||||
|
claudeBranch: data?.claudeBranch,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
|
||||||
|
getAllowedTools() {
|
||||||
|
return [
|
||||||
|
// Context tools - to know who the current user is
|
||||||
|
"mcp__github__get_me",
|
||||||
|
// 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",
|
||||||
|
];
|
||||||
|
},
|
||||||
|
|
||||||
|
getDisallowedTools() {
|
||||||
|
return [];
|
||||||
|
},
|
||||||
|
|
||||||
|
shouldCreateTrackingComment() {
|
||||||
|
return false; // Review mode uses the review body instead of a tracking comment
|
||||||
|
},
|
||||||
|
|
||||||
|
generatePrompt(
|
||||||
|
context: PreparedContext,
|
||||||
|
githubData: FetchDataResult,
|
||||||
|
): string {
|
||||||
|
// Support overridePrompt
|
||||||
|
if (context.overridePrompt) {
|
||||||
|
return context.overridePrompt;
|
||||||
|
}
|
||||||
|
|
||||||
|
const {
|
||||||
|
contextData,
|
||||||
|
comments,
|
||||||
|
changedFilesWithSHA,
|
||||||
|
reviewData,
|
||||||
|
imageUrlMap,
|
||||||
|
} = githubData;
|
||||||
|
const { eventData } = context;
|
||||||
|
|
||||||
|
const formattedContext = formatContext(contextData, true); // Reviews are always for PRs
|
||||||
|
const formattedComments = formatComments(comments, imageUrlMap);
|
||||||
|
const formattedReviewComments = formatReviewComments(
|
||||||
|
reviewData,
|
||||||
|
imageUrlMap,
|
||||||
|
);
|
||||||
|
const formattedChangedFiles =
|
||||||
|
formatChangedFilesWithSHA(changedFilesWithSHA);
|
||||||
|
const formattedBody = contextData?.body
|
||||||
|
? formatBody(contextData.body, imageUrlMap)
|
||||||
|
: "No description provided";
|
||||||
|
|
||||||
|
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>
|
||||||
|
${formattedContext}
|
||||||
|
</formatted_context>
|
||||||
|
|
||||||
|
<repository>${context.repository}</repository>
|
||||||
|
${eventData.isPR && eventData.prNumber ? `<pr_number>${eventData.prNumber}</pr_number>` : ""}
|
||||||
|
|
||||||
|
<comments>
|
||||||
|
${formattedComments || "No comments yet"}
|
||||||
|
</comments>
|
||||||
|
|
||||||
|
<review_comments>
|
||||||
|
${formattedReviewComments || "No review comments"}
|
||||||
|
</review_comments>
|
||||||
|
|
||||||
|
<changed_files>
|
||||||
|
${formattedChangedFiles}
|
||||||
|
</changed_files>
|
||||||
|
|
||||||
|
<formatted_body>
|
||||||
|
${formattedBody}
|
||||||
|
</formatted_body>
|
||||||
|
|
||||||
|
${
|
||||||
|
(eventData.eventName === "issue_comment" ||
|
||||||
|
eventData.eventName === "pull_request_review_comment" ||
|
||||||
|
eventData.eventName === "pull_request_review") &&
|
||||||
|
eventData.commentBody
|
||||||
|
? `<trigger_comment>
|
||||||
|
User @${context.triggerUsername}: ${eventData.commentBody}
|
||||||
|
</trigger_comment>`
|
||||||
|
: ""
|
||||||
|
}
|
||||||
|
|
||||||
|
${
|
||||||
|
context.directPrompt
|
||||||
|
? `<direct_prompt>
|
||||||
|
${context.directPrompt}
|
||||||
|
</direct_prompt>`
|
||||||
|
: ""
|
||||||
|
}
|
||||||
|
|
||||||
|
REVIEW MODE WORKFLOW:
|
||||||
|
|
||||||
|
1. First, understand the PR context:
|
||||||
|
- 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
|
||||||
|
- This provides the full context and latest state of the code
|
||||||
|
- Look at the changed_files section above to see which files were modified
|
||||||
|
|
||||||
|
2. Create a pending review:
|
||||||
|
- Use mcp__github__create_pending_pull_request_review to start your review
|
||||||
|
- This allows you to batch comments before submitting
|
||||||
|
|
||||||
|
3. Add inline comments:
|
||||||
|
- Use mcp__github__add_comment_to_pending_review for each issue or suggestion
|
||||||
|
- Parameters:
|
||||||
|
* path: The file path (e.g., "src/index.js")
|
||||||
|
* line: Line number for single-line comments
|
||||||
|
* 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:
|
||||||
|
* When replacing multiple consecutive lines
|
||||||
|
* When the fix requires changes across several lines
|
||||||
|
* Example: To replace lines 19-20, use startLine: 19, line: 20
|
||||||
|
|
||||||
|
- For code suggestions, use this EXACT format in the body:
|
||||||
|
\`\`\`suggestion
|
||||||
|
corrected code here
|
||||||
|
\`\`\`
|
||||||
|
|
||||||
|
CRITICAL: GitHub suggestion blocks must ONLY contain the replacement for the specific line(s) being commented on:
|
||||||
|
- For single-line comments: Replace ONLY that line
|
||||||
|
- For multi-line comments: Replace ONLY the lines in the range
|
||||||
|
- Do NOT include surrounding context or function signatures
|
||||||
|
- Do NOT suggest changes that span beyond the commented lines
|
||||||
|
|
||||||
|
Example for line 19 \`var name = user.name;\`:
|
||||||
|
WRONG:
|
||||||
|
\\\`\\\`\\\`suggestion
|
||||||
|
function processUser(user) {
|
||||||
|
if (!user) throw new Error('Invalid user');
|
||||||
|
const name = user.name;
|
||||||
|
\\\`\\\`\\\`
|
||||||
|
|
||||||
|
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:
|
||||||
|
|
||||||
|
- Focus on:
|
||||||
|
* Security vulnerabilities
|
||||||
|
* Bugs and logic errors
|
||||||
|
* Performance issues
|
||||||
|
* Code quality and maintainability
|
||||||
|
* Best practices and standards
|
||||||
|
* Edge cases and error handling
|
||||||
|
|
||||||
|
- Provide:
|
||||||
|
* Specific, actionable feedback
|
||||||
|
* Code suggestions when possible (following GitHub's format exactly)
|
||||||
|
* Clear explanations of issues
|
||||||
|
* Constructive criticism
|
||||||
|
* Recognition of good practices
|
||||||
|
* For complex changes that require multiple modifications:
|
||||||
|
- Create separate comments for each logical change
|
||||||
|
- Or explain the full solution in text without a suggestion block
|
||||||
|
|
||||||
|
- Communication:
|
||||||
|
* All feedback goes through GitHub's review system
|
||||||
|
* Be professional and respectful
|
||||||
|
* Your review body is the main communication channel
|
||||||
|
|
||||||
|
Before starting, analyze the PR inside <analysis> tags:
|
||||||
|
<analysis>
|
||||||
|
- PR title and description
|
||||||
|
- Number of files changed and scope
|
||||||
|
- Type of changes (feature, bug fix, refactor, etc.)
|
||||||
|
- Key areas to focus on
|
||||||
|
- Review strategy
|
||||||
|
</analysis>
|
||||||
|
|
||||||
|
Then proceed with the review workflow described above.
|
||||||
|
|
||||||
|
IMPORTANT: Your review body is the primary way users will understand your feedback. Make it comprehensive and well-structured with:
|
||||||
|
- Executive summary at the top
|
||||||
|
- Detailed findings organized by severity or category
|
||||||
|
- Clear action items and recommendations
|
||||||
|
- Recognition of good practices
|
||||||
|
This ensures users get value from the review even before checking individual inline comments.`;
|
||||||
|
},
|
||||||
|
|
||||||
|
async prepare({
|
||||||
|
context,
|
||||||
|
octokit,
|
||||||
|
githubToken,
|
||||||
|
}: ModeOptions): Promise<ModeResult> {
|
||||||
|
if (!isEntityContext(context)) {
|
||||||
|
throw new Error("Review mode requires entity context");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Review mode doesn't create a tracking comment
|
||||||
|
const githubData = await fetchGitHubData({
|
||||||
|
octokits: octokit,
|
||||||
|
repository: `${context.repository.owner}/${context.repository.repo}`,
|
||||||
|
prNumber: context.entityNumber.toString(),
|
||||||
|
isPR: context.isPR,
|
||||||
|
triggerUsername: context.actor,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Review mode doesn't need branch setup or git auth since it only creates comments
|
||||||
|
// Using minimal branch info since review mode doesn't create or modify branches
|
||||||
|
const branchInfo = {
|
||||||
|
baseBranch: "main",
|
||||||
|
currentBranch: "",
|
||||||
|
claudeBranch: undefined, // Review mode doesn't create branches
|
||||||
|
};
|
||||||
|
|
||||||
|
const modeContext = this.prepareContext(context, {
|
||||||
|
baseBranch: branchInfo.baseBranch,
|
||||||
|
claudeBranch: branchInfo.claudeBranch,
|
||||||
|
});
|
||||||
|
|
||||||
|
await createPrompt(reviewMode, modeContext, githubData, context);
|
||||||
|
|
||||||
|
// Export tool environment variables for review mode
|
||||||
|
const baseTools = [
|
||||||
|
"Edit",
|
||||||
|
"MultiEdit",
|
||||||
|
"Glob",
|
||||||
|
"Grep",
|
||||||
|
"LS",
|
||||||
|
"Read",
|
||||||
|
"Write",
|
||||||
|
];
|
||||||
|
|
||||||
|
// Add mode-specific and user-specified tools
|
||||||
|
const allowedTools = [
|
||||||
|
...baseTools,
|
||||||
|
...this.getAllowedTools(),
|
||||||
|
...context.inputs.allowedTools,
|
||||||
|
];
|
||||||
|
const disallowedTools = [
|
||||||
|
"WebSearch",
|
||||||
|
"WebFetch",
|
||||||
|
...context.inputs.disallowedTools,
|
||||||
|
];
|
||||||
|
|
||||||
|
// Export as INPUT_ prefixed variables for the base action
|
||||||
|
core.exportVariable("INPUT_ALLOWED_TOOLS", allowedTools.join(","));
|
||||||
|
core.exportVariable("INPUT_DISALLOWED_TOOLS", disallowedTools.join(","));
|
||||||
|
|
||||||
|
const additionalMcpConfig = process.env.MCP_CONFIG || "";
|
||||||
|
const mcpConfig = await prepareMcpConfig({
|
||||||
|
githubToken,
|
||||||
|
owner: context.repository.owner,
|
||||||
|
repo: context.repository.repo,
|
||||||
|
branch: branchInfo.claudeBranch || branchInfo.currentBranch,
|
||||||
|
baseBranch: branchInfo.baseBranch,
|
||||||
|
additionalMcpConfig,
|
||||||
|
allowedTools: [...this.getAllowedTools(), ...context.inputs.allowedTools],
|
||||||
|
context,
|
||||||
|
});
|
||||||
|
|
||||||
|
core.setOutput("mcp_config", mcpConfig);
|
||||||
|
|
||||||
|
return {
|
||||||
|
branchInfo,
|
||||||
|
mcpConfig,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -7,8 +7,10 @@ import { setupBranch } from "../../github/operations/branch";
|
|||||||
import { configureGitAuth } from "../../github/operations/git-config";
|
import { configureGitAuth } from "../../github/operations/git-config";
|
||||||
import { prepareMcpConfig } from "../../mcp/install-mcp-server";
|
import { prepareMcpConfig } from "../../mcp/install-mcp-server";
|
||||||
import { fetchGitHubData } from "../../github/data/fetcher";
|
import { fetchGitHubData } from "../../github/data/fetcher";
|
||||||
import { createPrompt } from "../../create-prompt";
|
import { createPrompt, generateDefaultPrompt } from "../../create-prompt";
|
||||||
import { isEntityContext } from "../../github/context";
|
import { isEntityContext } from "../../github/context";
|
||||||
|
import type { PreparedContext } from "../../create-prompt/types";
|
||||||
|
import type { FetchDataResult } from "../../github/data/fetcher";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tag mode implementation.
|
* Tag mode implementation.
|
||||||
@@ -120,4 +122,12 @@ export const tagMode: Mode = {
|
|||||||
mcpConfig,
|
mcpConfig,
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
|
|
||||||
|
generatePrompt(
|
||||||
|
context: PreparedContext,
|
||||||
|
githubData: FetchDataResult,
|
||||||
|
useCommitSigning: boolean,
|
||||||
|
): string {
|
||||||
|
return generateDefaultPrompt(context, githubData, useCommitSigning);
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,6 +1,9 @@
|
|||||||
import type { GitHubContext } from "../github/context";
|
import type { GitHubContext } from "../github/context";
|
||||||
|
import type { PreparedContext } from "../create-prompt/types";
|
||||||
|
import type { FetchDataResult } from "../github/data/fetcher";
|
||||||
|
import type { Octokits } from "../github/api/client";
|
||||||
|
|
||||||
export type ModeName = "tag" | "agent";
|
export type ModeName = "tag" | "agent" | "experimental-review";
|
||||||
|
|
||||||
export type ModeContext = {
|
export type ModeContext = {
|
||||||
mode: ModeName;
|
mode: ModeName;
|
||||||
@@ -54,6 +57,16 @@ export type Mode = {
|
|||||||
*/
|
*/
|
||||||
shouldCreateTrackingComment(): boolean;
|
shouldCreateTrackingComment(): boolean;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates the prompt for this mode.
|
||||||
|
* @returns The complete prompt string
|
||||||
|
*/
|
||||||
|
generatePrompt(
|
||||||
|
context: PreparedContext,
|
||||||
|
githubData: FetchDataResult,
|
||||||
|
useCommitSigning: boolean,
|
||||||
|
): string;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Prepares the GitHub environment for this mode.
|
* Prepares the GitHub environment for this mode.
|
||||||
* Each mode decides how to handle different event types.
|
* Each mode decides how to handle different event types.
|
||||||
@@ -62,10 +75,10 @@ export type Mode = {
|
|||||||
prepare(options: ModeOptions): Promise<ModeResult>;
|
prepare(options: ModeOptions): Promise<ModeResult>;
|
||||||
};
|
};
|
||||||
|
|
||||||
// Define types for mode prepare method to avoid circular dependencies
|
// Define types for mode prepare method
|
||||||
export type ModeOptions = {
|
export type ModeOptions = {
|
||||||
context: GitHubContext;
|
context: GitHubContext;
|
||||||
octokit: any; // We'll use any to avoid circular dependency with Octokits
|
octokit: Octokits;
|
||||||
githubToken: string;
|
githubToken: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -3,13 +3,37 @@
|
|||||||
import { describe, test, expect } from "bun:test";
|
import { describe, test, expect } from "bun:test";
|
||||||
import {
|
import {
|
||||||
generatePrompt,
|
generatePrompt,
|
||||||
|
generateDefaultPrompt,
|
||||||
getEventTypeAndContext,
|
getEventTypeAndContext,
|
||||||
buildAllowedToolsString,
|
buildAllowedToolsString,
|
||||||
buildDisallowedToolsString,
|
buildDisallowedToolsString,
|
||||||
} from "../src/create-prompt";
|
} from "../src/create-prompt";
|
||||||
import type { PreparedContext } from "../src/create-prompt";
|
import type { PreparedContext } from "../src/create-prompt";
|
||||||
|
import type { Mode } from "../src/modes/types";
|
||||||
|
|
||||||
describe("generatePrompt", () => {
|
describe("generatePrompt", () => {
|
||||||
|
// Create a mock tag mode that uses the default prompt
|
||||||
|
const mockTagMode: Mode = {
|
||||||
|
name: "tag",
|
||||||
|
description: "Tag mode",
|
||||||
|
shouldTrigger: () => true,
|
||||||
|
prepareContext: (context) => ({ mode: "tag", githubContext: context }),
|
||||||
|
getAllowedTools: () => [],
|
||||||
|
getDisallowedTools: () => [],
|
||||||
|
shouldCreateTrackingComment: () => true,
|
||||||
|
generatePrompt: (context, githubData, useCommitSigning) =>
|
||||||
|
generateDefaultPrompt(context, githubData, useCommitSigning),
|
||||||
|
prepare: async () => ({
|
||||||
|
commentId: 123,
|
||||||
|
branchInfo: {
|
||||||
|
baseBranch: "main",
|
||||||
|
currentBranch: "main",
|
||||||
|
claudeBranch: undefined,
|
||||||
|
},
|
||||||
|
mcpConfig: "{}",
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
const mockGitHubData = {
|
const mockGitHubData = {
|
||||||
contextData: {
|
contextData: {
|
||||||
title: "Test PR",
|
title: "Test PR",
|
||||||
@@ -133,7 +157,7 @@ describe("generatePrompt", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const prompt = generatePrompt(envVars, mockGitHubData, false);
|
const prompt = generatePrompt(envVars, mockGitHubData, false, mockTagMode);
|
||||||
|
|
||||||
expect(prompt).toContain("You are Claude, an AI assistant");
|
expect(prompt).toContain("You are Claude, an AI assistant");
|
||||||
expect(prompt).toContain("<event_type>GENERAL_COMMENT</event_type>");
|
expect(prompt).toContain("<event_type>GENERAL_COMMENT</event_type>");
|
||||||
@@ -161,7 +185,7 @@ describe("generatePrompt", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const prompt = generatePrompt(envVars, mockGitHubData, false);
|
const prompt = generatePrompt(envVars, mockGitHubData, false, mockTagMode);
|
||||||
|
|
||||||
expect(prompt).toContain("<event_type>PR_REVIEW</event_type>");
|
expect(prompt).toContain("<event_type>PR_REVIEW</event_type>");
|
||||||
expect(prompt).toContain("<is_pr>true</is_pr>");
|
expect(prompt).toContain("<is_pr>true</is_pr>");
|
||||||
@@ -187,7 +211,7 @@ describe("generatePrompt", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const prompt = generatePrompt(envVars, mockGitHubData, false);
|
const prompt = generatePrompt(envVars, mockGitHubData, false, mockTagMode);
|
||||||
|
|
||||||
expect(prompt).toContain("<event_type>ISSUE_CREATED</event_type>");
|
expect(prompt).toContain("<event_type>ISSUE_CREATED</event_type>");
|
||||||
expect(prompt).toContain(
|
expect(prompt).toContain(
|
||||||
@@ -215,7 +239,7 @@ describe("generatePrompt", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const prompt = generatePrompt(envVars, mockGitHubData, false);
|
const prompt = generatePrompt(envVars, mockGitHubData, false, mockTagMode);
|
||||||
|
|
||||||
expect(prompt).toContain("<event_type>ISSUE_ASSIGNED</event_type>");
|
expect(prompt).toContain("<event_type>ISSUE_ASSIGNED</event_type>");
|
||||||
expect(prompt).toContain(
|
expect(prompt).toContain(
|
||||||
@@ -242,7 +266,7 @@ describe("generatePrompt", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const prompt = generatePrompt(envVars, mockGitHubData, false);
|
const prompt = generatePrompt(envVars, mockGitHubData, false, mockTagMode);
|
||||||
|
|
||||||
expect(prompt).toContain("<event_type>ISSUE_LABELED</event_type>");
|
expect(prompt).toContain("<event_type>ISSUE_LABELED</event_type>");
|
||||||
expect(prompt).toContain(
|
expect(prompt).toContain(
|
||||||
@@ -269,7 +293,7 @@ describe("generatePrompt", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const prompt = generatePrompt(envVars, mockGitHubData, false);
|
const prompt = generatePrompt(envVars, mockGitHubData, false, mockTagMode);
|
||||||
|
|
||||||
expect(prompt).toContain("<direct_prompt>");
|
expect(prompt).toContain("<direct_prompt>");
|
||||||
expect(prompt).toContain("Fix the bug in the login form");
|
expect(prompt).toContain("Fix the bug in the login form");
|
||||||
@@ -292,7 +316,7 @@ describe("generatePrompt", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const prompt = generatePrompt(envVars, mockGitHubData, false);
|
const prompt = generatePrompt(envVars, mockGitHubData, false, mockTagMode);
|
||||||
|
|
||||||
expect(prompt).toContain("<event_type>PULL_REQUEST</event_type>");
|
expect(prompt).toContain("<event_type>PULL_REQUEST</event_type>");
|
||||||
expect(prompt).toContain("<is_pr>true</is_pr>");
|
expect(prompt).toContain("<is_pr>true</is_pr>");
|
||||||
@@ -317,7 +341,7 @@ describe("generatePrompt", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const prompt = generatePrompt(envVars, mockGitHubData, false);
|
const prompt = generatePrompt(envVars, mockGitHubData, false, mockTagMode);
|
||||||
|
|
||||||
expect(prompt).toContain("CUSTOM INSTRUCTIONS:\nAlways use TypeScript");
|
expect(prompt).toContain("CUSTOM INSTRUCTIONS:\nAlways use TypeScript");
|
||||||
});
|
});
|
||||||
@@ -336,7 +360,7 @@ describe("generatePrompt", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const prompt = generatePrompt(envVars, mockGitHubData, false);
|
const prompt = generatePrompt(envVars, mockGitHubData, false, mockTagMode);
|
||||||
|
|
||||||
expect(prompt).toBe("Simple prompt for owner/repo PR #123");
|
expect(prompt).toBe("Simple prompt for owner/repo PR #123");
|
||||||
expect(prompt).not.toContain("You are Claude, an AI assistant");
|
expect(prompt).not.toContain("You are Claude, an AI assistant");
|
||||||
@@ -371,7 +395,7 @@ describe("generatePrompt", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const prompt = generatePrompt(envVars, mockGitHubData, false);
|
const prompt = generatePrompt(envVars, mockGitHubData, false, mockTagMode);
|
||||||
|
|
||||||
expect(prompt).toContain("Repository: test/repo");
|
expect(prompt).toContain("Repository: test/repo");
|
||||||
expect(prompt).toContain("PR: 456");
|
expect(prompt).toContain("PR: 456");
|
||||||
@@ -418,7 +442,7 @@ describe("generatePrompt", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const prompt = generatePrompt(envVars, issueGitHubData, false);
|
const prompt = generatePrompt(envVars, issueGitHubData, false, mockTagMode);
|
||||||
|
|
||||||
expect(prompt).toBe("Issue #789: Bug: Login form broken in owner/repo");
|
expect(prompt).toBe("Issue #789: Bug: Login form broken in owner/repo");
|
||||||
});
|
});
|
||||||
@@ -438,7 +462,7 @@ describe("generatePrompt", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const prompt = generatePrompt(envVars, mockGitHubData, false);
|
const prompt = generatePrompt(envVars, mockGitHubData, false, mockTagMode);
|
||||||
|
|
||||||
expect(prompt).toBe("PR: 123, Issue: , Comment: ");
|
expect(prompt).toBe("PR: 123, Issue: , Comment: ");
|
||||||
});
|
});
|
||||||
@@ -458,7 +482,7 @@ describe("generatePrompt", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const prompt = generatePrompt(envVars, mockGitHubData, false);
|
const prompt = generatePrompt(envVars, mockGitHubData, false, mockTagMode);
|
||||||
|
|
||||||
expect(prompt).toContain("You are Claude, an AI assistant");
|
expect(prompt).toContain("You are Claude, an AI assistant");
|
||||||
expect(prompt).toContain("<event_type>ISSUE_CREATED</event_type>");
|
expect(prompt).toContain("<event_type>ISSUE_CREATED</event_type>");
|
||||||
@@ -481,7 +505,7 @@ describe("generatePrompt", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const prompt = generatePrompt(envVars, mockGitHubData, false);
|
const prompt = generatePrompt(envVars, mockGitHubData, false, mockTagMode);
|
||||||
|
|
||||||
expect(prompt).toContain("<trigger_username>johndoe</trigger_username>");
|
expect(prompt).toContain("<trigger_username>johndoe</trigger_username>");
|
||||||
// With commit signing disabled, co-author info appears in git commit instructions
|
// With commit signing disabled, co-author info appears in git commit instructions
|
||||||
@@ -503,7 +527,7 @@ describe("generatePrompt", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const prompt = generatePrompt(envVars, mockGitHubData, false);
|
const prompt = generatePrompt(envVars, mockGitHubData, false, mockTagMode);
|
||||||
|
|
||||||
// Should contain PR-specific instructions (git commands when not using signing)
|
// Should contain PR-specific instructions (git commands when not using signing)
|
||||||
expect(prompt).toContain("git push");
|
expect(prompt).toContain("git push");
|
||||||
@@ -534,7 +558,7 @@ describe("generatePrompt", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const prompt = generatePrompt(envVars, mockGitHubData, false);
|
const prompt = generatePrompt(envVars, mockGitHubData, false, mockTagMode);
|
||||||
|
|
||||||
// Should contain Issue-specific instructions
|
// Should contain Issue-specific instructions
|
||||||
expect(prompt).toContain(
|
expect(prompt).toContain(
|
||||||
@@ -573,7 +597,7 @@ describe("generatePrompt", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const prompt = generatePrompt(envVars, mockGitHubData, false);
|
const prompt = generatePrompt(envVars, mockGitHubData, false, mockTagMode);
|
||||||
|
|
||||||
// Should contain the actual branch name with timestamp
|
// Should contain the actual branch name with timestamp
|
||||||
expect(prompt).toContain(
|
expect(prompt).toContain(
|
||||||
@@ -603,7 +627,7 @@ describe("generatePrompt", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const prompt = generatePrompt(envVars, mockGitHubData, false);
|
const prompt = generatePrompt(envVars, mockGitHubData, false, mockTagMode);
|
||||||
|
|
||||||
// Should contain branch-specific instructions like issues
|
// Should contain branch-specific instructions like issues
|
||||||
expect(prompt).toContain(
|
expect(prompt).toContain(
|
||||||
@@ -641,7 +665,7 @@ describe("generatePrompt", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const prompt = generatePrompt(envVars, mockGitHubData, false);
|
const prompt = generatePrompt(envVars, mockGitHubData, false, mockTagMode);
|
||||||
|
|
||||||
// Should contain open PR instructions (git commands when not using signing)
|
// Should contain open PR instructions (git commands when not using signing)
|
||||||
expect(prompt).toContain("git push");
|
expect(prompt).toContain("git push");
|
||||||
@@ -672,7 +696,7 @@ describe("generatePrompt", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const prompt = generatePrompt(envVars, mockGitHubData, false);
|
const prompt = generatePrompt(envVars, mockGitHubData, false, mockTagMode);
|
||||||
|
|
||||||
// Should contain new branch instructions
|
// Should contain new branch instructions
|
||||||
expect(prompt).toContain(
|
expect(prompt).toContain(
|
||||||
@@ -700,7 +724,7 @@ describe("generatePrompt", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const prompt = generatePrompt(envVars, mockGitHubData, false);
|
const prompt = generatePrompt(envVars, mockGitHubData, false, mockTagMode);
|
||||||
|
|
||||||
// Should contain new branch instructions
|
// Should contain new branch instructions
|
||||||
expect(prompt).toContain(
|
expect(prompt).toContain(
|
||||||
@@ -728,7 +752,7 @@ describe("generatePrompt", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const prompt = generatePrompt(envVars, mockGitHubData, false);
|
const prompt = generatePrompt(envVars, mockGitHubData, false, mockTagMode);
|
||||||
|
|
||||||
// Should contain new branch instructions
|
// Should contain new branch instructions
|
||||||
expect(prompt).toContain(
|
expect(prompt).toContain(
|
||||||
@@ -752,7 +776,7 @@ describe("generatePrompt", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const prompt = generatePrompt(envVars, mockGitHubData, false);
|
const prompt = generatePrompt(envVars, mockGitHubData, false, mockTagMode);
|
||||||
|
|
||||||
// Should have git command instructions
|
// Should have git command instructions
|
||||||
expect(prompt).toContain("Use git commands via the Bash tool");
|
expect(prompt).toContain("Use git commands via the Bash tool");
|
||||||
@@ -781,7 +805,7 @@ describe("generatePrompt", () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const prompt = generatePrompt(envVars, mockGitHubData, true);
|
const prompt = generatePrompt(envVars, mockGitHubData, true, mockTagMode);
|
||||||
|
|
||||||
// Should have commit signing tool instructions
|
// Should have commit signing tool instructions
|
||||||
expect(prompt).toContain("mcp__github_file_ops__commit_files");
|
expect(prompt).toContain("mcp__github_file_ops__commit_files");
|
||||||
|
|||||||
@@ -252,6 +252,63 @@ describe("formatComments", () => {
|
|||||||
`[user1 at 2023-01-01T00:00:00Z]: Image: `,
|
`[user1 at 2023-01-01T00:00:00Z]: Image: `,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("filters out minimized comments", () => {
|
||||||
|
const comments: GitHubComment[] = [
|
||||||
|
{
|
||||||
|
id: "1",
|
||||||
|
databaseId: "100001",
|
||||||
|
body: "Normal comment",
|
||||||
|
author: { login: "user1" },
|
||||||
|
createdAt: "2023-01-01T00:00:00Z",
|
||||||
|
isMinimized: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "2",
|
||||||
|
databaseId: "100002",
|
||||||
|
body: "Minimized comment",
|
||||||
|
author: { login: "user2" },
|
||||||
|
createdAt: "2023-01-02T00:00:00Z",
|
||||||
|
isMinimized: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "3",
|
||||||
|
databaseId: "100003",
|
||||||
|
body: "Another normal comment",
|
||||||
|
author: { login: "user3" },
|
||||||
|
createdAt: "2023-01-03T00:00:00Z",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = formatComments(comments);
|
||||||
|
expect(result).toBe(
|
||||||
|
`[user1 at 2023-01-01T00:00:00Z]: Normal comment\n\n[user3 at 2023-01-03T00:00:00Z]: Another normal comment`,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns empty string when all comments are minimized", () => {
|
||||||
|
const comments: GitHubComment[] = [
|
||||||
|
{
|
||||||
|
id: "1",
|
||||||
|
databaseId: "100001",
|
||||||
|
body: "Minimized comment 1",
|
||||||
|
author: { login: "user1" },
|
||||||
|
createdAt: "2023-01-01T00:00:00Z",
|
||||||
|
isMinimized: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "2",
|
||||||
|
databaseId: "100002",
|
||||||
|
body: "Minimized comment 2",
|
||||||
|
author: { login: "user2" },
|
||||||
|
createdAt: "2023-01-02T00:00:00Z",
|
||||||
|
isMinimized: true,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const result = formatComments(comments);
|
||||||
|
expect(result).toBe("");
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("formatReviewComments", () => {
|
describe("formatReviewComments", () => {
|
||||||
@@ -517,6 +574,159 @@ describe("formatReviewComments", () => {
|
|||||||
`[Review by reviewer1 at 2023-01-01T00:00:00Z]: APPROVED\nReview body\n [Comment on src/index.ts:42]: Image: `,
|
`[Review by reviewer1 at 2023-01-01T00:00:00Z]: APPROVED\nReview body\n [Comment on src/index.ts:42]: Image: `,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("filters out minimized review comments", () => {
|
||||||
|
const reviewData = {
|
||||||
|
nodes: [
|
||||||
|
{
|
||||||
|
id: "review1",
|
||||||
|
databaseId: "300001",
|
||||||
|
author: { login: "reviewer1" },
|
||||||
|
body: "Review with mixed comments",
|
||||||
|
state: "APPROVED",
|
||||||
|
submittedAt: "2023-01-01T00:00:00Z",
|
||||||
|
comments: {
|
||||||
|
nodes: [
|
||||||
|
{
|
||||||
|
id: "comment1",
|
||||||
|
databaseId: "200001",
|
||||||
|
body: "Normal review comment",
|
||||||
|
author: { login: "reviewer1" },
|
||||||
|
createdAt: "2023-01-01T00:00:00Z",
|
||||||
|
path: "src/index.ts",
|
||||||
|
line: 42,
|
||||||
|
isMinimized: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "comment2",
|
||||||
|
databaseId: "200002",
|
||||||
|
body: "Minimized review comment",
|
||||||
|
author: { login: "reviewer1" },
|
||||||
|
createdAt: "2023-01-01T00:00:00Z",
|
||||||
|
path: "src/utils.ts",
|
||||||
|
line: 15,
|
||||||
|
isMinimized: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "comment3",
|
||||||
|
databaseId: "200003",
|
||||||
|
body: "Another normal comment",
|
||||||
|
author: { login: "reviewer1" },
|
||||||
|
createdAt: "2023-01-01T00:00:00Z",
|
||||||
|
path: "src/main.ts",
|
||||||
|
line: 10,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = formatReviewComments(reviewData);
|
||||||
|
expect(result).toBe(
|
||||||
|
`[Review by reviewer1 at 2023-01-01T00:00:00Z]: APPROVED\nReview with mixed comments\n [Comment on src/index.ts:42]: Normal review comment\n [Comment on src/main.ts:10]: Another normal comment`,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns review with only body when all review comments are minimized", () => {
|
||||||
|
const reviewData = {
|
||||||
|
nodes: [
|
||||||
|
{
|
||||||
|
id: "review1",
|
||||||
|
databaseId: "300001",
|
||||||
|
author: { login: "reviewer1" },
|
||||||
|
body: "Review body only",
|
||||||
|
state: "APPROVED",
|
||||||
|
submittedAt: "2023-01-01T00:00:00Z",
|
||||||
|
comments: {
|
||||||
|
nodes: [
|
||||||
|
{
|
||||||
|
id: "comment1",
|
||||||
|
databaseId: "200001",
|
||||||
|
body: "Minimized comment 1",
|
||||||
|
author: { login: "reviewer1" },
|
||||||
|
createdAt: "2023-01-01T00:00:00Z",
|
||||||
|
path: "src/index.ts",
|
||||||
|
line: 42,
|
||||||
|
isMinimized: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "comment2",
|
||||||
|
databaseId: "200002",
|
||||||
|
body: "Minimized comment 2",
|
||||||
|
author: { login: "reviewer1" },
|
||||||
|
createdAt: "2023-01-01T00:00:00Z",
|
||||||
|
path: "src/utils.ts",
|
||||||
|
line: 15,
|
||||||
|
isMinimized: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = formatReviewComments(reviewData);
|
||||||
|
expect(result).toBe(
|
||||||
|
`[Review by reviewer1 at 2023-01-01T00:00:00Z]: APPROVED\nReview body only`,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("handles multiple reviews with mixed minimized comments", () => {
|
||||||
|
const reviewData = {
|
||||||
|
nodes: [
|
||||||
|
{
|
||||||
|
id: "review1",
|
||||||
|
databaseId: "300001",
|
||||||
|
author: { login: "reviewer1" },
|
||||||
|
body: "First review",
|
||||||
|
state: "APPROVED",
|
||||||
|
submittedAt: "2023-01-01T00:00:00Z",
|
||||||
|
comments: {
|
||||||
|
nodes: [
|
||||||
|
{
|
||||||
|
id: "comment1",
|
||||||
|
databaseId: "200001",
|
||||||
|
body: "Good comment",
|
||||||
|
author: { login: "reviewer1" },
|
||||||
|
createdAt: "2023-01-01T00:00:00Z",
|
||||||
|
path: "src/index.ts",
|
||||||
|
line: 42,
|
||||||
|
isMinimized: false,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "review2",
|
||||||
|
databaseId: "300002",
|
||||||
|
author: { login: "reviewer2" },
|
||||||
|
body: "Second review",
|
||||||
|
state: "COMMENTED",
|
||||||
|
submittedAt: "2023-01-02T00:00:00Z",
|
||||||
|
comments: {
|
||||||
|
nodes: [
|
||||||
|
{
|
||||||
|
id: "comment2",
|
||||||
|
databaseId: "200002",
|
||||||
|
body: "Spam comment",
|
||||||
|
author: { login: "reviewer2" },
|
||||||
|
createdAt: "2023-01-02T00:00:00Z",
|
||||||
|
path: "src/utils.ts",
|
||||||
|
line: 15,
|
||||||
|
isMinimized: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = formatReviewComments(reviewData);
|
||||||
|
expect(result).toBe(
|
||||||
|
`[Review by reviewer1 at 2023-01-01T00:00:00Z]: APPROVED\nFirst review\n [Comment on src/index.ts:42]: Good comment\n\n[Review by reviewer2 at 2023-01-02T00:00:00Z]: COMMENTED\nSecond review`,
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe("formatChangedFiles", () => {
|
describe("formatChangedFiles", () => {
|
||||||
|
|||||||
10
test/fixtures/sample-turns-expected-output.md
vendored
10
test/fixtures/sample-turns-expected-output.md
vendored
@@ -28,7 +28,7 @@ if __name__ == "__main__":
|
|||||||
print(result)
|
print(result)
|
||||||
```
|
```
|
||||||
|
|
||||||
*Token usage: 100 input, 75 output*
|
*Token usage: 150 input, 75 output*
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -47,7 +47,7 @@ I can see the debug print statement that needs to be removed. Let me fix this by
|
|||||||
|
|
||||||
**→** File successfully edited. The debug print statement has been removed.
|
**→** File successfully edited. The debug print statement has been removed.
|
||||||
|
|
||||||
*Token usage: 200 input, 50 output*
|
*Token usage: 300 input, 50 output*
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -70,7 +70,7 @@ Perfect! I've successfully removed the debug print statement from the function.
|
|||||||
|
|
||||||
**→** Successfully posted review comment to PR #123
|
**→** Successfully posted review comment to PR #123
|
||||||
|
|
||||||
*Token usage: 150 input, 80 output*
|
*Token usage: 225 input, 80 output*
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -82,7 +82,7 @@ Great! I've successfully completed the requested task:
|
|||||||
|
|
||||||
The debug print statement has been removed as requested by the reviewers.
|
The debug print statement has been removed as requested by the reviewers.
|
||||||
|
|
||||||
*Token usage: 180 input, 60 output*
|
*Token usage: 270 input, 60 output*
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -91,5 +91,3 @@ The debug print statement has been removed as requested by the reviewers.
|
|||||||
Successfully removed debug print statement from file and added review comment to document the change.
|
Successfully removed debug print statement from file and added review comment to document the change.
|
||||||
|
|
||||||
**Cost:** $0.0347 | **Duration:** 18.8s
|
**Cost:** $0.0347 | **Duration:** 18.8s
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { getMode, isValidMode } from "../../src/modes/registry";
|
|||||||
import type { ModeName } from "../../src/modes/types";
|
import type { ModeName } from "../../src/modes/types";
|
||||||
import { tagMode } from "../../src/modes/tag";
|
import { tagMode } from "../../src/modes/tag";
|
||||||
import { agentMode } from "../../src/modes/agent";
|
import { agentMode } from "../../src/modes/agent";
|
||||||
|
import { reviewMode } from "../../src/modes/review";
|
||||||
import { createMockContext, createMockAutomationContext } from "../mockContext";
|
import { createMockContext, createMockAutomationContext } from "../mockContext";
|
||||||
|
|
||||||
describe("Mode Registry", () => {
|
describe("Mode Registry", () => {
|
||||||
@@ -30,6 +31,12 @@ describe("Mode Registry", () => {
|
|||||||
expect(mode.name).toBe("agent");
|
expect(mode.name).toBe("agent");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("getMode returns experimental-review mode", () => {
|
||||||
|
const mode = getMode("experimental-review", mockContext);
|
||||||
|
expect(mode).toBe(reviewMode);
|
||||||
|
expect(mode.name).toBe("experimental-review");
|
||||||
|
});
|
||||||
|
|
||||||
test("getMode throws error for tag mode with workflow_dispatch event", () => {
|
test("getMode throws error for tag mode with workflow_dispatch event", () => {
|
||||||
expect(() => getMode("tag", mockWorkflowDispatchContext)).toThrow(
|
expect(() => getMode("tag", mockWorkflowDispatchContext)).toThrow(
|
||||||
"Tag mode cannot handle workflow_dispatch events. Use 'agent' mode for automation events.",
|
"Tag mode cannot handle workflow_dispatch events. Use 'agent' mode for automation events.",
|
||||||
@@ -57,17 +64,17 @@ describe("Mode Registry", () => {
|
|||||||
test("getMode throws error for invalid mode", () => {
|
test("getMode throws error for invalid mode", () => {
|
||||||
const invalidMode = "invalid" as unknown as ModeName;
|
const invalidMode = "invalid" as unknown as ModeName;
|
||||||
expect(() => getMode(invalidMode, mockContext)).toThrow(
|
expect(() => getMode(invalidMode, mockContext)).toThrow(
|
||||||
"Invalid mode 'invalid'. Valid modes are: 'tag', 'agent'. Please check your workflow configuration.",
|
"Invalid mode 'invalid'. Valid modes are: 'tag', 'agent', 'experimental-review'. Please check your workflow configuration.",
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("isValidMode returns true for all valid modes", () => {
|
test("isValidMode returns true for all valid modes", () => {
|
||||||
expect(isValidMode("tag")).toBe(true);
|
expect(isValidMode("tag")).toBe(true);
|
||||||
expect(isValidMode("agent")).toBe(true);
|
expect(isValidMode("agent")).toBe(true);
|
||||||
|
expect(isValidMode("experimental-review")).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("isValidMode returns false for invalid mode", () => {
|
test("isValidMode returns false for invalid mode", () => {
|
||||||
expect(isValidMode("invalid")).toBe(false);
|
expect(isValidMode("invalid")).toBe(false);
|
||||||
expect(isValidMode("review")).toBe(false);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user