mirror of
https://github.com/anthropics/claude-code-action.git
synced 2026-11-22 21:59:37 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
51705da45e | ||
|
|
806af32823 | ||
|
|
0a08a86780 | ||
|
|
9dd8b95a39 | ||
|
|
4d7e1f0cd8 | ||
|
|
3d9f0dc7dc | ||
|
|
a5e5d3b82e | ||
|
|
d5726de019 | ||
|
|
56fa348258 | ||
|
|
82d95d45af | ||
|
|
0cb4f3e5e7 | ||
|
|
8551f4b0aa | ||
|
|
eba921ff6f | ||
|
|
36617bd48b | ||
|
|
24b915648e | ||
|
|
9441a7fe22 | ||
|
|
b371255139 | ||
|
|
84d317e8f9 | ||
|
|
cd59d5df0d | ||
|
|
8046d850b5 | ||
|
|
ee2b19d882 | ||
|
|
ebcdfe6dc6 | ||
|
|
0f97b95b65 | ||
|
|
eee73e2ae5 | ||
|
|
232c9a15f4 | ||
|
|
11ba60486e | ||
|
|
593d7a5c4e | ||
|
|
fbda2eb1bd | ||
|
|
64de744025 | ||
|
|
410165836e | ||
|
|
41ea7642c1 | ||
|
|
0b1b620029 | ||
|
|
70a6e5256e | ||
|
|
36a69b6a90 | ||
|
|
bfad70d6a1 | ||
|
|
dc081a3809 | ||
|
|
420335da51 | ||
|
|
7f37f2e373 | ||
|
|
fb53c379a0 | ||
|
|
c5c315c8a1 | ||
|
|
f809dea0ba | ||
|
|
0fb1b8f303 | ||
|
|
3d4c9fde8e | ||
|
|
324957b26b | ||
|
|
73c91f04a8 | ||
|
|
787c5a0ce9 | ||
|
|
4257c8e059 | ||
|
|
bbfaf8e1ff |
@@ -0,0 +1,162 @@
|
||||
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 };
|
||||
@@ -11,6 +11,9 @@ on:
|
||||
|
||||
permissions:
|
||||
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:
|
||||
ci:
|
||||
@@ -18,20 +21,15 @@ jobs:
|
||||
|
||||
test-base-action:
|
||||
uses: ./.github/workflows/test-base-action.yml
|
||||
secrets: inherit # Required for ANTHROPIC_API_KEY
|
||||
|
||||
test-custom-executables:
|
||||
uses: ./.github/workflows/test-custom-executables.yml
|
||||
secrets: inherit
|
||||
|
||||
test-mcp-servers:
|
||||
uses: ./.github/workflows/test-mcp-servers.yml
|
||||
secrets: inherit
|
||||
|
||||
test-settings:
|
||||
uses: ./.github/workflows/test-settings.yml
|
||||
secrets: inherit
|
||||
|
||||
test-structured-output:
|
||||
uses: ./.github/workflows/test-structured-output.yml
|
||||
secrets: inherit
|
||||
|
||||
@@ -20,7 +20,12 @@ jobs:
|
||||
- name: PR Review with Progress Tracking
|
||||
uses: anthropics/claude-code-action@v1
|
||||
with:
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
# Authenticate to the Claude API via Workload Identity Federation
|
||||
# (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 }}"
|
||||
claude_args: |
|
||||
|
||||
@@ -33,7 +33,12 @@ jobs:
|
||||
id: claude
|
||||
uses: anthropics/claude-code-action@main
|
||||
with:
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
# Authenticate to the Claude API via Workload Identity Federation
|
||||
# (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: |
|
||||
--allowedTools "Bash(bun install),Bash(bun test:*),Bash(bun run format),Bash(bun typecheck)"
|
||||
--model "claude-opus-4-7"
|
||||
|
||||
@@ -11,6 +11,9 @@ jobs:
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
# Required to mint the OIDC token that is exchanged for a Claude API
|
||||
# access token (Workload Identity Federation).
|
||||
id-token: write
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
@@ -24,6 +27,11 @@ jobs:
|
||||
CLAUDE_CODE_SCRIPT_CAPS: '{"edit-issue-labels.sh":2}'
|
||||
with:
|
||||
prompt: "/label-issue REPO: ${{ github.repository }} ISSUE_NUMBER: ${{ github.event.issue.number }}"
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
# Authenticate to the Claude API via Workload Identity Federation
|
||||
# (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
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
@@ -19,7 +19,7 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout source repository
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
|
||||
@@ -10,18 +10,27 @@ on:
|
||||
default: "List the files in the current directory starting with 'package'"
|
||||
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:
|
||||
test-inline-prompt:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Test with inline prompt
|
||||
id: inline-test
|
||||
uses: ./base-action
|
||||
with:
|
||||
prompt: ${{ github.event.inputs.test_prompt || 'List the files in the current directory starting with "package"' }}
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
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_tools: "LS,Read"
|
||||
|
||||
- name: Verify inline prompt output
|
||||
@@ -63,7 +72,7 @@ jobs:
|
||||
test-prompt-file:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Create test prompt file
|
||||
run: |
|
||||
@@ -78,7 +87,9 @@ jobs:
|
||||
uses: ./base-action
|
||||
with:
|
||||
prompt_file: "test-prompt.txt"
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
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_tools: "LS,Read"
|
||||
|
||||
- name: Verify prompt file output
|
||||
|
||||
@@ -5,11 +5,18 @@ on:
|
||||
workflow_dispatch:
|
||||
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:
|
||||
test-custom-executables:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Install Bun manually
|
||||
run: |
|
||||
@@ -47,7 +54,9 @@ jobs:
|
||||
with:
|
||||
prompt: |
|
||||
List the files in the current directory starting with "package"
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
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 }}
|
||||
path_to_claude_code_executable: /home/runner/.local/bin/claude
|
||||
path_to_bun_executable: /home/runner/.bun/bin/bun
|
||||
allowed_tools: "LS,Read"
|
||||
|
||||
@@ -5,15 +5,22 @@ on:
|
||||
workflow_dispatch:
|
||||
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:
|
||||
test-mcp-integration:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 #v4
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@735343b667d3e6f658f44d0eca948eb6282f2b76 #v2
|
||||
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
@@ -25,8 +32,11 @@ jobs:
|
||||
uses: ./base-action
|
||||
id: claude-test
|
||||
with:
|
||||
prompt: "List all available tools"
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
prompt: "Call the test_tool tool and report its response."
|
||||
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: --allowedTools mcp__test-server__test_tool
|
||||
env:
|
||||
# Change to test directory so it finds .mcp.json
|
||||
CLAUDE_WORKING_DIR: ${{ github.workspace }}/base-action/test/mcp-test
|
||||
@@ -50,21 +60,29 @@ jobs:
|
||||
if jq -e '.[] | select(.type == "system" and .subtype == "init") | .mcp_servers' "$OUTPUT_FILE" > /dev/null; then
|
||||
echo "✓ Found mcp_servers in output"
|
||||
|
||||
# Check if test-server is connected
|
||||
if jq -e '.[] | select(.type == "system" and .subtype == "init") | .mcp_servers[] | select(.name == "test-server" and .status == "connected")' "$OUTPUT_FILE" > /dev/null; then
|
||||
echo "✓ test-server is connected"
|
||||
# MCP servers can connect asynchronously, so the init event may
|
||||
# report the server as pending — check registration there, then
|
||||
# verify the tool actually ran.
|
||||
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
|
||||
echo "✗ test-server not found or not connected"
|
||||
echo "✗ test-server not found"
|
||||
jq '.[] | select(.type == "system" and .subtype == "init") | .mcp_servers' "$OUTPUT_FILE"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check if mcp tools are available
|
||||
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"
|
||||
|
||||
if jq -e '.[] | select(.type == "assistant") | .message.content[]? | select(.type == "tool_use" and .name == "mcp__test-server__test_tool")' "$OUTPUT_FILE" > /dev/null; then
|
||||
echo "✓ MCP test tool was called"
|
||||
else
|
||||
echo "✗ MCP test tool not found"
|
||||
jq '.[] | select(.type == "system" and .subtype == "init") | .tools' "$OUTPUT_FILE"
|
||||
echo "✗ MCP test tool was not called"
|
||||
jq '[.[] | select(.type == "assistant") | .message.content[]? | select(.type == "tool_use") | .name]' "$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
|
||||
fi
|
||||
else
|
||||
@@ -79,10 +97,10 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 #v4
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@735343b667d3e6f658f44d0eca948eb6282f2b76 #v2
|
||||
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
@@ -106,9 +124,13 @@ jobs:
|
||||
uses: ./base-action
|
||||
id: claude-config-test
|
||||
with:
|
||||
prompt: "List all available tools"
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
mcp_config: '{"mcpServers":{"test-server":{"type":"stdio","command":"bun","args":["simple-mcp-server.ts"],"env":{}}}}'
|
||||
prompt: "Call the test_tool tool and report its response."
|
||||
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: |
|
||||
--allowedTools mcp__test-server__test_tool
|
||||
--mcp-config '{"mcpServers":{"test-server":{"type":"stdio","command":"bun","args":["simple-mcp-server.ts"],"env":{}}}}'
|
||||
env:
|
||||
# Change to test directory so bun can find the MCP server script
|
||||
CLAUDE_WORKING_DIR: ${{ github.workspace }}/base-action/test/mcp-test
|
||||
@@ -132,21 +154,29 @@ jobs:
|
||||
if jq -e '.[] | select(.type == "system" and .subtype == "init") | .mcp_servers' "$OUTPUT_FILE" > /dev/null; then
|
||||
echo "✓ Found mcp_servers in output"
|
||||
|
||||
# Check if test-server is connected
|
||||
if jq -e '.[] | select(.type == "system" and .subtype == "init") | .mcp_servers[] | select(.name == "test-server" and .status == "connected")' "$OUTPUT_FILE" > /dev/null; then
|
||||
echo "✓ test-server is connected"
|
||||
# MCP servers can connect asynchronously, so the init event may
|
||||
# report the server as pending — check registration there, then
|
||||
# verify the tool actually ran.
|
||||
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
|
||||
echo "✗ test-server not found or not connected"
|
||||
echo "✗ test-server not found"
|
||||
jq '.[] | select(.type == "system" and .subtype == "init") | .mcp_servers' "$OUTPUT_FILE"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Check if mcp tools are available
|
||||
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"
|
||||
|
||||
if jq -e '.[] | select(.type == "assistant") | .message.content[]? | select(.type == "tool_use" and .name == "mcp__test-server__test_tool")' "$OUTPUT_FILE" > /dev/null; then
|
||||
echo "✓ MCP test tool was called"
|
||||
else
|
||||
echo "✗ MCP test tool not found"
|
||||
jq '.[] | select(.type == "system" and .subtype == "init") | .tools' "$OUTPUT_FILE"
|
||||
echo "✗ MCP test tool was not called"
|
||||
jq '[.[] | select(.type == "assistant") | .message.content[]? | select(.type == "tool_use") | .name]' "$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
|
||||
fi
|
||||
else
|
||||
|
||||
@@ -5,11 +5,18 @@ on:
|
||||
workflow_dispatch:
|
||||
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:
|
||||
test-settings-inline-allow:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Test with inline settings JSON (echo allowed)
|
||||
id: inline-settings-test
|
||||
@@ -17,7 +24,9 @@ jobs:
|
||||
with:
|
||||
prompt: |
|
||||
Use Bash to echo "Hello from settings test"
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
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 }}
|
||||
settings: |
|
||||
{
|
||||
"permissions": {
|
||||
@@ -58,7 +67,7 @@ jobs:
|
||||
test-settings-inline-deny:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Test with inline settings JSON (echo denied)
|
||||
id: inline-settings-test
|
||||
@@ -66,7 +75,9 @@ jobs:
|
||||
with:
|
||||
prompt: |
|
||||
Run the command `echo $HOME` to check the home directory path
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
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 }}
|
||||
settings: |
|
||||
{
|
||||
"permissions": {
|
||||
@@ -90,7 +101,7 @@ jobs:
|
||||
test-settings-file-allow:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Create settings file (echo allowed)
|
||||
run: |
|
||||
@@ -108,7 +119,9 @@ jobs:
|
||||
with:
|
||||
prompt: |
|
||||
Use Bash to echo "Hello from settings file test"
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
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 }}
|
||||
settings: "test-settings.json"
|
||||
|
||||
- name: Verify echo worked
|
||||
@@ -144,7 +157,7 @@ jobs:
|
||||
test-settings-file-deny:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Create settings file (echo denied)
|
||||
run: |
|
||||
@@ -162,7 +175,9 @@ jobs:
|
||||
with:
|
||||
prompt: |
|
||||
Run the command `echo $HOME` to check the home directory path
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
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 }}
|
||||
settings: "test-settings.json"
|
||||
|
||||
- name: Verify echo was denied
|
||||
|
||||
@@ -5,8 +5,12 @@ on:
|
||||
workflow_dispatch:
|
||||
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:
|
||||
test-basic-types:
|
||||
@@ -14,7 +18,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Test with explicit values
|
||||
id: test
|
||||
@@ -28,7 +32,9 @@ jobs:
|
||||
- number_field: 42
|
||||
- boolean_true: true
|
||||
- boolean_false: false
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
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: |
|
||||
--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"]}'
|
||||
@@ -73,7 +79,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Test complex types
|
||||
id: test
|
||||
@@ -86,7 +92,9 @@ jobs:
|
||||
- items: ["apple", "banana", "cherry"]
|
||||
- config: {"key": "value", "count": 3}
|
||||
- empty_array: []
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
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: |
|
||||
--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"]}'
|
||||
@@ -124,7 +132,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Test edge cases
|
||||
id: test
|
||||
@@ -138,7 +146,9 @@ jobs:
|
||||
- empty_string: ""
|
||||
- negative: -5
|
||||
- decimal: 3.14
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
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: |
|
||||
--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"]}'
|
||||
@@ -183,7 +193,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Test special characters in field names
|
||||
id: test
|
||||
@@ -192,7 +202,9 @@ jobs:
|
||||
prompt: |
|
||||
Run: echo "test"
|
||||
Return EXACTLY: {test-result: "passed", item_count: 10}
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
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: |
|
||||
--allowedTools Bash
|
||||
--json-schema '{"type":"object","properties":{"test-result":{"type":"string"},"item_count":{"type":"number"}},"required":["test-result","item_count"]}'
|
||||
@@ -223,14 +235,16 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Run with structured output
|
||||
id: test
|
||||
uses: ./base-action
|
||||
with:
|
||||
prompt: "Run: echo 'complete'. Return: {done: true}"
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
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: |
|
||||
--allowedTools Bash
|
||||
--json-schema '{"type":"object","properties":{"done":{"type":"boolean"}},"required":["done"]}'
|
||||
|
||||
+21
-7
@@ -187,6 +187,7 @@ runs:
|
||||
using: "composite"
|
||||
steps:
|
||||
- name: Install Bun
|
||||
id: setup-bun
|
||||
if: inputs.path_to_bun_executable == ''
|
||||
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # https://github.com/oven-sh/setup-bun/releases/tag/v2.2.0
|
||||
with:
|
||||
@@ -238,11 +239,20 @@ runs:
|
||||
if: ${{ inputs.allowed_non_write_users != '' }}
|
||||
continue-on-error: true
|
||||
shell: bash
|
||||
env:
|
||||
PATH_TO_BUN_EXECUTABLE: ${{ inputs.path_to_bun_executable }}
|
||||
SETUP_BUN_PATH: ${{ steps.setup-bun.outputs.bun-path }}
|
||||
run: |
|
||||
# Keep a copy of the bun binary alongside the action's own files so
|
||||
# post-steps use the same version that was on PATH at action start.
|
||||
# post-steps use the same version the action installed or was given.
|
||||
mkdir -p "$GITHUB_ACTION_PATH/bin"
|
||||
cp "$(command -v bun)" "$GITHUB_ACTION_PATH/bin/bun"
|
||||
for bun_path in "$PATH_TO_BUN_EXECUTABLE" "$SETUP_BUN_PATH" "$(command -v bun || true)"; do
|
||||
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
|
||||
if: ${{ inputs.allowed_non_write_users != '' && runner.os != 'Windows' }}
|
||||
@@ -256,9 +266,13 @@ runs:
|
||||
id: run
|
||||
shell: bash
|
||||
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 \
|
||||
--config="${GITHUB_ACTION_PATH}/bunfig.toml" \
|
||||
--tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json" \
|
||||
run ${GITHUB_ACTION_PATH}/src/entrypoints/run.ts
|
||||
env:
|
||||
# Prepare inputs
|
||||
@@ -307,8 +321,8 @@ runs:
|
||||
NODE_VERSION: ${{ env.NODE_VERSION }}
|
||||
|
||||
# Provider configuration
|
||||
ANTHROPIC_API_KEY: ${{ inputs.anthropic_api_key }}
|
||||
CLAUDE_CODE_OAUTH_TOKEN: ${{ inputs.claude_code_oauth_token }}
|
||||
ANTHROPIC_API_KEY: ${{ inputs.anthropic_api_key || env.ANTHROPIC_API_KEY }}
|
||||
CLAUDE_CODE_OAUTH_TOKEN: ${{ inputs.claude_code_oauth_token || env.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 }}
|
||||
@@ -398,9 +412,9 @@ runs:
|
||||
run: |
|
||||
BUN_BIN="${GITHUB_ACTION_PATH}/bin/bun"
|
||||
[ -x "$BUN_BIN" ] || BUN_BIN="bun"
|
||||
# No --tsconfig-override: see the "Run Claude Code Action" step above.
|
||||
"$BUN_BIN" --no-env-file \
|
||||
--config="${GITHUB_ACTION_PATH}/bunfig.toml" \
|
||||
--tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json" \
|
||||
run ${GITHUB_ACTION_PATH}/src/entrypoints/cleanup-ssh-signing.ts
|
||||
|
||||
- name: Post buffered inline comments
|
||||
@@ -415,9 +429,9 @@ runs:
|
||||
run: |
|
||||
BUN_BIN="${GITHUB_ACTION_PATH}/bin/bun"
|
||||
[ -x "$BUN_BIN" ] || BUN_BIN="bun"
|
||||
# No --tsconfig-override: see the "Run Claude Code Action" step above.
|
||||
"$BUN_BIN" --no-env-file \
|
||||
--config="${GITHUB_ACTION_PATH}/bunfig.toml" \
|
||||
--tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json" \
|
||||
run ${GITHUB_ACTION_PATH}/src/entrypoints/post-buffered-inline-comments.ts
|
||||
|
||||
- name: Revoke app token
|
||||
|
||||
+76
-41
@@ -93,45 +93,53 @@ Add the following to your workflow file:
|
||||
|
||||
### 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) by setting the federation environment variables on the step. Fetch an OIDC identity token from your provider, write it to a file, and point the action at it:
|
||||
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
|
||||
- name: Run Claude Code with workload identity federation
|
||||
uses: anthropics/claude-code-base-action@beta
|
||||
with:
|
||||
prompt: "Your prompt here"
|
||||
env:
|
||||
ANTHROPIC_FEDERATION_RULE_ID: fdrl_xxxxxxxxxxxx
|
||||
ANTHROPIC_ORGANIZATION_ID: 00000000-0000-0000-0000-000000000000
|
||||
ANTHROPIC_SERVICE_ACCOUNT_ID: svac_xxxxxxxxxxxx
|
||||
ANTHROPIC_IDENTITY_TOKEN_FILE: /path/to/identity-token
|
||||
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
|
||||
```
|
||||
|
||||
Note: the base action does not fetch or refresh the identity token itself — you are responsible for providing a valid token file. [`anthropics/claude-code-action`](https://github.com/anthropics/claude-code-action) handles fetching and refreshing the GitHub Actions OIDC token automatically via its `anthropic_federation_rule_id` input.
|
||||
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
|
||||
|
||||
| Input | Description | Required | Default |
|
||||
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------- | -------- | ---------------------------- |
|
||||
| `prompt` | 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 | '' |
|
||||
| `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 | '' |
|
||||
| `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 | '' |
|
||||
| `system_prompt` | Override 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 | '' |
|
||||
| `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' |
|
||||
| `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 | '' |
|
||||
| `claude_code_oauth_token` | Claude Code OAuth token (alternative to anthropic_api_key) | 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'\*\* |
|
||||
| Input | Description | Required | Default |
|
||||
| ------------------------------ | ----------------------------------------------------------------------------------------------------------------------- | -------- | ---------------------------- |
|
||||
| `prompt` | 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 | '' |
|
||||
| `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 | '' |
|
||||
| `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 | '' |
|
||||
| `system_prompt` | Override 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 | '' |
|
||||
| `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' |
|
||||
| `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 | '' |
|
||||
| `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 | '' |
|
||||
| `anthropic_organization_id` | Anthropic organization UUID used for workload identity federation | No | '' |
|
||||
| `anthropic_service_account_id` | Service account ID (svac\_...) the federated token acts as (optional) | No | '' |
|
||||
| `anthropic_workspace_id` | Workspace ID (wrkspc\_...) for federation. Optional when the rule targets a single workspace | No | '' |
|
||||
| `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.
|
||||
|
||||
@@ -139,10 +147,12 @@ Note: the base action does not fetch or refresh the identity token itself — yo
|
||||
|
||||
## Outputs
|
||||
|
||||
| Output | Description |
|
||||
| ---------------- | ---------------------------------------------------------- |
|
||||
| `conclusion` | Execution status of Claude Code ('success' or 'failure') |
|
||||
| `execution_file` | Path to the JSON file containing Claude Code execution log |
|
||||
| Output | Description |
|
||||
| ------------------- | ------------------------------------------------------------------------------------------------- |
|
||||
| `conclusion` | Execution status of Claude Code ('success' or 'failure') |
|
||||
| `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
|
||||
|
||||
@@ -387,18 +397,39 @@ jobs:
|
||||
const executionFile = '${{ steps.code-review.outputs.execution_file }}';
|
||||
const executionLog = JSON.parse(fs.readFileSync(executionFile, 'utf8'));
|
||||
|
||||
// Extract the review content from the execution log
|
||||
// The execution log contains the full conversation including Claude's responses
|
||||
// Extract the review content from the execution log.
|
||||
// The SDK writes top-level events with `type`; assistant text is nested
|
||||
// under `message.content`.
|
||||
let review = '';
|
||||
|
||||
// Find the last assistant message which should contain the review
|
||||
// Prefer the final result event when it is available.
|
||||
for (let i = executionLog.length - 1; i >= 0; i--) {
|
||||
if (executionLog[i].role === 'assistant') {
|
||||
review = executionLog[i].content;
|
||||
const entry = executionLog[i];
|
||||
if (entry?.type === 'result' && typeof entry.result === 'string') {
|
||||
review = entry.result;
|
||||
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) {
|
||||
github.rest.issues.createComment({
|
||||
issue_number: context.issue.number,
|
||||
@@ -409,6 +440,10 @@ 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).
|
||||
|
||||
## Using Cloud Providers
|
||||
|
||||
+28
-2
@@ -34,6 +34,26 @@ inputs:
|
||||
description: "Claude Code OAuth token (alternative to anthropic_api_key)"
|
||||
required: false
|
||||
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:
|
||||
description: "Use Amazon Bedrock with OIDC authentication instead of direct Anthropic API"
|
||||
required: false
|
||||
@@ -90,10 +110,11 @@ runs:
|
||||
using: "composite"
|
||||
steps:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # https://github.com/actions/setup-node/releases/tag/v4.4.0
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # https://github.com/actions/setup-node/releases/tag/v6.4.0
|
||||
with:
|
||||
node-version: ${{ env.NODE_VERSION || '18.x' }}
|
||||
cache: ${{ inputs.use_node_cache == 'true' && 'npm' || '' }}
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install Bun
|
||||
if: inputs.path_to_bun_executable == ''
|
||||
@@ -124,7 +145,7 @@ runs:
|
||||
PATH_TO_CLAUDE_CODE_EXECUTABLE: ${{ inputs.path_to_claude_code_executable }}
|
||||
run: |
|
||||
if [ -z "$PATH_TO_CLAUDE_CODE_EXECUTABLE" ]; then
|
||||
CLAUDE_CODE_VERSION="2.1.148"
|
||||
CLAUDE_CODE_VERSION="2.1.183"
|
||||
echo "Installing Claude Code v${CLAUDE_CODE_VERSION}..."
|
||||
for attempt in 1 2 3; do
|
||||
echo "Installation attempt $attempt..."
|
||||
@@ -175,6 +196,11 @@ runs:
|
||||
# Provider configuration
|
||||
ANTHROPIC_API_KEY: ${{ inputs.anthropic_api_key }}
|
||||
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_CUSTOM_HEADERS: ${{ env.ANTHROPIC_CUSTOM_HEADERS }}
|
||||
# Only set provider flags if explicitly true, since any value (including "false") is truthy
|
||||
|
||||
+10
-10
@@ -6,7 +6,7 @@
|
||||
"name": "@anthropic-ai/claude-code-base-action",
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.148",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.183",
|
||||
"shell-quote": "^1.8.3",
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -27,23 +27,23 @@
|
||||
|
||||
"@actions/io": ["@actions/[email protected]", "", {}, "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]48", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.148", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.148", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.148", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.148", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.148", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.148", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.148", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.148" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-S+KsA5ssz8/GJYjU3HqbGHq1ve75hKlRcd0JZRMQAjLI5G+VH2wJ74Yo7ZC8Q7ZrKVcZJwdLnio5o2zntKw/7w=="],
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]3", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.183", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.183", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.183", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.183", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.183", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.183", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.183", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.183" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-rAKws76RKdFu+DK5q9wYN0AGLRdPrw0vGd+TMzSFynFdxwUAehYc9vUKJoK27j2xRoHFdNt+JDsih5BzsUzi+Q=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]48", "", { "os": "darwin", "cpu": "arm64" }, "sha512-DNkhbT0Jiqo5iM+9HmejIg2eJVFQyvq2SC9h6iqOQSGRkFrbP1FN7rJpflHMb1nb3sAHZzjaDc5/tTczy5H3/Q=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-o/+sxwKgXuw6RG5cERWjvcvL1CDSPe/TaXMhax+dq+V4lDOI5iTqg3y5Wfb6dL3xlWoTA2OhWowDQllKbE04LQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]48", "", { "os": "darwin", "cpu": "x64" }, "sha512-bN5eu5wV+7Wu/LJgVwW6rhkd/y0cxk5xDujPelsAdHYSSrKDU/VPGuVcX8xA8PWgaag4pjKuXYTm1CHevB09ew=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]3", "", { "os": "darwin", "cpu": "x64" }, "sha512-V7Cf8JeD5EPf4MPomFUlEblCIQI0wg+aWdOSqvfMsDmCBEHljd52CQ3a7W263oVt6I7QUfRTpX2KNvdma56rDA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]48", "", { "os": "linux", "cpu": "arm64" }, "sha512-gCJBxAXt4Av8Y9PWmdVidnv83TZtPM7DpI5YqQ3G3gVyp/5S203XcaDta0vPjeMa595Dca6a8XIY/Xq3bcxjhA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]3", "", { "os": "linux", "cpu": "arm64" }, "sha512-qqnSf85D3uBH7kRHLGOMhr7aQrREUZ4hUlCztrkJe/twUT4bmJsO86zamnAf7vOYeCul/sHYwBMmXtOfI+cHZg=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]48", "", { "os": "linux", "cpu": "arm64" }, "sha512-6BYRuSyKzEPWXWjkXIQkWaOa+9z1FHEMcB+lHUZ3jf+aaEAqTomHiZrsF8nGF5rKSp79TjiZWoJNs225x/k4eQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]3", "", { "os": "linux", "cpu": "arm64" }, "sha512-ua6XaiCcYYKfd0CY9cjoyYnTQWI2GocpbP7Gwvmr+9taW/lTpQGVQH3FrF2VFKXVSt7AaVE6Z7WN9oPxcxl3VA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]48", "", { "os": "linux", "cpu": "x64" }, "sha512-SDjTBE8WismSmWxHFLciPaE+mQBAuwsBqbI5LvRXwYi8Ig/8D+1FElSRt1VyXkEkIzSyGzgTxusc8p07z8edIA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]3", "", { "os": "linux", "cpu": "x64" }, "sha512-GvfNp9XsKWFvr0EH3NgX2pqzHPYhFeqhOmVc4A+2e+GdxBMYUEa0ylfPLJItahQU9FkTJAw2oQNnzTHPPm1GxA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]48", "", { "os": "linux", "cpu": "x64" }, "sha512-dKWZYKCPXCYzP1CknqXzC4QaIuM+3YnCIHZ8Th0WMRHfSIisqAyrrXl42x4nPD7z5gnVwFwBmQ63pyhOxbMQRQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]3", "", { "os": "linux", "cpu": "x64" }, "sha512-wp+p+4xeZOW+h4InMKR7nIdGlgYftXyR+ErOVz7i2tMRcKuYMoc5jRIYjdJkuETMSr5nsRj0rDeO5gG7M6MGZQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]48", "", { "os": "win32", "cpu": "arm64" }, "sha512-4+JXXrWXGNIgzbhGQ45Wx6VRXhY22EU70Y9XCb0ju2SRDDZbjNn8vAFUFDSFxxMXGbo9PDlc0LTU62U8CqyYiA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]3", "", { "os": "win32", "cpu": "arm64" }, "sha512-cGyMC9YDsrCQ4av74dMVa2liOb5oLFX4+1SxwJGRCW7mBVBazcM6rg7ifWbd9XfkDhNPKOIfyiloipyMfoaE4g=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]48", "", { "os": "win32", "cpu": "x64" }, "sha512-592gVLIKVVFWQkOMIlfJF7r2ofzB9dRuG8xEx2pzh2QvRL4E0agP7qLSmiqBHAXkJL5vSLQff/wmBoQPFFc8rg=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]3", "", { "os": "win32", "cpu": "x64" }, "sha512-h/XzbrSmXGroTk/FYKR6J4/8G9vDb1HUUUeNXeBGqGW1kppIiWPJKLRzjtSe0brVjADOKOT6tE5IHK0mV/1gBw=="],
|
||||
|
||||
"@anthropic-ai/sdk": ["@anthropic-ai/[email protected]", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-q9vaSZQVFx6B/gPxetGYfLXSJD5v0sOmh0OpZDq7yCrTSA+Rscvrtyol7JJTW40wEpQB4U1B4JXzxQitbQ3CAA=="],
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.148",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.183",
|
||||
"shell-quote": "^1.8.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -7,9 +7,16 @@ import { setupClaudeCodeSettings } from "./setup-claude-code-settings";
|
||||
import { validateEnvironmentVariables } from "./validate-env";
|
||||
import { installPlugins } from "./install-plugins";
|
||||
import { setExecutionFileOutputIfPresent } from "./execution-file";
|
||||
import { setupWorkloadIdentity } from "./workload-identity";
|
||||
import type { WorkloadIdentityHandle } from "./workload-identity";
|
||||
|
||||
async function run() {
|
||||
let workloadIdentity: WorkloadIdentityHandle | undefined;
|
||||
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();
|
||||
|
||||
// The composite action's "Install Claude Code" step writes the binary to
|
||||
@@ -67,6 +74,9 @@ async function run() {
|
||||
core.setFailed(`Action failed with error: ${error}`);
|
||||
core.setOutput("conclusion", "failure");
|
||||
process.exit(1);
|
||||
} finally {
|
||||
// Stop refreshing the workload identity token file so the process can exit
|
||||
workloadIdentity?.stop();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,35 @@ const ACCUMULATING_FLAGS = new Set([
|
||||
// Delimiter used to join accumulated flag values
|
||||
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 = {
|
||||
mcpServers?: Record<string, unknown>;
|
||||
};
|
||||
@@ -106,9 +135,19 @@ function parseClaudeArgsToExtraArgs(
|
||||
if (!claudeArgs?.trim()) return {};
|
||||
|
||||
const result: Record<string, string | null> = {};
|
||||
const args = parseShellArgs(stripShellComments(claudeArgs)).filter(
|
||||
(arg): arg is string => typeof arg === "string",
|
||||
);
|
||||
const args = parseShellArgs(escapeShellMeta(stripShellComments(claudeArgs)))
|
||||
.map((arg) => {
|
||||
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++) {
|
||||
const arg = args[i];
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
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;
|
||||
}
|
||||
@@ -167,6 +167,16 @@ export async function runClaudeWithSdk(
|
||||
|
||||
if (message.type === "result") {
|
||||
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) {
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
import * as core from "@actions/core";
|
||||
import { mkdirSync, writeFileSync } from "fs";
|
||||
import { join } from "path";
|
||||
import { retryWithBackoff } from "../utils/retry";
|
||||
import { retryWithBackoff } from "./retry";
|
||||
|
||||
/** How often the GitHub OIDC identity token file is rewritten. */
|
||||
const REFRESH_INTERVAL_MS = 4 * 60 * 1000;
|
||||
@@ -137,6 +137,110 @@ 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", () => {
|
||||
const options: ClaudeOptions = {
|
||||
claudeArgs: '--allowedTools "Edit,Read" --allowed-tools "Write,Glob"',
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, mock } from "bun:test";
|
||||
import { retryWithBackoff } from "../src/utils/retry";
|
||||
import { retryWithBackoff } from "../src/retry";
|
||||
|
||||
describe("retryWithBackoff", () => {
|
||||
let originalConsoleLog: typeof console.log;
|
||||
@@ -8,7 +8,7 @@ import { join } from "path";
|
||||
import {
|
||||
isWorkloadIdentityConfigured,
|
||||
setupWorkloadIdentity,
|
||||
} from "../src/auth/workload-identity";
|
||||
} from "../src/workload-identity";
|
||||
|
||||
describe("workload identity federation", () => {
|
||||
let originalEnv: NodeJS.ProcessEnv;
|
||||
@@ -7,7 +7,7 @@
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"@actions/github": "^6.0.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.148",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.183",
|
||||
"@modelcontextprotocol/sdk": "^1.11.0",
|
||||
"@octokit/graphql": "^8.2.2",
|
||||
"@octokit/rest": "^21.1.1",
|
||||
@@ -37,23 +37,23 @@
|
||||
|
||||
"@actions/io": ["@actions/[email protected]", "", {}, "sha512-wi9JjgKLYS7U/z8PPbco+PvTb/nRWjeoFlJ1Qer83k/3C5PHQi28hiVdeE2kHXmIL99mQFawx8qt/JPjZilJ8Q=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]48", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.148", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.148", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.148", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.148", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.148", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.148", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.148", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.148" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-S+KsA5ssz8/GJYjU3HqbGHq1ve75hKlRcd0JZRMQAjLI5G+VH2wJ74Yo7ZC8Q7ZrKVcZJwdLnio5o2zntKw/7w=="],
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]3", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.183", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.183", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.183", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.183", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.183", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.183", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.183", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.183" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-rAKws76RKdFu+DK5q9wYN0AGLRdPrw0vGd+TMzSFynFdxwUAehYc9vUKJoK27j2xRoHFdNt+JDsih5BzsUzi+Q=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]48", "", { "os": "darwin", "cpu": "arm64" }, "sha512-DNkhbT0Jiqo5iM+9HmejIg2eJVFQyvq2SC9h6iqOQSGRkFrbP1FN7rJpflHMb1nb3sAHZzjaDc5/tTczy5H3/Q=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]3", "", { "os": "darwin", "cpu": "arm64" }, "sha512-o/+sxwKgXuw6RG5cERWjvcvL1CDSPe/TaXMhax+dq+V4lDOI5iTqg3y5Wfb6dL3xlWoTA2OhWowDQllKbE04LQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]48", "", { "os": "darwin", "cpu": "x64" }, "sha512-bN5eu5wV+7Wu/LJgVwW6rhkd/y0cxk5xDujPelsAdHYSSrKDU/VPGuVcX8xA8PWgaag4pjKuXYTm1CHevB09ew=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]3", "", { "os": "darwin", "cpu": "x64" }, "sha512-V7Cf8JeD5EPf4MPomFUlEblCIQI0wg+aWdOSqvfMsDmCBEHljd52CQ3a7W263oVt6I7QUfRTpX2KNvdma56rDA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]48", "", { "os": "linux", "cpu": "arm64" }, "sha512-gCJBxAXt4Av8Y9PWmdVidnv83TZtPM7DpI5YqQ3G3gVyp/5S203XcaDta0vPjeMa595Dca6a8XIY/Xq3bcxjhA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]3", "", { "os": "linux", "cpu": "arm64" }, "sha512-qqnSf85D3uBH7kRHLGOMhr7aQrREUZ4hUlCztrkJe/twUT4bmJsO86zamnAf7vOYeCul/sHYwBMmXtOfI+cHZg=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]48", "", { "os": "linux", "cpu": "arm64" }, "sha512-6BYRuSyKzEPWXWjkXIQkWaOa+9z1FHEMcB+lHUZ3jf+aaEAqTomHiZrsF8nGF5rKSp79TjiZWoJNs225x/k4eQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]3", "", { "os": "linux", "cpu": "arm64" }, "sha512-ua6XaiCcYYKfd0CY9cjoyYnTQWI2GocpbP7Gwvmr+9taW/lTpQGVQH3FrF2VFKXVSt7AaVE6Z7WN9oPxcxl3VA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]48", "", { "os": "linux", "cpu": "x64" }, "sha512-SDjTBE8WismSmWxHFLciPaE+mQBAuwsBqbI5LvRXwYi8Ig/8D+1FElSRt1VyXkEkIzSyGzgTxusc8p07z8edIA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]3", "", { "os": "linux", "cpu": "x64" }, "sha512-GvfNp9XsKWFvr0EH3NgX2pqzHPYhFeqhOmVc4A+2e+GdxBMYUEa0ylfPLJItahQU9FkTJAw2oQNnzTHPPm1GxA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]48", "", { "os": "linux", "cpu": "x64" }, "sha512-dKWZYKCPXCYzP1CknqXzC4QaIuM+3YnCIHZ8Th0WMRHfSIisqAyrrXl42x4nPD7z5gnVwFwBmQ63pyhOxbMQRQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]3", "", { "os": "linux", "cpu": "x64" }, "sha512-wp+p+4xeZOW+h4InMKR7nIdGlgYftXyR+ErOVz7i2tMRcKuYMoc5jRIYjdJkuETMSr5nsRj0rDeO5gG7M6MGZQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]48", "", { "os": "win32", "cpu": "arm64" }, "sha512-4+JXXrWXGNIgzbhGQ45Wx6VRXhY22EU70Y9XCb0ju2SRDDZbjNn8vAFUFDSFxxMXGbo9PDlc0LTU62U8CqyYiA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]3", "", { "os": "win32", "cpu": "arm64" }, "sha512-cGyMC9YDsrCQ4av74dMVa2liOb5oLFX4+1SxwJGRCW7mBVBazcM6rg7ifWbd9XfkDhNPKOIfyiloipyMfoaE4g=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]48", "", { "os": "win32", "cpu": "x64" }, "sha512-592gVLIKVVFWQkOMIlfJF7r2ofzB9dRuG8xEx2pzh2QvRL4E0agP7qLSmiqBHAXkJL5vSLQff/wmBoQPFFc8rg=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]3", "", { "os": "win32", "cpu": "x64" }, "sha512-h/XzbrSmXGroTk/FYKR6J4/8G9vDb1HUUUeNXeBGqGW1kppIiWPJKLRzjtSe0brVjADOKOT6tE5IHK0mV/1gBw=="],
|
||||
|
||||
"@anthropic-ai/sdk": ["@anthropic-ai/[email protected]", "", { "dependencies": { "json-schema-to-ts": "^3.1.1" }, "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" }, "optionalPeers": ["zod"], "bin": { "anthropic-ai-sdk": "bin/cli" } }, "sha512-q9vaSZQVFx6B/gPxetGYfLXSJD5v0sOmh0OpZDq7yCrTSA+Rscvrtyol7JJTW40wEpQB4U1B4JXzxQitbQ3CAA=="],
|
||||
|
||||
|
||||
+3
-6
@@ -63,17 +63,14 @@ The GitHub App for Claude doesn't have workflow write access for security reason
|
||||
|
||||
### Why won't Claude rebase my branch?
|
||||
|
||||
By default, Claude only uses commit tools for non-destructive changes to the branch. Claude is configured to:
|
||||
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:
|
||||
|
||||
- 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
|
||||
|
||||
You can grant additional tools via the `claude_args` input if needed:
|
||||
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.
|
||||
|
||||
```yaml
|
||||
claude_args: |
|
||||
--allowedTools "Bash(git rebase:*)" # Use with caution
|
||||
```
|
||||
If you need to rebase, do it yourself locally — or with the Claude Code CLI outside of this action — and push the result.
|
||||
|
||||
### Why won't Claude create a pull request?
|
||||
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"@actions/github": "^6.0.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.148",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.183",
|
||||
"@modelcontextprotocol/sdk": "^1.11.0",
|
||||
"@octokit/graphql": "^8.2.2",
|
||||
"@octokit/rest": "^21.1.1",
|
||||
|
||||
+11
-12
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env bun
|
||||
|
||||
import * as core from "@actions/core";
|
||||
import { writeFile, mkdir } from "fs/promises";
|
||||
import { writeFile, mkdir, rm } from "fs/promises";
|
||||
import type { FetchDataResult } from "../github/data/fetcher";
|
||||
import {
|
||||
formatContext,
|
||||
@@ -930,9 +930,14 @@ export async function createPrompt(
|
||||
claudeBranch,
|
||||
);
|
||||
|
||||
await mkdir(`${process.env.RUNNER_TEMP || "/tmp"}/claude-prompts`, {
|
||||
recursive: true,
|
||||
});
|
||||
// Clear any stale prompt files from a prior invocation. RUNNER_TEMP is documented
|
||||
// to be emptied between jobs, but on non-ephemeral self-hosted runners this is
|
||||
// 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
|
||||
const promptContent = generatePrompt(
|
||||
@@ -948,10 +953,7 @@ export async function createPrompt(
|
||||
console.log("=======================");
|
||||
|
||||
// Write the prompt file
|
||||
await writeFile(
|
||||
`${process.env.RUNNER_TEMP || "/tmp"}/claude-prompts/claude-prompt.txt`,
|
||||
promptContent,
|
||||
);
|
||||
await writeFile(`${promptDir}/claude-prompt.txt`, promptContent);
|
||||
|
||||
// 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")
|
||||
@@ -960,10 +962,7 @@ export async function createPrompt(
|
||||
githubData,
|
||||
);
|
||||
if (userRequest) {
|
||||
await writeFile(
|
||||
`${process.env.RUNNER_TEMP || "/tmp"}/claude-prompts/${USER_REQUEST_FILENAME}`,
|
||||
userRequest,
|
||||
);
|
||||
await writeFile(`${promptDir}/${USER_REQUEST_FILENAME}`, userRequest);
|
||||
console.log("===== USER REQUEST =====");
|
||||
console.log(userRequest);
|
||||
console.log("========================");
|
||||
|
||||
@@ -29,13 +29,13 @@ import { prepareAgentMode } from "../modes/agent";
|
||||
import { checkContainsTrigger } from "../github/validation/trigger";
|
||||
import { restoreConfigFromBase } from "../github/operations/restore-config";
|
||||
import { validateBranchName } from "../github/operations/branch";
|
||||
import { setupWorkloadIdentity } from "../auth/workload-identity";
|
||||
import type { WorkloadIdentityHandle } from "../auth/workload-identity";
|
||||
import { collectActionInputsPresence } from "./collect-inputs";
|
||||
import { updateCommentLink } from "./update-comment-link";
|
||||
import { formatTurnsFromData } from "./format-turns";
|
||||
import type { Turn } from "./format-turns";
|
||||
// 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 { setupClaudeCodeSettings } from "../../base-action/src/setup-claude-code-settings";
|
||||
import { installPlugins } from "../../base-action/src/install-plugins";
|
||||
@@ -68,7 +68,7 @@ async function installClaudeCode(): Promise<string> {
|
||||
return customExecutable;
|
||||
}
|
||||
|
||||
const claudeCodeVersion = "2.1.148";
|
||||
const claudeCodeVersion = "2.1.183";
|
||||
console.log(`Installing Claude Code v${claudeCodeVersion}...`);
|
||||
|
||||
for (let attempt = 1; attempt <= 3; attempt++) {
|
||||
|
||||
@@ -25,7 +25,7 @@ export const PR_QUERY = `
|
||||
additions
|
||||
deletions
|
||||
state
|
||||
labels(first: 1) {
|
||||
labels(first: 100) {
|
||||
nodes {
|
||||
name
|
||||
}
|
||||
@@ -113,7 +113,7 @@ export const ISSUE_QUERY = `
|
||||
updatedAt
|
||||
lastEditedAt
|
||||
state
|
||||
labels(first: 1) {
|
||||
labels(first: 100) {
|
||||
nodes {
|
||||
name
|
||||
}
|
||||
|
||||
@@ -8,6 +8,11 @@ import type {
|
||||
import type { GitHubFileWithSHA } from "./fetcher";
|
||||
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(
|
||||
contextData: GitHubPullRequest | GitHubIssue,
|
||||
isPR: boolean,
|
||||
@@ -19,6 +24,7 @@ export function formatContext(
|
||||
PR Author: ${prData.author.login}
|
||||
PR Branch: ${prData.headRefName} -> ${prData.baseRefName}
|
||||
PR State: ${prData.state}
|
||||
PR Labels: ${formatLabels(prData.labels.nodes)}
|
||||
PR Additions: ${prData.additions}
|
||||
PR Deletions: ${prData.deletions}
|
||||
Total Commits: ${prData.commits.totalCount}
|
||||
@@ -28,7 +34,8 @@ Changed Files: ${prData.files.nodes.length} files`;
|
||||
const sanitizedTitle = sanitizeContent(issueData.title);
|
||||
return `Issue Title: ${sanitizedTitle}
|
||||
Issue Author: ${issueData.author.login}
|
||||
Issue State: ${issueData.state}`;
|
||||
Issue State: ${issueData.state}
|
||||
Issue Labels: ${formatLabels(issueData.labels.nodes)}`;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+50
-20
@@ -10,6 +10,49 @@ 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> {
|
||||
try {
|
||||
const oidcToken = await core.getIDToken("claude-code-github-action");
|
||||
@@ -80,25 +123,11 @@ async function exchangeForAppToken(
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
const responseJson = (await response.json()) as {
|
||||
error?: {
|
||||
message?: string;
|
||||
details?: {
|
||||
error_code?: string;
|
||||
};
|
||||
};
|
||||
type?: string;
|
||||
message?: string;
|
||||
};
|
||||
const responseJson =
|
||||
(await response.json()) as AppTokenExchangeErrorResponse;
|
||||
|
||||
// Check for specific workflow validation error codes that should skip the action
|
||||
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";
|
||||
if (isWorkflowValidationError(response.status, responseJson)) {
|
||||
const message = getAppTokenExchangeErrorMessage(responseJson);
|
||||
core.warning(`Skipping action due to workflow validation: ${message}`);
|
||||
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.",
|
||||
@@ -106,10 +135,11 @@ async function exchangeForAppToken(
|
||||
throw new WorkflowValidationSkipError(message);
|
||||
}
|
||||
|
||||
const message = getAppTokenExchangeErrorMessage(responseJson);
|
||||
console.error(
|
||||
`App token exchange failed: ${response.status} ${response.statusText} - ${responseJson?.error?.message ?? "Unknown error"}`,
|
||||
`App token exchange failed: ${response.status} ${response.statusText} - ${message}`,
|
||||
);
|
||||
throw new Error(`${responseJson?.error?.message ?? "Unknown error"}`);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
const appTokenData = (await response.json()) as {
|
||||
|
||||
@@ -192,10 +192,6 @@ export async function downloadCommentImages(
|
||||
continue;
|
||||
}
|
||||
|
||||
const fileExtension = getImageExtension(originalUrl);
|
||||
const filename = `image-${Date.now()}-${i}${fileExtension}`;
|
||||
const localPath = path.join(downloadsDir, filename);
|
||||
|
||||
try {
|
||||
console.log(`Downloading ${originalUrl}...`);
|
||||
|
||||
@@ -209,6 +205,19 @@ export async function downloadCommentImages(
|
||||
const arrayBuffer = await imageResponse.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);
|
||||
console.log(`✓ Saved: ${localPath}`);
|
||||
|
||||
@@ -244,3 +253,56 @@ function getImageExtension(url: string): string {
|
||||
const match = filename.match(/\.(png|jpg|jpeg|gif|webp|svg)$/i);
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -20,15 +20,23 @@ export function stripMarkdownLinkTitles(content: string): string {
|
||||
}
|
||||
|
||||
export function stripHiddenAttributes(content: string): string {
|
||||
content = content.replace(/\salt\s*=\s*["'][^"']*["']/gi, "");
|
||||
// Quoted values are matched per quote type so that a value containing the
|
||||
// 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(/\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(/\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(/\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(/\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, "");
|
||||
return content;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { mkdir, writeFile } from "fs/promises";
|
||||
import { mkdir, rm, writeFile } from "fs/promises";
|
||||
import { prepareMcpConfig } from "../../mcp/install-mcp-server";
|
||||
import { parseAllowedTools } from "./parse-tools";
|
||||
import {
|
||||
@@ -64,20 +64,19 @@ export async function prepareAgentMode({
|
||||
}
|
||||
}
|
||||
|
||||
// Create prompt directory
|
||||
await mkdir(`${process.env.RUNNER_TEMP || "/tmp"}/claude-prompts`, {
|
||||
recursive: true,
|
||||
});
|
||||
// Create prompt directory. Clear any stale files from a prior invocation first —
|
||||
// see src/create-prompt/index.ts for context (non-ephemeral self-hosted runners
|
||||
// do not reliably honor the RUNNER_TEMP cleanup contract).
|
||||
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
|
||||
const promptContent =
|
||||
context.inputs.prompt ||
|
||||
`Repository: ${context.repository.owner}/${context.repository.repo}`;
|
||||
|
||||
await writeFile(
|
||||
`${process.env.RUNNER_TEMP || "/tmp"}/claude-prompts/claude-prompt.txt`,
|
||||
promptContent,
|
||||
);
|
||||
await writeFile(`${promptDir}/claude-prompt.txt`, promptContent);
|
||||
|
||||
// Parse allowed tools from user's claude_args
|
||||
const userClaudeArgs = process.env.CLAUDE_ARGS || "";
|
||||
|
||||
@@ -1,29 +1,77 @@
|
||||
export function parseAllowedTools(claudeArgs: string): string[] {
|
||||
// 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)
|
||||
];
|
||||
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[] {
|
||||
if (!claudeArgs?.trim()) return [];
|
||||
|
||||
const args = tokenize(claudeArgs);
|
||||
const tools: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const pattern of patterns) {
|
||||
for (const match of claudeArgs.matchAll(pattern)) {
|
||||
if (match[1]) {
|
||||
// Don't add if the value starts with -- (another flag)
|
||||
if (match[1].startsWith("--")) {
|
||||
continue;
|
||||
}
|
||||
for (const tool of match[1].split(",")) {
|
||||
const trimmed = tool.trim();
|
||||
if (trimmed && !seen.has(trimmed)) {
|
||||
seen.add(trimmed);
|
||||
tools.push(trimmed);
|
||||
}
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
if (!arg?.startsWith("--")) continue;
|
||||
|
||||
const flag = arg.slice(2);
|
||||
if (!ALLOWED_TOOLS_FLAGS.has(flag)) continue;
|
||||
|
||||
// Consume all consecutive non-flag values, e.g.
|
||||
// --allowedTools "Read" "Grep" "mcp__github__get_commit"
|
||||
while (i + 1 < args.length && !args[i + 1]!.startsWith("--")) {
|
||||
i++;
|
||||
for (const tool of args[i]!.split(",")) {
|
||||
const trimmed = tool.trim();
|
||||
if (trimmed && !seen.has(trimmed)) {
|
||||
seen.add(trimmed);
|
||||
tools.push(trimmed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+4
-47
@@ -1,47 +1,4 @@
|
||||
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;
|
||||
}
|
||||
export {
|
||||
retryWithBackoff,
|
||||
type RetryOptions,
|
||||
} from "../../base-action/src/retry";
|
||||
|
||||
@@ -54,6 +54,53 @@ describe("formatContext", () => {
|
||||
PR Author: test-user
|
||||
PR Branch: feature/test -> main
|
||||
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 Deletions: 30
|
||||
Total Commits: 3
|
||||
@@ -80,7 +127,36 @@ Changed Files: 2 files`,
|
||||
expect(result).toBe(
|
||||
`Issue Title: Test Issue
|
||||
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`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,520 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -158,6 +158,55 @@ 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: ``,
|
||||
},
|
||||
];
|
||||
|
||||
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 () => {
|
||||
const mockOctokit = createMockOctokit();
|
||||
const imageUrl =
|
||||
|
||||
@@ -37,9 +37,43 @@ describe("parseAllowedTools", () => {
|
||||
|
||||
test("handles --allowedTools followed by another --allowedTools flag", () => {
|
||||
const args = "--allowedTools --allowedTools mcp__github__*";
|
||||
// The second --allowedTools is consumed as a value of the first, then skipped.
|
||||
// This is an edge case with malformed input - returns empty.
|
||||
expect(parseAllowedTools(args)).toEqual([]);
|
||||
// The first --allowedTools has no value (the next token is another flag);
|
||||
// the second consumes mcp__github__*. This matches how the SDK option
|
||||
// parser (parse-sdk-options.ts) reads the same input.
|
||||
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", () => {
|
||||
|
||||
@@ -131,6 +131,21 @@ describe("stripHiddenAttributes", () => {
|
||||
),
|
||||
).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", () => {
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user