Compare commits

...
42 Commits
Author SHA1 Message Date
GitHub Actions 3b8197d3d4 chore: bump Claude Code to 2.1.274 and Agent SDK to 0.3.274 2026-09-17 00:12:40 +00:00
GitHub Actions 7b0b255830 chore: bump Claude Code to 2.1.273 and Agent SDK to 0.3.273 2026-09-15 20:23:44 +00:00
GitHub Actions bf38e86e58 chore: bump Claude Code to 2.1.272 and Agent SDK to 0.3.272 2026-09-15 00:43:27 +00:00
GitHub Actions 51db78a4b8 chore: bump Claude Code to 2.1.271 and Agent SDK to 0.3.271 2026-09-14 22:13:27 +00:00
GitHub Actions 9cdae7f0d9 chore: bump Claude Code to 2.1.270 and Agent SDK to 0.3.270 2026-09-12 19:46:49 +00:00
GitHub Actions 56cf60fde4 chore: bump Claude Code to 2.1.269 and Agent SDK to 0.3.269 2026-09-11 19:18:51 +00:00
GitHub Actions 0a8d3c9443 chore: bump Claude Code to 2.1.268 and Agent SDK to 0.3.268 2026-09-10 20:39:16 +00:00
GitHub Actions 19dda84776 chore: bump Claude Code to 2.1.267 and Agent SDK to 0.3.267 2026-09-09 20:11:01 +00:00
GitHub Actions 5ccc3a35a6 chore: bump Claude Code to 2.1.266 and Agent SDK to 0.3.266 2026-09-08 23:56:12 +00:00
GitHub Actions 0d0e0876d3 chore: bump Claude Code to 2.1.265 and Agent SDK to 0.3.265 2026-09-08 20:38:21 +00:00
GitHub Actions 9c5ddab2e6 chore: bump Claude Code to 2.1.263 and Agent SDK to 0.3.263 2026-09-06 02:55:18 +00:00
GitHub Actions d75b94d5ad chore: bump Claude Code to 2.1.261 and Agent SDK to 0.3.261 2026-09-04 19:58:53 +00:00
GitHub Actions ef8bb1e43b chore: bump Claude Code to 2.1.260 and Agent SDK to 0.3.260 2026-09-03 23:48:49 +00:00
GitHub Actions fa2b2666b7 chore: bump Claude Code to 2.1.259 and Agent SDK to 0.3.259 2026-09-02 22:34:41 +00:00
GitHub Actions 8251c103ac chore: bump Claude Code to 2.1.258 and Agent SDK to 0.3.258 2026-09-01 22:33:40 +00:00
GitHub Actions 781d62e9d5 chore: bump Claude Code to 2.1.257 and Agent SDK to 0.3.257 2026-09-01 17:54:28 +00:00
GitHub Actions 833fb0f8c9 chore: bump Claude Code to 2.1.252 and Agent SDK to 0.3.252 2026-08-31 19:47:59 +00:00
GitHub Actions a874e9ecd7 chore: bump Claude Code to 2.1.251 and Agent SDK to 0.3.251 2026-08-28 18:20:42 +00:00
GitHub Actions a60f3e1db3 chore: bump Claude Code to 2.1.250 and Agent SDK to 0.3.250 2026-08-28 00:50:11 +00:00
GitHub Actions e8c2d7c16c chore: bump Claude Code to 2.1.248 and Agent SDK to 0.3.248 2026-08-27 22:12:44 +00:00
GitHub Actions 70fec18385 chore: bump Claude Code to 2.1.247 and Agent SDK to 0.3.247 2026-08-27 00:09:24 +00:00
GitHub Actions 1f291e1cfe chore: bump Claude Code to 2.1.246 and Agent SDK to 0.3.246 2026-08-25 22:32:51 +00:00
Muhammad Abdullah khanandGitHub 76ac41a83e fix: encode branch names in GitHub links (#1713)
* fix: encode branch names in GitHub links

* style: format branch URL helper
2026-08-25 11:02:49 -07:00
Jeremy SchoemakerandGitHub 8ef9699156 fix: bound download_job_log against a stalled log fetch (#1719)
The download_job_log MCP tool called
client.actions.downloadJobLogsForWorkflowRun() with no timeout and no
AbortController. @octokit/rest@21 runs on Node's native fetch, which has
no default timeout, and Octokit only cancels a request when the caller
passes request.signal. If the log blob fetch stalls, that await never
resolves and never rejects.

This tool is always enabled in tag mode (src/modes/tag/index.ts), so a
"fix the failing CI" run that calls get_ci_status -> get_workflow_run_details
-> download_job_log can hang on this one await with nothing to recover it.
It's headless, so the run only ends when the Actions job-level
timeout-minutes kills it, burning the whole job budget with the tracking
comment stuck at "Claude Code is working...".

Sibling fetch in src/github/utils/image-downloader.ts (fetchImage) already
got this treatment in #1625 via a timeout-driven AbortController. Same
shape of call: fetch a GitHub-hosted resource by ID from untrusted PR/CI
content. This mirrors that fix for github-actions-server.ts.

Extracted the download+write logic into an exported downloadJobLog()
function (with an injectable timeoutMs) so the timeout path is directly
testable, and guarded the module's entrypoint side effects with
import.meta.main, matching the pattern already used by the other
entrypoints in src/entrypoints/.
2026-08-25 08:46:02 -07:00
Yauheni PapovichandGitHub 791545dab1 fix: allow parentheses in valid branch names (#1710)
Accept parentheses while preserving existing branch-name security checks.

Add regression coverage for scoped branch names.

Refs anthropics/claude-code-action#1709
2026-08-25 08:45:50 -07:00
2d7a787fbd fix: use paths in delete_files prompt example (#1702)
* fix: use paths param in delete_files prompt example

The tag-mode prompt told the model to call delete_files with
"files", but the MCP tool schema and handler expect "paths".

Co-authored-by: Cursor <cursoragent@cursor.com>

* test: prove delete_files prompt against the live MCP schema

The old {files} payload is rejected by the same Zod shape the
tool registers; the generated prompt example now parses cleanly.

Co-authored-by: Cursor <cursoragent@cursor.com>

* test: cover delete_files schema edges and the sibling commit_files tool

Confirm the old files-only payload still fails, types and required
fields are enforced, and commit_files was not inverted by the fix.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: RESILIENCE Agentic Solutions <286555414+WeAreResilience@users.noreply.github.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-25 08:45:33 -07:00
Mohammed AlkindiandGitHub b58c16b325 chore: add .gitattributes to normalize line endings (#1708)
On Windows, git's default core.autocrlf=true checks out CRLF, and the contributor commands in CONTRIBUTING.md then fail: bun run format:check reports 191 files because Prettier defaults to endOfLine "lf", and three tests that match LF-terminated content fail.

All tracked blobs are already LF, so this changes checkout behavior only and produces no renormalization diff. Every CI job runs on ubuntu-latest, where it is a no-op.
2026-08-25 08:45:13 -07:00
GitHub Actions 16b3b310c3 chore: bump Claude Code to 2.1.245 and Agent SDK to 0.3.245 2026-08-25 05:14:05 +00:00
GitHub Actions 6bcfb8263a chore: bump Claude Code to 2.1.241 and Agent SDK to 0.3.241 2026-08-25 03:43:35 +00:00
GitHub Actions b62c7454dc chore: bump Claude Code to 2.1.241 and Agent SDK to 0.3.243 2026-08-25 03:38:24 +00:00
GitHub Actions e5ad3c7725 chore: bump Claude Code to 2.1.243 and Agent SDK to 0.3.243 2026-08-24 23:41:35 +00:00
GitHub Actions c81e3bc69d chore: bump Claude Code to 2.1.241 and Agent SDK to 0.3.241 2026-08-23 00:53:06 +00:00
GitHub Actions 24dcd50c05 chore: bump Claude Code to 2.1.240 and Agent SDK to 0.3.240 2026-08-22 14:45:56 +00:00
GitHub Actions dcb57747bf chore: bump Claude Code to 2.1.239 and Agent SDK to 0.3.239 2026-08-21 19:55:45 +00:00
492d2d78ee fix: teach claude_args --allowedTools in the signed prompt (#1704)
allowed_tools was removed in v1.0. The tag-mode prompt still named it
as the way to enable Bash under commit signing.

Co-authored-by: RESILIENCE Agentic Solutions <286555414+WeAreResilience@users.noreply.github.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 16:17:53 -07:00
2ca5fb4027 fix: surface resolved model limits (#1608)
Signed-off-by: ulofiai <monsterking@tutamail.com>
Co-authored-by: ulofiai <monsterking@tutamail.com>
2026-08-20 16:17:36 -07:00
f3f2789f0a fix(mcp): recognize mcp__github aggregate selector for GitHub MCP server initialization (#1657)
* fix(mcp): accept shorthand selectors for GitHub MCP server initialization

## Problem

Signed-off-by: anish <anishesg@users.noreply.github.com>

* address review feedback: fix prettier formatting

Signed-off-by: anish <anishesg@users.noreply.github.com>

---------

Signed-off-by: anish <anishesg@users.noreply.github.com>
Co-authored-by: anish <anishesg@users.noreply.github.com>
2026-08-20 16:17:25 -07:00
Gautam SharmaandGitHub 6a5f1d8e0a fix(cleanup): keep the base-branch config revert out of the auto-commit (#1677)
restoreConfigFromBase replaces .claude/, CLAUDE.md and the other sensitive
paths with the PR base branch's versions, then deliberately unstages them so
the revert does not reach a commit. checkAndCommitOrDeleteBranch then ran a
bare `git add -A`, which staged them again and pushed a silent revert of the
PR author's own config onto their branch, under a commit message that says
only "Auto-commit: Save uncommitted changes from Claude".

restoreConfigFromBase now returns the paths it restored. run.ts threads them
through updateCommentLink into checkAndCommitOrDeleteBranch, which excludes
them via pathspec from both the staging and the git status check.

The exclusion is driven by what was actually restored rather than applied
unconditionally. This path also runs for issues, where no restore happens and
Claude may legitimately have been asked to edit CLAUDE.md or
.claude/settings.json; excluding those there would silently drop the work —
trading one silent-data-loss bug for another. Reverting the fix, dropping the
status scoping, and switching to an unconditional exclusion each fail the new
tests.

The status check is scoped the same way as the staging: when the reverted
config is the only dirty entry there is no real work, so the branch is now
correctly treated as empty and deleted instead of receiving a pure revert.

Reachable on a closed or merged PR where Claude left uncommitted changes with
use_commit_signing false — the only combination where a restore has run and
claudeBranch is set.

Fixes #1669
2026-08-20 16:17:03 -07:00
HyunSooandGitHub 39ad3c8977 fix(github): honor GITHUB_GRAPHQL_URL for the GraphQL client (#1575)
The REST client honors GITHUB_API_URL, but the GraphQL client derived its
base URL from GITHUB_API_URL as well and ignored the standard
GITHUB_GRAPHQL_URL variable that GitHub Actions provides. On standard GitHub
Enterprise Server this still worked because @octokit/graphql rewrites a
".../api/v3" REST base to ".../api/graphql", but any deployment whose GraphQL
endpoint is not derivable from the REST base (custom proxy, separate host)
sent GraphQL requests to the wrong URL.

Honor GITHUB_GRAPHQL_URL independently and fall back to GITHUB_API_URL when it
is unset, so behavior is unchanged for github.com and standard GHES. A single
trailing "/graphql" is stripped because @octokit/graphql appends its own.

Add wire-level regression tests that run the real client factory in a fresh
process and assert the final request URLs and Authorization headers;
constructor-option assertions are insufficient because @octokit/graphql
rewrites the path after the client is constructed.
2026-08-20 15:45:21 -07:00
GitHub Actions 3f854a8fb5 chore: bump Claude Code to 2.1.238 and Agent SDK to 0.3.238 2026-08-20 20:33:55 +00:00
GitHub Actions 5ee796a55f chore: bump Claude Code to 2.1.237 and Agent SDK to 0.3.237 2026-08-20 00:54:23 +00:00
Tem RevilandGitHub cff8d3c8f0 fix(git-config): neutralize checkout credential in include-based config (#1526)
configureGitAuth() removed the actions/checkout auth header with
`git config --unset-all http.<server>/.extraheader`, which only edits the
repo-local config. Since actions/checkout v6.0.0 (backported to v5.0.1 and
v4.3.1) the header is written to a separate file under RUNNER_TEMP and
pulled in via include.path, so --unset-all on the local config is a no-op:
the code logged "No existing authentication headers to remove" while the
checkout credential (usually the workflow GITHUB_TOKEN) stayed usable by
git for the rest of the job.

Also clear the header from every included file, so it is neutralized under
both the pre-v6 (local) and v6+ (include) layouts. Includes that do not
define the header are left untouched.

Fixes #1510
2026-08-19 17:23:23 -07:00
33 changed files with 1230 additions and 100 deletions
+3
View File
@@ -0,0 +1,3 @@
# Keep the working tree LF on every platform: Prettier defaults to
# endOfLine "lf" and several tests match LF-terminated content.
* text=auto eol=lf
+1 -1
View File
@@ -147,7 +147,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.236"
CLAUDE_CODE_VERSION="2.1.274"
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.236",
"@anthropic-ai/claude-agent-sdk": "^0.3.274",
"shell-quote": "^1.8.4",
},
"devDependencies": {
@@ -27,23 +27,23 @@
"@actions/io": ["@actions/io@1.1.3", "", {}, "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q=="],
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/claude-agent-sdk@0.3.236", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.236", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.236", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.236", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.236", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.236", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.236", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.236", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.236" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-6SX3gLk4z4cOuixRRILC3QPcVxudJJU6oWm142PFnPADpXS0wYAukGcLueox9AoTZryuGw/JDa9h0yXBOcF8iQ=="],
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/claude-agent-sdk@0.3.274", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.274", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.274", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.274", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.274", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.274", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.274", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.274", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.274" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-kFmWMsh/BEd4jKkOxUeihr0xMkaMdOxONhNNkZ2pGmP0ElHkArvFvuZxqJTPvREnhCsPZByv5f0EzyAb/hkRZw=="],
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/claude-agent-sdk-darwin-arm64@0.3.236", "", { "os": "darwin", "cpu": "arm64" }, "sha512-vqIqXSGe7Ggx7twjXtjY6bF1mLap1ilOWCXokttkx7IQUfCUh74bMCfGNef9joyJnBLK6os45pYnkWYsvVR8mg=="],
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/claude-agent-sdk-darwin-arm64@0.3.274", "", { "os": "darwin", "cpu": "arm64" }, "sha512-B0uAdUIbUhWuybOT5FkhbdsALGNduyaHYo+bEggKBSQS3RFRjgNbX/ah1+IwkmTn4UKDN7AX86DkTEjpj6TSWQ=="],
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/claude-agent-sdk-darwin-x64@0.3.236", "", { "os": "darwin", "cpu": "x64" }, "sha512-XGlKze0Ls1sth5882AxVdB/9ojeMts1ZMHbaoWotRGop/9voYnsVe8v7URra0OdKG6V/cVD0C/qPxZGu4E0Giw=="],
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/claude-agent-sdk-darwin-x64@0.3.274", "", { "os": "darwin", "cpu": "x64" }, "sha512-l5pp3Z+z2mti0H3y1O0MRbTg/r+MDm0hly4WpoKmZyIZSOrDQR7jhCqS6Ihj3Vvd7CMP9NZ8t6F0oXVBDCM6YQ=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/claude-agent-sdk-linux-arm64@0.3.236", "", { "os": "linux", "cpu": "arm64" }, "sha512-LIcAcei35JZ4HZm2F+n0I89wo+bOY686rm7f65j92jmy8DKl1Egg2IepPxwq1hFXEpiyoGDoFXotmIpJMMscIw=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/claude-agent-sdk-linux-arm64@0.3.274", "", { "os": "linux", "cpu": "arm64" }, "sha512-kYsmSN6zieDwVS3QZBBay9fxNp+h4t4OXleuk6xWhrUDEQRfRQEFlD7JVWWWjJIiHILnniycOxarwo4VpqTf1Q=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/claude-agent-sdk-linux-arm64-musl@0.3.236", "", { "os": "linux", "cpu": "arm64" }, "sha512-xbDSnNvuHFTS6od9fZh+vkP9QuYZQfZ9i4F/ClHpzCrKBvs4H3lDVzgayrXawTHKMCItBtDaIuiytkED1uzYtg=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/claude-agent-sdk-linux-arm64-musl@0.3.274", "", { "os": "linux", "cpu": "arm64" }, "sha512-pNjZQRF3f1O5JwnoifuAD7tSRfk9LSwwBzEPiUHB4sJgatF6hzqyDgTN05hcDx28xg44j0jpKpyVwsjveI/s4g=="],
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/claude-agent-sdk-linux-x64@0.3.236", "", { "os": "linux", "cpu": "x64" }, "sha512-9ESjHUylyrnReQtitQReYUN9AurhsHZ9hDcMBUOzXhKjp9muC/y+4jsFTrlgy7QBLFfwhb1QiciViXefZ24e8A=="],
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/claude-agent-sdk-linux-x64@0.3.274", "", { "os": "linux", "cpu": "x64" }, "sha512-QLeK9LzTtTdCjCDRYUVRHj1I3U6AfMvpXYI4Ur1s+vrUcad/C20kShS5/kgug+rERU5CNxNA9v0A052rt47ZXQ=="],
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/claude-agent-sdk-linux-x64-musl@0.3.236", "", { "os": "linux", "cpu": "x64" }, "sha512-7AEidXQl7Ag1/FC52nm9uWJmQfibcogWZvWDrFC5Hnf/XgLphUcChzn8EIEpD6PbTDuqAuibZM+FUOIlfN5hrA=="],
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/claude-agent-sdk-linux-x64-musl@0.3.274", "", { "os": "linux", "cpu": "x64" }, "sha512-a9eIkmgJ5sSywHwWJcComogjIMsfHsurckQ85ljPNTUSFguzl/ZvbTXGiWNRK5rHsoNd3amwQf2fVC/vFyv3eg=="],
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/claude-agent-sdk-win32-arm64@0.3.236", "", { "os": "win32", "cpu": "arm64" }, "sha512-MARkstVLnFL4ZVCAkHYtAQqOzBZQMh2HWC4UonJ+yp3c7JWuuTfE09FbZX1jWIHZP6Hw4qWO7LFmXr2CgKXf8Q=="],
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/claude-agent-sdk-win32-arm64@0.3.274", "", { "os": "win32", "cpu": "arm64" }, "sha512-A5wvZAXL3nhuabIXUcRuoYhuPPdEIt3LoA3jUkVLT3c0H+7SH0rv5bylpM9n+apf7lwLCm2TdMZ6x1Ze1Vzekg=="],
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/claude-agent-sdk-win32-x64@0.3.236", "", { "os": "win32", "cpu": "x64" }, "sha512-4HS8lLUubJQYiUNQ/6Qzqx6MgtorNA8nVpTo5B1iakfMha7/8BhIT1ZCIQM2FWOoIAP9bNP11ToDxKLx3U4QcA=="],
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/claude-agent-sdk-win32-x64@0.3.274", "", { "os": "win32", "cpu": "x64" }, "sha512-dGcaLfEpV4kwcSijPAIJru+iEiVhHvbBdkyixPyhhf8pniV9B62nUMFFsjNtYL37xIPHxixh2Gsx9/A+Yk4oww=="],
"@anthropic-ai/sdk": ["@anthropic-ai/sdk@0.93.0", "", { "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.236",
"@anthropic-ai/claude-agent-sdk": "^0.3.274",
"shell-quote": "^1.8.4"
},
"devDependencies": {
+30
View File
@@ -82,6 +82,35 @@ async function createPromptConfig(
return createMultiBlockMessage();
}
type ModelUsageSummary = Record<
string,
{
contextWindow: number;
maxOutputTokens: number;
}
>;
/**
* Keep resolved model limits visible without exposing token usage or cost details.
*/
function sanitizeModelUsage(
modelUsage: SDKResultMessage["modelUsage"] | undefined,
): ModelUsageSummary | undefined {
if (!modelUsage) {
return undefined;
}
return Object.fromEntries(
Object.entries(modelUsage).map(([model, usage]) => [
model,
{
contextWindow: usage.contextWindow,
maxOutputTokens: usage.maxOutputTokens,
},
]),
);
}
/**
* Sanitizes SDK output to match CLI sanitization behavior
*/
@@ -119,6 +148,7 @@ function sanitizeSdkOutput(
num_turns: resultMsg.num_turns,
total_cost_usd: resultMsg.total_cost_usd,
permission_denials_count: resultMsg.permission_denials?.length ?? 0,
modelUsage: sanitizeModelUsage(resultMsg.modelUsage),
},
null,
2,
+89
View File
@@ -64,6 +64,95 @@ describe("runClaudeWithSdk", () => {
}
});
test("logs resolved model limits without exposing token usage", async () => {
const consoleLogSpy = spyOn(console, "log").mockImplementation(() => {});
tempDir = await mkdtemp(join(tmpdir(), "claude-sdk-"));
process.env.RUNNER_TEMP = tempDir;
const promptPath = join(tempDir, "prompt.txt");
await writeFile(promptPath, "test prompt");
const initMessage = {
type: "system",
subtype: "init",
session_id: "session-123",
model: "claude-opus-5",
};
const resultMessage = {
type: "result",
subtype: "success",
is_error: false,
duration_ms: 434,
num_turns: 1,
total_cost_usd: 1.23,
permission_denials: [],
modelUsage: {
"claude-opus-5": {
inputTokens: 96209,
outputTokens: 55324,
cacheReadInputTokens: 1135701,
cacheCreationInputTokens: 149043,
webSearchRequests: 0,
costUSD: 1.23,
contextWindow: 200000,
maxOutputTokens: 64000,
},
},
};
mock.module("@anthropic-ai/claude-agent-sdk", () => ({
query: async function* () {
yield initMessage;
yield resultMessage;
},
}));
try {
const { runClaudeWithSdk } = await import("../src/run-claude-sdk");
await expect(
runClaudeWithSdk(promptPath, {
sdkOptions: {},
showFullOutput: false,
hasJsonSchema: false,
}),
).resolves.toMatchObject({ conclusion: "success" });
const sanitizedResult = consoleLogSpy.mock.calls
.map(([message]) => message)
.find(
(message) =>
typeof message === "string" && message.includes('"type": "result"'),
);
expect(sanitizedResult).toBeDefined();
if (typeof sanitizedResult !== "string") {
throw new Error("Sanitized result output was not logged");
}
expect(JSON.parse(sanitizedResult)).toEqual({
type: "result",
subtype: "success",
is_error: false,
duration_ms: 434,
num_turns: 1,
total_cost_usd: 1.23,
permission_denials_count: 0,
modelUsage: {
"claude-opus-5": {
contextWindow: 200000,
maxOutputTokens: 64000,
},
},
});
expect(sanitizedResult).not.toContain("inputTokens");
expect(sanitizedResult).not.toContain("costUSD");
} finally {
consoleLogSpy.mockRestore();
}
});
test("fails when result subtype is success but is_error is true", async () => {
const consoleErrorSpy = spyOn(console, "error").mockImplementation(
() => {},
+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.236",
"@anthropic-ai/claude-agent-sdk": "^0.3.274",
"@modelcontextprotocol/sdk": "^1.11.0",
"@octokit/graphql": "^8.2.2",
"@octokit/rest": "^21.1.1",
@@ -37,23 +37,23 @@
"@actions/io": ["@actions/io@1.1.3", "", {}, "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q=="],
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/claude-agent-sdk@0.3.236", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.236", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.236", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.236", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.236", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.236", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.236", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.236", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.236" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-6SX3gLk4z4cOuixRRILC3QPcVxudJJU6oWm142PFnPADpXS0wYAukGcLueox9AoTZryuGw/JDa9h0yXBOcF8iQ=="],
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/claude-agent-sdk@0.3.274", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.274", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.274", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.274", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.274", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.274", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.274", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.274", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.274" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-kFmWMsh/BEd4jKkOxUeihr0xMkaMdOxONhNNkZ2pGmP0ElHkArvFvuZxqJTPvREnhCsPZByv5f0EzyAb/hkRZw=="],
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/claude-agent-sdk-darwin-arm64@0.3.236", "", { "os": "darwin", "cpu": "arm64" }, "sha512-vqIqXSGe7Ggx7twjXtjY6bF1mLap1ilOWCXokttkx7IQUfCUh74bMCfGNef9joyJnBLK6os45pYnkWYsvVR8mg=="],
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/claude-agent-sdk-darwin-arm64@0.3.274", "", { "os": "darwin", "cpu": "arm64" }, "sha512-B0uAdUIbUhWuybOT5FkhbdsALGNduyaHYo+bEggKBSQS3RFRjgNbX/ah1+IwkmTn4UKDN7AX86DkTEjpj6TSWQ=="],
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/claude-agent-sdk-darwin-x64@0.3.236", "", { "os": "darwin", "cpu": "x64" }, "sha512-XGlKze0Ls1sth5882AxVdB/9ojeMts1ZMHbaoWotRGop/9voYnsVe8v7URra0OdKG6V/cVD0C/qPxZGu4E0Giw=="],
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/claude-agent-sdk-darwin-x64@0.3.274", "", { "os": "darwin", "cpu": "x64" }, "sha512-l5pp3Z+z2mti0H3y1O0MRbTg/r+MDm0hly4WpoKmZyIZSOrDQR7jhCqS6Ihj3Vvd7CMP9NZ8t6F0oXVBDCM6YQ=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/claude-agent-sdk-linux-arm64@0.3.236", "", { "os": "linux", "cpu": "arm64" }, "sha512-LIcAcei35JZ4HZm2F+n0I89wo+bOY686rm7f65j92jmy8DKl1Egg2IepPxwq1hFXEpiyoGDoFXotmIpJMMscIw=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/claude-agent-sdk-linux-arm64@0.3.274", "", { "os": "linux", "cpu": "arm64" }, "sha512-kYsmSN6zieDwVS3QZBBay9fxNp+h4t4OXleuk6xWhrUDEQRfRQEFlD7JVWWWjJIiHILnniycOxarwo4VpqTf1Q=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/claude-agent-sdk-linux-arm64-musl@0.3.236", "", { "os": "linux", "cpu": "arm64" }, "sha512-xbDSnNvuHFTS6od9fZh+vkP9QuYZQfZ9i4F/ClHpzCrKBvs4H3lDVzgayrXawTHKMCItBtDaIuiytkED1uzYtg=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/claude-agent-sdk-linux-arm64-musl@0.3.274", "", { "os": "linux", "cpu": "arm64" }, "sha512-pNjZQRF3f1O5JwnoifuAD7tSRfk9LSwwBzEPiUHB4sJgatF6hzqyDgTN05hcDx28xg44j0jpKpyVwsjveI/s4g=="],
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/claude-agent-sdk-linux-x64@0.3.236", "", { "os": "linux", "cpu": "x64" }, "sha512-9ESjHUylyrnReQtitQReYUN9AurhsHZ9hDcMBUOzXhKjp9muC/y+4jsFTrlgy7QBLFfwhb1QiciViXefZ24e8A=="],
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/claude-agent-sdk-linux-x64@0.3.274", "", { "os": "linux", "cpu": "x64" }, "sha512-QLeK9LzTtTdCjCDRYUVRHj1I3U6AfMvpXYI4Ur1s+vrUcad/C20kShS5/kgug+rERU5CNxNA9v0A052rt47ZXQ=="],
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/claude-agent-sdk-linux-x64-musl@0.3.236", "", { "os": "linux", "cpu": "x64" }, "sha512-7AEidXQl7Ag1/FC52nm9uWJmQfibcogWZvWDrFC5Hnf/XgLphUcChzn8EIEpD6PbTDuqAuibZM+FUOIlfN5hrA=="],
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/claude-agent-sdk-linux-x64-musl@0.3.274", "", { "os": "linux", "cpu": "x64" }, "sha512-a9eIkmgJ5sSywHwWJcComogjIMsfHsurckQ85ljPNTUSFguzl/ZvbTXGiWNRK5rHsoNd3amwQf2fVC/vFyv3eg=="],
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/claude-agent-sdk-win32-arm64@0.3.236", "", { "os": "win32", "cpu": "arm64" }, "sha512-MARkstVLnFL4ZVCAkHYtAQqOzBZQMh2HWC4UonJ+yp3c7JWuuTfE09FbZX1jWIHZP6Hw4qWO7LFmXr2CgKXf8Q=="],
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/claude-agent-sdk-win32-arm64@0.3.274", "", { "os": "win32", "cpu": "arm64" }, "sha512-A5wvZAXL3nhuabIXUcRuoYhuPPdEIt3LoA3jUkVLT3c0H+7SH0rv5bylpM9n+apf7lwLCm2TdMZ6x1Ze1Vzekg=="],
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/claude-agent-sdk-win32-x64@0.3.236", "", { "os": "win32", "cpu": "x64" }, "sha512-4HS8lLUubJQYiUNQ/6Qzqx6MgtorNA8nVpTo5B1iakfMha7/8BhIT1ZCIQM2FWOoIAP9bNP11ToDxKLx3U4QcA=="],
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/claude-agent-sdk-win32-x64@0.3.274", "", { "os": "win32", "cpu": "x64" }, "sha512-dGcaLfEpV4kwcSijPAIJru+iEiVhHvbBdkyixPyhhf8pniV9B62nUMFFsjNtYL37xIPHxixh2Gsx9/A+Yk4oww=="],
"@anthropic-ai/sdk": ["@anthropic-ai/sdk@0.93.0", "", { "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=="],
+23
View File
@@ -275,6 +275,29 @@ For provider-specific models:
# ... other inputs
```
### 1M context models through an API gateway
When `ANTHROPIC_BASE_URL` points to an Anthropic-compatible API gateway,
Claude Code may not be able to verify that the gateway supports a model's native
1M context window and can budget the session at 200K instead. Append the
`[1m]` selector to explicitly use the 1M context window for supported models,
including Claude Opus 5 and Claude Sonnet 5:
```yaml
- uses: anthropics/claude-code-action@v1
with:
claude_args: |
--model "claude-opus-5[1m]"
# ... other inputs
```
Use the same selector when setting a model through `ANTHROPIC_MODEL` or another
Claude Code model environment variable. The selector is resolved by Claude Code
before requests are sent to the provider. The action's sanitized result output
includes each model's resolved
`contextWindow` and `maxOutputTokens` under `modelUsage`, so these limits are
visible without enabling `show_full_output`.
## 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.
+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.236",
"@anthropic-ai/claude-agent-sdk": "^0.3.274",
"@modelcontextprotocol/sdk": "^1.11.0",
"@octokit/graphql": "^8.2.2",
"@octokit/rest": "^21.1.1",
+2 -2
View File
@@ -824,7 +824,7 @@ ${
? `- 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:
- 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: {"paths": ["path/to/old.js"], "message": "chore: remove deprecated file"}`
: `- Use git commands via the Bash tool for version control (remember that you have access to these git commands):
- Stage files: Bash(git add <files>)
- Commit changes: Bash(git commit -m "<message>")
@@ -856,7 +856,7 @@ What You CANNOT Do:
- Submit formal GitHub PR reviews
- Approve pull requests (for security reasons)
- Post multiple comments (you only update your initial comment)
- Execute commands outside the repository context${useCommitSigning ? "\n- Run arbitrary Bash commands (unless explicitly allowed via allowed_tools configuration)" : ""}
- Execute commands outside the repository context${useCommitSigning ? "\n- Run arbitrary Bash commands (unless explicitly allowed via claude_args with --allowedTools)" : ""}
- Perform branch operations (cannot merge branches, rebase, or perform other git operations beyond creating and pushing commits)
- Modify files in the .github/workflows directory (GitHub App permissions do not allow workflow modifications)
+6 -2
View File
@@ -77,7 +77,7 @@ async function installClaudeCode(): Promise<string> {
return customExecutable;
}
const claudeCodeVersion = "2.1.236";
const claudeCodeVersion = "2.1.274";
console.log(`Installing Claude Code v${claudeCodeVersion}...`);
for (let attempt = 1; attempt <= 3; attempt++) {
@@ -159,6 +159,9 @@ async function run() {
let context: GitHubContext | undefined;
let octokit: Octokits | undefined;
let workloadIdentity: WorkloadIdentityHandle | undefined;
// Paths reverted to the PR base branch, which cleanup must not commit back
// onto the PR author's branch. Empty unless restoreConfigFromBase ran.
let restoredConfigPaths: string[] = [];
// Track whether we've completed prepare phase, so we can attribute errors correctly
let prepareCompleted = false;
try {
@@ -268,7 +271,7 @@ async function run() {
validateBranchName(restoreBase);
}
if (restoreBase) {
restoreConfigFromBase(restoreBase);
restoredConfigPaths = restoreConfigFromBase(restoreBase);
}
}
@@ -348,6 +351,7 @@ async function run() {
prepareSuccess,
prepareError,
useCommitSigning: context.inputs.useCommitSigning,
restoredConfigPaths,
});
} catch (error) {
console.error("Error updating comment with job link:", error);
+10 -1
View File
@@ -16,6 +16,7 @@ import type { ParsedGitHubContext } from "../github/context";
import { GITHUB_SERVER_URL } from "../github/api/config";
import { checkAndCommitOrDeleteBranch } from "../github/operations/branch-cleanup";
import { updateClaudeComment } from "../github/operations/comments/update-claude-comment";
import { encodeBranchNameForUrl } from "../github/operations/comments/common";
export type UpdateCommentLinkParams = {
commentId: number;
@@ -30,6 +31,12 @@ export type UpdateCommentLinkParams = {
prepareSuccess: boolean;
prepareError?: string;
useCommitSigning: boolean;
/**
* Paths restored from the PR base branch by restoreConfigFromBase. The
* auto-commit in checkAndCommitOrDeleteBranch must leave these alone, or it
* commits the revert onto the PR author's branch.
*/
restoredConfigPaths?: string[];
};
export async function updateCommentLink(
@@ -43,6 +50,7 @@ export async function updateCommentLink(
context,
octokit,
useCommitSigning,
restoredConfigPaths = [],
} = params;
const { owner, repo } = context.repository;
@@ -116,6 +124,7 @@ export async function updateCommentLink(
claudeBranch,
baseBranch,
useCommitSigning,
restoredConfigPaths,
);
// Check if we need to add PR URL when we have a new branch
@@ -151,7 +160,7 @@ export async function updateCommentLink(
const prBody = encodeURIComponent(
`This PR addresses ${entityType.toLowerCase()} #${context.entityNumber}\n\nGenerated with [Claude Code](https://claude.ai/code)`,
);
const prUrl = `${serverUrl}/${owner}/${repo}/compare/${baseBranch}...${claudeBranch}?quick_pull=1&title=${prTitle}&body=${prBody}`;
const prUrl = `${serverUrl}/${owner}/${repo}/compare/${encodeBranchNameForUrl(baseBranch)}...${encodeBranchNameForUrl(claudeBranch)}?quick_pull=1&title=${prTitle}&body=${prBody}`;
prLink = `\n[Create a PR](${prUrl})`;
}
} catch (error) {
+2 -2
View File
@@ -1,6 +1,6 @@
import { Octokit } from "@octokit/rest";
import { graphql } from "@octokit/graphql";
import { GITHUB_API_URL } from "./config";
import { GITHUB_API_URL, GITHUB_GRAPHQL_URL } from "./config";
export type Octokits = {
rest: Octokit;
@@ -14,7 +14,7 @@ export function createOctokit(token: string): Octokits {
baseUrl: GITHUB_API_URL,
}),
graphql: graphql.defaults({
baseUrl: GITHUB_API_URL,
baseUrl: GITHUB_GRAPHQL_URL,
headers: {
authorization: `token ${token}`,
},
+13
View File
@@ -2,3 +2,16 @@ export const GITHUB_API_URL =
process.env.GITHUB_API_URL || "https://api.github.com";
export const GITHUB_SERVER_URL =
process.env.GITHUB_SERVER_URL || "https://github.com";
// GraphQL base URL for @octokit/graphql. GitHub Actions exposes the full GraphQL
// endpoint in GITHUB_GRAPHQL_URL (e.g. "https://HOST/api/graphql"), while
// @octokit/graphql appends "/graphql" to whatever baseUrl it is given, so a
// single trailing "/graphql" is stripped here to avoid "/graphql/graphql".
// When GITHUB_GRAPHQL_URL is unset we fall back to GITHUB_API_URL, preserving the
// existing behavior where @octokit/graphql rewrites a REST ".../api/v3" base to
// ".../api/graphql". The trailing-slash trim keeps that rewrite working.
export const GITHUB_GRAPHQL_URL = (
process.env.GITHUB_GRAPHQL_URL || GITHUB_API_URL
)
.replace(/\/+$/, "")
.replace(/\/graphql$/, "");
+34 -7
View File
@@ -1,5 +1,6 @@
import type { Octokits } from "../api/client";
import { GITHUB_SERVER_URL } from "../api/config";
import { encodeBranchNameForUrl } from "./comments/common";
import { $ } from "bun";
export async function checkAndCommitOrDeleteBranch(
@@ -9,10 +10,32 @@ export async function checkAndCommitOrDeleteBranch(
claudeBranch: string | undefined,
baseBranch: string,
useCommitSigning: boolean,
restoredConfigPaths: string[] = [],
): Promise<{ shouldDeleteBranch: boolean; branchLink: string }> {
let branchLink = "";
let shouldDeleteBranch = false;
// On pull requests, restoreConfigFromBase replaces .claude/, CLAUDE.md and
// friends with the base branch's versions and leaves them unstaged so the
// revert does not reach a commit. Auto-committing with a bare `git add -A`
// would stage them anyway and push a silent revert of the PR author's own
// config onto their branch.
//
// The exclusion is driven by what was actually restored rather than applied
// unconditionally: this path also runs for issues, where no restore happens
// and Claude may legitimately have been asked to edit CLAUDE.md or
// .claude/settings.json. Excluding those there would silently drop the work.
const pathspecArgs =
restoredConfigPaths.length > 0
? ["--", ".", ...restoredConfigPaths.map((p) => `:(exclude)${p}`)]
: [];
if (pathspecArgs.length > 0) {
console.log(
`Excluding base-restored config from auto-commit: ${restoredConfigPaths.join(", ")}`,
);
}
if (claudeBranch) {
// First check if the branch exists remotely
let branchExistsRemotely = false;
@@ -57,15 +80,19 @@ export async function checkAndCommitOrDeleteBranch(
// Check for uncommitted changes using git status
try {
const gitStatus = await $`git status --porcelain`.quiet();
// Scoped the same way as the staging below: if the restored config
// is the only dirty entry there is no real work, and the branch
// should be treated as empty rather than receiving a pure revert.
const gitStatus =
await $`git status --porcelain ${pathspecArgs}`.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`;
// Add all changes, minus anything restored from the base branch
await $`git add -A ${pathspecArgs}`;
// Commit with a descriptive message
const runId = process.env.GITHUB_RUN_ID || "unknown";
@@ -80,7 +107,7 @@ export async function checkAndCommitOrDeleteBranch(
);
// Set branch link since we now have commits
const branchUrl = `${GITHUB_SERVER_URL}/${owner}/${repo}/tree/${claudeBranch}`;
const branchUrl = `${GITHUB_SERVER_URL}/${owner}/${repo}/tree/${encodeBranchNameForUrl(claudeBranch)}`;
branchLink = `\n[View branch](${branchUrl})`;
} else {
console.log(
@@ -91,7 +118,7 @@ export async function checkAndCommitOrDeleteBranch(
} 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}`;
const branchUrl = `${GITHUB_SERVER_URL}/${owner}/${repo}/tree/${encodeBranchNameForUrl(claudeBranch)}`;
branchLink = `\n[View branch](${branchUrl})`;
}
} else {
@@ -102,13 +129,13 @@ export async function checkAndCommitOrDeleteBranch(
}
} else {
// 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/${encodeBranchNameForUrl(claudeBranch)}`;
branchLink = `\n[View branch](${branchUrl})`;
}
} catch (error) {
console.error("Error comparing commits on Claude branch:", error);
// 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/${encodeBranchNameForUrl(claudeBranch)}`;
branchLink = `\n[View branch](${branchUrl})`;
}
}
+6 -4
View File
@@ -29,7 +29,7 @@ function extractFirstLabel(githubData: FetchDataResult): string | undefined {
*
* Valid branch names:
* - Start with alphanumeric character, underscore, or @ (not dash, to prevent option injection)
* - Contain only alphanumeric, forward slash, hyphen, underscore, period, hash (#), plus (+), comma (,), or at sign (@)
* - Contain only alphanumeric, forward slash, hyphen, underscore, period, hash (#), plus (+), comma (,), at sign (@), or parentheses
* - Do not start or end with a period
* - Do not end with a slash
* - Do not contain '..' (path traversal)
@@ -60,7 +60,7 @@ export function validateBranchName(branchName: string): void {
);
}
// Strict whitelist pattern: alphanumeric or @ start, then alphanumeric/slash/hyphen/underscore/period/hash/plus/comma/at-sign.
// Strict whitelist pattern: alphanumeric or @ start, then alphanumeric/slash/hyphen/underscore/period/hash/plus/comma/at-sign/parentheses.
// # is valid per git-check-ref-format and commonly used in branch names like "fix/#123-description".
// + is valid per git-check-ref-format and generated by Claude Code's EnterWorktree tool when
// converting worktree names containing "/" (e.g. "feat/foo" becomes "worktree-feat+foo").
@@ -72,12 +72,14 @@ export function validateBranchName(branchName: string): void {
// _ is valid per git-check-ref-format anywhere in a ref name, including the first character;
// leading underscores are a common convention for release/internal branches (e.g.
// "_release/v1.2.3"), which previously failed validation as a PR's base branch.
// Parentheses are valid per git-check-ref-format and commonly appear in branch names that
// use Conventional Commit-style scopes (e.g. "feat(parser)-handle-empty-input").
// All git calls use execFileSync (not shell interpolation), so none of these characters carry injection risk.
const validPattern = /^[a-zA-Z0-9@_][a-zA-Z0-9/_.#+,@-]*$/;
const validPattern = /^[a-zA-Z0-9@_][a-zA-Z0-9/_.#+,@()-]*$/;
if (!validPattern.test(branchName)) {
throw new Error(
`Invalid branch name: "${branchName}". Branch names must start with an alphanumeric character, underscore, or '@' and contain only alphanumeric characters, forward slashes, hyphens, underscores, periods, hashes (#), plus signs (+), commas (,), or at signs (@).`,
`Invalid branch name: "${branchName}". Branch names must start with an alphanumeric character, underscore, or '@' and contain only alphanumeric characters, forward slashes, hyphens, underscores, periods, hashes (#), plus signs (+), commas (,), at signs (@), or parentheses.`,
);
}
+2 -1
View File
@@ -1,5 +1,6 @@
import { GITHUB_SERVER_URL } from "../api/config";
import { redactSecrets } from "../utils/sanitizer";
import { encodeBranchNameForUrl } from "./comments/common";
export type ExecutionDetails = {
total_cost_usd?: number;
@@ -161,7 +162,7 @@ export function updateCommentBody(input: CommentUpdateInput): string {
// Extract owner/repo from jobUrl
const repoMatch = jobUrl.match(/github\.com\/([^\/]+)\/([^\/]+)\//);
if (repoMatch) {
branchUrl = `${GITHUB_SERVER_URL}/${repoMatch[1]}/${repoMatch[2]}/tree/${finalBranchName}`;
branchUrl = `${GITHUB_SERVER_URL}/${repoMatch[1]}/${repoMatch[2]}/tree/${encodeBranchNameForUrl(finalBranchName)}`;
}
}
+6 -1
View File
@@ -12,12 +12,17 @@ export function createJobRunLink(
return `[View job run](${jobRunUrl})`;
}
/** Encode Git-ref path segments without turning `/` into `%2F`. */
export function encodeBranchNameForUrl(branchName: string): string {
return branchName.split("/").map(encodeURIComponent).join("/");
}
export function createBranchLink(
owner: string,
repo: string,
branchName: string,
): string {
const branchUrl = `${GITHUB_SERVER_URL}/${owner}/${repo}/tree/${branchName}`;
const branchUrl = `${GITHUB_SERVER_URL}/${owner}/${repo}/tree/${encodeBranchNameForUrl(branchName)}`;
return `\n[View branch](${branchUrl})`;
}
+37 -4
View File
@@ -56,6 +56,16 @@ export async function configureGitAuth(
* action's own token instead (a credential helper when non-write users are
* allowed, otherwise the origin URL). This applies to every mode, including API
* commit signing where no other git configuration is needed.
*
* actions/checkout < v6 stored the header directly in the repo-local config,
* where `git config --unset-all` removes it. Since v6.0.0 (backported to
* v5.0.1 and v4.3.1) the header is written to a separate file under
* RUNNER_TEMP that the repo config pulls in via `include.path`; `--unset-all`
* on the local config cannot touch an include-provided value, so the removal
* was a silent no-op and the checkout credential (typically the workflow
* GITHUB_TOKEN) stayed usable by git for the rest of the job. Clear the
* header from the local config AND from every included file so it can no
* longer authenticate while Claude runs.
*/
export async function replaceCheckoutCredentials(
githubToken: string,
@@ -65,12 +75,35 @@ export async function replaceCheckoutCredentials(
// Remove the authorization header that actions/checkout sets
console.log("Removing existing git authentication headers...");
const extraheaderKey = `http.${GITHUB_SERVER_URL}/.extraheader`;
let removedHeader = false;
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");
await $`git config --unset-all ${extraheaderKey}`;
removedHeader = true;
} catch {
// No extraheader in the local config (expected on the v6+ include layout).
}
try {
const includePaths =
await $`git config --local --get-all include.path`.text();
for (const includePath of includePaths.split("\n")) {
const path = includePath.trim();
if (!path) continue;
try {
await $`git config --file ${path} --unset-all ${extraheaderKey}`;
removedHeader = true;
} catch {
// This include does not define the header; leave it untouched.
}
}
} catch {
// No include.path entries in the local config.
}
console.log(
removedHeader
? "✓ Removed existing authentication headers"
: "No existing authentication headers to remove",
);
if (process.env.ALLOWED_NON_WRITE_USERS) {
// When processing content from non-write users, use a credential helper
+10 -2
View File
@@ -23,7 +23,7 @@ import { fetchDepthArgs } from "./fetch-depth";
// .gitconfig — git reads ~/.gitconfig and .git/config, never cwd/.gitconfig.
// .bashrc etc. — shells source these from $HOME; checkout cannot reach $HOME.
// .vscode/.idea— IDE config; nothing in the CLI's startup path reads them.
const SENSITIVE_PATHS = [
export const SENSITIVE_PATHS = [
".claude",
".mcp.json",
".claude.json",
@@ -262,8 +262,11 @@ function ensureClaudePrExcludedFromGit(): void {
*
* @param baseBranch - PR base branch name. Must be pre-validated (branch.ts
* calls validateBranchName on it before returning).
* @returns The paths whose working-tree state now comes from the base branch
* rather than the PR. Callers that stage files must exclude these, or they
* will commit the revert back onto the PR author's branch.
*/
export function restoreConfigFromBase(baseBranch: string): void {
export function restoreConfigFromBase(baseBranch: string): string[] {
console.log(
`Restoring ${SENSITIVE_PATHS.join(", ")} from origin/${baseBranch} (PR head is untrusted)`,
);
@@ -338,4 +341,9 @@ export function restoreConfigFromBase(baseBranch: string): void {
} catch {
// Nothing was staged, or paths don't exist on HEAD — either is fine.
}
// Every sensitive path is reported, not just the ones that changed: the
// restore also deletes paths the PR added that are absent on base, and those
// deletions are stageable too.
return [...SENSITIVE_PATHS];
}
+56 -26
View File
@@ -17,11 +17,18 @@ 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);
// Job logs are fetched by ID from GitHub-hosted storage; bound the request so a
// stalled fetch can't hang this MCP call forever. Mirrors the timeout added to
// fetchImage() in src/github/utils/image-downloader.ts (#1625).
const DOWNLOAD_JOB_LOG_TIMEOUT_MS = 30_000;
if (import.meta.main) {
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({
@@ -205,6 +212,40 @@ server.tool(
},
);
export async function downloadJobLog(
client: Octokit,
params: { owner: string; repo: string; job_id: number },
runnerTemp: string,
timeoutMs: number = DOWNLOAD_JOB_LOG_TIMEOUT_MS,
): Promise<{ path: string; size_bytes: number }> {
const controller = new AbortController();
const timeoutHandle = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await client.actions.downloadJobLogsForWorkflowRun({
owner: params.owner,
repo: params.repo,
job_id: params.job_id,
request: { signal: controller.signal },
});
const logsText = response.data as unknown as string;
const logsDir = `${runnerTemp}/github-ci-logs`;
await mkdir(logsDir, { recursive: true });
const logPath = `${logsDir}/job-${params.job_id}.log`;
await writeFile(logPath, logsText, "utf-8");
return {
path: logPath,
size_bytes: Buffer.byteLength(logsText, "utf-8"),
};
} finally {
clearTimeout(timeoutHandle);
}
}
server.tool(
"download_job_log",
"Download job logs to disk",
@@ -218,24 +259,11 @@ server.tool(
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"),
};
const result = await downloadJobLog(
client,
{ owner: REPO_OWNER!, repo: REPO_NAME!, job_id },
RUNNER_TEMP,
);
return {
content: [
@@ -277,6 +305,8 @@ async function runServer() {
}
}
runServer().catch(() => {
process.exit(1);
});
if (import.meta.main) {
runServer().catch(() => {
process.exit(1);
});
}
+24
View File
@@ -0,0 +1,24 @@
import { z } from "zod";
/** Raw shape passed to `server.tool` for commit_files. */
export const commitFilesInputSchema = {
files: z
.array(z.string())
.describe(
'Array of file paths relative to repository root (e.g. ["src/main.js", "README.md"]). All files must exist locally.',
),
message: z.string().describe("Commit message"),
};
/** Raw shape passed to `server.tool` for delete_files. */
export const deleteFilesInputSchema = {
paths: z
.array(z.string())
.describe(
'Array of file paths to delete relative to repository root (e.g. ["src/old-file.js", "docs/deprecated.md"])',
),
message: z.string().describe("Commit message"),
};
export const commitFilesPayloadSchema = z.object(commitFilesInputSchema);
export const deleteFilesPayloadSchema = z.object(deleteFilesInputSchema);
+6 -17
View File
@@ -2,7 +2,6 @@
// GitHub File Operations MCP Server
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import { readFile, stat } from "fs/promises";
import { resolve } from "path";
import { constants } from "fs";
@@ -11,6 +10,10 @@ import { GITHUB_API_URL } from "../github/api/config";
import { isBinaryContent } from "./binary-detection";
import { validatePathWithinRepo } from "./path-validation";
import { updateGitReference } from "./update-git-reference";
import {
commitFilesInputSchema,
deleteFilesInputSchema,
} from "./github-file-ops-schemas";
type GitHubRef = {
object: {
@@ -197,14 +200,7 @@ async function getFileMode(filePath: string): Promise<string> {
server.tool(
"commit_files",
"Commit one or more files to a repository in a single commit (this will commit them atomically in the remote repository)",
{
files: z
.array(z.string())
.describe(
'Array of file paths relative to repository root (e.g. ["src/main.js", "README.md"]). All files must exist locally.',
),
message: z.string().describe("Commit message"),
},
commitFilesInputSchema,
async ({ files, message }) => {
const owner = REPO_OWNER;
const repo = REPO_NAME;
@@ -414,14 +410,7 @@ server.tool(
server.tool(
"delete_files",
"Delete one or more files from a repository in a single commit",
{
paths: z
.array(z.string())
.describe(
'Array of file paths to delete relative to repository root (e.g. ["src/old-file.js", "docs/deprecated.md"])',
),
message: z.string().describe("Commit message"),
},
deleteFilesInputSchema,
async ({ paths, message }) => {
const owner = REPO_OWNER;
const repo = REPO_NAME;
+13 -8
View File
@@ -83,20 +83,25 @@ export async function prepareMcpConfig(
// Detect if we're in agent mode (explicit prompt provided)
const isAgentMode = mode === "agent";
const hasGitHubCommentTools = allowedToolsList.some((tool) =>
tool.startsWith("mcp__github_comment__"),
const hasGitHubCommentTools = allowedToolsList.some(
(tool) =>
tool === "mcp__github_comment" ||
tool.startsWith("mcp__github_comment__"),
);
const hasGitHubMcpTools = allowedToolsList.some((tool) =>
tool.startsWith("mcp__github__"),
const hasGitHubMcpTools = allowedToolsList.some(
(tool) => tool === "mcp__github" || tool.startsWith("mcp__github__"),
);
const hasInlineCommentTools = allowedToolsList.some((tool) =>
tool.startsWith("mcp__github_inline_comment__"),
const hasInlineCommentTools = allowedToolsList.some(
(tool) =>
tool === "mcp__github_inline_comment" ||
tool.startsWith("mcp__github_inline_comment__"),
);
const hasGitHubCITools = allowedToolsList.some((tool) =>
tool.startsWith("mcp__github_ci__"),
const hasGitHubCITools = allowedToolsList.some(
(tool) =>
tool === "mcp__github_ci" || tool.startsWith("mcp__github_ci__"),
);
const baseMcpConfig: { mcpServers: Record<string, unknown> } = {
+262
View File
@@ -0,0 +1,262 @@
#!/usr/bin/env bun
/**
* Tests the interaction between restoreConfigFromBase and the auto-commit in
* checkAndCommitOrDeleteBranch.
*
* On pull requests the restore replaces .claude/, CLAUDE.md and friends with
* the base branch's versions and leaves them unstaged, so the revert does not
* reach a commit. A bare `git add -A` re-staged them anyway and pushed a silent
* revert of the PR author's own config onto their branch.
*
* These run against real git the fix is a pathspec, so a mock would only
* assert that the arguments were passed, not that git honours them.
*/
import { describe, test, expect, beforeEach, afterEach, spyOn } from "bun:test";
import { execFileSync } from "node:child_process";
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { checkAndCommitOrDeleteBranch } from "../src/github/operations/branch-cleanup";
import { SENSITIVE_PATHS } from "../src/github/operations/restore-config";
import type { Octokits } from "../src/github/api/client";
const BRANCH = "claude/issue-1-20260101-0000";
let workDir: string;
let remoteDir: string;
let originalCwd: string;
let logSpy: ReturnType<typeof spyOn>;
let errorSpy: ReturnType<typeof spyOn>;
function git(...args: string[]): string {
return execFileSync("git", args, { cwd: workDir, encoding: "utf-8" }).trim();
}
function write(relative: string, contents: string) {
const full = join(workDir, relative);
mkdirSync(join(full, ".."), { recursive: true });
writeFileSync(full, contents);
}
/** Branch exists, and has no commits ahead of base, so cleanup inspects git. */
const mockOctokit = {
rest: {
repos: {
getBranch: async () => ({ data: {} }),
compareCommitsWithBasehead: async () => ({
data: { total_commits: 0 },
}),
},
git: { deleteRef: async () => ({ data: {} }) },
},
} as unknown as Octokits;
beforeEach(() => {
originalCwd = process.cwd();
const root = mkdtempSync(join(tmpdir(), "branch-cleanup-"));
remoteDir = join(root, "remote.git");
workDir = join(root, "work");
execFileSync("git", ["init", "-q", "--bare", remoteDir]);
execFileSync("git", ["init", "-q", "-b", "main", workDir]);
git("config", "user.email", "test@example.com");
git("config", "user.name", "Test");
git("remote", "add", "origin", remoteDir);
write(".claude/settings.json", '{"from":"base"}\n');
write("CLAUDE.md", "base docs\n");
write("src/app.ts", "base code\n");
git("add", "-A");
git("commit", "-qm", "base");
git("push", "-q", "origin", "main");
git("checkout", "-qb", BRANCH);
git("push", "-q", "origin", BRANCH);
process.chdir(workDir);
logSpy = spyOn(console, "log").mockImplementation(() => {});
errorSpy = spyOn(console, "error").mockImplementation(() => {});
});
afterEach(() => {
process.chdir(originalCwd);
logSpy.mockRestore();
errorSpy.mockRestore();
rmSync(join(workDir, ".."), { recursive: true, force: true });
});
/** Files touched by the most recent commit. */
function filesInHeadCommit(): string[] {
return git("show", "--name-only", "--format=", "HEAD")
.split("\n")
.filter(Boolean)
.sort();
}
/**
* Reproduce the working-tree state restoreConfigFromBase leaves behind: the
* PR-authored config overwritten with the base branch's content, unstaged, so
* git reports it as a plain modification.
*/
function simulateRestoredConfig() {
write(".claude/settings.json", '{"from":"base"}\n');
write("CLAUDE.md", "base docs\n");
}
function authorPrConfigEdits() {
write(".claude/settings.json", '{"from":"pr-author"}\n');
write("CLAUDE.md", "pr author docs\n");
git("commit", "-qam", "PR author edits config");
}
describe("auto-commit with restored config paths", () => {
test("does not commit the base-branch revert onto the PR branch", async () => {
authorPrConfigEdits();
simulateRestoredConfig(); // config now reverted + unstaged
write("src/app.ts", "claude's real change\n");
const result = await checkAndCommitOrDeleteBranch(
mockOctokit,
"owner",
"repo",
BRANCH,
"main",
false,
[...SENSITIVE_PATHS],
);
expect(filesInHeadCommit()).toEqual(["src/app.ts"]);
expect(result.shouldDeleteBranch).toBe(false);
});
test("leaves the reverted config dirty in the working tree", async () => {
authorPrConfigEdits();
simulateRestoredConfig();
write("src/app.ts", "claude's real change\n");
await checkAndCommitOrDeleteBranch(
mockOctokit,
"owner",
"repo",
BRANCH,
"main",
false,
[...SENSITIVE_PATHS],
);
// --name-only gives bare paths, avoiding porcelain's status-column prefix.
const stillDirty = git("diff", "--name-only")
.split("\n")
.filter(Boolean)
.sort();
expect(stillDirty).toEqual([".claude/settings.json", "CLAUDE.md"]);
});
test("treats a branch whose only change is the revert as empty", async () => {
// No real work — just the reverted config. Committing here would push a
// pure revert and keep an otherwise-empty branch alive.
authorPrConfigEdits();
simulateRestoredConfig();
const before = git("rev-parse", "HEAD");
const result = await checkAndCommitOrDeleteBranch(
mockOctokit,
"owner",
"repo",
BRANCH,
"main",
false,
[...SENSITIVE_PATHS],
);
expect(git("rev-parse", "HEAD")).toBe(before);
expect(result.shouldDeleteBranch).toBe(true);
expect(result.branchLink).toBe("");
});
test("still commits Claude's own changes to non-config files", async () => {
authorPrConfigEdits();
simulateRestoredConfig();
write("src/app.ts", "changed\n");
write("src/new-file.ts", "added\n");
await checkAndCommitOrDeleteBranch(
mockOctokit,
"owner",
"repo",
BRANCH,
"main",
false,
[...SENSITIVE_PATHS],
);
expect(filesInHeadCommit()).toEqual(["src/app.ts", "src/new-file.ts"]);
});
test("pushes the commit to the branch", async () => {
authorPrConfigEdits();
simulateRestoredConfig();
write("src/app.ts", "claude's real change\n");
const result = await checkAndCommitOrDeleteBranch(
mockOctokit,
"owner",
"repo",
BRANCH,
"main",
false,
[...SENSITIVE_PATHS],
);
const remoteHead = execFileSync(
"git",
["--git-dir", remoteDir, "rev-parse", BRANCH],
{ encoding: "utf-8" },
).trim();
expect(remoteHead).toBe(git("rev-parse", "HEAD"));
expect(result.branchLink).toContain(BRANCH);
});
});
describe("without restored config paths (the issue path)", () => {
test("commits config changes normally, since no revert happened", async () => {
// Reached for issues, where restoreConfigFromBase never runs and Claude may
// have been asked to edit CLAUDE.md. Excluding it here would drop the work.
write("CLAUDE.md", "claude wrote these docs\n");
write(".claude/settings.json", '{"written":"by claude"}\n');
write("src/app.ts", "and some code\n");
await checkAndCommitOrDeleteBranch(
mockOctokit,
"owner",
"repo",
BRANCH,
"main",
false,
[],
);
expect(filesInHeadCommit()).toEqual([
".claude/settings.json",
"CLAUDE.md",
"src/app.ts",
]);
});
test("defaults to committing everything when the argument is omitted", async () => {
// Backwards compatibility: the parameter is optional.
write("CLAUDE.md", "claude wrote these docs\n");
await checkAndCommitOrDeleteBranch(
mockOctokit,
"owner",
"repo",
BRANCH,
"main",
false,
);
expect(filesInHeadCommit()).toEqual(["CLAUDE.md"]);
});
});
+6
View File
@@ -36,6 +36,12 @@ describe("comments/common", () => {
);
});
test("encodes URL-significant characters in a branch name", () => {
expect(createBranchLink("o", "r", "claude/fix#123")).toBe(
`\n[View branch](${GITHUB_SERVER_URL}/o/r/tree/claude/fix%23123)`,
);
});
test("prefixes the link with a newline so it renders on its own line", () => {
expect(createBranchLink("o", "r", "main").startsWith("\n")).toBe(true);
});
+35
View File
@@ -819,11 +819,46 @@ describe("generatePrompt", () => {
// Should have commit signing tool instructions
expect(prompt).toContain("mcp__github_file_ops__commit_files");
expect(prompt).toContain("mcp__github_file_ops__delete_files");
expect(prompt).toContain(
'mcp__github_file_ops__delete_files: {"paths": ["path/to/old.js"]',
);
expect(prompt).not.toContain(
'mcp__github_file_ops__delete_files: {"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");
// Bash is off unless the user passes --allowedTools through claude_args.
// allowed_tools was removed in v1.0 and must not appear as live guidance.
expect(prompt).toContain(
"Run arbitrary Bash commands (unless explicitly allowed via claude_args with --allowedTools)",
);
expect(prompt).not.toContain("allowed_tools configuration");
});
test("does not mention allowed_tools when commit signing is off", async () => {
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 = await generatePrompt(envVars, mockGitHubData, false, "tag");
expect(prompt).not.toContain("allowed_tools");
expect(prompt).not.toContain(
"Run arbitrary Bash commands (unless explicitly allowed",
);
});
describe("simplified prompt (USE_SIMPLE_PROMPT)", () => {
+169
View File
@@ -0,0 +1,169 @@
#!/usr/bin/env bun
import { describe, expect, test, beforeAll } from "bun:test";
import { generatePrompt } from "../src/create-prompt";
import type { PreparedContext } from "../src/create-prompt";
import {
commitFilesPayloadSchema,
deleteFilesPayloadSchema,
} from "../src/mcp/github-file-ops-schemas";
beforeAll(() => {
process.env.GITHUB_ACTION_PATH = "/test/action/path";
});
const mockGitHubData = {
contextData: {
title: "Test PR",
body: "This is a test PR",
author: { login: "testuser" },
state: "OPEN",
labels: { nodes: [] },
createdAt: "2023-01-01T00:00:00Z",
additions: 15,
deletions: 5,
baseRefName: "main",
headRefName: "feature-branch",
headRefOid: "abc123",
isCrossRepository: false,
headRepository: { owner: { login: "testowner" }, name: "testrepo" },
commits: { totalCount: 0, nodes: [] },
files: { nodes: [] },
comments: { nodes: [] },
reviews: { nodes: [] },
},
comments: [],
changedFiles: [],
changedFilesWithSHA: [],
reviewData: null,
imageUrlMap: new Map<string, string>(),
};
const signingContext: PreparedContext = {
repository: "owner/repo",
claudeCommentId: "12345",
triggerPhrase: "@claude",
eventData: {
eventName: "issue_comment",
commentId: "67890",
isPR: true,
prNumber: "123",
commentBody: "@claude delete the old file",
},
};
function extractToolExample(
prompt: string,
tool: string,
): Record<string, unknown> {
const match = prompt.match(
new RegExp(
`${tool.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}:\\s*(\\{[^}]+\\})`,
),
);
if (!match) {
throw new Error(`No JSON example for ${tool} in prompt`);
}
return JSON.parse(match[1] as string);
}
describe("delete_files prompt vs live MCP schema (#1665)", () => {
test("the payload the old prompt taught is rejected by the tool schema", () => {
const taughtByOldPrompt = {
files: ["path/to/old.js"],
message: "chore: remove deprecated file",
};
const result = deleteFilesPayloadSchema.safeParse(taughtByOldPrompt);
expect(result.success).toBe(false);
if (!result.success) {
const fields = result.error.issues.map((issue) => issue.path.join("."));
expect(fields).toContain("paths");
}
});
test("the payload the new prompt teaches is accepted by the tool schema", () => {
const taughtByNewPrompt = {
paths: ["path/to/old.js"],
message: "chore: remove deprecated file",
};
const result = deleteFilesPayloadSchema.safeParse(taughtByNewPrompt);
expect(result.success).toBe(true);
});
test("generated tag-mode prompt example parses against the live schema", async () => {
const prompt = await generatePrompt(
signingContext,
mockGitHubData,
true,
"tag",
);
const example = extractToolExample(
prompt,
"mcp__github_file_ops__delete_files",
);
expect(example).toHaveProperty("paths");
expect(example).not.toHaveProperty("files");
const result = deleteFilesPayloadSchema.safeParse(example);
expect(result.success).toBe(true);
});
test("rejects paths when the value is a string instead of an array", () => {
const result = deleteFilesPayloadSchema.safeParse({
paths: "path/to/old.js",
message: "chore: remove deprecated file",
});
expect(result.success).toBe(false);
});
test("rejects a payload that has paths but omits message", () => {
const result = deleteFilesPayloadSchema.safeParse({
paths: ["path/to/old.js"],
});
expect(result.success).toBe(false);
if (!result.success) {
expect(
result.error.issues.map((issue) => issue.path.join(".")),
).toContain("message");
}
});
test("accepts a payload that still includes the old files key beside paths", () => {
const result = deleteFilesPayloadSchema.safeParse({
files: ["path/to/old.js"],
paths: ["path/to/old.js"],
message: "chore: remove deprecated file",
});
expect(result.success).toBe(true);
});
test("does not change commit_files — that sibling tool still requires files", async () => {
const prompt = await generatePrompt(
signingContext,
mockGitHubData,
true,
"tag",
);
const example = extractToolExample(
prompt,
"mcp__github_file_ops__commit_files",
);
expect(example).toHaveProperty("files");
expect(example).not.toHaveProperty("paths");
expect(commitFilesPayloadSchema.safeParse(example).success).toBe(true);
expect(deleteFilesPayloadSchema.safeParse(example).success).toBe(false);
});
test("generated delete_files example keys are exactly paths and message", async () => {
const prompt = await generatePrompt(
signingContext,
mockGitHubData,
true,
"tag",
);
const example = extractToolExample(
prompt,
"mcp__github_file_ops__delete_files",
);
expect(Object.keys(example).sort()).toEqual(["message", "paths"]);
});
});
+41
View File
@@ -0,0 +1,41 @@
// Wire-level probe for the GitHub API client's endpoint routing.
//
// `src/github/api/config.ts` reads GITHUB_API_URL / GITHUB_GRAPHQL_URL at module
// load time, so each endpoint configuration has to be exercised in its own fresh
// process (the companion test spawns this file once per case with the relevant
// env vars set). We stub global fetch to capture the FINAL request URL and
// Authorization header — asserting constructor options is not enough because
// @octokit/graphql rewrites/append the path (".../api/v3" -> ".../api/graphql",
// otherwise it appends "/graphql") after the client is constructed.
import { createOctokit } from "../../src/github/api/client";
type Captured = { url: string; auth: string | null };
const captured: Captured[] = [];
globalThis.fetch = (async (input: any, init?: any) => {
const url: string =
typeof input === "string" ? input : (input?.url ?? String(input));
const headers = new Headers(init?.headers ?? input?.headers);
captured.push({ url, auth: headers.get("authorization") });
return new Response(JSON.stringify({ data: {} }), {
status: 200,
headers: { "content-type": "application/json" },
});
}) as typeof fetch;
const octokits = createOctokit("test-token");
await octokits.graphql(`query { viewer { login } }`);
const graphql = captured[captured.length - 1]!;
await octokits.rest.request("GET /meta");
const rest = captured[captured.length - 1]!;
process.stdout.write(
JSON.stringify({
graphqlUrl: graphql.url,
graphqlAuth: graphql.auth,
restUrl: rest.url,
restAuth: rest.auth,
}),
);
+94
View File
@@ -0,0 +1,94 @@
import { describe, test, expect, afterEach } from "bun:test";
import { readFile, rm } from "fs/promises";
import os from "os";
import path from "path";
import { downloadJobLog } from "../src/mcp/github-actions-server";
import type { Octokit } from "@octokit/rest";
describe("downloadJobLog", () => {
const tmpDirs: string[] = [];
const makeRunnerTemp = () => {
const dir = path.join(
os.tmpdir(),
`download-job-log-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
);
tmpDirs.push(dir);
return dir;
};
afterEach(async () => {
while (tmpDirs.length) {
const dir = tmpDirs.pop()!;
await rm(dir, { recursive: true, force: true });
}
});
const createStallingClient = (): {
client: Octokit;
getSignal: () => AbortSignal | undefined;
} => {
let signal: AbortSignal | undefined;
const client = {
actions: {
downloadJobLogsForWorkflowRun: (params: {
request?: { signal?: AbortSignal };
}) => {
signal = params.request?.signal;
return new Promise((_resolve, reject) => {
signal?.addEventListener("abort", () => {
reject(new Error("This operation was aborted"));
});
// Otherwise never settles, simulating a stalled fetch.
});
},
},
} as unknown as Octokit;
return { client, getSignal: () => signal };
};
test("rejects with a timeout instead of hanging when the download stalls", async () => {
const { client, getSignal } = createStallingClient();
const runnerTemp = makeRunnerTemp();
await expect(
downloadJobLog(
client,
{ owner: "owner", repo: "repo", job_id: 123 },
runnerTemp,
5,
),
).rejects.toThrow();
expect(getSignal()?.aborted).toBe(true);
});
test("writes the log to disk and clears the timeout when the download succeeds", async () => {
const runnerTemp = makeRunnerTemp();
const client = {
actions: {
downloadJobLogsForWorkflowRun: async (params: {
request?: { signal?: AbortSignal };
}) => {
expect(params.request?.signal?.aborted).toBe(false);
return { data: "log line 1\nlog line 2\n" };
},
},
} as unknown as Octokit;
const result = await downloadJobLog(
client,
{ owner: "owner", repo: "repo", job_id: 456 },
runnerTemp,
30_000,
);
expect(result.path).toBe(`${runnerTemp}/github-ci-logs/job-456.log`);
expect(result.size_bytes).toBe(
Buffer.byteLength("log line 1\nlog line 2\n", "utf-8"),
);
const written = await readFile(result.path, "utf-8");
expect(written).toBe("log line 1\nlog line 2\n");
});
});
+121
View File
@@ -0,0 +1,121 @@
import { describe, expect, test } from "bun:test";
import { join } from "node:path";
// The GitHub client reads GITHUB_API_URL / GITHUB_GRAPHQL_URL when
// `src/github/api/config.ts` is first imported, so we cannot flip env vars
// between cases inside a single process. Instead each case runs the real
// `createOctokit` factory in a fresh Bun process (test/fixtures/graphql-endpoint-probe.ts)
// with a stubbed fetch that reports the FINAL wire URL and Authorization header.
//
// This is the level that matters: @octokit/graphql derives the GraphQL endpoint
// from its baseUrl AFTER construction (rewriting a REST ".../api/v3" base to
// ".../api/graphql", and otherwise appending "/graphql"), so a constructor-option
// assertion would not catch a regression.
const PROBE = join(import.meta.dir, "fixtures", "graphql-endpoint-probe.ts");
type ProbeResult = {
graphqlUrl: string;
graphqlAuth: string | null;
restUrl: string;
restAuth: string | null;
};
function probe(env: Record<string, string>): ProbeResult {
const result = Bun.spawnSync({
cmd: ["bun", "run", PROBE],
env: {
...process.env,
// Start from a clean slate so the host's own env cannot leak in.
GITHUB_API_URL: "",
GITHUB_GRAPHQL_URL: "",
...env,
},
stdout: "pipe",
stderr: "pipe",
});
if (result.exitCode !== 0) {
throw new Error(
`probe failed (exit ${result.exitCode}): ${result.stderr.toString()}`,
);
}
return JSON.parse(result.stdout.toString().trim()) as ProbeResult;
}
describe("GitHub API client endpoint routing", () => {
test("both env vars unset: REST and GraphQL use github.com", () => {
const r = probe({});
expect(r.restUrl).toBe("https://api.github.com/meta");
expect(r.graphqlUrl).toBe("https://api.github.com/graphql");
});
test("GITHUB_API_URL alone (GHES): GraphQL still resolves to /api/graphql", () => {
// Regression guard: @octokit/graphql rewrites a ".../api/v3" REST base to
// ".../api/graphql", so GraphQL must keep working when only GITHUB_API_URL
// is provided (e.g. under `act` or partial configs).
const r = probe({ GITHUB_API_URL: "https://ghe.example.test/api/v3" });
expect(r.restUrl).toBe("https://ghe.example.test/api/v3/meta");
expect(r.graphqlUrl).toBe("https://ghe.example.test/api/graphql");
});
test("GITHUB_GRAPHQL_URL alone: GraphQL honors it exactly, REST stays public", () => {
const r = probe({
GITHUB_GRAPHQL_URL: "https://ghe.example.test/api/graphql",
});
expect(r.graphqlUrl).toBe("https://ghe.example.test/api/graphql");
expect(r.restUrl).toBe("https://api.github.com/meta");
});
test("both set to standard GHES values: REST and GraphQL route independently", () => {
const r = probe({
GITHUB_API_URL: "https://ghe.example.test/api/v3",
GITHUB_GRAPHQL_URL: "https://ghe.example.test/api/graphql",
});
expect(r.restUrl).toBe("https://ghe.example.test/api/v3/meta");
expect(r.graphqlUrl).toBe("https://ghe.example.test/api/graphql");
});
test("GITHUB_GRAPHQL_URL wins over a GITHUB_API_URL-derived endpoint", () => {
// Distinguishing case: without honoring GITHUB_GRAPHQL_URL, GraphQL would be
// derived from GITHUB_API_URL and hit the wrong host.
const r = probe({
GITHUB_API_URL: "https://ghe.example.test/api/v3",
GITHUB_GRAPHQL_URL: "https://gql.example.test/api/graphql",
});
expect(r.graphqlUrl).toBe("https://gql.example.test/api/graphql");
expect(r.restUrl).toBe("https://ghe.example.test/api/v3/meta");
});
test("trailing slash on GITHUB_GRAPHQL_URL is normalized", () => {
const r = probe({
GITHUB_GRAPHQL_URL: "https://ghe.example.test/api/graphql/",
});
expect(r.graphqlUrl).toBe("https://ghe.example.test/api/graphql");
});
test("GITHUB_GRAPHQL_URL without a /graphql suffix is preserved before the client appends one", () => {
const r = probe({
GITHUB_GRAPHQL_URL: "https://gql.example.test/custom",
});
expect(r.graphqlUrl).toBe("https://gql.example.test/custom/graphql");
});
test("a base already ending in /graphql is not doubled", () => {
const r = probe({
GITHUB_GRAPHQL_URL: "https://gql.example.test/api/graphql",
});
expect(r.graphqlUrl).not.toContain("/graphql/graphql");
expect(r.graphqlUrl).toBe("https://gql.example.test/api/graphql");
});
test("the token authorization header is preserved on both clients", () => {
const r = probe({
GITHUB_API_URL: "https://ghe.example.test/api/v3",
GITHUB_GRAPHQL_URL: "https://ghe.example.test/api/graphql",
});
expect(r.graphqlAuth).toBe("token test-token");
expect(r.restAuth).toBe("token test-token");
});
});
+98
View File
@@ -354,4 +354,102 @@ describe("prepareMcpConfig", () => {
const parsed = JSON.parse(result);
expect(parsed.mcpServers.github_ci).not.toBeDefined();
});
test("should include github MCP server when mcp__github shorthand is used", async () => {
const result = await prepareMcpConfig({
githubToken: "test-token",
owner: "test-owner",
repo: "test-repo",
branch: "test-branch",
baseBranch: "main",
allowedTools: ["mcp__github"],
mode: "agent",
context: mockContext,
});
const parsed = JSON.parse(result);
expect(parsed.mcpServers.github).toBeDefined();
expect(parsed.mcpServers.github.command).toBe("docker");
expect(parsed.mcpServers.github.env.GITHUB_PERSONAL_ACCESS_TOKEN).toBe(
"test-token",
);
});
test("should include inline comment server when mcp__github_inline_comment shorthand is used", async () => {
const result = await prepareMcpConfig({
githubToken: "test-token",
owner: "test-owner",
repo: "test-repo",
branch: "test-branch",
baseBranch: "main",
allowedTools: ["mcp__github_inline_comment"],
mode: "agent",
context: mockPRContext,
});
const parsed = JSON.parse(result);
expect(parsed.mcpServers.github_inline_comment).toBeDefined();
expect(parsed.mcpServers.github_inline_comment.env.GITHUB_TOKEN).toBe(
"test-token",
);
expect(parsed.mcpServers.github_inline_comment.env.PR_NUMBER).toBe("456");
});
test("should include comment server in agent mode when mcp__github_comment shorthand is used", async () => {
const result = await prepareMcpConfig({
githubToken: "test-token",
owner: "test-owner",
repo: "test-repo",
branch: "test-branch",
baseBranch: "main",
allowedTools: ["mcp__github_comment"],
mode: "agent",
context: mockContext,
});
const parsed = JSON.parse(result);
expect(parsed.mcpServers.github_comment).toBeDefined();
expect(parsed.mcpServers.github_comment.env.GITHUB_TOKEN).toBe(
"test-token",
);
});
test("should include CI server in agent mode when mcp__github_ci shorthand is used", async () => {
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_ci"],
mode: "agent",
context: mockPRContext,
});
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");
delete process.env.DEFAULT_WORKFLOW_TOKEN;
});
test("should not include github MCP server when unrelated tool is specified", async () => {
const result = await prepareMcpConfig({
githubToken: "test-token",
owner: "test-owner",
repo: "test-repo",
branch: "test-branch",
baseBranch: "main",
allowedTools: ["Bash", "Read", "Grep"],
mode: "agent",
context: mockContext,
});
const parsed = JSON.parse(result);
expect(parsed.mcpServers.github).not.toBeDefined();
expect(parsed.mcpServers.github_inline_comment).not.toBeDefined();
});
});
+9
View File
@@ -29,6 +29,15 @@ describe("validateBranchName", () => {
expect(() => validateBranchName("release.1.2.3")).not.toThrow();
});
it("should accept branch names containing parentheses", () => {
expect(() =>
validateBranchName("feat(example)-valid-branch"),
).not.toThrow();
expect(() =>
validateBranchName("fix(parser)-handle-empty-input"),
).not.toThrow();
});
it("should accept typical branch name formats", () => {
expect(() =>
validateBranchName("claude/issue-123-20250101-1234"),