Compare commits

...
Author SHA1 Message Date
Nicolas Le Cam f849ef3c28 Merge pull request #3955 from KuSh/refactor/hook-decision-consolidation
refactor(hooks): consolidate the hook decision behind one shared decide
2026-09-11 13:55:21 +02:00
Nicolas Le CamandClaude Opus 5 6eb915bf6f fix(hooks): route rtk hook check through the real decision
`rtk hook check` called `registry::rewrite_command` directly, with no
permission verdict and none of the gates the hooks apply. It therefore
reported a rewrite for command substitutions, file redirects and heredocs
that both hook paths refuse to touch -- the diagnostic disagreed with the
thing it exists to diagnose, and did so in the direction that matters, by
claiming RTK would rewrite a command it deliberately leaves alone.

Route it through `hooks::decision` so it answers the same question, and
report a deny rule distinctly from "no rewrite" rather than collapsing both
into one message. Both still exit 1.

That makes the answer agent-dependent, so `--agent` stops being discarded.
`AgentPath` records what actually differs between agents, which is whose
permission rules their hook consults: the six that decide in-process via
`rtk hook <agent>` use their own host's rules, the five whose plugin shells
out to `rtk rewrite` get Claude's (that entry point cannot be told who is
asking), and the six that install only a rules file have no hook and so no
rules at all. Every install target resolves -- including `codex` and
`openclaw`, which are install flags rather than `AgentTarget` variants --
and only a genuine typo is rejected.

What does *not* differ is a rewrite that changed nothing: every agent
discards it, the in-process hosts in `hook_cmd` and the others in their own
plugin, since `hooks/opencode/rtk.ts`, `hooks/pi/rtk.ts` (shared with omp)
and hermes' `__init__.py` all gate on `rewritten != command`. `AgentPath`
suppresses it for every variant. Only the bare `rtk rewrite` CLI reports the
no-op, and no agent consumes that answer raw.

Consulting no rules and ignoring `--agent` is what made the diagnostic
contradict every host: under a Claude deny rule for `git status` it reported
`rtk git status` while `rtk hook claude` refused the command outright; it
reported a rewrite for `rtk git status`, which no agent applies; and since
`--agent` selected nothing, the answer described no host in particular.

The expectations pinned in the characterization commit are updated here, in
the same commit, so the behavior change is visible as a diff rather than as a
test that quietly stopped asserting. That harness now also asserts the hook
exits 0 and never panics: a crash produces empty stdout, which would let every
"expect no output" assertion pass vacuously. The agent list is derived from
`AgentTarget::value_variants()` so a new variant fails the test instead of
silently becoming unanswerable.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-11 13:51:24 +02:00
Nicolas Le CamandClaude Opus 5 d6ce8f71b6 refactor(hooks): extract the shared hook decision
`rtk hook <agent>` and `rtk rewrite` asked the same question -- may this
command be rewritten, and may the rewrite be auto-allowed? -- through two
independently written copies of the same four steps, over two isomorphic
enums (`HookDecision` and `RewriteOutcome`). A fix to the gate order, or a
new construct to refuse, had to be made twice. #3704 consolidated raw-command
lexing and named this duplication as its follow-up.

Move the decision into `hooks::decision`. What legitimately differs between
the callers stays outside it: `decide_with_params` takes both the permission
verdict and the rewrite parameters, so each host consults its own rules and no
test answers differently on a machine whose config.toml excludes a command
(#3146); `decide` is the wrapper that reads config for production callers.
The identity-rewrite policy is likewise applied by the caller that wants it:
`decide_for_agent` is the composition every hook shares, while `decide`
alone is what the `rtk rewrite` CLI renders.

That policy is the one place the two paths disagree. `get_rewritten`
suppressed a rewrite that changed nothing; `rewrite_cmd` had no such check and
reported it as a normal rewrite. Rather than silently picking a side, the
suppression is now an explicit `suppress_identity` applied at `hook_cmd`'s
single seam, with the difference and its one observable consequence documented
where it lives. Resolving it is a deliberate behavior change and is not part
of this refactor.

`get_rewritten`'s heredoc check is dropped as a duplicate rather than as the
guarantee itself: `rewrite_command` refuses heredocs through its own
`has_heredoc` (registry.rs:601,616), which is what the hook path was asking a
second time. It was also unreachable for the common forms, since a `<<`
operand reads as a file target and `contains_unattestable_construct` returns
first -- the exception being `<< /dev/null`, which that gate lets past and the
registry still refuses (#3980).

`rewrite_cmd::run` is reduced to exit-code rendering and `hook_cmd`'s eight
response builders are unchanged -- `HookDecision` keeps its name, so they
match on the shared type without edits. `rewrite_cmd`'s unattestable-construct
tests are dropped as verbatim duplicates of the shared module's that exercised
nothing in that file.

No behavior change. The characterization tests added in the previous commit
pass unmodified, and the out-of-crate suites are unchanged from their
pre-refactor baselines: hooks/claude/test-rtk-rewrite.sh 58/66 (the 8 are the
pre-existing audit-log gap, `rtk rewrite` never having logged), hermes 18
passed, scripts/test-all.sh 105/13/5. `rtk rewrite "git status"` benchmarks at
6.7ms.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-11 13:51:24 +02:00
Nicolas Le Cam 22d49e327f Merge pull request #1318 from kerta1n/feat/winget-automation
feat(ci): add winget manifest automation
2026-09-11 12:37:41 +02:00
Nicolas Le CamandClaude Opus 5 e8a1ef823e ci(release): pin winget-releaser to a maintained commit
The v2 tag is the action's only tag and has not moved since 2024-11-27,
while development continued on main. Four fixes sit between them, one of
which matters here: the action runs cargo binstall komac, and cargo is
missing on ubuntu-slim runners without it.

Pin to the most recent functional commit rather than to main, whose two
newer commits are documentation only. Its inputs are a superset of the
tag's, so the step needs no other change.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-10 23:10:58 +02:00
aesoft 79347d5e0e Merge branch 'master' into develop 2026-09-10 17:25:43 +02:00
aesoft 52ed9fe400 Merge pull request #3937 from rtk-ai/feat/process-wrapper-prefixes
fix(rewrite): process wrapper prefixes
2026-09-10 13:29:28 +02:00
Adrien Eppling 5b1d523ad2 fix(runner): die by the relayed signal after flushing
Re-raise SIGINT/SIGTERM once output is printed so callers still see signal death, not a plain exit code.
2026-09-10 11:53:47 +02:00
Adrien Eppling 9418aa87a1 fix(runner): keep an inherited SIG_IGN when relaying signals 2026-09-10 10:17:41 +02:00
kerta1n 7be287958e docs: list winget in the installation page description
The frontmatter description renders as the page's meta description and
search snippet, so it advertised an install method list that omitted the
one the page now documents.
2026-09-09 14:21:43 -04:00
kerta1n 7b09caadbe chore(cicd): fail-isolate and pin the winget job
The winget job sat in the release workflow's critical path: cd.yml gates
update-latest-tag on build-release without `if: always()`, so a failed
manifest submission would fail release.yml and leave the 'latest' tag on
the previous version. Mark the job continue-on-error so a submission
failure cannot hold back the release.

Pin winget-releaser to 4ffc7888bffd451b357355dc214d43bb9f23917e (v2)
rather than the mutable major tag, matching the pinning underway across
the repo. The step receives a classic PAT with write access to public
repositories, so the resolved ref should not be able to move underneath
it.
2026-09-09 14:21:39 -04:00
Nicolas Le CamandClaude Opus 5 af28c37216 test(hooks): characterize the hook decision paths end to end
`rtk rewrite`'s exit-code protocol is a public contract -- the claude and
cursor shell hooks, the opencode and pi TypeScript plugins, the hermes
Python adapter and openclaw all branch on it -- but no Rust test ever
called `run()`. `rewrite_cmd`'s own `exit_code_protocol` module asserts
against a locally re-implemented `expected_exit_code()` table, so the real
mapping could change without a single failure, including the #1155
invariant that a `Default` verdict must exit 3 and never 0.

Add an integration test that spawns the binary in a sandboxed
HOME/XDG_CONFIG_HOME/CLAUDE_CONFIG_DIR with project-level permission rules,
and pins the actual (exit code, stdout) pairs for allow, ask, deny,
compound deny, passthrough, default, compound rewrite, fd-dup redirect,
unattestable constructs and heredocs.

Alongside it, pin the two decision paths against each other on one corpus.
`rtk rewrite` and `rtk hook claude` answer the same question through two
independently written flows; the corpus asserts they agree, and a separate
test pins the one place they don't -- an already-RTK-prefixed command,
which the in-process hook defers on and `rtk rewrite` reports as an
ask-rewrite with the command unchanged. Modelled on registry.rs's
`segmenter_consistency` module.

Also pin `rtk hook check`, which had no test at all. It calls
`rewrite_command` directly with no verdict and none of the hooks' gates, so
it reports a rewrite for command substitutions and file redirects that both
hook paths refuse to touch.

No source change: this characterizes today's behavior so the decision-flow
consolidation can be shown to preserve it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-09 04:08:25 +02:00
Adrien Eppling ea67c7ee57 docs(discover): document process wrapper handling 2026-09-08 13:41:53 +02:00
Adrien Eppling 9900d70fd6 fix(runner): flush captured output when rtk is signalled
Relay SIGINT/SIGTERM to the child, escalating to SIGKILL then re-raise so a stubborn child cannot hold rtk open.
2026-09-08 13:41:49 +02:00
Adrien EpplingandYOMXXX b17dda3b69 feat(rewrite): peel process wrapper prefixes
Table-driven timeout/time/nice/nohup; unknown options and shell syntax before the command fall through to passthrough.

Co-authored-by: YOMXXX <liguanchen@xiaomi.com>
2026-09-08 13:41:46 +02:00
kerta1n 2f905f7b62 docs: complete winget coverage, normalise install headings
- README_pt.md: add the winget section (only translation missing it)
- docs/guide/getting-started/installation.md: add winget install and
  uninstall entries
- README_{es,fr,ja,ko,zh}.md: drop the superlative from the winget
  heading so all seven READMEs read "winget (Windows)", matching the
  existing "Homebrew (recommended)" convention
- README.md: shorten the Native Windows heading to "(manual install)",
  move the winget pointer into prose

Deliberately out of scope: docs/guide/getting-started/installation.md
still tells Windows users to use WSL "for full hook support". README.md
contradicts this - native Windows hooks have worked since v0.37.2.
Correcting it means rewriting text this PR does not otherwise touch, so
it is left for a separate change.
2026-09-07 17:26:55 -04:00
kerta1n 69cd16ee1a ci(release): pass release tag via env in winget job
Match the hardening applied to the release, homebrew and notify-discord
jobs in 9cc4937: interpolate inputs.tag and github.event.release.tag_name
into env vars rather than into the run script body.
2026-09-07 17:26:55 -04:00
kerta1n ece41fdcbe Merge branch 'develop' into feat/winget-automation 2026-09-07 17:26:50 -04:00
aesoft fde0a8f185 Merge pull request #3866 from rtk-ai/release-please--branches--master--components--rtk
chore(master): release 0.48.0
2026-09-04 16:34:42 +02:00
rtk-release-bot[bot] 84a652ab05 chore(master): release 0.48.0 2026-09-04 12:42:59 +00:00
aesoft 76b5397d71 Merge pull request #3835 from rtk-ai/develop
Next Release
2026-09-04 14:41:51 +02:00
aesoft 34fe255319 Merge pull request #3805 from rtk-ai/release-please--branches--master--components--rtk
chore(master): release 0.47.0
2026-09-02 09:31:11 +02:00
rtk-release-bot[bot] bd2c46734c chore(master): release 0.47.0 2026-09-01 18:09:31 +00:00
aesoft bdaa79289e Merge pull request #3811 from rtk-ai/develop
Next Release
2026-09-01 20:07:33 +02:00
aesoft cd42c64d1e Merge pull request #3721 from rtk-ai/develop
Next Release
2026-09-01 14:20:56 +02:00
aesoft 8dae5a750f Merge pull request #3718 from rtk-ai/release-please--branches--master--components--rtk
chore(master): release 0.46.0
2026-08-26 21:07:08 +02:00
rtk-release-bot[bot] 36f51239f3 chore(master): release 0.46.0 2026-08-26 18:52:02 +00:00
aesoft 867d31c639 Merge pull request #3544 from rtk-ai/develop
Next Release
2026-08-26 20:50:05 +02:00
aesoft b34be37caf Merge pull request #3468 from rtk-ai/release-please--branches--master--components--rtk
chore(master): release 0.45.0
2026-08-07 11:41:16 +02:00
rtk-release-bot[bot] b73b621d7c chore(master): release 0.45.0 2026-08-07 09:29:18 +00:00
aesoft bbd9a7041c Merge pull request #3367 from rtk-ai/develop
Next Release
2026-08-07 11:27:39 +02:00
aesoft 700bdde334 Merge pull request #3358 from rtk-ai/release-please--branches--master--components--rtk
chore(master): release 0.44.2
2026-08-01 18:46:43 +02:00
rtk-release-bot[bot] 981a6561f4 chore(master): release 0.44.2 2026-08-01 15:55:14 +00:00
aesoft cf04fd318d Merge pull request #3285 from rtk-ai/develop
Next Release
2026-08-01 17:54:03 +02:00
aesoft 36591fb00d Merge pull request #3281 from rtk-ai/release-please--branches--master--components--rtk
chore(master): release 0.44.1
2026-07-28 15:50:46 +02:00
rtk-release-bot[bot] 062468cd18 chore(master): release 0.44.1 2026-07-28 13:21:12 +00:00
aesoft a7fad1f4f5 Merge pull request #3252 from rtk-ai/develop
Next Release
2026-07-28 15:19:48 +02:00
aesoft 3fc4070275 Merge pull request #3217 from rtk-ai/release-please--branches--master--components--rtk
chore(master): release 0.44.0
2026-07-26 14:38:26 +02:00
rtk-release-bot[bot] 50830919f5 chore(master): release 0.44.0 2026-07-26 11:15:29 +00:00
aesoft 63bcebd44b Merge pull request #2774 from rtk-ai/develop
Next Release
2026-07-26 13:13:34 +02:00
kerta1n 5886d6f852 Merge branch 'develop' into feat/winget-automation 2026-07-10 20:39:52 -04:00
aesoft 5a7880d404 Merge pull request #2682 from rtk-ai/release-please--branches--master--components--rtk
chore(master): release 0.43.0
2026-06-28 10:54:56 +02:00
rtk-release-bot[bot] a52a2b2f01 chore(master): release 0.43.0 2026-06-28 08:40:47 +00:00
aesoft 431145c830 Merge pull request #2512 from rtk-ai/develop
Next Release
2026-06-28 10:39:49 +02:00
kerta1n d38cce2ec0 Fix docs per suggestions 2026-04-20 10:46:24 -04:00
kerta1nandClaude Sonnet 4.6 bd14120974 docs: fix winget placement, add for other lang in README and INSTALL
Move placement to make winget command easier to find
Add winget commands into other documentation

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-19 14:22:21 -04:00
kerta1nandClaude Sonnet 4.6 c4090c26a1 feat(ci): add winget manifest automation for Windows package manager
Auto-submit updated manifests to microsoft/winget-pkgs on stable releases
using vedantmgoyal9/winget-releaser. Windows users can now install via
`winget install rtk-ai.rtk`.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-14 21:59:30 -04:00
28 changed files with 2115 additions and 245 deletions

No files matched your search

+34
View File
@@ -368,3 +368,37 @@ jobs:
fi
env:
GH_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
winget:
name: Update winget manifest
needs: [release]
if: ${{ !inputs.prerelease }}
runs-on: ubuntu-latest
# A failed submission must not fail the release workflow: cd.yml gates
# update-latest-tag on build-release, so a red job here would leave the
# 'latest' tag on the previous version.
continue-on-error: true
steps:
- name: Get version
id: version
env:
INPUT_TAG: ${{ inputs.tag }}
RELEASE_TAG: ${{ github.event.release.tag_name }}
run: |
TAG="$INPUT_TAG"
if [ -z "$TAG" ]; then
TAG="$RELEASE_TAG"
fi
VERSION="${TAG#v}"
echo "tag=$TAG" >> $GITHUB_OUTPUT
echo "version=$VERSION" >> $GITHUB_OUTPUT
# Pinned to a main commit, not the v2 tag: v2 has not moved since 2024-11-27
# and is four fixes behind, including cargo binstall on ubuntu-slim runners.
- uses: vedantmgoyal9/winget-releaser@a43926ed822e5a076ac8a81e0a794915cbad51d1 # 2026-03-14
with:
identifier: rtk-ai.rtk
version: ${{ steps.version.outputs.version }}
installers-regex: 'rtk-x86_64-pc-windows-msvc\.zip$'
token: ${{ secrets.WINGET_TOKEN }}
release-tag: ${{ steps.version.outputs.tag }}
+1 -1
View File
@@ -1,3 +1,3 @@
{
".": "0.42.4"
".": "0.48.0"
}
+412 -7
View File
@@ -5,15 +5,420 @@ All notable changes to rtk (Rust Token Killer) will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [0.48.0](https://github.com/rtk-ai/rtk/compare/v0.47.0...v0.48.0) (2026-09-04)
### Changed
* **hooks:** add shared Oh My Pi support and protect Pi/OMP extensions from accidental overwrite or removal, including untouched historical stock revisions
* **hooks:** honor `PI_CODING_AGENT_DIR` for global OMP extension paths and keep dry-run uninstall output consistent
* **hooks:** make shared Pi/OMP path aliasing explicit during uninstall and keep dry-run install behavior non-destructive
* **hooks:** normalize Pi/OMP extension line endings and require explicit confirmation for protected overwrites and shared global uninstalls
* **hooks:** track Pi/OMP ownership for relocated shared extensions, make declined or unreadable protected actions observable (including nonzero `--no-patch` results), recognize older Pi rewrite extensions, and degrade `--show` gracefully for unreadable files
### Features
* add Bun and Deno runtime support ([856c345](https://github.com/rtk-ai/rtk/commit/856c34599a50086e00f145aa2690fdd309a3d136))
* **bun,deno:** add Bun and Deno runtime support ([36788f6](https://github.com/rtk-ai/rtk/commit/36788f6bd4932037caac5cbb1d15d6e2fb9f33da))
* **bun:** route bun x to bunx tool filters ([a9ef10f](https://github.com/rtk-ai/rtk/commit/a9ef10fcb1faa82563f54b7ea431e422236d9e66))
* **runner:** bun and deno test summaries ([f4ac0cc](https://github.com/rtk-ai/rtk/commit/f4ac0cc8a388248ebf079fd0f4cc6c4b26cdf874))
### Bug Fixes
* **benchmark:** skip find's disclosure note and tee pointer when counting names ([c7fc40a](https://github.com/rtk-ai/rtk/commit/c7fc40ab84a50ca11d31cf7270c997f0e59434f2))
* **benchmark:** skip find's disclosure note and tee pointer when counting names ([d952a6b](https://github.com/rtk-ai/rtk/commit/d952a6b5de06fe87a06815024839c128a40392fb))
* **bun,deno:** address review feedback ([55d2390](https://github.com/rtk-ai/rtk/commit/55d239036be584352328b30ee584bfa9a4e53ae9))
* **bun,deno:** fix routing bugs, align with project conventions ([2c52649](https://github.com/rtk-ai/rtk/commit/2c52649bfd8b6dc695e8dc4d4f76b8d2983d1d28))
* **bun,deno:** run via arg vectors, not shell ([2416b8c](https://github.com/rtk-ai/rtk/commit/2416b8c5b7ab4fde3affa6e757a870cc54e2f9a3))
* **bun:** add tee recovery to run_pkg/run_pm_ls ([3b6d1e4](https://github.com/rtk-ai/rtk/commit/3b6d1e4180dddb30bf9381b5c609aeeea13b3a79))
* **bun:** filter combined stdout and stderr ([b850696](https://github.com/rtk-ai/rtk/commit/b850696e3d4885bab9d89f14ffddd8576fb8062d))
* **bun:** parse real pm ls tree output ([4fb2c3a](https://github.com/rtk-ai/rtk/commit/4fb2c3abe1499c8bdae1cefc7ea5c11b67d47913))
* **bun:** route pkg and pm ls through the core runner ([0a7e992](https://github.com/rtk-ai/rtk/commit/0a7e9920955ae14d50077e7fac188c3bc3fedc0e))
* **bun:** stop rejecting valid package specs ([8f056b2](https://github.com/rtk-ai/rtk/commit/8f056b27f8f7c956ae7c47b225d7186bdafe6ba6))
* **deno:** route lint/check through core runner ([d23e158](https://github.com/rtk-ai/rtk/commit/d23e1587e79f90c5d0b404e85e672f785d4b7da3))
* **diff:** don't report byte-different files as identical ([4f3c9fe](https://github.com/rtk-ai/rtk/commit/4f3c9feddd0ef147ad8008cc1bd8f8c054bda051))
* **discover:** derive savings from passthrough status ([e78427b](https://github.com/rtk-ai/rtk/commit/e78427b82f80a7665f72f446c0a02499ebe5f230))
* **discover:** log real hook decisions instead of guessing coverage retroactively ([f57af35](https://github.com/rtk-ai/rtk/commit/f57af3581b86624790bce23cf3e5e31db2c5b53a))
* **discover:** stop crediting passthrough subcommands ([a3cca44](https://github.com/rtk-ai/rtk/commit/a3cca44a0f0e6b2cc9881b6dc23d4e1094551489))
* **filters:** reject unanchored TOML match_command at load ([3522477](https://github.com/rtk-ai/rtk/commit/35224779ea9e30744c16d447a3edef7b26e17851))
* **find:** bound disclosure bookkeeping, disclose through a symlinked root, align the note with ls ([68dc719](https://github.com/rtk-ai/rtk/commit/68dc719ddc084644bab9651853ac6e1d3fcdd95e))
* **find:** report a missing path like find does, and disclose hidden/gitignored matches ([9cf048a](https://github.com/rtk-ai/rtk/commit/9cf048ae8819f0685ebf7b2f7914f48ab243e47e))
* **find:** report a missing path like find does, and disclose hidden/gitignored matches ([765b270](https://github.com/rtk-ai/rtk/commit/765b2709047a0058e4eedf8baa87ac9d6469336b)), closes [#3851](https://github.com/rtk-ai/rtk/issues/3851)
* **js:** correct bun and deno filtering, routing, and accounting ([9bee7a0](https://github.com/rtk-ai/rtk/commit/9bee7a0d8f843949c0dae4420f3c2342c5f0a99b))
* **js:** correct bun and deno runtime behavior ([1173de0](https://github.com/rtk-ai/rtk/commit/1173de0686adb26792598525a6941722c498dd22))
* **js:** keep each caller's behavior for a missing tool ([6ff2571](https://github.com/rtk-ai/rtk/commit/6ff25718207350661bf78fe21d4bddb966b6d69a))
* **js:** run tools through the runner the user named ([c7c1d96](https://github.com/rtk-ai/rtk/commit/c7c1d9663ce4cec3f89965809ee000e04d6e6f90))
* **rebase:** clean up flat-layout stale files and fix i32 return types ([afcad86](https://github.com/rtk-ai/rtk/commit/afcad8691255840324b9572fc903189d0158e16f))
* **runner:** anchor bun test summary extraction ([9e2e4b6](https://github.com/rtk-ai/rtk/commit/9e2e4b6793402c7feca32e79a99e839f1b5d66c3))
* **runner:** keep real diagnostics, drop test stdout ([50bee30](https://github.com/rtk-ai/rtk/commit/50bee3097731cf1be40cc045e4183fdceff35eca))
* **runner:** parse current deno test output format ([65cd2f7](https://github.com/rtk-ai/rtk/commit/65cd2f785165a9a4eff0ae4534d53bd2e3132790))
* **telemetry:** distinguish "consent not given" from missing salt in status ([#1656](https://github.com/rtk-ai/rtk/issues/1656)) ([5189bde](https://github.com/rtk-ai/rtk/commit/5189bdec6ce1c403ec1d69d20378a1375f8cbad5))
* **telemetry:** distinguish "consent not given" from missing salt in status ([#1656](https://github.com/rtk-ai/rtk/issues/1656)) ([ef363a4](https://github.com/rtk-ai/rtk/commit/ef363a4da74f9f512247ed1ce675bad8c46e212c))
* **telemetry:** label the missing salt by the gate that actually fired ([3a0ed92](https://github.com/rtk-ai/rtk/commit/3a0ed926fd53ded92bcd22a50bf3eac73438a368))
* **telemetry:** treat an empty RTK_TELEMETRY_URL as no endpoint ([bb85017](https://github.com/rtk-ai/rtk/commit/bb85017131a137815a400897ddc52a623852b00c))
## [0.47.0](https://github.com/rtk-ai/rtk/compare/v0.46.0...v0.47.0) (2026-09-01)
### ⚠ BREAKING CHANGES
* **grep:** `rtk grep --file-type` and its `-t` short are removed. The option never reached the engine, so it was a silent no-op; `-t` now flows through, which means `rtk rg -t rust` filters by type while `rtk grep -t rust` returns grep's own `invalid option -- 't'`. `-l` and `-m` under `rtk grep` are likewise the native grep flags now rather than rtk's --max-len and --max.
### Features
* **ctest:** add compact output filter ([c75522e](https://github.com/rtk-ai/rtk/commit/c75522e200d6133bca79ef2ba777c29ae9b1df6d))
* **ctest:** add compact output filter ([ab48a68](https://github.com/rtk-ai/rtk/commit/ab48a6836ea18bdfd0dc1e76e7f060d2ca10f141))
* **ls:** cap listing with tee tail hint and standard dotfile semantics ([aa40853](https://github.com/rtk-ai/rtk/commit/aa408534859949ebac1dcc82ec4d25b575a539fa))
* **mvn:** add rtk mvnd support for Maven Daemon ([774465e](https://github.com/rtk-ai/rtk/commit/774465e379a4b723b1239ec0ea1b04c413ed0f10))
* **phpt:** add PHP .phpt filter for php-src run-tests.php (-99%) ([e8541d1](https://github.com/rtk-ai/rtk/commit/e8541d1e1180f7ef4c736322cedc8e834f2f8f77))
### Bug Fixes
* address review feedback on classic diff fallback ([d1a0d9c](https://github.com/rtk-ai/rtk/commit/d1a0d9c2c1bba186fb111f82f8f0e6cec921d71a))
* **benchmark:** assert the find --max cap, count its baseline once ([9b16854](https://github.com/rtk-ai/rtk/commit/9b1685497524daae34ab56304d23068d788c17a8))
* **benchmark:** compare find --max against full find, not head -N ([475f9dd](https://github.com/rtk-ai/rtk/commit/475f9ddfc20dbce4dab206329a36d8303cd9aa09))
* **bench:** stop benchmarking a grep command that errors ([901838d](https://github.com/rtk-ai/rtk/commit/901838ddae373deb7d3c8460d7f97feab2f7577d))
* **bom:** degrade gracefully on unparseable Gemini settings, strip BOM on claude/gemini hook stdin and rtk json fallback ([b6f354c](https://github.com/rtk-ai/rtk/commit/b6f354ca870d7bab30ad439efbf62926f6d9e5af))
* **ctest:** address review round 2 ([4147e99](https://github.com/rtk-ai/rtk/commit/4147e99aa3ee4487e5327cdc0ade33363b1672cf))
* **ctest:** address review round 3 ([87702bf](https://github.com/rtk-ai/rtk/commit/87702bf339e77125213865bac185a017f4cc830b))
* **ctest:** take the run total from the first result line and keep unparsed failures ([acbde6e](https://github.com/rtk-ai/rtk/commit/acbde6e4431e0f9ab23be2c7ccf04b2f0eda65db))
* **ctest:** validate framing lines and tee the failed section once ([6cf56a9](https://github.com/rtk-ai/rtk/commit/6cf56a9c830e786964966a66c991c3923224e14d))
* **ctest:** validate result lines by run total and bypass dashboard modes ([ffe1d45](https://github.com/rtk-ai/rtk/commit/ffe1d453c276799673ac99331ccee8b7cb033efa))
* **ctest:** validate the summary, keep reasons and trailers intact, size the caps ([143dc8c](https://github.com/rtk-ai/rtk/commit/143dc8cf239a80bea3a6f68196fef62bfa5de40c))
* **diff:** keep +/- markers at column 0 in condense_unified_diff ([cf6d99d](https://github.com/rtk-ai/rtk/commit/cf6d99df7619a359e849b9669c4f1972f2c8567a))
* **diff:** keep +/- markers at column 0 in condense_unified_diff ([ca85483](https://github.com/rtk-ai/rtk/commit/ca85483cbcd552548711105bbd429fb4bfc5e70c))
* **diff:** measure savings against the classic diff, not a dump of both files ([8495176](https://github.com/rtk-ai/rtk/commit/8495176c941f8e02df128320055547839ed0ab2a))
* **diff:** remove misleading overflow indicator from condense_unified_diff ([947467e](https://github.com/rtk-ai/rtk/commit/947467ebe285db55d0bf9206db36c773f3ff443f))
* emit classic hunk headers in the diff fallback ([1246ce3](https://github.com/rtk-ai/rtk/commit/1246ce335f4d45e2ed1b011d3df85a604707e322))
* **filters:** address PR review findings on spring-boot/liquibase/ssh ([cab2283](https://github.com/rtk-ai/rtk/commit/cab228398e7716a62c26aed8fb523f76e06d806b))
* **filters:** correct spring-boot description and drop plan artifact ([3853c71](https://github.com/rtk-ai/rtk/commit/3853c7170c94d2502953706a3f81c0e614b26b84))
* **filters:** tighten overly broad spring-boot/liquibase/ssh matching ([0de9610](https://github.com/rtk-ai/rtk/commit/0de9610d443ed1a642101e5c2acf8c6bef03c3d7))
* **git-diff:** count one truncated line as singular ([75dda6c](https://github.com/rtk-ai/rtk/commit/75dda6c0975c7faebbd95aad5b178b4d222abb23))
* **git-diff:** decode quoted paths, and read the header kind before splitting ([7409cb5](https://github.com/rtk-ai/rtk/commit/7409cb56337e620fee5754746ccf02efd55cb93e))
* **git-diff:** emit hunk lines at column 0 so `^-` anchors again ([b166396](https://github.com/rtk-ai/rtk/commit/b16639606f2541a585e83e4cf6cde3836a1f6f29))
* **git-diff:** emit hunk lines at column 0 so `^-` anchors again ([4e811fb](https://github.com/rtk-ai/rtk/commit/4e811fbb4e847b5aeb1331b90beb0a9fe812a8c9))
* **git-diff:** end hunks at their declared length, keep context adjacent ([844d6fa](https://github.com/rtk-ai/rtk/commit/844d6fa3d1410ec995dee4bdc59ec4d8007cbed4))
* **git-diff:** pass word diffs through, and stop guessing at path pairs ([e59276e](https://github.com/rtk-ai/rtk/commit/e59276e5c15976b5afebecc4905f8ac85d0a583e))
* **git-diff:** reset hunk state on combined diffs, exempt leading context ([5d4b549](https://github.com/rtk-ai/rtk/commit/5d4b5492cfff16dfa9da01ee35704c654d7f44e8))
* **git-diff:** slice markers as bytes, and bound a combined hunk by every parent ([eac9b99](https://github.com/rtk-ai/rtk/commit/eac9b996d7406a5d11a2c56bcb1d4d49ace2c04e))
* **git-diff:** stop dropping hunk content that starts with `++` or `--` ([60ec79f](https://github.com/rtk-ai/rtk/commit/60ec79fc4d9752c0268bd96494ba6ca6049777ce))
* **grep:** free -m for GNU --max-count instead of rtk --max ([d9a5893](https://github.com/rtk-ai/rtk/commit/d9a589389d1bd472328fc9d0f98b22cb3e6328f6))
* **grep:** repair the smoke assertion this PR invalidated ([187228d](https://github.com/rtk-ai/rtk/commit/187228dc508ebdf7346cc1882b797cd01984553b))
* **grep:** stop -l and -t shadowing native grep flags ([16228b7](https://github.com/rtk-ai/rtk/commit/16228b74b083f218766e909a8f8c80f3b0e1c171))
* **grep:** stop -l/-t shadowing native grep flags ([4ea0555](https://github.com/rtk-ai/rtk/commit/4ea0555776509a85f66230cd64cd2005bb3ee764))
* **hooks,json:** hermetic gemini BOM test, restore serde diagnostics, honest init summary, zero-copy fallback ([ed8b0eb](https://github.com/rtk-ai/rtk/commit/ed8b0eb50e5471345c7eb241b5be2c4120a647de))
* **hooks:** honor CLAUDE_CONFIG_DIR when loading permission rules ([196780d](https://github.com/rtk-ai/rtk/commit/196780d77cc4172d2c8e262e73eece1e3f553536))
* **hooks:** honor CLAUDE_CONFIG_DIR when loading permission rules ([f4404cb](https://github.com/rtk-ai/rtk/commit/f4404cbc970c2214b2b9e6fd233f4ca06f89b8ea))
* **hooks:** honour exclude_commands for head and tail ([7dc503d](https://github.com/rtk-ai/rtk/commit/7dc503d7513af4a4acb78606f734b6d14b07edb8))
* **hooks:** keep exclude_commands honoured under routable wrappers ([2eed6de](https://github.com/rtk-ai/rtk/commit/2eed6de33644c6907039c704a8d03415122a5a3c))
* **hooks:** match exclude_commands against the peeled command form ([e533c40](https://github.com/rtk-ai/rtk/commit/e533c40901ec7fc85dd0da69be979113348e234d))
* **hooks:** match exclude_commands against the peeled command form ([9ba5239](https://github.com/rtk-ai/rtk/commit/9ba523960b2e49d04e172ba3ebbc12c87a1f08c1))
* **hooks:** strip the BOM on Mistral Vibe hook stdin too ([ac3389a](https://github.com/rtk-ai/rtk/commit/ac3389a5978e2e150e9d126bd8fad589814e7136))
* **init,utils:** propagate Gemini settings parse errors, add from_json_str wrapper ([dd867b2](https://github.com/rtk-ai/rtk/commit/dd867b24e6ce5dd5cab2dafca8da05f65db78bdb))
* **json,deps:** tolerate UTF-8 BOM at the remaining JSON parse sites ([7e7be16](https://github.com/rtk-ai/rtk/commit/7e7be1676b8558ca8e39d9918afe80c820485c99))
* **json,deps:** tolerate UTF-8 BOM at the three remaining JSON parse sites ([a39a872](https://github.com/rtk-ai/rtk/commit/a39a8729ca651563d764c75496aa2ee82b1f0dd3))
* **ls:** avoid underflow in verbose reduction stat ([2f75c7a](https://github.com/rtk-ai/rtk/commit/2f75c7a7b0a0aefb82bb16a63b1a51cb7da58125))
* **ls:** record dot noise dirs under -A and track real args ([a7e7329](https://github.com/rtk-ai/rtk/commit/a7e732946dc3b8c6a03e755026d7425023673083))
* **mvn:** close review findings -- lane routing, summary budgets, mvnd.cmd rewrite ([150845c](https://github.com/rtk-ai/rtk/commit/150845cb66c603ac1ff599dfa5391a19a151cf9e))
* **mvn:** gate lane routing on daemon mode, repair summary cap, phase-marker generations ([ce26d60](https://github.com/rtk-ai/rtk/commit/ce26d60000dd3bc0af496823d898f52554448413))
* **mvn:** gate the Building keeper on arrival, phase-key the failures budget, tag-aware quiet mode ([37663ac](https://github.com/rtk-ai/rtk/commit/37663ac11f89d838d8e25e5b340e0e848737ea45))
* **mvn:** require Surefire's own emission shape to mint a Running lane ([323897b](https://github.com/rtk-ai/rtk/commit/323897b2f463783c19ace1c732d09907fae26fbd))
* **mvn:** second review round -- root-lane disarm, per-lane summary tails, opener narrowing, drop insta ([9e7e01d](https://github.com/rtk-ai/rtk/commit/9e7e01d7dd04f53506d4bcfd02b9f8c461d54dd0))
* **phpt:** use LazyLock and RtkRule::DEFAULT so develop builds ([c84288e](https://github.com/rtk-ai/rtk/commit/c84288edfcd767be7aea2e4eba282deaab365acf))
* **phpt:** use LazyLock and RtkRule::DEFAULT so develop builds ([a419e69](https://github.com/rtk-ai/rtk/commit/a419e691c9b23ab9f32c6fcb10e4ceace678f06e))
* render a real diff instead of dumping both files for modified lines ([e4b9705](https://github.com/rtk-ai/rtk/commit/e4b9705d506fd5771df5ad16ac2957a1e349e2d9))
* render a real diff instead of dumping both files for modified lines ([f2780d4](https://github.com/rtk-ai/rtk/commit/f2780d4cea35402e7bf40edb5a624a279f66bb33))
* **review:** compare fat pointers in render_json, cover droid BOM strip, name files in deps read errors ([9d78af2](https://github.com/rtk-ai/rtk/commit/9d78af249dddf3cbda8a2e781441f3909d13b857))
* **test:** make the -t smoke assertion actually gate something ([b3ae7be](https://github.com/rtk-ai/rtk/commit/b3ae7be09ed351bc2fbcd983a19afa45da3cb2ac))
* **tsc:** count global diagnostics and keep the failure head ([6232c37](https://github.com/rtk-ai/rtk/commit/6232c377e8e36acd9ca609df1642dbb1230f16ea))
* **tsc:** handle pretty diagnostics ([a93d63b](https://github.com/rtk-ai/rtk/commit/a93d63b9b99fbbdded5ce22cb83b9bc032b5b2a5))
* **tsc:** handle pretty diagnostics ([9d1c60a](https://github.com/rtk-ai/rtk/commit/9d1c60ab4e6d103eee7363486d9ddad548c011d1)), closes [#1772](https://github.com/rtk-ai/rtk/issues/1772) [#3220](https://github.com/rtk-ai/rtk/issues/3220)
* **tsc:** strip escapes before the blank filter and bound the failure dump ([1906cb2](https://github.com/rtk-ai/rtk/commit/1906cb2d6ee0fbdc019aa96118c988adba10ded9))
### Performance Improvements
* **hook:** avoid Pi package barrel import ([322db4d](https://github.com/rtk-ai/rtk/commit/322db4da98219b15608d5b71eddf6338c48d693c))
### Miscellaneous Chores
* release 0.47.0 ([fde8b79](https://github.com/rtk-ai/rtk/commit/fde8b79a272713bdbe7314180f8ab4bde99ca957))
### Code Refactoring
* **grep:** trim comments and align the siblings of the flag change ([eb3f814](https://github.com/rtk-ai/rtk/commit/eb3f8148726f3725f1de5b3cb546991d2b562df9))
## [0.46.0](https://github.com/rtk-ai/rtk/compare/v0.45.0...v0.46.0) (2026-08-26)
### Features
* **find:** dispatch on find's grammar; compress find output for unmodeled predicates ([5d697b0](https://github.com/rtk-ai/rtk/commit/5d697b0530ca9f9a7151be257c36a6178774ca5b))
* **find:** tee tail hint when rtk imposes the result cap ([d5a1ddc](https://github.com/rtk-ai/rtk/commit/d5a1ddc92d758d12a36b43659ab20af2817feacd))
### Bug Fixes
* **benchmark:** avoid negative cargo and curl cases ([4947eda](https://github.com/rtk-ai/rtk/commit/4947edaf0e8187151949a9113aba7a9e8d56a30d))
* **benchmark:** avoid negative curl/cargo cases that fail the benchmark job ([ba7a9ce](https://github.com/rtk-ai/rtk/commit/ba7a9ce0d92a46f2458b82b1fcdd000f887f651a))
* **benchmark:** serve curl/wget fixtures from loopback, drop mockhttp.org ([4644fa8](https://github.com/rtk-ai/rtk/commit/4644fa8fa43ab62fdfa87aa84ea99a9227ec3422))
* **cargo:** apply never-worse guard to test summary ([13bd8f2](https://github.com/rtk-ai/rtk/commit/13bd8f216d0b2c299665770d7cdbfff583b1f1c3))
* **cicd:** make benchmark loopback server port-agnostic and cleanup set -e safe ([7f6156f](https://github.com/rtk-ai/rtk/commit/7f6156f3a7b469d9faa89f9a5aad43d0c2c70881))
* **cicd:** stop benchmark.sh deleting the tracked scripts/benchmark harness ([3034b39](https://github.com/rtk-ai/rtk/commit/3034b3923f344f646539c2d31619881db21c3a61))
* **cicd:** stop benchmark.sh deleting the tracked scripts/benchmark harness ([962554d](https://github.com/rtk-ai/rtk/commit/962554d457fc29cc7fc8ed5de9474c6a04000335))
* **core:** decode per line, cover OEM code pages, and centralize on exec_capture ([f496f59](https://github.com/rtk-ai/rtk/commit/f496f59b77a9003a8cf8eefc5e4d7f1f4c4a1bca))
* **core:** decode process output using Windows console code page ([57872f8](https://github.com/rtk-ai/rtk/commit/57872f8d7ea8b4b80c24749b620e0882c57cc9a0))
* **core:** decode process output using Windows console code page ([5bd410e](https://github.com/rtk-ai/rtk/commit/5bd410eb516032e54f0f4b5bc34b5962c5d2785d)), closes [#2452](https://github.com/rtk-ai/rtk/issues/2452)
* **core:** keep the signal diagnostic when capturing child output ([32dc612](https://github.com/rtk-ai/rtk/commit/32dc612c2e35701ca2112b7da8ec489975e184f5))
* **core:** route all child-process output decoding through decode_process_output ([b35ff3a](https://github.com/rtk-ai/rtk/commit/b35ff3a3748677c8d37ce72f8dea32dccec45004))
* **core:** use windows-sys crate for code page detection, fix CI test ([945c3a5](https://github.com/rtk-ai/rtk/commit/945c3a57b3b3f72bd7e8b38c17e37b124da1eeb1))
* **discover:** sanitize drive-letter colon so Windows discover finds sessions ([6f0b0ca](https://github.com/rtk-ai/rtk/commit/6f0b0cad29bca345ecf05212c6d14d2276d964f0))
* **find:** apply never-worse guard against the capped listing ([e5cecd3](https://github.com/rtk-ai/rtk/commit/e5cecd356913db0a6a41842dec4ca3b44e74c873))
* **find:** exec_capture to exec_capture_stdin ([8942e75](https://github.com/rtk-ai/rtk/commit/8942e7575d5afd2c7cb0c9790ed9c3e0d74336b7))
* **find:** forward passthrough output as raw bytes ([0793198](https://github.com/rtk-ai/rtk/commit/0793198d4fd030a90976df456b2542beafc4d977))
* **find:** keep root-relative output and legacy name syntax ([988f2e3](https://github.com/rtk-ai/rtk/commit/988f2e396a3971cbab11747c3f96699c93142f2b))
* **find:** keep the hint under the guard; let find refuse rtk flags before actions; paths like find ([989f453](https://github.com/rtk-ai/rtk/commit/989f453d2f35477629d026de582666e347b9513d))
* **find:** never-worse guard, recovery hint, and dispatch on find's grammar ([203948b](https://github.com/rtk-ai/rtk/commit/203948b3f1edea2d2745f4be22e5cd287b157b71))
* **find:** parse less — rtk flags only in the native subset, find options forwarded ([d3f31dd](https://github.com/rtk-ai/rtk/commit/d3f31dd4d96851e76eb3562e674266aadc4090b1))
* **find:** passthrough to real find on unsupported flags ([6370e79](https://github.com/rtk-ai/rtk/commit/6370e79275ef8c1063fc9b682bc36e7e63041b53))
* **find:** print directory labels in full ([e269b40](https://github.com/rtk-ai/rtk/commit/e269b40d2e0fa50f6d26a50b54035d9bde8933b5))
* **find:** tee in display order so the tail hint returns hidden files ([7d4057e](https://github.com/rtk-ai/rtk/commit/7d4057ea4f05516b55add181e93422c4ef921ac0))
* **find:** track passthrough runs as 0/0 like search.rs ([35db3e1](https://github.com/rtk-ai/rtk/commit/35db3e111e60e9b783e7602adb20246a48bb7780))
* **find:** use the house helpers; honor trailing rtk flags; never block on legacy syntax ([f614c3c](https://github.com/rtk-ai/rtk/commit/f614c3c93dc498919acc07adc4317e441c09530c))
* **git:** --max-parents/--min-parents also only take an attached value ([1a1b306](https://github.com/rtk-ai/rtk/commit/1a1b306e31ec39c18d54d7d44af5d8cb6b53978a))
* **git:** -U, --unified, --expand-tabs don't take a separate-token value ([705a2f8](https://github.com/rtk-ai/rtk/commit/705a2f8a9086ebae1256abdb92da192bab8a5150))
* **git:** add --diff-algorithm/--diff-filter to value-consuming options ([84169e2](https://github.com/rtk-ai/rtk/commit/84169e27daa52fd790652a8d6974ff6f28396f65))
* **git:** don't misdetect a value-taking option's argument as a patch flag ([29f9bb7](https://github.com/rtk-ai/rtk/commit/29f9bb7161775cd807565fd3041eb2b7d1be071c))
* **git:** don't misdetect a value-taking option's argument as a patch flag ([3cc80b2](https://github.com/rtk-ai/rtk/commit/3cc80b243323226214488a837ff9b90a5a86993e))
* **git:** git log --stat/--numstat/etc. weren't requesting raw passthrough ([ca89767](https://github.com/rtk-ai/rtk/commit/ca8976730a6be58a5054485af53945d2ec8db300))
* **git:** preserve patch output from log commands ([d977e1c](https://github.com/rtk-ai/rtk/commit/d977e1c31621fe8704e6500ceeb9c7a0de2b6836))
* **git:** respect -- pathspec separator in git log patch detection ([40e4f3a](https://github.com/rtk-ai/rtk/commit/40e4f3aac9963b4ea3d4d9dbbf0e7a01937cc4f2))
* **git:** restore -- before requests_raw_log_output in run_log ([f8d636d](https://github.com/rtk-ai/rtk/commit/f8d636dde11c72939d0aafe144ad3a40ef918d4e))
* **git:** value/limit/format detection for git log misdetects --grep values as flags ([9bbf55c](https://github.com/rtk-ai/rtk/commit/9bbf55cd07729470a8fc56f2c393d41956411fe4))
* **stream:** address review feedback on read_lines_lossy ([ae5d1ae](https://github.com/rtk-ai/rtk/commit/ae5d1aec0c534aea2e8d374c437a8f81e051208c))
* **stream:** decode lossily instead of dropping lines on invalid UTF-8 ([1989899](https://github.com/rtk-ai/rtk/commit/198989966424a7514a7fae7e1a0190a08d5b500a))
* **tee:** hash long recovery-file slugs to prevent collisions and shorten hints ([983d0c9](https://github.com/rtk-ai/rtk/commit/983d0c956d18a881b83e781bcb40854aa0ac7b2d))
* **test:** accept both Ask and Allow verdicts in rewrite tests ([32c83cc](https://github.com/rtk-ai/rtk/commit/32c83cc60a1fdea24e46992bcbee9f7659d02936))
* **test:** insulate rewrite tests from the machine's permission settings ([668f449](https://github.com/rtk-ai/rtk/commit/668f449faf513aca38f0bc8bbfd70b181c37ac87)), closes [#3146](https://github.com/rtk-ai/rtk/issues/3146)
## [0.45.0](https://github.com/rtk-ai/rtk/compare/v0.44.2...v0.45.0) (2026-08-07)
### Features
* **hooks:** add transparent hook support for Mistral Vibe CLI ([d480f1e](https://github.com/rtk-ai/rtk/commit/d480f1ec481fbd30bce16269a31d5d063bb96023))
* **hooks:** transparent pre_tool rewrite for Mistral Vibe CLI (closes [#800](https://github.com/rtk-ai/rtk/issues/800)) ([de1f568](https://github.com/rtk-ai/rtk/commit/de1f568c50ec4eeaba6b89695050fc08dc6a9d54))
* **rewrite:** rewrite multiline blocks ([3044911](https://github.com/rtk-ai/rtk/commit/3044911b50bc59777d0dedbcd17eb513305c8de5))
### Bug Fixes
* **hooks:** copilot self heal dual hooks (drop camelCase entry) ([9936b2b](https://github.com/rtk-ai/rtk/commit/9936b2b9ce560283d7be21fdfad027cb537be69c))
* **hooks:** heal only rtk's own legacy camelCase entry, keep user config ([db31da9](https://github.com/rtk-ai/rtk/commit/db31da9af4d46ece27f996f350ecbaf6b724e208))
* **hooks:** self-heal stale dual-schema Copilot hook config ([d1f7139](https://github.com/rtk-ai/rtk/commit/d1f71398fde6e071c416cb2b6dbe9665b2bfb488))
* **hooks:** stop Copilot from silently deciding permission on unconfigured commands ([8722378](https://github.com/rtk-ai/rtk/commit/8722378a22d197ad8cc2e86d40b468cc8fb8571d))
* **vibe:** address PR review — exit code contract, tests, telemetry, docs ([1847b07](https://github.com/rtk-ai/rtk/commit/1847b07f7a87fecba7fe0e39ade3d360c897dd66))
## [0.44.2](https://github.com/rtk-ai/rtk/compare/v0.44.1...v0.44.2) (2026-08-01)
### Bug Fixes
* **security:** address followup review comments on private-file hardening ([e0ffd40](https://github.com/rtk-ai/rtk/commit/e0ffd40ef7c450489aca4a50c0ab1358e4375691))
* **security:** address followup review comments on private-file hardening ([2ba02f4](https://github.com/rtk-ai/rtk/commit/2ba02f4b6a4cdadd8ca887b32f81e526a1c53757))
* **security:** create data files owner-only instead of chmod after write ([a1bbcaf](https://github.com/rtk-ai/rtk/commit/a1bbcaf3eb7731b1025d541a961fcba4f06d078c))
* **security:** store history db, tee logs and audit log owner-only ([57b7900](https://github.com/rtk-ai/rtk/commit/57b79008d492bf6e070f7a56e3e25a699c4227a6))
* **security:** store history db, tee logs and audit log owner-only ([9cf7a6d](https://github.com/rtk-ai/rtk/commit/9cf7a6da27a99d65ed3f96a6978ef06abeb16108))
* **security:** tighten data dirs that already exist ([18925c2](https://github.com/rtk-ai/rtk/commit/18925c28346e4f76396ba3bb2fccdda96b14e3ec))
* **tee:** quote recovery hint paths with spaces ([8a24ce2](https://github.com/rtk-ai/rtk/commit/8a24ce2e2828117f69ffc31134ed12f36d33fac4))
## [0.44.1](https://github.com/rtk-ai/rtk/compare/v0.44.0...v0.44.1) (2026-07-28)
### Bug Fixes
* **cicd:** git app token for next release ([48d45d3](https://github.com/rtk-ai/rtk/commit/48d45d366627d405397d974808392f7294266e84))
* **cicd:** git app token for next release ([cdfb14c](https://github.com/rtk-ai/rtk/commit/cdfb14c0f036bc5c6d36a9dc794e536b4f8eca5f))
* **hook:** detect Copilot CLI shell tool on Windows ([7da2674](https://github.com/rtk-ai/rtk/commit/7da2674073394194754a228d346189a74869e6ba))
* **hook:** detect Copilot CLI shell tool on Windows ([10ca886](https://github.com/rtk-ai/rtk/commit/10ca886c92f8423f60c3fcbfd7a75e26f396845f)), closes [#3178](https://github.com/rtk-ai/rtk/issues/3178)
* **search:** display nb line only if requested ([a8b9eb3](https://github.com/rtk-ai/rtk/commit/a8b9eb39011cd64aa715861c2d11820ee55fb221))
## [0.44.0](https://github.com/rtk-ai/rtk/compare/v0.43.0...v0.44.0) (2026-07-26)
### Features
* add git checkout support ([be1844c](https://github.com/rtk-ai/rtk/commit/be1844c7c5bdcdbdad8698c7fb38f6670fdad494))
* add git checkout support ([bb01d6c](https://github.com/rtk-ai/rtk/commit/bb01d6c8ba6dc7dca8dfe209b04703dfef4c4264))
* add uv run support ([a5f0774](https://github.com/rtk-ai/rtk/commit/a5f0774d0ede5071f4d9231efc722e4ad04cded4))
* **cargo:** route --message-format=json builds through explicit arg detection ([5ea03f3](https://github.com/rtk-ai/rtk/commit/5ea03f3d1bd30803a333ead8082ee716e25256fc))
* **hook:** add Cargo.lock ([531bc93](https://github.com/rtk-ai/rtk/commit/531bc9380cd43e10914f1449315201aff15b9153))
* **hook:** add Cargo.lock ([fa0afa5](https://github.com/rtk-ai/rtk/commit/fa0afa51ee9f378670e2c55ab4022976e4e4646c))
* **hook:** add support for Kimi AI agent ([7624c43](https://github.com/rtk-ai/rtk/commit/7624c434882bf8781a0c7281b059397371341525))
* **hooks:** add Factory Droid integration ([8a8b356](https://github.com/rtk-ai/rtk/commit/8a8b356915c62e3a0c505fde76f8871239888e03))
* **hooks:** add Factory Droid integration ([38028b7](https://github.com/rtk-ai/rtk/commit/38028b7ce514e1b0f506d4ba94ea0a2d0589d924))
* **hook:** wire TOML filters + better tee tail hint ([31f9d43](https://github.com/rtk-ai/rtk/commit/31f9d43d81f90d29e89142f3306473e786e59f6c))
* **hook:** wire TOML filters into the rewrite path + reversible truncation ([73b8cb3](https://github.com/rtk-ai/rtk/commit/73b8cb3069297374a3de58552b9fe4aa2cda3a41))
* **php:** consolidated PHP tooling (php, artisan, phpunit, phpstan, pest, paratest, ecs, pint) ([1052c1c](https://github.com/rtk-ai/rtk/commit/1052c1c7027d5a720e3a416a5afb7c1c4c3f5bfc))
* **pipe:** expose PHP tool filters as stdin pipe filters ([214a79a](https://github.com/rtk-ai/rtk/commit/214a79a9ff0a5991ae7dc86badb72f3275333498))
* **sbt:** add SBT (Scala Build Tool) support ([4f86523](https://github.com/rtk-ai/rtk/commit/4f865233db81d9075d237bc8fea82f15013baedc))
* **trust:** gate custom filters (project + user-global) + init opt-in flags ([1130a7c](https://github.com/rtk-ai/rtk/commit/1130a7cafd4df9ca111525dc704a68898594d4ae))
* **trust:** rtk trust uses the same opt-in prompt as init ([e0a83ac](https://github.com/rtk-ai/rtk/commit/e0a83ac824a44450b014838e7bbcb2cfcb872c8f))
### Bug Fixes
* **analytics:** floor prefix slices to char boundary instead of full-string fallback ([c9468ee](https://github.com/rtk-ai/rtk/commit/c9468ee178083aeecbaafb2afdd00887f2eca193))
* **analytics:** truncate display strings on UTF-8 char boundaries ([e200764](https://github.com/rtk-ai/rtk/commit/e20076433e0a8e19801ed5c39e03ea25a98a9c1c))
* **analytics:** truncate display strings on UTF-8 char boundaries ([47b22e0](https://github.com/rtk-ai/rtk/commit/47b22e03a4759972c11032e642710a473b9706ce)), closes [#2787](https://github.com/rtk-ai/rtk/issues/2787)
* **benchmark:** use deterministic curl and wget responses ([3304d90](https://github.com/rtk-ai/rtk/commit/3304d903a6e3eb982ba60a27fb65a85c86f5090d))
* **benchmark:** use deterministic curl and wget responses ([6c57836](https://github.com/rtk-ai/rtk/commit/6c57836bfbfc09bddbafeee171dabe737d009c9b))
* **benchmark:** use stable indexed MockHTTP responses ([8dd5a34](https://github.com/rtk-ai/rtk/commit/8dd5a3476d2a81f1612fbc0be9cac07d09b19e89))
* **cargo:** give the json batch filter the exit code ([a3e65e9](https://github.com/rtk-ai/rtk/commit/a3e65e99e9eb7e1151b726b836b372ab5d857893))
* **cargo:** honor last --message-format when the flag is repeated ([25d6a09](https://github.com/rtk-ai/rtk/commit/25d6a09c01a6d906da49ba8c51f61ce4ee2d7785))
* **cargo:** keep "No issues found" wording for clean clippy json runs ([1f74614](https://github.com/rtk-ai/rtk/commit/1f74614ea8c148fbfe6886b445519e58d32af3ec))
* **cargo:** label check output as "check" instead of "build" ([90b4f5f](https://github.com/rtk-ai/rtk/commit/90b4f5f40fc561bad3616c3aefc3cb21c22c0088))
* **cargo:** match the human path when skipping the json warning summary ([59ed885](https://github.com/rtk-ai/rtk/commit/59ed885752a9ba3e77ee2dd02a75000cc6c1aba9))
* **cargo:** restore failure check before trusting reused build filter ([e4bfe35](https://github.com/rtk-ai/rtk/commit/e4bfe3593c04a497770f6f6492599ac77b3c948d))
* **cargo:** skip "N warnings generated" record in json diagnostics ([9ae0872](https://github.com/rtk-ai/rtk/commit/9ae0872aeebc777f7850d5b4f16b0943fe7bc765))
* **cargo:** strip ansi from json rendered diagnostics ([b47653a](https://github.com/rtk-ai/rtk/commit/b47653a9ec2d5a3fcc1df28b36d23156bb92112a))
* **cargo:** surface --message-format=json build errors instead of "compiled" ([a4b7f74](https://github.com/rtk-ai/rtk/commit/a4b7f7422e5a330c88ad33b9cfda86866a5c8c2c))
* **cargo:** surface --message-format=json clippy errors ([58abbf2](https://github.com/rtk-ai/rtk/commit/58abbf253c0fcca15ccd3d8f7441898fe72b3399))
* **cargo:** surface --message-format=json install errors ([7fb9459](https://github.com/rtk-ai/rtk/commit/7fb9459fc6fe7b4d69ad8abfeb815427b615c368))
* **cargo:** surface --message-format=json test compile errors ([f9b720c](https://github.com/rtk-ai/rtk/commit/f9b720c8f7e7c972739b84679d451e50ba0b6124))
* **cargo:** tee-hint dropped json diagnostics beyond the cap ([cf1caf9](https://github.com/rtk-ai/rtk/commit/cf1caf93b8cdfd2db974ff3cb1b3859cbb955257))
* **cargo:** tighten json warning-summary skip to ends_with ([6c9a60d](https://github.com/rtk-ai/rtk/commit/6c9a60d83e2911f7367642b2e8242d11035118e7))
* **ccusage:** accept `period` key from current ccusage ([d823aaf](https://github.com/rtk-ai/rtk/commit/d823aaf76721d9b0a02cd428ea714980ef80df2c))
* **ccusage:** accept `period` key from current ccusage ([d0a77cd](https://github.com/rtk-ai/rtk/commit/d0a77cdb4844027d37af9c7a6d853ad923cac37a))
* **cicd:** next release pr target fork compatibel ([6e34bba](https://github.com/rtk-ai/rtk/commit/6e34bbaa989487b671952c07105706f006841f23))
* **cicd:** next release pr target fork compatible ([ce30f37](https://github.com/rtk-ai/rtk/commit/ce30f378e3b6797361a73166adcb1238a7c054ad))
* **copilot:** add missing 'get' to kubectl example in init template ([f9d8c77](https://github.com/rtk-ai/rtk/commit/f9d8c775b1e7f94f449c400f4130410170e590ad))
* **copilot:** remove unnecessary test ([b49568f](https://github.com/rtk-ai/rtk/commit/b49568ff730608d6ae815a11ed2ab230aecd5657))
* **copilot:** support IDE terminal hooks ([1d6798d](https://github.com/rtk-ai/rtk/commit/1d6798de8aee0940b490719153e7554845f8f43c))
* **copilot:** support IDE terminal hooks ([d0f004f](https://github.com/rtk-ai/rtk/commit/d0f004f61da16eaba12f69c4542ac6d50754d63d))
* detect absolute rtk path in Claude hook settings ([5d32d07](https://github.com/rtk-ai/rtk/commit/5d32d0736f686b69d1e8b9dc45c007d4eb77a0a2))
* detect absolute rtk path in Claude hook settings ([48b883f](https://github.com/rtk-ai/rtk/commit/48b883f49eacc5c1e9301a5e9fb6916053f632a3))
* **filter:** address review findings in the TOML filter path ([315a943](https://github.com/rtk-ai/rtk/commit/315a94398ec06e70e7cebd3647d5a00a0bd76edc))
* **gain:** note untrusted custom filters so they can be re-trusted ([a4872d9](https://github.com/rtk-ai/rtk/commit/a4872d9bbf1e5002381d6c7973803b7ae2010077))
* **git:** compact git stash show instead of forcing -p ([1b38eec](https://github.com/rtk-ai/rtk/commit/1b38eece9b08ac00d4cd49a7354413485501afcc))
* **git:** compact git stash show instead of forcing -p ([add35e0](https://github.com/rtk-ai/rtk/commit/add35e0928540b44b7bdaa820a3620464e11fbf8))
* **git:** compress git stash show summary line ([0ac5f5c](https://github.com/rtk-ai/rtk/commit/0ac5f5c3118a5e244c58d2dc24d8b9cb0a954b21))
* **grep:** only insert -- separator when context flags are active ([34a0f0e](https://github.com/rtk-ai/rtk/commit/34a0f0e5c00e8f3e98ac8d430b9e1681bdf9b680))
* **grep:** preserve -- separator between non-adjacent match blocks ([6871e55](https://github.com/rtk-ai/rtk/commit/6871e55358acb43a2aa6390565be3b45d64e08b2))
* **grep:** preserve -- separator between non-adjacent match blocks ([cae9b71](https://github.com/rtk-ai/rtk/commit/cae9b710d4aca0f588ea1b1d5b1341b414c3f2c8)), closes [#2795](https://github.com/rtk-ai/rtk/issues/2795)
* **hook:** handle AskRewrite in Cursor hook when no rules configured ([ff0b9ac](https://github.com/rtk-ai/rtk/commit/ff0b9ac28cc1f5215760f123cefff23c62c0821a)), closes [#2372](https://github.com/rtk-ai/rtk/issues/2372)
* **hook:** include ask rules in cursor_has_explicit_rules check ([3362325](https://github.com/rtk-ai/rtk/commit/33623258b8354601bdfd83d1ff6cdb7a2b316fc8))
* **hook:** kimi init writes AGENTS.md instead of dead .kimirules ([8fe4a40](https://github.com/rtk-ai/rtk/commit/8fe4a406125a454450e6ffdbcf743c1a20a12418))
* **hooks:** distinguish explicit ask from default in AskRewrite ([0df6929](https://github.com/rtk-ai/rtk/commit/0df69293ac352f56e507ab9e72d7396abbccc078))
* **hooks:** don't force-allow Droid rewrites ([9dd8211](https://github.com/rtk-ai/rtk/commit/9dd82113adeccdb9597a1f871922f92335643a7b))
* **hooks:** emit permissionDecision allow for simple Copilot CLI rewrites ([23d1e89](https://github.com/rtk-ai/rtk/commit/23d1e899ce89bef54dfa7f3b6f66374c24f311e7))
* **hooks:** emit permissionDecision allow for simple Copilot CLI rewrites ([84aa4d6](https://github.com/rtk-ai/rtk/commit/84aa4d6f71bea0e39e234a0869dd82ee075c7286)), closes [#3037](https://github.com/rtk-ai/rtk/issues/3037)
* **hooks:** install Droid hook into canonical hooks.json ([da36ba3](https://github.com/rtk-ai/rtk/commit/da36ba3935a4c476edaedd3e447c9c58e1bc0f09))
* **hooks:** make Droid verdicts deny-only from explicit lists in all scopes ([3d40742](https://github.com/rtk-ai/rtk/commit/3d407426b5ca63ca7e6bd0f31a572e9b0342b05b))
* **hooks:** source Droid verdicts from Droid's own permission lists ([70ed82a](https://github.com/rtk-ai/rtk/commit/70ed82a7b7af743369daba99a9450cdbf5888049))
* **hook:** use ask action in audit log for AskRewrite verdict ([36dd8f2](https://github.com/rtk-ai/rtk/commit/36dd8f24792b4d36af59a114bdce01d4f5a8cbf1))
* **hook:** use ask permission for AskRewrite in Cursor hook ([a0c16ef](https://github.com/rtk-ai/rtk/commit/a0c16ef0bcf9d7f8403c098c5f26bb4f8dcd98f6))
* **init:** honor RTK_TELEMETRY_DISABLED in consent prompt ([#1307](https://github.com/rtk-ai/rtk/issues/1307)) ([66e09cb](https://github.com/rtk-ai/rtk/commit/66e09cbefe02bf82b159a44278250e45e506810b))
* **init:** honor RTK_TELEMETRY_DISABLED in consent prompt ([#1307](https://github.com/rtk-ai/rtk/issues/1307)) ([debac0f](https://github.com/rtk-ai/rtk/commit/debac0f4c62f875b25a8afa33e57dc4283fd24d7))
* **openclaw:** handle exit code 3 from rtk rewrite ([487a2e7](https://github.com/rtk-ai/rtk/commit/487a2e7b2c381071e61062e5dfff8d2e790c54c8)), closes [#2202](https://github.com/rtk-ai/rtk/issues/2202)
* **parser:** use byte offsets instead of char indices in extract_json_object ([32dda24](https://github.com/rtk-ai/rtk/commit/32dda24e5b71c04d1aabe36f299e4b6d786a5421))
* **parser:** use byte offsets instead of char indices in extract_json_object ([27f9739](https://github.com/rtk-ai/rtk/commit/27f9739b29e5e42bbe927cddf61bbbc03f1e53d9)), closes [#2509](https://github.com/rtk-ai/rtk/issues/2509)
* **permissions:** stop extra whitespace from evading deny rules ([3483786](https://github.com/rtk-ai/rtk/commit/348378602e97a93a4a39449c13cb00882bba44dc))
* **permissions:** stop extra whitespace from evading deny rules ([f6b9290](https://github.com/rtk-ai/rtk/commit/f6b92900603adf00ecd30d2119d63a322a471583))
* **php:** address phpstan review feedback (resolution, text fallback, path compaction) ([07c231e](https://github.com/rtk-ai/rtk/commit/07c231ee4cc31fa1df218a91ec7d8046144c1c7b))
* **php:** align pint/phpstan parsers with current tool schemas ([0b75581](https://github.com/rtk-ai/rtk/commit/0b75581f6b9a2df1a4066b01f0b1d6cf8dbbab37))
* **php:** anchor phpunit failure-heading detection to the "N) " format ([128d04f](https://github.com/rtk-ai/rtk/commit/128d04f7790990a20ee7609f77cc8baa105dc526))
* **php:** classify php subcommands in the PASSTHROUGH list ([4a37246](https://github.com/rtk-ai/rtk/commit/4a37246a051e6b4585a4a396e2581854a930f029))
* **php:** default pint applied_fixers when key is absent ([0cc15dc](https://github.com/rtk-ai/rtk/commit/0cc15dc4484d9bec5a11e770515f8c2d69378de5))
* **php:** detect phpstan analyse after global flags; avoid duplicate format ([7cc46b4](https://github.com/rtk-ai/rtk/commit/7cc46b46766e4b37256f385392ed0c6a4ea7bc85))
* **php:** drop bogus pest.php check in test-runner detection ([28366ce](https://github.com/rtk-ai/rtk/commit/28366ce17bd9f7fe898deee8b2a7ca8e3223c8de))
* **php:** rewrite ./vendor/bin/&lt;tool&gt; form for phpunit/pest/paratest/ecs/pint ([88e56ce](https://github.com/rtk-ai/rtk/commit/88e56cef85dbbaf74f9857ecfa634b9da6db57d9))
* **php:** route php_tool_command through resolved_command ([8eae6b7](https://github.com/rtk-ai/rtk/commit/8eae6b7334ccc43758f8870773c491ebc4e99f35))
* **php:** strip ANSI in phpunit filter and split errors from failures ([8825480](https://github.com/rtk-ai/rtk/commit/8825480b7af671cb7cbf87f8c902f79486d4eb95))
* **pipe:** anchor phpunit auto-detection to the leading banner ([50a8743](https://github.com/rtk-ai/rtk/commit/50a8743041081f7185ecd8e3ca48e432fb8ca5f4))
* **pytest:** strip ANSI so colored runs don't dump raw output ([aba7643](https://github.com/rtk-ai/rtk/commit/aba7643189cd19ed939f4f37b1e0159589a6f151))
* **python:** stop reporting a failed tool run as clean ([86b34df](https://github.com/rtk-ai/rtk/commit/86b34df8e3d4eb48b03b898a58757fccff43592b))
* remove absolute Claude hook commands ([b0c0b20](https://github.com/rtk-ai/rtk/commit/b0c0b204d841193ea83f27e1c194162195d6ab93))
* rewrite only safe final pipeline commands ([590445e](https://github.com/rtk-ai/rtk/commit/590445e7598a37c60b310d8f157dd0b7af7a3421))
* **rewrite:** keep pipeline-final wc commands raw ([1c5a23c](https://github.com/rtk-ai/rtk/commit/1c5a23c64a5912150989626be7e4c3a468848313))
* **ruff:** bound output when user sets --output-format ([fa82e18](https://github.com/rtk-ai/rtk/commit/fa82e18d56d55ddac6d1a18621e492786ed02016))
* **ruff:** honour a user-supplied --output-format ([44982e0](https://github.com/rtk-ai/rtk/commit/44982e070bc4e1668eb66abf1b05caacb0ab14df))
* **run:** propagate signal exit code instead of unwrap_or(1) ([113ae11](https://github.com/rtk-ai/rtk/commit/113ae1188aee7611754a1ac664eec9a138c14257))
* **sbt:** address review feedback on output guard, routing, and dead code ([ef38103](https://github.com/rtk-ai/rtk/commit/ef38103fed2480975b3d729e094628548d83130e))
* **sbt:** compute tee label before args_display move ([3dff2aa](https://github.com/rtk-ai/rtk/commit/3dff2aa0f7d476187db998e00b4a7fc3e5ab1a01))
* **sbt:** drop sbt 0.13 legacy task names ([f6a4c41](https://github.com/rtk-ai/rtk/commit/f6a4c416927663a35eca08f94298300c85154a75))
* **sbt:** filter testOnly/testQuick like sbt test ([194f392](https://github.com/rtk-ai/rtk/commit/194f39253992fbc8f8375159c4694e5936e04a1c))
* **sbt:** filter testOnly/testQuick like sbt test ([c02f4d0](https://github.com/rtk-ai/rtk/commit/c02f4d00f5213b83e189254b9ffe065fe1b0cf9d))
* **sbt:** separate tee label for selective test tasks ([973b3b6](https://github.com/rtk-ai/rtk/commit/973b3b6286049973945f82316ec684e13d205aae))
* **search:** stream piped grep and rg output ([66b95cb](https://github.com/rtk-ai/rtk/commit/66b95cb94abb8c97d35997fb1acd2a891b336e44))
* **test:** adapt new rewrite_command signature in php-tooling tests ([c37eed9](https://github.com/rtk-ai/rtk/commit/c37eed962850af470de5c1bc0a69f26f8ea92ef9))
* tokenize |& as a single pipe operator ([ee149ee](https://github.com/rtk-ai/rtk/commit/ee149ee34a9f1cd82206b1c5f868a6884040d93c))
* **trust:** label detected filters as project- or global-scoped ([a9c33e2](https://github.com/rtk-ai/rtk/commit/a9c33e298768b0f33f401f71ca78f4df272fd936))
* **trust:** skip untrusted filters silently on the command path ([9d3b678](https://github.com/rtk-ai/rtk/commit/9d3b6782420b8ea93267eca91321235f60253fc0))
* **trust:** surface parse errors, skip already-trusted files, fail loudly when non-interactive ([2d487cb](https://github.com/rtk-ai/rtk/commit/2d487cb9477a02e3bebd0ea7b77d7826c724442a))
* **uv:** make tee recovery hints resolve to the data they promise ([bf14bf5](https://github.com/rtk-ai/rtk/commit/bf14bf54f085c1f80510a05150e121cc0c72ab46))
* **uv:** pass guard_raw arg to print_with_hint after signature change ([7e42d92](https://github.com/rtk-ai/rtk/commit/7e42d929e44d7c4fbd412de5dd4e5356613deba5))
* **uv:** preserve program output and restore inner-command filtering ([dfd1810](https://github.com/rtk-ai/rtk/commit/dfd1810dc9d260b8a62931392368a34606301fc0))
* **uv:** preserve program stdout and restore inner-command filtering ([8dd4aac](https://github.com/rtk-ai/rtk/commit/8dd4aacd6d917245c6a3fa2e350dab4309498079))
* **uv:** remove uv run from transparent prefixes to fix rewrite conflicts ([8cdc861](https://github.com/rtk-ai/rtk/commit/8cdc861ede47b3871191265b90e12edc02188a31))
* **uv:** remove uv run from transparent prefixes to fix rewrite conflicts ([96f9422](https://github.com/rtk-ai/rtk/commit/96f94222cbae9c9c9de5e05959388356026db5b6))
### Performance Improvements
* **hook:** match TOML filters with a match-only RegexSet ([34c0bcf](https://github.com/rtk-ai/rtk/commit/34c0bcf2da7b585aa9a2fa619d23764b720c453b))
* **php:** cache composer_bin_dirs to avoid per-segment file reads ([5d2928c](https://github.com/rtk-ai/rtk/commit/5d2928c64e14b96e91a80761136aeb3e27fe5480))
* **php:** resolve cwd once in pint output instead of per file ([b5c3f7f](https://github.com/rtk-ai/rtk/commit/b5c3f7fac56a3f273c3a6517fb920e5970f7c545))
### Reverts
* **cargo:** drop --message-format=json install routing ([751bf3e](https://github.com/rtk-ai/rtk/commit/751bf3e76077db278a54a0bfa5177162478fe8b8))
## [0.43.0](https://github.com/rtk-ai/rtk/compare/v0.42.4...v0.43.0) (2026-06-28)
### Features
* **grep:** sort content alphabetically ([307b557](https://github.com/rtk-ai/rtk/commit/307b5573838d24cc59191c12422ef1f216b9a087))
* **oc:** add Openshift CLI support with shared k8s filtering ([39cbb96](https://github.com/rtk-ai/rtk/commit/39cbb968970d705d2080fc4062397f5b8650b595))
* **oc:** add Openshift CLI support with shared k8s filtering ([c7f493b](https://github.com/rtk-ai/rtk/commit/c7f493b0cd0fbe9ed1d2da8ea66f86f2ca26cd01))
* **pulumi:** add CLI filters for preview/up/destroy/refresh/stack ([ced70c6](https://github.com/rtk-ai/rtk/commit/ced70c6f0dcccd85365dcc78ca58f6b330d799e8))
### Bug Fixes
* **aws:** guard the s3 ls and s3 sync/cp text emits ([25a095e](https://github.com/rtk-ai/rtk/commit/25a095e90d7f8320d80577177f7623b13fa1bbad))
* **core:** never-worse output guard ([af81b08](https://github.com/rtk-ai/rtk/commit/af81b08175af063c8b631979959d80c9007d089f))
* **core:** never-worse output guard so RTK never exceeds the raw command ([861a46d](https://github.com/rtk-ai/rtk/commit/861a46dee57f50216862ac83b0ee57974f383203))
* **diff:** report modified-only diffs and follow diff exit convention ([3a73bcd](https://github.com/rtk-ai/rtk/commit/3a73bcdffc553c0b1b81ea423b98b221468a7289))
* **docker:** make the agent's command authoritative for the guard baseline ([b52db52](https://github.com/rtk-ai/rtk/commit/b52db52da065f65f9838e7fd12c496b7d28d06e8))
* **docker:** report 0 containers/images instead of empty output ([3d4189c](https://github.com/rtk-ai/rtk/commit/3d4189cc6304a8eefc7ab94388b268054b94a634))
* **dotnet:** keep raw fallback when parsed failures incomplete ([5e7eab5](https://github.com/rtk-ai/rtk/commit/5e7eab5846cfe2de1f0d0c2a7d6c38c8de6c65e5))
* **dotnet:** stop duplicating failures on failing test runs ([2d9dc1a](https://github.com/rtk-ai/rtk/commit/2d9dc1ab9e0d25bf7fa6b8696f8909a561dd267f)), closes [#2501](https://github.com/rtk-ai/rtk/issues/2501)
* **dotnet:** stop duplicating failures on failing test runs ([#2501](https://github.com/rtk-ai/rtk/issues/2501)) ([6946bf9](https://github.com/rtk-ai/rtk/commit/6946bf9562a26c7248d64d76564619a7d8dd4dd6))
* **env:** clean up feature from secrets rewrite ([223dda2](https://github.com/rtk-ai/rtk/commit/223dda2996c061e93605d996a14d454a56198ec4))
* **git:** propagate exit code on git status failure in compact path ([d86f007](https://github.com/rtk-ai/rtk/commit/d86f0073ec294d75a705c49c95061bd2c09e2b18))
* **git:** propagate exit code on git status failure in compact path ([756c2a4](https://github.com/rtk-ai/rtk/commit/756c2a4ce84424a17965810392b21c7320b12678))
* **git:** propagate exit code on git worktree list failure ([9a52647](https://github.com/rtk-ai/rtk/commit/9a52647f6529120723a04e5323f2b38be5b22655))
* **git:** propagate exit code on git worktree list failure ([ebaaf8d](https://github.com/rtk-ai/rtk/commit/ebaaf8db586a1a31904a122cd815242e183bd536))
* **git:** propagate exit code when commit fails instead of reporting ok ([2927248](https://github.com/rtk-ai/rtk/commit/29272484de23b1cd1144d97ca6c334da1ee81a61))
* **git:** propagate exit code when commit fails instead of reporting ok ([e36dd8c](https://github.com/rtk-ai/rtk/commit/e36dd8cbe7cf5f37b6c67115d6d53eccc90c94ab)), closes [#2494](https://github.com/rtk-ai/rtk/issues/2494)
* **grep:** correctly handle all flag shapes and never exceed raw output ([ee9e2f8](https://github.com/rtk-ai/rtk/commit/ee9e2f8a2ad9618495dad0f10763f4891ae47be8))
* **grep:** correctly handle all flag shapes and never exceed raw output ([0adfae6](https://github.com/rtk-ai/rtk/commit/0adfae6cf61a90a98a007a6ef4a8745ab6f42a31))
* **grep:** left-to-right cluster scan, long value flags, format passthrough ([b7d93b5](https://github.com/rtk-ai/rtk/commit/b7d93b509e67eee46de3bb518e7ca71429188a4b))
* **grep:** match real grep output and read piped stdin ([37ee6cf](https://github.com/rtk-ai/rtk/commit/37ee6cf6fa7ecb1b511aafd0b111b68ba1d5c945))
* **grep:** restore strip_r as explicit testable helper + pre-existing clippy fix ([8d29f75](https://github.com/rtk-ai/rtk/commit/8d29f75833c9afe5eebdb5d6d1ce1743503421e7))
* **grep:** run the invoked engine instead of substituting rg for grep ([eafadce](https://github.com/rtk-ai/rtk/commit/eafadcee0042411ab9d28339d865a626567a72b0))
* **grep:** stabilize argument parsing — trailing_var_arg, -v invert-match, --version passthrough, safe rg invocation ([d8c550e](https://github.com/rtk-ai/rtk/commit/d8c550eefba41e112bd174d58844a803db6e432f))
* **grep:** surface error on exit code &gt;= 2 instead of false "0 matches" ([d727db3](https://github.com/rtk-ai/rtk/commit/d727db3fa1f5b90d94cd8e1b893b6b10418b42bd)), closes [#2461](https://github.com/rtk-ai/rtk/issues/2461)
* **grep:** surface the engine error and exit code, add nothing ([05f3c54](https://github.com/rtk-ai/rtk/commit/05f3c54886e6d39476b1e65275c599fe4dc470a3))
* **grep:** use portable --null in system grep fallback (BSD/macOS) ([abe7d42](https://github.com/rtk-ai/rtk/commit/abe7d4210e0fe5c0b9322ec5210c6a6aadaa3db5))
* **hook:** rewrite pytest under uv run ([c8722bd](https://github.com/rtk-ai/rtk/commit/c8722bd55e4441ac377b9c141c5f445e62fe9ecc))
* **hook:** treat uv run as a transparent prefix ([34441dd](https://github.com/rtk-ai/rtk/commit/34441dd4648d5f73bf40988de0c9f2c839b3e988))
* **pipe:** apply the never-worse guard ([9d9ad7c](https://github.com/rtk-ai/rtk/commit/9d9ad7cb177a1da22c4395dc6716fdf5e640a6f3))
* **pulumi:** keep Owner and version in pulumi-stack filter ([5cfe4d5](https://github.com/rtk-ai/rtk/commit/5cfe4d5f87cecc7996cdbd837b7bf3dab2518a4e))
* **pulumi:** keep stack identity in pulumi-stack filter ([1f6e36b](https://github.com/rtk-ai/rtk/commit/1f6e36b27ef4fd2237465c97a8e73fbe4e990f61))
* **read:** make guard baseline faithful to cat/cat -n output ([9a2ad90](https://github.com/rtk-ai/rtk/commit/9a2ad90360b39ba8786f6056188ee9a939a9db28))
* **tests:** resync & list oc as passthrough for test ([444f1c0](https://github.com/rtk-ai/rtk/commit/444f1c09082f8a9a843499980f89b8c0682ddfef))
* **vitest:** add passthrough recovery hint ([f9469d1](https://github.com/rtk-ai/rtk/commit/f9469d12cfb48a6dda2b8c0578a7d5696804ae5f))
* **vitest:** preserve explicit reporters ([e3f60e9](https://github.com/rtk-ai/rtk/commit/e3f60e982261cd4a488a9f4593c40b13738f5f35))
## [0.42.4](https://github.com/rtk-ai/rtk/compare/v0.42.3...v0.42.4) (2026-06-12)
Generated
+1 -1
View File
@@ -930,7 +930,7 @@ dependencies = [
[[package]]
name = "rtk"
version = "0.42.4"
version = "0.48.0"
dependencies = [
"anyhow",
"automod",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "rtk"
version = "0.42.4"
version = "0.48.0"
edition = "2021"
rust-version = "1.91"
authors = ["Patrick Szymkowiak"]
+7
View File
@@ -52,6 +52,12 @@ After installation, **verify you have the correct rtk**:
rtk gain # Must show the savings dashboard (not "command not found")
```
### Quick Install (Windows)
```powershell
winget install rtk-ai.rtk
```
### Alternative: Manual Installation
```bash
@@ -265,6 +271,7 @@ cargo uninstall rtk
# If installed via package manager
brew uninstall rtk # macOS Homebrew
winget uninstall rtk-ai.rtk # Windows winget
sudo apt remove rtk # Debian/Ubuntu
sudo dnf remove rtk # Fedora/RHEL
```
+11 -1
View File
@@ -74,6 +74,14 @@ The token counts RTK reports are estimated as `bytes / 4` — RTK ships no token
brew install rtk
```
### winget (Windows)
Easiest way to install on Windows — one command, no PATH setup needed:
```powershell
winget install rtk-ai.rtk
```
### Quick Install (Linux/macOS)
```bash
@@ -368,7 +376,9 @@ By default `RTK.md` says nothing about RTK itself. Set `[awareness] level = "hig
RTK works fully on native Windows. Since **v0.37.2** the auto-rewrite hook runs as a **native binary command** (`rtk hook claude`) — no Unix shell, bash, or jq required — so commands are rewritten transparently on Command Prompt, PowerShell, and Windows Terminal, just like on Linux and macOS.
### Native Windows
### Native Windows (manual install)
Prefer [`winget`](#winget-windows) if you can — it handles PATH for you.
```powershell
# 1. Download and extract rtk-x86_64-pc-windows-msvc.zip from releases
+8
View File
@@ -72,6 +72,14 @@ Los recuentos de tokens que reporta RTK se estiman como `bytes / 4`: RTK no incl
brew install rtk
```
### winget (Windows)
La forma mas facil de instalar en Windows — un solo comando, sin configuracion de PATH:
```powershell
winget install rtk-ai.rtk
```
### Instalacion rapida (Linux/macOS)
```bash
+8
View File
@@ -72,6 +72,14 @@ Les nombres de tokens rapportes par RTK sont estimes avec `octets / 4` : RTK n'e
brew install rtk
```
### winget (Windows)
La manière la plus simple d'installer sur Windows — une seule commande, aucune modification de PATH requise :
```powershell
winget install rtk-ai.rtk
```
### Installation rapide (Linux/macOS)
```bash
+8
View File
@@ -72,6 +72,14 @@ RTK が報告するトークン数は `バイト数 / 4` で見積もられて
brew install rtk
```
### winget(Windows)
Windowsで最も簡単なインストール方法 — コマンド1つ、PATHの設定不要:
```powershell
winget install rtk-ai.rtk
```
### クイックインストール(Linux/macOS)
```bash
+8
View File
@@ -72,6 +72,14 @@ RTK가 보고하는 토큰 수는 `바이트 / 4`로 추정됩니다. RTK에는
brew install rtk
```
### winget (Windows)
Windows에서 가장 쉬운 설치 방법 — 명령어 하나로 끝, PATH 설정 불필요:
```powershell
winget install rtk-ai.rtk
```
### 빠른 설치 (Linux/macOS)
```bash
+8
View File
@@ -73,6 +73,14 @@ As contagens de tokens que o RTK reporta são estimadas como `bytes / 4`: o RTK
brew install rtk
```
### winget (Windows)
A forma mais simples de instalar no Windows — um único comando, sem configuração de PATH:
```powershell
winget install rtk-ai.rtk
```
### Instalação rápida (Linux/macOS)
```bash
+8
View File
@@ -72,6 +72,14 @@ RTK 报告的 token 数量按 `字节数 / 4` 估算:RTK 不内置分词器,
brew install rtk
```
### winget(Windows)
Windows 上最简单的安装方式 — 一条命令,无需配置 PATH:
```powershell
winget install rtk-ai.rtk
```
### 快速安装(Linux/macOS)
```bash
+8 -1
View File
@@ -1,6 +1,6 @@
---
title: Installation
description: Install RTK via curl, Homebrew, Cargo, or from source, and verify the correct version
description: Install RTK via curl, Homebrew, winget, Cargo, or from source, and verify the correct version
sidebar:
order: 1
---
@@ -37,6 +37,12 @@ curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/master/install.sh | sh
brew install rtk-ai/tap/rtk
```
## winget (Windows)
```powershell
winget install rtk-ai.rtk
```
## Cargo
:::caution[Name collision risk]
@@ -92,4 +98,5 @@ rtk init --global
rtk init -g --uninstall # remove hook, RTK.md, and settings.json entry
cargo uninstall rtk # remove binary (if installed via Cargo)
brew uninstall rtk # remove binary (if installed via Homebrew)
winget uninstall rtk-ai.rtk # remove binary (if installed via winget)
```
+13
View File
@@ -160,6 +160,19 @@ where
}
pub fn run(
cmd: Command,
tool_name: &str,
args_display: &str,
mode: RunMode<'_>,
opts: RunOptions<'_>,
) -> Result<i32> {
let result = run_inner(cmd, tool_name, args_display, mode, opts);
// #2375
stream::die_by_relayed_signal();
result
}
fn run_inner(
mut cmd: Command,
tool_name: &str,
args_display: &str,
+132
View File
@@ -268,6 +268,137 @@ impl StreamResult {
}
}
// #2375
#[cfg(unix)]
mod signal_relay {
use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, Ordering};
use std::thread;
use std::time::Duration;
const POLL: Duration = Duration::from_millis(25);
const KILL_GRACE: Duration = Duration::from_millis(750);
const EXIT_GRACE: Duration = Duration::from_millis(750);
static CHILD_PID: AtomicU32 = AtomicU32::new(0);
static RELAYED: AtomicI32 = AtomicI32::new(0);
static FINISHED: AtomicBool = AtomicBool::new(false);
#[allow(unsafe_code)]
unsafe extern "C" fn relay(sig: libc::c_int) {
let pid = CHILD_PID.load(Ordering::SeqCst);
if pid == 0 || RELAYED.swap(sig, Ordering::SeqCst) != 0 {
libc::signal(sig, libc::SIG_DFL);
libc::raise(sig);
return;
}
libc::kill(pid as libc::pid_t, sig);
}
fn escalate(pid: u32) {
thread::sleep(KILL_GRACE);
if FINISHED.load(Ordering::SeqCst) {
return;
}
#[allow(unsafe_code)]
// nosemgrep: unsafe-block
unsafe {
libc::kill(pid as libc::pid_t, libc::SIGKILL);
}
thread::sleep(EXIT_GRACE);
if FINISHED.load(Ordering::SeqCst) {
return;
}
let sig = RELAYED.load(Ordering::SeqCst);
#[allow(unsafe_code)]
// nosemgrep: unsafe-block
unsafe {
libc::signal(sig, libc::SIG_DFL);
libc::raise(sig);
}
}
pub fn relayed() -> Option<libc::c_int> {
match RELAYED.load(Ordering::SeqCst) {
0 => None,
sig => Some(sig),
}
}
pub struct Relay;
impl Relay {
pub fn install(pid: u32) -> Self {
CHILD_PID.store(pid, Ordering::SeqCst);
RELAYED.store(0, Ordering::SeqCst);
FINISHED.store(false, Ordering::SeqCst);
#[allow(unsafe_code)]
// nosemgrep: unsafe-block
unsafe {
for sig in [libc::SIGINT, libc::SIGTERM] {
let previous = libc::signal(sig, relay as *const () as libc::sighandler_t);
if previous == libc::SIG_IGN {
libc::signal(sig, libc::SIG_IGN);
}
}
}
thread::spawn(move || {
while !FINISHED.load(Ordering::SeqCst) {
if RELAYED.load(Ordering::SeqCst) != 0 {
escalate(pid);
return;
}
thread::sleep(POLL);
}
});
Relay
}
}
impl Drop for Relay {
fn drop(&mut self) {
FINISHED.store(true, Ordering::SeqCst);
CHILD_PID.store(0, Ordering::SeqCst);
#[allow(unsafe_code)]
// nosemgrep: unsafe-block
unsafe {
for sig in [libc::SIGINT, libc::SIGTERM] {
if libc::signal(sig, libc::SIG_DFL) == libc::SIG_IGN {
libc::signal(sig, libc::SIG_IGN);
}
}
}
}
}
}
#[cfg(not(unix))]
mod signal_relay {
pub struct Relay;
impl Relay {
pub fn install(_pid: u32) -> Self {
Relay
}
}
}
// #2375
#[cfg(unix)]
pub fn die_by_relayed_signal() {
let Some(sig) = signal_relay::relayed() else {
return;
};
#[allow(unsafe_code)]
// nosemgrep: unsafe-block
unsafe {
libc::signal(sig, libc::SIG_DFL);
libc::raise(sig);
}
}
#[cfg(not(unix))]
pub fn die_by_relayed_signal() {}
pub fn status_to_exit_code(status: std::process::ExitStatus) -> i32 {
if let Some(code) = status.code() {
return code;
@@ -332,6 +463,7 @@ pub fn run_streaming(
let is_streaming = matches!(stdout_mode, FilterMode::Streaming(_));
let mut child = ChildGuard(cmd.spawn().context("Failed to spawn process")?);
let _signal_relay = signal_relay::Relay::install(child.0.id());
let stdin_thread: Option<std::thread::JoinHandle<()>> = match stdin_mode {
StdinMode::Filter(mut filter) => {
+1 -1
View File
@@ -1499,7 +1499,7 @@ pub(crate) fn get_db_path() -> Result<PathBuf> {
// `config::cached_config`), not a fresh `Config::load()`: this runs inside
// `Tracker::new()`, which `log_hook_decision` now calls on every single
// PreToolUse hook invocation — `hook_rewrite_params()` (called earlier in the
// same hook invocation, via `get_rewritten`) already reads config too, so
// same hook invocation, via `hooks::decision::decide`) already reads config too, so
// without caching that's two full disk-read-plus-TOML-parse round trips per
// Bash tool call instead of one.
if let Some(db_path) = crate::core::config::cached_config()
+26
View File
@@ -76,6 +76,32 @@ The `ENV_PREFIX` regex strips env variable assignments and `env` from the front
The prefix is stripped twice: once in `classify_command()` to match the underlying command against rules, and again in `rewrite_segment()` to extract it for re-prepending to the rewritten command.
## Process Wrapper Handling
A process wrapper runs another command without changing which command runs, so
the rewrite peels it, rewrites what it wraps, and re-prepends the wrapper text
byte for byte: `timeout 300 cargo test` becomes `timeout 300 rtk cargo test`.
`PROCESS_WRAPPERS` in `registry.rs` describes each wrapper's own arguments —
options that take a value, options that do not, values that may be attached to
their option, and any positional argument the wrapper consumes before the
command (`timeout`'s duration).
Two rules keep the peeling honest. An option the table does not describe drops
the rewrite, because an unknown option may consume the following word and make
the wrong token look like the command. Shell syntax before the command (a
redirect, a subshell, a glob) does the same, because the wrapper's argv can no
longer be read off the token list.
`stdbuf` is deliberately not a wrapper here: it exists to make the wrapped
command emit output incrementally, and routing through rtk buffers that output
until the child exits, so rewriting it would remove the only reason to type it.
Wrapping also changes who receives a signal. `timeout 300 rtk cargo test`
signals rtk rather than cargo, so `core::stream` relays SIGINT/SIGTERM to the
child and lets the normal filter-and-print path finish. Without that relay a
killed run prints nothing at all, which is strictly worse than the unwrapped
command.
## Adding a New Rewrite Rule
Add an entry to `rules.rs`. Each rule has:
+1 -1
View File
@@ -172,7 +172,7 @@ fn estimate_hook_coverage(permission_cmd: &str, rewrite_cmd: &str, ctx: &Coverag
/// Pure core of `estimate_hook_coverage`, taking the permission verdict directly so
/// it's testable without depending on real config files. Mirrors the real hook's own
/// decision order (`hooks::hook_cmd::decide_from_verdict`): a `Deny`-rule match or an
/// decision order (`hooks::decision::decide`): a `Deny`-rule match or an
/// unattestable construct means the hook would never have rewritten this, regardless
/// of registry support. See `estimate_hook_coverage` for why `permission_cmd` and
/// `rewrite_cmd` can differ.
+321 -3
View File
@@ -1275,6 +1275,58 @@ const ROUTABLE_WRAPPER_PREFIXES: &[&str] = &["uv run"];
/// not spawnable, so they must never fall through: `rtk exec foo` cannot run.
const SHELL_KEYWORD_PREFIXES: &[&str] = &["noglob", "command", "builtin", "exec", "nocorrect"];
struct ProcessWrapper {
name: &'static str,
value_opts: &'static [&'static str],
flag_opts: &'static [&'static str],
attached_opts: &'static [&'static str],
positionals: usize,
numeric_opts: bool,
}
const PROCESS_WRAPPERS: &[ProcessWrapper] = &[
ProcessWrapper {
name: "timeout",
value_opts: &["-s", "-k", "--signal", "--kill-after"],
flag_opts: &["--preserve-status", "--foreground", "-v", "--verbose"],
attached_opts: &["-s", "-k"],
positionals: 1,
numeric_opts: false,
},
ProcessWrapper {
name: "time",
value_opts: &["-f", "-o", "--format", "--output"],
flag_opts: &[
"-p",
"-a",
"-v",
"--append",
"--verbose",
"--portability",
"--quiet",
],
attached_opts: &["-f", "-o"],
positionals: 0,
numeric_opts: false,
},
ProcessWrapper {
name: "nice",
value_opts: &["-n", "--adjustment"],
flag_opts: &[],
attached_opts: &["-n"],
positionals: 0,
numeric_opts: true,
},
ProcessWrapper {
name: "nohup",
value_opts: &[],
flag_opts: &[],
attached_opts: &[],
positionals: 0,
numeric_opts: false,
},
];
struct SafePipeConsumer {
name: &'static str,
unsafe_flags: &'static [&'static str],
@@ -1498,6 +1550,12 @@ fn rewrite_segment_inner(
}
}
// #2375
if let Some((prefix, rest)) = strip_process_wrapper_prefix(trimmed) {
return rewrite_segment_inner(rest, excluded, transparent_prefixes, context, depth + 1)
.map(|rewritten| format!("{} {}", prefix, rewritten));
}
// User-configured wrapper prefixes (e.g. `docker exec mycontainer`). These
// never fall through: an unmatched inner command drops the rewrite.
for prefix in transparent_prefixes {
@@ -1709,6 +1767,104 @@ fn tool_form(cmd_clean: &str, rtk_equivalent: &str) -> String {
.unwrap_or(normalized)
}
fn strip_process_wrapper_prefix(cmd: &str) -> Option<(&str, &str)> {
let tokens = tokenize(cmd);
let first = tokens.first()?;
if first.kind != TokenKind::Arg {
return None;
}
let wrapper = PROCESS_WRAPPERS
.iter()
.find(|candidate| candidate.name == command_basename(&first.value))?;
let inner = wrapper_inner_command(wrapper, &tokens)?;
if tokens[..inner_index(&tokens, inner)]
.iter()
.any(|token| token.value == "rtk")
{
return None;
}
let prefix = cmd[..inner.offset].trim_end();
let rest = cmd[inner.offset..].trim_start();
if prefix.is_empty() || rest.is_empty() {
return None;
}
Some((prefix, rest))
}
fn inner_index(tokens: &[ParsedToken], inner: &ParsedToken) -> usize {
tokens
.iter()
.position(|token| token.offset == inner.offset)
.unwrap_or(tokens.len())
}
fn command_basename(command: &str) -> &str {
command.rsplit('/').next().unwrap_or(command)
}
fn wrapper_inner_command<'a>(
wrapper: &ProcessWrapper,
tokens: &'a [ParsedToken],
) -> Option<&'a ParsedToken> {
let mut idx = 1;
let mut options_done = false;
let mut positionals = wrapper.positionals;
loop {
let token = arg_token(tokens, idx)?;
let arg = token.value.as_str();
if !options_done && arg == "--" {
options_done = true;
idx += 1;
continue;
}
if !options_done && wrapper.numeric_opts && is_numeric_option(arg) {
idx += 1;
continue;
}
if !options_done && arg.starts_with('-') && arg != "-" {
if wrapper.flag_opts.contains(&arg) || takes_attached_value(wrapper, arg) {
idx += 1;
continue;
}
if wrapper.value_opts.contains(&arg) {
arg_token(tokens, idx + 1)?;
idx += 2;
continue;
}
return None;
}
if positionals > 0 {
positionals -= 1;
idx += 1;
continue;
}
return Some(token);
}
}
fn arg_token(tokens: &[ParsedToken], idx: usize) -> Option<&ParsedToken> {
tokens.get(idx).filter(|token| token.kind == TokenKind::Arg)
}
fn is_numeric_option(arg: &str) -> bool {
let Some(digits) = arg.strip_prefix('-').or_else(|| arg.strip_prefix('+')) else {
return false;
};
!digits.is_empty() && digits.chars().all(|c| c.is_ascii_digit())
}
fn takes_attached_value(wrapper: &ProcessWrapper, arg: &str) -> bool {
if let Some((name, _)) = arg.split_once('=') {
return wrapper.value_opts.contains(&name);
}
wrapper
.attached_opts
.iter()
.any(|opt| arg.len() > opt.len() && arg.starts_with(opt))
}
/// Strip a command prefix with word-boundary check.
/// Returns the remainder of the command after the prefix, or `None` if no match.
fn strip_word_prefix<'a>(cmd: &'a str, prefix: &str) -> Option<&'a str> {
@@ -6265,6 +6421,166 @@ mod tests {
);
}
#[test]
fn test_process_wrapper_rewrites_inner_command() {
for (input, expected) in [
("timeout 300 cargo test", "timeout 300 rtk cargo test"),
("time cargo build", "time rtk cargo build"),
("nice -n 10 cargo test", "nice -n 10 rtk cargo test"),
("nohup cargo build", "nohup rtk cargo build"),
(
"/usr/bin/timeout 300 cargo test",
"/usr/bin/timeout 300 rtk cargo test",
),
] {
assert_eq!(
rewrite_command_no_prefixes(input, &[]),
Some(expected.into()),
"{}",
input
);
}
}
#[test]
fn test_process_wrapper_option_forms() {
for (input, expected) in [
(
"timeout -k 5s 300 cargo test",
"timeout -k 5s 300 rtk cargo test",
),
(
"timeout -k5s 300 cargo test",
"timeout -k5s 300 rtk cargo test",
),
(
"timeout --kill-after=5s 300 cargo test",
"timeout --kill-after=5s 300 rtk cargo test",
),
(
"timeout --preserve-status 300 cargo test",
"timeout --preserve-status 300 rtk cargo test",
),
("timeout -- 300 cargo test", "timeout -- 300 rtk cargo test"),
("timeout 300 -- cargo test", "timeout 300 -- rtk cargo test"),
("time -p cargo build", "time -p rtk cargo build"),
("time -f %e cargo build", "time -f %e rtk cargo build"),
("nice -n10 cargo test", "nice -n10 rtk cargo test"),
("nice -10 cargo test", "nice -10 rtk cargo test"),
("nice +5 cargo test", "nice +5 rtk cargo test"),
] {
assert_eq!(
rewrite_command_no_prefixes(input, &[]),
Some(expected.into()),
"{}",
input
);
}
}
#[test]
fn test_process_wrapper_unknown_option_is_passthrough() {
assert_eq!(
rewrite_command_no_prefixes("timeout --unknown 300 cargo test", &[]),
None
);
assert_eq!(
rewrite_command_no_prefixes("nice --unknown cargo test", &[]),
None
);
}
#[test]
fn test_process_wrapper_with_unsupported_inner_command_is_passthrough() {
assert_eq!(
rewrite_command_no_prefixes("timeout 300 mycustombinary --flag", &[]),
None
);
}
#[test]
fn test_process_wrapper_never_doubles_rtk() {
assert_eq!(
rewrite_command_no_prefixes("timeout rtk cargo test", &[]),
None
);
}
#[test]
fn test_process_wrapper_without_inner_command_is_passthrough() {
assert_eq!(rewrite_command_no_prefixes("timeout 300", &[]), None);
assert_eq!(rewrite_command_no_prefixes("time", &[]), None);
assert_eq!(rewrite_command_no_prefixes("timeout -k 5s", &[]), None);
}
#[test]
fn test_process_wrapper_refuses_shell_syntax() {
for input in [
"time (cargo build)",
"timeout 300 >out.log cargo test",
"timeout 300 $(which cargo) test",
"timeout 300 */bin/cargo test",
] {
assert_eq!(rewrite_command_no_prefixes(input, &[]), None, "{}", input);
}
}
#[test]
fn test_stdbuf_is_not_a_process_wrapper() {
assert_eq!(
rewrite_command_no_prefixes("stdbuf -oL cargo test", &[]),
None
);
}
#[test]
fn test_process_wrapper_composes_with_prefixes_and_compounds() {
assert_eq!(
rewrite_command_no_prefixes("CI=1 timeout 300 cargo test", &[]),
Some("CI=1 timeout 300 rtk cargo test".into())
);
assert_eq!(
rewrite_command_no_prefixes("nice -n 10 timeout 300 cargo test", &[]),
Some("nice -n 10 timeout 300 rtk cargo test".into())
);
assert_eq!(
rewrite_command_no_prefixes("timeout 300 cargo test && time git status", &[]),
Some("timeout 300 rtk cargo test && time rtk git status".into())
);
assert_eq!(
rewrite_command_no_prefixes("command timeout 300 git status", &[]),
Some("command timeout 300 rtk git status".into())
);
}
#[test]
fn test_process_wrapper_rewrite_is_idempotent() {
assert_eq!(
rewrite_command_no_prefixes("timeout 300 rtk cargo test", &[]),
None
);
}
#[test]
fn test_process_wrapper_keeps_pipeline_context() {
assert_eq!(
rewrite_command_no_prefixes("timeout 300 git log | head -5", &[]),
Some("timeout 300 rtk git log | head -5".into())
);
assert_eq!(
rewrite_command_no_prefixes("cargo test | timeout 5 grep error", &[]),
Some("cargo test | timeout 5 rtk grep error".into())
);
}
#[test]
fn test_process_wrapper_respects_exclusions() {
assert_eq!(
rewrite_command_no_prefixes("timeout 300 cargo test", &["cargo test".to_string()]),
None
);
}
#[test]
fn test_transparent_prefix_multiple_configured() {
let prefixes = vec!["shadowenv exec --".to_string(), "direnv exec .".to_string()];
@@ -6792,19 +7108,21 @@ mod tests {
/// `jj` is covered only by a TOML filter, never by the native RULES table,
/// so the bare case pins the TOML branch of the rewrite path and keeps the
/// wrapper assertions below from passing vacuously when TOML is disabled.
/// #2375: wrappers are peeled before matching; `is_fully_anchored` in
/// `core::toml_filter` is what keeps a filter off the wrapper itself.
#[test]
fn test_toml_filter_rewrites_bare_command_but_not_wrapped_invocations() {
fn test_toml_filter_rewrites_bare_and_wrapped_invocations() {
assert_eq!(
rewrite_command_no_prefixes("jj log", &[]),
Some("rtk jj log".into()),
);
assert_eq!(
rewrite_command_no_prefixes("timeout 5 /usr/bin/jj log", &[]),
None,
Some("timeout 5 rtk /usr/bin/jj log".into()),
);
assert_eq!(
rewrite_command_no_prefixes("nohup /opt/tools/jj log", &[]),
None,
Some("nohup rtk /opt/tools/jj log".into()),
);
}
+2 -1
View File
@@ -11,7 +11,8 @@ Owns: `rtk init` installation flows (6 agents via `AgentTarget` enum, now includ
Does **not** own: the deployed hook scripts themselves (that's `hooks/`), the rewrite pattern registry (that's `discover/`), or command filtering (that's `cmds/`).
Boundary notes:
- `rewrite_cmd.rs` is a thin CLI bridge — it exists to serve hooks (hooks call `rtk rewrite` as a subprocess) and delegates entirely to `discover/registry`.
- `decision.rs` is the single place RTK decides what a hook should do with a command — deny, defer, rewrite-and-allow, or rewrite-and-ask. All three entry points route through it: the in-process `rtk hook <agent>` hosts (`hook_cmd.rs`), the `rtk rewrite` subprocess path (`rewrite_cmd.rs`), and the `rtk hook check` diagnostic (`main.rs`). Add a gate there, not in a caller.
- `rewrite_cmd.rs` is a thin CLI bridge — it exists to serve hooks (hooks call `rtk rewrite` as a subprocess) and renders `decision.rs`'s verdict as the exit codes those delegates branch on.
- `trust.rs` gates project-local TOML filter execution. It lives here because the trust workflow is tied to hook-installed filter discovery, not to the core filter engine.
## Purpose
+420
View File
@@ -0,0 +1,420 @@
//! The single place RTK decides what a hook should do with a command.
//!
//! Three entry points ask the same question — may this command be rewritten,
//! and may the rewrite be auto-allowed?
//!
//! | Entry point | Verdict source | Identity rewrite |
//! |---|---|---|
//! | `rtk hook <agent>` (`hook_cmd`) | `check_command_for(cmd, host)` | suppressed |
//! | `rtk rewrite` (`rewrite_cmd`, run as a subprocess by the shell/TS/Python delegates) | `check_command` (always `Host::Claude`) | reported |
//! | `rtk hook check` (`main.rs`) | whatever the named `--agent` consults, via [`AgentPath`] | suppressed |
//!
//! [`decide`] is the shared answer. What legitimately differs between callers
//! stays outside it: the verdict is passed in rather than looked up, so each
//! host consults its own permission rules and tests stay independent of the
//! machine's settings (#3146); and the no-op-rewrite policy lives in
//! [`decide_for_agent`], which every hook shares and the CLI does not.
use super::permissions::{check_command_for, Host, PermissionVerdict};
use crate::discover::registry::rewrite_command;
/// What a hook should do with a command.
///
/// `rewrite_cmd` renders these as the exit codes its delegates branch on
/// (`AllowRewrite` → 0, `AskRewrite` → 3, `Deny` → 2, `Defer` → 1); the
/// in-process hosts render them as their own JSON response shapes.
#[derive(Debug, PartialEq)]
pub(crate) enum HookDecision {
/// Rewrite, and the host may auto-allow it — an explicit user allow rule matched.
AllowRewrite(String),
/// Rewrite, but leave approval to the host's own prompt.
AskRewrite(String),
/// Say nothing; let the host handle the command untouched.
Defer,
/// A deny rule matched — stay out of the way of the host's native deny.
Deny,
}
/// Decide what to do with `cmd`, given a permission verdict for it.
///
/// The gate order is load-bearing:
///
/// 1. **Deny wins outright.** Checked before anything else so a denied command
/// is never even considered for rewriting.
/// 2. **Unattestable constructs are refused.** Command substitution and
/// file-target redirects can't be decomposed into segments the permission
/// gate can check individually, so a rewrite could smuggle an unchecked
/// command past an allow rule. `check_command_with_rules` already forces
/// such a command to `Ask`; refusing to rewrite it at all is the stronger
/// guarantee. Heredocs reach the same outcome, though most of them stop at
/// this gate only because a `<<` operand reads as a file target; what
/// actually refuses them is `rewrite_command`'s own `has_heredoc`, which
/// catches the forms this gate lets past (see #3980).
/// 3. **Otherwise rewrite if a rule matches**, and auto-allow only on an
/// explicit `Allow`. Every other verdict — including `Default`, where no
/// rule matched at all — yields `AskRewrite`. `Default` must never reach
/// `AllowRewrite`: that would auto-approve every rewritable command on a
/// machine with no permission rules configured (#1155).
///
/// An identity rewrite (`cmd` was already RTK-prefixed) is reported here as a
/// normal rewrite. Callers that want it suppressed apply [`suppress_identity`].
pub(crate) fn decide(cmd: &str, verdict: PermissionVerdict) -> HookDecision {
let (excluded, transparent_prefixes) = crate::core::config::hook_rewrite_params();
decide_with_params(cmd, verdict, &excluded, &transparent_prefixes)
}
/// [`decide`] with the rewrite parameters supplied by the caller, mirroring
/// [`check_command_with_rules`](super::permissions::check_command_with_rules).
///
/// `hook_rewrite_params` reads the user's `config.toml`, so a test calling
/// [`decide`] changes answer with the developer's own `exclude_commands` and
/// `transparent_prefixes` — an `exclude_commands = ["git"]` on the machine
/// turns an expected rewrite into a defer, and the test fails there and only
/// there. Taking the parameters keeps the decision under test independent of
/// the host configuration, the same way the verdict is passed in rather than
/// looked up (#3146).
pub(crate) fn decide_with_params(
cmd: &str,
verdict: PermissionVerdict,
excluded: &[String],
transparent_prefixes: &[String],
) -> HookDecision {
if verdict == PermissionVerdict::Deny {
return HookDecision::Deny;
}
if crate::discover::lexer::contains_unattestable_construct(cmd) {
return HookDecision::Defer;
}
match rewrite_command(cmd, excluded, transparent_prefixes) {
Some(rewritten) if verdict == PermissionVerdict::Allow => {
HookDecision::AllowRewrite(rewritten)
}
Some(rewritten) => HookDecision::AskRewrite(rewritten),
None => HookDecision::Defer,
}
}
/// [`decide`], plus the no-op suppression every agent applies.
///
/// This is the composition every *hook* wants, as opposed to [`decide`] alone,
/// which is what the `rtk rewrite` CLI renders. Every hook entry point goes
/// through here so they cannot drift apart.
pub(crate) fn decide_for_agent(cmd: &str, verdict: PermissionVerdict) -> HookDecision {
suppress_identity(cmd, decide(cmd, verdict))
}
/// Turn a rewrite that changed nothing into a [`HookDecision::Defer`].
///
/// A command that is already RTK-prefixed rewrites to itself, and a hook that
/// reports that is asking its host to apply an edit with no effect. What that
/// costs is per host: Copilot IDE renders a rewrite as a deny-with-suggestion,
/// so it refuses the command and tells the user to re-run the very thing they
/// ran; Cursor raises a permission prompt for it. The plugins that shell out to
/// `rtk rewrite` reach the same outcome in their own code --
/// `hooks/opencode/rtk.ts`, `hooks/pi/rtk.ts` (shared with omp),
/// `hooks/hermes/rtk-rewrite/__init__.py` and `openclaw/index.ts` all gate on
/// `rewritten != command`.
///
/// `Defer` is not uniformly neutral, though: Gemini renders it as `ask_user`,
/// so there suppression trades a no-op rewrite for a confirmation prompt even
/// when that host's own allow rule covers the command.
///
/// The comparison is byte-exact while `rewrite_command` returns a trimmed,
/// continuation-collapsed string, so a command differing only in leading or
/// trailing whitespace is not suppressed.
///
/// `rtk rewrite` itself reports the no-op as a normal rewrite, exit 0 or 3 with
/// the command unchanged on stdout. It answers "what is the RTK form of this
/// command", and for an already-prefixed one that form is itself; whether that
/// counts as a change is the caller's question, which is why those plugins
/// compare. `decision_consistency` in `tests/hook_decision_protocol_test.rs`
/// pins the difference.
pub(crate) fn suppress_identity(cmd: &str, decision: HookDecision) -> HookDecision {
match decision {
HookDecision::AllowRewrite(ref rewritten) | HookDecision::AskRewrite(ref rewritten)
if rewritten == cmd =>
{
HookDecision::Defer
}
other => other,
}
}
/// How the hook RTK installs for a given `--agent` actually reaches a decision.
///
/// `rtk init` supports more agents than [`Host`] has variants, because they
/// differ in *whose* permission rules their hook consults — not all of them
/// consult any. A diagnostic that ignores that reports the wrong hook's answer.
///
/// They do not differ on a rewrite that changed nothing: every agent discards
/// it. The in-process hosts do so in `hook_cmd`; the ones that shell out to
/// `rtk rewrite` do so in their own plugin, because `rtk rewrite` reports the
/// no-op rather than suppressing it (see [`suppress_identity`]).
pub(crate) enum AgentPath {
/// `rtk hook <agent>` — decides in this process, against the host's own
/// permission rules.
InProcess(Host),
/// A plugin or shell script that shells out to `rtk rewrite`. That entry
/// point has no way to be told which host is asking, so it always reads
/// Claude Code's rules.
ViaRewrite,
/// A rules-file install — RTK ships instructions telling the agent to
/// prefix commands itself. There is no hook and no permission surface, so
/// only the rewrite rules apply.
RulesOnly,
}
impl AgentPath {
/// The path for an `--agent` value, reporting the accepted values on stderr
/// when there is no such install target.
///
/// Every [`crate::AgentTarget`] must resolve, plus the targets installed by
/// a flag rather than an enum variant — `rtk init --copilot`, `--gemini`,
/// `--codex`, `--opencode`, and OpenClaw's own installer — pinned by
/// `agent_path_covers_every_install_target`.
// Reached only from `rtk hook check`, never from a hook's own stream.
#[allow(clippy::print_stderr)]
pub(crate) fn from_agent(agent: &str) -> Option<Self> {
let path = Self::lookup(agent);
if path.is_none() {
eprintln!(
"Unknown agent: {} (expected one of: {})",
agent,
Self::AGENTS.join(", ")
);
}
path
}
/// The mapping itself, so tests can exercise it without writing to stderr.
fn lookup(agent: &str) -> Option<Self> {
match agent {
// `copilot` reads Claude Code's settings rather than a Copilot file
// (see `hook_cmd`'s `vscode_response` and `copilot_cli_response`).
"antigravity" | "cline" | "codex" | "kilocode" | "kimi" | "windsurf" => {
Some(Self::RulesOnly)
}
"claude" | "copilot" => Some(Self::InProcess(Host::Claude)),
"cursor" => Some(Self::InProcess(Host::Cursor)),
"droid" => Some(Self::InProcess(Host::Droid)),
"gemini" => Some(Self::InProcess(Host::Gemini)),
"hermes" | "omp" | "openclaw" | "opencode" | "pi" => Some(Self::ViaRewrite),
"vibe" => Some(Self::InProcess(Host::Vibe)),
_ => None,
}
}
/// The `--agent` values [`AgentPath::lookup`] accepts.
const AGENTS: &'static [&'static str] = &[
"antigravity",
"claude",
"cline",
"codex",
"copilot",
"cursor",
"droid",
"gemini",
"hermes",
"kilocode",
"kimi",
"omp",
"openclaw",
"opencode",
"pi",
"vibe",
"windsurf",
];
/// The verdict this agent's hook would judge `cmd` against.
fn verdict(&self, cmd: &str) -> PermissionVerdict {
match self {
Self::InProcess(host) => check_command_for(cmd, *host),
// `rtk rewrite` always reads Claude Code's rules.
Self::ViaRewrite => check_command_for(cmd, Host::Claude),
// No hook, so no rules to consult.
Self::RulesOnly => PermissionVerdict::Default,
}
}
/// What this agent's hook would do with `cmd` — the same answer it gives at
/// runtime, including discarding a rewrite that changed nothing.
pub(crate) fn decide(&self, cmd: &str) -> HookDecision {
decide_for_agent(cmd, self.verdict(cmd))
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A rewritable command with no rule matching it is an ask-rewrite, never
/// an allow-rewrite (#1155).
#[test]
fn default_verdict_asks_rather_than_allows() {
assert!(matches!(
decide_with_params("git status", PermissionVerdict::Default, &[], &[]),
HookDecision::AskRewrite(_)
));
}
#[test]
fn explicit_allow_permits_the_rewrite() {
assert!(matches!(
decide_with_params("git status", PermissionVerdict::Allow, &[], &[]),
HookDecision::AllowRewrite(_)
));
}
#[test]
fn deny_wins_before_anything_else() {
assert_eq!(
decide_with_params("git status", PermissionVerdict::Deny, &[], &[]),
HookDecision::Deny
);
}
#[test]
fn command_without_an_rtk_equivalent_defers() {
assert_eq!(
decide_with_params("htop", PermissionVerdict::Default, &[], &[]),
HookDecision::Defer
);
}
/// Refused whatever the verdict: the permission gate can't decompose these
/// into segments it can check, so a rewrite could carry an unchecked
/// command past an allow rule.
#[test]
fn unattestable_constructs_defer() {
for cmd in [
"git status `rm -rf /tmp/x`",
"git status $(rm -rf /tmp/x)",
"git log --pretty=\"$(rm -rf /tmp/x)\"",
"git log > /tmp/out.txt",
] {
assert_eq!(
decide_with_params(cmd, PermissionVerdict::Default, &[], &[]),
HookDecision::Defer,
"cmd: {cmd}"
);
}
}
/// A file-descriptor dup is not a file target — the rewrite still happens.
#[test]
fn fd_dup_redirect_still_rewrites() {
assert!(matches!(
decide_with_params("git status 2>&1", PermissionVerdict::Default, &[], &[]),
HookDecision::AskRewrite(_)
));
}
#[test]
fn heredoc_defers() {
assert_eq!(
decide_with_params(
"cat <<'EOF'\nhello\nEOF",
PermissionVerdict::Default,
&[],
&[]
),
HookDecision::Defer
);
}
/// `decide` itself reports a no-op rewrite as a normal one; only
/// `suppress_identity` turns it into a defer. `rtk rewrite` depends on the
/// former, the in-process hosts on the latter.
#[test]
fn identity_rewrite_is_reported_and_only_suppressed_on_request() {
let cmd = "rtk git status";
let decided = decide_with_params(cmd, PermissionVerdict::Default, &[], &[]);
assert_eq!(decided, HookDecision::AskRewrite(cmd.to_string()));
assert_eq!(suppress_identity(cmd, decided), HookDecision::Defer);
}
/// Suppression only fires on an actual no-op — a real rewrite is untouched.
#[test]
fn suppress_identity_leaves_a_real_rewrite_alone() {
let decided = decide_with_params("git status", PermissionVerdict::Allow, &[], &[]);
assert_eq!(
suppress_identity("git status", decided),
HookDecision::AllowRewrite("rtk git status".to_string())
);
}
/// Suppression only ever collapses a rewrite: a decision that carries no
/// rewritten command passes through untouched, so it can never mask a deny.
#[test]
fn suppress_identity_passes_deny_and_defer_through() {
assert_eq!(
suppress_identity("x", HookDecision::Deny),
HookDecision::Deny
);
assert_eq!(
suppress_identity("x", HookDecision::Defer),
HookDecision::Defer
);
}
/// Every install target `rtk` supports must resolve, or `rtk hook check`
/// rejects an agent the user really installed. Derived from `AgentTarget`
/// so a new variant fails here instead of silently going unanswerable.
#[test]
fn agent_path_covers_every_install_target() {
use clap::ValueEnum;
for variant in crate::AgentTarget::value_variants() {
let name = variant
.to_possible_value()
.expect("AgentTarget variant is not skipped")
.get_name()
.to_string();
assert!(
AgentPath::lookup(&name).is_some(),
"unmapped AgentTarget: {name}"
);
assert!(
AgentPath::AGENTS.contains(&name.as_str()),
"AgentTarget missing from the error message: {name}"
);
}
// Install targets reached by a flag rather than an `AgentTarget`
// variant, so the loop above cannot see them.
for name in ["codex", "copilot", "gemini", "openclaw", "opencode"] {
assert!(AgentPath::lookup(name).is_some(), "unmapped: {name}");
assert!(AgentPath::AGENTS.contains(&name), "not listed: {name}");
}
}
/// Everything advertised in the error message must actually resolve.
#[test]
fn every_listed_agent_resolves() {
for name in AgentPath::AGENTS {
assert!(
AgentPath::lookup(name).is_some(),
"listed but unmapped: {name}"
);
}
}
#[test]
fn agent_path_rejects_the_unknown() {
assert!(AgentPath::lookup("nope").is_none());
assert!(AgentPath::lookup("").is_none());
assert!(AgentPath::lookup("Claude").is_none());
}
/// A rules-file agent has no hook and no permission rules, so its answer
/// must not depend on any host's settings.
#[test]
fn rules_only_agent_uses_the_default_verdict() {
assert_eq!(
AgentPath::RulesOnly.verdict("git status"),
PermissionVerdict::Default
);
}
}
+5 -57
View File
@@ -4,6 +4,7 @@
//! corrupts the JSON protocol (Claude Code bug #4669 silently disables the hook).
use super::constants::PRE_TOOL_USE_KEY;
use super::decision::{self, HookDecision};
use super::permissions::{self, PermissionVerdict};
use anyhow::{Context, Result};
use serde_json::{json, Value};
@@ -11,7 +12,6 @@ use std::io::{self, Read, Write};
use crate::core::tracking::HookOutcome;
use crate::core::utils::strip_leading_bom;
use crate::discover::registry::{has_heredoc, rewrite_command};
const STDIN_CAP: usize = 1_048_576; // 1 MiB
@@ -233,42 +233,14 @@ fn heal_legacy_hook_file(path: &std::path::Path) -> bool {
.is_ok()
}
fn get_rewritten(cmd: &str) -> Option<String> {
if has_heredoc(cmd) {
return None;
}
let (excluded, transparent_prefixes) = crate::core::config::hook_rewrite_params();
let rewritten = rewrite_command(cmd, &excluded, &transparent_prefixes)?;
if rewritten == cmd {
return None;
}
Some(rewritten)
}
enum HookDecision {
AllowRewrite(String),
AskRewrite(String),
Defer,
Deny,
}
/// The decision every hook applies -- [`decision::decide_for_agent`] -- plus the
/// recall bookkeeping the hook path performs for any command it does not deny.
fn decide_from_verdict(cmd: &str, verdict: PermissionVerdict) -> HookDecision {
if verdict == PermissionVerdict::Deny {
return HookDecision::Deny;
}
crate::hooks::rewrite_cmd::track_tee_read(cmd);
if crate::discover::lexer::contains_unattestable_construct(cmd) {
return HookDecision::Defer;
}
match get_rewritten(cmd) {
Some(r) if verdict == PermissionVerdict::Allow => HookDecision::AllowRewrite(r),
Some(r) => HookDecision::AskRewrite(r),
None => HookDecision::Defer,
}
decision::decide_for_agent(cmd, verdict)
}
fn decide_hook_action(cmd: &str, host: permissions::Host) -> HookDecision {
@@ -1006,6 +978,7 @@ fn run_droid_inner_with_rules(
#[cfg(test)]
mod tests {
use super::*;
use crate::hooks::permissions::PermissionVerdict;
fn rewrite_command_no_prefixes(cmd: &str, excluded: &[String]) -> Option<String> {
crate::discover::registry::rewrite_command(cmd, excluded, &[])
@@ -1119,26 +1092,6 @@ mod tests {
assert!(matches!(detect_format(&json!({})), HookFormat::PassThrough));
}
#[test]
fn test_get_rewritten_supported() {
assert!(get_rewritten("git status").is_some());
}
#[test]
fn test_get_rewritten_unsupported() {
assert!(get_rewritten("htop").is_none());
}
#[test]
fn test_get_rewritten_already_rtk() {
assert!(get_rewritten("rtk git status").is_none());
}
#[test]
fn test_get_rewritten_heredoc() {
assert!(get_rewritten("cat <<'EOF'\nhello\nEOF").is_none());
}
// --- VS Code Copilot Chat / Copilot CLI (PascalCase) handler ---
// Serves both VS Code Copilot Chat's PreToolUse hook and Copilot CLI's
// PascalCase-compat entry (#3037): the same `rtk hook copilot` call
@@ -2026,11 +1979,6 @@ mod tests {
check_command_with_rules("cargo test", &deny, &[], &[]),
PermissionVerdict::Deny
);
// Denied commands must not be rewritten — Gemini handler checks deny before rewrite
assert!(
get_rewritten("cargo test").is_some(),
"cargo test should be rewritable when not denied"
);
}
// --- Shared decision flow (all hosts route through this) ---
+5
View File
@@ -1,6 +1,11 @@
//! Hook installation and lifecycle management for AI coding agents.
pub mod constants;
// Shares `hook_cmd`'s constraint: it runs inside the hook, where stray output
// corrupts the JSON protocol. `from_agent` is the one exception and carries its
// own allow -- it is reached only from the `rtk hook check` CLI.
#[deny(clippy::print_stdout, clippy::print_stderr)]
pub mod decision;
pub mod hook_audit_cmd;
pub mod hook_check;
#[deny(clippy::print_stdout, clippy::print_stderr)]
+29 -164
View File
@@ -1,20 +1,9 @@
//! Translates a raw shell command into its RTK-optimized equivalent.
use super::permissions::{check_command, PermissionVerdict};
use crate::discover::registry;
use super::decision::{self, HookDecision};
use super::permissions::check_command;
use std::io::Write;
/// Run the `rtk rewrite` command.
///
/// Prints the RTK-rewritten command to stdout and exits with a code that tells
/// the caller how to handle permissions:
///
/// | Exit | Stdout | Meaning |
/// |------|----------|--------------------------------------------------------------|
/// | 0 | rewritten| Rewrite allowed — hook may auto-allow the rewritten command. |
/// | 1 | (none) | No RTK equivalent — hook passes through unchanged. |
/// | 2 | (none) | Deny rule matched — hook defers to Claude Code native deny. |
/// | 3 | rewritten| Ask rule matched — hook rewrites but lets Claude Code prompt.|
const TEE_READERS: &[&str] = &[
"cat", "tail", "head", "less", "more", "bat", "grep", "rg", "sed", "awk",
];
@@ -71,74 +60,50 @@ pub(crate) fn track_tee_read(cmd: &str) {
}
}
/// Run the `rtk rewrite` command.
///
/// Prints the RTK-rewritten command to stdout and exits with a code that tells
/// the caller how to handle permissions:
///
/// | Exit | Stdout | Meaning |
/// |------|----------|--------------------------------------------------------------|
/// | 0 | rewritten| Rewrite allowed — hook may auto-allow the rewritten command. |
/// | 1 | (none) | No RTK equivalent — hook passes through unchanged. |
/// | 2 | (none) | Deny rule matched — hook defers to Claude Code native deny. |
/// | 3 | rewritten| Ask rule matched — hook rewrites but lets Claude Code prompt.|
///
/// The decision itself is [`decision::decide`], shared with the in-process
/// `rtk hook <agent>` path; this function is only its exit-code rendering.
pub fn run(cmd: &str) -> anyhow::Result<()> {
let (excluded, transparent_prefixes) = crate::core::config::hook_rewrite_params();
let outcome = evaluate(cmd, &excluded, &transparent_prefixes);
if !matches!(outcome, RewriteOutcome::Deny) {
// `rtk rewrite` is a subprocess entry point with no way to be told which
// host is asking, so every delegate that shells out to it -- hermes, omp,
// opencode, openclaw, pi -- is judged against `~/.claude`'s rules. The
// in-process `rtk hook <agent>` path is host-parameterized instead
// (`permissions::Host`).
let decided = decision::decide(cmd, check_command(cmd));
if !matches!(decided, HookDecision::Deny) {
track_tee_read(cmd);
}
match outcome {
RewriteOutcome::Allow(rewritten) => {
match decided {
HookDecision::AllowRewrite(rewritten) => {
print!("{}", rewritten);
let _ = std::io::stdout().flush();
Ok(())
}
RewriteOutcome::Ask(rewritten) => {
HookDecision::AskRewrite(rewritten) => {
print!("{}", rewritten);
let _ = std::io::stdout().flush();
std::process::exit(3);
}
RewriteOutcome::Deny => std::process::exit(2),
RewriteOutcome::Passthrough => std::process::exit(1),
}
}
#[derive(Debug, PartialEq)]
enum RewriteOutcome {
Allow(String),
Passthrough,
Deny,
Ask(String),
}
fn evaluate(cmd: &str, excluded: &[String], transparent_prefixes: &[String]) -> RewriteOutcome {
evaluate_with_verdict(cmd, check_command(cmd), excluded, transparent_prefixes)
}
/// Decision logic for [`evaluate`] with the permission verdict supplied by the
/// caller, mirroring [`check_command_with_rules`](super::permissions::check_command_with_rules).
///
/// `check_command` reads the machine's Claude Code settings files, so tests that
/// call [`evaluate`] directly would change verdict with the developer's local
/// `settings.local.json`. Taking the verdict as a parameter keeps the rewrite
/// logic under test independent of the host configuration (#3146).
fn evaluate_with_verdict(
cmd: &str,
verdict: PermissionVerdict,
excluded: &[String],
transparent_prefixes: &[String],
) -> RewriteOutcome {
if verdict == PermissionVerdict::Deny {
return RewriteOutcome::Deny;
}
if crate::discover::lexer::contains_unattestable_construct(cmd) {
return RewriteOutcome::Passthrough;
}
match registry::rewrite_command(cmd, excluded, transparent_prefixes) {
Some(rewritten) => match verdict {
PermissionVerdict::Allow => RewriteOutcome::Allow(rewritten),
_ => RewriteOutcome::Ask(rewritten),
},
None => RewriteOutcome::Passthrough,
HookDecision::Deny => std::process::exit(2),
HookDecision::Defer => std::process::exit(1),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::discover::registry;
#[test]
fn test_tee_read_slug_detects_tail_hint_command() {
@@ -223,106 +188,6 @@ mod tests {
);
}
/// The verdict still drives the outcome: an allow rule yields `Allow`.
/// Pinning both directions keeps the mapping covered without depending
/// on which rules the developer happens to have configured.
#[test]
fn test_allow_verdict_yields_allow() {
assert!(matches!(
evaluate_with_verdict("git status", PermissionVerdict::Allow, &[], &[]),
RewriteOutcome::Allow(_)
));
}
#[test]
fn test_deny_verdict_yields_deny() {
assert_eq!(
evaluate_with_verdict("git status", PermissionVerdict::Deny, &[], &[]),
RewriteOutcome::Deny
);
}
/// Commands with an unattestable construct are always a passthrough,
/// regardless of permission verdict.
///
/// The verdict is pinned to `Default` rather than going through `evaluate`,
/// which reads the developer's own `.claude/settings.local.json`: a
/// `Bash(git *)` allow rule turns the expected `Ask` into `Allow` and these
/// tests fail on that machine only (#3146). Pinning the verdict keeps the
/// assertions about the rewrite logic and nothing about the host.
mod unattestable_passthrough {
use super::super::{evaluate_with_verdict, RewriteOutcome};
use crate::hooks::permissions::PermissionVerdict;
#[test]
fn test_backtick_substitution_passthrough() {
assert_eq!(
evaluate_with_verdict(
"git status `rm -rf /tmp/x`",
PermissionVerdict::Default,
&[],
&[]
),
RewriteOutcome::Passthrough
);
}
#[test]
fn test_dollar_substitution_passthrough() {
assert_eq!(
evaluate_with_verdict(
"git status $(rm -rf /tmp/x)",
PermissionVerdict::Default,
&[],
&[]
),
RewriteOutcome::Passthrough
);
}
#[test]
fn test_double_quoted_substitution_passthrough() {
assert_eq!(
evaluate_with_verdict(
"git log --pretty=\"$(rm -rf /tmp/x)\"",
PermissionVerdict::Default,
&[],
&[]
),
RewriteOutcome::Passthrough
);
}
#[test]
fn test_file_redirect_passthrough() {
assert_eq!(
evaluate_with_verdict(
"git log > /tmp/out.txt",
PermissionVerdict::Default,
&[],
&[]
),
RewriteOutcome::Passthrough
);
}
#[test]
fn test_fd_dup_redirect_still_rewrites() {
assert!(matches!(
evaluate_with_verdict("git status 2>&1", PermissionVerdict::Default, &[], &[]),
RewriteOutcome::Ask(_)
));
}
#[test]
fn test_plain_command_still_rewrites() {
assert!(matches!(
evaluate_with_verdict("git status", PermissionVerdict::Default, &[], &[]),
RewriteOutcome::Ask(_)
));
}
}
/// SECURITY: Verify the exit code protocol for permission verdicts.
///
/// The bash hook (.claude/hooks/rtk-rewrite.sh) interprets exit codes as:
+22 -6
View File
@@ -2788,16 +2788,32 @@ fn run_cli() -> Result<i32> {
hooks::hook_cmd::run_vibe()?;
0
}
HookCommands::Check { agent: _, command } => {
use crate::discover::registry::rewrite_command;
HookCommands::Check { agent, command } => {
// Answers the same question the hooks answer, through the same
// decision (`hooks::decision`) — not just "does a rewrite rule
// match?". Checking the rule alone reported a rewrite for
// command substitutions, file redirects and heredocs that both
// hook paths refuse to touch, which is the opposite of what a
// diagnostic is for.
use crate::hooks::decision::{AgentPath, HookDecision};
let raw = command.join(" ");
let (excluded, transparent_prefixes) = crate::core::config::hook_rewrite_params();
match rewrite_command(&raw, &excluded, &transparent_prefixes) {
Some(rewritten) => {
// Answer for the agent that was asked about. Agents differ both
// in whose permission rules their hook reads and in how it
// decides -- see `AgentPath` -- so one hard-coded answer would
// misdescribe the very hook being diagnosed.
let Some(path) = AgentPath::from_agent(&agent) else {
return Ok(2);
};
match path.decide(&raw) {
HookDecision::AllowRewrite(rewritten) | HookDecision::AskRewrite(rewritten) => {
println!("{}", rewritten);
0
}
None => {
HookDecision::Deny => {
eprintln!("Denied by a permission rule: {}", raw);
1
}
HookDecision::Defer => {
eprintln!("No rewrite for: {}", raw);
1
}
+532
View File
@@ -0,0 +1,532 @@
//! End-to-end coverage of the hook decision entry points.
//!
//! `rtk rewrite`'s exit-code protocol is a public contract consumed entirely
//! outside this crate -- `hooks/hermes/rtk-rewrite/__init__.py`,
//! `hooks/opencode/rtk.ts`, `hooks/pi/rtk.ts` and `openclaw/index.ts` all
//! branch on it -- and `rewrite_cmd`'s in-module `exit_code_protocol` asserts
//! against a hand-copied `expected_exit_code()` table without ever calling
//! `run()`. These tests spawn the real binary in a sandboxed
//! HOME/CLAUDE_CONFIG_DIR and pin the actual `(exit code, stdout)` pairs,
//! including the #1155 invariant that a `Default` verdict exits 3 and never 0.
use std::path::PathBuf;
use std::process::Command;
use tempfile::TempDir;
/// An isolated machine: no developer settings, no user rtk config, no real HOME.
struct Sandbox {
_root: TempDir,
home: PathBuf,
claude_home: PathBuf,
project: PathBuf,
}
impl Sandbox {
/// Build a sandbox whose project-level `.claude/settings.json` carries
/// exactly the given rules, and nothing else anywhere.
fn with_rules(deny: &[&str], ask: &[&str], allow: &[&str]) -> Self {
let root = TempDir::new().expect("tempdir");
let home = root.path().join("home");
let claude_home = root.path().join("claude-home");
let project = root.path().join("project");
std::fs::create_dir_all(home.join(".config")).expect("mkdir home config");
std::fs::create_dir_all(&claude_home).expect("mkdir claude home");
std::fs::create_dir_all(project.join(".claude")).expect("mkdir project claude");
// A tee artefact plus an existing recall store: the recall path only
// writes to a store that already exists.
let tee = root.path().join("tee");
std::fs::create_dir_all(&tee).expect("mkdir tee");
std::fs::write(tee.join("1755590000_cargo-test.log"), "boom\n").expect("write tee log");
std::fs::write(root.path().join("recall.db"), b"").expect("seed recall store");
let quote = |rules: &[&str]| {
rules
.iter()
.map(|r| format!("\"Bash({r})\""))
.collect::<Vec<_>>()
.join(", ")
};
let settings = format!(
r#"{{"permissions": {{"deny": [{}], "ask": [{}], "allow": [{}]}}}}"#,
quote(deny),
quote(ask),
quote(allow)
);
std::fs::write(project.join(".claude/settings.json"), settings).expect("write settings");
Self {
_root: root,
home,
claude_home,
project,
}
}
/// A sandbox with no permission rules at all — every command lands on the
/// `Default` verdict.
fn bare() -> Self {
Self::with_rules(&[], &[], &[])
}
fn run(&self, args: &[&str]) -> (i32, String, String) {
let out = Command::new(env!("CARGO_BIN_EXE_rtk"))
.args(args)
.current_dir(&self.project)
.env("HOME", &self.home)
.env("XDG_CONFIG_HOME", self.home.join(".config"))
.env("CLAUDE_CONFIG_DIR", &self.claude_home)
.env("RTK_DB_PATH", self.project.join("rtk.db"))
.env("RTK_TEE_DIR", self.tee_dir())
.env("RTK_RECALL_DB", self.recall_db())
.env("LC_ALL", "C")
.output()
.expect("spawn rtk");
let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
// A crash produces empty stdout too, which would let every "expect no
// output" assertion below pass vacuously.
assert!(
!stderr.contains("panicked"),
"rtk panicked on {args:?}: {stderr}"
);
(
out.status.code().expect("exit code"),
String::from_utf8_lossy(&out.stdout).into_owned(),
stderr,
)
}
fn tee_dir(&self) -> PathBuf {
self._root.path().join("tee")
}
fn recall_db(&self) -> PathBuf {
self._root.path().join("recall.db")
}
fn tee_log(&self) -> String {
self.tee_dir()
.join("1755590000_cargo-test.log")
.to_string_lossy()
.into_owned()
}
/// Whether anything was written to the recall store. It is seeded empty, and
/// the schema is only created when a recall is actually recorded.
fn recorded_a_recall(&self) -> bool {
std::fs::metadata(self.recall_db())
.map(|m| m.len() > 0)
.unwrap_or(false)
}
fn rewrite(&self, cmd: &str) -> (i32, String) {
let (code, stdout, _) = self.run(&["rewrite", cmd]);
(code, stdout)
}
}
impl Sandbox {
/// Feed a Claude PreToolUse payload to the in-process hook and return stdout.
fn hook_claude(&self, cmd: &str) -> String {
use std::io::Write;
use std::process::Stdio;
let payload = serde_json::json!({
"tool_name": "Bash",
"tool_input": { "command": cmd },
})
.to_string();
let mut child = Command::new(env!("CARGO_BIN_EXE_rtk"))
.args(["hook", "claude"])
.current_dir(&self.project)
.env("HOME", &self.home)
.env("XDG_CONFIG_HOME", self.home.join(".config"))
.env("CLAUDE_CONFIG_DIR", &self.claude_home)
.env("RTK_DB_PATH", self.project.join("rtk.db"))
.env("RTK_TEE_DIR", self.tee_dir())
.env("RTK_RECALL_DB", self.recall_db())
.env("LC_ALL", "C")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn rtk hook claude");
child
.stdin
.take()
.expect("stdin")
.write_all(payload.as_bytes())
.expect("write payload");
let out = child.wait_with_output().expect("wait rtk");
// The hook protocol requires exit 0 whatever it decides; without this a
// crash is indistinguishable from a deliberate defer, and every
// `assert_eq!(..., None)` below would pass vacuously.
assert_eq!(
out.status.code(),
Some(0),
"rtk hook claude exited non-zero for {cmd:?}: {}",
String::from_utf8_lossy(&out.stderr)
);
String::from_utf8_lossy(&out.stdout).into_owned()
}
/// The command the in-process hook would substitute, or `None` when it defers.
fn hook_claude_rewrite(&self, cmd: &str) -> Option<String> {
let stdout = self.hook_claude(cmd);
if stdout.trim().is_empty() {
return None;
}
let v: serde_json::Value = serde_json::from_str(&stdout).expect("hook emitted valid JSON");
v.pointer("/hookSpecificOutput/updatedInput/command")
.and_then(|c| c.as_str())
.map(str::to_owned)
}
}
/// `rtk rewrite`'s four documented exit codes, against real permission rules.
///
/// The table in `rewrite_cmd`'s doc comment is the contract every delegate
/// branches on; this is the only place it is checked end to end.
mod rewrite_exit_codes {
use super::Sandbox;
#[test]
fn allow_rule_exits_zero_with_the_rewrite() {
let sb = Sandbox::with_rules(&[], &[], &["git status"]);
assert_eq!(sb.rewrite("git status"), (0, "rtk git status".into()));
}
#[test]
fn ask_rule_exits_three_with_the_rewrite() {
let sb = Sandbox::with_rules(&[], &["git status"], &[]);
assert_eq!(sb.rewrite("git status"), (3, "rtk git status".into()));
}
#[test]
fn deny_rule_exits_two_and_says_nothing() {
let sb = Sandbox::with_rules(&["git status"], &[], &[]);
assert_eq!(sb.rewrite("git status"), (2, String::new()));
}
/// A deny rule matching *any* segment denies the whole chain (#1213).
#[test]
fn deny_rule_on_one_segment_denies_the_compound() {
let sb = Sandbox::with_rules(&["rm -rf *"], &[], &[]);
assert_eq!(
sb.rewrite("git status && rm -rf /tmp/x"),
(2, String::new())
);
}
#[test]
fn unknown_command_exits_one_and_says_nothing() {
let sb = Sandbox::bare();
assert_eq!(sb.rewrite("htop"), (1, String::new()));
}
/// SECURITY (#1155): with no rule matching, the verdict is `Default`, and
/// `Default` must exit 3 (ask) — never 0. Exit 0 tells the hook it may
/// auto-allow, so mapping `Default` there would auto-approve every
/// rewritable command on a machine with no permission rules at all.
#[test]
fn default_verdict_exits_three_never_zero() {
let sb = Sandbox::bare();
let (code, stdout) = sb.rewrite("git status");
assert_eq!(code, 3, "Default verdict must exit 3 (ask), not 0 (allow)");
assert_eq!(stdout, "rtk git status");
}
#[test]
fn compound_command_rewrites_every_segment() {
let sb = Sandbox::bare();
assert_eq!(
sb.rewrite("git status && cargo test"),
(3, "rtk git status && rtk cargo test".into())
);
}
/// A file-descriptor dup is not a file target, so the rewrite still happens.
#[test]
fn fd_dup_redirect_still_rewrites() {
let sb = Sandbox::bare();
assert_eq!(
sb.rewrite("git status 2>&1"),
(3, "rtk git status 2>&1".into())
);
}
/// Constructs the permission gate cannot decompose are never rewritten,
/// so a hidden command can't ride along inside an approved rewrite.
#[test]
fn unattestable_constructs_pass_through() {
let sb = Sandbox::bare();
for cmd in [
"git status $(rm -rf /tmp/x)",
"git status `rm -rf /tmp/x`",
"git log > /tmp/out.txt",
] {
assert_eq!(sb.rewrite(cmd), (1, String::new()), "cmd: {cmd}");
}
}
#[test]
fn heredoc_passes_through() {
let sb = Sandbox::bare();
assert_eq!(sb.rewrite("cat <<EOF"), (1, String::new()));
assert_eq!(sb.rewrite("git status <<EOF"), (1, String::new()));
}
}
/// Reading back a tee artefact records a recall, and a denied command does not.
///
/// Both entry points perform that bookkeeping themselves rather than through the
/// shared decision, because the `rtk hook check` diagnostic must not write
/// counters that `rtk gain` reports. Two hand-written copies of one rule is
/// exactly what drifts, and nothing else asserts it.
mod recall_tracking {
use super::Sandbox;
#[test]
fn rewrite_records_a_tee_read_unless_denied() {
let sb = Sandbox::bare();
assert!(!sb.recorded_a_recall(), "store starts empty");
sb.rewrite(&format!("tail -n +52 {}", sb.tee_log()));
assert!(
sb.recorded_a_recall(),
"reading a tee artefact records a recall"
);
let denied = Sandbox::with_rules(&["tail *"], &[], &[]);
let (code, _) = denied.rewrite(&format!("tail -n +52 {}", denied.tee_log()));
assert_eq!(code, 2, "the deny rule must match, or this proves nothing");
assert!(
!denied.recorded_a_recall(),
"a denied command must not record a recall"
);
}
#[test]
fn hook_records_a_tee_read_unless_denied() {
let sb = Sandbox::bare();
sb.hook_claude(&format!("tail -n +52 {}", sb.tee_log()));
assert!(sb.recorded_a_recall(), "the hook path records a recall too");
let denied = Sandbox::with_rules(&["tail *"], &[], &[]);
denied.hook_claude(&format!("tail -n +52 {}", denied.tee_log()));
assert!(
!denied.recorded_a_recall(),
"a denied command must not record a recall"
);
}
/// A command that reads nothing from the tee directory records nothing.
#[test]
fn unrelated_command_records_nothing() {
let sb = Sandbox::bare();
sb.rewrite("git status");
assert!(!sb.recorded_a_recall());
}
}
/// The two decision paths, side by side on one corpus.
///
/// `rtk rewrite` (subprocess path) and `rtk hook claude` (in-process path)
/// answer the same question for the same command. Asserting both against one
/// corpus keeps a change to either from silently moving them apart.
///
/// Follows the shape of `registry.rs`'s `segmenter_consistency` module.
mod decision_consistency {
use super::Sandbox;
/// Everything the two paths already agree on: the rewrite is identical
/// where one happens, and both stay silent where it doesn't.
#[test]
fn both_paths_agree_on_the_corpus() {
let sb = Sandbox::bare();
let cases: [(&str, Option<&str>); 9] = [
("git status", Some("rtk git status")),
(
"git status && cargo test",
Some("rtk git status && rtk cargo test"),
),
("git status 2>&1", Some("rtk git status 2>&1")),
("git log | head", Some("rtk git log | head")),
("htop", None),
("git status $(rm -rf /tmp/x)", None),
("git status `rm -rf /tmp/x`", None),
("git log > /tmp/out.txt", None),
("cat <<EOF", None),
];
for (cmd, expected) in cases {
let (code, stdout) = sb.rewrite(cmd);
let via_rewrite = match code {
0 | 3 => Some(stdout),
_ => None,
};
let via_hook = sb.hook_claude_rewrite(cmd);
assert_eq!(
via_rewrite.as_deref(),
expected,
"rtk rewrite disagreed with the pinned corpus for: {cmd}"
);
assert_eq!(
via_hook.as_deref(),
expected,
"rtk hook claude disagreed with the pinned corpus for: {cmd}"
);
}
}
/// The one place the two paths differ.
///
/// A command that is already RTK-prefixed rewrites to itself. Every hook
/// discards that; `rtk rewrite` reports it, exiting 3 with the command
/// unchanged on stdout. The plugins that shell out to it gate on
/// `rewritten != command` for exactly this reason.
#[test]
fn identity_rewrite_is_where_the_paths_diverge() {
let sb = Sandbox::bare();
// Subprocess path: reported as an ask-rewrite, output identical to input.
assert_eq!(
sb.rewrite("rtk git status"),
(3, "rtk git status".into()),
"rtk rewrite reports the no-op rewrite"
);
// In-process path: nothing to say.
assert_eq!(
sb.hook_claude_rewrite("rtk git status"),
None,
"rtk hook claude defers on the no-op rewrite"
);
}
}
/// `rtk hook check` answers the same question the hooks answer.
///
/// A diagnostic that reported a rewrite the hooks refuse to apply would be
/// worse than none, so it routes through the shared decision and is pinned
/// here against the hooks themselves.
mod hook_check {
use super::Sandbox;
#[test]
fn reports_the_rewrite_for_a_plain_command() {
let sb = Sandbox::bare();
let (code, stdout, _) = sb.run(&["hook", "check", "git status"]);
assert_eq!((code, stdout.trim()), (0, "rtk git status"));
}
#[test]
fn exits_one_for_an_unknown_command() {
let sb = Sandbox::bare();
let (code, stdout, _) = sb.run(&["hook", "check", "htop"]);
assert_eq!((code, stdout.trim()), (1, ""));
}
/// Both hook paths refuse these, so the diagnostic must refuse them too.
#[test]
fn agrees_with_the_hooks_on_what_is_never_rewritten() {
let sb = Sandbox::bare();
for cmd in [
"git status $(rm -rf /tmp/x)",
"git log > /tmp/out.txt",
"cat <<EOF",
] {
let (code, stdout, _) = sb.run(&["hook", "check", cmd]);
assert_eq!((code, stdout.trim()), (1, ""), "hook check on: {cmd}");
assert_eq!(sb.hook_claude_rewrite(cmd), None, "hook claude on: {cmd}");
assert_eq!(sb.rewrite(cmd).0, 1, "rtk rewrite on: {cmd}");
}
}
/// An already-RTK-prefixed command rewrites to itself, and no agent applies
/// that: the in-process hosts discard it in `hook_cmd`, and the ones whose
/// plugin shells out to `rtk rewrite` discard it themselves. Only the bare
/// `rtk rewrite` CLI reports it -- see `decision_consistency`.
#[test]
fn no_agent_applies_a_rewrite_that_changed_nothing() {
let sb = Sandbox::bare();
for agent in ["claude", "pi", "kimi"] {
let (code, stdout, _) = sb.run(&["hook", "check", "--agent", agent, "rtk git status"]);
assert_eq!((code, stdout.trim()), (1, ""), "agent: {agent}");
}
assert_eq!(sb.hook_claude_rewrite("rtk git status"), None);
// The CLI itself still reports it, which is what the delegates guard against.
assert_eq!(sb.rewrite("rtk git status"), (3, "rtk git status".into()));
}
/// Every install target answers; only a genuine typo is rejected.
#[test]
fn answers_for_every_supported_agent() {
let sb = Sandbox::bare();
for agent in [
"claude",
"copilot",
"cursor",
"gemini",
"droid",
"vibe",
"opencode",
"openclaw",
"pi",
"omp",
"hermes",
"codex",
"windsurf",
"cline",
"kilocode",
"antigravity",
"kimi",
] {
let (code, stdout, _) = sb.run(&["hook", "check", "--agent", agent, "git status"]);
assert_eq!(
(code, stdout.trim()),
(0, "rtk git status"),
"agent: {agent}"
);
}
}
/// `--agent` selects whose rules are consulted. Hosts read different
/// settings files, so answering with Claude's verdict for another agent
/// would misdescribe the very hook being diagnosed: here a Claude deny rule
/// must not deny for Gemini, which has no rules of its own in this sandbox.
#[test]
fn agent_flag_selects_the_hosts_own_rules() {
let sb = Sandbox::with_rules(&["git status"], &[], &[]);
let (code, stdout, _) = sb.run(&["hook", "check", "--agent", "claude", "git status"]);
assert_eq!((code, stdout.trim()), (1, ""), "claude denies");
let (code, stdout, _) = sb.run(&["hook", "check", "--agent", "gemini", "git status"]);
assert_eq!(
(code, stdout.trim()),
(0, "rtk git status"),
"gemini has no deny rule here, so the rewrite stands"
);
}
#[test]
fn unknown_agent_is_rejected_rather_than_answered_for_claude() {
let sb = Sandbox::bare();
let (code, stdout, stderr) = sb.run(&["hook", "check", "--agent", "nope", "git status"]);
assert_eq!((code, stdout.trim()), (2, ""));
assert!(stderr.contains("Unknown agent: nope"), "stderr: {stderr}");
}
/// A denied command is not rewritten, and says so distinctly.
#[test]
fn reports_a_deny_rule_separately_from_no_rewrite() {
let sb = Sandbox::with_rules(&["git status"], &[], &[]);
let (code, stdout, stderr) = sb.run(&["hook", "check", "git status"]);
assert_eq!((code, stdout.trim()), (1, ""));
assert!(
stderr.contains("Denied by a permission rule"),
"stderr: {stderr}"
);
}
}
+83
View File
@@ -0,0 +1,83 @@
#![cfg(unix)]
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::process::{Command, Stdio};
use std::thread::sleep;
use std::time::{Duration, Instant};
fn shim_dir() -> tempfile::TempDir {
let dir = tempfile::tempdir().expect("tempdir");
let cargo = dir.path().join("cargo");
let marker = dir.path().join("emitted");
fs::write(
&cargo,
format!(
"#!/usr/bin/env bash\n\
for i in $(seq 1 50); do echo \" Compiling crate-$i v0.1.0\"; done\n\
echo 'error[E0308]: mismatched types'\n\
echo ' --> src/lib.rs:12:5'\n\
touch {}\n\
exec sleep 300\n",
marker.display()
),
)
.expect("write shim");
fs::set_permissions(&cargo, fs::Permissions::from_mode(0o755)).expect("chmod shim");
dir
}
fn wait_for(path: &std::path::Path, limit: Duration) -> bool {
let deadline = Instant::now() + limit;
while Instant::now() < deadline {
if path.exists() {
return true;
}
sleep(Duration::from_millis(50));
}
false
}
#[test]
fn signalled_run_still_prints_captured_output() {
let dir = shim_dir();
let home = dir.path().join("home");
fs::create_dir_all(&home).expect("home");
let path = format!(
"{}:{}",
dir.path().display(),
std::env::var("PATH").unwrap_or_default()
);
let child = Command::new(env!("CARGO_BIN_EXE_rtk"))
.args(["cargo", "clippy"])
.env("PATH", path)
.env("HOME", &home)
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.expect("spawn rtk");
assert!(
wait_for(&dir.path().join("emitted"), Duration::from_secs(60)),
"shim never produced output"
);
sleep(Duration::from_millis(500));
let killed = Command::new("kill")
.args(["-TERM", &child.id().to_string()])
.status()
.expect("send SIGTERM");
assert!(killed.success(), "kill failed");
let out = child.wait_with_output().expect("collect rtk output");
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
!stdout.trim().is_empty(),
"signalled run printed nothing; captured output was lost"
);
assert!(
stdout.contains("E0308"),
"signalled run dropped the diagnostic: {}",
stdout
);
}