From 737a3a29ecf449b05b001a04602b7908fdbbf4a1 Mon Sep 17 00:00:00 2001 From: kasun Date: Fri, 27 Nov 2026 03:27:38 +0100 Subject: [PATCH 1/3] chore(claude): add merge skill with review gate /merge takes changes from commit to merged PR in one run. A PreToolUse hook refuses any merge without a passing review comment for the PR's current head commit, so the review can't be skipped or go stale after new commits. --- .claude/hooks/guard-merge.sh | 52 ++++++++++++++++ .claude/settings.json | 5 +- .claude/skills/merge/SKILL.md | 109 ++++++++++++++++++++++++++++++++++ CLAUDE.md | 4 +- 4 files changed, 168 insertions(+), 2 deletions(-) create mode 100755 .claude/hooks/guard-merge.sh create mode 100644 .claude/skills/merge/SKILL.md diff --git a/.claude/hooks/guard-merge.sh b/.claude/hooks/guard-merge.sh new file mode 100755 index 0000000..67c2412 --- /dev/null +++ b/.claude/hooks/guard-merge.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +# PreToolUse hook for Bash: refuses a PR merge through gitea.sh unless the PR +# has a passing review comment for its current head commit. +# +# 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 +# instead of relying on the instruction alone. It checks that a claude-bot +# comment with `` exists and that the +# merge body pins `head_commit_id` to that same SHA. It can't check that the +# review behind the marker was done properly. +# +# Fails closed: if the PR or its comments can't be read, the merge is refused. +set -euo pipefail + +input=$(cat) +cmd=$(jq -r '.tool_input.command // empty' <<<"$input") + +merge_re="gitea\.sh[[:space:]]+POST[[:space:]]+[\"']?(/repos/[^/[:space:]]+/[^/[:space:]]+)/pulls/([0-9]+)/merge" +[[ $cmd =~ $merge_re ]] || exit 0 +repo="${BASH_REMATCH[1]}" +pr="${BASH_REMATCH[2]}" + +deny() { + jq -n --arg reason "Merge refused: $1" '{ + hookSpecificOutput: { + hookEventName: "PreToolUse", + permissionDecision: "deny", + permissionDecisionReason: $reason + } + }' + exit 0 +} + +gitea="$CLAUDE_PROJECT_DIR/.claude/scripts/gitea.sh" + +pr_json=$("$gitea" GET "$repo/pulls/$pr" 2>/dev/null) || deny "could not read PR #$pr" +sha=$(jq -r '.head.sha // empty' <<<"$pr_json") +[[ $sha =~ ^[0-9a-f]{40}$ ]] || deny "could not read the head commit of PR #$pr" + +body_re="[[:space:]]@([^[:space:]\"']+)" +[[ $cmd =~ $body_re ]] || deny "the merge body must be a file (@file) with head_commit_id" +body_file="${BASH_REMATCH[1]}" +pinned=$(jq -r '.head_commit_id // empty' "$body_file" 2>/dev/null) || deny "could not read $body_file" +[[ $pinned == "$sha" ]] || deny "head_commit_id ($pinned) is not the PR's head commit ($sha)" + +comments=$("$gitea" GET "$repo/issues/$pr/comments" 2>/dev/null) || deny "could not read the comments of PR #$pr" +marker="" +jq -e --arg m "$marker" 'any(.[]; .user.login == "claude-bot" and (.body | startswith($m)))' \ + <<<"$comments" >/dev/null \ + || deny "no passing review for head commit $sha. Run the review step of /merge first." + +exit 0 diff --git a/.claude/settings.json b/.claude/settings.json index 7b9405c..449af68 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -60,7 +60,6 @@ "Bash(pct *)", "Bash(qm *)", "Bash(curl *)", - "Bash(.claude/scripts/gitea.sh POST */merge*)", "Bash(.claude/scripts/gitea.sh PATCH *)", "Bash(.claude/scripts/gitea.sh PUT *)", "Bash(.claude/scripts/gitea.sh DELETE *)" @@ -95,6 +94,10 @@ { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/guard-live-infra.sh" + }, + { + "type": "command", + "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/guard-merge.sh" } ] } diff --git a/.claude/skills/merge/SKILL.md b/.claude/skills/merge/SKILL.md new file mode 100644 index 0000000..05904f1 --- /dev/null +++ b/.claude/skills/merge/SKILL.md @@ -0,0 +1,109 @@ +--- +name: merge +description: Commit the working tree changes that fit the branch, push, open a Gitea PR, wait for CI, review the PR with /code-review, and merge it, without stopping for confirmation. +argument-hint: [optional note on intent, or paths to limit the merge to] +disable-model-invocation: true +--- + +Take the working tree changes through commit, push, PR, review and merge in one run. If `$ARGUMENTS` names paths, include only those. If it describes intent, use it for the commit messages and PR. + +Typing `/merge` is the user's explicit instruction to commit, push, open a PR and merge these changes. It satisfies the "commit" and PR rules in `CLAUDE.md` for this run. Do not ask for confirmation, and do not pause to show drafts. Stop only for a condition under "Stop conditions". + +## Rules + +- Follow `CONVENTIONS.md` for branch names, commit messages and PR titles. The allowed commit scopes are in `.githooks/commit-msg`. +- Add no AI attribution to commits, PRs or comments. +- Never use `--no-verify`, force push, or commit directly to `main`. +- Never run `ansible`, `ansible-playbook` (not even `--check`), SSH or Docker commands. This skill changes git and Gitea only. +- Use `.claude/scripts/gitea.sh` for Gitea calls, because `gh` does not work here. `$REPO` below means `/repos/kasun/homelab-ansible`, and must be written out in full in each command. +- Never stage `vault.yml`, `.vault_pass*`, `.env` files, private keys, credentials, `.claude/settings.local.json` or `.venv/`. Leave them out, carry on, and mention them in the report. +- Write commit messages, JSON bodies and the review comment to files in the scratchpad directory with the Write tool. +- Run each command on its own, in the exact forms below, from the repo root. `cd` prefixes, pipes, loops and redirects cause permission prompts. + +## Stop conditions + +Stop and report only if: + +- HEAD is detached, or a merge or rebase is in progress. +- There are no changes and no unpushed commits. +- yamllint or ansible-lint fails. +- A file that looks like a secret is the only change. +- A commit hook, push or API call fails after one corrected retry of a message-format error. +- CI fails, or the PR is not mergeable. +- The review leaves an important finding open (step 7). +- The merge hook denies the merge. + +Leave the branch and PR in place when stopping after they exist, and say what is needed to continue. + +## 1. Inspect + +1. Run `git status`, `git diff --staged`, `git diff`, and `git log --oneline -5`. Read any untracked files that would be included. +2. Run `git fetch origin main`. +3. On a non-`main` branch, run `.claude/scripts/gitea.sh GET $REPO/pulls?state=open`. If this branch has an open PR, reuse it only for changes that serve its purpose. If all remaining changes are unrelated to it, take that PR through steps 6 to 8 first, which returns you to `main`, then continue with the remaining changes as new work. + +## 2. Group into commits + +Split by reason for the change, and decide without asking. Each commit should make sense and be revertable alone. + +- First decide the PR's purpose from `$ARGUMENTS`, the conversation, the branch name, or else the largest change. +- On the first `/merge`, leave out any change that does not serve that purpose. Keep it uncommitted and untouched, do not ask, and list it in the report. +- On a repeat `/merge`, meaning an earlier run this session left changes out or its PR is still open, handle all remaining changes in this run. Give each separate purpose its own branch and PR, and take them one at a time through steps 3 to 8, so each is merged and you are back on `main` before the next starts. If `$ARGUMENTS` names paths, handle only those. +- Use one commit when the remaining changes serve one purpose, and several when they are distinct steps toward it. +- Group whole files. If one file mixes purposes, put it in the commit for its main change. +- Scope: `ci` for `.gitea/workflows/`, `claude` for `.claude/`, otherwise the top-level folder if it is an allowed scope. Omit the scope for repo-wide changes. +- Add a body only when the diff shows a reason that is not obvious. Never invent a reason. + +## 3. Verify + +Run `.venv/bin/yamllint --strict .` and `.venv/bin/ansible-lint`. Both must pass. Dry runs against hosts belong in CI, not here. + +## 4. Commit and push + +1. If on `main`, run `git switch -c /`. This carries the changes across. +2. For each commit, run `git add -- `, then `git commit -F -- `. Naming the paths commits only those files, whatever else is staged. +3. Run `git status` to confirm only intentionally excluded files remain. +4. Run `git push -u origin `. + +## 5. Open the PR + +Unless one exists, run `.claude/scripts/gitea.sh POST $REPO/pulls @` with `title`, `body`, `head` and `base: "main"`. The body says what changed and why. + +## 6. Wait for CI + +Get the SHA with `git rev-parse HEAD`, then run `.claude/scripts/gitea.sh WAIT $REPO/commits//status` as a background command. Do not write a polling loop, because that causes a permission prompt. + +- Exit 0: checks passed, or it printed `no CI ran` because workflows are path-filtered. Continue. +- Exit 1: stop, and report the failing check and its `target_url`. +- Exit 3: CI timed out. Stop and report it. + +Then run `.claude/scripts/gitea.sh GET $REPO/pulls/` and confirm `mergeable` is true and `head.sha` equals the SHA from `git rev-parse HEAD`. + +## 7. Review + +1. Invoke the `code-review` skill with `medium origin/main...HEAD`. Wait for its findings, also if it runs in the background. +2. Check each finding against the code and the PR's purpose. Classify it as **important** (a real bug or broken `CLAUDE.md` rule this PR adds), **pre-existing**, or **nit**, and drop findings that don't hold up. +3. Write the review comment to a file. First line, exactly one of: + - `` when no important finding is left + - `` otherwise + + Then a `## Review` heading, the effort level, and one line per finding: `path:line`, what is wrong, its class. Write `No findings.` if there are none. +4. Run `.claude/scripts/gitea.sh POST $REPO/issues//comments @` with `{"body": ""}`. +5. On `fail`, stop and report the important findings. Do not fix them in this run; the user decides. + +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 + +1. Run `.claude/scripts/gitea.sh POST $REPO/pulls//merge @` with `{"Do":"merge","head_commit_id":""}`, so only the commit CI and the review checked can merge. The `guard-merge.sh` hook refuses the call without a matching `pass` comment. +2. Run `git fetch origin main:main`, then `git switch main`. + +## 9. Report + +Keep it short: + +- PR link and commits. +- The review result, with any pre-existing findings or nits worth a follow-up. +- What the merge triggers, from `on.push` in `.gitea/workflows/`. Today no workflow deploys on merge; say so until that changes. +- Anything left uncommitted. + +Do not delete the branch, dispatch a workflow, or change a live system. diff --git a/CLAUDE.md b/CLAUDE.md index b92f1d5..9e6da8c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -40,7 +40,9 @@ Branch names, commit messages and PR titles follow @CONVENTIONS.md. The git hook Only commit when I explicitly say "commit" for that change. A yes to a question that also mentioned committing is not enough; when unsure, ask. -The remote is a self-hosted Gitea, so `gh` doesn't work. For PRs and their CI status use `.claude/scripts/gitea.sh` (acts as `claude-bot`), e.g. `.claude/scripts/gitea.sh GET '/repos/kasun/homelab-ansible/pulls?state=open'`. Use it for PRs only, and ask before opening or merging one. Reading from Gitea is free. +The remote is a self-hosted Gitea, so `gh` doesn't work. For PRs and their CI status use `.claude/scripts/gitea.sh` (acts as `claude-bot`), e.g. `.claude/scripts/gitea.sh GET '/repos/kasun/homelab-ansible/pulls?state=open'`. Use it for PRs, and for issues when I ask. Reading from Gitea is free. + +Open and merge PRs through `/merge`: typing it is my OK to commit, open a PR and merge for that run. Outside `/merge`, ask first. Every merge needs a passing review comment for the PR's head commit; `.claude/hooks/guard-merge.sh` refuses the merge otherwise. Before deploy-on-merge is enabled, revisit this: PRs that deploy will need my approval. ## Verifying changes From f45fb7421aab06e8ae6efd7bd9f51644fbaad7aa Mon Sep 17 00:00:00 2001 From: kasun Date: Fri, 27 Nov 2026 03:39:19 +0100 Subject: [PATCH 2/3] chore(claude): make the merge gate fail closed The first review found ways around the hook: unexpected errors exited with non-blocking codes, unusual spellings of the merge path skipped it, and an older pass outlived a newer fail. The ask rule for merges is back as a second layer, so merging outside /merge is enforced, not just instructed. --- .claude/hooks/guard-merge.sh | 100 ++++++++++++++++++++++------------ .claude/scripts/gitea.sh | 7 ++- .claude/settings.json | 1 + .claude/skills/merge/SKILL.md | 2 +- CLAUDE.md | 2 +- 5 files changed, 73 insertions(+), 39 deletions(-) diff --git a/.claude/hooks/guard-merge.sh b/.claude/hooks/guard-merge.sh index 67c2412..c79a9c1 100755 --- a/.claude/hooks/guard-merge.sh +++ b/.claude/hooks/guard-merge.sh @@ -1,52 +1,84 @@ #!/usr/bin/env bash -# PreToolUse hook for Bash: refuses a PR merge through gitea.sh unless the PR -# has a passing review comment for its current head commit. +# PreToolUse hook for Bash: refuses a PR merge unless the PR's newest review +# comment is a pass for its current head commit. # # 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 -# instead of relying on the instruction alone. It checks that a claude-bot -# comment with `` exists and that the -# merge body pins `head_commit_id` to that same SHA. It can't check that the -# review behind the marker was done properly. +# instead of relying on the instruction alone. It can't check that the review +# 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. # -# Fails closed: if the PR or its comments can't be read, the merge is refused. -set -euo pipefail - -input=$(cat) -cmd=$(jq -r '.tool_input.command // empty' <<<"$input") - -merge_re="gitea\.sh[[:space:]]+POST[[:space:]]+[\"']?(/repos/[^/[:space:]]+/[^/[:space:]]+)/pulls/([0-9]+)/merge" -[[ $cmd =~ $merge_re ]] || exit 0 -repo="${BASH_REMATCH[1]}" -pr="${BASH_REMATCH[2]}" +# A merge must be exactly one command of the form +# .claude/scripts/gitea.sh POST /repos/OWNER/REPO/pulls/N/merge @FILE +# where FILE pins head_commit_id. Any other write call whose path mentions +# "merge", or a path it can't read safely, is refused. +# +# 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. +set -uo pipefail deny() { - jq -n --arg reason "Merge refused: $1" '{ - hookSpecificOutput: { - hookEventName: "PreToolUse", - permissionDecision: "deny", - permissionDecisionReason: $reason - } - }' - exit 0 + echo "Merge refused: $1" >&2 + exit 2 } +trap 'rc=$?; if [[ $rc -ne 0 && $rc -ne 2 ]]; then echo "Merge refused: guard-merge.sh failed (exit $rc)" >&2; exit 2; fi' EXIT -gitea="$CLAUDE_PROJECT_DIR/.claude/scripts/gitea.sh" +input=$(cat) +# Most commands mention neither a merge nor gitea.sh; let them through before parsing. +grep -qiE 'merge|gitea\.sh' <<<"$input" || exit 0 + +cmd=$(jq -r '.tool_input.command // empty' <<<"$input") || deny "could not read the hook input" +[[ -z $cmd ]] && exit 0 +shopt -s nocasematch + +# Merges go through gitea.sh only. +if [[ $cmd =~ (curl|wget|http) && $cmd =~ /api/v1 && $cmd =~ merge ]]; then + deny "merge PRs through .claude/scripts/gitea.sh, not curl or wget" +fi + +# Find gitea.sh write calls. Their path must be a plain literal so it can't +# hide a merge (variables, dot segments, encoding). Legitimate calls never need more. +write_re="gitea\.sh[\"']?[[:space:]]+[\"']?(POST|PUT|PATCH|DELETE)[\"']?[[:space:]]+[\"']?([^[:space:]\"']*)" +[[ $cmd =~ $write_re ]] || exit 0 +path="${BASH_REMATCH[2]}" +safe_path='^/[A-Za-z0-9_/?=&-]+$' +if ! [[ $path =~ $safe_path ]] || [[ $path == *//* ]]; then + deny "gitea.sh write call with a path that isn't plain ($path)" +fi +[[ $path =~ merge ]] || exit 0 + +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:];&|<>`$]+)$' +[[ $cmd =~ $strict_re ]] \ + || deny "a merge must be the single command '.claude/scripts/gitea.sh POST /repos/OWNER/REPO/pulls/N/merge @FILE'" +repo="${BASH_REMATCH[2]}" +pr="${BASH_REMATCH[3]}" +body_file="${BASH_REMATCH[4]}" + +gitea="${CLAUDE_PROJECT_DIR:?}/.claude/scripts/gitea.sh" pr_json=$("$gitea" GET "$repo/pulls/$pr" 2>/dev/null) || deny "could not read PR #$pr" -sha=$(jq -r '.head.sha // empty' <<<"$pr_json") +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" -body_re="[[:space:]]@([^[:space:]\"']+)" -[[ $cmd =~ $body_re ]] || deny "the merge body must be a file (@file) with head_commit_id" -body_file="${BASH_REMATCH[1]}" pinned=$(jq -r '.head_commit_id // empty' "$body_file" 2>/dev/null) || deny "could not read $body_file" [[ $pinned == "$sha" ]] || deny "head_commit_id ($pinned) is not the PR's head commit ($sha)" -comments=$("$gitea" GET "$repo/issues/$pr/comments" 2>/dev/null) || deny "could not read the comments of PR #$pr" -marker="" -jq -e --arg m "$marker" 'any(.[]; .user.login == "claude-bot" and (.body | startswith($m)))' \ - <<<"$comments" >/dev/null \ - || deny "no passing review for head commit $sha. Run the review step of /merge first." +# Collect all comments (oldest first) so the newest marker is really the newest. +comments='[]' +for page in 1 2 3 4 5 6 7 8 9 10; do + 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("" ]] \ + || 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." exit 0 diff --git a/.claude/scripts/gitea.sh b/.claude/scripts/gitea.sh index 545ba0b..471c91c 100755 --- a/.claude/scripts/gitea.sh +++ b/.claude/scripts/gitea.sh @@ -5,10 +5,11 @@ # This script calls the Gitea API instead, as the claude-bot account, so PRs # show up as the bot's work and it only has the rights you gave it. # -# Scope: used for PRs only (list, open, check CI status, merge after your OK). -# Technically it can call any endpoint; CLAUDE.md limits its use to PRs. +# Scope: PRs (list, open, check CI status, comment, merge), and issues when the +# user asks. Technically it can call any endpoint; CLAUDE.md limits its use. # In .claude/settings.json, GET and POST (e.g. opening a PR) run without a -# prompt. Merging a PR (POST .../merge), PATCH, PUT and DELETE always ask first. +# prompt. Merging a PR (POST .../merge), PATCH, PUT and DELETE always ask first, +# and .claude/hooks/guard-merge.sh refuses a merge without a passing review. # # Usage: gitea.sh METHOD PATH [BODY] # METHOD GET | POST | PATCH | PUT | DELETE diff --git a/.claude/settings.json b/.claude/settings.json index 449af68..767580f 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -60,6 +60,7 @@ "Bash(pct *)", "Bash(qm *)", "Bash(curl *)", + "Bash(.claude/scripts/gitea.sh POST */merge*)", "Bash(.claude/scripts/gitea.sh PATCH *)", "Bash(.claude/scripts/gitea.sh PUT *)", "Bash(.claude/scripts/gitea.sh DELETE *)" diff --git a/.claude/skills/merge/SKILL.md b/.claude/skills/merge/SKILL.md index 05904f1..4bbafb7 100644 --- a/.claude/skills/merge/SKILL.md +++ b/.claude/skills/merge/SKILL.md @@ -94,7 +94,7 @@ Never write a `pass` marker for a SHA you did not review, or when an important f ## 8. Merge -1. Run `.claude/scripts/gitea.sh POST $REPO/pulls//merge @` with `{"Do":"merge","head_commit_id":""}`, so only the commit CI and the review checked can merge. The `guard-merge.sh` hook refuses the call without a matching `pass` comment. +1. Run `.claude/scripts/gitea.sh POST $REPO/pulls//merge @` with `{"Do":"merge","head_commit_id":""}`, 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`. ## 9. Report diff --git a/CLAUDE.md b/CLAUDE.md index 9e6da8c..1e27684 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -42,7 +42,7 @@ Only commit when I explicitly say "commit" for that change. A yes to a question The remote is a self-hosted Gitea, so `gh` doesn't work. For PRs and their CI status use `.claude/scripts/gitea.sh` (acts as `claude-bot`), e.g. `.claude/scripts/gitea.sh GET '/repos/kasun/homelab-ansible/pulls?state=open'`. Use it for PRs, and for issues when I ask. Reading from Gitea is free. -Open and merge PRs through `/merge`: typing it is my OK to commit, open a PR and merge for that run. Outside `/merge`, ask first. Every merge needs a passing review comment for the PR's head commit; `.claude/hooks/guard-merge.sh` refuses the merge otherwise. Before deploy-on-merge is enabled, revisit this: PRs that deploy will need my approval. +Open and merge PRs through `/merge`: typing it is my OK to commit, open a PR and merge for that run. Outside `/merge`, ask first. Every merge call asks for permission (also inside `/merge`), and `.claude/hooks/guard-merge.sh` refuses it unless the PR's newest review comment is a pass for its head commit. Before deploy-on-merge is enabled, revisit this: PRs that deploy will need my approval. ## Verifying changes From 1e02dd593042f7607690168331039fbda239c1d3 Mon Sep 17 00:00:00 2001 From: kasun Date: Fri, 27 Nov 2026 03:57:18 +0100 Subject: [PATCH 3/3] chore(claude): close remaining gaps in the merge gate 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. --- .claude/hooks/guard-merge.sh | 84 ++++++++++++++++++++++------------- .claude/scripts/gitea.sh | 3 +- .claude/settings.json | 3 +- .claude/skills/merge/SKILL.md | 4 +- 4 files changed, 59 insertions(+), 35 deletions(-) diff --git a/.claude/hooks/guard-merge.sh b/.claude/hooks/guard-merge.sh index c79a9c1..d148c4e 100755 --- a/.claude/hooks/guard-merge.sh +++ b/.claude/hooks/guard-merge.sh @@ -4,14 +4,19 @@ # # 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 -# instead of relying on the instruction alone. It can't check that the review -# 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. +# instead of relying on the instruction alone. # # A merge must be exactly one command of the form -# .claude/scripts/gitea.sh POST /repos/OWNER/REPO/pulls/N/merge @FILE -# where FILE pins head_commit_id. Any other write call whose path mentions -# "merge", or a path it can't read safely, is refused. +# .claude/scripts/gitea.sh POST /repos/OWNER/REPO/pulls/N/merge @/abs/file.json +# where the file is exactly {"Do":"merge","head_commit_id":""}. +# 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 # 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) # 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" [[ -z $cmd ]] && exit 0 shopt -s nocasematch # 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" fi -# Find gitea.sh write calls. Their path must be a plain literal so it can't -# hide a merge (variables, dot segments, encoding). Legitimate calls never need more. -write_re="gitea\.sh[\"']?[[:space:]]+[\"']?(POST|PUT|PATCH|DELETE)[\"']?[[:space:]]+[\"']?([^[:space:]\"']*)" -[[ $cmd =~ $write_re ]] || exit 0 -path="${BASH_REMATCH[2]}" -safe_path='^/[A-Za-z0-9_/?=&-]+$' -if ! [[ $path =~ $safe_path ]] || [[ $path == *//* ]]; then - deny "gitea.sh write call with a path that isn't plain ($path)" +# Only commands that call gitea.sh matter. A call is gitea.sh at the start of a +# 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:]\"']*)" + if [[ $cmd =~ $write_re ]]; then + path="${BASH_REMATCH[2]}" + safe_path='^/[A-Za-z0-9_/?=&-]+$' + if ! [[ $path =~ $safe_path ]] || [[ $path == *//* ]]; then + deny "gitea.sh write call with a path that isn't plain ($path)" + fi + fi + exit 0 fi -[[ $path =~ merge ]] || exit 0 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 ]] \ - || 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]}" pr="${BASH_REMATCH[3]}" 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\":\"\"}" + gitea="${CLAUDE_PROJECT_DIR:?}/.claude/scripts/gitea.sh" 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 =~ ^[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)" -# Collect all comments (oldest first) so the newest marker is really the newest. -comments='[]' -for page in 1 2 3 4 5 6 7 8 9 10; do - 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 +# This endpoint returns all comments of the issue and ignores page/limit. +comments=$("$gitea" GET "$repo/issues/$pr/comments" 2>/dev/null) || deny "could not read the comments of PR #$pr" +jq -e 'type == "array"' <<<"$comments" >/dev/null 2>&1 || deny "could not parse the comments of PR #$pr" -latest=$(jq -r '[.[] | select(.user.login == "claude-bot" and (.body | startswith("" ]] \ || 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." diff --git a/.claude/scripts/gitea.sh b/.claude/scripts/gitea.sh index 471c91c..ab50895 100755 --- a/.claude/scripts/gitea.sh +++ b/.claude/scripts/gitea.sh @@ -68,7 +68,8 @@ done url=$(<"$config/url") 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. args+=(-H @-) if [[ -n "$body" ]]; then diff --git a/.claude/settings.json b/.claude/settings.json index 767580f..f06a5c7 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -98,7 +98,8 @@ }, { "type": "command", - "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/guard-merge.sh" + "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/guard-merge.sh", + "timeout": 90 } ] } diff --git a/.claude/skills/merge/SKILL.md b/.claude/skills/merge/SKILL.md index 4bbafb7..595f4dc 100644 --- a/.claude/skills/merge/SKILL.md +++ b/.claude/skills/merge/SKILL.md @@ -90,11 +90,13 @@ Then run `.claude/scripts/gitea.sh GET $REPO/pulls/` and confirm `mergea 4. Run `.claude/scripts/gitea.sh POST $REPO/issues//comments @` with `{"body": ""}`. 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. ## 8. Merge -1. Run `.claude/scripts/gitea.sh POST $REPO/pulls//merge @` with `{"Do":"merge","head_commit_id":""}`, 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//merge @` with exactly `{"Do":"merge","head_commit_id":""}` 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`. ## 9. Report