Compare commits

...

100 Commits

Author SHA1 Message Date
Ashwin Bhat
d909172ebf tmp 2025-07-16 12:22:25 -07:00
km-anthropic
b04be4e195 Update remaining allowed_domains references to experimental_allowed_domains 2025-07-16 12:13:41 -07:00
km-anthropic
c23800108f Merge branch 'main' into km/network-restrictions-feature 2025-07-16 12:11:42 -07:00
km-anthropic
23b54ce0d2 change to experimental allowed domains and add .blob.core.windows.net to use cached bun isntall 2025-07-16 12:10:11 -07:00
Ashwin Bhat
bf2400d475 docs: add missing use_commit_signing input to README (#283)
* docs: add missing use_commit_signing input to README

Added the `use_commit_signing` input to the README's inputs table. This input was present in action.yml but not documented in the README.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* ci: add documentation consistency check to PR reviews

Updated claude-review.yml to include checking that README.md and other documentation files are updated to reflect code changes, especially for new inputs, features, or configuration options.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-07-16 11:33:13 -07:00
km-anthropic
ed1e708634 Update example allowed_domains with tested domains for network restrictions 2025-07-16 10:54:03 -07:00
km-anthropic
37f5543283 update claude.yml to test 2025-07-16 09:53:51 -07:00
km-anthropic
533ec5356f Update potential EOF not being treated as a string issue 2025-07-16 09:52:14 -07:00
km-anthropic
f1e95926d6 Merge branch 'main' of https://github.com/anthropics/claude-code-action into km/network-restrictions-feature 2025-07-16 08:53:19 -07:00
Ashwin Bhat
4e2cfbac36 Fix: Pass correct branch names to MCP file ops server (#279)
* Reapply "feat: defer remote branch creation until first commit (#244)" (#278)

This reverts commit 018533dc9a.

* fix branch names
2025-07-15 17:10:23 -07:00
Ashwin Bhat
018533dc9a Revert "feat: defer remote branch creation until first commit (#244)" (#278)
This reverts commit cefe963a6b.
2025-07-15 16:05:30 -07:00
Ashwin Bhat
a9d9ad3612 feat: add settings input support (#276)
- Add settings input to action.yml that accepts JSON string or file path
- Pass settings parameter to claude-code-base-action
- Update README with comprehensive settings documentation
- Add link to official Claude Code settings documentation
- Document precedence rules for model and tool permissions

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Claude <noreply@anthropic.com>
2025-07-15 14:00:26 -07:00
GitHub Actions
4824494f4d chore: update claude-code-base-action to v0.0.35 2025-07-15 18:54:33 +00:00
Ashwin Bhat
c09fc691c5 docs: add custom GitHub App setup instructions (#267)
Add comprehensive section explaining how to create and use a custom GitHub App
instead of the official Claude app. This is particularly useful for users with
restrictive organization policies or those using AWS Bedrock/Google Vertex AI.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Claude <noreply@anthropic.com>
2025-07-14 17:17:56 -07:00
km-anthropic
e5b28393c7 Remove proxy example -- it's intuitive for users to figure it out 2025-07-14 15:27:08 -07:00
km-anthropic
168e891554 Remove unnecesssary NO_PROXY as packages are installed beforehand 2025-07-14 15:22:33 -07:00
km-anthropic
7673148cfb Give an example of network restriction in claude.yml 2025-07-14 15:16:23 -07:00
km-anthropic
af74c779a5 Update README with common domains 2025-07-14 15:13:47 -07:00
km-anthropic
2877ea975e Remove unnecessary network restrictions test and update readme + action.yml with no default domains and respective instructions in the readme 2025-07-14 14:47:07 -07:00
km-anthropic
c61f7b0167 Merge branch 'anthropics:main' into km/network-restrictions-feature 2025-07-14 14:21:58 -07:00
km-anthropic
b16ea06ada Simplify network restrictions -- Move it to actions, remove extended examples in claude.yml and move them to readme 2025-07-14 14:19:52 -07:00
km-anthropic
1eab4a208c Move network restrictions to actions.yml + show custom domains in the examples folder 2025-07-14 12:53:57 -07:00
km-anthropic
b938e69075 test: simplify network restrictions test
- Reduce to one allowed and one blocked domain
- Remove slow google.com test
- Fix TypeScript errors with AbortController
- Match test formatting conventions

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-07-14 12:31:11 -07:00
km-anthropic
ba5d64171b Minor bun format 2025-07-14 12:22:04 -07:00
km-anthropic
5b3ce5ec6d refactor: make network restrictions opt-in and move to examples
- Removed network restrictions from .github/workflows/claude.yml
- Added network restrictions to examples/claude.yml as opt-in feature
- Changed from DISABLE_NETWORK_RESTRICTIONS to ENABLE_NETWORK_RESTRICTIONS
- Added support for CUSTOM_ALLOWED_DOMAINS repository variable
- Organized whitelist by provider (Anthropic, Bedrock, Vertex AI)
- Removed package registries from whitelist (already in NO_PROXY)

Users can now enable network restrictions by setting ENABLE_NETWORK_RESTRICTIONS=true
and configure additional domains via CUSTOM_ALLOWED_DOMAINS.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-07-14 12:21:13 -07:00
GitHub Actions
b3c6de94ea chore: update claude-code-base-action to v0.0.34 2025-07-14 15:59:55 +00:00
km-anthropic
c6e906e3ba test: simplify network restrictions test output 2025-07-13 09:08:53 -07:00
km-anthropic
dbf69fe645 test: add network restrictions verification test 2025-07-13 08:57:04 -07:00
km-anthropic
b49014e105 feat: add Squid proxy network restrictions to Claude workflow
Implements URL whitelisting for GitHub Actions to prevent unauthorized network access.
Only allows connections to:
- Claude API (anthropic.com)
- GitHub services
- Package registries (npm, bun)
- Azure blob storage for caching

Uses NO_PROXY for package registries to avoid integrity check issues.
2025-07-13 08:21:37 -07:00
Jay Derinbogaz
b92e56a96b refactor: update branch naming convention for Kubernetes compatibility (#249)
* refactor: update branch naming convention for Kubernetes compatibility

- Changed timestamp format in branch names to a shorter, Kubernetes-compatible style (lowercase, hyphens only).
- Updated related tests to reflect new branch name format.
- Ensured branch names are limited to a maximum of 50 characters to comply with Kubernetes naming requirements.

* refactor: clean up timestamp formatting in branch naming logic

- Removed unnecessary whitespace and standardized string formatting for the Kubernetes-compatible timestamp in branch names.
- Ensured consistency in the use of double quotes for string literals.
2025-07-12 11:30:49 -07:00
David Wells
b6868bfc27 Expose the created branch for downstream usage (#237)
* Expose the created branch for downstream usage

* run bun format
2025-07-11 10:15:41 -07:00
Allen Li
0f9a2c4dc3 fix: add GITHUB_API_URL to all Octokit client instantiations (#243)
Not all Octokit client instantiations were respecting GITHUB_API_URL, so
these tools would fail on enterprise.
2025-07-11 07:46:23 -07:00
Ashwin Bhat
cefe963a6b feat: defer remote branch creation until first commit (#244)
* feat: defer remote branch creation until first commit

- For commit signing: branches are created remotely by github-file-ops-server on first commit
- For non-signing: branches are created locally with 'git checkout -b' and pushed when needed
- Consolidated duplicate branch creation logic in github-file-ops-server into a shared helper function
- Claude is unaware of these implementation details and simply sees it's on the correct branch
- No branch links are shown in initial comments since branches don't exist remotely yet

* fix: prevent broken branch links in final comment update

- Check if branch exists remotely before adding branch link
- Only add branch links for branches that actually exist on GitHub
- Add test coverage for non-existent remote branches
- Fixes issue where users would see broken branch links for local-only branches

* fix: don't show branch name in comment header when branch doesn't exist remotely

- Only pass branchName to updateCommentBody when branchLink exists
- Prevents showing branch names for branches that only exist locally
- Add test to verify branch name is not shown when branch doesn't exist

* tmp
2025-07-10 12:57:15 -07:00
GitHub Actions
eda5af4e69 chore: update claude-code-base-action to v0.0.33 2025-07-10 17:05:41 +00:00
Ashwin Bhat
87facd7051 feat: add use_commit_signing input with default false (#238)
* feat: add use_commit_signing input with default false

- Add new input 'use_commit_signing' to action.yml (defaults to false)
- Separate comment update functionality into standalone github-comment-server.ts
- Update MCP server configuration to conditionally load servers based on signing preference
- When commit signing is disabled, use specific Bash git commands (e.g., Bash(git add:*))
- When commit signing is enabled, use github-file-ops-server for atomic commits with signing
- Always include github-comment-server for comment updates regardless of signing mode
- Update prompt generation to provide appropriate instructions based on signing preference
- Add comprehensive test coverage for new functionality

This change simplifies the default setup for users who don't need commit signing,
while maintaining the option to enable it for those who require GitHub's commit
signature verification.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: auto-commit uncommitted changes when commit signing is disabled

- Check for uncommitted changes after Claude finishes (non-signing mode only)
- Automatically commit and push any uncommitted work to preserve Claude's changes
- Update tests to avoid actual git operations during test runs
- Pass use_commit_signing flag to branch cleanup logic

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-07-09 16:28:36 -07:00
Ashwin Bhat
a804c9e83f feat: add OAuth token authentication support (#236)
* feat: add OAuth token authentication support

Add claude_code_oauth_token as an alternative authentication method to anthropic_api_key.
This provides more flexibility for users who prefer OAuth authentication.

- Add claude_code_oauth_token input to action.yml
- Pass OAuth token through to claude-code-base-action
- Update README with OAuth token documentation and examples
- Update security best practices to cover both authentication methods
- Add OAuth example to examples/claude.yml

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* docs: add OAuth token generation instructions for Pro/Max users

Update README to mention that Pro and Max users can generate OAuth tokens
by running `claude setup-token` locally. This provides clearer guidance
for users who want to use OAuth authentication instead of API keys.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* docs: update CI capabilities documentation

- Move GitHub Actions access from limitations to capabilities in README
- Update FAQ to explain how to enable CI/CD access with actions:read permission
- Clarify that Claude can access workflow results on PRs where it's tagged

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-07-07 16:07:22 -07:00
GitHub Actions
d6bc8ddf8a chore: update claude-code-base-action to v0.0.32 2025-07-07 22:54:31 +00:00
Ashwin Bhat
86665d0984 feat: forward NODE_VERSION environment variable to base action (#230)
This allows users to override the default Node version by setting the
NODE_VERSION environment variable in their workflow.

Fixes #229

Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: Ashwin Bhat <ashwin-ant@users.noreply.github.com>
2025-07-06 16:21:00 -07:00
Tomohiro Ishibashi
6364776f60 fix: update MCP server image to version 0.6.0 (#234)
🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Claude <noreply@anthropic.com>
2025-07-05 22:12:48 -07:00
Rodrigo Yokota
e43c1b7fac fix(github): fixing claude login user name (#227)
* fix(github): fixing claude login user name

* fix: improving bot user identification conditions

* fix: making a const out of claude bot id
2025-07-04 11:14:14 -07:00
Ashwin Bhat
23fae74fdb Add GitHub Actions MCP server for viewing workflow results (#231)
* actions server

* tmp

* Replace view_actions_results with additional_permissions input

- Changed input from boolean view_actions_results to a more flexible additional_permissions format
- Uses newline-separated colon format similar to claude_env (e.g., "actions: read")
- Maintains permission checking to warn users when their token lacks required permissions
- Updated all tests to use the new format

This allows for future extensibility while currently supporting only "actions: read" permission.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Update GitHub Actions MCP server with RUNNER_TEMP and status filtering

- Use RUNNER_TEMP environment variable for log storage directory (defaults to /tmp)
- Add status parameter to get_ci_status tool to filter workflow runs
- Supported statuses: completed, action_required, cancelled, failure, neutral, skipped, stale, success, timed_out, in_progress, queued, requested, waiting, pending
- Pass RUNNER_TEMP from install-mcp-server.ts to the MCP server environment

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Add GitHub Actions MCP tools to allowed tools when actions:read is granted

- Automatically include github_ci MCP server tools in allowed tools list when actions:read permission is granted
- Added mcp__github_ci__get_ci_status, mcp__github_ci__get_workflow_run_details, mcp__github_ci__download_job_log
- Simplified permission checking to avoid duplicate parsing logic
- Added tests for the new functionality

This ensures Claude can use the Actions tools when the server is enabled.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Refactor additional permissions parsing to parseGitHubContext

- Moved additional permissions parsing from individual functions to centralized parseGitHubContext
- Added parseAdditionalPermissions function to handle newline-separated colon format
- Removed redundant additionalPermissions parameter from prepareMcpConfig
- Updated tests to use permissions from context instead of passing as parameter
- Added comprehensive tests for parseAdditionalPermissions function

This centralizes all input parsing logic in one place for better maintainability.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Remove unnecessary hasActionsReadPermission parameter from createPrompt

- Removed hasActionsReadPermission parameter since createPrompt has access to context
- Calculate hasActionsReadPermission directly from context.inputs.additionalPermissions inside createPrompt
- Simplified prepare.ts by removing intermediate permission check

This completes the refactoring to centralize all permission handling through the context object.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* docs: Add documentation for additional_permissions feature

- Document the new additional_permissions input that replaces view_actions_results
- Add dedicated section explaining CI/CD integration with actions:read permission
- Include example workflow showing how to grant GitHub token permissions
- Update main workflow example to show optional additional_permissions usage

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* roadmap

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-07-03 18:58:02 -07:00
Ashwin Bhat
3c739a8cf3 Add retry logic for intermittent 403 errors in MCP file operations (#232)
- Extract retry logic to shared utility in src/utils/retry.ts
- Update token.ts to use shared retry utility
- Add retry with exponential backoff to git reference updates
- Only retry on 403 errors, fail immediately on other errors
- Use shorter delays (1-5s) for transient GitHub API failures

This handles intermittent 403 'Resource not accessible by integration'
errors transparently without requiring workflow permission changes. These
errors appear to be transient GitHub API issues that succeed on retry.
2025-07-03 15:56:19 -07:00
GitHub Actions
aa28d465c5 chore: update claude-code-base-action to v0.0.31 2025-07-03 21:42:32 +00:00
Ashwin Bhat
55b7205cd2 feat: add fallback_model input to enable automatic model fallback (#228)
- Add fallback_model input to action.yml matching claude-code-base-action
- Pass fallback_model through to the base action
- Document the new input in README.md inputs table
- Enables automatic fallback when primary model is unavailable

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Claude <noreply@anthropic.com>
2025-07-03 11:09:10 -07:00
Piotr Padlewski
8fe405c45f feat: add formatted output for Claude Code execution reports (#18)
* feat: add formatted output for Claude Code execution reports

- Write turns formatter
- Modify GitHub Action to call formatter instead of dumping raw JSON
- Add comprehensive unit tests (30 tests) covering all functionality
- Add integration test with sample data for output consistency
- Support syntax highlighting for multiple content types (JSON, Python, bash, etc.)
- Include turn grouping logic and token usage tracking
- Provide CLI interface for standalone formatter usage

🤖 Generated with [Claude Code](https://claude.ai/code)
Note: seriously I have never written any line of ts code in my life, so
please make sure this is fine as I don't give any guarantees

Co-Authored-By: Claude <noreply@anthropic.com>

* Add fallback

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-07-03 10:59:12 -07:00
Ashwin Bhat
73012199e4 fix sticky comment variable name (#226)
* fix sticky comment variable name

* fix condition
2025-07-03 09:18:28 -07:00
GitHub Actions
459b56e54d chore: update claude-code-base-action to v0.0.30 2025-07-03 04:27:02 +00:00
GitHub Actions
00f9595fb4 chore: update claude-code-base-action to v0.0.29 2025-07-01 21:38:26 +00:00
Dmitriy Shekhovtsov
79f2086fce feat: add sticky_comment input to reduce GitHub comment spam (#211)
* feat: no claude spam

* feat: add silent property

* feat: add silent property

* feat: add silent property

* chore: call me a sticky comment

* chore: applying review comments

* chore: apply review comments

* format

* reword

---------

Co-authored-by: Ashwin Bhat <ashwin@anthropic.com>
2025-07-01 10:37:39 -07:00
Julien Tanay
bcb072b63f docs: add FAQ entry about assigning in a private repo (#218) 2025-07-01 07:17:03 -07:00
GitHub Actions
e3b3e531a7 chore: update claude-code-base-action to v0.0.28 2025-07-01 02:57:05 +00:00
Derek Bredensteiner
a7665d3698 fix: resolve CI issues - formatting and TypeScript errors (#217)
* fixed file ingestion

* working binary files

* added replaced baseUrl

* fix: add type assertion for GitHub blob API response

Fixes TypeScript error where blobData was of type 'unknown' by adding
proper type assertion for the blob creation response.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Andrew Grosser <dioptre@gmail.com>
Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Andrew Grosser <dioptre@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
2025-06-30 19:56:37 -07:00
taku.tsunose
91c510a769 fix: add missing LABEL_TRIGGER environment variable to prepare step (#209)
The label_trigger input was defined but not passed as an environment variable
to the prepare step, causing it to be undefined in the prepare script.
This adds the missing LABEL_TRIGGER environment variable mapping.

Co-authored-by: taku.tsunose <taku.tsunose@takutsunosenoMacBook-Pro.local>
2025-06-27 09:25:00 -07:00
GitHub Actions
1e006bf2d0 chore: update claude-code-base-action to v0.0.27 2025-06-26 01:00:41 +00:00
Stefano Amorelli
ece712ea81 chore(README): add base branch parameter (#201) 2025-06-25 14:21:46 -07:00
Stefano Amorelli
032008d3b6 feat(config): add branch prefix configuration (#197) 2025-06-25 14:01:25 -07:00
Tomohiro Ishibashi
b0d9b8c4cd Add label trigger functionality to Claude Code Action (#177)
- introduced a new input parameter `label_trigger` in `action.yml` to allow triggering actions based on specific labels applied to issues.
- Enhanced the context preparation and event handling in the code to support the new labled event.
2025-06-25 10:25:26 -07:00
GitHub Actions
c831be8f54 chore: update claude-code-base-action to v0.0.26 2025-06-24 23:47:06 +00:00
Tomohiro Ishibashi
38254908ae fix: allow direct_prompt with issue assignment without requiring assignee_trigger (#192)
- Modified validation logic to only require assignee_trigger when direct_prompt is not provided
- Made assigneeTrigger optional in IssueAssignedEvent type definition
- Enhanced context generation to handle missing assigneeTrigger gracefully
- Added comprehensive test coverage for the new behavior

This enables direct_prompt workflows on issue assignment events without
requiring assignee_trigger configuration, fixing the error:
"ASSIGNEE_TRIGGER is required for issue assigned event"

Fixes #113

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Claude <noreply@anthropic.com>
2025-06-23 17:41:25 -07:00
Tomohiro Ishibashi
882586e496 chore: remove unwanted files added in commit 91f620f (#193)
Remove example-dispatch-workflow.yml and pr-summary.md that were
unintentionally added to the root directory in commit 91f620f.
These files should not be in the repository root.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Claude <noreply@anthropic.com>
2025-06-23 17:39:14 -07:00
GitHub Actions
28aaa5404d chore: update claude-code-base-action to v0.0.25 2025-06-24 00:35:11 +00:00
GitHub Actions
ebbd9e9be4 chore: update claude-code-base-action to v0.0.24 2025-06-20 21:50:00 +00:00
GitHub Actions
237de9d329 chore: update claude-code-base-action to v0.0.23 2025-06-20 15:38:21 +00:00
Ashwin Bhat
91f620f8c2 docs: remove references to non-existent test-local.sh script (#187)
All tests for this repo can be run with `bun test` - the test-local.sh script was a holdover from the base action repo.

Fixes #172

Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: Ashwin Bhat <ashwin-ant@users.noreply.github.com>
2025-06-19 07:52:42 -07:00
GitHub Actions
3486c33ebf chore: update claude-code-base-action to v0.0.22 2025-06-17 21:59:57 +00:00
Kuma Taro
13ccdab2f8 fix: correct assignee trigger test to handle different assignee properly (#178)
* fix: use direct assignee field

* fix: correct assignee trigger test to handle different assignee properly

The test was failing because the mockIssueAssignedContext was missing the
top-level assignee field that the trigger validation logic checks. Added
the missing assignee field to the mock context and updated the test to
properly override both the top-level assignee and issue.assignee fields
when testing assignment to a different user.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* Adjust IssuesAssignedEvent import position (#2)

---------

Co-authored-by: Claude <noreply@anthropic.com>
2025-06-17 10:06:06 -07:00
GitHub Actions
bcf2fe94f8 chore: update claude-code-base-action to v0.0.21 2025-06-17 13:39:54 +00:00
Ashwin Bhat
2dab3f2afe Revert "feat: enhance error reporting with specific error types from Claude e…" (#179)
This reverts commit 1b94b9e5a8.
2025-06-16 16:52:07 -07:00
Ashwin Bhat
1b94b9e5a8 feat: enhance error reporting with specific error types from Claude execution (#164)
* feat: enhance error reporting with specific error types from Claude execution

- Extract error subtypes (error_during_execution, error_max_turns) from result object
- Display specific error messages in comment header based on error type
- Use total_cost_usd field from SDKResultMessage type
- Prevent showing redundant error details when already displayed in header

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* chore: update claude-code-base-action to v0.0.19

* feat: use GitHub display name in Co-authored-by trailers (#163)

* feat: use GitHub display name in Co-authored-by trailers

- Add name field to GitHubAuthor type
- Update GraphQL queries to fetch user display names
- Add triggerDisplayName to CommonFields type
- Extract display name from fetched GitHub data in prepareContext
- Update Co-authored-by trailer generation to use display name when available

This ensures consistency with GitHub's web interface behavior where
Co-authored-by trailers use the user's display name rather than username.

Co-authored-by: ashwin-ant <ashwin-ant@users.noreply.github.com>

* fix: update GraphQL queries to handle Actor type correctly

The name field is only available on the User subtype of Actor in GitHub's
GraphQL API. This commit updates the queries to use inline fragments
(... on User) to conditionally access the name field when the actor is
a User type.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: clarify Co-authored-by instructions in prompt

Replace interpolated values with clear references to XML tags and add
explicit formatting instructions. This makes it clearer how to use the
GitHub display name when available while maintaining the username for
the email portion.

Changes:
- Use explicit references to <trigger_display_name> and <trigger_username> tags
- Add clear formatting instructions and example
- Explain fallback behavior when display name is not available

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: fetch trigger user display name via dedicated GraphQL query

Instead of trying to extract the display name from existing data (which
was incomplete due to Actor type limitations), we now:

- Add a dedicated USER_QUERY to fetch user display names
- Pass the trigger username to fetchGitHubData
- Fetch the display name during data collection phase
- Simplify prepareContext to use the pre-fetched display name

This ensures we always get the correct display name for Co-authored-by
trailers, regardless of where the trigger came from.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: ashwin-ant <ashwin-ant@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>

* feat: use dynamic fetch depth based on PR commit count (#169)

- Replace fixed depth of 20 with dynamic calculation
- Use Math.max(commitCount, 20) to ensure minimum context

* Accept multiline input for allowed_tools and disallowed_tools (#168)

* docs: add uv example for Python MCP servers in mcp_config section (#170)

Added documentation showing how to configure Python-based MCP servers using uv
with the --directory argument, as requested in issue #130.

Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: Ashwin Bhat <ashwin-ant@users.noreply.github.com>

* feat: add release workflow with beta tag management (#171)

- Auto-increment patch version for new releases
- Update beta tag to point to latest release
- Update major version tag (v0) for simplified action usage
- Support dry run mode for testing
- Keep beta as the "latest" release channel

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Claude <noreply@anthropic.com>

* chore: update claude-code-base-action to v0.0.20

* update MCP server image to version 0.5.0 (#175)

* refactor: convert error subtype check to switch case

Replace if-else chain with switch statement for better readability
and maintainability when handling error subtypes.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: GitHub Actions <actions@github.com>
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: ashwin-ant <ashwin-ant@users.noreply.github.com>
Co-authored-by: Bastian Gutschke <bge@medicuja.com>
Co-authored-by: Hidetake Iwata <int128@gmail.com>
Co-authored-by: Tomohiro Ishibashi <103555868+tomoish@users.noreply.github.com>
2025-06-16 15:31:43 -07:00
Tomohiro Ishibashi
e0d3fec39f update MCP server image to version 0.5.0 (#175) 2025-06-16 07:40:13 -07:00
GitHub Actions
3c748dc927 chore: update claude-code-base-action to v0.0.20 2025-06-14 02:45:07 +00:00
Ashwin Bhat
ffb2927088 feat: add release workflow with beta tag management (#171)
- Auto-increment patch version for new releases
- Update beta tag to point to latest release
- Update major version tag (v0) for simplified action usage
- Support dry run mode for testing
- Keep beta as the "latest" release channel

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Claude <noreply@anthropic.com>
2025-06-13 17:43:56 -04:00
Ashwin Bhat
def1b3a94e docs: add uv example for Python MCP servers in mcp_config section (#170)
Added documentation showing how to configure Python-based MCP servers using uv
with the --directory argument, as requested in issue #130.

Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: Ashwin Bhat <ashwin-ant@users.noreply.github.com>
2025-06-13 14:15:50 -07:00
Hidetake Iwata
67d7753c80 Accept multiline input for allowed_tools and disallowed_tools (#168) 2025-06-13 10:19:36 -04:00
Bastian Gutschke
a8d323af27 feat: use dynamic fetch depth based on PR commit count (#169)
- Replace fixed depth of 20 with dynamic calculation
- Use Math.max(commitCount, 20) to ensure minimum context
2025-06-13 10:13:30 -04:00
Ashwin Bhat
41dd0aa695 feat: use GitHub display name in Co-authored-by trailers (#163)
* feat: use GitHub display name in Co-authored-by trailers

- Add name field to GitHubAuthor type
- Update GraphQL queries to fetch user display names
- Add triggerDisplayName to CommonFields type
- Extract display name from fetched GitHub data in prepareContext
- Update Co-authored-by trailer generation to use display name when available

This ensures consistency with GitHub's web interface behavior where
Co-authored-by trailers use the user's display name rather than username.

Co-authored-by: ashwin-ant <ashwin-ant@users.noreply.github.com>

* fix: update GraphQL queries to handle Actor type correctly

The name field is only available on the User subtype of Actor in GitHub's
GraphQL API. This commit updates the queries to use inline fragments
(... on User) to conditionally access the name field when the actor is
a User type.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* refactor: clarify Co-authored-by instructions in prompt

Replace interpolated values with clear references to XML tags and add
explicit formatting instructions. This makes it clearer how to use the
GitHub display name when available while maintaining the username for
the email portion.

Changes:
- Use explicit references to <trigger_display_name> and <trigger_username> tags
- Add clear formatting instructions and example
- Explain fallback behavior when display name is not available

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

* feat: fetch trigger user display name via dedicated GraphQL query

Instead of trying to extract the display name from existing data (which
was incomplete due to Actor type limitations), we now:

- Add a dedicated USER_QUERY to fetch user display names
- Pass the trigger username to fetchGitHubData
- Fetch the display name during data collection phase
- Simplify prepareContext to use the pre-fetched display name

This ensures we always get the correct display name for Co-authored-by
trailers, regardless of where the trigger came from.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: ashwin-ant <ashwin-ant@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
2025-06-12 18:16:36 -04:00
GitHub Actions
55966a1dc0 chore: update claude-code-base-action to v0.0.19 2025-06-12 21:55:17 +00:00
GitHub Actions
b10f287695 chore: update claude-code-base-action to v0.0.18 2025-06-11 23:01:51 +00:00
GitHub Actions
56d8eac7ce chore: update claude-code-base-action to v0.0.17 2025-06-11 22:03:34 +00:00
Ashwin Bhat
25f9b8ef9e fix: add baseUrl to Octokit initialization in update_claude_comment (#157)
* fix: add baseUrl to Octokit initialization in update_claude_comment

Fixes Bad credentials error on GitHub Enterprise Server by passing
GITHUB_API_URL as baseUrl when initializing Octokit, consistent with
other Octokit instances in the codebase.

Fixes #156
Related to #107

Co-authored-by: ashwin-ant <ashwin-ant@users.noreply.github.com>

* fix: pass GITHUB_API_URL as env var to MCP server

Update the MCP server initialization to pass GITHUB_API_URL as an
environment variable, allowing it to work correctly with GitHub
Enterprise Server instances.

Co-authored-by: ashwin-ant <ashwin-ant@users.noreply.github.com>

* fix: import GITHUB_API_URL from config in install-mcp-server

Use the centralized GITHUB_API_URL constant from src/github/api/config.ts instead of reading directly from process.env when passing environment variables to the MCP server. This ensures consistency with how the API URL is handled throughout the codebase.

Co-authored-by: ashwin-ant <ashwin-ant@users.noreply.github.com>

* fix

---------

Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: ashwin-ant <ashwin-ant@users.noreply.github.com>
2025-06-11 17:45:05 -04:00
Ashwin Bhat
3bcfbe7385 feat: add MultiEdit to base_allowed_tools (#155)
Add MultiEdit tool to the BASE_ALLOWED_TOOLS array to enable Claude Code to use the MultiEdit tool for making multiple edits to a single file in one operation.

Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: ashwin-ant <ashwin-ant@users.noreply.github.com>
2025-06-10 19:36:52 -04:00
GitHub Actions
bdd0c925cb chore: update claude-code-base-action to v0.0.14 2025-06-10 19:08:55 +00:00
atsushi-ishibashi
37ec8e4781 fix: set disallowed_tools as env when runing prepare.ts (#151) 2025-06-10 08:59:55 -04:00
Ashwin Bhat
e5b1633249 feat: add roadmap for Claude Code GitHub Action v1.0 (#150)
Add ROADMAP.md documenting planned features and improvements for reaching v1.0:
- GitHub Action CI results visibility
- Cross-repo support
- Workflow file modification capabilities
- Additional event trigger support
- Configurable commit signing
- Enhanced code review features
- Bot user trigger support
- Customizable base prompts

The roadmap provides transparency on development priorities and invites
community feedback and contributions.
2025-06-09 18:58:08 -04:00
Ashwin Bhat
37483ba112 feat: add max_turns parameter support (#149)
* feat: add max_turns parameter support

- Add max_turns input to action.yml with proper description
- Pass max_turns parameter through to claude-code-base-action
- Update README with documentation and examples for max_turns usage
- Add comprehensive tests to verify max_turns configuration
- Add yaml dependency for test parsing

Closes #148

Co-authored-by: ashwin-ant <ashwin-ant@users.noreply.github.com>

* chore: remove max-turns test and yaml dependency

Co-authored-by: ashwin-ant <ashwin-ant@users.noreply.github.com>

* chore: revert package.json and bun.lock changes

Co-authored-by: ashwin-ant <ashwin-ant@users.noreply.github.com>

* Update action.yml

* prettier

---------

Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: ashwin-ant <ashwin-ant@users.noreply.github.com>
2025-06-09 13:28:22 -04:00
Sepehr Sobhani
9b50f473cb Update allowed tools align with what is available in github-mcp-server (#145) 2025-06-08 16:24:25 -04:00
GitHub Actions
47ea5c2a69 chore: update claude-code-base-action to v0.0.13 2025-06-06 19:44:49 +00:00
GitHub Actions
4bd9c2053a chore: update claude-code-base-action to v0.0.12 2025-06-06 15:30:07 +00:00
GitHub Actions
f862b5a16a chore: update claude-code-base-action to v0.0.11 2025-06-05 23:19:03 +00:00
Ashwin Bhat
424d1b8f87 update package name (#135) 2025-06-05 13:41:23 -07:00
David Dworken
1d5e695d0c Update package name to reference under the @Anthropic-AI NPM org (#134) 2025-06-05 13:28:36 -07:00
Ashwin Bhat
8e8be41f15 fix: replace github.action_path with GITHUB_ACTION_PATH for containerized workflows (#133)
This change fixes an issue where the action fails in containerized workflow 
jobs. By using ${GITHUB_ACTION_PATH} instead of ${{ github.action_path }}, 
the action can properly locate its resources in container environments.

Fixes #132

Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: ashwin-ant <ashwin-ant@users.noreply.github.com>
2025-06-05 10:10:43 -07:00
Ashwin Bhat
c7957fda5d chore: update claude-code-base-action to v0.0.10 (#131) 2025-06-05 09:59:42 -07:00
Minsu Lee
1990b0bdb3 Update temp directory paths to use runner temp directory (#129)
* Update temp directory paths to use `runner` temp directory

* Update temp directory paths to use `runner` temp directory
2025-06-05 09:53:56 -07:00
Ashwin Bhat
699aa26b41 fix: only load GitHub MCP server when its tools are allowed (#124)
* fix: only load GitHub MCP server when its tools are allowed

- Add allowedTools parameter to prepareMcpConfig
- Check for mcp__github__ and mcp__github_file_ops__ tool prefixes
- Only include MCP servers when their tools are in allowed_tools
- Maintain backward compatibility when allowed_tools is not specified
- Update tests to reflect the new conditional loading behavior

This optimizes resource usage by not loading unnecessary MCP servers
when their tools are not allowed in the configuration.

Co-authored-by: ashwin-ant <ashwin-ant@users.noreply.github.com>

* fix: always load github_file_ops server regardless of allowed_tools

- Only apply conditional loading to the github MCP server
- Always load github_file_ops server as it contains essential tools
- Update tests to reflect this behavior

Co-authored-by: ashwin-ant <ashwin-ant@users.noreply.github.com>

* refactor: move allowedTools/disallowedTools parsing to parseGitHubContext

- Change allowedTools and disallowedTools from string to string[] in ParsedGitHubContext type
- Parse comma-separated environment variables into arrays in parseGitHubContext function
- Update create-prompt and install-mcp-server to use pre-parsed arrays
- Update all affected test files to use array syntax
- Eliminate duplicate parsing logic across the codebase

* style: apply prettier formatting

---------

Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: ashwin-ant <ashwin-ant@users.noreply.github.com>
2025-06-04 11:56:56 -07:00
Ashwin Bhat
94c0c31c1b chore: switch to upstream github-mcp-server v0.4.0 (#126)
* chore: switch to upstream github-mcp-server v0.4.0

Switch from anthropics fork to github/github-mcp-server at commit e9f748f
(version 0.4.0) as requested.

Release link: https://github.com/github/github-mcp-server/releases/tag/v0.4.0

Co-authored-by: ashwin-ant <ashwin-ant@users.noreply.github.com>

* fix comment

---------

Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: ashwin-ant <ashwin-ant@users.noreply.github.com>
2025-06-04 11:42:57 -07:00
Robb Walters
be799cbe7b fix: skip SHA computation for deleted files (#115) 2025-06-03 13:40:52 -07:00
Ashwin Bhat
bd71ac0e8f fix: wrap github MCP config with mcpServers in issue-triage workflow (#118)
Update the MCP configuration structure to properly wrap the github
server configuration within an mcpServers object, matching the
expected format for MCP config files.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-authored-by: Claude <noreply@anthropic.com>
2025-06-03 11:31:04 -07:00
Ashwin Bhat
65b9bcde80 chore: update claude-code-base-action to v0.0.9 (#116) 2025-06-02 21:42:23 -07:00
Ashwin Bhat
70245e56e3 feat: add claude_env input for custom environment variables (#102)
* feat: add claude_env input for custom environment variables

Co-authored-by: ashwin-ant <ashwin-ant@users.noreply.github.com>

* docs: add claude_env input documentation with clear syntax examples

Added comprehensive documentation for the new claude_env input including:
- Entry in the Inputs table with description
- Example in the basic workflow configuration
- Detailed section in Advanced Configuration with practical use cases

This makes it clear how users can pass custom environment variables
to Claude Code execution in YAML format for CI/test setups.

Co-authored-by: ashwin-ant <ashwin-ant@users.noreply.github.com>

---------

Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
Co-authored-by: ashwin-ant <ashwin-ant@users.noreply.github.com>
2025-06-02 20:52:34 -07:00
46 changed files with 4370 additions and 566 deletions

View File

@@ -26,7 +26,8 @@ jobs:
- Potential bugs or issues - Potential bugs or issues
- Suggestions for improvements - Suggestions for improvements
- Overall architecture and design decisions - Overall architecture and design decisions
- Documentation consistency: Verify that README.md and other documentation files are updated to reflect any code changes (especially new inputs, features, or configuration options)
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__add_pull_request_review_comment" 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"

View File

@@ -31,9 +31,14 @@ jobs:
- name: Run Claude Code - name: Run Claude Code
id: claude id: claude
uses: anthropics/claude-code-action@beta uses: ./
with: with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
allowed_tools: "Bash(bun install),Bash(bun test:*),Bash(bun run format),Bash(bun typecheck)" allowed_tools: "Bash(bun install),Bash(bun test:*),Bash(bun run format),Bash(bun typecheck)"
custom_instructions: "You have also been granted tools for editing files and running bun commands (install, run, test, typecheck) for testing your changes: bun install, bun test, bun run format, bun typecheck." custom_instructions: "You have also been granted tools for editing files and running bun commands (install, run, test, typecheck) for testing your changes: bun install, bun test, bun run format, bun typecheck."
model: "claude-opus-4-20250514" model: "claude-opus-4-20250514"
# Test network restrictions
allowed_domains: |
.anthropic.com
.github.com
.githubusercontent.com

View File

@@ -23,18 +23,20 @@ jobs:
mkdir -p /tmp/mcp-config mkdir -p /tmp/mcp-config
cat > /tmp/mcp-config/mcp-servers.json << 'EOF' cat > /tmp/mcp-config/mcp-servers.json << 'EOF'
{ {
"github": { "mcpServers": {
"command": "docker", "github": {
"args": [ "command": "docker",
"run", "args": [
"-i", "run",
"--rm", "-i",
"-e", "--rm",
"GITHUB_PERSONAL_ACCESS_TOKEN", "-e",
"ghcr.io/github/github-mcp-server:sha-7aced2b" "GITHUB_PERSONAL_ACCESS_TOKEN",
], "ghcr.io/github/github-mcp-server:sha-721fd3e"
"env": { ],
"GITHUB_PERSONAL_ACCESS_TOKEN": "${{ secrets.GITHUB_TOKEN }}" "env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "${{ secrets.GITHUB_TOKEN }}"
}
} }
} }
} }

138
.github/workflows/release.yml vendored Normal file
View File

@@ -0,0 +1,138 @@
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"

2
.prettierignore Normal file
View File

@@ -0,0 +1,2 @@
# Test fixtures should not be formatted to preserve exact output matching
test/fixtures/

View File

@@ -50,20 +50,6 @@ Thank you for your interest in contributing to Claude Code Action! This document
bun test 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 ## Pull Request Process
1. Create a new branch from `main`: 1. Create a new branch from `main`:
@@ -103,13 +89,7 @@ Thank you for your interest in contributing to Claude Code Action! This document
When modifying the action: When modifying the action:
1. Test locally with the test script: 1. Test in a real GitHub Actions workflow by:
```bash
./test-local.sh
```
2. Test in a real GitHub Actions workflow by:
- Creating a test repository - Creating a test repository
- Using your branch as the action source: - Using your branch as the action source:
```yaml ```yaml

29
FAQ.md
View File

@@ -12,6 +12,10 @@ The `github-actions` user cannot trigger subsequent GitHub Actions workflows. Th
Only users with **write permissions** to the repository can trigger Claude. This is a security feature to prevent unauthorized use. Make sure the user commenting has at least write access to the repository. Only users with **write permissions** to the repository can trigger Claude. This is a security feature to prevent unauthorized use. Make sure the user commenting has at least write access to the repository.
### Why can't I assign @claude to an issue on my repository?
If you're in a public repository, you should be able to assign to Claude without issue. If it's a private organization repository, you can only assign to users in your own organization, which Claude isn't. In this case, you'll need to make a custom user in that case.
### Why am I getting OIDC authentication errors? ### Why am I getting OIDC authentication errors?
If you're using the default GitHub App authentication, you must add the `id-token: write` permission to your workflow: If you're using the default GitHub App authentication, you must add the `id-token: write` permission to your workflow:
@@ -47,14 +51,29 @@ allowed_tools: "Bash(git rebase:*)" # Use with caution
Claude doesn't create PRs by default. Instead, it pushes commits to a branch and provides a link to a pre-filled PR submission page. This approach ensures your repository's branch protection rules are still adhered to and gives you final control over PR creation. Claude doesn't create PRs by default. Instead, it pushes commits to a branch and provides a link to a pre-filled PR submission page. This approach ensures your repository's branch protection rules are still adhered to and gives you final control over PR creation.
### Why can't Claude run my tests or see CI results? ### Can Claude see my GitHub Actions CI results?
Claude cannot access GitHub Actions logs, test results, or other CI/CD outputs by default. It only has access to the repository files. If you need Claude to see test results, you can either: Yes! Claude can access GitHub Actions workflow runs, job logs, and test results on the PR where it's tagged. To enable this:
1. Instruct Claude to run tests before making commits 1. Add `actions: read` permission to your workflow:
2. Copy and paste CI results into a comment for Claude to analyze
This limitation exists for security reasons but may be reconsidered in the future based on user feedback. ```yaml
permissions:
contents: write
pull-requests: write
issues: write
actions: read
```
2. Configure the action with additional permissions:
```yaml
- uses: anthropics/claude-code-action@beta
with:
additional_permissions: |
actions: read
```
Claude will then be able to analyze CI failures and help debug workflow issues. For running tests locally before commits, you can still instruct Claude to do so in your request.
### Why does Claude only update one comment instead of creating new ones? ### Why does Claude only update one comment instead of creating new ones?

444
README.md
View File

@@ -30,9 +30,91 @@ This command will guide you through setting up the GitHub app and required secre
**Requirements**: You must be a repository admin to complete these steps. **Requirements**: You must be a repository admin to complete these steps.
1. Install the Claude GitHub app to your repository: https://github.com/apps/claude 1. Install the Claude GitHub app to your repository: https://github.com/apps/claude
2. Add `ANTHROPIC_API_KEY` to your repository secrets ([Learn how to use secrets in GitHub Actions](https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions)) 2. Add authentication to your repository secrets ([Learn how to use secrets in GitHub Actions](https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions)):
- Either `ANTHROPIC_API_KEY` for API key authentication
- Or `CLAUDE_CODE_OAUTH_TOKEN` for OAuth token authentication (Pro and Max users can generate this by running `claude setup-token` locally)
3. Copy the workflow file from [`examples/claude.yml`](./examples/claude.yml) into your repository's `.github/workflows/` 3. Copy the workflow file from [`examples/claude.yml`](./examples/claude.yml) into your repository's `.github/workflows/`
### Using a Custom GitHub App
If you prefer not to install the official Claude app, you can create your own GitHub App to use with this action. This gives you complete control over permissions and access.
**When you may want to use a custom GitHub App:**
- You need more restrictive permissions than the official app
- Organization policies prevent installing third-party apps
- You're using AWS Bedrock or Google Vertex AI
**Steps to create and use a custom GitHub App:**
1. **Create a new GitHub App:**
- Go to https://github.com/settings/apps (for personal apps) or your organization's settings
- Click "New GitHub App"
- Configure the app with these minimum permissions:
- **Repository permissions:**
- Contents: Read & Write
- Issues: Read & Write
- Pull requests: Read & Write
- **Account permissions:** None required
- Set "Where can this GitHub App be installed?" to your preference
- Create the app
2. **Generate and download a private key:**
- After creating the app, scroll down to "Private keys"
- Click "Generate a private key"
- Download the `.pem` file (keep this secure!)
3. **Install the app on your repository:**
- Go to the app's settings page
- Click "Install App"
- Select the repositories where you want to use Claude
4. **Add the app credentials to your repository secrets:**
- Go to your repository's Settings → Secrets and variables → Actions
- Add these secrets:
- `APP_ID`: Your GitHub App's ID (found in the app settings)
- `APP_PRIVATE_KEY`: The contents of the downloaded `.pem` file
5. **Update your workflow to use the custom app:**
```yaml
name: Claude with Custom App
on:
issue_comment:
types: [created]
# ... other triggers
jobs:
claude-response:
runs-on: ubuntu-latest
steps:
# Generate a token from your custom app
- name: Generate GitHub App token
id: app-token
uses: actions/create-github-app-token@v1
with:
app-id: ${{ secrets.APP_ID }}
private-key: ${{ secrets.APP_PRIVATE_KEY }}
# Use Claude with your custom app's token
- uses: anthropics/claude-code-action@beta
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
github_token: ${{ steps.app-token.outputs.token }}
# ... other configuration
```
**Important notes:**
- The custom app must have read/write permissions for Issues, Pull Requests, and Contents
- Your app's token will have the exact permissions you configured, nothing more
For more information on creating GitHub Apps, see the [GitHub documentation](https://docs.github.com/en/apps/creating-github-apps).
## 📚 FAQ ## 📚 FAQ
Having issues or questions? Check out our [Frequently Asked Questions](./FAQ.md) for solutions to common problems and detailed explanations of Claude's capabilities and limitations. Having issues or questions? Check out our [Frequently Asked Questions](./FAQ.md) for solutions to common problems and detailed explanations of Claude's capabilities and limitations.
@@ -49,7 +131,7 @@ on:
pull_request_review_comment: pull_request_review_comment:
types: [created] types: [created]
issues: issues:
types: [opened, assigned] types: [opened, assigned, labeled]
pull_request_review: pull_request_review:
types: [submitted] types: [submitted]
@@ -60,31 +142,57 @@ jobs:
- uses: anthropics/claude-code-action@beta - uses: anthropics/claude-code-action@beta
with: with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
# Or use OAuth token instead:
# claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
github_token: ${{ secrets.GITHUB_TOKEN }} github_token: ${{ secrets.GITHUB_TOKEN }}
# Optional: add custom trigger phrase (default: @claude) # Optional: add custom trigger phrase (default: @claude)
# trigger_phrase: "/claude" # trigger_phrase: "/claude"
# Optional: add assignee trigger for issues # Optional: add assignee trigger for issues
# assignee_trigger: "claude" # assignee_trigger: "claude"
# Optional: add label trigger for issues
# label_trigger: "claude"
# Optional: add custom environment variables (YAML format)
# claude_env: |
# NODE_ENV: test
# DEBUG: true
# API_URL: https://api.example.com
# Optional: limit the number of conversation turns
# max_turns: "5"
# Optional: grant additional permissions (requires corresponding GitHub token permissions)
# additional_permissions: |
# actions: read
``` ```
## Inputs ## Inputs
| Input | Description | Required | Default | | Input | Description | Required | Default |
| --------------------- | -------------------------------------------------------------------------------------------------------------------- | -------- | --------- | | ------------------------------ | -------------------------------------------------------------------------------------------------------------------- | -------- | --------- |
| `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\* | - |
| `direct_prompt` | Direct prompt for Claude to execute automatically without needing a trigger (for automated workflows) | No | - | | `claude_code_oauth_token` | Claude Code OAuth token (alternative to anthropic_api_key) | No\* | - |
| `timeout_minutes` | Timeout in minutes for execution | No | `30` | | `direct_prompt` | Direct prompt for Claude to execute automatically without needing a trigger (for automated workflows) | 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 | - | | `base_branch` | The base branch to use for creating new branches (e.g., 'main', 'develop') | No | - |
| `model` | Model to use (provider-specific format required for Bedrock/Vertex) | No | - | | `max_turns` | Maximum number of conversation turns Claude can take (limits back-and-forth exchanges) | No | - |
| `anthropic_model` | **DEPRECATED**: Use `model` instead. Kept for backward compatibility. | No | - | | `timeout_minutes` | Timeout in minutes for execution | No | `30` |
| `use_bedrock` | Use Amazon Bedrock with OIDC authentication instead of direct Anthropic API | No | `false` | | `use_sticky_comment` | Use just one comment to deliver PR comments (only applies for pull_request event workflows) | No | `false` |
| `use_vertex` | Use Google Vertex AI with OIDC authentication instead of direct Anthropic API | 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 | - |
| `allowed_tools` | Additional tools for Claude to use (the base GitHub tools will always be included) | No | "" | | `model` | Model to use (provider-specific format required for Bedrock/Vertex) | No | - |
| `disallowed_tools` | Tools that Claude should never use | No | "" | | `fallback_model` | Enable automatic fallback to specified model when primary model is unavailable | No | - |
| `custom_instructions` | Additional custom instructions to include in the prompt for Claude | No | "" | | `anthropic_model` | **DEPRECATED**: Use `model` instead. Kept for backward compatibility. | No | - |
| `mcp_config` | Additional MCP configuration (JSON string) that merges with the built-in GitHub MCP servers | No | "" | | `use_bedrock` | Use Amazon Bedrock with OIDC authentication instead of direct Anthropic API | No | `false` |
| `assignee_trigger` | The assignee username that triggers the action (e.g. @claude). Only used for issue assignment | No | - | | `use_vertex` | Use Google Vertex AI with OIDC authentication instead of direct Anthropic API | No | `false` |
| `trigger_phrase` | The trigger phrase to look for in comments, issue/PR bodies, and issue titles | No | `@claude` | | `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 | "" |
| `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 | "" |
| `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 | - |
| `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/` |
| `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 | "" |
| `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 | "" |
| `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)
@@ -140,6 +248,40 @@ For MCP servers that require sensitive information like API keys or tokens, use
# ... other inputs # ... 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**: **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. - Always use GitHub Secrets (`${{ secrets.SECRET_NAME }}`) for sensitive values like API keys, tokens, or passwords. Never hardcode secrets directly in the workflow file.
@@ -276,6 +418,7 @@ This action is built on top of [`anthropics/claude-code-base-action`](https://gi
- When triggered on an **issue**: Always creates a new branch for the work - When triggered on an **issue**: Always creates a new branch for the work
- When triggered on an **open PR**: Always pushes directly to the existing PR branch - When triggered on an **open PR**: Always pushes directly to the existing PR branch
- When triggered on a **closed PR**: Creates a new branch since the original is no longer active - When triggered on a **closed PR**: Creates a new branch since the original is no longer active
- **View GitHub Actions Results**: Can access workflow runs, job logs, and test results on the PR where it's tagged when `actions: read` permission is configured (see [Additional Permissions for CI/CD Integration](#additional-permissions-for-cicd-integration))
### What Claude Cannot Do ### What Claude Cannot Do
@@ -284,11 +427,113 @@ This action is built on top of [`anthropics/claude-code-base-action`](https://gi
- **Post Multiple Comments**: Claude only acts by updating its initial comment - **Post Multiple Comments**: Claude only acts by updating its initial comment
- **Execute Commands Outside Its Context**: Claude only has access to the repository and PR/issue context it's triggered in - **Execute Commands Outside Its Context**: Claude only has access to the repository and PR/issue context it's triggered in
- **Run Arbitrary Bash Commands**: By default, Claude cannot execute Bash commands unless explicitly allowed using the `allowed_tools` configuration - **Run Arbitrary Bash Commands**: By default, Claude cannot execute Bash commands unless explicitly allowed using the `allowed_tools` configuration
- **View CI/CD Results**: Cannot access CI systems, test results, or build logs unless an additional tool or MCP server is configured
- **Perform Branch Operations**: Cannot merge branches, rebase, or perform other git operations beyond pushing commits - **Perform Branch Operations**: Cannot merge branches, rebase, or perform other git operations beyond pushing commits
## Advanced Configuration ## Advanced Configuration
### Additional Permissions for CI/CD Integration
The `additional_permissions` input allows Claude to access GitHub Actions workflow information when you grant the necessary permissions. This is particularly useful for analyzing CI/CD failures and debugging workflow issues.
#### Enabling GitHub Actions Access
To allow Claude to view workflow run results, job logs, and CI status:
1. **Grant the necessary permission to your GitHub token**:
- When using the default `GITHUB_TOKEN`, add the `actions: read` permission to your workflow:
```yaml
permissions:
contents: write
pull-requests: write
issues: write
actions: read # Add this line
```
2. **Configure the action with additional permissions**:
```yaml
- uses: anthropics/claude-code-action@beta
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
additional_permissions: |
actions: read
# ... other inputs
```
3. **Claude will automatically get access to CI/CD tools**:
When you enable `actions: read`, Claude can use the following MCP tools:
- `mcp__github_ci__get_ci_status` - View workflow run statuses
- `mcp__github_ci__get_workflow_run_details` - Get detailed workflow information
- `mcp__github_ci__download_job_log` - Download and analyze job logs
#### Example: Debugging Failed CI Runs
```yaml
name: Claude CI Helper
on:
issue_comment:
types: [created]
permissions:
contents: write
pull-requests: write
issues: write
actions: read # Required for CI access
jobs:
claude-ci-helper:
runs-on: ubuntu-latest
steps:
- uses: anthropics/claude-code-action@beta
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
additional_permissions: |
actions: read
# Now Claude can respond to "@claude why did the CI fail?"
```
**Important Notes**:
- The GitHub token must have the `actions: read` permission in your workflow
- If the permission is missing, Claude will warn you and suggest adding it
- Currently, only `actions: read` is supported, but the format allows for future extensions
### Custom Environment Variables
You can pass custom environment variables to Claude Code execution using the `claude_env` input. This is useful for CI/test setups that require specific environment variables:
```yaml
- uses: anthropics/claude-code-action@beta
with:
claude_env: |
NODE_ENV: test
CI: true
DATABASE_URL: postgres://test:test@localhost:5432/test_db
# ... other inputs
```
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 ### Custom Tools
By default, Claude only has access to: By default, Claude only has access to:
@@ -304,8 +549,15 @@ Claude does **not** have access to execute arbitrary Bash commands by default. I
```yaml ```yaml
- uses: anthropics/claude-code-action@beta - uses: anthropics/claude-code-action@beta
with: with:
allowed_tools: "Bash(npm install),Bash(npm run test),Edit,Replace,NotebookEditCell" allowed_tools: |
disallowed_tools: "TaskOutput,KillTask" Bash(npm install)
Bash(npm run test)
Edit
Replace
NotebookEditCell
disallowed_tools: |
TaskOutput
KillTask
# ... other inputs # ... other inputs
``` ```
@@ -322,6 +574,130 @@ Use a specific Claude model:
# ... other inputs # ... other inputs
``` ```
### Network Restrictions
For enhanced security, you can restrict Claude's network access to specific domains only. This feature is particularly useful for:
- Enterprise environments with strict security policies
- Preventing access to external services
- Limiting Claude to only your internal APIs and services
When `experimental_allowed_domains` is set, Claude can only access the domains you explicitly list. You'll need to include the appropriate provider domains based on your authentication method.
#### Provider-Specific Examples
##### If using Anthropic API or subscription
```yaml
- uses: anthropics/claude-code-action@beta
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
# Or: claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
experimental_allowed_domains: |
.anthropic.com
```
##### If using AWS Bedrock
```yaml
- uses: anthropics/claude-code-action@beta
with:
use_bedrock: "true"
experimental_allowed_domains: |
bedrock.*.amazonaws.com
bedrock-runtime.*.amazonaws.com
```
##### If using Google Vertex AI
```yaml
- uses: anthropics/claude-code-action@beta
with:
use_vertex: "true"
experimental_allowed_domains: |
*.googleapis.com
vertexai.googleapis.com
```
#### Common GitHub Domains
In addition to your provider domains, you may need to include GitHub-related domains. For GitHub.com users, common domains include:
```yaml
- uses: anthropics/claude-code-action@beta
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
experimental_allowed_domains: |
.anthropic.com # For Anthropic API
.github.com
.githubusercontent.com
ghcr.io
.blob.core.windows.net
```
For GitHub Enterprise users, replace the GitHub.com domains above with your enterprise domains (e.g., `.github.company.com`, `packages.company.com`, etc.).
To determine which domains your workflow needs, you can temporarily run without restrictions and monitor the network requests, or check your GitHub Enterprise configuration for the specific services you use.
### Claude Code Settings
You can provide Claude Code settings to customize behavior such as model selection, environment variables, permissions, and hooks. Settings can be provided either as a JSON string or a path to a settings file.
#### Option 1: Settings File
```yaml
- uses: anthropics/claude-code-action@beta
with:
settings: "path/to/settings.json"
# ... other inputs
```
#### Option 2: Inline Settings
```yaml
- uses: anthropics/claude-code-action@beta
with:
settings: |
{
"model": "claude-opus-4-20250514",
"env": {
"DEBUG": "true",
"API_URL": "https://api.example.com"
},
"permissions": {
"allow": ["Bash", "Read"],
"deny": ["WebFetch"]
},
"hooks": {
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{
"type": "command",
"command": "echo Running bash command..."
}]
}]
}
}
# ... other inputs
```
The settings support all Claude Code settings options including:
- `model`: Override the default model
- `env`: Environment variables for the session
- `permissions`: Tool usage permissions
- `hooks`: Pre/post tool execution hooks
- And more...
For a complete list of available settings and their descriptions, see the [Claude Code settings documentation](https://docs.anthropic.com/en/docs/claude-code/settings).
**Notes**:
- The `enableAllProjectMcpServers` setting is always set to `true` by this action to ensure MCP servers work correctly.
- If both the `model` input parameter and a `model` in settings are provided, the `model` input parameter takes precedence.
- The `allowed_tools` and `disallowed_tools` input parameters take precedence over `permissions` in settings.
- In a future version, we may deprecate individual input parameters in favor of using the settings file for all configuration.
## Cloud Providers ## Cloud Providers
You can authenticate with Claude using any of these three methods: You can authenticate with Claude using any of these three methods:
@@ -440,18 +816,21 @@ The [Claude Code GitHub app](https://github.com/apps/claude) requires these perm
All commits made by Claude through this action are automatically signed with commit signatures. This ensures the authenticity and integrity of commits, providing a verifiable trail of changes made by the action. All commits made by Claude through this action are automatically signed with commit signatures. This ensures the authenticity and integrity of commits, providing a verifiable trail of changes made by the action.
### ⚠️ ANTHROPIC_API_KEY Protection ### ⚠️ Authentication Protection
**CRITICAL: Never hardcode your Anthropic API key in workflow files!** **CRITICAL: Never hardcode your Anthropic API key or OAuth token in workflow files!**
Your ANTHROPIC_API_KEY must always be stored in GitHub secrets to prevent unauthorized access: Your authentication credentials must always be stored in GitHub secrets to prevent unauthorized access:
```yaml ```yaml
# CORRECT ✅ # CORRECT ✅
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
# OR
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
# NEVER DO THIS ❌ # NEVER DO THIS ❌
anthropic_api_key: "sk-ant-api03-..." # Exposed and vulnerable! anthropic_api_key: "sk-ant-api03-..." # Exposed and vulnerable!
claude_code_oauth_token: "oauth_token_..." # Exposed and vulnerable!
``` ```
### Setting Up GitHub Secrets ### Setting Up GitHub Secrets
@@ -459,17 +838,18 @@ anthropic_api_key: "sk-ant-api03-..." # Exposed and vulnerable!
1. Go to your repository's Settings 1. Go to your repository's Settings
2. Click on "Secrets and variables" → "Actions" 2. Click on "Secrets and variables" → "Actions"
3. Click "New repository secret" 3. Click "New repository secret"
4. Name: `ANTHROPIC_API_KEY` 4. For authentication, choose one:
5. Value: Your Anthropic API key (starting with `sk-ant-`) - API Key: Name: `ANTHROPIC_API_KEY`, Value: Your Anthropic API key (starting with `sk-ant-`)
6. Click "Add secret" - OAuth Token: Name: `CLAUDE_CODE_OAUTH_TOKEN`, Value: Your Claude Code OAuth token (Pro and Max users can generate this by running `claude setup-token` locally)
5. Click "Add secret"
### Best Practices for ANTHROPIC_API_KEY ### Best Practices for Authentication
1. ✅ Always use `${{ secrets.ANTHROPIC_API_KEY }}` in workflows 1. ✅ Always use `${{ secrets.ANTHROPIC_API_KEY }}` or `${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}` in workflows
2. ✅ Never commit API keys to version control 2. ✅ Never commit API keys or tokens to version control
3. ✅ Regularly rotate your API keys 3. ✅ Regularly rotate your API keys and tokens
4. ✅ Use environment secrets for organization-wide access 4. ✅ Use environment secrets for organization-wide access
5. ❌ Never share API keys in pull requests or issues 5. ❌ Never share API keys or tokens in pull requests or issues
6. ❌ Avoid logging workflow variables that might contain keys 6. ❌ Avoid logging workflow variables that might contain keys
## Security Best Practices ## Security Best Practices

20
ROADMAP.md Normal file
View File

@@ -0,0 +1,20 @@
# 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

@@ -12,9 +12,17 @@ inputs:
assignee_trigger: assignee_trigger:
description: "The assignee username that triggers the action (e.g. @claude)" description: "The assignee username that triggers the action (e.g. @claude)"
required: false required: false
label_trigger:
description: "The label that triggers the action (e.g. claude)"
required: false
default: "claude"
base_branch: base_branch:
description: "The branch to use as the base/source when creating new branches (defaults to repository default branch)" description: "The branch to use as the base/source when creating new branches (defaults to repository default branch)"
required: false required: false
branch_prefix:
description: "The prefix to use for Claude branches (defaults to 'claude/', use 'claude-' for dash format)"
required: false
default: "claude/"
# Claude Code configuration # Claude Code configuration
model: model:
@@ -23,6 +31,9 @@ inputs:
anthropic_model: anthropic_model:
description: "DEPRECATED: Use 'model' instead. Model to use (provider-specific format required for Bedrock/Vertex)" description: "DEPRECATED: Use 'model' instead. Model to use (provider-specific format required for Bedrock/Vertex)"
required: false required: false
fallback_model:
description: "Enable automatic fallback to specified model when primary model is unavailable"
required: false
allowed_tools: allowed_tools:
description: "Additional tools for Claude to use (the base GitHub tools will always be included)" description: "Additional tools for Claude to use (the base GitHub tools will always be included)"
required: false required: false
@@ -41,6 +52,16 @@ inputs:
default: "" default: ""
mcp_config: mcp_config:
description: "Additional MCP configuration (JSON string) that merges with the built-in GitHub MCP servers" description: "Additional MCP configuration (JSON string) that merges with the built-in GitHub MCP servers"
additional_permissions:
description: "Additional permissions to enable. Currently supports 'actions: read' for viewing workflow results"
required: false
default: ""
claude_env:
description: "Custom environment variables to pass to Claude Code execution (YAML format)"
required: false
default: ""
settings:
description: "Claude Code settings as JSON string or path to settings JSON file"
required: false required: false
default: "" default: ""
@@ -48,6 +69,9 @@ inputs:
anthropic_api_key: anthropic_api_key:
description: "Anthropic API key (required for direct API, not needed for Bedrock/Vertex)" description: "Anthropic API key (required for direct API, not needed for Bedrock/Vertex)"
required: false required: false
claude_code_oauth_token:
description: "Claude Code OAuth token (alternative to anthropic_api_key)"
required: false
github_token: github_token:
description: "GitHub token with repo and pull request permissions (optional if using GitHub App)" description: "GitHub token with repo and pull request permissions (optional if using GitHub App)"
required: false required: false
@@ -60,15 +84,34 @@ inputs:
required: false required: false
default: "false" default: "false"
max_turns:
description: "Maximum number of conversation turns"
required: false
default: ""
timeout_minutes: timeout_minutes:
description: "Timeout in minutes for execution" description: "Timeout in minutes for execution"
required: false required: false
default: "30" default: "30"
use_sticky_comment:
description: "Use just one comment to deliver issue/PR comments"
required: false
default: "false"
use_commit_signing:
description: "Enable commit signing using GitHub's commit signature verification. When false, Claude uses standard git commands"
required: false
default: "false"
experimental_allowed_domains:
description: "Restrict network access to these domains only (newline-separated). If not set, no restrictions are applied. Provider domains are auto-detected."
required: false
default: ""
outputs: outputs:
execution_file: execution_file:
description: "Path to the Claude Code execution output file" description: "Path to the Claude Code execution output file"
value: ${{ steps.claude-code.outputs.execution_file }} value: ${{ steps.claude-code.outputs.execution_file }}
branch_name:
description: "The branch created by Claude Code for this execution"
value: ${{ steps.prepare.outputs.CLAUDE_BRANCH }}
runs: runs:
using: "composite" using: "composite"
@@ -81,43 +124,88 @@ runs:
- name: Install Dependencies - name: Install Dependencies
shell: bash shell: bash
run: | run: |
cd ${{ github.action_path }} cd ${GITHUB_ACTION_PATH}
bun install bun install
- name: Prepare action - name: Prepare action
id: prepare id: prepare
shell: bash shell: bash
run: | run: |
bun run ${{ github.action_path }}/src/entrypoints/prepare.ts bun run ${GITHUB_ACTION_PATH}/src/entrypoints/prepare.ts
env: env:
TRIGGER_PHRASE: ${{ inputs.trigger_phrase }} TRIGGER_PHRASE: ${{ inputs.trigger_phrase }}
ASSIGNEE_TRIGGER: ${{ inputs.assignee_trigger }} ASSIGNEE_TRIGGER: ${{ inputs.assignee_trigger }}
LABEL_TRIGGER: ${{ inputs.label_trigger }}
BASE_BRANCH: ${{ inputs.base_branch }} BASE_BRANCH: ${{ inputs.base_branch }}
BRANCH_PREFIX: ${{ inputs.branch_prefix }}
ALLOWED_TOOLS: ${{ inputs.allowed_tools }} ALLOWED_TOOLS: ${{ inputs.allowed_tools }}
DISALLOWED_TOOLS: ${{ inputs.disallowed_tools }}
CUSTOM_INSTRUCTIONS: ${{ inputs.custom_instructions }} CUSTOM_INSTRUCTIONS: ${{ inputs.custom_instructions }}
DIRECT_PROMPT: ${{ inputs.direct_prompt }} DIRECT_PROMPT: ${{ inputs.direct_prompt }}
MCP_CONFIG: ${{ inputs.mcp_config }} MCP_CONFIG: ${{ inputs.mcp_config }}
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 }}
ACTIONS_TOKEN: ${{ github.token }}
ADDITIONAL_PERMISSIONS: ${{ inputs.additional_permissions }}
USE_COMMIT_SIGNING: ${{ inputs.use_commit_signing }}
- name: Setup Network Restrictions
if: steps.prepare.outputs.contains_trigger == 'true' && inputs.experimental_allowed_domains != ''
shell: bash
run: |
# Install and configure Squid proxy
sudo apt-get update && sudo apt-get install -y squid
echo "${{ inputs.experimental_allowed_domains }}" > $RUNNER_TEMP/whitelist.txt
# Configure Squid
sudo tee /etc/squid/squid.conf << EOF
http_port 127.0.0.1:3128
acl whitelist dstdomain "$RUNNER_TEMP/whitelist.txt"
acl localhost src 127.0.0.1/32
http_access allow localhost whitelist
http_access deny all
cache deny all
EOF
# Stop any existing squid instance and start with our config
sudo squid -k shutdown || true
sleep 2
sudo rm -f /run/squid.pid
sudo squid -N -d 1 &
sleep 5
# Set proxy environment variables
echo "http_proxy=http://127.0.0.1:3128" >> $GITHUB_ENV
echo "https_proxy=http://127.0.0.1:3128" >> $GITHUB_ENV
echo "HTTP_PROXY=http://127.0.0.1:3128" >> $GITHUB_ENV
echo "HTTPS_PROXY=http://127.0.0.1:3128" >> $GITHUB_ENV
- name: Run Claude Code - name: Run Claude Code
id: claude-code id: claude-code
if: steps.prepare.outputs.contains_trigger == 'true' if: steps.prepare.outputs.contains_trigger == 'true'
uses: anthropics/claude-code-base-action@c8e31bd52d9a149b3f8309d7978c6edaa282688d # v0.0.8 uses: anthropics/claude-code-base-action@503cc7080e62d63d2cc1d80035ed04617d5efb47 # v0.0.35
with: with:
prompt_file: /tmp/claude-prompts/claude-prompt.txt prompt_file: ${{ runner.temp }}/claude-prompts/claude-prompt.txt
allowed_tools: ${{ env.ALLOWED_TOOLS }} allowed_tools: ${{ env.ALLOWED_TOOLS }}
disallowed_tools: ${{ env.DISALLOWED_TOOLS }} disallowed_tools: ${{ env.DISALLOWED_TOOLS }}
timeout_minutes: ${{ inputs.timeout_minutes }} timeout_minutes: ${{ inputs.timeout_minutes }}
max_turns: ${{ inputs.max_turns }}
model: ${{ inputs.model || inputs.anthropic_model }} model: ${{ inputs.model || inputs.anthropic_model }}
fallback_model: ${{ inputs.fallback_model }}
mcp_config: ${{ steps.prepare.outputs.mcp_config }} mcp_config: ${{ steps.prepare.outputs.mcp_config }}
use_bedrock: ${{ inputs.use_bedrock }} use_bedrock: ${{ inputs.use_bedrock }}
use_vertex: ${{ inputs.use_vertex }} use_vertex: ${{ inputs.use_vertex }}
anthropic_api_key: ${{ inputs.anthropic_api_key }} anthropic_api_key: ${{ inputs.anthropic_api_key }}
claude_code_oauth_token: ${{ inputs.claude_code_oauth_token }}
claude_env: ${{ inputs.claude_env }}
settings: ${{ inputs.settings }}
env: env:
# Model configuration # Model configuration
ANTHROPIC_MODEL: ${{ inputs.model || inputs.anthropic_model }} ANTHROPIC_MODEL: ${{ inputs.model || inputs.anthropic_model }}
GITHUB_TOKEN: ${{ steps.prepare.outputs.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ steps.prepare.outputs.GITHUB_TOKEN }}
NODE_VERSION: ${{ env.NODE_VERSION }}
# Provider configuration # Provider configuration
ANTHROPIC_BASE_URL: ${{ env.ANTHROPIC_BASE_URL }} ANTHROPIC_BASE_URL: ${{ env.ANTHROPIC_BASE_URL }}
@@ -144,7 +232,7 @@ runs:
if: steps.prepare.outputs.contains_trigger == 'true' && steps.prepare.outputs.claude_comment_id && always() if: steps.prepare.outputs.contains_trigger == 'true' && steps.prepare.outputs.claude_comment_id && always()
shell: bash shell: bash
run: | run: |
bun run ${{ github.action_path }}/src/entrypoints/update-comment-link.ts bun run ${GITHUB_ACTION_PATH}/src/entrypoints/update-comment-link.ts
env: env:
REPOSITORY: ${{ github.repository }} REPOSITORY: ${{ github.repository }}
PR_NUMBER: ${{ github.event.issue.number || github.event.pull_request.number }} PR_NUMBER: ${{ github.event.issue.number || github.event.pull_request.number }}
@@ -161,15 +249,25 @@ runs:
TRIGGER_USERNAME: ${{ github.event.comment.user.login || github.event.issue.user.login || github.event.pull_request.user.login || github.event.sender.login || github.triggering_actor || github.actor || '' }} TRIGGER_USERNAME: ${{ github.event.comment.user.login || github.event.issue.user.login || github.event.pull_request.user.login || github.event.sender.login || github.triggering_actor || github.actor || '' }}
PREPARE_SUCCESS: ${{ steps.prepare.outcome == 'success' }} PREPARE_SUCCESS: ${{ steps.prepare.outcome == 'success' }}
PREPARE_ERROR: ${{ steps.prepare.outputs.prepare_error || '' }} PREPARE_ERROR: ${{ steps.prepare.outputs.prepare_error || '' }}
USE_STICKY_COMMENT: ${{ inputs.use_sticky_comment }}
USE_COMMIT_SIGNING: ${{ inputs.use_commit_signing }}
- name: Display Claude Code Report - name: Display Claude Code Report
if: steps.prepare.outputs.contains_trigger == 'true' && steps.claude-code.outputs.execution_file != '' if: steps.prepare.outputs.contains_trigger == 'true' && steps.claude-code.outputs.execution_file != ''
shell: bash shell: bash
run: | run: |
echo "## Claude Code Report" >> $GITHUB_STEP_SUMMARY # Try to format the turns, but if it fails, dump the raw JSON
echo '```json' >> $GITHUB_STEP_SUMMARY if bun run ${{ github.action_path }}/src/entrypoints/format-turns.ts "${{ steps.claude-code.outputs.execution_file }}" >> $GITHUB_STEP_SUMMARY 2>/dev/null; then
cat "${{ steps.claude-code.outputs.execution_file }}" >> $GITHUB_STEP_SUMMARY echo "Successfully formatted Claude Code report"
echo '```' >> $GITHUB_STEP_SUMMARY else
echo "## Claude Code Report (Raw Output)" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo "Failed to format output (please report). Here's the raw JSON:" >> $GITHUB_STEP_SUMMARY
echo "" >> $GITHUB_STEP_SUMMARY
echo '```json' >> $GITHUB_STEP_SUMMARY
cat "${{ steps.claude-code.outputs.execution_file }}" >> $GITHUB_STEP_SUMMARY
echo '```' >> $GITHUB_STEP_SUMMARY
fi
- name: Revoke app token - name: Revoke app token
if: always() && inputs.github_token == '' if: always() && inputs.github_token == ''

View File

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

View File

@@ -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__add_pull_request_review_comment" # 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"

View File

@@ -33,4 +33,15 @@ jobs:
uses: anthropics/claude-code-action@beta uses: anthropics/claude-code-action@beta
with: with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
# Or use OAuth token instead:
# claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
timeout_minutes: "60" timeout_minutes: "60"
# Optional: Restrict network access to specific domains only
# experimental_allowed_domains: |
# .anthropic.com
# .github.com
# api.github.com
# .githubusercontent.com
# bun.sh
# registry.npmjs.org
# .blob.core.windows.net

View File

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

View File

@@ -24,49 +24,81 @@ export type { CommonFields, PreparedContext } from "./types";
const BASE_ALLOWED_TOOLS = [ const BASE_ALLOWED_TOOLS = [
"Edit", "Edit",
"MultiEdit",
"Glob", "Glob",
"Grep", "Grep",
"LS", "LS",
"Read", "Read",
"Write", "Write",
"mcp__github_file_ops__commit_files",
"mcp__github_file_ops__delete_files",
"mcp__github_file_ops__update_claude_comment",
]; ];
const DISALLOWED_TOOLS = ["WebSearch", "WebFetch"]; const DISALLOWED_TOOLS = ["WebSearch", "WebFetch"];
export function buildAllowedToolsString(customAllowedTools?: string): string { export function buildAllowedToolsString(
customAllowedTools?: string[],
includeActionsTools: boolean = false,
useCommitSigning: boolean = false,
): string {
let baseTools = [...BASE_ALLOWED_TOOLS]; let baseTools = [...BASE_ALLOWED_TOOLS];
// Always include the comment update tool from the comment server
baseTools.push("mcp__github_comment__update_claude_comment");
// Add commit signing tools if enabled
if (useCommitSigning) {
baseTools.push(
"mcp__github_file_ops__commit_files",
"mcp__github_file_ops__delete_files",
);
} else {
// When not using commit signing, add specific Bash git commands only
baseTools.push(
"Bash(git add:*)",
"Bash(git commit:*)",
"Bash(git push:*)",
"Bash(git status:*)",
"Bash(git diff:*)",
"Bash(git log:*)",
"Bash(git rm:*)",
"Bash(git config user.name:*)",
"Bash(git config user.email:*)",
);
}
// Add GitHub Actions MCP tools if enabled
if (includeActionsTools) {
baseTools.push(
"mcp__github_ci__get_ci_status",
"mcp__github_ci__get_workflow_run_details",
"mcp__github_ci__download_job_log",
);
}
let allAllowedTools = baseTools.join(","); let allAllowedTools = baseTools.join(",");
if (customAllowedTools) { if (customAllowedTools && customAllowedTools.length > 0) {
allAllowedTools = `${allAllowedTools},${customAllowedTools}`; allAllowedTools = `${allAllowedTools},${customAllowedTools.join(",")}`;
} }
return allAllowedTools; return allAllowedTools;
} }
export function buildDisallowedToolsString( export function buildDisallowedToolsString(
customDisallowedTools?: string, customDisallowedTools?: string[],
allowedTools?: string, allowedTools?: string[],
): string { ): string {
let disallowedTools = [...DISALLOWED_TOOLS]; let disallowedTools = [...DISALLOWED_TOOLS];
// If user has explicitly allowed some hardcoded disallowed tools, remove them from disallowed list // If user has explicitly allowed some hardcoded disallowed tools, remove them from disallowed list
if (allowedTools) { if (allowedTools && allowedTools.length > 0) {
const allowedToolsArray = allowedTools
.split(",")
.map((tool) => tool.trim());
disallowedTools = disallowedTools.filter( disallowedTools = disallowedTools.filter(
(tool) => !allowedToolsArray.includes(tool), (tool) => !allowedTools.includes(tool),
); );
} }
let allDisallowedTools = disallowedTools.join(","); let allDisallowedTools = disallowedTools.join(",");
if (customDisallowedTools) { if (customDisallowedTools && customDisallowedTools.length > 0) {
if (allDisallowedTools) { if (allDisallowedTools) {
allDisallowedTools = `${allDisallowedTools},${customDisallowedTools}`; allDisallowedTools = `${allDisallowedTools},${customDisallowedTools.join(",")}`;
} else { } else {
allDisallowedTools = customDisallowedTools; allDisallowedTools = customDisallowedTools.join(",");
} }
} }
return allDisallowedTools; return allDisallowedTools;
@@ -83,6 +115,7 @@ export function prepareContext(
const eventAction = context.eventAction; const eventAction = context.eventAction;
const triggerPhrase = context.inputs.triggerPhrase || "@claude"; const triggerPhrase = context.inputs.triggerPhrase || "@claude";
const assigneeTrigger = context.inputs.assigneeTrigger; const assigneeTrigger = context.inputs.assigneeTrigger;
const labelTrigger = context.inputs.labelTrigger;
const customInstructions = context.inputs.customInstructions; const customInstructions = context.inputs.customInstructions;
const allowedTools = context.inputs.allowedTools; const allowedTools = context.inputs.allowedTools;
const disallowedTools = context.inputs.disallowedTools; const disallowedTools = context.inputs.disallowedTools;
@@ -120,8 +153,10 @@ export function prepareContext(
triggerPhrase, triggerPhrase,
...(triggerUsername && { triggerUsername }), ...(triggerUsername && { triggerUsername }),
...(customInstructions && { customInstructions }), ...(customInstructions && { customInstructions }),
...(allowedTools && { allowedTools }), ...(allowedTools.length > 0 && { allowedTools: allowedTools.join(",") }),
...(disallowedTools && { disallowedTools }), ...(disallowedTools.length > 0 && {
disallowedTools: disallowedTools.join(","),
}),
...(directPrompt && { directPrompt }), ...(directPrompt && { directPrompt }),
...(claudeBranch && { claudeBranch }), ...(claudeBranch && { claudeBranch }),
}; };
@@ -242,7 +277,7 @@ export function prepareContext(
} }
if (eventAction === "assigned") { if (eventAction === "assigned") {
if (!assigneeTrigger) { if (!assigneeTrigger && !directPrompt) {
throw new Error( throw new Error(
"ASSIGNEE_TRIGGER is required for issue assigned event", "ASSIGNEE_TRIGGER is required for issue assigned event",
); );
@@ -254,7 +289,20 @@ export function prepareContext(
issueNumber, issueNumber,
baseBranch, baseBranch,
claudeBranch, claudeBranch,
assigneeTrigger, ...(assigneeTrigger && { assigneeTrigger }),
};
} else if (eventAction === "labeled") {
if (!labelTrigger) {
throw new Error("LABEL_TRIGGER is required for issue labeled event");
}
eventData = {
eventName: "issues",
eventAction: "labeled",
isPR: false,
issueNumber,
baseBranch,
claudeBranch,
labelTrigger,
}; };
} else if (eventAction === "opened") { } else if (eventAction === "opened") {
eventData = { eventData = {
@@ -328,10 +376,17 @@ export function getEventTypeAndContext(envVars: PreparedContext): {
eventType: "ISSUE_CREATED", eventType: "ISSUE_CREATED",
triggerContext: `new issue with '${envVars.triggerPhrase}' in body`, triggerContext: `new issue with '${envVars.triggerPhrase}' in body`,
}; };
} else if (eventData.eventAction === "labeled") {
return {
eventType: "ISSUE_LABELED",
triggerContext: `issue labeled with '${eventData.labelTrigger}'`,
};
} }
return { return {
eventType: "ISSUE_ASSIGNED", eventType: "ISSUE_ASSIGNED",
triggerContext: `issue assigned to '${eventData.assigneeTrigger}'`, triggerContext: eventData.assigneeTrigger
? `issue assigned to '${eventData.assigneeTrigger}'`
: `issue assigned event`,
}; };
case "pull_request": case "pull_request":
@@ -347,9 +402,68 @@ export function getEventTypeAndContext(envVars: PreparedContext): {
} }
} }
function getCommitInstructions(
eventData: EventData,
githubData: FetchDataResult,
context: PreparedContext,
useCommitSigning: boolean,
): string {
const coAuthorLine =
(githubData.triggerDisplayName ?? context.triggerUsername !== "Unknown")
? `Co-authored-by: ${githubData.triggerDisplayName ?? context.triggerUsername} <${context.triggerUsername}@users.noreply.github.com>`
: "";
if (useCommitSigning) {
if (eventData.isPR && !eventData.claudeBranch) {
return `
- 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: "${coAuthorLine}"`;
} else {
return `
- 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: "${coAuthorLine}"`;
}
} else {
// Non-signing instructions
if (eventData.isPR && !eventData.claudeBranch) {
return `
- Use git commands via the Bash tool to commit and push your changes:
- Stage files: Bash(git add <files>)
- Commit with a descriptive message: Bash(git commit -m "<message>")
${
coAuthorLine
? `- When committing and the trigger user is not "Unknown", include a Co-authored-by trailer:
Bash(git commit -m "<message>\\n\\n${coAuthorLine}")`
: ""
}
- Push to the remote: Bash(git push origin HEAD)`;
} else {
const branchName = eventData.claudeBranch || eventData.baseBranch;
return `
- You are already on the correct branch (${eventData.claudeBranch || "the PR branch"}). Do not create a new branch.
- Use git commands via the Bash tool to commit and push your changes:
- Stage files: Bash(git add <files>)
- Commit with a descriptive message: Bash(git commit -m "<message>")
${
coAuthorLine
? `- When committing and the trigger user is not "Unknown", include a Co-authored-by trailer:
Bash(git commit -m "<message>\\n\\n${coAuthorLine}")`
: ""
}
- Push to the remote: Bash(git push origin ${branchName})`;
}
}
}
export function generatePrompt( export function generatePrompt(
context: PreparedContext, context: PreparedContext,
githubData: FetchDataResult, githubData: FetchDataResult,
useCommitSigning: boolean,
): string { ): string {
const { const {
contextData, contextData,
@@ -418,6 +532,7 @@ ${
} }
<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_phrase>${context.triggerPhrase}</trigger_phrase> <trigger_phrase>${context.triggerPhrase}</trigger_phrase>
${ ${
(eventData.eventName === "issue_comment" || (eventData.eventName === "issue_comment" ||
@@ -437,9 +552,9 @@ ${sanitizeContent(context.directPrompt)}
: "" : ""
} }
${`<comment_tool_info> ${`<comment_tool_info>
IMPORTANT: You have been provided with the mcp__github_file_ops__update_claude_comment tool to update your comment. This tool automatically handles both issue and PR comments. IMPORTANT: You have been provided with the mcp__github_comment__update_claude_comment tool to update your comment. This tool automatically handles both issue and PR comments.
Tool usage example for mcp__github_file_ops__update_claude_comment: Tool usage example for mcp__github_comment__update_claude_comment:
{ {
"body": "Your comment text here" "body": "Your comment text here"
} }
@@ -458,12 +573,13 @@ Follow these steps:
1. Create a Todo List: 1. Create a Todo List:
- Use your GitHub comment to maintain a detailed task list based on the request. - Use your GitHub comment to maintain a detailed task list based on the request.
- Format todos as a checklist (- [ ] for incomplete, - [x] for complete). - Format todos as a checklist (- [ ] for incomplete, - [x] for complete).
- Update the comment using mcp__github_file_ops__update_claude_comment with each task completion. - Update the comment using mcp__github_comment__update_claude_comment with each task completion.
2. Gather Context: 2. Gather Context:
- Analyze the pre-fetched data provided above. - Analyze the pre-fetched data provided above.
- For ISSUE_CREATED: Read the issue body to find the request after the trigger phrase. - For ISSUE_CREATED: Read the issue body to find the request after the trigger phrase.
- For ISSUE_ASSIGNED: Read the entire issue body to understand the task. - For ISSUE_ASSIGNED: Read the entire issue body to understand the task.
- For ISSUE_LABELED: Read the entire issue body to understand the task.
${eventData.eventName === "issue_comment" || eventData.eventName === "pull_request_review_comment" || eventData.eventName === "pull_request_review" ? ` - For comment/review events: Your instructions are in the <trigger_comment> tag above.` : ""} ${eventData.eventName === "issue_comment" || eventData.eventName === "pull_request_review_comment" || eventData.eventName === "pull_request_review" ? ` - For comment/review events: Your instructions are in the <trigger_comment> tag above.` : ""}
${context.directPrompt ? ` - DIRECT INSTRUCTION: A direct instruction was provided and is shown in the <direct_prompt> tag above. This is not from any GitHub comment but a direct instruction to execute.` : ""} ${context.directPrompt ? ` - DIRECT INSTRUCTION: A direct instruction was provided and is shown in the <direct_prompt> tag above. This is not from any GitHub comment but a direct instruction to execute.` : ""}
- IMPORTANT: Only the comment/issue containing '${context.triggerPhrase}' has your instructions. - IMPORTANT: Only the comment/issue containing '${context.triggerPhrase}' has your instructions.
@@ -488,27 +604,16 @@ ${context.directPrompt ? ` - DIRECT INSTRUCTION: A direct instruction was prov
- Look for bugs, security issues, performance problems, and other issues - Look for bugs, security issues, performance problems, and other issues
- Suggest improvements for readability and maintainability - Suggest improvements for readability and maintainability
- Check for best practices and coding standards - Check for best practices and coding standards
- Reference specific code sections with file paths and line numbers${eventData.isPR ? "\n - AFTER reading files and analyzing code, you MUST call mcp__github_file_ops__update_claude_comment to post your review" : ""} - Reference specific code sections with file paths and line numbers${eventData.isPR ? `\n - AFTER reading files and analyzing code, you MUST call mcp__github_comment__update_claude_comment to post your review` : ""}
- Formulate a concise, technical, and helpful response based on the context. - Formulate a concise, technical, and helpful response based on the context.
- Reference specific code with inline formatting or code blocks. - Reference specific code with inline formatting or code blocks.
- Include relevant file paths and line numbers when applicable. - Include relevant file paths and line numbers when applicable.
- ${eventData.isPR ? "IMPORTANT: Submit your review feedback by updating the Claude comment using mcp__github_file_ops__update_claude_comment. This will be displayed as your PR review." : "Remember that this feedback must be posted to the GitHub comment using mcp__github_file_ops__update_claude_comment."} - ${eventData.isPR ? `IMPORTANT: Submit your review feedback by updating the Claude comment using mcp__github_comment__update_claude_comment. This will be displayed as your PR review.` : `Remember that this feedback must be posted to the GitHub comment using mcp__github_comment__update_claude_comment.`}
B. For Straightforward Changes: B. For Straightforward Changes:
- Use file system tools to make the change locally. - Use file system tools to make the change locally.
- If you discover related tasks (e.g., updating tests), add them to the todo list. - If you discover related tasks (e.g., updating tests), add them to the todo list.
- Mark each subtask as completed as you progress. - Mark each subtask as completed as you progress.${getCommitInstructions(eventData, githubData, context, useCommitSigning)}
${
eventData.isPR && !eventData.claudeBranch
? `
- 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 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 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 eventData.claudeBranch
? `- Provide a URL to create a PR manually in this format: ? `- Provide a URL to create a PR manually in this format:
@@ -526,7 +631,6 @@ ${context.directPrompt ? ` - DIRECT INSTRUCTION: A direct instruction was prov
- The signature: "Generated with [Claude Code](https://claude.ai/code)" - The signature: "Generated with [Claude Code](https://claude.ai/code)"
- Just include the markdown link with text "Create a PR" - do not add explanatory text before it like "You can create a PR using this link"` - Just include the markdown link with text "Create a PR" - do not add explanatory text before it like "You can create a PR using this link"`
: "" : ""
}`
} }
C. For Complex Changes: C. For Complex Changes:
@@ -542,20 +646,31 @@ ${context.directPrompt ? ` - DIRECT INSTRUCTION: A direct instruction was prov
- Always update the GitHub comment to reflect the current todo state. - Always update the GitHub comment to reflect the current todo state.
- When all todos are completed, remove the spinner and add a brief summary of what was accomplished, and what was not done. - When all todos are completed, remove the spinner and add a brief summary of what was accomplished, and what was not done.
- Note: If you see previous Claude comments with headers like "**Claude finished @user's task**" followed by "---", do not include this in your comment. The system adds this automatically. - Note: If you see previous Claude comments with headers like "**Claude finished @user's task**" followed by "---", do not include this in your comment. The system adds this automatically.
- If you changed any files locally, you must update them in the remote branch via mcp__github_file_ops__commit_files before saying that you're done. - If you changed any files locally, you must update them in the remote branch via ${useCommitSigning ? "mcp__github_file_ops__commit_files" : "git commands (add, commit, push)"} before saying that you're done.
${eventData.claudeBranch ? `- If you created anything in your branch, your comment must include the PR URL with prefilled title and body mentioned above.` : ""} ${eventData.claudeBranch ? `- If you created anything in your branch, your comment must include the PR URL with prefilled title and body mentioned above.` : ""}
Important Notes: Important Notes:
- All communication must happen through GitHub PR comments. - All communication must happen through GitHub PR comments.
- Never create new comments. Only update the existing comment using mcp__github_file_ops__update_claude_comment. - Never create new comments. Only update the existing comment using mcp__github_comment__update_claude_comment.
- This includes ALL responses: code reviews, answers to questions, progress updates, and final results.${eventData.isPR ? "\n- PR CRITICAL: After reading files and forming your response, you MUST post it by calling mcp__github_file_ops__update_claude_comment. Do NOT just respond with a normal response, the user will not see it." : ""} - This includes ALL responses: code reviews, answers to questions, progress updates, and final results.${eventData.isPR ? `\n- PR CRITICAL: After reading files and forming your response, you MUST post it by calling mcp__github_comment__update_claude_comment. Do NOT just respond with a normal response, the user will not see it.` : ""}
- You communicate exclusively by editing your single comment - not through any other means. - You communicate exclusively by editing your single comment - not through any other means.
- Use this spinner HTML when work is in progress: <img src="https://github.com/user-attachments/assets/5ac382c7-e004-429b-8e35-7feb3e8f9c6f" width="14px" height="14px" style="vertical-align: middle; margin-left: 4px;" /> - Use this spinner HTML when work is in progress: <img src="https://github.com/user-attachments/assets/5ac382c7-e004-429b-8e35-7feb3e8f9c6f" width="14px" height="14px" style="vertical-align: middle; margin-left: 4px;" />
${eventData.isPR && !eventData.claudeBranch ? `- Always push to the existing branch when triggered on a PR.` : `- IMPORTANT: You are already on the correct branch (${eventData.claudeBranch || "the created branch"}). Never create new branches when triggered on issues or closed/merged PRs.`} ${eventData.isPR && !eventData.claudeBranch ? `- Always push to the existing branch when triggered on a PR.` : `- IMPORTANT: You are already on the correct branch (${eventData.claudeBranch || "the created branch"}). Never create new branches when triggered on issues or closed/merged PRs.`}
- Use mcp__github_file_ops__commit_files for making commits (works for both new and existing files, single or multiple). Use mcp__github_file_ops__delete_files for deleting files (supports deleting single or multiple files atomically), or mcp__github__delete_file for deleting a single file. Edit files locally, and the tool will read the content from the same path on disk. ${
useCommitSigning
? `- Use mcp__github_file_ops__commit_files for making commits (works for both new and existing files, single or multiple). Use mcp__github_file_ops__delete_files for deleting files (supports deleting single or multiple files atomically), or mcp__github__delete_file for deleting a single file. Edit files locally, and the tool will read the content from the same path on disk.
Tool usage examples: Tool usage examples:
- mcp__github_file_ops__commit_files: {"files": ["path/to/file1.js", "path/to/file2.py"], "message": "feat: add new feature"} - mcp__github_file_ops__commit_files: {"files": ["path/to/file1.js", "path/to/file2.py"], "message": "feat: add new feature"}
- mcp__github_file_ops__delete_files: {"files": ["path/to/old.js"], "message": "chore: remove deprecated file"} - mcp__github_file_ops__delete_files: {"files": ["path/to/old.js"], "message": "chore: remove deprecated file"}`
: `- Use git commands via the Bash tool for version control (you have access to specific git commands only):
- Stage files: Bash(git add <files>)
- Commit changes: Bash(git commit -m "<message>")
- Push to remote: Bash(git push origin <branch>) (NEVER force push)
- Delete files: Bash(git rm <files>) followed by commit and push
- Check status: Bash(git status)
- View diff: Bash(git diff)
- Configure git user: Bash(git config user.name "...") and Bash(git config user.email "...")`
}
- Display the todo list as a checklist in the GitHub comment and mark things off as you go. - Display the todo list as a checklist in the GitHub comment and mark things off as you go.
- REPOSITORY SETUP INSTRUCTIONS: The repository's CLAUDE.md file(s) contain critical repo-specific setup instructions, development guidelines, and preferences. Always read and follow these files, particularly the root CLAUDE.md, as they provide essential context for working with the codebase effectively. - REPOSITORY SETUP INSTRUCTIONS: The repository's CLAUDE.md file(s) contain critical repo-specific setup instructions, development guidelines, and preferences. Always read and follow these files, particularly the root CLAUDE.md, as they provide essential context for working with the codebase effectively.
- Use h3 headers (###) for section titles in your comments, not h1 headers (#). - Use h3 headers (###) for section titles in your comments, not h1 headers (#).
@@ -621,10 +736,16 @@ export async function createPrompt(
claudeBranch, claudeBranch,
); );
await mkdir("/tmp/claude-prompts", { recursive: true }); await mkdir(`${process.env.RUNNER_TEMP}/claude-prompts`, {
recursive: true,
});
// Generate the prompt // Generate the prompt
const promptContent = generatePrompt(preparedContext, githubData); const promptContent = generatePrompt(
preparedContext,
githubData,
context.inputs.useCommitSigning,
);
// Log the final prompt to console // Log the final prompt to console
console.log("===== FINAL PROMPT ====="); console.log("===== FINAL PROMPT =====");
@@ -632,15 +753,23 @@ export async function createPrompt(
console.log("======================="); console.log("=======================");
// Write the prompt file // Write the prompt file
await writeFile("/tmp/claude-prompts/claude-prompt.txt", promptContent); await writeFile(
`${process.env.RUNNER_TEMP}/claude-prompts/claude-prompt.txt`,
promptContent,
);
// Set allowed tools // Set allowed tools
const hasActionsReadPermission =
context.inputs.additionalPermissions.get("actions") === "read" &&
context.isPR;
const allAllowedTools = buildAllowedToolsString( const allAllowedTools = buildAllowedToolsString(
preparedContext.allowedTools, context.inputs.allowedTools,
hasActionsReadPermission,
context.inputs.useCommitSigning,
); );
const allDisallowedTools = buildDisallowedToolsString( const allDisallowedTools = buildDisallowedToolsString(
preparedContext.disallowedTools, context.inputs.disallowedTools,
preparedContext.allowedTools, context.inputs.allowedTools,
); );
core.exportVariable("ALLOWED_TOOLS", allAllowedTools); core.exportVariable("ALLOWED_TOOLS", allAllowedTools);

View File

@@ -65,7 +65,17 @@ type IssueAssignedEvent = {
issueNumber: string; issueNumber: string;
baseBranch: string; baseBranch: string;
claudeBranch: string; claudeBranch: string;
assigneeTrigger: string; assigneeTrigger?: string;
};
type IssueLabeledEvent = {
eventName: "issues";
eventAction: "labeled";
isPR: false;
issueNumber: string;
baseBranch: string;
claudeBranch: string;
labelTrigger: string;
}; };
type PullRequestEvent = { type PullRequestEvent = {
@@ -85,6 +95,7 @@ export type EventData =
| IssueCommentEvent | IssueCommentEvent
| IssueOpenedEvent | IssueOpenedEvent
| IssueAssignedEvent | IssueAssignedEvent
| IssueLabeledEvent
| PullRequestEvent; | PullRequestEvent;
// Combined type with separate eventData field // Combined type with separate eventData field

461
src/entrypoints/format-turns.ts Executable file
View File

@@ -0,0 +1,461 @@
#!/usr/bin/env bun
import { readFileSync, existsSync } from "fs";
import { exit } from "process";
export interface ToolUse {
type: string;
name?: string;
input?: Record<string, any>;
id?: string;
}
export interface ToolResult {
type: string;
tool_use_id?: string;
content?: any;
is_error?: boolean;
}
export interface ContentItem {
type: string;
text?: string;
tool_use_id?: string;
content?: any;
is_error?: boolean;
name?: string;
input?: Record<string, any>;
id?: string;
}
export interface Message {
content: ContentItem[];
usage?: {
input_tokens?: number;
output_tokens?: number;
};
}
export interface Turn {
type: string;
subtype?: string;
message?: Message;
tools?: any[];
cost_usd?: number;
duration_ms?: number;
result?: string;
}
export interface GroupedContent {
type: string;
tools_count?: number;
data?: Turn;
text_parts?: string[];
tool_calls?: { tool_use: ToolUse; tool_result?: ToolResult }[];
usage?: Record<string, number>;
}
export function detectContentType(content: any): string {
const contentStr = String(content).trim();
// Check for JSON
if (contentStr.startsWith("{") && contentStr.endsWith("}")) {
try {
JSON.parse(contentStr);
return "json";
} catch {
// Fall through
}
}
if (contentStr.startsWith("[") && contentStr.endsWith("]")) {
try {
JSON.parse(contentStr);
return "json";
} catch {
// Fall through
}
}
// Check for code-like content
const codeKeywords = [
"def ",
"class ",
"import ",
"from ",
"function ",
"const ",
"let ",
"var ",
];
if (codeKeywords.some((keyword) => contentStr.includes(keyword))) {
if (
contentStr.includes("def ") ||
contentStr.includes("import ") ||
contentStr.includes("from ")
) {
return "python";
} else if (
["function ", "const ", "let ", "var ", "=>"].some((js) =>
contentStr.includes(js),
)
) {
return "javascript";
} else {
return "python"; // default for code
}
}
// Check for shell/bash output
const shellIndicators = ["ls -", "cd ", "mkdir ", "rm ", "$ ", "# "];
if (
contentStr.startsWith("/") ||
contentStr.includes("Error:") ||
contentStr.startsWith("total ") ||
shellIndicators.some((indicator) => contentStr.includes(indicator))
) {
return "bash";
}
// Check for diff format
if (
contentStr.startsWith("@@") ||
contentStr.includes("+++ ") ||
contentStr.includes("--- ")
) {
return "diff";
}
// Check for HTML/XML
if (contentStr.startsWith("<") && contentStr.endsWith(">")) {
return "html";
}
// Check for markdown
const mdIndicators = ["# ", "## ", "### ", "- ", "* ", "```"];
if (mdIndicators.some((indicator) => contentStr.includes(indicator))) {
return "markdown";
}
// Default to plain text
return "text";
}
export function formatResultContent(content: any): string {
if (!content) {
return "*(No output)*\n\n";
}
let contentStr: string;
// Check if content is a list with "type": "text" structure
try {
let parsedContent: any;
if (typeof content === "string") {
parsedContent = JSON.parse(content);
} else {
parsedContent = content;
}
if (
Array.isArray(parsedContent) &&
parsedContent.length > 0 &&
typeof parsedContent[0] === "object" &&
parsedContent[0]?.type === "text"
) {
// Extract the text field from the first item
contentStr = parsedContent[0]?.text || "";
} else {
contentStr = String(content).trim();
}
} catch {
contentStr = String(content).trim();
}
// Truncate very long results
if (contentStr.length > 3000) {
contentStr = contentStr.substring(0, 2997) + "...";
}
// Detect content type
const contentType = detectContentType(contentStr);
// Handle JSON content specially - pretty print it
if (contentType === "json") {
try {
// Try to parse and pretty print JSON
const parsed = JSON.parse(contentStr);
contentStr = JSON.stringify(parsed, null, 2);
} catch {
// Keep original if parsing fails
}
}
// Format with appropriate syntax highlighting
if (
contentType === "text" &&
contentStr.length < 100 &&
!contentStr.includes("\n")
) {
// Short text results don't need code blocks
return `**→** ${contentStr}\n\n`;
} else {
return `**Result:**\n\`\`\`${contentType}\n${contentStr}\n\`\`\`\n\n`;
}
}
export function formatToolWithResult(
toolUse: ToolUse,
toolResult?: ToolResult,
): string {
const toolName = toolUse.name || "unknown_tool";
const toolInput = toolUse.input || {};
let result = `### 🔧 \`${toolName}\`\n\n`;
// Add parameters if they exist and are not empty
if (Object.keys(toolInput).length > 0) {
result += "**Parameters:**\n```json\n";
result += JSON.stringify(toolInput, null, 2);
result += "\n```\n\n";
}
// Add result if available
if (toolResult) {
const content = toolResult.content || "";
const isError = toolResult.is_error || false;
if (isError) {
result += `❌ **Error:** \`${content}\`\n\n`;
} else {
result += formatResultContent(content);
}
}
return result;
}
export function groupTurnsNaturally(data: Turn[]): GroupedContent[] {
const groupedContent: GroupedContent[] = [];
const toolResultsMap = new Map<string, ToolResult>();
// First pass: collect all tool results by tool_use_id
for (const turn of data) {
if (turn.type === "user") {
const content = turn.message?.content || [];
for (const item of content) {
if (item.type === "tool_result" && item.tool_use_id) {
toolResultsMap.set(item.tool_use_id, {
type: item.type,
tool_use_id: item.tool_use_id,
content: item.content,
is_error: item.is_error,
});
}
}
}
}
// Second pass: process turns and group naturally
for (const turn of data) {
const turnType = turn.type || "unknown";
if (turnType === "system") {
const subtype = turn.subtype || "";
if (subtype === "init") {
const tools = turn.tools || [];
groupedContent.push({
type: "system_init",
tools_count: tools.length,
});
} else {
groupedContent.push({
type: "system_other",
data: turn,
});
}
} else if (turnType === "assistant") {
const message = turn.message || { content: [] };
const content = message.content || [];
const usage = message.usage || {};
// Process content items
const textParts: string[] = [];
const toolCalls: { tool_use: ToolUse; tool_result?: ToolResult }[] = [];
for (const item of content) {
const itemType = item.type || "";
if (itemType === "text") {
textParts.push(item.text || "");
} else if (itemType === "tool_use") {
const toolUseId = item.id;
const toolResult = toolUseId
? toolResultsMap.get(toolUseId)
: undefined;
toolCalls.push({
tool_use: {
type: item.type,
name: item.name,
input: item.input,
id: item.id,
},
tool_result: toolResult,
});
}
}
if (textParts.length > 0 || toolCalls.length > 0) {
groupedContent.push({
type: "assistant_action",
text_parts: textParts,
tool_calls: toolCalls,
usage: usage,
});
}
} else if (turnType === "user") {
// Handle user messages that aren't tool results
const message = turn.message || { content: [] };
const content = message.content || [];
const textParts: string[] = [];
for (const item of content) {
if (item.type === "text") {
textParts.push(item.text || "");
}
}
if (textParts.length > 0) {
groupedContent.push({
type: "user_message",
text_parts: textParts,
});
}
} else if (turnType === "result") {
groupedContent.push({
type: "final_result",
data: turn,
});
}
}
return groupedContent;
}
export function formatGroupedContent(groupedContent: GroupedContent[]): string {
let markdown = "## Claude Code Report\n\n";
for (const item of groupedContent) {
const itemType = item.type;
if (itemType === "system_init") {
markdown += `## 🚀 System Initialization\n\n**Available Tools:** ${item.tools_count} tools loaded\n\n---\n\n`;
} else if (itemType === "system_other") {
markdown += `## ⚙️ System Message\n\n${JSON.stringify(item.data, null, 2)}\n\n---\n\n`;
} else if (itemType === "assistant_action") {
// Add text content first (if any) - no header needed
for (const text of item.text_parts || []) {
if (text.trim()) {
markdown += `${text}\n\n`;
}
}
// Add tool calls with their results
for (const toolCall of item.tool_calls || []) {
markdown += formatToolWithResult(
toolCall.tool_use,
toolCall.tool_result,
);
}
// Add usage info if available
const usage = item.usage || {};
if (Object.keys(usage).length > 0) {
const inputTokens = usage.input_tokens || 0;
const outputTokens = usage.output_tokens || 0;
markdown += `*Token usage: ${inputTokens} input, ${outputTokens} output*\n\n`;
}
// Only add separator if this section had content
if (
(item.text_parts && item.text_parts.length > 0) ||
(item.tool_calls && item.tool_calls.length > 0)
) {
markdown += "---\n\n";
}
} else if (itemType === "user_message") {
markdown += "## 👤 User\n\n";
for (const text of item.text_parts || []) {
if (text.trim()) {
markdown += `${text}\n\n`;
}
}
markdown += "---\n\n";
} else if (itemType === "final_result") {
const data = item.data || {};
const cost = (data as any).cost_usd || 0;
const duration = (data as any).duration_ms || 0;
const resultText = (data as any).result || "";
markdown += "## ✅ Final Result\n\n";
if (resultText) {
markdown += `${resultText}\n\n`;
}
markdown += `**Cost:** $${cost.toFixed(4)} | **Duration:** ${(duration / 1000).toFixed(1)}s\n\n`;
}
}
return markdown;
}
export function formatTurnsFromData(data: Turn[]): string {
// Group turns naturally
const groupedContent = groupTurnsNaturally(data);
// Generate markdown
const markdown = formatGroupedContent(groupedContent);
return markdown;
}
function main(): void {
// Get the JSON file path from command line arguments
const args = process.argv.slice(2);
if (args.length === 0) {
console.error("Usage: format-turns.ts <json-file>");
exit(1);
}
const jsonFile = args[0];
if (!jsonFile) {
console.error("Error: No JSON file provided");
exit(1);
}
if (!existsSync(jsonFile)) {
console.error(`Error: ${jsonFile} not found`);
exit(1);
}
try {
// Read the JSON file
const fileContent = readFileSync(jsonFile, "utf-8");
const data: Turn[] = JSON.parse(fileContent);
// Group turns naturally
const groupedContent = groupTurnsNaturally(data);
// Generate markdown
const markdown = formatGroupedContent(groupedContent);
// Print to stdout (so it can be captured by shell)
console.log(markdown);
} catch (error) {
console.error(`Error processing file: ${error}`);
exit(1);
}
}
if (import.meta.main) {
main();
}

View File

@@ -12,7 +12,7 @@ import { checkHumanActor } from "../github/validation/actor";
import { checkWritePermissions } from "../github/validation/permissions"; import { checkWritePermissions } from "../github/validation/permissions";
import { createInitialComment } from "../github/operations/comments/create-initial"; import { createInitialComment } from "../github/operations/comments/create-initial";
import { setupBranch } from "../github/operations/branch"; import { setupBranch } from "../github/operations/branch";
import { updateTrackingComment } from "../github/operations/comments/update-with-branch"; import { configureGitAuth } from "../github/operations/git-config";
import { prepareMcpConfig } from "../mcp/install-mcp-server"; import { prepareMcpConfig } from "../mcp/install-mcp-server";
import { createPrompt } from "../create-prompt"; import { createPrompt } from "../create-prompt";
import { createOctokit } from "../github/api/client"; import { createOctokit } from "../github/api/client";
@@ -51,7 +51,8 @@ async function run() {
await checkHumanActor(octokit.rest, context); await checkHumanActor(octokit.rest, context);
// Step 6: Create initial tracking comment // Step 6: Create initial tracking comment
const commentId = await createInitialComment(octokit.rest, context); const commentData = await createInitialComment(octokit.rest, context);
const commentId = commentData.id;
// Step 7: Fetch GitHub data (once for both branch setup and prompt creation) // Step 7: Fetch GitHub data (once for both branch setup and prompt creation)
const githubData = await fetchGitHubData({ const githubData = await fetchGitHubData({
@@ -59,19 +60,20 @@ async function run() {
repository: `${context.repository.owner}/${context.repository.repo}`, repository: `${context.repository.owner}/${context.repository.repo}`,
prNumber: context.entityNumber.toString(), prNumber: context.entityNumber.toString(),
isPR: context.isPR, isPR: context.isPR,
triggerUsername: context.actor,
}); });
// Step 8: Setup branch // Step 8: Setup branch
const branchInfo = await setupBranch(octokit, githubData, context); const branchInfo = await setupBranch(octokit, githubData, context);
// Step 9: Update initial comment with branch link (only for issues that created a new branch) // Step 9: Configure git authentication if not using commit signing
if (branchInfo.claudeBranch) { if (!context.inputs.useCommitSigning) {
await updateTrackingComment( try {
octokit, await configureGitAuth(githubToken, context, commentData.user);
context, } catch (error) {
commentId, console.error("Failed to configure git authentication:", error);
branchInfo.claudeBranch, throw error;
); }
} }
// Step 10: Create prompt file // Step 10: Create prompt file
@@ -89,9 +91,12 @@ async function run() {
githubToken, githubToken,
owner: context.repository.owner, owner: context.repository.owner,
repo: context.repository.repo, repo: context.repository.repo,
branch: branchInfo.currentBranch, branch: branchInfo.claudeBranch || branchInfo.currentBranch,
baseBranch: branchInfo.baseBranch,
additionalMcpConfig, additionalMcpConfig,
claudeCommentId: commentId.toString(), claudeCommentId: commentId.toString(),
allowedTools: context.inputs.allowedTools,
context,
}); });
core.setOutput("mcp_config", mcpConfig); core.setOutput("mcp_config", mcpConfig);
} catch (error) { } catch (error) {

View File

@@ -11,7 +11,7 @@ import {
isPullRequestReviewCommentEvent, isPullRequestReviewCommentEvent,
} from "../github/context"; } from "../github/context";
import { GITHUB_SERVER_URL } from "../github/api/config"; import { GITHUB_SERVER_URL } from "../github/api/config";
import { checkAndDeleteEmptyBranch } from "../github/operations/branch-cleanup"; import { checkAndCommitOrDeleteBranch } from "../github/operations/branch-cleanup";
import { updateClaudeComment } from "../github/operations/comments/update-claude-comment"; import { updateClaudeComment } from "../github/operations/comments/update-claude-comment";
async function run() { async function run() {
@@ -88,13 +88,16 @@ async function run() {
const currentBody = comment.body ?? ""; const currentBody = comment.body ?? "";
// Check if we need to add branch link for new branches // Check if we need to add branch link for new branches
const { shouldDeleteBranch, branchLink } = await checkAndDeleteEmptyBranch( const useCommitSigning = process.env.USE_COMMIT_SIGNING === "true";
octokit, const { shouldDeleteBranch, branchLink } =
owner, await checkAndCommitOrDeleteBranch(
repo, octokit,
claudeBranch, owner,
baseBranch, repo,
); claudeBranch,
baseBranch,
useCommitSigning,
);
// Check if we need to add PR URL when we have a new branch // Check if we need to add PR URL when we have a new branch
let prLink = ""; let prLink = "";
@@ -198,7 +201,7 @@ async function run() {
jobUrl, jobUrl,
branchLink, branchLink,
prLink, prLink,
branchName: shouldDeleteBranch ? undefined : claudeBranch, branchName: shouldDeleteBranch || !branchLink ? undefined : claudeBranch,
triggerUsername, triggerUsername,
errorDetails, errorDetails,
}; };

View File

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

View File

@@ -1,6 +1,7 @@
import * as github from "@actions/github"; import * as github from "@actions/github";
import type { import type {
IssuesEvent, IssuesEvent,
IssuesAssignedEvent,
IssueCommentEvent, IssueCommentEvent,
PullRequestEvent, PullRequestEvent,
PullRequestReviewEvent, PullRequestReviewEvent,
@@ -28,11 +29,16 @@ export type ParsedGitHubContext = {
inputs: { inputs: {
triggerPhrase: string; triggerPhrase: string;
assigneeTrigger: string; assigneeTrigger: string;
allowedTools: string; labelTrigger: string;
disallowedTools: string; allowedTools: string[];
disallowedTools: string[];
customInstructions: string; customInstructions: string;
directPrompt: string; directPrompt: string;
baseBranch?: string; baseBranch?: string;
branchPrefix: string;
useStickyComment: boolean;
additionalPermissions: Map<string, string>;
useCommitSigning: boolean;
}; };
}; };
@@ -52,11 +58,18 @@ export function parseGitHubContext(): ParsedGitHubContext {
inputs: { inputs: {
triggerPhrase: process.env.TRIGGER_PHRASE ?? "@claude", triggerPhrase: process.env.TRIGGER_PHRASE ?? "@claude",
assigneeTrigger: process.env.ASSIGNEE_TRIGGER ?? "", assigneeTrigger: process.env.ASSIGNEE_TRIGGER ?? "",
allowedTools: process.env.ALLOWED_TOOLS ?? "", labelTrigger: process.env.LABEL_TRIGGER ?? "",
disallowedTools: process.env.DISALLOWED_TOOLS ?? "", allowedTools: parseMultilineInput(process.env.ALLOWED_TOOLS ?? ""),
disallowedTools: parseMultilineInput(process.env.DISALLOWED_TOOLS ?? ""),
customInstructions: process.env.CUSTOM_INSTRUCTIONS ?? "", customInstructions: process.env.CUSTOM_INSTRUCTIONS ?? "",
directPrompt: process.env.DIRECT_PROMPT ?? "", directPrompt: process.env.DIRECT_PROMPT ?? "",
baseBranch: process.env.BASE_BRANCH, baseBranch: process.env.BASE_BRANCH,
branchPrefix: process.env.BRANCH_PREFIX ?? "claude/",
useStickyComment: process.env.USE_STICKY_COMMENT === "true",
additionalPermissions: parseAdditionalPermissions(
process.env.ADDITIONAL_PERMISSIONS ?? "",
),
useCommitSigning: process.env.USE_COMMIT_SIGNING === "true",
}, },
}; };
@@ -110,6 +123,33 @@ 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 parseAdditionalPermissions(s: string): Map<string, string> {
const permissions = new Map<string, string>();
if (!s || !s.trim()) {
return permissions;
}
const lines = s.trim().split("\n");
for (const line of lines) {
const trimmedLine = line.trim();
if (trimmedLine) {
const [key, value] = trimmedLine.split(":").map((part) => part.trim());
if (key && value) {
permissions.set(key, value);
}
}
}
return permissions;
}
export function isIssuesEvent( export function isIssuesEvent(
context: ParsedGitHubContext, context: ParsedGitHubContext,
): context is ParsedGitHubContext & { payload: IssuesEvent } { ): context is ParsedGitHubContext & { payload: IssuesEvent } {
@@ -139,3 +179,9 @@ export function isPullRequestReviewCommentEvent(
): context is ParsedGitHubContext & { payload: PullRequestReviewCommentEvent } { ): context is ParsedGitHubContext & { payload: PullRequestReviewCommentEvent } {
return context.eventName === "pull_request_review_comment"; 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,23 +1,24 @@
import { execSync } from "child_process"; import { execSync } from "child_process";
import type { Octokits } from "../api/client";
import { ISSUE_QUERY, PR_QUERY, USER_QUERY } from "../api/queries/github";
import type { import type {
GitHubPullRequest,
GitHubIssue,
GitHubComment, GitHubComment,
GitHubFile, GitHubFile,
GitHubIssue,
GitHubPullRequest,
GitHubReview, GitHubReview,
PullRequestQueryResponse,
IssueQueryResponse, IssueQueryResponse,
PullRequestQueryResponse,
} from "../types"; } from "../types";
import { PR_QUERY, ISSUE_QUERY } from "../api/queries/github";
import type { Octokits } from "../api/client";
import { downloadCommentImages } from "../utils/image-downloader";
import type { CommentWithImages } from "../utils/image-downloader"; import type { CommentWithImages } from "../utils/image-downloader";
import { downloadCommentImages } from "../utils/image-downloader";
type FetchDataParams = { type FetchDataParams = {
octokits: Octokits; octokits: Octokits;
repository: string; repository: string;
prNumber: string; prNumber: string;
isPR: boolean; isPR: boolean;
triggerUsername?: string;
}; };
export type GitHubFileWithSHA = GitHubFile & { export type GitHubFileWithSHA = GitHubFile & {
@@ -31,6 +32,7 @@ export type FetchDataResult = {
changedFilesWithSHA: GitHubFileWithSHA[]; changedFilesWithSHA: GitHubFileWithSHA[];
reviewData: { nodes: GitHubReview[] } | null; reviewData: { nodes: GitHubReview[] } | null;
imageUrlMap: Map<string, string>; imageUrlMap: Map<string, string>;
triggerDisplayName?: string | null;
}; };
export async function fetchGitHubData({ export async function fetchGitHubData({
@@ -38,6 +40,7 @@ export async function fetchGitHubData({
repository, repository,
prNumber, prNumber,
isPR, isPR,
triggerUsername,
}: FetchDataParams): Promise<FetchDataResult> { }: FetchDataParams): Promise<FetchDataResult> {
const [owner, repo] = repository.split("/"); const [owner, repo] = repository.split("/");
if (!owner || !repo) { if (!owner || !repo) {
@@ -101,6 +104,14 @@ export async function fetchGitHubData({
let changedFilesWithSHA: GitHubFileWithSHA[] = []; let changedFilesWithSHA: GitHubFileWithSHA[] = [];
if (isPR && changedFiles.length > 0) { if (isPR && changedFiles.length > 0) {
changedFilesWithSHA = changedFiles.map((file) => { changedFilesWithSHA = changedFiles.map((file) => {
// Don't compute SHA for deleted files
if (file.changeType === "DELETED") {
return {
...file,
sha: "deleted",
};
}
try { try {
// Use git hash-object to compute the SHA for the current file content // Use git hash-object to compute the SHA for the current file content
const sha = execSync(`git hash-object "${file.path}"`, { const sha = execSync(`git hash-object "${file.path}"`, {
@@ -183,6 +194,12 @@ export async function fetchGitHubData({
allComments, allComments,
); );
// Fetch trigger user display name if username is provided
let triggerDisplayName: string | null | undefined;
if (triggerUsername) {
triggerDisplayName = await fetchUserDisplayName(octokits, triggerUsername);
}
return { return {
contextData, contextData,
comments, comments,
@@ -190,5 +207,27 @@ export async function fetchGitHubData({
changedFilesWithSHA, changedFilesWithSHA,
reviewData, reviewData,
imageUrlMap, 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

@@ -1,17 +1,44 @@
import type { Octokits } from "../api/client"; import type { Octokits } from "../api/client";
import { GITHUB_SERVER_URL } from "../api/config"; import { GITHUB_SERVER_URL } from "../api/config";
import { $ } from "bun";
export async function checkAndDeleteEmptyBranch( export async function checkAndCommitOrDeleteBranch(
octokit: Octokits, octokit: Octokits,
owner: string, owner: string,
repo: string, repo: string,
claudeBranch: string | undefined, claudeBranch: string | undefined,
baseBranch: string, baseBranch: string,
useCommitSigning: boolean,
): Promise<{ shouldDeleteBranch: boolean; branchLink: string }> { ): Promise<{ shouldDeleteBranch: boolean; branchLink: string }> {
let branchLink = ""; let branchLink = "";
let shouldDeleteBranch = false; let shouldDeleteBranch = false;
if (claudeBranch) { if (claudeBranch) {
// First check if the branch exists remotely
let branchExistsRemotely = false;
try {
await octokit.rest.repos.getBranch({
owner,
repo,
branch: claudeBranch,
});
branchExistsRemotely = true;
} catch (error: any) {
if (error.status === 404) {
console.log(`Branch ${claudeBranch} does not exist remotely`);
} else {
console.error("Error checking if branch exists:", error);
}
}
// Only proceed if branch exists remotely
if (!branchExistsRemotely) {
console.log(
`Branch ${claudeBranch} does not exist remotely, no branch link will be added`,
);
return { shouldDeleteBranch: false, branchLink: "" };
}
// Check if Claude made any commits to the branch // Check if Claude made any commits to the branch
try { try {
const { data: comparison } = const { data: comparison } =
@@ -21,20 +48,66 @@ export async function checkAndDeleteEmptyBranch(
basehead: `${baseBranch}...${claudeBranch}`, basehead: `${baseBranch}...${claudeBranch}`,
}); });
// If there are no commits, mark branch for deletion // If there are no commits, check for uncommitted changes if not using commit signing
if (comparison.total_commits === 0) { if (comparison.total_commits === 0) {
console.log( if (!useCommitSigning) {
`Branch ${claudeBranch} has no commits from Claude, will delete it`, console.log(
); `Branch ${claudeBranch} has no commits from Claude, checking for uncommitted changes...`,
shouldDeleteBranch = true; );
// Check for uncommitted changes using git status
try {
const gitStatus = await $`git status --porcelain`.quiet();
const hasUncommittedChanges =
gitStatus.stdout.toString().trim().length > 0;
if (hasUncommittedChanges) {
console.log("Found uncommitted changes, committing them...");
// Add all changes
await $`git add -A`;
// Commit with a descriptive message
const runId = process.env.GITHUB_RUN_ID || "unknown";
const commitMessage = `Auto-commit: Save uncommitted changes from Claude\n\nRun ID: ${runId}`;
await $`git commit -m ${commitMessage}`;
// Push the changes
await $`git push origin ${claudeBranch}`;
console.log(
"✅ Successfully committed and pushed uncommitted changes",
);
// Set branch link since we now have commits
const branchUrl = `${GITHUB_SERVER_URL}/${owner}/${repo}/tree/${claudeBranch}`;
branchLink = `\n[View branch](${branchUrl})`;
} else {
console.log(
"No uncommitted changes found, marking branch for deletion",
);
shouldDeleteBranch = true;
}
} catch (gitError) {
console.error("Error checking/committing changes:", gitError);
// If we can't check git status, assume the branch might have changes
const branchUrl = `${GITHUB_SERVER_URL}/${owner}/${repo}/tree/${claudeBranch}`;
branchLink = `\n[View branch](${branchUrl})`;
}
} else {
console.log(
`Branch ${claudeBranch} has no commits from Claude, will delete it`,
);
shouldDeleteBranch = true;
}
} else { } else {
// Only add branch link if there are commits // Only add branch link if there are commits
const branchUrl = `${GITHUB_SERVER_URL}/${owner}/${repo}/tree/${claudeBranch}`; const branchUrl = `${GITHUB_SERVER_URL}/${owner}/${repo}/tree/${claudeBranch}`;
branchLink = `\n[View branch](${branchUrl})`; branchLink = `\n[View branch](${branchUrl})`;
} }
} catch (error) { } catch (error) {
console.error("Error checking for commits on Claude branch:", error); console.error("Error comparing commits on Claude branch:", error);
// If we can't check, assume the branch has commits to be safe // If we can't compare but the branch exists remotely, include the branch link
const branchUrl = `${GITHUB_SERVER_URL}/${owner}/${repo}/tree/${claudeBranch}`; const branchUrl = `${GITHUB_SERVER_URL}/${owner}/${repo}/tree/${claudeBranch}`;
branchLink = `\n[View branch](${branchUrl})`; branchLink = `\n[View branch](${branchUrl})`;
} }

View File

@@ -26,7 +26,7 @@ export async function setupBranch(
): Promise<BranchInfo> { ): Promise<BranchInfo> {
const { owner, repo } = context.repository; const { owner, repo } = context.repository;
const entityNumber = context.entityNumber; const entityNumber = context.entityNumber;
const { baseBranch } = context.inputs; const { baseBranch, branchPrefix } = context.inputs;
const isPR = context.isPR; const isPR = context.isPR;
if (isPR) { if (isPR) {
@@ -45,9 +45,16 @@ export async function setupBranch(
const branchName = prData.headRefName; const branchName = prData.headRefName;
// Execute git commands to checkout PR branch (shallow fetch for performance) // Determine optimal fetch depth based on PR commit count, with a minimum of 20
// Fetch the branch with a depth of 20 to avoid fetching too much history, while still allowing for some context const commitCount = prData.commits.totalCount;
await $`git fetch origin --depth=20 ${branchName}`; 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}`;
await $`git checkout ${branchName}`; await $`git checkout ${branchName}`;
console.log(`Successfully checked out PR branch for PR #${entityNumber}`); console.log(`Successfully checked out PR branch for PR #${entityNumber}`);
@@ -77,23 +84,23 @@ export async function setupBranch(
sourceBranch = repoResponse.data.default_branch; sourceBranch = repoResponse.data.default_branch;
} }
// Creating a new branch for either an issue or closed/merged PR // Generate branch name for either an issue or closed/merged PR
const entityType = isPR ? "pr" : "issue"; const entityType = isPR ? "pr" : "issue";
console.log(
`Creating new branch for ${entityType} #${entityNumber} from source branch: ${sourceBranch}...`,
);
const timestamp = new Date() // Create Kubernetes-compatible timestamp: lowercase, hyphens only, shorter format
.toISOString() const now = new Date();
.replace(/[:-]/g, "") const timestamp = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, "0")}${String(now.getDate()).padStart(2, "0")}-${String(now.getHours()).padStart(2, "0")}${String(now.getMinutes()).padStart(2, "0")}`;
.replace(/\.\d{3}Z/, "")
.split("T")
.join("_");
const newBranch = `claude/${entityType}-${entityNumber}-${timestamp}`; // Ensure branch name is Kubernetes-compatible:
// - Lowercase only
// - Alphanumeric with hyphens
// - No underscores
// - Max 50 chars (to allow for prefixes)
const branchName = `${branchPrefix}${entityType}-${entityNumber}-${timestamp}`;
const newBranch = branchName.toLowerCase().substring(0, 50);
try { try {
// Get the SHA of the source branch // Get the SHA of the source branch to verify it exists
const sourceBranchRef = await octokits.rest.git.getRef({ const sourceBranchRef = await octokits.rest.git.getRef({
owner, owner,
repo, repo,
@@ -101,23 +108,34 @@ export async function setupBranch(
}); });
const currentSHA = sourceBranchRef.data.object.sha; const currentSHA = sourceBranchRef.data.object.sha;
console.log(`Source branch SHA: ${currentSHA}`);
console.log(`Current SHA: ${currentSHA}`); // For commit signing, defer branch creation to the file ops server
if (context.inputs.useCommitSigning) {
console.log(
`Branch name generated: ${newBranch} (will be created by file ops server on first commit)`,
);
// Create branch using GitHub API // Set outputs for GitHub Actions
await octokits.rest.git.createRef({ core.setOutput("CLAUDE_BRANCH", newBranch);
owner, core.setOutput("BASE_BRANCH", sourceBranch);
repo, return {
ref: `refs/heads/${newBranch}`, baseBranch: sourceBranch,
sha: currentSHA, claudeBranch: newBranch,
}); currentBranch: sourceBranch, // Stay on source branch for now
};
}
// Checkout the new branch (shallow fetch for performance) // For non-signing case, create and checkout the branch locally only
await $`git fetch origin --depth=1 ${newBranch}`; console.log(
await $`git checkout ${newBranch}`; `Creating local branch ${newBranch} for ${entityType} #${entityNumber} from source branch: ${sourceBranch}...`,
);
// Create and checkout the new branch locally
await $`git checkout -b ${newBranch}`;
console.log( console.log(
`Successfully created and checked out new branch: ${newBranch}`, `Successfully created and checked out local branch: ${newBranch}`,
); );
// Set outputs for GitHub Actions // Set outputs for GitHub Actions
@@ -129,7 +147,7 @@ export async function setupBranch(
currentBranch: newBranch, currentBranch: newBranch,
}; };
} catch (error) { } catch (error) {
console.error("Error creating branch:", error); console.error("Error in branch setup:", error);
process.exit(1); process.exit(1);
} }
} }

View File

@@ -9,10 +9,13 @@ import { appendFileSync } from "fs";
import { createJobRunLink, createCommentBody } from "./common"; import { createJobRunLink, createCommentBody } from "./common";
import { import {
isPullRequestReviewCommentEvent, isPullRequestReviewCommentEvent,
isPullRequestEvent,
type ParsedGitHubContext, type ParsedGitHubContext,
} from "../../context"; } from "../../context";
import type { Octokit } from "@octokit/rest"; import type { Octokit } from "@octokit/rest";
const CLAUDE_APP_BOT_ID = 209825114;
export async function createInitialComment( export async function createInitialComment(
octokit: Octokit, octokit: Octokit,
context: ParsedGitHubContext, context: ParsedGitHubContext,
@@ -25,8 +28,43 @@ export async function createInitialComment(
try { try {
let response; let response;
// Only use createReplyForReviewComment if it's a PR review comment AND we have a comment_id if (
if (isPullRequestReviewCommentEvent(context)) { context.inputs.useStickyComment &&
context.isPR &&
isPullRequestEvent(context)
) {
const comments = await octokit.rest.issues.listComments({
owner,
repo,
issue_number: context.entityNumber,
});
const existingComment = comments.data.find((comment) => {
const idMatch = comment.user?.id === CLAUDE_APP_BOT_ID;
const botNameMatch =
comment.user?.type === "Bot" &&
comment.user?.login.toLowerCase().includes("claude");
const bodyMatch = comment.body === initialBody;
return idMatch || botNameMatch || bodyMatch;
});
if (existingComment) {
response = await octokit.rest.issues.updateComment({
owner,
repo,
comment_id: existingComment.id,
body: initialBody,
});
} else {
// Create new comment if no existing one found
response = await octokit.rest.issues.createComment({
owner,
repo,
issue_number: context.entityNumber,
body: initialBody,
});
}
} else if (isPullRequestReviewCommentEvent(context)) {
// Only use createReplyForReviewComment if it's a PR review comment AND we have a comment_id
response = await octokit.rest.pulls.createReplyForReviewComment({ response = await octokit.rest.pulls.createReplyForReviewComment({
owner, owner,
repo, repo,
@@ -48,7 +86,7 @@ export async function createInitialComment(
const githubOutput = process.env.GITHUB_OUTPUT!; const githubOutput = process.env.GITHUB_OUTPUT!;
appendFileSync(githubOutput, `claude_comment_id=${response.data.id}\n`); appendFileSync(githubOutput, `claude_comment_id=${response.data.id}\n`);
console.log(`✅ Created initial comment with ID: ${response.data.id}`); console.log(`✅ Created initial comment with ID: ${response.data.id}`);
return response.data.id; return response.data;
} catch (error) { } catch (error) {
console.error("Error in initial comment:", error); console.error("Error in initial comment:", error);
@@ -64,7 +102,7 @@ export async function createInitialComment(
const githubOutput = process.env.GITHUB_OUTPUT!; const githubOutput = process.env.GITHUB_OUTPUT!;
appendFileSync(githubOutput, `claude_comment_id=${response.data.id}\n`); appendFileSync(githubOutput, `claude_comment_id=${response.data.id}\n`);
console.log(`✅ Created fallback comment with ID: ${response.data.id}`); console.log(`✅ Created fallback comment with ID: ${response.data.id}`);
return response.data.id; return response.data;
} catch (fallbackError) { } catch (fallbackError) {
console.error("Error creating fallback comment:", fallbackError); console.error("Error creating fallback comment:", fallbackError);
throw fallbackError; throw fallbackError;

View File

@@ -0,0 +1,56 @@
#!/usr/bin/env bun
/**
* Configure git authentication for non-signing mode
* Sets up git user and authentication to work with GitHub App tokens
*/
import { $ } from "bun";
import type { ParsedGitHubContext } from "../context";
import { GITHUB_SERVER_URL } from "../api/config";
type GitUser = {
login: string;
id: number;
};
export async function configureGitAuth(
githubToken: string,
context: ParsedGitHubContext,
user: GitUser | null,
) {
console.log("Configuring git authentication for non-signing mode");
// Configure git user based on the comment creator
console.log("Configuring git user...");
if (user) {
const botName = user.login;
const botId = user.id;
console.log(`Setting git user as ${botName}...`);
await $`git config user.name "${botName}"`;
await $`git config user.email "${botId}+${botName}@users.noreply.github.com"`;
console.log(`✓ Set git user as ${botName}`);
} else {
console.log("No user data in comment, using default bot user");
await $`git config user.name "github-actions[bot]"`;
await $`git config user.email "41898282+github-actions[bot]@users.noreply.github.com"`;
}
// Remove the authorization header that actions/checkout sets
console.log("Removing existing git authentication headers...");
try {
await $`git config --unset-all http.${GITHUB_SERVER_URL}/.extraheader`;
console.log("✓ Removed existing authentication headers");
} catch (e) {
console.log("No existing authentication headers to remove");
}
// Update the remote URL to include the token for authentication
console.log("Updating remote URL with authentication...");
const serverUrl = new URL(GITHUB_SERVER_URL);
const remoteUrl = `https://x-access-token:${githubToken}@${serverUrl.host}/${context.repository.owner}/${context.repository.repo}.git`;
await $`git remote set-url origin ${remoteUrl}`;
console.log("✓ Updated remote URL with authentication token");
console.log("Git authentication configured successfully");
}

View File

@@ -1,47 +1,7 @@
#!/usr/bin/env bun #!/usr/bin/env bun
import * as core from "@actions/core"; import * as core from "@actions/core";
import { retryWithBackoff } from "../utils/retry";
type RetryOptions = {
maxAttempts?: number;
initialDelayMs?: number;
maxDelayMs?: number;
backoffFactor?: number;
};
async function retryWithBackoff<T>(
operation: () => Promise<T>,
options: RetryOptions = {},
): Promise<T> {
const {
maxAttempts = 3,
initialDelayMs = 5000,
maxDelayMs = 20000,
backoffFactor = 2,
} = options;
let delayMs = initialDelayMs;
let lastError: Error | undefined;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
console.log(`Attempt ${attempt} of ${maxAttempts}...`);
return await operation();
} catch (error) {
lastError = error instanceof Error ? error : new Error(String(error));
console.error(`Attempt ${attempt} failed:`, lastError.message);
if (attempt < maxAttempts) {
console.log(`Retrying in ${delayMs / 1000} seconds...`);
await new Promise((resolve) => setTimeout(resolve, delayMs));
delayMs = Math.min(delayMs * backoffFactor, maxDelayMs);
}
}
}
console.error(`Operation failed after ${maxAttempts} attempts`);
throw lastError;
}
async function getOidcToken(): Promise<string> { async function getOidcToken(): Promise<string> {
try { try {

View File

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

View File

@@ -3,6 +3,7 @@
import * as core from "@actions/core"; import * as core from "@actions/core";
import { import {
isIssuesEvent, isIssuesEvent,
isIssuesAssignedEvent,
isIssueCommentEvent, isIssueCommentEvent,
isPullRequestEvent, isPullRequestEvent,
isPullRequestReviewEvent, isPullRequestReviewEvent,
@@ -12,7 +13,7 @@ import type { ParsedGitHubContext } from "../context";
export function checkContainsTrigger(context: ParsedGitHubContext): boolean { export function checkContainsTrigger(context: ParsedGitHubContext): boolean {
const { const {
inputs: { assigneeTrigger, triggerPhrase, directPrompt }, inputs: { assigneeTrigger, labelTrigger, triggerPhrase, directPrompt },
} = context; } = context;
// If direct prompt is provided, always trigger // If direct prompt is provided, always trigger
@@ -22,10 +23,10 @@ export function checkContainsTrigger(context: ParsedGitHubContext): boolean {
} }
// Check for assignee trigger // Check for assignee trigger
if (isIssuesEvent(context) && context.eventAction === "assigned") { if (isIssuesAssignedEvent(context)) {
// Remove @ symbol from assignee_trigger if present // Remove @ symbol from assignee_trigger if present
let triggerUser = assigneeTrigger.replace(/^@/, ""); let triggerUser = assigneeTrigger.replace(/^@/, "");
const assigneeUsername = context.payload.issue.assignee?.login || ""; const assigneeUsername = context.payload.assignee?.login || "";
if (triggerUser && assigneeUsername === triggerUser) { if (triggerUser && assigneeUsername === triggerUser) {
console.log(`Issue assigned to trigger user '${triggerUser}'`); console.log(`Issue assigned to trigger user '${triggerUser}'`);
@@ -33,6 +34,16 @@ export function checkContainsTrigger(context: ParsedGitHubContext): boolean {
} }
} }
// Check for label trigger
if (isIssuesEvent(context) && context.eventAction === "labeled") {
const labelName = (context.payload as any).label?.name || "";
if (labelTrigger && labelName === labelTrigger) {
console.log(`Issue labeled with trigger label '${labelTrigger}'`);
return true;
}
}
// Check for issue body and title trigger on issue creation // Check for issue body and title trigger on issue creation
if (isIssuesEvent(context) && context.eventAction === "opened") { if (isIssuesEvent(context) && context.eventAction === "opened") {
const issueBody = context.payload.issue.body || ""; const issueBody = context.payload.issue.body || "";

View File

@@ -0,0 +1,279 @@
#!/usr/bin/env node
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import { GITHUB_API_URL } from "../github/api/config";
import { mkdir, writeFile } from "fs/promises";
import { Octokit } from "@octokit/rest";
const REPO_OWNER = process.env.REPO_OWNER;
const REPO_NAME = process.env.REPO_NAME;
const PR_NUMBER = process.env.PR_NUMBER;
const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
const RUNNER_TEMP = process.env.RUNNER_TEMP || "/tmp";
if (!REPO_OWNER || !REPO_NAME || !PR_NUMBER || !GITHUB_TOKEN) {
console.error(
"[GitHub CI Server] Error: REPO_OWNER, REPO_NAME, PR_NUMBER, and GITHUB_TOKEN environment variables are required",
);
process.exit(1);
}
const server = new McpServer({
name: "GitHub CI Server",
version: "0.0.1",
});
console.error("[GitHub CI Server] MCP Server instance created");
server.tool(
"get_ci_status",
"Get CI status summary for this PR",
{
status: z
.enum([
"completed",
"action_required",
"cancelled",
"failure",
"neutral",
"skipped",
"stale",
"success",
"timed_out",
"in_progress",
"queued",
"requested",
"waiting",
"pending",
])
.optional()
.describe("Filter workflow runs by status"),
},
async ({ status }) => {
try {
const client = new Octokit({
auth: GITHUB_TOKEN,
baseUrl: GITHUB_API_URL,
});
// Get the PR to find the head SHA
const { data: prData } = await client.pulls.get({
owner: REPO_OWNER!,
repo: REPO_NAME!,
pull_number: parseInt(PR_NUMBER!, 10),
});
const headSha = prData.head.sha;
const { data: runsData } = await client.actions.listWorkflowRunsForRepo({
owner: REPO_OWNER!,
repo: REPO_NAME!,
head_sha: headSha,
...(status && { status }),
});
// Process runs to create summary
const runs = runsData.workflow_runs || [];
const summary = {
total_runs: runs.length,
failed: 0,
passed: 0,
pending: 0,
};
const processedRuns = runs.map((run: any) => {
// Update summary counts
if (run.status === "completed") {
if (run.conclusion === "success") {
summary.passed++;
} else if (run.conclusion === "failure") {
summary.failed++;
}
} else {
summary.pending++;
}
return {
id: run.id,
name: run.name,
status: run.status,
conclusion: run.conclusion,
html_url: run.html_url,
created_at: run.created_at,
};
});
const result = {
summary,
runs: processedRuns,
};
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
};
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : String(error);
return {
content: [
{
type: "text",
text: `Error: ${errorMessage}`,
},
],
error: errorMessage,
isError: true,
};
}
},
);
server.tool(
"get_workflow_run_details",
"Get job and step details for a workflow run",
{
run_id: z.number().describe("The workflow run ID"),
},
async ({ run_id }) => {
try {
const client = new Octokit({
auth: GITHUB_TOKEN,
baseUrl: GITHUB_API_URL,
});
// Get jobs for this workflow run
const { data: jobsData } = await client.actions.listJobsForWorkflowRun({
owner: REPO_OWNER!,
repo: REPO_NAME!,
run_id,
});
const processedJobs = jobsData.jobs.map((job: any) => {
// Extract failed steps
const failedSteps = (job.steps || [])
.filter((step: any) => step.conclusion === "failure")
.map((step: any) => ({
name: step.name,
number: step.number,
}));
return {
id: job.id,
name: job.name,
conclusion: job.conclusion,
html_url: job.html_url,
failed_steps: failedSteps,
};
});
const result = {
jobs: processedJobs,
};
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
};
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : String(error);
return {
content: [
{
type: "text",
text: `Error: ${errorMessage}`,
},
],
error: errorMessage,
isError: true,
};
}
},
);
server.tool(
"download_job_log",
"Download job logs to disk",
{
job_id: z.number().describe("The job ID"),
},
async ({ job_id }) => {
try {
const client = new Octokit({
auth: GITHUB_TOKEN,
baseUrl: GITHUB_API_URL,
});
const response = await client.actions.downloadJobLogsForWorkflowRun({
owner: REPO_OWNER!,
repo: REPO_NAME!,
job_id,
});
const logsText = response.data as unknown as string;
const logsDir = `${RUNNER_TEMP}/github-ci-logs`;
await mkdir(logsDir, { recursive: true });
const logPath = `${logsDir}/job-${job_id}.log`;
await writeFile(logPath, logsText, "utf-8");
const result = {
path: logPath,
size_bytes: Buffer.byteLength(logsText, "utf-8"),
};
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
};
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : String(error);
return {
content: [
{
type: "text",
text: `Error: ${errorMessage}`,
},
],
error: errorMessage,
isError: true,
};
}
},
);
async function runServer() {
try {
const transport = new StdioServerTransport();
await server.connect(transport);
process.on("exit", () => {
server.close();
});
} catch (error) {
throw error;
}
}
runServer().catch(() => {
process.exit(1);
});

View File

@@ -0,0 +1,98 @@
#!/usr/bin/env node
// GitHub Comment MCP Server - Minimal server that only provides comment update functionality
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import { GITHUB_API_URL } from "../github/api/config";
import { Octokit } from "@octokit/rest";
import { updateClaudeComment } from "../github/operations/comments/update-claude-comment";
// Get repository information from environment variables
const REPO_OWNER = process.env.REPO_OWNER;
const REPO_NAME = process.env.REPO_NAME;
if (!REPO_OWNER || !REPO_NAME) {
console.error(
"Error: REPO_OWNER and REPO_NAME environment variables are required",
);
process.exit(1);
}
const server = new McpServer({
name: "GitHub Comment Server",
version: "0.0.1",
});
server.tool(
"update_claude_comment",
"Update the Claude comment with progress and results (automatically handles both issue and PR comments)",
{
body: z.string().describe("The updated comment content"),
},
async ({ body }) => {
try {
const githubToken = process.env.GITHUB_TOKEN;
const claudeCommentId = process.env.CLAUDE_COMMENT_ID;
const eventName = process.env.GITHUB_EVENT_NAME;
if (!githubToken) {
throw new Error("GITHUB_TOKEN environment variable is required");
}
if (!claudeCommentId) {
throw new Error("CLAUDE_COMMENT_ID environment variable is required");
}
const owner = REPO_OWNER;
const repo = REPO_NAME;
const commentId = parseInt(claudeCommentId, 10);
const octokit = new Octokit({
auth: githubToken,
baseUrl: GITHUB_API_URL,
});
const isPullRequestReviewComment =
eventName === "pull_request_review_comment";
const result = await updateClaudeComment(octokit, {
owner,
repo,
commentId,
body,
isPullRequestReviewComment,
});
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
};
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : String(error);
return {
content: [
{
type: "text",
text: `Error: ${errorMessage}`,
},
],
error: errorMessage,
isError: true,
};
}
},
);
async function runServer() {
const transport = new StdioServerTransport();
await server.connect(transport);
process.on("exit", () => {
server.close();
});
}
runServer().catch(console.error);

View File

@@ -7,8 +7,7 @@ import { readFile } from "fs/promises";
import { join } from "path"; import { join } from "path";
import fetch from "node-fetch"; import fetch from "node-fetch";
import { GITHUB_API_URL } from "../github/api/config"; import { GITHUB_API_URL } from "../github/api/config";
import { Octokit } from "@octokit/rest"; import { retryWithBackoff } from "../utils/retry";
import { updateClaudeComment } from "../github/operations/comments/update-claude-comment";
type GitHubRef = { type GitHubRef = {
object: { object: {
@@ -53,6 +52,116 @@ const server = new McpServer({
version: "0.0.1", version: "0.0.1",
}); });
// Helper function to get or create branch reference
async function getOrCreateBranchRef(
owner: string,
repo: string,
branch: string,
githubToken: string,
): Promise<string> {
// Try to get the branch reference
const refUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}/git/refs/heads/${branch}`;
const refResponse = await fetch(refUrl, {
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${githubToken}`,
"X-GitHub-Api-Version": "2022-11-28",
},
});
if (refResponse.ok) {
const refData = (await refResponse.json()) as GitHubRef;
return refData.object.sha;
}
if (refResponse.status !== 404) {
throw new Error(`Failed to get branch reference: ${refResponse.status}`);
}
const baseBranch = process.env.BASE_BRANCH!;
// Get the SHA of the base branch
const baseRefUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}/git/refs/heads/${baseBranch}`;
const baseRefResponse = await fetch(baseRefUrl, {
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${githubToken}`,
"X-GitHub-Api-Version": "2022-11-28",
},
});
let baseSha: string;
if (!baseRefResponse.ok) {
// If base branch doesn't exist, try default branch
const repoUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}`;
const repoResponse = await fetch(repoUrl, {
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${githubToken}`,
"X-GitHub-Api-Version": "2022-11-28",
},
});
if (!repoResponse.ok) {
throw new Error(`Failed to get repository info: ${repoResponse.status}`);
}
const repoData = (await repoResponse.json()) as {
default_branch: string;
};
const defaultBranch = repoData.default_branch;
// Try default branch
const defaultRefUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}/git/refs/heads/${defaultBranch}`;
const defaultRefResponse = await fetch(defaultRefUrl, {
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${githubToken}`,
"X-GitHub-Api-Version": "2022-11-28",
},
});
if (!defaultRefResponse.ok) {
throw new Error(
`Failed to get default branch reference: ${defaultRefResponse.status}`,
);
}
const defaultRefData = (await defaultRefResponse.json()) as GitHubRef;
baseSha = defaultRefData.object.sha;
} else {
const baseRefData = (await baseRefResponse.json()) as GitHubRef;
baseSha = baseRefData.object.sha;
}
// Create the new branch using the same pattern as octokit
const createRefUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}/git/refs`;
const createRefResponse = await fetch(createRefUrl, {
method: "POST",
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${githubToken}`,
"X-GitHub-Api-Version": "2022-11-28",
"Content-Type": "application/json",
},
body: JSON.stringify({
ref: `refs/heads/${branch}`,
sha: baseSha,
}),
});
if (!createRefResponse.ok) {
const errorText = await createRefResponse.text();
throw new Error(
`Failed to create branch: ${createRefResponse.status} - ${errorText}`,
);
}
console.log(`Successfully created branch ${branch}`);
return baseSha;
}
// Commit files tool // Commit files tool
server.tool( server.tool(
"commit_files", "commit_files",
@@ -82,24 +191,13 @@ server.tool(
return filePath; return filePath;
}); });
// 1. Get the branch reference // 1. Get the branch reference (create if doesn't exist)
const refUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}/git/refs/heads/${branch}`; const baseSha = await getOrCreateBranchRef(
const refResponse = await fetch(refUrl, { owner,
headers: { repo,
Accept: "application/vnd.github+json", branch,
Authorization: `Bearer ${githubToken}`, githubToken,
"X-GitHub-Api-Version": "2022-11-28", );
},
});
if (!refResponse.ok) {
throw new Error(
`Failed to get branch reference: ${refResponse.status}`,
);
}
const refData = (await refResponse.json()) as GitHubRef;
const baseSha = refData.object.sha;
// 2. Get the base commit // 2. Get the base commit
const commitUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}/git/commits/${baseSha}`; const commitUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}/git/commits/${baseSha}`;
@@ -125,13 +223,58 @@ server.tool(
? filePath ? filePath
: join(REPO_DIR, filePath); : join(REPO_DIR, filePath);
const content = await readFile(fullPath, "utf-8"); // Check if file is binary (images, etc.)
return { const isBinaryFile =
path: filePath, /\.(png|jpg|jpeg|gif|webp|ico|pdf|zip|tar|gz|exe|bin|woff|woff2|ttf|eot)$/i.test(
mode: "100644", filePath,
type: "blob", );
content: content,
}; if (isBinaryFile) {
// For binary files, create a blob first using the Blobs API
const binaryContent = await readFile(fullPath);
// Create blob using Blobs API (supports encoding parameter)
const blobUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}/git/blobs`;
const blobResponse = await fetch(blobUrl, {
method: "POST",
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${githubToken}`,
"X-GitHub-Api-Version": "2022-11-28",
"Content-Type": "application/json",
},
body: JSON.stringify({
content: binaryContent.toString("base64"),
encoding: "base64",
}),
});
if (!blobResponse.ok) {
const errorText = await blobResponse.text();
throw new Error(
`Failed to create blob for ${filePath}: ${blobResponse.status} - ${errorText}`,
);
}
const blobData = (await blobResponse.json()) as { sha: string };
// Return tree entry with blob SHA
return {
path: filePath,
mode: "100644",
type: "blob",
sha: blobData.sha,
};
} else {
// For text files, include content directly in tree
const content = await readFile(fullPath, "utf-8");
return {
path: filePath,
mode: "100644",
type: "blob",
content: content,
};
}
}), }),
); );
@@ -188,26 +331,49 @@ server.tool(
// 6. Update the reference to point to the new commit // 6. Update the reference to point to the new commit
const updateRefUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}/git/refs/heads/${branch}`; const updateRefUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}/git/refs/heads/${branch}`;
const updateRefResponse = await fetch(updateRefUrl, {
method: "PATCH",
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${githubToken}`,
"X-GitHub-Api-Version": "2022-11-28",
"Content-Type": "application/json",
},
body: JSON.stringify({
sha: newCommitData.sha,
force: false,
}),
});
if (!updateRefResponse.ok) { // We're seeing intermittent 403 "Resource not accessible by integration" errors
const errorText = await updateRefResponse.text(); // on certain repos when updating git references. These appear to be transient
throw new Error( // GitHub API issues that succeed on retry.
`Failed to update reference: ${updateRefResponse.status} - ${errorText}`, await retryWithBackoff(
); async () => {
} const updateRefResponse = await fetch(updateRefUrl, {
method: "PATCH",
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${githubToken}`,
"X-GitHub-Api-Version": "2022-11-28",
"Content-Type": "application/json",
},
body: JSON.stringify({
sha: newCommitData.sha,
force: false,
}),
});
if (!updateRefResponse.ok) {
const errorText = await updateRefResponse.text();
const error = new Error(
`Failed to update reference: ${updateRefResponse.status} - ${errorText}`,
);
// Only retry on 403 errors - these are the intermittent failures we're targeting
if (updateRefResponse.status === 403) {
throw error;
}
// For non-403 errors, fail immediately without retry
console.error("Non-retryable error:", updateRefResponse.status);
throw error;
}
},
{
maxAttempts: 3,
initialDelayMs: 1000, // Start with 1 second delay
maxDelayMs: 5000, // Max 5 seconds delay
backoffFactor: 2, // Double the delay each time
},
);
const simplifiedResult = { const simplifiedResult = {
commit: { commit: {
@@ -285,24 +451,13 @@ server.tool(
return filePath; return filePath;
}); });
// 1. Get the branch reference // 1. Get the branch reference (create if doesn't exist)
const refUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}/git/refs/heads/${branch}`; const baseSha = await getOrCreateBranchRef(
const refResponse = await fetch(refUrl, { owner,
headers: { repo,
Accept: "application/vnd.github+json", branch,
Authorization: `Bearer ${githubToken}`, githubToken,
"X-GitHub-Api-Version": "2022-11-28", );
},
});
if (!refResponse.ok) {
throw new Error(
`Failed to get branch reference: ${refResponse.status}`,
);
}
const refData = (await refResponse.json()) as GitHubRef;
const baseSha = refData.object.sha;
// 2. Get the base commit // 2. Get the base commit
const commitUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}/git/commits/${baseSha}`; const commitUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}/git/commits/${baseSha}`;
@@ -382,26 +537,50 @@ server.tool(
// 6. Update the reference to point to the new commit // 6. Update the reference to point to the new commit
const updateRefUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}/git/refs/heads/${branch}`; const updateRefUrl = `${GITHUB_API_URL}/repos/${owner}/${repo}/git/refs/heads/${branch}`;
const updateRefResponse = await fetch(updateRefUrl, {
method: "PATCH",
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${githubToken}`,
"X-GitHub-Api-Version": "2022-11-28",
"Content-Type": "application/json",
},
body: JSON.stringify({
sha: newCommitData.sha,
force: false,
}),
});
if (!updateRefResponse.ok) { // We're seeing intermittent 403 "Resource not accessible by integration" errors
const errorText = await updateRefResponse.text(); // on certain repos when updating git references. These appear to be transient
throw new Error( // GitHub API issues that succeed on retry.
`Failed to update reference: ${updateRefResponse.status} - ${errorText}`, await retryWithBackoff(
); async () => {
} const updateRefResponse = await fetch(updateRefUrl, {
method: "PATCH",
headers: {
Accept: "application/vnd.github+json",
Authorization: `Bearer ${githubToken}`,
"X-GitHub-Api-Version": "2022-11-28",
"Content-Type": "application/json",
},
body: JSON.stringify({
sha: newCommitData.sha,
force: false,
}),
});
if (!updateRefResponse.ok) {
const errorText = await updateRefResponse.text();
const error = new Error(
`Failed to update reference: ${updateRefResponse.status} - ${errorText}`,
);
// Only retry on 403 errors - these are the intermittent failures we're targeting
if (updateRefResponse.status === 403) {
console.log("Received 403 error, will retry...");
throw error;
}
// For non-403 errors, fail immediately without retry
console.error("Non-retryable error:", updateRefResponse.status);
throw error;
}
},
{
maxAttempts: 3,
initialDelayMs: 1000, // Start with 1 second delay
maxDelayMs: 5000, // Max 5 seconds delay
backoffFactor: 2, // Double the delay each time
},
);
const simplifiedResult = { const simplifiedResult = {
commit: { commit: {
@@ -441,69 +620,6 @@ server.tool(
}, },
); );
server.tool(
"update_claude_comment",
"Update the Claude comment with progress and results (automatically handles both issue and PR comments)",
{
body: z.string().describe("The updated comment content"),
},
async ({ body }) => {
try {
const githubToken = process.env.GITHUB_TOKEN;
const claudeCommentId = process.env.CLAUDE_COMMENT_ID;
const eventName = process.env.GITHUB_EVENT_NAME;
if (!githubToken) {
throw new Error("GITHUB_TOKEN environment variable is required");
}
if (!claudeCommentId) {
throw new Error("CLAUDE_COMMENT_ID environment variable is required");
}
const owner = REPO_OWNER;
const repo = REPO_NAME;
const commentId = parseInt(claudeCommentId, 10);
const octokit = new Octokit({
auth: githubToken,
});
const isPullRequestReviewComment =
eventName === "pull_request_review_comment";
const result = await updateClaudeComment(octokit, {
owner,
repo,
commentId,
body,
isPullRequestReviewComment,
});
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
};
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : String(error);
return {
content: [
{
type: "text",
text: `Error: ${errorMessage}`,
},
],
error: errorMessage,
isError: true,
};
}
},
);
async function runServer() { async function runServer() {
const transport = new StdioServerTransport(); const transport = new StdioServerTransport();
await server.connect(transport); await server.connect(transport);

View File

@@ -1,14 +1,52 @@
import * as core from "@actions/core"; import * as core from "@actions/core";
import { GITHUB_API_URL } from "../github/api/config";
import type { ParsedGitHubContext } from "../github/context";
import { Octokit } from "@octokit/rest";
type PrepareConfigParams = { type PrepareConfigParams = {
githubToken: string; githubToken: string;
owner: string; owner: string;
repo: string; repo: string;
branch: string; branch: string;
baseBranch: string;
additionalMcpConfig?: string; additionalMcpConfig?: string;
claudeCommentId?: string; claudeCommentId?: string;
allowedTools: string[];
context: ParsedGitHubContext;
}; };
async function checkActionsReadPermission(
token: string,
owner: string,
repo: string,
): Promise<boolean> {
try {
const client = new Octokit({ auth: token, baseUrl: GITHUB_API_URL });
// Try to list workflow runs - this requires actions:read
// We use per_page=1 to minimize the response size
await client.actions.listWorkflowRunsForRepo({
owner,
repo,
per_page: 1,
});
return true;
} catch (error: any) {
// Check if it's a permission error
if (
error.status === 403 &&
error.message?.includes("Resource not accessible")
) {
return false;
}
// For other errors (network issues, etc), log but don't fail
core.debug(`Failed to check actions permission: ${error.message}`);
return false;
}
}
export async function prepareMcpConfig( export async function prepareMcpConfig(
params: PrepareConfigParams, params: PrepareConfigParams,
): Promise<string> { ): Promise<string> {
@@ -17,46 +55,115 @@ export async function prepareMcpConfig(
owner, owner,
repo, repo,
branch, branch,
baseBranch,
additionalMcpConfig, additionalMcpConfig,
claudeCommentId, claudeCommentId,
allowedTools,
context,
} = params; } = params;
try { try {
const baseMcpConfig = { const allowedToolsList = allowedTools || [];
mcpServers: {
github: { const hasGitHubMcpTools = allowedToolsList.some((tool) =>
command: "docker", tool.startsWith("mcp__github__"),
args: [ );
"run",
"-i", const baseMcpConfig: { mcpServers: Record<string, unknown> } = {
"--rm", mcpServers: {},
"-e", };
"GITHUB_PERSONAL_ACCESS_TOKEN",
"ghcr.io/anthropics/github-mcp-server:sha-7382253", // Always include comment server for updating Claude comments
], baseMcpConfig.mcpServers.github_comment = {
env: { command: "bun",
GITHUB_PERSONAL_ACCESS_TOKEN: githubToken, args: [
}, "run",
}, `${process.env.GITHUB_ACTION_PATH}/src/mcp/github-comment-server.ts`,
github_file_ops: { ],
command: "bun", env: {
args: [ GITHUB_TOKEN: githubToken,
"run", REPO_OWNER: owner,
`${process.env.GITHUB_ACTION_PATH}/src/mcp/github-file-ops-server.ts`, REPO_NAME: repo,
], ...(claudeCommentId && { CLAUDE_COMMENT_ID: claudeCommentId }),
env: { GITHUB_EVENT_NAME: process.env.GITHUB_EVENT_NAME || "",
GITHUB_TOKEN: githubToken, GITHUB_API_URL: GITHUB_API_URL,
REPO_OWNER: owner,
REPO_NAME: repo,
BRANCH_NAME: branch,
REPO_DIR: process.env.GITHUB_WORKSPACE || process.cwd(),
...(claudeCommentId && { CLAUDE_COMMENT_ID: claudeCommentId }),
GITHUB_EVENT_NAME: process.env.GITHUB_EVENT_NAME || "",
IS_PR: process.env.IS_PR || "false",
},
},
}, },
}; };
// Include file ops server when commit signing is enabled
if (context.inputs.useCommitSigning) {
baseMcpConfig.mcpServers.github_file_ops = {
command: "bun",
args: [
"run",
`${process.env.GITHUB_ACTION_PATH}/src/mcp/github-file-ops-server.ts`,
],
env: {
GITHUB_TOKEN: githubToken,
REPO_OWNER: owner,
REPO_NAME: repo,
BRANCH_NAME: branch,
BASE_BRANCH: baseBranch,
REPO_DIR: process.env.GITHUB_WORKSPACE || process.cwd(),
GITHUB_EVENT_NAME: process.env.GITHUB_EVENT_NAME || "",
IS_PR: process.env.IS_PR || "false",
GITHUB_API_URL: GITHUB_API_URL,
},
};
}
// Only add CI server if we have actions:read permission and we're in a PR context
const hasActionsReadPermission =
context.inputs.additionalPermissions.get("actions") === "read";
if (context.isPR && hasActionsReadPermission) {
// Verify the token actually has actions:read permission
const actuallyHasPermission = await checkActionsReadPermission(
process.env.ACTIONS_TOKEN || "",
owner,
repo,
);
if (!actuallyHasPermission) {
core.warning(
"The github_ci MCP server requires 'actions: read' permission. " +
"Please ensure your GitHub token has this permission. " +
"See: https://docs.github.com/en/actions/security-guides/automatic-token-authentication#permissions-for-the-github_token",
);
}
baseMcpConfig.mcpServers.github_ci = {
command: "bun",
args: [
"run",
`${process.env.GITHUB_ACTION_PATH}/src/mcp/github-actions-server.ts`,
],
env: {
// Use workflow github token, not app token
GITHUB_TOKEN: process.env.ACTIONS_TOKEN,
REPO_OWNER: owner,
REPO_NAME: repo,
PR_NUMBER: context.entityNumber.toString(),
RUNNER_TEMP: process.env.RUNNER_TEMP || "/tmp",
},
};
}
if (hasGitHubMcpTools) {
baseMcpConfig.mcpServers.github = {
command: "docker",
args: [
"run",
"-i",
"--rm",
"-e",
"GITHUB_PERSONAL_ACCESS_TOKEN",
"ghcr.io/github/github-mcp-server:sha-721fd3e", // https://github.com/github/github-mcp-server/releases/tag/v0.6.0
],
env: {
GITHUB_PERSONAL_ACCESS_TOKEN: githubToken,
},
};
}
// Merge with additional MCP config if provided // Merge with additional MCP config if provided
if (additionalMcpConfig && additionalMcpConfig.trim()) { if (additionalMcpConfig && additionalMcpConfig.trim()) {
try { try {

40
src/utils/retry.ts Normal file
View File

@@ -0,0 +1,40 @@
export type RetryOptions = {
maxAttempts?: number;
initialDelayMs?: number;
maxDelayMs?: number;
backoffFactor?: number;
};
export async function retryWithBackoff<T>(
operation: () => Promise<T>,
options: RetryOptions = {},
): Promise<T> {
const {
maxAttempts = 3,
initialDelayMs = 5000,
maxDelayMs = 20000,
backoffFactor = 2,
} = options;
let delayMs = initialDelayMs;
let lastError: Error | undefined;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
console.log(`Attempt ${attempt} of ${maxAttempts}...`);
return await operation();
} catch (error) {
lastError = error instanceof Error ? error : new Error(String(error));
console.error(`Attempt ${attempt} failed:`, lastError.message);
if (attempt < maxAttempts) {
console.log(`Retrying in ${delayMs / 1000} seconds...`);
await new Promise((resolve) => setTimeout(resolve, delayMs));
delayMs = Math.min(delayMs * backoffFactor, maxDelayMs);
}
}
}
console.error(`Operation failed after ${maxAttempts} attempts`);
throw lastError;
}

View File

@@ -1,9 +1,9 @@
import { describe, test, expect, beforeEach, afterEach, spyOn } from "bun:test"; import { describe, test, expect, beforeEach, afterEach, spyOn } from "bun:test";
import { checkAndDeleteEmptyBranch } from "../src/github/operations/branch-cleanup"; import { checkAndCommitOrDeleteBranch } from "../src/github/operations/branch-cleanup";
import type { Octokits } from "../src/github/api/client"; import type { Octokits } from "../src/github/api/client";
import { GITHUB_SERVER_URL } from "../src/github/api/config"; import { GITHUB_SERVER_URL } from "../src/github/api/config";
describe("checkAndDeleteEmptyBranch", () => { describe("checkAndCommitOrDeleteBranch", () => {
let consoleLogSpy: any; let consoleLogSpy: any;
let consoleErrorSpy: any; let consoleErrorSpy: any;
@@ -21,6 +21,7 @@ describe("checkAndDeleteEmptyBranch", () => {
const createMockOctokit = ( const createMockOctokit = (
compareResponse?: any, compareResponse?: any,
deleteRefError?: Error, deleteRefError?: Error,
branchExists: boolean = true,
): Octokits => { ): Octokits => {
return { return {
rest: { rest: {
@@ -28,6 +29,14 @@ describe("checkAndDeleteEmptyBranch", () => {
compareCommitsWithBasehead: async () => ({ compareCommitsWithBasehead: async () => ({
data: compareResponse || { total_commits: 0 }, data: compareResponse || { total_commits: 0 },
}), }),
getBranch: async () => {
if (!branchExists) {
const error: any = new Error("Not Found");
error.status = 404;
throw error;
}
return { data: {} };
},
}, },
git: { git: {
deleteRef: async () => { deleteRef: async () => {
@@ -43,12 +52,13 @@ describe("checkAndDeleteEmptyBranch", () => {
test("should return no branch link and not delete when branch is undefined", async () => { test("should return no branch link and not delete when branch is undefined", async () => {
const mockOctokit = createMockOctokit(); const mockOctokit = createMockOctokit();
const result = await checkAndDeleteEmptyBranch( const result = await checkAndCommitOrDeleteBranch(
mockOctokit, mockOctokit,
"owner", "owner",
"repo", "repo",
undefined, undefined,
"main", "main",
false,
); );
expect(result.shouldDeleteBranch).toBe(false); expect(result.shouldDeleteBranch).toBe(false);
@@ -56,39 +66,38 @@ describe("checkAndDeleteEmptyBranch", () => {
expect(consoleLogSpy).not.toHaveBeenCalled(); expect(consoleLogSpy).not.toHaveBeenCalled();
}); });
test("should delete branch and return no link when branch has no commits", async () => { test("should mark branch for deletion when commit signing is enabled and no commits", async () => {
const mockOctokit = createMockOctokit({ total_commits: 0 }); const mockOctokit = createMockOctokit({ total_commits: 0 });
const result = await checkAndDeleteEmptyBranch( const result = await checkAndCommitOrDeleteBranch(
mockOctokit, mockOctokit,
"owner", "owner",
"repo", "repo",
"claude/issue-123-20240101_123456", "claude/issue-123-20240101-1234",
"main", "main",
true, // commit signing enabled
); );
expect(result.shouldDeleteBranch).toBe(true); expect(result.shouldDeleteBranch).toBe(true);
expect(result.branchLink).toBe(""); expect(result.branchLink).toBe("");
expect(consoleLogSpy).toHaveBeenCalledWith( expect(consoleLogSpy).toHaveBeenCalledWith(
"Branch claude/issue-123-20240101_123456 has no commits from Claude, will delete it", "Branch claude/issue-123-20240101-1234 has no commits from Claude, will delete it",
);
expect(consoleLogSpy).toHaveBeenCalledWith(
"✅ Deleted empty branch: claude/issue-123-20240101_123456",
); );
}); });
test("should not delete branch and return link when branch has commits", async () => { test("should not delete branch and return link when branch has commits", async () => {
const mockOctokit = createMockOctokit({ total_commits: 3 }); const mockOctokit = createMockOctokit({ total_commits: 3 });
const result = await checkAndDeleteEmptyBranch( const result = await checkAndCommitOrDeleteBranch(
mockOctokit, mockOctokit,
"owner", "owner",
"repo", "repo",
"claude/issue-123-20240101_123456", "claude/issue-123-20240101-1234",
"main", "main",
false,
); );
expect(result.shouldDeleteBranch).toBe(false); expect(result.shouldDeleteBranch).toBe(false);
expect(result.branchLink).toBe( expect(result.branchLink).toBe(
`\n[View branch](${GITHUB_SERVER_URL}/owner/repo/tree/claude/issue-123-20240101_123456)`, `\n[View branch](${GITHUB_SERVER_URL}/owner/repo/tree/claude/issue-123-20240101-1234)`,
); );
expect(consoleLogSpy).not.toHaveBeenCalledWith( expect(consoleLogSpy).not.toHaveBeenCalledWith(
expect.stringContaining("has no commits"), expect.stringContaining("has no commits"),
@@ -102,6 +111,7 @@ describe("checkAndDeleteEmptyBranch", () => {
compareCommitsWithBasehead: async () => { compareCommitsWithBasehead: async () => {
throw new Error("API error"); throw new Error("API error");
}, },
getBranch: async () => ({ data: {} }), // Branch exists
}, },
git: { git: {
deleteRef: async () => ({ data: {} }), deleteRef: async () => ({ data: {} }),
@@ -109,20 +119,21 @@ describe("checkAndDeleteEmptyBranch", () => {
}, },
} as any as Octokits; } as any as Octokits;
const result = await checkAndDeleteEmptyBranch( const result = await checkAndCommitOrDeleteBranch(
mockOctokit, mockOctokit,
"owner", "owner",
"repo", "repo",
"claude/issue-123-20240101_123456", "claude/issue-123-20240101-1234",
"main", "main",
false,
); );
expect(result.shouldDeleteBranch).toBe(false); expect(result.shouldDeleteBranch).toBe(false);
expect(result.branchLink).toBe( expect(result.branchLink).toBe(
`\n[View branch](${GITHUB_SERVER_URL}/owner/repo/tree/claude/issue-123-20240101_123456)`, `\n[View branch](${GITHUB_SERVER_URL}/owner/repo/tree/claude/issue-123-20240101-1234)`,
); );
expect(consoleErrorSpy).toHaveBeenCalledWith( expect(consoleErrorSpy).toHaveBeenCalledWith(
"Error checking for commits on Claude branch:", "Error comparing commits on Claude branch:",
expect.any(Error), expect.any(Error),
); );
}); });
@@ -131,19 +142,46 @@ describe("checkAndDeleteEmptyBranch", () => {
const deleteError = new Error("Delete failed"); const deleteError = new Error("Delete failed");
const mockOctokit = createMockOctokit({ total_commits: 0 }, deleteError); const mockOctokit = createMockOctokit({ total_commits: 0 }, deleteError);
const result = await checkAndDeleteEmptyBranch( const result = await checkAndCommitOrDeleteBranch(
mockOctokit, mockOctokit,
"owner", "owner",
"repo", "repo",
"claude/issue-123-20240101_123456", "claude/issue-123-20240101-1234",
"main", "main",
true, // commit signing enabled - will try to delete
); );
expect(result.shouldDeleteBranch).toBe(true); expect(result.shouldDeleteBranch).toBe(true);
expect(result.branchLink).toBe(""); expect(result.branchLink).toBe("");
expect(consoleErrorSpy).toHaveBeenCalledWith( expect(consoleErrorSpy).toHaveBeenCalledWith(
"Failed to delete branch claude/issue-123-20240101_123456:", "Failed to delete branch claude/issue-123-20240101-1234:",
deleteError, deleteError,
); );
}); });
test("should return no branch link when branch doesn't exist remotely", async () => {
const mockOctokit = createMockOctokit(
{ total_commits: 0 },
undefined,
false, // branch doesn't exist
);
const result = await checkAndCommitOrDeleteBranch(
mockOctokit,
"owner",
"repo",
"claude/issue-123-20240101-1234",
"main",
false,
);
expect(result.shouldDeleteBranch).toBe(false);
expect(result.branchLink).toBe("");
expect(consoleLogSpy).toHaveBeenCalledWith(
"Branch claude/issue-123-20240101-1234 does not exist remotely",
);
expect(consoleLogSpy).toHaveBeenCalledWith(
"Branch claude/issue-123-20240101-1234 does not exist remotely, no branch link will be added",
);
});
}); });

View File

@@ -1,5 +1,8 @@
import { describe, it, expect } from "bun:test"; import { describe, it, expect } from "bun:test";
import { updateCommentBody } from "../src/github/operations/comment-logic"; import {
updateCommentBody,
type CommentUpdateInput,
} from "../src/github/operations/comment-logic";
describe("updateCommentBody", () => { describe("updateCommentBody", () => {
const baseInput = { const baseInput = {
@@ -100,12 +103,12 @@ describe("updateCommentBody", () => {
it("adds branch name with link to header when provided", () => { it("adds branch name with link to header when provided", () => {
const input = { const input = {
...baseInput, ...baseInput,
branchName: "claude/issue-123-20240101_120000", branchName: "claude/issue-123-20240101-1200",
}; };
const result = updateCommentBody(input); const result = updateCommentBody(input);
expect(result).toContain( expect(result).toContain(
"• [`claude/issue-123-20240101_120000`](https://github.com/owner/repo/tree/claude/issue-123-20240101_120000)", "• [`claude/issue-123-20240101-1200`](https://github.com/owner/repo/tree/claude/issue-123-20240101-1200)",
); );
}); });
@@ -381,9 +384,9 @@ describe("updateCommentBody", () => {
const input = { const input = {
...baseInput, ...baseInput,
currentBody: "Claude Code is working… <img src='spinner.gif' />", currentBody: "Claude Code is working… <img src='spinner.gif' />",
branchName: "claude/pr-456-20240101_120000", branchName: "claude/pr-456-20240101-1200",
prLink: prLink:
"\n[Create a PR](https://github.com/owner/repo/compare/main...claude/pr-456-20240101_120000)", "\n[Create a PR](https://github.com/owner/repo/compare/main...claude/pr-456-20240101-1200)",
triggerUsername: "jane-doe", triggerUsername: "jane-doe",
}; };
@@ -391,7 +394,7 @@ describe("updateCommentBody", () => {
// Should include the PR link in the formatted style // Should include the PR link in the formatted style
expect(result).toContain( expect(result).toContain(
"• [Create PR ➔](https://github.com/owner/repo/compare/main...claude/pr-456-20240101_120000)", "• [Create PR ➔](https://github.com/owner/repo/compare/main...claude/pr-456-20240101-1200)",
); );
expect(result).toContain("**Claude finished @jane-doe's task**"); expect(result).toContain("**Claude finished @jane-doe's task**");
}); });
@@ -400,22 +403,44 @@ describe("updateCommentBody", () => {
const input = { const input = {
...baseInput, ...baseInput,
currentBody: "Claude Code is working…", currentBody: "Claude Code is working…",
branchName: "claude/issue-123-20240101_120000", branchName: "claude/issue-123-20240101-1200",
branchLink: branchLink:
"\n[View branch](https://github.com/owner/repo/tree/claude/issue-123-20240101_120000)", "\n[View branch](https://github.com/owner/repo/tree/claude/issue-123-20240101-1200)",
prLink: prLink:
"\n[Create a PR](https://github.com/owner/repo/compare/main...claude/issue-123-20240101_120000)", "\n[Create a PR](https://github.com/owner/repo/compare/main...claude/issue-123-20240101-1200)",
}; };
const result = updateCommentBody(input); const result = updateCommentBody(input);
// Should include both links in formatted style // Should include both links in formatted style
expect(result).toContain( expect(result).toContain(
"• [`claude/issue-123-20240101_120000`](https://github.com/owner/repo/tree/claude/issue-123-20240101_120000)", "• [`claude/issue-123-20240101-1200`](https://github.com/owner/repo/tree/claude/issue-123-20240101-1200)",
); );
expect(result).toContain( expect(result).toContain(
"• [Create PR ➔](https://github.com/owner/repo/compare/main...claude/issue-123-20240101_120000)", "• [Create PR ➔](https://github.com/owner/repo/compare/main...claude/issue-123-20240101-1200)",
); );
}); });
it("should not show branch name when branch doesn't exist remotely", () => {
const input: CommentUpdateInput = {
currentBody: "@claude can you help with this?",
actionFailed: false,
executionDetails: { duration_ms: 90000 },
jobUrl: "https://github.com/owner/repo/actions/runs/123",
branchLink: "", // Empty branch link means branch doesn't exist remotely
branchName: undefined, // Should be undefined when branchLink is empty
triggerUsername: "claude",
prLink: "",
};
const result = updateCommentBody(input);
expect(result).toContain("Claude finished @claude's task in 1m 30s");
expect(result).toContain(
"[View job](https://github.com/owner/repo/actions/runs/123)",
);
expect(result).not.toContain("claude/issue-123");
expect(result).not.toContain("tree/claude/issue-123");
});
}); });
}); });

View File

@@ -127,13 +127,13 @@ describe("generatePrompt", () => {
commentId: "67890", commentId: "67890",
isPR: false, isPR: false,
baseBranch: "main", baseBranch: "main",
claudeBranch: "claude/issue-67890-20240101_120000", claudeBranch: "claude/issue-67890-20240101-1200",
issueNumber: "67890", issueNumber: "67890",
commentBody: "@claude please fix this", commentBody: "@claude please fix this",
}, },
}; };
const prompt = generatePrompt(envVars, mockGitHubData); const prompt = generatePrompt(envVars, mockGitHubData, false);
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 +161,7 @@ describe("generatePrompt", () => {
}, },
}; };
const prompt = generatePrompt(envVars, mockGitHubData); const prompt = generatePrompt(envVars, mockGitHubData, false);
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>");
@@ -183,11 +183,11 @@ describe("generatePrompt", () => {
isPR: false, isPR: false,
issueNumber: "789", issueNumber: "789",
baseBranch: "main", baseBranch: "main",
claudeBranch: "claude/issue-789-20240101_120000", claudeBranch: "claude/issue-789-20240101-1200",
}, },
}; };
const prompt = generatePrompt(envVars, mockGitHubData); const prompt = generatePrompt(envVars, mockGitHubData, false);
expect(prompt).toContain("<event_type>ISSUE_CREATED</event_type>"); expect(prompt).toContain("<event_type>ISSUE_CREATED</event_type>");
expect(prompt).toContain( expect(prompt).toContain(
@@ -210,12 +210,12 @@ describe("generatePrompt", () => {
isPR: false, isPR: false,
issueNumber: "999", issueNumber: "999",
baseBranch: "develop", baseBranch: "develop",
claudeBranch: "claude/issue-999-20240101_120000", claudeBranch: "claude/issue-999-20240101-1200",
assigneeTrigger: "claude-bot", assigneeTrigger: "claude-bot",
}, },
}; };
const prompt = generatePrompt(envVars, mockGitHubData); const prompt = generatePrompt(envVars, mockGitHubData, false);
expect(prompt).toContain("<event_type>ISSUE_ASSIGNED</event_type>"); expect(prompt).toContain("<event_type>ISSUE_ASSIGNED</event_type>");
expect(prompt).toContain( expect(prompt).toContain(
@@ -226,6 +226,33 @@ describe("generatePrompt", () => {
); );
}); });
test("should generate prompt for issue labeled event", () => {
const envVars: PreparedContext = {
repository: "owner/repo",
claudeCommentId: "12345",
triggerPhrase: "@claude",
eventData: {
eventName: "issues",
eventAction: "labeled",
isPR: false,
issueNumber: "888",
baseBranch: "main",
claudeBranch: "claude/issue-888-20240101-1200",
labelTrigger: "claude-task",
},
};
const prompt = generatePrompt(envVars, mockGitHubData, false);
expect(prompt).toContain("<event_type>ISSUE_LABELED</event_type>");
expect(prompt).toContain(
"<trigger_context>issue labeled with 'claude-task'</trigger_context>",
);
expect(prompt).toContain(
"[Create a PR](https://github.com/owner/repo/compare/main",
);
});
test("should include direct prompt when provided", () => { test("should include direct prompt when provided", () => {
const envVars: PreparedContext = { const envVars: PreparedContext = {
repository: "owner/repo", repository: "owner/repo",
@@ -238,11 +265,11 @@ describe("generatePrompt", () => {
isPR: false, isPR: false,
issueNumber: "789", issueNumber: "789",
baseBranch: "main", baseBranch: "main",
claudeBranch: "claude/issue-789-20240101_120000", claudeBranch: "claude/issue-789-20240101-1200",
}, },
}; };
const prompt = generatePrompt(envVars, mockGitHubData); const prompt = generatePrompt(envVars, mockGitHubData, false);
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");
@@ -265,7 +292,7 @@ describe("generatePrompt", () => {
}, },
}; };
const prompt = generatePrompt(envVars, mockGitHubData); const prompt = generatePrompt(envVars, mockGitHubData, false);
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>");
@@ -285,12 +312,12 @@ describe("generatePrompt", () => {
isPR: false, isPR: false,
issueNumber: "123", issueNumber: "123",
baseBranch: "main", baseBranch: "main",
claudeBranch: "claude/issue-67890-20240101_120000", claudeBranch: "claude/issue-67890-20240101-1200",
commentBody: "@claude please fix this", commentBody: "@claude please fix this",
}, },
}; };
const prompt = generatePrompt(envVars, mockGitHubData); const prompt = generatePrompt(envVars, mockGitHubData, false);
expect(prompt).toContain("CUSTOM INSTRUCTIONS:\nAlways use TypeScript"); expect(prompt).toContain("CUSTOM INSTRUCTIONS:\nAlways use TypeScript");
}); });
@@ -307,14 +334,15 @@ describe("generatePrompt", () => {
isPR: false, isPR: false,
issueNumber: "123", issueNumber: "123",
baseBranch: "main", baseBranch: "main",
claudeBranch: "claude/issue-67890-20240101_120000", claudeBranch: "claude/issue-67890-20240101-1200",
commentBody: "@claude please fix this", commentBody: "@claude please fix this",
}, },
}; };
const prompt = generatePrompt(envVars, mockGitHubData); const prompt = generatePrompt(envVars, mockGitHubData, false);
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
expect(prompt).toContain( expect(prompt).toContain(
"Co-authored-by: johndoe <johndoe@users.noreply.github.com>", "Co-authored-by: johndoe <johndoe@users.noreply.github.com>",
); );
@@ -333,12 +361,10 @@ describe("generatePrompt", () => {
}, },
}; };
const prompt = generatePrompt(envVars, mockGitHubData); const prompt = generatePrompt(envVars, mockGitHubData, false);
// Should contain PR-specific instructions // Should contain PR-specific instructions (git commands when not using signing)
expect(prompt).toContain( expect(prompt).toContain("git push");
"Push directly using mcp__github_file_ops__commit_files to the existing branch",
);
expect(prompt).toContain( expect(prompt).toContain(
"Always push to the existing branch when triggered on a PR", "Always push to the existing branch when triggered on a PR",
); );
@@ -362,18 +388,18 @@ describe("generatePrompt", () => {
isPR: false, isPR: false,
issueNumber: "789", issueNumber: "789",
baseBranch: "main", baseBranch: "main",
claudeBranch: "claude/issue-789-20240101_120000", claudeBranch: "claude/issue-789-20240101-1200",
}, },
}; };
const prompt = generatePrompt(envVars, mockGitHubData); const prompt = generatePrompt(envVars, mockGitHubData, false);
// Should contain Issue-specific instructions // Should contain Issue-specific instructions
expect(prompt).toContain( expect(prompt).toContain(
"You are already on the correct branch (claude/issue-789-20240101_120000)", "You are already on the correct branch (claude/issue-789-20240101-1200)",
); );
expect(prompt).toContain( expect(prompt).toContain(
"IMPORTANT: You are already on the correct branch (claude/issue-789-20240101_120000)", "IMPORTANT: You are already on the correct branch (claude/issue-789-20240101-1200)",
); );
expect(prompt).toContain("Create a PR](https://github.com/"); expect(prompt).toContain("Create a PR](https://github.com/");
expect(prompt).toContain( expect(prompt).toContain(
@@ -400,22 +426,22 @@ describe("generatePrompt", () => {
isPR: false, isPR: false,
issueNumber: "123", issueNumber: "123",
baseBranch: "main", baseBranch: "main",
claudeBranch: "claude/issue-123-20240101_120000", claudeBranch: "claude/issue-123-20240101-1200",
commentBody: "@claude please fix this", commentBody: "@claude please fix this",
}, },
}; };
const prompt = generatePrompt(envVars, mockGitHubData); const prompt = generatePrompt(envVars, mockGitHubData, false);
// Should contain the actual branch name with timestamp // Should contain the actual branch name with timestamp
expect(prompt).toContain( expect(prompt).toContain(
"You are already on the correct branch (claude/issue-123-20240101_120000)", "You are already on the correct branch (claude/issue-123-20240101-1200)",
); );
expect(prompt).toContain( expect(prompt).toContain(
"IMPORTANT: You are already on the correct branch (claude/issue-123-20240101_120000)", "IMPORTANT: You are already on the correct branch (claude/issue-123-20240101-1200)",
); );
expect(prompt).toContain( expect(prompt).toContain(
"The branch-name is the current branch: claude/issue-123-20240101_120000", "The branch-name is the current branch: claude/issue-123-20240101-1200",
); );
}); });
@@ -430,22 +456,22 @@ describe("generatePrompt", () => {
isPR: true, isPR: true,
prNumber: "456", prNumber: "456",
commentBody: "@claude please fix this", commentBody: "@claude please fix this",
claudeBranch: "claude/pr-456-20240101_120000", claudeBranch: "claude/pr-456-20240101-1200",
baseBranch: "main", baseBranch: "main",
}, },
}; };
const prompt = generatePrompt(envVars, mockGitHubData); const prompt = generatePrompt(envVars, mockGitHubData, false);
// Should contain branch-specific instructions like issues // Should contain branch-specific instructions like issues
expect(prompt).toContain( expect(prompt).toContain(
"You are already on the correct branch (claude/pr-456-20240101_120000)", "You are already on the correct branch (claude/pr-456-20240101-1200)",
); );
expect(prompt).toContain( expect(prompt).toContain(
"Create a PR](https://github.com/owner/repo/compare/main", "Create a PR](https://github.com/owner/repo/compare/main",
); );
expect(prompt).toContain( expect(prompt).toContain(
"The branch-name is the current branch: claude/pr-456-20240101_120000", "The branch-name is the current branch: claude/pr-456-20240101-1200",
); );
expect(prompt).toContain("Reference to the original PR"); expect(prompt).toContain("Reference to the original PR");
expect(prompt).toContain( expect(prompt).toContain(
@@ -473,12 +499,10 @@ describe("generatePrompt", () => {
}, },
}; };
const prompt = generatePrompt(envVars, mockGitHubData); const prompt = generatePrompt(envVars, mockGitHubData, false);
// Should contain open PR instructions // Should contain open PR instructions (git commands when not using signing)
expect(prompt).toContain( expect(prompt).toContain("git push");
"Push directly using mcp__github_file_ops__commit_files to the existing branch",
);
expect(prompt).toContain( expect(prompt).toContain(
"Always push to the existing branch when triggered on a PR", "Always push to the existing branch when triggered on a PR",
); );
@@ -501,16 +525,16 @@ describe("generatePrompt", () => {
isPR: true, isPR: true,
prNumber: "789", prNumber: "789",
commentBody: "@claude please update this", commentBody: "@claude please update this",
claudeBranch: "claude/pr-789-20240101_123000", claudeBranch: "claude/pr-789-20240101-1230",
baseBranch: "develop", baseBranch: "develop",
}, },
}; };
const prompt = generatePrompt(envVars, mockGitHubData); const prompt = generatePrompt(envVars, mockGitHubData, false);
// Should contain new branch instructions // Should contain new branch instructions
expect(prompt).toContain( expect(prompt).toContain(
"You are already on the correct branch (claude/pr-789-20240101_123000)", "You are already on the correct branch (claude/pr-789-20240101-1230)",
); );
expect(prompt).toContain( expect(prompt).toContain(
"Create a PR](https://github.com/owner/repo/compare/develop", "Create a PR](https://github.com/owner/repo/compare/develop",
@@ -529,16 +553,16 @@ describe("generatePrompt", () => {
prNumber: "999", prNumber: "999",
commentId: "review-comment-123", commentId: "review-comment-123",
commentBody: "@claude fix this issue", commentBody: "@claude fix this issue",
claudeBranch: "claude/pr-999-20240101_140000", claudeBranch: "claude/pr-999-20240101-1400",
baseBranch: "main", baseBranch: "main",
}, },
}; };
const prompt = generatePrompt(envVars, mockGitHubData); const prompt = generatePrompt(envVars, mockGitHubData, false);
// Should contain new branch instructions // Should contain new branch instructions
expect(prompt).toContain( expect(prompt).toContain(
"You are already on the correct branch (claude/pr-999-20240101_140000)", "You are already on the correct branch (claude/pr-999-20240101-1400)",
); );
expect(prompt).toContain("Create a PR](https://github.com/"); expect(prompt).toContain("Create a PR](https://github.com/");
expect(prompt).toContain("Reference to the original PR"); expect(prompt).toContain("Reference to the original PR");
@@ -557,20 +581,75 @@ describe("generatePrompt", () => {
eventAction: "closed", eventAction: "closed",
isPR: true, isPR: true,
prNumber: "555", prNumber: "555",
claudeBranch: "claude/pr-555-20240101_150000", claudeBranch: "claude/pr-555-20240101-1500",
baseBranch: "main", baseBranch: "main",
}, },
}; };
const prompt = generatePrompt(envVars, mockGitHubData); const prompt = generatePrompt(envVars, mockGitHubData, false);
// Should contain new branch instructions // Should contain new branch instructions
expect(prompt).toContain( expect(prompt).toContain(
"You are already on the correct branch (claude/pr-555-20240101_150000)", "You are already on the correct branch (claude/pr-555-20240101-1500)",
); );
expect(prompt).toContain("Create a PR](https://github.com/"); expect(prompt).toContain("Create a PR](https://github.com/");
expect(prompt).toContain("Reference to the original PR"); expect(prompt).toContain("Reference to the original PR");
}); });
test("should include git commands when useCommitSigning is false", () => {
const envVars: PreparedContext = {
repository: "owner/repo",
claudeCommentId: "12345",
triggerPhrase: "@claude",
eventData: {
eventName: "issue_comment",
commentId: "67890",
isPR: true,
prNumber: "123",
commentBody: "@claude fix the bug",
},
};
const prompt = generatePrompt(envVars, mockGitHubData, false);
// Should have git command instructions
expect(prompt).toContain("Use git commands via the Bash tool");
expect(prompt).toContain("git add");
expect(prompt).toContain("git commit");
expect(prompt).toContain("git push");
// Should use the minimal comment tool
expect(prompt).toContain("mcp__github_comment__update_claude_comment");
// Should not have commit signing tool references
expect(prompt).not.toContain("mcp__github_file_ops__commit_files");
});
test("should include commit signing tools when useCommitSigning is true", () => {
const envVars: PreparedContext = {
repository: "owner/repo",
claudeCommentId: "12345",
triggerPhrase: "@claude",
eventData: {
eventName: "issue_comment",
commentId: "67890",
isPR: true,
prNumber: "123",
commentBody: "@claude fix the bug",
},
};
const prompt = generatePrompt(envVars, mockGitHubData, true);
// Should have commit signing tool instructions
expect(prompt).toContain("mcp__github_file_ops__commit_files");
expect(prompt).toContain("mcp__github_file_ops__delete_files");
// Comment tool should always be from comment server, not file ops
expect(prompt).toContain("mcp__github_comment__update_claude_comment");
// Should not have git command instructions
expect(prompt).not.toContain("Use git commands via the Bash tool");
});
}); });
describe("getEventTypeAndContext", () => { describe("getEventTypeAndContext", () => {
@@ -604,7 +683,7 @@ describe("getEventTypeAndContext", () => {
isPR: false, isPR: false,
issueNumber: "999", issueNumber: "999",
baseBranch: "main", baseBranch: "main",
claudeBranch: "claude/issue-999-20240101_120000", claudeBranch: "claude/issue-999-20240101-1200",
assigneeTrigger: "claude-bot", assigneeTrigger: "claude-bot",
}, },
}; };
@@ -614,10 +693,55 @@ describe("getEventTypeAndContext", () => {
expect(result.eventType).toBe("ISSUE_ASSIGNED"); expect(result.eventType).toBe("ISSUE_ASSIGNED");
expect(result.triggerContext).toBe("issue assigned to 'claude-bot'"); expect(result.triggerContext).toBe("issue assigned to 'claude-bot'");
}); });
test("should return correct type and context for issue labeled", () => {
const envVars: PreparedContext = {
repository: "owner/repo",
claudeCommentId: "12345",
triggerPhrase: "@claude",
eventData: {
eventName: "issues",
eventAction: "labeled",
isPR: false,
issueNumber: "888",
baseBranch: "main",
claudeBranch: "claude/issue-888-20240101-1200",
labelTrigger: "claude-task",
},
};
const result = getEventTypeAndContext(envVars);
expect(result.eventType).toBe("ISSUE_LABELED");
expect(result.triggerContext).toBe("issue labeled with 'claude-task'");
});
test("should return correct type and context for issue assigned without assigneeTrigger", () => {
const envVars: PreparedContext = {
repository: "owner/repo",
claudeCommentId: "12345",
triggerPhrase: "@claude",
directPrompt: "Please assess this issue",
eventData: {
eventName: "issues",
eventAction: "assigned",
isPR: false,
issueNumber: "999",
baseBranch: "main",
claudeBranch: "claude/issue-999-20240101-1200",
// No assigneeTrigger when using directPrompt
},
};
const result = getEventTypeAndContext(envVars);
expect(result.eventType).toBe("ISSUE_ASSIGNED");
expect(result.triggerContext).toBe("issue assigned event");
});
}); });
describe("buildAllowedToolsString", () => { describe("buildAllowedToolsString", () => {
test("should return issue comment tool for regular events", () => { test("should return correct tools for regular events (default no signing)", () => {
const result = buildAllowedToolsString(); const result = buildAllowedToolsString();
// The base tools should be in the result // The base tools should be in the result
@@ -627,15 +751,20 @@ describe("buildAllowedToolsString", () => {
expect(result).toContain("LS"); expect(result).toContain("LS");
expect(result).toContain("Read"); expect(result).toContain("Read");
expect(result).toContain("Write"); expect(result).toContain("Write");
expect(result).toContain("mcp__github_file_ops__update_claude_comment");
expect(result).not.toContain("mcp__github__update_issue_comment"); // Default is no commit signing, so should have specific Bash git commands
expect(result).not.toContain("mcp__github__update_pull_request_comment"); expect(result).toContain("Bash(git add:*)");
expect(result).toContain("mcp__github_file_ops__commit_files"); expect(result).toContain("Bash(git commit:*)");
expect(result).toContain("mcp__github_file_ops__delete_files"); expect(result).toContain("Bash(git push:*)");
expect(result).toContain("mcp__github_comment__update_claude_comment");
// Should not have commit signing tools
expect(result).not.toContain("mcp__github_file_ops__commit_files");
expect(result).not.toContain("mcp__github_file_ops__delete_files");
}); });
test("should return PR comment tool for inline review comments", () => { test("should return correct tools with default parameters", () => {
const result = buildAllowedToolsString(); const result = buildAllowedToolsString([], false, false);
// The base tools should be in the result // The base tools should be in the result
expect(result).toContain("Edit"); expect(result).toContain("Edit");
@@ -644,15 +773,19 @@ describe("buildAllowedToolsString", () => {
expect(result).toContain("LS"); expect(result).toContain("LS");
expect(result).toContain("Read"); expect(result).toContain("Read");
expect(result).toContain("Write"); expect(result).toContain("Write");
expect(result).toContain("mcp__github_file_ops__update_claude_comment");
expect(result).not.toContain("mcp__github__update_issue_comment"); // Should have specific Bash git commands for non-signing mode
expect(result).not.toContain("mcp__github__update_pull_request_comment"); expect(result).toContain("Bash(git add:*)");
expect(result).toContain("mcp__github_file_ops__commit_files"); expect(result).toContain("Bash(git commit:*)");
expect(result).toContain("mcp__github_file_ops__delete_files"); expect(result).toContain("mcp__github_comment__update_claude_comment");
// Should not have commit signing tools
expect(result).not.toContain("mcp__github_file_ops__commit_files");
expect(result).not.toContain("mcp__github_file_ops__delete_files");
}); });
test("should append custom tools when provided", () => { test("should append custom tools when provided", () => {
const customTools = "Tool1,Tool2,Tool3"; const customTools = ["Tool1", "Tool2", "Tool3"];
const result = buildAllowedToolsString(customTools); const result = buildAllowedToolsString(customTools);
// Base tools should be present // Base tools should be present
@@ -671,6 +804,109 @@ describe("buildAllowedToolsString", () => {
expect(basePlusCustom).toContain("Tool2"); expect(basePlusCustom).toContain("Tool2");
expect(basePlusCustom).toContain("Tool3"); expect(basePlusCustom).toContain("Tool3");
}); });
test("should include GitHub Actions tools when includeActionsTools is true", () => {
const result = buildAllowedToolsString([], true);
// Base tools should be present
expect(result).toContain("Edit");
expect(result).toContain("Glob");
// GitHub Actions tools should be included
expect(result).toContain("mcp__github_ci__get_ci_status");
expect(result).toContain("mcp__github_ci__get_workflow_run_details");
expect(result).toContain("mcp__github_ci__download_job_log");
});
test("should include both custom and Actions tools when both provided", () => {
const customTools = ["Tool1", "Tool2"];
const result = buildAllowedToolsString(customTools, true);
// Base tools should be present
expect(result).toContain("Edit");
// Custom tools should be included
expect(result).toContain("Tool1");
expect(result).toContain("Tool2");
// GitHub Actions tools should be included
expect(result).toContain("mcp__github_ci__get_ci_status");
expect(result).toContain("mcp__github_ci__get_workflow_run_details");
expect(result).toContain("mcp__github_ci__download_job_log");
});
test("should include commit signing tools when useCommitSigning is true", () => {
const result = buildAllowedToolsString([], false, true);
// Base tools should be present
expect(result).toContain("Edit");
expect(result).toContain("Glob");
expect(result).toContain("Grep");
expect(result).toContain("LS");
expect(result).toContain("Read");
expect(result).toContain("Write");
// Commit signing tools should be included
expect(result).toContain("mcp__github_file_ops__commit_files");
expect(result).toContain("mcp__github_file_ops__delete_files");
// Comment tool should always be from github_comment server
expect(result).toContain("mcp__github_comment__update_claude_comment");
// Bash should NOT be included when using commit signing (except in comment tool name)
expect(result).not.toContain("Bash(");
});
test("should include specific Bash git commands when useCommitSigning is false", () => {
const result = buildAllowedToolsString([], false, false);
// Base tools should be present
expect(result).toContain("Edit");
expect(result).toContain("Glob");
expect(result).toContain("Grep");
expect(result).toContain("LS");
expect(result).toContain("Read");
expect(result).toContain("Write");
// Specific Bash git commands should be included
expect(result).toContain("Bash(git add:*)");
expect(result).toContain("Bash(git commit:*)");
expect(result).toContain("Bash(git push:*)");
expect(result).toContain("Bash(git status:*)");
expect(result).toContain("Bash(git diff:*)");
expect(result).toContain("Bash(git log:*)");
expect(result).toContain("Bash(git rm:*)");
expect(result).toContain("Bash(git config user.name:*)");
expect(result).toContain("Bash(git config user.email:*)");
// Comment tool from minimal server should be included
expect(result).toContain("mcp__github_comment__update_claude_comment");
// Commit signing tools should NOT be included
expect(result).not.toContain("mcp__github_file_ops__commit_files");
expect(result).not.toContain("mcp__github_file_ops__delete_files");
});
test("should handle all combinations of options", () => {
const customTools = ["CustomTool1", "CustomTool2"];
const result = buildAllowedToolsString(customTools, true, false);
// Base tools should be present
expect(result).toContain("Edit");
expect(result).toContain("Bash(git add:*)");
// Custom tools should be included
expect(result).toContain("CustomTool1");
expect(result).toContain("CustomTool2");
// GitHub Actions tools should be included
expect(result).toContain("mcp__github_ci__get_ci_status");
// Comment tool from minimal server should be included
expect(result).toContain("mcp__github_comment__update_claude_comment");
// Commit signing tools should NOT be included
expect(result).not.toContain("mcp__github_file_ops__commit_files");
});
}); });
describe("buildDisallowedToolsString", () => { describe("buildDisallowedToolsString", () => {
@@ -683,7 +919,7 @@ describe("buildDisallowedToolsString", () => {
}); });
test("should append custom disallowed tools when provided", () => { test("should append custom disallowed tools when provided", () => {
const customDisallowedTools = "BadTool1,BadTool2"; const customDisallowedTools = ["BadTool1", "BadTool2"];
const result = buildDisallowedToolsString(customDisallowedTools); const result = buildDisallowedToolsString(customDisallowedTools);
// Base disallowed tools should be present // Base disallowed tools should be present
@@ -701,8 +937,8 @@ describe("buildDisallowedToolsString", () => {
}); });
test("should remove hardcoded disallowed tools if they are in allowed tools", () => { test("should remove hardcoded disallowed tools if they are in allowed tools", () => {
const customDisallowedTools = "BadTool1,BadTool2"; const customDisallowedTools = ["BadTool1", "BadTool2"];
const allowedTools = "WebSearch,SomeOtherTool"; const allowedTools = ["WebSearch", "SomeOtherTool"];
const result = buildDisallowedToolsString( const result = buildDisallowedToolsString(
customDisallowedTools, customDisallowedTools,
allowedTools, allowedTools,
@@ -720,7 +956,7 @@ describe("buildDisallowedToolsString", () => {
}); });
test("should remove all hardcoded disallowed tools if they are all in allowed tools", () => { test("should remove all hardcoded disallowed tools if they are all in allowed tools", () => {
const allowedTools = "WebSearch,WebFetch,SomeOtherTool"; const allowedTools = ["WebSearch", "WebFetch", "SomeOtherTool"];
const result = buildDisallowedToolsString(undefined, allowedTools); const result = buildDisallowedToolsString(undefined, allowedTools);
// Both hardcoded disallowed tools should be removed // Both hardcoded disallowed tools should be removed
@@ -732,8 +968,8 @@ describe("buildDisallowedToolsString", () => {
}); });
test("should handle custom disallowed tools when all hardcoded tools are overridden", () => { test("should handle custom disallowed tools when all hardcoded tools are overridden", () => {
const customDisallowedTools = "BadTool1,BadTool2"; const customDisallowedTools = ["BadTool1", "BadTool2"];
const allowedTools = "WebSearch,WebFetch"; const allowedTools = ["WebSearch", "WebFetch"];
const result = buildDisallowedToolsString( const result = buildDisallowedToolsString(
customDisallowedTools, customDisallowedTools,
allowedTools, allowedTools,

View File

@@ -0,0 +1,95 @@
## Claude Code Report
## 🚀 System Initialization
**Available Tools:** 8 tools loaded
---
I'll help you with this task. Let me start by examining the file to understand what needs to be changed.
### 🔧 `Read`
**Parameters:**
```json
{
"file_path": "/path/to/sample/file.py"
}
```
**Result:**
```python
def example_function():
print("Debug message") # This should be removed
return "Hello World"
if __name__ == "__main__":
result = example_function()
print(result)
```
*Token usage: 100 input, 75 output*
---
I can see the debug print statement that needs to be removed. Let me fix this by editing the file.
### 🔧 `Edit`
**Parameters:**
```json
{
"file_path": "/path/to/sample/file.py",
"old_string": "def example_function():\n print(\"Debug message\") # This should be removed\n return \"Hello World\"",
"new_string": "def example_function():\n return \"Hello World\""
}
```
**→** File successfully edited. The debug print statement has been removed.
*Token usage: 200 input, 50 output*
---
Perfect! I've successfully removed the debug print statement from the function. Let me now create a pull request comment to document this change.
### 🔧 `mcp__github__add_pull_request_review_comment`
**Parameters:**
```json
{
"owner": "example-org",
"repo": "example-repo",
"pull_number": 123,
"body": "Removed debug print statement as requested.",
"commit_id": "abc123def456",
"path": "sample/file.py",
"line": 2
}
```
**→** Successfully posted review comment to PR #123
*Token usage: 150 input, 80 output*
---
Great! I've successfully completed the requested task:
1. ✅ Located the debug print statement in the file
2. ✅ Removed the print statement while preserving the function logic
3. ✅ Added a review comment documenting the change
The debug print statement has been removed as requested by the reviewers.
*Token usage: 180 input, 60 output*
---
## ✅ Final Result
Successfully removed debug print statement from file and added review comment to document the change.
**Cost:** $0.0347 | **Duration:** 18.8s

196
test/fixtures/sample-turns.json vendored Normal file
View File

@@ -0,0 +1,196 @@
[
{
"type": "system",
"subtype": "init",
"session_id": "sample-session-id",
"tools": [
"Task",
"Bash",
"Read",
"Edit",
"Write",
"mcp__github__get_file_contents",
"mcp__github__create_or_update_file",
"mcp__github__add_pull_request_review_comment"
],
"mcp_servers": [
{
"name": "github",
"status": "connected"
}
]
},
{
"type": "assistant",
"message": {
"id": "msg_sample123",
"type": "message",
"role": "assistant",
"model": "claude-test-model",
"content": [
{
"type": "text",
"text": "I'll help you with this task. Let me start by examining the file to understand what needs to be changed."
},
{
"type": "tool_use",
"id": "tool_call_1",
"name": "Read",
"input": {
"file_path": "/path/to/sample/file.py"
}
}
],
"stop_reason": "tool_use",
"stop_sequence": null,
"usage": {
"input_tokens": 100,
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 50,
"output_tokens": 75
}
},
"session_id": "sample-session-id"
},
{
"type": "user",
"message": {
"content": [
{
"type": "tool_result",
"tool_use_id": "tool_call_1",
"content": "def example_function():\n print(\"Debug message\") # This should be removed\n return \"Hello World\"\n\nif __name__ == \"__main__\":\n result = example_function()\n print(result)",
"is_error": false
}
]
}
},
{
"type": "assistant",
"message": {
"id": "msg_sample124",
"type": "message",
"role": "assistant",
"model": "claude-test-model",
"content": [
{
"type": "text",
"text": "I can see the debug print statement that needs to be removed. Let me fix this by editing the file."
},
{
"type": "tool_use",
"id": "tool_call_2",
"name": "Edit",
"input": {
"file_path": "/path/to/sample/file.py",
"old_string": "def example_function():\n print(\"Debug message\") # This should be removed\n return \"Hello World\"",
"new_string": "def example_function():\n return \"Hello World\""
}
}
],
"stop_reason": "tool_use",
"stop_sequence": null,
"usage": {
"input_tokens": 200,
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 100,
"output_tokens": 50
}
},
"session_id": "sample-session-id"
},
{
"type": "user",
"message": {
"content": [
{
"type": "tool_result",
"tool_use_id": "tool_call_2",
"content": "File successfully edited. The debug print statement has been removed.",
"is_error": false
}
]
}
},
{
"type": "assistant",
"message": {
"id": "msg_sample125",
"type": "message",
"role": "assistant",
"model": "claude-test-model",
"content": [
{
"type": "text",
"text": "Perfect! I've successfully removed the debug print statement from the function. Let me now create a pull request comment to document this change."
},
{
"type": "tool_use",
"id": "tool_call_3",
"name": "mcp__github__add_pull_request_review_comment",
"input": {
"owner": "example-org",
"repo": "example-repo",
"pull_number": 123,
"body": "Removed debug print statement as requested.",
"commit_id": "abc123def456",
"path": "sample/file.py",
"line": 2
}
}
],
"stop_reason": "tool_use",
"stop_sequence": null,
"usage": {
"input_tokens": 150,
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 75,
"output_tokens": 80
}
},
"session_id": "sample-session-id"
},
{
"type": "user",
"message": {
"content": [
{
"type": "tool_result",
"tool_use_id": "tool_call_3",
"content": "Successfully posted review comment to PR #123",
"is_error": false
}
]
}
},
{
"type": "assistant",
"message": {
"id": "msg_sample126",
"type": "message",
"role": "assistant",
"model": "claude-test-model",
"content": [
{
"type": "text",
"text": "Great! I've successfully completed the requested task:\n\n1. ✅ Located the debug print statement in the file\n2. ✅ Removed the print statement while preserving the function logic\n3. ✅ Added a review comment documenting the change\n\nThe debug print statement has been removed as requested by the reviewers."
}
],
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {
"input_tokens": 180,
"cache_creation_input_tokens": 0,
"cache_read_input_tokens": 90,
"output_tokens": 60
}
},
"session_id": "sample-session-id"
},
{
"type": "result",
"cost_usd": 0.0347,
"duration_ms": 18750,
"result": "Successfully removed debug print statement from file and added review comment to document the change."
}
]

439
test/format-turns.test.ts Normal file
View File

@@ -0,0 +1,439 @@
import { expect, test, describe } from "bun:test";
import { readFileSync } from "fs";
import { join } from "path";
import {
formatTurnsFromData,
groupTurnsNaturally,
formatGroupedContent,
detectContentType,
formatResultContent,
formatToolWithResult,
type Turn,
type ToolUse,
type ToolResult,
} from "../src/entrypoints/format-turns";
describe("detectContentType", () => {
test("detects JSON objects", () => {
expect(detectContentType('{"key": "value"}')).toBe("json");
expect(detectContentType('{"number": 42}')).toBe("json");
});
test("detects JSON arrays", () => {
expect(detectContentType("[1, 2, 3]")).toBe("json");
expect(detectContentType('["a", "b"]')).toBe("json");
});
test("detects Python code", () => {
expect(detectContentType("def hello():\n pass")).toBe("python");
expect(detectContentType("import os")).toBe("python");
expect(detectContentType("from math import pi")).toBe("python");
});
test("detects JavaScript code", () => {
expect(detectContentType("function test() {}")).toBe("javascript");
expect(detectContentType("const x = 5")).toBe("javascript");
expect(detectContentType("let y = 10")).toBe("javascript");
expect(detectContentType("const fn = () => console.log()")).toBe(
"javascript",
);
});
test("detects bash/shell content", () => {
expect(detectContentType("/usr/bin/test")).toBe("bash");
expect(detectContentType("Error: command not found")).toBe("bash");
expect(detectContentType("ls -la")).toBe("bash");
expect(detectContentType("$ echo hello")).toBe("bash");
});
test("detects diff format", () => {
expect(detectContentType("@@ -1,3 +1,3 @@")).toBe("diff");
expect(detectContentType("+++ file.txt")).toBe("diff");
expect(detectContentType("--- file.txt")).toBe("diff");
});
test("detects HTML/XML", () => {
expect(detectContentType("<div>hello</div>")).toBe("html");
expect(detectContentType("<xml>content</xml>")).toBe("html");
});
test("detects markdown", () => {
expect(detectContentType("- List item")).toBe("markdown");
expect(detectContentType("* List item")).toBe("markdown");
expect(detectContentType("```code```")).toBe("markdown");
});
test("defaults to text", () => {
expect(detectContentType("plain text")).toBe("text");
expect(detectContentType("just some words")).toBe("text");
});
});
describe("formatResultContent", () => {
test("handles empty content", () => {
expect(formatResultContent("")).toBe("*(No output)*\n\n");
expect(formatResultContent(null)).toBe("*(No output)*\n\n");
expect(formatResultContent(undefined)).toBe("*(No output)*\n\n");
});
test("formats short text without code blocks", () => {
const result = formatResultContent("success");
expect(result).toBe("**→** success\n\n");
});
test("formats long text with code blocks", () => {
const longText =
"This is a longer piece of text that should be formatted in a code block because it exceeds the short text threshold";
const result = formatResultContent(longText);
expect(result).toContain("**Result:**");
expect(result).toContain("```text");
expect(result).toContain(longText);
});
test("pretty prints JSON content", () => {
const jsonContent = '{"key": "value", "number": 42}';
const result = formatResultContent(jsonContent);
expect(result).toContain("```json");
expect(result).toContain('"key": "value"');
expect(result).toContain('"number": 42');
});
test("truncates very long content", () => {
const veryLongContent = "A".repeat(4000);
const result = formatResultContent(veryLongContent);
expect(result).toContain("...");
// Should not contain the full long content
expect(result.length).toBeLessThan(veryLongContent.length);
});
test("handles type:text structure", () => {
const structuredContent = [{ type: "text", text: "Hello world" }];
const result = formatResultContent(JSON.stringify(structuredContent));
expect(result).toBe("**→** Hello world\n\n");
});
});
describe("formatToolWithResult", () => {
test("formats tool with parameters and result", () => {
const toolUse: ToolUse = {
type: "tool_use",
name: "read_file",
input: { file_path: "/path/to/file.txt" },
id: "tool_123",
};
const toolResult: ToolResult = {
type: "tool_result",
tool_use_id: "tool_123",
content: "File content here",
is_error: false,
};
const result = formatToolWithResult(toolUse, toolResult);
expect(result).toContain("### 🔧 `read_file`");
expect(result).toContain("**Parameters:**");
expect(result).toContain('"file_path": "/path/to/file.txt"');
expect(result).toContain("**→** File content here");
});
test("formats tool with error result", () => {
const toolUse: ToolUse = {
type: "tool_use",
name: "failing_tool",
input: { param: "value" },
};
const toolResult: ToolResult = {
type: "tool_result",
content: "Permission denied",
is_error: true,
};
const result = formatToolWithResult(toolUse, toolResult);
expect(result).toContain("### 🔧 `failing_tool`");
expect(result).toContain("❌ **Error:** `Permission denied`");
});
test("formats tool without parameters", () => {
const toolUse: ToolUse = {
type: "tool_use",
name: "simple_tool",
};
const result = formatToolWithResult(toolUse);
expect(result).toContain("### 🔧 `simple_tool`");
expect(result).not.toContain("**Parameters:**");
});
test("handles unknown tool name", () => {
const toolUse: ToolUse = {
type: "tool_use",
};
const result = formatToolWithResult(toolUse);
expect(result).toContain("### 🔧 `unknown_tool`");
});
});
describe("groupTurnsNaturally", () => {
test("groups system initialization", () => {
const data: Turn[] = [
{
type: "system",
subtype: "init",
tools: [{ name: "tool1" }, { name: "tool2" }],
},
];
const result = groupTurnsNaturally(data);
expect(result).toHaveLength(1);
expect(result[0]?.type).toBe("system_init");
expect(result[0]?.tools_count).toBe(2);
});
test("groups assistant actions with tool calls", () => {
const data: Turn[] = [
{
type: "assistant",
message: {
content: [
{ type: "text", text: "I'll help you" },
{
type: "tool_use",
id: "tool_123",
name: "read_file",
input: { file_path: "/test.txt" },
},
],
usage: { input_tokens: 100, output_tokens: 50 },
},
},
{
type: "user",
message: {
content: [
{
type: "tool_result",
tool_use_id: "tool_123",
content: "file content",
is_error: false,
},
],
},
},
];
const result = groupTurnsNaturally(data);
expect(result).toHaveLength(1);
expect(result[0]?.type).toBe("assistant_action");
expect(result[0]?.text_parts).toEqual(["I'll help you"]);
expect(result[0]?.tool_calls).toHaveLength(1);
expect(result[0]?.tool_calls?.[0]?.tool_use.name).toBe("read_file");
expect(result[0]?.tool_calls?.[0]?.tool_result?.content).toBe(
"file content",
);
expect(result[0]?.usage).toEqual({ input_tokens: 100, output_tokens: 50 });
});
test("groups user messages", () => {
const data: Turn[] = [
{
type: "user",
message: {
content: [{ type: "text", text: "Please help me" }],
},
},
];
const result = groupTurnsNaturally(data);
expect(result).toHaveLength(1);
expect(result[0]?.type).toBe("user_message");
expect(result[0]?.text_parts).toEqual(["Please help me"]);
});
test("groups final results", () => {
const data: Turn[] = [
{
type: "result",
cost_usd: 0.1234,
duration_ms: 5000,
result: "Task completed",
},
];
const result = groupTurnsNaturally(data);
expect(result).toHaveLength(1);
expect(result[0]?.type).toBe("final_result");
expect(result[0]?.data).toEqual(data[0]!);
});
});
describe("formatGroupedContent", () => {
test("formats system initialization", () => {
const groupedContent = [
{
type: "system_init",
tools_count: 3,
},
];
const result = formatGroupedContent(groupedContent);
expect(result).toContain("## Claude Code Report");
expect(result).toContain("## 🚀 System Initialization");
expect(result).toContain("**Available Tools:** 3 tools loaded");
});
test("formats assistant actions", () => {
const groupedContent = [
{
type: "assistant_action",
text_parts: ["I'll help you with that"],
tool_calls: [
{
tool_use: {
type: "tool_use",
name: "test_tool",
input: { param: "value" },
},
tool_result: {
type: "tool_result",
content: "result",
is_error: false,
},
},
],
usage: { input_tokens: 100, output_tokens: 50 },
},
];
const result = formatGroupedContent(groupedContent);
expect(result).toContain("I'll help you with that");
expect(result).toContain("### 🔧 `test_tool`");
expect(result).toContain("*Token usage: 100 input, 50 output*");
});
test("formats user messages", () => {
const groupedContent = [
{
type: "user_message",
text_parts: ["Help me please"],
},
];
const result = formatGroupedContent(groupedContent);
expect(result).toContain("## 👤 User");
expect(result).toContain("Help me please");
});
test("formats final results", () => {
const groupedContent = [
{
type: "final_result",
data: {
type: "result",
cost_usd: 0.1234,
duration_ms: 5678,
result: "Success!",
} as Turn,
},
];
const result = formatGroupedContent(groupedContent);
expect(result).toContain("## ✅ Final Result");
expect(result).toContain("Success!");
expect(result).toContain("**Cost:** $0.1234");
expect(result).toContain("**Duration:** 5.7s");
});
});
describe("formatTurnsFromData", () => {
test("handles empty data", () => {
const result = formatTurnsFromData([]);
expect(result).toBe("## Claude Code Report\n\n");
});
test("formats complete conversation", () => {
const data: Turn[] = [
{
type: "system",
subtype: "init",
tools: [{ name: "tool1" }],
},
{
type: "assistant",
message: {
content: [
{ type: "text", text: "I'll help you" },
{
type: "tool_use",
id: "tool_123",
name: "read_file",
input: { file_path: "/test.txt" },
},
],
},
},
{
type: "user",
message: {
content: [
{
type: "tool_result",
tool_use_id: "tool_123",
content: "file content",
is_error: false,
},
],
},
},
{
type: "result",
cost_usd: 0.05,
duration_ms: 2000,
result: "Done",
},
];
const result = formatTurnsFromData(data);
expect(result).toContain("## Claude Code Report");
expect(result).toContain("## 🚀 System Initialization");
expect(result).toContain("I'll help you");
expect(result).toContain("### 🔧 `read_file`");
expect(result).toContain("## ✅ Final Result");
expect(result).toContain("Done");
});
});
describe("integration tests", () => {
test("formats real conversation data correctly", () => {
// Load the sample JSON data
const jsonPath = join(__dirname, "fixtures", "sample-turns.json");
const expectedPath = join(
__dirname,
"fixtures",
"sample-turns-expected-output.md",
);
const jsonData = JSON.parse(readFileSync(jsonPath, "utf-8"));
const expectedOutput = readFileSync(expectedPath, "utf-8").trim();
// Format the data using our function
const actualOutput = formatTurnsFromData(jsonData).trim();
// Compare the outputs
expect(actualOutput).toBe(expectedOutput);
});
});

115
test/github/context.test.ts Normal file
View File

@@ -0,0 +1,115 @@
import { describe, it, expect } from "bun:test";
import {
parseMultilineInput,
parseAdditionalPermissions,
} 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([]);
});
});
describe("parseAdditionalPermissions", () => {
it("should parse single permission", () => {
const input = "actions: read";
const result = parseAdditionalPermissions(input);
expect(result.get("actions")).toBe("read");
expect(result.size).toBe(1);
});
it("should parse multiple permissions", () => {
const input = `actions: read
packages: write
contents: read`;
const result = parseAdditionalPermissions(input);
expect(result.get("actions")).toBe("read");
expect(result.get("packages")).toBe("write");
expect(result.get("contents")).toBe("read");
expect(result.size).toBe(3);
});
it("should handle empty string", () => {
const input = "";
const result = parseAdditionalPermissions(input);
expect(result.size).toBe(0);
});
it("should handle whitespace and empty lines", () => {
const input = `
actions: read
packages: write
`;
const result = parseAdditionalPermissions(input);
expect(result.get("actions")).toBe("read");
expect(result.get("packages")).toBe("write");
expect(result.size).toBe(2);
});
it("should ignore lines without colon separator", () => {
const input = `actions: read
invalid line
packages: write`;
const result = parseAdditionalPermissions(input);
expect(result.get("actions")).toBe("read");
expect(result.get("packages")).toBe("write");
expect(result.size).toBe(2);
});
it("should trim whitespace around keys and values", () => {
const input = " actions : read ";
const result = parseAdditionalPermissions(input);
expect(result.get("actions")).toBe("read");
expect(result.size).toBe(1);
});
});

View File

@@ -1,6 +1,7 @@
import { describe, test, expect, beforeEach, afterEach, spyOn } from "bun:test"; import { describe, test, expect, beforeEach, afterEach, spyOn } from "bun:test";
import { prepareMcpConfig } from "../src/mcp/install-mcp-server"; import { prepareMcpConfig } from "../src/mcp/install-mcp-server";
import * as core from "@actions/core"; import * as core from "@actions/core";
import type { ParsedGitHubContext } from "../src/github/context";
describe("prepareMcpConfig", () => { describe("prepareMcpConfig", () => {
let consoleInfoSpy: any; let consoleInfoSpy: any;
@@ -8,6 +9,58 @@ describe("prepareMcpConfig", () => {
let setFailedSpy: any; let setFailedSpy: any;
let processExitSpy: any; let processExitSpy: any;
// Create a mock context for tests
const mockContext: ParsedGitHubContext = {
runId: "test-run-id",
eventName: "issue_comment",
eventAction: "created",
repository: {
owner: "test-owner",
repo: "test-repo",
full_name: "test-owner/test-repo",
},
actor: "test-actor",
payload: {} as any,
entityNumber: 123,
isPR: false,
inputs: {
triggerPhrase: "@claude",
assigneeTrigger: "",
labelTrigger: "",
allowedTools: [],
disallowedTools: [],
customInstructions: "",
directPrompt: "",
branchPrefix: "",
useStickyComment: false,
additionalPermissions: new Map(),
useCommitSigning: false,
},
};
const mockPRContext: ParsedGitHubContext = {
...mockContext,
eventName: "pull_request",
isPR: true,
entityNumber: 456,
};
const mockContextWithSigning: ParsedGitHubContext = {
...mockContext,
inputs: {
...mockContext.inputs,
useCommitSigning: true,
},
};
const mockPRContextWithSigning: ParsedGitHubContext = {
...mockPRContext,
inputs: {
...mockPRContext.inputs,
useCommitSigning: true,
},
};
beforeEach(() => { beforeEach(() => {
consoleInfoSpy = spyOn(core, "info").mockImplementation(() => {}); consoleInfoSpy = spyOn(core, "info").mockImplementation(() => {});
consoleWarningSpy = spyOn(core, "warning").mockImplementation(() => {}); consoleWarningSpy = spyOn(core, "warning").mockImplementation(() => {});
@@ -15,6 +68,11 @@ describe("prepareMcpConfig", () => {
processExitSpy = spyOn(process, "exit").mockImplementation(() => { processExitSpy = spyOn(process, "exit").mockImplementation(() => {
throw new Error("Process exit"); throw new Error("Process exit");
}); });
// Set up required environment variables
if (!process.env.GITHUB_ACTION_PATH) {
process.env.GITHUB_ACTION_PATH = "/test/action/path";
}
}); });
afterEach(() => { afterEach(() => {
@@ -24,21 +82,53 @@ describe("prepareMcpConfig", () => {
processExitSpy.mockRestore(); processExitSpy.mockRestore();
}); });
test("should return base config when no additional config is provided", async () => { test("should return comment server when commit signing is disabled", async () => {
const result = await prepareMcpConfig({ const result = await prepareMcpConfig({
githubToken: "test-token", githubToken: "test-token",
owner: "test-owner", owner: "test-owner",
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
baseBranch: "main",
allowedTools: [],
context: mockContext,
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
expect(parsed.mcpServers).toBeDefined(); expect(parsed.mcpServers).toBeDefined();
expect(parsed.mcpServers.github).toBeDefined(); expect(parsed.mcpServers.github).not.toBeDefined();
expect(parsed.mcpServers.github_file_ops).toBeDefined(); expect(parsed.mcpServers.github_file_ops).not.toBeDefined();
expect(parsed.mcpServers.github.env.GITHUB_PERSONAL_ACCESS_TOKEN).toBe( expect(parsed.mcpServers.github_comment).toBeDefined();
expect(parsed.mcpServers.github_comment.env.GITHUB_TOKEN).toBe(
"test-token", "test-token",
); );
expect(parsed.mcpServers.github_comment.env.REPO_OWNER).toBe("test-owner");
expect(parsed.mcpServers.github_comment.env.REPO_NAME).toBe("test-repo");
});
test("should return file ops server when commit signing is enabled", async () => {
const contextWithSigning = {
...mockContext,
inputs: {
...mockContext.inputs,
useCommitSigning: true,
},
};
const result = await prepareMcpConfig({
githubToken: "test-token",
owner: "test-owner",
repo: "test-repo",
branch: "test-branch",
baseBranch: "main",
allowedTools: [],
context: contextWithSigning,
});
const parsed = JSON.parse(result);
expect(parsed.mcpServers).toBeDefined();
expect(parsed.mcpServers.github).not.toBeDefined();
expect(parsed.mcpServers.github_comment).toBeDefined();
expect(parsed.mcpServers.github_file_ops).toBeDefined();
expect(parsed.mcpServers.github_file_ops.env.GITHUB_TOKEN).toBe( expect(parsed.mcpServers.github_file_ops.env.GITHUB_TOKEN).toBe(
"test-token", "test-token",
); );
@@ -49,19 +139,92 @@ describe("prepareMcpConfig", () => {
); );
}); });
test("should include github MCP server when mcp__github__ tools are allowed", async () => {
const result = await prepareMcpConfig({
githubToken: "test-token",
owner: "test-owner",
repo: "test-repo",
branch: "test-branch",
baseBranch: "main",
allowedTools: [
"mcp__github__create_issue",
"mcp__github_file_ops__commit_files",
],
context: mockContext,
});
const parsed = JSON.parse(result);
expect(parsed.mcpServers).toBeDefined();
expect(parsed.mcpServers.github).toBeDefined();
expect(parsed.mcpServers.github_comment).toBeDefined();
expect(parsed.mcpServers.github_file_ops).not.toBeDefined();
expect(parsed.mcpServers.github.env.GITHUB_PERSONAL_ACCESS_TOKEN).toBe(
"test-token",
);
});
test("should not include github MCP server when only file_ops tools are allowed", async () => {
const contextWithSigning = {
...mockContext,
inputs: {
...mockContext.inputs,
useCommitSigning: true,
},
};
const result = await prepareMcpConfig({
githubToken: "test-token",
owner: "test-owner",
repo: "test-repo",
branch: "test-branch",
baseBranch: "main",
allowedTools: [
"mcp__github_file_ops__commit_files",
"mcp__github_file_ops__update_claude_comment",
],
context: contextWithSigning,
});
const parsed = JSON.parse(result);
expect(parsed.mcpServers).toBeDefined();
expect(parsed.mcpServers.github).not.toBeDefined();
expect(parsed.mcpServers.github_file_ops).toBeDefined();
});
test("should include comment server when no GitHub tools are allowed and signing disabled", async () => {
const result = await prepareMcpConfig({
githubToken: "test-token",
owner: "test-owner",
repo: "test-repo",
branch: "test-branch",
baseBranch: "main",
allowedTools: ["Edit", "Read", "Write"],
context: mockContext,
});
const parsed = JSON.parse(result);
expect(parsed.mcpServers).toBeDefined();
expect(parsed.mcpServers.github).not.toBeDefined();
expect(parsed.mcpServers.github_file_ops).not.toBeDefined();
expect(parsed.mcpServers.github_comment).toBeDefined();
});
test("should return base config when additional config is empty string", async () => { test("should return base config when additional config is empty string", async () => {
const result = await prepareMcpConfig({ const result = await prepareMcpConfig({
githubToken: "test-token", githubToken: "test-token",
owner: "test-owner", owner: "test-owner",
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
baseBranch: "main",
additionalMcpConfig: "", additionalMcpConfig: "",
allowedTools: [],
context: mockContext,
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
expect(parsed.mcpServers).toBeDefined(); expect(parsed.mcpServers).toBeDefined();
expect(parsed.mcpServers.github).toBeDefined(); expect(parsed.mcpServers.github).not.toBeDefined();
expect(parsed.mcpServers.github_file_ops).toBeDefined(); expect(parsed.mcpServers.github_comment).toBeDefined();
expect(consoleWarningSpy).not.toHaveBeenCalled(); expect(consoleWarningSpy).not.toHaveBeenCalled();
}); });
@@ -71,13 +234,16 @@ describe("prepareMcpConfig", () => {
owner: "test-owner", owner: "test-owner",
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
baseBranch: "main",
additionalMcpConfig: " \n\t ", additionalMcpConfig: " \n\t ",
allowedTools: [],
context: mockContext,
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
expect(parsed.mcpServers).toBeDefined(); expect(parsed.mcpServers).toBeDefined();
expect(parsed.mcpServers.github).toBeDefined(); expect(parsed.mcpServers.github).not.toBeDefined();
expect(parsed.mcpServers.github_file_ops).toBeDefined(); expect(parsed.mcpServers.github_comment).toBeDefined();
expect(consoleWarningSpy).not.toHaveBeenCalled(); expect(consoleWarningSpy).not.toHaveBeenCalled();
}); });
@@ -99,7 +265,13 @@ describe("prepareMcpConfig", () => {
owner: "test-owner", owner: "test-owner",
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
baseBranch: "main",
additionalMcpConfig: additionalConfig, additionalMcpConfig: additionalConfig,
allowedTools: [
"mcp__github__create_issue",
"mcp__github_file_ops__commit_files",
],
context: mockContextWithSigning,
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
@@ -132,7 +304,13 @@ describe("prepareMcpConfig", () => {
owner: "test-owner", owner: "test-owner",
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
baseBranch: "main",
additionalMcpConfig: additionalConfig, additionalMcpConfig: additionalConfig,
allowedTools: [
"mcp__github__create_issue",
"mcp__github_file_ops__commit_files",
],
context: mockContextWithSigning,
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
@@ -168,13 +346,16 @@ describe("prepareMcpConfig", () => {
owner: "test-owner", owner: "test-owner",
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
baseBranch: "main",
additionalMcpConfig: additionalConfig, additionalMcpConfig: additionalConfig,
allowedTools: [],
context: mockContextWithSigning,
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
expect(parsed.customProperty).toBe("custom-value"); expect(parsed.customProperty).toBe("custom-value");
expect(parsed.anotherProperty).toEqual({ nested: "value" }); expect(parsed.anotherProperty).toEqual({ nested: "value" });
expect(parsed.mcpServers.github).toBeDefined(); expect(parsed.mcpServers.github).not.toBeDefined();
expect(parsed.mcpServers.custom_server).toBeDefined(); expect(parsed.mcpServers.custom_server).toBeDefined();
}); });
@@ -186,14 +367,17 @@ describe("prepareMcpConfig", () => {
owner: "test-owner", owner: "test-owner",
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
baseBranch: "main",
additionalMcpConfig: invalidJson, additionalMcpConfig: invalidJson,
allowedTools: [],
context: mockContextWithSigning,
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
expect(consoleWarningSpy).toHaveBeenCalledWith( expect(consoleWarningSpy).toHaveBeenCalledWith(
expect.stringContaining("Failed to parse additional MCP config:"), expect.stringContaining("Failed to parse additional MCP config:"),
); );
expect(parsed.mcpServers.github).toBeDefined(); expect(parsed.mcpServers.github).not.toBeDefined();
expect(parsed.mcpServers.github_file_ops).toBeDefined(); expect(parsed.mcpServers.github_file_ops).toBeDefined();
}); });
@@ -205,7 +389,10 @@ describe("prepareMcpConfig", () => {
owner: "test-owner", owner: "test-owner",
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
baseBranch: "main",
additionalMcpConfig: nonObjectJson, additionalMcpConfig: nonObjectJson,
allowedTools: [],
context: mockContextWithSigning,
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
@@ -215,7 +402,7 @@ describe("prepareMcpConfig", () => {
expect(consoleWarningSpy).toHaveBeenCalledWith( expect(consoleWarningSpy).toHaveBeenCalledWith(
expect.stringContaining("MCP config must be a valid JSON object"), expect.stringContaining("MCP config must be a valid JSON object"),
); );
expect(parsed.mcpServers.github).toBeDefined(); expect(parsed.mcpServers.github).not.toBeDefined();
expect(parsed.mcpServers.github_file_ops).toBeDefined(); expect(parsed.mcpServers.github_file_ops).toBeDefined();
}); });
@@ -227,7 +414,10 @@ describe("prepareMcpConfig", () => {
owner: "test-owner", owner: "test-owner",
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
baseBranch: "main",
additionalMcpConfig: nullJson, additionalMcpConfig: nullJson,
allowedTools: [],
context: mockContextWithSigning,
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
@@ -237,7 +427,7 @@ describe("prepareMcpConfig", () => {
expect(consoleWarningSpy).toHaveBeenCalledWith( expect(consoleWarningSpy).toHaveBeenCalledWith(
expect.stringContaining("MCP config must be a valid JSON object"), expect.stringContaining("MCP config must be a valid JSON object"),
); );
expect(parsed.mcpServers.github).toBeDefined(); expect(parsed.mcpServers.github).not.toBeDefined();
expect(parsed.mcpServers.github_file_ops).toBeDefined(); expect(parsed.mcpServers.github_file_ops).toBeDefined();
}); });
@@ -249,7 +439,10 @@ describe("prepareMcpConfig", () => {
owner: "test-owner", owner: "test-owner",
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
baseBranch: "main",
additionalMcpConfig: arrayJson, additionalMcpConfig: arrayJson,
allowedTools: [],
context: mockContextWithSigning,
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
@@ -258,7 +451,7 @@ describe("prepareMcpConfig", () => {
expect(consoleInfoSpy).toHaveBeenCalledWith( expect(consoleInfoSpy).toHaveBeenCalledWith(
"Merging additional MCP server configuration with built-in servers", "Merging additional MCP server configuration with built-in servers",
); );
expect(parsed.mcpServers.github).toBeDefined(); expect(parsed.mcpServers.github).not.toBeDefined();
expect(parsed.mcpServers.github_file_ops).toBeDefined(); expect(parsed.mcpServers.github_file_ops).toBeDefined();
// The array will be spread into the config (0: 1, 1: 2, 2: 3) // The array will be spread into the config (0: 1, 1: 2, 2: 3)
expect(parsed[0]).toBe(1); expect(parsed[0]).toBe(1);
@@ -294,13 +487,16 @@ describe("prepareMcpConfig", () => {
owner: "test-owner", owner: "test-owner",
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
baseBranch: "main",
additionalMcpConfig: additionalConfig, additionalMcpConfig: additionalConfig,
allowedTools: [],
context: mockContextWithSigning,
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
expect(parsed.mcpServers.server1).toBeDefined(); expect(parsed.mcpServers.server1).toBeDefined();
expect(parsed.mcpServers.server2).toBeDefined(); expect(parsed.mcpServers.server2).toBeDefined();
expect(parsed.mcpServers.github).toBeDefined(); expect(parsed.mcpServers.github).not.toBeDefined();
expect(parsed.mcpServers.github_file_ops.command).toBe("overridden"); expect(parsed.mcpServers.github_file_ops.command).toBe("overridden");
expect(parsed.mcpServers.github_file_ops.env.CUSTOM).toBe("value"); expect(parsed.mcpServers.github_file_ops.env.CUSTOM).toBe("value");
expect(parsed.otherConfig.nested.deeply).toBe("value"); expect(parsed.otherConfig.nested.deeply).toBe("value");
@@ -315,6 +511,9 @@ describe("prepareMcpConfig", () => {
owner: "test-owner", owner: "test-owner",
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
baseBranch: "main",
allowedTools: [],
context: mockContextWithSigning,
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
@@ -334,6 +533,9 @@ describe("prepareMcpConfig", () => {
owner: "test-owner", owner: "test-owner",
repo: "test-repo", repo: "test-repo",
branch: "test-branch", branch: "test-branch",
baseBranch: "main",
allowedTools: [],
context: mockContextWithSigning,
}); });
const parsed = JSON.parse(result); const parsed = JSON.parse(result);
@@ -341,4 +543,138 @@ describe("prepareMcpConfig", () => {
process.env.GITHUB_WORKSPACE = oldEnv; process.env.GITHUB_WORKSPACE = oldEnv;
}); });
test("should include github_ci server when context.isPR is true and actions:read permission is granted", async () => {
const oldEnv = process.env.ACTIONS_TOKEN;
process.env.ACTIONS_TOKEN = "workflow-token";
const contextWithPermissions = {
...mockPRContext,
inputs: {
...mockPRContext.inputs,
additionalPermissions: new Map([["actions", "read"]]),
useCommitSigning: true,
},
};
const result = await prepareMcpConfig({
githubToken: "test-token",
owner: "test-owner",
repo: "test-repo",
branch: "test-branch",
baseBranch: "main",
allowedTools: [],
context: contextWithPermissions,
});
const parsed = JSON.parse(result);
expect(parsed.mcpServers.github_ci).toBeDefined();
expect(parsed.mcpServers.github_ci.env.GITHUB_TOKEN).toBe("workflow-token");
expect(parsed.mcpServers.github_ci.env.PR_NUMBER).toBe("456");
expect(parsed.mcpServers.github_file_ops).toBeDefined();
process.env.ACTIONS_TOKEN = oldEnv;
});
test("should not include github_ci server when context.isPR is false", async () => {
const result = await prepareMcpConfig({
githubToken: "test-token",
owner: "test-owner",
repo: "test-repo",
branch: "test-branch",
baseBranch: "main",
allowedTools: [],
context: mockContextWithSigning,
});
const parsed = JSON.parse(result);
expect(parsed.mcpServers.github_ci).not.toBeDefined();
expect(parsed.mcpServers.github_file_ops).toBeDefined();
});
test("should not include github_ci server when actions:read permission is not granted", async () => {
const oldTokenEnv = process.env.ACTIONS_TOKEN;
process.env.ACTIONS_TOKEN = "workflow-token";
const result = await prepareMcpConfig({
githubToken: "test-token",
owner: "test-owner",
repo: "test-repo",
branch: "test-branch",
baseBranch: "main",
allowedTools: [],
context: mockPRContextWithSigning,
});
const parsed = JSON.parse(result);
expect(parsed.mcpServers.github_ci).not.toBeDefined();
expect(parsed.mcpServers.github_file_ops).toBeDefined();
process.env.ACTIONS_TOKEN = oldTokenEnv;
});
test("should parse additional_permissions with multiple lines correctly", async () => {
const oldTokenEnv = process.env.ACTIONS_TOKEN;
process.env.ACTIONS_TOKEN = "workflow-token";
const contextWithPermissions = {
...mockPRContext,
inputs: {
...mockPRContext.inputs,
additionalPermissions: new Map([
["actions", "read"],
["future", "permission"],
]),
},
};
const result = await prepareMcpConfig({
githubToken: "test-token",
owner: "test-owner",
repo: "test-repo",
branch: "test-branch",
baseBranch: "main",
allowedTools: [],
context: contextWithPermissions,
});
const parsed = JSON.parse(result);
expect(parsed.mcpServers.github_ci).toBeDefined();
expect(parsed.mcpServers.github_ci.env.GITHUB_TOKEN).toBe("workflow-token");
process.env.ACTIONS_TOKEN = oldTokenEnv;
});
test("should warn when actions:read is requested but token lacks permission", async () => {
const oldTokenEnv = process.env.ACTIONS_TOKEN;
process.env.ACTIONS_TOKEN = "invalid-token";
const contextWithPermissions = {
...mockPRContext,
inputs: {
...mockPRContext.inputs,
additionalPermissions: new Map([["actions", "read"]]),
},
};
const result = await prepareMcpConfig({
githubToken: "test-token",
owner: "test-owner",
repo: "test-repo",
branch: "test-branch",
baseBranch: "main",
allowedTools: [],
context: contextWithPermissions,
});
const parsed = JSON.parse(result);
expect(parsed.mcpServers.github_ci).toBeDefined();
expect(consoleWarningSpy).toHaveBeenCalledWith(
expect.stringContaining(
"The github_ci MCP server requires 'actions: read' permission",
),
);
process.env.ACTIONS_TOKEN = oldTokenEnv;
});
}); });

View File

@@ -10,14 +10,19 @@ import type {
const defaultInputs = { const defaultInputs = {
triggerPhrase: "/claude", triggerPhrase: "/claude",
assigneeTrigger: "", assigneeTrigger: "",
labelTrigger: "",
anthropicModel: "claude-3-7-sonnet-20250219", anthropicModel: "claude-3-7-sonnet-20250219",
allowedTools: "", allowedTools: [] as string[],
disallowedTools: "", disallowedTools: [] as string[],
customInstructions: "", customInstructions: "",
directPrompt: "", directPrompt: "",
useBedrock: false, useBedrock: false,
useVertex: false, useVertex: false,
timeoutMinutes: 30, timeoutMinutes: 30,
branchPrefix: "claude/",
useStickyComment: false,
additionalPermissions: new Map<string, string>(),
useCommitSigning: false,
}; };
const defaultRepository = { const defaultRepository = {
@@ -91,6 +96,12 @@ export const mockIssueAssignedContext: ParsedGitHubContext = {
actor: "admin-user", actor: "admin-user",
payload: { payload: {
action: "assigned", action: "assigned",
assignee: {
login: "claude-bot",
id: 11111,
avatar_url: "https://avatars.githubusercontent.com/u/11111",
html_url: "https://github.com/claude-bot",
},
issue: { issue: {
number: 123, number: 123,
title: "Feature: Add dark mode support", title: "Feature: Add dark mode support",
@@ -122,6 +133,46 @@ export const mockIssueAssignedContext: ParsedGitHubContext = {
inputs: { ...defaultInputs, assigneeTrigger: "@claude-bot" }, inputs: { ...defaultInputs, assigneeTrigger: "@claude-bot" },
}; };
export const mockIssueLabeledContext: ParsedGitHubContext = {
runId: "1234567890",
eventName: "issues",
eventAction: "labeled",
repository: defaultRepository,
actor: "admin-user",
payload: {
action: "labeled",
issue: {
number: 1234,
title: "Enhancement: Improve search functionality",
body: "The current search is too slow and needs optimization",
user: {
login: "alice-wonder",
id: 54321,
avatar_url: "https://avatars.githubusercontent.com/u/54321",
html_url: "https://github.com/alice-wonder",
},
assignee: null,
},
label: {
id: 987654321,
name: "claude-task",
color: "f29513",
description: "Label for Claude AI interactions",
},
repository: {
name: "test-repo",
full_name: "test-owner/test-repo",
private: false,
owner: {
login: "test-owner",
},
},
} as IssuesEvent,
entityNumber: 1234,
isPR: false,
inputs: { ...defaultInputs, labelTrigger: "claude-task" },
};
// Issue comment on issue event // Issue comment on issue event
export const mockIssueCommentContext: ParsedGitHubContext = { export const mockIssueCommentContext: ParsedGitHubContext = {
runId: "1234567890", runId: "1234567890",

View File

@@ -62,10 +62,15 @@ describe("checkWritePermissions", () => {
inputs: { inputs: {
triggerPhrase: "@claude", triggerPhrase: "@claude",
assigneeTrigger: "", assigneeTrigger: "",
allowedTools: "", labelTrigger: "",
disallowedTools: "", allowedTools: [],
disallowedTools: [],
customInstructions: "", customInstructions: "",
directPrompt: "", directPrompt: "",
branchPrefix: "claude/",
useStickyComment: false,
additionalPermissions: new Map(),
useCommitSigning: false,
}, },
}); });

View File

@@ -35,7 +35,7 @@ describe("parseEnvVarsWithContext", () => {
process.env = { process.env = {
...BASE_ENV, ...BASE_ENV,
BASE_BRANCH: "main", BASE_BRANCH: "main",
CLAUDE_BRANCH: "claude/issue-67890-20240101_120000", CLAUDE_BRANCH: "claude/issue-67890-20240101-1200",
}; };
}); });
@@ -44,7 +44,7 @@ describe("parseEnvVarsWithContext", () => {
mockIssueCommentContext, mockIssueCommentContext,
"12345", "12345",
"main", "main",
"claude/issue-67890-20240101_120000", "claude/issue-67890-20240101-1200",
); );
expect(result.repository).toBe("test-owner/test-repo"); expect(result.repository).toBe("test-owner/test-repo");
@@ -60,7 +60,7 @@ describe("parseEnvVarsWithContext", () => {
expect(result.eventData.issueNumber).toBe("55"); expect(result.eventData.issueNumber).toBe("55");
expect(result.eventData.commentId).toBe("12345678"); expect(result.eventData.commentId).toBe("12345678");
expect(result.eventData.claudeBranch).toBe( expect(result.eventData.claudeBranch).toBe(
"claude/issue-67890-20240101_120000", "claude/issue-67890-20240101-1200",
); );
expect(result.eventData.baseBranch).toBe("main"); expect(result.eventData.baseBranch).toBe("main");
expect(result.eventData.commentBody).toBe( expect(result.eventData.commentBody).toBe(
@@ -81,7 +81,7 @@ describe("parseEnvVarsWithContext", () => {
mockIssueCommentContext, mockIssueCommentContext,
"12345", "12345",
undefined, undefined,
"claude/issue-67890-20240101_120000", "claude/issue-67890-20240101-1200",
), ),
).toThrow("BASE_BRANCH is required for issue_comment event"); ).toThrow("BASE_BRANCH is required for issue_comment event");
}); });
@@ -152,7 +152,7 @@ describe("parseEnvVarsWithContext", () => {
process.env = { process.env = {
...BASE_ENV, ...BASE_ENV,
BASE_BRANCH: "main", BASE_BRANCH: "main",
CLAUDE_BRANCH: "claude/issue-42-20240101_120000", CLAUDE_BRANCH: "claude/issue-42-20240101-1200",
}; };
}); });
@@ -161,7 +161,7 @@ describe("parseEnvVarsWithContext", () => {
mockIssueOpenedContext, mockIssueOpenedContext,
"12345", "12345",
"main", "main",
"claude/issue-42-20240101_120000", "claude/issue-42-20240101-1200",
); );
expect(result.eventData.eventName).toBe("issues"); expect(result.eventData.eventName).toBe("issues");
@@ -174,7 +174,7 @@ describe("parseEnvVarsWithContext", () => {
expect(result.eventData.issueNumber).toBe("42"); expect(result.eventData.issueNumber).toBe("42");
expect(result.eventData.baseBranch).toBe("main"); expect(result.eventData.baseBranch).toBe("main");
expect(result.eventData.claudeBranch).toBe( expect(result.eventData.claudeBranch).toBe(
"claude/issue-42-20240101_120000", "claude/issue-42-20240101-1200",
); );
} }
}); });
@@ -184,7 +184,7 @@ describe("parseEnvVarsWithContext", () => {
mockIssueAssignedContext, mockIssueAssignedContext,
"12345", "12345",
"main", "main",
"claude/issue-123-20240101_120000", "claude/issue-123-20240101-1200",
); );
expect(result.eventData.eventName).toBe("issues"); expect(result.eventData.eventName).toBe("issues");
@@ -197,7 +197,7 @@ describe("parseEnvVarsWithContext", () => {
expect(result.eventData.issueNumber).toBe("123"); expect(result.eventData.issueNumber).toBe("123");
expect(result.eventData.baseBranch).toBe("main"); expect(result.eventData.baseBranch).toBe("main");
expect(result.eventData.claudeBranch).toBe( expect(result.eventData.claudeBranch).toBe(
"claude/issue-123-20240101_120000", "claude/issue-123-20240101-1200",
); );
expect(result.eventData.assigneeTrigger).toBe("@claude-bot"); expect(result.eventData.assigneeTrigger).toBe("@claude-bot");
} }
@@ -215,10 +215,59 @@ describe("parseEnvVarsWithContext", () => {
mockIssueOpenedContext, mockIssueOpenedContext,
"12345", "12345",
undefined, undefined,
"claude/issue-42-20240101_120000", "claude/issue-42-20240101-1200",
), ),
).toThrow("BASE_BRANCH is required for issues event"); ).toThrow("BASE_BRANCH is required for issues event");
}); });
test("should allow issue assigned event with direct_prompt and no assigneeTrigger", () => {
const contextWithDirectPrompt = createMockContext({
...mockIssueAssignedContext,
inputs: {
...mockIssueAssignedContext.inputs,
assigneeTrigger: "", // No assignee trigger
directPrompt: "Please assess this issue", // But direct prompt is provided
},
});
const result = prepareContext(
contextWithDirectPrompt,
"12345",
"main",
"claude/issue-123-20240101-1200",
);
expect(result.eventData.eventName).toBe("issues");
expect(result.eventData.isPR).toBe(false);
expect(result.directPrompt).toBe("Please assess this issue");
if (
result.eventData.eventName === "issues" &&
result.eventData.eventAction === "assigned"
) {
expect(result.eventData.issueNumber).toBe("123");
expect(result.eventData.assigneeTrigger).toBeUndefined();
}
});
test("should throw error when neither assigneeTrigger nor directPrompt provided for issue assigned event", () => {
const contextWithoutTriggers = createMockContext({
...mockIssueAssignedContext,
inputs: {
...mockIssueAssignedContext.inputs,
assigneeTrigger: "", // No assignee trigger
directPrompt: "", // No direct prompt
},
});
expect(() =>
prepareContext(
contextWithoutTriggers,
"12345",
"main",
"claude/issue-123-20240101-1200",
),
).toThrow("ASSIGNEE_TRIGGER is required for issue assigned event");
});
}); });
describe("optional fields", () => { describe("optional fields", () => {
@@ -242,7 +291,7 @@ describe("parseEnvVarsWithContext", () => {
...mockPullRequestCommentContext, ...mockPullRequestCommentContext,
inputs: { inputs: {
...mockPullRequestCommentContext.inputs, ...mockPullRequestCommentContext.inputs,
allowedTools: "Tool1,Tool2", allowedTools: ["Tool1", "Tool2"],
}, },
}); });
const result = prepareContext(contextWithAllowedTools, "12345"); const result = prepareContext(contextWithAllowedTools, "12345");

View File

@@ -6,6 +6,7 @@ import { describe, it, expect } from "bun:test";
import { import {
createMockContext, createMockContext,
mockIssueAssignedContext, mockIssueAssignedContext,
mockIssueLabeledContext,
mockIssueCommentContext, mockIssueCommentContext,
mockIssueOpenedContext, mockIssueOpenedContext,
mockPullRequestReviewContext, mockPullRequestReviewContext,
@@ -29,10 +30,15 @@ describe("checkContainsTrigger", () => {
inputs: { inputs: {
triggerPhrase: "/claude", triggerPhrase: "/claude",
assigneeTrigger: "", assigneeTrigger: "",
labelTrigger: "",
directPrompt: "Fix the bug in the login form", directPrompt: "Fix the bug in the login form",
allowedTools: "", allowedTools: [],
disallowedTools: "", disallowedTools: [],
customInstructions: "", customInstructions: "",
branchPrefix: "claude/",
useStickyComment: false,
additionalPermissions: new Map(),
useCommitSigning: false,
}, },
}); });
expect(checkContainsTrigger(context)).toBe(true); expect(checkContainsTrigger(context)).toBe(true);
@@ -55,10 +61,15 @@ describe("checkContainsTrigger", () => {
inputs: { inputs: {
triggerPhrase: "/claude", triggerPhrase: "/claude",
assigneeTrigger: "", assigneeTrigger: "",
labelTrigger: "",
directPrompt: "", directPrompt: "",
allowedTools: "", allowedTools: [],
disallowedTools: "", disallowedTools: [],
customInstructions: "", customInstructions: "",
branchPrefix: "claude/",
useStickyComment: false,
additionalPermissions: new Map(),
useCommitSigning: false,
}, },
}); });
expect(checkContainsTrigger(context)).toBe(false); expect(checkContainsTrigger(context)).toBe(false);
@@ -87,6 +98,11 @@ describe("checkContainsTrigger", () => {
...mockIssueAssignedContext, ...mockIssueAssignedContext,
payload: { payload: {
...mockIssueAssignedContext.payload, ...mockIssueAssignedContext.payload,
assignee: {
...(mockIssueAssignedContext.payload as IssuesAssignedEvent)
.assignee,
login: "otherUser",
},
issue: { issue: {
...(mockIssueAssignedContext.payload as IssuesAssignedEvent).issue, ...(mockIssueAssignedContext.payload as IssuesAssignedEvent).issue,
assignee: { assignee: {
@@ -102,6 +118,39 @@ describe("checkContainsTrigger", () => {
}); });
}); });
describe("label trigger", () => {
it("should return true when issue is labeled with the trigger label", () => {
const context = mockIssueLabeledContext;
expect(checkContainsTrigger(context)).toBe(true);
});
it("should return false when issue is labeled with a different label", () => {
const context = {
...mockIssueLabeledContext,
payload: {
...mockIssueLabeledContext.payload,
label: {
...(mockIssueLabeledContext.payload as any).label,
name: "bug",
},
},
} as ParsedGitHubContext;
expect(checkContainsTrigger(context)).toBe(false);
});
it("should return false for non-labeled events", () => {
const context = {
...mockIssueLabeledContext,
eventAction: "opened",
payload: {
...mockIssueLabeledContext.payload,
action: "opened",
},
} as ParsedGitHubContext;
expect(checkContainsTrigger(context)).toBe(false);
});
});
describe("issue body and title trigger", () => { describe("issue body and title trigger", () => {
it("should return true when issue body contains trigger phrase", () => { it("should return true when issue body contains trigger phrase", () => {
const context = mockIssueOpenedContext; const context = mockIssueOpenedContext;
@@ -227,10 +276,15 @@ describe("checkContainsTrigger", () => {
inputs: { inputs: {
triggerPhrase: "@claude", triggerPhrase: "@claude",
assigneeTrigger: "", assigneeTrigger: "",
labelTrigger: "",
directPrompt: "", directPrompt: "",
allowedTools: "", allowedTools: [],
disallowedTools: "", disallowedTools: [],
customInstructions: "", customInstructions: "",
branchPrefix: "claude/",
useStickyComment: false,
additionalPermissions: new Map(),
useCommitSigning: false,
}, },
}); });
expect(checkContainsTrigger(context)).toBe(true); expect(checkContainsTrigger(context)).toBe(true);
@@ -254,10 +308,15 @@ describe("checkContainsTrigger", () => {
inputs: { inputs: {
triggerPhrase: "@claude", triggerPhrase: "@claude",
assigneeTrigger: "", assigneeTrigger: "",
labelTrigger: "",
directPrompt: "", directPrompt: "",
allowedTools: "", allowedTools: [],
disallowedTools: "", disallowedTools: [],
customInstructions: "", customInstructions: "",
branchPrefix: "claude/",
useStickyComment: false,
additionalPermissions: new Map(),
useCommitSigning: false,
}, },
}); });
expect(checkContainsTrigger(context)).toBe(true); expect(checkContainsTrigger(context)).toBe(true);
@@ -281,10 +340,15 @@ describe("checkContainsTrigger", () => {
inputs: { inputs: {
triggerPhrase: "@claude", triggerPhrase: "@claude",
assigneeTrigger: "", assigneeTrigger: "",
labelTrigger: "",
directPrompt: "", directPrompt: "",
allowedTools: "", allowedTools: [],
disallowedTools: "", disallowedTools: [],
customInstructions: "", customInstructions: "",
branchPrefix: "claude/",
useStickyComment: false,
additionalPermissions: new Map(),
useCommitSigning: false,
}, },
}); });
expect(checkContainsTrigger(context)).toBe(false); expect(checkContainsTrigger(context)).toBe(false);