Compare commits

..
5 Commits
Author SHA1 Message Date
d1f58ad5e6 Use the base branch's AGENTS.md on pull requests (#2059)
Claude Code can load AGENTS.md as project instructions, as it does CLAUDE.md.
On pull requests the root AGENTS.md now comes from the base branch too. The
pull request's version is kept under .claude-pr/.

Co-authored-by: Claude <[email protected]>
2026-11-16 11:02:42 -08:00
fe99289f39 Keep deny rules that hold commas or parentheses (#2033)
* Keep deny rules that hold commas or parentheses

A narrower deny rule for a git command, such as git add on a path with
parentheses, wasn't carried over whole to the wrapper script that runs it. One
with a comma could lose its end when the same text also appeared in the rule
added for the wrapper.

Co-authored-by: mhegazy <[email protected]>

* Find deny rules next to line breaks and across values

A rule after a comma and a line break is read whole too, and a rule written as
two quoted values is carried over again.

Co-authored-by: mhegazy <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
2026-11-16 11:02:36 -08:00
514ab7e6d3 Close gaps in using the base branch's npm and Bun config (#2026)
On pull requests from authors without write access, check package.json as it is on disk where .gitattributes converts it, take .gitattributes from the index, keep Bash in the repository root, and match restored directories exactly. Other directories fields than bin no longer count as commands.

Co-authored-by: Claude <[email protected]>
2026-11-16 11:01:31 -08:00
bcbcedd16c Start Bun with the action's own tsconfig again (#2058)
The run step, the post steps and the MCP servers pass --tsconfig-override
next to --no-env-file and --config. The Bun message that led to removing it
in #1315 is gone from 1.4.3, and the action pins 1.4.4.

Co-authored-by: Claude <[email protected]>
2026-11-16 19:01:23 +00:00
9fa68854da Use the base branch's npm and Bun config on outside pull requests (#2020)
* Use the base branch's npm and Bun config on outside pull requests

Config from the base branch, such as a hook or an MCP server, can start npm or Bun
in the checkout. On pull requests from authors without write access, what those tools
read from the repository root now comes from the base branch wherever it differs.

Co-authored-by: mhegazy <[email protected]>

* Leave already restored directories alone when replacing tool config

The replacement could rewrite files that were restored from the base branch just
before. It also now keeps a new package's name, and handles a directory in a config
file's place and a file that is re-encoded on checkout.

Co-authored-by: mhegazy <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
2026-11-13 22:23:52 +00:00
15 changed files with 1267 additions and 24 deletions
+6 -7
View File
@@ -281,13 +281,12 @@ runs:
id: run
shell: bash
run: |
# Do NOT pass --tsconfig-override here. It triggers a Bun runtime bug
# ("Internal error: directory mismatch for directory .../tsconfig.json")
# that aborts the run with exit code 1. Bun already auto-discovers the
# action's own tsconfig.json by walking up from the entry file, so the
# override is redundant. See oven-sh/bun#25730.
# Keep these options wherever the action runs its own scripts, so that Bun
# takes its settings from the action's directory. Bun before 1.4.3 logs
# "directory mismatch" for --tsconfig-override (oven-sh/bun#25730).
bun --no-env-file \
--config="${GITHUB_ACTION_PATH}/bunfig.toml" \
--tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json" \
run ${GITHUB_ACTION_PATH}/src/entrypoints/run.ts
env:
# Prepare inputs
@@ -428,9 +427,9 @@ runs:
run: |
BUN_BIN="${GITHUB_ACTION_PATH}/bin/bun"
[ -x "$BUN_BIN" ] || BUN_BIN="bun"
# No --tsconfig-override: see the "Run Claude Code Action" step above.
"$BUN_BIN" --no-env-file \
--config="${GITHUB_ACTION_PATH}/bunfig.toml" \
--tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json" \
run ${GITHUB_ACTION_PATH}/src/entrypoints/cleanup-ssh-signing.ts
- name: Post buffered inline comments
@@ -445,9 +444,9 @@ runs:
run: |
BUN_BIN="${GITHUB_ACTION_PATH}/bin/bun"
[ -x "$BUN_BIN" ] || BUN_BIN="bun"
# No --tsconfig-override: see the "Run Claude Code Action" step above.
"$BUN_BIN" --no-env-file \
--config="${GITHUB_ACTION_PATH}/bunfig.toml" \
--tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json" \
run ${GITHUB_ACTION_PATH}/src/entrypoints/post-buffered-inline-comments.ts
- name: Revoke app token
+5 -2
View File
@@ -24,7 +24,7 @@ const ACCUMULATING_FLAGS = new Set([
]);
// Delimiter used to join accumulated flag values
const ACCUMULATE_DELIMITER = "\x00";
export const ACCUMULATE_DELIMITER = "\x00";
// shell-quote treats ()|&;<> as control operators and splits adjacent text
// around them into separate tokens (returned as `{op}` objects, which we then
@@ -275,8 +275,11 @@ export function parseSdkOptions(options: ClaudeOptions): ParsedSdkOptions {
const directDisallowedTools = options.disallowedTools
? options.disallowedTools.split(",").map((t) => t.trim())
: [];
// Not deduplicated: a rule can hold a comma, so these can be pieces of rules, and the
// SDK joins them again. Dropping a repeated piece would break a rule and the ones after it.
const mergedDisallowedTools = [
...new Set([...extraArgsDisallowedTools, ...directDisallowedTools]),
...extraArgsDisallowedTools,
...directDisallowedTools,
];
delete extraArgs["disallowedTools"];
delete extraArgs["disallowed-tools"];
@@ -269,6 +269,17 @@ describe("parseSdkOptions", () => {
expect(result.sdkOptions.extraArgs?.["disallowedTools"]).toBeUndefined();
});
test("keeps rules that share text after a comma", () => {
const result = parseSdkOptions({
claudeArgs: `--disallowedTools 'Bash(/x.sh {a,b}/*)' --disallowedTools 'Bash(git add {a,b}/*)'`,
disallowedTools: "Bash(bun:*)",
});
expect(result.sdkOptions.disallowedTools?.join(",")).toBe(
"Bash(/x.sh {a,b}/*),Bash(git add {a,b}/*),Bash(bun:*)",
);
});
test("should merge disallowedTools from both sources", () => {
const options: ClaudeOptions = {
claudeArgs: '--disallowedTools "Bash"',
+8 -4
View File
@@ -57,11 +57,15 @@ This is general guidance for these event types — see [GitHub's documentation](
### Which files come from the base branch on pull requests
When the action runs against a pull request, it restores a fixed list of Claude configuration paths from the PR base branch before starting Claude: `.claude/`, `.mcp.json`, `.claude.json`, `.gitmodules`, `.ripgreprc`, `CLAUDE.md`, `CLAUDE.local.md`, and `.husky/`. Paths in that list that do not exist on the base branch are removed, and the PR-authored versions are kept under `.claude-pr/` for reference only.
When the action runs against a pull request, it restores a fixed list of Claude configuration paths from the PR base branch before starting Claude: `.claude/`, `.mcp.json`, `.claude.json`, `.gitmodules`, `.ripgreprc`, `CLAUDE.md`, `CLAUDE.local.md`, `AGENTS.md`, and `.husky/`. Paths in that list that do not exist on the base branch are removed, and the PR-authored versions are kept under `.claude-pr/` for reference only.
Everything else in the working tree — including `package.json`, lockfiles, `Makefile`, `node_modules/`, and formatter/linter config files — stays at the PR head. If a hook, `apiKeyHelper`, or `statusLine` command in your base-branch `.claude/settings.json` runs a package-manager script (`bun run …`, `npm run …`, `yarn …`, `pnpm run …`), a `make` target, a repo-relative script, or a tool that loads executable project config, that command resolves through files the pull request supplies. Keep such commands self-contained: invoke the tool directly with a pinned version and pass its configuration on the command line (for example `bunx [email protected] --no-config --write .` rather than `bun run format`).
Everything else in the working tree — including `package.json`, lockfiles, `Makefile`, `node_modules/`, and formatter/linter config files — stays at the PR head, apart from the files described below. If a hook, `apiKeyHelper`, or `statusLine` command in your base-branch `.claude/settings.json` runs a package-manager script (`bun run …`, `npm run …`, `yarn …`, `pnpm run …`), a `make` target, a repo-relative script, or a tool that loads executable project config, that command resolves through files the pull request supplies. Keep such commands self-contained: invoke the tool directly with a pinned version and pass its configuration on the command line (for example `bunx [email protected] --no-config --write .` rather than `bun run format`).
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 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.
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.
### Running code from pull requests
@@ -88,7 +92,7 @@ Job logs, and job and step names, are text the pull request controls. To turn of
Bots often open pull requests from branches in your own repository. Runs there usually need no approval and can get secrets, so these steps don't protect you in that case.
**Upgrading:** workflows that use a floating tag or branch such as `@v1` or `@main` get this behavior without changing anything. If a workflow relied on commands like `npm test` running on pull requests from outside contributors or bots, those commands are now denied. The run still succeeds, so check the log for the warning. Set `restrict_untrusted_prs: false` to turn this off.
**Upgrading:** workflows that use a floating tag or branch such as `@v1` or `@main` get this behavior without changing anything. If a workflow relied on commands like `npm test` running on pull requests from outside contributors or bots, those commands are now denied, tool config comes from the base branch as described [above](#which-files-come-from-the-base-branch-on-pull-requests), and a `cd` no longer carries over to the next Bash command. The run still succeeds, so check the log for the warning. Set `restrict_untrusted_prs: false` to turn this off.
### What a session can leave behind
+29 -5
View File
@@ -39,6 +39,10 @@ import {
snapshotSessionFiles,
} from "../github/operations/session-guard";
import { restoreConfigFromBase } from "../github/operations/restore-config";
import {
restoreToolConfigFromBase,
toolConfigDenyRules,
} from "../github/operations/tool-config";
import { validateBranchName } from "../github/operations/branch";
import { collectActionInputsPresence } from "./collect-inputs";
import { updateCommentLink } from "./update-comment-link";
@@ -283,6 +287,13 @@ async function run() {
validateEnvironmentVariables();
// Tag mode sets claudeBranch only when it branched from the base instead of
// checking out the PR's head, as for a closed or merged PR.
const checkedOutPrHead = modeName !== "tag" || !claudeBranch;
const isUntrustedCheckout =
checkedOutPrHead && untrustedPrDisallowedTools.length > 0;
let restoredToolConfig: string[] = [];
// On PRs, .claude/ and .mcp.json in the checkout are attacker-controlled.
// Restore them from the base branch before the CLI reads them.
//
@@ -304,6 +315,11 @@ async function run() {
}
if (restoreBase) {
restoredConfigPaths = restoreConfigFromBase(restoreBase);
// Before plugins are installed, which can already start package managers here.
if (isUntrustedCheckout) {
restoredToolConfig = restoreToolConfigFromBase(restoreBase);
restoredConfigPaths.push(...restoredToolConfig);
}
}
}
@@ -323,12 +339,20 @@ async function run() {
promptFile,
});
// Tag mode sets claudeBranch only when it branched from the base instead of
// checking out the PR's head, as for a closed or merged PR. The deny rules are
// passed separately because text added to claudeArgs can be lost: a comment at
// Passed separately because text added to claudeArgs can be lost: a comment at
// the end of the user's claude_args would swallow it.
const checkedOutPrHead = modeName !== "tag" || !claudeBranch;
const disallowedTools = checkedOutPrHead ? untrustedPrDisallowedTools : [];
const disallowedTools = isUntrustedCheckout
? [
...untrustedPrDisallowedTools,
...toolConfigDenyRules(restoredToolConfig),
]
: [];
// A hook runs in the session's current directory, and only the repository root's tool
// config comes from the base branch. This keeps Bash from moving the session.
if (isUntrustedCheckout) {
process.env.CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR = "1";
}
const restoreSessionFiles = snapshotSessionFiles(() =>
prepareGitForSession({ hooks: hooksOff }),
+4 -2
View File
@@ -31,6 +31,7 @@ export const SENSITIVE_PATHS = [
".ripgreprc",
"CLAUDE.md",
"CLAUDE.local.md",
"AGENTS.md",
".husky",
];
@@ -206,7 +207,7 @@ function snapshotSensitivePath(
}
}
function ensureClaudePrExcludedFromGit(): void {
export function ensureClaudePrExcludedFromGit(): void {
const excludePath = execFileSync(
"git",
["rev-parse", "--git-path", "info/exclude"],
@@ -258,7 +259,8 @@ function ensureClaudePrExcludedFromGit(): void {
* extends to the runtime itself: `bunx <tool>` runs the tool under `node` when
* `node` is on PATH, but on a Bun-only runner Bun executes the script and reads
* `bunfig.toml` (e.g. `preload`) from the checkout, so `bunfig.toml` and
* `.npmrc` there are PR-controlled runtime config too.
* `.npmrc` there are PR-controlled runtime config too. On PRs from authors without
* write access, restoreToolConfigFromBase replaces those.
*
* @param baseBranch - PR base branch name. Must be pre-validated (branch.ts
* calls validateBranchName on it before returning).
+422
View File
@@ -0,0 +1,422 @@
import * as core from "@actions/core";
import { execFileSync } from "child_process";
import {
lstatSync,
mkdirSync,
readdirSync,
readFileSync,
rmdirSync,
rmSync,
symlinkSync,
writeFileSync,
} from "fs";
import { dirname } from "path";
import {
ensureClaudePrExcludedFromGit,
SENSITIVE_PATHS,
} from "./restore-config";
// What npm and Bun read from the repository root to decide which program to run and
// where to download it from. Config from the base branch can start them, for example
// in a hook or an MCP server. node_modules counts because its .bin comes first on PATH,
// and package.json because npx looks for commands there first.
const TOOL_CONFIG = [".npmrc", "bunfig.toml", "node_modules"];
const PACKAGE_JSON = "package.json";
// The fields that provide commands. A bin that is a string is named after the package,
// and npx looks in workspaces too.
const COMMAND_FIELDS = ["name", "bin", "directories", "workspaces"];
const NO_COMMANDS = "none";
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 };
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";
// No file name or content, which the pull request controls, reaches the log.
function warn(what: string, error: unknown): void {
const { code, status } = error as { code?: string; status?: number };
core.warning(`${what} (${code ?? `exit code ${status ?? "unknown"}`})`);
}
function git(args: string[], input: string | Buffer = ""): Buffer {
return execFileSync("git", args, {
stdio: ["pipe", "pipe", "ignore"],
input,
env: { ...process.env },
maxBuffer: MAX_OUTPUT_BYTES,
});
}
// A parent that is a file or a looping link means there is nothing there.
function onDisk(path: string) {
try {
return lstatSync(fsPath(path));
} catch {
return undefined;
}
}
// File systems can ignore case, and some the way a character is encoded.
const fold = (path: string): string =>
fsPath(path).toString().normalize("NFKC").toLowerCase();
/**
* Whether a path is in a directory that comes from the base branch already. The index
* has the pull request's version of it, so nothing there may be rebuilt from that.
*/
function isRestored(path: string, topLevel: Set<string>): boolean {
const [dir] = path.split("/") as [string];
return SENSITIVE_PATHS.some(
(restored) =>
dir === restored ||
// Another spelling is a directory of its own only if the file system lists it.
(fold(dir) === fold(restored) && !topLevel.has(dir)),
);
}
/** Which tool config a path belongs to. */
function rootName(path: string): string | undefined {
const folded = fold(path);
// A directory with one of these names is in the file's place, whatever it holds.
const name = TOOL_CONFIG.find(
(name) => folded === name || folded.startsWith(`${name}/`),
);
if (name) return name;
return folded === PACKAGE_JSON || folded.endsWith(`/${PACKAGE_JSON}`)
? PACKAGE_JSON
: undefined;
}
/** Whether no parent of a path is a link, which could lead out of the checkout. */
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 {
rmSync(fsPath(path), { recursive: true, force: true });
// An empty directory would stand in the way of a file of that name.
try {
for (let dir = dirname(path); dir !== "."; dir = dirname(dir)) {
rmdirSync(fsPath(dir));
}
} catch {
// It isn't empty.
}
}
// Each entry is "<mode> <other fields>\t<path>", relative to the working directory.
function parseEntries(listing: Buffer, oidField: number): Map<string, Entry> {
const entries = new Map<string, Entry>();
const topLevel = new Set(
readdirSync(".", { encoding: "buffer" }).map((name) =>
name.toString("latin1"),
),
);
for (const line of listing.toString("latin1").split("\0")) {
const [info, path] = line.split(/\t(.*)/s);
if (!info || !path || !rootName(path) || isRestored(path, topLevel)) {
continue;
}
const fields = info.split(" ");
entries.set(path, { mode: fields[0]!, oid: fields[oidField]! });
}
return entries;
}
const pullRequestEntries = (): Map<string, Entry> =>
parseEntries(git(["ls-files", "--stage", "-z"]), 1);
// A checkout with a narrow refspec has no remote-tracking branch, only FETCH_HEAD.
function baseEntries(baseBranch: string): Map<string, Entry> {
let ref = `refs/remotes/origin/${baseBranch}`;
try {
git(["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]);
} catch {
ref = "FETCH_HEAD";
}
return parseEntries(git(["ls-tree", "-r", "-z", ref]), 2);
}
/** The stored content of each entry, which no .gitattributes has been applied to. */
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;
const output = git(["cat-file", "--batch"], `${oids.join("\n")}\n`);
// "<oid> <type> <size>\n<content>\n", or "<oid> missing\n"
for (let at = 0; at < output.length; ) {
const end = output.indexOf("\n", at);
const [oid, , size] = output.toString("latin1", at, end).split(" ");
at = end + 1;
if (size === undefined) continue;
blobs.set(oid!, output.subarray(at, at + Number(size)));
at += Number(size) + 1;
}
return blobs;
}
type Json = Record<string, unknown>;
/** Parses a package.json, or returns undefined if it can't be understood. */
function parsePackageJson(size: number, read: () => Buffer): Json | undefined {
if (size > MAX_PACKAGE_JSON_BYTES) return undefined;
// trimStart also drops a byte order mark.
const json = JSON.parse(read().toString().trimStart());
return json && typeof json === "object" ? json : undefined;
}
/** The package.json that git stores. */
function readPackageJson(entry: Entry): Json | undefined {
if (!isFile(entry)) return undefined;
try {
const size = Number(git(["cat-file", "-s", entry.oid]).toString());
return parsePackageJson(size, () => git(["cat-file", "blob", entry.oid]));
} catch {
return undefined;
}
}
/** The package.json on disk, which .gitattributes can make differ from what git stores. */
function readPackageJsonOnDisk(path: string): Json | undefined {
try {
const { size } = lstatSync(fsPath(path));
return parsePackageJson(size, () => readFileSync(fsPath(path)));
} catch {
return undefined;
}
}
/** The commands a package.json provides, or undefined if that can't be told. */
function commands(json: Json | undefined): string | undefined {
if (!json) return undefined;
// Other directories, such as the one for tests, provide no commands.
const directories = (json.directories as Json | null | undefined)?.bin;
if (!json.bin && !directories && !json.workspaces) return NO_COMMANDS;
const provided: Json = { ...json, directories };
return JSON.stringify(COMMAND_FIELDS.map((field) => provided[field] ?? null));
}
/**
* The attributes that make git write each file differently from what it stores. The
* pull request controls .gitattributes.
*/
function conversions(paths: string[]): Map<string, Set<string>> {
const found = new Map<string, Set<string>>();
if (paths.length === 0) return found;
// Checkout uses the index's .gitattributes, and the one on disk can be converted too.
// If the index has none, it uses the one on disk.
for (const source of [["--cached"], []]) {
const fields = git(
["check-attr", ...source, "-z", "--stdin", ENCODING, "ident", "filter"],
Buffer.from(paths.map((path) => `${path}\0`).join(""), "latin1"),
)
.toString("latin1")
.split("\0");
// "<path> <attribute> <value>", each ended by a NUL
for (let i = 0; i + 2 < fields.length; i += 3) {
const [path, attribute, value] = fields.slice(i) as [
string,
string,
string,
];
if (value === "unspecified" || value === "unset") continue;
// Git takes this as no conversion.
if (attribute === ENCODING && /^utf-?8$/i.test(value)) continue;
found.set(path, (found.get(path) ?? new Set()).add(attribute));
}
}
return found;
}
function differs(
path: string,
converted: Set<string> | undefined,
pr?: Entry,
base?: Entry,
): boolean {
const isSame = pr?.oid === base?.oid && pr?.mode === base?.mode;
// Even an unchanged file can then be one that npm or Bun can't read.
if (converted?.has(ENCODING)) return true;
if (rootName(path) !== PACKAGE_JSON) return !isSame;
if (!pr || isSame) return false;
const provided = [commands(readPackageJson(pr))];
// npm reads what is on disk, unless an earlier step removed it.
if (converted && hasRealParents(path) && onDisk(path)?.isFile()) {
provided.push(commands(readPackageJsonOnDisk(path)));
}
// Only one that provides commands matters, so most pull requests keep their own.
const allowed = [
NO_COMMANDS,
base ? commands(readPackageJson(base)) : NO_COMMANDS,
];
return provided.some((value) => !value || !allowed.includes(value));
}
/** The pull request's package.json with the base branch's commands. */
function withBaseCommands(
pr: Entry,
base: Entry | undefined,
): Buffer | undefined {
const json = readPackageJson(pr);
const baseJson = base ? readPackageJson(base) : {};
if (!json || !baseJson) return undefined;
for (const field of COMMAND_FIELDS) {
// Without a bin, a new package's name provides no command.
if (field === "name" && !base) continue;
if (baseJson[field] === undefined) delete json[field];
else json[field] = baseJson[field];
}
return Buffer.from(`${JSON.stringify(json, null, 2)}\n`);
}
/** Keeps the pull request's version readable, as for the other restored config. */
function snapshotForReview(path: string, entry: Entry): void {
if (!isFile(entry) || rootName(path) === "node_modules") return;
try {
const content = git(["cat-file", "blob", entry.oid]);
const copy = fsPath(`.claude-pr/${path}`);
mkdirSync(fsPath(`.claude-pr/${dirname(path)}`), { recursive: true });
writeFileSync(copy, content);
ensureClaudePrExcludedFromGit();
} catch (error) {
warn("Could not keep a copy of tool config for review", error);
}
}
/**
* Replaces the pull request's tool config with the base branch's wherever they differ.
* Like restoreConfigFromBase, which must run first because it fetches the base branch,
* it changes the working tree and not the index. Only tracked files are replaced, so
* what an earlier step created stays. In a package.json only the commands are replaced.
*
* @returns The names that were replaced, from a fixed list. Callers that stage files
* must exclude them.
* @throws If the base branch's version can't be put in place. The message holds no
* file name, because the pull request controls those.
*/
export function restoreToolConfigFromBase(baseBranch: string): string[] {
try {
return restoreToolConfig(baseBranch);
} catch (error) {
warn("Could not replace tool config", error);
throw new Error(
"Could not use the base branch's version of the files that npm and Bun read",
);
}
}
function restoreToolConfig(baseBranch: string): string[] {
const pr = pullRequestEntries();
const base = baseEntries(baseBranch);
const all = [...new Set([...pr.keys(), ...base.keys()])];
// npx reads the packages in subdirectories only through the root's workspaces, and
// a pull request's own are replaced below.
const rootJson = base.get(PACKAGE_JSON);
const hasWorkspaces =
rootJson !== undefined &&
readPackageJson(rootJson)?.workspaces !== undefined;
const matters = (path: string): boolean =>
hasWorkspaces || rootName(path) !== PACKAGE_JSON || !path.includes("/");
const converted = conversions(
[...pr].flatMap(([path, entry]) =>
isFile(entry) && matters(path) && rootName(path) !== "node_modules"
? [path]
: [],
),
);
// Names that differ only in case can be the same file.
const differing = new Set(
all
.filter(
(path) =>
matters(path) &&
differs(path, converted.get(path), pr.get(path), base.get(path)),
)
.map(fold),
);
const candidates = all.filter((path) => differing.has(fold(path)));
// A directory where the pull request has a file or link came from an earlier step.
const replaced = candidates.filter((path) => {
const entry = pr.get(path);
const stats = entry && onDisk(path);
return (
stats &&
(!stats.isDirectory() || isSubmodule(entry)) &&
hasRealParents(path)
);
});
// All of these go before anything is written.
for (const path of replaced) {
snapshotForReview(path, pr.get(path)!);
remove(path);
}
const removed = new Set(replaced);
const toWrite = candidates.flatMap((path): Replacement[] => {
const entry = base.get(path);
const prEntry = pr.get(path);
// One that the pull request has but is not on disk was left out or deleted by the
// workflow. One that only the base has matters unless it's a package.json.
const wanted = prEntry
? removed.has(path)
: rootName(path) !== PACKAGE_JSON;
if (!wanted || onDisk(path)) return [];
const content =
prEntry && rootName(path) === PACKAGE_JSON
? withBaseCommands(prEntry, entry)
: undefined;
if (content) return [{ path, entry: prEntry!, content }];
return entry && !isSubmodule(entry) ? [{ path, entry, content }] : [];
});
const blobs = readBlobs(
toWrite.flatMap(({ entry, content }) => (content ? [] : [entry])),
);
const written: string[] = [];
for (const { path, entry, content = blobs.get(entry.oid) } of toWrite) {
if (!hasRealParents(path)) continue;
if (!content) throw new Error("missing object");
mkdirSync(fsPath(dirname(path)), { recursive: true });
if (isLink(entry)) symlinkSync(content, fsPath(path));
else {
const mode = entry.mode === "100755" ? 0o755 : 0o644;
writeFileSync(fsPath(path), content, { mode, flag: "wx" });
}
written.push(path);
}
const names = [
...new Set([...replaced, ...written].map((path) => rootName(path)!)),
];
if (names.length > 0) {
core.warning(
`The pull request and its base branch differ in what npm and Bun read (${names.join(", ")}), so the base branch's version is used and Claude can't edit it. See docs/security.md.`,
);
}
return names;
}
/**
* Rules that stop a session from editing tool config, for a pull request whose author
* doesn't have write access. Other package.json edits are ordinary work. The rules
* cover subdirectories too, because a hook runs in the session's current directory.
*/
export const toolConfigDenyRules = (replaced: string[]): string[] => [
...TOOL_CONFIG.map((name) =>
name === "node_modules" ? "Edit(./node_modules/**)" : `Edit(./${name})`,
),
...(replaced.includes(PACKAGE_JSON) ? ["Edit(package.json)"] : []),
];
+1
View File
@@ -26,6 +26,7 @@ function bunServerArgs(scriptPath: string): string[] {
return [
"--no-env-file",
`--config=${actionPath}/bunfig.toml`,
`--tsconfig-override=${actionPath}/tsconfig.json`,
"run",
`${actionPath}/${scriptPath}`,
];
+17 -3
View File
@@ -1,5 +1,6 @@
import { parse as parseShellArgs } from "shell-quote";
import {
ACCUMULATE_DELIMITER,
escapeShellMeta,
parseClaudeArgsToExtraArgs,
unescapeShellMeta,
@@ -99,11 +100,24 @@ export function parseDeniedBashPatterns(claudeArgs: string): string[] {
: [];
},
);
return values.flatMap((value) =>
[...value.matchAll(/Bash\(([^)]*)\)/g)].map((match) => match[1]!),
);
const patterns = values.flatMap((value) => [
// Whole rules, whose own text can hold parentheses: Bash(git add "app/(auth)/*").
...value
.split(ACCUMULATE_DELIMITER)
.flatMap((part) => part.match(RULE) ?? [])
.flatMap((rule) => rule.trim().match(/^Bash\((.*)\)$/)?.[1] ?? []),
// Also whatever looks like a rule, so that one the CLI can't read still denies.
...[...value.matchAll(/Bash\(([^)]*)\)/g)].map((match) => match[1]!),
]);
return [...new Set(patterns)];
}
/**
* One rule in a list. Like the CLI, it ends at a comma or space outside parentheses,
* where any `)` ends the parentheses.
*/
const RULE = /(?:\([^)]*\)?|[^ ,(])+/g;
/**
* The deny rules a wrapper needs so a workflow's rules for the command it runs still
* apply: all of it for a rule that covers every use, otherwise each narrower form, so
+19
View File
@@ -27,6 +27,25 @@ describe("action metadata", () => {
);
});
test("should start each of the action's scripts with the same Bun options", () => {
const commands = readFileSync(
new URL("../action.yml", import.meta.url),
"utf8",
)
.replace(/\\\n\s*/g, "")
.split("\n")
.filter((line) => line.includes("${GITHUB_ACTION_PATH}/src/"));
expect(commands).toHaveLength(3);
for (const command of commands) {
expect(command).toContain(
' --no-env-file --config="${GITHUB_ACTION_PATH}/bunfig.toml"' +
' --tsconfig-override="${GITHUB_ACTION_PATH}/tsconfig.json"' +
" run ${GITHUB_ACTION_PATH}/src/entrypoints/",
);
}
});
test("should not put step outputs into shell scripts", () => {
// A session can write step outputs, so an expression in a script could run
// its commands. Scripts have to read these values from the environment.
+1
View File
@@ -246,6 +246,7 @@ describe("prepareMcpConfig", () => {
expect(parsed.mcpServers[name].args).toEqual([
"--no-env-file",
"--config=/test/action/path/bunfig.toml",
"--tsconfig-override=/test/action/path/tsconfig.json",
"run",
`/test/action/path/${script}`,
]);
+16
View File
@@ -24,6 +24,22 @@ describe("parseDeniedBashPatterns", () => {
expected as string[],
);
});
test.each([
[`'Bash(git add "app/(auth)/*")'`, `git add "app/(auth)/*"`],
[`'Bash(a:*) Bash(git add "(x)/*"),Bash(b:*)'`, `git add "(x)/*"`],
[`'Bash(git add {a,b}/*)'`, "git add {a,b}/*"],
[`"Read(x(" "Bash(a b:*)"`, "a b:*"],
[`"Bash(a:*)\nBash(b c:*)"`, "b c:*"],
[`"Bash(a:*),\nBash(git add \\"(x)/*\\")"`, `git add "(x)/*"`],
[`"Bash(git add {a" "b}/*)"`, "git add {a\0b}/*"],
[`"Bash(a:*);Read(x)"`, "a:*"],
[`"Bash(a:*))"`, "a:*"],
])("finds the rule in %s", (rules, expected) => {
expect(parseDeniedBashPatterns(`--disallowedTools ${rules}`)).toContain(
expected,
);
});
});
describe("deniesCommand", () => {
+1 -1
View File
@@ -191,7 +191,7 @@ describe("Tag Mode", () => {
expect(args).toContain(
`--disallowedTools 'Bash(/action/scripts/git-add.sh -A:*)'`,
);
for (const rest of [`"a b"`, "it's", "$HOME/x"]) {
for (const rest of [`"a b"`, "it's", "$HOME/x", `"(a)/x"`]) {
const denied = await prepare(
`--disallowedTools 'Bash(git add ${rest.replace(/'/g, "'\\''")}:*)'`,
);
+29
View File
@@ -148,6 +148,35 @@ describe("restoreConfigFromBase", () => {
);
});
test("removes an AGENTS.md that only the PR has", () => {
writeRepoFile("AGENTS.md", "pr agent instructions\n");
git(["add", "AGENTS.md"]);
git(["commit", "-m", "pr adds agents file"]);
const restored = restoreConfigFromBase("main");
expect(restored).toContain("AGENTS.md");
expect(existsRepoFile("AGENTS.md")).toBe(false);
expect(readRepoFile(".claude-pr/AGENTS.md")).toBe(
"pr agent instructions\n",
);
});
test("uses the base branch's AGENTS.md, also through a CLAUDE.md link", () => {
setupSymlinkedMainBranch();
writeRepoFile("AGENTS.md", "pr agent instructions\n");
git(["commit", "-am", "pr edits agents file"]);
restoreConfigFromBase("main");
expect(readRepoFile("AGENTS.md")).toBe("shared agent instructions\n");
expect(readRepoFile("CLAUDE.md")).toBe("shared agent instructions\n");
expect(readRepoFile(".claude-pr/AGENTS.md")).toBe(
"pr agent instructions\n",
);
expect(git(["diff", "--cached", "--name-only"])).toBe("");
});
test("records dangling links as placeholders, including top-level ones", () => {
setupSymlinkedMainBranch();
+698
View File
@@ -0,0 +1,698 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { execFileSync } from "child_process";
import {
chmodSync,
existsSync,
lstatSync,
mkdirSync,
mkdtempSync,
readdirSync,
readFileSync,
readlinkSync,
rmSync,
symlinkSync,
writeFileSync,
} from "fs";
import { tmpdir } from "os";
import { dirname, join } from "path";
import {
toolConfigDenyRules,
restoreToolConfigFromBase,
} from "../src/github/operations/tool-config";
import { restoreConfigFromBase } from "../src/github/operations/restore-config";
describe("restoreToolConfigFromBase", () => {
let originalCwd: string;
let tempDir: string;
const git = (...args: string[]) =>
execFileSync("git", args, { encoding: "utf8", stdio: "pipe" }).trim();
const write = (path: string, content: string, executable = false) => {
mkdirSync(dirname(path), { recursive: true });
writeFileSync(path, content);
if (executable) chmodSync(path, 0o755);
};
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");
};
beforeEach(() => {
originalCwd = process.cwd();
tempDir = mkdtempSync(join(tmpdir(), "tool-config-"));
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);
rmSync(tempDir, { recursive: true, force: true });
});
test("does nothing when the pull request has the same tool config", () => {
write(".npmrc", "base\n");
write("package.json", '{"name":"x","bin":"cli.js"}');
startPr();
write("src/index.ts", "pr\n");
commit("pr");
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(git("status", "--porcelain")).toBe("");
expect(existsSync(".claude-pr")).toBe(false);
});
test("uses the base version of a changed file, and removes an added one", () => {
write(".npmrc", "base\n");
startPr();
write(".npmrc", "pr\n");
write("bunfig.toml", "pr\n");
write("node_modules/.bin/node", "#!/bin/sh\n", true);
commit("pr");
expect(restoreToolConfigFromBase("main").sort()).toEqual([
".npmrc",
"bunfig.toml",
"node_modules",
]);
expect(read(".npmrc")).toBe("base\n");
expect(existsSync("bunfig.toml")).toBe(false);
expect(existsSync("node_modules")).toBe(false);
expect(read(".claude-pr/.npmrc")).toBe("pr\n");
// Nothing is staged, so the pull request's versions are still what git has.
expect(git("diff", "--cached", "--name-only")).toBe("");
});
test("brings back a file the pull request deleted", () => {
write(".npmrc", "base\n");
write("node_modules/.bin/tool", "base\n", true);
startPr();
rmSync(".npmrc");
rmSync("node_modules", { recursive: true });
commit("pr");
restoreToolConfigFromBase("main");
expect(read(".npmrc")).toBe("base\n");
expect(read("node_modules/.bin/tool")).toBe("base\n");
expect(lstatSync("node_modules/.bin/tool").mode & 0o111).not.toBe(0);
});
test("leaves untracked files that an earlier step created", () => {
write("bunfig.toml", "base\n");
startPr();
rmSync("bunfig.toml");
write(".npmrc.example", "pr\n");
commit("pr");
write("bunfig.toml", "from a step\n");
write(".npmrc", "from a step\n");
write("node_modules/.bin/tool", "installed\n", true);
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(read("bunfig.toml")).toBe("from a step\n");
expect(read(".npmrc")).toBe("from a step\n");
expect(read("node_modules/.bin/tool")).toBe("installed\n");
});
test("keeps a step's change to a file the pull request leaves alone", () => {
write(".npmrc", "base\n");
startPr();
write("src/index.ts", "pr\n");
commit("pr");
write(".npmrc", "base\nfrom a step\n");
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(read(".npmrc")).toBe("base\nfrom a step\n");
});
test("keeps a file deleted by an earlier step deleted", () => {
write(".npmrc", "base\n");
startPr();
write(".npmrc", "pr\n");
commit("pr");
rmSync(".npmrc");
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(existsSync(".npmrc")).toBe(false);
});
test("leaves a directory an earlier step put in a tracked link's place", () => {
startPr();
symlinkSync("elsewhere", "node_modules");
commit("pr");
rmSync("node_modules");
write("node_modules/tool/a", "installed\n");
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(read("node_modules/tool/a")).toBe("installed\n");
});
test("leaves files that a sparse checkout leaves out", () => {
write("node_modules/tool/a", "base\n");
startPr();
write("node_modules/tool/a", "pr\n");
commit("pr");
git("sparse-checkout", "set", "src");
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(existsSync("node_modules/tool/a")).toBe(false);
});
test("replaces links without following them", () => {
write("node_modules/.bin/tool", "base\n", true);
startPr();
const outside = join(tempDir, "outside");
write(join(outside, ".bin/tool"), "outside\n");
rmSync("node_modules", { recursive: true });
symlinkSync(outside, "node_modules");
symlinkSync(join(outside, ".bin/tool"), ".npmrc");
commit("pr");
restoreToolConfigFromBase("main");
expect(lstatSync("node_modules").isDirectory()).toBe(true);
expect(read("node_modules/.bin/tool")).toBe("base\n");
expect(existsSync(".npmrc")).toBe(false);
expect(read(join(outside, ".bin/tool"))).toBe("outside\n");
});
test("writes and removes nothing through a link an earlier step added", () => {
write("node_modules/a/b", "base\n");
write("node_modules/c/d", "base\n");
startPr();
write("node_modules/a/b", "pr\n");
rmSync("node_modules/c", { recursive: true });
commit("pr");
const outside = join(tempDir, "outside");
write(join(outside, "a/b"), "outside\n");
rmSync("node_modules", { recursive: true });
symlinkSync(outside, "node_modules");
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(read(join(outside, "a/b"))).toBe("outside\n");
expect(existsSync(join(outside, "c"))).toBe(false);
});
test("brings back a link the base branch has", () => {
write("node_modules/tool/cli.js", "base\n");
mkdirSync("node_modules/.bin");
symlinkSync("../tool/cli.js", "node_modules/.bin/tool");
startPr();
rmSync("node_modules/.bin/tool");
write("node_modules/.bin/tool", "pr\n", true);
commit("pr");
restoreToolConfigFromBase("main");
expect(readlinkSync("node_modules/.bin/tool")).toBe("../tool/cli.js");
});
test("replaces a directory the pull request puts in a file's place", () => {
write(".npmrc", "base\n");
startPr();
rmSync(".npmrc");
write(".npmrc/keep", "pr\n");
commit("pr");
restoreToolConfigFromBase("main");
expect(read(".npmrc")).toBe("base\n");
});
test("replaces a directory that holds a package.json too", () => {
write(".npmrc", "base\n");
startPr();
rmSync(".npmrc");
write(".npmrc/package.json", "{}");
commit("pr");
restoreToolConfigFromBase("main");
expect(read(".npmrc")).toBe("base\n");
});
test("rewrites an unchanged file that .gitattributes re-encodes", () => {
write(".npmrc", "ignore-scripts=true\n");
startPr();
write(".gitattributes", ".npmrc working-tree-encoding=UTF-16LE-BOM\n");
git("add", ".gitattributes");
git("commit", "-qm", "pr");
expect(git("rev-parse", "HEAD:.npmrc")).toBe(
git("rev-parse", "main:.npmrc"),
);
rmSync(".npmrc");
git("checkout", "--", ".npmrc");
expect(read(".npmrc")).not.toBe("ignore-scripts=true\n");
expect(restoreToolConfigFromBase("main")).toEqual([".npmrc"]);
expect(read(".npmrc")).toBe("ignore-scripts=true\n");
});
test("sees re-encoding when .gitattributes is re-encoded too", () => {
write(".npmrc", "ignore-scripts=true\n");
startPr();
const encoding = "working-tree-encoding=UTF-16LE-BOM";
write(".gitattributes", `.npmrc ${encoding}\n.gitattributes ${encoding}\n`);
const oid = git("hash-object", "-w", "--no-filters", ".gitattributes");
git("update-index", "--add", "--cacheinfo", `100644,${oid},.gitattributes`);
git("commit", "-qm", "pr");
rmSync(".npmrc");
rmSync(".gitattributes");
git("checkout", "--", ".");
expect(read(".npmrc")).not.toBe("ignore-scripts=true\n");
expect(read(".gitattributes")).not.toContain(encoding);
expect(restoreToolConfigFromBase("main")).toEqual([".npmrc"]);
expect(read(".npmrc")).toBe("ignore-scripts=true\n");
});
test("sees re-encoding by a .gitattributes that is only on disk", () => {
write(".npmrc", "ignore-scripts=true\n");
startPr();
write("f.txt", "pr\n");
commit("pr");
write(".gitattributes", ".npmrc working-tree-encoding=UTF-16LE-BOM\n");
rmSync(".npmrc");
git("checkout", "--", ".npmrc");
expect(read(".npmrc")).not.toBe("ignore-scripts=true\n");
expect(restoreToolConfigFromBase("main")).toEqual([".npmrc"]);
expect(read(".npmrc")).toBe("ignore-scripts=true\n");
});
test("matches names without regard to case", () => {
write(".npmrc", "base\n");
startPr();
write("BUNFIG.toml", "pr\n");
write("Node_Modules/.bin/node", "pr\n");
commit("pr");
restoreToolConfigFromBase("main");
expect(existsSync("BUNFIG.toml")).toBe(false);
expect(existsSync("Node_Modules/.bin/node")).toBe(false);
});
test("writes the base version as it is, whatever .gitattributes says", () => {
write(".npmrc", "ignore-scripts=true\n");
startPr();
write(".npmrc", "pr\n");
commit("pr");
write(".gitattributes", ".npmrc working-tree-encoding=UTF-16LE-BOM\n");
restoreToolConfigFromBase("main");
expect(read(".npmrc")).toBe("ignore-scripts=true\n");
});
test("keeps binary and empty content intact", () => {
const content = Buffer.from([0, 10, 255, 10, 13, 0]);
mkdirSync("node_modules");
writeFileSync("node_modules/a", content);
writeFileSync("node_modules/b", "");
writeFileSync("node_modules/c", "no newline");
startPr();
for (const name of ["a", "b", "c"]) write(`node_modules/${name}`, "pr");
commit("pr");
restoreToolConfigFromBase("main");
expect(readFileSync("node_modules/a").equals(content)).toBe(true);
expect(read("node_modules/b")).toBe("");
expect(read("node_modules/c")).toBe("no newline");
});
test("reports names from a fixed list, not the pull request's file names", () => {
startPr();
write("node_modules/a\n::stop-commands::x", "pr\n");
commit("pr");
const names = restoreToolConfigFromBase("main");
expect(names).toEqual(["node_modules"]);
expect(existsSync("node_modules")).toBe(false);
});
test("handles names that are not valid UTF-8", () => {
startPr();
const name = Buffer.from([...Buffer.from("node_modules/"), 0xff]);
mkdirSync("node_modules");
try {
writeFileSync(name, "pr\n");
} catch {
return; // This file system refuses such names.
}
commit("pr");
restoreToolConfigFromBase("main");
expect(existsSync(name)).toBe(false);
});
test("is not misled by a local branch with the base's name", () => {
write(".npmrc", "base\n");
startPr();
write(".npmrc", "pr\n");
commit("pr");
git("branch", "origin/main");
restoreToolConfigFromBase("main");
expect(read(".npmrc")).toBe("base\n");
});
test("works in a checkout with no remote-tracking branch for the base", () => {
write(".npmrc", "base\n");
startPr();
write(".npmrc", "pr\n");
commit("pr");
git("fetch", "-q", "origin", "main");
git("update-ref", "-d", "refs/remotes/origin/main");
restoreToolConfigFromBase("main");
expect(read(".npmrc")).toBe("base\n");
});
test("stops edits to tool config, and to package.json only if replaced", () => {
const rules = [
"Edit(./.npmrc)",
"Edit(./bunfig.toml)",
"Edit(./node_modules/**)",
];
expect(toolConfigDenyRules([])).toEqual(rules);
expect(toolConfigDenyRules(["package.json"])).toEqual([
...rules,
"Edit(package.json)",
]);
});
test("matches names a file system can treat as the same", () => {
startPr();
write("node_module\u017F/.bin/node", "pr\n");
commit("pr");
expect(restoreToolConfigFromBase("main")).toEqual(["node_modules"]);
});
test("fails without naming a file if the base version can't be read", () => {
write(".npmrc", "base\n");
startPr();
write(".npmrc", "pr\n");
commit("pr");
const oid = git("rev-parse", "main:.npmrc");
rmSync(join(".git/objects", oid.slice(0, 2), oid.slice(2)));
expect(() => restoreToolConfigFromBase("main")).toThrow(
/^Could not use the base branch's version/,
);
expect(existsSync(".npmrc")).toBe(false);
});
describe("package.json", () => {
const baseJson = { name: "x", bin: { x: "x.js" }, version: "1.0.0" };
const start = (pr: unknown) => {
write("package.json", JSON.stringify(baseJson));
startPr();
write("package.json", typeof pr === "string" ? pr : JSON.stringify(pr));
commit("pr");
};
test("keeps the pull request's version when only other fields change", () => {
const pr = { ...baseJson, version: "2.0.0", dependencies: { a: "1" } };
start(pr);
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(JSON.parse(read("package.json"))).toEqual(pr);
});
test("keeps the pull request's version when it removes the commands", () => {
start({ name: "x" });
expect(restoreToolConfigFromBase("main")).toEqual([]);
});
test.each([
["bin", { bin: { "tool@latest": "a.js" } }],
["directories", { directories: { bin: "bin" } }],
["name", { name: "tool" }],
["workspaces", { workspaces: ["pkgs/*"] }],
])("uses only the base's commands when %s changes", (_, change) => {
const pr = { ...baseJson, ...change, dependencies: { a: "1" } };
start(pr);
expect(restoreToolConfigFromBase("main")).toEqual(["package.json"]);
expect(JSON.parse(read("package.json"))).toEqual({
...baseJson,
dependencies: { a: "1" },
});
expect(JSON.parse(read(".claude-pr/package.json"))).toEqual(pr);
});
describe("that .gitattributes converts", () => {
const commitRaw = (attributes: string, stored: string) => {
write(".gitattributes", `package.json ${attributes}\n`);
write("package.json", stored);
const oid = git("hash-object", "-w", "--no-filters", "package.json");
git("add", ".gitattributes");
git("update-index", "--cacheinfo", `100644,${oid},package.json`);
git("commit", "-qm", "pr");
rmSync("package.json");
git("checkout", "--", "package.json");
};
const startFromBase = () => {
write("package.json", JSON.stringify(baseJson));
startPr();
};
test("replaces commands that are only on disk", () => {
startFromBase();
commitRaw(
"ident",
'{"name":"x","a":"$Id:","b":{"c":"$","bin":{"x":"pr.js"},"d":"$Id:"},"e":"$"}',
);
expect(JSON.parse(read("package.json")).bin).toEqual({ x: "pr.js" });
expect(restoreToolConfigFromBase("main")).toEqual(["package.json"]);
expect(JSON.parse(read("package.json")).bin).toEqual(baseJson.bin);
});
test("replaces one that can't be understood", () => {
startFromBase();
commitRaw(
"working-tree-encoding=UTF-16LE-BOM",
JSON.stringify(baseJson),
);
expect(restoreToolConfigFromBase("main")).toEqual(["package.json"]);
expect(JSON.parse(read("package.json"))).toEqual(baseJson);
});
test("replaces commands that aren't on disk", () => {
startFromBase();
commitRaw(
"ident",
'{"name":"x","a":"$Id: ","bin":{"x":"pr.js"},"b":" $"}',
);
expect(JSON.parse(read("package.json")).bin).toBeUndefined();
expect(restoreToolConfigFromBase("main")).toEqual(["package.json"]);
});
test("keeps a step's change to one that the pull request leaves alone", () => {
write(".gitattributes", "* ident\n");
startFromBase();
write("f.txt", "pr\n");
commit("pr");
const changed = JSON.stringify({ ...baseJson, name: "@scope/x" });
write("package.json", changed);
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(read("package.json")).toBe(changed);
});
test("keeps one whose encoding is no conversion", () => {
startFromBase();
const pr = JSON.stringify({ ...baseJson, version: "2.0.0" });
commitRaw("working-tree-encoding=UTF-8", pr);
expect(restoreToolConfigFromBase("main")).toEqual([]);
});
test("keeps what a step changed in one that is not converted", () => {
startFromBase();
write(
"package.json",
JSON.stringify({ ...baseJson, version: "2.0.0" }),
);
commit("pr");
const changed = JSON.stringify({ ...baseJson, name: "@scope/x" });
write("package.json", changed);
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(read("package.json")).toBe(changed);
});
test("keeps one with the same commands", () => {
startFromBase();
const pr = JSON.stringify({ ...baseJson, version: "2.0.0" });
commitRaw("ident", pr);
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(read("package.json")).toBe(pr);
});
});
test("keeps a new name if directories holds no commands", () => {
const directories = { test: "test" };
write("package.json", JSON.stringify({ name: "x", directories }));
startPr();
const pr = JSON.stringify({ name: "y", directories: { test: "t" } });
write("package.json", pr);
commit("pr");
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(read("package.json")).toBe(pr);
});
test.each([[null], ["bin"], [["bin"]], [1]])(
"copes with directories being %p",
(directories) => {
start({ name: "y", directories });
expect(restoreToolConfigFromBase("main")).toEqual([]);
},
);
test("uses the base version when it can't be understood", () => {
start("{");
restoreToolConfigFromBase("main");
expect(JSON.parse(read("package.json"))).toEqual(baseJson);
});
test("understands a byte order mark", () => {
start(`\uFEFF${JSON.stringify({ ...baseJson, version: "2.0.0" })}`);
expect(restoreToolConfigFromBase("main")).toEqual([]);
});
test("looks in subdirectories only if the base branch has workspaces", () => {
const tool = JSON.stringify({ name: "tool", bin: "x.js", version: "1" });
startPr();
write("pkgs/p/package.json", tool);
commit("pr");
expect(restoreToolConfigFromBase("main")).toEqual([]);
git("checkout", "-q", "main");
write("package.json", '{"name":"x","workspaces":["pkgs/*"]}');
commit("base 2");
git("push", "-q", "origin", "main");
git("checkout", "-q", "-b", "pr2");
write("pkgs/p/package.json", tool);
commit("pr2");
expect(restoreToolConfigFromBase("main")).toEqual(["package.json"]);
expect(JSON.parse(read("pkgs/p/package.json"))).toEqual({
name: "tool",
version: "1",
});
expect(JSON.parse(read(".claude-pr/pkgs/p/package.json")).name).toBe(
"tool",
);
});
test("leaves what the base branch's .claude and .husky hold", () => {
const base = '{"name":"hooks","bin":"a.js","scripts":{"check":"base"}}';
write("package.json", '{"name":"x","workspaces":["pkgs/*"]}');
write(".claude/hooks/package.json", base);
write(".husky/package.json", base);
startPr();
for (const dir of [".claude/hooks", ".husky"]) {
write(`${dir}/package.json`, '{"bin":"b.js","scripts":{"check":"pr"}}');
}
commit("pr");
restoreConfigFromBase("main");
expect(restoreToolConfigFromBase("main")).toEqual([]);
expect(read(".claude/hooks/package.json")).toBe(base);
expect(read(".husky/package.json")).toBe(base);
});
test("counts another spelling of a restored directory only if it is that one", () => {
const tool = '{"name":"tool","bin":"x.js"}';
write("package.json", '{"name":"x","workspaces":["*"]}');
write(".husky/package.json", tool);
startPr();
write(".Husky/package.json", tool);
write("claude.md/package.json", tool);
commit("pr");
restoreConfigFromBase("main");
const ownDirectories = readdirSync(".").filter((name) =>
[".Husky", "claude.md"].includes(name),
);
expect(restoreToolConfigFromBase("main")).toEqual(
ownDirectories.length > 0 ? ["package.json"] : [],
);
expect(read(".husky/package.json")).toBe(tool);
for (const dir of ownDirectories) {
expect(JSON.parse(read(`${dir}/package.json`))).toEqual({
name: "tool",
});
}
});
test("reports a restored directory's other spelling that it removes", () => {
write("package.json", '{"name":"x","workspaces":["*"]}');
startPr();
write("claude.md/package.json", "{");
commit("pr");
expect(restoreToolConfigFromBase("main")).toEqual(["package.json"]);
expect(existsSync("claude.md")).toBe(false);
});
test("takes the commands out of a new package.json", () => {
startPr();
write("package.json", '{"name":"x"}');
commit("pr");
expect(restoreToolConfigFromBase("main")).toEqual([]);
write("package.json", '{"name":"x","version":"1","bin":{"t":"a.js"}}');
commit("pr 2");
expect(restoreToolConfigFromBase("main")).toEqual(["package.json"]);
expect(JSON.parse(read("package.json"))).toEqual({
name: "x",
version: "1",
});
});
});
});