Compare commits

..

No commits in common. "main" and "v1.0.129" have entirely different histories.

77 changed files with 416 additions and 5759 deletions

View File

@ -1,162 +0,0 @@
export const meta = {
name: "pr-stamp-sweep",
description:
"Review candidate PRs for stampability, then adversarially verify security of stamp candidates",
whenToUse:
"Sweep candidate PRs for stampability: per-PR review + adversarial security verify. Requires pre-fetched PR dossiers in /tmp/claude/pr-sweep/<n>.md and args {prs: [...]}.",
phases: [
{ title: "Review", detail: "one reviewer agent per PR" },
{
title: "Verify",
detail: "adversarial security skeptic per stamp candidate",
},
],
};
// PRECONDITION: before invoking this workflow, pre-fetch each candidate PR to
// /tmp/claude/pr-sweep/<n>.md, containing the PR's metadata, body, existing
// reviews/comments, and the full diff (e.g. via `gh pr view` + `gh pr diff`).
// Sandboxed agents can't reliably call gh themselves, so they read these
// dossier files instead. Pass the PR numbers as args: {prs: [<PR numbers>]}.
const REVIEW_SCHEMA = {
type: "object",
properties: {
number: { type: "number" },
verdict: { type: "string", enum: ["stamp", "skip", "needs-discussion"] },
category: {
type: "string",
description: "docs | tests | bugfix | nicety | security-fix | other",
},
summary: {
type: "string",
description: "1-2 sentence plain-language summary of what the PR does",
},
reasoning: {
type: "string",
description: "why this verdict — correctness, scope, quality",
},
behaviorChange: {
type: "string",
description: 'what user-visible behavior changes, or "none"',
},
concerns: { type: "array", items: { type: "string" } },
securitySensitive: {
type: "boolean",
description:
"true if it touches auth, sanitization, parsers of untrusted input, actor checks, file restore, or shell construction",
},
duplicateOf: {
type: "string",
description: "PR number(s) this duplicates, or empty string",
},
},
required: [
"number",
"verdict",
"category",
"summary",
"reasoning",
"behaviorChange",
"concerns",
"securitySensitive",
"duplicateOf",
],
};
const VERDICT_SCHEMA = {
type: "object",
properties: {
number: { type: "number" },
safeToStamp: { type: "boolean" },
findings: {
type: "array",
items: { type: "string" },
description:
"concrete security/correctness problems found, empty if clean",
},
confidence: { type: "string", enum: ["high", "medium", "low"] },
},
required: ["number", "safeToStamp", "findings", "confidence"],
};
if (!args || !Array.isArray(args.prs) || args.prs.length === 0)
throw new Error(
"pass {prs: [<PR numbers>]} as args; pre-fetch each PR to /tmp/claude/pr-sweep/<n>.md first",
);
const prs = args.prs;
log(`Reviewing ${prs.length} candidate PRs`);
const results = await pipeline(
prs,
(n) =>
agent(
`You are reviewing open PR #${n} on anthropics/claude-code-action to decide if it is safe for a maintainer to approve ("stamp") with minimal further discussion.
The full PR (metadata, body, existing reviews/comments, and complete diff) is in /tmp/claude/pr-sweep/${n}.md read it first. The repo is checked out at the current working directory. Read the actual current source files the diff touches to verify the diff applies cleanly conceptually and the claims in the PR body are true. Do NOT modify anything or run git commands that change state.
Context about this repo:
- It's a GitHub Action that runs Claude on issues/PRs. It processes UNTRUSTED content (PR bodies, comments, branch names, file contents from forks). Treat any change touching content sanitization, actor/bot allowlists, config restoration, prompt construction, or shell command construction as high-risk.
- Most candidate PRs are from EXTERNAL contributors. Treat the diff with suspicion: look for subtle malicious changes, weakened validation, injection vectors, overly broad permissions, or changes whose description doesn't match the code.
- Runtime is Bun; strict TypeScript (noUnusedLocals/noUnusedParameters). Tests are unit tests run with bun test.
Stamp criteria (ALL must hold):
1. Small, focused, and the code does exactly what the title/body says.
2. No major behavior change bug fixes restoring intended behavior, docs fixes, test-only additions, and small niceties qualify. New inputs/features, behavior redesigns, or large refactors do NOT.
3. Correct: you verified the logic against the actual current source, not just the diff. Check edge cases.
4. No security concern. Check explicitly for: prompt injection (untrusted text reaching Claude's prompt without sanitization), code execution (untrusted data reaching shell commands, eval/spawn, or GitHub workflow expressions), path traversal (untrusted input influencing filesystem paths), credential exposure (tokens reaching logs, comments, or attacker-readable output), weakened validation or permission checks, and suspicious hunks unrelated to the stated purpose.
5. Wouldn't break the public API of base-action/ or action.yml output wiring.
If the PR is a docs change, verify the docs claims against the actual code behavior. If test-only, check tests actually pass conceptually (assert the right things, match real implementations) and don't weaken or skip anything.
Verdicts: "stamp" = approve as-is; "needs-discussion" = plausible but has questions/issues worth a comment; "skip" = too big, wrong, redundant, or risky.
If this PR appears to duplicate another open PR (same fix, same files), still judge it on its own merits but note the duplication in duplicateOf.
Return structured output only.`,
{ label: `review:#${n}`, phase: "Review", schema: REVIEW_SCHEMA },
),
(review, n) => {
if (!review) return null;
if (review.verdict !== "stamp") return { review, verify: null };
return agent(
`You are an adversarial security skeptic. Another reviewer recommended APPROVING open PR #${n} on anthropics/claude-code-action. Your job is to REFUTE that recommendation — find any reason it should NOT be stamped.
Their assessment: ${JSON.stringify(review)}
Read the full PR at /tmp/claude/pr-sweep/${n}.md and the touched source files in the current working directory. This repo processes untrusted PR/issue content from forks; anything that lets untrusted content reach Claude's prompt, a shell command, a workflow expression, or a filesystem path unsanitized is a critical vulnerability.
Hunt specifically for:
- Subtle malice or scope creep: hunks that don't match the stated purpose, weakened validation, regex changes that widen acceptance, removed escaping.
- Prompt injection: untrusted data (comment bodies, branch names, file contents, command output, downloaded files) reaching Claude's prompt or context without sanitization, including indirect routes like tool output Claude later reads.
- Code execution: untrusted data reaching shell commands, eval/spawn argv, GitHub workflow \${{ }} expressions, or API call templates; new process spawning; path traversal letting untrusted input write or read outside intended directories.
- Credential exposure: tokens or secrets flowing into logs, posted comments, error messages, env passed to untrusted code, or files Claude can read.
- Logic errors the first reviewer missed: off-by-one, wrong polarity, unhandled edge cases (empty strings, unicode, very long inputs).
- Supply-chain angles: pinned versions that don't match the claimed SHA/tag, new dependencies, fetched URLs.
- For docs PRs: claims that would mislead users into insecure configurations.
- For test-only PRs: tests that codify wrong behavior, or that would mask future regressions.
If the diff pins a version/SHA, verify the claim is plausible from local information; flag if unverifiable. Be strict: if uncertain whether something is a real problem, lean toward reporting it as a finding with your uncertainty noted. Only return safeToStamp=true if you genuinely failed to find any disqualifying issue.
Return structured output only.`,
{ label: `verify:#${n}`, phase: "Verify", schema: VERDICT_SCHEMA },
).then((v) => ({ review, verify: v }));
},
);
const clean = results.filter(Boolean);
const stamped = clean.filter(
(r) => r.review.verdict === "stamp" && r.verify && r.verify.safeToStamp,
);
const demoted = clean.filter(
(r) => r.review.verdict === "stamp" && (!r.verify || !r.verify.safeToStamp),
);
const discuss = clean.filter((r) => r.review.verdict === "needs-discussion");
const skipped = clean.filter((r) => r.review.verdict === "skip");
log(
`stamp: ${stamped.length}, demoted by verifier: ${demoted.length}, needs-discussion: ${discuss.length}, skip: ${skipped.length}`,
);
return { stamped, demoted, discuss, skipped };

View File

@ -11,9 +11,6 @@ on:
permissions: permissions:
contents: read contents: read
# Lets the test workflows mint the GitHub OIDC token they exchange for a
# Claude API access token (workload identity federation). See docs/setup.md.
id-token: write
jobs: jobs:
ci: ci:
@ -21,15 +18,20 @@ jobs:
test-base-action: test-base-action:
uses: ./.github/workflows/test-base-action.yml uses: ./.github/workflows/test-base-action.yml
secrets: inherit # Required for ANTHROPIC_API_KEY
test-custom-executables: test-custom-executables:
uses: ./.github/workflows/test-custom-executables.yml uses: ./.github/workflows/test-custom-executables.yml
secrets: inherit
test-mcp-servers: test-mcp-servers:
uses: ./.github/workflows/test-mcp-servers.yml uses: ./.github/workflows/test-mcp-servers.yml
secrets: inherit
test-settings: test-settings:
uses: ./.github/workflows/test-settings.yml uses: ./.github/workflows/test-settings.yml
secrets: inherit
test-structured-output: test-structured-output:
uses: ./.github/workflows/test-structured-output.yml uses: ./.github/workflows/test-structured-output.yml
secrets: inherit

View File

@ -20,12 +20,7 @@ jobs:
- name: PR Review with Progress Tracking - name: PR Review with Progress Tracking
uses: anthropics/claude-code-action@v1 uses: anthropics/claude-code-action@v1
with: with:
# Authenticate to the Claude API via Workload Identity Federation anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
# (the workflow's OIDC token is exchanged for a short-lived access
# token) instead of a static API key. See docs/setup.md.
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }}
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
prompt: "/review-pr REPO: ${{ github.repository }} PR_NUMBER: ${{ github.event.pull_request.number }}" prompt: "/review-pr REPO: ${{ github.repository }} PR_NUMBER: ${{ github.event.pull_request.number }}"
claude_args: | claude_args: |

View File

@ -33,12 +33,7 @@ jobs:
id: claude id: claude
uses: anthropics/claude-code-action@main uses: anthropics/claude-code-action@main
with: with:
# Authenticate to the Claude API via Workload Identity Federation anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
# (the workflow's OIDC token is exchanged for a short-lived access
# token) instead of a static API key. See docs/setup.md.
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }}
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
claude_args: | claude_args: |
--allowedTools "Bash(bun install),Bash(bun test:*),Bash(bun run format),Bash(bun typecheck)" --allowedTools "Bash(bun install),Bash(bun test:*),Bash(bun run format),Bash(bun typecheck)"
--model "claude-opus-4-7" --model "claude-opus-4-7"

View File

@ -11,9 +11,6 @@ jobs:
permissions: permissions:
contents: read contents: read
issues: write issues: write
# Required to mint the OIDC token that is exchanged for a Claude API
# access token (Workload Identity Federation).
id-token: write
steps: steps:
- name: Checkout repository - name: Checkout repository
@ -27,11 +24,6 @@ jobs:
CLAUDE_CODE_SCRIPT_CAPS: '{"edit-issue-labels.sh":2}' CLAUDE_CODE_SCRIPT_CAPS: '{"edit-issue-labels.sh":2}'
with: with:
prompt: "/label-issue REPO: ${{ github.repository }} ISSUE_NUMBER: ${{ github.event.issue.number }}" prompt: "/label-issue REPO: ${{ github.repository }} ISSUE_NUMBER: ${{ github.event.issue.number }}"
# Authenticate to the Claude API via Workload Identity Federation anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
# (the workflow's OIDC token is exchanged for a short-lived access
# token) instead of a static API key. See docs/setup.md.
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }}
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
allowed_non_write_users: "*" # Required for issue triage workflow, if users without repo write access create issues allowed_non_write_users: "*" # Required for issue triage workflow, if users without repo write access create issues
github_token: ${{ secrets.GITHUB_TOKEN }} github_token: ${{ secrets.GITHUB_TOKEN }}

View File

@ -19,7 +19,7 @@ jobs:
timeout-minutes: 10 timeout-minutes: 10
steps: steps:
- name: Checkout source repository - name: Checkout source repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
with: with:
fetch-depth: 1 fetch-depth: 1

View File

@ -10,27 +10,18 @@ on:
default: "List the files in the current directory starting with 'package'" default: "List the files in the current directory starting with 'package'"
workflow_call: workflow_call:
# The Claude API is authenticated via workload identity federation: id-token
# lets the action mint the GitHub OIDC token it exchanges for a short-lived
# access token. See docs/setup.md.
permissions:
contents: read
id-token: write
jobs: jobs:
test-inline-prompt: test-inline-prompt:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- name: Test with inline prompt - name: Test with inline prompt
id: inline-test id: inline-test
uses: ./base-action uses: ./base-action
with: with:
prompt: ${{ github.event.inputs.test_prompt || 'List the files in the current directory starting with "package"' }} prompt: ${{ github.event.inputs.test_prompt || 'List the files in the current directory starting with "package"' }}
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }} anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
allowed_tools: "LS,Read" allowed_tools: "LS,Read"
- name: Verify inline prompt output - name: Verify inline prompt output
@ -72,7 +63,7 @@ jobs:
test-prompt-file: test-prompt-file:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- name: Create test prompt file - name: Create test prompt file
run: | run: |
@ -87,9 +78,7 @@ jobs:
uses: ./base-action uses: ./base-action
with: with:
prompt_file: "test-prompt.txt" prompt_file: "test-prompt.txt"
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }} anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
allowed_tools: "LS,Read" allowed_tools: "LS,Read"
- name: Verify prompt file output - name: Verify prompt file output

View File

@ -5,18 +5,11 @@ on:
workflow_dispatch: workflow_dispatch:
workflow_call: workflow_call:
# The Claude API is authenticated via workload identity federation: id-token
# lets the action mint the GitHub OIDC token it exchanges for a short-lived
# access token. See docs/setup.md.
permissions:
contents: read
id-token: write
jobs: jobs:
test-custom-executables: test-custom-executables:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- name: Install Bun manually - name: Install Bun manually
run: | run: |
@ -54,9 +47,7 @@ jobs:
with: with:
prompt: | prompt: |
List the files in the current directory starting with "package" List the files in the current directory starting with "package"
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }} anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
path_to_claude_code_executable: /home/runner/.local/bin/claude path_to_claude_code_executable: /home/runner/.local/bin/claude
path_to_bun_executable: /home/runner/.bun/bin/bun path_to_bun_executable: /home/runner/.bun/bin/bun
allowed_tools: "LS,Read" allowed_tools: "LS,Read"

View File

@ -5,22 +5,15 @@ on:
workflow_dispatch: workflow_dispatch:
workflow_call: workflow_call:
# The Claude API is authenticated via workload identity federation: id-token
# lets the action mint the GitHub OIDC token it exchanges for a short-lived
# access token. See docs/setup.md.
permissions:
contents: read
id-token: write
jobs: jobs:
test-mcp-integration: test-mcp-integration:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 #v4
- name: Setup Bun - name: Setup Bun
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 uses: oven-sh/setup-bun@735343b667d3e6f658f44d0eca948eb6282f2b76 #v2
- name: Install dependencies - name: Install dependencies
run: | run: |
@ -32,11 +25,8 @@ jobs:
uses: ./base-action uses: ./base-action
id: claude-test id: claude-test
with: with:
prompt: "Call the test_tool tool and report its response." prompt: "List all available tools"
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }} anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
claude_args: --allowedTools mcp__test-server__test_tool
env: env:
# Change to test directory so it finds .mcp.json # Change to test directory so it finds .mcp.json
CLAUDE_WORKING_DIR: ${{ github.workspace }}/base-action/test/mcp-test CLAUDE_WORKING_DIR: ${{ github.workspace }}/base-action/test/mcp-test
@ -60,29 +50,21 @@ jobs:
if jq -e '.[] | select(.type == "system" and .subtype == "init") | .mcp_servers' "$OUTPUT_FILE" > /dev/null; then if jq -e '.[] | select(.type == "system" and .subtype == "init") | .mcp_servers' "$OUTPUT_FILE" > /dev/null; then
echo "✓ Found mcp_servers in output" echo "✓ Found mcp_servers in output"
# MCP servers can connect asynchronously, so the init event may # Check if test-server is connected
# report the server as pending — check registration there, then if jq -e '.[] | select(.type == "system" and .subtype == "init") | .mcp_servers[] | select(.name == "test-server" and .status == "connected")' "$OUTPUT_FILE" > /dev/null; then
# verify the tool actually ran. echo "✓ test-server is connected"
if jq -e '.[] | select(.type == "system" and .subtype == "init") | .mcp_servers[] | select(.name == "test-server")' "$OUTPUT_FILE" > /dev/null; then
echo "✓ test-server is registered"
else else
echo "✗ test-server not found" echo "✗ test-server not found or not connected"
jq '.[] | select(.type == "system" and .subtype == "init") | .mcp_servers' "$OUTPUT_FILE" jq '.[] | select(.type == "system" and .subtype == "init") | .mcp_servers' "$OUTPUT_FILE"
exit 1 exit 1
fi fi
if jq -e '.[] | select(.type == "assistant") | .message.content[]? | select(.type == "tool_use" and .name == "mcp__test-server__test_tool")' "$OUTPUT_FILE" > /dev/null; then # Check if mcp tools are available
echo "✓ MCP test tool was called" if jq -e '.[] | select(.type == "system" and .subtype == "init") | .tools[] | select(. == "mcp__test-server__test_tool")' "$OUTPUT_FILE" > /dev/null; then
echo "✓ MCP test tool found"
else else
echo "✗ MCP test tool was not called" echo "✗ MCP test tool not found"
jq '[.[] | select(.type == "assistant") | .message.content[]? | select(.type == "tool_use") | .name]' "$OUTPUT_FILE" jq '.[] | select(.type == "system" and .subtype == "init") | .tools' "$OUTPUT_FILE"
exit 1
fi
if jq -e '.[] | select(.type == "user") | .message.content[]? | select(.type == "tool_result") | select(.content | tostring | contains("Test tool response"))' "$OUTPUT_FILE" > /dev/null; then
echo "✓ MCP test tool returned its response"
else
echo "✗ MCP test tool response not found"
exit 1 exit 1
fi fi
else else
@ -97,10 +79,10 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 #v4
- name: Setup Bun - name: Setup Bun
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 uses: oven-sh/setup-bun@735343b667d3e6f658f44d0eca948eb6282f2b76 #v2
- name: Install dependencies - name: Install dependencies
run: | run: |
@ -124,13 +106,9 @@ jobs:
uses: ./base-action uses: ./base-action
id: claude-config-test id: claude-config-test
with: with:
prompt: "Call the test_tool tool and report its response." prompt: "List all available tools"
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }} anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }} mcp_config: '{"mcpServers":{"test-server":{"type":"stdio","command":"bun","args":["simple-mcp-server.ts"],"env":{}}}}'
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
claude_args: |
--allowedTools mcp__test-server__test_tool
--mcp-config '{"mcpServers":{"test-server":{"type":"stdio","command":"bun","args":["simple-mcp-server.ts"],"env":{}}}}'
env: env:
# Change to test directory so bun can find the MCP server script # Change to test directory so bun can find the MCP server script
CLAUDE_WORKING_DIR: ${{ github.workspace }}/base-action/test/mcp-test CLAUDE_WORKING_DIR: ${{ github.workspace }}/base-action/test/mcp-test
@ -154,29 +132,21 @@ jobs:
if jq -e '.[] | select(.type == "system" and .subtype == "init") | .mcp_servers' "$OUTPUT_FILE" > /dev/null; then if jq -e '.[] | select(.type == "system" and .subtype == "init") | .mcp_servers' "$OUTPUT_FILE" > /dev/null; then
echo "✓ Found mcp_servers in output" echo "✓ Found mcp_servers in output"
# MCP servers can connect asynchronously, so the init event may # Check if test-server is connected
# report the server as pending — check registration there, then if jq -e '.[] | select(.type == "system" and .subtype == "init") | .mcp_servers[] | select(.name == "test-server" and .status == "connected")' "$OUTPUT_FILE" > /dev/null; then
# verify the tool actually ran. echo "✓ test-server is connected"
if jq -e '.[] | select(.type == "system" and .subtype == "init") | .mcp_servers[] | select(.name == "test-server")' "$OUTPUT_FILE" > /dev/null; then
echo "✓ test-server is registered"
else else
echo "✗ test-server not found" echo "✗ test-server not found or not connected"
jq '.[] | select(.type == "system" and .subtype == "init") | .mcp_servers' "$OUTPUT_FILE" jq '.[] | select(.type == "system" and .subtype == "init") | .mcp_servers' "$OUTPUT_FILE"
exit 1 exit 1
fi fi
if jq -e '.[] | select(.type == "assistant") | .message.content[]? | select(.type == "tool_use" and .name == "mcp__test-server__test_tool")' "$OUTPUT_FILE" > /dev/null; then # Check if mcp tools are available
echo "✓ MCP test tool was called" if jq -e '.[] | select(.type == "system" and .subtype == "init") | .tools[] | select(. == "mcp__test-server__test_tool")' "$OUTPUT_FILE" > /dev/null; then
echo "✓ MCP test tool found"
else else
echo "✗ MCP test tool was not called" echo "✗ MCP test tool not found"
jq '[.[] | select(.type == "assistant") | .message.content[]? | select(.type == "tool_use") | .name]' "$OUTPUT_FILE" jq '.[] | select(.type == "system" and .subtype == "init") | .tools' "$OUTPUT_FILE"
exit 1
fi
if jq -e '.[] | select(.type == "user") | .message.content[]? | select(.type == "tool_result") | select(.content | tostring | contains("Test tool response"))' "$OUTPUT_FILE" > /dev/null; then
echo "✓ MCP test tool returned its response"
else
echo "✗ MCP test tool response not found"
exit 1 exit 1
fi fi
else else

View File

@ -5,18 +5,11 @@ on:
workflow_dispatch: workflow_dispatch:
workflow_call: workflow_call:
# The Claude API is authenticated via workload identity federation: id-token
# lets the action mint the GitHub OIDC token it exchanges for a short-lived
# access token. See docs/setup.md.
permissions:
contents: read
id-token: write
jobs: jobs:
test-settings-inline-allow: test-settings-inline-allow:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- name: Test with inline settings JSON (echo allowed) - name: Test with inline settings JSON (echo allowed)
id: inline-settings-test id: inline-settings-test
@ -24,9 +17,7 @@ jobs:
with: with:
prompt: | prompt: |
Use Bash to echo "Hello from settings test" Use Bash to echo "Hello from settings test"
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }} anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
settings: | settings: |
{ {
"permissions": { "permissions": {
@ -67,7 +58,7 @@ jobs:
test-settings-inline-deny: test-settings-inline-deny:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- name: Test with inline settings JSON (echo denied) - name: Test with inline settings JSON (echo denied)
id: inline-settings-test id: inline-settings-test
@ -75,9 +66,7 @@ jobs:
with: with:
prompt: | prompt: |
Run the command `echo $HOME` to check the home directory path Run the command `echo $HOME` to check the home directory path
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }} anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
settings: | settings: |
{ {
"permissions": { "permissions": {
@ -101,7 +90,7 @@ jobs:
test-settings-file-allow: test-settings-file-allow:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- name: Create settings file (echo allowed) - name: Create settings file (echo allowed)
run: | run: |
@ -119,9 +108,7 @@ jobs:
with: with:
prompt: | prompt: |
Use Bash to echo "Hello from settings file test" Use Bash to echo "Hello from settings file test"
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }} anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
settings: "test-settings.json" settings: "test-settings.json"
- name: Verify echo worked - name: Verify echo worked
@ -157,7 +144,7 @@ jobs:
test-settings-file-deny: test-settings-file-deny:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- name: Create settings file (echo denied) - name: Create settings file (echo denied)
run: | run: |
@ -175,9 +162,7 @@ jobs:
with: with:
prompt: | prompt: |
Run the command `echo $HOME` to check the home directory path Run the command `echo $HOME` to check the home directory path
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }} anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
settings: "test-settings.json" settings: "test-settings.json"
- name: Verify echo was denied - name: Verify echo was denied

View File

@ -5,12 +5,8 @@ on:
workflow_dispatch: workflow_dispatch:
workflow_call: workflow_call:
# The Claude API is authenticated via workload identity federation: id-token
# lets the action mint the GitHub OIDC token it exchanges for a short-lived
# access token. See docs/setup.md.
permissions: permissions:
contents: read contents: read
id-token: write
jobs: jobs:
test-basic-types: test-basic-types:
@ -18,7 +14,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- name: Test with explicit values - name: Test with explicit values
id: test id: test
@ -32,9 +28,7 @@ jobs:
- number_field: 42 - number_field: 42
- boolean_true: true - boolean_true: true
- boolean_false: false - boolean_false: false
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }} anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
claude_args: | claude_args: |
--allowedTools Bash --allowedTools Bash
--json-schema '{"type":"object","properties":{"text_field":{"type":"string"},"number_field":{"type":"number"},"boolean_true":{"type":"boolean"},"boolean_false":{"type":"boolean"}},"required":["text_field","number_field","boolean_true","boolean_false"]}' --json-schema '{"type":"object","properties":{"text_field":{"type":"string"},"number_field":{"type":"number"},"boolean_true":{"type":"boolean"},"boolean_false":{"type":"boolean"}},"required":["text_field","number_field","boolean_true","boolean_false"]}'
@ -79,7 +73,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- name: Test complex types - name: Test complex types
id: test id: test
@ -92,9 +86,7 @@ jobs:
- items: ["apple", "banana", "cherry"] - items: ["apple", "banana", "cherry"]
- config: {"key": "value", "count": 3} - config: {"key": "value", "count": 3}
- empty_array: [] - empty_array: []
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }} anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
claude_args: | claude_args: |
--allowedTools Bash --allowedTools Bash
--json-schema '{"type":"object","properties":{"items":{"type":"array","items":{"type":"string"}},"config":{"type":"object"},"empty_array":{"type":"array"}},"required":["items","config","empty_array"]}' --json-schema '{"type":"object","properties":{"items":{"type":"array","items":{"type":"string"}},"config":{"type":"object"},"empty_array":{"type":"array"}},"required":["items","config","empty_array"]}'
@ -132,7 +124,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- name: Test edge cases - name: Test edge cases
id: test id: test
@ -146,9 +138,7 @@ jobs:
- empty_string: "" - empty_string: ""
- negative: -5 - negative: -5
- decimal: 3.14 - decimal: 3.14
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }} anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
claude_args: | claude_args: |
--allowedTools Bash --allowedTools Bash
--json-schema '{"type":"object","properties":{"zero":{"type":"number"},"empty_string":{"type":"string"},"negative":{"type":"number"},"decimal":{"type":"number"}},"required":["zero","empty_string","negative","decimal"]}' --json-schema '{"type":"object","properties":{"zero":{"type":"number"},"empty_string":{"type":"string"},"negative":{"type":"number"},"decimal":{"type":"number"}},"required":["zero","empty_string","negative","decimal"]}'
@ -193,7 +183,7 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- name: Test special characters in field names - name: Test special characters in field names
id: test id: test
@ -202,9 +192,7 @@ jobs:
prompt: | prompt: |
Run: echo "test" Run: echo "test"
Return EXACTLY: {test-result: "passed", item_count: 10} Return EXACTLY: {test-result: "passed", item_count: 10}
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }} anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
claude_args: | claude_args: |
--allowedTools Bash --allowedTools Bash
--json-schema '{"type":"object","properties":{"test-result":{"type":"string"},"item_count":{"type":"number"}},"required":["test-result","item_count"]}' --json-schema '{"type":"object","properties":{"test-result":{"type":"string"},"item_count":{"type":"number"}},"required":["test-result","item_count"]}'
@ -235,16 +223,14 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
- name: Run with structured output - name: Run with structured output
id: test id: test
uses: ./base-action uses: ./base-action
with: with:
prompt: "Run: echo 'complete'. Return: {done: true}" prompt: "Run: echo 'complete'. Return: {done: true}"
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }} anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
claude_args: | claude_args: |
--allowedTools Bash --allowedTools Bash
--json-schema '{"type":"object","properties":{"done":{"type":"boolean"}},"required":["done"]}' --json-schema '{"type":"object","properties":{"done":{"type":"boolean"}},"required":["done"]}'

View File

@ -2,7 +2,7 @@
# Claude Code Action # Claude Code Action
A general-purpose [Claude Code](https://claude.ai/code) action for GitHub PRs and issues that can answer questions and implement code changes. This action intelligently detects when to activate based on your workflow context—whether responding to @claude mentions, issue assignments, or executing automation tasks with explicit prompts. It supports multiple authentication methods including Anthropic direct API (API key or workload identity federation), Amazon Bedrock, Google Vertex AI, and Microsoft Foundry. A general-purpose [Claude Code](https://claude.ai/code) action for GitHub PRs and issues that can answer questions and implement code changes. This action intelligently detects when to activate based on your workflow context—whether responding to @claude mentions, issue assignments, or executing automation tasks with explicit prompts. It supports multiple authentication methods including Anthropic direct API, Amazon Bedrock, Google Vertex AI, and Microsoft Foundry.
## Features ## Features

View File

@ -70,21 +70,6 @@ inputs:
claude_code_oauth_token: claude_code_oauth_token:
description: "Claude Code OAuth token (alternative to anthropic_api_key)" description: "Claude Code OAuth token (alternative to anthropic_api_key)"
required: false required: false
anthropic_federation_rule_id:
description: "Workload identity federation rule ID (fdrl_...). When set with anthropic_organization_id, the action authenticates to the Claude API by exchanging the workflow's GitHub OIDC token instead of using a static API key. Requires `id-token: write` permission."
required: false
anthropic_organization_id:
description: "Anthropic organization UUID used for workload identity federation"
required: false
anthropic_service_account_id:
description: "Service account ID (svac_...) the federated token acts as (optional, used with workload identity federation)"
required: false
anthropic_workspace_id:
description: "Workspace ID (wrkspc_...) for workload identity federation. Optional when the federation rule targets a single workspace."
required: false
anthropic_oidc_audience:
description: "Audience to request on the GitHub OIDC token used for workload identity federation. Defaults to https://api.anthropic.com."
required: false
github_token: github_token:
description: "GitHub token with repo and pull request permissions (optional if using GitHub App)" description: "GitHub token with repo and pull request permissions (optional if using GitHub App)"
required: false required: false
@ -187,7 +172,6 @@ runs:
using: "composite" using: "composite"
steps: steps:
- name: Install Bun - name: Install Bun
id: setup-bun
if: inputs.path_to_bun_executable == '' if: inputs.path_to_bun_executable == ''
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # https://github.com/oven-sh/setup-bun/releases/tag/v2.2.0 uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # https://github.com/oven-sh/setup-bun/releases/tag/v2.2.0
with: with:
@ -239,20 +223,11 @@ runs:
if: ${{ inputs.allowed_non_write_users != '' }} if: ${{ inputs.allowed_non_write_users != '' }}
continue-on-error: true continue-on-error: true
shell: bash shell: bash
env:
PATH_TO_BUN_EXECUTABLE: ${{ inputs.path_to_bun_executable }}
SETUP_BUN_PATH: ${{ steps.setup-bun.outputs.bun-path }}
run: | run: |
# Keep a copy of the bun binary alongside the action's own files so # Keep a copy of the bun binary alongside the action's own files so
# post-steps use the same version the action installed or was given. # post-steps use the same version that was on PATH at action start.
mkdir -p "$GITHUB_ACTION_PATH/bin" mkdir -p "$GITHUB_ACTION_PATH/bin"
for bun_path in "$PATH_TO_BUN_EXECUTABLE" "$SETUP_BUN_PATH" "$(command -v bun || true)"; do cp "$(command -v bun)" "$GITHUB_ACTION_PATH/bin/bun"
if [ -n "$bun_path" ] && [ -x "$bun_path" ]; then
cp "$bun_path" "$GITHUB_ACTION_PATH/bin/bun"
break
fi
done
test -x "$GITHUB_ACTION_PATH/bin/bun"
- name: Prepend system bin dirs to PATH - name: Prepend system bin dirs to PATH
if: ${{ inputs.allowed_non_write_users != '' && runner.os != 'Windows' }} if: ${{ inputs.allowed_non_write_users != '' && runner.os != 'Windows' }}
@ -266,13 +241,9 @@ runs:
id: run id: run
shell: bash shell: bash
run: | run: |
# Do NOT pass --tsconfig-override here. It triggers a Bun runtime bug
# ("Internal error: directory mismatch for directory .../tsconfig.json")
# that aborts the run with exit code 1. Bun already auto-discovers the
# action's own tsconfig.json by walking up from the entry file, so the
# override is redundant. See oven-sh/bun#25730.
bun --no-env-file \ bun --no-env-file \
--config="${GITHUB_ACTION_PATH}/bunfig.toml" \ --config="${GITHUB_ACTION_PATH}/bunfig.toml" \
--tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json" \
run ${GITHUB_ACTION_PATH}/src/entrypoints/run.ts run ${GITHUB_ACTION_PATH}/src/entrypoints/run.ts
env: env:
# Prepare inputs # Prepare inputs
@ -321,13 +292,8 @@ runs:
NODE_VERSION: ${{ env.NODE_VERSION }} NODE_VERSION: ${{ env.NODE_VERSION }}
# Provider configuration # Provider configuration
ANTHROPIC_API_KEY: ${{ inputs.anthropic_api_key || env.ANTHROPIC_API_KEY }} ANTHROPIC_API_KEY: ${{ inputs.anthropic_api_key }}
CLAUDE_CODE_OAUTH_TOKEN: ${{ inputs.claude_code_oauth_token || env.CLAUDE_CODE_OAUTH_TOKEN }} CLAUDE_CODE_OAUTH_TOKEN: ${{ inputs.claude_code_oauth_token }}
ANTHROPIC_FEDERATION_RULE_ID: ${{ inputs.anthropic_federation_rule_id }}
ANTHROPIC_ORGANIZATION_ID: ${{ inputs.anthropic_organization_id }}
ANTHROPIC_SERVICE_ACCOUNT_ID: ${{ inputs.anthropic_service_account_id }}
ANTHROPIC_WORKSPACE_ID: ${{ inputs.anthropic_workspace_id }}
ANTHROPIC_OIDC_AUDIENCE: ${{ inputs.anthropic_oidc_audience }}
ANTHROPIC_BASE_URL: ${{ env.ANTHROPIC_BASE_URL }} ANTHROPIC_BASE_URL: ${{ env.ANTHROPIC_BASE_URL }}
ANTHROPIC_CUSTOM_HEADERS: ${{ env.ANTHROPIC_CUSTOM_HEADERS }} ANTHROPIC_CUSTOM_HEADERS: ${{ env.ANTHROPIC_CUSTOM_HEADERS }}
CLAUDE_CODE_USE_BEDROCK: ${{ inputs.use_bedrock == 'true' && '1' || '' }} CLAUDE_CODE_USE_BEDROCK: ${{ inputs.use_bedrock == 'true' && '1' || '' }}
@ -412,9 +378,9 @@ runs:
run: | run: |
BUN_BIN="${GITHUB_ACTION_PATH}/bin/bun" BUN_BIN="${GITHUB_ACTION_PATH}/bin/bun"
[ -x "$BUN_BIN" ] || BUN_BIN="bun" [ -x "$BUN_BIN" ] || BUN_BIN="bun"
# No --tsconfig-override: see the "Run Claude Code Action" step above.
"$BUN_BIN" --no-env-file \ "$BUN_BIN" --no-env-file \
--config="${GITHUB_ACTION_PATH}/bunfig.toml" \ --config="${GITHUB_ACTION_PATH}/bunfig.toml" \
--tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json" \
run ${GITHUB_ACTION_PATH}/src/entrypoints/cleanup-ssh-signing.ts run ${GITHUB_ACTION_PATH}/src/entrypoints/cleanup-ssh-signing.ts
- name: Post buffered inline comments - name: Post buffered inline comments
@ -429,9 +395,9 @@ runs:
run: | run: |
BUN_BIN="${GITHUB_ACTION_PATH}/bin/bun" BUN_BIN="${GITHUB_ACTION_PATH}/bin/bun"
[ -x "$BUN_BIN" ] || BUN_BIN="bun" [ -x "$BUN_BIN" ] || BUN_BIN="bun"
# No --tsconfig-override: see the "Run Claude Code Action" step above.
"$BUN_BIN" --no-env-file \ "$BUN_BIN" --no-env-file \
--config="${GITHUB_ACTION_PATH}/bunfig.toml" \ --config="${GITHUB_ACTION_PATH}/bunfig.toml" \
--tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json" \
run ${GITHUB_ACTION_PATH}/src/entrypoints/post-buffered-inline-comments.ts run ${GITHUB_ACTION_PATH}/src/entrypoints/post-buffered-inline-comments.ts
- name: Revoke app token - name: Revoke app token
@ -439,10 +405,8 @@ runs:
shell: bash shell: bash
run: | run: |
curl -L \ curl -L \
--connect-timeout 5 \
--max-time 10 \
-X DELETE \ -X DELETE \
-H "Accept: application/vnd.github+json" \ -H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer ${{ steps.run.outputs.github_token }}" \ -H "Authorization: Bearer ${{ steps.run.outputs.github_token }}" \
-H "X-GitHub-Api-Version: 2022-11-28" \ -H "X-GitHub-Api-Version: 2022-11-28" \
${GITHUB_API_URL:-https://api.github.com}/installation/token || true ${GITHUB_API_URL:-https://api.github.com}/installation/token

View File

@ -1,123 +0,0 @@
# Agent Approval Check
Require **N human approvals** on any pull request that contains commits
authored by an AI agent (Claude, Claude Code, or any bot identity you
configure). PRs without agent activity are unaffected.
This is the same gate Anthropic runs internally on every agent-authored PR.
## What it does
When a PR is opened, pushed to, or commented on, this action:
1. Scans the PR's commits, author, and reviews for the configured agent
identities (committer email, bot login, or an `APPROVED` review from a
bot). If none are found it posts `success: No agent activity` and stops.
2. Counts distinct human approvals: the latest `APPROVED` review per login,
plus any `/approve <head-sha>` comment whose SHA matches the current
head. Only users with write access to the repo count (verified per-user
via the collaborators permission API); agent and excluded-bot logins
never count.
3. Posts an `agent-approval-check` commit status (`success` once the count
reaches `required_approvals`, otherwise `pending`) and a sticky PR
comment explaining what's still needed.
4. Re-evaluates on every new push or comment. A push moves the head SHA,
so earlier `/approve <old-sha>` comments are flagged stale. Approving
reviews still count toward the threshold — they're picked up the next
time the workflow runs (on push or `/approve`); they just don't trigger
a run on their own.
Mark `agent-approval-check` as a **required status check** on your protected
branches and GitHub will refuse to merge until it's green.
## Setup
Copy [`examples/agent-approval-check.yml`](../examples/agent-approval-check.yml)
into `.github/workflows/` in your repo, then add `agent-approval-check` to the
required status checks on your protected branch.
This action is designed to run **alongside** GitHub's native branch
protection, not replace it. On the same protected branch you should also:
1. Require at least 1 approving review from someone with write access.
2. Enable **Dismiss stale pull request approvals when new commits are pushed**.
```yaml
name: agent-approval-check
on:
pull_request_target:
types: [opened, synchronize, reopened, ready_for_review]
issue_comment:
types: [created]
permissions:
contents: read
pull-requests: write
statuses: write
jobs:
check:
if: github.event_name != 'issue_comment' || github.event.issue.pull_request
runs-on: ubuntu-latest
steps:
- uses: anthropics/claude-code-action/agent-approval-check@main
with:
required_approvals: 2
agent_emails: noreply@anthropic.com
agent_logins: claude[bot],claude-code[bot]
```
## Inputs
| Input | Default | Meaning |
| ---------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| `required_approvals` | `2` | Distinct human approvals needed. |
| `agent_emails` | `noreply@anthropic.com` | Committer emails that mark a commit agent-authored. |
| `agent_logins` | `claude[bot],claude-code[bot]` | Logins treated as agents (PR author or approving reviewer). |
| `excluded_approvers` | _(empty)_ | Logins whose approvals never count. |
| `exempt_head_branches` | _(empty)_ | Head-branch globs that auto-pass. ⚠️ Leave empty — branch names are attacker-controlled, so this is not a safe place to encode trust. |
| `exempt_path_prefixes` | _(empty)_ | PRs touching only these prefixes auto-pass. |
| `protected_bases` | _(default branch)_ | Base branches this check gates (see threat model). |
| `config_file` | _(empty)_ | Path to an [agent-identities YAML](./agent-identities.example.yaml) replacing the inline inputs. See the warning below. |
| `docs_url` | this README | Link in the PR comment footer. |
| `github_token` | `${{ github.token }}` | Needs `statuses:write` + `pull-requests:write`. |
> ⚠️ **`config_file` and checkout:** if you set `config_file`, your workflow
> must check out the **base** branch to read it (the default behaviour of
> `actions/checkout` under `pull_request_target`). Never check out the PR
> head ref — doing so would let the PR author control the config and bypass
> this check.
## Approving
A human counts as an approver by either:
- submitting a normal GitHub **Approve** review, or
- commenting `/approve <sha>` where `<sha>` is the current head commit
(1240 hex chars). This path lets the PR author — who can't approve their
own PR in GitHub's UI — vouch for commits an agent pushed on their behalf.
The author's `/approve` is subject to the same write-access verification
as any other approver, so a fork-PR author without write access on the
base repository cannot self-count. The author counts as **one** approval;
the remaining approvals must come from other reviewers with write access.
## Threat model
- **Tamper-proof triggers.** `pull_request_target` and `issue_comment` run
the workflow file from the base/default branch, so the PR under review
cannot edit this check. `pull_request_review` does **not** share this
property — it runs from the merge ref — so the example workflow omits it;
native Approve reviews are picked up on the next synchronize or
`/approve` comment. This tamper-resistance assumes the workflow file
itself is protected: an actor who can push workflow changes to the
default branch can spoof any required status check, including this one,
so protect `.github/workflows/` via branch protection or CODEOWNERS.
- **Fail-closed.** Any unhandled error exits non-zero; the required status
stays non-success and the PR stays blocked. PRs with >100 commits are
treated as agent-authored because the full commit list can't be verified.
- **Sibling-PR guard.** Commit statuses attach to a SHA, not a PR. The
action refuses to post a status on a PR whose base isn't in
`protected_bases`, and withholds `success` while another open PR to a
protected base shares the same head commit — otherwise a green status on
one PR would also unblock the other.
- **No checkout of PR code.** The action never checks out the PR's branch;
it reads PR metadata via the GitHub API, so the usual
`pull_request_target` code-execution risk does not apply.

View File

@ -1,72 +0,0 @@
name: Agent Approval Check
description: |
Require N human approvals on PRs that contain agent-authored commits
(Claude, Claude Code, or any configured bot identity). Posts an
`agent-approval-check` commit status — mark it as a required check on
protected branches to gate merges.
inputs:
github_token:
description: Token with statuses:write and pull-requests:write on this repo.
default: ${{ github.token }}
required_approvals:
description: Number of distinct human approvals required. Must be >= 1.
default: "2"
agent_emails:
description: Comma-separated committer emails treated as agent-authored.
default: noreply@anthropic.com
agent_logins:
description: |
Comma-separated GitHub logins treated as agents — a PR opened by, or an
APPROVED review from, one of these triggers the check.
default: claude[bot],claude-code[bot]
excluded_approvers:
description: Comma-separated logins whose approvals never count (e.g. rubber-stamp bots).
default: ""
exempt_head_branches:
description: |
Comma-separated glob patterns; PRs from matching head branches auto-pass.
WARNING: leave empty — branch names are attacker-controlled, so this is
not a safe place to encode trust.
default: ""
exempt_path_prefixes:
description: Comma-separated path prefixes; PRs touching only these auto-pass.
default: ""
protected_bases:
description: |
Comma-separated base branches this check gates. Empty = the repo's
default branch only. PRs targeting any other base are refused (no
status posted) so a sibling PR sharing the head SHA can't get the
shared commit stamped green.
default: ""
config_file:
description: Optional path to an agent-identities YAML file (overrides the inline inputs).
default: ""
docs_url:
description: Link shown in the PR comment footer.
default: "https://github.com/anthropics/claude-code-action/tree/main/agent-approval-check"
runs:
using: composite
steps:
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with:
python-version: "3.12"
- run: pip install 'httpx==0.28.1' 'pyyaml==6.0.3' 'tenacity==9.1.4'
shell: bash
- run: python "${{ github.action_path }}/agent_approval_check.py"
shell: bash
env:
GH_TOKEN: ${{ inputs.github_token }}
GH_REPOSITORY: ${{ github.repository }}
GH_EVENT_NAME: ${{ github.event_name }}
GH_EVENT_PATH: ${{ github.event_path }}
REQUIRED_APPROVALS: ${{ inputs.required_approvals }}
AGENT_EMAILS: ${{ inputs.agent_emails }}
AGENT_LOGINS: ${{ inputs.agent_logins }}
EXCLUDED_APPROVERS: ${{ inputs.excluded_approvers }}
EXEMPT_HEAD_BRANCHES: ${{ inputs.exempt_head_branches }}
EXEMPT_PATH_PREFIXES: ${{ inputs.exempt_path_prefixes }}
PROTECTED_BASES: ${{ inputs.protected_bases }}
CONFIG_FILE: ${{ inputs.config_file }}
DOCS_URL: ${{ inputs.docs_url }}

View File

@ -1,33 +0,0 @@
---
# Optional config-file form of the agent-approval-check inputs.
# Pass via `with: { config_file: .github/agent-identities.yaml }` instead of
# the inline `agent_emails` / `agent_logins` / … inputs.
# Committer emails that mark a commit as agent-authored.
agent_emails:
- noreply@anthropic.com
# GitHub logins treated as agents — a PR opened by, or an APPROVED review
# from, one of these triggers the check.
agent_app_logins:
- claude[bot]
- claude-code[bot]
# Logins whose approvals never count toward the required total.
excluded_approver_logins: []
# Head-branch glob patterns that auto-pass. Leave empty: branch names are
# attacker-controlled, so this is not a safe place to encode trust.
exempt_head_branches: []
# Per-repo path prefixes whose PRs auto-pass when ONLY those paths change.
exempt_path_prefixes:
owner/repo:
- docs/
# Per-repo base branches this check gates. A repo with no entry defaults to
# its default branch only. Listing a repo here REPLACES that default.
protected_bases:
owner/repo:
exact: [main]
prefixes: [release/]

File diff suppressed because it is too large Load Diff

View File

@ -91,55 +91,29 @@ Add the following to your workflow file:
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }} claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
``` ```
### Workload Identity Federation
Instead of a static API key or OAuth token, you can authenticate via [Workload Identity Federation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation): the action fetches the workflow's GitHub OIDC token and the Claude Code CLI exchanges it for a short-lived access token. Requires the `id-token: write` permission on the job:
```yaml
permissions:
contents: read
id-token: write
steps:
- name: Run Claude Code with workload identity federation
uses: anthropics/claude-code-base-action@beta
with:
prompt: "Your prompt here"
anthropic_federation_rule_id: fdrl_xxxxxxxxxxxx
anthropic_organization_id: 00000000-0000-0000-0000-000000000000
anthropic_service_account_id: svac_xxxxxxxxxxxx
```
Do not set `anthropic_api_key` or `claude_code_oauth_token` alongside the federation inputs — a static credential takes precedence and federation will not be used.
## Inputs ## Inputs
| Input | Description | Required | Default | | Input | Description | Required | Default |
| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------- | -------- | ---------------------------- | | ------------------------- | ----------------------------------------------------------------------------------------------------------------------- | -------- | ---------------------------- |
| `prompt` | The prompt to send to Claude Code | No\* | '' | | `prompt` | The prompt to send to Claude Code | No\* | '' |
| `prompt_file` | Path to a file containing the prompt to send to Claude Code | No\* | '' | | `prompt_file` | Path to a file containing the prompt to send to Claude Code | No\* | '' |
| `allowed_tools` | Comma-separated list of allowed tools for Claude Code to use | No | '' | | `allowed_tools` | Comma-separated list of allowed tools for Claude Code to use | No | '' |
| `disallowed_tools` | Comma-separated list of disallowed tools that Claude Code cannot use | No | '' | | `disallowed_tools` | Comma-separated list of disallowed tools that Claude Code cannot use | No | '' |
| `max_turns` | Maximum number of conversation turns (default: no limit) | No | '' | | `max_turns` | Maximum number of conversation turns (default: no limit) | No | '' |
| `mcp_config` | Path to the MCP configuration JSON file, or MCP configuration JSON string | No | '' | | `mcp_config` | Path to the MCP configuration JSON file, or MCP configuration JSON string | No | '' |
| `settings` | Path to Claude Code settings JSON file, or settings JSON string | No | '' | | `settings` | Path to Claude Code settings JSON file, or settings JSON string | No | '' |
| `system_prompt` | Override system prompt | No | '' | | `system_prompt` | Override system prompt | No | '' |
| `append_system_prompt` | Append to system prompt | No | '' | | `append_system_prompt` | Append to system prompt | No | '' |
| `claude_env` | Custom environment variables to pass to Claude Code execution (YAML multiline format) | No | '' | | `claude_env` | Custom environment variables to pass to Claude Code execution (YAML multiline format) | No | '' |
| `model` | Model to use (provider-specific format required for Bedrock/Vertex) | No | 'claude-4-0-sonnet-20250219' | | `model` | Model to use (provider-specific format required for Bedrock/Vertex) | No | 'claude-4-0-sonnet-20250219' |
| `anthropic_model` | DEPRECATED: Use 'model' instead | No | 'claude-4-0-sonnet-20250219' | | `anthropic_model` | DEPRECATED: Use 'model' instead | No | 'claude-4-0-sonnet-20250219' |
| `fallback_model` | Enable automatic fallback to specified model when default model is overloaded | No | '' | | `fallback_model` | Enable automatic fallback to specified model when default model is overloaded | No | '' |
| `anthropic_api_key` | Anthropic API key (required for direct Anthropic API) | No | '' | | `anthropic_api_key` | Anthropic API key (required for direct Anthropic API) | No | '' |
| `claude_code_oauth_token` | Claude Code OAuth token (alternative to anthropic_api_key) | No | '' | | `claude_code_oauth_token` | Claude Code OAuth token (alternative to anthropic_api_key) | No | '' |
| `anthropic_federation_rule_id` | Workload identity federation rule ID (fdrl\_...). Requires `id-token: write` permission | No | '' | | `use_bedrock` | Use Amazon Bedrock with OIDC authentication instead of direct Anthropic API | No | 'false' |
| `anthropic_organization_id` | Anthropic organization UUID used for workload identity federation | No | '' | | `use_vertex` | Use Google Vertex AI with OIDC authentication instead of direct Anthropic API | No | 'false' |
| `anthropic_service_account_id` | Service account ID (svac\_...) the federated token acts as (optional) | No | '' | | `use_node_cache` | Whether to use Node.js dependency caching (set to true only for Node.js projects with lock files) | No | 'false' |
| `anthropic_workspace_id` | Workspace ID (wrkspc\_...) for federation. Optional when the rule targets a single workspace | No | '' | | `show_full_output` | Show full JSON output (⚠️ May expose secrets - see [security docs](../docs/security.md#-full-output-security-warning)) | No | 'false'\*\* |
| `anthropic_oidc_audience` | Audience to request on the GitHub OIDC token. Defaults to https://api.anthropic.com | No | '' |
| `use_bedrock` | Use Amazon Bedrock with OIDC authentication instead of direct Anthropic API | No | 'false' |
| `use_vertex` | Use Google Vertex AI with OIDC authentication instead of direct Anthropic API | No | 'false' |
| `use_node_cache` | Whether to use Node.js dependency caching (set to true only for Node.js projects with lock files) | No | 'false' |
| `show_full_output` | Show full JSON output (⚠️ May expose secrets - see [security docs](../docs/security.md#-full-output-security-warning)) | No | 'false'\*\* |
\*Either `prompt` or `prompt_file` must be provided, but not both. \*Either `prompt` or `prompt_file` must be provided, but not both.
@ -147,12 +121,10 @@ Do not set `anthropic_api_key` or `claude_code_oauth_token` alongside the federa
## Outputs ## Outputs
| Output | Description | | Output | Description |
| ------------------- | ------------------------------------------------------------------------------------------------- | | ---------------- | ---------------------------------------------------------- |
| `conclusion` | Execution status of Claude Code ('success' or 'failure') | | `conclusion` | Execution status of Claude Code ('success' or 'failure') |
| `execution_file` | Path to the JSON file containing Claude Code execution log | | `execution_file` | Path to the JSON file containing Claude Code execution log |
| `structured_output` | JSON string containing structured output fields when `--json-schema` is provided in `claude_args` |
| `session_id` | The Claude Code session ID that can be used with `--resume` to continue this conversation |
## Environment Variables ## Environment Variables
@ -397,39 +369,18 @@ jobs:
const executionFile = '${{ steps.code-review.outputs.execution_file }}'; const executionFile = '${{ steps.code-review.outputs.execution_file }}';
const executionLog = JSON.parse(fs.readFileSync(executionFile, 'utf8')); const executionLog = JSON.parse(fs.readFileSync(executionFile, 'utf8'));
// Extract the review content from the execution log. // Extract the review content from the execution log
// The SDK writes top-level events with `type`; assistant text is nested // The execution log contains the full conversation including Claude's responses
// under `message.content`.
let review = ''; let review = '';
// Prefer the final result event when it is available. // Find the last assistant message which should contain the review
for (let i = executionLog.length - 1; i >= 0; i--) { for (let i = executionLog.length - 1; i >= 0; i--) {
const entry = executionLog[i]; if (executionLog[i].role === 'assistant') {
if (entry?.type === 'result' && typeof entry.result === 'string') { review = executionLog[i].content;
review = entry.result;
break; break;
} }
} }
// Fallback to the last assistant text block if no result event was written.
if (!review) {
for (let i = executionLog.length - 1; i >= 0; i--) {
const entry = executionLog[i];
if (entry?.type !== 'assistant' || !Array.isArray(entry.message?.content)) {
continue;
}
review = entry.message.content
.filter((block) => block?.type === 'text' && typeof block.text === 'string')
.map((block) => block.text)
.join('\n');
if (review) {
break;
}
}
}
if (review) { if (review) {
github.rest.issues.createComment({ github.rest.issues.createComment({
issue_number: context.issue.number, issue_number: context.issue.number,
@ -440,10 +391,6 @@ jobs:
} }
``` ```
For typed automation output, prefer passing `--json-schema` in `claude_args`
and reading `steps.<id>.outputs.structured_output` instead of parsing the full
execution log.
Check out additional examples in [`./examples`](./examples). Check out additional examples in [`./examples`](./examples).
## Using Cloud Providers ## Using Cloud Providers

View File

@ -34,26 +34,6 @@ inputs:
description: "Claude Code OAuth token (alternative to anthropic_api_key)" description: "Claude Code OAuth token (alternative to anthropic_api_key)"
required: false required: false
default: "" default: ""
anthropic_federation_rule_id:
description: "Workload identity federation rule ID (fdrl_...). When set with anthropic_organization_id, the action authenticates to the Claude API by exchanging the workflow's GitHub OIDC token instead of using a static API key. Requires `id-token: write` permission."
required: false
default: ""
anthropic_organization_id:
description: "Anthropic organization UUID used for workload identity federation"
required: false
default: ""
anthropic_service_account_id:
description: "Service account ID (svac_...) the federated token acts as (optional, used with workload identity federation)"
required: false
default: ""
anthropic_workspace_id:
description: "Workspace ID (wrkspc_...) for workload identity federation. Optional when the federation rule targets a single workspace."
required: false
default: ""
anthropic_oidc_audience:
description: "Audience to request on the GitHub OIDC token used for workload identity federation. Defaults to https://api.anthropic.com."
required: false
default: ""
use_bedrock: use_bedrock:
description: "Use Amazon Bedrock with OIDC authentication instead of direct Anthropic API" description: "Use Amazon Bedrock with OIDC authentication instead of direct Anthropic API"
required: false required: false
@ -110,11 +90,10 @@ runs:
using: "composite" using: "composite"
steps: steps:
- name: Setup Node.js - name: Setup Node.js
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # https://github.com/actions/setup-node/releases/tag/v6.4.0 uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # https://github.com/actions/setup-node/releases/tag/v4.4.0
with: with:
node-version: ${{ env.NODE_VERSION || '18.x' }} node-version: ${{ env.NODE_VERSION || '18.x' }}
cache: ${{ inputs.use_node_cache == 'true' && 'npm' || '' }} cache: ${{ inputs.use_node_cache == 'true' && 'npm' || '' }}
package-manager-cache: false
- name: Install Bun - name: Install Bun
if: inputs.path_to_bun_executable == '' if: inputs.path_to_bun_executable == ''
@ -145,7 +124,7 @@ runs:
PATH_TO_CLAUDE_CODE_EXECUTABLE: ${{ inputs.path_to_claude_code_executable }} PATH_TO_CLAUDE_CODE_EXECUTABLE: ${{ inputs.path_to_claude_code_executable }}
run: | run: |
if [ -z "$PATH_TO_CLAUDE_CODE_EXECUTABLE" ]; then if [ -z "$PATH_TO_CLAUDE_CODE_EXECUTABLE" ]; then
CLAUDE_CODE_VERSION="2.1.220" CLAUDE_CODE_VERSION="2.1.147"
echo "Installing Claude Code v${CLAUDE_CODE_VERSION}..." echo "Installing Claude Code v${CLAUDE_CODE_VERSION}..."
for attempt in 1 2 3; do for attempt in 1 2 3; do
echo "Installation attempt $attempt..." echo "Installation attempt $attempt..."
@ -196,11 +175,6 @@ runs:
# Provider configuration # Provider configuration
ANTHROPIC_API_KEY: ${{ inputs.anthropic_api_key }} ANTHROPIC_API_KEY: ${{ inputs.anthropic_api_key }}
CLAUDE_CODE_OAUTH_TOKEN: ${{ inputs.claude_code_oauth_token }} CLAUDE_CODE_OAUTH_TOKEN: ${{ inputs.claude_code_oauth_token }}
ANTHROPIC_FEDERATION_RULE_ID: ${{ inputs.anthropic_federation_rule_id }}
ANTHROPIC_ORGANIZATION_ID: ${{ inputs.anthropic_organization_id }}
ANTHROPIC_SERVICE_ACCOUNT_ID: ${{ inputs.anthropic_service_account_id }}
ANTHROPIC_WORKSPACE_ID: ${{ inputs.anthropic_workspace_id }}
ANTHROPIC_OIDC_AUDIENCE: ${{ inputs.anthropic_oidc_audience }}
ANTHROPIC_BASE_URL: ${{ env.ANTHROPIC_BASE_URL }} ANTHROPIC_BASE_URL: ${{ env.ANTHROPIC_BASE_URL }}
ANTHROPIC_CUSTOM_HEADERS: ${{ env.ANTHROPIC_CUSTOM_HEADERS }} ANTHROPIC_CUSTOM_HEADERS: ${{ env.ANTHROPIC_CUSTOM_HEADERS }}
# Only set provider flags if explicitly true, since any value (including "false") is truthy # Only set provider flags if explicitly true, since any value (including "false") is truthy

View File

@ -6,7 +6,7 @@
"name": "@anthropic-ai/claude-code-base-action", "name": "@anthropic-ai/claude-code-base-action",
"dependencies": { "dependencies": {
"@actions/core": "^1.10.1", "@actions/core": "^1.10.1",
"@anthropic-ai/claude-agent-sdk": "^0.3.220", "@anthropic-ai/claude-agent-sdk": "^0.3.147",
"shell-quote": "^1.8.3", "shell-quote": "^1.8.3",
}, },
"devDependencies": { "devDependencies": {
@ -27,23 +27,23 @@
"@actions/io": ["@actions/io@1.1.3", "", {}, "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q=="], "@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.220", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.220", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.220", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.220", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.220", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.220", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.220", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.220", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.220" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-glc7SdwPkOkLw8oxwLo9PKTdLJGqW/PIR4urWXFoRtX9YllwozsEVc5Tc1+EvLSkfrsxPJqQWqOgpjUOQXf1oA=="], "@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/claude-agent-sdk@0.3.147", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.147", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.147", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.147", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.147", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.147", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.147", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.147", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.147" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-FEp8oqvvzPLHCNMIvCP2KueiXy1R3djrBIlC58kh9m4BlALllwE1376aHbXP+YYgrim2PCrWuxRgteQClzs8+w=="],
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/claude-agent-sdk-darwin-arm64@0.3.220", "", { "os": "darwin", "cpu": "arm64" }, "sha512-7VxlbEosK7DODiOnsjoVd0DSJzbnaPrM2jelMHI0y8zx1UnLS3WC6EFUXbvy74F2sXqEznh2tzn7EKWInaRN6Q=="], "@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/claude-agent-sdk-darwin-arm64@0.3.147", "", { "os": "darwin", "cpu": "arm64" }, "sha512-znnkx53xxLnDbC7hqpx6CnA/5Pr3OYg/0AG75P/qzztd4RaXA2J1QjSwgccFP2Itv+Ucv1qbHsFErcrT0AUZ1Q=="],
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/claude-agent-sdk-darwin-x64@0.3.220", "", { "os": "darwin", "cpu": "x64" }, "sha512-X9RwDsSmbF6ultKZroaip+DL8WRgC64gHbrAwrRlAFSPNZV7zmJyP2ur8rW7KrxqmtuehdMMkw8+SAC/6hD2PA=="], "@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/claude-agent-sdk-darwin-x64@0.3.147", "", { "os": "darwin", "cpu": "x64" }, "sha512-o+KIQE0kqoxvYFJlCFBui4fQ3GlaEMUf1ISvTCgTiLFEZge7cEvcou7dFMGbotJ6F3M+dXPhaoMVCbwvSY5TQg=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/claude-agent-sdk-linux-arm64@0.3.220", "", { "os": "linux", "cpu": "arm64" }, "sha512-WkROPwWskqhKR9XgnmseHQ6rLi9zM9qt57IWoToIjL/eXOqDWipp7JXZ1L5ud+LrA42dunHPZfBwD/vXZ+A7LA=="], "@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/claude-agent-sdk-linux-arm64@0.3.147", "", { "os": "linux", "cpu": "arm64" }, "sha512-Kbt5fLZth/HMoMwhh9oEV07IMAbHLsxALjPTe1vDOPz2lz/lqtjQ0+/TY3I688WrR6LNUKhft+dQW+z3epwk4g=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/claude-agent-sdk-linux-arm64-musl@0.3.220", "", { "os": "linux", "cpu": "arm64" }, "sha512-OHoZOZ8Cf2TBr6oXIXPwyvUxj9jrq2w8E4poA8dMpacXszcPSPiCQCMuuOh4aWJzfeJE1+TtWxhKMVb2csXyZQ=="], "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/claude-agent-sdk-linux-arm64-musl@0.3.147", "", { "os": "linux", "cpu": "arm64" }, "sha512-9X0ai5uDtiHwaPyhp41wgwKcxTu9SkYhkMt9Xaoxwo59m8dAKzR4AhEPh5e1gwlP3RI/fSKGYBju20DRNKgg2Q=="],
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/claude-agent-sdk-linux-x64@0.3.220", "", { "os": "linux", "cpu": "x64" }, "sha512-tkTJFnpR9VifvWX2fmkCAPkT6+8Wk/gVu8B5jsVekKZPiZoWRHmMXO30BnZn+f0TZhgYP+82PSX3S8crH1kn+w=="], "@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/claude-agent-sdk-linux-x64@0.3.147", "", { "os": "linux", "cpu": "x64" }, "sha512-VJF6OXNGQEHrwNt4C5t/VS2ffk3SUR8EL25J7oFB8yr8+i/z1hDi7nrTNdD7Mi03c9gY/2qmTTv9JG+1By2vdA=="],
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/claude-agent-sdk-linux-x64-musl@0.3.220", "", { "os": "linux", "cpu": "x64" }, "sha512-K+FWj+LcGhC1Z7wqeWoLxm1iemcba5xKpLLFVwYm4V6HyMx3ruYd/2r2TiQtjT+JWeNFWIys0ScHiItR6vWAiA=="], "@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/claude-agent-sdk-linux-x64-musl@0.3.147", "", { "os": "linux", "cpu": "x64" }, "sha512-q/+mXhoPXWj6S0KAKPfI1FeoswN/Hh2Ra8+FoRKRd546YvMPN1OB18+XUfiLI2se2iW6JCI7LHBhoJ3aHhO6qA=="],
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/claude-agent-sdk-win32-arm64@0.3.220", "", { "os": "win32", "cpu": "arm64" }, "sha512-rIwgq0UwQExWl6KrHUyC4w5KwpL9l6nd95aUTx6RitexaAuEw//xtfTVLnuE4hDDQZFkzEwpdKc3nxDWoGcUbA=="], "@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/claude-agent-sdk-win32-arm64@0.3.147", "", { "os": "win32", "cpu": "arm64" }, "sha512-92F9YWo43C6gPpS6PdWUT3r+EM6xnjPkxDGP+yrXejCpPHsIrTPaqUj5x+NYYarHVk/rMexSa7+xuhIXY5vfOA=="],
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/claude-agent-sdk-win32-x64@0.3.220", "", { "os": "win32", "cpu": "x64" }, "sha512-MuOuXhbr66HlGaWXD2f3w0k2PsvmnbkwcUZ0dAe2poFLdl72GC2dapwwOBefxm9QmoNqk9+jmv/dSKGOVWyvLw=="], "@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/claude-agent-sdk-win32-x64@0.3.147", "", { "os": "win32", "cpu": "x64" }, "sha512-Km8K8VnZN920Rlnt+pBCqnkk1p6x0G/nepAapBlo2cx7YIMSKdbiSCehVb0JO9m9WdL5gHIFGsu5RFC61JOqeg=="],
"@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=="], "@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=="],

View File

@ -11,7 +11,7 @@
}, },
"dependencies": { "dependencies": {
"@actions/core": "^1.10.1", "@actions/core": "^1.10.1",
"@anthropic-ai/claude-agent-sdk": "^0.3.220", "@anthropic-ai/claude-agent-sdk": "^0.3.147",
"shell-quote": "^1.8.3" "shell-quote": "^1.8.3"
}, },
"devDependencies": { "devDependencies": {

View File

@ -7,16 +7,9 @@ import { setupClaudeCodeSettings } from "./setup-claude-code-settings";
import { validateEnvironmentVariables } from "./validate-env"; import { validateEnvironmentVariables } from "./validate-env";
import { installPlugins } from "./install-plugins"; import { installPlugins } from "./install-plugins";
import { setExecutionFileOutputIfPresent } from "./execution-file"; import { setExecutionFileOutputIfPresent } from "./execution-file";
import { setupWorkloadIdentity } from "./workload-identity";
import type { WorkloadIdentityHandle } from "./workload-identity";
async function run() { async function run() {
let workloadIdentity: WorkloadIdentityHandle | undefined;
try { try {
// When workload identity federation is configured, fetch the GitHub OIDC
// identity token and expose it to the CLI before validating auth env vars.
workloadIdentity = await setupWorkloadIdentity();
validateEnvironmentVariables(); validateEnvironmentVariables();
// The composite action's "Install Claude Code" step writes the binary to // The composite action's "Install Claude Code" step writes the binary to
@ -74,10 +67,6 @@ async function run() {
core.setFailed(`Action failed with error: ${error}`); core.setFailed(`Action failed with error: ${error}`);
core.setOutput("conclusion", "failure"); core.setOutput("conclusion", "failure");
process.exit(1); process.exit(1);
} finally {
// Stop refreshing the workload identity token file (so the process can
// exit) and delete the token material so it doesn't outlive this step
workloadIdentity?.stop();
} }
} }

View File

@ -19,41 +19,11 @@ const ACCUMULATING_FLAGS = new Set([
"disallowedTools", "disallowedTools",
"disallowed-tools", "disallowed-tools",
"mcp-config", "mcp-config",
"add-dir",
]); ]);
// Delimiter used to join accumulated flag values // Delimiter used to join accumulated flag values
const ACCUMULATE_DELIMITER = "\x00"; const ACCUMULATE_DELIMITER = "\x00";
// shell-quote treats ()|&;<> as control operators and splits adjacent text
// around them into separate tokens (returned as `{op}` objects, which we then
// dropped). For CLI args these must be literal characters — e.g. unquoted
// `--allowedTools Bash(gh:*)` was being mangled into bare `Bash`, silently
// widening a scoped permission rule to Bash(*). We escape each metachar to a
// Unicode private-use codepoint before parsing and restore it afterward,
// keeping shell-quote's quote/whitespace handling intact.
const SHELL_META_PAIRS: [string, string][] = [
["(", ""],
[")", ""],
["|", ""],
["&", ""],
[";", ""],
["<", ""],
[">", ""],
];
const SHELL_META_ESCAPE = new Map(SHELL_META_PAIRS);
const SHELL_META_UNESCAPE = new Map(SHELL_META_PAIRS.map(([k, v]) => [v, k]));
const SHELL_META_ESCAPE_RE = /[()|&;<>]/g;
const SHELL_META_UNESCAPE_RE = /[-]/g;
function escapeShellMeta(s: string): string {
return s.replace(SHELL_META_ESCAPE_RE, (c) => SHELL_META_ESCAPE.get(c)!);
}
function unescapeShellMeta(s: string): string {
return s.replace(SHELL_META_UNESCAPE_RE, (c) => SHELL_META_UNESCAPE.get(c)!);
}
type McpConfig = { type McpConfig = {
mcpServers?: Record<string, unknown>; mcpServers?: Record<string, unknown>;
}; };
@ -136,19 +106,9 @@ function parseClaudeArgsToExtraArgs(
if (!claudeArgs?.trim()) return {}; if (!claudeArgs?.trim()) return {};
const result: Record<string, string | null> = {}; const result: Record<string, string | null> = {};
const args = parseShellArgs(escapeShellMeta(stripShellComments(claudeArgs))) const args = parseShellArgs(stripShellComments(claudeArgs)).filter(
.map((arg) => { (arg): arg is string => typeof arg === "string",
if (typeof arg === "string") return unescapeShellMeta(arg); );
// With control metachars escaped above, the only non-string shell-quote
// can still emit is a glob op (bareword containing *, ?, or [). Its
// `pattern` field is the verbatim token text — use it as-is so values
// like `Bash(cmd:*)` and `Read(path/**)` round-trip intact.
if (typeof arg === "object" && arg !== null && "pattern" in arg) {
return unescapeShellMeta((arg as { pattern: string }).pattern);
}
return undefined;
})
.filter((arg): arg is string => typeof arg === "string");
for (let i = 0; i < args.length; i++) { for (let i = 0; i < args.length; i++) {
const arg = args[i]; const arg = args[i];
@ -201,17 +161,6 @@ export function parseSdkOptions(options: ClaudeOptions): ParsedSdkOptions {
// Detect if --json-schema is present (for hasJsonSchema flag) // Detect if --json-schema is present (for hasJsonSchema flag)
const hasJsonSchema = "json-schema" in extraArgs; const hasJsonSchema = "json-schema" in extraArgs;
const modelFromClaudeArgs = extraArgs["model"] || undefined;
delete extraArgs["model"];
const additionalDirectories = extraArgs["add-dir"]
? extraArgs["add-dir"]
.split(ACCUMULATE_DELIMITER)
.map((dir) => dir.trim())
.filter(Boolean)
: [];
delete extraArgs["add-dir"];
// Extract and merge allowedTools from all sources: // Extract and merge allowedTools from all sources:
// 1. From extraArgs (parsed from claudeArgs - contains tag mode's tools) // 1. From extraArgs (parsed from claudeArgs - contains tag mode's tools)
// - Check both camelCase (--allowedTools) and hyphenated (--allowed-tools) variants // - Check both camelCase (--allowedTools) and hyphenated (--allowed-tools) variants
@ -307,7 +256,7 @@ export function parseSdkOptions(options: ClaudeOptions): ParsedSdkOptions {
// Build SDK options - use merged tools from both direct options and claudeArgs // Build SDK options - use merged tools from both direct options and claudeArgs
const sdkOptions: SdkOptions = { const sdkOptions: SdkOptions = {
// Direct options from ClaudeOptions inputs // Direct options from ClaudeOptions inputs
model: options.model || modelFromClaudeArgs, model: options.model,
maxTurns: options.maxTurns ? parseInt(options.maxTurns, 10) : undefined, maxTurns: options.maxTurns ? parseInt(options.maxTurns, 10) : undefined,
allowedTools: allowedTools:
mergedAllowedTools.length > 0 ? mergedAllowedTools : undefined, mergedAllowedTools.length > 0 ? mergedAllowedTools : undefined,
@ -316,8 +265,6 @@ export function parseSdkOptions(options: ClaudeOptions): ParsedSdkOptions {
systemPrompt, systemPrompt,
fallbackModel: options.fallbackModel, fallbackModel: options.fallbackModel,
pathToClaudeCodeExecutable: options.pathToClaudeCodeExecutable, pathToClaudeCodeExecutable: options.pathToClaudeCodeExecutable,
additionalDirectories:
additionalDirectories.length > 0 ? additionalDirectories : undefined,
// Pass through claudeArgs as extraArgs - CLI handles --mcp-config, --json-schema, etc. // Pass through claudeArgs as extraArgs - CLI handles --mcp-config, --json-schema, etc.
// Note: allowedTools and disallowedTools have been removed from extraArgs to prevent duplicates // Note: allowedTools and disallowedTools have been removed from extraArgs to prevent duplicates

View File

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

View File

@ -167,16 +167,6 @@ export async function runClaudeWithSdk(
if (message.type === "result") { if (message.type === "result") {
resultMessage = message as SDKResultMessage; resultMessage = message as SDKResultMessage;
// The SDK's query() iterator should close itself after the
// result message, but in some workflow contexts (notably
// pull_request-triggered runs) it stays open indefinitely and
// the for-await hangs until the workflow's timeout-minutes
// kills the job. This causes the action to "succeed" inside
// Claude (verdict posted, $cost recorded) but be reported as
// cancelled with no execution-output.json written. Break
// explicitly: by SDK contract no further messages follow a
// result, so the break is safe.
break;
} }
} }
} catch (error) { } catch (error) {
@ -208,10 +198,7 @@ export async function runClaudeWithSdk(
throw new Error("No result message received from Claude"); throw new Error("No result message received from Claude");
} }
// subtype "success" with is_error:true means the run errored without producing const isSuccess = resultMessage.subtype === "success";
// a real result — treat it as failure so CI does not show a misleading green check.
const isSuccess =
resultMessage.subtype === "success" && !resultMessage.is_error;
result.conclusion = isSuccess ? "success" : "failure"; result.conclusion = isSuccess ? "success" : "failure";
// Handle structured output // Handle structured output
@ -237,21 +224,14 @@ export async function runClaudeWithSdk(
} }
if (!isSuccess) { if (!isSuccess) {
if (resultMessage.subtype === "success" && resultMessage.is_error) {
core.error(
"Claude result reported subtype success with is_error:true (run did not complete successfully)",
);
}
if ("errors" in resultMessage && resultMessage.errors) { if ("errors" in resultMessage && resultMessage.errors) {
core.error(`Execution failed: ${resultMessage.errors.join(", ")}`); core.error(`Execution failed: ${resultMessage.errors.join(", ")}`);
} }
throw new Error( throw new Error(
`Claude execution failed: ${ `Claude execution failed: ${
resultMessage.subtype === "success" && resultMessage.is_error "errors" in resultMessage && resultMessage.errors
? "result is_error:true" ? resultMessage.errors.join(", ")
: "errors" in resultMessage && resultMessage.errors : "unknown error"
? resultMessage.errors.join(", ")
: "unknown error"
}`, }`,
); );
} }

View File

@ -8,14 +8,6 @@ export function validateEnvironmentVariables() {
const useFoundry = process.env.CLAUDE_CODE_USE_FOUNDRY === "1"; const useFoundry = process.env.CLAUDE_CODE_USE_FOUNDRY === "1";
const anthropicApiKey = process.env.ANTHROPIC_API_KEY; const anthropicApiKey = process.env.ANTHROPIC_API_KEY;
const claudeCodeOAuthToken = process.env.CLAUDE_CODE_OAUTH_TOKEN; const claudeCodeOAuthToken = process.env.CLAUDE_CODE_OAUTH_TOKEN;
const federationRuleId = process.env.ANTHROPIC_FEDERATION_RULE_ID;
const federationOrganizationId = process.env.ANTHROPIC_ORGANIZATION_ID;
const hasWorkloadIdentity = Boolean(
federationRuleId && federationOrganizationId,
);
const hasPartialWorkloadIdentity =
!hasWorkloadIdentity &&
Boolean(federationRuleId || federationOrganizationId);
const errors: string[] = []; const errors: string[] = [];
@ -28,16 +20,10 @@ export function validateEnvironmentVariables() {
} }
if (!useBedrock && !useVertex && !useFoundry) { if (!useBedrock && !useVertex && !useFoundry) {
if (!anthropicApiKey && !claudeCodeOAuthToken && !hasWorkloadIdentity) { if (!anthropicApiKey && !claudeCodeOAuthToken) {
if (hasPartialWorkloadIdentity) { errors.push(
errors.push( "Either ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN is required when using direct Anthropic API.",
"Workload identity federation requires both ANTHROPIC_FEDERATION_RULE_ID and ANTHROPIC_ORGANIZATION_ID to be set.", );
);
} else {
errors.push(
"Either ANTHROPIC_API_KEY, CLAUDE_CODE_OAUTH_TOKEN, or workload identity federation (ANTHROPIC_FEDERATION_RULE_ID and ANTHROPIC_ORGANIZATION_ID) is required when using direct Anthropic API.",
);
}
} }
} else if (useBedrock) { } else if (useBedrock) {
const awsRegion = process.env.AWS_REGION; const awsRegion = process.env.AWS_REGION;

View File

@ -1,196 +0,0 @@
#!/usr/bin/env bun
/**
* Workload Identity Federation support.
*
* When the federation inputs are configured, the action fetches a GitHub
* Actions OIDC token (JWT), writes it to a file, and points the Claude Code
* CLI at it via ANTHROPIC_IDENTITY_TOKEN_FILE. The CLI exchanges the JWT for
* a short-lived Anthropic access token using the federation rule, so no
* static ANTHROPIC_API_KEY is needed.
*
* GitHub's OIDC tokens are short-lived and the CLI re-reads the token file
* every time it refreshes its Anthropic access token, so the action keeps the
* file fresh in the background for long-running executions.
*/
import * as core from "@actions/core";
import { createHash } from "crypto";
import { mkdirSync, rmSync, writeFileSync } from "fs";
import { join } from "path";
import { retryWithBackoff } from "./retry";
/** How often the GitHub OIDC identity token file is rewritten. */
const REFRESH_INTERVAL_MS = 4 * 60 * 1000;
/**
* Default audience requested on the GitHub OIDC token. Scopes the JWT to the
* Claude API token exchange; override with the anthropic_oidc_audience input
* if your federation rule expects a different audience.
*/
const DEFAULT_OIDC_AUDIENCE = "https://api.anthropic.com";
export type WorkloadIdentityHandle = {
tokenFile: string;
stop: () => void;
};
/**
* Whether the workload identity federation inputs are configured.
* Mirrors the Claude Code CLI's env detection, which requires the federation
* rule ID and organization ID.
*/
export function isWorkloadIdentityConfigured(): boolean {
return Boolean(
process.env.ANTHROPIC_FEDERATION_RULE_ID?.trim() &&
process.env.ANTHROPIC_ORGANIZATION_ID?.trim(),
);
}
async function fetchIdentityToken(audience: string) {
return retryWithBackoff(() => core.getIDToken(audience));
}
/**
* Writes a profile config that switches federation resolution to the
* file-backed path. Resolving federation through a profile (rather than bare
* env vars) enables the SDK's on-disk credentials cache, so the several
* `claude` processes the action spawns (plugin installs, main query) share
* one exchanged access token instead of each re-exchanging the single-use
* GitHub OIDC token, which fails with 401 (`jti_reused`).
*
* The profile is intentionally minimal: the SDK gap-fills the federation
* fields (rule, organization, identity-token file, service account, base URL)
* from the ANTHROPIC_* env vars the action already exports, so the file only
* needs to exist to turn the cache on.
*
* The config dir name embeds a fingerprint of the federation inputs. The
* SDK's cache reuses a token on `expires_at` alone, with no record of the
* config that minted it, and the token's scope is bound at mint time so a
* later action step in the same job (RUNNER_TEMP is per-job) with different
* federation inputs must land in a different dir or it would silently reuse
* the first step's token.
*
* Sharing the cache is only safe while the action spawns its `claude`
* subprocesses sequentially: the SDK cache is not cross-process serialized,
* and concurrent cache misses would each re-exchange the same single-use
* identity token. Parallelizing the plugin installs would reintroduce the
* `jti_reused` failures.
*/
function writeFederationProfile(baseDir: string): string {
// Every input that changes which credential the exchange mints must be in
// here; service_account_id and scope are sent in the exchange request body.
const fingerprint = createHash("sha256")
.update(
JSON.stringify([
process.env.ANTHROPIC_FEDERATION_RULE_ID?.trim() ?? "",
process.env.ANTHROPIC_ORGANIZATION_ID?.trim() ?? "",
process.env.ANTHROPIC_SERVICE_ACCOUNT_ID?.trim() ?? "",
process.env.ANTHROPIC_WORKSPACE_ID?.trim() ?? "",
process.env.ANTHROPIC_BASE_URL?.trim() ?? "",
process.env.ANTHROPIC_SCOPE?.trim() ?? "",
]),
)
.digest("hex")
.slice(0, 16);
const configDir = join(baseDir, `config-${fingerprint}`);
mkdirSync(join(configDir, "configs"), { recursive: true, mode: 0o700 });
writeFileSync(
join(configDir, "configs", "default.json"),
JSON.stringify(
{ version: "1.0", authentication: { type: "oidc_federation" } },
null,
2,
),
{ mode: 0o600 },
);
return configDir;
}
/**
* Fetches a GitHub Actions OIDC token, writes it to a file in RUNNER_TEMP,
* exports ANTHROPIC_IDENTITY_TOKEN_FILE, and starts a background refresh so
* the file stays valid for long executions.
*
* Returns undefined when federation is not configured or is shadowed by a
* higher-precedence credential. Callers must invoke stop() when execution
* finishes; it also deletes the identity token and any cached exchanged
* credential.
*/
export async function setupWorkloadIdentity(): Promise<
WorkloadIdentityHandle | undefined
> {
if (!isWorkloadIdentityConfigured()) {
return undefined;
}
if (
process.env.ANTHROPIC_API_KEY?.trim() ||
process.env.CLAUDE_CODE_OAUTH_TOKEN?.trim()
) {
core.warning(
"Workload identity federation inputs are set alongside anthropic_api_key or claude_code_oauth_token. The API key/OAuth token takes precedence, so federation will not be used.",
);
return undefined;
}
const audience =
process.env.ANTHROPIC_OIDC_AUDIENCE?.trim() || DEFAULT_OIDC_AUDIENCE;
const tokenDir = join(
process.env.RUNNER_TEMP || "/tmp",
"claude-workload-identity",
);
const tokenFile = join(tokenDir, "identity-token");
const writeIdentityToken = async () => {
const identityToken = await fetchIdentityToken(audience);
core.setSecret(identityToken);
mkdirSync(tokenDir, { recursive: true, mode: 0o700 });
writeFileSync(tokenFile, identityToken, { mode: 0o600 });
};
try {
await writeIdentityToken();
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(
`Failed to fetch a GitHub Actions OIDC token for workload identity federation: ${message}. Did you remember to add \`id-token: write\` to your workflow permissions?`,
);
}
process.env.ANTHROPIC_IDENTITY_TOKEN_FILE = tokenFile;
if (
process.env.ANTHROPIC_CONFIG_DIR?.trim() ||
process.env.ANTHROPIC_PROFILE?.trim()
) {
core.warning(
"ANTHROPIC_CONFIG_DIR or ANTHROPIC_PROFILE is already set, so the action will not write its own federation profile. Credential caching across the spawned Claude processes follows the existing profile configuration.",
);
} else {
process.env.ANTHROPIC_CONFIG_DIR = writeFederationProfile(tokenDir);
process.env.ANTHROPIC_PROFILE = "default";
}
console.log(
`Workload identity federation configured (rule: ${process.env.ANTHROPIC_FEDERATION_RULE_ID}, identity token file: ${tokenFile})`,
);
const refreshInterval = setInterval(() => {
writeIdentityToken().catch((error) => {
core.warning(
`Failed to refresh the GitHub Actions OIDC identity token: ${error instanceof Error ? error.message : String(error)}`,
);
});
}, REFRESH_INTERVAL_MS);
return {
tokenFile,
stop: () => {
clearInterval(refreshInterval);
// RUNNER_TEMP is per-job, not per-step: remove the identity token, the
// profile, and the cached exchanged credential so they don't outlive
// this step.
rmSync(tokenDir, { recursive: true, force: true });
},
};
}

View File

@ -106,8 +106,7 @@ describe("parseSdkOptions", () => {
const result = parseSdkOptions(options); const result = parseSdkOptions(options);
expect(result.sdkOptions.extraArgs?.["allowedTools"]).toBeUndefined(); expect(result.sdkOptions.extraArgs?.["allowedTools"]).toBeUndefined();
expect(result.sdkOptions.extraArgs?.["model"]).toBeUndefined(); expect(result.sdkOptions.extraArgs?.["model"]).toBe("claude-3-5-sonnet");
expect(result.sdkOptions.model).toBe("claude-3-5-sonnet");
}); });
test("should handle hyphenated --allowed-tools flag", () => { test("should handle hyphenated --allowed-tools flag", () => {
@ -138,110 +137,6 @@ describe("parseSdkOptions", () => {
]); ]);
}); });
test("should preserve unquoted Bash(cmd:*) rules instead of collapsing to bare Bash", () => {
// Regression: shell-quote tokenizes unquoted `(`/`)` as control ops and
// `*` as a glob, which were filtered out — collapsing scoped rules like
// `Bash(gh:*)` into bare `Bash` (= Bash(*), unrestricted shell).
const options: ClaudeOptions = {
claudeArgs: "--allowedTools View,Bash(gh:*),Bash(cat:*)",
};
const result = parseSdkOptions(options);
expect(result.sdkOptions.allowedTools).toEqual([
"View",
"Bash(gh:*)",
"Bash(cat:*)",
]);
expect(result.sdkOptions.allowedTools).not.toContain("Bash");
});
test("should preserve unquoted space-separated Bash(cmd:*) rules", () => {
const options: ClaudeOptions = {
claudeArgs: "--allowed-tools Bash(gh:*) Bash(cat:*) Read(//tmp/**)",
};
const result = parseSdkOptions(options);
expect(result.sdkOptions.allowedTools).toEqual([
"Bash(gh:*)",
"Bash(cat:*)",
"Read(//tmp/**)",
]);
expect(result.sdkOptions.allowedTools).not.toContain("Bash");
});
test("should preserve unquoted Tool(content) rules without glob chars", () => {
const options: ClaudeOptions = {
claudeArgs:
"--allowedTools Read(~/file),WebFetch(domain:example.com),Edit",
};
const result = parseSdkOptions(options);
expect(result.sdkOptions.allowedTools).toEqual([
"Read(~/file)",
"WebFetch(domain:example.com)",
"Edit",
]);
});
test("should still preserve quoted Bash(cmd:*) rules (no regression)", () => {
const options: ClaudeOptions = {
claudeArgs: '--allowedTools "Bash(gh:*),Bash(cat:*)"',
};
const result = parseSdkOptions(options);
expect(result.sdkOptions.allowedTools).toEqual([
"Bash(gh:*)",
"Bash(cat:*)",
]);
});
test("should merge quoted tag-mode tools with unquoted user tools without widening", () => {
// Real-world shape: the action's tag mode wraps its own --allowedTools in
// double quotes, then appends the user's claude_args (typically unquoted
// in workflow YAML). Both halves must round-trip.
const options: ClaudeOptions = {
claudeArgs:
'--permission-mode acceptEdits --allowedTools "Glob,Grep,Read,Bash(git add:*),Bash(git commit:*)" ' +
"--model claude-opus-4-7\n" +
"--allowedTools View,Bash(gh:*),Bash(printf:*),Bash(cat:*)",
};
const result = parseSdkOptions(options);
expect(result.sdkOptions.allowedTools).toEqual([
"Glob",
"Grep",
"Read",
"Bash(git add:*)",
"Bash(git commit:*)",
"View",
"Bash(gh:*)",
"Bash(printf:*)",
"Bash(cat:*)",
]);
expect(result.sdkOptions.allowedTools).not.toContain("Bash");
});
test("should preserve unquoted disallowedTools rules without widening", () => {
// Same bug class on the deny side: a scoped deny collapsing to bare
// `Bash` would block all shell instead of the intended prefix.
const options: ClaudeOptions = {
claudeArgs: "--disallowedTools Bash(rm:*),Bash(sudo:*)",
};
const result = parseSdkOptions(options);
expect(result.sdkOptions.disallowedTools).toEqual([
"Bash(rm:*)",
"Bash(sudo:*)",
]);
expect(result.sdkOptions.disallowedTools).not.toContain("Bash");
});
test("should handle mixed camelCase and hyphenated allowedTools flags", () => { test("should handle mixed camelCase and hyphenated allowedTools flags", () => {
const options: ClaudeOptions = { const options: ClaudeOptions = {
claudeArgs: '--allowedTools "Edit,Read" --allowed-tools "Write,Glob"', claudeArgs: '--allowedTools "Edit,Read" --allowed-tools "Write,Glob"',
@ -367,8 +262,7 @@ describe("parseSdkOptions", () => {
); );
expect(mcpConfig.mcpServers).toHaveProperty("server1"); expect(mcpConfig.mcpServers).toHaveProperty("server1");
expect(mcpConfig.mcpServers).toHaveProperty("server2"); expect(mcpConfig.mcpServers).toHaveProperty("server2");
expect(result.sdkOptions.extraArgs?.["model"]).toBeUndefined(); expect(result.sdkOptions.extraArgs?.["model"]).toBe("claude-3-5-sonnet");
expect(result.sdkOptions.model).toBe("claude-3-5-sonnet");
}); });
test("should handle real-world scenario: action config + user config", () => { test("should handle real-world scenario: action config + user config", () => {
@ -404,46 +298,6 @@ describe("parseSdkOptions", () => {
}); });
}); });
describe("add-dir handling", () => {
test("should accumulate multiple add-dir flags into additionalDirectories", () => {
const options: ClaudeOptions = {
claudeArgs: '--add-dir "/path/to/dir-a"\n--add-dir "/path/to/dir-b"',
};
const result = parseSdkOptions(options);
expect(result.sdkOptions.additionalDirectories).toEqual([
"/path/to/dir-a",
"/path/to/dir-b",
]);
expect(result.sdkOptions.extraArgs?.["add-dir"]).toBeUndefined();
});
test("should map a single add-dir flag to additionalDirectories", () => {
const options: ClaudeOptions = {
claudeArgs: '--add-dir "/path/to/dir"',
};
const result = parseSdkOptions(options);
expect(result.sdkOptions.additionalDirectories).toEqual(["/path/to/dir"]);
expect(result.sdkOptions.extraArgs?.["add-dir"]).toBeUndefined();
});
test("should preserve other extraArgs when extracting add-dir", () => {
const options: ClaudeOptions = {
claudeArgs: '--model "claude-3-5-sonnet" --add-dir "/path/to/dir"',
};
const result = parseSdkOptions(options);
expect(result.sdkOptions.additionalDirectories).toEqual(["/path/to/dir"]);
expect(result.sdkOptions.extraArgs?.["model"]).toBeUndefined();
expect(result.sdkOptions.model).toBe("claude-3-5-sonnet");
expect(result.sdkOptions.extraArgs?.["add-dir"]).toBeUndefined();
});
});
describe("other extraArgs passthrough", () => { describe("other extraArgs passthrough", () => {
test("should pass through json-schema in extraArgs", () => { test("should pass through json-schema in extraArgs", () => {
const options: ClaudeOptions = { const options: ClaudeOptions = {
@ -467,8 +321,7 @@ describe("parseSdkOptions", () => {
const result = parseSdkOptions(options); const result = parseSdkOptions(options);
expect(result.sdkOptions.extraArgs?.["model"]).toBeUndefined(); expect(result.sdkOptions.extraArgs?.["model"]).toBe("claude-haiku");
expect(result.sdkOptions.model).toBe("claude-haiku");
expect(result.sdkOptions.allowedTools).toEqual(["Edit"]); expect(result.sdkOptions.allowedTools).toEqual(["Edit"]);
}); });
@ -479,8 +332,7 @@ describe("parseSdkOptions", () => {
const result = parseSdkOptions(options); const result = parseSdkOptions(options);
expect(result.sdkOptions.extraArgs?.["model"]).toBeUndefined(); expect(result.sdkOptions.extraArgs?.["model"]).toBe("claude-haiku");
expect(result.sdkOptions.model).toBe("claude-haiku");
}); });
test("should not strip inline # that appears inside a quoted value", () => { test("should not strip inline # that appears inside a quoted value", () => {
@ -490,37 +342,11 @@ describe("parseSdkOptions", () => {
const result = parseSdkOptions(options); const result = parseSdkOptions(options);
expect(result.sdkOptions.extraArgs?.["model"]).toBeUndefined(); expect(result.sdkOptions.extraArgs?.["model"]).toBe("claude-haiku");
expect(result.sdkOptions.model).toBe("claude-haiku");
expect(result.sdkOptions.extraArgs?.["prompt"]).toBe("use color #ff0000"); expect(result.sdkOptions.extraArgs?.["prompt"]).toBe("use color #ff0000");
}); });
}); });
describe("model handling", () => {
test("should map --model from claudeArgs to sdkOptions.model", () => {
const options: ClaudeOptions = {
claudeArgs: "--model claude-haiku-4-5-20251001",
};
const result = parseSdkOptions(options);
expect(result.sdkOptions.model).toBe("claude-haiku-4-5-20251001");
expect(result.sdkOptions.extraArgs?.["model"]).toBeUndefined();
});
test("should prefer direct model option over --model from claudeArgs", () => {
const options: ClaudeOptions = {
model: "claude-sonnet-4-6",
claudeArgs: "--model claude-haiku-4-5-20251001",
};
const result = parseSdkOptions(options);
expect(result.sdkOptions.model).toBe("claude-sonnet-4-6");
expect(result.sdkOptions.extraArgs?.["model"]).toBeUndefined();
});
});
describe("environment variables passthrough", () => { describe("environment variables passthrough", () => {
test("should include OTEL environment variables in sdkOptions.env", () => { test("should include OTEL environment variables in sdkOptions.env", () => {
// Set up test environment variables // Set up test environment variables

View File

@ -63,69 +63,4 @@ describe("runClaudeWithSdk", () => {
consoleLogSpy.mockRestore(); consoleLogSpy.mockRestore();
} }
}); });
test("fails when result subtype is success but is_error is true", async () => {
const consoleErrorSpy = spyOn(console, "error").mockImplementation(
() => {},
);
const consoleLogSpy = spyOn(console, "log").mockImplementation(() => {});
const coreErrorSpy = spyOn(
await import("@actions/core"),
"error",
).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-sonnet-5",
};
const errorResultMessage = {
type: "result",
subtype: "success",
is_error: true,
duration_ms: 434,
num_turns: 1,
total_cost_usd: 0,
permission_denials: [],
};
mock.module("@anthropic-ai/claude-agent-sdk", () => ({
query: async function* () {
yield initMessage;
yield errorResultMessage;
},
}));
try {
const { runClaudeWithSdk } = await import("../src/run-claude-sdk");
await expect(
runClaudeWithSdk(promptPath, {
sdkOptions: {},
showFullOutput: false,
hasJsonSchema: false,
}),
).rejects.toThrow("result is_error:true");
const executionFile = join(tempDir, "claude-execution-output.json");
await expect(readFile(executionFile, "utf-8")).resolves.toBe(
JSON.stringify([initMessage, errorResultMessage], null, 2),
);
expect(coreErrorSpy).toHaveBeenCalledWith(
"Claude result reported subtype success with is_error:true (run did not complete successfully)",
);
} finally {
consoleErrorSpy.mockRestore();
consoleLogSpy.mockRestore();
coreErrorSpy.mockRestore();
}
});
}); });

View File

@ -11,8 +11,6 @@ describe("validateEnvironmentVariables", () => {
originalEnv = { ...process.env }; originalEnv = { ...process.env };
// Clear relevant environment variables // Clear relevant environment variables
delete process.env.ANTHROPIC_API_KEY; delete process.env.ANTHROPIC_API_KEY;
delete process.env.ANTHROPIC_FEDERATION_RULE_ID;
delete process.env.ANTHROPIC_ORGANIZATION_ID;
delete process.env.CLAUDE_CODE_USE_BEDROCK; delete process.env.CLAUDE_CODE_USE_BEDROCK;
delete process.env.CLAUDE_CODE_USE_VERTEX; delete process.env.CLAUDE_CODE_USE_VERTEX;
delete process.env.CLAUDE_CODE_USE_FOUNDRY; delete process.env.CLAUDE_CODE_USE_FOUNDRY;
@ -44,32 +42,7 @@ describe("validateEnvironmentVariables", () => {
test("should fail when ANTHROPIC_API_KEY is missing", () => { test("should fail when ANTHROPIC_API_KEY is missing", () => {
expect(() => validateEnvironmentVariables()).toThrow( expect(() => validateEnvironmentVariables()).toThrow(
"Either ANTHROPIC_API_KEY, CLAUDE_CODE_OAUTH_TOKEN, or workload identity federation (ANTHROPIC_FEDERATION_RULE_ID and ANTHROPIC_ORGANIZATION_ID) is required when using direct Anthropic API.", "Either ANTHROPIC_API_KEY or CLAUDE_CODE_OAUTH_TOKEN is required when using direct Anthropic API.",
);
});
test("should pass when workload identity federation variables are provided", () => {
process.env.ANTHROPIC_FEDERATION_RULE_ID = "fdrl_test";
process.env.ANTHROPIC_ORGANIZATION_ID =
"00000000-0000-0000-0000-000000000000";
expect(() => validateEnvironmentVariables()).not.toThrow();
});
test("should fail when only ANTHROPIC_FEDERATION_RULE_ID is provided", () => {
process.env.ANTHROPIC_FEDERATION_RULE_ID = "fdrl_test";
expect(() => validateEnvironmentVariables()).toThrow(
"Workload identity federation requires both ANTHROPIC_FEDERATION_RULE_ID and ANTHROPIC_ORGANIZATION_ID to be set.",
);
});
test("should fail when only ANTHROPIC_ORGANIZATION_ID is provided", () => {
process.env.ANTHROPIC_ORGANIZATION_ID =
"00000000-0000-0000-0000-000000000000";
expect(() => validateEnvironmentVariables()).toThrow(
"Workload identity federation requires both ANTHROPIC_FEDERATION_RULE_ID and ANTHROPIC_ORGANIZATION_ID to be set.",
); );
}); });
}); });

View File

@ -1,258 +0,0 @@
#!/usr/bin/env bun
import { describe, test, expect, beforeEach, afterEach, spyOn } from "bun:test";
import * as core from "@actions/core";
import {
existsSync,
mkdtempSync,
readdirSync,
readFileSync,
rmSync,
statSync,
} from "fs";
import { tmpdir } from "os";
import { join } from "path";
import {
isWorkloadIdentityConfigured,
setupWorkloadIdentity,
} from "../src/workload-identity";
describe("workload identity federation", () => {
let originalEnv: NodeJS.ProcessEnv;
let tempDir: string;
let getIDTokenSpy: ReturnType<typeof spyOn>;
let warningSpy: ReturnType<typeof spyOn>;
let setSecretSpy: ReturnType<typeof spyOn>;
beforeEach(() => {
originalEnv = { ...process.env };
tempDir = mkdtempSync(join(tmpdir(), "wif-test-"));
process.env.RUNNER_TEMP = tempDir;
delete process.env.ANTHROPIC_API_KEY;
delete process.env.CLAUDE_CODE_OAUTH_TOKEN;
delete process.env.ANTHROPIC_FEDERATION_RULE_ID;
delete process.env.ANTHROPIC_ORGANIZATION_ID;
delete process.env.ANTHROPIC_OIDC_AUDIENCE;
delete process.env.ANTHROPIC_IDENTITY_TOKEN_FILE;
delete process.env.ANTHROPIC_SERVICE_ACCOUNT_ID;
delete process.env.ANTHROPIC_WORKSPACE_ID;
delete process.env.ANTHROPIC_BASE_URL;
delete process.env.ANTHROPIC_SCOPE;
delete process.env.ANTHROPIC_CONFIG_DIR;
delete process.env.ANTHROPIC_PROFILE;
getIDTokenSpy = spyOn(core, "getIDToken").mockResolvedValue(
"test-identity-token",
);
warningSpy = spyOn(core, "warning").mockImplementation(() => {});
setSecretSpy = spyOn(core, "setSecret").mockImplementation(() => {});
});
afterEach(() => {
process.env = originalEnv;
getIDTokenSpy.mockRestore();
warningSpy.mockRestore();
setSecretSpy.mockRestore();
rmSync(tempDir, { recursive: true, force: true });
});
describe("isWorkloadIdentityConfigured", () => {
test("returns false when no federation variables are set", () => {
expect(isWorkloadIdentityConfigured()).toBe(false);
});
test("returns false when only one federation variable is set", () => {
process.env.ANTHROPIC_FEDERATION_RULE_ID = "fdrl_test";
expect(isWorkloadIdentityConfigured()).toBe(false);
});
test("returns true when rule ID and organization ID are set", () => {
process.env.ANTHROPIC_FEDERATION_RULE_ID = "fdrl_test";
process.env.ANTHROPIC_ORGANIZATION_ID =
"00000000-0000-0000-0000-000000000000";
expect(isWorkloadIdentityConfigured()).toBe(true);
});
});
describe("setupWorkloadIdentity", () => {
test("returns undefined when federation is not configured", async () => {
const handle = await setupWorkloadIdentity();
expect(handle).toBeUndefined();
expect(getIDTokenSpy).not.toHaveBeenCalled();
});
test("returns undefined and warns when an API key is also set", async () => {
process.env.ANTHROPIC_FEDERATION_RULE_ID = "fdrl_test";
process.env.ANTHROPIC_ORGANIZATION_ID =
"00000000-0000-0000-0000-000000000000";
process.env.ANTHROPIC_API_KEY = "sk-ant-test";
const handle = await setupWorkloadIdentity();
expect(handle).toBeUndefined();
expect(warningSpy).toHaveBeenCalled();
expect(getIDTokenSpy).not.toHaveBeenCalled();
expect(process.env.ANTHROPIC_IDENTITY_TOKEN_FILE).toBeUndefined();
});
test("writes the identity token file and exports its path", async () => {
process.env.ANTHROPIC_FEDERATION_RULE_ID = "fdrl_test";
process.env.ANTHROPIC_ORGANIZATION_ID =
"00000000-0000-0000-0000-000000000000";
const handle = await setupWorkloadIdentity();
try {
expect(handle).toBeDefined();
expect(handle!.tokenFile).toBe(
join(tempDir, "claude-workload-identity", "identity-token"),
);
expect(process.env.ANTHROPIC_IDENTITY_TOKEN_FILE).toBe(
handle!.tokenFile,
);
expect(existsSync(handle!.tokenFile)).toBe(true);
expect(readFileSync(handle!.tokenFile, "utf-8")).toBe(
"test-identity-token",
);
expect(statSync(handle!.tokenFile).mode & 0o777).toBe(0o600);
expect(setSecretSpy).toHaveBeenCalledWith("test-identity-token");
// Default audience scopes the JWT to the Claude API token exchange
expect(getIDTokenSpy).toHaveBeenCalledWith("https://api.anthropic.com");
} finally {
handle?.stop();
}
});
test("requests the configured audience", async () => {
process.env.ANTHROPIC_FEDERATION_RULE_ID = "fdrl_test";
process.env.ANTHROPIC_ORGANIZATION_ID =
"00000000-0000-0000-0000-000000000000";
process.env.ANTHROPIC_OIDC_AUDIENCE = "https://example.com/custom";
const handle = await setupWorkloadIdentity();
try {
expect(getIDTokenSpy).toHaveBeenCalledWith(
"https://example.com/custom",
);
} finally {
handle?.stop();
}
});
test("writes a minimal federation profile and selects it", async () => {
process.env.ANTHROPIC_FEDERATION_RULE_ID = "fdrl_test";
process.env.ANTHROPIC_ORGANIZATION_ID =
"00000000-0000-0000-0000-000000000000";
process.env.ANTHROPIC_SERVICE_ACCOUNT_ID = "svac_test";
process.env.ANTHROPIC_WORKSPACE_ID = "wrkspc_test";
const handle = await setupWorkloadIdentity();
try {
const configDir = process.env.ANTHROPIC_CONFIG_DIR;
expect(configDir).toBeDefined();
expect(
configDir!.startsWith(
join(tempDir, "claude-workload-identity", "config-"),
),
).toBe(true);
expect(process.env.ANTHROPIC_PROFILE).toBe("default");
const profilePath = join(configDir!, "configs", "default.json");
expect(statSync(profilePath).mode & 0o777).toBe(0o600);
// Minimal on purpose: the SDK gap-fills the federation fields from
// the ANTHROPIC_* env vars the action exports.
expect(JSON.parse(readFileSync(profilePath, "utf-8"))).toEqual({
version: "1.0",
authentication: { type: "oidc_federation" },
});
} finally {
handle?.stop();
}
});
test("derives the config dir from the federation inputs", async () => {
process.env.ANTHROPIC_FEDERATION_RULE_ID = "fdrl_test";
process.env.ANTHROPIC_ORGANIZATION_ID =
"00000000-0000-0000-0000-000000000000";
process.env.ANTHROPIC_WORKSPACE_ID = "wrkspc_a";
(await setupWorkloadIdentity())?.stop();
const firstConfigDir = process.env.ANTHROPIC_CONFIG_DIR;
expect(firstConfigDir).toBeDefined();
// A later step in the same job with a different workspace must not
// share the first step's credentials cache.
delete process.env.ANTHROPIC_CONFIG_DIR;
delete process.env.ANTHROPIC_PROFILE;
process.env.ANTHROPIC_WORKSPACE_ID = "wrkspc_b";
(await setupWorkloadIdentity())?.stop();
const secondConfigDir = process.env.ANTHROPIC_CONFIG_DIR;
expect(secondConfigDir).toBeDefined();
expect(secondConfigDir).not.toBe(firstConfigDir);
// Same inputs land in the same dir, so an unchanged config can still
// reuse a cached token.
delete process.env.ANTHROPIC_CONFIG_DIR;
delete process.env.ANTHROPIC_PROFILE;
(await setupWorkloadIdentity())?.stop();
expect(process.env.ANTHROPIC_CONFIG_DIR).toBe(secondConfigDir!);
});
test("does not overwrite an operator-set ANTHROPIC_PROFILE", async () => {
process.env.ANTHROPIC_FEDERATION_RULE_ID = "fdrl_test";
process.env.ANTHROPIC_ORGANIZATION_ID =
"00000000-0000-0000-0000-000000000000";
process.env.ANTHROPIC_PROFILE = "operator";
const handle = await setupWorkloadIdentity();
try {
expect(process.env.ANTHROPIC_PROFILE).toBe("operator");
expect(process.env.ANTHROPIC_CONFIG_DIR).toBeUndefined();
expect(warningSpy).toHaveBeenCalled();
const entries = readdirSync(join(tempDir, "claude-workload-identity"));
expect(entries.filter((e) => e.startsWith("config-"))).toEqual([]);
// The identity token file is still provisioned for the operator's
// profile (or the env-var fallback) to consume.
expect(process.env.ANTHROPIC_IDENTITY_TOKEN_FILE).toBe(
handle!.tokenFile,
);
} finally {
handle?.stop();
}
});
test("does not overwrite an operator-set ANTHROPIC_CONFIG_DIR", async () => {
process.env.ANTHROPIC_FEDERATION_RULE_ID = "fdrl_test";
process.env.ANTHROPIC_ORGANIZATION_ID =
"00000000-0000-0000-0000-000000000000";
const operatorConfigDir = join(tempDir, "operator-config");
process.env.ANTHROPIC_CONFIG_DIR = operatorConfigDir;
const handle = await setupWorkloadIdentity();
try {
expect(process.env.ANTHROPIC_CONFIG_DIR).toBe(operatorConfigDir);
expect(process.env.ANTHROPIC_PROFILE).toBeUndefined();
expect(warningSpy).toHaveBeenCalled();
} finally {
handle?.stop();
}
});
test("stop removes the identity token and credential cache", async () => {
process.env.ANTHROPIC_FEDERATION_RULE_ID = "fdrl_test";
process.env.ANTHROPIC_ORGANIZATION_ID =
"00000000-0000-0000-0000-000000000000";
const handle = await setupWorkloadIdentity();
const tokenDir = join(tempDir, "claude-workload-identity");
expect(existsSync(handle!.tokenFile)).toBe(true);
expect(existsSync(process.env.ANTHROPIC_CONFIG_DIR!)).toBe(true);
handle!.stop();
expect(existsSync(tokenDir)).toBe(false);
});
});
});

View File

@ -7,7 +7,7 @@
"dependencies": { "dependencies": {
"@actions/core": "^1.10.1", "@actions/core": "^1.10.1",
"@actions/github": "^6.0.1", "@actions/github": "^6.0.1",
"@anthropic-ai/claude-agent-sdk": "^0.3.220", "@anthropic-ai/claude-agent-sdk": "^0.3.147",
"@modelcontextprotocol/sdk": "^1.11.0", "@modelcontextprotocol/sdk": "^1.11.0",
"@octokit/graphql": "^8.2.2", "@octokit/graphql": "^8.2.2",
"@octokit/rest": "^21.1.1", "@octokit/rest": "^21.1.1",
@ -37,23 +37,23 @@
"@actions/io": ["@actions/io@1.1.3", "", {}, "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q=="], "@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.220", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.220", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.220", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.220", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.220", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.220", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.220", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.220", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.220" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-glc7SdwPkOkLw8oxwLo9PKTdLJGqW/PIR4urWXFoRtX9YllwozsEVc5Tc1+EvLSkfrsxPJqQWqOgpjUOQXf1oA=="], "@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/claude-agent-sdk@0.3.147", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.147", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.147", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.147", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.147", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.147", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.147", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.147", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.147" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-FEp8oqvvzPLHCNMIvCP2KueiXy1R3djrBIlC58kh9m4BlALllwE1376aHbXP+YYgrim2PCrWuxRgteQClzs8+w=="],
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/claude-agent-sdk-darwin-arm64@0.3.220", "", { "os": "darwin", "cpu": "arm64" }, "sha512-7VxlbEosK7DODiOnsjoVd0DSJzbnaPrM2jelMHI0y8zx1UnLS3WC6EFUXbvy74F2sXqEznh2tzn7EKWInaRN6Q=="], "@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/claude-agent-sdk-darwin-arm64@0.3.147", "", { "os": "darwin", "cpu": "arm64" }, "sha512-znnkx53xxLnDbC7hqpx6CnA/5Pr3OYg/0AG75P/qzztd4RaXA2J1QjSwgccFP2Itv+Ucv1qbHsFErcrT0AUZ1Q=="],
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/claude-agent-sdk-darwin-x64@0.3.220", "", { "os": "darwin", "cpu": "x64" }, "sha512-X9RwDsSmbF6ultKZroaip+DL8WRgC64gHbrAwrRlAFSPNZV7zmJyP2ur8rW7KrxqmtuehdMMkw8+SAC/6hD2PA=="], "@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/claude-agent-sdk-darwin-x64@0.3.147", "", { "os": "darwin", "cpu": "x64" }, "sha512-o+KIQE0kqoxvYFJlCFBui4fQ3GlaEMUf1ISvTCgTiLFEZge7cEvcou7dFMGbotJ6F3M+dXPhaoMVCbwvSY5TQg=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/claude-agent-sdk-linux-arm64@0.3.220", "", { "os": "linux", "cpu": "arm64" }, "sha512-WkROPwWskqhKR9XgnmseHQ6rLi9zM9qt57IWoToIjL/eXOqDWipp7JXZ1L5ud+LrA42dunHPZfBwD/vXZ+A7LA=="], "@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/claude-agent-sdk-linux-arm64@0.3.147", "", { "os": "linux", "cpu": "arm64" }, "sha512-Kbt5fLZth/HMoMwhh9oEV07IMAbHLsxALjPTe1vDOPz2lz/lqtjQ0+/TY3I688WrR6LNUKhft+dQW+z3epwk4g=="],
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/claude-agent-sdk-linux-arm64-musl@0.3.220", "", { "os": "linux", "cpu": "arm64" }, "sha512-OHoZOZ8Cf2TBr6oXIXPwyvUxj9jrq2w8E4poA8dMpacXszcPSPiCQCMuuOh4aWJzfeJE1+TtWxhKMVb2csXyZQ=="], "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/claude-agent-sdk-linux-arm64-musl@0.3.147", "", { "os": "linux", "cpu": "arm64" }, "sha512-9X0ai5uDtiHwaPyhp41wgwKcxTu9SkYhkMt9Xaoxwo59m8dAKzR4AhEPh5e1gwlP3RI/fSKGYBju20DRNKgg2Q=="],
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/claude-agent-sdk-linux-x64@0.3.220", "", { "os": "linux", "cpu": "x64" }, "sha512-tkTJFnpR9VifvWX2fmkCAPkT6+8Wk/gVu8B5jsVekKZPiZoWRHmMXO30BnZn+f0TZhgYP+82PSX3S8crH1kn+w=="], "@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/claude-agent-sdk-linux-x64@0.3.147", "", { "os": "linux", "cpu": "x64" }, "sha512-VJF6OXNGQEHrwNt4C5t/VS2ffk3SUR8EL25J7oFB8yr8+i/z1hDi7nrTNdD7Mi03c9gY/2qmTTv9JG+1By2vdA=="],
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/claude-agent-sdk-linux-x64-musl@0.3.220", "", { "os": "linux", "cpu": "x64" }, "sha512-K+FWj+LcGhC1Z7wqeWoLxm1iemcba5xKpLLFVwYm4V6HyMx3ruYd/2r2TiQtjT+JWeNFWIys0ScHiItR6vWAiA=="], "@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/claude-agent-sdk-linux-x64-musl@0.3.147", "", { "os": "linux", "cpu": "x64" }, "sha512-q/+mXhoPXWj6S0KAKPfI1FeoswN/Hh2Ra8+FoRKRd546YvMPN1OB18+XUfiLI2se2iW6JCI7LHBhoJ3aHhO6qA=="],
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/claude-agent-sdk-win32-arm64@0.3.220", "", { "os": "win32", "cpu": "arm64" }, "sha512-rIwgq0UwQExWl6KrHUyC4w5KwpL9l6nd95aUTx6RitexaAuEw//xtfTVLnuE4hDDQZFkzEwpdKc3nxDWoGcUbA=="], "@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/claude-agent-sdk-win32-arm64@0.3.147", "", { "os": "win32", "cpu": "arm64" }, "sha512-92F9YWo43C6gPpS6PdWUT3r+EM6xnjPkxDGP+yrXejCpPHsIrTPaqUj5x+NYYarHVk/rMexSa7+xuhIXY5vfOA=="],
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/claude-agent-sdk-win32-x64@0.3.220", "", { "os": "win32", "cpu": "x64" }, "sha512-MuOuXhbr66HlGaWXD2f3w0k2PsvmnbkwcUZ0dAe2poFLdl72GC2dapwwOBefxm9QmoNqk9+jmv/dSKGOVWyvLw=="], "@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/claude-agent-sdk-win32-x64@0.3.147", "", { "os": "win32", "cpu": "x64" }, "sha512-Km8K8VnZN920Rlnt+pBCqnkk1p6x0G/nepAapBlo2cx7YIMSKdbiSCehVb0JO9m9WdL5gHIFGsu5RFC61JOqeg=="],
"@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=="], "@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=="],

View File

@ -337,17 +337,17 @@ For a complete list of available settings and their descriptions, see the [Claud
Many individual input parameters have been consolidated into `claude_args` or `settings`. Here's how to migrate: Many individual input parameters have been consolidated into `claude_args` or `settings`. Here's how to migrate:
| Old Input | New Approach | | Old Input | New Approach |
| --------------------- | --------------------------------------------------------------- | | --------------------- | -------------------------------------------------------- |
| `allowed_tools` | Use `claude_args: "--allowedTools Tool1,Tool2"` | | `allowed_tools` | Use `claude_args: "--allowedTools Tool1,Tool2"` |
| `disallowed_tools` | Use `claude_args: "--disallowedTools Tool1,Tool2"` | | `disallowed_tools` | Use `claude_args: "--disallowedTools Tool1,Tool2"` |
| `max_turns` | Use `claude_args: "--max-turns 10"` | | `max_turns` | Use `claude_args: "--max-turns 10"` |
| `model` | Use `claude_args: "--model claude-4-0-sonnet-20250805"` | | `model` | Use `claude_args: "--model claude-4-0-sonnet-20250805"` |
| `claude_env` | Use `settings` with `"env"` object | | `claude_env` | Use `settings` with `"env"` object |
| `custom_instructions` | Use `claude_args: "--append-system-prompt 'Your instructions'"` | | `custom_instructions` | Use `claude_args: "--system-prompt 'Your instructions'"` |
| `mcp_config` | Use `claude_args: "--mcp-config '{...}'"` | | `mcp_config` | Use `claude_args: "--mcp-config '{...}'"` |
| `direct_prompt` | Use `prompt` input instead | | `direct_prompt` | Use `prompt` input instead |
| `override_prompt` | Use `prompt` with GitHub context variables | | `override_prompt` | Use `prompt` with GitHub context variables |
## Custom Executables for Specialized Environments ## Custom Executables for Specialized Environments

View File

@ -26,7 +26,7 @@ This action supports the following GitHub events ([learn more GitHub event trigg
## Automated Documentation Updates ## Automated Documentation Updates
Automatically update documentation when specific files change (see [`examples/pr-review-filtered-paths.yml`](../examples/pr-review-filtered-paths.yml)): Automatically update documentation when specific files change (see [`examples/claude-pr-path-specific.yml`](../examples/claude-pr-path-specific.yml)):
```yaml ```yaml
on: on:
@ -47,7 +47,7 @@ When API files are modified, the action automatically detects that a `prompt` is
## Author-Specific Code Reviews ## Author-Specific Code Reviews
Automatically review PRs from specific authors or external contributors (see [`examples/pr-review-filtered-authors.yml`](../examples/pr-review-filtered-authors.yml)): Automatically review PRs from specific authors or external contributors (see [`examples/claude-review-from-author.yml`](../examples/claude-review-from-author.yml)):
```yaml ```yaml
on: on:

View File

@ -63,14 +63,17 @@ The GitHub App for Claude doesn't have workflow write access for security reason
### Why won't Claude rebase my branch? ### Why won't Claude rebase my branch?
Claude only creates and pushes commits. It does not merge branches, rebase, force push, or perform other destructive git operations. Specifically, Claude is configured to: By default, Claude only uses commit tools for non-destructive changes to the branch. Claude is configured to:
- Never push to branches other than where it was invoked (either its own branch or the PR branch) - Never push to branches other than where it was invoked (either its own branch or the PR branch)
- Never force push or perform destructive operations - Never force push or perform destructive operations
This restriction is enforced in Claude's system prompt, so it applies even if you grant the underlying git tools (for example `--allowedTools "Bash(git rebase:*)"`). In that case Claude will still decline rebase requests and explain the limitation rather than running the command. You can grant additional tools via the `claude_args` input if needed:
If you need to rebase, do it yourself locally — or with the Claude Code CLI outside of this action — and push the result. ```yaml
claude_args: |
--allowedTools "Bash(git rebase:*)" # Use with caution
```
### Why won't Claude create a pull request? ### Why won't Claude create a pull request?
@ -153,7 +156,7 @@ prompt: "Review this PR for security vulnerabilities"
**These inputs are deprecated in v1.0:** **These inputs are deprecated in v1.0:**
- **`direct_prompt`** → Use `prompt` instead - **`direct_prompt`** → Use `prompt` instead
- **`custom_instructions`** → Use `claude_args` with `--append-system-prompt` (appends to the default system prompt, matching v0 behavior; `--system-prompt` replaces it entirely) - **`custom_instructions`** → Use `claude_args` with `--system-prompt`
Migration examples: Migration examples:
@ -165,7 +168,7 @@ custom_instructions: "Focus on security"
# New (v1.0) # New (v1.0)
prompt: "Review this PR" prompt: "Review this PR"
claude_args: | claude_args: |
--append-system-prompt "Focus on security" --system-prompt "Focus on security"
``` ```
### Why doesn't Claude execute my bash commands? ### Why doesn't Claude execute my bash commands?

View File

@ -14,19 +14,19 @@ This guide helps you migrate from Claude Code Action v0.x to v1.0. The new versi
The following inputs have been deprecated and replaced: The following inputs have been deprecated and replaced:
| Deprecated Input | Replacement | Notes | | Deprecated Input | Replacement | Notes |
| --------------------- | ------------------------------------- | ----------------------------------------------------------------------------------- | | --------------------- | ------------------------------------ | --------------------------------------------- |
| `mode` | Auto-detected | Action automatically chooses based on context | | `mode` | Auto-detected | Action automatically chooses based on context |
| `direct_prompt` | `prompt` | Direct drop-in replacement | | `direct_prompt` | `prompt` | Direct drop-in replacement |
| `override_prompt` | `prompt` | Use GitHub context variables instead | | `override_prompt` | `prompt` | Use GitHub context variables instead |
| `custom_instructions` | `claude_args: --append-system-prompt` | Appends to the default prompt (v0 behavior); `--system-prompt` replaces it entirely | | `custom_instructions` | `claude_args: --system-prompt` | Move to CLI arguments |
| `max_turns` | `claude_args: --max-turns` | Use CLI format | | `max_turns` | `claude_args: --max-turns` | Use CLI format |
| `model` | `claude_args: --model` | Specify via CLI | | `model` | `claude_args: --model` | Specify via CLI |
| `allowed_tools` | `claude_args: --allowedTools` | Use CLI format | | `allowed_tools` | `claude_args: --allowedTools` | Use CLI format |
| `disallowed_tools` | `claude_args: --disallowedTools` | Use CLI format | | `disallowed_tools` | `claude_args: --disallowedTools` | Use CLI format |
| `claude_env` | `settings` with env object | Use settings JSON | | `claude_env` | `settings` with env object | Use settings JSON |
| `mcp_config` | `claude_args: --mcp-config` | Pass MCP config via CLI arguments | | `mcp_config` | `claude_args: --mcp-config` | Pass MCP config via CLI arguments |
| `timeout_minutes` | Use GitHub Actions `timeout-minutes` | Configure at job level instead of input level | | `timeout_minutes` | Use GitHub Actions `timeout-minutes` | Configure at job level instead of input level |
## Migration Examples ## Migration Examples
@ -52,7 +52,7 @@ The following inputs have been deprecated and replaced:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
claude_args: | claude_args: |
--max-turns 10 --max-turns 10
--append-system-prompt "Follow our coding standards" --system-prompt "Follow our coding standards"
--allowedTools Edit,Read,Write --allowedTools Edit,Read,Write
``` ```
@ -255,15 +255,14 @@ claude_args: |
### Common claude_args Options ### Common claude_args Options
| Option | Description | Example | | Option | Description | Example |
| ------------------------ | ------------------------------------------------------------------------- | ------------------------------------------------------ | | ------------------- | ------------------------ | -------------------------------------- |
| `--max-turns` | Limit conversation turns | `--max-turns 10` | | `--max-turns` | Limit conversation turns | `--max-turns 10` |
| `--model` | Specify Claude model | `--model claude-4-0-sonnet-20250805` | | `--model` | Specify Claude model | `--model claude-4-0-sonnet-20250805` |
| `--allowedTools` | Enable specific tools | `--allowedTools Edit,Read,Write` | | `--allowedTools` | Enable specific tools | `--allowedTools Edit,Read,Write` |
| `--disallowedTools` | Disable specific tools | `--disallowedTools WebSearch` | | `--disallowedTools` | Disable specific tools | `--disallowedTools WebSearch` |
| `--system-prompt` | Replace the entire default system prompt | `--system-prompt "Focus on security"` | | `--system-prompt` | Add system instructions | `--system-prompt "Focus on security"` |
| `--append-system-prompt` | Append to the default system prompt (keeps Claude Code's built-in prompt) | `--append-system-prompt "Follow our coding standards"` | | `--mcp-config` | Add MCP server config | `--mcp-config '{"mcpServers": {...}}'` |
| `--mcp-config` | Add MCP server config | `--mcp-config '{"mcpServers": {...}}'` |
## Provider-Specific Updates ## Provider-Specific Updates
@ -331,7 +330,7 @@ You can also pass MCP configuration from a file:
- [ ] Remove `mode` input (auto-detected now) - [ ] Remove `mode` input (auto-detected now)
- [ ] Replace `direct_prompt` with `prompt` - [ ] Replace `direct_prompt` with `prompt`
- [ ] Replace `override_prompt` with `prompt` using GitHub context - [ ] Replace `override_prompt` with `prompt` using GitHub context
- [ ] Move `custom_instructions` to `claude_args` with `--append-system-prompt` - [ ] Move `custom_instructions` to `claude_args` with `--system-prompt`
- [ ] Convert `max_turns` to `claude_args` with `--max-turns` - [ ] Convert `max_turns` to `claude_args` with `--max-turns`
- [ ] Convert `model` to `claude_args` with `--model` - [ ] Convert `model` to `claude_args` with `--model`
- [ ] Convert `allowed_tools` to `claude_args` with `--allowedTools` - [ ] Convert `allowed_tools` to `claude_args` with `--allowedTools`

View File

@ -10,52 +10,6 @@
- Or `CLAUDE_CODE_OAUTH_TOKEN` for OAuth token authentication (Pro and Max users can generate this by running `claude setup-token` locally) - Or `CLAUDE_CODE_OAUTH_TOKEN` for OAuth token authentication (Pro and Max users can generate this by running `claude setup-token` locally)
3. Copy the workflow file from [`examples/claude.yml`](../examples/claude.yml) into your repository's `.github/workflows/` 3. Copy the workflow file from [`examples/claude.yml`](../examples/claude.yml) into your repository's `.github/workflows/`
> Don't want to store a static API key at all? See [Workload Identity Federation](#workload-identity-federation) below.
## Workload Identity Federation
Workload Identity Federation (WIF) lets the action authenticate to the Claude API by exchanging the workflow's GitHub Actions OIDC token for a short-lived Anthropic access token — no `ANTHROPIC_API_KEY` secret to create, store, or rotate.
### One-time setup in the Claude Console
You need admin access to your Anthropic organization (Console → **Settings → Workload identity**):
1. **Register an issuer** for GitHub Actions with issuer URL `https://token.actions.githubusercontent.com` (JWKS source: `discovery`).
2. **Create a service account** (Settings → Service accounts) and add it to the workspace it should act in. Note the `svac_...` ID.
3. **Create a federation rule** targeting that service account, matched to your repository's OIDC claims (for example a subject prefix of `repo:your-org/your-repo:`). Note the `fdrl_...` rule ID.
See the [Workload Identity Federation documentation](https://platform.claude.com/docs/en/manage-claude/workload-identity-federation) for full details.
### Workflow configuration
```yaml
jobs:
claude-response:
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
issues: write
id-token: write # required: used to fetch the GitHub OIDC token
steps:
- uses: anthropics/claude-code-action@v1
with:
anthropic_federation_rule_id: fdrl_xxxxxxxxxxxx
anthropic_organization_id: 00000000-0000-0000-0000-000000000000
anthropic_service_account_id: svac_xxxxxxxxxxxx
# Optional when the federation rule targets a single workspace:
anthropic_workspace_id: wrkspc_xxxxxxxxxxxx
```
These values are identifiers, not credentials, so they can live directly in the workflow file (or in repository variables).
Notes:
- The workflow must grant `id-token: write` permission so the action can fetch a GitHub OIDC token. The default GitHub App authentication path already requires this permission.
- Do not set `anthropic_api_key` or `claude_code_oauth_token` alongside the federation inputs — a static credential takes precedence and federation will not be used.
- The GitHub OIDC token is requested with audience `https://api.anthropic.com` by default, so set the federation rule's expected audience to that value (or leave the rule's audience unmatched). Use `anthropic_oidc_audience` only if your rule expects a different audience.
- Inline comment classification (`classify_inline_comments`) currently requires `anthropic_api_key`; with federation it is skipped and unconfirmed inline comments are posted directly.
## Using a Custom GitHub App ## Using a Custom GitHub App
If you prefer not to install the official Claude app, you can create your own GitHub App to use with this action. This gives you complete control over permissions and access. If you prefer not to install the official Claude app, you can create your own GitHub App to use with this action. This gives you complete control over permissions and access.

View File

@ -52,43 +52,38 @@ jobs:
## Inputs ## Inputs
| Input | Description | Required | Default | | Input | Description | Required | Default |
| -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | --------------------------- | | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | ------------- |
| `anthropic_api_key` | Anthropic API key (required for direct API, not needed for Bedrock/Vertex) | No\* | - | | `anthropic_api_key` | Anthropic API key (required for direct API, not needed for Bedrock/Vertex) | No\* | - |
| `claude_code_oauth_token` | Claude Code OAuth token (alternative to anthropic_api_key) | No\* | - | | `claude_code_oauth_token` | Claude Code OAuth token (alternative to anthropic_api_key) | No\* | - |
| `anthropic_federation_rule_id` | Workload identity federation rule ID (`fdrl_...`). With `anthropic_organization_id`, authenticates via the workflow's GitHub OIDC token instead of a static API key. See [Setup Guide](./setup.md#workload-identity-federation) | No\* | - | | `prompt` | Instructions for Claude. Can be a direct prompt or custom template for automation workflows | No | - |
| `anthropic_organization_id` | Anthropic organization UUID for workload identity federation | No\* | - | | `track_progress` | Force tag mode with tracking comments. Only works with specific PR/issue events. Preserves GitHub context | No | `false` |
| `anthropic_service_account_id` | Service account ID (`svac_...`) the federated token acts as (optional) | No | - | | `include_fix_links` | Include 'Fix this' links in PR code review feedback that open Claude Code with context to fix the identified issue | No | `true` |
| `anthropic_workspace_id` | Workspace ID (`wrkspc_...`) for workload identity federation. Optional when the federation rule targets a single workspace | No | - | | `claude_args` | Additional [arguments to pass directly to Claude CLI](https://docs.claude.com/en/docs/claude-code/cli-reference#cli-flags) (e.g., `--max-turns 10 --model claude-4-0-sonnet-20250805`) | No | "" |
| `anthropic_oidc_audience` | Audience requested on the GitHub OIDC token used for workload identity federation | No | `https://api.anthropic.com` | | `base_branch` | The base branch to use for creating new branches (e.g., 'main', 'develop') | No | - |
| `prompt` | Instructions for Claude. Can be a direct prompt or custom template for automation workflows | No | - | | `use_sticky_comment` | Use just one comment to deliver PR comments (only applies for pull_request event workflows) | No | `false` |
| `track_progress` | Force tag mode with tracking comments. Only works with specific PR/issue events. Preserves GitHub context | No | `false` | | `classify_inline_comments` | Buffer inline comments without `confirmed: true` and classify them (real review vs test/probe) via Haiku before posting after the session ends. Prevents subagent test comments. Set `'false'` to post all inline comments immediately | No | `true` |
| `include_fix_links` | Include 'Fix this' links in PR code review feedback that open Claude Code with context to fix the identified issue | No | `true` | | `github_token` | GitHub token for Claude to operate with. **Only include this if you're connecting a custom GitHub app of your own!** | No | - |
| `claude_args` | Additional [arguments to pass directly to Claude CLI](https://docs.claude.com/en/docs/claude-code/cli-reference#cli-flags) (e.g., `--max-turns 10 --model claude-4-0-sonnet-20250805`) | No | "" | | `use_bedrock` | Use Amazon Bedrock with OIDC authentication instead of direct Anthropic API | No | `false` |
| `base_branch` | The base branch to use for creating new branches (e.g., 'main', 'develop') | No | - | | `use_vertex` | Use Google Vertex AI with OIDC authentication instead of direct Anthropic API | No | `false` |
| `use_sticky_comment` | Use just one comment to deliver PR comments (only applies for pull_request event workflows) | No | `false` | | `assignee_trigger` | The assignee username that triggers the action (e.g. @claude). Only used for issue assignment | No | - |
| `classify_inline_comments` | Buffer inline comments without `confirmed: true` and classify them (real review vs test/probe) via Haiku before posting after the session ends. Prevents subagent test comments. Set `'false'` to post all inline comments immediately | No | `true` | | `label_trigger` | The label name that triggers the action when applied to an issue (e.g. "claude") | No | - |
| `github_token` | GitHub token for Claude to operate with. **Only include this if you're connecting a custom GitHub app of your own!** | No | - | | `trigger_phrase` | The trigger phrase to look for in comments, issue/PR bodies, and issue titles | No | `@claude` |
| `use_bedrock` | Use Amazon Bedrock with OIDC authentication instead of direct Anthropic API | No | `false` | | `branch_prefix` | The prefix to use for Claude branches (defaults to 'claude/', use 'claude-' for dash format) | No | `claude/` |
| `use_vertex` | Use Google Vertex AI with OIDC authentication instead of direct Anthropic API | No | `false` | | `settings` | Claude Code settings as JSON string or path to settings JSON file | No | "" |
| `assignee_trigger` | The assignee username that triggers the action (e.g. @claude). Only used for issue assignment | No | - | | `additional_permissions` | Additional permissions to enable. Currently supports 'actions: read' for viewing workflow results | No | "" |
| `label_trigger` | The label name that triggers the action when applied to an issue (e.g. "claude") | No | - | | `use_commit_signing` | Enable commit signing using GitHub's API. Simple but cannot perform complex git operations like rebasing. See [Security](./security.md#commit-signing) | No | `false` |
| `trigger_phrase` | The trigger phrase to look for in comments, issue/PR bodies, and issue titles | No | `@claude` | | `ssh_signing_key` | SSH private key for signing commits. Enables signed commits with full git CLI support (rebasing, etc.). See [Security](./security.md#commit-signing) | No | "" |
| `branch_prefix` | The prefix to use for Claude branches (defaults to 'claude/', use 'claude-' for dash format) | No | `claude/` | | `bot_id` | GitHub user ID to use for git operations (defaults to Claude's bot ID). Required with `ssh_signing_key` for verified commits | No | `41898282` |
| `settings` | Claude Code settings as JSON string or path to settings JSON file | No | "" | | `bot_name` | GitHub username to use for git operations (defaults to Claude's bot name). Required with `ssh_signing_key` for verified commits | No | `claude[bot]` |
| `additional_permissions` | Additional permissions to enable. Currently supports 'actions: read' for viewing workflow results | No | "" | | `include_comments_by_actor` | Comma-separated list of actor usernames to INCLUDE in comments. Supports the `*[bot]` wildcard to match all bot accounts. Empty (default) includes all actors | No | "" |
| `use_commit_signing` | Enable commit signing using GitHub's API. Simple but cannot perform complex git operations like rebasing. See [Security](./security.md#commit-signing) | No | `false` | | `exclude_comments_by_actor` | Comma-separated list of actor usernames to EXCLUDE from comments. Supports the `*[bot]` wildcard to match all bot accounts. If an actor matches both lists, exclusion takes priority | No | "" |
| `ssh_signing_key` | SSH private key for signing commits. Enables signed commits with full git CLI support (rebasing, etc.). See [Security](./security.md#commit-signing) | No | "" | | `allowed_bots` | Comma-separated list of allowed bot usernames, or '\*' to allow all bots. Empty string (default) allows no bots. **⚠️ On public repos with `'*'`, external Apps may be able to invoke this action.** See [Security](./security.md) | No | "" |
| `bot_id` | GitHub user ID to use for git operations (defaults to Claude's bot ID). Required with `ssh_signing_key` for verified commits | No | `41898282` | | `allowed_non_write_users` | **⚠️ RISKY**: Comma-separated list of usernames to allow without write permissions, or '\*' for all users. Only works with `github_token` input. See [Security](./security.md) | No | "" |
| `bot_name` | GitHub username to use for git operations (defaults to Claude's bot name). Required with `ssh_signing_key` for verified commits | No | `claude[bot]` | | `path_to_claude_code_executable` | Optional path to a custom Claude Code executable. Skips automatic installation. Useful for Nix, custom containers, or specialized environments | No | "" |
| `include_comments_by_actor` | Comma-separated list of actor usernames to INCLUDE in comments. Supports the `*[bot]` wildcard to match all bot accounts. Empty (default) includes all actors | No | "" | | `path_to_bun_executable` | Optional path to a custom Bun executable. Skips automatic Bun installation. Useful for Nix, custom containers, or specialized environments | No | "" |
| `exclude_comments_by_actor` | Comma-separated list of actor usernames to EXCLUDE from comments. Supports the `*[bot]` wildcard to match all bot accounts. If an actor matches both lists, exclusion takes priority | No | "" | | `plugin_marketplaces` | Newline-separated list of Claude Code plugin marketplace Git URLs to install from (e.g., see example in workflow above). Marketplaces are added before plugin installation | No | "" |
| `allowed_bots` | Comma-separated list of allowed bot usernames, or '\*' to allow all bots. Empty string (default) allows no bots. **⚠️ On public repos with `'*'`, external Apps may be able to invoke this action.** See [Security](./security.md) | No | "" | | `plugins` | Newline-separated list of Claude Code plugin names to install (e.g., see example in workflow above). Plugins are installed before Claude Code execution | No | "" |
| `allowed_non_write_users` | **⚠️ RISKY**: Comma-separated list of usernames to allow without write permissions, or '\*' for all users. Only works with `github_token` input. See [Security](./security.md) | No | "" |
| `path_to_claude_code_executable` | Optional path to a custom Claude Code executable. Skips automatic installation. Useful for Nix, custom containers, or specialized environments | No | "" |
| `path_to_bun_executable` | Optional path to a custom Bun executable. Skips automatic Bun installation. Useful for Nix, custom containers, or specialized environments | No | "" |
| `plugin_marketplaces` | Newline-separated list of Claude Code plugin marketplace Git URLs to install from (e.g., see example in workflow above). Marketplaces are added before plugin installation | No | "" |
| `plugins` | Newline-separated list of Claude Code plugin names to install (e.g., see example in workflow above). Plugins are installed before Claude Code execution | No | "" |
### Deprecated Inputs ### Deprecated Inputs
@ -99,7 +94,7 @@ These inputs are deprecated and will be removed in a future version:
| `mode` | **DEPRECATED**: Mode is now automatically detected based on workflow context | Remove this input; the action auto-detects the correct mode | | `mode` | **DEPRECATED**: Mode is now automatically detected based on workflow context | Remove this input; the action auto-detects the correct mode |
| `direct_prompt` | **DEPRECATED**: Use `prompt` instead | Replace with `prompt` | | `direct_prompt` | **DEPRECATED**: Use `prompt` instead | Replace with `prompt` |
| `override_prompt` | **DEPRECATED**: Use `prompt` with template variables or `claude_args` with `--system-prompt` | Use `prompt` for templates or `claude_args` for system prompts | | `override_prompt` | **DEPRECATED**: Use `prompt` with template variables or `claude_args` with `--system-prompt` | Use `prompt` for templates or `claude_args` for system prompts |
| `custom_instructions` | **DEPRECATED**: Use `claude_args` with `--append-system-prompt` or include in `prompt` | Move instructions to `prompt` or use `claude_args` | | `custom_instructions` | **DEPRECATED**: Use `claude_args` with `--system-prompt` or include in `prompt` | Move instructions to `prompt` or use `claude_args` |
| `max_turns` | **DEPRECATED**: Use `claude_args` with `--max-turns` instead | Use `claude_args: "--max-turns 5"` | | `max_turns` | **DEPRECATED**: Use `claude_args` with `--max-turns` instead | Use `claude_args: "--max-turns 5"` |
| `model` | **DEPRECATED**: Use `claude_args` with `--model` instead | Use `claude_args: "--model claude-4-0-sonnet-20250805"` | | `model` | **DEPRECATED**: Use `claude_args` with `--model` instead | Use `claude_args: "--model claude-4-0-sonnet-20250805"` |
| `fallback_model` | **DEPRECATED**: Use `claude_args` with fallback configuration | Configure fallback in `claude_args` or `settings` | | `fallback_model` | **DEPRECATED**: Use `claude_args` with fallback configuration | Configure fallback in `claude_args` or `settings` |
@ -139,7 +134,7 @@ For a comprehensive guide on migrating from v0.x to v1.0, including step-by-step
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
claude_args: | claude_args: |
--max-turns 10 --max-turns 10
--append-system-prompt "Focus on security" --system-prompt "Focus on security"
``` ```
#### Automation Workflows #### Automation Workflows

View File

@ -1,39 +0,0 @@
# Require human approvals on PRs that contain agent-authored commits.
#
# Both triggers run the workflow file from the BASE/DEFAULT branch, so a PR
# cannot edit this check to approve itself. (`pull_request_review` is not
# used because it runs from the merge ref, not the default branch; native
# Approve reviews are picked up on the next synchronize or `/approve`
# comment.)
#
# After adding this workflow, mark `agent-approval-check` as a required
# status check on your protected branches.
name: agent-approval-check
on:
pull_request_target:
types: [opened, synchronize, reopened, ready_for_review]
issue_comment:
types: [created]
permissions:
contents: read
pull-requests: write
statuses: write
jobs:
check:
# issue_comment also fires on plain issues; skip those early.
if: github.event_name != 'issue_comment' || github.event.issue.pull_request
runs-on: ubuntu-latest
steps:
- uses: anthropics/claude-code-action/agent-approval-check@main
with:
required_approvals: 2
agent_emails: noreply@anthropic.com
agent_logins: claude[bot],claude-code[bot]
# Uncomment to tune:
# excluded_approvers: dependabot[bot]
# exempt_path_prefixes: docs/
# protected_bases: main,release

View File

@ -1,56 +0,0 @@
name: Claude Code (Workload Identity Federation)
# Authenticates to the Claude API by exchanging the workflow's GitHub OIDC
# token for a short-lived access token — no ANTHROPIC_API_KEY secret needed.
# One-time Console setup (issuer, service account, federation rule):
# https://platform.claude.com/docs/en/manage-claude/workload-identity-federation
# See also docs/setup.md#workload-identity-federation in this repository.
on:
issue_comment:
types: [created]
pull_request_review_comment:
types: [created]
issues:
types: [opened, assigned]
pull_request_review:
types: [submitted]
jobs:
claude:
if: |
(github.event_name == 'issue_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
issues: write
id-token: write # Required: used to fetch the GitHub OIDC token for the federation exchange
actions: read # Required for Claude to read CI results on PRs
steps:
- name: Checkout repository
uses: actions/checkout@v6
with:
fetch-depth: 1
- name: Run Claude Code
id: claude
uses: anthropics/claude-code-action@v1
with:
# These values are identifiers, not secrets — they can live directly
# in the workflow file or in repository variables.
anthropic_federation_rule_id: fdrl_xxxxxxxxxxxx
anthropic_organization_id: 00000000-0000-0000-0000-000000000000
anthropic_service_account_id: svac_xxxxxxxxxxxx
# Optional: only needed when the federation rule targets more than
# one workspace.
# anthropic_workspace_id: wrkspc_xxxxxxxxxxxx
# Optional: audience requested on the GitHub OIDC token. Defaults to
# https://api.anthropic.com — only set this if your federation rule
# expects a different audience.
# anthropic_oidc_audience: https://example.com/custom-audience

View File

@ -12,7 +12,7 @@
"dependencies": { "dependencies": {
"@actions/core": "^1.10.1", "@actions/core": "^1.10.1",
"@actions/github": "^6.0.1", "@actions/github": "^6.0.1",
"@anthropic-ai/claude-agent-sdk": "^0.3.220", "@anthropic-ai/claude-agent-sdk": "^0.3.147",
"@modelcontextprotocol/sdk": "^1.11.0", "@modelcontextprotocol/sdk": "^1.11.0",
"@octokit/graphql": "^8.2.2", "@octokit/graphql": "^8.2.2",
"@octokit/rest": "^21.1.1", "@octokit/rest": "^21.1.1",

View File

@ -1,7 +1,7 @@
#!/usr/bin/env bun #!/usr/bin/env bun
import * as core from "@actions/core"; import * as core from "@actions/core";
import { writeFile, mkdir, rm } from "fs/promises"; import { writeFile, mkdir } from "fs/promises";
import type { FetchDataResult } from "../github/data/fetcher"; import type { FetchDataResult } from "../github/data/fetcher";
import { import {
formatContext, formatContext,
@ -122,7 +122,6 @@ export function prepareContext(
// Extract trigger username and comment data based on event type // Extract trigger username and comment data based on event type
let triggerUsername: string | undefined; let triggerUsername: string | undefined;
let triggerUserId: number | undefined;
let commentId: string | undefined; let commentId: string | undefined;
let commentBody: string | undefined; let commentBody: string | undefined;
@ -130,19 +129,15 @@ export function prepareContext(
commentId = context.payload.comment.id.toString(); commentId = context.payload.comment.id.toString();
commentBody = context.payload.comment.body; commentBody = context.payload.comment.body;
triggerUsername = context.payload.comment.user.login; triggerUsername = context.payload.comment.user.login;
triggerUserId = context.payload.comment.user.id;
} else if (isPullRequestReviewEvent(context)) { } else if (isPullRequestReviewEvent(context)) {
commentBody = context.payload.review.body ?? ""; commentBody = context.payload.review.body ?? "";
triggerUsername = context.payload.review.user.login; triggerUsername = context.payload.review.user.login;
triggerUserId = context.payload.review.user.id;
} else if (isPullRequestReviewCommentEvent(context)) { } else if (isPullRequestReviewCommentEvent(context)) {
commentId = context.payload.comment.id.toString(); commentId = context.payload.comment.id.toString();
commentBody = context.payload.comment.body; commentBody = context.payload.comment.body;
triggerUsername = context.payload.comment.user.login; triggerUsername = context.payload.comment.user.login;
triggerUserId = context.payload.comment.user.id;
} else if (isIssuesEvent(context)) { } else if (isIssuesEvent(context)) {
triggerUsername = context.payload.issue.user.login; triggerUsername = context.payload.issue.user.login;
triggerUserId = context.payload.issue.user.id;
} }
// Create infrastructure fields object // Create infrastructure fields object
@ -151,7 +146,6 @@ export function prepareContext(
claudeCommentId, claudeCommentId,
triggerPhrase, triggerPhrase,
...(triggerUsername && { triggerUsername }), ...(triggerUsername && { triggerUsername }),
...(triggerUserId && { triggerUserId }),
...(prompt && { prompt }), ...(prompt && { prompt }),
...(claudeBranch && { claudeBranch }), ...(claudeBranch && { claudeBranch }),
}; };
@ -400,16 +394,9 @@ function getCommitInstructions(
context: PreparedContext, context: PreparedContext,
useCommitSigning: boolean, useCommitSigning: boolean,
): string { ): string {
const triggerName = githubData.triggerDisplayName ?? context.triggerUsername;
const triggerEmail =
context.triggerUserId && context.triggerUsername
? `${context.triggerUserId}+${context.triggerUsername}@users.noreply.github.com`
: context.triggerUsername
? `${context.triggerUsername}@users.noreply.github.com`
: undefined;
const coAuthorLine = const coAuthorLine =
triggerName && triggerName !== "Unknown" && triggerEmail (githubData.triggerDisplayName ?? context.triggerUsername) !== "Unknown"
? `Co-authored-by: ${triggerName} <${triggerEmail}>` ? `Co-authored-by: ${githubData.triggerDisplayName ?? context.triggerUsername} <${context.triggerUsername}@users.noreply.github.com>`
: ""; : "";
if (useCommitSigning) { if (useCommitSigning) {
@ -943,14 +930,9 @@ export async function createPrompt(
claudeBranch, claudeBranch,
); );
// Clear any stale prompt files from a prior invocation. RUNNER_TEMP is documented await mkdir(`${process.env.RUNNER_TEMP || "/tmp"}/claude-prompts`, {
// to be emptied between jobs, but on non-ephemeral self-hosted runners this is recursive: true,
// not reliably honored — a stale claude-user-request.txt left behind by a prior });
// mention-mode invocation would not be overwritten by a subsequent agent-mode
// invocation, and would leak into the model's context.
const promptDir = `${process.env.RUNNER_TEMP || "/tmp"}/claude-prompts`;
await rm(promptDir, { recursive: true, force: true });
await mkdir(promptDir, { recursive: true });
// Generate the prompt directly // Generate the prompt directly
const promptContent = generatePrompt( const promptContent = generatePrompt(
@ -966,7 +948,10 @@ export async function createPrompt(
console.log("======================="); console.log("=======================");
// Write the prompt file // Write the prompt file
await writeFile(`${promptDir}/claude-prompt.txt`, promptContent); await writeFile(
`${process.env.RUNNER_TEMP || "/tmp"}/claude-prompts/claude-prompt.txt`,
promptContent,
);
// Extract and write the user request separately for SDK multi-block messaging // Extract and write the user request separately for SDK multi-block messaging
// This allows the CLI to process slash commands (e.g., "@claude /review-pr") // This allows the CLI to process slash commands (e.g., "@claude /review-pr")
@ -975,7 +960,10 @@ export async function createPrompt(
githubData, githubData,
); );
if (userRequest) { if (userRequest) {
await writeFile(`${promptDir}/${USER_REQUEST_FILENAME}`, userRequest); await writeFile(
`${process.env.RUNNER_TEMP || "/tmp"}/claude-prompts/${USER_REQUEST_FILENAME}`,
userRequest,
);
console.log("===== USER REQUEST ====="); console.log("===== USER REQUEST =====");
console.log(userRequest); console.log(userRequest);
console.log("========================"); console.log("========================");

View File

@ -5,7 +5,6 @@ export type CommonFields = {
claudeCommentId: string; claudeCommentId: string;
triggerPhrase: string; triggerPhrase: string;
triggerUsername?: string; triggerUsername?: string;
triggerUserId?: number;
prompt?: string; prompt?: string;
claudeBranch?: string; claudeBranch?: string;
}; };

View File

@ -20,11 +20,6 @@ export function collectActionInputsPresence(): string {
settings: "", settings: "",
anthropic_api_key: "", anthropic_api_key: "",
claude_code_oauth_token: "", claude_code_oauth_token: "",
anthropic_federation_rule_id: "",
anthropic_organization_id: "",
anthropic_service_account_id: "",
anthropic_workspace_id: "",
anthropic_oidc_audience: "",
github_token: "", github_token: "",
max_turns: "", max_turns: "",
use_sticky_comment: "false", use_sticky_comment: "false",

3
src/entrypoints/format-turns.ts Normal file → Executable file
View File

@ -268,8 +268,7 @@ export function groupTurnsNaturally(data: Turn[]): GroupedContent[] {
type: "system_init", type: "system_init",
tools_count: tools.length, tools_count: tools.length,
}); });
} else if (subtype !== "thinking_tokens") { } else {
// Skip thinking_tokens - internal progress events not meant for summary
groupedContent.push({ groupedContent.push({
type: "system_other", type: "system_other",
data: turn, data: turn,

View File

@ -34,8 +34,6 @@ import { updateCommentLink } from "./update-comment-link";
import { formatTurnsFromData } from "./format-turns"; import { formatTurnsFromData } from "./format-turns";
import type { Turn } from "./format-turns"; import type { Turn } from "./format-turns";
// Base-action imports (used directly instead of subprocess) // Base-action imports (used directly instead of subprocess)
import { setupWorkloadIdentity } from "../../base-action/src/workload-identity";
import type { WorkloadIdentityHandle } from "../../base-action/src/workload-identity";
import { validateEnvironmentVariables } from "../../base-action/src/validate-env"; import { validateEnvironmentVariables } from "../../base-action/src/validate-env";
import { setupClaudeCodeSettings } from "../../base-action/src/setup-claude-code-settings"; import { setupClaudeCodeSettings } from "../../base-action/src/setup-claude-code-settings";
import { installPlugins } from "../../base-action/src/install-plugins"; import { installPlugins } from "../../base-action/src/install-plugins";
@ -44,13 +42,6 @@ import { runClaude } from "../../base-action/src/run-claude";
import type { ClaudeRunResult } from "../../base-action/src/run-claude-sdk"; import type { ClaudeRunResult } from "../../base-action/src/run-claude-sdk";
import { setExecutionFileOutputIfPresent } from "../../base-action/src/execution-file"; import { setExecutionFileOutputIfPresent } from "../../base-action/src/execution-file";
// Exported for unit testing. `set -o pipefail` makes curl's non-zero exit
// propagate through the pipe so the install retry logic actually triggers
// on 429/403 instead of silently succeeding (see #1136).
export function buildInstallCommand(version: string): string {
return `set -o pipefail; curl -fsSL https://claude.ai/install.sh | bash -s -- ${version}`;
}
/** /**
* Install Claude Code CLI, handling retry logic and custom executable paths. * Install Claude Code CLI, handling retry logic and custom executable paths.
* Returns the absolute path to the claude executable. * Returns the absolute path to the claude executable.
@ -75,7 +66,7 @@ async function installClaudeCode(): Promise<string> {
return customExecutable; return customExecutable;
} }
const claudeCodeVersion = "2.1.220"; const claudeCodeVersion = "2.1.147";
console.log(`Installing Claude Code v${claudeCodeVersion}...`); console.log(`Installing Claude Code v${claudeCodeVersion}...`);
for (let attempt = 1; attempt <= 3; attempt++) { for (let attempt = 1; attempt <= 3; attempt++) {
@ -84,7 +75,10 @@ async function installClaudeCode(): Promise<string> {
await new Promise<void>((resolve, reject) => { await new Promise<void>((resolve, reject) => {
const child = spawn( const child = spawn(
"bash", "bash",
["-c", buildInstallCommand(claudeCodeVersion)], [
"-c",
`curl -fsSL https://claude.ai/install.sh | bash -s -- ${claudeCodeVersion}`,
],
{ stdio: "inherit" }, { stdio: "inherit" },
); );
child.on("close", (code) => { child.on("close", (code) => {
@ -156,7 +150,6 @@ async function run() {
let prepareError: string | undefined; let prepareError: string | undefined;
let context: GitHubContext | undefined; let context: GitHubContext | undefined;
let octokit: Octokits | undefined; let octokit: Octokits | undefined;
let workloadIdentity: WorkloadIdentityHandle | undefined;
// Track whether we've completed prepare phase, so we can attribute errors correctly // Track whether we've completed prepare phase, so we can attribute errors correctly
let prepareCompleted = false; let prepareCompleted = false;
try { try {
@ -238,10 +231,6 @@ async function run() {
process.env.CLAUDE_CODE_ACTION = "1"; process.env.CLAUDE_CODE_ACTION = "1";
process.env.DETAILED_PERMISSION_MESSAGES = "1"; process.env.DETAILED_PERMISSION_MESSAGES = "1";
// When workload identity federation is configured, fetch the GitHub OIDC
// identity token and expose it to the CLI before validating auth env vars.
workloadIdentity = await setupWorkloadIdentity();
validateEnvironmentVariables(); validateEnvironmentVariables();
// On PRs, .claude/ and .mcp.json in the checkout are attacker-controlled. // On PRs, .claude/ and .mcp.json in the checkout are attacker-controlled.
@ -318,10 +307,6 @@ async function run() {
} finally { } finally {
// Phase 4: Cleanup (always runs) // Phase 4: Cleanup (always runs)
// Stop refreshing the workload identity token file and delete the token
// material so it doesn't outlive this step
workloadIdentity?.stop();
// Update tracking comment // Update tracking comment
if ( if (
commentId && commentId &&

View File

@ -25,7 +25,7 @@ export const PR_QUERY = `
additions additions
deletions deletions
state state
labels(first: 100) { labels(first: 1) {
nodes { nodes {
name name
} }
@ -113,7 +113,7 @@ export const ISSUE_QUERY = `
updatedAt updatedAt
lastEditedAt lastEditedAt
state state
labels(first: 100) { labels(first: 1) {
nodes { nodes {
name name
} }

View File

@ -204,9 +204,11 @@ export function isBodySafeToUse(
* @param excludeActors - Comma-separated actors to exclude * @param excludeActors - Comma-separated actors to exclude
* @returns Filtered array of comments * @returns Filtered array of comments
*/ */
export function filterCommentsByActor< export function filterCommentsByActor<T extends { author: { login: string } }>(
T extends { author: { login: string } | null }, comments: T[],
>(comments: T[], includeActors: string = "", excludeActors: string = ""): T[] { includeActors: string = "",
excludeActors: string = "",
): T[] {
const includeParsed = parseActorFilter(includeActors); const includeParsed = parseActorFilter(includeActors);
const excludeParsed = parseActorFilter(excludeActors); const excludeParsed = parseActorFilter(excludeActors);
@ -217,9 +219,7 @@ export function filterCommentsByActor<
return comments.filter((comment) => return comments.filter((comment) =>
shouldIncludeCommentByActor( shouldIncludeCommentByActor(
// author is null for comments from deleted ("ghost") accounts; treat them comment.author.login,
// as the "ghost" login so filtering never dereferences null and crashes.
comment.author?.login ?? "ghost",
includeParsed, includeParsed,
excludeParsed, excludeParsed,
), ),
@ -378,26 +378,34 @@ export async function fetchGitHubData({
body: c.body, body: c.body,
})); }));
// Filter reviews and inline review comments to trigger time and by actor // Filter review bodies to trigger time
// before building anything from them. The trigger-time filter is the TOCTOU const filteredReviewBodies = reviewData?.nodes
// protection applied to issue/PR comments and the body above: it drops ? filterReviewsToTriggerTime(reviewData.nodes, triggerTime).filter(
// anything submitted, created, or edited at/after the trigger so an attacker (r) => r.body,
// cannot inject content into the prompt after an authorized trigger. Without )
// it, review bodies and inline review comments would reach the prompt : [];
// verbatim regardless of when they landed.
const reviewBodies: CommentWithImages[] = filteredReviewBodies.map((r) => ({
type: "review_body" as const,
id: r.databaseId,
pullNumber: prNumber,
body: r.body,
}));
// Filter review comments to trigger time and by actor
if (reviewData && reviewData.nodes) { if (reviewData && reviewData.nodes) {
// Drop reviews submitted or edited after the trigger, then filter by actor. // Filter reviews by actor
reviewData.nodes = filterCommentsByActor( reviewData.nodes = filterCommentsByActor(
filterReviewsToTriggerTime(reviewData.nodes, triggerTime), reviewData.nodes,
includeCommentsByActor, includeCommentsByActor,
excludeCommentsByActor, excludeCommentsByActor,
); );
// Apply the same trigger-time + actor filtering to inline review comments. // Also filter inline review comments within each review
reviewData.nodes.forEach((review) => { reviewData.nodes.forEach((review) => {
if (review.comments?.nodes) { if (review.comments?.nodes) {
review.comments.nodes = filterCommentsByActor( review.comments.nodes = filterCommentsByActor(
filterCommentsToTriggerTime(review.comments.nodes, triggerTime), review.comments.nodes,
includeCommentsByActor, includeCommentsByActor,
excludeCommentsByActor, excludeCommentsByActor,
); );
@ -405,19 +413,14 @@ export async function fetchGitHubData({
}); });
} }
// Build the image-processing lists from the already-filtered review nodes, const allReviewComments =
// so reviews/comments excluded from the prompt are not processed for images. reviewData?.nodes?.flatMap((r) => r.comments?.nodes ?? []) ?? [];
const reviewBodies: CommentWithImages[] = (reviewData?.nodes ?? []) const filteredReviewComments = filterCommentsToTriggerTime(
.filter((r) => r.body) allReviewComments,
.map((r) => ({ triggerTime,
type: "review_body" as const, );
id: r.databaseId,
pullNumber: prNumber,
body: r.body,
}));
const reviewComments: CommentWithImages[] = (reviewData?.nodes ?? []) const reviewComments: CommentWithImages[] = filteredReviewComments
.flatMap((r) => r.comments?.nodes ?? [])
.filter((c) => c.body && !c.isMinimized) .filter((c) => c.body && !c.isMinimized)
.map((c) => ({ .map((c) => ({
type: "review_comment" as const, type: "review_comment" as const,

View File

@ -8,11 +8,6 @@ import type {
import type { GitHubFileWithSHA } from "./fetcher"; import type { GitHubFileWithSHA } from "./fetcher";
import { sanitizeContent } from "../utils/sanitizer"; import { sanitizeContent } from "../utils/sanitizer";
function formatLabels(labelNodes: Array<{ name: string }>): string {
if (labelNodes.length === 0) return "none";
return labelNodes.map((l) => l.name).join(", ");
}
export function formatContext( export function formatContext(
contextData: GitHubPullRequest | GitHubIssue, contextData: GitHubPullRequest | GitHubIssue,
isPR: boolean, isPR: boolean,
@ -21,10 +16,9 @@ export function formatContext(
const prData = contextData as GitHubPullRequest; const prData = contextData as GitHubPullRequest;
const sanitizedTitle = sanitizeContent(prData.title); const sanitizedTitle = sanitizeContent(prData.title);
return `PR Title: ${sanitizedTitle} return `PR Title: ${sanitizedTitle}
PR Author: ${prData.author?.login ?? "ghost"} PR Author: ${prData.author.login}
PR Branch: ${prData.headRefName} -> ${prData.baseRefName} PR Branch: ${prData.headRefName} -> ${prData.baseRefName}
PR State: ${prData.state} PR State: ${prData.state}
PR Labels: ${formatLabels(prData.labels.nodes)}
PR Additions: ${prData.additions} PR Additions: ${prData.additions}
PR Deletions: ${prData.deletions} PR Deletions: ${prData.deletions}
Total Commits: ${prData.commits.totalCount} Total Commits: ${prData.commits.totalCount}
@ -33,9 +27,8 @@ Changed Files: ${prData.files.nodes.length} files`;
const issueData = contextData as GitHubIssue; const issueData = contextData as GitHubIssue;
const sanitizedTitle = sanitizeContent(issueData.title); const sanitizedTitle = sanitizeContent(issueData.title);
return `Issue Title: ${sanitizedTitle} return `Issue Title: ${sanitizedTitle}
Issue Author: ${issueData.author?.login ?? "ghost"} Issue Author: ${issueData.author.login}
Issue State: ${issueData.state} Issue State: ${issueData.state}`;
Issue Labels: ${formatLabels(issueData.labels.nodes)}`;
} }
} }
@ -71,7 +64,7 @@ export function formatComments(
body = sanitizeContent(body); body = sanitizeContent(body);
return `[${comment.author?.login ?? "ghost"} at ${comment.createdAt}]: ${body}`; return `[${comment.author.login} at ${comment.createdAt}]: ${body}`;
}) })
.join("\n\n"); .join("\n\n");
} }
@ -85,7 +78,7 @@ export function formatReviewComments(
} }
const formattedReviews = reviewData.nodes.map((review) => { const formattedReviews = reviewData.nodes.map((review) => {
let reviewOutput = `[Review by ${review.author?.login ?? "ghost"} at ${review.submittedAt}]: ${review.state}`; let reviewOutput = `[Review by ${review.author.login} at ${review.submittedAt}]: ${review.state}`;
if (review.body && review.body.trim()) { if (review.body && review.body.trim()) {
let body = review.body; let body = review.body;

View File

@ -27,15 +27,14 @@ function extractFirstLabel(githubData: FetchDataResult): string | undefined {
* This prevents command injection by ensuring only safe characters are used. * This prevents command injection by ensuring only safe characters are used.
* *
* Valid branch names: * Valid branch names:
* - Start with alphanumeric character, underscore, or @ (not dash, to prevent option injection) * - Start with alphanumeric character (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, or hash (#)
* - Do not start or end with a period * - Do not start or end with a period
* - Do not end with a slash * - Do not end with a slash
* - Do not contain '..' (path traversal) * - Do not contain '..' (path traversal)
* - Do not contain '//' (consecutive slashes) * - Do not contain '//' (consecutive slashes)
* - Do not end with '.lock' * - Do not end with '.lock'
* - Do not contain '@{' * - Do not contain '@{'
* - Are not the single character '@' (HEAD shorthand in git revision syntax)
* - Do not contain control characters or special git characters (~^:?*[\]) * - Do not contain control characters or special git characters (~^:?*[\])
*/ */
export function validateBranchName(branchName: string): void { export function validateBranchName(branchName: string): void {
@ -59,24 +58,18 @@ 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 start, then alphanumeric/slash/hyphen/underscore/period/hash/plus/comma.
// # 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 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 // + 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"). // converting worktree names containing "/" (e.g. "feat/foo" becomes "worktree-feat+foo").
// , is valid per git-check-ref-format and commonly appears in branch names derived from titles // , is valid per git-check-ref-format and commonly appears in branch names derived from titles
// or external identifiers (e.g. place names like "feature/paris,france"). // or external identifiers (e.g. place names like "feature/paris,france").
// @ is valid per git-check-ref-format anywhere in a ref name, including the first character
// (e.g. ticket conventions like "TICKET-123@add-feature" or prefixes like "@hotfix/...");
// the bare name "@" (HEAD shorthand) and the "@{" sequence (reflog syntax) are rejected below.
// _ 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.
// All git calls use execFileSync (not shell interpolation), so none of these characters carry injection risk. // 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)) { if (!validPattern.test(branchName)) {
throw new Error( 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 and contain only alphanumeric characters, forward slashes, hyphens, underscores, periods, hashes (#), plus signs (+), or commas (,).`,
); );
} }
@ -119,15 +112,6 @@ export function validateBranchName(branchName: string): void {
`Invalid branch name: "${branchName}". Branch names cannot contain '@{'`, `Invalid branch name: "${branchName}". Branch names cannot contain '@{'`,
); );
} }
// Per git-check-ref-format, a refname cannot be the single character "@"; "@" also
// resolves to HEAD in git revision syntax, so a bare "@" must never reach git as a
// branch argument where it could be interpreted as a revision instead.
if (branchName === "@") {
throw new Error(
`Invalid branch name: "@". Branch names cannot be the single character '@'.`,
);
}
} }
/** /**

View File

@ -30,21 +30,6 @@ const SENSITIVE_PATHS = [
const CLAUDE_PR_EXCLUDE_PATTERN = "/.claude-pr/"; const CLAUDE_PR_EXCLUDE_PATTERN = "/.claude-pr/";
function snapshotSensitivePath(src: string, dest: string): void {
try {
cpSync(src, dest, { recursive: true, dereference: true });
} catch (error) {
// Symlinks whose targets are absent on the PR head (e.g. `.claude/CLAUDE.md`
// -> `../AGENTS.md` when the PR deleted the target) make dereferenced
// copies throw ENOENT. Preserve the symlink for the review snapshot instead.
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
cpSync(src, dest, { recursive: true });
return;
}
throw error;
}
}
function ensureClaudePrExcludedFromGit(): void { function ensureClaudePrExcludedFromGit(): void {
const excludePath = execFileSync( const excludePath = execFileSync(
"git", "git",
@ -101,7 +86,7 @@ export function restoreConfigFromBase(baseBranch: string): void {
rmSync(".claude-pr", { recursive: true, force: true }); rmSync(".claude-pr", { recursive: true, force: true });
for (const p of SENSITIVE_PATHS) { for (const p of SENSITIVE_PATHS) {
if (existsSync(p)) { if (existsSync(p)) {
snapshotSensitivePath(p, `.claude-pr/${p}`); cpSync(p, `.claude-pr/${p}`, { recursive: true, dereference: true });
} }
} }
if (existsSync(".claude-pr")) { if (existsSync(".claude-pr")) {

View File

@ -10,49 +10,6 @@ export class WorkflowValidationSkipError extends Error {
} }
} }
type AppTokenExchangeErrorResponse = {
error?: {
message?: string;
details?: {
error_code?: string;
};
};
type?: string;
message?: string;
};
const WORKFLOW_VALIDATION_ERROR_CODES = new Set([
"workflow_not_found_on_default_branch",
]);
function getAppTokenExchangeErrorMessage(
responseJson: AppTokenExchangeErrorResponse,
): string {
return responseJson.error?.message ?? responseJson.message ?? "Unknown error";
}
function isWorkflowValidationError(
status: number,
responseJson: AppTokenExchangeErrorResponse,
): boolean {
const errorCode = responseJson.error?.details?.error_code;
if (
errorCode !== undefined &&
WORKFLOW_VALIDATION_ERROR_CODES.has(errorCode)
) {
return true;
}
if (status !== 401) {
return false;
}
const workflowValidationMessage = "workflow validation failed";
return [responseJson.message, responseJson.error?.message].some((message) =>
message?.toLowerCase().includes(workflowValidationMessage),
);
}
async function getOidcToken(): Promise<string> { async function getOidcToken(): Promise<string> {
try { try {
const oidcToken = await core.getIDToken("claude-code-github-action"); const oidcToken = await core.getIDToken("claude-code-github-action");
@ -123,11 +80,25 @@ async function exchangeForAppToken(
); );
if (!response.ok) { if (!response.ok) {
const responseJson = const responseJson = (await response.json()) as {
(await response.json()) as AppTokenExchangeErrorResponse; error?: {
message?: string;
details?: {
error_code?: string;
};
};
type?: string;
message?: string;
};
if (isWorkflowValidationError(response.status, responseJson)) { // Check for specific workflow validation error codes that should skip the action
const message = getAppTokenExchangeErrorMessage(responseJson); const errorCode = responseJson.error?.details?.error_code;
if (errorCode === "workflow_not_found_on_default_branch") {
const message =
responseJson.message ??
responseJson.error?.message ??
"Workflow validation failed";
core.warning(`Skipping action due to workflow validation: ${message}`); core.warning(`Skipping action due to workflow validation: ${message}`);
console.log( console.log(
"Action skipped due to workflow validation error. This is expected when adding Claude Code workflows to new repositories or on PRs with workflow changes. If you're seeing this, your workflow will begin working once you merge your PR.", "Action skipped due to workflow validation error. This is expected when adding Claude Code workflows to new repositories or on PRs with workflow changes. If you're seeing this, your workflow will begin working once you merge your PR.",
@ -135,11 +106,10 @@ async function exchangeForAppToken(
throw new WorkflowValidationSkipError(message); throw new WorkflowValidationSkipError(message);
} }
const message = getAppTokenExchangeErrorMessage(responseJson);
console.error( console.error(
`App token exchange failed: ${response.status} ${response.statusText} - ${message}`, `App token exchange failed: ${response.status} ${response.statusText} - ${responseJson?.error?.message ?? "Unknown error"}`,
); );
throw new Error(message); throw new Error(`${responseJson?.error?.message ?? "Unknown error"}`);
} }
const appTokenData = (await response.json()) as { const appTokenData = (await response.json()) as {

View File

@ -1,8 +1,4 @@
// Types for GitHub GraphQL query responses // Types for GitHub GraphQL query responses
// GitHub's GraphQL `author`/`actor` fields resolve to null when the underlying
// account has been deleted (the "ghost" user). Any field typed as
// `GitHubAuthor | null` can therefore be null at runtime and must be guarded.
export type GitHubAuthor = { export type GitHubAuthor = {
login: string; login: string;
name?: string; name?: string;
@ -12,7 +8,7 @@ export type GitHubComment = {
id: string; id: string;
databaseId: string; databaseId: string;
body: string; body: string;
author: GitHubAuthor | null; author: GitHubAuthor;
createdAt: string; createdAt: string;
updatedAt?: string; updatedAt?: string;
lastEditedAt?: string; lastEditedAt?: string;
@ -43,7 +39,7 @@ export type GitHubFile = {
export type GitHubReview = { export type GitHubReview = {
id: string; id: string;
databaseId: string; databaseId: string;
author: GitHubAuthor | null; author: GitHubAuthor;
body: string; body: string;
state: string; state: string;
submittedAt: string; submittedAt: string;
@ -57,7 +53,7 @@ export type GitHubReview = {
export type GitHubPullRequest = { export type GitHubPullRequest = {
title: string; title: string;
body: string; body: string;
author: GitHubAuthor | null; author: GitHubAuthor;
baseRefName: string; baseRefName: string;
headRefName: string; headRefName: string;
headRefOid: string; headRefOid: string;
@ -99,7 +95,7 @@ export type GitHubPullRequest = {
export type GitHubIssue = { export type GitHubIssue = {
title: string; title: string;
body: string; body: string;
author: GitHubAuthor | null; author: GitHubAuthor;
createdAt: string; createdAt: string;
updatedAt?: string; updatedAt?: string;
lastEditedAt?: string; lastEditedAt?: string;

View File

@ -192,6 +192,10 @@ export async function downloadCommentImages(
continue; continue;
} }
const fileExtension = getImageExtension(originalUrl);
const filename = `image-${Date.now()}-${i}${fileExtension}`;
const localPath = path.join(downloadsDir, filename);
try { try {
console.log(`Downloading ${originalUrl}...`); console.log(`Downloading ${originalUrl}...`);
@ -205,19 +209,6 @@ export async function downloadCommentImages(
const arrayBuffer = await imageResponse.arrayBuffer(); const arrayBuffer = await imageResponse.arrayBuffer();
const buffer = Buffer.from(arrayBuffer); const buffer = Buffer.from(arrayBuffer);
// GitHub user-attachment URLs (/user-attachments/assets/<uuid>) carry
// no file extension, so the URL-based guess silently falls back to
// ".png". When the bytes are actually JPEG/GIF/WebP, the saved file is
// mislabeled and the Read tool sends a base64 image with the wrong
// media_type, which the Anthropic API rejects (400 invalid_request).
// Detect the real type from the magic bytes and only fall back to the
// URL extension when the signature is unrecognized.
const fileExtension =
detectImageExtensionFromBuffer(buffer) ??
getImageExtension(originalUrl);
const filename = `image-${Date.now()}-${i}${fileExtension}`;
const localPath = path.join(downloadsDir, filename);
await fs.writeFile(localPath, buffer); await fs.writeFile(localPath, buffer);
console.log(`✓ Saved: ${localPath}`); console.log(`✓ Saved: ${localPath}`);
@ -253,56 +244,3 @@ function getImageExtension(url: string): string {
const match = filename.match(/\.(png|jpg|jpeg|gif|webp|svg)$/i); const match = filename.match(/\.(png|jpg|jpeg|gif|webp|svg)$/i);
return match ? match[0] : ".png"; return match ? match[0] : ".png";
} }
/**
* Determine an image's file extension from its magic bytes, independent of the
* (often extensionless) source URL. Returns undefined when the signature is not
* a format we can confidently identify, so the caller can fall back to the
* URL-based extension. Covers the raster formats the Anthropic API accepts.
*/
function detectImageExtensionFromBuffer(buffer: Buffer): string | undefined {
// PNG: 89 50 4E 47 0D 0A 1A 0A
if (
buffer.length >= 8 &&
buffer[0] === 0x89 &&
buffer[1] === 0x50 &&
buffer[2] === 0x4e &&
buffer[3] === 0x47
) {
return ".png";
}
// JPEG: FF D8 FF
if (
buffer.length >= 3 &&
buffer[0] === 0xff &&
buffer[1] === 0xd8 &&
buffer[2] === 0xff
) {
return ".jpg";
}
// GIF: "GIF8" (47 49 46 38)
if (
buffer.length >= 6 &&
buffer[0] === 0x47 &&
buffer[1] === 0x49 &&
buffer[2] === 0x46 &&
buffer[3] === 0x38
) {
return ".gif";
}
// WebP: "RIFF" (52 49 46 46) .... "WEBP" (57 45 42 50) at offset 8
if (
buffer.length >= 12 &&
buffer[0] === 0x52 &&
buffer[1] === 0x49 &&
buffer[2] === 0x46 &&
buffer[3] === 0x46 &&
buffer[8] === 0x57 &&
buffer[9] === 0x45 &&
buffer[10] === 0x42 &&
buffer[11] === 0x50
) {
return ".webp";
}
return undefined;
}

View File

@ -10,13 +10,7 @@ export function stripInvisibleCharacters(content: string): string {
} }
export function stripMarkdownImageAltText(content: string): string { export function stripMarkdownImageAltText(content: string): string {
// Inline images: ![alt](url) -> ![](url) return content.replace(/!\[[^\]]*\]\(/g, "![](");
content = content.replace(/!\[[^\]]*\]\(/g, "![](");
// Reference-style images: ![alt][ref] -> ![][ref] (keep the label, drop the
// alt text, which is otherwise a hidden-instruction channel just like the
// inline form above).
content = content.replace(/!\[[^\]]*\](\[[^\]]*\])/g, "![]$1");
return content;
} }
export function stripMarkdownLinkTitles(content: string): string { export function stripMarkdownLinkTitles(content: string): string {
@ -26,23 +20,15 @@ export function stripMarkdownLinkTitles(content: string): string {
} }
export function stripHiddenAttributes(content: string): string { export function stripHiddenAttributes(content: string): string {
// Quoted values are matched per quote type so that a value containing the content = content.replace(/\salt\s*=\s*["'][^"']*["']/gi, "");
// other quote character (e.g. an apostrophe inside a double-quoted value)
// does not terminate the match early and mangle surrounding content (#1366).
content = content.replace(/\salt\s*=\s*"[^"]*"/gi, "");
content = content.replace(/\salt\s*=\s*'[^']*'/gi, "");
content = content.replace(/\salt\s*=\s*[^\s>]+/gi, ""); content = content.replace(/\salt\s*=\s*[^\s>]+/gi, "");
content = content.replace(/\stitle\s*=\s*"[^"]*"/gi, ""); content = content.replace(/\stitle\s*=\s*["'][^"']*["']/gi, "");
content = content.replace(/\stitle\s*=\s*'[^']*'/gi, "");
content = content.replace(/\stitle\s*=\s*[^\s>]+/gi, ""); content = content.replace(/\stitle\s*=\s*[^\s>]+/gi, "");
content = content.replace(/\saria-label\s*=\s*"[^"]*"/gi, ""); content = content.replace(/\saria-label\s*=\s*["'][^"']*["']/gi, "");
content = content.replace(/\saria-label\s*=\s*'[^']*'/gi, "");
content = content.replace(/\saria-label\s*=\s*[^\s>]+/gi, ""); content = content.replace(/\saria-label\s*=\s*[^\s>]+/gi, "");
content = content.replace(/\sdata-[a-zA-Z0-9-]+\s*=\s*"[^"]*"/gi, ""); content = content.replace(/\sdata-[a-zA-Z0-9-]+\s*=\s*["'][^"']*["']/gi, "");
content = content.replace(/\sdata-[a-zA-Z0-9-]+\s*=\s*'[^']*'/gi, "");
content = content.replace(/\sdata-[a-zA-Z0-9-]+\s*=\s*[^\s>]+/gi, ""); content = content.replace(/\sdata-[a-zA-Z0-9-]+\s*=\s*[^\s>]+/gi, "");
content = content.replace(/\splaceholder\s*=\s*"[^"]*"/gi, ""); content = content.replace(/\splaceholder\s*=\s*["'][^"']*["']/gi, "");
content = content.replace(/\splaceholder\s*=\s*'[^']*'/gi, "");
content = content.replace(/\splaceholder\s*=\s*[^\s>]+/gi, ""); content = content.replace(/\splaceholder\s*=\s*[^\s>]+/gi, "");
return content; return content;
} }
@ -89,12 +75,6 @@ export function redactGitHubTokens(content: string): string {
"[REDACTED_GITHUB_TOKEN]", "[REDACTED_GITHUB_TOKEN]",
); );
// GitHub user-to-server tokens: ghu_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX (40 chars)
content = content.replace(
/\bghu_[A-Za-z0-9]{36}\b/g,
"[REDACTED_GITHUB_TOKEN]",
);
// GitHub installation tokens: ghs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX (40 chars) // GitHub installation tokens: ghs_XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX (40 chars)
content = content.replace( content = content.replace(
/\bghs_[A-Za-z0-9]{36}\b/g, /\bghs_[A-Za-z0-9]{36}\b/g,

View File

@ -5,7 +5,6 @@ import { appendFileSync } from "fs";
import { z } from "zod"; import { z } from "zod";
import { createOctokit } from "../github/api/client"; import { createOctokit } from "../github/api/client";
import { sanitizeContent } from "../github/utils/sanitizer"; import { sanitizeContent } from "../github/utils/sanitizer";
import { removeBufferedComment } from "./inline-comment-buffer";
// Get repository and PR information from environment variables // Get repository and PR information from environment variables
const REPO_OWNER = process.env.REPO_OWNER; const REPO_OWNER = process.env.REPO_OWNER;
@ -181,16 +180,6 @@ server.tool(
const result = await octokit.rest.pulls.createReviewComment(params); const result = await octokit.rest.pulls.createReviewComment(params);
// The comment is now live. Drop any buffered copy of it so the
// post-session replay step cannot post it a second time (the model often
// re-issues a buffered call with confirmed=true after the buffer reply).
if (CLASSIFY_ENABLED) {
removeBufferedComment(
{ path, line, startLine, body: sanitizedBody },
BUFFER_PATH,
);
}
return { return {
content: [ content: [
{ {

View File

@ -1,54 +0,0 @@
import { existsSync, readFileSync, writeFileSync } from "fs";
export type BufferedCommentMatch = {
path: string;
line?: number;
startLine?: number;
body: string;
};
/**
* Remove any buffered inline comment that matches an already-posted comment.
*
* When a comment is posted live (confirmed=true), an earlier buffered copy of
* the same comment must be dropped so the post-session replay step does not
* post it a second time. The model frequently re-issues a buffered call with
* confirmed=true after reading the "Set confirmed=true to post immediately"
* reply; previously the original buffered entry was left behind and replayed,
* producing duplicate inline comments.
*
* Entries are matched on path, line, startLine and body. Lines that cannot be
* parsed are kept untouched.
*/
export function removeBufferedComment(
match: BufferedCommentMatch,
bufferPath: string,
): void {
if (!existsSync(bufferPath)) {
return;
}
const remaining = readFileSync(bufferPath, "utf8")
.split("\n")
.filter((line) => line.trim() !== "")
.filter((line) => {
let entry: BufferedCommentMatch;
try {
entry = JSON.parse(line);
} catch {
// Keep anything we cannot parse rather than silently dropping it.
return true;
}
const isSameComment =
entry.path === match.path &&
entry.line === match.line &&
entry.startLine === match.startLine &&
entry.body === match.body;
return !isSameComment;
});
writeFileSync(
bufferPath,
remaining.length > 0 ? remaining.join("\n") + "\n" : "",
);
}

View File

@ -1,4 +1,4 @@
import { mkdir, rm, writeFile } from "fs/promises"; import { mkdir, writeFile } from "fs/promises";
import { prepareMcpConfig } from "../../mcp/install-mcp-server"; import { prepareMcpConfig } from "../../mcp/install-mcp-server";
import { parseAllowedTools } from "./parse-tools"; import { parseAllowedTools } from "./parse-tools";
import { import {
@ -64,19 +64,20 @@ export async function prepareAgentMode({
} }
} }
// Create prompt directory. Clear any stale files from a prior invocation first — // Create prompt directory
// see src/create-prompt/index.ts for context (non-ephemeral self-hosted runners await mkdir(`${process.env.RUNNER_TEMP || "/tmp"}/claude-prompts`, {
// do not reliably honor the RUNNER_TEMP cleanup contract). recursive: true,
const promptDir = `${process.env.RUNNER_TEMP || "/tmp"}/claude-prompts`; });
await rm(promptDir, { recursive: true, force: true });
await mkdir(promptDir, { recursive: true });
// Write the prompt file - use the user's prompt directly // Write the prompt file - use the user's prompt directly
const promptContent = const promptContent =
context.inputs.prompt || context.inputs.prompt ||
`Repository: ${context.repository.owner}/${context.repository.repo}`; `Repository: ${context.repository.owner}/${context.repository.repo}`;
await writeFile(`${promptDir}/claude-prompt.txt`, promptContent); await writeFile(
`${process.env.RUNNER_TEMP || "/tmp"}/claude-prompts/claude-prompt.txt`,
promptContent,
);
// Parse allowed tools from user's claude_args // Parse allowed tools from user's claude_args
const userClaudeArgs = process.env.CLAUDE_ARGS || ""; const userClaudeArgs = process.env.CLAUDE_ARGS || "";

View File

@ -1,77 +1,29 @@
import { parse as parseShellArgs } from "shell-quote";
// Flags whose values make up the allowed-tools list.
// Include both camelCase and hyphenated variants for CLI compatibility.
const ALLOWED_TOOLS_FLAGS = new Set(["allowedTools", "allowed-tools"]);
/**
* Strip comment lines from a shell argument string.
* Lines whose first non-whitespace character is `#` are removed entirely.
* Mirrors stripShellComments in base-action/src/parse-sdk-options.ts.
*/
function stripShellComments(input: string): string {
return input
.split("\n")
.filter((line) => !line.trim().startsWith("#"))
.join("\n");
}
/**
* Tokenize a claude_args string the same way base-action/src/parse-sdk-options.ts
* does: strip full comment lines, then run shell-quote. shell-quote returns
* unquoted glob patterns (e.g. `mcp__github__*`) as `{ op: "glob", pattern }`
* objects rather than strings, so recover their literal text; drop operator
* tokens (`|`, `>`, `;`, ...) which carry no value.
*/
function tokenize(claudeArgs: string): string[] {
return parseShellArgs(stripShellComments(claudeArgs))
.map((token) => {
if (typeof token === "string") return token;
if (token && typeof token === "object" && "pattern" in token) {
return (token as { pattern: string }).pattern;
}
return null;
})
.filter((token): token is string => token !== null);
}
/**
* Parse the list of allowed tool names from a user-provided claude_args string.
*
* This is used to decide which GitHub MCP servers to install. It MUST stay in
* agreement with how the actual tool list is built for the SDK in
* base-action/src/parse-sdk-options.ts (parseClaudeArgsToExtraArgs): otherwise a
* tool can be granted to Claude without its MCP server being installed, or a
* server can be installed for a tool that was never granted (#1357).
*
* To stay in agreement it uses the same shell-quote tokenizer and the same
* "an accumulating flag consumes all consecutive non-flag values" semantics,
* so `--allowedTools "Read" "Grep" "mcp__github__get_commit"` captures all
* three values, and commented-out lines are ignored.
*/
export function parseAllowedTools(claudeArgs: string): string[] { export function parseAllowedTools(claudeArgs: string): string[] {
if (!claudeArgs?.trim()) return []; // Match --allowedTools or --allowed-tools followed by the value
// Handle both quoted and unquoted values
// Use /g flag to find ALL occurrences, not just the first one
const patterns = [
/--(?:allowedTools|allowed-tools)\s+"([^"]+)"/g, // Double quoted
/--(?:allowedTools|allowed-tools)\s+'([^']+)'/g, // Single quoted
/--(?:allowedTools|allowed-tools)\s+([^'"\s][^\s]*)/g, // Unquoted (must not start with quote)
];
const args = tokenize(claudeArgs);
const tools: string[] = []; const tools: string[] = [];
const seen = new Set<string>(); const seen = new Set<string>();
for (let i = 0; i < args.length; i++) { for (const pattern of patterns) {
const arg = args[i]; for (const match of claudeArgs.matchAll(pattern)) {
if (!arg?.startsWith("--")) continue; if (match[1]) {
// Don't add if the value starts with -- (another flag)
const flag = arg.slice(2); if (match[1].startsWith("--")) {
if (!ALLOWED_TOOLS_FLAGS.has(flag)) continue; continue;
}
// Consume all consecutive non-flag values, e.g. for (const tool of match[1].split(",")) {
// --allowedTools "Read" "Grep" "mcp__github__get_commit" const trimmed = tool.trim();
while (i + 1 < args.length && !args[i + 1]!.startsWith("--")) { if (trimmed && !seen.has(trimmed)) {
i++; seen.add(trimmed);
for (const tool of args[i]!.split(",")) { tools.push(trimmed);
const trimmed = tool.trim(); }
if (trimmed && !seen.has(trimmed)) {
seen.add(trimmed);
tools.push(trimmed);
} }
} }
} }

View File

@ -28,20 +28,6 @@ function extractDescription(
.replace(/^-|-$/g, ""); // Remove leading/trailing hyphens .replace(/^-|-$/g, ""); // Remove leading/trailing hyphens
} }
/**
* Sanitizes a label into a git-safe branch segment. Labels are free-form and
* often scoped (e.g. "area:permissions"), so characters that are invalid in a
* branch name (":", "/", spaces, ...) are replaced with a hyphen rather than
* dropped, keeping the label readable. Returns "" if nothing usable remains.
*/
function sanitizeLabel(label: string): string {
return label
.toLowerCase()
.replace(/[^a-z0-9-]+/g, "-") // Replace runs of invalid chars with a hyphen
.replace(/-+/g, "-") // Collapse multiple hyphens
.replace(/^-|-$/g, ""); // Remove leading/trailing hyphens
}
export interface BranchTemplateVariables { export interface BranchTemplateVariables {
prefix: string; prefix: string;
entityType: string; entityType: string;
@ -92,7 +78,7 @@ export function generateBranchName(
entityNumber, entityNumber,
timestamp: `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, "0")}${String(now.getDate()).padStart(2, "0")}-${String(now.getHours()).padStart(2, "0")}${String(now.getMinutes()).padStart(2, "0")}`, timestamp: `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, "0")}${String(now.getDate()).padStart(2, "0")}-${String(now.getHours()).padStart(2, "0")}${String(now.getMinutes()).padStart(2, "0")}`,
sha: sha?.substring(0, 8), // First 8 characters of SHA sha: sha?.substring(0, 8), // First 8 characters of SHA
label: (label && sanitizeLabel(label)) || entityType, // Sanitize; fall back to entityType if empty/no label label: label || entityType, // Fall back to entityType if no label
description: title ? extractDescription(title) : undefined, description: title ? extractDescription(title) : undefined,
}; };

View File

@ -1,4 +1,47 @@
export { export type RetryOptions = {
retryWithBackoff, maxAttempts?: number;
type RetryOptions, initialDelayMs?: number;
} from "../../base-action/src/retry"; maxDelayMs?: number;
backoffFactor?: number;
shouldRetry?: (error: Error) => boolean;
};
export async function retryWithBackoff<T>(
operation: () => Promise<T>,
options: RetryOptions = {},
): Promise<T> {
const {
maxAttempts = 3,
initialDelayMs = 5000,
maxDelayMs = 20000,
backoffFactor = 2,
shouldRetry,
} = options;
let delayMs = initialDelayMs;
let lastError: Error | undefined;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
console.log(`Attempt ${attempt} of ${maxAttempts}...`);
return await operation();
} catch (error) {
lastError = error instanceof Error ? error : new Error(String(error));
console.error(`Attempt ${attempt} failed:`, lastError.message);
if (shouldRetry && !shouldRetry(lastError)) {
console.error("Error is not retryable, giving up immediately");
throw lastError;
}
if (attempt < maxAttempts) {
console.log(`Retrying in ${delayMs / 1000} seconds...`);
await new Promise((resolve) => setTimeout(resolve, delayMs));
delayMs = Math.min(delayMs * backoffFactor, maxDelayMs);
}
}
}
console.error(`Operation failed after ${maxAttempts} attempts`);
throw lastError;
}

View File

@ -5,7 +5,6 @@ import {
applyBranchTemplate, applyBranchTemplate,
generateBranchName, generateBranchName,
} from "../src/utils/branch-template"; } from "../src/utils/branch-template";
import { validateBranchName } from "../src/github/operations/branch";
describe("branch template utilities", () => { describe("branch template utilities", () => {
describe("applyBranchTemplate", () => { describe("applyBranchTemplate", () => {
@ -145,53 +144,6 @@ describe("branch template utilities", () => {
expect(result).toBe("dev/enhancement-issue_789"); expect(result).toBe("dev/enhancement-issue_789");
}); });
it("should sanitize scoped labels that contain invalid git characters", () => {
const template = "{{prefix}}{{label}}/{{entityNumber}}";
const result = generateBranchName(
template,
"claude/",
"issue",
123,
undefined,
"area:permissions",
);
expect(result).toBe("claude/area-permissions/123");
// Regression: an unsanitized ":" here previously failed validateBranchName
// and crashed the run via process.exit(1).
expect(() => validateBranchName(result)).not.toThrow();
});
it("should replace spaces in labels with hyphens", () => {
const template = "{{prefix}}{{label}}-{{entityNumber}}";
const result = generateBranchName(
template,
"fix/",
"issue",
456,
undefined,
"needs review",
);
expect(result).toBe("fix/needs-review-456");
expect(() => validateBranchName(result)).not.toThrow();
});
it("should fall back to entityType when a label sanitizes to empty", () => {
const template = "{{prefix}}{{label}}-{{entityNumber}}";
const result = generateBranchName(
template,
"fix/",
"pr",
789,
undefined,
"🎉",
);
expect(result).toBe("fix/pr-789");
expect(() => validateBranchName(result)).not.toThrow();
});
it("should use description in template when provided", () => { it("should use description in template when provided", () => {
const template = "{{prefix}}{{description}}/{{entityNumber}}"; const template = "{{prefix}}{{description}}/{{entityNumber}}";
const result = generateBranchName( const result = generateBranchName(

View File

@ -1,74 +0,0 @@
import { describe, test, expect } from "bun:test";
import {
SPINNER_HTML,
createJobRunLink,
createBranchLink,
createCommentBody,
} from "../src/github/operations/comments/common";
import { GITHUB_SERVER_URL } from "../src/github/api/config";
describe("comments/common", () => {
describe("createJobRunLink", () => {
test("builds a markdown link to the workflow run", () => {
const result = createJobRunLink("anthropics", "claude-code-action", "42");
expect(result).toBe(
`[View job run](${GITHUB_SERVER_URL}/anthropics/claude-code-action/actions/runs/42)`,
);
});
test("honors GITHUB_SERVER_URL (GHES) rather than hardcoding github.com", () => {
// The link is built from the configured server URL, so it must point at
// whatever GITHUB_SERVER_URL resolves to (github.com by default, a GHES
// host in enterprise setups).
expect(createJobRunLink("o", "r", "1")).toContain(GITHUB_SERVER_URL);
});
});
describe("createBranchLink", () => {
test("builds a leading-newline markdown link to the branch tree", () => {
const result = createBranchLink(
"anthropics",
"claude-code-action",
"feature/x",
);
expect(result).toBe(
`\n[View branch](${GITHUB_SERVER_URL}/anthropics/claude-code-action/tree/feature/x)`,
);
});
test("prefixes the link with a newline so it renders on its own line", () => {
expect(createBranchLink("o", "r", "main").startsWith("\n")).toBe(true);
});
});
describe("createCommentBody", () => {
test("includes the spinner, the working message, and the job run link", () => {
const jobRunLink = createJobRunLink("o", "r", "7");
const body = createCommentBody(jobRunLink);
expect(body).toContain(SPINNER_HTML);
expect(body).toContain("Claude Code is working…");
expect(body).toContain(jobRunLink);
});
test("omits the branch link when none is provided (defaults to empty)", () => {
const body = createCommentBody(createJobRunLink("o", "r", "7"));
expect(body).not.toContain("View branch");
// No trailing branch content: body ends with the job run link.
expect(body.endsWith(")")).toBe(true);
});
test("appends the branch link when provided", () => {
const jobRunLink = createJobRunLink("o", "r", "7");
const branchLink = createBranchLink("o", "r", "feature/x");
const body = createCommentBody(jobRunLink, branchLink);
expect(body).toContain(jobRunLink);
expect(body).toContain(branchLink);
// The branch link (with its leading newline) comes after the job run link.
expect(body.indexOf(branchLink)).toBeGreaterThan(
body.indexOf(jobRunLink),
);
});
});
});

View File

@ -6,10 +6,8 @@ import {
getEventTypeAndContext, getEventTypeAndContext,
buildAllowedToolsString, buildAllowedToolsString,
buildDisallowedToolsString, buildDisallowedToolsString,
prepareContext,
} from "../src/create-prompt"; } from "../src/create-prompt";
import type { PreparedContext } from "../src/create-prompt"; import type { PreparedContext } from "../src/create-prompt";
import { createMockContext } from "./mockContext";
beforeAll(() => { beforeAll(() => {
process.env.GITHUB_ACTION_PATH = "/test/action/path"; process.env.GITHUB_ACTION_PATH = "/test/action/path";
@ -497,32 +495,6 @@ describe("generatePrompt", () => {
); );
}); });
test("should use numeric GitHub noreply address when trigger user id is provided", async () => {
const envVars: PreparedContext = {
repository: "owner/repo",
claudeCommentId: "12345",
triggerPhrase: "@claude",
triggerUsername: "johndoe",
triggerUserId: 123456,
eventData: {
eventName: "issue_comment",
commentId: "67890",
isPR: false,
issueNumber: "123",
baseBranch: "main",
claudeBranch: "claude/issue-67890-20240101-1200",
commentBody: "@claude please fix this",
},
};
const prompt = await generatePrompt(envVars, mockGitHubData, false, "tag");
expect(prompt).toContain(
"Co-authored-by: johndoe <123456+johndoe@users.noreply.github.com>",
);
expect(prompt).not.toContain("<johndoe@users.noreply.github.com>");
});
test("should include PR-specific instructions only for PR events", async () => { test("should include PR-specific instructions only for PR events", async () => {
const envVars: PreparedContext = { const envVars: PreparedContext = {
repository: "owner/repo", repository: "owner/repo",
@ -1272,83 +1244,3 @@ describe("buildDisallowedToolsString", () => {
expect(result).toBe("BadTool1,BadTool2"); expect(result).toBe("BadTool1,BadTool2");
}); });
}); });
describe("prepareContext validation errors", () => {
const commentId = "12345";
test("throws on an unsupported event type", () => {
const context = createMockContext({
eventName: "deployment_status" as any,
});
expect(() => prepareContext(context, commentId)).toThrow(
"Unsupported event type: deployment_status",
);
});
test("pull_request event requires a PR number (isPR must be true)", () => {
const context = createMockContext({
eventName: "pull_request",
eventAction: "opened",
isPR: false,
});
expect(() => prepareContext(context, commentId)).toThrow(
"PR_NUMBER is required for pull_request event",
);
});
test("pull_request_review event requires a PR number", () => {
const context = createMockContext({
eventName: "pull_request_review",
isPR: false,
payload: {
review: { body: "please fix", user: { login: "user1" } },
} as any,
});
expect(() => prepareContext(context, commentId)).toThrow(
"PR_NUMBER is required for pull_request_review event",
);
});
test("issues event requires an event action", () => {
const context = createMockContext({
eventName: "issues",
eventAction: "",
isPR: false,
payload: { issue: { user: { login: "user1" } } } as any,
});
expect(() => prepareContext(context, commentId)).toThrow(
"GITHUB_EVENT_ACTION is required for issues event",
);
});
test("issues event rejects an unsupported action", () => {
const context = createMockContext({
eventName: "issues",
eventAction: "deleted",
isPR: false,
payload: { issue: { user: { login: "user1" } } } as any,
});
expect(() =>
prepareContext(context, commentId, "main", "claude/issue-1"),
).toThrow("Unsupported issue action: deleted");
});
test("issue_comment on an issue requires a claude branch", () => {
const context = createMockContext({
eventName: "issue_comment",
isPR: false,
payload: {
comment: { id: 999, body: "@claude help", user: { login: "user1" } },
} as any,
});
expect(() => prepareContext(context, commentId)).toThrow(
"CLAUDE_BRANCH is required for issue_comment event",
);
});
});

View File

@ -723,17 +723,16 @@ describe("fetchGitHubData integration with time filtering", () => {
triggerTime: "2024-01-15T12:00:00Z", triggerTime: "2024-01-15T12:00:00Z",
}); });
// Only the review submitted before the trigger and not edited afterward // The reviewData field returns all reviews (not filtered), but the filtering
// reaches the prompt. The review submitted after the trigger and the one // happens when processing review bodies for download
// edited after the trigger are dropped (TOCTOU protection), matching the // We can check the image download map to verify filtering
// issue/PR comment and body handling. expect(result.reviewData?.nodes?.length).toBe(3); // All reviews are returned
expect(result.reviewData?.nodes?.length).toBe(1);
expect(result.reviewData?.nodes?.[0]?.databaseId).toBe("1");
// Only that surviving review's body is queued for image download. // Check that only the first review's body would be downloaded (filtered)
const reviewsInMap = Object.keys(result.imageUrlMap).filter((key) => const reviewsInMap = Object.keys(result.imageUrlMap).filter((key) =>
key.startsWith("review_body"), key.startsWith("review_body"),
); );
// Only review 1 should have its body processed (before trigger and not edited after)
expect(reviewsInMap.length).toBeLessThanOrEqual(1); expect(reviewsInMap.length).toBeLessThanOrEqual(1);
}); });
@ -806,83 +805,14 @@ describe("fetchGitHubData integration with time filtering", () => {
triggerTime: "2024-01-15T12:00:00Z", triggerTime: "2024-01-15T12:00:00Z",
}); });
// The review itself is pre-trigger and kept, but its inline comments are // The imageUrlMap contains processed comments for image downloading
// filtered to trigger time: the comment created after the trigger (id 11) // We should have processed review comments, but only those before trigger time
// and the one edited after the trigger (id 12) are dropped, leaving only // The exact check depends on how imageUrlMap is structured, but we can verify
// the pre-trigger comment (id 10). // that filtering occurred by checking the review data still has all nodes
expect(result.reviewData?.nodes?.length).toBe(1); expect(result.reviewData?.nodes?.length).toBe(1); // Original review is kept
const reviewCommentIds =
result.reviewData?.nodes?.[0]?.comments?.nodes?.map((c) => c.databaseId);
expect(reviewCommentIds).toEqual(["10"]);
});
it("should filter reviews by both trigger time and actor", async () => { // The actual filtering happens during processing for image download
const mockOctokits = { // Since the mock doesn't actually download images, we verify the input was correct
graphql: jest.fn().mockResolvedValue({
repository: {
pullRequest: {
number: 321,
title: "Test PR",
body: "PR body",
author: { login: "author" },
comments: { nodes: [] },
files: { nodes: [] },
reviews: {
nodes: [
{
id: "1",
databaseId: "1",
author: { login: "reviewer1" },
body: "Pre-trigger human review",
state: "APPROVED",
submittedAt: "2024-01-15T11:00:00Z",
comments: { nodes: [] },
},
{
id: "2",
databaseId: "2",
author: { login: "scanner[bot]" },
body: "Pre-trigger bot review",
state: "COMMENTED",
submittedAt: "2024-01-15T11:00:00Z",
comments: { nodes: [] },
},
{
id: "3",
databaseId: "3",
author: { login: "reviewer3" },
body: "Post-trigger human review",
state: "CHANGES_REQUESTED",
submittedAt: "2024-01-15T13:00:00Z",
comments: { nodes: [] },
},
],
},
},
},
user: { login: "trigger-user" },
}),
rest: {
pulls: {
listFiles: jest.fn().mockResolvedValue({ data: [] }),
},
},
};
const result = await fetchGitHubData({
octokits: mockOctokits as any,
repository: "test-owner/test-repo",
prNumber: "321",
isPR: true,
triggerUsername: "trigger-user",
triggerTime: "2024-01-15T12:00:00Z",
excludeCommentsByActor: "*[bot]",
});
// The trigger-time and actor filters compose: the pre-trigger human review
// is kept, the pre-trigger bot review is dropped by actor, and the
// post-trigger human review is dropped by trigger time.
expect(result.reviewData?.nodes?.map((r) => r.databaseId)).toEqual(["1"]);
}); });
it("should handle backward compatibility when no trigger time provided", async () => { it("should handle backward compatibility when no trigger time provided", async () => {
@ -1499,42 +1429,4 @@ describe("filterCommentsByActor", () => {
const filtered = filterCommentsByActor(comments, "user1", ""); const filtered = filterCommentsByActor(comments, "user1", "");
expect(filtered).toHaveLength(0); expect(filtered).toHaveLength(0);
}); });
test("does not crash on comments from deleted (null-author) accounts", () => {
// GitHub's GraphQL returns author: null for comments whose account was
// deleted. With an exclude filter set (the exact `*[bot]` config we
// recommend), the null author must not throw when dereferenced.
const comments = [
{ author: { login: "user1" }, body: "comment1" },
{ author: null, body: "from a deleted account" },
{ author: { login: "bot[bot]" }, body: "comment3" },
];
const { filterCommentsByActor } = require("../src/github/data/fetcher");
const filtered = filterCommentsByActor(comments, "", "*[bot]");
// ghost comment is retained (it matches no exclude pattern); the bot is dropped.
expect(filtered).toHaveLength(2);
expect(filtered.map((c: any) => c.body)).toEqual([
"comment1",
"from a deleted account",
]);
});
test("treats null author as the 'ghost' login for include/exclude", () => {
const comments = [
{ author: null, body: "from a deleted account" },
{ author: { login: "user1" }, body: "comment2" },
];
const { filterCommentsByActor } = require("../src/github/data/fetcher");
// Excluding "ghost" removes the deleted-account comment.
expect(filterCommentsByActor(comments, "", "ghost")).toHaveLength(1);
expect(filterCommentsByActor(comments, "", "ghost")[0].body).toBe(
"comment2",
);
// Including only "ghost" keeps just the deleted-account comment.
const onlyGhost = filterCommentsByActor(comments, "ghost", "");
expect(onlyGhost).toHaveLength(1);
expect(onlyGhost[0].body).toBe("from a deleted account");
});
}); });

View File

@ -54,53 +54,6 @@ describe("formatContext", () => {
PR Author: test-user PR Author: test-user
PR Branch: feature/test -> main PR Branch: feature/test -> main
PR State: OPEN PR State: OPEN
PR Labels: none
PR Additions: 50
PR Deletions: 30
Total Commits: 3
Changed Files: 2 files`,
);
});
test("formats PR context with labels", () => {
const prData: GitHubPullRequest = {
title: "Test PR",
body: "PR body",
author: { login: "test-user" },
baseRefName: "main",
headRefName: "feature/test",
headRefOid: "abc123",
isCrossRepository: false,
headRepository: { owner: { login: "testowner" }, name: "testrepo" },
createdAt: "2023-01-01T00:00:00Z",
additions: 50,
deletions: 30,
state: "OPEN",
labels: {
nodes: [{ name: "bug" }, { name: "enhancement" }],
},
commits: {
totalCount: 3,
nodes: [],
},
files: {
nodes: [{} as GitHubFile, {} as GitHubFile],
},
comments: {
nodes: [],
},
reviews: {
nodes: [],
},
};
const result = formatContext(prData, true);
expect(result).toBe(
`PR Title: Test PR
PR Author: test-user
PR Branch: feature/test -> main
PR State: OPEN
PR Labels: bug, enhancement
PR Additions: 50 PR Additions: 50
PR Deletions: 30 PR Deletions: 30
Total Commits: 3 Total Commits: 3
@ -127,53 +80,9 @@ Changed Files: 2 files`,
expect(result).toBe( expect(result).toBe(
`Issue Title: Test Issue `Issue Title: Test Issue
Issue Author: test-user Issue Author: test-user
Issue State: OPEN Issue State: OPEN`,
Issue Labels: none`,
); );
}); });
test("formats Issue context with labels", () => {
const issueData: GitHubIssue = {
title: "Test Issue",
body: "Issue body",
author: { login: "test-user" },
createdAt: "2023-01-01T00:00:00Z",
state: "OPEN",
labels: {
nodes: [
{ name: "architecture" },
{ name: "agent-sdk" },
{ name: "drift:functional" },
],
},
comments: {
nodes: [],
},
};
const result = formatContext(issueData, false);
expect(result).toBe(
`Issue Title: Test Issue
Issue Author: test-user
Issue State: OPEN
Issue Labels: architecture, agent-sdk, drift:functional`,
);
});
test("renders a deleted (null-author) issue author as 'ghost'", () => {
const issueData: GitHubIssue = {
title: "Test Issue",
body: "Issue body",
author: null,
createdAt: "2023-01-01T00:00:00Z",
state: "OPEN",
labels: { nodes: [] },
comments: { nodes: [] },
};
const result = formatContext(issueData, false);
expect(result).toContain("Issue Author: ghost");
});
}); });
describe("formatBody", () => { describe("formatBody", () => {
@ -267,24 +176,6 @@ describe("formatComments", () => {
); );
}); });
test("renders deleted (null-author) comments as 'ghost'", () => {
// GitHub returns author: null for comments from deleted accounts.
const comments: GitHubComment[] = [
{
id: "1",
databaseId: "100001",
body: "From a deleted account",
author: null,
createdAt: "2023-01-01T00:00:00Z",
},
];
const result = formatComments(comments);
expect(result).toBe(
"[ghost at 2023-01-01T00:00:00Z]: From a deleted account",
);
});
test("returns empty string for empty comments array", () => { test("returns empty string for empty comments array", () => {
const result = formatComments([]); const result = formatComments([]);
expect(result).toBe(""); expect(result).toBe("");
@ -527,29 +418,6 @@ describe("formatReviewComments", () => {
); );
}); });
test("renders deleted (null-author) reviews as 'ghost'", () => {
const reviewData = {
nodes: [
{
id: "review1",
databaseId: "300099",
author: null,
body: "Left before deleting the account",
state: "COMMENTED",
submittedAt: "2023-01-01T00:00:00Z",
comments: {
nodes: [],
},
},
],
};
const result = formatReviewComments(reviewData);
expect(result).toBe(
`[Review by ghost at 2023-01-01T00:00:00Z]: COMMENTED\nLeft before deleting the account`,
);
});
test("formats multiple reviews correctly", () => { test("formats multiple reviews correctly", () => {
const reviewData = { const reviewData = {
nodes: [ nodes: [

View File

@ -437,81 +437,3 @@ describe("integration tests", () => {
expect(actualOutput).toBe(expectedOutput); expect(actualOutput).toBe(expectedOutput);
}); });
}); });
describe("detectContentType fallbacks", () => {
test("falls back to text for malformed JSON objects", () => {
// Looks like an object (starts with { ends with }) but does not parse.
expect(detectContentType("{not valid json}")).toBe("text");
});
test("falls back to text for malformed JSON arrays", () => {
// Looks like an array (starts with [ ends with ]) but does not parse.
expect(detectContentType("[not, valid, json]")).toBe("text");
});
test("classifies non-python, non-js code keywords as python by default", () => {
// Contains a code keyword ("class ") but matches neither the python-specific
// nor the javascript-specific checks, so it hits the default branch.
expect(detectContentType("class Foo {}")).toBe("python");
});
});
describe("formatResultContent non-string input", () => {
test("handles a numeric (non-string) result value", () => {
const result = formatResultContent(42);
expect(result).toContain("42");
});
test("handles a plain object (non-string, non-text-array) result value", () => {
const result = formatResultContent({ status: "ok" });
expect(typeof result).toBe("string");
expect(result.length).toBeGreaterThan(0);
});
});
describe("system_other handling", () => {
test("groups a non-init system turn as system_other", () => {
const systemTurn: Turn = { type: "system", subtype: "some_other_subtype" };
const grouped = groupTurnsNaturally([systemTurn]);
expect(grouped).toHaveLength(1);
expect(grouped[0]?.type).toBe("system_other");
expect(grouped[0]?.data).toEqual(systemTurn);
});
test("renders a system_other group as a System Message section", () => {
const markdown = formatGroupedContent([
{ type: "system_other", data: { type: "system" } as Turn },
]);
expect(markdown).toContain("## ⚙️ System Message");
});
test("filters out thinking_tokens system messages", () => {
const data: Turn[] = [
{ type: "system", subtype: "init", tools: [{ name: "tool1" }] },
{ type: "system", subtype: "thinking_tokens" },
{ type: "system", subtype: "thinking_tokens" },
{ type: "system", subtype: "other_subtype" },
];
const grouped = groupTurnsNaturally(data);
// Should have init and other_subtype, but not thinking_tokens
expect(grouped).toHaveLength(2);
expect(grouped[0]?.type).toBe("system_init");
expect(grouped[1]?.type).toBe("system_other");
expect(grouped[1]?.data?.subtype).toBe("other_subtype");
});
test("thinking_tokens does not appear in formatted output", () => {
const data: Turn[] = [
{ type: "system", subtype: "init", tools: [] },
{ type: "system", subtype: "thinking_tokens" },
{ type: "system", subtype: "thinking_tokens" },
];
const result = formatTurnsFromData(data);
expect(result).not.toContain("thinking_tokens");
expect(result).toContain("## 🚀 System Initialization");
});
});

View File

@ -1,520 +0,0 @@
import { afterAll, beforeEach, describe, expect, mock, test } from "bun:test";
import type {
IssuesEvent,
IssueCommentEvent,
PullRequestEvent,
PullRequestReviewEvent,
PullRequestReviewCommentEvent,
WorkflowRunEvent,
} from "@octokit/webhooks-types";
// parseGitHubContext() reads the singleton `github.context` from
// @actions/github, so the module is mocked with a mutable context object
// that each test configures. Nothing else in the codebase imports
// @actions/github, so the mock does not leak into other suites.
const fakeGithubContext = {
eventName: "",
payload: {} as Record<string, unknown>,
repo: { owner: "test-owner", repo: "test-repo" },
actor: "test-actor",
};
mock.module("@actions/github", () => ({
context: fakeGithubContext,
}));
import {
parseGitHubContext,
isIssuesEvent,
isIssueCommentEvent,
isPullRequestEvent,
isPullRequestReviewEvent,
isPullRequestReviewCommentEvent,
isIssuesAssignedEvent,
isEntityContext,
isAutomationContext,
} from "../src/github/context";
import { CLAUDE_APP_BOT_ID, CLAUDE_BOT_LOGIN } from "../src/github/constants";
import { createMockContext, createMockAutomationContext } from "./mockContext";
const ENV_KEYS = [
"GITHUB_RUN_ID",
"PROMPT",
"TRIGGER_PHRASE",
"ASSIGNEE_TRIGGER",
"LABEL_TRIGGER",
"BASE_BRANCH",
"BRANCH_PREFIX",
"BRANCH_NAME_TEMPLATE",
"USE_STICKY_COMMENT",
"CLASSIFY_INLINE_COMMENTS",
"USE_COMMIT_SIGNING",
"SSH_SIGNING_KEY",
"BOT_ID",
"BOT_NAME",
"ALLOWED_BOTS",
"ALLOWED_NON_WRITE_USERS",
"TRACK_PROGRESS",
"INCLUDE_FIX_LINKS",
"INCLUDE_COMMENTS_BY_ACTOR",
"EXCLUDE_COMMENTS_BY_ACTOR",
] as const;
const originalEnv: Record<string, string | undefined> = {};
for (const key of ENV_KEYS) {
originalEnv[key] = process.env[key];
}
beforeEach(() => {
for (const key of ENV_KEYS) {
delete process.env[key];
}
process.env.GITHUB_RUN_ID = "9876543210";
fakeGithubContext.eventName = "";
fakeGithubContext.payload = {};
fakeGithubContext.repo = { owner: "test-owner", repo: "test-repo" };
fakeGithubContext.actor = "test-actor";
});
afterAll(() => {
for (const key of ENV_KEYS) {
if (originalEnv[key] === undefined) {
delete process.env[key];
} else {
process.env[key] = originalEnv[key];
}
}
});
const repositoryPayload = {
name: "test-repo",
full_name: "test-owner/test-repo",
private: false,
default_branch: "main",
owner: { login: "test-owner" },
};
function setEvent(eventName: string, payload: unknown) {
fakeGithubContext.eventName = eventName;
fakeGithubContext.payload = payload as Record<string, unknown>;
}
describe("parseGitHubContext", () => {
describe("entity events (one test per equivalence partition)", () => {
test("issues event extracts issue number and isPR false", () => {
setEvent("issues", {
action: "opened",
issue: { number: 42 },
repository: repositoryPayload,
} as unknown as IssuesEvent);
const context = parseGitHubContext();
expect(context.eventName).toBe("issues");
expect(context.eventAction).toBe("opened");
if (!isEntityContext(context)) {
throw new Error("expected entity context");
}
expect(context.entityNumber).toBe(42);
expect(context.isPR).toBe(false);
});
test("issue_comment on a plain issue has isPR false", () => {
setEvent("issue_comment", {
action: "created",
issue: { number: 55 },
comment: { id: 1, body: "hello" },
repository: repositoryPayload,
} as unknown as IssueCommentEvent);
const context = parseGitHubContext();
expect(context.eventName).toBe("issue_comment");
if (!isEntityContext(context)) {
throw new Error("expected entity context");
}
expect(context.entityNumber).toBe(55);
expect(context.isPR).toBe(false);
});
test("issue_comment on a pull request has isPR true", () => {
setEvent("issue_comment", {
action: "created",
issue: {
number: 789,
pull_request: {
url: "https://api.github.com/repos/test-owner/test-repo/pulls/789",
},
},
comment: { id: 2, body: "hello" },
repository: repositoryPayload,
} as unknown as IssueCommentEvent);
const context = parseGitHubContext();
if (!isEntityContext(context)) {
throw new Error("expected entity context");
}
expect(context.entityNumber).toBe(789);
expect(context.isPR).toBe(true);
});
test("pull_request event extracts PR number and isPR true", () => {
setEvent("pull_request", {
action: "opened",
number: 456,
pull_request: { number: 456 },
repository: repositoryPayload,
} as unknown as PullRequestEvent);
const context = parseGitHubContext();
expect(context.eventName).toBe("pull_request");
if (!isEntityContext(context)) {
throw new Error("expected entity context");
}
expect(context.entityNumber).toBe(456);
expect(context.isPR).toBe(true);
});
test("pull_request_target is normalized to pull_request", () => {
setEvent("pull_request_target", {
action: "opened",
number: 457,
pull_request: { number: 457 },
repository: repositoryPayload,
} as unknown as PullRequestEvent);
const context = parseGitHubContext();
expect(context.eventName).toBe("pull_request");
if (!isEntityContext(context)) {
throw new Error("expected entity context");
}
expect(context.entityNumber).toBe(457);
expect(context.isPR).toBe(true);
});
test("pull_request_review event extracts PR number and isPR true", () => {
setEvent("pull_request_review", {
action: "submitted",
review: { id: 9, state: "approved" },
pull_request: { number: 321 },
repository: repositoryPayload,
} as unknown as PullRequestReviewEvent);
const context = parseGitHubContext();
expect(context.eventName).toBe("pull_request_review");
if (!isEntityContext(context)) {
throw new Error("expected entity context");
}
expect(context.entityNumber).toBe(321);
expect(context.isPR).toBe(true);
});
test("pull_request_review_comment event extracts PR number and isPR true", () => {
setEvent("pull_request_review_comment", {
action: "created",
comment: { id: 7, body: "inline" },
pull_request: { number: 999 },
repository: repositoryPayload,
} as unknown as PullRequestReviewCommentEvent);
const context = parseGitHubContext();
expect(context.eventName).toBe("pull_request_review_comment");
if (!isEntityContext(context)) {
throw new Error("expected entity context");
}
expect(context.entityNumber).toBe(999);
expect(context.isPR).toBe(true);
});
});
describe("automation events (no entityNumber, no isPR)", () => {
test("workflow_dispatch produces an automation context", () => {
setEvent("workflow_dispatch", {
inputs: { task: "run" },
repository: repositoryPayload,
sender: { login: "test-actor" },
workflow: "ci.yml",
});
const context = parseGitHubContext();
expect(context.eventName).toBe("workflow_dispatch");
expect(isAutomationContext(context)).toBe(true);
expect("entityNumber" in context).toBe(false);
expect("isPR" in context).toBe(false);
});
test("repository_dispatch produces an automation context", () => {
setEvent("repository_dispatch", {
action: "trigger-analysis",
client_payload: { issue_number: 42 },
repository: repositoryPayload,
sender: { login: "automation-user" },
});
const context = parseGitHubContext();
expect(context.eventName).toBe("repository_dispatch");
expect(context.eventAction).toBe("trigger-analysis");
expect(isAutomationContext(context)).toBe(true);
});
test("schedule produces an automation context", () => {
setEvent("schedule", {
schedule: "0 0 * * *",
repository: repositoryPayload,
});
const context = parseGitHubContext();
expect(context.eventName).toBe("schedule");
expect(isAutomationContext(context)).toBe(true);
});
test("payload without repository keeps default_branch undefined", () => {
setEvent("schedule", { schedule: "0 0 * * *" });
const context = parseGitHubContext();
expect(context.repository.default_branch).toBeUndefined();
});
test("workflow_run produces an automation context", () => {
setEvent("workflow_run", {
action: "completed",
workflow_run: { id: 123 },
repository: repositoryPayload,
} as unknown as WorkflowRunEvent);
const context = parseGitHubContext();
expect(context.eventName).toBe("workflow_run");
expect(isAutomationContext(context)).toBe(true);
});
});
describe("invalid partition", () => {
test("unsupported event type throws", () => {
setEvent("deployment_status", { repository: repositoryPayload });
expect(() => parseGitHubContext()).toThrow(
"Unsupported event type: deployment_status",
);
});
});
describe("common fields", () => {
test("repository and runId come from the action context", () => {
setEvent("issues", {
action: "opened",
issue: { number: 1 },
repository: repositoryPayload,
} as unknown as IssuesEvent);
const context = parseGitHubContext();
expect(context.runId).toBe("9876543210");
expect(context.actor).toBe("test-actor");
expect(context.repository).toEqual({
owner: "test-owner",
repo: "test-repo",
full_name: "test-owner/test-repo",
default_branch: "main",
});
});
test("inputs fall back to documented defaults when env vars are unset", () => {
setEvent("issues", {
action: "opened",
issue: { number: 1 },
repository: repositoryPayload,
} as unknown as IssuesEvent);
const { inputs } = parseGitHubContext();
expect(inputs.prompt).toBe("");
expect(inputs.triggerPhrase).toBe("@claude");
expect(inputs.assigneeTrigger).toBe("");
expect(inputs.labelTrigger).toBe("");
expect(inputs.branchPrefix).toBe("claude/");
expect(inputs.branchNameTemplate).toBeUndefined();
expect(inputs.useStickyComment).toBe(false);
expect(inputs.classifyInlineComments).toBe(true);
expect(inputs.useCommitSigning).toBe(false);
expect(inputs.sshSigningKey).toBe("");
expect(inputs.botId).toBe(String(CLAUDE_APP_BOT_ID));
expect(inputs.botName).toBe(CLAUDE_BOT_LOGIN);
expect(inputs.allowedBots).toBe("");
expect(inputs.allowedNonWriteUsers).toBe("");
expect(inputs.trackProgress).toBe(false);
expect(inputs.includeFixLinks).toBe(false);
expect(inputs.includeCommentsByActor).toBe("");
expect(inputs.excludeCommentsByActor).toBe("");
expect(inputs.baseBranch).toBeUndefined();
});
test("inputs reflect the env vars set by action.yml", () => {
process.env.PROMPT = "do something";
process.env.TRIGGER_PHRASE = "/claude";
process.env.ASSIGNEE_TRIGGER = "@claude-bot";
process.env.LABEL_TRIGGER = "claude-task";
process.env.BASE_BRANCH = "develop";
process.env.BRANCH_PREFIX = "bot/";
process.env.BRANCH_NAME_TEMPLATE = "{{description}}";
process.env.USE_STICKY_COMMENT = "true";
process.env.CLASSIFY_INLINE_COMMENTS = "false";
process.env.USE_COMMIT_SIGNING = "true";
process.env.SSH_SIGNING_KEY = "ssh-key-material";
process.env.BOT_ID = "111";
process.env.BOT_NAME = "custom-bot";
process.env.ALLOWED_BOTS = "dependabot[bot]";
process.env.ALLOWED_NON_WRITE_USERS = "trusted-user";
process.env.TRACK_PROGRESS = "true";
process.env.INCLUDE_FIX_LINKS = "true";
process.env.INCLUDE_COMMENTS_BY_ACTOR = "alice";
process.env.EXCLUDE_COMMENTS_BY_ACTOR = "bob";
setEvent("issues", {
action: "opened",
issue: { number: 1 },
repository: repositoryPayload,
} as unknown as IssuesEvent);
const { inputs } = parseGitHubContext();
expect(inputs.prompt).toBe("do something");
expect(inputs.triggerPhrase).toBe("/claude");
expect(inputs.assigneeTrigger).toBe("@claude-bot");
expect(inputs.labelTrigger).toBe("claude-task");
expect(inputs.baseBranch).toBe("develop");
expect(inputs.branchPrefix).toBe("bot/");
expect(inputs.branchNameTemplate).toBe("{{description}}");
expect(inputs.useStickyComment).toBe(true);
expect(inputs.classifyInlineComments).toBe(false);
expect(inputs.useCommitSigning).toBe(true);
expect(inputs.sshSigningKey).toBe("ssh-key-material");
expect(inputs.botId).toBe("111");
expect(inputs.botName).toBe("custom-bot");
expect(inputs.allowedBots).toBe("dependabot[bot]");
expect(inputs.allowedNonWriteUsers).toBe("trusted-user");
expect(inputs.trackProgress).toBe(true);
expect(inputs.includeFixLinks).toBe(true);
expect(inputs.includeCommentsByActor).toBe("alice");
expect(inputs.excludeCommentsByActor).toBe("bob");
});
test("boolean inputs only accept the lowercase string true", () => {
process.env.USE_STICKY_COMMENT = "TRUE";
process.env.USE_COMMIT_SIGNING = "1";
setEvent("issues", {
action: "opened",
issue: { number: 1 },
repository: repositoryPayload,
} as unknown as IssuesEvent);
const { inputs } = parseGitHubContext();
expect(inputs.useStickyComment).toBe(false);
expect(inputs.useCommitSigning).toBe(false);
});
});
});
describe("type guards", () => {
const issuesContext = createMockContext({ eventName: "issues" });
const issueCommentContext = createMockContext({
eventName: "issue_comment",
});
const pullRequestContext = createMockContext({ eventName: "pull_request" });
const reviewContext = createMockContext({
eventName: "pull_request_review",
});
const reviewCommentContext = createMockContext({
eventName: "pull_request_review_comment",
});
const workflowDispatchContext = createMockAutomationContext({
eventName: "workflow_dispatch",
});
test("isIssuesEvent accepts only issues events", () => {
expect(isIssuesEvent(issuesContext)).toBe(true);
expect(isIssuesEvent(issueCommentContext)).toBe(false);
expect(isIssuesEvent(workflowDispatchContext)).toBe(false);
});
test("isIssueCommentEvent accepts only issue_comment events", () => {
expect(isIssueCommentEvent(issueCommentContext)).toBe(true);
expect(isIssueCommentEvent(issuesContext)).toBe(false);
});
test("isPullRequestEvent accepts only pull_request events", () => {
expect(isPullRequestEvent(pullRequestContext)).toBe(true);
expect(isPullRequestEvent(reviewContext)).toBe(false);
expect(isPullRequestEvent(issuesContext)).toBe(false);
});
test("isPullRequestReviewEvent accepts only pull_request_review events", () => {
expect(isPullRequestReviewEvent(reviewContext)).toBe(true);
expect(isPullRequestReviewEvent(reviewCommentContext)).toBe(false);
});
test("isPullRequestReviewCommentEvent accepts only review comment events", () => {
expect(isPullRequestReviewCommentEvent(reviewCommentContext)).toBe(true);
expect(isPullRequestReviewCommentEvent(reviewContext)).toBe(false);
});
test("isIssuesAssignedEvent requires issues event with assigned action", () => {
const assignedContext = createMockContext({
eventName: "issues",
eventAction: "assigned",
});
const openedContext = createMockContext({
eventName: "issues",
eventAction: "opened",
});
const assignedCommentContext = createMockContext({
eventName: "issue_comment",
eventAction: "assigned",
});
expect(isIssuesAssignedEvent(assignedContext)).toBe(true);
expect(isIssuesAssignedEvent(openedContext)).toBe(false);
expect(isIssuesAssignedEvent(assignedCommentContext)).toBe(false);
});
test("isEntityContext accepts the five entity events", () => {
expect(isEntityContext(issuesContext)).toBe(true);
expect(isEntityContext(issueCommentContext)).toBe(true);
expect(isEntityContext(pullRequestContext)).toBe(true);
expect(isEntityContext(reviewContext)).toBe(true);
expect(isEntityContext(reviewCommentContext)).toBe(true);
expect(isEntityContext(workflowDispatchContext)).toBe(false);
});
test("isAutomationContext accepts the four automation events", () => {
expect(isAutomationContext(workflowDispatchContext)).toBe(true);
expect(
isAutomationContext(
createMockAutomationContext({ eventName: "repository_dispatch" }),
),
).toBe(true);
expect(
isAutomationContext(
createMockAutomationContext({ eventName: "schedule" }),
),
).toBe(true);
expect(
isAutomationContext(
createMockAutomationContext({ eventName: "workflow_run" }),
),
).toBe(true);
expect(isAutomationContext(issuesContext)).toBe(false);
});
});

View File

@ -158,55 +158,6 @@ describe("downloadCommentImages", () => {
); );
}); });
test("should save a JPEG from an extensionless URL with a .jpg extension", async () => {
// Regression for the case where a JPEG screenshot is pasted into an issue.
// GitHub serves it from /user-attachments/assets/<uuid> (no extension), so
// 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";
// @ts-expect-error Mock implementation doesn't match full type signature
mockOctokit.rest.issues.get = jest.fn().mockResolvedValue({
data: {
body_html: `<img src="${signedUrl}">`,
},
});
// JPEG magic bytes: FF D8 FF, then arbitrary padding.
const jpegBytes = new Uint8Array([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10]);
fetchSpy = spyOn(global, "fetch").mockResolvedValue({
ok: true,
arrayBuffer: async () => jpegBytes.buffer,
} as Response);
const comments: CommentWithImages[] = [
{
type: "issue_body",
issueNumber: "143",
body: `![Screenshot_20260607_204205_Chrome.jpg](${imageUrl})`,
},
];
const result = await downloadCommentImages(
mockOctokit,
"owner",
"repo",
comments,
);
expect(fsWriteFileSpy).toHaveBeenCalledWith(
"/tmp/github-images/image-1704067200000-0.jpg",
Buffer.from(jpegBytes.buffer),
);
expect(result.get(imageUrl)).toBe(
"/tmp/github-images/image-1704067200000-0.jpg",
);
});
test("should handle review comments", async () => { test("should handle review comments", async () => {
const mockOctokit = createMockOctokit(); const mockOctokit = createMockOctokit();
const imageUrl = const imageUrl =

View File

@ -1,139 +0,0 @@
import { describe, it, expect, beforeEach, afterEach } from "bun:test";
import {
existsSync,
mkdtempSync,
readFileSync,
rmSync,
writeFileSync,
} from "fs";
import { tmpdir } from "os";
import { join } from "path";
import { removeBufferedComment } from "../src/mcp/inline-comment-buffer";
describe("removeBufferedComment", () => {
let dir: string;
let bufferPath: string;
const entryA = {
ts: "2026-06-13T00:00:00.000Z",
path: "src/index.ts",
line: 10,
startLine: undefined,
side: "RIGHT",
body: "Comment A",
};
const entryB = {
ts: "2026-06-13T00:00:01.000Z",
path: "src/other.ts",
line: 20,
startLine: undefined,
side: "RIGHT",
body: "Comment B",
};
const writeBuffer = (entries: object[]): void => {
writeFileSync(
bufferPath,
entries.map((e) => JSON.stringify(e)).join("\n") + "\n",
);
};
const readBuffer = (): Array<{ body: string }> => {
if (!existsSync(bufferPath)) {
return [];
}
return readFileSync(bufferPath, "utf8")
.split("\n")
.filter((line) => line.trim() !== "")
.map((line) => JSON.parse(line));
};
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "inline-buffer-"));
bufferPath = join(dir, "buffer.jsonl");
});
afterEach(() => {
rmSync(dir, { recursive: true, force: true });
});
it("removes the matching buffered entry and keeps the others", () => {
writeBuffer([entryA, entryB]);
removeBufferedComment(
{
path: "src/index.ts",
line: 10,
startLine: undefined,
body: "Comment A",
},
bufferPath,
);
const remaining = readBuffer();
expect(remaining.map((e) => e.body)).toEqual(["Comment B"]);
});
it("removes every copy when the same comment was buffered more than once", () => {
writeBuffer([entryA, entryA, entryB]);
removeBufferedComment(
{
path: "src/index.ts",
line: 10,
startLine: undefined,
body: "Comment A",
},
bufferPath,
);
expect(readBuffer().map((e) => e.body)).toEqual(["Comment B"]);
});
it("leaves the buffer untouched when nothing matches", () => {
writeBuffer([entryA, entryB]);
removeBufferedComment(
{
path: "src/index.ts",
line: 999,
startLine: undefined,
body: "Comment A",
},
bufferPath,
);
expect(readBuffer().map((e) => e.body)).toEqual(["Comment A", "Comment B"]);
});
it("does nothing when the buffer file does not exist", () => {
expect(() =>
removeBufferedComment(
{ path: "src/index.ts", line: 10, body: "Comment A" },
bufferPath,
),
).not.toThrow();
expect(existsSync(bufferPath)).toBe(false);
});
it("keeps lines that cannot be parsed as JSON", () => {
writeFileSync(
bufferPath,
["not json", JSON.stringify(entryA)].join("\n") + "\n",
);
removeBufferedComment(
{
path: "src/index.ts",
line: 10,
startLine: undefined,
body: "Comment A",
},
bufferPath,
);
const raw = readFileSync(bufferPath, "utf8");
expect(raw).toContain("not json");
expect(raw).not.toContain("Comment A");
});
});

View File

@ -1,50 +0,0 @@
import { describe, it, expect } from "bun:test";
import { spawnSync } from "child_process";
import { buildInstallCommand } from "../src/entrypoints/run";
describe("buildInstallCommand (regression for #1136)", () => {
it("includes the pinned claude version in the bash -s args", () => {
const cmd = buildInstallCommand("2.1.114");
expect(cmd).toContain("bash -s -- 2.1.114");
});
it("prefixes the pipeline with `set -o pipefail`", () => {
const cmd = buildInstallCommand("2.1.114");
expect(cmd.startsWith("set -o pipefail;")).toBe(true);
});
it("keeps the curl -fsSL flags so the script is fetched, not inlined", () => {
const cmd = buildInstallCommand("2.1.114");
expect(cmd).toContain(
"curl -fsSL https://claude.ai/install.sh | bash -s --",
);
});
});
describe("pipefail semantics (proves the bug shape and the fix)", () => {
// Mirrors the real install invocation: a curl that returns non-zero
// feeding into `bash -s --`. Without pipefail, the pipeline exits 0
// because bash -s receives an empty stdin and does nothing. With
// pipefail, curl's exit code wins and the retry loop in run.ts triggers.
//
// Uses port 1 (reserved/unused) so curl fails deterministically with no
// network access. No shell-escaping traps here: the version argument is
// a numeric literal.
const unreachable = "http://127.0.0.1:1/nope";
const version = "2.1.114";
it("BEFORE FIX: pipeline without pipefail swallows curl failure (exit 0)", () => {
const buggy = `curl -fsSL ${unreachable} | bash -s -- ${version}`;
const result = spawnSync("bash", ["-c", buggy], { stdio: "pipe" });
expect(result.status).toBe(0);
});
it("AFTER FIX: buildInstallCommand (against unreachable host) exits non-zero", () => {
const fixed = buildInstallCommand(version).replace(
"https://claude.ai/install.sh",
unreachable,
);
const result = spawnSync("bash", ["-c", fixed], { stdio: "pipe" });
expect(result.status).not.toBe(0);
});
});

View File

@ -37,43 +37,9 @@ describe("parseAllowedTools", () => {
test("handles --allowedTools followed by another --allowedTools flag", () => { test("handles --allowedTools followed by another --allowedTools flag", () => {
const args = "--allowedTools --allowedTools mcp__github__*"; const args = "--allowedTools --allowedTools mcp__github__*";
// The first --allowedTools has no value (the next token is another flag); // The second --allowedTools is consumed as a value of the first, then skipped.
// the second consumes mcp__github__*. This matches how the SDK option // This is an edge case with malformed input - returns empty.
// parser (parse-sdk-options.ts) reads the same input. expect(parseAllowedTools(args)).toEqual([]);
expect(parseAllowedTools(args)).toEqual(["mcp__github__*"]);
});
test("captures multiple values after a single --allowedTools flag", () => {
// Regression for #1357: the install-decision parser must capture every
// value, not just the first, so it agrees with the tools actually granted
// to Claude. Previously only "Read" was seen, so the github MCP server was
// not installed even though mcp__github__get_commit was granted.
const args = '--allowedTools "Read" "Grep" "mcp__github__get_commit"';
expect(parseAllowedTools(args)).toEqual([
"Read",
"Grep",
"mcp__github__get_commit",
]);
});
test("captures multiple values spread across lines under one flag", () => {
const args = `--allowedTools
"Read"
"Grep"
"mcp__github__get_commit"`;
expect(parseAllowedTools(args)).toEqual([
"Read",
"Grep",
"mcp__github__get_commit",
]);
});
test("ignores commented-out lines", () => {
// Regression for #1357: a commented-out flag must not be counted, matching
// the SDK parser which strips comment lines before parsing.
const args = `# --allowedTools "mcp__github__get_commit"
--allowedTools "Read"`;
expect(parseAllowedTools(args)).toEqual(["Read"]);
}); });
test("parses multiple separate --allowed-tools flags", () => { test("parses multiple separate --allowed-tools flags", () => {

View File

@ -2,12 +2,10 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { execFileSync } from "child_process"; import { execFileSync } from "child_process";
import { import {
existsSync, existsSync,
lstatSync,
mkdtempSync, mkdtempSync,
mkdirSync, mkdirSync,
readFileSync, readFileSync,
rmSync, rmSync,
symlinkSync,
writeFileSync, writeFileSync,
} from "fs"; } from "fs";
import { dirname, isAbsolute, join } from "path"; import { dirname, isAbsolute, join } from "path";
@ -123,48 +121,6 @@ describe("restoreConfigFromBase", () => {
} }
}); });
test("restores symlinked CLAUDE.md paths from the PR base branch", () => {
setupSymlinkedMainBranch();
git(["checkout", "pr"]);
writeRepoFile(
".claude/settings.json",
`${JSON.stringify({ source: "pr-with-symlinks" })}\n`,
);
git(["add", ".claude/settings.json"]);
git(["commit", "-m", "pr updates settings"]);
restoreConfigFromBase("main");
expect(lstatRepoFile("CLAUDE.md").isSymbolicLink()).toBe(true);
expect(lstatRepoFile(".claude/CLAUDE.md").isSymbolicLink()).toBe(true);
expect(readRepoFile("CLAUDE.md").trim()).toBe("shared agent instructions");
expect(readRepoFile(".claude/CLAUDE.md").trim()).toBe(
"shared agent instructions",
);
expect(readRepoFile(".claude/settings.json")).toBe(
`${JSON.stringify({ source: "base" })}\n`,
);
});
test("snapshots symlinked sensitive paths even when the PR head target is missing", () => {
setupSymlinkedMainBranch();
git(["checkout", "pr"]);
rmSync(join(repoDir, "AGENTS.md"), { force: true });
git(["add", "-A"]);
git(["commit", "-m", "pr deletes agents file"]);
restoreConfigFromBase("main");
expect(lstatRepoFile(".claude-pr/.claude/CLAUDE.md").isSymbolicLink()).toBe(
true,
);
expect(readRepoFile(".claude/settings.json")).toBe(
`${JSON.stringify({ source: "base" })}\n`,
);
});
test("does not modify an existing .gitignore", () => { test("does not modify an existing .gitignore", () => {
writeRepoFile(".gitignore", "node_modules\n"); writeRepoFile(".gitignore", "node_modules\n");
git(["add", ".gitignore"]); git(["add", ".gitignore"]);
@ -200,29 +156,6 @@ describe("restoreConfigFromBase", () => {
return existsSync(join(repoDir, path)); return existsSync(join(repoDir, path));
} }
function symlinkRepoFile(path: string, target: string): void {
const fullPath = join(repoDir, path);
mkdirSync(dirname(fullPath), { recursive: true });
symlinkSync(target, fullPath);
}
function lstatRepoFile(path: string) {
return lstatSync(join(repoDir, path));
}
function setupSymlinkedMainBranch(): void {
git(["checkout", "main"]);
rmSync(join(repoDir, "CLAUDE.md"), { force: true });
writeRepoFile("AGENTS.md", "shared agent instructions\n");
symlinkRepoFile("CLAUDE.md", "AGENTS.md");
symlinkRepoFile(".claude/CLAUDE.md", "../AGENTS.md");
git(["add", "AGENTS.md", "CLAUDE.md", ".claude/CLAUDE.md"]);
git(["commit", "-m", "add symlinked claude files"]);
git(["push", "origin", "main"]);
git(["branch", "-D", "pr"]);
git(["checkout", "-b", "pr"]);
}
function countClaudePrExcludeEntries(): number { function countClaudePrExcludeEntries(): number {
return readFileSync(getExcludePath(), "utf8") return readFileSync(getExcludePath(), "utf8")
.split(/\r?\n/) .split(/\r?\n/)

View File

@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach, afterEach, mock } from "bun:test"; import { describe, it, expect, beforeEach, afterEach, mock } from "bun:test";
import { retryWithBackoff } from "../src/retry"; import { retryWithBackoff } from "../src/utils/retry";
describe("retryWithBackoff", () => { describe("retryWithBackoff", () => {
let originalConsoleLog: typeof console.log; let originalConsoleLog: typeof console.log;

View File

@ -59,22 +59,6 @@ describe("stripMarkdownImageAltText", () => {
it("should handle empty alt text", () => { it("should handle empty alt text", () => {
expect(stripMarkdownImageAltText("![](image.png)")).toBe("![](image.png)"); expect(stripMarkdownImageAltText("![](image.png)")).toBe("![](image.png)");
}); });
it("should remove alt text from reference-style images", () => {
expect(stripMarkdownImageAltText("![example alt text][img1]")).toBe(
"![][img1]",
);
expect(
stripMarkdownImageAltText("Text ![description][ref] more text"),
).toBe("Text ![][ref] more text");
});
it("should preserve the reference label of a reference-style image", () => {
// the [ref] label must survive so the image definition still resolves;
// only the alt text (the injection channel) is removed
expect(stripMarkdownImageAltText("![alt][my-ref]")).toBe("![][my-ref]");
expect(stripMarkdownImageAltText("![][keep]")).toBe("![][keep]");
});
}); });
describe("stripMarkdownLinkTitles", () => { describe("stripMarkdownLinkTitles", () => {
@ -147,21 +131,6 @@ describe("stripHiddenAttributes", () => {
), ),
).toBe('<img src="pic.jpg" class="image">'); ).toBe('<img src="pic.jpg" class="image">');
}); });
it("should not corrupt content when an attribute value contains the other quote type", () => {
// Regression for #1366: an apostrophe inside a double-quoted attribute
// (or a double quote inside a single-quoted attribute) must not cause the
// closing quote to be mismatched, which previously mangled later text.
expect(
stripHiddenAttributes(`<Tooltip title="We'll do it" placement="top">`),
).toBe('<Tooltip placement="top">');
expect(
stripHiddenAttributes(`<img alt="Bob's avatar" src="pic.jpg">`),
).toBe('<img src="pic.jpg">');
expect(stripHiddenAttributes(`<div title='say "hi"'>Content</div>`)).toBe(
"<div>Content</div>",
);
});
}); });
describe("normalizeHtmlEntities", () => { describe("normalizeHtmlEntities", () => {
@ -292,16 +261,6 @@ describe("redactGitHubTokens", () => {
); );
}); });
it("should redact user-to-server tokens (ghu_)", () => {
const token = "ghu_16C7e42F292c6912E7710c838347Ae178B4a";
expect(redactGitHubTokens(`User token: ${token}`)).toBe(
"User token: [REDACTED_GITHUB_TOKEN]",
);
expect(
redactGitHubTokens(`In a URL: x-access-token:${token}@github.com`),
).toBe("In a URL: x-access-token:[REDACTED_GITHUB_TOKEN]@github.com");
});
it("should redact installation tokens (ghs_)", () => { it("should redact installation tokens (ghs_)", () => {
const token = "ghs_xz7yzju2SZjGPa0dUNMAx0SH4xDOCS31LXQW"; const token = "ghs_xz7yzju2SZjGPa0dUNMAx0SH4xDOCS31LXQW";
expect(redactGitHubTokens(`Install token: ${token}`)).toBe( expect(redactGitHubTokens(`Install token: ${token}`)).toBe(

View File

@ -1,164 +0,0 @@
import { describe, expect, test, beforeEach, afterEach, spyOn } from "bun:test";
import * as core from "@actions/core";
import {
setupGitHubToken,
WorkflowValidationSkipError,
} from "../src/github/token";
describe("setupGitHubToken", () => {
let originalOverrideToken: string | undefined;
let originalAdditionalPermissions: string | undefined;
let getIDTokenSpy: any;
let setSecretSpy: any;
let warningSpy: any;
let fetchSpy: any;
let setTimeoutSpy: any;
let consoleLogSpy: any;
let consoleErrorSpy: any;
beforeEach(() => {
originalOverrideToken = process.env.OVERRIDE_GITHUB_TOKEN;
originalAdditionalPermissions = process.env.ADDITIONAL_PERMISSIONS;
delete process.env.OVERRIDE_GITHUB_TOKEN;
delete process.env.ADDITIONAL_PERMISSIONS;
getIDTokenSpy = spyOn(core, "getIDToken").mockResolvedValue("oidc-token");
setSecretSpy = spyOn(core, "setSecret").mockImplementation(() => {});
warningSpy = spyOn(core, "warning").mockImplementation(() => {});
fetchSpy = spyOn(global, "fetch").mockResolvedValue(
new Response(JSON.stringify({ token: "app-token" }), {
status: 200,
statusText: "OK",
}),
);
setTimeoutSpy = spyOn(global, "setTimeout").mockImplementation(((
handler: any,
) => {
handler();
return 0 as any;
}) as any);
consoleLogSpy = spyOn(console, "log").mockImplementation(() => {});
consoleErrorSpy = spyOn(console, "error").mockImplementation(() => {});
});
afterEach(() => {
if (originalOverrideToken === undefined) {
delete process.env.OVERRIDE_GITHUB_TOKEN;
} else {
process.env.OVERRIDE_GITHUB_TOKEN = originalOverrideToken;
}
if (originalAdditionalPermissions === undefined) {
delete process.env.ADDITIONAL_PERMISSIONS;
} else {
process.env.ADDITIONAL_PERMISSIONS = originalAdditionalPermissions;
}
getIDTokenSpy.mockRestore();
setSecretSpy.mockRestore();
warningSpy.mockRestore();
fetchSpy.mockRestore();
setTimeoutSpy.mockRestore();
consoleLogSpy.mockRestore();
consoleErrorSpy.mockRestore();
});
test("returns app token from OIDC exchange", async () => {
await expect(setupGitHubToken()).resolves.toBe("app-token");
expect(getIDTokenSpy).toHaveBeenCalledWith("claude-code-github-action");
expect(setSecretSpy).toHaveBeenCalledWith("app-token");
});
test("skips without retrying when workflow is missing from default branch", async () => {
const message =
"Workflow validation failed. The workflow file must exist and have identical content to the version on the repository's default branch.";
fetchSpy.mockResolvedValue(
new Response(
JSON.stringify({
error: {
message,
details: {
error_code: "workflow_not_found_on_default_branch",
},
},
}),
{ status: 401, statusText: "Unauthorized" },
),
);
await expect(setupGitHubToken()).rejects.toBeInstanceOf(
WorkflowValidationSkipError,
);
expect(fetchSpy).toHaveBeenCalledTimes(1);
expect(warningSpy).toHaveBeenCalledWith(
`Skipping action due to workflow validation: ${message}`,
);
});
test("skips without retrying when workflow validation message has no error code", async () => {
const message =
"Workflow validation failed. The workflow file must exist and have identical content to the version on the repository's default branch.";
fetchSpy.mockResolvedValue(
new Response(
JSON.stringify({
error: {
message,
},
}),
{ status: 401, statusText: "Unauthorized" },
),
);
await expect(setupGitHubToken()).rejects.toBeInstanceOf(
WorkflowValidationSkipError,
);
expect(fetchSpy).toHaveBeenCalledTimes(1);
expect(warningSpy).toHaveBeenCalledWith(
`Skipping action due to workflow validation: ${message}`,
);
});
test("retries ordinary token exchange errors instead of skipping", async () => {
const message = "Bad credentials";
fetchSpy.mockImplementation(
async () =>
new Response(
JSON.stringify({
error: {
message,
},
}),
{ status: 401, statusText: "Unauthorized" },
),
);
await expect(setupGitHubToken()).rejects.toThrow(message);
expect(fetchSpy).toHaveBeenCalledTimes(3);
expect(warningSpy).not.toHaveBeenCalled();
});
test("does not skip message-only workflow validation errors with unexpected status", async () => {
const message =
"Workflow validation failed. The workflow file must exist and have identical content to the version on the repository's default branch.";
fetchSpy.mockImplementation(
async () =>
new Response(
JSON.stringify({
error: {
message,
},
}),
{ status: 500, statusText: "Internal Server Error" },
),
);
await expect(setupGitHubToken()).rejects.toThrow(message);
expect(fetchSpy).toHaveBeenCalledTimes(3);
expect(warningSpy).not.toHaveBeenCalled();
});
});

View File

@ -64,26 +64,6 @@ describe("validateBranchName", () => {
expect(() => validateBranchName("feature/paris,france")).not.toThrow(); expect(() => validateBranchName("feature/paris,france")).not.toThrow();
expect(() => validateBranchName("fix/issue-1,2,3")).not.toThrow(); expect(() => validateBranchName("fix/issue-1,2,3")).not.toThrow();
}); });
it("should accept branch names containing @ (git-valid, used in team and tooling conventions)", () => {
// Reported in #998: branches like "TICKET-123@add-feature" were rejected, even
// though git check-ref-format and GitHub both accept @ anywhere in a ref name.
// Also common as a leading prefix (e.g. "@hotfix/...") and in agent-generated
// names ("task@sessionid"). Bare "@" and "@{" are still rejected.
expect(() => validateBranchName("TICKET-123@add-feature")).not.toThrow();
expect(() => validateBranchName("@hotfix/login-timeout")).not.toThrow();
expect(() => validateBranchName("agent/task@abc123")).not.toThrow();
});
it("should accept branch names starting with underscore (git-valid, common for release branches)", () => {
// Leading underscores are valid per git check-ref-format and a common
// convention for release/internal branches. Rejecting them broke the
// action on any open PR whose base branch was e.g. "_release/v1.2.3",
// since setupBranch validates the PR's baseRefName after checkout.
expect(() => validateBranchName("_release/v1.2.3")).not.toThrow();
expect(() => validateBranchName("_internal")).not.toThrow();
expect(() => validateBranchName("_wip/feature-x")).not.toThrow();
});
}); });
describe("command injection attempts", () => { describe("command injection attempts", () => {
@ -157,12 +137,6 @@ describe("validateBranchName", () => {
expect(() => validateBranchName("HEAD@{yesterday}")).toThrow(/@{/); expect(() => validateBranchName("HEAD@{yesterday}")).toThrow(/@{/);
}); });
it("should reject the single character @", () => {
// Per git-check-ref-format, a refname cannot be the single character "@";
// "@" also resolves to HEAD in git revision syntax.
expect(() => validateBranchName("@")).toThrow(/single character '@'/);
});
it("should reject .lock suffix", () => { it("should reject .lock suffix", () => {
expect(() => validateBranchName("branch.lock")).toThrow(/\.lock/); expect(() => validateBranchName("branch.lock")).toThrow(/\.lock/);
expect(() => validateBranchName("feature.lock")).toThrow(/\.lock/); expect(() => validateBranchName("feature.lock")).toThrow(/\.lock/);