mirror of
https://github.com/anthropics/claude-code-action.git
synced 2026-11-24 14:37:22 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4a461cbbb7 | ||
|
|
b5e37652b7 | ||
|
|
423df53bc5 |
+9
-12
@@ -45,9 +45,9 @@ inputs:
|
||||
required: false
|
||||
default: ""
|
||||
allow_fork_prs:
|
||||
description: "Whether to run on pull requests from forks, and on workflow_run events for a fork's run. With any value other than 'true', the action skips them, whoever opened them, before it checks anything out. See docs/security.md."
|
||||
description: "Set to 'true' to run on pull requests from forks, and on workflow_run events for a fork's run. By default, and with any other value, the action skips them, whoever opened them, before it checks anything out. Where the event has credentials, a run that the actor checks refuse fails instead. See docs/security.md."
|
||||
required: false
|
||||
default: "true"
|
||||
default: "false"
|
||||
restrict_untrusted_prs:
|
||||
description: "On pull requests whose author does not have write access, deny commands that commonly run code from the checkout (package managers, test runners, interpreters, shells), even if claude_args allows them. Set to 'false' to turn this off. See docs/security.md."
|
||||
required: false
|
||||
@@ -289,16 +289,13 @@ runs:
|
||||
# takes its settings from the action's directory. Bun before 1.4.3 logs
|
||||
# "directory mismatch" for --tsconfig-override (oven-sh/bun#25730).
|
||||
#
|
||||
# Bash reads this script as it runs. The braces and exit make it read the
|
||||
# rest first and stop there. With exec instead, cancelling the run would
|
||||
# interrupt Bun at once, before it can clean up.
|
||||
{
|
||||
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
|
||||
exit
|
||||
}
|
||||
# Bash reads this script as it runs, so exec also keeps it from running what a
|
||||
# session adds. When the run is cancelled, the runner signals only this step's
|
||||
# own process, and Bun has to get that signal to stop the session.
|
||||
exec 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:
|
||||
# Turns off Bun's cache of transpiled files, which is outside the action's
|
||||
# directory. Set it wherever the action runs its own scripts.
|
||||
|
||||
@@ -147,7 +147,7 @@ runs:
|
||||
PATH_TO_CLAUDE_CODE_EXECUTABLE: ${{ inputs.path_to_claude_code_executable }}
|
||||
run: |
|
||||
if [ -z "$PATH_TO_CLAUDE_CODE_EXECUTABLE" ]; then
|
||||
CLAUDE_CODE_VERSION="2.1.330"
|
||||
CLAUDE_CODE_VERSION="2.1.331"
|
||||
echo "Installing Claude Code v${CLAUDE_CODE_VERSION}..."
|
||||
for attempt in 1 2 3; do
|
||||
echo "Installation attempt $attempt..."
|
||||
@@ -183,13 +183,10 @@ runs:
|
||||
echo "Changing directory to CLAUDE_WORKING_DIR: $CLAUDE_WORKING_DIR"
|
||||
cd "$CLAUDE_WORKING_DIR"
|
||||
fi
|
||||
# Bash reads this script as it runs. The braces and exit make it read the
|
||||
# rest first and stop there. With exec instead, cancelling the run would
|
||||
# interrupt Bun at once, before it can clean up.
|
||||
{
|
||||
bun run ${GITHUB_ACTION_PATH}/src/index.ts
|
||||
exit
|
||||
}
|
||||
# Bash reads this script as it runs, so exec also keeps it from running what a
|
||||
# session adds. When the run is cancelled, the runner signals only this step's
|
||||
# own process, and Bun has to get that signal to stop the session.
|
||||
exec bun run ${GITHUB_ACTION_PATH}/src/index.ts
|
||||
env:
|
||||
# Turns off Bun's cache of transpiled files, which is outside the action's
|
||||
# directory
|
||||
|
||||
+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.330",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.331",
|
||||
"shell-quote": "^1.8.4",
|
||||
},
|
||||
"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]0", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.330", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.330", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.330", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.330", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.330", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.330", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.330", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.330" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-7om9Xus6tfkeCUCfzg6ilJuN6Z7okkEvJ0mx+ukXa/Id5U/6BGtPkOYni+3ebedwa3b9SVF7A05+ln+/9EoU/w=="],
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]1", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.331", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.331", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.331", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.331", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.331", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.331", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.331", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.331" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-ml/MPqgO95tG5zcApBFxEyoDk57d9htP09R8AtPbKPUCHpsobf84IjkN4zhGvQgk8zsA9dXoeMGrQcCc8gQE/w=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-J9nqvcfD2V90O5uoR8At66R51VYtSMKnxSmPc0S4A4F5oX1VbokcpJLXU1yVCOuTtzr/OIHjRr9nn2vKi/S6rQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-PQrn7YTiSV5Bg+ueF2hNvswc+wI7YKC2c32XNedvs6vfMCUUnIlq93VEbZiRY23b+JIVkEm8gb1VhkJTjsYISQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]0", "", { "os": "darwin", "cpu": "x64" }, "sha512-woe+f9qeZYWML5fACibNyth0xMDf22riNRNDryIYuhdteh7IoWrK6zC31cC2MrZRoqDZcPVtfOLND79+iZbrLA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]1", "", { "os": "darwin", "cpu": "x64" }, "sha512-dc3iB+CY3jDpKpDpmvYc4V+UKSkudY29iJ62p0s5TK3h+b7Wqa2Hv0bPow0LUs4ZzDUXxEtCEHzk9X29VfLovw=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-2Q+kfzaoTvJv1rsyu+iR4UHDZ3nxiOfdXISk+2ydQShU9DqXNlgQAt3BdJMh0Yx4MrxB66TMphVvVQeRslwwhA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]1", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-xiRxBxoM8Qa5fnjCFk5iFheL5GUroLuHPJ7UnD4v2Sv1tWxGoSL67AYnMZ6OdjMguZK09X4WlgOn1nL1m6NEOA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-fXmuAEegw31v+kiBd51yn7RVhjs7Rz2lnhfx/+XJXqt5lyqR2v7Ul/U/9r1CQZKuIw8M3ms9jQqGpmKbgKndqQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]1", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-KdIClOdBUIpvf4PTFe2qedtPCOM3tC/jbsjh8U6WXF0QS8VjYkP0QR9i2AXG1PSAnI24T5xTxQb1scPAgRTIUQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-9w4uMdA3vNZXocwOUhivOGotXoRDxN/C/xPMkZMY9WPpKLAlj8upMZskNgPjQKlVRXhxPfNagcBijGPUH4WepA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]1", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-nfHSiLJdkpsVAFsXTriyW3r64gS1sp5zxvaoF2dmNqKixR4rf9ISDDi81gF9L1uk/bAEcBGRx34U6Itw+NYIEg=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-kooZMdp6tFwNFkDXbGoNTZMgFcPQfJVfG+gZ2qAdkk11S6MFts9ybHRLQmzUK3VrqlahH7T9fmI2mNfzYgOXkw=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]1", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-CSeT1JF++Vckf6TSXjQeuSjQ/sJnoTVL/XX44v4jHNAtU5i22nI9b27E6wkzudYVxoRoLWIU00V05dXhYYCvlg=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]0", "", { "os": "win32", "cpu": "arm64" }, "sha512-6jscch7vk/XBSn7mm1i6zwTeiz05q98nKrQ3HdTavQEDGvXycMcB/QxIdMrs3vrdNEjWuoxwrL1qlT1lOyAWLg=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]1", "", { "os": "win32", "cpu": "arm64" }, "sha512-FsPHWUpgHBFgSZESwM53JsbEoQiWPnigSCyjSfHDyiWnH66e0NsuksuJ/Nu9qI8UVgBDh/y1NOnnd4eGrB3eFQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]0", "", { "os": "win32", "cpu": "x64" }, "sha512-ooThWbUXlXKTDgj2VgWBXQ/6vSOTaAbBDWPvvCGNHi20haoSkw4uPX9gczkX+HJuVTslvvLiYIfe8zleVPzi7A=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]1", "", { "os": "win32", "cpu": "x64" }, "sha512-AsLur4ov9MGTQTrnZ49ZDPasQ35U3X/rZDdF/rPhytN3h1F3w/0IkC6esW3OzldvPlci60QvggOLVGnFlUzdxw=="],
|
||||
|
||||
"@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.330",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.331",
|
||||
"shell-quote": "^1.8.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
import { spawnSync } from "child_process";
|
||||
import { readdirSync, readFileSync } from "fs";
|
||||
|
||||
// The runner sends SIGINT, SIGTERM after 7.5 seconds, and kills the step 2.5 seconds
|
||||
// later, so a cancel that starts with SIGTERM has to fit into that.
|
||||
const GRACE_MS = 1000;
|
||||
const PAUSE_MS = 500;
|
||||
const POLL_MS = 50;
|
||||
|
||||
type Process = { pid: number; parent: number };
|
||||
|
||||
function listProcesses(): Process[] {
|
||||
if (process.platform === "linux") {
|
||||
return readdirSync("/proc")
|
||||
.filter((name) => /^\d+$/.test(name))
|
||||
.flatMap((name) => {
|
||||
try {
|
||||
const stat = readFileSync(`/proc/${name}/stat`, "utf8");
|
||||
// The command's name comes before these fields and can hold anything.
|
||||
const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
|
||||
const threads = Number(fields[17]);
|
||||
// This process can't reap its children while it waits for them. One whose
|
||||
// first thread has ended, but not its others, is a zombie here too.
|
||||
if (fields[0] === "Z" && threads <= 1) return [];
|
||||
return [{ pid: Number(name), parent: Number(fields[1]) }];
|
||||
} catch {
|
||||
return []; // It has ended
|
||||
}
|
||||
});
|
||||
}
|
||||
if (process.platform === "win32") return []; // The runner's Ctrl+C reaches these
|
||||
// By path, because a session may be able to write to a directory in PATH
|
||||
const ps = spawnSync("/bin/ps", ["-A", "-o", "pid=,ppid=,state="], {
|
||||
encoding: "utf8",
|
||||
});
|
||||
if (ps.error) throw ps.error;
|
||||
if (ps.status !== 0) throw new Error("ps failed");
|
||||
return ps.stdout.split("\n").flatMap((line) => {
|
||||
const [pid, parent, state] = line.trim().split(/\s+/);
|
||||
if (!pid || Number(pid) === ps.pid || state!.startsWith("Z")) return [];
|
||||
return [{ pid: Number(pid), parent: Number(parent) }];
|
||||
});
|
||||
}
|
||||
|
||||
/** What these processes have started, and they themselves, if still running. */
|
||||
function listTree(roots: Iterable<number>): Set<number> {
|
||||
const processes = listProcesses();
|
||||
const running = new Set(processes.map(({ pid }) => pid));
|
||||
const children = new Map<number, number[]>();
|
||||
for (const { pid, parent } of processes) {
|
||||
children.set(parent, [...(children.get(parent) ?? []), pid]);
|
||||
}
|
||||
const tree = new Set([...roots].filter((pid) => running.has(pid)));
|
||||
// A set's iterator also visits what is added meanwhile.
|
||||
for (const pid of tree)
|
||||
children.get(pid)?.forEach((child) => tree.add(child));
|
||||
tree.delete(process.pid);
|
||||
return tree;
|
||||
}
|
||||
|
||||
const cannotSignal = new Set<number>();
|
||||
|
||||
function signal(pids: Iterable<number>, name: NodeJS.Signals): void {
|
||||
for (const pid of pids) {
|
||||
try {
|
||||
process.kill(pid, name);
|
||||
} catch (error) {
|
||||
if ((error as { code?: string }).code === "EPERM") cannotSignal.add(pid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops everything this process started that is still in its process tree. Programs
|
||||
* first get to clean up after themselves, as git does with its lock files. They are
|
||||
* paused before each signal, because what a process starts while it is being stopped
|
||||
* would leave the tree.
|
||||
*/
|
||||
export function stopDescendants(): void {
|
||||
const known = new Set<number>();
|
||||
// What one of these started stays known once that one has ended.
|
||||
const update = () => {
|
||||
const running = listTree([process.pid, ...known]);
|
||||
known.clear();
|
||||
running.forEach((pid) => known.add(pid));
|
||||
return known;
|
||||
};
|
||||
const pause = () => {
|
||||
const paused = new Set<number>();
|
||||
for (const end = Date.now() + PAUSE_MS; Date.now() < end; ) {
|
||||
const added = [...update()].filter((pid) => !paused.has(pid));
|
||||
if (added.length === 0) return;
|
||||
signal(added, "SIGSTOP");
|
||||
added.forEach((pid) => paused.add(pid));
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
pause();
|
||||
signal(known, "SIGTERM");
|
||||
signal(known, "SIGCONT");
|
||||
for (const end = Date.now() + GRACE_MS; Date.now() < end; ) {
|
||||
if (update().size === 0) return;
|
||||
Bun.sleepSync(POLL_MS);
|
||||
}
|
||||
pause();
|
||||
} finally {
|
||||
// Also when the processes can't be listed, so that none stays paused.
|
||||
signal(known, "SIGKILL");
|
||||
const left = [...known].filter((pid) => cannotSignal.has(pid));
|
||||
if (left.length > 0) {
|
||||
console.log(
|
||||
`::warning::Processes of another user could not be stopped: ${left.join(", ")}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the session, cleans up and exits when the run is cancelled or times out. The
|
||||
* steps are synchronous, and each runs whether or not the ones before it failed. Once
|
||||
* isFinishing returns true, only the runner's second signal does this.
|
||||
*/
|
||||
export function onCancel(
|
||||
steps: (() => void)[],
|
||||
isFinishing: () => boolean = () => false,
|
||||
): void {
|
||||
let cancelled = false;
|
||||
const cancel = (name: NodeJS.Signals) => {
|
||||
if (cancelled || (name === "SIGINT" && isFinishing())) return;
|
||||
cancelled = true;
|
||||
for (const step of [stopDescendants, ...steps]) {
|
||||
try {
|
||||
step();
|
||||
} catch (error) {
|
||||
// A message could hold anything, such as a value that was being written.
|
||||
const { code, name } = error as { code?: string; name?: string };
|
||||
console.error(`Error cleaning up the cancelled run (${code ?? name})`);
|
||||
}
|
||||
}
|
||||
process.exit(130);
|
||||
};
|
||||
process.on("SIGINT", cancel);
|
||||
process.on("SIGTERM", cancel);
|
||||
process.on("SIGBREAK", cancel); // The runner's second signal on Windows
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { runClaude } from "./run-claude";
|
||||
import { setupClaudeCodeSettings } from "./setup-claude-code-settings";
|
||||
import { validateEnvironmentVariables } from "./validate-env";
|
||||
import { installPlugins } from "./install-plugins";
|
||||
import { onCancel } from "./cancel";
|
||||
import { setExecutionFileOutputIfPresent } from "./execution-file";
|
||||
import { setupWorkloadIdentity } from "./workload-identity";
|
||||
import type { WorkloadIdentityHandle } from "./workload-identity";
|
||||
@@ -15,6 +16,14 @@ async function run() {
|
||||
delete process.env.BUN_RUNTIME_TRANSPILER_CACHE_PATH;
|
||||
|
||||
let workloadIdentity: WorkloadIdentityHandle | undefined;
|
||||
let isFinishing = false;
|
||||
onCancel(
|
||||
[
|
||||
() => workloadIdentity?.stop(),
|
||||
() => isFinishing || core.setOutput("conclusion", "failure"),
|
||||
],
|
||||
() => isFinishing,
|
||||
);
|
||||
try {
|
||||
// When workload identity federation is configured, fetch the GitHub OIDC
|
||||
// identity token and expose it to the CLI before validating auth env vars.
|
||||
@@ -62,6 +71,7 @@ async function run() {
|
||||
});
|
||||
|
||||
// Set outputs for the standalone base-action
|
||||
isFinishing = true;
|
||||
core.setOutput("conclusion", result.conclusion);
|
||||
if (result.executionFile) {
|
||||
core.setOutput("execution_file", result.executionFile);
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"@actions/github": "^6.0.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.330",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.331",
|
||||
"@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]0", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.330", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.330", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.330", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.330", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.330", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.330", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.330", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.330" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-7om9Xus6tfkeCUCfzg6ilJuN6Z7okkEvJ0mx+ukXa/Id5U/6BGtPkOYni+3ebedwa3b9SVF7A05+ln+/9EoU/w=="],
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]1", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.331", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.331", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.331", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.331", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.331", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.331", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.331", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.331" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-ml/MPqgO95tG5zcApBFxEyoDk57d9htP09R8AtPbKPUCHpsobf84IjkN4zhGvQgk8zsA9dXoeMGrQcCc8gQE/w=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-J9nqvcfD2V90O5uoR8At66R51VYtSMKnxSmPc0S4A4F5oX1VbokcpJLXU1yVCOuTtzr/OIHjRr9nn2vKi/S6rQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]1", "", { "os": "darwin", "cpu": "arm64" }, "sha512-PQrn7YTiSV5Bg+ueF2hNvswc+wI7YKC2c32XNedvs6vfMCUUnIlq93VEbZiRY23b+JIVkEm8gb1VhkJTjsYISQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]0", "", { "os": "darwin", "cpu": "x64" }, "sha512-woe+f9qeZYWML5fACibNyth0xMDf22riNRNDryIYuhdteh7IoWrK6zC31cC2MrZRoqDZcPVtfOLND79+iZbrLA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]1", "", { "os": "darwin", "cpu": "x64" }, "sha512-dc3iB+CY3jDpKpDpmvYc4V+UKSkudY29iJ62p0s5TK3h+b7Wqa2Hv0bPow0LUs4ZzDUXxEtCEHzk9X29VfLovw=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]0", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-2Q+kfzaoTvJv1rsyu+iR4UHDZ3nxiOfdXISk+2ydQShU9DqXNlgQAt3BdJMh0Yx4MrxB66TMphVvVQeRslwwhA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]1", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-xiRxBxoM8Qa5fnjCFk5iFheL5GUroLuHPJ7UnD4v2Sv1tWxGoSL67AYnMZ6OdjMguZK09X4WlgOn1nL1m6NEOA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]0", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-fXmuAEegw31v+kiBd51yn7RVhjs7Rz2lnhfx/+XJXqt5lyqR2v7Ul/U/9r1CQZKuIw8M3ms9jQqGpmKbgKndqQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]1", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-KdIClOdBUIpvf4PTFe2qedtPCOM3tC/jbsjh8U6WXF0QS8VjYkP0QR9i2AXG1PSAnI24T5xTxQb1scPAgRTIUQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]0", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-9w4uMdA3vNZXocwOUhivOGotXoRDxN/C/xPMkZMY9WPpKLAlj8upMZskNgPjQKlVRXhxPfNagcBijGPUH4WepA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]1", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-nfHSiLJdkpsVAFsXTriyW3r64gS1sp5zxvaoF2dmNqKixR4rf9ISDDi81gF9L1uk/bAEcBGRx34U6Itw+NYIEg=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]0", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-kooZMdp6tFwNFkDXbGoNTZMgFcPQfJVfG+gZ2qAdkk11S6MFts9ybHRLQmzUK3VrqlahH7T9fmI2mNfzYgOXkw=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]1", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-CSeT1JF++Vckf6TSXjQeuSjQ/sJnoTVL/XX44v4jHNAtU5i22nI9b27E6wkzudYVxoRoLWIU00V05dXhYYCvlg=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]0", "", { "os": "win32", "cpu": "arm64" }, "sha512-6jscch7vk/XBSn7mm1i6zwTeiz05q98nKrQ3HdTavQEDGvXycMcB/QxIdMrs3vrdNEjWuoxwrL1qlT1lOyAWLg=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]1", "", { "os": "win32", "cpu": "arm64" }, "sha512-FsPHWUpgHBFgSZESwM53JsbEoQiWPnigSCyjSfHDyiWnH66e0NsuksuJ/Nu9qI8UVgBDh/y1NOnnd4eGrB3eFQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]0", "", { "os": "win32", "cpu": "x64" }, "sha512-ooThWbUXlXKTDgj2VgWBXQ/6vSOTaAbBDWPvvCGNHi20haoSkw4uPX9gczkX+HJuVTslvvLiYIfe8zleVPzi7A=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]1", "", { "os": "win32", "cpu": "x64" }, "sha512-AsLur4ov9MGTQTrnZ49ZDPasQ35U3X/rZDdF/rPhytN3h1F3w/0IkC6esW3OzldvPlci60QvggOLVGnFlUzdxw=="],
|
||||
|
||||
"@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=="],
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ The action doesn't give Claude tools for these. In [auto mode](./usage.md#permis
|
||||
|
||||
- **Submit PR Reviews**: Claude cannot submit formal GitHub PR reviews
|
||||
- **Approve PRs**: For security reasons, Claude cannot approve pull requests
|
||||
- **Push to Other Branches**: By default, Claude can only push to the branch it was set up on: a new branch for an issue or closed PR, or the branch of an open PR. For a PR from a fork, that is a `pr-N` branch in your repository, and the fork's branch is not updated. [Keep that branch out of CI that holds secrets](./security.md#running-code-from-pull-requests)
|
||||
- **Push to Other Branches**: By default, Claude can only push to the branch it was set up on: a new branch for an issue or closed PR, or the branch of an open PR. For a PR from a fork, which needs [`allow_fork_prs`](./security.md#pull-requests-from-forks) set to `true`, that is a `pr-N` branch in your repository, and the fork's branch is not updated. [Keep that branch out of CI that holds secrets](./security.md#running-code-from-pull-requests)
|
||||
- **Post Multiple Comments**: Claude only acts by updating its initial comment
|
||||
- **Execute Commands Outside Its Context**: Claude only has access to the repository and PR/issue context it's triggered in
|
||||
- **Run Bash Commands Unchecked**: A Bash command runs only if an allow rule covers it or the safety review passes it
|
||||
|
||||
@@ -69,6 +69,8 @@ jobs:
|
||||
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
```
|
||||
|
||||
The action skips pull requests from forks unless [`allow_fork_prs`](./security.md#pull-requests-from-forks) is `true`.
|
||||
|
||||
Perfect for automatically reviewing PRs from new team members, external contributors, or specific developers who need extra guidance. The action automatically runs in agent mode when a `prompt` is provided.
|
||||
|
||||
## Custom Prompt Templates
|
||||
|
||||
+1
-1
@@ -98,7 +98,7 @@ Yes! Claude can access GitHub Actions workflow runs, job logs, and test results
|
||||
actions: read
|
||||
```
|
||||
|
||||
Claude will then be able to analyze CI failures and help debug workflow issues. For running tests locally before commits, you can still instruct Claude to do so in your request, except on pull requests whose author does not have write access. For pull requests from forks, see [Security](./security.md#running-code-from-pull-requests) for another way to get test results.
|
||||
Claude will then be able to analyze CI failures and help debug workflow issues. For running tests locally before commits, you can still instruct Claude to do so in your request, except on pull requests whose author does not have write access. For pull requests from forks, which need `allow_fork_prs: "true"`, see [Security](./security.md#running-code-from-pull-requests) for another way to get test results.
|
||||
|
||||
### Why does Claude only update one comment instead of creating new ones?
|
||||
|
||||
|
||||
+17
-11
@@ -26,7 +26,7 @@
|
||||
|
||||
## Using this action with `pull_request_target` or `workflow_run`
|
||||
|
||||
For `workflow_run` events, the action checks the repository access of the actor that started the upstream run (for example, the author of the fork pull request that triggered your CI workflow) in addition to the workflow actor. When the run came from a fork, it also checks the fork's owner, because GitHub credits a run to whoever caused it, such as a maintainer reopening the pull request. If any of these accounts does not have write access, the action stops before running Claude. To run on `workflow_run` events downstream of pull requests from contributors without write access, add those users to `allowed_non_write_users` and pass `github_token: ${{ secrets.GITHUB_TOKEN }}` — see the notes on that input above and keep the workflow's permissions minimal.
|
||||
For `workflow_run` events, the action checks the repository access of the actor that started the upstream run (for example, the author of the fork pull request that triggered your CI workflow) in addition to the workflow actor. When the run came from a fork, it also checks the fork's owner, because GitHub credits a run to whoever caused it, such as a maintainer reopening the pull request. If any of these accounts does not have write access, the action stops before running Claude. The action skips a run from a fork unless [`allow_fork_prs`](#pull-requests-from-forks) is `true`. To run on `workflow_run` events downstream of pull requests from contributors without write access, also add those users to `allowed_non_write_users` and pass `github_token: ${{ secrets.GITHUB_TOKEN }}` — see the notes on that input above and keep the workflow's permissions minimal.
|
||||
|
||||
`pull_request_target` and `workflow_run` execute with the **base repository's secrets**. If your workflow checks out the PR head (`ref: ${{ github.event.pull_request.head.sha }}` for `pull_request_target`, `ref: ${{ github.event.workflow_run.head_sha }}` for `workflow_run`) into `$GITHUB_WORKSPACE` before this action, the action and Claude run with that checkout as the working directory.
|
||||
|
||||
@@ -71,19 +71,23 @@ This doesn't cover other package managers, the `.env` files and `tsconfig.json`
|
||||
|
||||
Note that the runtime executing the tool also reads project config. `bunx <tool>` runs the tool's script under `node` when `node` is on `PATH` (as it is on GitHub-hosted runners); when only Bun is available, Bun executes the script itself and reads `bunfig.toml` from the checkout — including `preload` entries — which comes from the PR head. On such runners, make sure `node` is on `PATH` for the hook, and treat `bunfig.toml` and `.npmrc` in the checkout as PR-controlled runtime config on pull requests from authors with write access.
|
||||
|
||||
### Refusing pull requests from forks
|
||||
<a id="refusing-pull-requests-from-forks"></a>
|
||||
|
||||
By default, someone with write access can have the action work on a pull request from a fork. If you don't need that, turn it off, so that the action itself never checks out a fork's code:
|
||||
### Pull requests from forks
|
||||
|
||||
By default, the action skips pull requests from forks, so that it never checks out a fork's code itself. To let someone with write access have it work on them, read [Running code from pull requests](#running-code-from-pull-requests), then opt in:
|
||||
|
||||
```yaml
|
||||
- uses: anthropics/claude-code-action@v1
|
||||
with:
|
||||
allow_fork_prs: "false"
|
||||
allow_fork_prs: "true"
|
||||
```
|
||||
|
||||
The action then skips a pull request whose branch is in another repository, or in a fork that was deleted. It does so for every event, including comments on the conversation, whoever opened the pull request and whether it is open or closed. It also skips `workflow_run` events for a fork's run. It logs a warning, checks nothing out and doesn't start Claude, and the step succeeds without Claude's outputs, so a required check that only runs the action passes. Any value other than `true` turns forks off, including an empty one.
|
||||
Without that, the action skips a pull request whose branch is in another repository, or in a fork that was deleted. It does so for every event that names the pull request, including comments on the conversation, whoever opened the pull request and whether it is open or closed. It also skips `workflow_run` events for a fork's run. It logs a warning, checks nothing out and doesn't start Claude, and the step succeeds without Claude's outputs, so a required check that only runs the action passes without a review. A later step that needs the action's outputs has to handle empty ones. Any value other than `true` turns forks off, including an empty one.
|
||||
|
||||
For a comment on the conversation, the action asks GitHub where the branch is, after it has checked the commenter's write access. The token needs `pull-requests: read` for that. If the answer can't be read, the run fails before anything is checked out.
|
||||
Where a fork's event comes with credentials, the action first checks write access and, for a bot, `allowed_bots`, and a run that those checks refuse fails instead of being skipped. This covers comments on the conversation, `pull_request_target` and `workflow_run`, and in a private repository other events that get a token or the Anthropic secrets.
|
||||
|
||||
For a comment on the conversation that triggers it, the action asks GitHub where the branch is, after it has checked the commenter's write access. It does so for pull requests from your own repository too, so the token needs `pull-requests: read`. If the answer can't be read, the run fails before anything is checked out.
|
||||
|
||||
This covers what the action does with the event that started it. It doesn't cover:
|
||||
|
||||
@@ -93,6 +97,8 @@ This covers what the action does with the event that started it. It doesn't cove
|
||||
- **Commits already in your repository**, such as a `pr-N` branch from an earlier run, or a fork's commits that someone pushed to a branch of yours.
|
||||
- **Text.** Issues and comments from outside contributors still reach Claude.
|
||||
|
||||
**Upgrading:** `allow_fork_prs` used to default to `true`. Workflows that use a floating tag or branch such as `@v1` or `@main` get the new default without changing anything. If yours relied on Claude working on pull requests from forks, including your team's own forks, or on `workflow_run` events for a fork's run, set `allow_fork_prs: "true"`. This is needed with `allowed_non_write_users` too. Otherwise, a required check on those pull requests can now pass without Claude having run. If you already set it to `"false"`, runs with credentials that the write and bot checks refuse now fail where they used to be skipped. If it runs on comments on pull requests with a token of its own, check that the token has `pull-requests: read`.
|
||||
|
||||
### Running code from pull requests
|
||||
|
||||
A command that runs repository code (`npm install`, `bun test`, `make`) runs whatever the checkout contains, in a job that holds your workflow's tokens. Tag mode checks out the pull request's head, so on a pull request from an outside contributor that code is theirs, even when a maintainer triggered the run.
|
||||
@@ -105,13 +111,13 @@ By default, when the pull request's author does not have write access, the actio
|
||||
- **Text can still steer Claude.** On an issue or a trusted author's pull request these commands stay allowed, so text from an outside contributor could try to get Claude to edit a file and then run it. Keep the rules you grant in `claude_args` as narrow as you can.
|
||||
- **Other broad rules weaken the protections.** `Write` lets Claude write outside the workspace, and `Bash(git:*)` can still run programs through forms this list does not deny, such as `git rebase --exec`. Avoid them in workflows that handle outside contributions.
|
||||
|
||||
**Pushes on pull requests from forks:** in tag mode on an open pull request from a fork, Claude pushes to `pr-N` in your repository. That branch holds the fork's commits as well as Claude's, and GitHub's limits on runs from forks don't apply to it. A workflow or other CI that builds it runs the contributor's code and can have your secrets.
|
||||
**Pushes on pull requests from forks:** with `allow_fork_prs: "true"`, in tag mode on an open pull request from a fork, Claude pushes to `pr-N` in your repository. That branch holds the fork's commits as well as Claude's, and GitHub's limits on runs from forks don't apply to it. A workflow or other CI that builds it runs the contributor's code and can have your secrets.
|
||||
|
||||
- Keep `pr-*` out of CI that holds secrets, for example with `branches-ignore: ["pr-*"]` on `push` triggers, and check CI outside GitHub too.
|
||||
- Don't deploy or release from `pr-N`. Review the fork's commits before you merge the branch or open a pull request from it, and delete it when you are done.
|
||||
- To stop Claude's pushes in a workflow, on all pull requests and issues, add `--disallowedTools "Bash(git push:*)"` to `claude_args`. With `use_commit_signing`, also deny `mcp__github_file_ops`.
|
||||
|
||||
**Getting test results:** on pull requests from forks, run the tests in a separate `pull_request` workflow that needs no secrets, and let Claude read the outcome. The pull request's code then runs outside the job that holds Claude's tokens, which is not the case with `restrict_untrusted_prs: false`.
|
||||
**Getting test results:** if you [allow pull requests from forks](#pull-requests-from-forks), run their tests in a separate `pull_request` workflow that needs no secrets, and let Claude read the outcome. The pull request's code then runs outside the job that holds Claude's tokens, which is not the case with `restrict_untrusted_prs: false`.
|
||||
|
||||
1. In the test workflow, set `permissions: contents: read`. GitHub also limits the token to read access and withholds secrets on pull requests from forks of a public repository. That limit is the real protection, because a pull request can edit the workflow file.
|
||||
2. Set your repository to require approval for all external contributors. Review the changes, including workflow files, and then approve the runs. GitHub doesn't ask for approval on pull requests from members of your organization.
|
||||
@@ -130,7 +136,7 @@ Bots often open pull requests from branches in your own repository. Runs there u
|
||||
|
||||
Steps that run after Claude, including post steps such as `actions/checkout`'s cleanup, trust `GITHUB_ENV`, `GITHUB_PATH` and git's config files. When the session ends, the action restores those files, including config pulled in through `include.path`, to how they were before it started, and logs a warning naming any it changed. A session therefore can't pass environment variables to later steps through `GITHUB_ENV`, and `git config` changes it made, such as the upstream that `git push -u` records, don't last. Use `GITHUB_OUTPUT` or `--json-schema` to pass results on. What a session writes to `GITHUB_OUTPUT` and `GITHUB_STEP_SUMMARY` is kept, unless it replaced the file with a link or something else that isn't a file.
|
||||
|
||||
While Claude runs, and for the action's own git commands afterwards, git ignores `core.fsmonitor`. Git hooks are off for the action's own commits after the session, and from before the checkout on pull requests that `restrict_untrusted_prs` applies to. During the session these are set in the repository's git config and by the wrapper scripts. Global git config also sets `safe.bareRepository=explicit` for the session, so git won't use a repository it finds in a folder that has no `.git`. A workflow that has Claude work in a bare repository needs to pass `--git-dir`. If a run is cancelled before it restores this, the setting stays in the global config of a self-hosted runner that keeps its home directory. Git LFS uploads through a hook, so the action uploads objects itself for its own commits, but a push Claude makes on such a pull request won't include them.
|
||||
While Claude runs, and for the action's own git commands afterwards, git ignores `core.fsmonitor`. Git hooks are off for the action's own commits after the session, and from before the checkout on pull requests that `restrict_untrusted_prs` applies to. During the session these are set in the repository's git config and by the wrapper scripts. Global git config also sets `safe.bareRepository=explicit` for the session, so git won't use a repository it finds in a folder that has no `.git`. A workflow that has Claude work in a bare repository needs to pass `--git-dir`. If a run is killed before it restores this, the setting stays in the global config of a self-hosted runner that keeps its home directory. Git LFS uploads through a hook, so the action uploads objects itself for its own commits, but a push Claude makes on such a pull request won't include them.
|
||||
|
||||
The action's own git commands use `safe.bareRepository=explicit` too. If the action starts in a bare repository, it doesn't set this before the session, unless `restrict_untrusted_prs` applies. On pull requests that `restrict_untrusted_prs` applies to, the action also checks out the pull request with `GIT_LFS_SKIP_SMUDGE=1`, so files that Git LFS hasn't downloaded yet stay as pointer files. The variable is set for that checkout only.
|
||||
|
||||
@@ -139,7 +145,7 @@ Claude's wrapper scripts for `git add`, `git rm`, `git commit` and `git push` al
|
||||
This has limits:
|
||||
|
||||
- It is not a sandbox. Code running on the runner, for example through an allowed `npm test`, can stop the action before it restores anything, or change the files later steps run, including the code of this and other actions. An allow rule for `Write` can reach those files too, so treat it like allowing code to run.
|
||||
- A run that is cancelled or times out during the session does not restore anything, and later `always()` and post steps still run.
|
||||
- When a run is cancelled or times out during the session, the action stops Claude and what it started, restores these files and has the app token revoked. It also drops what the session wrote to `GITHUB_OUTPUT`. Later `always()` and post steps still run, and the tracking comment isn't updated. Processes that run as another user or no longer belong to one that Claude started keep running, and on Windows Claude itself can too. Nothing is restored or revoked when the action doesn't get the runner's signal, as in a job with `container:`, or can't react before the runner kills it, as during a long `git fetch`.
|
||||
- Submodule config, a repository checked out to a subdirectory, and an `include.path` target that does not exist yet are not restored.
|
||||
- The git settings need git 2.31 or newer, and `safe.bareRepository` needs 2.38. On older versions they have no effect.
|
||||
|
||||
@@ -152,7 +158,7 @@ This has limits:
|
||||
In its default configuration, **Claude does not create pull requests automatically** when responding to `@claude` mentions. Instead:
|
||||
|
||||
- Claude commits code changes to a new branch, or to the pull request's branch, through wrapper scripts in the action. A deny rule for `git add`, `git rm`, `git commit` or `git push` in `claude_args` also covers those scripts, including a narrower rule such as `git add -A:*`. A deny rule in a settings file doesn't, so pass it in `claude_args`
|
||||
- Claude's push command can't update any other branch. For a pull request from a fork, its branch is `pr-N` in your repository, which also holds the [fork's commits](#running-code-from-pull-requests), and the fork's branch is not updated
|
||||
- Claude's push command can't update any other branch. For a pull request from a fork, with `allow_fork_prs: "true"`, its branch is `pr-N` in your repository, which also holds the [fork's commits](#running-code-from-pull-requests), and the fork's branch is not updated
|
||||
- Branch protection on your default branch is still worth having: a workflow can allow other push commands, and a pull request opened from the default branch has that branch as its own
|
||||
- Claude provides a **link to the GitHub PR creation page** in its response
|
||||
- **The user must click the link and create the PR themselves**, ensuring human oversight before any code is proposed for merging
|
||||
|
||||
@@ -17,6 +17,8 @@ This guide provides complete, ready-to-use solutions for common automation scena
|
||||
|
||||
## Automatic PR Code Review
|
||||
|
||||
> The action skips pull requests from forks unless [`allow_fork_prs`](./security.md#pull-requests-from-forks) is `true`.
|
||||
|
||||
**When to use:** Automatically review every PR opened or updated in your repository.
|
||||
|
||||
### Basic Example (No Tracking)
|
||||
@@ -194,6 +196,8 @@ jobs:
|
||||
|
||||
**When to use:** Apply stricter review criteria for external or new contributors.
|
||||
|
||||
> As written, this doesn't run Claude on pull requests from forks, which is where first-time contributors' pull requests come from. See [Security](./security.md#pull-requests-from-forks) before you allow them.
|
||||
|
||||
**Complete Example:**
|
||||
|
||||
```yaml
|
||||
|
||||
+5
-5
@@ -84,7 +84,7 @@ jobs:
|
||||
| `include_comments_by_actor` | Comma-separated list of actor usernames to INCLUDE in comments. Supports the `*[bot]` wildcard to match all bot accounts. Empty (default) includes all actors | No | "" |
|
||||
| `exclude_comments_by_actor` | Comma-separated list of actor usernames to EXCLUDE from comments. Supports the `*[bot]` wildcard to match all bot accounts. If an actor matches both lists, exclusion takes priority | No | "" |
|
||||
| `allowed_bots` | Comma-separated list of allowed bot usernames, or '\*' to allow all bots. Empty string (default) allows no bots. **⚠️ On public repos with `'*'`, external Apps may be able to invoke this action.** See [Security](./security.md) | No | "" |
|
||||
| `allow_fork_prs` | Whether to run on pull requests from forks, and on `workflow_run` events for a fork's run. With any value other than `true`, the action skips them. See [Security](./security.md#refusing-pull-requests-from-forks). | No | `true` |
|
||||
| `allow_fork_prs` | Set to `true` to run on pull requests from forks, and on `workflow_run` events for a fork's run. By default, and with any other value, the action skips them. See [Security](./security.md#pull-requests-from-forks). | No | `false` |
|
||||
| `restrict_untrusted_prs` | On pull requests whose author does not have write access, deny commands that commonly run code from the checkout, even if `claude_args` allows them. See [Security](./security.md#running-code-from-pull-requests). | No | `true` |
|
||||
| `allowed_non_write_users` | **⚠️ RISKY**: Comma-separated list of usernames to allow without write permissions, or '\*' for all users. Only works with `github_token` input. See [Security](./security.md) | No | "" |
|
||||
| `path_to_claude_code_executable` | Optional path to a custom Claude Code executable. Skips automatic installation. Useful for Nix, custom containers, or specialized environments | No | "" |
|
||||
@@ -255,7 +255,7 @@ Get validated JSON results from Claude that automatically become GitHub Action o
|
||||
--json-schema '{"type":"object","properties":{"is_flaky":{"type":"boolean"},"confidence":{"type":"number"},"summary":{"type":"string"}},"required":["is_flaky"]}'
|
||||
|
||||
- name: Retry if flaky
|
||||
if: fromJSON(steps.analyze.outputs.structured_output).is_flaky == true
|
||||
if: fromJSON(steps.analyze.outputs.structured_output || '{}').is_flaky == true
|
||||
run: gh workflow run CI
|
||||
```
|
||||
|
||||
@@ -268,14 +268,14 @@ Get validated JSON results from Claude that automatically become GitHub Action o
|
||||
|
||||
### Accessing Structured Outputs
|
||||
|
||||
All structured output fields are available in the `structured_output` output as a JSON string:
|
||||
All structured output fields are available in the `structured_output` output as a JSON string. It is empty when the action skips the run, which is why these expressions fall back to `'{}'`. Test fields against `true`, because a missing field also equals `false`:
|
||||
|
||||
**In GitHub Actions expressions:**
|
||||
|
||||
```yaml
|
||||
if: |
|
||||
fromJSON(steps.analyze.outputs.structured_output).is_flaky == true &&
|
||||
fromJSON(steps.analyze.outputs.structured_output).confidence >= 0.7
|
||||
fromJSON(steps.analyze.outputs.structured_output || '{}').is_flaky == true &&
|
||||
fromJSON(steps.analyze.outputs.structured_output || '{}').confidence >= 0.7
|
||||
run: ./retry-tests.sh
|
||||
```
|
||||
|
||||
|
||||
@@ -6,7 +6,8 @@ on:
|
||||
|
||||
jobs:
|
||||
review-by-author:
|
||||
# Only run for PRs from specific authors
|
||||
# Only run for PRs from specific authors. The action skips PRs from forks by
|
||||
# default: see docs/security.md.
|
||||
if: |
|
||||
github.event.pull_request.user.login == 'developer1' ||
|
||||
github.event.pull_request.user.login == 'developer2' ||
|
||||
|
||||
@@ -17,7 +17,10 @@ permissions:
|
||||
jobs:
|
||||
detect-flaky:
|
||||
runs-on: ubuntu-latest
|
||||
if: ${{ github.event.workflow_run.conclusion == 'failure' }}
|
||||
# The action skips a fork's run by default, so skip it here too
|
||||
if: >-
|
||||
github.event.workflow_run.conclusion == 'failure' &&
|
||||
github.event.workflow_run.head_repository.id == github.event.repository.id
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"@actions/github": "^6.0.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.330",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.331",
|
||||
"@modelcontextprotocol/sdk": "^1.11.0",
|
||||
"@octokit/graphql": "^8.2.2",
|
||||
"@octokit/rest": "^21.1.1",
|
||||
|
||||
@@ -6,7 +6,7 @@ export function collectActionInputsPresence(): string {
|
||||
base_branch: "",
|
||||
branch_prefix: "claude/",
|
||||
allowed_bots: "",
|
||||
allow_fork_prs: "true",
|
||||
allow_fork_prs: "false",
|
||||
restrict_untrusted_prs: "true",
|
||||
mode: "tag",
|
||||
model: "",
|
||||
|
||||
+60
-13
@@ -16,6 +16,7 @@ import {
|
||||
checkBotActorPullRequestAuthor,
|
||||
checkWritePermissions,
|
||||
} from "../github/validation/permissions";
|
||||
import { checkHumanActor } from "../github/validation/actor";
|
||||
import {
|
||||
isCommentOnRefusedForkPr,
|
||||
isRefusedForkEvent,
|
||||
@@ -74,6 +75,7 @@ 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";
|
||||
import { preparePrompt } from "../../base-action/src/prepare-prompt";
|
||||
import { onCancel } from "../../base-action/src/cancel";
|
||||
import { runClaude } from "../../base-action/src/run-claude";
|
||||
import type { ClaudeRunResult } from "../../base-action/src/run-claude-sdk";
|
||||
import { setExecutionFileOutputIfPresent } from "../../base-action/src/execution-file";
|
||||
@@ -109,7 +111,7 @@ async function installClaudeCode(): Promise<string> {
|
||||
return customExecutable;
|
||||
}
|
||||
|
||||
const claudeCodeVersion = "2.1.330";
|
||||
const claudeCodeVersion = "2.1.331";
|
||||
console.log(`Installing Claude Code v${claudeCodeVersion}...`);
|
||||
|
||||
for (let attempt = 1; attempt <= 3; attempt++) {
|
||||
@@ -180,7 +182,7 @@ async function writeStepSummary(executionFile: string): Promise<void> {
|
||||
}
|
||||
|
||||
const FORK_REFUSED =
|
||||
"Skipped, because allow_fork_prs is not true and this pull request or workflow run is from a fork.";
|
||||
"Skipped, because allow_fork_prs is not true and this pull request or workflow run is from a fork. To allow forks, read 'Pull requests from forks' in docs/security.md in anthropics/claude-code-action, then set allow_fork_prs: \"true\".";
|
||||
|
||||
async function run() {
|
||||
// Bun has read this by now, and it's only for the action's own scripts
|
||||
@@ -202,13 +204,52 @@ async function run() {
|
||||
let restoredConfigPaths: string[] = [];
|
||||
// Track whether we've completed prepare phase, so we can attribute errors correctly
|
||||
let prepareCompleted = false;
|
||||
// Set while a session could be running
|
||||
let restoreSessionFiles: ReturnType<typeof snapshotSessionFiles> | undefined;
|
||||
let isFinishing = false;
|
||||
|
||||
// Revoking the app token depends on this output, and a session can write it.
|
||||
const keepRevocationOn = () =>
|
||||
core.setOutput("skipped_due_to_workflow_validation_mismatch", "false");
|
||||
|
||||
onCancel(
|
||||
[
|
||||
() => restoreSessionFiles?.({ cancelled: true }),
|
||||
() => restoreSessionFiles && keepRevocationOn(),
|
||||
// The step that revokes the app token reads it from here.
|
||||
() => githubToken && core.setOutput("github_token", githubToken),
|
||||
() => core.setOutput("branch_name", claudeBranch),
|
||||
// A session can write this one too.
|
||||
() => core.setOutput("conclusion", claudeSuccess ? "success" : "failure"),
|
||||
clearSessionState,
|
||||
() => workloadIdentity?.stop(),
|
||||
],
|
||||
() => isFinishing,
|
||||
);
|
||||
|
||||
try {
|
||||
// Phase 1: Prepare
|
||||
const actionInputsPresent = collectActionInputsPresence();
|
||||
context = parseGitHubContext();
|
||||
|
||||
// Before a token, which GitHub doesn't give to some of these events
|
||||
if (isRefusedForkEvent(context)) {
|
||||
// A fork's event with no credentials is skipped before a token is needed. One that
|
||||
// has them goes through the actor checks first: a run those refuse must fail, as
|
||||
// later steps in the job could use the credentials. pull_request_target and
|
||||
// workflow_run always have them. Other events from forks can have them only in a
|
||||
// private repository, depending on its settings.
|
||||
const isRefusedFork = isRefusedForkEvent(context);
|
||||
const hasRepositoryCredentials =
|
||||
isWorkflowRunEvent(context) ||
|
||||
process.env.GITHUB_EVENT_NAME === "pull_request_target" ||
|
||||
((context.payload.repository as { private?: boolean } | undefined)
|
||||
?.private === true &&
|
||||
!!(
|
||||
process.env.OVERRIDE_GITHUB_TOKEN ||
|
||||
process.env.ACTIONS_ID_TOKEN_REQUEST_URL ||
|
||||
process.env.ANTHROPIC_API_KEY ||
|
||||
process.env.CLAUDE_CODE_OAUTH_TOKEN
|
||||
));
|
||||
if (isRefusedFork && !hasRepositoryCredentials) {
|
||||
core.warning(FORK_REFUSED);
|
||||
return;
|
||||
}
|
||||
@@ -268,12 +309,6 @@ async function run() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Before the action checks anything out
|
||||
if (await isCommentOnRefusedForkPr(octokit.rest, context)) {
|
||||
core.warning(FORK_REFUSED);
|
||||
return;
|
||||
}
|
||||
|
||||
const botActorAllowed = await checkBotActorPullRequestAuthor(
|
||||
octokit.rest,
|
||||
context,
|
||||
@@ -286,6 +321,17 @@ async function run() {
|
||||
);
|
||||
}
|
||||
|
||||
// Before the action checks anything out
|
||||
if (
|
||||
isRefusedFork ||
|
||||
(await isCommentOnRefusedForkPr(octokit.rest, context))
|
||||
) {
|
||||
// Prepare would have refused a bot that isn't allowed
|
||||
await checkHumanActor(octokit.rest, context);
|
||||
core.warning(FORK_REFUSED);
|
||||
return;
|
||||
}
|
||||
|
||||
// Run prepare
|
||||
// Commands that run checkout code are denied on PRs from authors without write
|
||||
// access. Hooks go off here, before the action checks out such a PR's head, and
|
||||
@@ -430,7 +476,7 @@ async function run() {
|
||||
process.env.CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR = "1";
|
||||
}
|
||||
|
||||
const restoreSessionFiles = snapshotSessionFiles(() =>
|
||||
restoreSessionFiles = snapshotSessionFiles(() =>
|
||||
prepareGitForSession({ hooks: hooksOff }),
|
||||
);
|
||||
|
||||
@@ -451,8 +497,8 @@ async function run() {
|
||||
// The action's own git commands from here on hold the job's credentials,
|
||||
// and the session could have edited a tracked hook.
|
||||
disableGitPrograms({ hooks: true });
|
||||
// Revoking the app token depends on this output, and a session can write it.
|
||||
core.setOutput("skipped_due_to_workflow_validation_mismatch", "false");
|
||||
keepRevocationOn();
|
||||
restoreSessionFiles = undefined;
|
||||
}
|
||||
|
||||
claudeSuccess = claudeResult.conclusion === "success";
|
||||
@@ -480,6 +526,7 @@ async function run() {
|
||||
core.setFailed(`Action failed with error: ${redactSecrets(errorMessage)}`);
|
||||
} finally {
|
||||
// Phase 4: Cleanup (always runs)
|
||||
isFinishing = true;
|
||||
clearSessionState();
|
||||
|
||||
// Stop refreshing the workload identity token file and delete the token
|
||||
|
||||
@@ -216,28 +216,35 @@ function isItsOwnFile(before: FileSnapshot): boolean {
|
||||
/**
|
||||
* Records the files later steps trust, and returns a function that puts them
|
||||
* back. Call the returned function as soon as the session ends and before the
|
||||
* action runs git again. Replacing a file rather than writing to it means a
|
||||
* session cannot redirect the write by swapping in a symlink.
|
||||
* action runs git again. If the session was cancelled, that also drops the outputs it
|
||||
* wrote, because a half-written one would take the action's own with it. Replacing a
|
||||
* file rather than writing to it means a session cannot redirect the write by swapping
|
||||
* in a symlink.
|
||||
*
|
||||
* This stops a session that can only write through its tools. It is not a
|
||||
* sandbox: code running as the runner's user can stop the action before it
|
||||
* restores anything.
|
||||
*/
|
||||
export function snapshotSessionFiles(beforeSession?: () => void): () => void {
|
||||
export function snapshotSessionFiles(
|
||||
beforeSession?: () => void,
|
||||
): (options?: { cancelled: boolean }) => void {
|
||||
const files = filesLaterStepsTrust();
|
||||
const snapshots = files.map(readSnapshot);
|
||||
// What the action changes for the session goes back too, without a warning.
|
||||
beforeSession?.();
|
||||
const atStart = files.map(readSnapshot);
|
||||
|
||||
return () => {
|
||||
return ({ cancelled } = { cancelled: false }) => {
|
||||
const restored: string[] = [];
|
||||
for (const [index, before] of snapshots.entries()) {
|
||||
try {
|
||||
const now = readSnapshot(before);
|
||||
if (before.keepsWrites && isItsOwnFile(before)) continue;
|
||||
const dropsWrites = cancelled && before.label === "GITHUB_OUTPUT";
|
||||
const ownFile = before.keepsWrites && isItsOwnFile(before);
|
||||
if (ownFile && !dropsWrites) continue;
|
||||
// The file it leads to can have the same content so far.
|
||||
const leadsElsewhere = before.keepsWrites && now.state === "file";
|
||||
const leadsElsewhere =
|
||||
before.keepsWrites && !ownFile && now.state === "file";
|
||||
if (!leadsElsewhere && isUnchanged(before, now)) continue;
|
||||
const changedBySession =
|
||||
leadsElsewhere || !isUnchanged(atStart[index]!, now);
|
||||
|
||||
@@ -15,7 +15,7 @@ const isSameRepository = (head: Repository, base: Repository): boolean =>
|
||||
|
||||
// Only "true" allows forks, so a mistyped or empty value refuses them.
|
||||
export const forksAllowed = (): boolean =>
|
||||
(process.env.ALLOW_FORK_PRS ?? "true").trim().toLowerCase() === "true";
|
||||
process.env.ALLOW_FORK_PRS?.trim().toLowerCase() === "true";
|
||||
|
||||
/**
|
||||
* Whether allow_fork_prs is off and the event says that it is about a fork's pull
|
||||
|
||||
@@ -68,11 +68,11 @@ describe("action metadata", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("should allow fork pull requests by default and pass the input to the run step", () => {
|
||||
test("should refuse fork pull requests by default and pass the input to the run step", () => {
|
||||
const metadata = readMetadata("action.yml");
|
||||
|
||||
expect(metadata).toMatch(
|
||||
/^ allow_fork_prs:\n description: .+\n required: false\n default: "true"$/m,
|
||||
/^ allow_fork_prs:\n description: .+\n required: false\n default: "false"$/m,
|
||||
);
|
||||
expect(metadata).toMatch(
|
||||
/^ ALLOW_FORK_PRS: \$\{\{ inputs\.allow_fork_prs \}\}$/m,
|
||||
@@ -120,15 +120,15 @@ describe("action metadata", () => {
|
||||
},
|
||||
);
|
||||
|
||||
test("should let Bun finish when the shell is interrupted", async () => {
|
||||
test("should let Bun clean up when the step is interrupted", async () => {
|
||||
const { output, exitCode } = await runStep(
|
||||
path,
|
||||
`exec "${process.execPath}" -e 'console.log("started"); setTimeout(() => console.log("finished"), 500)'`,
|
||||
`exec "${process.execPath}" -e 'process.once("SIGINT", () => { console.log("cleaned up"); process.exit(130) }); setTimeout(() => {}, 5000); console.log("started")'`,
|
||||
true,
|
||||
);
|
||||
|
||||
expect(output).toBe("started\nfinished\n");
|
||||
expect(exitCode).toBe(0);
|
||||
expect(output).toBe("started\ncleaned up\n");
|
||||
expect(exitCode).toBe(130);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { execFileSync } from "child_process";
|
||||
import {
|
||||
chmodSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readdirSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
} from "fs";
|
||||
import { tmpdir } from "os";
|
||||
import { join } from "path";
|
||||
|
||||
const isRunning = (pid: number) => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
// A process that has ended but that nobody waited for still has an entry.
|
||||
return !/^\S+ \(.*\) Z/s.test(readFileSync(`/proc/${pid}/stat`, "utf8"));
|
||||
} catch (error) {
|
||||
return (error as { code?: string }).code === "ENOENT"
|
||||
? process.platform !== "linux"
|
||||
: false;
|
||||
}
|
||||
};
|
||||
|
||||
async function until(condition: () => boolean, what: string) {
|
||||
for (let i = 0; i < 200; i++) {
|
||||
if (condition()) return;
|
||||
await Bun.sleep(50);
|
||||
}
|
||||
throw new Error(`Timed out waiting for ${what}`);
|
||||
}
|
||||
|
||||
// Like a session. Its child is in its own process group, and both ignore SIGTERM. A
|
||||
// third process takes SIGTERM as git does, which removes its lock files.
|
||||
const SESSION = `#!/bin/bash
|
||||
trap '' TERM INT
|
||||
perl -e 'use POSIX; POSIX::setsid(); sleep 300' &
|
||||
child=$!
|
||||
perl -e '$SIG{TERM} = sub { unlink "$ENV{TEST_DIR}/lock"; exit }; open(F, ">$ENV{TEST_DIR}/lock"); sleep 300' &
|
||||
git_like=$!
|
||||
echo "$$ $child $git_like" > "$TEST_DIR/pids"
|
||||
until [ -e "$TEST_DIR/lock" ]; do sleep 0.05; done
|
||||
echo 'ADDED=1' >> "$GITHUB_ENV"
|
||||
printf '%s\\n' skipped_due_to_workflow_validation_mismatch=true conclusion=success >> "$GITHUB_OUTPUT"
|
||||
eval "$IN_SESSION"
|
||||
touch "$TEST_DIR/started"
|
||||
while :; do sleep 1; done
|
||||
`;
|
||||
|
||||
const stepScript = (metadata: string) =>
|
||||
metadata
|
||||
.split(/^ - name: /m)
|
||||
.find((step) => step.includes("${GITHUB_ACTION_PATH}/src/"))!
|
||||
.match(/^ run: \|\n((?: {8}.*\n|\n)+)/m)![1]!
|
||||
.replace(/^ {8}/gm, "");
|
||||
|
||||
const parseOutputs = (file: string) =>
|
||||
Object.fromEntries(
|
||||
[
|
||||
...readFileSync(file, "utf8").matchAll(
|
||||
/^([^=\n]+?)(?:=|<<(\S+)\n)(.*)$(?:\n\2$)?/gm,
|
||||
),
|
||||
].map(([, name, , value]) => [name, value]),
|
||||
);
|
||||
|
||||
/** Runs an action's step, as the runner does, and cancels it during the session. */
|
||||
async function cancelStep(
|
||||
actionDir: string,
|
||||
{ signals = ["SIGINT"] as NodeJS.Signals[], inSession = ":" } = {},
|
||||
) {
|
||||
const source = join(import.meta.dir, "..", actionDir);
|
||||
const dir = mkdtempSync(join(tmpdir(), "cancel-"));
|
||||
const path = (file: string) => join(dir, file);
|
||||
const server = Bun.serve({
|
||||
port: 0,
|
||||
hostname: "127.0.0.1",
|
||||
fetch: () =>
|
||||
Response.json({ login: "writer", type: "User", value: "identity" }),
|
||||
});
|
||||
const pids = () =>
|
||||
existsSync(path("pids"))
|
||||
? [...readFileSync(path("pids"), "utf8").matchAll(/\d+/g)].map(Number)
|
||||
: [];
|
||||
let step: Bun.Subprocess | undefined;
|
||||
try {
|
||||
// The action keeps files for the session in its own directory.
|
||||
for (const name of ["repo", "bin", "outputs", "action", "action/scripts"]) {
|
||||
mkdirSync(path(name));
|
||||
}
|
||||
for (const name of readdirSync(source)) {
|
||||
if (name === "scripts") continue;
|
||||
symlinkSync(join(source, name), path(join("action", name)));
|
||||
}
|
||||
execFileSync("git", ["init", "-q", path("repo")]);
|
||||
for (const file of ["outputs/output", "env", "path"]) {
|
||||
writeFileSync(path(file), "");
|
||||
}
|
||||
writeFileSync(path("event.json"), JSON.stringify({ inputs: {} }));
|
||||
writeFileSync(path("prompt.txt"), "x");
|
||||
writeFileSync(path("claude"), SESSION, { mode: 0o755 });
|
||||
writeFileSync(
|
||||
path("step.sh"),
|
||||
stepScript(readFileSync(join(source, "action.yml"), "utf8")),
|
||||
);
|
||||
writeFileSync(
|
||||
path("bin/bun"),
|
||||
`#!/bin/bash\nexec "${process.execPath}" "$@"\n`,
|
||||
{ mode: 0o755 },
|
||||
);
|
||||
|
||||
const running = Bun.spawn(
|
||||
[
|
||||
"bash",
|
||||
"--noprofile",
|
||||
"--norc",
|
||||
"-e",
|
||||
"-o",
|
||||
"pipefail",
|
||||
path("step.sh"),
|
||||
],
|
||||
{
|
||||
cwd: path("repo"),
|
||||
stdout: "ignore",
|
||||
stderr: "ignore",
|
||||
env: {
|
||||
PATH: `${path("bin")}:${process.env.PATH}`,
|
||||
HOME: dir,
|
||||
RUNNER_TEMP: dir,
|
||||
TEST_DIR: dir,
|
||||
IN_SESSION: inSession,
|
||||
GITHUB_ACTION_PATH: path("action"),
|
||||
GITHUB_API_URL: `http://127.0.0.1:${server.port}`,
|
||||
GITHUB_EVENT_NAME: "workflow_dispatch",
|
||||
GITHUB_EVENT_PATH: path("event.json"),
|
||||
GITHUB_REPOSITORY: "o/r",
|
||||
GITHUB_ACTOR: "writer",
|
||||
GITHUB_RUN_ID: "1",
|
||||
GITHUB_OUTPUT: path("outputs/output"),
|
||||
GITHUB_ENV: path("env"),
|
||||
GITHUB_PATH: path("path"),
|
||||
OVERRIDE_GITHUB_TOKEN: "the-token",
|
||||
ANTHROPIC_FEDERATION_RULE_ID: "rule",
|
||||
ANTHROPIC_ORGANIZATION_ID: "org",
|
||||
ACTIONS_ID_TOKEN_REQUEST_URL: `http://127.0.0.1:${server.port}/?`,
|
||||
ACTIONS_ID_TOKEN_REQUEST_TOKEN: "unused",
|
||||
PROMPT: "x",
|
||||
INPUT_PROMPT_FILE: path("prompt.txt"),
|
||||
PATH_TO_CLAUDE_CODE_EXECUTABLE: path("claude"),
|
||||
INPUT_PATH_TO_CLAUDE_CODE_EXECUTABLE: path("claude"),
|
||||
},
|
||||
},
|
||||
);
|
||||
step = running;
|
||||
await until(() => existsSync(path("started")), "the session");
|
||||
expect(pids().slice(0, 3).map(isRunning)).toEqual([true, true, true]);
|
||||
const identity = path("claude-workload-identity");
|
||||
expect(existsSync(identity)).toBe(true);
|
||||
|
||||
// The runner signals the step's own process and nothing else.
|
||||
for (const name of signals) running.kill(name);
|
||||
const exitCode = await running.exited;
|
||||
// What was killed can take a moment to be gone.
|
||||
await until(() => !pids().some(isRunning), "the session to end");
|
||||
|
||||
return {
|
||||
exitCode,
|
||||
outputs: parseOutputs(path("outputs/output")),
|
||||
env: readFileSync(path("env"), "utf8"),
|
||||
leftBehind: [path("lock"), identity]
|
||||
.filter(existsSync)
|
||||
.concat(readdirSync(path("action/scripts"))),
|
||||
};
|
||||
} finally {
|
||||
step?.kill("SIGKILL");
|
||||
chmodSync(path("outputs"), 0o755);
|
||||
for (const pid of pids().filter(isRunning)) process.kill(pid, "SIGKILL");
|
||||
server.stop(true);
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
describe.skipIf(process.platform === "win32")("a cancelled run", () => {
|
||||
test.each([
|
||||
[["SIGINT"]],
|
||||
[["SIGTERM"]],
|
||||
[["SIGINT", "SIGINT", "SIGTERM"]],
|
||||
] as [NodeJS.Signals[]][])(
|
||||
"stops the session and has the app token revoked (%p)",
|
||||
async (signals) => {
|
||||
const result = await cancelStep("", { signals });
|
||||
|
||||
expect(result).toMatchObject({
|
||||
exitCode: 130,
|
||||
leftBehind: [],
|
||||
outputs: {
|
||||
github_token: "the-token",
|
||||
// A session can't have the revocation skipped, or report success.
|
||||
skipped_due_to_workflow_validation_mismatch: "false",
|
||||
conclusion: "failure",
|
||||
},
|
||||
});
|
||||
expect(result.env).not.toContain("ADDED");
|
||||
},
|
||||
20_000,
|
||||
);
|
||||
|
||||
test("stops every process a session keeps starting", async () => {
|
||||
const result = await cancelStep("", {
|
||||
inSession:
|
||||
'bash -c "while :; do sleep 30.25 & echo \\$! >> \\"$TEST_DIR/pids\\"; sleep 0.005; done" & until [ $(wc -l < "$TEST_DIR/pids") -gt 9 ]; do sleep 0.05; done',
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({ exitCode: 130, leftBehind: [] });
|
||||
}, 20_000);
|
||||
|
||||
test("writes its outputs when the session was in the middle of one", async () => {
|
||||
const result = await cancelStep("", {
|
||||
inSession: `echo 'report<<END' >> "$GITHUB_OUTPUT"`,
|
||||
});
|
||||
|
||||
expect(result.outputs).toEqual({
|
||||
skipped_due_to_workflow_validation_mismatch: "false",
|
||||
github_token: "the-token",
|
||||
branch_name: "",
|
||||
conclusion: "failure",
|
||||
});
|
||||
}, 20_000);
|
||||
|
||||
test("stops the session in the base action", async () => {
|
||||
const result = await cancelStep("base-action");
|
||||
|
||||
expect(result).toMatchObject({
|
||||
exitCode: 130,
|
||||
leftBehind: [],
|
||||
outputs: { conclusion: "failure" },
|
||||
});
|
||||
}, 20_000);
|
||||
|
||||
test.skipIf(process.getuid?.() === 0)(
|
||||
"cleans up what it can when outputs can't be written",
|
||||
async () => {
|
||||
const result = await cancelStep("", {
|
||||
inSession: 'chmod a-w "$GITHUB_OUTPUT" "$(dirname "$GITHUB_OUTPUT")"',
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({ exitCode: 130, leftBehind: [] });
|
||||
expect(result.env).not.toContain("ADDED");
|
||||
},
|
||||
20_000,
|
||||
);
|
||||
});
|
||||
|
||||
describe("onCancel", () => {
|
||||
// Prints once it is ready, and finishes by itself after a second.
|
||||
const finishing = (...signals: NodeJS.Signals[]) => {
|
||||
const source = join(import.meta.dir, "../base-action/src/cancel.ts");
|
||||
const child = Bun.spawn(
|
||||
[
|
||||
process.execPath,
|
||||
"-e",
|
||||
`import { onCancel } from ${JSON.stringify(source)};
|
||||
onCancel([() => console.log("stopped")], () => true);
|
||||
setTimeout(() => { console.log("finished"); process.exit(0); }, 1000);
|
||||
console.log("ready");`,
|
||||
],
|
||||
{ stdout: "pipe" },
|
||||
);
|
||||
return (async () => {
|
||||
let output = "";
|
||||
for await (const chunk of child.stdout) {
|
||||
output += new TextDecoder().decode(chunk);
|
||||
if (output === "ready\n") signals.forEach((name) => child.kill(name));
|
||||
}
|
||||
return { output, exitCode: await child.exited };
|
||||
})();
|
||||
};
|
||||
|
||||
test.skipIf(process.platform === "win32")(
|
||||
"lets a run whose session has ended finish until the second signal",
|
||||
async () => {
|
||||
expect(await finishing("SIGINT")).toEqual({
|
||||
output: "ready\nfinished\n",
|
||||
exitCode: 0,
|
||||
});
|
||||
expect(await finishing("SIGINT", "SIGTERM")).toEqual({
|
||||
output: "ready\nstopped\n",
|
||||
exitCode: 130,
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -140,6 +140,7 @@ describe("in a shallow checkout of the default branch", () => {
|
||||
let originalCwd: string;
|
||||
let dir: string;
|
||||
let head: string;
|
||||
const allowForkPrs = process.env.ALLOW_FORK_PRS;
|
||||
const git = (cwd: string, ...args: string[]) =>
|
||||
execFileSync(
|
||||
"git",
|
||||
@@ -173,9 +174,12 @@ describe("in a shallow checkout of the default branch", () => {
|
||||
git(checkout, "fetch", "--depth=1", "origin", "trunk");
|
||||
git(checkout, "checkout", "-B", "trunk", "origin/trunk");
|
||||
process.chdir(checkout);
|
||||
process.env.ALLOW_FORK_PRS = "true";
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (allowForkPrs === undefined) delete process.env.ALLOW_FORK_PRS;
|
||||
else process.env.ALLOW_FORK_PRS = allowForkPrs;
|
||||
process.chdir(originalCwd);
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
+123
-6
@@ -97,9 +97,9 @@ describe("allow_fork_prs", () => {
|
||||
},
|
||||
);
|
||||
|
||||
test("allows forks when action.yml didn't pass the input", async () => {
|
||||
test("refuses forks when the input isn't passed", async () => {
|
||||
delete process.env.ALLOW_FORK_PRS;
|
||||
expect(await isRefusedForkPr(unused, fork)).toBe(false);
|
||||
expect(await isRefusedForkPr(unused, fork)).toBe(true);
|
||||
});
|
||||
|
||||
test.each(["false", "False", "", "no", "flase", "0"])(
|
||||
@@ -185,10 +185,15 @@ test("setupBranch refuses a fork when allow_fork_prs is off", async () => {
|
||||
}
|
||||
});
|
||||
|
||||
describe("run.ts with allow_fork_prs: false", () => {
|
||||
describe("run.ts with allow_fork_prs off, the default", () => {
|
||||
// Returns the exit code, the output and the requests made. The directory is not a
|
||||
// git repository, so a run that goes on to check something out fails.
|
||||
async function run(eventName: string, event: object, pull?: object) {
|
||||
async function run(
|
||||
eventName: string,
|
||||
event: object,
|
||||
pull?: object,
|
||||
env: Record<string, string> = {},
|
||||
) {
|
||||
const dir = mkdtempSync(join(tmpdir(), "fork-pr-"));
|
||||
const requests: string[] = [];
|
||||
const server = Bun.serve({
|
||||
@@ -197,8 +202,13 @@ describe("run.ts with allow_fork_prs: false", () => {
|
||||
fetch(request) {
|
||||
const { pathname } = new URL(request.url);
|
||||
requests.push(pathname);
|
||||
if (pathname.startsWith("/users/")) {
|
||||
const type = pathname.includes("bot") ? "Bot" : "User";
|
||||
return Response.json({ type });
|
||||
}
|
||||
if (pathname.endsWith("/permission")) {
|
||||
return Response.json({ permission: "write" });
|
||||
const writer = pathname.includes("/writer/");
|
||||
return Response.json({ permission: writer ? "write" : "read" });
|
||||
}
|
||||
return pull && pathname.endsWith("/pulls/7")
|
||||
? Response.json(pull)
|
||||
@@ -231,9 +241,9 @@ describe("run.ts with allow_fork_prs: false", () => {
|
||||
GITHUB_ENV: join(dir, "env"),
|
||||
GITHUB_API_URL: `http://127.0.0.1:${server.port}`,
|
||||
TRIGGER_PHRASE: "@claude",
|
||||
ALLOW_FORK_PRS: "false",
|
||||
// With no token, a run that asks for one fails.
|
||||
...(pull && { OVERRIDE_GITHUB_TOKEN: "t" }),
|
||||
...env,
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -282,9 +292,116 @@ describe("run.ts with allow_fork_prs: false", () => {
|
||||
expect(result.requests).toEqual([
|
||||
"/repos/o/r/collaborators/writer/permission",
|
||||
"/repos/o/r/pulls/7",
|
||||
"/users/writer",
|
||||
]);
|
||||
});
|
||||
|
||||
test.each([
|
||||
["writer", "pull_request_target", 0],
|
||||
["outsider", "pull_request_target", 1],
|
||||
["writer", "workflow_run", 0],
|
||||
["outsider", "workflow_run", 1],
|
||||
])("%s's fork on %s exits %p", async (login, eventName, exitCode) => {
|
||||
const actor = { login, type: "User" };
|
||||
const head = { ...FORK, full_name: `${login}/r` };
|
||||
const event =
|
||||
eventName === "workflow_run"
|
||||
? {
|
||||
action: "completed",
|
||||
repository: { ...repository, full_name: "o/r" },
|
||||
sender: actor,
|
||||
workflow_run: { id: 1, actor, head_repository: head },
|
||||
}
|
||||
: {
|
||||
action: "opened",
|
||||
repository,
|
||||
sender: actor,
|
||||
pull_request: { number: 7, user: actor, ...pullRequest(FORK) },
|
||||
};
|
||||
const env = { GITHUB_ACTOR: login, PROMPT: "Review this" };
|
||||
const result = await run(eventName, event, pullRequest(FORK), env);
|
||||
expect(result.exitCode).toBe(exitCode);
|
||||
expect(result.log).toContain(
|
||||
exitCode
|
||||
? "Actor does not have write permissions"
|
||||
: "Skipped, because allow_fork_prs",
|
||||
);
|
||||
});
|
||||
|
||||
test("a bot's action on an outsider's fork still fails", async () => {
|
||||
const bot = { login: "helper[bot]", type: "Bot" };
|
||||
const result = await run(
|
||||
"pull_request_target",
|
||||
{
|
||||
action: "synchronize",
|
||||
repository,
|
||||
sender: bot,
|
||||
pull_request: {
|
||||
number: 7,
|
||||
user: { login: "outsider" },
|
||||
...pullRequest(FORK),
|
||||
},
|
||||
},
|
||||
pullRequest(FORK),
|
||||
{ GITHUB_ACTOR: bot.login, ALLOWED_BOTS: "*", PROMPT: "Review this" },
|
||||
);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.log).toContain("A bot acted on this pull request");
|
||||
});
|
||||
|
||||
test.each([
|
||||
["writer", "t", "", 0],
|
||||
["outsider", "t", "", 1],
|
||||
["outsider", "", "", 0],
|
||||
["outsider", "", "key", 1],
|
||||
])(
|
||||
"%s's fork in a private repository with token %p and key %p exits %p",
|
||||
async (login, token, key, exitCode) => {
|
||||
const actor = { login, type: "User" };
|
||||
const result = await run(
|
||||
"pull_request",
|
||||
{
|
||||
action: "opened",
|
||||
repository: { ...repository, private: true },
|
||||
sender: actor,
|
||||
pull_request: { number: 7, user: actor, ...pullRequest(FORK) },
|
||||
},
|
||||
pullRequest(FORK),
|
||||
{
|
||||
GITHUB_ACTOR: login,
|
||||
PROMPT: "Review",
|
||||
OVERRIDE_GITHUB_TOKEN: token,
|
||||
ANTHROPIC_API_KEY: key,
|
||||
},
|
||||
);
|
||||
expect(result.exitCode).toBe(exitCode);
|
||||
},
|
||||
30_000, // without a token, the action retries before it fails
|
||||
);
|
||||
|
||||
test.each([
|
||||
["", 1],
|
||||
["helper", 0],
|
||||
])(
|
||||
"a bot's own fork with allowed_bots %p exits %p",
|
||||
async (bots, exitCode) => {
|
||||
const bot = { login: "helper[bot]", type: "Bot" };
|
||||
const result = await run(
|
||||
"pull_request_target",
|
||||
{
|
||||
action: "opened",
|
||||
repository,
|
||||
sender: bot,
|
||||
pull_request: { number: 7, user: bot, ...pullRequest(FORK) },
|
||||
},
|
||||
pullRequest(FORK),
|
||||
{ GITHUB_ACTOR: bot.login, ALLOWED_BOTS: bots, PROMPT: "Review" },
|
||||
);
|
||||
expect(result.exitCode).toBe(exitCode);
|
||||
if (exitCode) expect(result.log).toContain("non-human actor");
|
||||
},
|
||||
);
|
||||
|
||||
test("goes on with a comment on a pull request in this repository", async () => {
|
||||
const result = await run(
|
||||
"issue_comment",
|
||||
|
||||
Reference in New Issue
Block a user