diff --git a/.agents/hook/enforce_gh_review_approval.sh b/.agents/hook/enforce_gh_review_approval.sh deleted file mode 100755 index e6d5999d..00000000 --- a/.agents/hook/enforce_gh_review_approval.sh +++ /dev/null @@ -1,278 +0,0 @@ -#!/usr/bin/env bash -# enforce_gh_review_approval.sh -- Claude Code PreToolUse hook (matcher: Bash). -# -# DENIES `gh issue create|edit` and `gh pr create|edit` unless the user -# has explicitly approved the drafted content in the session transcript. -# -# Rationale (issue #34): the agent used to jump straight to -# `gh issue create` / `gh pr create` after drafting the body in English, -# so the user never saw the draft before it landed on a public, indexed -# repo. `enforce_gh_english.sh` only enforces that the body is English; -# it does not enforce that the user approved the content. This hook makes -# the review step enforceable, the same way -# `enforce_shellcheck_disable_approval.sh` requires `approve SC`. -# -# Desired flow (also documented in -# .agents/rules/common/development-workflow.md): -# 1. Agent writes a draft in the user's working language (zh-TW) to a -# local file, e.g. /tmp/.zh.md. -# 2. Agent shows the path / a short summary to the user for review. -# 3. After the user approves, the agent translates to English. -# 4. Agent runs `gh issue create` / `gh pr create` with the English -# `--body-file`. -# -# Approval phrases (case-insensitive, any one is enough): -# - `approve issue` / `issue ok` -> authorizes gh issue create|edit -# - `approve pr` / `pr ok` -> authorizes gh pr create|edit -# - `skip review` -> the escape hatch; authorizes both -# (the user explicitly opting out of the review step) -# The canonical tokens stay English so the check is locale-agnostic; -# locale equivalents may be layered on later. -# -# Per-draft scoping (issue #34): approval is scoped to the CURRENT draft, -# not the whole session. One `approve issue` no longer authorizes every -# later `gh issue create` — after the agent has already run a -# `gh create|edit`, a fresh approval (post-dating that publish) is -# required for the next one. Otherwise a second, never-reviewed draft -# would ride in on a stale approval. -# -# Modules (each a function with a narrow stdin/stdout/exit contract so it -# can be exercised in isolation by bats): -# - read_user_messages [min_index] -# Emits every user-typed text message (one per line) on a line whose -# 1-based index is > min_index (default 0 = whole transcript). Skips -# tool_result entries (synthetic content, not user-typed). Missing -# or unreadable file -> empty stdout. -# - _last_publish_line_index -# The 1-based line index of the last assistant Bash tool_use that -# already ran `gh create|edit` (the scoping boundary); 0 when -# none. Per-kind, so an issue publish never resets a pr approval. -# - is_review_approved -# kind is `issue` or `pr`. Exit 0 if the text contains a matching -# approval phrase (or the `skip review` escape hatch); exit 1 -# otherwise. -# - main -# Orchestrates the above against PreToolUse JSON stdin: computes the -# per-draft boundary, reads only the approvals after it, decides. -# -# Output contract (per ADR-0007 exit-code-contract convention): -# - allow -> exit 0, no stdout -# - deny -> exit 0, emit permissionDecision JSON on stdout -# -# Bypass: ECC_ALLOW_GH_REVIEW=1 env var -> allow silently (leaves an -# audit trail in shell history). -# -# Template-first (ADR-0029): sources lib/hook_bootstrap.sh for set -uo pipefail -# (ADR-0007 exit-code-contract) + input reading (hook_read_input / hook_command). -# The per-draft transcript scoping, approval-phrase matching, and -# permissionDecision=deny emission are this hook's unique logic and are unchanged. -# The isolated modules stay independently source-able for bats (main runs only as -# the entrypoint, below). - -# shellcheck source=../../lib/hook_bootstrap.sh -source "${LIB_DIR:-$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../../lib" && pwd -P)}/hook_bootstrap.sh" -hook_bootstrap "enforce-gh-review-approval" - -# ── read_user_messages ─────────────────────────────────────────────────────── -# Args: $1 = transcript_path, $2 = min_index (optional, default 0). -# Stdout: every user-typed text message on a transcript line whose 1-based -# index is STRICTLY GREATER than min_index, one per line, in file order. -# Algorithm: scan JSONL for entries where `.type == "user"` AND -# `.message.role == "user"` AND `.message.content` is either a plain -# string or an array containing `type:"text"` block(s) (NOT tool_result, -# which is synthetic). Concatenate the text blocks of each entry. -# -# min_index implements per-draft scoping (issue #34): approvals that -# predate the boundary line (the last `gh create|edit` the agent -# already ran) are ignored, so one approval cannot authorize a later, -# separately-drafted publish. min_index == 0 -> whole transcript. -read_user_messages() { - local transcript_path="${1:-}" - local min_index="${2:-0}" - [[ -z "${transcript_path}" ]] && return 0 - [[ ! -r "${transcript_path}" ]] && return 0 - - local line text idx=0 - while IFS= read -r line; do - idx=$((idx + 1)) - (( idx <= min_index )) && continue - text="$(printf '%s' "${line}" | jq -r ' - select(.type == "user") - | select(.message.role == "user") - | .message.content - | if type == "string" then . - elif type == "array" then - ( map(select(.type == "text") | .text) | join(" ") ) - else empty - end - ' 2>/dev/null)" - [[ -n "${text}" ]] && printf '%s\n' "${text}" - done < "${transcript_path}" - return 0 -} - -# ── _last_publish_line_index ───────────────────────────────────────────────── -# Args: $1 = transcript_path, $2 = kind (issue|pr). -# Stdout: the 1-based transcript line index of the LAST assistant Bash -# tool_use that already invoked `gh create|edit` (the boundary -# after which a fresh approval is required); `0` when there is none, the -# file is missing/unreadable, or the args are empty. -# -# Rationale (issue #34, per-draft review): without a boundary, a single -# `approve issue` earlier in the session would authorize every later -# `gh issue create` — including a different, never-reviewed draft. The -# current (about-to-run) command is NOT in the transcript yet (PreToolUse -# fires before execution), so only PRIOR publishes are counted. The -# boundary is per-kind so an issue publish never invalidates a pr -# approval (and vice versa). -_last_publish_line_index() { - local transcript_path="${1:-}" - local kind="${2:-}" - if [[ -z "${transcript_path}" || -z "${kind}" || ! -r "${transcript_path}" ]]; then - printf '0' - return 0 - fi - - local line idx=0 last=0 cmd - while IFS= read -r line; do - idx=$((idx + 1)) - cmd="$(printf '%s' "${line}" | jq -r ' - select(.type == "assistant") - | .message.content - | if type == "array" then - ( map(select(.type == "tool_use" and .name == "Bash") - | .input.command // empty) | join("\n") ) - else empty - end - ' 2>/dev/null)" - [[ -z "${cmd}" ]] && continue - [[ "$(_triggering_kind "${cmd}")" == "${kind}" ]] && last=${idx} - done < "${transcript_path}" - printf '%s' "${last}" - return 0 -} - -# ── is_review_approved ─────────────────────────────────────────────────────── -# Args: $1 = kind (issue|pr), $2 = messages_text. -# Exit 0 if approved, 1 otherwise. Matching is case-insensitive and -# treats the whole text as one flattened line so phrases split across -# messages still match at word boundaries. -is_review_approved() { - local kind="${1:-}" - local msg="${2:-}" - [[ -z "${kind}" || -z "${msg}" ]] && return 1 - - local flat - flat="$(printf '%s' "${msg}" | tr '[:upper:]' '[:lower:]' | tr '\n' ' ')" - - # `skip review` is the explicit opt-out; it authorizes either kind. - if printf '%s' "${flat}" \ - | grep -qE '(^|[^[:alnum:]_])skip[[:space:]]+review([^[:alnum:]_]|$)'; then - return 0 - fi - - local pattern - case "${kind}" in - issue) - pattern='(^|[^[:alnum:]_])(approve[[:space:]]+issue|issue[[:space:]]+ok)([^[:alnum:]_]|$)' - ;; - pr) - pattern='(^|[^[:alnum:]_])(approve[[:space:]]+pr|pr[[:space:]]+ok)([^[:alnum:]_]|$)' - ;; - *) - return 1 - ;; - esac - - if printf '%s' "${flat}" | grep -qE "${pattern}"; then - return 0 - fi - return 1 -} - -# ── main ───────────────────────────────────────────────────────────────────── - -_emit_deny() { - local reason="$1" - jq -n --arg m "${reason}" '{ - systemMessage: $m, - hookSpecificOutput: { - hookEventName: "PreToolUse", - permissionDecision: "deny", - permissionDecisionReason: $m - } - }' -} - -# Detect the triggering gh subcommand. Echoes `issue` or `pr` on a match, -# empty otherwise. -_triggering_kind() { - local cmd="$1" - if [[ "${cmd}" =~ (^|[[:space:]\;\|\&]|\$\()[[:space:]]*gh[[:space:]]+issue[[:space:]]+(create|edit)([[:space:]]|$) ]]; then - printf 'issue' - elif [[ "${cmd}" =~ (^|[[:space:]\;\|\&]|\$\()[[:space:]]*gh[[:space:]]+pr[[:space:]]+(create|edit)([[:space:]]|$) ]]; then - printf 'pr' - fi -} - -main() { - if [[ "${ECC_ALLOW_GH_REVIEW:-}" == "1" ]]; then - return 0 - fi - - hook_read_input - local input="${HOOK_INPUT}" cmd - [[ -z "${input}" ]] && return 0 - cmd="$(hook_command)" - [[ -z "${cmd}" ]] && return 0 - - local kind - kind="$(_triggering_kind "${cmd}")" - [[ -z "${kind}" ]] && return 0 - - local transcript_path boundary messages - transcript_path="$(printf '%s' "${input}" | jq -r '.transcript_path // empty' 2>/dev/null)" - # Per-draft scoping: only approvals AFTER the last `gh create|edit` - # the agent already ran count for the current publish (issue #34). - boundary="$(_last_publish_line_index "${transcript_path}" "${kind}")" - messages="$(read_user_messages "${transcript_path}" "${boundary}")" - - if is_review_approved "${kind}" "${messages}"; then - return 0 - fi - - local phrase - if [[ "${kind}" == "issue" ]]; then - phrase="\`approve issue\` / \`issue ok\`" - else - phrase="\`approve pr\` / \`pr ok\`" - fi - - local reason="GitHub review approval required (issue #34, hook source: .claude/hook/enforce_gh_review_approval.sh). - -A \`gh ${kind} create|edit\` was attempted but the user has not approved the drafted content in this session's transcript. - -Expected flow (per .claude/rules/common/development-workflow.md): - 1. Write the draft in the user's working language (zh-TW) to a local - file, e.g. /tmp/.zh.md. - 2. Show the path / a short summary and ask the user to review it. - 3. After approval, translate the approved content to English. - 4. Re-run \`gh ${kind} create|edit\` with the English --body-file. - -To approve, the user says one of (case-insensitive): ${phrase}. The -user may also say \`skip review\` to opt out for either kind. Approval is -read from the session transcript -- it cannot be forged. English -enforcement (enforce_gh_english.sh) still runs after approval. - -Emergency bypass: ECC_ALLOW_GH_REVIEW=1 env var (leaves an audit trail -in shell history)." - - _emit_deny "${reason}" - return 0 -} - -# Only run main when this script is the entrypoint. Allows bats specs to -# `source` the file and exercise individual functions in isolation. -if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then - main "$@" -fi diff --git a/.agents/rules/common/development-workflow.md b/.agents/rules/common/development-workflow.md index ea5c1aca..057179fe 100644 --- a/.agents/rules/common/development-workflow.md +++ b/.agents/rules/common/development-workflow.md @@ -43,32 +43,25 @@ The Feature Implementation Workflow describes the development pipeline: research - Ensure branch is up to date with target branch - Only request review after these checks pass -## GitHub Issue / PR Review Approval (mandatory before `gh ... create`) +## Autonomous issue / PR policy -`gh issue create|edit` and `gh pr create|edit` publish content to a -public, indexed repo. The user must see and approve the draft BEFORE it -lands. Enforced by `.claude/hook/enforce_gh_review_approval.sh` -(PreToolUse on Bash), which denies these commands until the session -transcript contains an explicit user approval phrase -- the same -transcript-based approval discipline as -`enforce_shellcheck_disable_approval.sh`. +Issues and PRs are created and merged by agents without a per-item human +draft approval. The gate is technical, not conversational: a PR merges once +TDD is done and CI (`ci-passed`) is green -- push, `gh pr create`, arm +`gh pr merge --auto`, let the aggregator decide. No draft file, no +approval phrase, no wait for the maintainer. -Default flow: +The only thing that still needs the maintainer's explicit consent is a +**release tag** (`.claude/script/release-tag.sh`; see +`doc/process/release.md`). -1. Write the draft in the user's working language (zh-TW) to a local - file, e.g. `/tmp/.zh.md`. -2. Show the path (and/or a short summary) and ask the user to review it. -3. After the user approves, translate the approved content to English. -4. Run `gh issue create` / `gh pr create` with the English `--body-file`. - English-only enforcement (`enforce_gh_english.sh`) still runs. +What still applies to every `gh issue|pr create|comment`: -Approval phrases (case-insensitive; any one is enough): +- English-only, emoji-free titles / bodies for this repository's issues + and PRs (`enforce_gh_english.sh`). +- `--body-file` for bodies (`enforce_gh_body_file.sh`) and the issue + template (`enforce_gh_issue_template.sh`). -- `approve issue` / `issue ok` -> authorizes `gh issue create|edit` -- `approve pr` / `pr ok` -> authorizes `gh pr create|edit` -- `skip review` -> the explicit opt-out; authorizes either kind when the - user says to go straight to create ("just open the issue" style). - -The canonical tokens stay English so the hook check is locale-agnostic. -Emergency bypass (leaves an audit trail in shell history): -`ECC_ALLOW_GH_REVIEW=1`. +History: the previous transcript-approval gate +(`enforce_gh_review_approval.sh`, issue #34) was retired on 2026-09-19 -- +see `doc/changelog/CHANGELOG.md`. diff --git a/.agents/rules/zh/development-workflow.md b/.agents/rules/zh/development-workflow.md index c9f9a371..bbd045ac 100644 --- a/.agents/rules/zh/development-workflow.md +++ b/.agents/rules/zh/development-workflow.md @@ -43,27 +43,22 @@ - 确保分支已与目标分支同步 - 仅在这些检查通过后请求审查 -## GitHub Issue / PR 审查批准(`gh ... create` 前必需) +## 自主 Issue / PR 策略 -`gh issue create|edit` 与 `gh pr create|edit` 会把内容发布到一个公开且被 -索引的仓库。用户必须在内容落地之前看到并批准草稿。由 -`.claude/hook/enforce_gh_review_approval.sh`(Bash 的 PreToolUse)强制执行: -在会话记录(transcript)包含明确的用户批准短语之前,拒绝这些命令 -- -与 `enforce_shellcheck_disable_approval.sh` 相同的基于记录的批准机制。 +Issue 与 PR 由代理自主创建与合并,不再逐项等待人工审批草稿。门槛是技术性 +的而非对话性的:完成 TDD 且 CI(`ci-passed`)为绿后,PR 即可合并 -- 推送、 +`gh pr create`、启用 `gh pr merge --auto`,交由聚合检查决定。不需要草稿文件、 +不需要批准短语、不需要等待维护者。 -默认流程: +唯一仍需维护者明确同意的是**发布标签**(`.claude/script/release-tag.sh`; +参见 `doc/process/release.md`)。 -1. 用用户的工作语言(zh-TW)把草稿写到本地文件,例如 `/tmp/.zh.md`。 -2. 展示该路径(以及/或简短摘要),请用户审查。 -3. 用户批准后,把批准的内容翻译为英文。 -4. 用英文的 `--body-file` 运行 `gh issue create` / `gh pr create`。 - 英文强制检查(`enforce_gh_english.sh`)仍会运行。 +对每个 `gh issue|pr create|comment` 仍然适用的规则: -批准短语(大小写不敏感;任意一个即可): +- 本仓库的 issue / PR 标题与正文必须为纯英文且不含 emoji + (`enforce_gh_english.sh`)。 +- 正文使用 `--body-file`(`enforce_gh_body_file.sh`),并遵循 issue 模板 + (`enforce_gh_issue_template.sh`)。 -- `approve issue` / `issue ok` -> 授权 `gh issue create|edit` -- `approve pr` / `pr ok` -> 授权 `gh pr create|edit` -- `skip review` -> 显式跳过;当用户表示直接开 issue/PR 时授权两种。 - -规范 token 保持英文,使钩子检查与语言无关。 -应急绕过(会在 shell 历史留下审计痕迹):`ECC_ALLOW_GH_REVIEW=1`。 +历史:先前基于会话记录的审批门(`enforce_gh_review_approval.sh`,issue #34) +已于 2026-09-19 退役 -- 参见 `doc/changelog/CHANGELOG.md`。 diff --git a/.claude/settings.json b/.claude/settings.json index 1ff3852f..f0ea96a8 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -40,10 +40,6 @@ "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hook/enforce_gh_english.sh" }, - { - "type": "command", - "command": "${CLAUDE_PROJECT_DIR}/.claude/hook/enforce_gh_review_approval.sh" - }, { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hook/remind_ci_auto_merge.sh" diff --git a/doc/changelog/CHANGELOG.md b/doc/changelog/CHANGELOG.md index eca3c703..eb2350bb 100644 --- a/doc/changelog/CHANGELOG.md +++ b/doc/changelog/CHANGELOG.md @@ -1110,6 +1110,21 @@ not deferred to release. `release-tag.sh` promotes `[Unreleased]` → ### Removed +- **`enforce_gh_review_approval.sh` hook retired** (autonomous issue / PR + policy, 2026-09-19): issues and PRs are now created and merged by agents + once TDD + CI (`ci-passed`) are green; only a release tag still needs the + maintainer's explicit consent. The transcript-approval gate from issue #34 + (`approve issue` / `approve pr` / `skip review` phrases, + `ECC_ALLOW_GH_REVIEW=1` bypass) therefore no longer applies. Removed + `.agents/hook/enforce_gh_review_approval.sh`, its `.claude/settings.json` + PreToolUse Bash registration, and + `test/unit/hook/enforce_gh_review_approval_spec.bats`; the "GitHub Issue / + PR Review Approval" section of + `.agents/rules/{common,zh}/development-workflow.md` is replaced by a short + "Autonomous issue / PR policy" section. `test/unit/tool_hook_conformance_spec.bats` + gains a `RETIRED_HOOKS` ledger asserting a retired hook is neither on disk + nor registered in `settings.json`, so it cannot creep back. The + English-only hook (`enforce_gh_english.sh`) is unchanged and still applies. - **ranger module** (issue #319, supersedes #61): yazi (#60) is now the daily file manager across machines, so the redundant ranger catalog entry is dropped. Removed `module/ranger.module.sh`, `module/config/ranger/rifle.conf`, diff --git a/test/unit/hook/enforce_gh_review_approval_spec.bats b/test/unit/hook/enforce_gh_review_approval_spec.bats deleted file mode 100644 index 11f0da1e..00000000 --- a/test/unit/hook/enforce_gh_review_approval_spec.bats +++ /dev/null @@ -1,303 +0,0 @@ -#!/usr/bin/env bats -# test/unit/hook/enforce_gh_review_approval_spec.bats -# -# Tests for the enforce_gh_review_approval.sh hook (issue #34). The hook -# blocks `gh issue create|edit` / `gh pr create|edit` unless the session -# transcript contains an explicit user approval phrase. -# -# Two layers: -# - Unit: source the script, exercise read_user_messages / -# is_review_approved in isolation. -# - Integration: drive the script as a subprocess (stdin JSON, stdout -# permissionDecision JSON or empty) the way Claude Code invokes it. - -load "${BATS_TEST_DIRNAME}/../../helper/common" - -setup() { - setup_test_env - HOOK_SH="${REPO_ROOT}/.claude/hook/enforce_gh_review_approval.sh" - # shellcheck source=../../../.claude/hook/enforce_gh_review_approval.sh - source "${HOOK_SH}" - FIXTURE_DIR="${BATS_TEST_TMPDIR}/fixtures" - mkdir -p "${FIXTURE_DIR}" - - # Default transcript: a user message that does NOT approve anything. - TRANSCRIPT="${FIXTURE_DIR}/transcript.jsonl" - cat > "${TRANSCRIPT}" <<'EOF' -{"type":"assistant","message":{"role":"assistant","content":"drafting..."}} -{"type":"user","message":{"role":"user","content":"please open an issue for the bug"}} -EOF -} - -teardown() { - teardown_test_env - unset ECC_ALLOW_GH_REVIEW -} - -# Build a PreToolUse Bash JSON payload pointing at the current TRANSCRIPT. -_pre_bash_json() { - local command="$1" - jq -n \ - --arg c "${command}" \ - --arg tp "${TRANSCRIPT}" \ - '{tool_name:"Bash", transcript_path:$tp, tool_input:{command:$c}}' -} - -# ── read_user_messages ─────────────────────────────────────────────────────── - -@test "read_user_messages: missing file -> empty stdout, exit 0" { - run read_user_messages "${FIXTURE_DIR}/nope.jsonl" - assert_success - assert_output "" -} - -@test "read_user_messages: empty arg -> empty stdout, exit 0" { - run read_user_messages "" - assert_success - assert_output "" -} - -@test "read_user_messages: emits string + array text, skips tool_result" { - local f="${FIXTURE_DIR}/mixed.jsonl" - cat > "${f}" <<'EOF' -{"type":"assistant","message":{"role":"assistant","content":"hi"}} -{"type":"user","message":{"role":"user","content":"approve pr please"}} -{"type":"user","message":{"role":"user","content":[{"type":"tool_result","content":"synthetic"}]}} -{"type":"user","message":{"role":"user","content":[{"type":"text","text":"looks good"}]}} -EOF - run read_user_messages "${f}" - assert_success - assert_line "approve pr please" - assert_line "looks good" - refute_output --partial "synthetic" -} - -@test "read_user_messages: min_index skips messages at/before the boundary line" { - local f="${FIXTURE_DIR}/indexed.jsonl" - cat > "${f}" <<'EOF' -{"type":"user","message":{"role":"user","content":"before boundary"}} -{"type":"assistant","message":{"role":"assistant","content":"boundary line"}} -{"type":"user","message":{"role":"user","content":"after boundary"}} -EOF - # Boundary at line 2 -> only line 3 (index 3) survives. - run read_user_messages "${f}" 2 - assert_success - assert_output "after boundary" - refute_output --partial "before boundary" -} - -# ── _last_publish_line_index (per-draft scoping boundary) ───────────────────── - -@test "_last_publish_line_index: no prior publish -> 0" { - local f="${FIXTURE_DIR}/nopublish.jsonl" - cat > "${f}" <<'EOF' -{"type":"user","message":{"role":"user","content":"approve issue"}} -{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","name":"Bash","input":{"command":"gh issue view 34"}}]}} -EOF - run _last_publish_line_index "${f}" "issue" - assert_success - assert_output "0" -} - -@test "_last_publish_line_index: returns line of last matching-kind create" { - local f="${FIXTURE_DIR}/withpublish.jsonl" - cat > "${f}" <<'EOF' -{"type":"user","message":{"role":"user","content":"approve issue"}} -{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","name":"Bash","input":{"command":"gh issue create --title a --body-file /tmp/a.md"}}]}} -{"type":"user","message":{"role":"user","content":"thanks"}} -EOF - run _last_publish_line_index "${f}" "issue" - assert_success - assert_output "2" -} - -@test "_last_publish_line_index: a prior PR create does not move the issue boundary" { - local f="${FIXTURE_DIR}/crosskind.jsonl" - cat > "${f}" <<'EOF' -{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","name":"Bash","input":{"command":"gh pr create --body-file /tmp/a.md"}}]}} -{"type":"user","message":{"role":"user","content":"approve issue"}} -EOF - run _last_publish_line_index "${f}" "issue" - assert_success - assert_output "0" -} - -@test "_last_publish_line_index: missing file -> 0" { - run _last_publish_line_index "${FIXTURE_DIR}/nope.jsonl" "issue" - assert_success - assert_output "0" -} - -# ── is_review_approved ─────────────────────────────────────────────────────── - -@test "is_review_approved: 'approve issue' authorizes issue" { - run is_review_approved "issue" "ok, approve issue" - assert_success -} - -@test "is_review_approved: 'issue ok' authorizes issue" { - run is_review_approved "issue" "the draft is fine, issue ok" - assert_success -} - -@test "is_review_approved: 'approve pr' authorizes pr" { - run is_review_approved "pr" "APPROVE PR" - assert_success -} - -@test "is_review_approved: 'pr ok' authorizes pr" { - run is_review_approved "pr" "pr ok, ship it" - assert_success -} - -@test "is_review_approved: 'skip review' authorizes issue" { - run is_review_approved "issue" "just open it, skip review" - assert_success -} - -@test "is_review_approved: 'skip review' authorizes pr" { - run is_review_approved "pr" "skip review and open the pr" - assert_success -} - -@test "is_review_approved: issue approval does not authorize pr" { - run is_review_approved "pr" "approve issue" - assert_failure -} - -@test "is_review_approved: pr approval does not authorize issue" { - run is_review_approved "issue" "approve pr" - assert_failure -} - -@test "is_review_approved: unrelated text -> not approved" { - run is_review_approved "issue" "please write the draft first" - assert_failure -} - -@test "is_review_approved: empty message -> not approved" { - run is_review_approved "issue" "" - assert_failure -} - -# ── main: allow paths ──────────────────────────────────────────────────────── - -@test "main: non-gh command -> allow silently" { - local input; input="$(_pre_bash_json "echo hello")" - run bash -c "printf '%s' \"\$1\" | '${HOOK_SH}'" _ "${input}" - assert_success - assert_output "" -} - -@test "main: gh issue view (read-only) -> allow silently" { - local input; input="$(_pre_bash_json "gh issue view 34")" - run bash -c "printf '%s' \"\$1\" | '${HOOK_SH}'" _ "${input}" - assert_success - assert_output "" -} - -@test "main: gh issue create WITH approval -> allow" { - cat > "${TRANSCRIPT}" <<'EOF' -{"type":"user","message":{"role":"user","content":"draft looks good, approve issue"}} -EOF - local input; input="$(_pre_bash_json "gh issue create --title t --body-file /tmp/x.md --label bug")" - run bash -c "printf '%s' \"\$1\" | '${HOOK_SH}'" _ "${input}" - assert_success - assert_output "" -} - -@test "main: gh pr create WITH approval -> allow" { - cat > "${TRANSCRIPT}" <<'EOF' -{"type":"user","message":{"role":"user","content":"pr ok"}} -EOF - local input; input="$(_pre_bash_json "gh pr create --base main --head auto/x --body-file /tmp/x.md")" - run bash -c "printf '%s' \"\$1\" | '${HOOK_SH}'" _ "${input}" - assert_success - assert_output "" -} - -@test "main: ECC_ALLOW_GH_REVIEW=1 bypass -> allow even without approval" { - local input; input="$(_pre_bash_json "gh pr create --body-file /tmp/x.md")" - ECC_ALLOW_GH_REVIEW=1 run bash -c "printf '%s' \"\$1\" | '${HOOK_SH}'" _ "${input}" - assert_success - assert_output "" -} - -# ── main: deny paths ───────────────────────────────────────────────────────── - -@test "main: gh issue create WITHOUT approval -> deny JSON" { - local input; input="$(_pre_bash_json "gh issue create --title t --body-file /tmp/x.md --label bug")" - run bash -c "printf '%s' \"\$1\" | '${HOOK_SH}'" _ "${input}" - assert_success - assert_output --partial '"permissionDecision": "deny"' - assert_output --partial 'GitHub review approval required' - assert_output --partial 'approve issue' -} - -@test "main: gh pr create WITHOUT approval -> deny JSON" { - local input; input="$(_pre_bash_json "gh pr create --base main --head auto/x --body-file /tmp/x.md")" - run bash -c "printf '%s' \"\$1\" | '${HOOK_SH}'" _ "${input}" - assert_success - assert_output --partial '"permissionDecision": "deny"' - assert_output --partial 'approve pr' -} - -@test "main: gh pr edit WITHOUT approval -> deny JSON" { - local input; input="$(_pre_bash_json "gh pr edit 5 --body-file /tmp/x.md")" - run bash -c "printf '%s' \"\$1\" | '${HOOK_SH}'" _ "${input}" - assert_success - assert_output --partial '"permissionDecision": "deny"' -} - -@test "main: issue approval does NOT unlock a pr create -> deny" { - cat > "${TRANSCRIPT}" <<'EOF' -{"type":"user","message":{"role":"user","content":"approve issue"}} -EOF - local input; input="$(_pre_bash_json "gh pr create --body-file /tmp/x.md")" - run bash -c "printf '%s' \"\$1\" | '${HOOK_SH}'" _ "${input}" - assert_success - assert_output --partial '"permissionDecision": "deny"' -} - -# ── main: per-draft scoping (issue #34: approval scoped to the current draft) ── - -@test "main: an approval consumed by a prior issue create does NOT authorize a second, unreviewed issue -> deny" { - # Approve once, create issue A, then draft issue B with no fresh approval. - cat > "${TRANSCRIPT}" <<'EOF' -{"type":"user","message":{"role":"user","content":"approve issue"}} -{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","name":"Bash","input":{"command":"gh issue create --title a --body-file /tmp/a.md"}}]}} -{"type":"assistant","message":{"role":"assistant","content":"drafted issue B"}} -EOF - local input; input="$(_pre_bash_json "gh issue create --title b --body-file /tmp/b.md")" - run bash -c "printf '%s' \"\$1\" | '${HOOK_SH}'" _ "${input}" - assert_success - assert_output --partial '"permissionDecision": "deny"' -} - -@test "main: a fresh approval AFTER the prior create authorizes the next issue -> allow" { - cat > "${TRANSCRIPT}" <<'EOF' -{"type":"user","message":{"role":"user","content":"approve issue"}} -{"type":"assistant","message":{"role":"assistant","content":[{"type":"tool_use","name":"Bash","input":{"command":"gh issue create --title a --body-file /tmp/a.md"}}]}} -{"type":"user","message":{"role":"user","content":"the second draft is good too, approve issue"}} -EOF - local input; input="$(_pre_bash_json "gh issue create --title b --body-file /tmp/b.md")" - run bash -c "printf '%s' \"\$1\" | '${HOOK_SH}'" _ "${input}" - assert_success - assert_output "" -} - -# ── registration: the hook must actually be wired into settings.json ────────── -# Issue #34's acceptance criterion is that the hook runs in a live session; -# an unregistered hook is inert. Guard the wiring so it cannot silently rot. - -@test "settings.json: hook is registered as a PreToolUse Bash command" { - local settings="${REPO_ROOT}/.claude/settings.json" - [[ -r "${settings}" ]] || fail "settings.json not readable: ${settings}" - run jq -r ' - .hooks.PreToolUse[] - | select(.matcher == "Bash") - | .hooks[].command - ' "${settings}" - assert_success - assert_output --partial "enforce_gh_review_approval.sh" -} diff --git a/test/unit/tool_hook_conformance_spec.bats b/test/unit/tool_hook_conformance_spec.bats index 64344465..7f06571a 100644 --- a/test/unit/tool_hook_conformance_spec.bats +++ b/test/unit/tool_hook_conformance_spec.bats @@ -47,6 +47,19 @@ ALLOWLIST_TOOLS=" # Empty: all hooks are migrated onto lib/hook_bootstrap.sh and enforced. ALLOWLIST_HOOKS="" +# ── Retired hooks ledger (must STAY gone) ──────────────────────────────────── +# Newline-delimited basenames of hooks the project deliberately retired. A +# retired hook must be neither on disk under .agents/hook/ nor registered in +# .claude/settings.json, so a stale copy cannot creep back through a merge or +# a reflexive restore. Add an entry here when a hook is retired (with the +# policy change that retired it noted in doc/changelog/CHANGELOG.md). +# enforce_gh_review_approval.sh — retired 2026-09-19: issues / PRs are +# created and merged autonomously once TDD + CI are green; only a release +# tag needs the maintainer's explicit consent. +RETIRED_HOOKS=" +enforce_gh_review_approval.sh +" + setup() { setup_test_env export LIB_DIR REPO_ROOT @@ -214,3 +227,39 @@ _json() { jq -n --arg c "$1" '{tool_name:"Bash", tool_input:{command:$c}}'; } return 1 } } + +# ── Retired hooks (must stay gone) ─────────────────────────────────────────── + +@test "every retired hook is absent from .agents/hook/" { + local _base _present="" + while IFS= read -r _base; do + [[ -n "${_base}" ]] || continue + [[ -e "${HOOK_DIR}/${_base}" ]] && \ + _present+=" ${_base}: still exists under .agents/hook/ — it was retired, delete it"$'\n' + done <<< "${RETIRED_HOOKS}" + [[ -z "${_present}" ]] || { + printf 'retired hooks still on disk:\n%s' "${_present}" >&2 + return 1 + } +} + +@test "every retired hook is not registered in .claude/settings.json" { + local _settings="${REPO_ROOT}/.claude/settings.json" + [[ -r "${_settings}" ]] || { + printf 'settings.json not readable: %s\n' "${_settings}" >&2 + return 1 + } + local _registered _base _wired="" + _registered="$(jq -r ' + [.hooks // {} | .[] | .[] | .hooks[]? | .command // empty] | .[] + ' "${_settings}")" + while IFS= read -r _base; do + [[ -n "${_base}" ]] || continue + grep -qF "${_base}" <<< "${_registered}" && \ + _wired+=" ${_base}: still registered in .claude/settings.json — it was retired, drop the entry"$'\n' + done <<< "${RETIRED_HOOKS}" + [[ -z "${_wired}" ]] || { + printf 'retired hooks still wired into settings.json:\n%s' "${_wired}" >&2 + return 1 + } +}