mirror of
https://github.com/anthropics/claude-code-action.git
synced 2026-11-22 21:59:37 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
16f9f71ab9 | ||
|
|
8d70a0dd26 | ||
|
|
ae68417a74 | ||
|
|
6b6870e649 | ||
|
|
aa8a7738e4 | ||
|
|
a5a423f75c | ||
|
|
e4a6faad49 | ||
|
|
db77d4d3c9 | ||
|
|
5eb090f3c3 | ||
|
|
f27be6b65a | ||
|
|
374f254f5e | ||
|
|
a26b07d8c7 | ||
|
|
34968b5981 | ||
|
|
1d6de8cb0c | ||
|
|
2dca132ff0 | ||
|
|
38c80c1a32 | ||
|
|
6fed3ca145 | ||
|
|
58985842b8 | ||
|
|
86d88e619d | ||
|
|
6c690188da | ||
|
|
cab360f656 | ||
|
|
ed670b4cf9 | ||
|
|
97c5347339 | ||
|
|
12dd8d74c7 | ||
|
|
a8cb0db4d8 | ||
|
|
fd1c128679 | ||
|
|
8ce9314fa9 | ||
|
|
756cc22e19 | ||
|
|
9171db3e57 | ||
|
|
8cf3482550 | ||
|
|
46a42b4323 | ||
|
|
9ca9355b36 | ||
|
|
cfc3eb22bf | ||
|
|
4036a180cf | ||
|
|
a4f54ef2c5 | ||
|
|
2261fcfc88 | ||
|
|
3b8197d3d4 | ||
|
|
7b0b255830 | ||
|
|
bf38e86e58 | ||
|
|
51db78a4b8 | ||
|
|
9cdae7f0d9 | ||
|
|
56cf60fde4 | ||
|
|
0a8d3c9443 | ||
|
|
19dda84776 | ||
|
|
5ccc3a35a6 | ||
|
|
0d0e0876d3 | ||
|
|
9c5ddab2e6 | ||
|
|
d75b94d5ad | ||
|
|
ef8bb1e43b | ||
|
|
fa2b2666b7 | ||
|
|
8251c103ac | ||
|
|
781d62e9d5 | ||
|
|
833fb0f8c9 | ||
|
|
a874e9ecd7 | ||
|
|
a60f3e1db3 | ||
|
|
e8c2d7c16c | ||
|
|
70fec18385 | ||
|
|
1f291e1cfe | ||
|
|
76ac41a83e | ||
|
|
8ef9699156 | ||
|
|
791545dab1 | ||
|
|
2d7a787fbd | ||
|
|
b58c16b325 | ||
|
|
16b3b310c3 | ||
|
|
6bcfb8263a | ||
|
|
b62c7454dc | ||
|
|
e5ad3c7725 | ||
|
|
c81e3bc69d | ||
|
|
24dcd50c05 | ||
|
|
dcb57747bf | ||
|
|
492d2d78ee | ||
|
|
2ca5fb4027 | ||
|
|
f3f2789f0a | ||
|
|
6a5f1d8e0a | ||
|
|
39ad3c8977 | ||
|
|
3f854a8fb5 | ||
|
|
5ee796a55f | ||
|
|
cff8d3c8f0 | ||
|
|
e2a4b761cd | ||
|
|
65b50df083 | ||
|
|
0a80d21df7 | ||
|
|
54eadc2f72 | ||
|
|
d40ddef4c0 | ||
|
|
459ad358ae | ||
|
|
d721746d68 | ||
|
|
5da4c76dde | ||
|
|
a2cac87e27 | ||
|
|
b49813d0e7 | ||
|
|
9678fce999 | ||
|
|
ed186becce | ||
|
|
05ee4b30d7 |
@@ -0,0 +1,3 @@
|
||||
# Keep the working tree LF on every platform: Prettier defaults to
|
||||
# endOfLine "lf" and several tests match LF-terminated content.
|
||||
* text=auto eol=lf
|
||||
@@ -0,0 +1,29 @@
|
||||
# Hosts that jobs on GitHub's egress-firewall runner (runs-on: ubuntu-24.04-firewall)
|
||||
# may reach. All other hosts are blocked, apart from any that GitHub's firewall allows
|
||||
# by default. Add a host only when a workflow step needs it, name it in full (no '*'), and say what uses it.
|
||||
mode: enforce
|
||||
allow:
|
||||
# Claude API: model requests, trading the workflow's GitHub identity token for a
|
||||
# short-lived API token, and fetching the Claude GitHub App's token in claude.yml and
|
||||
# claude-review.yml
|
||||
- api.anthropic.com
|
||||
# GitHub API: calls made by the Claude Code action, by gh in scripts/gh.sh and
|
||||
# scripts/edit-issue-labels.sh, and by the /review-pr command
|
||||
- api.github.com
|
||||
# Claude Code install script: fetched by the Claude Code action, and by
|
||||
# test-custom-executables.yml ("Install Claude Code manually")
|
||||
- claude.ai
|
||||
# Claude Code binary, downloaded by the install script
|
||||
- downloads.claude.ai
|
||||
# Bun and Node.js release downloads (oven-sh/setup-bun and actions/setup-node)
|
||||
- release-assets.githubusercontent.com
|
||||
# npm packages (bun install in action.yml, base-action/action.yml and
|
||||
# test-mcp-servers.yml)
|
||||
- registry.npmjs.org
|
||||
# Bun install script (test-custom-executables.yml, "Install Bun manually")
|
||||
- bun.sh
|
||||
# apt packages bubblewrap and socat, which the Claude Code action installs when a
|
||||
# workflow admits users without write access (issue-triage.yml)
|
||||
- azure.archive.ubuntu.com
|
||||
- archive.ubuntu.com
|
||||
- security.ubuntu.com
|
||||
Executable
+339
@@ -0,0 +1,339 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Fail if a workflow job that calls Claude, or .github/egress-firewall.yaml, breaks a rule in CLAUDE.md,
|
||||
"Security hardening for GitHub Actions". Run from the repository root. A job calls Claude when it runs the
|
||||
Claude Code action, or when it or a local action it uses mentions ANTHROPIC_FEDERATION_RULE_ID.
|
||||
"""
|
||||
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
FIREWALL_RUNNER = "ubuntu-24.04-firewall"
|
||||
WORKFLOW_DIR = pathlib.Path(".github/workflows")
|
||||
POLICY_PATH = pathlib.Path(".github/egress-firewall.yaml")
|
||||
SIGN_IN_MARKER = "anthropic_federation_rule_id"
|
||||
CLAUDE_ACTIONS = ("anthropics/claude-code-action", "anthropics/claude-code-base-action")
|
||||
HELP = 'See CLAUDE.md, "Security hardening for GitHub Actions".'
|
||||
# Claude Code runs auto mode only on claude-opus-4-6 and newer models. On an older model it
|
||||
# falls back to its default permission mode, with no safety review.
|
||||
AUTO_MODE_MIN_VERSION = (4, 6)
|
||||
# The version in a model name: claude-opus-4-6, claude-sonnet-4-5-20250929, claude-3-5-sonnet-latest.
|
||||
MODEL_VERSION = re.compile(
|
||||
r"claude-(?:(?:opus|sonnet|haiku)-(\d+)(?:-(\d{1,2}))?"
|
||||
r"|(\d+)(?:-(\d{1,2}))?-(?:opus|sonnet|haiku))(?![\d.])"
|
||||
)
|
||||
|
||||
# Key: "<workflow file name>:<job id>". Value: why that job is exempt from the table's rule.
|
||||
EXEMPT_FROM_FIREWALL_RUNNER: dict[str, str] = {}
|
||||
EXEMPT_FROM_AUTO_MODE: dict[str, str] = {}
|
||||
|
||||
|
||||
def stop(message: str):
|
||||
sys.exit(f"::error::{message}")
|
||||
|
||||
|
||||
def load_yaml(path: pathlib.Path):
|
||||
"""Parse a YAML file with PyYAML, or with the yq command if PyYAML is absent."""
|
||||
try:
|
||||
import yaml
|
||||
except ImportError:
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["yq", "-o=json", ".", str(path)], check=True, capture_output=True, text=True
|
||||
)
|
||||
except FileNotFoundError:
|
||||
stop(
|
||||
f"Cannot read {path}: Python has no 'yaml' module and no 'yq' command was found. "
|
||||
"Add a step that runs 'pip install pyyaml' before this check."
|
||||
)
|
||||
except subprocess.CalledProcessError:
|
||||
stop(f"Cannot read {path}: 'yq' could not parse it. Check that the file is valid YAML.")
|
||||
return json.loads(result.stdout)
|
||||
try:
|
||||
with path.open(encoding="utf-8") as handle:
|
||||
return yaml.safe_load(handle)
|
||||
except yaml.YAMLError as error:
|
||||
stop(f"Cannot read {path}: it is not valid YAML ({error}).")
|
||||
|
||||
|
||||
def contains_marker(node) -> bool:
|
||||
"""Whether any key or string under node contains SIGN_IN_MARKER, ignoring case."""
|
||||
if isinstance(node, dict):
|
||||
return any(contains_marker(k) or contains_marker(v) for k, v in node.items())
|
||||
if isinstance(node, list):
|
||||
return any(contains_marker(item) for item in node)
|
||||
return isinstance(node, str) and SIGN_IN_MARKER in node.lower()
|
||||
|
||||
|
||||
def load_local_action(uses: str):
|
||||
"""The parsed action file of a local action (uses: ./path), or None."""
|
||||
if not uses.startswith("./"):
|
||||
return None
|
||||
for name in ("action.yml", "action.yaml"):
|
||||
action_file = pathlib.Path(uses) / name
|
||||
if action_file.is_file():
|
||||
action = load_yaml(action_file)
|
||||
return action if isinstance(action, dict) else {}
|
||||
return None
|
||||
|
||||
|
||||
def steps_of(job: dict) -> list[dict]:
|
||||
return [step for step in job.get("steps") or [] if isinstance(step, dict)]
|
||||
|
||||
|
||||
def runs_claude_code_action(step: dict) -> bool:
|
||||
"""Whether the step runs the Claude Code action: the published action, or a
|
||||
local action that accepts a claude_args input."""
|
||||
uses = str(step.get("uses", ""))
|
||||
if uses.lower().startswith(CLAUDE_ACTIONS):
|
||||
return True
|
||||
action = load_local_action(uses)
|
||||
return action is not None and "claude_args" in (action.get("inputs") or {})
|
||||
|
||||
|
||||
def job_calls_claude(job: dict) -> bool:
|
||||
if contains_marker(job):
|
||||
return True
|
||||
for step in steps_of(job):
|
||||
if runs_claude_code_action(step):
|
||||
return True
|
||||
action = load_local_action(str(step.get("uses", "")))
|
||||
if action is not None and contains_marker(action):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def permission_mode_problem(step: dict, exempt: bool, inherited_env: dict) -> str | None:
|
||||
"""The message for a step whose permission mode is wrong, or None if it is right.
|
||||
|
||||
A step must set auto mode, on a model that supports it. A step of a job in
|
||||
EXEMPT_FROM_AUTO_MODE must set no mode at all. inherited_env is the workflow's and the
|
||||
job's 'env'.
|
||||
"""
|
||||
inputs = step.get("with") or {}
|
||||
lines = str(inputs.get("claude_args", "")).splitlines()
|
||||
text = " ".join(line for line in lines if not line.strip().startswith("#"))
|
||||
try:
|
||||
args = shlex.split(text, comments=True)
|
||||
except ValueError:
|
||||
return "'claude_args' has a quote that is never closed. Close it"
|
||||
modes = []
|
||||
for index, arg in enumerate(args):
|
||||
if arg == "--dangerously-skip-permissions":
|
||||
return (
|
||||
"remove '--dangerously-skip-permissions' from 'claude_args': "
|
||||
"it turns off permission checks"
|
||||
)
|
||||
if arg == "--permission-mode":
|
||||
modes.append(args[index + 1] if index + 1 < len(args) else "")
|
||||
elif arg.startswith("--permission-mode="):
|
||||
modes.append(arg.split("=", 1)[1])
|
||||
if exempt and modes:
|
||||
return (
|
||||
"remove '--permission-mode' from 'claude_args': this job is listed in "
|
||||
"EXEMPT_FROM_AUTO_MODE (.github/scripts/check_workflow_hardening.py), and a job listed "
|
||||
"there must not set a permission mode"
|
||||
)
|
||||
if not modes and not exempt:
|
||||
return "add '--permission-mode auto' to 'claude_args' under the step's 'with:'"
|
||||
for mode in modes:
|
||||
if mode == "":
|
||||
return (
|
||||
"'claude_args' has '--permission-mode' with nothing after it. "
|
||||
"Write '--permission-mode auto'"
|
||||
)
|
||||
if mode != "auto":
|
||||
return (
|
||||
f"'claude_args' has '--permission-mode {mode}'. "
|
||||
"Change it to '--permission-mode auto'"
|
||||
)
|
||||
env = {**inherited_env, **(step.get("env") or {})}
|
||||
models = [
|
||||
("the step's 'model'", inputs.get("model", "")),
|
||||
("ANTHROPIC_MODEL", env.get("ANTHROPIC_MODEL", "")),
|
||||
]
|
||||
models += [
|
||||
(f"'{flag}' in 'claude_args'", value)
|
||||
for flag in ("--model", "--fallback-model")
|
||||
for value in flag_values(args, flag)
|
||||
]
|
||||
settings = [("the step's 'settings'", inputs.get("settings", ""))]
|
||||
settings += [
|
||||
("'--settings' in 'claude_args'", value) for value in flag_values(args, "--settings")
|
||||
]
|
||||
for where, value in settings:
|
||||
text = settings_text(value)
|
||||
if text is None:
|
||||
return (
|
||||
f"{where} names a file outside the repository, which this check cannot read. "
|
||||
"Use inline settings or a file inside the repository"
|
||||
)
|
||||
if "defaultMode" in text:
|
||||
return f"remove 'defaultMode' from {where}: settings must not set a permission mode"
|
||||
try:
|
||||
parsed = json.loads(text) if text else {}
|
||||
except ValueError:
|
||||
parsed = {}
|
||||
if isinstance(parsed, dict) and "model" in parsed:
|
||||
models.append((f"'model' in {where}", parsed["model"]))
|
||||
if not exempt:
|
||||
for where, model in models:
|
||||
if predates_auto_mode(str(model or "")):
|
||||
return (
|
||||
f"{where} is '{model}', which Claude Code does not run in auto mode: it "
|
||||
"falls back to the default permission mode. Use claude-opus-4-6 or a newer model"
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def flag_values(args: list[str], flag: str) -> list[str]:
|
||||
"""The values a flag in claude_args is given, as '--flag value' or '--flag=value'."""
|
||||
values = [
|
||||
args[index + 1] for index, arg in enumerate(args) if arg == flag and index + 1 < len(args)
|
||||
]
|
||||
return values + [arg.split("=", 1)[1] for arg in args if arg.startswith(f"{flag}=")]
|
||||
|
||||
|
||||
def predates_auto_mode(model: str) -> bool:
|
||||
"""Whether the model is older than AUTO_MODE_MIN_VERSION. A name with no version, such as
|
||||
'opus' or 'default', stands for a current model, except 'haiku' (claude-haiku-4-5)."""
|
||||
if model.strip().lower() == "haiku":
|
||||
return True
|
||||
match = MODEL_VERSION.search(model.lower())
|
||||
if not match:
|
||||
return False
|
||||
major, minor = match.group(1, 2) if match.group(1) else match.group(3, 4)
|
||||
return (int(major), int(minor or 0)) < AUTO_MODE_MIN_VERSION
|
||||
|
||||
|
||||
def settings_text(value) -> str | None:
|
||||
"""The settings JSON a 'settings' value stands for: the value itself, or the contents of
|
||||
the file it names when it is a path inside the repository. None when it names a path
|
||||
outside the repository."""
|
||||
text = str(value or "").strip()
|
||||
if not text or text.startswith("{"):
|
||||
return text
|
||||
path = pathlib.Path(text)
|
||||
root = pathlib.Path.cwd().resolve()
|
||||
try:
|
||||
resolved = path.resolve()
|
||||
resolved.relative_to(root)
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
if resolved.is_file():
|
||||
return resolved.read_text(encoding="utf-8", errors="replace")
|
||||
return text
|
||||
|
||||
|
||||
def check_job(file_name: str, job_id: str, job: dict, workflow_env: dict) -> list[str]:
|
||||
key = f"{file_name}:{job_id}"
|
||||
where = f".github/workflows/{file_name}: job '{job_id}'"
|
||||
errors = []
|
||||
runs_on = job.get("runs-on")
|
||||
if isinstance(runs_on, list) and len(runs_on) == 1:
|
||||
runs_on = runs_on[0]
|
||||
if key in EXEMPT_FROM_FIREWALL_RUNNER:
|
||||
print(
|
||||
f"The egress-firewall runner is not required for job '{job_id}' in {file_name}. "
|
||||
f"Reason: {EXEMPT_FROM_FIREWALL_RUNNER[key]}."
|
||||
)
|
||||
elif runs_on != FIREWALL_RUNNER:
|
||||
if "runs-on" not in job:
|
||||
has = "no 'runs-on'"
|
||||
elif isinstance(job["runs-on"], str):
|
||||
has = f"'runs-on: {job['runs-on']}'"
|
||||
else:
|
||||
has = "a 'runs-on' list or group"
|
||||
errors.append(
|
||||
f"{where} calls Claude, so it must have 'runs-on: {FIREWALL_RUNNER}'. "
|
||||
f"It has {has}. {HELP}"
|
||||
)
|
||||
exempt = key in EXEMPT_FROM_AUTO_MODE
|
||||
if exempt:
|
||||
print(
|
||||
f"Auto permission mode is not required for job '{job_id}' in {file_name}. "
|
||||
f"Reason: {EXEMPT_FROM_AUTO_MODE[key]}."
|
||||
)
|
||||
if "defaultMode" in json.dumps(job):
|
||||
# Catches a settings file that an earlier step of the job writes, which the
|
||||
# step-level check cannot read.
|
||||
errors.append(
|
||||
f"{where} mentions 'defaultMode': settings must not set a permission mode. {HELP}"
|
||||
)
|
||||
for index, step in enumerate(steps_of(job), start=1):
|
||||
if not runs_claude_code_action(step):
|
||||
continue
|
||||
inherited_env = {**workflow_env, **(job.get("env") or {})}
|
||||
problem = permission_mode_problem(step, exempt, inherited_env)
|
||||
if problem:
|
||||
step_label = f"step '{step['name']}'" if "name" in step else f"step {index}"
|
||||
errors.append(f"{where}, {step_label}: {problem}. {HELP}")
|
||||
return errors
|
||||
|
||||
|
||||
def check_policy() -> list[str]:
|
||||
if not POLICY_PATH.is_file():
|
||||
return [
|
||||
f"{POLICY_PATH} is missing. Jobs on the egress-firewall runner need it "
|
||||
f"to limit outbound network access. {HELP}"
|
||||
]
|
||||
policy = load_yaml(POLICY_PATH)
|
||||
if not isinstance(policy, dict):
|
||||
return [
|
||||
f"{POLICY_PATH} is empty or is not a set of 'name: value' lines. It needs 'mode: enforce' "
|
||||
f"and an 'allow:' list of hosts. {HELP}"
|
||||
]
|
||||
errors = []
|
||||
if "mode" not in policy:
|
||||
errors.append(f"{POLICY_PATH}: 'mode' is missing. Add 'mode: enforce'. {HELP}")
|
||||
elif policy["mode"] != "enforce":
|
||||
errors.append(
|
||||
f"{POLICY_PATH}: 'mode' is '{policy['mode']}'. It must be 'enforce'. {HELP}"
|
||||
)
|
||||
allow = policy.get("allow")
|
||||
if not isinstance(allow, list) or not allow:
|
||||
errors.append(
|
||||
f"{POLICY_PATH}: the 'allow' list is missing or empty. List under 'allow:' "
|
||||
f"each host the jobs need. {HELP}"
|
||||
)
|
||||
else:
|
||||
for host in allow:
|
||||
if "*" in str(host):
|
||||
errors.append(
|
||||
f"{POLICY_PATH}: the 'allow' entry '{host}' contains '*'. "
|
||||
f"Name each host in full. {HELP}"
|
||||
)
|
||||
return errors
|
||||
|
||||
|
||||
def main() -> int:
|
||||
if not WORKFLOW_DIR.is_dir():
|
||||
stop(f"{WORKFLOW_DIR} not found. Run this check from the repository root.")
|
||||
errors = []
|
||||
checked = 0
|
||||
for path in sorted([*WORKFLOW_DIR.glob("*.yml"), *WORKFLOW_DIR.glob("*.yaml")]):
|
||||
workflow = load_yaml(path)
|
||||
jobs = workflow.get("jobs") if isinstance(workflow, dict) else None
|
||||
for job_id, job in (jobs or {}).items():
|
||||
if not isinstance(job, dict) or not job_calls_claude(job):
|
||||
continue
|
||||
checked += 1
|
||||
errors.extend(check_job(path.name, job_id, job, workflow.get("env") or {}))
|
||||
if checked:
|
||||
errors.extend(check_policy())
|
||||
for error in errors:
|
||||
print(f"::error::{error}")
|
||||
if errors:
|
||||
return 1
|
||||
if checked == 0:
|
||||
print("OK: no workflow job calls Claude, so there was nothing to check.")
|
||||
else:
|
||||
print(f"OK: checked {checked} job(s) that call Claude and found no problems.")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -6,7 +6,11 @@ on:
|
||||
|
||||
jobs:
|
||||
review:
|
||||
runs-on: ubuntu-latest
|
||||
# Skip on fork PRs since they can't mint the OIDC token used for Claude API auth
|
||||
if: github.event.pull_request.head.repo.full_name == github.repository
|
||||
# This job calls Claude, so it runs on GitHub's egress-firewall runner, which
|
||||
# filters the job's outbound network traffic (allow list: .github/egress-firewall.yaml).
|
||||
runs-on: ubuntu-24.04-firewall
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
@@ -28,6 +32,10 @@ jobs:
|
||||
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
|
||||
|
||||
prompt: "/review-pr REPO: ${{ github.repository }} PR_NUMBER: ${{ github.event.pull_request.number }}"
|
||||
# --permission-mode auto: a tool call that needs permission and is outside --allowedTools
|
||||
# below and the allowed-tools list in .claude/commands/review-pr.md runs only if Claude
|
||||
# Code's safety review passes it.
|
||||
claude_args: |
|
||||
--permission-mode auto
|
||||
--allowedTools "mcp__github_inline_comment__create_inline_comment"
|
||||
--model "claude-opus-4-7"
|
||||
|
||||
@@ -17,7 +17,9 @@ jobs:
|
||||
(github.event_name == 'pull_request_review_comment' && contains(github.event.comment.body, '@claude')) ||
|
||||
(github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) ||
|
||||
(github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude')))
|
||||
runs-on: ubuntu-latest
|
||||
# This job calls Claude, so it runs on GitHub's egress-firewall runner, which
|
||||
# filters the job's outbound network traffic (allow list: .github/egress-firewall.yaml).
|
||||
runs-on: ubuntu-24.04-firewall
|
||||
permissions:
|
||||
contents: write
|
||||
pull-requests: write
|
||||
@@ -39,6 +41,10 @@ jobs:
|
||||
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }}
|
||||
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
|
||||
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
|
||||
# --permission-mode auto: a tool call that needs permission and that the allowed tools
|
||||
# do not cover runs only if Claude Code's safety review passes it. The action sets
|
||||
# --permission-mode acceptEdits for @claude mentions, and this one, which comes after it, wins.
|
||||
claude_args: |
|
||||
--allowedTools "Bash(bun install),Bash(bun test:*),Bash(bun run format),Bash(bun typecheck)"
|
||||
--model "claude-opus-4-7"
|
||||
--permission-mode auto
|
||||
|
||||
@@ -6,7 +6,9 @@ on:
|
||||
|
||||
jobs:
|
||||
triage-issue:
|
||||
runs-on: ubuntu-latest
|
||||
# This job calls Claude, so it runs on GitHub's egress-firewall runner, which
|
||||
# filters the job's outbound network traffic (allow list: .github/egress-firewall.yaml).
|
||||
runs-on: ubuntu-24.04-firewall
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -33,5 +35,9 @@ jobs:
|
||||
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }}
|
||||
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
|
||||
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
|
||||
# --permission-mode auto: a tool call that needs permission and is outside the allowed-tools list in
|
||||
# .claude/commands/label-issue.md runs only if Claude Code's safety review passes it. Tools in
|
||||
# --disallowedTools never run. --model is set because Claude Code's default model changes between releases.
|
||||
claude_args: '--model claude-opus-5 --permission-mode auto --disallowedTools "WebFetch,WebSearch,Write,Edit,MultiEdit,NotebookEdit"'
|
||||
allowed_non_write_users: "*" # Required for issue triage workflow, if users without repo write access create issues
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
@@ -17,9 +17,16 @@ permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
# Pin the model so these tests don't depend on the CLI's default model,
|
||||
# which can change with each Claude Code release.
|
||||
env:
|
||||
ANTHROPIC_MODEL: claude-opus-5
|
||||
|
||||
jobs:
|
||||
test-inline-prompt:
|
||||
runs-on: ubuntu-latest
|
||||
# Skip on fork PRs since they can't mint the OIDC token used for Claude API auth
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
runs-on: ubuntu-24.04-firewall
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
@@ -31,7 +38,7 @@ jobs:
|
||||
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }}
|
||||
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
|
||||
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
|
||||
claude_args: '--allowedTools "LS,Read"'
|
||||
claude_args: '--allowedTools "LS,Read" --permission-mode auto'
|
||||
|
||||
- name: Verify inline prompt output
|
||||
run: |
|
||||
@@ -70,7 +77,9 @@ jobs:
|
||||
fi
|
||||
|
||||
test-prompt-file:
|
||||
runs-on: ubuntu-latest
|
||||
# Skip on fork PRs since they can't mint the OIDC token used for Claude API auth
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
runs-on: ubuntu-24.04-firewall
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
@@ -90,7 +99,7 @@ jobs:
|
||||
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }}
|
||||
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
|
||||
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
|
||||
claude_args: '--allowedTools "LS,Read"'
|
||||
claude_args: '--allowedTools "LS,Read" --permission-mode auto'
|
||||
|
||||
- name: Verify prompt file output
|
||||
run: |
|
||||
|
||||
@@ -12,9 +12,16 @@ permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
# Pin the model so these tests don't depend on the CLI's default model,
|
||||
# which can change with each Claude Code release.
|
||||
env:
|
||||
ANTHROPIC_MODEL: claude-opus-5
|
||||
|
||||
jobs:
|
||||
test-custom-executables:
|
||||
runs-on: ubuntu-latest
|
||||
# Skip on fork PRs since they can't mint the OIDC token used for Claude API auth
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
runs-on: ubuntu-24.04-firewall
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
@@ -59,7 +66,7 @@ jobs:
|
||||
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
|
||||
path_to_claude_code_executable: /home/runner/.local/bin/claude
|
||||
path_to_bun_executable: /home/runner/.bun/bin/bun
|
||||
claude_args: '--allowedTools "LS,Read"'
|
||||
claude_args: '--allowedTools "LS,Read" --permission-mode auto'
|
||||
|
||||
- name: Verify custom executables worked
|
||||
run: |
|
||||
|
||||
@@ -12,9 +12,16 @@ permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
# Pin the model so these tests don't depend on the CLI's default model,
|
||||
# which can change with each Claude Code release.
|
||||
env:
|
||||
ANTHROPIC_MODEL: claude-opus-5
|
||||
|
||||
jobs:
|
||||
test-mcp-integration:
|
||||
runs-on: ubuntu-latest
|
||||
# Skip on fork PRs since they can't mint the OIDC token used for Claude API auth
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
runs-on: ubuntu-24.04-firewall
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
@@ -36,7 +43,7 @@ jobs:
|
||||
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }}
|
||||
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
|
||||
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
|
||||
claude_args: --allowedTools mcp__test-server__test_tool
|
||||
claude_args: --allowedTools mcp__test-server__test_tool --permission-mode auto
|
||||
env:
|
||||
# Change to test directory so it finds .mcp.json
|
||||
CLAUDE_WORKING_DIR: ${{ github.workspace }}/base-action/test/mcp-test
|
||||
@@ -94,7 +101,9 @@ jobs:
|
||||
echo "✓ All MCP server checks passed!"
|
||||
|
||||
test-mcp-config-flag:
|
||||
runs-on: ubuntu-latest
|
||||
# Skip on fork PRs since they can't mint the OIDC token used for Claude API auth
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
runs-on: ubuntu-24.04-firewall
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
@@ -129,6 +138,7 @@ jobs:
|
||||
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
|
||||
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
|
||||
claude_args: |
|
||||
--permission-mode auto
|
||||
--allowedTools mcp__test-server__test_tool
|
||||
--mcp-config '{"mcpServers":{"test-server":{"type":"stdio","command":"bun","args":["simple-mcp-server.ts"],"env":{}}}}'
|
||||
env:
|
||||
|
||||
@@ -12,9 +12,16 @@ permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
# Pin the model so these tests don't depend on the CLI's default model,
|
||||
# which can change with each Claude Code release.
|
||||
env:
|
||||
ANTHROPIC_MODEL: claude-opus-5
|
||||
|
||||
jobs:
|
||||
test-settings-inline-allow:
|
||||
runs-on: ubuntu-latest
|
||||
# Skip on fork PRs since they can't mint the OIDC token used for Claude API auth
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
runs-on: ubuntu-24.04-firewall
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
@@ -27,6 +34,7 @@ jobs:
|
||||
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }}
|
||||
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
|
||||
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
|
||||
claude_args: "--permission-mode auto"
|
||||
settings: |
|
||||
{
|
||||
"permissions": {
|
||||
@@ -65,7 +73,9 @@ jobs:
|
||||
fi
|
||||
|
||||
test-settings-inline-deny:
|
||||
runs-on: ubuntu-latest
|
||||
# Skip on fork PRs since they can't mint the OIDC token used for Claude API auth
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
runs-on: ubuntu-24.04-firewall
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
@@ -78,6 +88,7 @@ jobs:
|
||||
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }}
|
||||
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
|
||||
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
|
||||
claude_args: "--permission-mode auto"
|
||||
settings: |
|
||||
{
|
||||
"permissions": {
|
||||
@@ -99,7 +110,9 @@ jobs:
|
||||
fi
|
||||
|
||||
test-settings-file-allow:
|
||||
runs-on: ubuntu-latest
|
||||
# Skip on fork PRs since they can't mint the OIDC token used for Claude API auth
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
runs-on: ubuntu-24.04-firewall
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
@@ -122,6 +135,7 @@ jobs:
|
||||
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }}
|
||||
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
|
||||
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
|
||||
claude_args: "--permission-mode auto"
|
||||
settings: "test-settings.json"
|
||||
|
||||
- name: Verify echo worked
|
||||
@@ -155,7 +169,9 @@ jobs:
|
||||
fi
|
||||
|
||||
test-settings-file-deny:
|
||||
runs-on: ubuntu-latest
|
||||
# Skip on fork PRs since they can't mint the OIDC token used for Claude API auth
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
runs-on: ubuntu-24.04-firewall
|
||||
steps:
|
||||
- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
@@ -178,6 +194,7 @@ jobs:
|
||||
anthropic_federation_rule_id: ${{ vars.ANTHROPIC_FEDERATION_RULE_ID }}
|
||||
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
|
||||
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
|
||||
claude_args: "--permission-mode auto"
|
||||
settings: "test-settings.json"
|
||||
|
||||
- name: Verify echo was denied
|
||||
|
||||
@@ -12,10 +12,17 @@ permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
# Pin the model so these tests don't depend on the CLI's default model,
|
||||
# which can change with each Claude Code release.
|
||||
env:
|
||||
ANTHROPIC_MODEL: claude-opus-5
|
||||
|
||||
jobs:
|
||||
test-basic-types:
|
||||
name: Test Basic Type Conversions
|
||||
runs-on: ubuntu-latest
|
||||
# Skip on fork PRs since they can't mint the OIDC token used for Claude API auth
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
runs-on: ubuntu-24.04-firewall
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
@@ -36,6 +43,7 @@ jobs:
|
||||
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
|
||||
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
|
||||
claude_args: |
|
||||
--permission-mode auto
|
||||
--allowedTools Bash
|
||||
--json-schema '{"type":"object","properties":{"text_field":{"type":"string"},"number_field":{"type":"number"},"boolean_true":{"type":"boolean"},"boolean_false":{"type":"boolean"}},"required":["text_field","number_field","boolean_true","boolean_false"]}'
|
||||
|
||||
@@ -76,7 +84,9 @@ jobs:
|
||||
|
||||
test-complex-types:
|
||||
name: Test Arrays and Objects
|
||||
runs-on: ubuntu-latest
|
||||
# Skip on fork PRs since they can't mint the OIDC token used for Claude API auth
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
runs-on: ubuntu-24.04-firewall
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
@@ -96,6 +106,7 @@ jobs:
|
||||
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
|
||||
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
|
||||
claude_args: |
|
||||
--permission-mode auto
|
||||
--allowedTools Bash
|
||||
--json-schema '{"type":"object","properties":{"items":{"type":"array","items":{"type":"string"}},"config":{"type":"object"},"empty_array":{"type":"array"}},"required":["items","config","empty_array"]}'
|
||||
|
||||
@@ -129,7 +140,9 @@ jobs:
|
||||
|
||||
test-edge-cases:
|
||||
name: Test Edge Cases
|
||||
runs-on: ubuntu-latest
|
||||
# Skip on fork PRs since they can't mint the OIDC token used for Claude API auth
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
runs-on: ubuntu-24.04-firewall
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
@@ -150,6 +163,7 @@ jobs:
|
||||
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
|
||||
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
|
||||
claude_args: |
|
||||
--permission-mode auto
|
||||
--allowedTools Bash
|
||||
--json-schema '{"type":"object","properties":{"zero":{"type":"number"},"empty_string":{"type":"string"},"negative":{"type":"number"},"decimal":{"type":"number"}},"required":["zero","empty_string","negative","decimal"]}'
|
||||
|
||||
@@ -190,7 +204,9 @@ jobs:
|
||||
|
||||
test-name-sanitization:
|
||||
name: Test Output Name Sanitization
|
||||
runs-on: ubuntu-latest
|
||||
# Skip on fork PRs since they can't mint the OIDC token used for Claude API auth
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
runs-on: ubuntu-24.04-firewall
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
@@ -206,6 +222,7 @@ jobs:
|
||||
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
|
||||
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
|
||||
claude_args: |
|
||||
--permission-mode auto
|
||||
--allowedTools Bash
|
||||
--json-schema '{"type":"object","properties":{"test-result":{"type":"string"},"item_count":{"type":"number"}},"required":["test-result","item_count"]}'
|
||||
|
||||
@@ -232,7 +249,9 @@ jobs:
|
||||
|
||||
test-execution-file-structure:
|
||||
name: Test Execution File Format
|
||||
runs-on: ubuntu-latest
|
||||
# Skip on fork PRs since they can't mint the OIDC token used for Claude API auth
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
runs-on: ubuntu-24.04-firewall
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
@@ -246,6 +265,7 @@ jobs:
|
||||
anthropic_organization_id: ${{ vars.ANTHROPIC_ORGANIZATION_ID }}
|
||||
anthropic_service_account_id: ${{ vars.ANTHROPIC_SERVICE_ACCOUNT_ID }}
|
||||
claude_args: |
|
||||
--permission-mode auto
|
||||
--allowedTools Bash
|
||||
--json-schema '{"type":"object","properties":{"done":{"type":"boolean"}},"required":["done"]}'
|
||||
|
||||
@@ -284,7 +304,7 @@ jobs:
|
||||
- test-edge-cases
|
||||
- test-name-sanitization
|
||||
- test-execution-file-structure
|
||||
if: always()
|
||||
if: ${{ always() && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) }}
|
||||
steps:
|
||||
- name: Generate Summary
|
||||
run: |
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
# Fails when a workflow job that calls Claude lacks its security settings.
|
||||
# The rules are in CLAUDE.md, "Security hardening for GitHub Actions".
|
||||
name: Security check for workflows that call Claude
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
workflow-hardening:
|
||||
name: Check security settings
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 5
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
|
||||
- name: Check security settings of workflows that call Claude
|
||||
run: python3 .github/scripts/check_workflow_hardening.py
|
||||
@@ -42,3 +42,17 @@ Single entrypoint: `src/entrypoints/run.ts` orchestrates everything — prepare
|
||||
- `moduleResolution: "bundler"` — imports don't need `.js` extensions.
|
||||
- GitHub API calls should use retry logic (`src/utils/retry.ts`).
|
||||
- MCP servers are auto-installed at runtime to `~/.claude/mcp/github-{type}-server/`.
|
||||
|
||||
## Security hardening for GitHub Actions
|
||||
|
||||
Workflow jobs in this repository that call Claude run with three protections. Keep them when you add or edit a workflow.
|
||||
|
||||
1. **Egress-firewall runner.** The job has `runs-on: ubuntu-24.04-firewall`, a GitHub-hosted runner that filters the job's outbound network traffic. Do not move a job that calls Claude to another runner.
|
||||
2. **Network allow list.** `.github/egress-firewall.yaml` lists the hosts those jobs may reach, besides any that GitHub's firewall allows by default. Keep `mode: enforce`, which is what makes the firewall block the rest. Follow that file's header when you add a host.
|
||||
3. **Auto permission mode.** Every step that runs the Claude Code action (`uses: anthropics/claude-code-action`, or this repository's own `./` and `./base-action`) passes `--permission-mode auto` in `claude_args`. A tool call that needs permission and that the allowed tools do not cover then runs only if Claude Code's safety review passes it. Allow only the tools the job needs, and keep any `--disallowedTools` list a step has. Use `claude-opus-4-6` or a newer model: on an older one Claude Code falls back to its default permission mode.
|
||||
|
||||
`claude.yml` answers `@claude` mentions. The Claude Code action sets `--permission-mode acceptEdits` for those, and the `--permission-mode auto` in the workflow's `claude_args`, which comes after it, replaces it.
|
||||
|
||||
`.github/workflows/workflow-hardening.yml` fails when a job that runs the Claude Code action or mentions `ANTHROPIC_FEDERATION_RULE_ID` breaks protection 1 or 3, or when the allow list is missing, empty, not `mode: enforce`, or names a host with `*`. It cannot see a job that calls Claude another way, so check new workflows by hand too. If a job cannot meet protection 1 or 3, add it with the reason to the matching exemption table in `.github/scripts/check_workflow_hardening.py`. A job in `EXEMPT_FROM_AUTO_MODE` must set no permission mode at all. Do not skip or weaken the check.
|
||||
|
||||
Keep each workflow's `permissions:` block minimal, and never print tokens or environment variables in workflow logs.
|
||||
|
||||
@@ -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.233"
|
||||
CLAUDE_CODE_VERSION="2.1.310"
|
||||
echo "Installing Claude Code v${CLAUDE_CODE_VERSION}..."
|
||||
for attempt in 1 2 3; do
|
||||
echo "Installation attempt $attempt..."
|
||||
@@ -165,6 +165,8 @@ runs:
|
||||
sleep 5
|
||||
done
|
||||
echo "Claude Code installed successfully"
|
||||
# Add ~/.local/bin to PATH so the claude executable is available in subsequent steps
|
||||
echo "$HOME/.local/bin" >> "$GITHUB_PATH"
|
||||
else
|
||||
echo "Using custom Claude Code executable: $PATH_TO_CLAUDE_CODE_EXECUTABLE"
|
||||
# Add the directory containing the custom executable to PATH
|
||||
|
||||
+16
-14
@@ -6,8 +6,8 @@
|
||||
"name": "@anthropic-ai/claude-code-base-action",
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.233",
|
||||
"shell-quote": "^1.8.3",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.310",
|
||||
"shell-quote": "^1.8.4",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "^1.2.12",
|
||||
@@ -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].233", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.233", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.233", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.233", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.233", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.233", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.233", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.233", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.233" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-Dy+YqhggwtbezDy3Ap2pb1sK3bOqnI+sLNnsVjB3AUWvR0QlGnjjrjORXY03Y50I+B1eFRNEcYPAZKRYlCkSLQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected].310", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.310", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.310", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.310", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.310", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.310", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.310", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.310", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.310" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-fo+sr+9Ks73P001f6XKRQlyzfIBAJMgXArLUkH5Tu98NikRDZeGtFQVj23d5/hj2ijpFgzffrr4fHywY9qUkoQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected].233", "", { "os": "darwin", "cpu": "arm64" }, "sha512-4WDiBZgcrmvTDJjS8RNZwoxGgMz/0EpOM+sYa6EtyjwHTd6It1H/+k5zBckCmBajbgS5/ASCJqdwZzi7dwBl0Q=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected].310", "", { "os": "darwin", "cpu": "arm64" }, "sha512-gpzMjDZdcdA2Webuqm9j76exG8yNK/755ZYWbS3MM4vVBlAsm+enEO+hhNt0Mx1VMil28RWetvTO4ZJ3YODVMA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected].233", "", { "os": "darwin", "cpu": "x64" }, "sha512-RaaEfNrbqSh77H5NdVF9cJQ0xhAUO92aOv71LSKSdAYModMeUvJN0k22Q7gvmx0TlmqJ+aVyCG8J8gVfgSL9mg=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected].310", "", { "os": "darwin", "cpu": "x64" }, "sha512-ZRQ4ZrzE2OOfR+Fx8h+CM4NKh0UiYqlh5TowP7HUhn5KUoYMjoSR/xIhix8ow42X2IDiBy0FjEVaA/Awhu2KAw=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected].233", "", { "os": "linux", "cpu": "arm64" }, "sha512-Az9HjQthYQqRjJCacBtDIAHX3TRGK9WlACNb/UOGAK3JndNzZMprM2mK/t6YmP2cRLJsGyorxL7HZmR9R9HYaw=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected].310", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-l6SPgUmJknjx+6/Pb7OR353fm3xBNAWqodFoC/Cflg0yMcLfz9iwNIc3Drgos2DqfHnid+ODqDzSO93AgQ7RmA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected].233", "", { "os": "linux", "cpu": "arm64" }, "sha512-Z3uZdzt6xgJ3f4NIgO6lzBYSELULKSq6AL4OsNLBzuaEpVW0iYs1kUCaD9rcMlMrf3cV+Dk/GA/lTCGMgbucjQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected].310", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-viXuvvtli3pfHzTEI+oeJzk3nldkfHvj757Xh/uAeximUT9ANZIq4SMZw2cSqbhASjni0qcO6B1x4BGx2LuQpw=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected].233", "", { "os": "linux", "cpu": "x64" }, "sha512-jpbhV+n9PnxLiyheQ/HjtHIg/E5/jVsk2Vdu132BSoL/3bsObSmMqKgsqoMutzwRZvtpqRs2RPVcjsC8G4A9Zw=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected].310", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-jx7awHPoofXuE6cRRQSzLUFyW6aUXbYD9AtnNIDUHmmPPrgJ9nSnqjPaqcNhOdaZH7onUUujEAq26N2tx29fYg=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected].233", "", { "os": "linux", "cpu": "x64" }, "sha512-kYBIAQCu2f1YITcGbpUN2jfrkAzs59TVAragAhE2z+GrkIcxcpZwmaRY6heMBtaSY8SuyrwgqbCW9hJALYFnEg=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected].310", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-/qFgN5LcofB8PayxBXoa+xDxkYPPQeo/eCyN0DsyyeI67ifH/l49pz9J+sH0+ctDe9und0vMCJPzng70bx2K+Q=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected].233", "", { "os": "win32", "cpu": "arm64" }, "sha512-aO2MaNdmQofyPLKszE4s+Ope/sLJPeI/ZlGdCcjYp7qhji2hgZ4bRWWsOrx5eKjz0gFK5CFFltILkFcNcxCsVg=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected].310", "", { "os": "win32", "cpu": "arm64" }, "sha512-tRmDMhZpoWAIrZxFBTh6vyZB8W5gldU5/Rfo+cyq/OvBKTxxbim+/0tIa9QlJQncoVLXVN9eySYeeB9KMjio7w=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected].233", "", { "os": "win32", "cpu": "x64" }, "sha512-TcAYyWPXS5mREZGUksuCZsLIRQjbo/Vriur2PqIhAmgZ1oiqBZO27a90sX60EUczD7yV8wpwOVhVLhUxO0kAEg=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected].310", "", { "os": "win32", "cpu": "x64" }, "sha512-zvrIApxPccTJc6gCOtw5hj27QjWhhTi3z5x5iMmf9f0LZAKR+9mrgENVeFL7PP7zRGdYVhhX2SahbzxN83L/eA=="],
|
||||
|
||||
"@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=="],
|
||||
|
||||
@@ -223,7 +223,7 @@
|
||||
|
||||
"shebang-regex": ["[email protected]", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],
|
||||
|
||||
"shell-quote": ["[email protected].3", "", {}, "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw=="],
|
||||
"shell-quote": ["[email protected].4", "", {}, "sha512-VsC6n6vz1ihYYyZZwX7YZSF5l5x36ca17OC+a69h94YqB7X6XLwf+5MOgynYir2SLFUbl8gIYvBo8K8RoNQ6bQ=="],
|
||||
|
||||
"side-channel": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.3", "side-channel-list": "^1.0.0", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" } }, "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw=="],
|
||||
|
||||
@@ -257,8 +257,10 @@
|
||||
|
||||
"wrappy": ["[email protected]", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
|
||||
|
||||
"zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
|
||||
"zod": ["zod@4.6.7", "", {}, "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="],
|
||||
|
||||
"zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],
|
||||
"@modelcontextprotocol/sdk/zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
|
||||
|
||||
"@modelcontextprotocol/sdk/zod-to-json-schema": ["[email protected]", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+4
-4
@@ -9,7 +9,7 @@
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"shell-quote": "^1.8.3"
|
||||
"shell-quote": "^1.8.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "^1.2.12",
|
||||
@@ -139,9 +139,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/shell-quote": {
|
||||
"version": "1.8.3",
|
||||
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.3.tgz",
|
||||
"integrity": "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw==",
|
||||
"version": "1.8.4",
|
||||
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.4.tgz",
|
||||
"integrity": "sha512-VsC6n6vz1ihYYyZZwX7YZSF5l5x36ca17OC+a69h94YqB7X6XLwf+5MOgynYir2SLFUbl8gIYvBo8K8RoNQ6bQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 0.4"
|
||||
|
||||
@@ -11,8 +11,8 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.233",
|
||||
"shell-quote": "^1.8.3"
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.310",
|
||||
"shell-quote": "^1.8.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/bun": "^1.2.12",
|
||||
|
||||
@@ -289,6 +289,10 @@ export function parseSdkOptions(options: ClaudeOptions): ParsedSdkOptions {
|
||||
delete env.ACTIONS_ID_TOKEN_REQUEST_URL;
|
||||
delete env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;
|
||||
|
||||
// Remove ALL_INPUTS as it is only needed during initial setup to determine
|
||||
// input presence (collectActionInputsPresence) and contains serialized workflow inputs.
|
||||
delete env.ALL_INPUTS;
|
||||
|
||||
// Build system prompt option - default to claude_code preset
|
||||
let systemPrompt: SdkOptions["systemPrompt"];
|
||||
if (options.systemPrompt) {
|
||||
|
||||
@@ -82,6 +82,35 @@ async function createPromptConfig(
|
||||
return createMultiBlockMessage();
|
||||
}
|
||||
|
||||
type ModelUsageSummary = Record<
|
||||
string,
|
||||
{
|
||||
contextWindow: number;
|
||||
maxOutputTokens: number;
|
||||
}
|
||||
>;
|
||||
|
||||
/**
|
||||
* Keep resolved model limits visible without exposing token usage or cost details.
|
||||
*/
|
||||
function sanitizeModelUsage(
|
||||
modelUsage: SDKResultMessage["modelUsage"] | undefined,
|
||||
): ModelUsageSummary | undefined {
|
||||
if (!modelUsage) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return Object.fromEntries(
|
||||
Object.entries(modelUsage).map(([model, usage]) => [
|
||||
model,
|
||||
{
|
||||
contextWindow: usage.contextWindow,
|
||||
maxOutputTokens: usage.maxOutputTokens,
|
||||
},
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitizes SDK output to match CLI sanitization behavior
|
||||
*/
|
||||
@@ -119,6 +148,7 @@ function sanitizeSdkOutput(
|
||||
num_turns: resultMsg.num_turns,
|
||||
total_cost_usd: resultMsg.total_cost_usd,
|
||||
permission_denials_count: resultMsg.permission_denials?.length ?? 0,
|
||||
modelUsage: sanitizeModelUsage(resultMsg.modelUsage),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
|
||||
@@ -620,5 +620,22 @@ describe("parseSdkOptions", () => {
|
||||
process.env = originalEnv;
|
||||
}
|
||||
});
|
||||
|
||||
test("should strip ALL_INPUTS from env", () => {
|
||||
const originalEnv = { ...process.env };
|
||||
process.env.ALL_INPUTS = JSON.stringify({
|
||||
anthropic_api_key: "sk-ant-test-key",
|
||||
github_token: "ghp_test_token",
|
||||
});
|
||||
|
||||
try {
|
||||
const options: ClaudeOptions = {};
|
||||
const result = parseSdkOptions(options);
|
||||
|
||||
expect(result.sdkOptions.env?.ALL_INPUTS).toBeUndefined();
|
||||
} finally {
|
||||
process.env = originalEnv;
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -64,6 +64,95 @@ describe("runClaudeWithSdk", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("logs resolved model limits without exposing token usage", async () => {
|
||||
const consoleLogSpy = spyOn(console, "log").mockImplementation(() => {});
|
||||
|
||||
tempDir = await mkdtemp(join(tmpdir(), "claude-sdk-"));
|
||||
process.env.RUNNER_TEMP = tempDir;
|
||||
|
||||
const promptPath = join(tempDir, "prompt.txt");
|
||||
await writeFile(promptPath, "test prompt");
|
||||
|
||||
const initMessage = {
|
||||
type: "system",
|
||||
subtype: "init",
|
||||
session_id: "session-123",
|
||||
model: "claude-opus-5",
|
||||
};
|
||||
|
||||
const resultMessage = {
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
duration_ms: 434,
|
||||
num_turns: 1,
|
||||
total_cost_usd: 1.23,
|
||||
permission_denials: [],
|
||||
modelUsage: {
|
||||
"claude-opus-5": {
|
||||
inputTokens: 96209,
|
||||
outputTokens: 55324,
|
||||
cacheReadInputTokens: 1135701,
|
||||
cacheCreationInputTokens: 149043,
|
||||
webSearchRequests: 0,
|
||||
costUSD: 1.23,
|
||||
contextWindow: 200000,
|
||||
maxOutputTokens: 64000,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
mock.module("@anthropic-ai/claude-agent-sdk", () => ({
|
||||
query: async function* () {
|
||||
yield initMessage;
|
||||
yield resultMessage;
|
||||
},
|
||||
}));
|
||||
|
||||
try {
|
||||
const { runClaudeWithSdk } = await import("../src/run-claude-sdk");
|
||||
|
||||
await expect(
|
||||
runClaudeWithSdk(promptPath, {
|
||||
sdkOptions: {},
|
||||
showFullOutput: false,
|
||||
hasJsonSchema: false,
|
||||
}),
|
||||
).resolves.toMatchObject({ conclusion: "success" });
|
||||
|
||||
const sanitizedResult = consoleLogSpy.mock.calls
|
||||
.map(([message]) => message)
|
||||
.find(
|
||||
(message) =>
|
||||
typeof message === "string" && message.includes('"type": "result"'),
|
||||
);
|
||||
|
||||
expect(sanitizedResult).toBeDefined();
|
||||
if (typeof sanitizedResult !== "string") {
|
||||
throw new Error("Sanitized result output was not logged");
|
||||
}
|
||||
expect(JSON.parse(sanitizedResult)).toEqual({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
duration_ms: 434,
|
||||
num_turns: 1,
|
||||
total_cost_usd: 1.23,
|
||||
permission_denials_count: 0,
|
||||
modelUsage: {
|
||||
"claude-opus-5": {
|
||||
contextWindow: 200000,
|
||||
maxOutputTokens: 64000,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(sanitizedResult).not.toContain("inputTokens");
|
||||
expect(sanitizedResult).not.toContain("costUSD");
|
||||
} finally {
|
||||
consoleLogSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
test("fails when result subtype is success but is_error is true", async () => {
|
||||
const consoleErrorSpy = spyOn(console, "error").mockImplementation(
|
||||
() => {},
|
||||
|
||||
@@ -7,13 +7,13 @@
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"@actions/github": "^6.0.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.233",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.310",
|
||||
"@modelcontextprotocol/sdk": "^1.11.0",
|
||||
"@octokit/graphql": "^8.2.2",
|
||||
"@octokit/rest": "^21.1.1",
|
||||
"@octokit/webhooks-types": "^7.6.1",
|
||||
"node-fetch": "^3.3.2",
|
||||
"shell-quote": "^1.8.3",
|
||||
"shell-quote": "^1.8.4",
|
||||
"zod": "^3.24.4",
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -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].233", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.233", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.233", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.233", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.233", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.233", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.233", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.233", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.233" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-Dy+YqhggwtbezDy3Ap2pb1sK3bOqnI+sLNnsVjB3AUWvR0QlGnjjrjORXY03Y50I+B1eFRNEcYPAZKRYlCkSLQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected].310", "", { "optionalDependencies": { "@anthropic-ai/claude-agent-sdk-darwin-arm64": "0.3.310", "@anthropic-ai/claude-agent-sdk-darwin-x64": "0.3.310", "@anthropic-ai/claude-agent-sdk-linux-arm64": "0.3.310", "@anthropic-ai/claude-agent-sdk-linux-arm64-musl": "0.3.310", "@anthropic-ai/claude-agent-sdk-linux-x64": "0.3.310", "@anthropic-ai/claude-agent-sdk-linux-x64-musl": "0.3.310", "@anthropic-ai/claude-agent-sdk-win32-arm64": "0.3.310", "@anthropic-ai/claude-agent-sdk-win32-x64": "0.3.310" }, "peerDependencies": { "@anthropic-ai/sdk": ">=0.93.0", "@modelcontextprotocol/sdk": "^1.29.0", "zod": "^4.0.0" } }, "sha512-fo+sr+9Ks73P001f6XKRQlyzfIBAJMgXArLUkH5Tu98NikRDZeGtFQVj23d5/hj2ijpFgzffrr4fHywY9qUkoQ=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected].233", "", { "os": "darwin", "cpu": "arm64" }, "sha512-4WDiBZgcrmvTDJjS8RNZwoxGgMz/0EpOM+sYa6EtyjwHTd6It1H/+k5zBckCmBajbgS5/ASCJqdwZzi7dwBl0Q=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-arm64": ["@anthropic-ai/[email protected].310", "", { "os": "darwin", "cpu": "arm64" }, "sha512-gpzMjDZdcdA2Webuqm9j76exG8yNK/755ZYWbS3MM4vVBlAsm+enEO+hhNt0Mx1VMil28RWetvTO4ZJ3YODVMA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected].233", "", { "os": "darwin", "cpu": "x64" }, "sha512-RaaEfNrbqSh77H5NdVF9cJQ0xhAUO92aOv71LSKSdAYModMeUvJN0k22Q7gvmx0TlmqJ+aVyCG8J8gVfgSL9mg=="],
|
||||
"@anthropic-ai/claude-agent-sdk-darwin-x64": ["@anthropic-ai/[email protected].310", "", { "os": "darwin", "cpu": "x64" }, "sha512-ZRQ4ZrzE2OOfR+Fx8h+CM4NKh0UiYqlh5TowP7HUhn5KUoYMjoSR/xIhix8ow42X2IDiBy0FjEVaA/Awhu2KAw=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected].233", "", { "os": "linux", "cpu": "arm64" }, "sha512-Az9HjQthYQqRjJCacBtDIAHX3TRGK9WlACNb/UOGAK3JndNzZMprM2mK/t6YmP2cRLJsGyorxL7HZmR9R9HYaw=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64": ["@anthropic-ai/[email protected].310", "", { "os": "linux", "cpu": "arm64", "libc": "glibc" }, "sha512-l6SPgUmJknjx+6/Pb7OR353fm3xBNAWqodFoC/Cflg0yMcLfz9iwNIc3Drgos2DqfHnid+ODqDzSO93AgQ7RmA=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected].233", "", { "os": "linux", "cpu": "arm64" }, "sha512-Z3uZdzt6xgJ3f4NIgO6lzBYSELULKSq6AL4OsNLBzuaEpVW0iYs1kUCaD9rcMlMrf3cV+Dk/GA/lTCGMgbucjQ=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-arm64-musl": ["@anthropic-ai/[email protected].310", "", { "os": "linux", "cpu": "arm64", "libc": "musl" }, "sha512-viXuvvtli3pfHzTEI+oeJzk3nldkfHvj757Xh/uAeximUT9ANZIq4SMZw2cSqbhASjni0qcO6B1x4BGx2LuQpw=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected].233", "", { "os": "linux", "cpu": "x64" }, "sha512-jpbhV+n9PnxLiyheQ/HjtHIg/E5/jVsk2Vdu132BSoL/3bsObSmMqKgsqoMutzwRZvtpqRs2RPVcjsC8G4A9Zw=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64": ["@anthropic-ai/[email protected].310", "", { "os": "linux", "cpu": "x64", "libc": "glibc" }, "sha512-jx7awHPoofXuE6cRRQSzLUFyW6aUXbYD9AtnNIDUHmmPPrgJ9nSnqjPaqcNhOdaZH7onUUujEAq26N2tx29fYg=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected].233", "", { "os": "linux", "cpu": "x64" }, "sha512-kYBIAQCu2f1YITcGbpUN2jfrkAzs59TVAragAhE2z+GrkIcxcpZwmaRY6heMBtaSY8SuyrwgqbCW9hJALYFnEg=="],
|
||||
"@anthropic-ai/claude-agent-sdk-linux-x64-musl": ["@anthropic-ai/[email protected].310", "", { "os": "linux", "cpu": "x64", "libc": "musl" }, "sha512-/qFgN5LcofB8PayxBXoa+xDxkYPPQeo/eCyN0DsyyeI67ifH/l49pz9J+sH0+ctDe9und0vMCJPzng70bx2K+Q=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected].233", "", { "os": "win32", "cpu": "arm64" }, "sha512-aO2MaNdmQofyPLKszE4s+Ope/sLJPeI/ZlGdCcjYp7qhji2hgZ4bRWWsOrx5eKjz0gFK5CFFltILkFcNcxCsVg=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-arm64": ["@anthropic-ai/[email protected].310", "", { "os": "win32", "cpu": "arm64" }, "sha512-tRmDMhZpoWAIrZxFBTh6vyZB8W5gldU5/Rfo+cyq/OvBKTxxbim+/0tIa9QlJQncoVLXVN9eySYeeB9KMjio7w=="],
|
||||
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected].233", "", { "os": "win32", "cpu": "x64" }, "sha512-TcAYyWPXS5mREZGUksuCZsLIRQjbo/Vriur2PqIhAmgZ1oiqBZO27a90sX60EUczD7yV8wpwOVhVLhUxO0kAEg=="],
|
||||
"@anthropic-ai/claude-agent-sdk-win32-x64": ["@anthropic-ai/[email protected].310", "", { "os": "win32", "cpu": "x64" }, "sha512-zvrIApxPccTJc6gCOtw5hj27QjWhhTi3z5x5iMmf9f0LZAKR+9mrgENVeFL7PP7zRGdYVhhX2SahbzxN83L/eA=="],
|
||||
|
||||
"@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=="],
|
||||
|
||||
@@ -75,8 +75,6 @@
|
||||
|
||||
"@octokit/plugin-paginate-rest": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/types": "^12.6.0" }, "peerDependencies": { "@octokit/core": "5" } }, "sha512-u3KYkGF7GcZnSD/3UP0S7K5XUFT2FkOQdcfXZGZQPGv3lm4F2Xbf71lvjldr8c1H3nNbF+33cLEkWYbokGWqiQ=="],
|
||||
|
||||
"@octokit/plugin-request-log": ["@octokit/[email protected]", "", { "peerDependencies": { "@octokit/core": ">=6" } }, "sha512-n/lNeCtq+9ofhC15xzmJCNKP2BWTv8Ih2TTy+jatNCCq/gQP/V7rK3fjIfuz0pDWDALO/o/4QY4hyOF6TQQFUw=="],
|
||||
|
||||
"@octokit/plugin-rest-endpoint-methods": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/types": "^12.6.0" }, "peerDependencies": { "@octokit/core": "5" } }, "sha512-xV1b+ceKV9KytQe3zCVqjg+8GTGfDYwaT1ATU5isiUyVtlVAO3HNdzpS4sr4GBx4hxQ46s7ITtZrAsxG22+rVg=="],
|
||||
|
||||
"@octokit/request": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/endpoint": "^9.0.6", "@octokit/request-error": "^5.1.1", "@octokit/types": "^13.1.0", "universal-user-agent": "^6.0.0" } }, "sha512-qnB2+SY3hkCmBxZsR/MPCybNmbJe4KAlfWErXq+rBKkQJlbjdJeS85VI9r8UqeLYLvnAenU8Q1okM/0MBsAGXw=="],
|
||||
@@ -275,7 +273,7 @@
|
||||
|
||||
"shebang-regex": ["[email protected]", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],
|
||||
|
||||
"shell-quote": ["[email protected].3", "", {}, "sha512-ObmnIF4hXNg1BqhnHmgbDETF8dLPCggZWBjkQfhZpbszZnYur5DUljTcCHii5LC3J5E0yeO/1LIMyH+UvHQgyw=="],
|
||||
"shell-quote": ["[email protected].4", "", {}, "sha512-VsC6n6vz1ihYYyZZwX7YZSF5l5x36ca17OC+a69h94YqB7X6XLwf+5MOgynYir2SLFUbl8gIYvBo8K8RoNQ6bQ=="],
|
||||
|
||||
"side-channel": ["[email protected]", "", { "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.3", "side-channel-list": "^1.0.0", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" } }, "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw=="],
|
||||
|
||||
@@ -333,8 +331,6 @@
|
||||
|
||||
"@octokit/plugin-paginate-rest/@octokit/types": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/openapi-types": "^20.0.0" } }, "sha512-1rhSOfRa6H9w4YwK0yrf5faDaDTb+yLyBUKOCV4xtCDB5VmIPqd/v9yr9o6SAzOAlRxMiRiCic6JVM1/kunVkw=="],
|
||||
|
||||
"@octokit/plugin-request-log/@octokit/core": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/auth-token": "^5.0.0", "@octokit/graphql": "^8.2.2", "@octokit/request": "^9.2.3", "@octokit/request-error": "^6.1.8", "@octokit/types": "^14.0.0", "before-after-hook": "^3.0.2", "universal-user-agent": "^7.0.0" } }, "sha512-kIU8SLQkYWGp3pVKiYzA5OSaNF5EE03P/R8zEmmrG6XwOg5oBjXyQVVIauQ0dgau4zYhpZEhJrvIYt6oM+zZZA=="],
|
||||
|
||||
"@octokit/plugin-rest-endpoint-methods/@octokit/types": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/openapi-types": "^20.0.0" } }, "sha512-1rhSOfRa6H9w4YwK0yrf5faDaDTb+yLyBUKOCV4xtCDB5VmIPqd/v9yr9o6SAzOAlRxMiRiCic6JVM1/kunVkw=="],
|
||||
|
||||
"@octokit/request/@octokit/types": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/openapi-types": "^24.2.0" } }, "sha512-ifLaO34EbbPj0Xgro4G5lP5asESjwHracYJvVaPIyXMuiuXLlhic3S47cBdTb+jfODkTE5YtGCLt3Ay3+J97sA=="],
|
||||
@@ -347,6 +343,8 @@
|
||||
|
||||
"@octokit/rest/@octokit/plugin-paginate-rest": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/types": "^13.10.0" }, "peerDependencies": { "@octokit/core": ">=6" } }, "sha512-n5KPteiF7pWKgBIBJSk8qzoZWcUkza2O6A0za97pMGVrGfPdltxrfmfF5GucHYvHGZD8BdaZmmHGz5cX/3gdpw=="],
|
||||
|
||||
"@octokit/rest/@octokit/plugin-request-log": ["@octokit/[email protected]", "", { "peerDependencies": { "@octokit/core": ">=6" } }, "sha512-n/lNeCtq+9ofhC15xzmJCNKP2BWTv8Ih2TTy+jatNCCq/gQP/V7rK3fjIfuz0pDWDALO/o/4QY4hyOF6TQQFUw=="],
|
||||
|
||||
"@octokit/rest/@octokit/plugin-rest-endpoint-methods": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/types": "^13.10.0" }, "peerDependencies": { "@octokit/core": ">=6" } }, "sha512-9Pas60Iv9ejO3WlAX3maE1+38c5nqbJXV5GrncEfkndIpZrJ/WPMRd2xYDcPPEt5yzpxcjw9fWNoPhsSGzqKqw=="],
|
||||
|
||||
"accepts/mime-types": ["[email protected]", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA=="],
|
||||
@@ -367,14 +365,6 @@
|
||||
|
||||
"@octokit/plugin-paginate-rest/@octokit/types/@octokit/openapi-types": ["@octokit/[email protected]", "", {}, "sha512-EtqRBEjp1dL/15V7WiX5LJMIxxkdiGJnabzYx5Apx4FkQIFgAfKumXeYAqqJCj1s+BMX4cPFIFC4OLCR6stlnA=="],
|
||||
|
||||
"@octokit/plugin-request-log/@octokit/core/@octokit/auth-token": ["@octokit/[email protected]", "", {}, "sha512-JcQDsBdg49Yky2w2ld20IHAlwr8d/d8N6NiOXbtuoPCqzbsiJgF633mVUw3x4mo0H5ypataQIX7SFu3yy44Mpw=="],
|
||||
|
||||
"@octokit/plugin-request-log/@octokit/core/@octokit/request": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/endpoint": "^10.1.4", "@octokit/request-error": "^6.1.8", "@octokit/types": "^14.0.0", "fast-content-type-parse": "^2.0.0", "universal-user-agent": "^7.0.2" } }, "sha512-q8ybdytBmxa6KogWlNa818r0k1wlqzNC+yNkcQDECHvQo8Vmstrg18JwqJHdJdUiHD2sjlwBgSm9kHkOKe2iyA=="],
|
||||
|
||||
"@octokit/plugin-request-log/@octokit/core/@octokit/request-error": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/types": "^14.0.0" } }, "sha512-WEi/R0Jmq+IJKydWlKDmryPcmdYSVjL3ekaiEL1L9eo1sUnqMJ+grqmC9cjk7CA7+b2/T397tO5d8YLOH3qYpQ=="],
|
||||
|
||||
"@octokit/plugin-request-log/@octokit/core/before-after-hook": ["[email protected]", "", {}, "sha512-Nik3Sc0ncrMK4UUdXQmAnRtzmNQTAAXmXIopizwZ1W1t8QmfJj+zL4OA2I7XPTPW5z5TDqv4hRo/JzouDJnX3A=="],
|
||||
|
||||
"@octokit/plugin-rest-endpoint-methods/@octokit/types/@octokit/openapi-types": ["@octokit/[email protected]", "", {}, "sha512-EtqRBEjp1dL/15V7WiX5LJMIxxkdiGJnabzYx5Apx4FkQIFgAfKumXeYAqqJCj1s+BMX4cPFIFC4OLCR6stlnA=="],
|
||||
|
||||
"@octokit/request-error/@octokit/types/@octokit/openapi-types": ["@octokit/[email protected]", "", {}, "sha512-9sIH3nSUttelJSXUrmGzl7QUBFul0/mB8HRYl3fOlgHbIWG+WnYDXU3v/2zMtAvuzZ/ed00Ei6on975FhBfzrg=="],
|
||||
@@ -401,8 +391,6 @@
|
||||
|
||||
"type-is/mime-types/mime-db": ["[email protected]", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="],
|
||||
|
||||
"@octokit/plugin-request-log/@octokit/core/@octokit/request/@octokit/endpoint": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/types": "^14.0.0", "universal-user-agent": "^7.0.2" } }, "sha512-OlYOlZIsfEVZm5HCSR8aSg02T2lbUWOsCQoPKfTXJwDzcHQBrVBGdGXb89dv2Kw2ToZaRtudp8O3ZIYoaOjKlA=="],
|
||||
|
||||
"@octokit/rest/@octokit/core/@octokit/request/@octokit/endpoint": ["@octokit/[email protected]", "", { "dependencies": { "@octokit/types": "^14.0.0", "universal-user-agent": "^7.0.2" } }, "sha512-OlYOlZIsfEVZm5HCSR8aSg02T2lbUWOsCQoPKfTXJwDzcHQBrVBGdGXb89dv2Kw2ToZaRtudp8O3ZIYoaOjKlA=="],
|
||||
|
||||
"@octokit/rest/@octokit/plugin-paginate-rest/@octokit/types/@octokit/openapi-types": ["@octokit/[email protected]", "", {}, "sha512-9sIH3nSUttelJSXUrmGzl7QUBFul0/mB8HRYl3fOlgHbIWG+WnYDXU3v/2zMtAvuzZ/ed00Ei6on975FhBfzrg=="],
|
||||
|
||||
@@ -275,6 +275,29 @@ For provider-specific models:
|
||||
# ... other inputs
|
||||
```
|
||||
|
||||
### 1M context models through an API gateway
|
||||
|
||||
When `ANTHROPIC_BASE_URL` points to an Anthropic-compatible API gateway,
|
||||
Claude Code may not be able to verify that the gateway supports a model's native
|
||||
1M context window and can budget the session at 200K instead. Append the
|
||||
`[1m]` selector to explicitly use the 1M context window for supported models,
|
||||
including Claude Opus 5 and Claude Sonnet 5:
|
||||
|
||||
```yaml
|
||||
- uses: anthropics/claude-code-action@v1
|
||||
with:
|
||||
claude_args: |
|
||||
--model "claude-opus-5[1m]"
|
||||
# ... other inputs
|
||||
```
|
||||
|
||||
Use the same selector when setting a model through `ANTHROPIC_MODEL` or another
|
||||
Claude Code model environment variable. The selector is resolved by Claude Code
|
||||
before requests are sent to the provider. The action's sanitized result output
|
||||
includes each model's resolved
|
||||
`contextWindow` and `maxOutputTokens` under `modelUsage`, so these limits are
|
||||
visible without enabling `show_full_output`.
|
||||
|
||||
## Claude Code Settings
|
||||
|
||||
You can provide Claude Code settings to customize behavior such as model selection, environment variables, permissions, and hooks. Settings can be provided either as a JSON string or a path to a settings file.
|
||||
|
||||
+2
-2
@@ -12,13 +12,13 @@
|
||||
"dependencies": {
|
||||
"@actions/core": "^1.10.1",
|
||||
"@actions/github": "^6.0.1",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.233",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.310",
|
||||
"@modelcontextprotocol/sdk": "^1.11.0",
|
||||
"@octokit/graphql": "^8.2.2",
|
||||
"@octokit/rest": "^21.1.1",
|
||||
"@octokit/webhooks-types": "^7.6.1",
|
||||
"node-fetch": "^3.3.2",
|
||||
"shell-quote": "^1.8.3",
|
||||
"shell-quote": "^1.8.4",
|
||||
"zod": "^3.24.4"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -824,7 +824,7 @@ ${
|
||||
? `- Use mcp__github_file_ops__commit_files for making commits (works for both new and existing files, single or multiple). Use mcp__github_file_ops__delete_files for deleting files (supports deleting single or multiple files atomically), or mcp__github__delete_file for deleting a single file. Edit files locally, and the tool will read the content from the same path on disk.
|
||||
Tool usage examples:
|
||||
- mcp__github_file_ops__commit_files: {"files": ["path/to/file1.js", "path/to/file2.py"], "message": "feat: add new feature"}
|
||||
- mcp__github_file_ops__delete_files: {"files": ["path/to/old.js"], "message": "chore: remove deprecated file"}`
|
||||
- mcp__github_file_ops__delete_files: {"paths": ["path/to/old.js"], "message": "chore: remove deprecated file"}`
|
||||
: `- Use git commands via the Bash tool for version control (remember that you have access to these git commands):
|
||||
- Stage files: Bash(git add <files>)
|
||||
- Commit changes: Bash(git commit -m "<message>")
|
||||
@@ -856,7 +856,7 @@ What You CANNOT Do:
|
||||
- Submit formal GitHub PR reviews
|
||||
- Approve pull requests (for security reasons)
|
||||
- Post multiple comments (you only update your initial comment)
|
||||
- Execute commands outside the repository context${useCommitSigning ? "\n- Run arbitrary Bash commands (unless explicitly allowed via allowed_tools configuration)" : ""}
|
||||
- Execute commands outside the repository context${useCommitSigning ? "\n- Run arbitrary Bash commands (unless explicitly allowed via claude_args with --allowedTools)" : ""}
|
||||
- Perform branch operations (cannot merge branches, rebase, or perform other git operations beyond creating and pushing commits)
|
||||
- Modify files in the .github/workflows directory (GitHub App permissions do not allow workflow modifications)
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
*/
|
||||
import { readFileSync } from "fs";
|
||||
import { createOctokit } from "../github/api/client";
|
||||
import { redactSecrets } from "../github/utils/sanitizer";
|
||||
|
||||
const BUFFER_PATH = "/tmp/inline-comments-buffer.jsonl";
|
||||
|
||||
@@ -120,7 +121,7 @@ async function postComment(
|
||||
owner,
|
||||
repo,
|
||||
pull_number,
|
||||
body: c.body,
|
||||
body: redactSecrets(c.body),
|
||||
path: c.path,
|
||||
side: c.side || "RIGHT",
|
||||
commit_id: c.commit_id || headSha,
|
||||
|
||||
@@ -77,7 +77,7 @@ async function installClaudeCode(): Promise<string> {
|
||||
return customExecutable;
|
||||
}
|
||||
|
||||
const claudeCodeVersion = "2.1.233";
|
||||
const claudeCodeVersion = "2.1.310";
|
||||
console.log(`Installing Claude Code v${claudeCodeVersion}...`);
|
||||
|
||||
for (let attempt = 1; attempt <= 3; attempt++) {
|
||||
@@ -159,6 +159,9 @@ async function run() {
|
||||
let context: GitHubContext | undefined;
|
||||
let octokit: Octokits | undefined;
|
||||
let workloadIdentity: WorkloadIdentityHandle | undefined;
|
||||
// Paths reverted to the PR base branch, which cleanup must not commit back
|
||||
// onto the PR author's branch. Empty unless restoreConfigFromBase ran.
|
||||
let restoredConfigPaths: string[] = [];
|
||||
// Track whether we've completed prepare phase, so we can attribute errors correctly
|
||||
let prepareCompleted = false;
|
||||
try {
|
||||
@@ -268,7 +271,7 @@ async function run() {
|
||||
validateBranchName(restoreBase);
|
||||
}
|
||||
if (restoreBase) {
|
||||
restoreConfigFromBase(restoreBase);
|
||||
restoredConfigPaths = restoreConfigFromBase(restoreBase);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -348,6 +351,7 @@ async function run() {
|
||||
prepareSuccess,
|
||||
prepareError,
|
||||
useCommitSigning: context.inputs.useCommitSigning,
|
||||
restoredConfigPaths,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("Error updating comment with job link:", error);
|
||||
|
||||
@@ -16,6 +16,7 @@ import type { ParsedGitHubContext } from "../github/context";
|
||||
import { GITHUB_SERVER_URL } from "../github/api/config";
|
||||
import { checkAndCommitOrDeleteBranch } from "../github/operations/branch-cleanup";
|
||||
import { updateClaudeComment } from "../github/operations/comments/update-claude-comment";
|
||||
import { encodeBranchNameForUrl } from "../github/operations/comments/common";
|
||||
|
||||
export type UpdateCommentLinkParams = {
|
||||
commentId: number;
|
||||
@@ -30,6 +31,12 @@ export type UpdateCommentLinkParams = {
|
||||
prepareSuccess: boolean;
|
||||
prepareError?: string;
|
||||
useCommitSigning: boolean;
|
||||
/**
|
||||
* Paths restored from the PR base branch by restoreConfigFromBase. The
|
||||
* auto-commit in checkAndCommitOrDeleteBranch must leave these alone, or it
|
||||
* commits the revert onto the PR author's branch.
|
||||
*/
|
||||
restoredConfigPaths?: string[];
|
||||
};
|
||||
|
||||
export async function updateCommentLink(
|
||||
@@ -43,6 +50,7 @@ export async function updateCommentLink(
|
||||
context,
|
||||
octokit,
|
||||
useCommitSigning,
|
||||
restoredConfigPaths = [],
|
||||
} = params;
|
||||
|
||||
const { owner, repo } = context.repository;
|
||||
@@ -116,6 +124,7 @@ export async function updateCommentLink(
|
||||
claudeBranch,
|
||||
baseBranch,
|
||||
useCommitSigning,
|
||||
restoredConfigPaths,
|
||||
);
|
||||
|
||||
// Check if we need to add PR URL when we have a new branch
|
||||
@@ -151,7 +160,7 @@ export async function updateCommentLink(
|
||||
const prBody = encodeURIComponent(
|
||||
`This PR addresses ${entityType.toLowerCase()} #${context.entityNumber}\n\nGenerated with [Claude Code](https://claude.ai/code)`,
|
||||
);
|
||||
const prUrl = `${serverUrl}/${owner}/${repo}/compare/${baseBranch}...${claudeBranch}?quick_pull=1&title=${prTitle}&body=${prBody}`;
|
||||
const prUrl = `${serverUrl}/${owner}/${repo}/compare/${encodeBranchNameForUrl(baseBranch)}...${encodeBranchNameForUrl(claudeBranch)}?quick_pull=1&title=${prTitle}&body=${prBody}`;
|
||||
prLink = `\n[Create a PR](${prUrl})`;
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Octokit } from "@octokit/rest";
|
||||
import { graphql } from "@octokit/graphql";
|
||||
import { GITHUB_API_URL } from "./config";
|
||||
import { GITHUB_API_URL, GITHUB_GRAPHQL_URL } from "./config";
|
||||
|
||||
export type Octokits = {
|
||||
rest: Octokit;
|
||||
@@ -14,7 +14,7 @@ export function createOctokit(token: string): Octokits {
|
||||
baseUrl: GITHUB_API_URL,
|
||||
}),
|
||||
graphql: graphql.defaults({
|
||||
baseUrl: GITHUB_API_URL,
|
||||
baseUrl: GITHUB_GRAPHQL_URL,
|
||||
headers: {
|
||||
authorization: `token ${token}`,
|
||||
},
|
||||
|
||||
@@ -2,3 +2,16 @@ export const GITHUB_API_URL =
|
||||
process.env.GITHUB_API_URL || "https://api.github.com";
|
||||
export const GITHUB_SERVER_URL =
|
||||
process.env.GITHUB_SERVER_URL || "https://github.com";
|
||||
|
||||
// GraphQL base URL for @octokit/graphql. GitHub Actions exposes the full GraphQL
|
||||
// endpoint in GITHUB_GRAPHQL_URL (e.g. "https://HOST/api/graphql"), while
|
||||
// @octokit/graphql appends "/graphql" to whatever baseUrl it is given, so a
|
||||
// single trailing "/graphql" is stripped here to avoid "/graphql/graphql".
|
||||
// When GITHUB_GRAPHQL_URL is unset we fall back to GITHUB_API_URL, preserving the
|
||||
// existing behavior where @octokit/graphql rewrites a REST ".../api/v3" base to
|
||||
// ".../api/graphql". The trailing-slash trim keeps that rewrite working.
|
||||
export const GITHUB_GRAPHQL_URL = (
|
||||
process.env.GITHUB_GRAPHQL_URL || GITHUB_API_URL
|
||||
)
|
||||
.replace(/\/+$/, "")
|
||||
.replace(/\/graphql$/, "");
|
||||
|
||||
@@ -7,6 +7,7 @@ export const PR_QUERY = `
|
||||
title
|
||||
body
|
||||
author {
|
||||
__typename
|
||||
login
|
||||
}
|
||||
baseRefName
|
||||
@@ -57,6 +58,7 @@ export const PR_QUERY = `
|
||||
databaseId
|
||||
body
|
||||
author {
|
||||
__typename
|
||||
login
|
||||
}
|
||||
createdAt
|
||||
@@ -70,6 +72,7 @@ export const PR_QUERY = `
|
||||
id
|
||||
databaseId
|
||||
author {
|
||||
__typename
|
||||
login
|
||||
}
|
||||
body
|
||||
@@ -84,7 +87,9 @@ export const PR_QUERY = `
|
||||
body
|
||||
path
|
||||
line
|
||||
diffHunk
|
||||
author {
|
||||
__typename
|
||||
login
|
||||
}
|
||||
createdAt
|
||||
@@ -107,6 +112,7 @@ export const ISSUE_QUERY = `
|
||||
title
|
||||
body
|
||||
author {
|
||||
__typename
|
||||
login
|
||||
}
|
||||
createdAt
|
||||
@@ -124,6 +130,7 @@ export const ISSUE_QUERY = `
|
||||
databaseId
|
||||
body
|
||||
author {
|
||||
__typename
|
||||
login
|
||||
}
|
||||
createdAt
|
||||
|
||||
@@ -23,6 +23,7 @@ import type { CommentWithImages } from "../utils/image-downloader";
|
||||
import { downloadCommentImages } from "../utils/image-downloader";
|
||||
import {
|
||||
parseActorFilter,
|
||||
resolveActorName,
|
||||
shouldIncludeCommentByActor,
|
||||
} from "../utils/actor-filter";
|
||||
|
||||
@@ -339,7 +340,7 @@ export function isBodySafeToUse(
|
||||
* @returns Filtered array of comments
|
||||
*/
|
||||
export function filterCommentsByActor<
|
||||
T extends { author: { login: string } | null },
|
||||
T extends { author: { login: string; __typename?: string } | null },
|
||||
>(comments: T[], includeActors: string = "", excludeActors: string = ""): T[] {
|
||||
const includeParsed = parseActorFilter(includeActors);
|
||||
const excludeParsed = parseActorFilter(excludeActors);
|
||||
@@ -351,9 +352,10 @@ export function filterCommentsByActor<
|
||||
|
||||
return comments.filter((comment) =>
|
||||
shouldIncludeCommentByActor(
|
||||
// author is null for comments from deleted ("ghost") accounts; treat them
|
||||
// as the "ghost" login so filtering never dereferences null and crashes.
|
||||
comment.author?.login ?? "ghost",
|
||||
// Normalizes App actors to their "[bot]"-suffixed name, which is the form
|
||||
// filter patterns are written in. Also maps deleted ("ghost") accounts,
|
||||
// whose author is null, to "ghost" so filtering never dereferences null.
|
||||
resolveActorName(comment.author),
|
||||
includeParsed,
|
||||
excludeParsed,
|
||||
),
|
||||
|
||||
@@ -118,7 +118,16 @@ export function formatReviewComments(
|
||||
|
||||
body = sanitizeContent(body);
|
||||
|
||||
return ` [Comment on ${comment.path}:${comment.line || "?"}]: ${body}`;
|
||||
let formatted = ` [Comment on ${comment.path}:${comment.line || "?"}]: ${body}`;
|
||||
|
||||
// The diff hunk is the code the comment was left on. Without it the
|
||||
// comment arrives without the context it was written against.
|
||||
if (comment.diffHunk) {
|
||||
const diffHunk = sanitizeContent(comment.diffHunk);
|
||||
formatted += `\n Diff context:\n\`\`\`diff\n${diffHunk}\n\`\`\``;
|
||||
}
|
||||
|
||||
return formatted;
|
||||
})
|
||||
.join("\n");
|
||||
if (comments) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { Octokits } from "../api/client";
|
||||
import { GITHUB_SERVER_URL } from "../api/config";
|
||||
import { encodeBranchNameForUrl } from "./comments/common";
|
||||
import { $ } from "bun";
|
||||
|
||||
export async function checkAndCommitOrDeleteBranch(
|
||||
@@ -9,10 +10,32 @@ export async function checkAndCommitOrDeleteBranch(
|
||||
claudeBranch: string | undefined,
|
||||
baseBranch: string,
|
||||
useCommitSigning: boolean,
|
||||
restoredConfigPaths: string[] = [],
|
||||
): Promise<{ shouldDeleteBranch: boolean; branchLink: string }> {
|
||||
let branchLink = "";
|
||||
let shouldDeleteBranch = false;
|
||||
|
||||
// On pull requests, restoreConfigFromBase replaces .claude/, CLAUDE.md and
|
||||
// friends with the base branch's versions and leaves them unstaged so the
|
||||
// revert does not reach a commit. Auto-committing with a bare `git add -A`
|
||||
// would stage them anyway and push a silent revert of the PR author's own
|
||||
// config onto their branch.
|
||||
//
|
||||
// The exclusion is driven by what was actually restored rather than applied
|
||||
// unconditionally: this path also runs for issues, where no restore happens
|
||||
// and Claude may legitimately have been asked to edit CLAUDE.md or
|
||||
// .claude/settings.json. Excluding those there would silently drop the work.
|
||||
const pathspecArgs =
|
||||
restoredConfigPaths.length > 0
|
||||
? ["--", ".", ...restoredConfigPaths.map((p) => `:(exclude)${p}`)]
|
||||
: [];
|
||||
|
||||
if (pathspecArgs.length > 0) {
|
||||
console.log(
|
||||
`Excluding base-restored config from auto-commit: ${restoredConfigPaths.join(", ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (claudeBranch) {
|
||||
// First check if the branch exists remotely
|
||||
let branchExistsRemotely = false;
|
||||
@@ -57,15 +80,19 @@ export async function checkAndCommitOrDeleteBranch(
|
||||
|
||||
// Check for uncommitted changes using git status
|
||||
try {
|
||||
const gitStatus = await $`git status --porcelain`.quiet();
|
||||
// Scoped the same way as the staging below: if the restored config
|
||||
// is the only dirty entry there is no real work, and the branch
|
||||
// should be treated as empty rather than receiving a pure revert.
|
||||
const gitStatus =
|
||||
await $`git status --porcelain ${pathspecArgs}`.quiet();
|
||||
const hasUncommittedChanges =
|
||||
gitStatus.stdout.toString().trim().length > 0;
|
||||
|
||||
if (hasUncommittedChanges) {
|
||||
console.log("Found uncommitted changes, committing them...");
|
||||
|
||||
// Add all changes
|
||||
await $`git add -A`;
|
||||
// Add all changes, minus anything restored from the base branch
|
||||
await $`git add -A ${pathspecArgs}`;
|
||||
|
||||
// Commit with a descriptive message
|
||||
const runId = process.env.GITHUB_RUN_ID || "unknown";
|
||||
@@ -80,7 +107,7 @@ export async function checkAndCommitOrDeleteBranch(
|
||||
);
|
||||
|
||||
// Set branch link since we now have commits
|
||||
const branchUrl = `${GITHUB_SERVER_URL}/${owner}/${repo}/tree/${claudeBranch}`;
|
||||
const branchUrl = `${GITHUB_SERVER_URL}/${owner}/${repo}/tree/${encodeBranchNameForUrl(claudeBranch)}`;
|
||||
branchLink = `\n[View branch](${branchUrl})`;
|
||||
} else {
|
||||
console.log(
|
||||
@@ -91,7 +118,7 @@ export async function checkAndCommitOrDeleteBranch(
|
||||
} catch (gitError) {
|
||||
console.error("Error checking/committing changes:", gitError);
|
||||
// If we can't check git status, assume the branch might have changes
|
||||
const branchUrl = `${GITHUB_SERVER_URL}/${owner}/${repo}/tree/${claudeBranch}`;
|
||||
const branchUrl = `${GITHUB_SERVER_URL}/${owner}/${repo}/tree/${encodeBranchNameForUrl(claudeBranch)}`;
|
||||
branchLink = `\n[View branch](${branchUrl})`;
|
||||
}
|
||||
} else {
|
||||
@@ -102,13 +129,13 @@ export async function checkAndCommitOrDeleteBranch(
|
||||
}
|
||||
} else {
|
||||
// Only add branch link if there are commits
|
||||
const branchUrl = `${GITHUB_SERVER_URL}/${owner}/${repo}/tree/${claudeBranch}`;
|
||||
const branchUrl = `${GITHUB_SERVER_URL}/${owner}/${repo}/tree/${encodeBranchNameForUrl(claudeBranch)}`;
|
||||
branchLink = `\n[View branch](${branchUrl})`;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error comparing commits on Claude branch:", error);
|
||||
// If we can't compare but the branch exists remotely, include the branch link
|
||||
const branchUrl = `${GITHUB_SERVER_URL}/${owner}/${repo}/tree/${claudeBranch}`;
|
||||
const branchUrl = `${GITHUB_SERVER_URL}/${owner}/${repo}/tree/${encodeBranchNameForUrl(claudeBranch)}`;
|
||||
branchLink = `\n[View branch](${branchUrl})`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,10 +9,13 @@
|
||||
import { $ } from "bun";
|
||||
import { execFileSync } from "child_process";
|
||||
import type { ParsedGitHubContext } from "../context";
|
||||
import { isPullRequestEvent } from "../context";
|
||||
import { retryWithBackoff } from "../../utils/retry";
|
||||
import type { GitHubPullRequest } from "../types";
|
||||
import type { Octokits } from "../api/client";
|
||||
import type { FetchDataResult } from "../data/fetcher";
|
||||
import { generateBranchName } from "../../utils/branch-template";
|
||||
import { fetchDepthArgs } from "./fetch-depth";
|
||||
|
||||
/**
|
||||
* Extracts the first label from GitHub data, or returns undefined if no labels exist
|
||||
@@ -28,7 +31,7 @@ function extractFirstLabel(githubData: FetchDataResult): string | undefined {
|
||||
*
|
||||
* Valid branch names:
|
||||
* - Start with alphanumeric character, underscore, or @ (not dash, to prevent option injection)
|
||||
* - Contain only alphanumeric, forward slash, hyphen, underscore, period, hash (#), plus (+), comma (,), or at sign (@)
|
||||
* - Contain only alphanumeric, forward slash, hyphen, underscore, period, hash (#), plus (+), comma (,), at sign (@), or parentheses
|
||||
* - Do not start or end with a period
|
||||
* - Do not end with a slash
|
||||
* - Do not contain '..' (path traversal)
|
||||
@@ -59,7 +62,7 @@ export function validateBranchName(branchName: string): void {
|
||||
);
|
||||
}
|
||||
|
||||
// Strict whitelist pattern: alphanumeric or @ start, then alphanumeric/slash/hyphen/underscore/period/hash/plus/comma/at-sign.
|
||||
// Strict whitelist pattern: alphanumeric or @ start, then alphanumeric/slash/hyphen/underscore/period/hash/plus/comma/at-sign/parentheses.
|
||||
// # is valid per git-check-ref-format and commonly used in branch names like "fix/#123-description".
|
||||
// + is valid per git-check-ref-format and generated by Claude Code's EnterWorktree tool when
|
||||
// converting worktree names containing "/" (e.g. "feat/foo" becomes "worktree-feat+foo").
|
||||
@@ -71,12 +74,14 @@ export function validateBranchName(branchName: string): void {
|
||||
// _ is valid per git-check-ref-format anywhere in a ref name, including the first character;
|
||||
// leading underscores are a common convention for release/internal branches (e.g.
|
||||
// "_release/v1.2.3"), which previously failed validation as a PR's base branch.
|
||||
// Parentheses are valid per git-check-ref-format and commonly appear in branch names that
|
||||
// use Conventional Commit-style scopes (e.g. "feat(parser)-handle-empty-input").
|
||||
// All git calls use execFileSync (not shell interpolation), so none of these characters carry injection risk.
|
||||
const validPattern = /^[a-zA-Z0-9@_][a-zA-Z0-9/_.#+,@-]*$/;
|
||||
const validPattern = /^[a-zA-Z0-9@_][a-zA-Z0-9/_.#+,@()-]*$/;
|
||||
|
||||
if (!validPattern.test(branchName)) {
|
||||
throw new Error(
|
||||
`Invalid branch name: "${branchName}". Branch names must start with an alphanumeric character, underscore, or '@' and contain only alphanumeric characters, forward slashes, hyphens, underscores, periods, hashes (#), plus signs (+), commas (,), or at signs (@).`,
|
||||
`Invalid branch name: "${branchName}". Branch names must start with an alphanumeric character, underscore, or '@' and contain only alphanumeric characters, forward slashes, hyphens, underscores, periods, hashes (#), plus signs (+), commas (,), at signs (@), or parentheses.`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -153,6 +158,7 @@ export async function setupBranch(
|
||||
octokits: Octokits,
|
||||
githubData: FetchDataResult,
|
||||
context: ParsedGitHubContext,
|
||||
triggerTime?: string,
|
||||
): Promise<BranchInfo> {
|
||||
const { owner, repo } = context.repository;
|
||||
const entityNumber = context.entityNumber;
|
||||
@@ -174,36 +180,75 @@ export async function setupBranch(
|
||||
console.log("This is an open PR, checking out PR branch...");
|
||||
|
||||
const branchName = prData.headRefName;
|
||||
const headSha = prData.headRefOid;
|
||||
|
||||
// Determine optimal fetch depth based on PR commit count, with a minimum of 20
|
||||
// Determine optimal fetch depth based on PR commit count, with a minimum
|
||||
// of 20. Only applied to a checkout that is already shallow — see
|
||||
// fetchDepthArgs.
|
||||
const commitCount = prData.commits.totalCount;
|
||||
const fetchDepth = Math.max(commitCount, 20);
|
||||
const depthArgs = fetchDepthArgs(fetchDepth);
|
||||
|
||||
console.log(
|
||||
`PR #${entityNumber}: ${commitCount} commits, using fetch depth ${fetchDepth}`,
|
||||
`PR #${entityNumber}: ${commitCount} commits, ${
|
||||
depthArgs.length > 0
|
||||
? `using fetch depth ${fetchDepth}`
|
||||
: "fetching without a depth limit (checkout has full history)"
|
||||
}`,
|
||||
);
|
||||
|
||||
// Validate branch names before use to prevent command injection
|
||||
validateBranchName(branchName);
|
||||
if (!/^[0-9a-f]{40}$/.test(headSha)) {
|
||||
throw new Error(
|
||||
`Unexpected head SHA for PR #${entityNumber}: ${headSha}`,
|
||||
);
|
||||
}
|
||||
|
||||
// For cross-repository (fork) PRs, fetch via the pull ref since the
|
||||
// branch only exists on the fork's remote, not on origin.
|
||||
if (prData.isCrossRepository) {
|
||||
console.log(
|
||||
`PR #${entityNumber} is from a fork, fetching via refs/pull/${entityNumber}/head...`,
|
||||
if (isPullRequestEvent(context)) {
|
||||
const eventSha = context.payload.pull_request.head.sha;
|
||||
if (eventSha !== headSha) {
|
||||
throw new Error(
|
||||
`PR #${entityNumber} was updated after the trigger (${eventSha} -> ${headSha}). Push again or mention Claude to run on the latest version.`,
|
||||
);
|
||||
}
|
||||
} else if (triggerTime) {
|
||||
if (!prData.headRepository) {
|
||||
throw new Error(
|
||||
`PR #${entityNumber}: head repository is not available, cannot pin the PR version`,
|
||||
);
|
||||
}
|
||||
const pushedAt = await headPushedAt(
|
||||
octokits,
|
||||
{
|
||||
owner: prData.headRepository.owner.login,
|
||||
repo: prData.headRepository.name,
|
||||
},
|
||||
branchName,
|
||||
headSha,
|
||||
);
|
||||
if (new Date(pushedAt).getTime() >= new Date(triggerTime).getTime()) {
|
||||
throw new Error(
|
||||
`PR #${entityNumber} was updated after the trigger (${pushedAt} >= ${triggerTime}). Mention Claude again to run on the latest version.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const localBranch = prData.isCrossRepository
|
||||
? `pr-${entityNumber}`
|
||||
: branchName;
|
||||
console.log(`PR #${entityNumber}: pinning ${localBranch} to ${headSha}`);
|
||||
execGit(["fetch", "origin", ...depthArgs, headSha]);
|
||||
execGit(["checkout", "-B", localBranch, headSha, "--"]);
|
||||
|
||||
const checkedOut = execFileSync("git", ["rev-parse", "HEAD"], {
|
||||
encoding: "utf8",
|
||||
}).trim();
|
||||
if (checkedOut !== headSha) {
|
||||
throw new Error(
|
||||
`PR #${entityNumber}: checked out ${checkedOut}, expected ${headSha}`,
|
||||
);
|
||||
execGit([
|
||||
"fetch",
|
||||
"origin",
|
||||
`--depth=${fetchDepth}`,
|
||||
`pull/${entityNumber}/head:${branchName}`,
|
||||
]);
|
||||
} else {
|
||||
// Execute git commands to checkout PR branch (dynamic depth based on PR size)
|
||||
// Using execFileSync instead of shell template literals for security
|
||||
execGit(["fetch", "origin", `--depth=${fetchDepth}`, branchName]);
|
||||
}
|
||||
execGit(["checkout", branchName, "--"]);
|
||||
|
||||
console.log(`Successfully checked out PR branch for PR #${entityNumber}`);
|
||||
|
||||
@@ -213,7 +258,7 @@ export async function setupBranch(
|
||||
|
||||
return {
|
||||
baseBranch,
|
||||
currentBranch: branchName,
|
||||
currentBranch: localBranch,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -302,7 +347,7 @@ export async function setupBranch(
|
||||
// Ensure we're on the source branch
|
||||
console.log(`Fetching and checking out source branch: ${sourceBranch}`);
|
||||
validateBranchName(sourceBranch);
|
||||
execGit(["fetch", "origin", sourceBranch, "--depth=1"]);
|
||||
execGit(["fetch", "origin", sourceBranch, ...fetchDepthArgs(1)]);
|
||||
execGit(["checkout", sourceBranch, "--"]);
|
||||
|
||||
return {
|
||||
@@ -320,7 +365,7 @@ export async function setupBranch(
|
||||
// Fetch and checkout the source branch first to ensure we branch from the correct base
|
||||
console.log(`Fetching and checking out source branch: ${sourceBranch}`);
|
||||
validateBranchName(sourceBranch);
|
||||
execGit(["fetch", "origin", sourceBranch, "--depth=1"]);
|
||||
execGit(["fetch", "origin", sourceBranch, ...fetchDepthArgs(1)]);
|
||||
execGit(["checkout", sourceBranch, "--"]);
|
||||
|
||||
// Create and checkout the new branch from the source branch
|
||||
@@ -340,3 +385,26 @@ export async function setupBranch(
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
async function headPushedAt(
|
||||
octokits: Octokits,
|
||||
headRepo: { owner: string; repo: string },
|
||||
branchName: string,
|
||||
headSha: string,
|
||||
): Promise<string> {
|
||||
const { data } = await retryWithBackoff(() =>
|
||||
octokits.rest.request("GET /repos/{owner}/{repo}/activity", {
|
||||
owner: headRepo.owner,
|
||||
repo: headRepo.repo,
|
||||
ref: `refs/heads/${branchName}`,
|
||||
per_page: 1,
|
||||
}),
|
||||
);
|
||||
const latest = (data as Array<{ after: string; timestamp: string }>)[0];
|
||||
if (!latest || latest.after !== headSha) {
|
||||
throw new Error(
|
||||
`Could not determine when ${headSha} was pushed to ${headRepo.owner}/${headRepo.repo}:${branchName}`,
|
||||
);
|
||||
}
|
||||
return latest.timestamp;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { GITHUB_SERVER_URL } from "../api/config";
|
||||
import { redactSecrets } from "../utils/sanitizer";
|
||||
import { encodeBranchNameForUrl } from "./comments/common";
|
||||
|
||||
export type ExecutionDetails = {
|
||||
total_cost_usd?: number;
|
||||
@@ -161,7 +162,7 @@ export function updateCommentBody(input: CommentUpdateInput): string {
|
||||
// Extract owner/repo from jobUrl
|
||||
const repoMatch = jobUrl.match(/github\.com\/([^\/]+)\/([^\/]+)\//);
|
||||
if (repoMatch) {
|
||||
branchUrl = `${GITHUB_SERVER_URL}/${repoMatch[1]}/${repoMatch[2]}/tree/${finalBranchName}`;
|
||||
branchUrl = `${GITHUB_SERVER_URL}/${repoMatch[1]}/${repoMatch[2]}/tree/${encodeBranchNameForUrl(finalBranchName)}`;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,12 +12,17 @@ export function createJobRunLink(
|
||||
return `[View job run](${jobRunUrl})`;
|
||||
}
|
||||
|
||||
/** Encode Git-ref path segments without turning `/` into `%2F`. */
|
||||
export function encodeBranchNameForUrl(branchName: string): string {
|
||||
return branchName.split("/").map(encodeURIComponent).join("/");
|
||||
}
|
||||
|
||||
export function createBranchLink(
|
||||
owner: string,
|
||||
repo: string,
|
||||
branchName: string,
|
||||
): string {
|
||||
const branchUrl = `${GITHUB_SERVER_URL}/${owner}/${repo}/tree/${branchName}`;
|
||||
const branchUrl = `${GITHUB_SERVER_URL}/${owner}/${repo}/tree/${encodeBranchNameForUrl(branchName)}`;
|
||||
return `\n[View branch](${branchUrl})`;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { execFileSync } from "child_process";
|
||||
|
||||
/**
|
||||
* Builds the `--depth` argument for a `git fetch`, unless the checkout still
|
||||
* has its full history.
|
||||
*
|
||||
* `--depth` does not only cap what gets downloaded. Against a complete checkout
|
||||
* (`actions/checkout` with `fetch-depth: 0`) it also truncates the history that
|
||||
* is already there and marks the repository shallow, which drops the merge base
|
||||
* with the base branch: `git log origin/<base>..HEAD` then quietly lists
|
||||
* commits that are already merged, and `git diff origin/<base>...HEAD` fails
|
||||
* with "no merge base". Those are the commands the prompt tells Claude to run
|
||||
* to scope its work to the PR.
|
||||
*
|
||||
* A shallow checkout (the `fetch-depth: 1` default) has no history left to
|
||||
* lose, so the limit still applies there and large repositories keep the fetch
|
||||
* savings it was added for.
|
||||
*/
|
||||
export function fetchDepthArgs(depth: number): string[] {
|
||||
return isShallowRepository() ? [`--depth=${depth}`] : [];
|
||||
}
|
||||
|
||||
function isShallowRepository(): boolean {
|
||||
try {
|
||||
const output = execFileSync(
|
||||
"git",
|
||||
["rev-parse", "--is-shallow-repository"],
|
||||
{
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
},
|
||||
);
|
||||
return output.trim() === "true";
|
||||
} catch {
|
||||
// No repository yet, or a git old enough not to know the flag. Treat the
|
||||
// checkout as complete: fetching more than necessary is recoverable,
|
||||
// truncating history is not.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -56,6 +56,16 @@ export async function configureGitAuth(
|
||||
* action's own token instead (a credential helper when non-write users are
|
||||
* allowed, otherwise the origin URL). This applies to every mode, including API
|
||||
* commit signing where no other git configuration is needed.
|
||||
*
|
||||
* actions/checkout < v6 stored the header directly in the repo-local config,
|
||||
* where `git config --unset-all` removes it. Since v6.0.0 (backported to
|
||||
* v5.0.1 and v4.3.1) the header is written to a separate file under
|
||||
* RUNNER_TEMP that the repo config pulls in via `include.path`; `--unset-all`
|
||||
* on the local config cannot touch an include-provided value, so the removal
|
||||
* was a silent no-op and the checkout credential (typically the workflow
|
||||
* GITHUB_TOKEN) stayed usable by git for the rest of the job. Clear the
|
||||
* header from the local config AND from every included file so it can no
|
||||
* longer authenticate while Claude runs.
|
||||
*/
|
||||
export async function replaceCheckoutCredentials(
|
||||
githubToken: string,
|
||||
@@ -65,12 +75,35 @@ export async function replaceCheckoutCredentials(
|
||||
|
||||
// Remove the authorization header that actions/checkout sets
|
||||
console.log("Removing existing git authentication headers...");
|
||||
const extraheaderKey = `http.${GITHUB_SERVER_URL}/.extraheader`;
|
||||
let removedHeader = false;
|
||||
try {
|
||||
await $`git config --unset-all http.${GITHUB_SERVER_URL}/.extraheader`;
|
||||
console.log("✓ Removed existing authentication headers");
|
||||
} catch (e) {
|
||||
console.log("No existing authentication headers to remove");
|
||||
await $`git config --unset-all ${extraheaderKey}`;
|
||||
removedHeader = true;
|
||||
} catch {
|
||||
// No extraheader in the local config (expected on the v6+ include layout).
|
||||
}
|
||||
try {
|
||||
const includePaths =
|
||||
await $`git config --local --get-all include.path`.text();
|
||||
for (const includePath of includePaths.split("\n")) {
|
||||
const path = includePath.trim();
|
||||
if (!path) continue;
|
||||
try {
|
||||
await $`git config --file ${path} --unset-all ${extraheaderKey}`;
|
||||
removedHeader = true;
|
||||
} catch {
|
||||
// This include does not define the header; leave it untouched.
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// No include.path entries in the local config.
|
||||
}
|
||||
console.log(
|
||||
removedHeader
|
||||
? "✓ Removed existing authentication headers"
|
||||
: "No existing authentication headers to remove",
|
||||
);
|
||||
|
||||
if (process.env.ALLOWED_NON_WRITE_USERS) {
|
||||
// When processing content from non-write users, use a credential helper
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
writeFileSync,
|
||||
} from "fs";
|
||||
import { dirname, join, posix, relative, sep } from "path";
|
||||
import { fetchDepthArgs } from "./fetch-depth";
|
||||
|
||||
// Paths that are both PR-controllable and read from cwd at CLI startup.
|
||||
//
|
||||
@@ -22,7 +23,7 @@ import { dirname, join, posix, relative, sep } from "path";
|
||||
// .gitconfig — git reads ~/.gitconfig and .git/config, never cwd/.gitconfig.
|
||||
// .bashrc etc. — shells source these from $HOME; checkout cannot reach $HOME.
|
||||
// .vscode/.idea— IDE config; nothing in the CLI's startup path reads them.
|
||||
const SENSITIVE_PATHS = [
|
||||
export const SENSITIVE_PATHS = [
|
||||
".claude",
|
||||
".mcp.json",
|
||||
".claude.json",
|
||||
@@ -261,8 +262,11 @@ function ensureClaudePrExcludedFromGit(): void {
|
||||
*
|
||||
* @param baseBranch - PR base branch name. Must be pre-validated (branch.ts
|
||||
* calls validateBranchName on it before returning).
|
||||
* @returns The paths whose working-tree state now comes from the base branch
|
||||
* rather than the PR. Callers that stage files must exclude these, or they
|
||||
* will commit the revert back onto the PR author's branch.
|
||||
*/
|
||||
export function restoreConfigFromBase(baseBranch: string): void {
|
||||
export function restoreConfigFromBase(baseBranch: string): string[] {
|
||||
console.log(
|
||||
`Restoring ${SENSITIVE_PATHS.join(", ")} from origin/${baseBranch} (PR head is untrusted)`,
|
||||
);
|
||||
@@ -305,7 +309,13 @@ export function restoreConfigFromBase(baseBranch: string): void {
|
||||
// fetch.recurseSubmodules config. Defense-in-depth alongside the delete above.
|
||||
execFileSync(
|
||||
"git",
|
||||
["fetch", "origin", baseBranch, "--depth=1", "--no-recurse-submodules"],
|
||||
[
|
||||
"fetch",
|
||||
"origin",
|
||||
baseBranch,
|
||||
...fetchDepthArgs(1),
|
||||
"--no-recurse-submodules",
|
||||
],
|
||||
{
|
||||
stdio: "inherit",
|
||||
env: process.env,
|
||||
@@ -331,4 +341,9 @@ export function restoreConfigFromBase(baseBranch: string): void {
|
||||
} catch {
|
||||
// Nothing was staged, or paths don't exist on HEAD — either is fine.
|
||||
}
|
||||
|
||||
// Every sensitive path is reported, not just the ones that changed: the
|
||||
// restore also deletes paths the PR added that are absent on base, and those
|
||||
// deletions are stageable too.
|
||||
return [...SENSITIVE_PATHS];
|
||||
}
|
||||
|
||||
@@ -3,9 +3,14 @@
|
||||
// GitHub's GraphQL `author`/`actor` fields resolve to null when the underlying
|
||||
// account has been deleted (the "ghost" user). Any field typed as
|
||||
// `GitHubAuthor | null` can therefore be null at runtime and must be guarded.
|
||||
// `__typename` distinguishes an App/bot actor from a human. GraphQL's
|
||||
// `Actor.login` returns the bare name for bots ("dependabot"), unlike REST which
|
||||
// appends a suffix ("dependabot[bot]"), so the typename is the only reliable bot
|
||||
// signal on this data. See `resolveActorName` in `utils/actor-filter.ts`.
|
||||
export type GitHubAuthor = {
|
||||
login: string;
|
||||
name?: string;
|
||||
__typename?: string;
|
||||
};
|
||||
|
||||
export type GitHubComment = {
|
||||
@@ -22,6 +27,7 @@ export type GitHubComment = {
|
||||
export type GitHubReviewComment = GitHubComment & {
|
||||
path: string;
|
||||
line: number | null;
|
||||
diffHunk?: string | null;
|
||||
};
|
||||
|
||||
export type GitHubCommit = {
|
||||
|
||||
@@ -11,6 +11,31 @@ export function parseActorFilter(filterString: string): string[] {
|
||||
.filter((actor) => actor.length > 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolves the name to match actor filter patterns against.
|
||||
*
|
||||
* GitHub's GraphQL API returns the bare login for App actors ("dependabot"),
|
||||
* whereas REST and the GitHub UI use a "[bot]" suffix ("dependabot[bot]"). Users
|
||||
* write filter patterns in the suffixed form, both the documented "*[bot]"
|
||||
* wildcard and exact entries like "renovate[bot]", so GraphQL bot logins are
|
||||
* normalized to that form before matching. Without this no "[bot]" pattern can
|
||||
* ever match, because the suffix is simply absent from the data.
|
||||
*
|
||||
* @param author - Comment author; null for deleted ("ghost") accounts
|
||||
* @returns Actor name, "[bot]"-suffixed for App actors
|
||||
*/
|
||||
export function resolveActorName(
|
||||
author: { login: string; __typename?: string } | null | undefined,
|
||||
): string {
|
||||
if (!author) return "ghost";
|
||||
|
||||
if (author.__typename === "Bot" && !author.login.endsWith("[bot]")) {
|
||||
return `${author.login}[bot]`;
|
||||
}
|
||||
|
||||
return author.login;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if an actor matches a pattern
|
||||
* Supports wildcards: "*[bot]" matches all bots, "dependabot[bot]" matches specific
|
||||
|
||||
@@ -34,6 +34,8 @@ const SIGNED_URL_HOST = "private-user-images.githubusercontent.com";
|
||||
const SIGNED_URL_PATH_REGEX =
|
||||
/^\/[^/]+\/[^/]*-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?:\.[a-z0-9]+)?$/i;
|
||||
|
||||
const DEFAULT_IMAGE_DOWNLOAD_TIMEOUT_MS = 30_000;
|
||||
|
||||
function extractSignedUrlAssetGuid(signedUrl: string): string | undefined {
|
||||
let parsed: URL;
|
||||
try {
|
||||
@@ -85,13 +87,19 @@ export type CommentWithImages =
|
||||
| IssueBody
|
||||
| PullRequestBody;
|
||||
|
||||
type ImageDownloadOptions = {
|
||||
timeoutMs?: number;
|
||||
};
|
||||
|
||||
export async function downloadCommentImages(
|
||||
octokits: Octokits,
|
||||
owner: string,
|
||||
repo: string,
|
||||
comments: CommentWithImages[],
|
||||
options: ImageDownloadOptions = {},
|
||||
): Promise<Map<string, string>> {
|
||||
const urlToPathMap = new Map<string, string>();
|
||||
const timeoutMs = options.timeoutMs ?? DEFAULT_IMAGE_DOWNLOAD_TIMEOUT_MS;
|
||||
const downloadsDir = "/tmp/github-images";
|
||||
|
||||
await fs.mkdir(downloadsDir, { recursive: true });
|
||||
@@ -241,15 +249,7 @@ export async function downloadCommentImages(
|
||||
try {
|
||||
console.log(`Downloading ${originalUrl}...`);
|
||||
|
||||
const imageResponse = await fetch(signedUrl);
|
||||
if (!imageResponse.ok) {
|
||||
throw new Error(
|
||||
`HTTP ${imageResponse.status}: ${imageResponse.statusText}`,
|
||||
);
|
||||
}
|
||||
|
||||
const arrayBuffer = await imageResponse.arrayBuffer();
|
||||
const buffer = Buffer.from(arrayBuffer);
|
||||
const buffer = await fetchImage(signedUrl, timeoutMs);
|
||||
|
||||
// GitHub user-attachment URLs (/user-attachments/assets/<uuid>) carry
|
||||
// no file extension, so the URL-based guess silently falls back to
|
||||
@@ -289,6 +289,37 @@ export async function downloadCommentImages(
|
||||
return urlToPathMap;
|
||||
}
|
||||
|
||||
async function fetchImage(url: string, timeoutMs: number): Promise<Buffer> {
|
||||
const controller = new AbortController();
|
||||
let timeoutHandle: ReturnType<typeof setTimeout> | undefined;
|
||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
||||
timeoutHandle = setTimeout(() => {
|
||||
controller.abort();
|
||||
reject(new Error(`Image download timed out after ${timeoutMs}ms`));
|
||||
}, timeoutMs);
|
||||
});
|
||||
|
||||
try {
|
||||
const response = await Promise.race([
|
||||
fetch(url, { signal: controller.signal }),
|
||||
timeoutPromise,
|
||||
]);
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const arrayBuffer = await Promise.race([
|
||||
response.arrayBuffer(),
|
||||
timeoutPromise,
|
||||
]);
|
||||
return Buffer.from(arrayBuffer);
|
||||
} finally {
|
||||
if (timeoutHandle !== undefined) {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getImageExtension(url: string): string {
|
||||
const urlParts = url.split("/");
|
||||
const filename = urlParts[urlParts.length - 1];
|
||||
|
||||
@@ -17,11 +17,18 @@ const PR_NUMBER = process.env.PR_NUMBER;
|
||||
const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
|
||||
const RUNNER_TEMP = process.env.RUNNER_TEMP || "/tmp";
|
||||
|
||||
if (!REPO_OWNER || !REPO_NAME || !PR_NUMBER || !GITHUB_TOKEN) {
|
||||
console.error(
|
||||
"[GitHub CI Server] Error: REPO_OWNER, REPO_NAME, PR_NUMBER, and GITHUB_TOKEN environment variables are required",
|
||||
);
|
||||
process.exit(1);
|
||||
// Job logs are fetched by ID from GitHub-hosted storage; bound the request so a
|
||||
// stalled fetch can't hang this MCP call forever. Mirrors the timeout added to
|
||||
// fetchImage() in src/github/utils/image-downloader.ts (#1625).
|
||||
const DOWNLOAD_JOB_LOG_TIMEOUT_MS = 30_000;
|
||||
|
||||
if (import.meta.main) {
|
||||
if (!REPO_OWNER || !REPO_NAME || !PR_NUMBER || !GITHUB_TOKEN) {
|
||||
console.error(
|
||||
"[GitHub CI Server] Error: REPO_OWNER, REPO_NAME, PR_NUMBER, and GITHUB_TOKEN environment variables are required",
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
const server = new McpServer({
|
||||
@@ -205,6 +212,40 @@ server.tool(
|
||||
},
|
||||
);
|
||||
|
||||
export async function downloadJobLog(
|
||||
client: Octokit,
|
||||
params: { owner: string; repo: string; job_id: number },
|
||||
runnerTemp: string,
|
||||
timeoutMs: number = DOWNLOAD_JOB_LOG_TIMEOUT_MS,
|
||||
): Promise<{ path: string; size_bytes: number }> {
|
||||
const controller = new AbortController();
|
||||
const timeoutHandle = setTimeout(() => controller.abort(), timeoutMs);
|
||||
|
||||
try {
|
||||
const response = await client.actions.downloadJobLogsForWorkflowRun({
|
||||
owner: params.owner,
|
||||
repo: params.repo,
|
||||
job_id: params.job_id,
|
||||
request: { signal: controller.signal },
|
||||
});
|
||||
|
||||
const logsText = response.data as unknown as string;
|
||||
|
||||
const logsDir = `${runnerTemp}/github-ci-logs`;
|
||||
await mkdir(logsDir, { recursive: true });
|
||||
|
||||
const logPath = `${logsDir}/job-${params.job_id}.log`;
|
||||
await writeFile(logPath, logsText, "utf-8");
|
||||
|
||||
return {
|
||||
path: logPath,
|
||||
size_bytes: Buffer.byteLength(logsText, "utf-8"),
|
||||
};
|
||||
} finally {
|
||||
clearTimeout(timeoutHandle);
|
||||
}
|
||||
}
|
||||
|
||||
server.tool(
|
||||
"download_job_log",
|
||||
"Download job logs to disk",
|
||||
@@ -218,24 +259,11 @@ server.tool(
|
||||
baseUrl: GITHUB_API_URL,
|
||||
});
|
||||
|
||||
const response = await client.actions.downloadJobLogsForWorkflowRun({
|
||||
owner: REPO_OWNER!,
|
||||
repo: REPO_NAME!,
|
||||
job_id,
|
||||
});
|
||||
|
||||
const logsText = response.data as unknown as string;
|
||||
|
||||
const logsDir = `${RUNNER_TEMP}/github-ci-logs`;
|
||||
await mkdir(logsDir, { recursive: true });
|
||||
|
||||
const logPath = `${logsDir}/job-${job_id}.log`;
|
||||
await writeFile(logPath, logsText, "utf-8");
|
||||
|
||||
const result = {
|
||||
path: logPath,
|
||||
size_bytes: Buffer.byteLength(logsText, "utf-8"),
|
||||
};
|
||||
const result = await downloadJobLog(
|
||||
client,
|
||||
{ owner: REPO_OWNER!, repo: REPO_NAME!, job_id },
|
||||
RUNNER_TEMP,
|
||||
);
|
||||
|
||||
return {
|
||||
content: [
|
||||
@@ -277,6 +305,8 @@ async function runServer() {
|
||||
}
|
||||
}
|
||||
|
||||
runServer().catch(() => {
|
||||
process.exit(1);
|
||||
});
|
||||
if (import.meta.main) {
|
||||
runServer().catch(() => {
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import { z } from "zod";
|
||||
import { GITHUB_API_URL } from "../github/api/config";
|
||||
import { Octokit } from "@octokit/rest";
|
||||
import { updateClaudeComment } from "../github/operations/comments/update-claude-comment";
|
||||
import { sanitizeContent } from "../github/utils/sanitizer";
|
||||
import { redactSecrets, sanitizeContent } from "../github/utils/sanitizer";
|
||||
|
||||
// Get repository information from environment variables
|
||||
const REPO_OWNER = process.env.REPO_OWNER;
|
||||
@@ -55,7 +55,7 @@ server.tool(
|
||||
const isPullRequestReviewComment =
|
||||
eventName === "pull_request_review_comment";
|
||||
|
||||
const sanitizedBody = sanitizeContent(body);
|
||||
const sanitizedBody = redactSecrets(sanitizeContent(body));
|
||||
|
||||
const result = await updateClaudeComment(octokit, {
|
||||
owner,
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { z } from "zod";
|
||||
|
||||
/** Raw shape passed to `server.tool` for commit_files. */
|
||||
export const commitFilesInputSchema = {
|
||||
files: z
|
||||
.array(z.string())
|
||||
.describe(
|
||||
'Array of file paths relative to repository root (e.g. ["src/main.js", "README.md"]). All files must exist locally.',
|
||||
),
|
||||
message: z.string().describe("Commit message"),
|
||||
};
|
||||
|
||||
/** Raw shape passed to `server.tool` for delete_files. */
|
||||
export const deleteFilesInputSchema = {
|
||||
paths: z
|
||||
.array(z.string())
|
||||
.describe(
|
||||
'Array of file paths to delete relative to repository root (e.g. ["src/old-file.js", "docs/deprecated.md"])',
|
||||
),
|
||||
message: z.string().describe("Commit message"),
|
||||
};
|
||||
|
||||
export const commitFilesPayloadSchema = z.object(commitFilesInputSchema);
|
||||
export const deleteFilesPayloadSchema = z.object(deleteFilesInputSchema);
|
||||
@@ -2,7 +2,6 @@
|
||||
// GitHub File Operations MCP Server
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
||||
import { z } from "zod";
|
||||
import { readFile, stat } from "fs/promises";
|
||||
import { resolve } from "path";
|
||||
import { constants } from "fs";
|
||||
@@ -11,6 +10,10 @@ import { GITHUB_API_URL } from "../github/api/config";
|
||||
import { isBinaryContent } from "./binary-detection";
|
||||
import { validatePathWithinRepo } from "./path-validation";
|
||||
import { updateGitReference } from "./update-git-reference";
|
||||
import {
|
||||
commitFilesInputSchema,
|
||||
deleteFilesInputSchema,
|
||||
} from "./github-file-ops-schemas";
|
||||
|
||||
type GitHubRef = {
|
||||
object: {
|
||||
@@ -197,14 +200,7 @@ async function getFileMode(filePath: string): Promise<string> {
|
||||
server.tool(
|
||||
"commit_files",
|
||||
"Commit one or more files to a repository in a single commit (this will commit them atomically in the remote repository)",
|
||||
{
|
||||
files: z
|
||||
.array(z.string())
|
||||
.describe(
|
||||
'Array of file paths relative to repository root (e.g. ["src/main.js", "README.md"]). All files must exist locally.',
|
||||
),
|
||||
message: z.string().describe("Commit message"),
|
||||
},
|
||||
commitFilesInputSchema,
|
||||
async ({ files, message }) => {
|
||||
const owner = REPO_OWNER;
|
||||
const repo = REPO_NAME;
|
||||
@@ -414,14 +410,7 @@ server.tool(
|
||||
server.tool(
|
||||
"delete_files",
|
||||
"Delete one or more files from a repository in a single commit",
|
||||
{
|
||||
paths: z
|
||||
.array(z.string())
|
||||
.describe(
|
||||
'Array of file paths to delete relative to repository root (e.g. ["src/old-file.js", "docs/deprecated.md"])',
|
||||
),
|
||||
message: z.string().describe("Commit message"),
|
||||
},
|
||||
deleteFilesInputSchema,
|
||||
async ({ paths, message }) => {
|
||||
const owner = REPO_OWNER;
|
||||
const repo = REPO_NAME;
|
||||
@@ -432,21 +421,18 @@ server.tool(
|
||||
throw new Error("GITHUB_TOKEN environment variable is required");
|
||||
}
|
||||
|
||||
// Convert absolute paths to relative if they match CWD
|
||||
const cwd = process.cwd();
|
||||
const processedPaths = paths.map((filePath) => {
|
||||
if (filePath.startsWith("/")) {
|
||||
if (filePath.startsWith(cwd)) {
|
||||
// Strip CWD from absolute path
|
||||
return filePath.slice(cwd.length + 1);
|
||||
} else {
|
||||
throw new Error(
|
||||
`Path '${filePath}' must be relative to repository root or within current working directory`,
|
||||
);
|
||||
}
|
||||
}
|
||||
return filePath;
|
||||
});
|
||||
// Validate all paths are within the repository root and normalize them to
|
||||
// repo-relative paths for the git tree entries. This mirrors the validation
|
||||
// already performed by the commit_files tool and rejects path traversal
|
||||
// ("../") and symlinked escapes as defense-in-depth.
|
||||
const resolvedRepoDir = resolve(REPO_DIR);
|
||||
const processedPaths = await Promise.all(
|
||||
paths.map(async (filePath) => {
|
||||
await validatePathWithinRepo(filePath, REPO_DIR);
|
||||
const normalizedPath = resolve(resolvedRepoDir, filePath);
|
||||
return normalizedPath.slice(resolvedRepoDir.length + 1);
|
||||
}),
|
||||
);
|
||||
|
||||
// 1. Get the branch reference (create if doesn't exist)
|
||||
const baseSha = await getOrCreateBranchRef(
|
||||
|
||||
@@ -4,7 +4,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
|
||||
import { appendFileSync } from "fs";
|
||||
import { z } from "zod";
|
||||
import { createOctokit } from "../github/api/client";
|
||||
import { sanitizeContent } from "../github/utils/sanitizer";
|
||||
import { redactSecrets, sanitizeContent } from "../github/utils/sanitizer";
|
||||
import { removeBufferedComment } from "./inline-comment-buffer";
|
||||
|
||||
// Get repository and PR information from environment variables
|
||||
@@ -98,8 +98,8 @@ server.tool(
|
||||
const repo = REPO_NAME;
|
||||
const pull_number = parseInt(PR_NUMBER, 10);
|
||||
|
||||
// Sanitize the comment body to remove any potential GitHub tokens
|
||||
const sanitizedBody = sanitizeContent(body);
|
||||
// Sanitize the comment body to remove potential prompt injections and redact secrets
|
||||
const sanitizedBody = redactSecrets(sanitizeContent(body));
|
||||
|
||||
// Validate that either line or both startLine and line are provided
|
||||
if (!line && !startLine) {
|
||||
|
||||
@@ -83,20 +83,25 @@ export async function prepareMcpConfig(
|
||||
// Detect if we're in agent mode (explicit prompt provided)
|
||||
const isAgentMode = mode === "agent";
|
||||
|
||||
const hasGitHubCommentTools = allowedToolsList.some((tool) =>
|
||||
tool.startsWith("mcp__github_comment__"),
|
||||
const hasGitHubCommentTools = allowedToolsList.some(
|
||||
(tool) =>
|
||||
tool === "mcp__github_comment" ||
|
||||
tool.startsWith("mcp__github_comment__"),
|
||||
);
|
||||
|
||||
const hasGitHubMcpTools = allowedToolsList.some((tool) =>
|
||||
tool.startsWith("mcp__github__"),
|
||||
const hasGitHubMcpTools = allowedToolsList.some(
|
||||
(tool) => tool === "mcp__github" || tool.startsWith("mcp__github__"),
|
||||
);
|
||||
|
||||
const hasInlineCommentTools = allowedToolsList.some((tool) =>
|
||||
tool.startsWith("mcp__github_inline_comment__"),
|
||||
const hasInlineCommentTools = allowedToolsList.some(
|
||||
(tool) =>
|
||||
tool === "mcp__github_inline_comment" ||
|
||||
tool.startsWith("mcp__github_inline_comment__"),
|
||||
);
|
||||
|
||||
const hasGitHubCITools = allowedToolsList.some((tool) =>
|
||||
tool.startsWith("mcp__github_ci__"),
|
||||
const hasGitHubCITools = allowedToolsList.some(
|
||||
(tool) =>
|
||||
tool === "mcp__github_ci" || tool.startsWith("mcp__github_ci__"),
|
||||
);
|
||||
|
||||
const baseMcpConfig: { mcpServers: Record<string, unknown> } = {
|
||||
|
||||
+30
-2
@@ -14,7 +14,12 @@ import {
|
||||
extractOriginalBody,
|
||||
} from "../../github/data/fetcher";
|
||||
import { createPrompt } from "../../create-prompt";
|
||||
import { isEntityContext } from "../../github/context";
|
||||
import {
|
||||
isEntityContext,
|
||||
isIssueCommentEvent,
|
||||
isPullRequestReviewCommentEvent,
|
||||
} from "../../github/context";
|
||||
import { updateClaudeComment } from "../../github/operations/comments/update-claude-comment";
|
||||
import type { GitHubContext } from "../../github/context";
|
||||
import type { Octokits } from "../../github/api/client";
|
||||
import { parseAllowedTools } from "../agent/parse-tools";
|
||||
@@ -64,7 +69,30 @@ export async function prepareTagMode({
|
||||
});
|
||||
|
||||
// Setup branch
|
||||
const branchInfo = await setupBranch(octokit, githubData, context);
|
||||
const editedAt =
|
||||
context.eventAction === "edited" &&
|
||||
(isIssueCommentEvent(context) || isPullRequestReviewCommentEvent(context))
|
||||
? context.payload.comment.updated_at
|
||||
: undefined;
|
||||
let branchInfo;
|
||||
try {
|
||||
branchInfo = await setupBranch(
|
||||
octokit,
|
||||
githubData,
|
||||
context,
|
||||
editedAt || triggerTime,
|
||||
);
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
await updateClaudeComment(octokit.rest, {
|
||||
owner: context.repository.owner,
|
||||
repo: context.repository.repo,
|
||||
commentId,
|
||||
body: message,
|
||||
isPullRequestReviewComment: isPullRequestReviewCommentEvent(context),
|
||||
}).catch((e) => console.error(`Failed to update tracking comment: ${e}`));
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Configure git authentication
|
||||
// SSH signing takes precedence if provided
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
parseActorFilter,
|
||||
actorMatchesPattern,
|
||||
resolveActorName,
|
||||
shouldIncludeCommentByActor,
|
||||
} from "../src/github/utils/actor-filter";
|
||||
|
||||
@@ -170,3 +171,49 @@ describe("shouldIncludeCommentByActor", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveActorName", () => {
|
||||
test("appends the [bot] suffix to GraphQL App actors", () => {
|
||||
// GraphQL returns the bare login for bots; REST would say "dependabot[bot]".
|
||||
expect(resolveActorName({ __typename: "Bot", login: "dependabot" })).toBe(
|
||||
"dependabot[bot]",
|
||||
);
|
||||
});
|
||||
|
||||
test("leaves human logins untouched", () => {
|
||||
expect(resolveActorName({ __typename: "User", login: "octocat" })).toBe(
|
||||
"octocat",
|
||||
);
|
||||
});
|
||||
|
||||
test("does not double-suffix a login that already ends with [bot]", () => {
|
||||
expect(
|
||||
resolveActorName({ __typename: "Bot", login: "dependabot[bot]" }),
|
||||
).toBe("dependabot[bot]");
|
||||
});
|
||||
|
||||
test("maps deleted accounts to ghost", () => {
|
||||
expect(resolveActorName(null)).toBe("ghost");
|
||||
expect(resolveActorName(undefined)).toBe("ghost");
|
||||
});
|
||||
|
||||
test("falls back to the login when __typename is absent", () => {
|
||||
expect(resolveActorName({ login: "octocat" })).toBe("octocat");
|
||||
});
|
||||
|
||||
test("a bot actor matches the *[bot] wildcard once resolved", () => {
|
||||
const actor = resolveActorName({ __typename: "Bot", login: "renovate" });
|
||||
|
||||
expect(actorMatchesPattern(actor, "*[bot]")).toBe(true);
|
||||
// The raw GraphQL login never matches, which is the bug being fixed.
|
||||
expect(actorMatchesPattern("renovate", "*[bot]")).toBe(false);
|
||||
});
|
||||
|
||||
test("a bot actor matches an exact [bot] pattern once resolved", () => {
|
||||
const actor = resolveActorName({ __typename: "Bot", login: "dependabot" });
|
||||
|
||||
expect(shouldIncludeCommentByActor(actor, [], ["dependabot[bot]"])).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
#!/usr/bin/env bun
|
||||
|
||||
/**
|
||||
* Tests the interaction between restoreConfigFromBase and the auto-commit in
|
||||
* checkAndCommitOrDeleteBranch.
|
||||
*
|
||||
* On pull requests the restore replaces .claude/, CLAUDE.md and friends with
|
||||
* the base branch's versions and leaves them unstaged, so the revert does not
|
||||
* reach a commit. A bare `git add -A` re-staged them anyway and pushed a silent
|
||||
* revert of the PR author's own config onto their branch.
|
||||
*
|
||||
* These run against real git — the fix is a pathspec, so a mock would only
|
||||
* assert that the arguments were passed, not that git honours them.
|
||||
*/
|
||||
|
||||
import { describe, test, expect, beforeEach, afterEach, spyOn } from "bun:test";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { checkAndCommitOrDeleteBranch } from "../src/github/operations/branch-cleanup";
|
||||
import { SENSITIVE_PATHS } from "../src/github/operations/restore-config";
|
||||
import type { Octokits } from "../src/github/api/client";
|
||||
|
||||
const BRANCH = "claude/issue-1-20260101-0000";
|
||||
|
||||
let workDir: string;
|
||||
let remoteDir: string;
|
||||
let originalCwd: string;
|
||||
let logSpy: ReturnType<typeof spyOn>;
|
||||
let errorSpy: ReturnType<typeof spyOn>;
|
||||
|
||||
function git(...args: string[]): string {
|
||||
return execFileSync("git", args, { cwd: workDir, encoding: "utf-8" }).trim();
|
||||
}
|
||||
|
||||
function write(relative: string, contents: string) {
|
||||
const full = join(workDir, relative);
|
||||
mkdirSync(join(full, ".."), { recursive: true });
|
||||
writeFileSync(full, contents);
|
||||
}
|
||||
|
||||
/** Branch exists, and has no commits ahead of base, so cleanup inspects git. */
|
||||
const mockOctokit = {
|
||||
rest: {
|
||||
repos: {
|
||||
getBranch: async () => ({ data: {} }),
|
||||
compareCommitsWithBasehead: async () => ({
|
||||
data: { total_commits: 0 },
|
||||
}),
|
||||
},
|
||||
git: { deleteRef: async () => ({ data: {} }) },
|
||||
},
|
||||
} as unknown as Octokits;
|
||||
|
||||
beforeEach(() => {
|
||||
originalCwd = process.cwd();
|
||||
const root = mkdtempSync(join(tmpdir(), "branch-cleanup-"));
|
||||
remoteDir = join(root, "remote.git");
|
||||
workDir = join(root, "work");
|
||||
|
||||
execFileSync("git", ["init", "-q", "--bare", remoteDir]);
|
||||
execFileSync("git", ["init", "-q", "-b", "main", workDir]);
|
||||
git("config", "user.email", "[email protected]");
|
||||
git("config", "user.name", "Test");
|
||||
git("remote", "add", "origin", remoteDir);
|
||||
|
||||
write(".claude/settings.json", '{"from":"base"}\n');
|
||||
write("CLAUDE.md", "base docs\n");
|
||||
write("src/app.ts", "base code\n");
|
||||
git("add", "-A");
|
||||
git("commit", "-qm", "base");
|
||||
git("push", "-q", "origin", "main");
|
||||
git("checkout", "-qb", BRANCH);
|
||||
git("push", "-q", "origin", BRANCH);
|
||||
|
||||
process.chdir(workDir);
|
||||
logSpy = spyOn(console, "log").mockImplementation(() => {});
|
||||
errorSpy = spyOn(console, "error").mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(originalCwd);
|
||||
logSpy.mockRestore();
|
||||
errorSpy.mockRestore();
|
||||
rmSync(join(workDir, ".."), { recursive: true, force: true });
|
||||
});
|
||||
|
||||
/** Files touched by the most recent commit. */
|
||||
function filesInHeadCommit(): string[] {
|
||||
return git("show", "--name-only", "--format=", "HEAD")
|
||||
.split("\n")
|
||||
.filter(Boolean)
|
||||
.sort();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reproduce the working-tree state restoreConfigFromBase leaves behind: the
|
||||
* PR-authored config overwritten with the base branch's content, unstaged, so
|
||||
* git reports it as a plain modification.
|
||||
*/
|
||||
function simulateRestoredConfig() {
|
||||
write(".claude/settings.json", '{"from":"base"}\n');
|
||||
write("CLAUDE.md", "base docs\n");
|
||||
}
|
||||
|
||||
function authorPrConfigEdits() {
|
||||
write(".claude/settings.json", '{"from":"pr-author"}\n');
|
||||
write("CLAUDE.md", "pr author docs\n");
|
||||
git("commit", "-qam", "PR author edits config");
|
||||
}
|
||||
|
||||
describe("auto-commit with restored config paths", () => {
|
||||
test("does not commit the base-branch revert onto the PR branch", async () => {
|
||||
authorPrConfigEdits();
|
||||
simulateRestoredConfig(); // config now reverted + unstaged
|
||||
write("src/app.ts", "claude's real change\n");
|
||||
|
||||
const result = await checkAndCommitOrDeleteBranch(
|
||||
mockOctokit,
|
||||
"owner",
|
||||
"repo",
|
||||
BRANCH,
|
||||
"main",
|
||||
false,
|
||||
[...SENSITIVE_PATHS],
|
||||
);
|
||||
|
||||
expect(filesInHeadCommit()).toEqual(["src/app.ts"]);
|
||||
expect(result.shouldDeleteBranch).toBe(false);
|
||||
});
|
||||
|
||||
test("leaves the reverted config dirty in the working tree", async () => {
|
||||
authorPrConfigEdits();
|
||||
simulateRestoredConfig();
|
||||
write("src/app.ts", "claude's real change\n");
|
||||
|
||||
await checkAndCommitOrDeleteBranch(
|
||||
mockOctokit,
|
||||
"owner",
|
||||
"repo",
|
||||
BRANCH,
|
||||
"main",
|
||||
false,
|
||||
[...SENSITIVE_PATHS],
|
||||
);
|
||||
|
||||
// --name-only gives bare paths, avoiding porcelain's status-column prefix.
|
||||
const stillDirty = git("diff", "--name-only")
|
||||
.split("\n")
|
||||
.filter(Boolean)
|
||||
.sort();
|
||||
expect(stillDirty).toEqual([".claude/settings.json", "CLAUDE.md"]);
|
||||
});
|
||||
|
||||
test("treats a branch whose only change is the revert as empty", async () => {
|
||||
// No real work — just the reverted config. Committing here would push a
|
||||
// pure revert and keep an otherwise-empty branch alive.
|
||||
authorPrConfigEdits();
|
||||
simulateRestoredConfig();
|
||||
|
||||
const before = git("rev-parse", "HEAD");
|
||||
const result = await checkAndCommitOrDeleteBranch(
|
||||
mockOctokit,
|
||||
"owner",
|
||||
"repo",
|
||||
BRANCH,
|
||||
"main",
|
||||
false,
|
||||
[...SENSITIVE_PATHS],
|
||||
);
|
||||
|
||||
expect(git("rev-parse", "HEAD")).toBe(before);
|
||||
expect(result.shouldDeleteBranch).toBe(true);
|
||||
expect(result.branchLink).toBe("");
|
||||
});
|
||||
|
||||
test("still commits Claude's own changes to non-config files", async () => {
|
||||
authorPrConfigEdits();
|
||||
simulateRestoredConfig();
|
||||
write("src/app.ts", "changed\n");
|
||||
write("src/new-file.ts", "added\n");
|
||||
|
||||
await checkAndCommitOrDeleteBranch(
|
||||
mockOctokit,
|
||||
"owner",
|
||||
"repo",
|
||||
BRANCH,
|
||||
"main",
|
||||
false,
|
||||
[...SENSITIVE_PATHS],
|
||||
);
|
||||
|
||||
expect(filesInHeadCommit()).toEqual(["src/app.ts", "src/new-file.ts"]);
|
||||
});
|
||||
|
||||
test("pushes the commit to the branch", async () => {
|
||||
authorPrConfigEdits();
|
||||
simulateRestoredConfig();
|
||||
write("src/app.ts", "claude's real change\n");
|
||||
|
||||
const result = await checkAndCommitOrDeleteBranch(
|
||||
mockOctokit,
|
||||
"owner",
|
||||
"repo",
|
||||
BRANCH,
|
||||
"main",
|
||||
false,
|
||||
[...SENSITIVE_PATHS],
|
||||
);
|
||||
|
||||
const remoteHead = execFileSync(
|
||||
"git",
|
||||
["--git-dir", remoteDir, "rev-parse", BRANCH],
|
||||
{ encoding: "utf-8" },
|
||||
).trim();
|
||||
expect(remoteHead).toBe(git("rev-parse", "HEAD"));
|
||||
expect(result.branchLink).toContain(BRANCH);
|
||||
});
|
||||
});
|
||||
|
||||
describe("without restored config paths (the issue path)", () => {
|
||||
test("commits config changes normally, since no revert happened", async () => {
|
||||
// Reached for issues, where restoreConfigFromBase never runs and Claude may
|
||||
// have been asked to edit CLAUDE.md. Excluding it here would drop the work.
|
||||
write("CLAUDE.md", "claude wrote these docs\n");
|
||||
write(".claude/settings.json", '{"written":"by claude"}\n');
|
||||
write("src/app.ts", "and some code\n");
|
||||
|
||||
await checkAndCommitOrDeleteBranch(
|
||||
mockOctokit,
|
||||
"owner",
|
||||
"repo",
|
||||
BRANCH,
|
||||
"main",
|
||||
false,
|
||||
[],
|
||||
);
|
||||
|
||||
expect(filesInHeadCommit()).toEqual([
|
||||
".claude/settings.json",
|
||||
"CLAUDE.md",
|
||||
"src/app.ts",
|
||||
]);
|
||||
});
|
||||
|
||||
test("defaults to committing everything when the argument is omitted", async () => {
|
||||
// Backwards compatibility: the parameter is optional.
|
||||
write("CLAUDE.md", "claude wrote these docs\n");
|
||||
|
||||
await checkAndCommitOrDeleteBranch(
|
||||
mockOctokit,
|
||||
"owner",
|
||||
"repo",
|
||||
BRANCH,
|
||||
"main",
|
||||
false,
|
||||
);
|
||||
|
||||
expect(filesInHeadCommit()).toEqual(["CLAUDE.md"]);
|
||||
});
|
||||
});
|
||||
@@ -36,6 +36,12 @@ describe("comments/common", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("encodes URL-significant characters in a branch name", () => {
|
||||
expect(createBranchLink("o", "r", "claude/fix#123")).toBe(
|
||||
`\n[View branch](${GITHUB_SERVER_URL}/o/r/tree/claude/fix%23123)`,
|
||||
);
|
||||
});
|
||||
|
||||
test("prefixes the link with a newline so it renders on its own line", () => {
|
||||
expect(createBranchLink("o", "r", "main").startsWith("\n")).toBe(true);
|
||||
});
|
||||
|
||||
@@ -819,11 +819,46 @@ describe("generatePrompt", () => {
|
||||
// Should have commit signing tool instructions
|
||||
expect(prompt).toContain("mcp__github_file_ops__commit_files");
|
||||
expect(prompt).toContain("mcp__github_file_ops__delete_files");
|
||||
expect(prompt).toContain(
|
||||
'mcp__github_file_ops__delete_files: {"paths": ["path/to/old.js"]',
|
||||
);
|
||||
expect(prompt).not.toContain(
|
||||
'mcp__github_file_ops__delete_files: {"files":',
|
||||
);
|
||||
// Comment tool should always be from comment server, not file ops
|
||||
expect(prompt).toContain("mcp__github_comment__update_claude_comment");
|
||||
|
||||
// Should not have git command instructions
|
||||
expect(prompt).not.toContain("Use git commands via the Bash tool");
|
||||
|
||||
// Bash is off unless the user passes --allowedTools through claude_args.
|
||||
// allowed_tools was removed in v1.0 and must not appear as live guidance.
|
||||
expect(prompt).toContain(
|
||||
"Run arbitrary Bash commands (unless explicitly allowed via claude_args with --allowedTools)",
|
||||
);
|
||||
expect(prompt).not.toContain("allowed_tools configuration");
|
||||
});
|
||||
|
||||
test("does not mention allowed_tools when commit signing is off", async () => {
|
||||
const envVars: PreparedContext = {
|
||||
repository: "owner/repo",
|
||||
claudeCommentId: "12345",
|
||||
triggerPhrase: "@claude",
|
||||
eventData: {
|
||||
eventName: "issue_comment",
|
||||
commentId: "67890",
|
||||
isPR: true,
|
||||
prNumber: "123",
|
||||
commentBody: "@claude fix the bug",
|
||||
},
|
||||
};
|
||||
|
||||
const prompt = await generatePrompt(envVars, mockGitHubData, false, "tag");
|
||||
|
||||
expect(prompt).not.toContain("allowed_tools");
|
||||
expect(prompt).not.toContain(
|
||||
"Run arbitrary Bash commands (unless explicitly allowed",
|
||||
);
|
||||
});
|
||||
|
||||
describe("simplified prompt (USE_SIMPLE_PROMPT)", () => {
|
||||
|
||||
@@ -1215,7 +1215,10 @@ describe("fetchGitHubData integration with time filtering", () => {
|
||||
{
|
||||
id: "2",
|
||||
databaseId: "2",
|
||||
author: { login: "scanner[bot]" },
|
||||
// GraphQL returns the bare login for App actors plus
|
||||
// __typename: "Bot". It does NOT append a "[bot]" suffix the
|
||||
// way REST does, so this mirrors a real payload.
|
||||
author: { __typename: "Bot", login: "scanner" },
|
||||
body: "Pre-trigger bot review",
|
||||
state: "COMMENTED",
|
||||
submittedAt: "2024-01-15T11:00:00Z",
|
||||
|
||||
@@ -508,6 +508,112 @@ describe("formatReviewComments", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("includes the diff hunk as context when present", () => {
|
||||
const reviewData = {
|
||||
nodes: [
|
||||
{
|
||||
id: "review1",
|
||||
databaseId: "300001",
|
||||
author: { login: "reviewer1" },
|
||||
body: "",
|
||||
state: "COMMENTED",
|
||||
submittedAt: "2023-01-01T00:00:00Z",
|
||||
comments: {
|
||||
nodes: [
|
||||
{
|
||||
id: "comment1",
|
||||
databaseId: "200001",
|
||||
body: "This can overflow",
|
||||
author: { login: "reviewer1" },
|
||||
createdAt: "2023-01-01T00:00:00Z",
|
||||
path: "src/index.ts",
|
||||
line: 42,
|
||||
diffHunk: "@@ -40,3 +40,3 @@\n-const a = 1;\n+const a = 2;",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = formatReviewComments(reviewData);
|
||||
|
||||
expect(result).toContain("[Comment on src/index.ts:42]: This can overflow");
|
||||
expect(result).toContain("Diff context:");
|
||||
expect(result).toContain("@@ -40,3 +40,3 @@");
|
||||
expect(result).toContain("+const a = 2;");
|
||||
});
|
||||
|
||||
test("omits the diff context when the comment has no diff hunk", () => {
|
||||
const reviewData = {
|
||||
nodes: [
|
||||
{
|
||||
id: "review1",
|
||||
databaseId: "300001",
|
||||
author: { login: "reviewer1" },
|
||||
body: "",
|
||||
state: "COMMENTED",
|
||||
submittedAt: "2023-01-01T00:00:00Z",
|
||||
comments: {
|
||||
nodes: [
|
||||
{
|
||||
id: "comment1",
|
||||
databaseId: "200001",
|
||||
body: "No hunk here",
|
||||
author: { login: "reviewer1" },
|
||||
createdAt: "2023-01-01T00:00:00Z",
|
||||
path: "src/index.ts",
|
||||
line: 42,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = formatReviewComments(reviewData);
|
||||
|
||||
expect(result).toContain("[Comment on src/index.ts:42]: No hunk here");
|
||||
expect(result).not.toContain("Diff context:");
|
||||
});
|
||||
|
||||
// GitHub returns line: null and diffHunk: "" for outdated comments whose
|
||||
// line no longer exists in the diff (observed on anthropics/claude-code-action#1025).
|
||||
test("omits the diff context for an outdated comment with an empty diff hunk", () => {
|
||||
const reviewData = {
|
||||
nodes: [
|
||||
{
|
||||
id: "review1",
|
||||
databaseId: "300001",
|
||||
author: { login: "reviewer1" },
|
||||
body: "",
|
||||
state: "COMMENTED",
|
||||
submittedAt: "2023-01-01T00:00:00Z",
|
||||
comments: {
|
||||
nodes: [
|
||||
{
|
||||
id: "comment1",
|
||||
databaseId: "200001",
|
||||
body: "Outdated comment",
|
||||
author: { login: "reviewer1" },
|
||||
createdAt: "2023-01-01T00:00:00Z",
|
||||
path: "src/index.ts",
|
||||
line: null,
|
||||
diffHunk: "",
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const result = formatReviewComments(reviewData);
|
||||
|
||||
expect(result).toContain("[Comment on src/index.ts:?]: Outdated comment");
|
||||
expect(result).not.toContain("Diff context:");
|
||||
expect(result).not.toContain("```diff");
|
||||
});
|
||||
|
||||
test("formats review with only body (no comments) correctly", () => {
|
||||
const reviewData = {
|
||||
nodes: [
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
#!/usr/bin/env bun
|
||||
|
||||
import { describe, expect, test, beforeAll } from "bun:test";
|
||||
import { generatePrompt } from "../src/create-prompt";
|
||||
import type { PreparedContext } from "../src/create-prompt";
|
||||
import {
|
||||
commitFilesPayloadSchema,
|
||||
deleteFilesPayloadSchema,
|
||||
} from "../src/mcp/github-file-ops-schemas";
|
||||
|
||||
beforeAll(() => {
|
||||
process.env.GITHUB_ACTION_PATH = "/test/action/path";
|
||||
});
|
||||
|
||||
const mockGitHubData = {
|
||||
contextData: {
|
||||
title: "Test PR",
|
||||
body: "This is a test PR",
|
||||
author: { login: "testuser" },
|
||||
state: "OPEN",
|
||||
labels: { nodes: [] },
|
||||
createdAt: "2023-01-01T00:00:00Z",
|
||||
additions: 15,
|
||||
deletions: 5,
|
||||
baseRefName: "main",
|
||||
headRefName: "feature-branch",
|
||||
headRefOid: "abc123",
|
||||
isCrossRepository: false,
|
||||
headRepository: { owner: { login: "testowner" }, name: "testrepo" },
|
||||
commits: { totalCount: 0, nodes: [] },
|
||||
files: { nodes: [] },
|
||||
comments: { nodes: [] },
|
||||
reviews: { nodes: [] },
|
||||
},
|
||||
comments: [],
|
||||
changedFiles: [],
|
||||
changedFilesWithSHA: [],
|
||||
reviewData: null,
|
||||
imageUrlMap: new Map<string, string>(),
|
||||
};
|
||||
|
||||
const signingContext: PreparedContext = {
|
||||
repository: "owner/repo",
|
||||
claudeCommentId: "12345",
|
||||
triggerPhrase: "@claude",
|
||||
eventData: {
|
||||
eventName: "issue_comment",
|
||||
commentId: "67890",
|
||||
isPR: true,
|
||||
prNumber: "123",
|
||||
commentBody: "@claude delete the old file",
|
||||
},
|
||||
};
|
||||
|
||||
function extractToolExample(
|
||||
prompt: string,
|
||||
tool: string,
|
||||
): Record<string, unknown> {
|
||||
const match = prompt.match(
|
||||
new RegExp(
|
||||
`${tool.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}:\\s*(\\{[^}]+\\})`,
|
||||
),
|
||||
);
|
||||
if (!match) {
|
||||
throw new Error(`No JSON example for ${tool} in prompt`);
|
||||
}
|
||||
return JSON.parse(match[1] as string);
|
||||
}
|
||||
|
||||
describe("delete_files prompt vs live MCP schema (#1665)", () => {
|
||||
test("the payload the old prompt taught is rejected by the tool schema", () => {
|
||||
const taughtByOldPrompt = {
|
||||
files: ["path/to/old.js"],
|
||||
message: "chore: remove deprecated file",
|
||||
};
|
||||
const result = deleteFilesPayloadSchema.safeParse(taughtByOldPrompt);
|
||||
expect(result.success).toBe(false);
|
||||
if (!result.success) {
|
||||
const fields = result.error.issues.map((issue) => issue.path.join("."));
|
||||
expect(fields).toContain("paths");
|
||||
}
|
||||
});
|
||||
|
||||
test("the payload the new prompt teaches is accepted by the tool schema", () => {
|
||||
const taughtByNewPrompt = {
|
||||
paths: ["path/to/old.js"],
|
||||
message: "chore: remove deprecated file",
|
||||
};
|
||||
const result = deleteFilesPayloadSchema.safeParse(taughtByNewPrompt);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
test("generated tag-mode prompt example parses against the live schema", async () => {
|
||||
const prompt = await generatePrompt(
|
||||
signingContext,
|
||||
mockGitHubData,
|
||||
true,
|
||||
"tag",
|
||||
);
|
||||
const example = extractToolExample(
|
||||
prompt,
|
||||
"mcp__github_file_ops__delete_files",
|
||||
);
|
||||
expect(example).toHaveProperty("paths");
|
||||
expect(example).not.toHaveProperty("files");
|
||||
const result = deleteFilesPayloadSchema.safeParse(example);
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
test("rejects paths when the value is a string instead of an array", () => {
|
||||
const result = deleteFilesPayloadSchema.safeParse({
|
||||
paths: "path/to/old.js",
|
||||
message: "chore: remove deprecated file",
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
});
|
||||
|
||||
test("rejects a payload that has paths but omits message", () => {
|
||||
const result = deleteFilesPayloadSchema.safeParse({
|
||||
paths: ["path/to/old.js"],
|
||||
});
|
||||
expect(result.success).toBe(false);
|
||||
if (!result.success) {
|
||||
expect(
|
||||
result.error.issues.map((issue) => issue.path.join(".")),
|
||||
).toContain("message");
|
||||
}
|
||||
});
|
||||
|
||||
test("accepts a payload that still includes the old files key beside paths", () => {
|
||||
const result = deleteFilesPayloadSchema.safeParse({
|
||||
files: ["path/to/old.js"],
|
||||
paths: ["path/to/old.js"],
|
||||
message: "chore: remove deprecated file",
|
||||
});
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
test("does not change commit_files — that sibling tool still requires files", async () => {
|
||||
const prompt = await generatePrompt(
|
||||
signingContext,
|
||||
mockGitHubData,
|
||||
true,
|
||||
"tag",
|
||||
);
|
||||
const example = extractToolExample(
|
||||
prompt,
|
||||
"mcp__github_file_ops__commit_files",
|
||||
);
|
||||
expect(example).toHaveProperty("files");
|
||||
expect(example).not.toHaveProperty("paths");
|
||||
expect(commitFilesPayloadSchema.safeParse(example).success).toBe(true);
|
||||
expect(deleteFilesPayloadSchema.safeParse(example).success).toBe(false);
|
||||
});
|
||||
|
||||
test("generated delete_files example keys are exactly paths and message", async () => {
|
||||
const prompt = await generatePrompt(
|
||||
signingContext,
|
||||
mockGitHubData,
|
||||
true,
|
||||
"tag",
|
||||
);
|
||||
const example = extractToolExample(
|
||||
prompt,
|
||||
"mcp__github_file_ops__delete_files",
|
||||
);
|
||||
expect(Object.keys(example).sort()).toEqual(["message", "paths"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { execFileSync } from "child_process";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "fs";
|
||||
import { join } from "path";
|
||||
import { setupBranch } from "../src/github/operations/branch";
|
||||
import { fetchDepthArgs } from "../src/github/operations/fetch-depth";
|
||||
import { createMockContext } from "./mockContext";
|
||||
|
||||
const octokits = {
|
||||
rest: {
|
||||
repos: { get: async () => ({ data: { default_branch: "main" } }) },
|
||||
git: { getRef: async () => ({ data: { object: { sha: "abc1234" } } }) },
|
||||
},
|
||||
} as any;
|
||||
|
||||
const githubData = {
|
||||
contextData: { title: "Add feature", labels: { nodes: [] } },
|
||||
} as any;
|
||||
|
||||
describe("setupBranch fetch depth", () => {
|
||||
let originalCwd: string;
|
||||
let tempDir = "";
|
||||
let repoDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
originalCwd = process.cwd();
|
||||
tempDir = mkdtempSync(join("/tmp", "fetch-depth-"));
|
||||
repoDir = join(tempDir, "repo");
|
||||
const remoteDir = join(tempDir, "origin.git");
|
||||
|
||||
// Pin the remote's HEAD to main: with the default init.defaultBranch of
|
||||
// master it would dangle, and `git clone --depth=1` (which implies
|
||||
// --single-branch) then produces an empty, non-shallow clone.
|
||||
execFileSync(
|
||||
"git",
|
||||
["init", "--bare", "--initial-branch=main", remoteDir],
|
||||
{
|
||||
stdio: "pipe",
|
||||
},
|
||||
);
|
||||
execFileSync("git", ["init", repoDir], { stdio: "pipe" });
|
||||
git(["checkout", "-b", "main"]);
|
||||
git(["config", "user.email", "[email protected]"]);
|
||||
git(["config", "user.name", "Test User"]);
|
||||
|
||||
for (const message of ["first", "second", "third"]) {
|
||||
writeFileSync(join(repoDir, `${message}.txt`), `${message}\n`);
|
||||
git(["add", "."]);
|
||||
git(["commit", "-m", message]);
|
||||
}
|
||||
|
||||
git(["remote", "add", "origin", remoteDir]);
|
||||
git(["push", "-u", "origin", "main"]);
|
||||
|
||||
process.chdir(repoDir);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(originalCwd);
|
||||
if (tempDir) {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
for (const useCommitSigning of [false, true]) {
|
||||
test(`keeps the full history of a complete checkout with use_commit_signing: ${useCommitSigning}`, async () => {
|
||||
const context = createMockContext({
|
||||
isPR: false,
|
||||
entityNumber: 7,
|
||||
inputs: { useCommitSigning, branchPrefix: "claude/" },
|
||||
});
|
||||
|
||||
await setupBranch(octokits, githubData, context);
|
||||
|
||||
expect(git(["rev-parse", "--is-shallow-repository"]).trim()).toBe(
|
||||
"false",
|
||||
);
|
||||
expect(git(["rev-list", "--count", "HEAD"]).trim()).toBe("3");
|
||||
});
|
||||
}
|
||||
|
||||
test("still limits the depth on an already shallow checkout", () => {
|
||||
const shallowDir = join(tempDir, "shallow");
|
||||
execFileSync(
|
||||
"git",
|
||||
[
|
||||
"clone",
|
||||
"--depth=1",
|
||||
`file://${join(tempDir, "origin.git")}`,
|
||||
shallowDir,
|
||||
],
|
||||
{ stdio: "pipe" },
|
||||
);
|
||||
|
||||
process.chdir(shallowDir);
|
||||
expect(
|
||||
execFileSync("git", ["rev-parse", "--is-shallow-repository"], {
|
||||
cwd: shallowDir,
|
||||
encoding: "utf8",
|
||||
}).trim(),
|
||||
).toBe("true");
|
||||
expect(fetchDepthArgs(20)).toEqual(["--depth=20"]);
|
||||
});
|
||||
|
||||
test("drops the depth limit on a complete checkout", () => {
|
||||
expect(fetchDepthArgs(20)).toEqual([]);
|
||||
});
|
||||
|
||||
function git(args: string[]): string {
|
||||
return execFileSync("git", args, {
|
||||
cwd: repoDir,
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
}
|
||||
});
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
// Wire-level probe for the GitHub API client's endpoint routing.
|
||||
//
|
||||
// `src/github/api/config.ts` reads GITHUB_API_URL / GITHUB_GRAPHQL_URL at module
|
||||
// load time, so each endpoint configuration has to be exercised in its own fresh
|
||||
// process (the companion test spawns this file once per case with the relevant
|
||||
// env vars set). We stub global fetch to capture the FINAL request URL and
|
||||
// Authorization header — asserting constructor options is not enough because
|
||||
// @octokit/graphql rewrites/append the path (".../api/v3" -> ".../api/graphql",
|
||||
// otherwise it appends "/graphql") after the client is constructed.
|
||||
import { createOctokit } from "../../src/github/api/client";
|
||||
|
||||
type Captured = { url: string; auth: string | null };
|
||||
const captured: Captured[] = [];
|
||||
|
||||
globalThis.fetch = (async (input: any, init?: any) => {
|
||||
const url: string =
|
||||
typeof input === "string" ? input : (input?.url ?? String(input));
|
||||
const headers = new Headers(init?.headers ?? input?.headers);
|
||||
captured.push({ url, auth: headers.get("authorization") });
|
||||
return new Response(JSON.stringify({ data: {} }), {
|
||||
status: 200,
|
||||
headers: { "content-type": "application/json" },
|
||||
});
|
||||
}) as typeof fetch;
|
||||
|
||||
const octokits = createOctokit("test-token");
|
||||
|
||||
await octokits.graphql(`query { viewer { login } }`);
|
||||
const graphql = captured[captured.length - 1]!;
|
||||
|
||||
await octokits.rest.request("GET /meta");
|
||||
const rest = captured[captured.length - 1]!;
|
||||
|
||||
process.stdout.write(
|
||||
JSON.stringify({
|
||||
graphqlUrl: graphql.url,
|
||||
graphqlAuth: graphql.auth,
|
||||
restUrl: rest.url,
|
||||
restAuth: rest.auth,
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,94 @@
|
||||
import { describe, test, expect, afterEach } from "bun:test";
|
||||
import { readFile, rm } from "fs/promises";
|
||||
import os from "os";
|
||||
import path from "path";
|
||||
import { downloadJobLog } from "../src/mcp/github-actions-server";
|
||||
import type { Octokit } from "@octokit/rest";
|
||||
|
||||
describe("downloadJobLog", () => {
|
||||
const tmpDirs: string[] = [];
|
||||
|
||||
const makeRunnerTemp = () => {
|
||||
const dir = path.join(
|
||||
os.tmpdir(),
|
||||
`download-job-log-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
||||
);
|
||||
tmpDirs.push(dir);
|
||||
return dir;
|
||||
};
|
||||
|
||||
afterEach(async () => {
|
||||
while (tmpDirs.length) {
|
||||
const dir = tmpDirs.pop()!;
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
const createStallingClient = (): {
|
||||
client: Octokit;
|
||||
getSignal: () => AbortSignal | undefined;
|
||||
} => {
|
||||
let signal: AbortSignal | undefined;
|
||||
const client = {
|
||||
actions: {
|
||||
downloadJobLogsForWorkflowRun: (params: {
|
||||
request?: { signal?: AbortSignal };
|
||||
}) => {
|
||||
signal = params.request?.signal;
|
||||
return new Promise((_resolve, reject) => {
|
||||
signal?.addEventListener("abort", () => {
|
||||
reject(new Error("This operation was aborted"));
|
||||
});
|
||||
// Otherwise never settles, simulating a stalled fetch.
|
||||
});
|
||||
},
|
||||
},
|
||||
} as unknown as Octokit;
|
||||
return { client, getSignal: () => signal };
|
||||
};
|
||||
|
||||
test("rejects with a timeout instead of hanging when the download stalls", async () => {
|
||||
const { client, getSignal } = createStallingClient();
|
||||
const runnerTemp = makeRunnerTemp();
|
||||
|
||||
await expect(
|
||||
downloadJobLog(
|
||||
client,
|
||||
{ owner: "owner", repo: "repo", job_id: 123 },
|
||||
runnerTemp,
|
||||
5,
|
||||
),
|
||||
).rejects.toThrow();
|
||||
|
||||
expect(getSignal()?.aborted).toBe(true);
|
||||
});
|
||||
|
||||
test("writes the log to disk and clears the timeout when the download succeeds", async () => {
|
||||
const runnerTemp = makeRunnerTemp();
|
||||
const client = {
|
||||
actions: {
|
||||
downloadJobLogsForWorkflowRun: async (params: {
|
||||
request?: { signal?: AbortSignal };
|
||||
}) => {
|
||||
expect(params.request?.signal?.aborted).toBe(false);
|
||||
return { data: "log line 1\nlog line 2\n" };
|
||||
},
|
||||
},
|
||||
} as unknown as Octokit;
|
||||
|
||||
const result = await downloadJobLog(
|
||||
client,
|
||||
{ owner: "owner", repo: "repo", job_id: 456 },
|
||||
runnerTemp,
|
||||
30_000,
|
||||
);
|
||||
|
||||
expect(result.path).toBe(`${runnerTemp}/github-ci-logs/job-456.log`);
|
||||
expect(result.size_bytes).toBe(
|
||||
Buffer.byteLength("log line 1\nlog line 2\n", "utf-8"),
|
||||
);
|
||||
|
||||
const written = await readFile(result.path, "utf-8");
|
||||
expect(written).toBe("log line 1\nlog line 2\n");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { join } from "node:path";
|
||||
|
||||
// The GitHub client reads GITHUB_API_URL / GITHUB_GRAPHQL_URL when
|
||||
// `src/github/api/config.ts` is first imported, so we cannot flip env vars
|
||||
// between cases inside a single process. Instead each case runs the real
|
||||
// `createOctokit` factory in a fresh Bun process (test/fixtures/graphql-endpoint-probe.ts)
|
||||
// with a stubbed fetch that reports the FINAL wire URL and Authorization header.
|
||||
//
|
||||
// This is the level that matters: @octokit/graphql derives the GraphQL endpoint
|
||||
// from its baseUrl AFTER construction (rewriting a REST ".../api/v3" base to
|
||||
// ".../api/graphql", and otherwise appending "/graphql"), so a constructor-option
|
||||
// assertion would not catch a regression.
|
||||
|
||||
const PROBE = join(import.meta.dir, "fixtures", "graphql-endpoint-probe.ts");
|
||||
|
||||
type ProbeResult = {
|
||||
graphqlUrl: string;
|
||||
graphqlAuth: string | null;
|
||||
restUrl: string;
|
||||
restAuth: string | null;
|
||||
};
|
||||
|
||||
function probe(env: Record<string, string>): ProbeResult {
|
||||
const result = Bun.spawnSync({
|
||||
cmd: ["bun", "run", PROBE],
|
||||
env: {
|
||||
...process.env,
|
||||
// Start from a clean slate so the host's own env cannot leak in.
|
||||
GITHUB_API_URL: "",
|
||||
GITHUB_GRAPHQL_URL: "",
|
||||
...env,
|
||||
},
|
||||
stdout: "pipe",
|
||||
stderr: "pipe",
|
||||
});
|
||||
|
||||
if (result.exitCode !== 0) {
|
||||
throw new Error(
|
||||
`probe failed (exit ${result.exitCode}): ${result.stderr.toString()}`,
|
||||
);
|
||||
}
|
||||
|
||||
return JSON.parse(result.stdout.toString().trim()) as ProbeResult;
|
||||
}
|
||||
|
||||
describe("GitHub API client endpoint routing", () => {
|
||||
test("both env vars unset: REST and GraphQL use github.com", () => {
|
||||
const r = probe({});
|
||||
expect(r.restUrl).toBe("https://api.github.com/meta");
|
||||
expect(r.graphqlUrl).toBe("https://api.github.com/graphql");
|
||||
});
|
||||
|
||||
test("GITHUB_API_URL alone (GHES): GraphQL still resolves to /api/graphql", () => {
|
||||
// Regression guard: @octokit/graphql rewrites a ".../api/v3" REST base to
|
||||
// ".../api/graphql", so GraphQL must keep working when only GITHUB_API_URL
|
||||
// is provided (e.g. under `act` or partial configs).
|
||||
const r = probe({ GITHUB_API_URL: "https://ghe.example.test/api/v3" });
|
||||
expect(r.restUrl).toBe("https://ghe.example.test/api/v3/meta");
|
||||
expect(r.graphqlUrl).toBe("https://ghe.example.test/api/graphql");
|
||||
});
|
||||
|
||||
test("GITHUB_GRAPHQL_URL alone: GraphQL honors it exactly, REST stays public", () => {
|
||||
const r = probe({
|
||||
GITHUB_GRAPHQL_URL: "https://ghe.example.test/api/graphql",
|
||||
});
|
||||
expect(r.graphqlUrl).toBe("https://ghe.example.test/api/graphql");
|
||||
expect(r.restUrl).toBe("https://api.github.com/meta");
|
||||
});
|
||||
|
||||
test("both set to standard GHES values: REST and GraphQL route independently", () => {
|
||||
const r = probe({
|
||||
GITHUB_API_URL: "https://ghe.example.test/api/v3",
|
||||
GITHUB_GRAPHQL_URL: "https://ghe.example.test/api/graphql",
|
||||
});
|
||||
expect(r.restUrl).toBe("https://ghe.example.test/api/v3/meta");
|
||||
expect(r.graphqlUrl).toBe("https://ghe.example.test/api/graphql");
|
||||
});
|
||||
|
||||
test("GITHUB_GRAPHQL_URL wins over a GITHUB_API_URL-derived endpoint", () => {
|
||||
// Distinguishing case: without honoring GITHUB_GRAPHQL_URL, GraphQL would be
|
||||
// derived from GITHUB_API_URL and hit the wrong host.
|
||||
const r = probe({
|
||||
GITHUB_API_URL: "https://ghe.example.test/api/v3",
|
||||
GITHUB_GRAPHQL_URL: "https://gql.example.test/api/graphql",
|
||||
});
|
||||
expect(r.graphqlUrl).toBe("https://gql.example.test/api/graphql");
|
||||
expect(r.restUrl).toBe("https://ghe.example.test/api/v3/meta");
|
||||
});
|
||||
|
||||
test("trailing slash on GITHUB_GRAPHQL_URL is normalized", () => {
|
||||
const r = probe({
|
||||
GITHUB_GRAPHQL_URL: "https://ghe.example.test/api/graphql/",
|
||||
});
|
||||
expect(r.graphqlUrl).toBe("https://ghe.example.test/api/graphql");
|
||||
});
|
||||
|
||||
test("GITHUB_GRAPHQL_URL without a /graphql suffix is preserved before the client appends one", () => {
|
||||
const r = probe({
|
||||
GITHUB_GRAPHQL_URL: "https://gql.example.test/custom",
|
||||
});
|
||||
expect(r.graphqlUrl).toBe("https://gql.example.test/custom/graphql");
|
||||
});
|
||||
|
||||
test("a base already ending in /graphql is not doubled", () => {
|
||||
const r = probe({
|
||||
GITHUB_GRAPHQL_URL: "https://gql.example.test/api/graphql",
|
||||
});
|
||||
expect(r.graphqlUrl).not.toContain("/graphql/graphql");
|
||||
expect(r.graphqlUrl).toBe("https://gql.example.test/api/graphql");
|
||||
});
|
||||
|
||||
test("the token authorization header is preserved on both clients", () => {
|
||||
const r = probe({
|
||||
GITHUB_API_URL: "https://ghe.example.test/api/v3",
|
||||
GITHUB_GRAPHQL_URL: "https://ghe.example.test/api/graphql",
|
||||
});
|
||||
expect(r.graphqlAuth).toBe("token test-token");
|
||||
expect(r.restAuth).toBe("token test-token");
|
||||
});
|
||||
});
|
||||
@@ -148,7 +148,9 @@ describe("downloadCommentImages", () => {
|
||||
mediaType: { format: "full+json" },
|
||||
});
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalledWith(signedUrl);
|
||||
expect(fetchSpy).toHaveBeenCalledWith(signedUrl, {
|
||||
signal: expect.any(AbortSignal),
|
||||
});
|
||||
expect(fsWriteFileSpy).toHaveBeenCalledWith(
|
||||
"/tmp/github-images/image-1704067200000-0.png",
|
||||
Buffer.from(mockArrayBuffer),
|
||||
@@ -481,8 +483,12 @@ describe("downloadCommentImages", () => {
|
||||
);
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalledTimes(2);
|
||||
expect(fetchSpy).toHaveBeenNthCalledWith(1, signedUrl1);
|
||||
expect(fetchSpy).toHaveBeenNthCalledWith(2, signedUrl2);
|
||||
expect(fetchSpy).toHaveBeenNthCalledWith(1, signedUrl1, {
|
||||
signal: expect.any(AbortSignal),
|
||||
});
|
||||
expect(fetchSpy).toHaveBeenNthCalledWith(2, signedUrl2, {
|
||||
signal: expect.any(AbortSignal),
|
||||
});
|
||||
expect(result.get(imageUrl1)).toBe(
|
||||
"/tmp/github-images/image-1704067200000-0.png",
|
||||
);
|
||||
@@ -523,7 +529,9 @@ describe("downloadCommentImages", () => {
|
||||
comments,
|
||||
);
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalledWith(signedUrl);
|
||||
expect(fetchSpy).toHaveBeenCalledWith(signedUrl, {
|
||||
signal: expect.any(AbortSignal),
|
||||
});
|
||||
expect(result.get(imageUrl)).toBe(
|
||||
"/tmp/github-images/image-1704067200000-0.png",
|
||||
);
|
||||
@@ -766,6 +774,95 @@ describe("downloadCommentImages", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("should skip an image when the fetch times out", async () => {
|
||||
const mockOctokit = createMockOctokit();
|
||||
const imageUrl = assetUrl(GUID_1);
|
||||
const signedUrl = signedUrlFor(GUID_1, ".png");
|
||||
let signal: AbortSignal | null | undefined;
|
||||
|
||||
// @ts-expect-error Mock implementation doesn't match full type signature
|
||||
mockOctokit.rest.issues.getComment = jest.fn().mockResolvedValue({
|
||||
data: {
|
||||
body_html: `<img src="${signedUrl}">`,
|
||||
},
|
||||
});
|
||||
|
||||
fetchSpy = spyOn(global, "fetch");
|
||||
fetchSpy.mockImplementation((_input: unknown, init?: RequestInit) => {
|
||||
signal = init?.signal;
|
||||
return new Promise<Response>(() => {});
|
||||
});
|
||||
|
||||
const result = await downloadCommentImages(
|
||||
mockOctokit,
|
||||
"owner",
|
||||
"repo",
|
||||
[
|
||||
{
|
||||
type: "issue_comment",
|
||||
id: "445",
|
||||
body: `Stalled image: `,
|
||||
},
|
||||
],
|
||||
{ timeoutMs: 5 },
|
||||
);
|
||||
|
||||
expect(result.size).toBe(0);
|
||||
expect(signal?.aborted).toBe(true);
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining("Failed to download"),
|
||||
expect.objectContaining({
|
||||
message: "Image download timed out after 5ms",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test("should time out while reading a response body", async () => {
|
||||
const mockOctokit = createMockOctokit();
|
||||
const imageUrl = assetUrl(GUID_1);
|
||||
const signedUrl = signedUrlFor(GUID_1, ".png");
|
||||
let signal: AbortSignal | null | undefined;
|
||||
|
||||
// @ts-expect-error Mock implementation doesn't match full type signature
|
||||
mockOctokit.rest.issues.getComment = jest.fn().mockResolvedValue({
|
||||
data: {
|
||||
body_html: `<img src="${signedUrl}">`,
|
||||
},
|
||||
});
|
||||
|
||||
fetchSpy = spyOn(global, "fetch");
|
||||
fetchSpy.mockImplementation((_input: unknown, init?: RequestInit) => {
|
||||
signal = init?.signal;
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
arrayBuffer: () => new Promise<ArrayBuffer>(() => {}),
|
||||
} as Response);
|
||||
});
|
||||
|
||||
const result = await downloadCommentImages(
|
||||
mockOctokit,
|
||||
"owner",
|
||||
"repo",
|
||||
[
|
||||
{
|
||||
type: "issue_comment",
|
||||
id: "446",
|
||||
body: `Stalled body: `,
|
||||
},
|
||||
],
|
||||
{ timeoutMs: 5 },
|
||||
);
|
||||
|
||||
expect(result.size).toBe(0);
|
||||
expect(signal?.aborted).toBe(true);
|
||||
expect(consoleErrorSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining("Failed to download"),
|
||||
expect.objectContaining({
|
||||
message: "Image download timed out after 5ms",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test("should handle API errors gracefully", async () => {
|
||||
const mockOctokit = createMockOctokit();
|
||||
const imageUrl = assetUrl(GUID_1);
|
||||
@@ -936,7 +1033,9 @@ describe("downloadCommentImages", () => {
|
||||
mediaType: { format: "full+json" },
|
||||
});
|
||||
|
||||
expect(fetchSpy).toHaveBeenCalledWith(signedUrl);
|
||||
expect(fetchSpy).toHaveBeenCalledWith(signedUrl, {
|
||||
signal: expect.any(AbortSignal),
|
||||
});
|
||||
expect(fsWriteFileSpy).toHaveBeenCalledWith(
|
||||
"/tmp/github-images/image-1704067200000-0.png",
|
||||
Buffer.from(mockArrayBuffer),
|
||||
|
||||
@@ -354,4 +354,102 @@ describe("prepareMcpConfig", () => {
|
||||
const parsed = JSON.parse(result);
|
||||
expect(parsed.mcpServers.github_ci).not.toBeDefined();
|
||||
});
|
||||
|
||||
test("should include github MCP server when mcp__github shorthand is used", async () => {
|
||||
const result = await prepareMcpConfig({
|
||||
githubToken: "test-token",
|
||||
owner: "test-owner",
|
||||
repo: "test-repo",
|
||||
branch: "test-branch",
|
||||
baseBranch: "main",
|
||||
allowedTools: ["mcp__github"],
|
||||
mode: "agent",
|
||||
context: mockContext,
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
expect(parsed.mcpServers.github).toBeDefined();
|
||||
expect(parsed.mcpServers.github.command).toBe("docker");
|
||||
expect(parsed.mcpServers.github.env.GITHUB_PERSONAL_ACCESS_TOKEN).toBe(
|
||||
"test-token",
|
||||
);
|
||||
});
|
||||
|
||||
test("should include inline comment server when mcp__github_inline_comment shorthand is used", async () => {
|
||||
const result = await prepareMcpConfig({
|
||||
githubToken: "test-token",
|
||||
owner: "test-owner",
|
||||
repo: "test-repo",
|
||||
branch: "test-branch",
|
||||
baseBranch: "main",
|
||||
allowedTools: ["mcp__github_inline_comment"],
|
||||
mode: "agent",
|
||||
context: mockPRContext,
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
expect(parsed.mcpServers.github_inline_comment).toBeDefined();
|
||||
expect(parsed.mcpServers.github_inline_comment.env.GITHUB_TOKEN).toBe(
|
||||
"test-token",
|
||||
);
|
||||
expect(parsed.mcpServers.github_inline_comment.env.PR_NUMBER).toBe("456");
|
||||
});
|
||||
|
||||
test("should include comment server in agent mode when mcp__github_comment shorthand is used", async () => {
|
||||
const result = await prepareMcpConfig({
|
||||
githubToken: "test-token",
|
||||
owner: "test-owner",
|
||||
repo: "test-repo",
|
||||
branch: "test-branch",
|
||||
baseBranch: "main",
|
||||
allowedTools: ["mcp__github_comment"],
|
||||
mode: "agent",
|
||||
context: mockContext,
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
expect(parsed.mcpServers.github_comment).toBeDefined();
|
||||
expect(parsed.mcpServers.github_comment.env.GITHUB_TOKEN).toBe(
|
||||
"test-token",
|
||||
);
|
||||
});
|
||||
|
||||
test("should include CI server in agent mode when mcp__github_ci shorthand is used", async () => {
|
||||
process.env.DEFAULT_WORKFLOW_TOKEN = "workflow-token";
|
||||
|
||||
const result = await prepareMcpConfig({
|
||||
githubToken: "test-token",
|
||||
owner: "test-owner",
|
||||
repo: "test-repo",
|
||||
branch: "test-branch",
|
||||
baseBranch: "main",
|
||||
allowedTools: ["mcp__github_ci"],
|
||||
mode: "agent",
|
||||
context: mockPRContext,
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
expect(parsed.mcpServers.github_ci).toBeDefined();
|
||||
expect(parsed.mcpServers.github_ci.env.GITHUB_TOKEN).toBe("workflow-token");
|
||||
expect(parsed.mcpServers.github_ci.env.PR_NUMBER).toBe("456");
|
||||
|
||||
delete process.env.DEFAULT_WORKFLOW_TOKEN;
|
||||
});
|
||||
|
||||
test("should not include github MCP server when unrelated tool is specified", async () => {
|
||||
const result = await prepareMcpConfig({
|
||||
githubToken: "test-token",
|
||||
owner: "test-owner",
|
||||
repo: "test-repo",
|
||||
branch: "test-branch",
|
||||
baseBranch: "main",
|
||||
allowedTools: ["Bash", "Read", "Grep"],
|
||||
mode: "agent",
|
||||
context: mockContext,
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(result);
|
||||
expect(parsed.mcpServers.github).not.toBeDefined();
|
||||
expect(parsed.mcpServers.github_inline_comment).not.toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, expect, it } from "bun:test";
|
||||
import { redactSecrets, sanitizeContent } from "../src/github/utils/sanitizer";
|
||||
|
||||
describe("Public Comment Output Sanitization & Redaction", () => {
|
||||
it("redacts all credential types from public comment output", () => {
|
||||
const rawComment = [
|
||||
"Here is the summary of the work done:",
|
||||
"- GitHub Token: ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890",
|
||||
"- Anthropic Key: sk-ant-api03-abcdefghijklmnopqrstuvwxyz1234567890",
|
||||
"- AWS Access Key: AKIAIOSFODNN7EXAMPLE",
|
||||
"- Slack Bot Token: xoxb-1234567890-abcdefghijkl-mnopqrstuvwx",
|
||||
"- JWT Bearer: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U",
|
||||
"<!-- Hidden instruction injection -->",
|
||||
"Invisible\u200Bzero-width chars",
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
const sanitizedOutput = redactSecrets(sanitizeContent(rawComment));
|
||||
|
||||
// Ensure all secret types are redacted
|
||||
expect(sanitizedOutput).not.toContain(
|
||||
"ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890",
|
||||
);
|
||||
expect(sanitizedOutput).not.toContain(
|
||||
"sk-ant-api03-abcdefghijklmnopqrstuvwxyz1234567890",
|
||||
);
|
||||
expect(sanitizedOutput).not.toContain("AKIAIOSFODNN7EXAMPLE");
|
||||
expect(sanitizedOutput).not.toContain(
|
||||
"xoxb-1234567890-abcdefghijkl-mnopqrstuvwx",
|
||||
);
|
||||
expect(sanitizedOutput).not.toContain(
|
||||
"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U",
|
||||
);
|
||||
|
||||
expect(sanitizedOutput).toContain("[REDACTED_GITHUB_TOKEN]");
|
||||
expect(sanitizedOutput).toContain("[REDACTED_ANTHROPIC_KEY]");
|
||||
expect(sanitizedOutput).toContain("[REDACTED_AWS_KEY_ID]");
|
||||
expect(sanitizedOutput).toContain("[REDACTED_SLACK_TOKEN]");
|
||||
expect(sanitizedOutput).toContain("[REDACTED_JWT]");
|
||||
|
||||
// Ensure prompt injection / invisible chars / hidden tags are also sanitized
|
||||
expect(sanitizedOutput).not.toContain(
|
||||
"<!-- Hidden instruction injection -->",
|
||||
);
|
||||
expect(sanitizedOutput).not.toContain("\u200B");
|
||||
expect(sanitizedOutput).not.toContain("Image Alt Injection");
|
||||
expect(sanitizedOutput).toContain("");
|
||||
});
|
||||
|
||||
it("ensures public comments have the same secret redaction coverage as logs/errors", () => {
|
||||
const errorDetails =
|
||||
"Error: failed to connect with sk-ant-abcdefghijklmnopqrstuvwxyz123456 and AKIAIOSFODNN7EXAMPLE";
|
||||
const commentBody =
|
||||
"Report: encountered sk-ant-abcdefghijklmnopqrstuvwxyz123456 and AKIAIOSFODNN7EXAMPLE";
|
||||
|
||||
const redactedError = redactSecrets(errorDetails);
|
||||
const redactedComment = redactSecrets(sanitizeContent(commentBody));
|
||||
|
||||
expect(redactedError).toContain("[REDACTED_ANTHROPIC_KEY]");
|
||||
expect(redactedError).toContain("[REDACTED_AWS_KEY_ID]");
|
||||
expect(redactedComment).toContain("[REDACTED_ANTHROPIC_KEY]");
|
||||
expect(redactedComment).toContain("[REDACTED_AWS_KEY_ID]");
|
||||
});
|
||||
});
|
||||
@@ -394,6 +394,37 @@ describe("restoreConfigFromBase", () => {
|
||||
expect(countClaudePrExcludeEntries()).toBe(1);
|
||||
});
|
||||
|
||||
test("leaves a full checkout unshallow so base..HEAD stays scoped to the PR", () => {
|
||||
// The damage only shows up once base has moved on since the PR branched:
|
||||
// the merge base is then an older commit that a depth-limited fetch of base
|
||||
// truncates away, and every base..HEAD comparison silently changes meaning.
|
||||
git(["checkout", "main"]);
|
||||
writeRepoFile("src/other.ts", "export const advanced = true;\n");
|
||||
git(["add", "src/other.ts"]);
|
||||
git(["commit", "-m", "base advance"]);
|
||||
git(["push", "origin", "main"]);
|
||||
git(["checkout", "pr"]);
|
||||
|
||||
expect(git(["rev-parse", "--is-shallow-repository"]).trim()).toBe("false");
|
||||
const mergeBaseBefore = git(["merge-base", "origin/main", "HEAD"]).trim();
|
||||
|
||||
restoreConfigFromBase("main");
|
||||
|
||||
expect(git(["rev-parse", "--is-shallow-repository"]).trim()).toBe("false");
|
||||
expect(git(["merge-base", "origin/main", "HEAD"]).trim()).toBe(
|
||||
mergeBaseBefore,
|
||||
);
|
||||
// These are the two commands the prompt tells Claude to run to scope its
|
||||
// work to the PR: the log range must not pick up already-merged commits,
|
||||
// and the three-dot diff must still resolve a merge base at all.
|
||||
expect(git(["log", "--format=%s", "origin/main..HEAD"]).trim()).toBe(
|
||||
"pr config",
|
||||
);
|
||||
expect(
|
||||
git(["diff", "--name-only", "origin/main...HEAD"]).trim().split("\n"),
|
||||
).toEqual([".claude/settings.json", "CLAUDE.md"]);
|
||||
});
|
||||
|
||||
function git(args: string[]): string {
|
||||
return execFileSync("git", args, {
|
||||
cwd: repoDir,
|
||||
|
||||
@@ -518,3 +518,28 @@ describe("stripHtmlComments (legacy)", () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("outbound comment sanitization and redaction", () => {
|
||||
it("should sanitize content and redact all credential types for public comments", () => {
|
||||
const rawComment =
|
||||
"Done! Configured AWS AKIAIOSFODNN7EXAMPLE, Anthropic sk-ant-api03-abcdefghijklmnopqrstuvwxyz1234567890, Slack xoxb-1234567890-abcdefghijkl-mnopqrstuvwx, and GitHub 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 <!-- secret note -->";
|
||||
const sanitizedAndRedacted = redactSecrets(sanitizeContent(rawComment));
|
||||
|
||||
expect(sanitizedAndRedacted).not.toContain("AKIAIOSFODNN7EXAMPLE");
|
||||
expect(sanitizedAndRedacted).not.toContain(
|
||||
"sk-ant-api03-abcdefghijklmnopqrstuvwxyz1234567890",
|
||||
);
|
||||
expect(sanitizedAndRedacted).not.toContain(
|
||||
"xoxb-1234567890-abcdefghijkl-mnopqrstuvwx",
|
||||
);
|
||||
expect(sanitizedAndRedacted).not.toContain(
|
||||
"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",
|
||||
);
|
||||
expect(sanitizedAndRedacted).not.toContain("secret note");
|
||||
|
||||
expect(sanitizedAndRedacted).toContain("[REDACTED_AWS_KEY_ID]");
|
||||
expect(sanitizedAndRedacted).toContain("[REDACTED_ANTHROPIC_KEY]");
|
||||
expect(sanitizedAndRedacted).toContain("[REDACTED_SLACK_TOKEN]");
|
||||
expect(sanitizedAndRedacted).toContain("[REDACTED_GITHUB_TOKEN]");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -29,6 +29,15 @@ describe("validateBranchName", () => {
|
||||
expect(() => validateBranchName("release.1.2.3")).not.toThrow();
|
||||
});
|
||||
|
||||
it("should accept branch names containing parentheses", () => {
|
||||
expect(() =>
|
||||
validateBranchName("feat(example)-valid-branch"),
|
||||
).not.toThrow();
|
||||
expect(() =>
|
||||
validateBranchName("fix(parser)-handle-empty-input"),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it("should accept typical branch name formats", () => {
|
||||
expect(() =>
|
||||
validateBranchName("claude/issue-123-20250101-1234"),
|
||||
|
||||
Reference in New Issue
Block a user