chore(claude): close remaining gaps in the merge gate
Checks / Secret Scan (pull_request) Successful in 8s
Checks / Lint (pull_request) Successful in 9s

Gitea's issue comments endpoint ignores paging, so the hook now reads all
comments in one call; the paged loop refused every merge. Any command that
calls gitea.sh and mentions a merge must now be the strict form as a whole,
while commands that only name gitea.sh as a file (git add, git diff) pass.
The body may only pin the head commit, and curl calls have time limits so
the hook can't time out into a non-blocking error.
This commit is contained in:
kasun committed 2026-11-27 03:57:18 +01:00
1 parent f45fb7421a
commit 1e02dd5930
4 files changed
+54 -30

No files matched your search

+47 -27
View File
@@ -4,14 +4,19 @@
# #
# Why: the /merge skill tells Claude to review before merging. This hook makes # Why: the /merge skill tells Claude to review before merging. This hook makes
# skipping the review, or merging after new commits made a review stale, fail # skipping the review, or merging after new commits made a review stale, fail
# instead of relying on the instruction alone. It can't check that the review # instead of relying on the instruction alone.
# behind a marker was done properly. The ask rule for merges in
# .claude/settings.json stays as a second layer, so every merge also prompts.
# #
# A merge must be exactly one command of the form # A merge must be exactly one command of the form
# .claude/scripts/gitea.sh POST /repos/OWNER/REPO/pulls/N/merge @FILE # .claude/scripts/gitea.sh POST /repos/OWNER/REPO/pulls/N/merge @/abs/file.json
# where FILE pins head_commit_id. Any other write call whose path mentions # where the file is exactly {"Do":"merge","head_commit_id":"<head sha>"}.
# "merge", or a path it can't read safely, is refused. # Any other command that calls gitea.sh and mentions "merg" (outside @file
# names) is refused, as are gitea.sh write calls with a path that isn't plain.
# Commands that only name gitea.sh as a file (git add, git diff) pass.
#
# Limits: this catches mistakes and shortcuts, not a deliberate workaround such
# as a script that merges on its own. The ask rule for merges in
# .claude/settings.json and the required checks on the server are the other
# layers. It also can't check that the review behind a marker was done properly.
# #
# Fails closed: exit 2 blocks the tool call, and any unexpected error ends in # Fails closed: exit 2 blocks the tool call, and any unexpected error ends in
# exit 2 too, because Claude Code treats other exit codes as non-blocking. # exit 2 too, because Claude Code treats other exit codes as non-blocking.
@@ -25,58 +30,73 @@ trap 'rc=$?; if [[ $rc -ne 0 && $rc -ne 2 ]]; then echo "Merge refused: guard-me
input=$(cat) input=$(cat)
# Most commands mention neither a merge nor gitea.sh; let them through before parsing. # Most commands mention neither a merge nor gitea.sh; let them through before parsing.
grep -qiE 'merge|gitea\.sh' <<<"$input" || exit 0 grep -qiE 'merg|gitea\.sh' <<<"$input" || exit 0
cmd=$(jq -r '.tool_input.command // empty' <<<"$input") || deny "could not read the hook input" cmd=$(jq -r '.tool_input.command // empty' <<<"$input") || deny "could not read the hook input"
[[ -z $cmd ]] && exit 0 [[ -z $cmd ]] && exit 0
shopt -s nocasematch shopt -s nocasematch
# Merges go through gitea.sh only. # Merges go through gitea.sh only.
if [[ $cmd =~ (curl|wget|http) && $cmd =~ /api/v1 && $cmd =~ merge ]]; then if [[ $cmd =~ (curl|wget|http) && $cmd =~ /api/v1 && $cmd =~ merg ]]; then
deny "merge PRs through .claude/scripts/gitea.sh, not curl or wget" deny "merge PRs through .claude/scripts/gitea.sh, not curl or wget"
fi fi
# Find gitea.sh write calls. Their path must be a plain literal so it can't # Only commands that call gitea.sh matter. A call is gitea.sh at the start of a
# hide a merge (variables, dot segments, encoding). Legitimate calls never need more. # command (after ; & | ( a backtick, quote or newline) or after a launcher such
# as xargs or bash. As a plain argument (git add -- .claude/scripts/gitea.sh)
# it is just a file name.
flat=${cmd//$'\n'/;}
launcher='(xargs|env|sh|bash|zsh|exec|command|nohup|time|timeout|sudo|nice|eval)'
call_re="(^|[;&|(\`\"'\$])[[:space:]]*[^[:space:];&|]*gitea\.sh|(^|[[:space:];&|(])${launcher}([[:space:]]+[^[:space:];&|]+)*[[:space:]]+[^[:space:];&|]*gitea\.sh"
[[ $flat =~ $call_re ]] || exit 0
# File names may contain "merge" (e.g. a PR body file); everything else may not,
# unless the whole command is the strict merge form checked below.
without_files=$(sed -E 's/@[^[:space:]]+//g' <<<"$cmd")
if ! [[ $without_files =~ merg ]]; then
# Not a merge. Write calls still need a plain path, so nothing can hide in it.
write_re="gitea\.sh[\"']?[[:space:]]+[\"']?(POST|PUT|PATCH|DELETE)[\"']?[[:space:]]+[\"']?([^[:space:]\"']*)" write_re="gitea\.sh[\"']?[[:space:]]+[\"']?(POST|PUT|PATCH|DELETE)[\"']?[[:space:]]+[\"']?([^[:space:]\"']*)"
[[ $cmd =~ $write_re ]] || exit 0 if [[ $cmd =~ $write_re ]]; then
path="${BASH_REMATCH[2]}" path="${BASH_REMATCH[2]}"
safe_path='^/[A-Za-z0-9_/?=&-]+$' safe_path='^/[A-Za-z0-9_/?=&-]+$'
if ! [[ $path =~ $safe_path ]] || [[ $path == *//* ]]; then if ! [[ $path =~ $safe_path ]] || [[ $path == *//* ]]; then
deny "gitea.sh write call with a path that isn't plain ($path)" deny "gitea.sh write call with a path that isn't plain ($path)"
fi fi
[[ $path =~ merge ]] || exit 0 fi
exit 0
fi
shopt -u nocasematch shopt -u nocasematch
strict_re='^(\.claude/scripts/|/[^[:space:]]*/\.claude/scripts/)gitea\.sh POST (/repos/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)/pulls/([0-9]+)/merge @([^[:space:];&|<>`$]+)$' strict_re='^(\.claude/scripts/|/[^[:space:]]*/\.claude/scripts/)gitea\.sh POST (/repos/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+)/pulls/([0-9]+)/merge @(/[^[:space:];&|<>`$]+)$'
[[ $cmd =~ $strict_re ]] \ [[ $cmd =~ $strict_re ]] \
|| deny "a merge must be the single command '.claude/scripts/gitea.sh POST /repos/OWNER/REPO/pulls/N/merge @FILE'" || deny "a merge must be the single command '.claude/scripts/gitea.sh POST /repos/OWNER/REPO/pulls/N/merge @/absolute/body.json'"
repo="${BASH_REMATCH[2]}" repo="${BASH_REMATCH[2]}"
pr="${BASH_REMATCH[3]}" pr="${BASH_REMATCH[3]}"
body_file="${BASH_REMATCH[4]}" body_file="${BASH_REMATCH[4]}"
jq -e 'type == "object" and keys == ["Do", "head_commit_id"] and .Do == "merge"' "$body_file" >/dev/null 2>&1 \
|| deny "the merge body must be exactly {\"Do\":\"merge\",\"head_commit_id\":\"<sha>\"}"
gitea="${CLAUDE_PROJECT_DIR:?}/.claude/scripts/gitea.sh" gitea="${CLAUDE_PROJECT_DIR:?}/.claude/scripts/gitea.sh"
pr_json=$("$gitea" GET "$repo/pulls/$pr" 2>/dev/null) || deny "could not read PR #$pr" pr_json=$("$gitea" GET "$repo/pulls/$pr" 2>/dev/null) || deny "could not read PR #$pr"
sha=$(jq -r '.head.sha // empty' <<<"$pr_json" 2>/dev/null) || deny "could not parse PR #$pr" sha=$(jq -r '.head.sha // empty' <<<"$pr_json" 2>/dev/null) || deny "could not parse PR #$pr"
[[ $sha =~ ^[0-9a-f]{40}$ ]] || deny "could not read the head commit of PR #$pr" [[ $sha =~ ^[0-9a-f]{40}$ ]] || deny "could not read the head commit of PR #$pr"
pinned=$(jq -r '.head_commit_id // empty' "$body_file" 2>/dev/null) || deny "could not read $body_file" pinned=$(jq -r '.head_commit_id' "$body_file")
[[ $pinned == "$sha" ]] || deny "head_commit_id ($pinned) is not the PR's head commit ($sha)" [[ $pinned == "$sha" ]] || deny "head_commit_id ($pinned) is not the PR's head commit ($sha)"
# Collect all comments (oldest first) so the newest marker is really the newest. # This endpoint returns all comments of the issue and ignores page/limit.
comments='[]' comments=$("$gitea" GET "$repo/issues/$pr/comments" 2>/dev/null) || deny "could not read the comments of PR #$pr"
for page in 1 2 3 4 5 6 7 8 9 10; do jq -e 'type == "array"' <<<"$comments" >/dev/null 2>&1 || deny "could not parse the comments of PR #$pr"
batch=$("$gitea" GET "$repo/issues/$pr/comments?page=$page&limit=50" 2>/dev/null) \
|| deny "could not read the comments of PR #$pr"
count=$(jq 'length' <<<"$batch" 2>/dev/null) || deny "could not parse the comments of PR #$pr"
[[ $count -eq 0 ]] && break
comments=$(jq -s 'add' <(echo "$comments") <(echo "$batch")) || deny "could not merge comment pages"
[[ $page -eq 10 ]] && deny "PR #$pr has too many comments to check"
done
latest=$(jq -r '[.[] | select(.user.login == "claude-bot" and (.body | startswith("<!-- claude-review: ")))] reviews='[.[] | select(.user.login == "claude-bot" and (.body | startswith("<!-- claude-review: ")))]'
| sort_by(.created_at, .id) | last | .body // "" | split("\n")[0]' <<<"$comments") \ # An edited review would keep its old position, so edits aren't accepted at all.
jq -e "$reviews | all(.updated_at == .created_at)" <<<"$comments" >/dev/null \
|| deny "a review comment on PR #$pr was edited; post a new review instead"
latest=$(jq -r "$reviews | sort_by(.created_at, .id) | last | .body // \"\"
| (split(\"\n\")[0] // \"\") | sub(\"[[:space:]]+\$\"; \"\")" <<<"$comments") \
|| deny "could not read the review markers of PR #$pr" || deny "could not read the review markers of PR #$pr"
[[ $latest == "<!-- claude-review: pass $sha -->" ]] \ [[ $latest == "<!-- claude-review: pass $sha -->" ]] \
|| deny "the newest review of PR #$pr is not a pass for head commit $sha (found: ${latest:-none}). Run the review step of /merge first." || deny "the newest review of PR #$pr is not a pass for head commit $sha (found: ${latest:-none}). Run the review step of /merge first."
+2 -1
View File
@@ -68,7 +68,8 @@ done
url=$(<"$config/url") url=$(<"$config/url")
token=$(<"$config/token") token=$(<"$config/token")
args=(-sS --fail-with-body -X "$method" -H "Accept: application/json") # Time limits keep callers such as guard-merge.sh within their hook timeout.
args=(-sS --fail-with-body --connect-timeout 5 --max-time 20 -X "$method" -H "Accept: application/json")
# The token header is read from stdin so it never shows up in the process list. # The token header is read from stdin so it never shows up in the process list.
args+=(-H @-) args+=(-H @-)
if [[ -n "$body" ]]; then if [[ -n "$body" ]]; then
+2 -1
View File
@@ -98,7 +98,8 @@
}, },
{ {
"type": "command", "type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/guard-merge.sh" "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/guard-merge.sh",
"timeout": 90
} }
] ]
} }
+3 -1
View File
@@ -90,11 +90,13 @@ Then run `.claude/scripts/gitea.sh GET $REPO/pulls/<number>` and confirm `mergea
4. Run `.claude/scripts/gitea.sh POST $REPO/issues/<number>/comments @<json file>` with `{"body": "<comment>"}`. 4. Run `.claude/scripts/gitea.sh POST $REPO/issues/<number>/comments @<json file>` with `{"body": "<comment>"}`.
5. On `fail`, stop and report the important findings. Do not fix them in this run; the user decides. 5. On `fail`, stop and report the important findings. Do not fix them in this run; the user decides.
Never edit a review comment; post a new one. The merge hook refuses PRs with edited review comments.
Never write a `pass` marker for a SHA you did not review, or when an important finding is open. The merge hook only checks that the marker exists, so the honesty of the marker is on you. Never write a `pass` marker for a SHA you did not review, or when an important finding is open. The merge hook only checks that the marker exists, so the honesty of the marker is on you.
## 8. Merge ## 8. Merge
1. Run `.claude/scripts/gitea.sh POST $REPO/pulls/<number>/merge @<json file>` with `{"Do":"merge","head_commit_id":"<sha>"}`, so only the commit CI and the review checked can merge. Run it exactly in this form, alone. The `guard-merge.sh` hook refuses any other form, and refuses the call unless the newest review comment is a `pass` for this SHA. This call asks the user for permission: that prompt is the one intended pause of the run. If the user declines, stop. 1. Run `.claude/scripts/gitea.sh POST $REPO/pulls/<number>/merge @<absolute path of json file>` with exactly `{"Do":"merge","head_commit_id":"<sha>"}` and no other fields, so only the commit CI and the review checked can merge. Run it exactly in this form, alone. The `guard-merge.sh` hook refuses any other form, and refuses the call unless the newest review comment is a `pass` for this SHA. This call asks the user for permission: that prompt is the one intended pause of the run. If the user declines, stop.
2. Run `git fetch origin main:main`, then `git switch main`. 2. Run `git fetch origin main:main`, then `git switch main`.
## 9. Report ## 9. Report