Skip to content

fix(hooks): honor permissions.defaultMode in claude hook (closes #1771) - #1808

Closed
giulioleone097 wants to merge 20 commits into
rtk-ai:masterfrom
giulioleone097:fix/honor-default-mode-bypass-permissions
Closed

giulioleone097 wants to merge 20 commits into
rtk-ai:masterfrom
giulioleone097:fix/honor-default-mode-bypass-permissions

Conversation

@giulioleone097

Copy link
Copy Markdown

Summary

  • The Claude Code PreToolUse hook (rtk hook claude) read only permissions.allow/deny/ask from settings.json and ignored permissions.defaultMode. When users opted into a non-prompting mode (bypassPermissions, acceptEdits, auto, dontAsk), unmatched commands fell through to `Default` (= ask) instead of auto-allowing.
  • Symptom: on the Claude Code Mac desktop app, every Bash command triggered a permission prompt for `rtk ` even with `defaultMode: "bypassPermissions"` set — defeating the transparent-rewrite design that opt-in via `rtk init -g` is meant to deliver.
  • This PR makes `check_command_with_rules` mode-aware: when the user has chosen a non-prompting mode and no rule matches, it returns `Allow` (so the hook emits `permissionDecision: "allow"`).

Closes #1771.

Root cause

`permissions::check_command_with_rules` had no awareness of `defaultMode`. The rewrite path therefore never emitted `hookSpecificOutput.permissionDecision: "allow"` unless the user had written explicit allow rules — duplicating the global mode at rule level.

Changes

  • New `DefaultMode` enum in `src/hooks/permissions.rs` mirroring the JSON schema (`default | acceptEdits | auto | bypassPermissions | dontAsk | plan`).
  • `load_permission_rules()` now also reads `permissions.defaultMode`. Project-local files take precedence over user-global, matching Claude Code's settings layering.
  • `check_command_with_rules` takes a new `default_mode: DefaultMode` parameter. When no rule matches and the mode is non-prompting (`bypassPermissions`, `acceptEdits`, `auto`, `dontAsk`), it returns `Allow` instead of `Default`.
  • Security floor preserved: `Deny` and `Ask` rules still win regardless of `defaultMode`. `Plan` and `Default` still fall through to least-privilege.
  • Callsite updates: every internal caller of `check_command_with_rules` (in `hook_cmd.rs`, `rewrite_cmd.rs`, and the test suite) now passes a `DefaultMode`. The public surface (`check_command(cmd)`) is unchanged — it loads `defaultMode` from settings transparently.

Behavior table

Settings `defaultMode` No rule matches Deny matches Ask matches Allow matches
`default` (or unset) Default (ask) Deny Ask Allow
`plan` Default (ask) Deny Ask Allow
`bypassPermissions` Allow ← fix Deny Ask Allow
`acceptEdits` Allow ← fix Deny Ask Allow
`auto` Allow ← fix Deny Ask Allow
`dontAsk` Allow ← fix Deny Ask Allow

Test coverage

12 new unit tests in `src/hooks/permissions.rs`:

  • One per `DefaultMode` value (`bypassPermissions`, `acceptEdits`, `auto`, `dontAsk`, `default`, `plan`) verifying the no-rule fallback.
  • `test_default_mode_does_not_override_deny` and `test_default_mode_does_not_override_ask` verifying the security floor.
  • `test_default_mode_explicit_allow_still_returns_allow` verifying allow rules + bypass don't conflict.
  • `test_default_mode_compound_command_with_bypass` and `test_default_mode_compound_with_partial_deny_still_denies` verifying compound-command behavior.
  • `test_default_mode_from_str` covering parser correctness.

Full suite: 1828 passed, 0 failed, 6 ignored (`cargo test`).
`cargo clippy` produces no new warnings on touched files.

Verification on the actual Claude Code Mac app

Before this fix, with `~/.claude/settings.json`:
```json
{ "permissions": { "defaultMode": "bypassPermissions" } }
```

```bash
$ echo '{"tool_name":"Bash","tool_input":{"command":"git status"}}' | rtk hook claude
{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecisionReason":"RTK auto-rewrite","updatedInput":{"command":"rtk git status"}}}

← no permissionDecision field, Mac app prompts the user

```

After:
```bash
$ echo '{"tool_name":"Bash","tool_input":{"command":"git status"}}' | rtk hook claude
{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecisionReason":"RTK auto-rewrite","updatedInput":{"command":"rtk git status"},"permissionDecision":"allow"}}

← permissionDecision: "allow" present, Mac app skips the prompt

```

Backward compatibility

  • Public API (`check_command(cmd)`) signature unchanged.
  • Default behavior with no `defaultMode` set or `defaultMode: "default"` is identical to before this PR.
  • Users with explicit allow rules see no behavior change.
  • Only users who explicitly opted into a non-prompting `defaultMode` get the new auto-allow — which is exactly what they asked for.

Test plan

  • `cargo build` — clean
  • `cargo test` — 1828 passed, 0 failed
  • `cargo clippy` — no new warnings on touched files
  • `cargo fmt --check` — clean
  • Manual verification on Claude Code Mac app with `bypassPermissions` mode

kherembourg and others added 20 commits May 5, 2026 10:59
Adds rtk gradlew command for build, test, lint, and dependency
operations on Gradle projects. Filters task progress noise, preserves
build scan URLs, test failures, lint violations, and compiler warnings.

Recognises ./gradlew, gradlew, gradlew.bat, and gradle invocations.
Surfaces unit-test report paths and shows a progress indicator for
long-running tasks.

Targets 75% savings (90% on test, 80% on build).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Extract a new_gradle_command() helper that uses string literals in
every Command::new() branch. The .semgrep.yml dynamic-command-execution
rule rejects Command::new(var) — semgrep needs to statically audit
the executable set.

Same runtime behaviour: prefer ./gradlew (or gradlew.bat on Windows),
fall back to gradle.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Replaces custom run_streaming / run_batch / run_passthrough / ProgressIndicator
with the shared runner helpers used by cargo and other commands:

- Build → runner::run_streamed with a BuildLineFilter implementing StreamFilter
- Test/Lint/Connected/Deps → runner::run_filtered with the existing filter_*
  closures (filter_test, filter_connected, filter_lint, filter_dependencies)
- Other / verbose flags → runner::run_passthrough(tool, args, verbose)

Benefits inherited from runner.rs: ChildGuard zombie prevention, 10 MiB output
cap, broken pipe handling, proper Result<i32> exit-code propagation.

run() now returns Result<i32> like cargo_cmd / golangci_cmd. main.rs updated
to forward the exit code with `?` directly (no manual `0` wrapper).

All Command::new() invocations remain string literals (semgrep
dynamic-command-execution rule).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
new_gradle_command() now uses resolved_command("gradle") for the two
fallback branches (Windows + Unix when no local wrapper is present),
matching how cargo / golangci-lint / etc. resolve system binaries.

Local wrappers (./gradlew, gradlew.bat) stay as string literals — they
are relative paths, not on PATH, and semgrep's dynamic-command-execution
rule needs literals here.

Net effect: PATHEXT-aware resolution on Windows (.CMD/.BAT shims work),
no behavioural change on Unix.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…upport

feat(gradlew): Gradle support for Android/Kotlin developers
The `ok` / `fail` verdict line was emitted at the top of the filtered
output, before errors and warnings. Consumers reading the tail of the
stream — `| tail -N`, IDE log followers, agent watch/monitor loops,
bounded-context-window readers — saw error noise followed by EOF with
no verdict anywhere near the end, silently breaking any agent loop that
gates the next step on build success.

Reorder `format_build_output`, `format_test_output`, and
`format_restore_output` to emit the body first, then the separator
(only when the body is non-empty), then the verdict header last,
matching native `dotnet` which ends with `Build succeeded.` or
`Build FAILED.`.

Add three regression tests using strict `output.lines().last()` plus a
`tail -5` inclusion assertion so future regressions that append a
trailing context line get caught.

Closes rtk-ai#1574

Signed-off-by: Artiom Tofan <[email protected]>
- Separate warnings and errors into distinct sections.
- Ensure status line is emitted last for clarity.
- Maintain consistency with native `dotnet` output behavior.
- Improve formatting of output summaries for build, test, and restore commands.
- Ensure status lines are emitted last for better stream consumption.
- Refactor warning formatting to improve consistency across output sections.
- Ensure warnings are displayed correctly in all relevant output formats.
Command wrappers like shadowenv (https://github.com/Shopify/shadowenv),
`direnv exec .`, `nix develop --command`, `docker exec <container>`,
`poetry run`, and `bundle exec` sit in front of every command in their
respective project layouts. When rtk is driving a Claude Code / Gemini /
Copilot / opencode hook, these wrappers defeat the rewrite — `rtk
rewrite "shadowenv exec -- git status"` returns exit 1 (no rewrite)
because the registry can't see past the wrapper to the inner `git
status`. Every build tool, test runner, linter, and `git` invocation
in such a layout stays uncompressed.

rtk already solves exactly this shape for shell builtins via
SHELL_PREFIX_BUILTINS (`noglob`, `command`, `builtin`, `exec`,
`nocorrect`): strip the prefix, recurse on the inner command, re-prepend
the prefix to the rewrite. This commit extends that pattern with a new
[hooks].transparent_prefixes config field so users can register
multi-word wrappers that don't change what runs, only how.

  [hooks]
  transparent_prefixes = ["shadowenv exec --", "direnv exec ."]

With that config, `rtk rewrite "shadowenv exec -- cargo test"` becomes
`shadowenv exec -- rtk cargo test` and exits 3 (ask, matching the
existing ask semantics for inner commands).

Implementation:

- New `rewrite_command_with_prefixes(cmd, excluded, transparent_prefixes)`
  public entry. The original `rewrite_command(cmd, excluded)` is kept as
  a thin back-compat wrapper that passes an empty prefix slice, so the
  ~150 existing unit-test call sites don't need updating.
- `transparent_prefixes: &[String]` threaded through `rewrite_compound`,
  `rewrite_segment`, `rewrite_segment_inner`.
- In `rewrite_segment_inner`, a second strip loop runs after the
  SHELL_PREFIX_BUILTINS loop, with identical strip-recurse-reprepend
  semantics. Matching is whole-word via the existing `strip_word_prefix`
  helper (multi-word prefixes like `"shadowenv exec --"` are handled
  by-value — byte-level `starts_with` plus a space check).
- Recursion is bounded by the existing MAX_PREFIX_DEPTH so pathological
  or self-referential configs cannot stack-overflow.
- Production callers (`hooks/rewrite_cmd.rs`, `hooks/hook_cmd.rs`,
  `main.rs`) now load both `exclude_commands` and `transparent_prefixes`
  from config in the same `Config::load()` call — no new I/O.

Tests (14 new):

- config: 3 TOML roundtrip tests (present, missing, mixed with older
  fields).
- registry: 11 behavior tests — strip/reprepend, unknown inner returns
  None, unmatched passthrough, composed with shell builtin, multiple
  prefixes configured, whole-word matching, empty-rest None, blank-entry
  skip, compound `&&` with prefix on both segments, excluded-inner
  returns None, recursion bounded.

Design principles (from CONTRIBUTING.md):
- Extensibility: extends an existing, documented pattern.
- Zero Overhead: config load already happens on every hook invocation;
  this reads one additional vec. Empty `transparent_prefixes` is the
  default and adds one cheap loop-over-zero-elements on the hot path.
- Correctness vs Token Savings: without this, hook rewrites silently
  miss every command run through a wrapper — exactly the kind of
  correctness gap the principle warns against.
When -bench is present, benchmark output is already compact and useful.
Injecting -json causes the filter to discard benchmark results since they
don't produce pass/fail events the JSON parser expects.

Fixes rtk-ai#1609
fix: don't inject -json for go test -bench runs
inform user how to solve CI pr-target failing check
fix(cicd): pr-target clean msg + git app token
…ai#1771)

The Claude Code PreToolUse hook (`rtk hook claude`) read only
`permissions.allow/deny/ask` from settings.json and ignored
`permissions.defaultMode`. When users opted into a non-prompting mode
(`bypassPermissions`, `acceptEdits`, `auto`, `dontAsk`), unmatched
commands fell through to `Default` (= ask) instead of auto-allowing.

Symptom: on the Claude Code Mac desktop app every Bash command triggered
a permission prompt for `rtk <subcommand>` even with
`defaultMode: "bypassPermissions"` set, defeating the transparent-rewrite
design that opt-in via `rtk init -g` is meant to deliver.

Root cause: `permissions::check_command_with_rules` had no awareness of
`defaultMode`, so the rewrite path never emitted
`hookSpecificOutput.permissionDecision: "allow"` unless the user had
written explicit allow rules — duplicating the global mode at rule level.

Fix:

- New `DefaultMode` enum mirroring the schema at
  json.schemastore.org/claude-code-settings.json.
- `load_permission_rules()` now also reads `permissions.defaultMode`
  with project-local files taking precedence over user-global.
- `check_command_with_rules` takes `default_mode: DefaultMode`. When no
  rule matches and the mode is non-prompting (bypassPermissions,
  acceptEdits, auto, dontAsk), returns `Allow` instead of `Default`.
- Deny and Ask rules still win — the security floor is preserved.
- Plan/Default still fall through to `Default` (least-privilege).

Test additions: 12 new tests covering each defaultMode value, the
deny/ask precedence over auto-allow, compound commands, and from_str
parsing. All 1828 existing tests still pass.
@CLAassistant

CLAassistant commented May 9, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
6 out of 7 committers have signed the CLA.

✅ vsumner
✅ F0rty-Tw0
✅ KuSh
✅ aeppling
✅ mykaul
✅ kherembourg
❌ giulioleone097
You have signed the CLA already but the status is still pending? Let us recheck it.

@rtk-release-bot

Copy link
Copy Markdown
Contributor

Automatic message from CI checks : It seems like this branche is targeting the wrong branch, any contribution should target develop branch.

See CONTRIBUTING.md for details.

@rtk-release-bot rtk-release-bot Bot added the wrong-base PR targets master instead of develop label May 9, 2026
@giulio-leone

Copy link
Copy Markdown

Reopening from correct account targeting develop branch (the default). Will be reposted shortly. Apologies for the noise.

@giulioleone097

Copy link
Copy Markdown
Author

Reopening from correct account (giulio-leone / [email protected]) and targeting develop branch (default). Apologies for the noise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

wrong-base PR targets master instead of develop

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants