Compare commits

..
7 Commits
Author SHA1 Message Date
GitHub Actions 9db594c7a0 chore: bump Claude Code to 2.1.222 and Agent SDK to 0.3.222 2026-08-04 22:40:25 +00:00
Ashwin BhatandGitHub acb0385805 Check collaborator permissions for workflow_run events (#1590)
The write-permission gate previously only ran for issue/PR entity
events. Apply it to workflow_run events as well, checking both the
workflow actor and the actor recorded on the upstream run when they
differ. allowed_non_write_users and the github_token override behave
the same as for entity events. Document the behavior for workflow_run
pipelines.
2026-08-04 10:05:34 -07:00
Ashwin BhatandGitHub b80a0f042f Match downloaded images to their source URLs by asset identifier (#1588)
* Match downloaded images to source URLs by asset identifier

* Derive the signed URL asset identifier from the parsed path
2026-08-04 10:04:47 -07:00
Ashwin BhatandGitHub 6fb6bb6858 Pin bun config for MCP server processes (#1589) 2026-08-04 10:03:43 -07:00
Ashwin BhatandGitHub b2963b9127 Derive trigger timestamps for issues and pull_request events (#1592)
* Derive trigger timestamps for issues and pull_request events

For issues labeled/assigned triggers, look up the matching event in the
issue's event history to get the exact time of the label/assignment,
falling back to the payload's updated_at/created_at when the lookup
fails. issues opened uses issue.created_at; pull_request opened uses
pull_request.created_at and other pull_request actions use updated_at.

* Ignore issue label/assign events older than the payload snapshot

A matching labeled/assigned event that predates the webhook payload's
issue.updated_at cannot be the event that fired the webhook, so fall
back to the payload timestamps instead of adopting it as the boundary.
2026-08-03 19:15:50 -07:00
GitHub Actions 86180fa9e4 chore: bump Claude Code to 2.1.221 and Agent SDK to 0.3.221 2026-08-04 00:15:10 +00:00
GitHub Actions be7b93b190 chore: bump Claude Code to 2.1.220 and Agent SDK to 0.3.220 2026-07-25 01:36:28 +00:00
20 changed files with 1163 additions and 165 deletions
+1 -1
View File
@@ -145,7 +145,7 @@ runs:
PATH_TO_CLAUDE_CODE_EXECUTABLE: ${{ inputs.path_to_claude_code_executable }}
run: |
if [ -z "$PATH_TO_CLAUDE_CODE_EXECUTABLE" ]; then
CLAUDE_CODE_VERSION="2.1.219"
CLAUDE_CODE_VERSION="2.1.222"
echo "Installing Claude Code v${CLAUDE_CODE_VERSION}..."
for attempt in 1 2 3; do
echo "Installation attempt $attempt..."
+10 -10
View File
@@ -6,7 +6,7 @@
"name": "@anthropic-ai/claude-code-base-action",
"dependencies": {
"@actions/core": "^1.10.1",
"@anthropic-ai/claude-agent-sdk": "^0.3.219",
"@anthropic-ai/claude-agent-sdk": "^0.3.222",
"shell-quote": "^1.8.3",
},
"devDependencies": {
@@ -27,23 +27,23 @@
"@actions/io": ["@actions/[email protected]", "", {}, "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q=="],
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]19", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.219", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.219", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.219", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.219", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.219", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.219", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.219", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.219" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-dJjzKxoyCQSEEEo9a0g3wBQprRMCpsqjmsNOZaGOWw+W+JHZsolDBhoYfoZ9BA8EdwgaJmbQUvhkAZjROUsBnQ=="],
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]22", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.222", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.222", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.222", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.222", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.222", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.222", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.222", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.222" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-muAyjIzXJjIpSrj91vSmnU76/z7rNlV8+lSuq48h4eUPSYVBSgOasgkfQAMUrIZJCfI15XF9/EYoRrx/eKD7Og=="],
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]19", "", { "os": "darwin", "cpu": "arm64" }, "sha512-TQhGAlbMsOGXi03dwf4nD274Lc5BOJg4QFJTuXcQyhLhx0hUqzxCmtvpXt6S70K6yl1Zgc+2n5W/r1Dgt8G8iw=="],
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]22", "", { "os": "darwin", "cpu": "arm64" }, "sha512-h3nCSwRbUsXDnRRYvMhzI1u1q5w6jClc9jTtOJBY6+mijjJEGk+Fa5Kuhw0Tb5ec+1iatiTyCIT46HrV0Skqcg=="],
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]19", "", { "os": "darwin", "cpu": "x64" }, "sha512-zA/wHN+os4yqXASXJxvGGNSD1p7LZ6BMN71CCphoy5u+d6IpNOCtATnZwINEc2fGFHpv/QDci6jhywJ2O9Flbw=="],
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]22", "", { "os": "darwin", "cpu": "x64" }, "sha512-kVzR6qBZv1ddbb+uJfDDEVdW6/cl1dtc2nAIa8prk4IcuyK1RwQE/BOO8dO6iRl5PnHuv9BFKS9AO1UErOkT5Q=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]19", "", { "os": "linux", "cpu": "arm64" }, "sha512-lizasky9Xj0ouYrz/Akst573Sm8NO3k/0iGCeCDBoQKLnONbVFwc7sHq9x426Pfcllgb4C2Xyc79/1iOALh/9g=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]22", "", { "os": "linux", "cpu": "arm64" }, "sha512-wn4XYkaWbAXc8PoznZqjCqbqB/Qet8dNdpZuRtbNSA1yZR0vYg2u28C5zV0QqVTXGgQVBYFUZabouyoERL6PsA=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]19", "", { "os": "linux", "cpu": "arm64" }, "sha512-yiZo+UBCp42FAYqSakgVj/g6LfTH0AklWqIZNEHfVDPaofledXdSu0QJM5yScWNg0hVMaNRXPt0DmuS1oIWW6g=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]22", "", { "os": "linux", "cpu": "arm64" }, "sha512-sVvPAUzRq+Am3+wNrFJ7URaWORu8t5hOu4vJnMhOeey66ZFFfzNwP0uz/7sTWjg+cRse/wG/hek34lZ0Gdu2+w=="],
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]19", "", { "os": "linux", "cpu": "x64" }, "sha512-yzXhEsT5XcKa8Dc3sM4D1CQ92/6YGmsBbAhRAdw0PYNkG8x6wbHqfzYZS491Bdjry4tSWemNFtGPNkHiWVo3Hg=="],
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]22", "", { "os": "linux", "cpu": "x64" }, "sha512-deZh3tVoYy9ememF5oirZNx1une7IG79JbKrB3Cynggt2gnq3TFXvPfkVGWgNsocK035wAW9HhGZui832OFSqA=="],
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]19", "", { "os": "linux", "cpu": "x64" }, "sha512-IhfG57/XorWOQTB6BVdjEFPGH0LwOWO6HnAi+FNuCeiC+XRFl9QI9AKY43opS0gbvJWRobZO865tHX5j7Ou+ow=="],
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]22", "", { "os": "linux", "cpu": "x64" }, "sha512-vM48p8GRM5N57+jPFdPj1ZS8Y770frJ1NTRecA06/GXtRANn7dOUVpvJbpu6fJBFF3BCacM1uVcBCMZh6wEMjw=="],
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]19", "", { "os": "win32", "cpu": "arm64" }, "sha512-L/cAT27t3FGP4GlJ16WpXMtaeqDu9olpOlIaqqmjElQp5Lknd8alJ3NIY/SlRAtHDvm4WXug74wnfBOSlwppkg=="],
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]22", "", { "os": "win32", "cpu": "arm64" }, "sha512-VuJjTLP2jQ1j8yn44/YODFR8GhI60Tvzok6AaXUYpKgeZTbBndDOpqwxvdWAraJSSyDreSSMztYyI6lP6nVypg=="],
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]19", "", { "os": "win32", "cpu": "x64" }, "sha512-Fl8Rb9K64jbpC/omIF9y828LIvwRmm1zhZgO8zjalTpjZR/0C31Kl+5FwAS9KkXXUXwmdHSY+82e9dyvBrbIRw=="],
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]22", "", { "os": "win32", "cpu": "x64" }, "sha512-mr4eZ+bmZA0hPl2wN031qy3TJXZJZIpdE4khvCc0AJ7ljVpJUEG654wz9NJoPxfPo4cRg41niHqUU5rN9BfQVw=="],
"@anthropic-ai/sdk": ["@anthropic-ai/[email protected]", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-q9vaSZQVFx6B/gPxetGYfLXSJD5v0sOmh0OpZDq7yCrTSA+Rscvrtyol7JJTW40wEpQB4U1B4JXzxQitbQ3CAA=="],
+1 -1
View File
@@ -11,7 +11,7 @@
},
"dependencies": {
"@actions/core": "^1.10.1",
"@anthropic-ai/claude-agent-sdk": "^0.3.219",
"@anthropic-ai/claude-agent-sdk": "^0.3.222",
"shell-quote": "^1.8.3"
},
"devDependencies": {
+10 -10
View File
@@ -7,7 +7,7 @@
"dependencies": {
"@actions/core": "^1.10.1",
"@actions/github": "^6.0.1",
"@anthropic-ai/claude-agent-sdk": "^0.3.219",
"@anthropic-ai/claude-agent-sdk": "^0.3.222",
"@modelcontextprotocol/sdk": "^1.11.0",
"@octokit/graphql": "^8.2.2",
"@octokit/rest": "^21.1.1",
@@ -37,23 +37,23 @@
"@actions/io": ["@actions/[email protected]", "", {}, "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q=="],
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]19", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.219", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.219", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.219", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.219", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.219", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.219", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.219", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.219" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-dJjzKxoyCQSEEEo9a0g3wBQprRMCpsqjmsNOZaGOWw+W+JHZsolDBhoYfoZ9BA8EdwgaJmbQUvhkAZjROUsBnQ=="],
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]22", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.222", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.222", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.222", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.222", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.222", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.222", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.222", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.222" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-muAyjIzXJjIpSrj91vSmnU76/z7rNlV8+lSuq48h4eUPSYVBSgOasgkfQAMUrIZJCfI15XF9/EYoRrx/eKD7Og=="],
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]19", "", { "os": "darwin", "cpu": "arm64" }, "sha512-TQhGAlbMsOGXi03dwf4nD274Lc5BOJg4QFJTuXcQyhLhx0hUqzxCmtvpXt6S70K6yl1Zgc+2n5W/r1Dgt8G8iw=="],
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]22", "", { "os": "darwin", "cpu": "arm64" }, "sha512-h3nCSwRbUsXDnRRYvMhzI1u1q5w6jClc9jTtOJBY6+mijjJEGk+Fa5Kuhw0Tb5ec+1iatiTyCIT46HrV0Skqcg=="],
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]19", "", { "os": "darwin", "cpu": "x64" }, "sha512-zA/wHN+os4yqXASXJxvGGNSD1p7LZ6BMN71CCphoy5u+d6IpNOCtATnZwINEc2fGFHpv/QDci6jhywJ2O9Flbw=="],
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]22", "", { "os": "darwin", "cpu": "x64" }, "sha512-kVzR6qBZv1ddbb+uJfDDEVdW6/cl1dtc2nAIa8prk4IcuyK1RwQE/BOO8dO6iRl5PnHuv9BFKS9AO1UErOkT5Q=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]19", "", { "os": "linux", "cpu": "arm64" }, "sha512-lizasky9Xj0ouYrz/Akst573Sm8NO3k/0iGCeCDBoQKLnONbVFwc7sHq9x426Pfcllgb4C2Xyc79/1iOALh/9g=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]22", "", { "os": "linux", "cpu": "arm64" }, "sha512-wn4XYkaWbAXc8PoznZqjCqbqB/Qet8dNdpZuRtbNSA1yZR0vYg2u28C5zV0QqVTXGgQVBYFUZabouyoERL6PsA=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]19", "", { "os": "linux", "cpu": "arm64" }, "sha512-yiZo+UBCp42FAYqSakgVj/g6LfTH0AklWqIZNEHfVDPaofledXdSu0QJM5yScWNg0hVMaNRXPt0DmuS1oIWW6g=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]22", "", { "os": "linux", "cpu": "arm64" }, "sha512-sVvPAUzRq+Am3+wNrFJ7URaWORu8t5hOu4vJnMhOeey66ZFFfzNwP0uz/7sTWjg+cRse/wG/hek34lZ0Gdu2+w=="],
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]19", "", { "os": "linux", "cpu": "x64" }, "sha512-yzXhEsT5XcKa8Dc3sM4D1CQ92/6YGmsBbAhRAdw0PYNkG8x6wbHqfzYZS491Bdjry4tSWemNFtGPNkHiWVo3Hg=="],
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]22", "", { "os": "linux", "cpu": "x64" }, "sha512-deZh3tVoYy9ememF5oirZNx1une7IG79JbKrB3Cynggt2gnq3TFXvPfkVGWgNsocK035wAW9HhGZui832OFSqA=="],
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]19", "", { "os": "linux", "cpu": "x64" }, "sha512-IhfG57/XorWOQTB6BVdjEFPGH0LwOWO6HnAi+FNuCeiC+XRFl9QI9AKY43opS0gbvJWRobZO865tHX5j7Ou+ow=="],
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]22", "", { "os": "linux", "cpu": "x64" }, "sha512-vM48p8GRM5N57+jPFdPj1ZS8Y770frJ1NTRecA06/GXtRANn7dOUVpvJbpu6fJBFF3BCacM1uVcBCMZh6wEMjw=="],
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]19", "", { "os": "win32", "cpu": "arm64" }, "sha512-L/cAT27t3FGP4GlJ16WpXMtaeqDu9olpOlIaqqmjElQp5Lknd8alJ3NIY/SlRAtHDvm4WXug74wnfBOSlwppkg=="],
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]22", "", { "os": "win32", "cpu": "arm64" }, "sha512-VuJjTLP2jQ1j8yn44/YODFR8GhI60Tvzok6AaXUYpKgeZTbBndDOpqwxvdWAraJSSyDreSSMztYyI6lP6nVypg=="],
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]19", "", { "os": "win32", "cpu": "x64" }, "sha512-Fl8Rb9K64jbpC/omIF9y828LIvwRmm1zhZgO8zjalTpjZR/0C31Kl+5FwAS9KkXXUXwmdHSY+82e9dyvBrbIRw=="],
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]22", "", { "os": "win32", "cpu": "x64" }, "sha512-mr4eZ+bmZA0hPl2wN031qy3TJXZJZIpdE4khvCc0AJ7ljVpJUEG654wz9NJoPxfPo4cRg41niHqUU5rN9BfQVw=="],
"@anthropic-ai/sdk": ["@anthropic-ai/[email protected]", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-q9vaSZQVFx6B/gPxetGYfLXSJD5v0sOmh0OpZDq7yCrTSA+Rscvrtyol7JJTW40wEpQB4U1B4JXzxQitbQ3CAA=="],
+3 -1
View File
@@ -2,7 +2,7 @@
## Access Control
- **Repository Access**: The action can only be triggered by users with write access to the repository
- **Repository Access**: The action can only be triggered by users with write access to the repository. This is checked for issue, pull request, comment, and review events, and for `workflow_run` events, where both the workflow actor and the actor that started the upstream run are checked. `workflow_dispatch`, `repository_dispatch`, and `schedule` events are not checked separately — GitHub itself requires write access to dispatch a workflow, and scheduled runs have no external actor.
- **Bot User Control**: By default, GitHub Apps and bots cannot trigger this action for security reasons. Use the `allowed_bots` parameter to enable specific bots or all bots
- **⚠️ Allowed bots are not checked for repository permissions.** A bot that matches an entry does **not** need to be installed on your repository or have write access. On a **public repository**, external parties — including GitHub Apps created by anyone — may be able to trigger workflow events such as opening issues, commenting, or reviewing pull requests. If your workflow listens on those events and `allowed_bots` is set to `'*'`, any such App can invoke this action with a prompt it controls.
- Prefer an explicit list over `'*'`
@@ -22,6 +22,8 @@
## Using this action with `pull_request_target` or `workflow_run`
For `workflow_run` events, the action checks the repository access of the actor that started the upstream run (for example, the author of the fork pull request that triggered your CI workflow) in addition to the workflow actor. If that actor does not have write access, the action stops before running Claude. To run on `workflow_run` events downstream of pull requests from contributors without write access, add those users to `allowed_non_write_users` and pass `github_token: ${{ secrets.GITHUB_TOKEN }}` — see the notes on that input above and keep the workflow's permissions minimal.
`pull_request_target` and `workflow_run` execute with the **base repository's secrets**. If your workflow checks out the PR head (`ref: ${{ github.event.pull_request.head.sha }}` for `pull_request_target`, `ref: ${{ github.event.workflow_run.head_sha }}` for `workflow_run`) into `$GITHUB_WORKSPACE` before this action, the action and Claude run with that checkout as the working directory.
**Do not check out an untrusted ref into the workspace root before this action.** Use one of these patterns instead:
+1 -1
View File
@@ -12,7 +12,7 @@
"dependencies": {
"@actions/core": "^1.10.1",
"@actions/github": "^6.0.1",
"@anthropic-ai/claude-agent-sdk": "^0.3.219",
"@anthropic-ai/claude-agent-sdk": "^0.3.222",
"@modelcontextprotocol/sdk": "^1.11.0",
"@octokit/graphql": "^8.2.2",
"@octokit/rest": "^21.1.1",
+7 -3
View File
@@ -9,7 +9,11 @@ import * as core from "@actions/core";
import { setupGitHubToken } from "../github/token";
import { checkWritePermissions } from "../github/validation/permissions";
import { createOctokit } from "../github/api/client";
import { parseGitHubContext, isEntityContext } from "../github/context";
import {
parseGitHubContext,
isEntityContext,
isWorkflowRunEvent,
} from "../github/context";
import { detectMode } from "../modes/detector";
import { prepareTagMode } from "../modes/tag";
import { prepareAgentMode } from "../modes/agent";
@@ -33,8 +37,8 @@ async function run() {
const githubToken = await setupGitHubToken();
const octokit = createOctokit(githubToken);
// Step 3: Check write permissions (only for entity contexts)
if (isEntityContext(context)) {
// Step 3: Check write permissions (entity contexts and workflow_run)
if (isEntityContext(context) || isWorkflowRunEvent(context)) {
// Check if github_token was provided as input (not from app)
const githubTokenProvided = !!process.env.OVERRIDE_GITHUB_TOKEN;
const hasWritePermissions = await checkWritePermissions(
+6 -3
View File
@@ -21,6 +21,7 @@ import {
isPullRequestEvent,
isPullRequestReviewEvent,
isPullRequestReviewCommentEvent,
isWorkflowRunEvent,
} from "../github/context";
import type { GitHubContext } from "../github/context";
import { detectMode } from "../modes/detector";
@@ -75,7 +76,7 @@ async function installClaudeCode(): Promise<string> {
return customExecutable;
}
const claudeCodeVersion = "2.1.219";
const claudeCodeVersion = "2.1.222";
console.log(`Installing Claude Code v${claudeCodeVersion}...`);
for (let attempt = 1; attempt <= 3; attempt++) {
@@ -185,8 +186,10 @@ async function run() {
process.env.GITHUB_TOKEN = githubToken;
process.env.GH_TOKEN = githubToken;
// Check write permissions (only for entity contexts)
if (isEntityContext(context)) {
// Check write permissions for entity contexts, and for workflow_run
// events, whose upstream run may have been started by an actor without
// write access (e.g. the author of a fork pull request)
if (isEntityContext(context) || isWorkflowRunEvent(context)) {
const hasWritePermissions = await checkWritePermissions(
octokit.rest,
context,
+6
View File
@@ -282,6 +282,12 @@ export function isPullRequestReviewCommentEvent(
return context.eventName === "pull_request_review_comment";
}
export function isWorkflowRunEvent(
context: GitHubContext,
): context is AutomationContext & { payload: WorkflowRunEvent } {
return context.eventName === "workflow_run";
}
export function isIssuesAssignedEvent(
context: GitHubContext,
): context is ParsedGitHubContext & { payload: IssuesAssignedEvent } {
+134
View File
@@ -1,4 +1,5 @@
import { execFileSync } from "child_process";
import type { IssuesEvent } from "@octokit/webhooks-types";
import type { Octokits } from "../api/client";
import { ISSUE_QUERY, PR_QUERY, USER_QUERY } from "../api/queries/github";
import {
@@ -29,6 +30,12 @@ import {
* Extracts the trigger timestamp from the GitHub webhook payload.
* This timestamp represents when the triggering comment/review/event was created.
*
* For `issues` and `pull_request` events there is no dedicated trigger
* object in the payload, so the issue/PR's own timestamps from the webhook
* snapshot are used: `created_at` for opened events, otherwise `updated_at`
* (falling back to `created_at`). For issues labeled/assigned events,
* prefer resolveTriggerTimestamp() which looks up the exact event time.
*
* @param context - Parsed GitHub context from webhook
* @returns ISO timestamp string or undefined if not available
*/
@@ -41,11 +48,138 @@ export function extractTriggerTimestamp(
return context.payload.review.submitted_at || undefined;
} else if (isPullRequestReviewCommentEvent(context)) {
return context.payload.comment.created_at || undefined;
} else if (isIssuesEvent(context)) {
const issue = context.payload.issue;
if (context.eventAction === "opened") {
return issue?.created_at || issue?.updated_at || undefined;
}
// updated_at reflects the last comment or edit on the issue, so the
// newest pre-existing comment can share this timestamp and be excluded
// along with anything newer.
return issue?.updated_at || issue?.created_at || undefined;
} else if (isPullRequestEvent(context)) {
const pullRequest = context.payload.pull_request;
if (context.eventAction === "opened") {
return pullRequest?.created_at || pullRequest?.updated_at || undefined;
}
return pullRequest?.updated_at || pullRequest?.created_at || undefined;
}
return undefined;
}
/**
* Resolves the trigger timestamp for the event, consulting the GitHub API
* where the webhook payload does not carry an exact time for the triggering
* action.
*
* For issues labeled/assigned events the label/assignment carries no
* timestamp of its own in the payload, so the matching entry in the issue's
* event history is looked up and its `created_at` is used. If the lookup
* fails, this falls back to extractTriggerTimestamp().
*
* @param context - Parsed GitHub context from webhook
* @param octokits - GitHub API clients
* @returns ISO timestamp string or undefined if not available
*/
export async function resolveTriggerTimestamp(
context: ParsedGitHubContext,
octokits: Octokits,
): Promise<string | undefined> {
if (
isIssuesEvent(context) &&
(context.eventAction === "labeled" || context.eventAction === "assigned")
) {
const eventTime = await findIssueEventTime(context, octokits);
if (eventTime) {
return eventTime;
}
console.warn(
`Could not resolve the ${context.eventAction} event time for issue #${context.entityNumber}; falling back to the webhook payload timestamps`,
);
}
return extractTriggerTimestamp(context);
}
/**
* Looks up the most recent labeled/assigned event on the issue that matches
* the label or assignee in the webhook payload, returning its created_at.
*/
async function findIssueEventTime(
context: ParsedGitHubContext & { payload: IssuesEvent },
octokits: Octokits,
): Promise<string | undefined> {
const payload = context.payload;
let matches: (event: {
event: string;
label?: { name?: string | null };
assignee?: { login?: string } | null;
}) => boolean;
if (payload.action === "labeled") {
const labelName = payload.label?.name;
if (!labelName) return undefined;
matches = (event) =>
event.event === "labeled" && event.label?.name === labelName;
} else if (payload.action === "assigned") {
const assigneeLogin = payload.assignee?.login;
if (!assigneeLogin) return undefined;
matches = (event) =>
event.event === "assigned" && event.assignee?.login === assigneeLogin;
} else {
return undefined;
}
try {
const events = await octokits.rest.paginate(
octokits.rest.issues.listEvents,
{
owner: context.repository.owner,
repo: context.repository.repo,
issue_number: context.entityNumber,
per_page: 100,
},
);
let latest: (typeof events)[number] | undefined;
for (const event of events.filter(matches)) {
if (
!latest ||
new Date(event.created_at).getTime() >
new Date(latest.created_at).getTime()
) {
latest = event;
}
}
// Labeling/assignment does not bump the issue's updated_at, so the event
// that fired this webhook cannot predate the payload snapshot's
// updated_at. An older match means the current event is not visible in
// the events API yet; ignore it rather than adopt a stale boundary.
const snapshotUpdatedAt = payload.issue?.updated_at;
if (
latest &&
snapshotUpdatedAt &&
new Date(latest.created_at).getTime() <
new Date(snapshotUpdatedAt).getTime()
) {
console.warn(
`Latest matching ${payload.action} event on issue #${context.entityNumber} predates the issue's updated_at; treating it as stale`,
);
return undefined;
}
return latest?.created_at || undefined;
} catch (error) {
console.warn(
`Failed to fetch events for issue #${context.entityNumber}:`,
error,
);
return undefined;
}
}
/**
* Extracts the original title from the GitHub webhook payload.
* This is the title as it existed when the trigger event occurred.
+56 -10
View File
@@ -14,6 +14,39 @@ const HTML_IMG_REGEX = new RegExp(
"gi",
);
const SIGNED_URL_REGEX =
/https:\/\/private-user-images\.githubusercontent\.com\/[^"]+\?jwt=[^"]+/g;
// GitHub identifies an uploaded asset by a GUID that appears both in the
// user-attachment URL and in the signed download URL rendered in body_html.
const ASSET_GUID_REGEX =
/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
function extractAssetGuid(url: string): string | undefined {
return url.match(ASSET_GUID_REGEX)?.[0]?.toLowerCase();
}
const SIGNED_URL_HOST = "private-user-images.githubusercontent.com";
// Signed download URLs have the shape /<owner-id>/<asset-id>-<guid>.<ext>.
// The GUID must come from the resolved filename, not from anywhere in the raw
// string, so text that merely embeds a GUID cannot claim another asset.
const SIGNED_URL_PATH_REGEX =
/^\/[^/]+\/[^/]*-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:\.[a-z0-9]+)?$/i;
function extractSignedUrlAssetGuid(signedUrl: string): string | undefined {
let parsed: URL;
try {
parsed = new URL(signedUrl);
} catch {
return undefined;
}
if (parsed.host !== SIGNED_URL_HOST) {
return undefined;
}
return parsed.pathname.match(SIGNED_URL_PATH_REGEX)?.[1]?.toLowerCase();
}
type IssueComment = {
type: "issue_comment";
id: string;
@@ -174,21 +207,34 @@ export async function downloadCommentImages(
}
// Extract signed URLs from HTML
const signedUrlRegex =
/https:\/\/private-user-images\.githubusercontent\.com\/[^"]+\?jwt=[^"]+/g;
const signedUrls = bodyHtml.match(signedUrlRegex) || [];
const signedUrls = bodyHtml.match(SIGNED_URL_REGEX) || [];
// Index the signed URLs by the asset GUID they reference. The signed
// URLs come from a separate render of the body, so their order and
// count are not guaranteed to line up with the URLs extracted from the
// markdown; pairing by asset identifier keeps each download tied to the
// URL it actually belongs to.
const signedUrlByGuid = new Map<string, string>();
for (const signedUrl of signedUrls) {
const guid = extractSignedUrlAssetGuid(signedUrl);
if (guid && !signedUrlByGuid.has(guid)) {
signedUrlByGuid.set(guid, signedUrl);
}
}
// Download each image
for (let i = 0; i < Math.min(signedUrls.length, urls.length); i++) {
const signedUrl = signedUrls[i];
const originalUrl = urls[i];
if (!signedUrl || !originalUrl) {
for (const [i, originalUrl] of urls.entries()) {
// Check if we've already downloaded this URL
if (urlToPathMap.has(originalUrl)) {
continue;
}
// Check if we've already downloaded this URL
if (urlToPathMap.has(originalUrl)) {
const guid = extractAssetGuid(originalUrl);
const signedUrl = guid ? signedUrlByGuid.get(guid) : undefined;
if (!signedUrl) {
console.warn(
`No matching signed URL found for ${originalUrl}, skipping`,
);
continue;
}
+45 -3
View File
@@ -1,5 +1,5 @@
import * as core from "@actions/core";
import type { ParsedGitHubContext } from "../context";
import { isWorkflowRunEvent, type GitHubContext } from "../context";
import type { Octokit } from "@octokit/rest";
/**
@@ -24,6 +24,28 @@ function isAllowedBot(actor: string, allowedBots: string): boolean {
return allowedList.includes(normalizedActor);
}
/**
* Collect the actors whose repository access should be checked. This is
* normally just the workflow actor (GITHUB_ACTOR). For workflow_run events
* the actor that started the upstream run is checked as well when it
* differs, since that is the account the run originates from.
*/
function getActorsToCheck(context: GitHubContext): string[] {
const actors = [context.actor];
if (isWorkflowRunEvent(context)) {
const runActor = context.payload.workflow_run?.actor?.login;
if (runActor && !actors.includes(runActor)) {
core.info(
`workflow_run was started by ${runActor}; checking permissions for that actor as well`,
);
actors.push(runActor);
}
}
return actors;
}
/**
* Check if the actor has write permissions to the repository
* @param octokit - The Octokit REST client
@@ -34,11 +56,31 @@ function isAllowedBot(actor: string, allowedBots: string): boolean {
*/
export async function checkWritePermissions(
octokit: Octokit,
context: ParsedGitHubContext,
context: GitHubContext,
allowedNonWriteUsers?: string,
githubTokenProvided?: boolean,
): Promise<boolean> {
const { repository, actor } = context;
for (const actor of getActorsToCheck(context)) {
const allowed = await checkActorWritePermissions(
octokit,
context,
actor,
allowedNonWriteUsers,
githubTokenProvided,
);
if (!allowed) return false;
}
return true;
}
async function checkActorWritePermissions(
octokit: Octokit,
context: GitHubContext,
actor: string,
allowedNonWriteUsers?: string,
githubTokenProvided?: boolean,
): Promise<boolean> {
const { repository } = context;
const allowedBots = context.inputs.allowedBots ?? "";
try {
+18 -16
View File
@@ -17,6 +17,20 @@ type PrepareConfigParams = {
context: GitHubContext;
};
// Build the bun invocation for one of the action's own MCP servers. The
// flags mirror the entrypoint invocation in action.yml so the server process
// reads its runtime config from the action directory rather than from the
// process working directory.
function bunServerArgs(scriptPath: string): string[] {
const actionPath = process.env.GITHUB_ACTION_PATH;
return [
"--no-env-file",
`--config=${actionPath}/bunfig.toml`,
"run",
`${actionPath}/${scriptPath}`,
];
}
async function checkActionsReadPermission(
token: string,
owner: string,
@@ -97,10 +111,7 @@ export async function prepareMcpConfig(
if (shouldIncludeCommentServer) {
baseMcpConfig.mcpServers.github_comment = {
command: "bun",
args: [
"run",
`${process.env.GITHUB_ACTION_PATH}/src/mcp/github-comment-server.ts`,
],
args: bunServerArgs("src/mcp/github-comment-server.ts"),
env: {
GITHUB_TOKEN: githubToken,
REPO_OWNER: owner,
@@ -116,10 +127,7 @@ export async function prepareMcpConfig(
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`,
],
args: bunServerArgs("src/mcp/github-file-ops-server.ts"),
env: {
GITHUB_TOKEN: githubToken,
REPO_OWNER: owner,
@@ -142,10 +150,7 @@ export async function prepareMcpConfig(
) {
baseMcpConfig.mcpServers.github_inline_comment = {
command: "bun",
args: [
"run",
`${process.env.GITHUB_ACTION_PATH}/src/mcp/github-inline-comment-server.ts`,
],
args: bunServerArgs("src/mcp/github-inline-comment-server.ts"),
env: {
GITHUB_TOKEN: githubToken,
REPO_OWNER: owner,
@@ -187,10 +192,7 @@ export async function prepareMcpConfig(
} else {
baseMcpConfig.mcpServers.github_ci = {
command: "bun",
args: [
"run",
`${process.env.GITHUB_ACTION_PATH}/src/mcp/github-actions-server.ts`,
],
args: bunServerArgs("src/mcp/github-actions-server.ts"),
env: {
// Use workflow github token, not app token
GITHUB_TOKEN: process.env.DEFAULT_WORKFLOW_TOKEN,
+2 -2
View File
@@ -8,7 +8,7 @@ import {
import { prepareMcpConfig } from "../../mcp/install-mcp-server";
import {
fetchGitHubData,
extractTriggerTimestamp,
resolveTriggerTimestamp,
extractOriginalTitle,
extractOriginalBody,
} from "../../github/data/fetcher";
@@ -45,7 +45,7 @@ export async function prepareTagMode({
const commentData = await createInitialComment(octokit.rest, context);
const commentId = commentData.id;
const triggerTime = extractTriggerTimestamp(context);
const triggerTime = await resolveTriggerTimestamp(context, octokit);
const originalTitle = extractOriginalTitle(context);
const originalBody = extractOriginalBody(context);
+377 -3
View File
@@ -1,6 +1,7 @@
import { describe, expect, it, jest, test } from "bun:test";
import {
extractTriggerTimestamp,
resolveTriggerTimestamp,
extractOriginalTitle,
extractOriginalBody,
fetchGitHubData,
@@ -8,6 +9,7 @@ import {
filterReviewsToTriggerTime,
isBodySafeToUse,
} from "../src/github/data/fetcher";
import type { ParsedGitHubContext } from "../src/github/context";
import {
createMockContext,
mockIssueCommentContext,
@@ -16,6 +18,8 @@ import {
mockPullRequestReviewCommentContext,
mockPullRequestOpenedContext,
mockIssueOpenedContext,
mockIssueAssignedContext,
mockIssueLabeledContext,
} from "./mockContext";
import type { GitHubComment, GitHubReview } from "../src/github/types";
@@ -38,15 +42,112 @@ describe("extractTriggerTimestamp", () => {
expect(timestamp).toBe("2024-01-15T16:45:00Z");
});
it("should return undefined for pull_request event", () => {
it("should extract created_at timestamp from pull_request opened event", () => {
const context = mockPullRequestOpenedContext;
const timestamp = extractTriggerTimestamp(context);
expect(timestamp).toBeUndefined();
expect(timestamp).toBe("2024-01-15T14:00:00Z");
});
it("should return undefined for issues event", () => {
it("should extract updated_at timestamp from pull_request synchronize event", () => {
const context: ParsedGitHubContext = {
...mockPullRequestOpenedContext,
eventAction: "synchronize",
payload: {
...(mockPullRequestOpenedContext.payload as any),
action: "synchronize",
},
};
const timestamp = extractTriggerTimestamp(context);
expect(timestamp).toBe("2024-01-15T14:05:00Z");
});
it("should extract updated_at timestamp from pull_request edited event", () => {
const context: ParsedGitHubContext = {
...mockPullRequestOpenedContext,
eventAction: "edited",
payload: {
...(mockPullRequestOpenedContext.payload as any),
action: "edited",
},
};
const timestamp = extractTriggerTimestamp(context);
expect(timestamp).toBe("2024-01-15T14:05:00Z");
});
it("should extract created_at timestamp from issues opened event", () => {
const context = mockIssueOpenedContext;
const timestamp = extractTriggerTimestamp(context);
expect(timestamp).toBe("2024-01-15T10:30:00Z");
});
it("should fall back to updated_at for issues labeled event", () => {
const context = mockIssueLabeledContext;
const timestamp = extractTriggerTimestamp(context);
expect(timestamp).toBe("2024-01-15T11:30:00Z");
});
it("should fall back to updated_at for issues assigned event", () => {
const context = mockIssueAssignedContext;
const timestamp = extractTriggerTimestamp(context);
expect(timestamp).toBe("2024-01-15T11:00:00Z");
});
it("should fall back to created_at for issues labeled event without updated_at", () => {
const context = createMockContext({
eventName: "issues",
eventAction: "labeled",
payload: {
action: "labeled",
issue: {
number: 1,
title: "test",
body: "test",
created_at: "2024-01-15T08:00:00Z",
},
} as any,
entityNumber: 1,
isPR: false,
});
const timestamp = extractTriggerTimestamp(context);
expect(timestamp).toBe("2024-01-15T08:00:00Z");
});
it("should fall back to created_at for pull_request synchronize event without updated_at", () => {
const context = createMockContext({
eventName: "pull_request",
eventAction: "synchronize",
payload: {
action: "synchronize",
pull_request: {
number: 1,
title: "test",
body: "test",
created_at: "2024-01-15T08:30:00Z",
},
} as any,
entityNumber: 1,
isPR: true,
});
const timestamp = extractTriggerTimestamp(context);
expect(timestamp).toBe("2024-01-15T08:30:00Z");
});
it("should return undefined for issues event without timestamps", () => {
const context = createMockContext({
eventName: "issues",
eventAction: "labeled",
payload: {
action: "labeled",
issue: {
number: 1,
title: "test",
body: "test",
},
} as any,
entityNumber: 1,
isPR: false,
});
const timestamp = extractTriggerTimestamp(context);
expect(timestamp).toBeUndefined();
});
@@ -66,6 +167,195 @@ describe("extractTriggerTimestamp", () => {
});
});
describe("resolveTriggerTimestamp", () => {
const createEventsOctokits = (events: any[]) => {
const paginate = jest.fn().mockResolvedValue(events);
return {
octokits: {
rest: {
paginate,
issues: { listEvents: jest.fn() },
},
graphql: jest.fn(),
} as any,
paginate,
};
};
it("should use the labeled event time for issues labeled event", async () => {
const { octokits, paginate } = createEventsOctokits([
{
event: "labeled",
label: { name: "other-label" },
created_at: "2024-01-15T10:45:00Z",
},
{
event: "labeled",
label: { name: "claude-task" },
created_at: "2024-01-15T10:50:00Z",
},
{
event: "labeled",
label: { name: "claude-task" },
created_at: "2024-01-15T11:45:00Z",
},
{
event: "assigned",
assignee: { login: "claude-bot" },
created_at: "2024-01-15T11:50:00Z",
},
]);
const timestamp = await resolveTriggerTimestamp(
mockIssueLabeledContext,
octokits,
);
expect(timestamp).toBe("2024-01-15T11:45:00Z");
expect(paginate).toHaveBeenCalledWith(octokits.rest.issues.listEvents, {
owner: "test-owner",
repo: "test-repo",
issue_number: 1234,
per_page: 100,
});
});
it("should use the assigned event time for issues assigned event", async () => {
const { octokits } = createEventsOctokits([
{
event: "assigned",
assignee: { login: "someone-else" },
created_at: "2024-01-15T10:40:00Z",
},
{
event: "assigned",
assignee: { login: "claude-bot" },
created_at: "2024-01-15T11:05:00Z",
},
]);
const timestamp = await resolveTriggerTimestamp(
mockIssueAssignedContext,
octokits,
);
expect(timestamp).toBe("2024-01-15T11:05:00Z");
});
it("should ignore a matching event that predates the issue's updated_at", async () => {
// A match older than the payload's updated_at is a previous
// labeling, not the one that fired this webhook.
const { octokits } = createEventsOctokits([
{
event: "labeled",
label: { name: "claude-task" },
created_at: "2024-01-15T10:50:00Z",
},
]);
const timestamp = await resolveTriggerTimestamp(
mockIssueLabeledContext,
octokits,
);
expect(timestamp).toBe("2024-01-15T11:30:00Z");
});
it("should fall back to updated_at when no matching labeled event exists", async () => {
const { octokits } = createEventsOctokits([
{
event: "labeled",
label: { name: "unrelated" },
created_at: "2024-01-15T10:45:00Z",
},
]);
const timestamp = await resolveTriggerTimestamp(
mockIssueLabeledContext,
octokits,
);
expect(timestamp).toBe("2024-01-15T11:30:00Z");
});
it("should fall back to updated_at when the events lookup fails", async () => {
const octokits = {
rest: {
paginate: jest.fn().mockRejectedValue(new Error("API failure")),
issues: { listEvents: jest.fn() },
},
graphql: jest.fn(),
} as any;
const timestamp = await resolveTriggerTimestamp(
mockIssueAssignedContext,
octokits,
);
expect(timestamp).toBe("2024-01-15T11:00:00Z");
});
it("should fall back to created_at when updated_at is also missing", async () => {
const context = createMockContext({
eventName: "issues",
eventAction: "labeled",
payload: {
action: "labeled",
label: { name: "claude-task" },
issue: {
number: 1,
title: "test",
body: "test",
created_at: "2024-01-15T08:00:00Z",
},
} as any,
entityNumber: 1,
isPR: false,
});
const { octokits } = createEventsOctokits([]);
const timestamp = await resolveTriggerTimestamp(context, octokits);
expect(timestamp).toBe("2024-01-15T08:00:00Z");
});
it("should use created_at for issues opened event without an API call", async () => {
const { octokits, paginate } = createEventsOctokits([]);
const timestamp = await resolveTriggerTimestamp(
mockIssueOpenedContext,
octokits,
);
expect(timestamp).toBe("2024-01-15T10:30:00Z");
expect(paginate).not.toHaveBeenCalled();
});
it("should use created_at for pull_request opened event without an API call", async () => {
const { octokits, paginate } = createEventsOctokits([]);
const timestamp = await resolveTriggerTimestamp(
mockPullRequestOpenedContext,
octokits,
);
expect(timestamp).toBe("2024-01-15T14:00:00Z");
expect(paginate).not.toHaveBeenCalled();
});
it("should use the existing comment timestamp for issue_comment events", async () => {
const { octokits, paginate } = createEventsOctokits([]);
const timestamp = await resolveTriggerTimestamp(
mockIssueCommentContext,
octokits,
);
expect(timestamp).toBe("2024-01-15T12:30:00Z");
expect(paginate).not.toHaveBeenCalled();
});
});
describe("extractOriginalTitle", () => {
it("should extract title from IssueCommentEvent on PR", () => {
const title = extractOriginalTitle(mockPullRequestCommentContext);
@@ -659,6 +949,90 @@ describe("fetchGitHubData integration with time filtering", () => {
expect(result.comments[0]?.body).toBe("Comment before trigger");
});
it("should filter comments using the resolved issues labeled event time", async () => {
const mockOctokits = {
graphql: jest.fn().mockResolvedValue({
repository: {
issue: {
number: 1234,
title: "Test Issue",
body: "Issue body",
author: { login: "author" },
comments: {
nodes: [
{
id: "1",
databaseId: "1",
body: "Comment before label",
author: { login: "user1" },
createdAt: "2024-01-15T10:00:00Z",
updatedAt: "2024-01-15T10:00:00Z",
},
{
id: "2",
databaseId: "2",
body: "Comment created after label",
author: { login: "user2" },
createdAt: "2024-01-15T12:00:00Z",
updatedAt: "2024-01-15T12:00:00Z",
},
{
id: "3",
databaseId: "3",
body: "Comment edited after label",
author: { login: "user3" },
createdAt: "2024-01-15T10:00:00Z",
updatedAt: "2024-01-15T12:00:00Z",
lastEditedAt: "2024-01-15T12:00:00Z",
},
{
id: "4",
databaseId: "4",
body: "Latest comment before label",
author: { login: "user4" },
createdAt: "2024-01-15T11:30:00Z",
updatedAt: "2024-01-15T11:30:00Z",
},
],
},
},
},
user: { login: "trigger-user" },
}),
rest: {
paginate: jest.fn().mockResolvedValue([
{
event: "labeled",
label: { name: "claude-task" },
created_at: "2024-01-15T11:45:00Z",
},
]),
issues: { listEvents: jest.fn() },
},
};
// The issues (labeled) webhook has no trigger comment; the boundary is
// the labeled event's own timestamp from the issue event history.
const triggerTime = await resolveTriggerTimestamp(
mockIssueLabeledContext,
mockOctokits as any,
);
expect(triggerTime).toBe("2024-01-15T11:45:00Z");
const result = await fetchGitHubData({
octokits: mockOctokits as any,
repository: "test-owner/test-repo",
prNumber: "1234",
isPR: false,
triggerUsername: "trigger-user",
triggerTime,
});
// Comments created before the label are kept (including the most
// recent one); comments created or edited after it are excluded.
expect(result.comments.map((c) => c.id)).toEqual(["1", "4"]);
});
it("should filter PR reviews based on trigger time", async () => {
const mockOctokits = {
graphql: jest.fn().mockResolvedValue({
+11
View File
@@ -33,6 +33,7 @@ import {
isIssuesAssignedEvent,
isEntityContext,
isAutomationContext,
isWorkflowRunEvent,
} from "../src/github/context";
import { CLAUDE_APP_BOT_ID, CLAUDE_BOT_LOGIN } from "../src/github/constants";
import { createMockContext, createMockAutomationContext } from "./mockContext";
@@ -517,4 +518,14 @@ describe("type guards", () => {
).toBe(true);
expect(isAutomationContext(issuesContext)).toBe(false);
});
test("isWorkflowRunEvent accepts only workflow_run", () => {
expect(
isWorkflowRunEvent(
createMockAutomationContext({ eventName: "workflow_run" }),
),
).toBe(true);
expect(isWorkflowRunEvent(workflowDispatchContext)).toBe(false);
expect(isWorkflowRunEvent(issuesContext)).toBe(false);
});
});
+272 -100
View File
@@ -13,6 +13,17 @@ import { downloadCommentImages } from "../src/github/utils/image-downloader";
import type { CommentWithImages } from "../src/github/utils/image-downloader";
import type { Octokits } from "../src/github/api/client";
// Asset URLs and their signed download URLs share the asset's GUID.
const GUID_1 = "f871c23e-a84d-4f1f-b9a0-86626c63f161";
const GUID_2 = "0b0c9d33-4e6a-4f4e-8a1a-2f9e5c6d7e8f";
const GUID_3 = "a1b2c3d4-e5f6-4789-abcd-ef0123456789";
const assetUrl = (guid: string, suffix = "") =>
`https://github.com/user-attachments/assets/${guid}${suffix}`;
const signedUrlFor = (guid: string, ext: string, token = "token") =>
`https://private-user-images.githubusercontent.com/12345/98765432-${guid}${ext}?jwt=${token}`;
describe("downloadCommentImages", () => {
let consoleLogSpy: any;
let consoleWarnSpy: any;
@@ -97,10 +108,8 @@ describe("downloadCommentImages", () => {
test("should detect and download images from issue comments", async () => {
const mockOctokit = createMockOctokit();
const imageUrl =
"https://github.com/user-attachments/assets/test-image.png";
const signedUrl =
"https://private-user-images.githubusercontent.com/test.png?jwt=token";
const imageUrl = assetUrl(GUID_1);
const signedUrl = signedUrlFor(GUID_1, ".png");
// Mock octokit response
// @ts-expect-error Mock implementation doesn't match full type signature
@@ -164,10 +173,8 @@ describe("downloadCommentImages", () => {
// the URL-based guess used to default to ".png" while the bytes are JPEG —
// producing a mislabeled file that the Anthropic API rejected with a 400.
const mockOctokit = createMockOctokit();
const imageUrl =
"https://github.com/user-attachments/assets/f871c23e-a84d-4f1f-b9a0-86626c63f161";
const signedUrl =
"https://private-user-images.githubusercontent.com/screenshot?jwt=token";
const imageUrl = assetUrl(GUID_1);
const signedUrl = signedUrlFor(GUID_1, ".jpg");
// @ts-expect-error Mock implementation doesn't match full type signature
mockOctokit.rest.issues.get = jest.fn().mockResolvedValue({
@@ -209,10 +216,8 @@ describe("downloadCommentImages", () => {
test("should handle review comments", async () => {
const mockOctokit = createMockOctokit();
const imageUrl =
"https://github.com/user-attachments/assets/review-image.jpg";
const signedUrl =
"https://private-user-images.githubusercontent.com/review.jpg?jwt=token";
const imageUrl = assetUrl(GUID_1, ".jpg");
const signedUrl = signedUrlFor(GUID_1, ".jpg");
// @ts-expect-error Mock implementation doesn't match full type signature
mockOctokit.rest.pulls.getReviewComment = jest.fn().mockResolvedValue({
@@ -255,10 +260,8 @@ describe("downloadCommentImages", () => {
test("should handle review bodies", async () => {
const mockOctokit = createMockOctokit();
const imageUrl =
"https://github.com/user-attachments/assets/review-body.png";
const signedUrl =
"https://private-user-images.githubusercontent.com/body.png?jwt=token";
const imageUrl = assetUrl(GUID_1);
const signedUrl = signedUrlFor(GUID_1, ".png");
// @ts-expect-error Mock implementation doesn't match full type signature
mockOctokit.rest.pulls.getReview = jest.fn().mockResolvedValue({
@@ -303,10 +306,8 @@ describe("downloadCommentImages", () => {
test("should handle issue bodies", async () => {
const mockOctokit = createMockOctokit();
const imageUrl =
"https://github.com/user-attachments/assets/issue-body.gif";
const signedUrl =
"https://private-user-images.githubusercontent.com/issue.gif?jwt=token";
const imageUrl = assetUrl(GUID_1, ".gif");
const signedUrl = signedUrlFor(GUID_1, ".gif");
// @ts-expect-error Mock implementation doesn't match full type signature
mockOctokit.rest.issues.get = jest.fn().mockResolvedValue({
@@ -352,9 +353,8 @@ describe("downloadCommentImages", () => {
test("should handle PR bodies", async () => {
const mockOctokit = createMockOctokit();
const imageUrl = "https://github.com/user-attachments/assets/pr-body.webp";
const signedUrl =
"https://private-user-images.githubusercontent.com/pr.webp?jwt=token";
const imageUrl = assetUrl(GUID_1, ".webp");
const signedUrl = signedUrlFor(GUID_1, ".webp");
// @ts-expect-error Mock implementation doesn't match full type signature
mockOctokit.rest.pulls.get = jest.fn().mockResolvedValue({
@@ -400,12 +400,10 @@ describe("downloadCommentImages", () => {
test("should handle multiple images in a single comment", async () => {
const mockOctokit = createMockOctokit();
const imageUrl1 = "https://github.com/user-attachments/assets/image1.png";
const imageUrl2 = "https://github.com/user-attachments/assets/image2.jpg";
const signedUrl1 =
"https://private-user-images.githubusercontent.com/1.png?jwt=token1";
const signedUrl2 =
"https://private-user-images.githubusercontent.com/2.jpg?jwt=token2";
const imageUrl1 = assetUrl(GUID_1);
const imageUrl2 = assetUrl(GUID_2, ".jpg");
const signedUrl1 = signedUrlFor(GUID_1, ".png", "token1");
const signedUrl2 = signedUrlFor(GUID_2, ".jpg", "token2");
// @ts-expect-error Mock implementation doesn't match full type signature
mockOctokit.rest.issues.getComment = jest.fn().mockResolvedValue({
@@ -447,11 +445,215 @@ describe("downloadCommentImages", () => {
);
});
test("should pair images by asset identifier even when the HTML order differs", async () => {
const mockOctokit = createMockOctokit();
const imageUrl1 = assetUrl(GUID_1);
const imageUrl2 = assetUrl(GUID_2);
const signedUrl1 = signedUrlFor(GUID_1, ".png", "token1");
const signedUrl2 = signedUrlFor(GUID_2, ".png", "token2");
// The rendered HTML lists the second asset first.
// @ts-expect-error Mock implementation doesn't match full type signature
mockOctokit.rest.issues.getComment = jest.fn().mockResolvedValue({
data: {
body_html: `<img src="${signedUrl2}"><img src="${signedUrl1}">`,
},
});
fetchSpy = spyOn(global, "fetch").mockResolvedValue({
ok: true,
arrayBuffer: async () => new ArrayBuffer(8),
} as Response);
const comments: CommentWithImages[] = [
{
type: "issue_comment",
id: "999",
body: `Two images: ![img1](${imageUrl1}) and ![img2](${imageUrl2})`,
},
];
const result = await downloadCommentImages(
mockOctokit,
"owner",
"repo",
comments,
);
expect(fetchSpy).toHaveBeenCalledTimes(2);
expect(fetchSpy).toHaveBeenNthCalledWith(1, signedUrl1);
expect(fetchSpy).toHaveBeenNthCalledWith(2, signedUrl2);
expect(result.get(imageUrl1)).toBe(
"/tmp/github-images/image-1704067200000-0.png",
);
expect(result.get(imageUrl2)).toBe(
"/tmp/github-images/image-1704067200000-1.png",
);
});
test("should match asset identifiers case-insensitively", async () => {
const mockOctokit = createMockOctokit();
const imageUrl = assetUrl(GUID_1.toUpperCase());
const signedUrl = signedUrlFor(GUID_1, ".png");
// @ts-expect-error Mock implementation doesn't match full type signature
mockOctokit.rest.issues.getComment = jest.fn().mockResolvedValue({
data: {
body_html: `<img src="${signedUrl}">`,
},
});
fetchSpy = spyOn(global, "fetch").mockResolvedValue({
ok: true,
arrayBuffer: async () => new ArrayBuffer(8),
} as Response);
const comments: CommentWithImages[] = [
{
type: "issue_comment",
id: "1002",
body: `Uppercase: ![test](${imageUrl})`,
},
];
const result = await downloadCommentImages(
mockOctokit,
"owner",
"repo",
comments,
);
expect(fetchSpy).toHaveBeenCalledWith(signedUrl);
expect(result.get(imageUrl)).toBe(
"/tmp/github-images/image-1704067200000-0.png",
);
});
test("should skip an image whose signed URL refers to a different asset", async () => {
const mockOctokit = createMockOctokit();
const imageUrl = assetUrl(GUID_1);
// The rendered HTML only contains a signed URL for a different asset.
const signedUrl = signedUrlFor(GUID_2, ".png");
// @ts-expect-error Mock implementation doesn't match full type signature
mockOctokit.rest.issues.getComment = jest.fn().mockResolvedValue({
data: {
body_html: `<img src="${signedUrl}">`,
},
});
fetchSpy = spyOn(global, "fetch").mockResolvedValue({
ok: true,
arrayBuffer: async () => new ArrayBuffer(8),
} as Response);
const comments: CommentWithImages[] = [
{
type: "issue_comment",
id: "1003",
body: `Original image: ![test](${imageUrl})`,
},
];
const result = await downloadCommentImages(
mockOctokit,
"owner",
"repo",
comments,
);
expect(fetchSpy).not.toHaveBeenCalled();
expect(result.size).toBe(0);
expect(consoleWarnSpy).toHaveBeenCalledWith(
`No matching signed URL found for ${imageUrl}, skipping`,
);
});
test("should not pair a signed URL that only names the asset in a leading path segment", async () => {
const mockOctokit = createMockOctokit();
const imageUrl = assetUrl(GUID_1);
// The path segment mentions the requested asset, but the URL resolves to a
// different asset's filename once ".." is applied.
const signedUrl = `https://private-user-images.githubusercontent.com/${GUID_1}/../12345/98765432-${GUID_2}.png?jwt=token`;
// @ts-expect-error Mock implementation doesn't match full type signature
mockOctokit.rest.issues.getComment = jest.fn().mockResolvedValue({
data: {
body_html: `<a href="${signedUrl}">${signedUrl}</a>`,
},
});
fetchSpy = spyOn(global, "fetch").mockResolvedValue({
ok: true,
arrayBuffer: async () => new ArrayBuffer(8),
} as Response);
const comments: CommentWithImages[] = [
{
type: "issue_comment",
id: "1005",
body: `Original image: ![test](${imageUrl})`,
},
];
const result = await downloadCommentImages(
mockOctokit,
"owner",
"repo",
comments,
);
expect(fetchSpy).not.toHaveBeenCalled();
expect(result.size).toBe(0);
expect(consoleWarnSpy).toHaveBeenCalledWith(
`No matching signed URL found for ${imageUrl}, skipping`,
);
});
test("should skip an image URL without an asset identifier", async () => {
const mockOctokit = createMockOctokit();
const imageUrl =
"https://github.com/user-attachments/assets/test-image.png";
const signedUrl = signedUrlFor(GUID_1, ".png");
// @ts-expect-error Mock implementation doesn't match full type signature
mockOctokit.rest.issues.getComment = jest.fn().mockResolvedValue({
data: {
body_html: `<img src="${signedUrl}">`,
},
});
fetchSpy = spyOn(global, "fetch").mockResolvedValue({
ok: true,
arrayBuffer: async () => new ArrayBuffer(8),
} as Response);
const comments: CommentWithImages[] = [
{
type: "issue_comment",
id: "1004",
body: `No identifier: ![test](${imageUrl})`,
},
];
const result = await downloadCommentImages(
mockOctokit,
"owner",
"repo",
comments,
);
expect(fetchSpy).not.toHaveBeenCalled();
expect(result.size).toBe(0);
expect(consoleWarnSpy).toHaveBeenCalledWith(
`No matching signed URL found for ${imageUrl}, skipping`,
);
});
test("should skip already downloaded images", async () => {
const mockOctokit = createMockOctokit();
const imageUrl = "https://github.com/user-attachments/assets/duplicate.png";
const signedUrl =
"https://private-user-images.githubusercontent.com/dup.png?jwt=token";
const imageUrl = assetUrl(GUID_1);
const signedUrl = signedUrlFor(GUID_1, ".png");
// @ts-expect-error Mock implementation doesn't match full type signature
mockOctokit.rest.issues.getComment = jest.fn().mockResolvedValue({
@@ -494,7 +696,7 @@ describe("downloadCommentImages", () => {
test("should handle missing HTML body", async () => {
const mockOctokit = createMockOctokit();
const imageUrl = "https://github.com/user-attachments/assets/missing.png";
const imageUrl = assetUrl(GUID_1);
// @ts-expect-error Mock implementation doesn't match full type signature
mockOctokit.rest.issues.getComment = jest.fn().mockResolvedValue({
@@ -526,9 +728,8 @@ describe("downloadCommentImages", () => {
test("should handle fetch errors", async () => {
const mockOctokit = createMockOctokit();
const imageUrl = "https://github.com/user-attachments/assets/error.png";
const signedUrl =
"https://private-user-images.githubusercontent.com/error.png?jwt=token";
const imageUrl = assetUrl(GUID_1);
const signedUrl = signedUrlFor(GUID_1, ".png");
// @ts-expect-error Mock implementation doesn't match full type signature
mockOctokit.rest.issues.getComment = jest.fn().mockResolvedValue({
@@ -567,7 +768,7 @@ describe("downloadCommentImages", () => {
test("should handle API errors gracefully", async () => {
const mockOctokit = createMockOctokit();
const imageUrl = "https://github.com/user-attachments/assets/api-error.png";
const imageUrl = assetUrl(GUID_1);
// @ts-expect-error Mock implementation doesn't match full type signature
mockOctokit.rest.issues.getComment = jest
@@ -599,42 +800,21 @@ describe("downloadCommentImages", () => {
test("should extract correct file extensions", async () => {
const mockOctokit = createMockOctokit();
const extensions = [
{
url: "https://github.com/user-attachments/assets/test.png",
ext: ".png",
},
{
url: "https://github.com/user-attachments/assets/test.jpg",
ext: ".jpg",
},
{
url: "https://github.com/user-attachments/assets/test.jpeg",
ext: ".jpeg",
},
{
url: "https://github.com/user-attachments/assets/test.gif",
ext: ".gif",
},
{
url: "https://github.com/user-attachments/assets/test.webp",
ext: ".webp",
},
{
url: "https://github.com/user-attachments/assets/test.svg",
ext: ".svg",
},
{
// default
url: "https://github.com/user-attachments/assets/no-extension",
ext: ".png",
},
{ url: assetUrl(GUID_1, ".png"), ext: ".png" },
{ url: assetUrl(GUID_1, ".jpg"), ext: ".jpg" },
{ url: assetUrl(GUID_1, ".jpeg"), ext: ".jpeg" },
{ url: assetUrl(GUID_1, ".gif"), ext: ".gif" },
{ url: assetUrl(GUID_1, ".webp"), ext: ".webp" },
{ url: assetUrl(GUID_1, ".svg"), ext: ".svg" },
// default
{ url: assetUrl(GUID_1), ext: ".png" },
];
let callIndex = 0;
// @ts-expect-error Mock implementation doesn't match full type signature
mockOctokit.rest.issues.getComment = jest.fn().mockResolvedValue({
data: {
body_html: `<img src="https://private-user-images.githubusercontent.com/test?jwt=token">`,
body_html: `<img src="${signedUrlFor(GUID_1, "")}">`,
},
});
@@ -669,12 +849,11 @@ describe("downloadCommentImages", () => {
}
});
test("should handle mismatched signed URL count", async () => {
test("should handle a signed URL missing for one of several images", async () => {
const mockOctokit = createMockOctokit();
const imageUrl1 = "https://github.com/user-attachments/assets/img1.png";
const imageUrl2 = "https://github.com/user-attachments/assets/img2.png";
const signedUrl1 =
"https://private-user-images.githubusercontent.com/1.png?jwt=token";
const imageUrl1 = assetUrl(GUID_1);
const imageUrl2 = assetUrl(GUID_2);
const signedUrl1 = signedUrlFor(GUID_1, ".png");
// Only one signed URL for two images
// @ts-expect-error Mock implementation doesn't match full type signature
@@ -710,14 +889,15 @@ describe("downloadCommentImages", () => {
"/tmp/github-images/image-1704067200000-0.png",
);
expect(result.get(imageUrl2)).toBeUndefined();
expect(consoleWarnSpy).toHaveBeenCalledWith(
`No matching signed URL found for ${imageUrl2}, skipping`,
);
});
test("should detect and download images from HTML img tags", async () => {
const mockOctokit = createMockOctokit();
const imageUrl =
"https://github.com/user-attachments/assets/html-image.png";
const signedUrl =
"https://private-user-images.githubusercontent.com/html.png?jwt=token";
const imageUrl = assetUrl(GUID_1);
const signedUrl = signedUrlFor(GUID_1, ".png");
// Mock octokit response
// @ts-expect-error Mock implementation doesn't match full type signature
@@ -777,14 +957,10 @@ describe("downloadCommentImages", () => {
test("should handle HTML img tags with different quote styles", async () => {
const mockOctokit = createMockOctokit();
const imageUrl1 =
"https://github.com/user-attachments/assets/single-quote.jpg";
const imageUrl2 =
"https://github.com/user-attachments/assets/double-quote.png";
const signedUrl1 =
"https://private-user-images.githubusercontent.com/single.jpg?jwt=token1";
const signedUrl2 =
"https://private-user-images.githubusercontent.com/double.png?jwt=token2";
const imageUrl1 = assetUrl(GUID_1, ".jpg");
const imageUrl2 = assetUrl(GUID_2, ".png");
const signedUrl1 = signedUrlFor(GUID_1, ".jpg", "token1");
const signedUrl2 = signedUrlFor(GUID_2, ".png", "token2");
// @ts-expect-error Mock implementation doesn't match full type signature
mockOctokit.rest.issues.getComment = jest.fn().mockResolvedValue({
@@ -828,18 +1004,17 @@ describe("downloadCommentImages", () => {
test("should handle mixed Markdown and HTML images", async () => {
const mockOctokit = createMockOctokit();
const markdownUrl =
"https://github.com/user-attachments/assets/markdown.png";
const htmlUrl = "https://github.com/user-attachments/assets/html.jpg";
const signedUrl1 =
"https://private-user-images.githubusercontent.com/md.png?jwt=token1";
const signedUrl2 =
"https://private-user-images.githubusercontent.com/html.jpg?jwt=token2";
const markdownUrl = assetUrl(GUID_1);
const htmlUrl = assetUrl(GUID_2, ".jpg");
const signedUrl1 = signedUrlFor(GUID_1, ".png", "token1");
const signedUrl2 = signedUrlFor(GUID_2, ".jpg", "token2");
// The rendered HTML has the images in document order (HTML tag first),
// which is the reverse of the order in which the URLs are extracted.
// @ts-expect-error Mock implementation doesn't match full type signature
mockOctokit.rest.issues.getComment = jest.fn().mockResolvedValue({
data: {
body_html: `<img src="${signedUrl1}"><img src="${signedUrl2}">`,
body_html: `<img src="${signedUrl2}"><img src="${signedUrl1}">`,
},
});
@@ -852,7 +1027,7 @@ describe("downloadCommentImages", () => {
{
type: "issue_comment",
id: "999",
body: `Markdown: ![test](${markdownUrl}) and HTML: <img src="${htmlUrl}" alt="test">`,
body: `HTML: <img src="${htmlUrl}" alt="test"> and Markdown: ![test](${markdownUrl})`,
},
];
@@ -878,9 +1053,8 @@ describe("downloadCommentImages", () => {
test("should deduplicate identical URLs from Markdown and HTML", async () => {
const mockOctokit = createMockOctokit();
const imageUrl = "https://github.com/user-attachments/assets/duplicate.png";
const signedUrl =
"https://private-user-images.githubusercontent.com/dup.png?jwt=token";
const imageUrl = assetUrl(GUID_1);
const signedUrl = signedUrlFor(GUID_1, ".png");
// @ts-expect-error Mock implementation doesn't match full type signature
mockOctokit.rest.issues.getComment = jest.fn().mockResolvedValue({
@@ -921,10 +1095,8 @@ describe("downloadCommentImages", () => {
test("should handle HTML img tags with additional attributes", async () => {
const mockOctokit = createMockOctokit();
const imageUrl =
"https://github.com/user-attachments/assets/complex-tag.webp";
const signedUrl =
"https://private-user-images.githubusercontent.com/complex.webp?jwt=token";
const imageUrl = assetUrl(GUID_3, ".webp");
const signedUrl = signedUrlFor(GUID_3, ".webp");
// @ts-expect-error Mock implementation doesn't match full type signature
mockOctokit.rest.issues.getComment = jest.fn().mockResolvedValue({
+40
View File
@@ -214,6 +214,46 @@ describe("prepareMcpConfig", () => {
);
});
test("should pin bun config flags before run for every bun server", async () => {
process.env.GITHUB_ACTION_PATH = "/test/action/path";
process.env.DEFAULT_WORKFLOW_TOKEN = "workflow-token";
const result = await prepareMcpConfig({
githubToken: "test-token",
owner: "test-owner",
repo: "test-repo",
branch: "test-branch",
baseBranch: "main",
allowedTools: ["mcp__github_inline_comment__create_inline_comment"],
mode: "tag",
context: {
...mockPRContext,
inputs: { ...mockPRContext.inputs, useCommitSigning: true },
},
});
const parsed = JSON.parse(result);
const servers: Record<string, string> = {
github_comment: "src/mcp/github-comment-server.ts",
github_file_ops: "src/mcp/github-file-ops-server.ts",
github_inline_comment: "src/mcp/github-inline-comment-server.ts",
github_ci: "src/mcp/github-actions-server.ts",
};
for (const [name, script] of Object.entries(servers)) {
expect(parsed.mcpServers[name]).toBeDefined();
expect(parsed.mcpServers[name].command).toBe("bun");
expect(parsed.mcpServers[name].args).toEqual([
"--no-env-file",
"--config=/test/action/path/bunfig.toml",
"run",
`/test/action/path/${script}`,
]);
}
delete process.env.DEFAULT_WORKFLOW_TOKEN;
});
test("should use current working directory when GITHUB_WORKSPACE is not set", async () => {
delete process.env.GITHUB_WORKSPACE;
+7 -1
View File
@@ -140,7 +140,7 @@ export const mockIssueOpenedContext: ParsedGitHubContext = {
body: "## Description\n\nThe application crashes immediately after launching.\n\n## Steps to reproduce\n\n1. Install the app\n2. Launch it\n3. See crash\n\n/claude please help me fix this",
assignee: null,
created_at: "2024-01-15T10:30:00Z",
updated_at: "2024-01-15T10:30:00Z",
updated_at: "2024-01-15T10:35:00Z",
html_url: "https://github.com/test-owner/test-repo/issues/42",
user: {
login: "john-doe",
@@ -191,6 +191,8 @@ export const mockIssueAssignedContext: ParsedGitHubContext = {
avatar_url: "https://avatars.githubusercontent.com/u/11111",
html_url: "https://github.com/claude-bot",
},
created_at: "2024-01-15T09:00:00Z",
updated_at: "2024-01-15T11:00:00Z",
},
repository: {
name: "test-repo",
@@ -225,6 +227,8 @@ export const mockIssueLabeledContext: ParsedGitHubContext = {
html_url: "https://github.com/alice-wonder",
},
assignee: null,
created_at: "2024-01-15T09:30:00Z",
updated_at: "2024-01-15T11:30:00Z",
},
label: {
id: 987654321,
@@ -355,6 +359,8 @@ export const mockPullRequestOpenedContext: ParsedGitHubContext = {
avatar_url: "https://avatars.githubusercontent.com/u/55555",
html_url: "https://github.com/feature-developer",
},
created_at: "2024-01-15T14:00:00Z",
updated_at: "2024-01-15T14:05:00Z",
},
repository: {
name: "test-repo",
+156
View File
@@ -3,6 +3,7 @@ import * as core from "@actions/core";
import { checkWritePermissions } from "../src/github/validation/permissions";
import type { ParsedGitHubContext } from "../src/github/context";
import { CLAUDE_APP_BOT_ID, CLAUDE_BOT_LOGIN } from "../src/github/constants";
import { createMockAutomationContext } from "./mockContext";
describe("checkWritePermissions", () => {
let coreInfoSpy: any;
@@ -455,4 +456,159 @@ describe("checkWritePermissions", () => {
expect(result).toBe(true);
});
});
describe("workflow_run contexts", () => {
const createWorkflowRunContext = (
actor: string,
runActor: string = actor,
) =>
createMockAutomationContext({
eventName: "workflow_run",
eventAction: "completed",
actor,
payload: {
action: "completed",
workflow_run: {
id: 123,
event: "pull_request",
actor: { login: runActor },
head_repository: { full_name: "fork-owner/test-repo" },
},
} as any,
});
const createMockOctokitWithLevels = (levels: Record<string, string>) =>
({
repos: {
getCollaboratorPermissionLevel: async (params: {
username: string;
}) => ({
data: { permission: levels[params.username] ?? "none" },
}),
},
}) as any;
test("should return false when the run actor lacks write access", async () => {
const mockOctokit = createMockOctokit("read");
const context = createWorkflowRunContext("fork-contributor");
const result = await checkWritePermissions(mockOctokit, context);
expect(result).toBe(false);
expect(coreWarningSpy).toHaveBeenCalledWith(
"Actor has insufficient permissions: read",
);
});
test("should return true when the run actor has write access", async () => {
const mockOctokit = createMockOctokit("write");
const context = createWorkflowRunContext("maintainer");
const result = await checkWritePermissions(mockOctokit, context);
expect(result).toBe(true);
});
test("should return true when the run actor has admin access", async () => {
const mockOctokit = createMockOctokit("admin");
const context = createWorkflowRunContext("maintainer");
const result = await checkWritePermissions(mockOctokit, context);
expect(result).toBe(true);
});
test("should also check the payload run actor when it differs from the workflow actor", async () => {
const mockOctokit = createMockOctokitWithLevels({
maintainer: "write",
"fork-contributor": "read",
});
const context = createWorkflowRunContext(
"maintainer",
"fork-contributor",
);
const result = await checkWritePermissions(mockOctokit, context);
expect(result).toBe(false);
expect(coreInfoSpy).toHaveBeenCalledWith(
"workflow_run was started by fork-contributor; checking permissions for that actor as well",
);
});
test("should return true when both the workflow actor and run actor have write access", async () => {
const mockOctokit = createMockOctokitWithLevels({
maintainer: "write",
"other-maintainer": "admin",
});
const context = createWorkflowRunContext(
"maintainer",
"other-maintainer",
);
const result = await checkWritePermissions(mockOctokit, context);
expect(result).toBe(true);
});
test("should allow a run actor listed in allowed_non_write_users when github_token is provided", async () => {
const mockOctokit = createMockOctokit("read");
const context = createWorkflowRunContext("fork-contributor");
const result = await checkWritePermissions(
mockOctokit,
context,
"fork-contributor,other-user",
true,
);
expect(result).toBe(true);
expect(coreWarningSpy).toHaveBeenCalledWith(
"⚠️ SECURITY WARNING: Bypassing write permission check for fork-contributor due to allowed_non_write_users configuration. This should only be used for workflows with very limited permissions.",
);
});
test("should NOT bypass for a run actor in allowed_non_write_users when github_token is not provided", async () => {
const mockOctokit = createMockOctokit("read");
const context = createWorkflowRunContext("fork-contributor");
const result = await checkWritePermissions(
mockOctokit,
context,
"fork-contributor",
false,
);
expect(result).toBe(false);
expect(coreWarningSpy).toHaveBeenCalledWith(
"Actor has insufficient permissions: read",
);
});
test("should require the payload run actor to also be in allowed_non_write_users", async () => {
const mockOctokit = createMockOctokit("read");
const context = createWorkflowRunContext(
"maintainer",
"fork-contributor",
);
const result = await checkWritePermissions(
mockOctokit,
context,
"maintainer",
true,
);
expect(result).toBe(false);
});
test("should return true for [bot] run actors", async () => {
const mockOctokit = createMockOctokit("none");
const context = createWorkflowRunContext("dependabot[bot]");
const result = await checkWritePermissions(mockOctokit, context);
expect(result).toBe(true);
});
});
});