mirror of
https://github.com/anthropics/claude-code-action.git
synced 2026-11-24 06:31:00 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b5e37652b7 | ||
|
|
423df53bc5 | ||
|
|
acfe799285 | ||
|
|
3c38c04401 | ||
|
|
c84e279f85 | ||
|
|
f431adaf77 |
+7
-10
@@ -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.327"
|
||||
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.327",
|
||||
"@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]27", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.327", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.327", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.327", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.327", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.327", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.327", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.327", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.327" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-zS5RIrYphnhftgafFUpNCGwNUwR6UzLUv3cEy6iD1+LDxmVKnwJAaYTgzgsdijqwuGvcpeiWmbkVrEk0Jc4M5A=="],
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]31", "", { "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]27", "", { "os": "darwin", "cpu": "arm64" }, "sha512-n+tQOPqz264l12BAKBcBPBbdB/bmZ2SfyONtEXQufTU6EeCoQMPS58RSt51Cxk5sDUme1hTF0vVAqRPdhq8tFg=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]31", "", { "os": "darwin", "cpu": "arm64" }, "sha512-PQrn7YTiSV5Bg+ueF2hNvswc+wI7YKC2c32XNedvs6vfMCUUnIlq93VEbZiRY23b+JIVkEm8gb1VhkJTjsYISQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]27", "", { "os": "darwin", "cpu": "x64" }, "sha512-u091X+eQIyqg8BIEYLWJ0o6U3BaivMcf8Im4hI3hti/NGJ6YC5sR+LLEa1RjSIKE+JoOfCxipdCNSKaEI+0d5Q=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]31", "", { "os": "darwin", "cpu": "x64" }, "sha512-dc3iB+CY3jDpKpDpmvYc4V+UKSkudY29iJ62p0s5TK3h+b7Wqa2Hv0bPow0LUs4ZzDUXxEtCEHzk9X29VfLovw=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]27", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-/k6BfV+L2er67UoLUabcp0w3L1DMemJjoijdxvXDiU8w81fGfHaKWKhRuhUQFmIrMLyMyQcBKaoyUNSLWovPnw=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]31", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-xiRxBxoM8Qa5fnjCFk5iFheL5GUroLuHPJ7UnD4v2Sv1tWxGoSL67AYnMZ6OdjMguZK09X4WlgOn1nL1m6NEOA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]27", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-oV8/+ZixiPzEW1BStoP9FOXsHcznONaom6S2PwwIfhi5Pxa5fGuloy8TiOB9wK+03zavqt7jmzLgVPF2a2NsTA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]31", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-KdIClOdBUIpvf4PTFe2qedtPCOM3tC/jbsjh8U6WXF0QS8VjYkP0QR9i2AXG1PSAnI24T5xTxQb1scPAgRTIUQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]27", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-oAdL7KM9UVAZlATeSjh2haeEjex1N7ZcHzWO1tY2hgyhkyLNVw/tWUhITOucxMwokBx++h2dMVjxiPJiZ5uVOQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]31", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-nfHSiLJdkpsVAFsXTriyW3r64gS1sp5zxvaoF2dmNqKixR4rf9ISDDi81gF9L1uk/bAEcBGRx34U6Itw+NYIEg=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]27", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-O0nDZ1gpXi83qAdd8SM0gTdjlzrqpOlW0M4W7PfHVrMXWLh9I+1tvHat+s17ehIW6A9VQIWIq4oMwq7jb708Dg=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]31", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-CSeT1JF++Vckf6TSXjQeuSjQ/sJnoTVL/XX44v4jHNAtU5i22nI9b27E6wkzudYVxoRoLWIU00V05dXhYYCvlg=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]27", "", { "os": "win32", "cpu": "arm64" }, "sha512-a5ju83mylDvUwvQyRt1E0TQ0ar2nzVMPeWZhjcmgpB1cNTjf+KT5jgUnLvxPOG2tyjhm8bYGysRMdgB+tVnhvw=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]31", "", { "os": "win32", "cpu": "arm64" }, "sha512-FsPHWUpgHBFgSZESwM53JsbEoQiWPnigSCyjSfHDyiWnH66e0NsuksuJ/Nu9qI8UVgBDh/y1NOnnd4eGrB3eFQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]27", "", { "os": "win32", "cpu": "x64" }, "sha512-bf52nw4j5RCvkXI5Poj5Qf0jWvuLQ/UPFqdav86UwaGTZZ0txNV33MKBIUoCyxXV6IC1/p2BNfkwmCAZ+Uc9pw=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]31", "", { "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.327",
|
||||
"@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.327",
|
||||
"@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]27", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.327", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.327", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.327", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.327", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.327", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.327", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.327", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.327" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-zS5RIrYphnhftgafFUpNCGwNUwR6UzLUv3cEy6iD1+LDxmVKnwJAaYTgzgsdijqwuGvcpeiWmbkVrEk0Jc4M5A=="],
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]31", "", { "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]27", "", { "os": "darwin", "cpu": "arm64" }, "sha512-n+tQOPqz264l12BAKBcBPBbdB/bmZ2SfyONtEXQufTU6EeCoQMPS58RSt51Cxk5sDUme1hTF0vVAqRPdhq8tFg=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected]31", "", { "os": "darwin", "cpu": "arm64" }, "sha512-PQrn7YTiSV5Bg+ueF2hNvswc+wI7YKC2c32XNedvs6vfMCUUnIlq93VEbZiRY23b+JIVkEm8gb1VhkJTjsYISQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]27", "", { "os": "darwin", "cpu": "x64" }, "sha512-u091X+eQIyqg8BIEYLWJ0o6U3BaivMcf8Im4hI3hti/NGJ6YC5sR+LLEa1RjSIKE+JoOfCxipdCNSKaEI+0d5Q=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected]31", "", { "os": "darwin", "cpu": "x64" }, "sha512-dc3iB+CY3jDpKpDpmvYc4V+UKSkudY29iJ62p0s5TK3h+b7Wqa2Hv0bPow0LUs4ZzDUXxEtCEHzk9X29VfLovw=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]27", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-/k6BfV+L2er67UoLUabcp0w3L1DMemJjoijdxvXDiU8w81fGfHaKWKhRuhUQFmIrMLyMyQcBKaoyUNSLWovPnw=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected]31", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-xiRxBxoM8Qa5fnjCFk5iFheL5GUroLuHPJ7UnD4v2Sv1tWxGoSL67AYnMZ6OdjMguZK09X4WlgOn1nL1m6NEOA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]27", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-oV8/+ZixiPzEW1BStoP9FOXsHcznONaom6S2PwwIfhi5Pxa5fGuloy8TiOB9wK+03zavqt7jmzLgVPF2a2NsTA=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected]31", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-KdIClOdBUIpvf4PTFe2qedtPCOM3tC/jbsjh8U6WXF0QS8VjYkP0QR9i2AXG1PSAnI24T5xTxQb1scPAgRTIUQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]27", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-oAdL7KM9UVAZlATeSjh2haeEjex1N7ZcHzWO1tY2hgyhkyLNVw/tWUhITOucxMwokBx++h2dMVjxiPJiZ5uVOQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected]31", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-nfHSiLJdkpsVAFsXTriyW3r64gS1sp5zxvaoF2dmNqKixR4rf9ISDDi81gF9L1uk/bAEcBGRx34U6Itw+NYIEg=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]27", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-O0nDZ1gpXi83qAdd8SM0gTdjlzrqpOlW0M4W7PfHVrMXWLh9I+1tvHat+s17ehIW6A9VQIWIq4oMwq7jb708Dg=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected]31", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-CSeT1JF++Vckf6TSXjQeuSjQ/sJnoTVL/XX44v4jHNAtU5i22nI9b27E6wkzudYVxoRoLWIU00V05dXhYYCvlg=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]27", "", { "os": "win32", "cpu": "arm64" }, "sha512-a5ju83mylDvUwvQyRt1E0TQ0ar2nzVMPeWZhjcmgpB1cNTjf+KT5jgUnLvxPOG2tyjhm8bYGysRMdgB+tVnhvw=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected]31", "", { "os": "win32", "cpu": "arm64" }, "sha512-FsPHWUpgHBFgSZESwM53JsbEoQiWPnigSCyjSfHDyiWnH66e0NsuksuJ/Nu9qI8UVgBDh/y1NOnnd4eGrB3eFQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]27", "", { "os": "win32", "cpu": "x64" }, "sha512-bf52nw4j5RCvkXI5Poj5Qf0jWvuLQ/UPFqdav86UwaGTZZ0txNV33MKBIUoCyxXV6IC1/p2BNfkwmCAZ+Uc9pw=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected]31", "", { "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=="],
|
||||
|
||||
|
||||
+4
-2
@@ -65,6 +65,8 @@ Everything else in the working tree — including `package.json`, lockfiles, `Ma
|
||||
|
||||
On pull requests from authors without write access, the action also replaces what npm and Bun read from the repository root with the base branch's version, wherever the two differ: `.npmrc`, `bunfig.toml` and tracked files in `node_modules/`. In a `package.json` whose `name`, `bin`, `directories.bin` or `workspaces` change the commands it provides, only `name`, `bin`, `directories` and `workspaces` are replaced, or the whole file if it can't be understood, including in other directories if the base branch uses workspaces. The pull request's versions are kept under `.claude-pr/` for reading, except for `node_modules/`. Claude can't edit `.npmrc`, `bunfig.toml`, `node_modules/` or, where one was replaced, `package.json` on these pull requests, in any directory. Its Bash commands start in the repository root there, because a hook runs in the session's current directory and only the root's files are replaced. The replaced files stay in the working tree for later steps in the job, and if Claude stages everything, its commit can include them, as with the paths above. `restrict_untrusted_prs: false` turns this off.
|
||||
|
||||
On these pull requests, files and directories in the checkout that your workflow's inputs name also come from the base branch where the pull request changes them or a `.gitattributes` that applies to them: `settings`, `plugin_marketplaces`, and in `claude_args` `--settings`, `--mcp-config`, `--plugin-dir`, `--plugin-dir-no-mcp`, `--agents`, `--project-config-root`, `--system-prompt-file`, `--append-system-prompt-file` and `--append-subagent-system-prompt-file`. The pull request's versions are kept under `.claude-pr/` for reading, and Claude can't edit what these inputs name, apart from the paths listed above. The replaced files stay in the working tree here too. A file that only the pull request has is removed. The run stops if an input names the whole repository as a plugin or marketplace, except that a marketplace at the root works if all its plugins are in subdirectories, if it names a path with `..` after another directory, or if it names files in a submodule that the pull request has at another commit. What symbolic links lead to, files that other config names, for example in a `settings.json`, and executables are not covered. Git LFS files are written as pointers.
|
||||
|
||||
This doesn't cover other package managers, the `.env` files and `tsconfig.json` that Bun loads, other files that a hook's own command reads, or a git command that resets the working tree during the session, so keep hooks self-contained as described above. Files that git doesn't track, such as packages an earlier step installed, stay as they are. A file that is the same link on both branches is left as a link.
|
||||
|
||||
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.
|
||||
@@ -128,7 +130,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.
|
||||
|
||||
@@ -137,7 +139,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.
|
||||
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"@actions/github": "^6.0.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.327",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.331",
|
||||
"@modelcontextprotocol/sdk": "^1.11.0",
|
||||
"@octokit/graphql": "^8.2.2",
|
||||
"@octokit/rest": "^21.1.1",
|
||||
|
||||
+44
-5
@@ -56,6 +56,10 @@ import {
|
||||
restoreToolConfigFromBase,
|
||||
toolConfigDenyRules,
|
||||
} from "../github/operations/tool-config";
|
||||
import {
|
||||
namedConfigPaths,
|
||||
restoreConfigPathsFromBase,
|
||||
} from "../github/operations/config-paths";
|
||||
import { validateBranchName } from "../github/operations/branch";
|
||||
import type { BranchInfo } from "../github/operations/branch";
|
||||
import { collectActionInputsPresence } from "./collect-inputs";
|
||||
@@ -70,6 +74,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";
|
||||
@@ -105,7 +110,7 @@ async function installClaudeCode(): Promise<string> {
|
||||
return customExecutable;
|
||||
}
|
||||
|
||||
const claudeCodeVersion = "2.1.327";
|
||||
const claudeCodeVersion = "2.1.331";
|
||||
console.log(`Installing Claude Code v${claudeCodeVersion}...`);
|
||||
|
||||
for (let attempt = 1; attempt <= 3; attempt++) {
|
||||
@@ -198,6 +203,29 @@ 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();
|
||||
@@ -332,6 +360,7 @@ async function run() {
|
||||
const isUntrustedCheckout =
|
||||
checkedOutPrHead && untrustedPrDisallowedTools.length > 0;
|
||||
let restoredToolConfig: string[] = [];
|
||||
let configPathDenyRules: string[] = [];
|
||||
|
||||
// On PRs, .claude/ and .mcp.json in the checkout are attacker-controlled.
|
||||
// Restore them from a trusted branch before the CLI reads them.
|
||||
@@ -373,7 +402,15 @@ async function run() {
|
||||
// Before plugins are installed, which can already start package managers here.
|
||||
if (isUntrustedCheckout) {
|
||||
restoredToolConfig = restoreToolConfigFromBase(configBranch);
|
||||
restoredConfigPaths.push(...restoredToolConfig);
|
||||
const configPaths = restoreConfigPathsFromBase(
|
||||
configBranch,
|
||||
namedConfigPaths(prepareResult.claudeArgs),
|
||||
);
|
||||
configPathDenyRules = configPaths.denyRules;
|
||||
restoredConfigPaths.push(
|
||||
...restoredToolConfig,
|
||||
...configPaths.replaced,
|
||||
);
|
||||
}
|
||||
if (isOtherBranch) {
|
||||
// A branch from the base has none of the pull request's version of them.
|
||||
@@ -407,6 +444,7 @@ async function run() {
|
||||
? [
|
||||
...untrustedPrDisallowedTools,
|
||||
...toolConfigDenyRules(restoredToolConfig),
|
||||
...configPathDenyRules,
|
||||
]
|
||||
: [];
|
||||
|
||||
@@ -416,7 +454,7 @@ async function run() {
|
||||
process.env.CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR = "1";
|
||||
}
|
||||
|
||||
const restoreSessionFiles = snapshotSessionFiles(() =>
|
||||
restoreSessionFiles = snapshotSessionFiles(() =>
|
||||
prepareGitForSession({ hooks: hooksOff }),
|
||||
);
|
||||
|
||||
@@ -437,8 +475,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";
|
||||
@@ -466,6 +504,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
|
||||
|
||||
@@ -37,7 +37,7 @@ export async function checkAndCommitOrDeleteBranch(
|
||||
// .claude/settings.json. Excluding those there would silently drop the work.
|
||||
const pathspecArgs =
|
||||
restoredConfigPaths.length > 0
|
||||
? ["--", ".", ...restoredConfigPaths.map((p) => `:(exclude)${p}`)]
|
||||
? ["--", ".", ...restoredConfigPaths.map((p) => `:(exclude,literal)${p}`)]
|
||||
: [];
|
||||
|
||||
if (pathspecArgs.length > 0) {
|
||||
|
||||
@@ -0,0 +1,381 @@
|
||||
import * as core from "@actions/core";
|
||||
import { mkdirSync, symlinkSync, writeFileSync } from "fs";
|
||||
import { isAbsolute, posix, relative, resolve, sep } from "path";
|
||||
import {
|
||||
ACCUMULATE_DELIMITER,
|
||||
parseClaudeArgsToExtraArgs,
|
||||
} from "../../../base-action/src/parse-sdk-options";
|
||||
import { SENSITIVE_PATHS } from "./restore-config";
|
||||
import {
|
||||
fold,
|
||||
fsPath,
|
||||
git,
|
||||
hasRealParents,
|
||||
isFile,
|
||||
isLink,
|
||||
isSubmodule,
|
||||
onDisk,
|
||||
readBlobs,
|
||||
remove,
|
||||
snapshotForReview,
|
||||
} from "./tool-config";
|
||||
import type { Entry } from "./tool-config";
|
||||
|
||||
// The arguments that name config in files.
|
||||
const FILE_FLAGS = new Set([
|
||||
"agents",
|
||||
"append-subagent-system-prompt-file",
|
||||
"append-system-prompt-file",
|
||||
"mcp-config",
|
||||
"plugin-dir",
|
||||
"plugin-dir-no-mcp",
|
||||
"settings",
|
||||
"system-prompt-file",
|
||||
]);
|
||||
// Only the project's config in this directory.
|
||||
const PROJECT_FLAG = "project-config-root";
|
||||
const MARKETPLACE_FILE = ".claude-plugin/marketplace.json";
|
||||
|
||||
// Git's entries by path, relative to the working directory. As in tool-config.ts,
|
||||
// Latin-1 characters stand for bytes.
|
||||
type Entries = Map<string, Entry>;
|
||||
|
||||
const toBytes = (path: string): string => Buffer.from(path).toString("latin1");
|
||||
const toText = (path: string): string => fsPath(path).toString();
|
||||
const isSameOrInside = (path: string, parent: string): boolean =>
|
||||
path === parent || path.startsWith(`${parent}/`);
|
||||
const isSensitive = (path: string): boolean =>
|
||||
SENSITIVE_PATHS.some((sensitive) => isSameOrInside(path, sensitive));
|
||||
|
||||
// Each is "<mode> <other fields>\t<path>".
|
||||
function parseEntries(listing: Buffer, oidField: number): Entries {
|
||||
const entries: Entries = new Map();
|
||||
for (const line of listing.toString("latin1").split("\0")) {
|
||||
const [info, path] = line.split(/\t(.*)/s);
|
||||
if (!info || !path) continue;
|
||||
const fields = info.split(" ");
|
||||
entries.set(path, { mode: fields[0]!, oid: fields[oidField]! });
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/**
|
||||
* A path as it is relative to the checkout, or undefined if it's outside. Links are not
|
||||
* followed, because the pull request can change them. The workspace can have another
|
||||
* name than the working directory, which is free of links.
|
||||
*/
|
||||
function inCheckout(path: string): string | undefined {
|
||||
const roots = [process.cwd(), process.env.GITHUB_WORKSPACE || process.cwd()];
|
||||
for (const root of roots) {
|
||||
const inRoot = relative(root, resolve(path));
|
||||
if (!isAbsolute(inRoot) && inRoot.split(sep)[0] !== "..") {
|
||||
return toBytes(inRoot.split(sep).join("/"));
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function isJson(value: string): boolean {
|
||||
if (!value.startsWith("{")) return false;
|
||||
try {
|
||||
JSON.parse(value);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const WHOLE_REPOSITORY =
|
||||
"The workflow takes a plugin from the whole repository, which can't come from a trusted branch on a pull request from an author without write access. Put the plugin in a subdirectory, or set restrict_untrusted_prs to false.";
|
||||
const UNCLEAR_PATH =
|
||||
'A path in the workflow\'s inputs has ".." after another name, so it can\'t come from a trusted branch on a pull request from an author without write access. Write it without "..", or set restrict_untrusted_prs to false.';
|
||||
|
||||
const OTHER_SUBMODULE =
|
||||
"The pull request and the trusted branch have different commits of a submodule that the workflow's inputs name, so that branch's version can't be used. Bring the pull request up to date, put the files in the repository, or set restrict_untrusted_prs to false.";
|
||||
|
||||
class PathError extends Error {}
|
||||
|
||||
/**
|
||||
* Whether a path has ".." after a name in the checkout, which the pull request could
|
||||
* make a link.
|
||||
*/
|
||||
function goesBack(path: string): boolean {
|
||||
const parts = path.split(/[\\/]/);
|
||||
return parts.some(
|
||||
(part, index) =>
|
||||
part === ".." && !!inCheckout(parts.slice(0, index).join("/") || "/"),
|
||||
);
|
||||
}
|
||||
|
||||
type NamedPaths = { paths: string[]; marketplaces: string[] };
|
||||
|
||||
/** The paths in this checkout that the workflow's inputs name as config. */
|
||||
export function namedConfigPaths(claudeArgs: string): NamedPaths {
|
||||
const args = Object.entries(parseClaudeArgsToExtraArgs(claudeArgs)).flatMap(
|
||||
([key, value]) => {
|
||||
const [flag, inlineValue] = key.split(/=(.*)/s);
|
||||
return [...(value?.split(ACCUMULATE_DELIMITER) ?? []), inlineValue ?? ""]
|
||||
.map((path) => path.trim())
|
||||
.flatMap((path) => (path ? [{ flag: flag!, path }] : []));
|
||||
},
|
||||
);
|
||||
const fromArgs = args.flatMap(({ flag, path }) =>
|
||||
flag === PROJECT_FLAG
|
||||
? SENSITIVE_PATHS.map((name) => `${path}/${name}`)
|
||||
: FILE_FLAGS.has(flag)
|
||||
? [path]
|
||||
: [],
|
||||
);
|
||||
const toPaths = (values: string[]): string[] =>
|
||||
values
|
||||
.map((value) => value.trim())
|
||||
.filter((value) => value && !isJson(value))
|
||||
.flatMap((value) => {
|
||||
if (goesBack(value)) throw new PathError(UNCLEAR_PATH);
|
||||
const path = inCheckout(value);
|
||||
return path === undefined ? [] : [path];
|
||||
});
|
||||
return {
|
||||
paths: toPaths([process.env.INPUT_SETTINGS ?? "", ...fromArgs]),
|
||||
marketplaces: toPaths(
|
||||
(process.env.INPUT_PLUGIN_MARKETPLACES ?? "")
|
||||
.split("\n")
|
||||
.filter((entry) => /^\s*((\.\.?)?\/|[a-z]:[\\/])/i.test(entry)),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
type RestoredPaths = { replaced: string[]; denyRules: string[] };
|
||||
|
||||
/**
|
||||
* On a pull request from an author without write access, takes the files that the
|
||||
* workflow's inputs name from the base branch. Links are restored but not followed. Only
|
||||
* files that the pull request changes, or whose .gitattributes it changes, are replaced,
|
||||
* so what an earlier step created or changed stays. restoreConfigFromBase must run
|
||||
* first, because it fetches the base branch. Like it, this changes the working tree and
|
||||
* not the index.
|
||||
*
|
||||
* @returns The paths that were replaced, all named by the base branch or the workflow,
|
||||
* and rules that stop a session from editing these and the rest of that config.
|
||||
* @throws If the base branch's version can't be put in place.
|
||||
*/
|
||||
export function restoreConfigPathsFromBase(
|
||||
baseBranch: string,
|
||||
named: NamedPaths,
|
||||
): RestoredPaths {
|
||||
if (named.paths.length + named.marketplaces.length === 0) {
|
||||
return { replaced: [], denyRules: [] };
|
||||
}
|
||||
let restored: RestoredPaths;
|
||||
try {
|
||||
restored = restoreConfigPaths(`refs/remotes/origin/${baseBranch}`, named);
|
||||
} catch (error) {
|
||||
if (error instanceof PathError) throw error;
|
||||
const { code, status } = error as { code?: string; status?: number };
|
||||
core.warning(
|
||||
`Could not replace config files (${code ?? `exit code ${status ?? "unknown"}`})`,
|
||||
);
|
||||
throw new Error(
|
||||
"Could not use the trusted branch's version of the files that the workflow's inputs name",
|
||||
);
|
||||
}
|
||||
if (restored.replaced.length > 0) {
|
||||
core.warning(
|
||||
`The pull request and ${baseBranch} differ in files that the workflow's inputs name (${restored.replaced.join(", ")}), so that branch's version is used and Claude can't edit it. See docs/security.md.`,
|
||||
);
|
||||
}
|
||||
return restored;
|
||||
}
|
||||
|
||||
function restoreConfigPaths(ref: string, named: NamedPaths): RestoredPaths {
|
||||
const base = parseEntries(git(["ls-tree", "-r", "-z", ref]), 2);
|
||||
const pr = parseEntries(git(["ls-files", "--stage", "-z"]), 1);
|
||||
|
||||
// The rest of Claude's config has been restored already.
|
||||
const targets = [
|
||||
...named.paths,
|
||||
...named.marketplaces.flatMap((path) => marketplacePaths(path, base)),
|
||||
]
|
||||
.map((path) => posix.join(path || ".").replace(/\/$/, ""))
|
||||
.filter((path) => !isSameOrInside(path, "..") && !isSensitive(path));
|
||||
if (targets.includes(".")) throw new PathError(WHOLE_REPOSITORY);
|
||||
|
||||
const replaced = replaceFiles([...new Set(targets)], base, pr).map(toText);
|
||||
return {
|
||||
replaced,
|
||||
denyRules: [...new Set([...targets.map(toText), ...replaced])]
|
||||
.map((path) => path.replace(/[\\*?[\]]/g, "\\$&"))
|
||||
.flatMap((path) => [`Edit(./${path})`, `Edit(./${path}/**)`]),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* What a local marketplace is made of. One at the root of the repository has only its
|
||||
* own plugins in other directories.
|
||||
*/
|
||||
function marketplacePaths(path: string, base: Entries): string[] {
|
||||
const isManifest = path.endsWith(".json");
|
||||
// The CLI takes the directory above the manifest's as the marketplace's root.
|
||||
if (isManifest && !path.includes("/")) return [path];
|
||||
const root = isManifest
|
||||
? posix.join(posix.dirname(path), "..")
|
||||
: path === ""
|
||||
? "."
|
||||
: path;
|
||||
if (root !== ".") return [root];
|
||||
|
||||
const manifest = isManifest ? path : MARKETPLACE_FILE;
|
||||
const own = isManifest ? path : posix.dirname(MARKETPLACE_FILE);
|
||||
const entry = base.get(manifest);
|
||||
// Without one that the base branch has, there is nothing to take plugins from.
|
||||
if (!entry || !isFile(entry)) return [own];
|
||||
const { plugins, metadata } = JSON.parse(
|
||||
readBlobs([entry])
|
||||
.get(entry.oid)!
|
||||
.toString()
|
||||
.replace(/^\uFEFF/, ""),
|
||||
) as {
|
||||
plugins?: ({ source?: unknown } | null)[];
|
||||
metadata?: { pluginRoot?: unknown };
|
||||
};
|
||||
const pluginRoot =
|
||||
typeof metadata?.pluginRoot === "string" ? metadata.pluginRoot : "";
|
||||
const sources = (plugins ?? []).flatMap((plugin) =>
|
||||
typeof plugin?.source === "string" ? [plugin.source] : [],
|
||||
);
|
||||
return [
|
||||
own,
|
||||
...sources.flatMap((source) =>
|
||||
// A bare name can be in the marketplace's plugin root.
|
||||
[source, ...(pluginRoot ? [posix.join(pluginRoot, source)] : [])].map(
|
||||
(dir) => toBytes(posix.join(".", dir)),
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a path that differs from a target at most in case, or in how a character is
|
||||
* encoded, is in it or above it on this file system.
|
||||
*/
|
||||
function namesSameFile(name: string, target: string): boolean {
|
||||
const names = name.split("/");
|
||||
const targets = target.split("/");
|
||||
const spelled = [
|
||||
...targets.slice(0, names.length),
|
||||
...names.slice(targets.length),
|
||||
].join("/");
|
||||
if (name === spelled) return true;
|
||||
const [stats, other] = [onDisk(name), onDisk(spelled)];
|
||||
return !!stats && !!other && stats.ino === other.ino;
|
||||
}
|
||||
|
||||
/** The directories whose .gitattributes the pull request changes, ignoring case. */
|
||||
function changedAttributes(base: Entries, pr: Entries): string[] {
|
||||
const names = new Set([...base.keys(), ...pr.keys()]);
|
||||
return [...names].flatMap((name) =>
|
||||
fold(posix.basename(name)) === ".gitattributes" &&
|
||||
base.get(name)?.oid !== pr.get(name)?.oid
|
||||
? [fold(posix.dirname(name))]
|
||||
: [],
|
||||
);
|
||||
}
|
||||
|
||||
const isInside = (name: string, foldedDir: string): boolean =>
|
||||
foldedDir === "." || fold(name).startsWith(`${foldedDir}/`);
|
||||
|
||||
/** Puts the base branch's version of these paths in place. Returns those that differed. */
|
||||
function replaceFiles(targets: string[], base: Entries, pr: Entries): string[] {
|
||||
const foldedPr = [...pr.keys()].map((name) => [name, fold(name)] as const);
|
||||
const namesByTarget = new Map(
|
||||
targets.map((target) => {
|
||||
const folded = fold(target);
|
||||
const names = [
|
||||
...[...base.keys()].filter(
|
||||
(name) =>
|
||||
isSameOrInside(name, target) || isSameOrInside(target, name),
|
||||
),
|
||||
// A pull request can also have a file or link where the base branch has a
|
||||
// directory.
|
||||
...foldedPr.flatMap(([name, other]) =>
|
||||
(isSameOrInside(other, folded) || isSameOrInside(folded, other)) &&
|
||||
namesSameFile(name, target)
|
||||
? [name]
|
||||
: [],
|
||||
),
|
||||
];
|
||||
return [target, [...new Set(names)]] as const;
|
||||
}),
|
||||
);
|
||||
const attributes = changedAttributes(base, pr);
|
||||
const differs = (name: string): boolean => {
|
||||
const [ours, theirs] = [base.get(name), pr.get(name)];
|
||||
return (
|
||||
ours?.oid !== theirs?.oid ||
|
||||
ours?.mode !== theirs?.mode ||
|
||||
// Git can write even an unchanged file differently then.
|
||||
(isFile(theirs!) && attributes.some((dir) => isInside(name, dir)))
|
||||
);
|
||||
};
|
||||
const differing = [...namesByTarget].flatMap(([target, names]) => {
|
||||
// Names that differ only in case can be the same file.
|
||||
const folded = new Set(names.filter(differs).map(fold));
|
||||
const changed = names.filter((name) => folded.has(fold(name)));
|
||||
return changed.length > 0 ? [[target, changed] as const] : [];
|
||||
});
|
||||
const changed = [...new Set(differing.flatMap(([, names]) => names))];
|
||||
// Claude Code goes on without a plugin that is missing.
|
||||
if (changed.some((name) => base.has(name) && isSubmodule(base.get(name)!))) {
|
||||
throw new PathError(OTHER_SUBMODULE);
|
||||
}
|
||||
|
||||
// All of these go before anything is written. A directory where the pull request has
|
||||
// a file or link came from an earlier step.
|
||||
const removed = new Set(
|
||||
changed.filter((name) => {
|
||||
const entry = pr.get(name);
|
||||
const stats = entry && onDisk(name);
|
||||
return (
|
||||
stats &&
|
||||
(!stats.isDirectory() || isSubmodule(entry)) &&
|
||||
hasRealParents(name)
|
||||
);
|
||||
}),
|
||||
);
|
||||
for (const name of removed) {
|
||||
const entry = pr.get(name)!;
|
||||
if (entry.oid !== base.get(name)?.oid) snapshotForReview(name, entry);
|
||||
remove(name);
|
||||
}
|
||||
|
||||
// One that the pull request has but is not on disk was left out or deleted by the
|
||||
// workflow. What is on disk now came from an earlier step.
|
||||
const toWrite = changed.flatMap((name) => {
|
||||
const entry = base.get(name);
|
||||
const wanted = pr.has(name) ? removed.has(name) : true;
|
||||
return entry && !isSubmodule(entry) && wanted && !onDisk(name)
|
||||
? [{ name, entry }]
|
||||
: [];
|
||||
});
|
||||
const blobs = readBlobs(toWrite.map(({ entry }) => entry));
|
||||
for (const { name, entry } of toWrite) {
|
||||
if (!hasRealParents(name)) continue;
|
||||
const content = blobs.get(entry.oid);
|
||||
if (!content) throw new Error("missing object");
|
||||
mkdirSync(fsPath(posix.dirname(name)), { recursive: true });
|
||||
if (isLink(entry)) symlinkSync(content, fsPath(name));
|
||||
else {
|
||||
const mode = entry.mode === "100755" ? 0o755 : 0o644;
|
||||
writeFileSync(fsPath(name), content, { mode, flag: "wx" });
|
||||
}
|
||||
}
|
||||
// Where the pull request has a file above a target, that is gone too.
|
||||
return [
|
||||
...new Set(
|
||||
differing.flatMap(([target, names]) => [
|
||||
target,
|
||||
...names.filter((name) => target.startsWith(`${name}/`)),
|
||||
]),
|
||||
),
|
||||
];
|
||||
}
|
||||
@@ -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);
|
||||
@@ -329,7 +336,9 @@ export function pinPushBranch(branch: string): void {
|
||||
export function pinRestoredPaths(paths: string[]): void {
|
||||
const pathspecs = paths.map((path) =>
|
||||
// Its commands are replaced in subdirectories too.
|
||||
path === "package.json" ? ":(top,glob)**/package.json" : `:(top)${path}`,
|
||||
path === "package.json"
|
||||
? ":(top,glob)**/package.json"
|
||||
: `:(top,literal)${path}`,
|
||||
);
|
||||
try {
|
||||
writeSessionFile(".restored-paths", `${pathspecs.join("\n")}\n`);
|
||||
|
||||
@@ -32,14 +32,14 @@ const ENCODING = "working-tree-encoding";
|
||||
const MAX_OUTPUT_BYTES = 1024 ** 3;
|
||||
const MAX_PACKAGE_JSON_BYTES = 4 * 1024 * 1024;
|
||||
|
||||
type Entry = { mode: string; oid: string };
|
||||
export type Entry = { mode: string; oid: string };
|
||||
type Replacement = { path: string; entry: Entry; content?: Buffer };
|
||||
|
||||
// File names can be any bytes. Latin-1 keeps each one intact.
|
||||
const fsPath = (path: string): Buffer => Buffer.from(path, "latin1");
|
||||
const isFile = (entry: Entry): boolean => entry.mode.startsWith("100");
|
||||
const isLink = (entry: Entry): boolean => entry.mode === "120000";
|
||||
const isSubmodule = (entry: Entry): boolean => entry.mode === "160000";
|
||||
export const fsPath = (path: string): Buffer => Buffer.from(path, "latin1");
|
||||
export const isFile = (entry: Entry): boolean => entry.mode.startsWith("100");
|
||||
export const isLink = (entry: Entry): boolean => entry.mode === "120000";
|
||||
export const isSubmodule = (entry: Entry): boolean => entry.mode === "160000";
|
||||
|
||||
// No file name or content, which the pull request controls, reaches the log.
|
||||
function warn(what: string, error: unknown): void {
|
||||
@@ -47,7 +47,7 @@ function warn(what: string, error: unknown): void {
|
||||
core.warning(`${what} (${code ?? `exit code ${status ?? "unknown"}`})`);
|
||||
}
|
||||
|
||||
function git(args: string[], input: string | Buffer = ""): Buffer {
|
||||
export function git(args: string[], input: string | Buffer = ""): Buffer {
|
||||
return execFileSync("git", args, {
|
||||
stdio: ["pipe", "pipe", "ignore"],
|
||||
input,
|
||||
@@ -57,7 +57,7 @@ function git(args: string[], input: string | Buffer = ""): Buffer {
|
||||
}
|
||||
|
||||
// A parent that is a file or a looping link means there is nothing there.
|
||||
function onDisk(path: string) {
|
||||
export function onDisk(path: string) {
|
||||
try {
|
||||
return lstatSync(fsPath(path));
|
||||
} catch {
|
||||
@@ -66,7 +66,7 @@ function onDisk(path: string) {
|
||||
}
|
||||
|
||||
// File systems can ignore case, and some the way a character is encoded.
|
||||
const fold = (path: string): string =>
|
||||
export const fold = (path: string): string =>
|
||||
fsPath(path).toString().normalize("NFKC").toLowerCase();
|
||||
|
||||
/**
|
||||
@@ -97,14 +97,14 @@ function rootName(path: string): string | undefined {
|
||||
}
|
||||
|
||||
/** Whether no parent of a path is a link, which could lead out of the checkout. */
|
||||
function hasRealParents(path: string): boolean {
|
||||
export function hasRealParents(path: string): boolean {
|
||||
for (let dir = dirname(path); dir !== "."; dir = dirname(dir)) {
|
||||
if (onDisk(dir)?.isSymbolicLink()) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function remove(path: string): void {
|
||||
export function remove(path: string): void {
|
||||
rmSync(fsPath(path), { recursive: true, force: true });
|
||||
// An empty directory would stand in the way of a file of that name.
|
||||
try {
|
||||
@@ -150,7 +150,7 @@ function baseEntries(baseBranch: string): Map<string, Entry> {
|
||||
}
|
||||
|
||||
/** The stored content of each entry, which no .gitattributes has been applied to. */
|
||||
function readBlobs(entries: Entry[]): Map<string, Buffer> {
|
||||
export function readBlobs(entries: Entry[]): Map<string, Buffer> {
|
||||
const blobs = new Map<string, Buffer>();
|
||||
const oids = [...new Set(entries.map(({ oid }) => oid))];
|
||||
if (oids.length === 0) return blobs;
|
||||
@@ -282,7 +282,7 @@ function withBaseCommands(
|
||||
}
|
||||
|
||||
/** Keeps the pull request's version readable, as for the other restored config. */
|
||||
function snapshotForReview(path: string, entry: Entry): void {
|
||||
export function snapshotForReview(path: string, entry: Entry): void {
|
||||
if (!isFile(entry) || rootName(path) === "node_modules") return;
|
||||
try {
|
||||
const content = git(["cat-file", "blob", entry.oid]);
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -313,7 +313,7 @@ describe("in a shallow checkout whose history contains the config branch", () =>
|
||||
);
|
||||
});
|
||||
|
||||
test("run.ts restores both kinds of config from the chosen branch", () => {
|
||||
test("run.ts restores every kind of config from the chosen branch", () => {
|
||||
const source = readFileSync(
|
||||
join(import.meta.dir, "../src/entrypoints/run.ts"),
|
||||
"utf8",
|
||||
@@ -327,5 +327,8 @@ test("run.ts restores both kinds of config from the chosen branch", () => {
|
||||
expect(source).toContain("restoreHeadHistory?.();");
|
||||
expect(source).toContain("pinRestoredPaths(restoredConfigPaths)");
|
||||
expect(source).toContain("restoreToolConfigFromBase(configBranch)");
|
||||
expect(source.replace(/\s+/g, " ")).toContain(
|
||||
"restoreConfigPathsFromBase( configBranch, namedConfigPaths(prepareResult.claudeArgs), )",
|
||||
);
|
||||
expect(source).toContain("fetchBranch(restoreBase)");
|
||||
});
|
||||
|
||||
@@ -0,0 +1,560 @@
|
||||
import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
|
||||
import * as core from "@actions/core";
|
||||
import { execFileSync } from "child_process";
|
||||
import {
|
||||
existsSync,
|
||||
lstatSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
readlinkSync,
|
||||
rmSync,
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
} from "fs";
|
||||
import { tmpdir } from "os";
|
||||
import { dirname, join } from "path";
|
||||
import {
|
||||
namedConfigPaths,
|
||||
restoreConfigPathsFromBase,
|
||||
} from "../src/github/operations/config-paths";
|
||||
import { restoreConfigFromBase } from "../src/github/operations/restore-config";
|
||||
|
||||
const INPUTS = [
|
||||
"INPUT_SETTINGS",
|
||||
"INPUT_PLUGIN_MARKETPLACES",
|
||||
"GITHUB_WORKSPACE",
|
||||
];
|
||||
|
||||
let originalCwd: string;
|
||||
let tempDir: string;
|
||||
let saved: Record<string, string | undefined>;
|
||||
let warningSpy: any;
|
||||
|
||||
const git = (...args: string[]) =>
|
||||
execFileSync("git", args, { encoding: "utf8", stdio: "pipe" }).trim();
|
||||
const write = (path: string, content: string) => {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
rmSync(path, { recursive: true, force: true });
|
||||
writeFileSync(path, content);
|
||||
};
|
||||
const link = (path: string, target: string) => {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
rmSync(path, { recursive: true, force: true });
|
||||
symlinkSync(target, path);
|
||||
};
|
||||
const read = (path: string) => readFileSync(path, "utf8");
|
||||
const commit = (message: string) => {
|
||||
git("add", "-A", "-f");
|
||||
git("commit", "-qm", message);
|
||||
};
|
||||
|
||||
// Commits the base branch, pushes it and starts the pull request's branch from it.
|
||||
const startPr = () => {
|
||||
commit("base");
|
||||
git("push", "-q", "origin", "main");
|
||||
git("checkout", "-qb", "pr");
|
||||
};
|
||||
|
||||
const restoreAll = (named = { paths: [], marketplaces: [] } as any) => {
|
||||
restoreConfigFromBase("main");
|
||||
return restoreConfigPathsFromBase("main", named);
|
||||
};
|
||||
const named = (...paths: string[]) => ({ paths, marketplaces: [] as string[] });
|
||||
const restore = (named?: any) => restoreAll(named).replaced;
|
||||
|
||||
beforeEach(() => {
|
||||
originalCwd = process.cwd();
|
||||
saved = Object.fromEntries(INPUTS.map((key) => [key, process.env[key]]));
|
||||
INPUTS.forEach((key) => delete process.env[key]);
|
||||
warningSpy = spyOn(core, "warning").mockImplementation(() => {});
|
||||
tempDir = mkdtempSync(join(tmpdir(), "config-paths-"));
|
||||
const remote = join(tempDir, "origin.git");
|
||||
const repo = join(tempDir, "repo");
|
||||
execFileSync("git", ["init", "-q", "--bare", remote]);
|
||||
execFileSync("git", ["init", "-q", "-b", "main", repo]);
|
||||
process.chdir(repo);
|
||||
git("config", "user.email", "[email protected]");
|
||||
git("config", "user.name", "Test User");
|
||||
git("remote", "add", "origin", remote);
|
||||
write("src/index.ts", "base\n");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(originalCwd);
|
||||
warningSpy.mockRestore();
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
for (const key of INPUTS) {
|
||||
if (saved[key] === undefined) delete process.env[key];
|
||||
else process.env[key] = saved[key];
|
||||
}
|
||||
});
|
||||
|
||||
describe("a named directory", () => {
|
||||
const inputs = () => namedConfigPaths("--plugin-dir ci/plugin");
|
||||
beforeEach(() => write("ci/plugin/a.json", "base\n"));
|
||||
|
||||
test("is left alone if the pull request doesn't change it", () => {
|
||||
startPr();
|
||||
write("src/index.ts", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
expect(restore(inputs())).toEqual([]);
|
||||
expect(git("status", "--porcelain")).toBe("");
|
||||
expect(warningSpy).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("comes from the base branch, without what the pull request adds", () => {
|
||||
startPr();
|
||||
write("ci/plugin/a.json", "pr\n");
|
||||
write("ci/plugin/b.json", "pr\n");
|
||||
write("src/index.ts", "pr\n");
|
||||
commit("pr");
|
||||
write("ci/plugin/generated.json", "by an earlier step\n");
|
||||
|
||||
expect(restore(inputs())).toEqual(["ci/plugin"]);
|
||||
|
||||
expect(read("ci/plugin/a.json")).toBe("base\n");
|
||||
expect(existsSync("ci/plugin/b.json")).toBe(false);
|
||||
expect(read("ci/plugin/generated.json")).toBe("by an earlier step\n");
|
||||
expect(read("src/index.ts")).toBe("pr\n");
|
||||
expect(read(".claude-pr/ci/plugin/a.json")).toBe("pr\n");
|
||||
// Nothing is staged, so a commit doesn't include it.
|
||||
expect(git("diff", "--cached", "--name-only")).toBe("");
|
||||
expect(warningSpy.mock.calls[0][0]).toContain("ci/plugin");
|
||||
});
|
||||
|
||||
test.each(["ci", "ci/plugin", "ci/plugin/a.json"])(
|
||||
"is put back if the pull request has a link at %s",
|
||||
(path) => {
|
||||
startPr();
|
||||
write(join(tempDir, "outside", "keep"), "untouched\n");
|
||||
rmSync(path, { recursive: true });
|
||||
link(path, join(tempDir, "outside"));
|
||||
commit("pr");
|
||||
|
||||
expect(restore(inputs()).sort()).toEqual(
|
||||
path === "ci" ? ["ci", "ci/plugin"] : ["ci/plugin"],
|
||||
);
|
||||
expect(read("ci/plugin/a.json")).toBe("base\n");
|
||||
expect(read(join(tempDir, "outside", "keep"))).toBe("untouched\n");
|
||||
},
|
||||
);
|
||||
|
||||
test("is put back if the pull request has a file in its parent's place", () => {
|
||||
startPr();
|
||||
rmSync("ci", { recursive: true });
|
||||
write("ci", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
expect(restore(inputs()).sort()).toEqual(["ci", "ci/plugin"]);
|
||||
expect(read("ci/plugin/a.json")).toBe("base\n");
|
||||
});
|
||||
|
||||
test("is put back if the pull request makes its parent a submodule", () => {
|
||||
startPr();
|
||||
git("rm", "-rq", "ci");
|
||||
git(
|
||||
"update-index",
|
||||
"--add",
|
||||
"--cacheinfo",
|
||||
`160000,${git("rev-parse", "HEAD")},ci`,
|
||||
);
|
||||
git("commit", "-qm", "pr");
|
||||
mkdirSync("ci");
|
||||
|
||||
expect(restore(inputs()).sort()).toEqual(["ci", "ci/plugin"]);
|
||||
expect(read("ci/plugin/a.json")).toBe("base\n");
|
||||
});
|
||||
|
||||
test("keeps its own links, and loses the pull request's", () => {
|
||||
link("ci/plugin/hooks", "../hooks");
|
||||
startPr();
|
||||
link("ci/plugin/hooks", "../evil");
|
||||
link("ci/plugin/more", "../evil");
|
||||
commit("pr");
|
||||
|
||||
expect(restore(inputs())).toEqual(["ci/plugin"]);
|
||||
expect(readlinkSync("ci/plugin/hooks")).toBe("../hooks");
|
||||
expect(lstatSync("ci/plugin/more", { throwIfNoEntry: false })).toBe(
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test("a file that an earlier step created stays", () => {
|
||||
startPr();
|
||||
write("generated/settings.json", "by an earlier step\n");
|
||||
|
||||
expect(restore(named("generated/settings.json"))).toEqual([]);
|
||||
expect(read("generated/settings.json")).toBe("by an earlier step\n");
|
||||
});
|
||||
|
||||
test("a link that the pull request puts above a missing path is removed", () => {
|
||||
startPr();
|
||||
write("evil/settings.json", "pr\n");
|
||||
link("generated", "evil");
|
||||
commit("pr");
|
||||
|
||||
expect(restore(named("generated/settings.json")).sort()).toEqual([
|
||||
"generated",
|
||||
"generated/settings.json",
|
||||
]);
|
||||
expect(existsSync("generated/settings.json")).toBe(false);
|
||||
});
|
||||
|
||||
test("a submodule that the pull request moves stops the run", () => {
|
||||
const add = (oid: string) =>
|
||||
git("update-index", "--add", "--cacheinfo", `160000,${oid},vendor`);
|
||||
commit("first");
|
||||
add(git("rev-parse", "HEAD"));
|
||||
git("commit", "-qm", "base");
|
||||
git("push", "-q", "origin", "main");
|
||||
git("checkout", "-qb", "pr");
|
||||
const inputs = namedConfigPaths("--plugin-dir vendor/plugin");
|
||||
expect(restore(inputs)).toEqual([]);
|
||||
|
||||
add(git("rev-parse", "HEAD"));
|
||||
git("commit", "-qm", "pr");
|
||||
expect(() => restore(inputs)).toThrow("different commits of a submodule");
|
||||
});
|
||||
|
||||
test("the base branch's link above a named path is put back", () => {
|
||||
write("tools/ci/plugin/a.json", "base\n");
|
||||
link("ci", "tools/ci");
|
||||
startPr();
|
||||
rmSync("ci");
|
||||
write("ci/plugin/a.json", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
expect(restore(named("ci/plugin")).sort()).toEqual(["ci", "ci/plugin"]);
|
||||
expect(readlinkSync("ci")).toBe("tools/ci");
|
||||
expect(read("ci/plugin/a.json")).toBe("base\n");
|
||||
});
|
||||
|
||||
test.each(["working-tree-encoding=UTF-16", "text eol=crlf", "ident"])(
|
||||
"a .gitattributes can't make git write a file differently: %s",
|
||||
(attribute) => {
|
||||
write("ci/a.sh", "base $Id$\n");
|
||||
write("ci/b.sh", "base\n");
|
||||
startPr();
|
||||
write("ci/b.sh", "pr\n");
|
||||
commit("pr");
|
||||
write(".gitattributes", `*.sh ${attribute}\n`);
|
||||
git("add", ".gitattributes");
|
||||
git("commit", "-qm", "attributes");
|
||||
rmSync("ci", { recursive: true });
|
||||
git("checkout", "-q", "--", "ci");
|
||||
expect(read("ci/a.sh")).not.toBe("base $Id$\n");
|
||||
|
||||
expect(restore(named("ci/a.sh", "ci/b.sh")).sort()).toEqual([
|
||||
"ci/a.sh",
|
||||
"ci/b.sh",
|
||||
]);
|
||||
expect(read("ci/a.sh")).toBe("base $Id$\n");
|
||||
expect(read("ci/b.sh")).toBe("base\n");
|
||||
},
|
||||
);
|
||||
|
||||
test("the base branch's own .gitattributes are left alone", () => {
|
||||
write("ci/a.sh", "base\n");
|
||||
write(".gitattributes", "*.sh text eol=crlf\n");
|
||||
write("other/.gitattributes", "");
|
||||
startPr();
|
||||
write("other/.gitattributes", "* text\n");
|
||||
commit("pr");
|
||||
rmSync("ci", { recursive: true });
|
||||
git("checkout", "-q", "--", "ci");
|
||||
|
||||
expect(restore(named("ci/a.sh"))).toEqual([]);
|
||||
expect(read("ci/a.sh")).toBe("base\r\n");
|
||||
});
|
||||
|
||||
test("what an earlier step changed stays if the pull request doesn't change it", () => {
|
||||
write("ci/plugin/dist.js", "base\n");
|
||||
write("ci/plugin/a.json", "base\n");
|
||||
startPr();
|
||||
write("ci/plugin/a.json", "pr\n");
|
||||
commit("pr");
|
||||
write("ci/plugin/dist.js", "by an earlier step\n");
|
||||
|
||||
expect(restore(namedConfigPaths("--plugin-dir ci/plugin"))).toEqual([
|
||||
"ci/plugin",
|
||||
]);
|
||||
expect(read("ci/plugin/dist.js")).toBe("by an earlier step\n");
|
||||
expect(read("ci/plugin/a.json")).toBe("base\n");
|
||||
});
|
||||
|
||||
test("a link that leads out of the checkout can't become a file", () => {
|
||||
link("ci/mcp.json", "/opt/shared/mcp.json");
|
||||
startPr();
|
||||
write("ci/mcp.json", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
expect(restore(named("ci/mcp.json"))).toEqual(["ci/mcp.json"]);
|
||||
expect(readlinkSync("ci/mcp.json")).toBe("/opt/shared/mcp.json");
|
||||
});
|
||||
|
||||
test("a path can't go back through a directory", () => {
|
||||
for (const path of [
|
||||
"tools/../ci/s.json",
|
||||
"./a/b/../../s.json",
|
||||
"a/./../s",
|
||||
"tools/../../shared/s.json",
|
||||
join(process.cwd(), "tools") + "/../s.json",
|
||||
]) {
|
||||
process.env.INPUT_SETTINGS = path;
|
||||
expect(() => namedConfigPaths("")).toThrow('Write it without ".."');
|
||||
}
|
||||
for (const path of [
|
||||
"./ci/..s.json",
|
||||
"a..b/s",
|
||||
"../outside/../s.json",
|
||||
process.cwd() + "/../s.json",
|
||||
]) {
|
||||
process.env.INPUT_SETTINGS = path;
|
||||
namedConfigPaths("");
|
||||
}
|
||||
});
|
||||
|
||||
test("a name that differs in case is another file where the file system says so", () => {
|
||||
write("docs/guide.md", "base\n");
|
||||
write("Docs/guide.md/readme", "base\n");
|
||||
const isCaseSensitive = read("docs/guide.md") === "base\n";
|
||||
startPr();
|
||||
if (!isCaseSensitive) return;
|
||||
write("Docs/guide.md/readme", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
expect(restore(named("docs/guide.md"))).toEqual([]);
|
||||
expect(read("Docs/guide.md/readme")).toBe("pr\n");
|
||||
});
|
||||
|
||||
test("names with glob characters are literal in the rules", () => {
|
||||
write("plugins/[ci]/x", "base\n");
|
||||
startPr();
|
||||
write("plugins/[ci]/x", "pr\n");
|
||||
commit("pr");
|
||||
expect(
|
||||
restoreAll(namedConfigPaths("--plugin-dir 'plugins/[ci]'")).denyRules,
|
||||
).toEqual(["Edit(./plugins/\\[ci\\])", "Edit(./plugins/\\[ci\\]/**)"]);
|
||||
});
|
||||
|
||||
test("a workspace reached through a link is the same checkout", () => {
|
||||
write("ci/mcp.json", "base\n");
|
||||
const workspace = join(tempDir, "workspace");
|
||||
symlinkSync(process.cwd(), workspace);
|
||||
process.env.GITHUB_WORKSPACE = workspace;
|
||||
startPr();
|
||||
write("ci/mcp.json", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
expect(
|
||||
restore(namedConfigPaths(`--mcp-config ${workspace}/ci/mcp.json`)),
|
||||
).toEqual(["ci/mcp.json"]);
|
||||
expect(read("ci/mcp.json")).toBe("base\n");
|
||||
});
|
||||
|
||||
test("a session can't edit what the inputs name, changed or not", () => {
|
||||
write("ci/plugin/check.sh", "base\n");
|
||||
write("ci/s.json", "base\n");
|
||||
startPr();
|
||||
write("ci/s.json", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
const { replaced, denyRules } = restoreAll(
|
||||
namedConfigPaths("--plugin-dir ci/plugin --settings ci/s.json"),
|
||||
);
|
||||
expect(replaced).toEqual(["ci/s.json"]);
|
||||
expect(denyRules.sort()).toEqual([
|
||||
"Edit(./ci/plugin)",
|
||||
"Edit(./ci/plugin/**)",
|
||||
"Edit(./ci/s.json)",
|
||||
"Edit(./ci/s.json/**)",
|
||||
]);
|
||||
});
|
||||
|
||||
test("what nothing names stays, also if Claude's config links to it", () => {
|
||||
write("docs/guide.md", "base\n");
|
||||
link("CLAUDE.md", "docs/guide.md");
|
||||
startPr();
|
||||
write("docs/guide.md", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
expect(restoreAll(namedConfigPaths("--model m"))).toEqual({
|
||||
replaced: [],
|
||||
denyRules: [],
|
||||
});
|
||||
});
|
||||
|
||||
describe("what the workflow's inputs name", () => {
|
||||
test("comes from the base branch, or is removed if only the pull request has it", () => {
|
||||
write("ci/settings.json", "base\n");
|
||||
write("ci/plugin/hooks/hooks.json", "base\n");
|
||||
startPr();
|
||||
write("ci/settings.json", "pr\n");
|
||||
write("ci/plugin/hooks/hooks.json", "pr\n");
|
||||
write("ci/mcp.json", "pr\n");
|
||||
write("ci/other.json", "pr\n");
|
||||
commit("pr");
|
||||
process.env.INPUT_SETTINGS = "ci/settings.json";
|
||||
|
||||
const named = namedConfigPaths(
|
||||
"--mcp-config ci/mcp.json --plugin-dir ./ci/plugin",
|
||||
);
|
||||
expect(restore(named).sort()).toEqual([
|
||||
"ci/mcp.json",
|
||||
"ci/plugin",
|
||||
"ci/settings.json",
|
||||
]);
|
||||
|
||||
expect(read("ci/settings.json")).toBe("base\n");
|
||||
expect(read("ci/plugin/hooks/hooks.json")).toBe("base\n");
|
||||
expect(existsSync("ci/mcp.json")).toBe(false);
|
||||
expect(read("ci/other.json")).toBe("pr\n");
|
||||
});
|
||||
|
||||
test("can't be the whole repository", () => {
|
||||
startPr();
|
||||
write("hooks/hooks.json", "pr\n");
|
||||
commit("pr");
|
||||
|
||||
expect(() => restore(namedConfigPaths("--plugin-dir ."))).toThrow(
|
||||
"Put the plugin in a subdirectory",
|
||||
);
|
||||
});
|
||||
|
||||
test("is the manifest and the plugins of a marketplace at the root", () => {
|
||||
write(
|
||||
".claude-plugin/marketplace.json",
|
||||
JSON.stringify({
|
||||
metadata: { pluginRoot: "./more" },
|
||||
plugins: [
|
||||
{ name: "a", source: "./plugins/a/" },
|
||||
{ name: "b", source: "b" },
|
||||
{ name: "d", source: "../d" },
|
||||
{ name: "c", source: { source: "github", repo: "o/c" } },
|
||||
],
|
||||
}),
|
||||
);
|
||||
write("plugins/a/hooks/hooks.json", "base\n");
|
||||
write("more/b/hooks/hooks.json", "base\n");
|
||||
startPr();
|
||||
write(
|
||||
".claude-plugin/marketplace.json",
|
||||
JSON.stringify({ plugins: [{ name: "a", source: "./evil" }] }),
|
||||
);
|
||||
write("plugins/a/hooks/hooks.json", "pr\n");
|
||||
write("more/b/hooks/hooks.json", "pr\n");
|
||||
commit("pr");
|
||||
process.env.INPUT_PLUGIN_MARKETPLACES = "https://example.com/x.git\n./\n";
|
||||
|
||||
expect(restore(namedConfigPaths("")).sort()).toEqual([
|
||||
".claude-plugin",
|
||||
"more/b",
|
||||
"plugins/a",
|
||||
]);
|
||||
expect(read("plugins/a/hooks/hooks.json")).toBe("base\n");
|
||||
expect(read("more/b/hooks/hooks.json")).toBe("base\n");
|
||||
expect(read(".claude-plugin/marketplace.json")).not.toContain("evil");
|
||||
expect(read("src/index.ts")).toBe("base\n");
|
||||
});
|
||||
|
||||
test.each([
|
||||
["ci/marketplace.json", "ci/marketplace.json"],
|
||||
["./", ".claude-plugin/marketplace.json"],
|
||||
])("finds the plugins of a marketplace at %s", (input, path) => {
|
||||
const manifest = JSON.stringify({
|
||||
plugins: [{ name: "a", source: "./plugins/a" }],
|
||||
});
|
||||
write(path, manifest);
|
||||
write("plugins/a/hooks/hooks.json", "base\n");
|
||||
startPr();
|
||||
write("plugins/a/hooks/hooks.json", "pr\n");
|
||||
commit("pr");
|
||||
process.env.INPUT_PLUGIN_MARKETPLACES = input.startsWith(".")
|
||||
? input
|
||||
: `./${input}`;
|
||||
|
||||
expect(restore(namedConfigPaths(""))).toEqual(["plugins/a"]);
|
||||
expect(read("plugins/a/hooks/hooks.json")).toBe("base\n");
|
||||
});
|
||||
|
||||
test("is a whole marketplace in a directory", () => {
|
||||
write("market/.claude-plugin/marketplace.json", "base\n");
|
||||
write("market/a/hooks.json", "base\n");
|
||||
startPr();
|
||||
write("market/a/hooks.json", "pr\n");
|
||||
commit("pr");
|
||||
for (const input of [
|
||||
"./market",
|
||||
"./market/.claude-plugin/marketplace.json",
|
||||
]) {
|
||||
process.env.INPUT_PLUGIN_MARKETPLACES = input;
|
||||
expect(restore(namedConfigPaths(""))).toEqual(["market"]);
|
||||
expect(read("market/a/hooks.json")).toBe("base\n");
|
||||
git("checkout", "-q", "--", "market");
|
||||
}
|
||||
});
|
||||
|
||||
test("can't be a plugin that is the whole repository", () => {
|
||||
write(
|
||||
".claude-plugin/marketplace.json",
|
||||
JSON.stringify({ plugins: [{ name: "a", source: "./" }] }),
|
||||
);
|
||||
startPr();
|
||||
process.env.INPUT_PLUGIN_MARKETPLACES = "./";
|
||||
|
||||
expect(() => restore(namedConfigPaths(""))).toThrow(
|
||||
"Put the plugin in a subdirectory",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("namedConfigPaths", () => {
|
||||
test("finds paths in every input that names files", () => {
|
||||
process.env.INPUT_SETTINGS = " .github/settings.json ";
|
||||
process.env.INPUT_PLUGIN_MARKETPLACES =
|
||||
"./market\n../outside\n/elsewhere\n";
|
||||
expect(
|
||||
namedConfigPaths(
|
||||
`--mcp-config '{"mcpServers":{}}' a.json b.json
|
||||
--plugin-dir=plugin --settings '{"a":1}' --agents agents.json
|
||||
--append-system-prompt-file p.md --system-prompt-file ../x.md
|
||||
--plugin-dir-no-mcp 2024 --append-subagent-system-prompt-file q.md
|
||||
--setting-sources user --json-schema '{}'
|
||||
--allowedTools Read --model m`,
|
||||
),
|
||||
).toEqual({
|
||||
paths: [
|
||||
".github/settings.json",
|
||||
"a.json",
|
||||
"b.json",
|
||||
"plugin",
|
||||
"agents.json",
|
||||
"p.md",
|
||||
"2024",
|
||||
"q.md",
|
||||
],
|
||||
marketplaces: ["market"],
|
||||
});
|
||||
});
|
||||
|
||||
test("finds the project config in a --project-config-root", () => {
|
||||
startPr();
|
||||
const { paths } = namedConfigPaths("--project-config-root app");
|
||||
expect(paths).toContain("app/.claude");
|
||||
expect(paths).toContain("app/.mcp.json");
|
||||
expect(paths).not.toContain("app");
|
||||
expect(restore(namedConfigPaths(`--project-config-root .`))).toEqual([]);
|
||||
});
|
||||
|
||||
test("finds nothing in inputs that name no files in the checkout", () => {
|
||||
process.env.INPUT_SETTINGS = '{"permissions":{}}';
|
||||
process.env.INPUT_PLUGIN_MARKETPLACES = "https://example.com/x.git";
|
||||
expect(namedConfigPaths("--mcp-config /etc/mcp.json --settings")).toEqual({
|
||||
paths: [],
|
||||
marketplaces: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -282,7 +282,7 @@ describe("git wrappers", () => {
|
||||
|
||||
describe("with files taken from another branch", () => {
|
||||
const RESTORED =
|
||||
":(top).claude\n:(top)CLAUDE.md\n:(top)AGENTS.md\n:(top).mcp.json\n:(top,glob)**/package.json\n";
|
||||
":(top,literal).claude\n:(top,literal)CLAUDE.md\n:(top,literal)AGENTS.md\n:(top,literal).mcp.json\n:(top,glob)**/package.json\n";
|
||||
const write = (path: string, content: string) => {
|
||||
mkdirSync(join(repo, path, ".."), { recursive: true });
|
||||
writeFileSync(join(repo, path), content);
|
||||
|
||||
@@ -441,7 +441,7 @@ describe("session guard", () => {
|
||||
pinRestoredPaths([".claude", "package.json"]);
|
||||
const restoredFile = join(dir, "scripts/.restored-paths");
|
||||
expect(readFileSync(restoredFile, "utf8")).toBe(
|
||||
":(top).claude\n:(top,glob)**/package.json\n",
|
||||
":(top,literal).claude\n:(top,glob)**/package.json\n",
|
||||
);
|
||||
clearSessionState();
|
||||
expect(existsSync(join(dir, "scripts/.push-branch"))).toBe(false);
|
||||
|
||||
Reference in New Issue
Block a user