Repository navigation
feat(hook): re-ask before a mutation the user already refused - #1028
Conversation
|
Warning Review limit reached
Next review available in: 38 minutes Limit details: You’ve used all 1 included review currently available under your plan. You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: defaults Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (11)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Verification —
|
| # | Claim | Result |
|---|---|---|
| 1 | 거부가 휴리스틱 0으로 복원 가능하다 — 스캐너가 실제 전사에서 실제 거부를 전부 되찾는다 | PASS(live) |
| 2 | 거부 판정이 좁다 — 훅 차단·automode 차단은 사용자 거부로 세지 않는다 | PASS(live) |
| 3 | P1 술어가 양방향이다 — 같은 식별자만 ask, 다른 식별자·읽기 전용은 침묵 |
PASS(live) |
| 4 | 스위트·매니페스트 체크가 통과한다 | PASS(live) |
Unverified — (a) Bash 전용이라 최초 사건은 잡지 못했을 것(설계상 수용), (b) 표본이 4건이라 이 4건 밖의 거부 레코드 변형은 미확인, (c) PR 본문의 `is_error` 위치 서술이 부정확
(a) PR 본문이 헤드라인으로 적어 둔 한계입니다 — 이 게이트를 부른 사건의 발화 지점은 에이전트/워커 디스패치였고 Bash 매처는 거기 닿지 않습니다. 그때 멈춘 것도 praxis 가 아니라 명령 분류기였습니다. 디스패치 표면 확장은 별도 이슈로 미뤄졌고, 이 PR 이 그것을 해결한다고 주장하지 않습니다.
(b) 행 1 의 모집단은 이 머신의 전사 19개에 들어 있는 user-rejected 4건 전부 입니다. 4건이 전수라는 점은 확인했지만(같은 블록의 원시 집계), 4건은 표본으로는 작습니다 — 다른 형태의 거부 레코드(예: 다른 클라이언트 버전이 쓴 필드 배치)가 있다면 이 스캔은 그것을 보지 못합니다.
(c) PR 본문은 거부 레코드가 "최상위 필드 toolDenialKind, toolUseResult, is_error: true 를 싣는다" 고 적었는데, 실제로는 is_error 만 최상위가 아니라 message.content[0] 안에 있습니다. 구현은 옳습니다 — _transcript.py:424 가 그 블록에서 읽고 주석(:306)도 그렇게 그려 뒀습니다. 틀린 것은 PR 본문 문장 하나이고 코드가 아닙니다. 이 앵커에 기록만 하고 본문은 고치지 않았습니다.
Evidence 1 — 스캐너가 존재하기 전에 쓰인 실제 전사에 스캐너를 돌림
이 PR 의 픽스처는 전부 이 PR 이 저작한 것이라, 픽스처만 통과하는 것은 "목이 코드와 맞는다" 는 증거이지 "코드가 현실과 맞는다" 는 증거가 아닙니다. 그래서 오라클을 바깥에서 가져왔습니다 — 이 머신이 스캐너가 생기기 전에 남긴 세션 전사 19개.
$ python3 "$P/probe_1028.py"
transcripts scanned: 19
raw toolDenialKind population: {'permission-rule': 116, 'automode-blocked': 2, 'user-rejected': 4}
d64ce646…jsonl -> 1 rejection(s)
tool_name='Bash' resolved=True ts=2026-08-14T09:53:32
identifier surface recovered: 359 chars, input keys=['command', 'description']
e43a3532…jsonl -> 1 rejection(s)
tool_name='Bash' resolved=True ts=2026-07-27T08:44:24
identifier surface recovered: 211 chars, input keys=['command', 'description']
f9bf9bdb…jsonl -> 2 rejection(s)
tool_name='AskUserQuestion' resolved=True ts=2026-08-08T10:19:46
identifier surface recovered: 398 chars, input keys=['questions']
tool_name='Bash' resolved=True ts=2026-08-08T14:46:54
identifier surface recovered: 232 chars, input keys=['command', 'description', 'timeout']
scanner total: 4 raw user-rejected: 4
마지막 줄이 핵심입니다 — 원시 레코드를 직접 센 4건과 스캐너가 되찾은 4건이 같습니다. 그리고 네 건 모두 resolved=True 로, sourceToolAssistantUUID 를 따라가 원래 도구의 이름과 입력까지 복원했습니다. "휴리스틱 0" 이 실제 데이터에서 성립합니다.
되찾은 텍스트는 실제 세션 내용(경로·저장소명)이라 크기만 찍었습니다. 프로브 안에도 그 이유를 주석으로 남겼습니다. $P 는 프로브를 워크트리 밖에 두려고 담아 둔 경로 변수입니다.
Evidence 2 — 같은 블록의 원시 집계가 좁음을 고정
"사용자가 거부했다" 를 넓게 잡으면 훅이 스스로 막은 것까지 사용자 의사로 읽히고, 그러면 게이트가 자기 자신을 근거로 재차 묻습니다. 위 블록 두 번째 줄이 그 경계를 보입니다 — 별도 실행이 아닙니다.
raw toolDenialKind population: {'permission-rule': 116, 'automode-blocked': 2, 'user-rejected': 4}
...
scanner total: 4 raw user-rejected: 4
같은 필드의 세 값 중 스캐너가 집는 것은 user-rejected 뿐입니다. Refutation: 판정이 넓었다면 스캐너 합계가 4 가 아니라 122 쪽으로 갔어야 합니다. Positive control: 스캐너가 그냥 아무것도 못 찾는 것이 아니라는 근거는 같은 실행의 4건 복원이고, 그중 하나는 AskUserQuestion 이라 도구 종류에 관계없이 집는다는 것도 함께 보입니다.
permission-rule 116건이 훅 차단이고, 그 안에는 이 저장소의 다른 게이트들이 낸 차단도 들어 있습니다 — 그것이 사용자 거부로 새면 안 되는 이유가 그대로 116 이라는 숫자입니다.
Evidence 3 — P1 술어의 양방향을 스위트 출력에서
식별자 겹침 술어는 좁게 짜면 못 잡고 넓게 짜면 한 번 거부 뒤 세션 내내 무관한 삭제까지 막습니다. 그래서 발화·침묵을 같은 무게로 봐야 합니다.
$ bash tests/hooks/preflight-gate/test_rejected_mutation_reconsent_gate.sh | grep -iE 'prefix|different|no prior|non-ask|s3'
PASS [ask] rejected s3 prefix, delete on the SAME prefix
PASS [ask] same prefix without the trailing slash normalizes equal
PASS [ask] gsutil rm on the rejected prefix (gs:// scheme)
PASS [ask] compound command: destructive half carries the rejected prefix
PASS [pass] SAME delete on a DIFFERENT prefix
PASS [pass] sibling prefix is not a containment match
PASS [pass] different bucket, same key path
PASS [pass] no prior rejection in the transcript
PASS [pass] rejection joined to a non-AskUserQuestion tool
PASS [pass] read-only command on the rejected prefix
PASS [pass] read-only sync of the rejected prefix
PASS [pass] different table than the rejected one
위 4줄이 발화, 아래 8줄이 침묵입니다. 침묵 쪽이 두 배인 것이 이 술어의 성격을 그대로 보여 줍니다 — sibling prefix is not a containment match 와 different bucket, same key path 가 정규화가 과하게 겹치지 않는다는 잠금이고, read-only command on the rejected prefix 는 동사 축이 살아 있다는 잠금입니다.
Evidence 4 — 스위트 전량과 매니페스트 정합성
행 1~3 은 제가 고른 창이므로 이 PR 이 고정한 기대값 전량과, 훅을 추가하면 함께 재생성돼야 하는 매니페스트 정합성도 돌립니다.
$ bash tests/hooks/preflight-gate/test_rejected_mutation_reconsent_gate.sh
PASS: 25 FAIL: 0
$ python3 -m pytest tests/test_transcript.py tests/hooks/_lib/test_dispatch.py -q
................................ [100%]
104 passed in 6.46s
$ python3 scripts/check-plugin-manifests.py; echo "manifest-check exit=$?"
plugin-manifest check OK
manifest-check exit=0
test_dispatch.py 가 함께 든 이유는 이 PR 이 새 훅을 디스패치 표에 넣으면서 그 테스트의 기대 개수를 갱신했기 때문입니다(diff 상 8줄).
History — rev 3, 이월 판정 기록 · rev 2, 리베이스 충돌 해결 후 행 4 재측정 · rev 1, 최초 게시
rev 3 — 머지 직전 Carried: #1035 를 표 위에 적었습니다. 근거 블록과 판정은 그대로입니다.
rev 2 — cd7d5d2 → 32135d3. main 이 14커밋 앞서 pre-merge 리베이스를 돌렸고, tests/hooks/_lib/test_dispatch.py 에서 충돌이 하나 났습니다. 훅 본체·전사 파서·전용 스위트는 리베이스 전후 동일합니다:
$ git diff --quiet cd7d5d2 HEAD -- hooks/preflight-gate/rejected-mutation-reconsent-gate/ hooks/_lib/_transcript.py tests/hooks/preflight-gate/test_rejected_mutation_reconsent_gate.sh tests/test_transcript.py ; echo "core verified-paths exit=$?"
core verified-paths exit=0
바뀐 것은 디스패처 카운트 네 자리뿐인데, 그 중 셋은 텍스트 충돌 없이 조용히 넘어갈 뻔했습니다. 충돌이 난 것은 role 별 숫자 한 곳이고, 총계 assert len(members) == 49 는 양쪽 문자열이 같아 자동 병합됐습니다 — 이 브랜치가 컷될 당시 48→49 로 올린 값과, 그 사이 #1026 이 올려 둔 값이 우연히 일치한 것입니다. 실제 매니페스트를 세면 50이라 그대로 뒀으면 CI 에서 깨졌을 자리입니다.
$ python3 -c "…hooks/manifest.json 에서 event=PreToolUse 이고 matcher 가 정확히 'Bash' 인 항목을 role 별로 집계…"
total: 50
Counter({'preflight-gate': 27, 'advisory-nudge': 23})
그래서 len(members) 49→50, len(unfiltered) 49→50, len(codex) 43→44(신규 훅에 hosts 제한이 없어 codex 에도 노출됨), ARCHITECTURE.md 의 49→50 을 함께 맞췄습니다.
행 4 는 그 카운트를 오라클로 삼는 행이므로 SHA 만 고치지 않고 새 HEAD 에서 다시 돌렸습니다:
$ python3 scripts/check-plugin-manifests.py
plugin-manifest check OK
$ bash tests/hooks/preflight-gate/test_rejected_mutation_reconsent_gate.sh
PASS: 25 FAIL: 0
$ python3 -m pytest tests/test_transcript.py tests/hooks/_lib/test_dispatch.py -q
105 passed, 1760 warnings in 3.73s
행 1~3 은 전사 스캔과 P1 술어를 오라클로 삼고 그 경로가 무변경이므로 재실행하지 않았습니다.
rev 1 — 최초 게시.
A user rejects an AskUserQuestion for an irreversible mutation. The next user message — a two-word instruction about running two workstreams in parallel, naming no deletion scope — is read as approval, and a ~295M-object deletion is launched. A command classifier stopped it; judgement did not. A rejection is a standing NO, and nothing re-read it before the next utterance was consumed as consent. hooks/preflight-gate/rejected-mutation-reconsent-gate emits permissionDecision "ask" when all three hold: the pending Bash command carries a destructive marker AND a literal identifier (s3://, gs://, or a table named after DROP / TRUNCATE / DELETE FROM); an earlier AskUserQuestion in this session was structurally rejected; and the rejected question named the SAME normalized identifier. The reason quotes the rejected question verbatim — a re-consent prompt that does not say what was refused cannot be answered. Rejection detection is STRUCTURAL ONLY, in a new shared enumerator hooks/_lib/_transcript.py::scan_user_rejections. Three independent markers must agree — toolDenialKind == "user-rejected", the tool_result's is_error: true, and the runtime's fixed refusal sentence — and the tool name/input are resolved through the uuid index (sourceToolAssistantUUID → the assistant record's uuid → the tool_use block matching tool_use_id), because the rejection record carries neither. The shape was verified against a live transcript (659 events, 2 rejection records) before anything was built on it. Option-label text is never classified: NL refusal detection at a permission boundary is what DESIGN.md's structural-tokenization rule keeps out of hooks. The cost is a real miss, stated in spec.md rather than hidden. Overlap is a literal shared identifier — no verb-class fallback and no prefix containment (s3://b/raw does not match s3://b/raw/2024). Scheme and bucket fold case, the object key does not (keys are case-sensitive); SQL names fold entirely and stay qualified. On the command side a URI is extracted only from a segment that also carries a destructive token, via safe_tokenize → iter_command_starts, so `aws s3 ls` on the rejected prefix stays silent and one half of a && cannot inherit the other half's verb. Tier is ask, not deny, and there is no bypass marker: the gate makes a claim about consent state, which is exactly what the user is authoritative on, and approving the ask IS the fresh per-action approval it demands. Recorded honestly in spec.md: a Bash-only matcher would NOT have intercepted the originating incident, whose firing point was an agent/worker dispatch. That is an accepted limitation; the dispatch surface is deferred to a separate issue. Bounded and fail-open: 20 MB / 20 most-recent rejections, substring pre-filter before any json.loads, 0.015 s measured on a real 1.9 MB transcript against a 5 s budget; any error yields silence, never a block. Fixtures cover both directions — 7 ask paths, 10 silent controls (different prefix, sibling prefix, different bucket, no rejection, non-AskUserQuestion source, read-only commands, different/unqualified table, no identifier), a structural control where a rejection record missing is_error must not count, the cascade-hint pair, and fail-open infrastructure. tests/test_transcript.py adds 13 scanner cases, three of which each drop exactly one structural marker, plus an ordinary is_error tool failure as the nearby input a loose scan would also match. Not-tested: live Claude Code runtime (registration is applied per-branch by the orchestrator; the manifest entry was verified through the real dispatcher against a scratch manifest copy). Closes #1007 Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_014Q4o2BtBPpsrr19he6qVpc
A wrapped sentence left an issue reference at column 0, and markdownlint reads that shape as a heading (MD018). Nothing rendered wrong — CommonMark requires a space after the hash — but the rule is not among the four the repo disables, and reviewdog's suggested fix would have inserted that space and turned prose into a real heading. Moving the previous line's last word down silences the rule without touching a word of the text. Confidence: high Session-Id: 9e3b4abb-9995-41aa-8c70-4c2be1bb61ba
cd7d5d2 to
32135d3
Compare
|
Verification updated — |
|
Verification updated — |
결정
정의 A(구조적만) + 술어 P1(리터럴 공유 식별자) + 매처 Bash 만 + 티어
ask(유지보수자 판정). 본문이 열어둔 두 정의를 모두 가장 좁은 쪽으로 닫았습니다.근거 — 실제 전사 레코드
거부 레코드가 최상위 필드
toolDenialKind: "user-rejected",toolUseResult: "User rejected tool use",is_error: true를 싣고,sourceToolAssistantUUID가 원래tool_use의 name+input 을 담은 assistant 레코드로 해석된다. 휴리스틱 0으로 복원 가능하다. 실제 전사에서 확인한 뒤 그 위에 구현했다.hooks/_lib/_transcript.py에 스캐너 하나를 추가했고, 이 PR 과 #1013 이 같은 것을 쓴다.구현한 정의 — 좁은 쪽으로 닫음
toolDenialKind == "user-rejected"(+is_error이중 확인), tool_use_id 로 AskUserQuestion 에 조인s3://bucket/prefix,gs://…, DROP/TRUNCATE/DELETE FROM 뒤 테이블명을 양쪽에서 뽑아 정규화 식별자가 겹칠 때만askdeny정직하게 기록한 한계
Bash 전용으로는 최초 사건을 가로채지 못했을 것이다. 그 발화 지점은 에이전트/워커 디스패치였고, 본문도 그것을 멈춘 것은 praxis 가 아니라 명령 분류기였다고 적고 있다. 유지보수자가 이 한계를 수용하고 디스패치 표면은 별도 이슈로 미뤘다 — spec.md 에 그렇게 적었다.
회귀 — 4방향
오케스트레이터가 고친 규약 위반 하나
에이전트가 ask 사유를 손으로 조립했는데,
tests/test_block_message.py가 레거시 허용목록에 없는 훅에 대해 그것을 금지한다. 형제cross-boundary-preflight는 그 목록에 있어 통과하지만, 새 게이트는 그 면제를 주장할 수 없다. 허용목록에 추가하는 대신hooks/_lib/block_message.format_block으로 렌더링하도록 바꿨다.bypass_env는 의도적으로None— ask 자체가 탈출구라 이름 붙일 변수가 없고,format_block이 Bypass 줄을 생략한다.등록
매니페스트 엔트리 추가 후
build-plugin-manifests.py재생성. PreToolUse(Bash) 디스패치 그룹 멤버라 래퍼도 플랫폼 hooks.json 항목도 필요 없다(cross-boundary-preflight와 동일). 디스패치 카운트를 48→49, preflight-gate 26→27, codex 42→43 으로 올렸다.hosts키 없음 — 다른 모든 전사 판독 훅과 같고, 전사 형태가 다른 호스트에서는 fail open 한다.미확인
Workflow도구 호출의 것이다. 런타임이 거부된 AskUserQuestion 에도 같은 봉투를 쓴다는 가정은 미검증이며, 이 훅의 하중을 지고 있다.Closes #1007
🤖 Generated with Claude Code
https://claude.ai/code/session_014Q4o2BtBPpsrr19he6qVpc
Generated by Claude Code