Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fc19d7a778 | ||
|
|
bc1108bc47 | ||
|
|
66eeb10bdf | ||
|
|
96a8ecf1a6 | ||
|
|
f849ef3c28 | ||
|
|
6eb915bf6f | ||
|
|
d6ce8f71b6 | ||
|
|
22d49e327f | ||
|
|
1ba6f1a64f | ||
|
|
e8a1ef823e | ||
|
|
79347d5e0e | ||
|
|
52ed9fe400 | ||
|
|
5b1d523ad2 | ||
|
|
9418aa87a1 | ||
|
|
7be287958e | ||
|
|
7b09caadbe | ||
|
|
af28c37216 | ||
|
|
06bae5abd6 | ||
|
|
67e47294d9 | ||
|
|
dae3b2929e | ||
|
|
ed106db06f | ||
|
|
9da32707ee | ||
|
|
533b96415e | ||
|
|
39ff99e5c0 | ||
|
|
693d534195 | ||
|
|
d29650acdf | ||
|
|
5be75c2897 | ||
|
|
108a453b6b | ||
|
|
c8c2526450 | ||
|
|
f8c28795c7 | ||
|
|
ea67c7ee57 | ||
|
|
9900d70fd6 | ||
|
|
b17dda3b69 | ||
|
|
a7cc7871f1 | ||
|
|
2f905f7b62 | ||
|
|
69cd16ee1a | ||
|
|
ece41fdcbe | ||
|
|
fde0a8f185 | ||
|
|
84a652ab05 | ||
|
|
76b5397d71 | ||
|
|
630b7ad418 | ||
|
|
34fe255319 | ||
|
|
bd2c46734c | ||
|
|
bdaa79289e | ||
|
|
cd42c64d1e | ||
|
|
8dae5a750f | ||
|
|
36f51239f3 | ||
|
|
867d31c639 | ||
|
|
b34be37caf | ||
|
|
b73b621d7c | ||
|
|
bbd9a7041c | ||
|
|
700bdde334 | ||
|
|
981a6561f4 | ||
|
|
cf04fd318d | ||
|
|
36591fb00d | ||
|
|
062468cd18 | ||
|
|
a7fad1f4f5 | ||
|
|
3fc4070275 | ||
|
|
50830919f5 | ||
|
|
63bcebd44b | ||
|
|
5886d6f852 | ||
|
|
5a7880d404 | ||
|
|
a52a2b2f01 | ||
|
|
431145c830 | ||
|
|
d38cce2ec0 | ||
|
|
bd14120974 | ||
|
|
c4090c26a1 |
No files matched your search
@@ -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,3 +1,3 @@
|
||||
{
|
||||
".": "0.42.4"
|
||||
".": "0.48.0"
|
||||
}
|
||||
+412
-7
@@ -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/<tool> 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 >= 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
@@ -930,7 +930,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rtk"
|
||||
version = "0.42.4"
|
||||
version = "0.48.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"automod",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "rtk"
|
||||
version = "0.42.4"
|
||||
version = "0.48.0"
|
||||
edition = "2021"
|
||||
rust-version = "1.91"
|
||||
authors = ["Patrick Szymkowiak"]
|
||||
|
||||
@@ -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
|
||||
```
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -72,6 +72,14 @@ RTK が報告するトークン数は `バイト数 / 4` で見積もられて
|
||||
brew install rtk
|
||||
```
|
||||
|
||||
### winget(Windows)
|
||||
|
||||
Windowsで最も簡単なインストール方法 — コマンド1つ、PATHの設定不要:
|
||||
|
||||
```powershell
|
||||
winget install rtk-ai.rtk
|
||||
```
|
||||
|
||||
### クイックインストール(Linux/macOS)
|
||||
|
||||
```bash
|
||||
|
||||
@@ -72,6 +72,14 @@ RTK가 보고하는 토큰 수는 `바이트 / 4`로 추정됩니다. RTK에는
|
||||
brew install rtk
|
||||
```
|
||||
|
||||
### winget (Windows)
|
||||
|
||||
Windows에서 가장 쉬운 설치 방법 — 명령어 하나로 끝, PATH 설정 불필요:
|
||||
|
||||
```powershell
|
||||
winget install rtk-ai.rtk
|
||||
```
|
||||
|
||||
### 빠른 설치 (Linux/macOS)
|
||||
|
||||
```bash
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -72,6 +72,14 @@ RTK 报告的 token 数量按 `字节数 / 4` 估算:RTK 不内置分词器,
|
||||
brew install rtk
|
||||
```
|
||||
|
||||
### winget(Windows)
|
||||
|
||||
Windows 上最简单的安装方式 — 一条命令,无需配置 PATH:
|
||||
|
||||
```powershell
|
||||
winget install rtk-ai.rtk
|
||||
```
|
||||
|
||||
### 快速安装(Linux/macOS)
|
||||
|
||||
```bash
|
||||
|
||||
@@ -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)
|
||||
```
|
||||
@@ -420,6 +420,14 @@ rtk git show [args...]
|
||||
|
||||
Affiche le resume du commit + stat + diff compact.
|
||||
|
||||
> **Attention (redirection vers un fichier).** Pour un blob volumineux
|
||||
> (`rtk git show HEAD:gros-fichier`), la sortie est fenetree : seul un apercu
|
||||
> est affiche, suivi d'un indice `[see remaining: git show 'HEAD:...' | tail -n +N]`.
|
||||
> Un `rtk git show HEAD:x > fichier` ecrit a la main peut donc tronquer
|
||||
> silencieusement le contenu (le code de sortie reste 0). Pour capturer le
|
||||
> fichier complet, utilisez `git show` directement, ou suivez l'indice de
|
||||
> recuperation.
|
||||
|
||||
---
|
||||
|
||||
### `rtk git add` -- Add ultra-compact
|
||||
|
||||
+101
-26
@@ -487,15 +487,9 @@ pub fn run_stdin(_verbose: u8) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Filter a piped stream: parse strictly (the parser reads structure through
|
||||
/// an ANSI-stripped view, so a `git diff --color` stream parses instead of
|
||||
/// condensing to silence, while content lines keep their bytes) and apply
|
||||
/// the never-worse check — inlined rather than via `guard::never_worse`,
|
||||
/// which hands back the winning `&str`, where this path needs `None` to
|
||||
/// mean byte-exact fallback. `None` means the caller must emit its exact
|
||||
/// input bytes — including for non-UTF-8 input, where filtering would
|
||||
/// rewrite the user's content bytes to U+FFFD (byte fidelity outranks
|
||||
/// savings here).
|
||||
/// Filter a piped stream. `None` means the caller emits its input bytes
|
||||
/// exactly: non-UTF-8 input takes that path, so content that is not valid
|
||||
/// UTF-8 survives byte for byte.
|
||||
fn condense_stdin(bytes: &[u8]) -> Option<String> {
|
||||
let input = std::str::from_utf8(bytes).ok()?;
|
||||
// PowerShell 5.1's `>` writes a BOM; without this the first `diff
|
||||
@@ -1839,6 +1833,24 @@ fn shared_tail(x: &str, y: &str) -> Option<usize> {
|
||||
tail.find('/').map(|p| n - p).filter(|&m| m > 1)
|
||||
}
|
||||
|
||||
/// Record the roots GNU diff was given, taken from a pair of paths it printed
|
||||
/// for the same file. What precedes the shared tail is that side's root; an
|
||||
/// `Only in <dir>: <file>` line later splits on whichever of these it starts
|
||||
/// with, which is how a directory holding `: ` keeps its name. A root already
|
||||
/// held is not recorded twice, and a pair with no root above the shared tail
|
||||
/// records nothing.
|
||||
fn record_gnu_roots(set: &mut Vec<String>, x: &str, y: &str) {
|
||||
let Some(n) = shared_tail(x, y) else {
|
||||
return;
|
||||
};
|
||||
for side in [x, y] {
|
||||
let root = side[..side.len() - n].trim_end_matches('/');
|
||||
if !root.is_empty() && !set.iter().any(|r| r == root) {
|
||||
set.push(root.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse `@@ -a[,b] +c[,d] @@ ...` (and `@@@ -a,b -c,d +e,f @@@ ...` with one
|
||||
/// `-` range per parent) into per-parent old-line budgets and the new-line
|
||||
/// budget. Omitted counts default to 1 per the unified-diff spec.
|
||||
@@ -2480,14 +2492,7 @@ fn condense_unified_diff_strict(diff: &str) -> Option<String> {
|
||||
if gnu_roots && !hg_stream {
|
||||
// The roots GNU diff was given, for `Only in` (rule 6).
|
||||
let (x, y) = (dequote(minus), dequote(plus));
|
||||
if let Some(n) = shared_tail(&x, &y) {
|
||||
for side in [&x, &y] {
|
||||
let root = side[..side.len() - n].trim_end_matches('/');
|
||||
if !root.is_empty() && !gnu_root_set.iter().any(|r| r == root) {
|
||||
gnu_root_set.push(root.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
record_gnu_roots(&mut gnu_root_set, &x, &y);
|
||||
}
|
||||
match current.as_mut().filter(|e| e.header_only()) {
|
||||
// `rename to`/`copy to` is git's exact path; the pair
|
||||
@@ -2639,14 +2644,7 @@ fn condense_unified_diff_strict(diff: &str) -> Option<String> {
|
||||
std::borrow::Cow::Borrowed(pair),
|
||||
std::borrow::Cow::Borrowed(pair),
|
||||
));
|
||||
if let Some(n) = shared_tail(&x, &y) {
|
||||
for side in [&x, &y] {
|
||||
let root = side[..side.len() - n].trim_end_matches('/');
|
||||
if !root.is_empty() && !gnu_root_set.iter().any(|r| r == root) {
|
||||
gnu_root_set.push(root.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
record_gnu_roots(&mut gnu_root_set, &x, &y);
|
||||
let name = header_name(&x, &y, Some(("", "")));
|
||||
flush(&mut entries, &mut current)?;
|
||||
entries.push(FileEntry {
|
||||
@@ -4674,6 +4672,84 @@ mod tests {
|
||||
assert_eq!(code, 1);
|
||||
}
|
||||
|
||||
/// git's `index` and `similarity index` lines are structure, not prose.
|
||||
/// Counting one as a dropped line costs nothing on a git-only stream —
|
||||
/// nothing consults the drop until a GNU echo has been seen — but a stream
|
||||
/// carrying both producers then bails to raw on a section that parses.
|
||||
#[test]
|
||||
fn git_index_lines_are_structural_in_a_gnu_stream() {
|
||||
let mixed = "diff -ru a/z.txt b/z.txt\n\
|
||||
--- a/z.txt\t2026-09-08 00:00:00.000000000 +0000\n\
|
||||
+++ b/z.txt\t2026-09-08 00:00:00.000000000 +0000\n\
|
||||
@@ -1 +1 @@\n\
|
||||
-one\n\
|
||||
+two\n\
|
||||
diff --git a/g.txt b/g.txt\n\
|
||||
index 1234567..89abcde 100644\n\
|
||||
--- a/g.txt\n\
|
||||
+++ b/g.txt\n\
|
||||
@@ -1 +1 @@\n\
|
||||
-old\n\
|
||||
+new\n";
|
||||
let out = condense_unified_diff_strict(mixed).expect("both sections parse");
|
||||
assert!(out.contains("[file] b/z.txt"), "GNU section: {out}");
|
||||
assert!(out.contains("[file] g.txt"), "git section: {out}");
|
||||
}
|
||||
|
||||
/// The roots GNU diff was given are what an `Only in <dir>: <file>` line
|
||||
/// splits on, so a directory holding `: ` keeps its name. Recorded once
|
||||
/// each, and only when the pair has a root above its shared tail.
|
||||
#[test]
|
||||
fn gnu_roots_are_recorded_once_and_never_empty() {
|
||||
let mut set = Vec::new();
|
||||
record_gnu_roots(&mut set, "cd1/d: x/f.txt", "cd2/e: y/f.txt");
|
||||
assert_eq!(set, ["cd1/d: x", "cd2/e: y"]);
|
||||
|
||||
// Same roots again from a sibling file: still one entry each.
|
||||
record_gnu_roots(&mut set, "cd1/d: x/g.txt", "cd2/e: y/g.txt");
|
||||
assert_eq!(set, ["cd1/d: x", "cd2/e: y"]);
|
||||
|
||||
// A bare pair has no root above the shared tail, and a trailing slash
|
||||
// is not a root of its own.
|
||||
let mut bare = Vec::new();
|
||||
record_gnu_roots(&mut bare, "f.txt", "f.txt");
|
||||
record_gnu_roots(&mut bare, "/f.txt", "/f.txt");
|
||||
assert!(bare.is_empty(), "{bare:?}");
|
||||
}
|
||||
|
||||
/// Every fixture is a real capture, so the detectors only ever see
|
||||
/// well-formed lines there. These are the near misses they must reject:
|
||||
/// a line one edit away from the shape, which prose can reach.
|
||||
#[test]
|
||||
fn detectors_reject_near_misses() {
|
||||
assert!(is_hg_echo("diff -r 0123456789ab -r 0123456789cd f.txt"));
|
||||
assert!(is_hg_echo("diff -r 0123456789ab f.txt"));
|
||||
assert!(!is_hg_echo("diff -r zzzzzzzzzzzz -r 0123456789cd f.txt"));
|
||||
assert!(!is_hg_echo("diff -r 0123456789ab -r zzzzzzzzzzzz f.txt"));
|
||||
assert!(!is_hg_echo("diff -r 0123456789abcd -r 0123456789cd f.txt"));
|
||||
|
||||
let sha1 = "a".repeat(40);
|
||||
assert!(is_mbox_from(&format!("From {sha1} Mon Sep 17 00:00:00 2001")));
|
||||
assert!(is_mbox_from(&format!(
|
||||
"From {} Mon Sep 17 00:00:00 2001",
|
||||
"b".repeat(64)
|
||||
)));
|
||||
assert!(!is_mbox_from(&format!(
|
||||
"From {} Mon Sep 17 00:00:00 2001",
|
||||
"z".repeat(40)
|
||||
)));
|
||||
assert!(!is_mbox_from(&format!("From {sha1}")));
|
||||
assert!(!is_mbox_from(
|
||||
"From the reporter's description this looked like a parser bug, but"
|
||||
));
|
||||
|
||||
assert!(is_submodule_range("Submodule sub 0123456..89abcde:"));
|
||||
assert!(is_submodule_range("Submodule sub 0123456..89abcde (rewind):"));
|
||||
assert!(!is_submodule_range("Submodule sub zzzzzzz..89abcde:"));
|
||||
assert!(!is_submodule_range("Submodule sub 0123456..zzzzzzz:"));
|
||||
assert!(!is_submodule_range("Submodule sub 01234..89abcde:"));
|
||||
assert!(!is_submodule_range("Submodule sub contains modified content"));
|
||||
}
|
||||
// --- condense_unified_diff ---
|
||||
|
||||
#[test]
|
||||
@@ -7187,4 +7263,3 @@ diff --git a/b.rs b/b.rs
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+749
-18
@@ -223,20 +223,47 @@ fn run_show(
|
||||
) -> Result<i32> {
|
||||
let timer = tracking::TimedExecution::start();
|
||||
|
||||
// If user wants --stat or --format only, pass through
|
||||
let wants_stat_only = args
|
||||
.iter()
|
||||
.any(|arg| arg == "--stat" || arg == "--numstat" || arg == "--shortstat");
|
||||
// Re-insert `--` when clap's trailing_var_arg consumed it (issue #1215), same as
|
||||
// run_diff/run_checkout. Without this the pathspec separator never reaches
|
||||
// `show_positionals`, so `git show <rev> -- <path:with:colon>` would misread the
|
||||
// colon'd pathspec as a `<rev>:<path>` blob and dump it instead of a commit-diff.
|
||||
let args = &args_utils::restore_double_dash(args);
|
||||
|
||||
let wants_format = args
|
||||
.iter()
|
||||
.any(|arg| arg.starts_with("--pretty") || arg.starts_with("--format"));
|
||||
// Pick one of three handlers for `git show`. `show_route` decides the blob case
|
||||
// FIRST (see its docs): the two branches below are mutually exclusive on `route`,
|
||||
// so their source order does not affect which one runs.
|
||||
let positionals = show_positionals(args);
|
||||
// Authoritative blob decision (belt-and-suspenders). `show_route` is the cheap pure
|
||||
// pre-filter: does ANY positional look like `rev:path`? Only then do we probe with
|
||||
// `git cat-file -t` — and we probe EVERY colon positional, not just the first. The
|
||||
// cluster-aware `show_positionals` already drops option-value operands (`-S 'url:1'`,
|
||||
// the `-G` value in `-wG a:b HEAD:blob`, …), but probing all candidates means that
|
||||
// even if the walker ever missed some exotic short-flag cluster, a non-object like
|
||||
// `a:b` is still rejected by `cat-file` and the REAL blob elsewhere on the line is
|
||||
// rescued instead of being silently dropped or misrouted through lossy decoding.
|
||||
// * exactly one blob → window it (the byte-safe path below),
|
||||
// * more than one → git concatenates the objects with no separator, so the
|
||||
// hint can't reconstruct them → raw passthrough,
|
||||
// * zero → ordinary commit-diff / --stat classification.
|
||||
// Any presence of a blob object takes the byte-safe path: its output carries raw
|
||||
// blob bytes that the commit-diff path's lossy UTF-8 decode would corrupt (a Latin-1
|
||||
// `0xF1` becomes the `U+FFFD` replacement char — verified).
|
||||
let (route, blob_objects) = match show_route(args) {
|
||||
ShowRoute::Blob => {
|
||||
let blobs: Vec<&String> = blob_candidates(args)
|
||||
.into_iter()
|
||||
.filter(|c| probe_is_blob(global_args, c))
|
||||
.collect();
|
||||
if blobs.is_empty() {
|
||||
(commit_or_stat_route(args), blobs)
|
||||
} else {
|
||||
(ShowRoute::Blob, blobs)
|
||||
}
|
||||
}
|
||||
other => (other, Vec::new()),
|
||||
};
|
||||
|
||||
// `git show rev:path` prints a blob, not a commit diff. In this mode we should
|
||||
// pass through directly to avoid duplicated output from compact-show steps.
|
||||
let wants_blob_show = args.iter().any(|arg| is_blob_show_arg(arg));
|
||||
|
||||
if wants_stat_only || wants_format || wants_blob_show || emits_word_diff(args) {
|
||||
if route == ShowRoute::StatOrFormat {
|
||||
let mut cmd = git_cmd(global_args);
|
||||
cmd.arg("show");
|
||||
for arg in args {
|
||||
@@ -247,11 +274,7 @@ fn run_show(
|
||||
eprintln!("{}", result.stderr);
|
||||
return Ok(result.exit_code);
|
||||
}
|
||||
if wants_blob_show {
|
||||
print!("{}", result.stdout);
|
||||
} else {
|
||||
println!("{}", result.stdout.trim());
|
||||
}
|
||||
println!("{}", result.stdout.trim());
|
||||
|
||||
timer.track(
|
||||
&format!("git show {}", args.join(" ")),
|
||||
@@ -263,6 +286,114 @@ fn run_show(
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
if route == ShowRoute::Blob {
|
||||
let mut cmd = git_cmd(global_args);
|
||||
cmd.arg("show");
|
||||
for arg in args {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
// Capture raw bytes: `git show` of an ISO-8859/Latin-1 file (e.g. Oracle
|
||||
// PL/SQL `.pck`) is not UTF-8, and we must preserve git's exact bytes for the
|
||||
// passthrough path below — decoding into a `String` first would lose them.
|
||||
let result =
|
||||
crate::core::stream::exec_capture_bytes(&mut cmd).context("Failed to run git show")?;
|
||||
let label = format!("git show {}", args.join(" "));
|
||||
let rtk_label = format!("rtk git show {}", args.join(" "));
|
||||
if !result.success() {
|
||||
eprint!("{}", crate::core::utils::decode_process_output(&result.stderr));
|
||||
return Ok(result.exit_code);
|
||||
}
|
||||
// git can warn on stderr (e.g. CRLF / autocrlf notices) while still exiting 0;
|
||||
// surface it instead of swallowing it just because the command succeeded.
|
||||
if !result.stderr.is_empty() {
|
||||
eprint!("{}", crate::core::utils::decode_process_output(&result.stderr));
|
||||
}
|
||||
// Fidelity invariant: "byte-identical unless we successfully windowed."
|
||||
//
|
||||
// Windowing shows a head and points at the rest with `git show 'rev:path' |
|
||||
// tail -n +N`. That recovery reconstructs the file EXACTLY only if the head we
|
||||
// printed is a BYTE-EXACT prefix of what git wrote — which holds only when the
|
||||
// content is valid UTF-8 as-is. Any transcode (Latin-1 → UTF-8), BOM rewrite,
|
||||
// UTF-16 (whose `tail`-sliced bytes are UTF-16 that won't concatenate with a
|
||||
// UTF-8 head), U+FFFD from lossy decoding, or true binary would make the head
|
||||
// diverge from git's bytes and silently break recovery — and can even inflate
|
||||
// the output past what git emitted.
|
||||
//
|
||||
// So we window ONLY content that is valid UTF-8 recoverable byte-for-byte AND
|
||||
// whose flags/pathspec don't perturb the dump (see the `can_window` gate below:
|
||||
// no `--textconv`/`--filters`/`--ext-diff`, no trailing `-- <pathspec>`, a single
|
||||
// sole blob object); everything else goes through `emit_raw_bytes_passthrough`,
|
||||
// byte-identical to a plain `git show`. This makes the recovery hint reconstruct
|
||||
// exactly whenever we DO window, and scopes windowing to the common text-lockfile
|
||||
// case the filter exists for.
|
||||
//
|
||||
// Larger blobs window regardless of whether stdout is a pipe or a TTY: the whole
|
||||
// point of the filter is to shrink what the agent reads, and the agent reads
|
||||
// through a pipe. That mirrors the diff/log filters (which also compact in a
|
||||
// pipe); a consumer that needs the full content follows the `| tail -n +N`
|
||||
// recovery hint — the same tradeoff `git log | grep` already makes.
|
||||
// (`is_terminal()` is not a reliable "human is watching" signal anyway: the hook
|
||||
// always pipes rtk's stdout — verified `isatty: False` — and CI agents hand rtk
|
||||
// a pseudo-TTY. Had this branch gated on it, it would have been the first gate to
|
||||
// drop CONTENT; every other `stdout().is_terminal()` gate in the tree governs
|
||||
// only PRESENTATION — color, line-buffering, curl formatting.)
|
||||
let text = match std::str::from_utf8(&result.stdout) {
|
||||
// Valid UTF-8: the string's bytes ARE git's bytes, so a head prefix + tail
|
||||
// recovery is byte-exact. Below the budget it passes through unchanged; over
|
||||
// it, `compact_blob_show` windows it (or declines and returns it whole).
|
||||
Ok(s) => s,
|
||||
// Latin-1, UTF-16/BOM, or binary: recovery would not be byte-exact, so pass
|
||||
// the raw bytes through verbatim, tracked as a passthrough.
|
||||
Err(_) => {
|
||||
return emit_raw_bytes_passthrough(
|
||||
&result.stdout,
|
||||
&label,
|
||||
&rtk_label,
|
||||
&timer,
|
||||
result.exit_code,
|
||||
);
|
||||
}
|
||||
};
|
||||
// A blob dump is unfiltered file content: cap large text blobs to a byte
|
||||
// budget with a tail-recovery pointer, mirroring how the commit-diff path
|
||||
// below caps at `max_lines`. `--max-lines` does not apply here — blob output
|
||||
// is bounded by bytes, not lines.
|
||||
//
|
||||
// Window ONLY when git emits exactly this one blob and nothing that makes the
|
||||
// `git show <rev>:<path> | tail` recovery hint diverge from git's bytes:
|
||||
// * a single positional that is the sole blob object — git concatenates
|
||||
// multiple objects with no separator, so cutting the first would silently
|
||||
// drop the rest, and that concatenation is not the single `rev:path` the
|
||||
// hint reconstructs;
|
||||
// * no content-transforming flag (`--textconv`/`--filters`/`--ext-diff`
|
||||
// rewrite the dump, and the hint omits them — see `has_content_transform_flag`);
|
||||
// * no trailing `-- <pathspec>` (also omitted from the hint — see
|
||||
// `has_trailing_pathspec`).
|
||||
// Everything else passes the raw bytes through, byte-identical to plain git show.
|
||||
// Below the budget, `compact_blob_show` returns the text unchanged, so a windowed
|
||||
// single-object print stays byte-identical to git there too.
|
||||
let can_window = positionals.len() == 1
|
||||
&& blob_objects.len() == 1
|
||||
&& !has_content_transform_flag(args)
|
||||
&& !has_trailing_pathspec(args);
|
||||
if can_window {
|
||||
let shown = compact_blob_show(text, blob_objects[0], global_args);
|
||||
print!("{}", shown);
|
||||
// Track savings against the bytes git actually wrote (`result.stdout`).
|
||||
timer.track_bytes(&label, &rtk_label, result.stdout.len(), &shown);
|
||||
return Ok(0);
|
||||
}
|
||||
// Not windowable (multiple concatenated objects, a content-transforming flag, or
|
||||
// a trailing pathspec): pass through byte-identical.
|
||||
return emit_raw_bytes_passthrough(
|
||||
&result.stdout,
|
||||
&label,
|
||||
&rtk_label,
|
||||
&timer,
|
||||
result.exit_code,
|
||||
);
|
||||
}
|
||||
|
||||
// Get raw output for tracking
|
||||
let mut raw_cmd = git_cmd(global_args);
|
||||
raw_cmd.arg("show");
|
||||
@@ -364,7 +495,301 @@ fn emits_word_diff(args: &[String]) -> bool {
|
||||
|
||||
fn is_blob_show_arg(arg: &str) -> bool {
|
||||
// Detect `rev:path` style arguments while ignoring flags like `--pretty=format:...`.
|
||||
!arg.starts_with('-') && arg.contains(':')
|
||||
// `:/text` is a commit-message search, not a blob, so it is excluded. `:path` and
|
||||
// `:N:path` (index / merge-stage blobs) start with `:` but ARE blobs, so only the
|
||||
// `:/` prefix is filtered out there.
|
||||
//
|
||||
// Magic pathspecs (`:(exclude)…`, `:(top)…`, `:!…`, and `:^…` — an exact synonym
|
||||
// of `:!…` for exclude magic) also start with `:` but are NOT blobs: they only
|
||||
// ever appear as pathspecs, so exclude them too. An option value with a colon
|
||||
// (`git show -S 'a:b' HEAD`) is handled by `show_positionals`, which skips a
|
||||
// flag's operand via git's argument grammar, so it never reaches here as a blob.
|
||||
!arg.starts_with('-')
|
||||
&& !arg.starts_with(":/")
|
||||
&& !arg.starts_with(":(")
|
||||
&& !arg.starts_with(":!")
|
||||
&& !arg.starts_with(":^")
|
||||
&& arg.contains(':')
|
||||
// A colons-only token (`:`, `::`) is never a blob object: route it to git
|
||||
// rather than the blob window, which would only surface git's own error.
|
||||
&& arg.chars().any(|c| c != ':')
|
||||
}
|
||||
|
||||
/// The positional (non-option) arguments of a `git show` — its objects. Options and
|
||||
/// the value tokens they consume (`-S 'url:1'`, `-L 1,2:file`) are dropped via git's
|
||||
/// own flag/value grammar ([`flag_token_consumes_next`]), so an option operand that
|
||||
/// happens to contain a colon is never mistaken for a blob and truncated. This handles
|
||||
/// short-flag CLUSTERS too (`-wG a:b`, `-pS a:b`), whose value-flag tail git re-parses.
|
||||
/// Args after a `--` are pathspecs, never objects, so a colon in a filename there
|
||||
/// (`-- weird:name`) is excluded by scanning only the args before the first `--`; a
|
||||
/// trailing `-- <path>` beside a real object arg is thus ignored (git still dumps the
|
||||
/// blob) rather than emptying the list.
|
||||
fn show_positionals(args: &[String]) -> Vec<&String> {
|
||||
let rev_args = match args.iter().position(|a| a == "--") {
|
||||
Some(sep) => &args[..sep],
|
||||
None => args,
|
||||
};
|
||||
let mut positionals = Vec::new();
|
||||
let mut iter = rev_args.iter();
|
||||
while let Some(arg) = iter.next() {
|
||||
if arg.starts_with('-') {
|
||||
if flag_token_consumes_next(arg) {
|
||||
iter.next(); // skip this flag's value token
|
||||
}
|
||||
continue;
|
||||
}
|
||||
positionals.push(arg);
|
||||
}
|
||||
positionals
|
||||
}
|
||||
|
||||
/// Whether a flag token consumes the NEXT arg as its value (so `show_positionals` must
|
||||
/// skip it). Handles long flags (`--grep foo`) via [`consumes_next_token_as_value`] and
|
||||
/// short-flag CLUSTERS (`-wG foo`, `-pS bar`), which git re-parses char by char.
|
||||
///
|
||||
/// Inside a cluster, the first value-taking short flag (`-S -G -I -L -O -l -n`) takes
|
||||
/// the REST of the cluster as an INLINE value when more chars follow it (`-Sfoo` == `-S
|
||||
/// foo`, so it does NOT consume the next arg), or the NEXT arg when it is the cluster's
|
||||
/// last char (`-wG` == `-w -G`, consuming the next arg). Any earlier char is a boolean
|
||||
/// flag we skip over. This reuses the single flag/value table rather than re-tokenizing
|
||||
/// git's whole grammar, so `git show -wG x:y HEAD:big` correctly treats `x:y` as `-G`'s
|
||||
/// value and `HEAD:big` as the object.
|
||||
//
|
||||
// TODO(after #3681): replace this short-cluster walk with the ValueSpec factorization;
|
||||
// the per-char logic here is exactly what a ValueSpec table subsumes.
|
||||
fn flag_token_consumes_next(arg: &str) -> bool {
|
||||
// A short cluster is a single leading `-` followed by non-empty flag chars (not the
|
||||
// `--long` form and not the bare `-` stdin sentinel). Everything else (`--foo`, `-`)
|
||||
// uses the exact-match table directly.
|
||||
match arg.strip_prefix('-') {
|
||||
Some(cluster) if !cluster.is_empty() && !cluster.starts_with('-') => {
|
||||
for (i, c) in cluster.char_indices() {
|
||||
if is_short_value_flag(c) {
|
||||
// Consumes the next arg only if no inline value follows in-cluster.
|
||||
return i + c.len_utf8() == cluster.len();
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
_ => consumes_next_token_as_value(arg),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a single-letter short flag takes a value (`-S`, `-G`, `-L`, …). Derived from
|
||||
/// [`consumes_next_token_as_value`] so the flag/value table stays the single source of
|
||||
/// truth and no parallel list can drift out of sync.
|
||||
fn is_short_value_flag(c: char) -> bool {
|
||||
c.is_ascii() && consumes_next_token_as_value(format!("-{c}").as_str())
|
||||
}
|
||||
|
||||
/// The `git show` positionals that look like `<rev>:<path>` blob objects — the
|
||||
/// windowing candidates. ALL of them are returned (not just the first) so `run_show`
|
||||
/// can `cat-file`-probe every one: a value operand a missed exotic cluster might leave
|
||||
/// behind is rejected by the probe, while the real blob elsewhere on the line is found.
|
||||
fn blob_candidates(args: &[String]) -> Vec<&String> {
|
||||
show_positionals(args)
|
||||
.into_iter()
|
||||
.filter(|a| is_blob_show_arg(a))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether a `git show` invocation carries any content-transforming flag
|
||||
/// (`--textconv`/`--filters`/`--ext-diff`) that rewrites a blob's bytes. The `git show
|
||||
/// <rev>:<path> | tail` recovery hint omits these flags, so its output would not match
|
||||
/// what git printed; their presence forces byte-identical raw passthrough instead of
|
||||
/// windowing. The `--no-*` spellings restore the default (no rewrite) and are safe, so
|
||||
/// only the enabling spellings count. Flags precede `--`, so scan up to it.
|
||||
fn has_content_transform_flag(args: &[String]) -> bool {
|
||||
args.iter()
|
||||
.take_while(|a| *a != "--")
|
||||
.any(|a| matches!(a.as_str(), "--textconv" | "--filters" | "--ext-diff"))
|
||||
}
|
||||
|
||||
/// Whether a `-- <pathspec>` with at least one path after it is present. Empirically
|
||||
/// git ignores a trailing pathspec for a `rev:path` blob dump (verified: output is
|
||||
/// byte-identical with and without it), but the recovery hint omits it, so rather than
|
||||
/// bank on that holding for every git version and pathspec form we force byte-identical
|
||||
/// raw passthrough whenever one accompanies a blob.
|
||||
fn has_trailing_pathspec(args: &[String]) -> bool {
|
||||
matches!(args.iter().position(|a| a == "--"), Some(sep) if args.len() > sep + 1)
|
||||
}
|
||||
|
||||
/// Which `git show` handler an invocation routes to.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum ShowRoute {
|
||||
/// A `<rev>:<path>` blob dump → byte-safe decode/window path.
|
||||
Blob,
|
||||
/// `--stat`/`--numstat`/`--shortstat`/`--pretty`/`--format` with NO blob target
|
||||
/// → summary-only passthrough.
|
||||
StatOrFormat,
|
||||
/// An ordinary commit → compacted commit-diff.
|
||||
CommitDiff,
|
||||
}
|
||||
|
||||
/// Classify a `git show` invocation. Blob detection wins over --stat/--format
|
||||
/// because git accepts and silently ignores those flags when the argument resolves
|
||||
/// to a blob (verified against git 2.39 — output byte-identical to a plain blob
|
||||
/// dump), still emitting the full file. Routing such a call to the --stat passthrough
|
||||
/// would send it through lossy UTF-8 decoding and reintroduce the blob corruption the
|
||||
/// byte-safe path fixes, so the blob case is checked first.
|
||||
///
|
||||
/// This is a cheap, pure PRE-FILTER: a `Blob` result here only means SOME positional
|
||||
/// *looks like* `rev:path`. The authoritative blob decision is a `git cat-file -t`
|
||||
/// probe run by `run_show` (see `probe_is_blob`) on those candidates — the pre-filter
|
||||
/// keeps the probe off every other invocation.
|
||||
fn show_route(args: &[String]) -> ShowRoute {
|
||||
if !blob_candidates(args).is_empty() {
|
||||
return ShowRoute::Blob;
|
||||
}
|
||||
commit_or_stat_route(args)
|
||||
}
|
||||
|
||||
/// Classify a `git show` that is NOT a blob dump: `--stat`/`--format`/word-diff
|
||||
/// summary passthrough vs. a compacted commit-diff. Split out from `show_route` so
|
||||
/// `run_show` can fall back to it when the `cat-file` probe rejects a `rev:path`
|
||||
/// candidate (a flag value like `-S 'url:1'`, or a tree/commit/bogus object).
|
||||
fn commit_or_stat_route(args: &[String]) -> ShowRoute {
|
||||
let wants_stat = args
|
||||
.iter()
|
||||
.any(|a| a == "--stat" || a == "--numstat" || a == "--shortstat");
|
||||
let wants_format = args
|
||||
.iter()
|
||||
.any(|a| a.starts_with("--pretty") || a.starts_with("--format"));
|
||||
// A word/color-word diff has no unified-diff markers for `compact_diff` to read,
|
||||
// so it passes through untouched like a --stat/--format summary (see
|
||||
// `emits_word_diff`). It only ever applies to a commit-diff, so it is checked
|
||||
// after the blob case above.
|
||||
if wants_stat || wants_format || emits_word_diff(args) {
|
||||
return ShowRoute::StatOrFormat;
|
||||
}
|
||||
ShowRoute::CommitDiff
|
||||
}
|
||||
|
||||
/// Authoritatively decide whether a `git show` argument is a blob, by asking git
|
||||
/// instead of mirroring its flag grammar. `git cat-file -t <arg>` prints the object
|
||||
/// type; only an exact `blob` is a windowing target. A tree/commit/tag, or any
|
||||
/// non-zero exit (a flag value that isn't an object, e.g. `-S 'url:1'`, or a bogus
|
||||
/// `rev:path`), is not a blob and routes to the normal commit-diff / passthrough path.
|
||||
///
|
||||
/// Run with the SAME global args as the command (`git_cmd(global_args)`) so `-C`,
|
||||
/// `-c`, `--git-dir`, `--work-tree` resolve the object in the right repo — the same
|
||||
/// requirement the recovery hint has. Only called on the path where the arg already
|
||||
/// looks like `rev:path` (the `show_route` pre-filter), so the ~1 ms subprocess never
|
||||
/// runs on an ordinary commit show.
|
||||
///
|
||||
// TODO(after #3681): once ValueSpec factorization lands, a flag pre-filter can avoid
|
||||
// the cat-file probe on the common path.
|
||||
fn probe_is_blob(global_args: &[String], arg: &str) -> bool {
|
||||
let mut cmd = git_cmd(global_args);
|
||||
cmd.args(["cat-file", "-t", arg]);
|
||||
match exec_capture(&mut cmd) {
|
||||
Ok(result) if result.success() => result.stdout.trim() == "blob",
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Byte budget for a blob preview before truncation kicks in (~2k tokens).
|
||||
const MAX_BLOB_BYTES: Budget = Budget(8192);
|
||||
|
||||
/// Byte budget after which a blob preview is truncated. A newtype rather than a bare
|
||||
/// `usize` so a call site can't silently pass some other length in its place.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Budget(usize);
|
||||
|
||||
/// Decide how to window a `git show <rev>:<path>` blob. Returns
|
||||
/// `Some((head, remaining_lines, tail_offset))` when the blob should be truncated,
|
||||
/// or `None` to pass it through unchanged: a small blob, a binary blob, a tree
|
||||
/// listing, or a single line too long to cut at a line boundary.
|
||||
///
|
||||
/// Pure and side-effect free so it can be unit-tested against real blob fixtures.
|
||||
fn blob_truncation(raw: &str, budget: Budget) -> Option<(&str, usize, usize)> {
|
||||
let Budget(budget) = budget;
|
||||
// No content-sniffing for object type here: the caller only reaches this function
|
||||
// for an arg the `git cat-file -t` probe has already confirmed is a blob, so a tree
|
||||
// listing never arrives (and the old `raw.starts_with("tree ")` heuristic — a false
|
||||
// positive for Newick/NEXUS blobs that genuinely begin "tree " — is gone with it).
|
||||
// A defensive binary guard is likewise unnecessary now: `run_show` only calls this
|
||||
// on valid UTF-8 (`\0`/`U+FFFD` content routes to byte-exact passthrough upstream),
|
||||
// but keep the cheap check so the pure function stays safe when unit-tested directly.
|
||||
if raw.contains('\0') || raw.contains('\u{FFFD}') {
|
||||
return None;
|
||||
}
|
||||
if raw.len() <= budget {
|
||||
return None;
|
||||
}
|
||||
// Slicing a `&str` at a byte index that is not a UTF-8 char boundary panics, so
|
||||
// walk the budget back to the nearest boundary at or below it before cutting.
|
||||
let mut end = budget;
|
||||
while end > 0 && !raw.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
// Cut at the last line boundary inside the window. No newline means a single line
|
||||
// longer than the budget, which tail-based recovery cannot re-window: pass through.
|
||||
let cut = raw[..end].rfind('\n')? + 1;
|
||||
let head = &raw[..cut];
|
||||
let head_lines = head.lines().count();
|
||||
let total_lines = raw.lines().count();
|
||||
let remaining = total_lines.checked_sub(head_lines).filter(|&r| r > 0)?;
|
||||
// `tail -n +offset` recovers everything from the first un-shown line onward.
|
||||
Some((head, remaining, head_lines + 1))
|
||||
}
|
||||
|
||||
/// POSIX single-quote a blob arg so a hint with a space or shell metachar in the path
|
||||
/// stays copy-paste safe.
|
||||
fn shell_single_quote(s: &str) -> String {
|
||||
format!("'{}'", s.replace('\'', r"'\''"))
|
||||
}
|
||||
|
||||
/// Window a single blob dump: cap a large text blob and point at the rest with a hint
|
||||
/// re-derived from the blob arg itself — `git show <rev>:<path> | tail -n +N`.
|
||||
///
|
||||
/// The hint deliberately does not lean on a tee file. The tee is capped at
|
||||
/// `max_file_size` (1 MB by default), so it would refuse to store exactly the giant
|
||||
/// lockfiles this filter most wants to trim, leaving the biggest blobs un-windowed;
|
||||
/// re-running `git show` reproduces the tail at any size, with no cap and no I/O.
|
||||
fn compact_blob_show(raw: &str, blob_arg: &str, global_args: &[String]) -> String {
|
||||
let Some((head, remaining, offset)) = blob_truncation(raw, MAX_BLOB_BYTES) else {
|
||||
return raw.to_string();
|
||||
};
|
||||
// Carry the command's global args (`-C <dir>`, `-c k=v`, `--git-dir`, `--work-tree`)
|
||||
// into the hint so it is runnable from anywhere, not just the repo root: without
|
||||
// them `rtk git -C /repo show HEAD:big` would emit `git show 'HEAD:big' | tail …`,
|
||||
// which fails outside /repo. Each is shell-quoted for copy-paste safety.
|
||||
let mut prefix = String::new();
|
||||
for arg in global_args {
|
||||
prefix.push_str(&shell_single_quote(arg));
|
||||
prefix.push(' ');
|
||||
}
|
||||
let hint = format!(
|
||||
"[see remaining: git {}show {} | tail -n +{}]",
|
||||
prefix,
|
||||
shell_single_quote(blob_arg),
|
||||
offset
|
||||
);
|
||||
let out = format!("{}... (+{} lines) {}\n", head, remaining, hint);
|
||||
never_worse(raw, &out).to_string()
|
||||
}
|
||||
|
||||
/// Write raw bytes straight to stdout, tracked as a passthrough. Used when the blob
|
||||
/// must reach the caller byte-for-byte — binary or ambiguously-encoded content that
|
||||
/// decoding would corrupt, or a passthrough where any rewrite (BOM strip, transcode)
|
||||
/// would diverge from what plain `git show` emits — so it goes through the locked
|
||||
/// stdout handle as bytes rather than a `String`.
|
||||
fn emit_raw_bytes_passthrough(
|
||||
bytes: &[u8],
|
||||
label: &str,
|
||||
rtk_label: &str,
|
||||
timer: &tracking::TimedExecution,
|
||||
exit_code: i32,
|
||||
) -> Result<i32> {
|
||||
use std::io::Write;
|
||||
let stdout = std::io::stdout();
|
||||
let mut handle = stdout.lock();
|
||||
handle
|
||||
.write_all(bytes)
|
||||
.context("Failed to write blob to stdout")?;
|
||||
timer.track_passthrough(label, rtk_label);
|
||||
Ok(exit_code)
|
||||
}
|
||||
|
||||
/// Path named by a diff section header.
|
||||
@@ -3413,9 +3838,315 @@ mod tests {
|
||||
fn test_is_blob_show_arg() {
|
||||
assert!(is_blob_show_arg("develop:modules/pairs_backtest.py"));
|
||||
assert!(is_blob_show_arg("HEAD:src/main.rs"));
|
||||
// Index / merge-stage blobs start with `:` but are still blobs.
|
||||
assert!(is_blob_show_arg(":Cargo.toml"));
|
||||
assert!(is_blob_show_arg(":2:conflict.rs"));
|
||||
assert!(!is_blob_show_arg("--pretty=format:%h"));
|
||||
assert!(!is_blob_show_arg("--format=short"));
|
||||
assert!(!is_blob_show_arg("HEAD"));
|
||||
// `:/text` is a commit-message search, not a blob.
|
||||
assert!(!is_blob_show_arg(":/fix the bug"));
|
||||
// Magic pathspecs are pathspecs, never blobs.
|
||||
assert!(!is_blob_show_arg(":(exclude)b.txt"));
|
||||
assert!(!is_blob_show_arg(":(top,glob)*.rs"));
|
||||
assert!(!is_blob_show_arg(":!b.txt"));
|
||||
// `:^` is an exact synonym of `:!` (exclude magic), also a pathspec.
|
||||
assert!(!is_blob_show_arg(":^b.txt"));
|
||||
// A colons-only token is not a blob object.
|
||||
assert!(!is_blob_show_arg(":"));
|
||||
assert!(!is_blob_show_arg("::"));
|
||||
}
|
||||
|
||||
/// Helper: build an args slice from string literals.
|
||||
fn show_args(v: &[&str]) -> Vec<String> {
|
||||
v.iter().map(|x| x.to_string()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_show_route_blob_wins_over_stat_and_format() {
|
||||
// Blocking bug #1: git accepts and silently ignores --stat/--numstat/--pretty/
|
||||
// --format for a blob target and still dumps the file, so these must NOT shadow
|
||||
// the blob path (which would send the blob through lossy UTF-8 decoding).
|
||||
assert_eq!(
|
||||
show_route(&show_args(&["--stat", "HEAD:legacy.pck"])),
|
||||
ShowRoute::Blob
|
||||
);
|
||||
assert_eq!(
|
||||
show_route(&show_args(&["--numstat", "HEAD:legacy.pck"])),
|
||||
ShowRoute::Blob
|
||||
);
|
||||
assert_eq!(
|
||||
show_route(&show_args(&["--format=medium", "HEAD:legacy.pck"])),
|
||||
ShowRoute::Blob
|
||||
);
|
||||
assert_eq!(
|
||||
show_route(&show_args(&["--pretty=oneline", "HEAD:legacy.pck"])),
|
||||
ShowRoute::Blob
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_show_route_trailing_pathspec_stays_a_blob() {
|
||||
// Blocking bug #2: a trailing `-- <path>` beside a blob arg is ignored by git
|
||||
// (still a blob dump), so it must not disable blob handling.
|
||||
let args = show_args(&["HEAD:Cargo.toml", "--", "Cargo.toml"]);
|
||||
assert_eq!(show_route(&args), ShowRoute::Blob);
|
||||
assert_eq!(blob_candidates(&args), vec![&"HEAD:Cargo.toml".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_blob_candidates_skip_flag_operand_with_colon() {
|
||||
// Blocking bug #2: `-S 'url:1'`'s operand contains a colon but is the value of
|
||||
// a pickaxe flag, not an object — it must not be read as a blob and truncated.
|
||||
// The commit is the real (colon-free) object, so this is a commit-diff.
|
||||
let args = show_args(&["-S", "url:1", "HEAD"]);
|
||||
assert!(blob_candidates(&args).is_empty());
|
||||
assert_eq!(show_route(&args), ShowRoute::CommitDiff);
|
||||
// `-L <start,end>:<file>` operand likewise carries a colon.
|
||||
let args = show_args(&["-L", "1,2:file.rs", "HEAD"]);
|
||||
assert!(blob_candidates(&args).is_empty());
|
||||
// A real blob still routes as a blob even with a preceding value flag.
|
||||
let args = show_args(&["-S", "needle", "HEAD:src/main.rs"]);
|
||||
assert_eq!(blob_candidates(&args), vec![&"HEAD:src/main.rs".to_string()]);
|
||||
// A value operand that IS a valid-looking blob (`-S 'HEAD:real'`) is the pickaxe
|
||||
// value, not an object: the walker excludes it, so only the trailing commit
|
||||
// remains and nothing is offered as a windowing candidate.
|
||||
let args = show_args(&["-S", "HEAD:real", "HEAD"]);
|
||||
assert!(blob_candidates(&args).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_blob_candidates_short_flag_clusters() {
|
||||
// BLOCKER: a short-flag cluster whose value-taking tail consumes the NEXT token
|
||||
// (`-wG x:y` == `-w -G x:y`) must skip `x:y` and expose the real blob object, not
|
||||
// mistake `x:y` for the blob. Covers the clusters git re-parses.
|
||||
for cluster in ["-wG", "-pS", "-pI", "-pwG", "-wpG"] {
|
||||
let args = show_args(&[cluster, "x:y", "HEAD:big.txt"]);
|
||||
assert_eq!(
|
||||
blob_candidates(&args),
|
||||
vec![&"HEAD:big.txt".to_string()],
|
||||
"cluster {cluster}: x:y is the value flag's operand, HEAD:big.txt the object",
|
||||
);
|
||||
}
|
||||
// An INLINE cluster value (`-Sfoo` == `-S foo`) does NOT consume the next token,
|
||||
// so the following object is still exposed.
|
||||
let args = show_args(&["-Sneedle", "HEAD:big.txt"]);
|
||||
assert_eq!(blob_candidates(&args), vec![&"HEAD:big.txt".to_string()]);
|
||||
// `-Gx:y` (value flag NOT last, inline value `x:y`) consumes no next token.
|
||||
let args = show_args(&["-Gx:y", "HEAD:big.txt"]);
|
||||
assert_eq!(blob_candidates(&args), vec![&"HEAD:big.txt".to_string()]);
|
||||
// A boolean-only cluster (`-wp`) consumes nothing: the object stays a candidate.
|
||||
let args = show_args(&["-wp", "HEAD:big.txt"]);
|
||||
assert_eq!(blob_candidates(&args), vec![&"HEAD:big.txt".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_show_route_colon_pathspec_after_dashdash_is_not_a_blob() {
|
||||
// A filename containing a colon AFTER `--` is a pathspec, not a blob target.
|
||||
// This `--` is representative of the real CLI path: clap strips the separator,
|
||||
// but `run_show` restores it via `restore_double_dash` before calling
|
||||
// `show_route`/`show_positionals` (verified live: `git show HEAD -- a:b.txt`
|
||||
// renders a commit-diff, not a blob dump).
|
||||
let args = show_args(&["HEAD", "--", "weird:name.txt"]);
|
||||
assert_eq!(show_route(&args), ShowRoute::CommitDiff);
|
||||
assert!(blob_candidates(&args).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_show_route_plain_cases() {
|
||||
assert_eq!(
|
||||
show_route(&show_args(&["--stat", "HEAD"])),
|
||||
ShowRoute::StatOrFormat
|
||||
);
|
||||
assert_eq!(show_route(&show_args(&["HEAD"])), ShowRoute::CommitDiff);
|
||||
assert_eq!(
|
||||
show_route(&show_args(&["HEAD:src/main.rs"])),
|
||||
ShowRoute::Blob
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_blob_windowing_token_savings() {
|
||||
// A filter must verify its savings claim with a real fixture. The enforced floor
|
||||
// is 20% (CONTRIBUTING.md), and `blob_large.txt` (a real `git show
|
||||
// HEAD:src/main.rs | head -350`, ~10.7 KB) has always cleared it: windowing to
|
||||
// the 8 KiB head plus a few-token recovery hint is the savings floor. (An earlier
|
||||
// revision introduced a synthetic ~107 KB fixture to chase a stale 60% figure
|
||||
// that only `.claude/rules/cli-testing.md` still cites; that churn is reverted.)
|
||||
fn count_tokens(text: &str) -> usize {
|
||||
text.split_whitespace().count()
|
||||
}
|
||||
let raw = include_str!("../../../tests/fixtures/git/blob_large.txt");
|
||||
assert!(raw.len() > MAX_BLOB_BYTES.0);
|
||||
let (head, _remaining, _offset) =
|
||||
blob_truncation(raw, MAX_BLOB_BYTES).expect("large blob should window");
|
||||
let savings = 100.0 - (count_tokens(head) as f64 / count_tokens(raw) as f64 * 100.0);
|
||||
assert!(
|
||||
savings >= 20.0,
|
||||
"expected ≥20% token savings, got {:.1}%",
|
||||
savings
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_blob_truncation_small_passthrough() {
|
||||
// Real committed file, ~1.7KB < budget: passed through unchanged.
|
||||
let small = include_str!("../../../Cargo.toml");
|
||||
assert!(blob_truncation(small, MAX_BLOB_BYTES).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_blob_truncation_large_windowed() {
|
||||
// Real blob fixture (`git show HEAD:src/main.rs | head -350`), ~10.7KB.
|
||||
let large = include_str!("../../../tests/fixtures/git/blob_large.txt");
|
||||
let (head, remaining, offset) =
|
||||
blob_truncation(large, MAX_BLOB_BYTES).expect("large blob should window");
|
||||
assert!(head.len() <= MAX_BLOB_BYTES.0);
|
||||
assert!(head.ends_with('\n'), "head must end at a line boundary");
|
||||
let head_lines = head.lines().count();
|
||||
// N formula: remaining == total - head_lines, offset == head_lines + 1.
|
||||
assert_eq!(offset, head_lines + 1);
|
||||
assert_eq!(remaining, large.lines().count() - head_lines);
|
||||
assert!(remaining > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_blob_truncation_tree_passthrough() {
|
||||
// Real tree listing (`git show HEAD:src`): `tree <rev>:<dir>\n\n...`. In the live
|
||||
// path the `git cat-file -t` probe classifies a tree as non-blob before this
|
||||
// function is ever reached, so the old `starts_with("tree ")` content-sniff was
|
||||
// removed; this small (87 B) listing still declines here via the size check.
|
||||
let tree = include_str!("../../../tests/fixtures/git/tree_listing.txt");
|
||||
assert!(tree.starts_with("tree "));
|
||||
assert!(blob_truncation(tree, MAX_BLOB_BYTES).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_blob_truncation_binary_passthrough() {
|
||||
let mut binary = "x".repeat(9000);
|
||||
binary.push('\0');
|
||||
assert!(blob_truncation(&binary, MAX_BLOB_BYTES).is_none());
|
||||
// Replacement char from lossy UTF-8 decoding of a binary blob.
|
||||
let lossy = format!("{}\u{FFFD}", "y".repeat(9000));
|
||||
assert!(blob_truncation(&lossy, MAX_BLOB_BYTES).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_blob_truncation_giant_single_line_passthrough() {
|
||||
// A single line longer than the budget has no line boundary to cut at.
|
||||
let giant = "a".repeat(20_000);
|
||||
assert!(blob_truncation(&giant, MAX_BLOB_BYTES).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_blob_truncation_utf8_boundary_no_panic() {
|
||||
// Multibyte content so the byte budget can land mid-codepoint: must not panic.
|
||||
let mut s = String::new();
|
||||
while s.len() < 9000 {
|
||||
s.push_str("áéíóú-ñ-日本語");
|
||||
s.push('\n');
|
||||
}
|
||||
// Exercise budgets straddling a multibyte char around the window edge.
|
||||
let _ = blob_truncation(&s, MAX_BLOB_BYTES);
|
||||
let _ = blob_truncation(&s, Budget(8191));
|
||||
let _ = blob_truncation(&s, Budget(8193));
|
||||
// Should still window (multi-line, over budget) without crashing.
|
||||
assert!(blob_truncation(&s, MAX_BLOB_BYTES).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_blob_truncation_no_trailing_newline() {
|
||||
let mut s = String::new();
|
||||
for i in 0..500 {
|
||||
s.push_str(&format!("line number {i} with a bit of content here\n"));
|
||||
}
|
||||
s.pop(); // drop the final newline
|
||||
let (head, remaining, offset) =
|
||||
blob_truncation(&s, MAX_BLOB_BYTES).expect("should window");
|
||||
assert_eq!(offset, head.lines().count() + 1);
|
||||
assert_eq!(remaining, s.lines().count() - head.lines().count());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_compact_blob_show_hint_is_tee_independent() {
|
||||
// The recovery hint re-derives the tail from the blob arg itself — no tee file,
|
||||
// so it works at any size (N2) and quotes a path with a space for safe paste.
|
||||
let mut s = String::new();
|
||||
for i in 0..2000 {
|
||||
s.push_str(&format!("line {i} with enough content to exceed the byte budget\n"));
|
||||
}
|
||||
let offset = blob_truncation(&s, MAX_BLOB_BYTES).expect("should window").2;
|
||||
let out = compact_blob_show(&s, "HEAD:my dir/big.lock", &[]);
|
||||
assert!(out.len() < s.len(), "windowing must shrink the output");
|
||||
let expected = format!(
|
||||
"[see remaining: git show 'HEAD:my dir/big.lock' | tail -n +{offset}]"
|
||||
);
|
||||
assert!(out.contains(&expected), "hint missing/unquoted: {out:?}");
|
||||
assert!(!out.contains("tail -n +0"));
|
||||
|
||||
// A path containing a single quote must be escaped `'\''` so the hint stays
|
||||
// copy-paste safe (the dangerous branch of `shell_single_quote`).
|
||||
let out_q = compact_blob_show(&s, "HEAD:it's/a.lock", &[]);
|
||||
let expected_q =
|
||||
format!("[see remaining: git show 'HEAD:it'\\''s/a.lock' | tail -n +{offset}]");
|
||||
assert!(out_q.contains(&expected_q), "single-quote path unescaped: {out_q:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_compact_blob_show_small_passes_through() {
|
||||
// Below the byte budget: returned unchanged, no hint.
|
||||
let small = "a few\nshort\nlines\n";
|
||||
assert_eq!(compact_blob_show(small, "HEAD:x.txt", &[]), small);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_compact_blob_show_hint_carries_global_args() {
|
||||
// `rtk git -C /repo -c core.x=y show HEAD:big` must produce a hint that is
|
||||
// runnable from OUTSIDE the repo: the global args go between `git` and `show`,
|
||||
// each shell-quoted, so the recovery command targets the same repo.
|
||||
let mut s = String::new();
|
||||
for i in 0..2000 {
|
||||
s.push_str(&format!("line {i} with enough content to exceed the byte budget\n"));
|
||||
}
|
||||
let offset = blob_truncation(&s, MAX_BLOB_BYTES).expect("should window").2;
|
||||
let globals = vec![
|
||||
"-C".to_string(),
|
||||
"/tmp/my repo".to_string(),
|
||||
"-c".to_string(),
|
||||
"core.autocrlf=false".to_string(),
|
||||
];
|
||||
let out = compact_blob_show(&s, "HEAD:big.lock", &globals);
|
||||
// Every token is shell-quoted (same policy as the blob arg) — quoting a flag
|
||||
// like `-C` is a harmless no-op and keeps the hint copy-paste safe.
|
||||
let expected = format!(
|
||||
"[see remaining: git '-C' '/tmp/my repo' '-c' 'core.autocrlf=false' show 'HEAD:big.lock' | tail -n +{offset}]"
|
||||
);
|
||||
assert!(out.contains(&expected), "global-args hint wrong: {out:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
// `from_utf8` on a `include_bytes!` literal is exactly the point here (asserting the
|
||||
// fixture is NOT valid UTF-8, matching `run_show`'s decision predicate), so silence
|
||||
// clippy's "literal always errors" lint rather than obscure the intent.
|
||||
#[allow(invalid_from_utf8)]
|
||||
fn test_blob_latin1_fixture_passes_through() {
|
||||
// Real ISO-8859-1 slice of an Oracle PL/SQL `.pck` (14 KB, contains "MÉTODO",
|
||||
// NOT valid UTF-8). Earlier revisions transcoded it to UTF-8 and windowed it,
|
||||
// but the head shown was then no longer a byte-exact prefix of git's bytes, so
|
||||
// `git show 'rev:path' | tail -n +N` could not reconstruct the original. Under
|
||||
// the fidelity invariant, `run_show` windows ONLY content that is valid UTF-8
|
||||
// byte-for-byte; anything that would need transcoding passes through unchanged.
|
||||
//
|
||||
// The decision predicate is `std::str::from_utf8(git_bytes).is_ok()`, so assert
|
||||
// the fixture is NOT valid UTF-8 — which is exactly why it takes the byte-exact
|
||||
// passthrough path rather than being windowed.
|
||||
let bytes = include_bytes!("../../../tests/fixtures/git/latin1_blob.pck");
|
||||
assert!(bytes.len() > MAX_BLOB_BYTES.0);
|
||||
assert!(
|
||||
std::str::from_utf8(bytes).is_err(),
|
||||
"a Latin-1 .pck is not valid UTF-8, so it must pass through byte-identically \
|
||||
(exact recovery is impossible once transcoded)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -316,7 +316,9 @@ fn filter_migrate_status(output: &str) -> String {
|
||||
applied_count += 1;
|
||||
if latest_migration.is_empty() && line.contains("202") {
|
||||
if let Some(pos) = line.find("202") {
|
||||
let end = line[pos..].find(|c: char| c.is_whitespace()).unwrap_or(20);
|
||||
let end = line[pos..]
|
||||
.find(|c: char| c.is_whitespace())
|
||||
.unwrap_or(line.len() - pos);
|
||||
latest_migration = line[pos..pos + end].to_string();
|
||||
}
|
||||
}
|
||||
@@ -462,6 +464,21 @@ import { PrismaClient } from '@prisma/client'
|
||||
assert!(!result.contains("Start by importing"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_migrate_status_reads_a_timestamp_at_end_of_line() {
|
||||
// The migration id ran to the end of the line, so there was no whitespace to find and
|
||||
// the hardcoded fallback of 20 sliced past it -- a panic, which aborts in release and
|
||||
// takes the user's whole command output with it.
|
||||
let output = "Migration could not be applied at 2024-01-01T12:00:00";
|
||||
let result = filter_migrate_status(output);
|
||||
assert!(result.contains("2024-01-01T12:00:00"), "{result}");
|
||||
|
||||
// A multibyte character after the id must not split mid-char either.
|
||||
let output = "1 migration applied 20240101_café";
|
||||
let result = filter_migrate_status(output);
|
||||
assert!(result.contains("20240101_café"), "{result}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_migrate_dev() {
|
||||
let output = r#"
|
||||
|
||||
@@ -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,
|
||||
|
||||
+170
-3
@@ -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) => {
|
||||
@@ -588,16 +720,51 @@ pub fn exec_capture_stdin(cmd: &mut Command) -> Result<CaptureResult> {
|
||||
/// `.output()` keep the diagnostic instead of losing it. The program name is
|
||||
/// used as the label so no call site has to pass one.
|
||||
fn capture(cmd: &mut Command) -> Result<CaptureResult> {
|
||||
let raw = capture_raw(cmd)?;
|
||||
Ok(CaptureResult {
|
||||
stdout: super::utils::decode_process_output(&raw.stdout),
|
||||
stderr: super::utils::decode_process_output(&raw.stderr),
|
||||
exit_code: raw.exit_code,
|
||||
})
|
||||
}
|
||||
|
||||
/// Run `cmd` to completion and return its raw bytes plus a signal-aware exit code.
|
||||
/// The single spot that turns an `ExitStatus` into a code via
|
||||
/// [`exit_code_from_output`](super::utils::exit_code_from_output) — so the
|
||||
/// `process terminated by signal N` diagnostic is emitted uniformly whether the
|
||||
/// caller decodes the bytes ([`capture`]) or keeps them raw ([`exec_capture_bytes`]),
|
||||
/// instead of the raw path silently dropping it.
|
||||
fn capture_raw(cmd: &mut Command) -> Result<CaptureBytes> {
|
||||
let program = cmd.get_program().to_string_lossy().into_owned();
|
||||
let output = cmd.output().context("Failed to execute command")?;
|
||||
let exit_code = super::utils::exit_code_from_output(&output, &program);
|
||||
Ok(CaptureResult {
|
||||
stdout: super::utils::decode_process_output(&output.stdout),
|
||||
stderr: super::utils::decode_process_output(&output.stderr),
|
||||
Ok(CaptureBytes {
|
||||
stdout: output.stdout,
|
||||
stderr: output.stderr,
|
||||
exit_code,
|
||||
})
|
||||
}
|
||||
|
||||
/// Raw-byte capture result, for callers that must control decoding themselves —
|
||||
/// e.g. non-UTF-8 output that [`exec_capture`]'s `from_utf8_lossy` would corrupt.
|
||||
pub struct CaptureBytes {
|
||||
pub stdout: Vec<u8>,
|
||||
pub stderr: Vec<u8>,
|
||||
pub exit_code: i32,
|
||||
}
|
||||
|
||||
impl CaptureBytes {
|
||||
pub fn success(&self) -> bool {
|
||||
self.exit_code == 0
|
||||
}
|
||||
}
|
||||
|
||||
/// Like [`exec_capture`] but returns raw bytes so the caller decides how to decode.
|
||||
pub fn exec_capture_bytes(cmd: &mut Command) -> Result<CaptureBytes> {
|
||||
cmd.stdin(Stdio::null());
|
||||
capture_raw(cmd)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
|
||||
+19
-5
@@ -730,13 +730,21 @@ mod tests {
|
||||
Ok(t) => t,
|
||||
Err(_) => return, // No DB — skip
|
||||
};
|
||||
let (cmds, top, pct, saved_24h, saved_total) = get_stats(&tracker);
|
||||
// The trailing saved-token sums are unbounded and signed: `tokens_saved_24h` and
|
||||
// `total_tokens_saved` return an unclamped `SUM(saved_tokens)`, so a window whose
|
||||
// filters emitted more than they saved sums negative, and the 24h window can
|
||||
// exceed the all-time total when the rows outside it are the negative ones.
|
||||
// Nothing about their value is assertable, so this test does not bind them.
|
||||
let (cmds, top, pct, ..) = get_stats(&tracker);
|
||||
assert!(cmds >= 0);
|
||||
assert!(top.len() <= 5);
|
||||
assert!(saved_24h >= 0);
|
||||
assert!(saved_total >= 0);
|
||||
if let Some(p) = pct {
|
||||
assert!((0.0..=100.0).contains(&p));
|
||||
// Signed savings: a net-regressing DB makes overall savings honestly
|
||||
// negative; only the upper bound is a real invariant (never saves > 100%).
|
||||
assert!(
|
||||
p <= 100.0,
|
||||
"overall savings pct must never exceed 100, got {p}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -750,7 +758,13 @@ mod tests {
|
||||
assert!(stats.passthrough_top.len() <= 5);
|
||||
assert!(stats.parse_failures_24h >= 0);
|
||||
assert!(stats.low_savings_commands.len() <= 5);
|
||||
assert!((0.0..=100.0).contains(&stats.avg_savings_per_command));
|
||||
// Signed savings: avg_savings_per_command can be negative for a regressing
|
||||
// filter; bound only the upper end (a real saving never exceeds 100%).
|
||||
assert!(
|
||||
stats.avg_savings_per_command <= 100.0,
|
||||
"avg savings per command must never exceed 100, got {}",
|
||||
stats.avg_savings_per_command
|
||||
);
|
||||
assert!(
|
||||
["claude", "gemini", "codex", "cursor", "copilot", "vibe", "none", "unknown"]
|
||||
.iter()
|
||||
|
||||
+124
-12
@@ -515,7 +515,12 @@ impl Tracker {
|
||||
output_tokens: usize,
|
||||
exec_time_ms: u64,
|
||||
) -> Result<()> {
|
||||
let saved = input_tokens.saturating_sub(output_tokens);
|
||||
// Signed, so a command that emitted MORE than the wrapped command records the
|
||||
// truth (a negative saving / negative pct) instead of `saturating_sub` clamping
|
||||
// to 0 and reporting a fake "0% — did nothing". SQLite INTEGER/REAL both hold
|
||||
// negatives. Aggregate readers clamp these to 0 for their unsigned token-count
|
||||
// API, but per-command `savings_pct` keeps the honest negative.
|
||||
let saved = input_tokens as i64 - output_tokens as i64;
|
||||
let pct = if input_tokens > 0 {
|
||||
(saved as f64 / input_tokens as f64) * 100.0
|
||||
} else {
|
||||
@@ -534,7 +539,7 @@ impl Tracker {
|
||||
project_path, // added
|
||||
input_tokens as i64,
|
||||
output_tokens as i64,
|
||||
saved as i64,
|
||||
saved,
|
||||
pct,
|
||||
exec_time_ms as i64
|
||||
],
|
||||
@@ -838,7 +843,9 @@ impl Tracker {
|
||||
Ok((
|
||||
row.get::<_, i64>(0)? as usize,
|
||||
row.get::<_, i64>(1)? as usize,
|
||||
row.get::<_, i64>(2)? as usize,
|
||||
// saved_tokens may be negative (a command that worsened output); clamp
|
||||
// to 0 for the unsigned aggregate so it never wraps to a huge usize.
|
||||
row.get::<_, i64>(2)?.max(0) as usize,
|
||||
row.get::<_, i64>(3)? as u64,
|
||||
))
|
||||
})?;
|
||||
@@ -899,7 +906,8 @@ impl Tracker {
|
||||
Ok((
|
||||
row.get::<_, String>(0)?,
|
||||
row.get::<_, i64>(1)? as usize,
|
||||
row.get::<_, i64>(2)? as usize,
|
||||
// SUM(saved_tokens): clamp a net-negative group to 0 (unsigned field).
|
||||
row.get::<_, i64>(2)?.max(0) as usize,
|
||||
row.get::<_, f64>(3)?,
|
||||
row.get::<_, f64>(4)? as u64,
|
||||
))
|
||||
@@ -924,7 +932,11 @@ impl Tracker {
|
||||
|
||||
let rows = stmt.query_map(params![project_exact, project_glob], |row| {
|
||||
// added: params
|
||||
Ok((row.get::<_, String>(0)?, row.get::<_, i64>(1)? as usize))
|
||||
// SUM(saved_tokens) per day: clamp a net-negative day to 0 (unsigned field).
|
||||
Ok((
|
||||
row.get::<_, String>(0)?,
|
||||
row.get::<_, i64>(1)?.max(0) as usize,
|
||||
))
|
||||
})?;
|
||||
|
||||
let mut result: Vec<_> = rows.collect::<Result<Vec<_>, _>>()?;
|
||||
@@ -974,7 +986,7 @@ impl Tracker {
|
||||
let rows = stmt.query_map(params![project_exact, project_glob], |row| {
|
||||
// added: params
|
||||
let input = row.get::<_, i64>(2)? as usize;
|
||||
let saved = row.get::<_, i64>(4)? as usize;
|
||||
let saved = row.get::<_, i64>(4)?.max(0) as usize; // clamp net-negative group
|
||||
let commands = row.get::<_, i64>(1)? as usize;
|
||||
let total_time = row.get::<_, i64>(5)? as u64;
|
||||
let savings_pct = if input > 0 {
|
||||
@@ -1048,7 +1060,7 @@ impl Tracker {
|
||||
let rows = stmt.query_map(params![project_exact, project_glob], |row| {
|
||||
// added: params
|
||||
let input = row.get::<_, i64>(3)? as usize;
|
||||
let saved = row.get::<_, i64>(5)? as usize;
|
||||
let saved = row.get::<_, i64>(5)?.max(0) as usize; // clamp net-negative group
|
||||
let commands = row.get::<_, i64>(2)? as usize;
|
||||
let total_time = row.get::<_, i64>(6)? as u64;
|
||||
let savings_pct = if input > 0 {
|
||||
@@ -1122,7 +1134,7 @@ impl Tracker {
|
||||
let rows = stmt.query_map(params![project_exact, project_glob], |row| {
|
||||
// added: params
|
||||
let input = row.get::<_, i64>(2)? as usize;
|
||||
let saved = row.get::<_, i64>(4)? as usize;
|
||||
let saved = row.get::<_, i64>(4)?.max(0) as usize; // clamp net-negative group
|
||||
let commands = row.get::<_, i64>(1)? as usize;
|
||||
let total_time = row.get::<_, i64>(5)? as u64;
|
||||
let savings_pct = if input > 0 {
|
||||
@@ -1202,7 +1214,7 @@ impl Tracker {
|
||||
.map(|dt| dt.with_timezone(&Utc))
|
||||
.unwrap_or_else(|_| Utc::now()),
|
||||
rtk_cmd: row.get(1)?,
|
||||
saved_tokens: row.get::<_, i64>(2)? as usize,
|
||||
saved_tokens: row.get::<_, i64>(2)?.max(0) as usize, // clamp negative
|
||||
savings_pct: row.get(3)?,
|
||||
})
|
||||
},
|
||||
@@ -1318,6 +1330,12 @@ impl Tracker {
|
||||
}
|
||||
|
||||
/// Average savings percentage per command (unweighted — each command name counts once).
|
||||
///
|
||||
/// Keeps the honest signed value: a command whose filter consistently emits
|
||||
/// more than it saves yields a negative average, mirroring `overall_savings_pct`
|
||||
/// and the signed per-command `savings_pct` (see `record`). Only the upper end is
|
||||
/// bounded (a real saving never exceeds 100%); telemetry consumers assert on that,
|
||||
/// not on a `0..=100` floor.
|
||||
pub fn avg_savings_per_command(&self) -> Result<f64> {
|
||||
let avg: f64 = self.conn.query_row(
|
||||
"SELECT COALESCE(AVG(avg_sav), 0.0) FROM (
|
||||
@@ -1499,7 +1517,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()
|
||||
@@ -1655,8 +1673,14 @@ pub fn record_parse_failure_silent(raw_command: &str, error_message: &str, succe
|
||||
/// assert_eq!(estimate_tokens("hello world"), 3); // 11 chars = ceil(2.75) = 3
|
||||
/// ```
|
||||
pub fn estimate_tokens(text: &str) -> usize {
|
||||
// ~4 chars per token on average
|
||||
(text.len() as f64 / 4.0).ceil() as usize
|
||||
estimate_tokens_from_len(text.len())
|
||||
}
|
||||
|
||||
/// Token estimate from a raw byte length, for callers that hold a byte count rather
|
||||
/// than a `&str` (e.g. non-UTF-8 captured output). Same ~4-chars-per-token model as
|
||||
/// [`estimate_tokens`].
|
||||
pub fn estimate_tokens_from_len(len: usize) -> usize {
|
||||
(len as f64 / 4.0).ceil() as usize
|
||||
}
|
||||
|
||||
/// Helper struct for timing command execution
|
||||
@@ -1742,6 +1766,27 @@ impl TimedExecution {
|
||||
}
|
||||
}
|
||||
|
||||
/// Like [`track`](Self::track), but the input size is supplied as a raw byte
|
||||
/// count instead of a `&str`. For callers whose captured input is non-UTF-8
|
||||
/// bytes (e.g. a Latin-1 blob): measuring the decoded string would count the
|
||||
/// transcoded (inflated) length rather than what the wrapped command emitted,
|
||||
/// overstating the reduction.
|
||||
pub fn track_bytes(&self, original_cmd: &str, rtk_cmd: &str, input_len: usize, output: &str) {
|
||||
let elapsed_ms = self.start.elapsed().as_millis() as u64;
|
||||
let input_tokens = estimate_tokens_from_len(input_len);
|
||||
let output_tokens = estimate_tokens(output);
|
||||
|
||||
if let Ok(tracker) = Tracker::new() {
|
||||
let _ = tracker.record(
|
||||
original_cmd,
|
||||
rtk_cmd,
|
||||
input_tokens,
|
||||
output_tokens,
|
||||
elapsed_ms,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Track passthrough commands (timing-only, no token counting).
|
||||
///
|
||||
/// For commands that stream output or run interactively where output
|
||||
@@ -1894,6 +1939,73 @@ mod tests {
|
||||
// because the savings calculation is correct for both cases
|
||||
}
|
||||
|
||||
// record() must reflect a REGRESSION (output larger than the wrapped command's)
|
||||
// as a negative saving, not saturate it to 0 and report a fake "0% — did nothing".
|
||||
#[test]
|
||||
fn test_record_reflects_worsening_not_zero() {
|
||||
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
|
||||
// Emitted 150 tokens where plain git emitted 100: a real regression.
|
||||
tracker
|
||||
.record("cmd", "rtk cmd worse", 100, 150, 5)
|
||||
.expect("Failed to record worsening command");
|
||||
|
||||
// The DB stores the honest negative saving (isolated in-memory DB, one row).
|
||||
assert_eq!(
|
||||
tracker.total_tokens_saved().expect("sum saved"),
|
||||
-50,
|
||||
"worsening must be stored as a negative saving, not saturated to 0"
|
||||
);
|
||||
|
||||
// The per-command savings_pct is negative, not the old fake 0%.
|
||||
let recent = tracker.get_recent(10).expect("Failed to get recent");
|
||||
let rec = recent
|
||||
.iter()
|
||||
.find(|r| r.rtk_cmd == "rtk cmd worse")
|
||||
.expect("worsening record not found");
|
||||
assert!(
|
||||
(rec.savings_pct - (-50.0)).abs() < 1e-9,
|
||||
"expected -50% savings, got {}",
|
||||
rec.savings_pct
|
||||
);
|
||||
|
||||
// Aggregate telemetry also reflects the regression as negative, and the unsigned
|
||||
// summary counter clamps rather than wrapping to a huge usize.
|
||||
assert!(
|
||||
tracker.overall_savings_pct().expect("overall pct") < 0.0,
|
||||
"overall savings must be negative for a net regression"
|
||||
);
|
||||
let summary = tracker.get_summary().expect("summary");
|
||||
assert_eq!(
|
||||
summary.total_saved, 0,
|
||||
"unsigned aggregate clamps a negative saving to 0 (never wraps)"
|
||||
);
|
||||
}
|
||||
|
||||
// avg_savings_per_command keeps the honest signed value: a command whose filter
|
||||
// consistently emits more than it saves yields a negative average (mirroring
|
||||
// overall_savings_pct), never saturated to a fake 0. This is the aggregate that
|
||||
// feeds the telemetry payload, so this pins that telemetry can carry a negative
|
||||
// savings signal instead of hiding a regressing filter behind 0%.
|
||||
#[test]
|
||||
fn test_avg_savings_per_command_reflects_negative() {
|
||||
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
|
||||
// 100 tokens in, 150 out: the filter made things worse => -50% per-command.
|
||||
tracker
|
||||
.record("cmd", "rtk worse", 100, 150, 5)
|
||||
.expect("Failed to record worsening command");
|
||||
|
||||
// Single command group, AVG(savings_pct) == -50%: the aggregate stays negative.
|
||||
let avg = tracker
|
||||
.avg_savings_per_command()
|
||||
.expect("avg_savings_per_command");
|
||||
assert!(
|
||||
(avg - (-50.0)).abs() < 1e-9,
|
||||
"expected honest -50% aggregate, got {avg}"
|
||||
);
|
||||
// Upper bound still holds (a real saving never exceeds 100%).
|
||||
assert!(avg <= 100.0, "aggregate must never exceed 100, got {avg}");
|
||||
}
|
||||
|
||||
// 5. TimedExecution::track records with exec_time > 0
|
||||
//
|
||||
// TimedExecution::track() hardcodes Tracker::new() internally (real
|
||||
|
||||
@@ -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
@@ -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
@@ -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
@@ -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
|
||||
|
||||
@@ -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
@@ -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) ---
|
||||
|
||||
@@ -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
@@ -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
@@ -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
|
||||
}
|
||||
|
||||
Vendored
+350
@@ -0,0 +1,350 @@
|
||||
mod analytics;
|
||||
mod cmds;
|
||||
mod core;
|
||||
mod discover;
|
||||
mod hooks;
|
||||
mod learn;
|
||||
mod parser;
|
||||
|
||||
// Re-export command modules for routing
|
||||
use cmds::cloud::{aws_cmd, container, curl_cmd, psql_cmd, wget_cmd};
|
||||
use cmds::dotnet::{binlog, dotnet_cmd, dotnet_format_report, dotnet_trx};
|
||||
use cmds::git::{diff_cmd, gh_cmd, git, glab_cmd, gt_cmd};
|
||||
use cmds::go::{go_cmd, golangci_cmd};
|
||||
use cmds::js::{
|
||||
lint_cmd, next_cmd, npm_cmd, playwright_cmd, pnpm_cmd, prettier_cmd, prisma_cmd, tsc_cmd,
|
||||
vitest_cmd,
|
||||
};
|
||||
use cmds::jvm::{gradlew_cmd, mvn_cmd};
|
||||
use cmds::php::{ecs_cmd, paratest_cmd, pest_cmd, php_cmd, phpstan_cmd, phpunit_cmd, pint_cmd};
|
||||
use cmds::python::{mypy_cmd, pip_cmd, pytest_cmd, ruff_cmd, uv_cmd};
|
||||
use cmds::ruby::{rake_cmd, rspec_cmd, rubocop_cmd};
|
||||
use cmds::rust::{cargo_cmd, runner};
|
||||
use cmds::system::{
|
||||
deps, env_cmd, find_cmd, format_cmd, json_cmd, local_llm, log_cmd, ls, pipe_cmd, read, search,
|
||||
summary, tree, wc_cmd,
|
||||
};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use clap::error::ErrorKind;
|
||||
use clap::{Parser, Subcommand, ValueEnum};
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Target agent for hook installation.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, ValueEnum)]
|
||||
pub enum AgentTarget {
|
||||
/// Claude Code (default)
|
||||
Claude,
|
||||
/// Cursor Agent (editor and CLI)
|
||||
Cursor,
|
||||
/// Windsurf IDE (Cascade)
|
||||
Windsurf,
|
||||
/// Cline / Roo Code (VS Code)
|
||||
Cline,
|
||||
/// Kilo Code
|
||||
Kilocode,
|
||||
/// Google Antigravity
|
||||
Antigravity,
|
||||
/// Pi coding agent
|
||||
Pi,
|
||||
/// Hermes CLI
|
||||
Hermes,
|
||||
/// Factory Droid CLI
|
||||
Droid,
|
||||
}
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
name = "rtk",
|
||||
version,
|
||||
about = "Rust Token Killer - Minimize LLM token consumption",
|
||||
long_about = "A high-performance CLI proxy designed to filter and summarize system outputs before they reach your LLM context."
|
||||
)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: Commands,
|
||||
|
||||
/// Verbosity level (-v, -vv, -vvv) — only recognized before the subcommand
|
||||
#[arg(short, long, action = clap::ArgAction::Count)]
|
||||
verbose: u8,
|
||||
|
||||
/// Ultra-compact mode: ASCII icons, inline format (Level 2 optimizations)
|
||||
#[arg(long, global = true)]
|
||||
ultra_compact: bool,
|
||||
|
||||
/// Set SKIP_ENV_VALIDATION=1 for child processes (Next.js, tsc, lint, prisma)
|
||||
#[arg(long = "skip-env", global = true)]
|
||||
skip_env: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Subcommand)]
|
||||
enum Commands {
|
||||
/// List directory contents with token-optimized output (proxy to native ls)
|
||||
Ls {
|
||||
/// Arguments passed to ls (supports all native ls flags like -l, -a, -h, -R)
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
},
|
||||
|
||||
/// Directory tree with token-optimized output (proxy to native tree)
|
||||
Tree {
|
||||
/// Arguments passed to tree (supports all native tree flags like -L, -d, -a)
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
},
|
||||
|
||||
/// Read file with intelligent filtering
|
||||
Read {
|
||||
/// Files to read (supports multiple, like cat)
|
||||
#[arg(required = true, num_args = 1..)]
|
||||
files: Vec<PathBuf>,
|
||||
/// Filter: none (default, full content), minimal, aggressive
|
||||
#[arg(short, long, default_value = "none")]
|
||||
level: core::filter::FilterLevel,
|
||||
/// Max lines
|
||||
#[arg(short, long, conflicts_with = "tail_lines")]
|
||||
max_lines: Option<usize>,
|
||||
/// Keep only last N lines
|
||||
#[arg(long, conflicts_with = "max_lines")]
|
||||
tail_lines: Option<usize>,
|
||||
/// Show line numbers
|
||||
#[arg(short = 'n', long)]
|
||||
line_numbers: bool,
|
||||
},
|
||||
|
||||
/// Generate 2-line technical summary (heuristic-based)
|
||||
Smart {
|
||||
/// File to analyze
|
||||
file: PathBuf,
|
||||
/// Model: heuristic
|
||||
#[arg(short, long, default_value = "heuristic")]
|
||||
model: String,
|
||||
/// Force model download
|
||||
#[arg(long)]
|
||||
force_download: bool,
|
||||
},
|
||||
|
||||
/// Git commands with compact output
|
||||
Git {
|
||||
/// Change to directory before executing (like git -C <path>, can be repeated)
|
||||
#[arg(short = 'C', action = clap::ArgAction::Append)]
|
||||
directory: Vec<String>,
|
||||
|
||||
/// Git configuration override (like git -c key=value, can be repeated)
|
||||
#[arg(short = 'c', action = clap::ArgAction::Append)]
|
||||
config_override: Vec<String>,
|
||||
|
||||
/// Set the path to the .git directory
|
||||
#[arg(long = "git-dir")]
|
||||
git_dir: Option<String>,
|
||||
|
||||
/// Set the path to the working tree
|
||||
#[arg(long = "work-tree")]
|
||||
work_tree: Option<String>,
|
||||
|
||||
/// Disable pager (like git --no-pager)
|
||||
#[arg(long = "no-pager")]
|
||||
no_pager: bool,
|
||||
|
||||
/// Skip optional locks (like git --no-optional-locks)
|
||||
#[arg(long = "no-optional-locks")]
|
||||
no_optional_locks: bool,
|
||||
|
||||
/// Treat repository as bare (like git --bare)
|
||||
#[arg(long)]
|
||||
bare: bool,
|
||||
|
||||
/// Treat pathspecs literally (like git --literal-pathspecs)
|
||||
#[arg(long = "literal-pathspecs")]
|
||||
literal_pathspecs: bool,
|
||||
|
||||
#[command(subcommand)]
|
||||
command: GitCommands,
|
||||
},
|
||||
|
||||
/// GitHub CLI (gh) commands with token-optimized output
|
||||
Gh {
|
||||
/// Subcommand: pr, issue, run, repo
|
||||
subcommand: String,
|
||||
/// Additional arguments
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
},
|
||||
|
||||
/// GitLab CLI (glab) commands with token-optimized output
|
||||
Glab {
|
||||
/// Target repository (owner/repo), passed as glab -R flag
|
||||
#[arg(short = 'R', long = "repo")]
|
||||
repo: Option<String>,
|
||||
/// Target group, passed as glab -g flag
|
||||
#[arg(short = 'g', long = "group")]
|
||||
group: Option<String>,
|
||||
/// Subcommand: mr, issue, ci, pipeline, api
|
||||
subcommand: String,
|
||||
/// Additional arguments
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
},
|
||||
|
||||
/// AWS CLI with compact output (force JSON, compress)
|
||||
Aws {
|
||||
/// AWS service subcommand (e.g., sts, s3, ec2, ecs, rds, cloudformation)
|
||||
subcommand: String,
|
||||
/// Additional arguments
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
},
|
||||
|
||||
/// PostgreSQL client with compact output (strip borders, compress tables)
|
||||
#[command(disable_help_flag = true)]
|
||||
Psql {
|
||||
/// psql arguments
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
},
|
||||
|
||||
/// pnpm commands with ultra-compact output
|
||||
Pnpm {
|
||||
/// pnpm filter arguments (can be repeated: --filter @app1 --filter @app2)
|
||||
#[arg(long, short = 'F')]
|
||||
filter: Vec<String>,
|
||||
|
||||
#[command(subcommand)]
|
||||
command: PnpmCommands,
|
||||
},
|
||||
|
||||
/// Run command and show only errors/warnings
|
||||
Err {
|
||||
/// Command to run
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
command: Vec<String>,
|
||||
},
|
||||
|
||||
/// Run tests and show only failures
|
||||
Test {
|
||||
/// Test command (e.g. cargo test)
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
command: Vec<String>,
|
||||
},
|
||||
|
||||
/// Show JSON (compact values by default, or keys-only with --keys-only)
|
||||
Json {
|
||||
/// JSON file
|
||||
file: PathBuf,
|
||||
/// Max depth
|
||||
#[arg(short, long, default_value = "5")]
|
||||
depth: usize,
|
||||
/// Show keys only (strip all values, show structure)
|
||||
#[arg(long)]
|
||||
keys_only: bool,
|
||||
},
|
||||
|
||||
/// Summarize project dependencies
|
||||
Deps {
|
||||
/// Project path
|
||||
#[arg(default_value = ".")]
|
||||
path: PathBuf,
|
||||
},
|
||||
|
||||
/// Show environment variables (filtered)
|
||||
Env {
|
||||
/// Filter by name (e.g. PATH, AWS)
|
||||
#[arg(short, long)]
|
||||
filter: Option<String>,
|
||||
},
|
||||
|
||||
/// Find files with compact tree output (accepts native find flags like -name, -type)
|
||||
Find {
|
||||
/// All find arguments (supports both RTK and native find syntax)
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
},
|
||||
|
||||
/// Ultra-condensed diff (only changed lines)
|
||||
Diff {
|
||||
/// First file or - for stdin (unified diff)
|
||||
file1: PathBuf,
|
||||
/// Second file (optional if stdin)
|
||||
file2: Option<PathBuf>,
|
||||
},
|
||||
|
||||
/// Filter and deduplicate log output
|
||||
Log {
|
||||
/// Log file (omit for stdin)
|
||||
file: Option<PathBuf>,
|
||||
},
|
||||
|
||||
/// .NET commands with compact output (build/test/restore/format)
|
||||
Dotnet {
|
||||
#[command(subcommand)]
|
||||
command: DotnetCommands,
|
||||
},
|
||||
|
||||
/// Docker commands with compact output
|
||||
Docker {
|
||||
#[command(subcommand)]
|
||||
command: DockerCommands,
|
||||
},
|
||||
|
||||
/// Kubectl commands with compact output
|
||||
Kubectl {
|
||||
#[command(subcommand)]
|
||||
command: KubectlCommands,
|
||||
},
|
||||
|
||||
/// OpenShift CLI (oc) commands with compact output
|
||||
Oc {
|
||||
#[command(subcommand)]
|
||||
command: OcCommands,
|
||||
},
|
||||
|
||||
/// Run command and show heuristic summary
|
||||
Summary {
|
||||
/// Command to run and summarize
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
command: Vec<String>,
|
||||
},
|
||||
|
||||
/// Compact grep - strips whitespace, truncates, groups by file
|
||||
Grep {
|
||||
/// Max line length
|
||||
#[arg(short = 'l', long, default_value = "80")]
|
||||
max_len: usize,
|
||||
/// Max results to show
|
||||
#[arg(short, long, default_value = "200")]
|
||||
max: usize,
|
||||
/// Show only match context (not full line)
|
||||
#[arg(long)]
|
||||
context_only: bool,
|
||||
/// Filter by file type (e.g., ts, py, rust)
|
||||
#[arg(short = 't', long)]
|
||||
file_type: Option<String>,
|
||||
/// Pattern, path, and any grep/rg flags (e.g. -v, -i, -A 3, --glob, --version)
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
extra_args: Vec<String>,
|
||||
},
|
||||
|
||||
/// Compact ripgrep - runs rg natively, same output filter as grep
|
||||
Rg {
|
||||
/// Pattern, path, and any rg flags (e.g. -v, -i, -t rust, --glob)
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
extra_args: Vec<String>,
|
||||
},
|
||||
|
||||
/// Initialize rtk instructions for assistant CLI usage
|
||||
Init {
|
||||
/// Add to global assistant config directory instead of local project file
|
||||
#[arg(short, long)]
|
||||
global: bool,
|
||||
|
||||
/// Install OpenCode plugin (in addition to Claude Code)
|
||||
#[arg(long)]
|
||||
opencode: bool,
|
||||
|
||||
/// Initialize for Gemini CLI instead of Claude Code
|
||||
#[arg(long)]
|
||||
gemini: bool,
|
||||
|
||||
/// Target agent to install hooks for (default: claude)
|
||||
#[arg(long, value_enum)]
|
||||
Vendored
+309
@@ -0,0 +1,309 @@
|
||||
encia %TYPE,
|
||||
pNtrc_Code IN PTOVENTA.VTA_OPERACION_FUNO.NTRC_CODE%TYPE,
|
||||
pNumPedidoVta IN PTOVENTA.VTA_OPERACION_FUNO.NUM_PED_VTA%TYPE,
|
||||
pEstComisionCash IN PTOVENTA.VTA_OPERACION_FUNO.EST_COMISION_CASH%TYPE);
|
||||
--FIN JPARCO 06052026
|
||||
end PTOVENTA_FUNO;
|
||||
/
|
||||
create or replace package body PTOVENTA.PTOVENTA_FUNO is
|
||||
|
||||
--INI CANTONIO 03/10/2019
|
||||
function EST_FUNO_RECAUDACION RETURN VARCHAR2 IS
|
||||
vRpta VARCHAR2(20);
|
||||
BEGIN
|
||||
SELECT LLAVE_TAB_GRAL
|
||||
INTO vRpta
|
||||
FROM PTOVENTA.PBL_TAB_GRAL PTO
|
||||
WHERE PTO.COD_TAB_GRAL = 'EST_FUNO'
|
||||
AND EST_TAB_GRAL = 'A';
|
||||
|
||||
RETURN vRpta;
|
||||
|
||||
END;
|
||||
-- FIN CANTONIO
|
||||
--INI SLEYVA 05/11/2019
|
||||
function COD_COMERCIO_FARMA RETURN VARCHAR2 IS
|
||||
vRpta VARCHAR2(20);
|
||||
BEGIN
|
||||
SELECT LLAVE_TAB_GRAL
|
||||
INTO vRpta
|
||||
FROM PTOVENTA.PBL_TAB_GRAL PTO
|
||||
WHERE PTO.COD_TAB_GRAL = 'COD_COMERCIO'
|
||||
AND EST_TAB_GRAL = 'A';
|
||||
|
||||
RETURN vRpta;
|
||||
|
||||
END;
|
||||
--INI SLEYVA 05/11/2019
|
||||
|
||||
-- INI SLEYVA 11/10/2019
|
||||
function imprimirVoucherComprobacion(codGrupoCia IN VARCHAR2,
|
||||
codLocal IN VARCHAR2,
|
||||
numero IN VARCHAR2,
|
||||
monto IN VARCHAR2)
|
||||
RETURN FarmaCursor IS
|
||||
curDataCupon FarmaCursor;
|
||||
vIdDoc IMPRESION_TERMICA.ID_DOC%type;
|
||||
vIpPc IMPRESION_TERMICA.IP_PC%type;
|
||||
vNumero VARCHAR2(20);
|
||||
vMonto VARCHAR(20);
|
||||
BEGIN
|
||||
|
||||
vIdDoc := FARMA_PRINTER.F_GENERA_ID_DOC;
|
||||
vIpPc := FARMA_PRINTER.F_GET_IP_SESS;
|
||||
vNumero := 'Numero: ' || numero;
|
||||
vMonto := 'Monto: S/.' || monto;
|
||||
|
||||
FARMA_PRINTER.P_AGREGA_LOGO_MARCA(vIdDoc_in => vIdDoc,
|
||||
vIpPc_in => vIpPc,
|
||||
vCodGrupoCia => codGrupoCia,
|
||||
vCodLocal_in => codLocal);
|
||||
|
||||
FARMA_PRINTER.P_AGREGA_LINEA_BLANCO(vIdDoc, vIpPc);
|
||||
|
||||
FARMA_PRINTER.P_AGREGA_TEXTO(vIdDoc_in => vIdDoc,
|
||||
vIpPc_in => vIpPc,
|
||||
vValor_in => vNumero,
|
||||
vTamanio_in => FARMA_PRINTER.TAMANIO_3,
|
||||
vAlineado_in => FARMA_PRINTER.ALING_CEN,
|
||||
vNegrita_in => FARMA_PRINTER.BOLD_ACT);
|
||||
FARMA_PRINTER.P_AGREGA_LINEA_BLANCO(vIdDoc, vIpPc);
|
||||
|
||||
FARMA_PRINTER.P_AGREGA_TEXTO(vIdDoc_in => vIdDoc,
|
||||
vIpPc_in => vIpPc,
|
||||
vValor_in => vMonto,
|
||||
vTamanio_in => FARMA_PRINTER.TAMANIO_3,
|
||||
vAlineado_in => FARMA_PRINTER.ALING_CEN,
|
||||
vNegrita_in => FARMA_PRINTER.BOLD_ACT);
|
||||
FARMA_PRINTER.P_AGREGA_LINEA_BLANCO(vIdDoc, vIpPc);
|
||||
|
||||
curDataCupon := FARMA_PRINTER.F_CUR_OBTIENE_DOC_IMPRIMIR(vIdDoc, vIpPc);
|
||||
|
||||
RETURN curDataCupon;
|
||||
END;
|
||||
-- FIN SLEYVA 11/10/2019
|
||||
-- INI SLEYVA 09/10/2019
|
||||
PROCEDURE REGISTRA_OPERACION_FUNO(pCoCompania IN PTOVENTA.VTA_OPERACION_FUNO.COD_GRUPO_CIA%TYPE,
|
||||
pCoLocal IN PTOVENTA.VTA_OPERACION_FUNO.COD_LOCAL%TYPE,
|
||||
pDeRespondeCode IN PTOVENTA.VTA_OPERACION_FUNO.DESC_RESPONDE_COD%TYPE,
|
||||
pVaMonto IN VARCHAR2,
|
||||
pCoAprobacion IN PTOVENTA.VTA_OPERACION_FUNO.COD_APROBACION%TYPE,
|
||||
pDeMensaje IN PTOVENTA.VTA_OPERACION_FUNO.DES_MENSAJE%TYPE,
|
||||
pDeTarjeta IN PTOVENTA.VTA_OPERACION_FUNO.DES_TARJETA%TYPE,
|
||||
pDeIdTarjeta IN PTOVENTA.VTA_OPERACION_FUNO.DES_ID_TARJETA%TYPE,
|
||||
pNuCuotas IN PTOVENTA.VTA_OPERACION_FUNO.NUM_CUOTAS%TYPE,
|
||||
pVaMontoCuota IN VARCHAR2,
|
||||
pTiCredito IN PTOVENTA.VTA_OPERACION_FUNO.TI_CREDITO%TYPE,
|
||||
pDeNombreCliente IN PTOVENTA.VTA_OPERACION_FUNO.DES_NOMBRE_CLIENTE%TYPE,
|
||||
pDeCodigoMoneda IN PTOVENTA.VTA_OPERACION_FUNO.DES_COD_MONEDA%TYPE,
|
||||
pDeAplicacion IN PTOVENTA.VTA_OPERACION_FUNO.DES_APLICACION%TYPE,
|
||||
pDeTipoTransaccion IN PTOVENTA.VTA_OPERACION_FUNO.DES_TIPO_TRANSACCION%TYPE,
|
||||
pCoTipoServicioFuno IN PTOVENTA.VTA_OPERACION_FUNO.COD_TIPO_SERVICIO_FUNO%TYPE,
|
||||
pCoComercio IN PTOVENTA.VTA_OPERACION_FUNO.COD_COMERCIO%TYPE,
|
||||
pCoAdquiriente IN PTOVENTA.VTA_OPERACION_FUNO.COD_ADQUIRIENTE%TYPE,
|
||||
pIdAutorizacion IN PTOVENTA.VTA_OPERACION_FUNO.ID_AUTORIZACION%TYPE,
|
||||
pDeDatetime IN PTOVENTA.VTA_OPERACION_FUNO.DES_DATETIME%TYPE,
|
||||
pDeTipo IN PTOVENTA.VTA_OPERACION_FUNO.DES_TIPO%TYPE,
|
||||
pTiLectura IN PTOVENTA.VTA_OPERACION_FUNO.TI_LECTURA%TYPE,
|
||||
pDeTerminal IN PTOVENTA.VTA_OPERACION_FUNO.DE_TERMINAL%TYPE,
|
||||
pNuLote IN PTOVENTA.VTA_OPERACION_FUNO.NUM_LOTE%TYPE,
|
||||
pNuReferencia IN PTOVENTA.VTA_OPERACION_FUNO.NUM_REFERENCIA%TYPE,
|
||||
pIdCreaOperacionFuno IN PTOVENTA.VTA_OPERACION_FUNO.COD_CREA_OPERACION_FUNO%TYPE,
|
||||
pCoCajero IN PTOVENTA.VTA_OPERACION_FUNO.COD_CAJERO%TYPE,
|
||||
pNuCaja IN PTOVENTA.VTA_OPERACION_FUNO.NUM_CAJA%TYPE,
|
||||
pNuTurno IN PTOVENTA.VTA_OPERACION_FUNO.NUM_TURNO%TYPE,
|
||||
pDeOperador IN PTOVENTA.VTA_OPERACION_FUNO.DES_OPERADOR%TYPE) AS
|
||||
V_CoTipoServicioFuno PTOVENTA.VTA_OPERACION_FUNO.COD_TIPO_SERVICIO_FUNO%TYPE;
|
||||
BEGIN
|
||||
--SE HA DEJADO EL MÉTODO IGUAL A INKAVENTA
|
||||
IF (LENGTH(TRIM(pCoTipoServicioFuno)) = 0) THEN
|
||||
V_CoTipoServicioFuno := NULL;
|
||||
ELSE
|
||||
V_CoTipoServicioFuno := pCoTipoServicioFuno;
|
||||
END IF;
|
||||
|
||||
INSERT INTO PTOVENTA.VTA_OPERACION_FUNO
|
||||
(COD_GRUPO_CIA,
|
||||
COD_LOCAL,
|
||||
COD_TRANSACCION_FUNO,
|
||||
DESC_RESPONDE_COD,
|
||||
VAL_MONTO,
|
||||
COD_APROBACION,
|
||||
DES_MENSAJE,
|
||||
DES_TARJETA,
|
||||
DES_ID_TARJETA,
|
||||
NUM_CUOTAS,
|
||||
VA_MONTO_CUOTA,
|
||||
TI_CREDITO,
|
||||
DES_NOMBRE_CLIENTE,
|
||||
DES_COD_MONEDA,
|
||||
DES_APLICACION,
|
||||
DES_TIPO_TRANSACCION,
|
||||
COD_TIPO_SERVICIO_FUNO,
|
||||
COD_COMERCIO,
|
||||
COD_ADQUIRIENTE,
|
||||
ID_AUTORIZACION,
|
||||
DES_DATETIME,
|
||||
DES_TIPO,
|
||||
TI_LECTURA,
|
||||
DE_TERMINAL,
|
||||
NUM_LOTE,
|
||||
NUM_REFERENCIA,
|
||||
COD_CREA_OPERACION_FUNO,
|
||||
FEC_CREA_OPERACION_FUNO,
|
||||
COD_CAJERO,
|
||||
NUM_CAJA,
|
||||
NUM_TURNO,
|
||||
DES_OPERADOR)
|
||||
Values
|
||||
(pCoCompania,
|
||||
pCoLocal,
|
||||
SEQ_OPERACION_FUNO.NEXTVAL,
|
||||
pDeRespondeCode,
|
||||
TO_NUMBER(SUBSTR(pVaMonto, 0, LENGTH(pVaMonto) - 2) || '.' || SUBSTR(pVaMonto, LENGTH(pVaMonto) - 1), '9999999999999.99'), --RARGUMEDO 21-05-2020
|
||||
pCoAprobacion,
|
||||
pDeTarjeta, -- RARGUMEDO 26-05-2020
|
||||
pDeTarjeta,
|
||||
pDeIdTarjeta,
|
||||
pNuCuotas,
|
||||
TO_NUMBER(SUBSTR(pVaMontoCuota, 0, LENGTH(pVaMontoCuota) - 2) || '.' || SUBSTR(pVaMontoCuota, LENGTH(pVaMontoCuota) - 1), '9999999999999.99'), -- RARGUMEDO 21-05-2020
|
||||
pTiCredito,
|
||||
pDeNombreCliente,
|
||||
pDeCodigoMoneda,
|
||||
pDeAplicacion,
|
||||
pDeTipoTransaccion,
|
||||
V_CoTipoServicioFuno,
|
||||
pCoComercio,
|
||||
pCoAdquiriente,
|
||||
pIdAutorizacion,
|
||||
pDeDateTime,
|
||||
pDeTipo,
|
||||
pTiLectura,
|
||||
pDeTerminal,
|
||||
pNuLote,
|
||||
pNuReferencia,
|
||||
pIdCreaOperacionFuno,
|
||||
sysdate,
|
||||
pCoCajero,
|
||||
pNuCaja,
|
||||
pNuTurno,
|
||||
pDeOperador);
|
||||
|
||||
END;
|
||||
-- FIN SLEYVA 09/10/2019
|
||||
|
||||
-- INI SLEYVA 09/10/2019
|
||||
FUNCTION GET_TRANSACCIONES_FUNO(codigocompania_in IN VTA_COMP_PAGO.COD_GRUPO_CIA%TYPE,
|
||||
codigolocal_in IN VTA_COMP_PAGO.COD_LOCAL%TYPE,
|
||||
feTx_in IN CHAR,
|
||||
feTx_fin IN CHAR)
|
||||
RETURN FarmaCursor IS
|
||||
farmacur FarmaCursor;
|
||||
BEGIN
|
||||
OPEN farmacur FOR
|
||||
SELECT CASE
|
||||
WHEN A.DES_TIPO_TRANSACCION = '03' THEN
|
||||
'DISPOSICIÓN EFECTIVO'
|
||||
WHEN A.DES_TIPO_TRANSACCION = '06' THEN
|
||||
'ANULACIÓN DISPOSICIÓN EFECTIVO'
|
||||
WHEN A.DES_TIPO_TRANSACCION = '13' THEN
|
||||
'PAGO SERVICIOS'
|
||||
WHEN A.DES_TIPO_TRANSACCION = '07' THEN
|
||||
'ANULACIÓN PAGO SERVICIOS'
|
||||
ELSE
|
||||
' '
|
||||
END || 'Ã' || NVL(A.COD_TIPO_SERVICIO_FUNO, ' ') || 'Ã' ||
|
||||
NVL(B.DES_TIPO_SERVICIO_FUNO, ' ') || 'Ã' ||
|
||||
TO_CHAR(A.VAL_MONTO, '999,999,999.99') || 'Ã' ||
|
||||
NVL(A.COD_APROBACION, ' ') || 'Ã' || NVL(A.DES_TARJETA, ' ') || 'Ã' ||
|
||||
NVL(A.DES_ID_TARJETA, ' ') || 'Ã' ||
|
||||
NVL(A.DES_NOMBRE_CLIENTE, ' ') || 'Ã' || NVL(A.NUM_LOTE, ' ') || 'Ã' ||
|
||||
NVL(A.NUM_REFERENCIA, ' ') || 'Ã' || NVL(A.COD_CAJERO, ' ') || 'Ã' ||
|
||||
TRIM(C.APE_PAT) || ' ' || TRIM(C.APE_MAT) || ' ' ||
|
||||
TRIM(C.NOM_USU) || 'Ã' || A.NUM_CAJA || 'Ã' || A.NUM_TURNO || 'Ã' ||
|
||||
A.DES_OPERADOR || 'Ã' ||
|
||||
NVL(A.IP_PC, ' ')
|
||||
FROM PTOVENTA.VTA_OPERACION_FUNO A,
|
||||
VTA_TIPO_SERVICIO_FUNO B,
|
||||
PBL_USU_LOCAL C
|
||||
WHERE A.COD_GRUPO_CIA = codigocompania_in
|
||||
AND A.COD_LOCAL = codigolocal_in
|
||||
AND A.FEC_CREA_OPERACION_FUNO BETWEEN
|
||||
TO_DATE(feTx_in || ' 00:00:00', 'DD/MM/YYYY HH24:MI:SS') AND
|
||||
TO_DATE(feTx_fin || ' 23:59:59', 'DD/MM/YYYY HH24:MI:SS')
|
||||
AND A.COD_TIPO_SERVICIO_FUNO = B.COD_TIPO_SERVICIO_FUNO(+)
|
||||
AND A.COD_GRUPO_CIA = C.COD_GRUPO_CIA
|
||||
AND A.COD_LOCAL = C.COD_LOCAL
|
||||
AND A.COD_CAJERO = C.SEC_USU_LOCAL;
|
||||
|
||||
RETURN farmacur;
|
||||
END;
|
||||
-- FIN SLEYVA 09/10/2019
|
||||
|
||||
-- INI SLEYVA 10/10/2019
|
||||
PROCEDURE GRABA_OPERACON_INVALIDA(codigogrupocia_in IN PTOVENTA.VTA_OPERACIONES_INVALIDAS.COD_GRUPO_CIA%TYPE,
|
||||
codigolocal_in IN PTOVENTA.VTA_OPERACIONES_INVALIDAS.COD_LOCAL%TYPE,
|
||||
cocajero_in IN PTOVENTA.VTA_OPERACIONES_INVALIDAS.COD_CAJERO%TYPE,
|
||||
coopesolicitada_in IN PTOVENTA.VTA_OPERACIONES_INVALIDAS.COD_OPERACION_SOLICITADA%TYPE,
|
||||
cooperealizada_in IN PTOVENTA.VTA_OPERACIONES_INVALIDAS.COD_OPERACION_EFECTUADA%TYPE,
|
||||
vamonto_in IN PTOVENTA.VTA_OPERACIONES_INVALIDAS.VAL_MONTO%TYPE,
|
||||
idtransaccion_in IN PTOVENTA.VTA_OPERACIONES_INVALIDAS.COD_TRANSACCION%TYPE,
|
||||
cocomercio_in IN PTOVENTA.VTA_OPERACIONES_INVALIDAS.COD_COMERCIO%TYPE,
|
||||
determinal_in IN PTOVENTA.VTA_OPERACIONES_INVALIDAS.DES_TERMINAL%TYPE,
|
||||
nulote_in IN PTOVENTA.VTA_OPERACIONES_INVALIDAS.NUM_LOTE%TYPE,
|
||||
nureferencia_in IN PTOVENTA.VTA_OPERACIONES_INVALIDAS.NUM_REFERENCIA%TYPE,
|
||||
nuap_in IN PTOVENTA.VTA_OPERACIONES_INVALIDAS.NUM_AP%TYPE) IS
|
||||
V_CO_SECUENCIAL NUMBER;
|
||||
BEGIN
|
||||
SELECT NVL(MAX(COD_SECUENCIAL), 0) + 1
|
||||
INTO V_CO_SECUENCIAL
|
||||
FROM PTOVENTA.VTA_OPERACIONES_INVALIDAS
|
||||
WHERE COD_GRUPO_CIA = codigogrupocia_in
|
||||
AND COD_LOCAL = CODIGOLOCAL_IN;
|
||||
|
||||
INSERT INTO PTOVENTA.VTA_OPERACIONES_INVALIDAS
|
||||
(COD_GRUPO_CIA,
|
||||
COD_LOCAL,
|
||||
COD_SECUENCIAL,
|
||||
FEC_OPERACION,
|
||||
COD_CAJERO,
|
||||
COD_OPERACION_SOLICITADA,
|
||||
COD_OPERACION_EFECTUADA,
|
||||
VAL_MONTO,
|
||||
COD_TRANSACCION,
|
||||
COD_COMERCIO,
|
||||
DES_TERMINAL,
|
||||
NUM_LOTE,
|
||||
NUM_REFERENCIA,
|
||||
NUM_AP)
|
||||
VALUES
|
||||
(codigogrupocia_in,
|
||||
CODIGOLOCAL_IN,
|
||||
V_CO_SECUENCIAL,
|
||||
SYSDATE,
|
||||
COCAJERO_IN,
|
||||
COOPESOLICITADA_IN,
|
||||
COOPEREALIZADA_IN,
|
||||
VAMONTO_IN,
|
||||
IDTRANSACCION_IN,
|
||||
COCOMERCIO_IN,
|
||||
DETERMINAL_IN,
|
||||
NULOTE_IN,
|
||||
NUREFERENCIA_IN,
|
||||
NUAP_IN);
|
||||
|
||||
COMMIT;
|
||||
END;
|
||||
-- FIN SLEYVA 10/10/2019
|
||||
--INI RARGUMEDO 10-02-2020 -- OPERACIONES AGORA
|
||||
PROCEDURE UPDATE_TIPO_RCD(pCoGrupoCia IN PTOVENTA.VTA_OPERACION_FUNO.cod_grupo_cia%TYPE,
|
||||
pCoCia IN PTOVENTA.VTA_OPERACION_FUNO.COD_CIA %TYPE,
|
||||
pCoLocal IN PTOVENTA.VTA_OPERACION_FUNO.cod_local %TYPE,
|
||||
pCoAprobacion IN PTOVENTA.VTA_OPERACION_FUNO.cod_aprobacion %TYPE,
|
||||
pDeTarjeta IN PTOVENTA.VTA_OPERACION_FUNO.des_tarjeta %TYPE,
|
||||
pDeTipoTransaccion IN PTOVENTA.VTA_OPERACION_FUNO.des_tipo_transaccion %TYPE,
|
||||
pIdAutorizacion IN PTOVENTA.VTA_OPERACION_FUNO.id_autorizacion %TYPE,
|
||||
pNuLote IN PTOVENTA.VTA_OPERACION_FUNO.num_lote %TYPE,
|
||||
pNuReferencia IN PTOVENTA.VTA_OPERACION_FUNO.num_referencia %TYPE,
|
||||
pNtrc_Code IN PTOVENTA.VTA_OPERACION_FUNO.NTRC_CODE%TYPE,
|
||||
pTipR
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
tree HEAD:src
|
||||
|
||||
analytics/
|
||||
cmds/
|
||||
core/
|
||||
discover/
|
||||
filters/
|
||||
hooks/
|
||||
learn/
|
||||
main.rs
|
||||
parser/
|
||||
@@ -0,0 +1,592 @@
|
||||
//! Differential fuzzer for `rtk git show` blob classification.
|
||||
//!
|
||||
//! The blob-windowing bug ("is this `git show` arg a blob to window, or a commit-diff /
|
||||
//! flag value?") was reopened three times because the classifier tried to mirror git's
|
||||
//! flag grammar. The fix asks git instead: `git cat-file -t <arg>` is the authority, and
|
||||
//! `rtk` only ever windows an arg git calls a `blob`.
|
||||
//!
|
||||
//! This test is the standing guarantee that no misroute class is hiding. It builds a
|
||||
//! hermetic git repo with objects of every relevant type, then — with a FIXED seed so CI
|
||||
//! is deterministic — generates hundreds of `git show <random flags> <arg>` invocations
|
||||
//! and checks rtk's CLASSIFICATION (did it window? pass through? render a commit-diff?)
|
||||
//! against ground truth from `git cat-file -t`. It asserts:
|
||||
//! - 0 misroutes: rtk never windows anything git does not call a `blob`;
|
||||
//! - 0 silent losses: a large, byte-recoverable UTF-8 blob is ALWAYS windowed — INCLUDING
|
||||
//! when a colon-carrying short-flag CLUSTER (`-wG x:y`, `-pS url:1`, …) precedes it, the
|
||||
//! exact cross the old fuzzer never generated so the blocker hid for three rounds;
|
||||
//! - byte fidelity: a blob rtk declines to window (Latin-1 / UTF-16 / small text, a
|
||||
//! Latin-1 blob behind a cluster flag, or a blob with `--textconv` / a trailing
|
||||
//! `-- <path>`) is emitted byte-identically to `git show` — no U+FFFD mojibake.
|
||||
//!
|
||||
//! It shells out to the real `git` and the built `rtk` binary, matching the repo's other
|
||||
//! integration tests (e.g. `diff_byte_accuracy_test.rs`).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Output};
|
||||
|
||||
const RTK_BIN: &str = env!("CARGO_BIN_EXE_rtk");
|
||||
|
||||
/// Number of fuzz iterations. Seeded, so this is deterministic across runs/CI.
|
||||
const ITERATIONS: usize = 600;
|
||||
/// Fixed seed — change only intentionally.
|
||||
const SEED: u64 = 0x5DEE_CE66_D3A1_2B4F;
|
||||
|
||||
// ---- deterministic PRNG (SplitMix64) -------------------------------------------------
|
||||
|
||||
struct Rng(u64);
|
||||
|
||||
impl Rng {
|
||||
fn next_u64(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
fn below(&mut self, n: usize) -> usize {
|
||||
(self.next_u64() % n as u64) as usize
|
||||
}
|
||||
fn pick<'a, T>(&mut self, xs: &'a [T]) -> &'a T {
|
||||
&xs[self.below(xs.len())]
|
||||
}
|
||||
fn chance(&mut self, n: usize, d: usize) -> bool {
|
||||
self.below(d) < n
|
||||
}
|
||||
}
|
||||
|
||||
// ---- git / rtk helpers ---------------------------------------------------------------
|
||||
|
||||
/// Env that isolates git and rtk from the developer's real config/identity/home.
|
||||
fn isolate(cmd: &mut Command, home: &Path) {
|
||||
cmd.env("HOME", home)
|
||||
.env("GIT_CONFIG_GLOBAL", home.join("nonexistent-global"))
|
||||
.env("GIT_CONFIG_SYSTEM", home.join("nonexistent-system"))
|
||||
.env("GIT_AUTHOR_NAME", "t")
|
||||
.env("GIT_AUTHOR_EMAIL", "t@example.com")
|
||||
.env("GIT_COMMITTER_NAME", "t")
|
||||
.env("GIT_COMMITTER_EMAIL", "t@example.com")
|
||||
.env("GIT_TERMINAL_PROMPT", "0")
|
||||
.env_remove("GIT_DIR")
|
||||
.env_remove("GIT_WORK_TREE");
|
||||
}
|
||||
|
||||
fn git(repo: &Path, home: &Path, args: &[&str]) -> Output {
|
||||
let mut cmd = Command::new("git");
|
||||
cmd.arg("-C").arg(repo);
|
||||
// Never sign or convert line endings in the hermetic repo.
|
||||
cmd.args(["-c", "commit.gpgsign=false", "-c", "core.autocrlf=false"]);
|
||||
cmd.args(args);
|
||||
isolate(&mut cmd, home);
|
||||
cmd.output().expect("run git")
|
||||
}
|
||||
|
||||
fn git_ok(repo: &Path, home: &Path, args: &[&str]) {
|
||||
let out = git(repo, home, args);
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"git {:?} failed: {}",
|
||||
args,
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
);
|
||||
}
|
||||
|
||||
/// `git cat-file -t <arg>` → object type, or None on a non-zero exit (not an object).
|
||||
fn cat_file_type(repo: &Path, home: &Path, arg: &str) -> Option<String> {
|
||||
let out = git(repo, home, &["cat-file", "-t", arg]);
|
||||
if out.status.success() {
|
||||
Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn rtk_show(repo: &Path, home: &Path, args: &[&str]) -> Output {
|
||||
let mut cmd = Command::new(RTK_BIN);
|
||||
cmd.arg("git").arg("show").args(args).current_dir(repo);
|
||||
isolate(&mut cmd, home);
|
||||
cmd.output().expect("run rtk git show")
|
||||
}
|
||||
|
||||
// ---- hermetic repo -------------------------------------------------------------------
|
||||
|
||||
struct Repo {
|
||||
_dir: tempfile::TempDir,
|
||||
path: PathBuf,
|
||||
home: PathBuf,
|
||||
}
|
||||
|
||||
fn setup_repo() -> Repo {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let path = dir.path().to_path_buf();
|
||||
let home = path.join("home");
|
||||
std::fs::create_dir_all(&home).expect("home dir");
|
||||
|
||||
git_ok(&path, &home, &["init", "-q"]);
|
||||
|
||||
// A large, valid-UTF-8 text blob (~90 KB): the one thing that MUST be windowed.
|
||||
let mut large = String::new();
|
||||
for i in 0..2000 {
|
||||
large.push_str(&format!(
|
||||
"line {i:04} — lorem ipsum dolor sit amet with enough width to pass the budget\n"
|
||||
));
|
||||
}
|
||||
std::fs::write(path.join("large.txt"), &large).expect("write large.txt");
|
||||
|
||||
// A small UTF-8 blob: below the byte budget, always passed through.
|
||||
std::fs::write(path.join("small.txt"), "alpha\nbeta\ngamma\n").expect("write small.txt");
|
||||
|
||||
// A directory → its `git show <rev>:<dir>` renders a tree listing (type tree).
|
||||
std::fs::create_dir_all(path.join("dir")).expect("mkdir dir");
|
||||
std::fs::write(path.join("dir/inner.txt"), "inner\n").expect("write inner");
|
||||
|
||||
// A large Latin-1 (ISO-8859-1) blob: invalid UTF-8, so exact recovery after a
|
||||
// transcode is impossible → must pass through byte-identically, never windowed.
|
||||
let mut latin1: Vec<u8> = Vec::new();
|
||||
for i in 0..1200 {
|
||||
latin1.extend_from_slice(b"M\xC9TODO n"); // "MÉTODO n" in Latin-1
|
||||
latin1.extend_from_slice(i.to_string().as_bytes());
|
||||
latin1.extend_from_slice(b" ADI\xD3S PARDON\n"); // "ADIÓS ..." in Latin-1
|
||||
}
|
||||
assert!(
|
||||
std::str::from_utf8(&latin1).is_err(),
|
||||
"fixture must be non-UTF-8"
|
||||
);
|
||||
std::fs::write(path.join("latin1.pck"), &latin1).expect("write latin1.pck");
|
||||
|
||||
// A large UTF-16LE-with-BOM blob: `tail`-sliced bytes cannot concatenate with a
|
||||
// UTF-8 head, so it must pass through byte-identically, never windowed.
|
||||
let mut utf16: Vec<u8> = vec![0xFF, 0xFE]; // UTF-16LE BOM
|
||||
for i in 0..3000 {
|
||||
for u in format!("row {i} of the utf-16 blob\n").encode_utf16() {
|
||||
utf16.extend_from_slice(&u.to_le_bytes());
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
std::str::from_utf8(&utf16).is_err(),
|
||||
"utf16 fixture must be non-UTF-8"
|
||||
);
|
||||
std::fs::write(path.join("utf16.txt"), &utf16).expect("write utf16.txt");
|
||||
|
||||
git_ok(&path, &home, &["add", "-A"]);
|
||||
git_ok(&path, &home, &["commit", "-q", "-m", "seed"]);
|
||||
// A second commit so HEAD~1 exists and commit-diffs have content.
|
||||
std::fs::write(path.join("small.txt"), "alpha\nbeta\ngamma\ndelta\n").expect("edit");
|
||||
git_ok(&path, &home, &["commit", "-q", "-am", "second"]);
|
||||
|
||||
Repo {
|
||||
_dir: dir,
|
||||
path,
|
||||
home,
|
||||
}
|
||||
}
|
||||
|
||||
// ---- classification ------------------------------------------------------------------
|
||||
|
||||
/// rtk windowed the blob iff its recovery hint is present (unique to blob windowing).
|
||||
fn was_windowed(out: &Output) -> bool {
|
||||
String::from_utf8_lossy(&out.stdout).contains("[see remaining: git ")
|
||||
}
|
||||
|
||||
/// The object categories the fuzzer draws from, with their expected classification.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Kind {
|
||||
/// Large valid-UTF-8 blob → MUST window.
|
||||
LargeUtf8,
|
||||
/// Small blob → passthrough, byte-identical.
|
||||
Small,
|
||||
/// Latin-1 blob → passthrough, byte-identical.
|
||||
Latin1,
|
||||
/// UTF-16 blob → passthrough, byte-identical.
|
||||
Utf16,
|
||||
/// A tree (directory) → never windowed.
|
||||
Tree,
|
||||
/// A commit ref, usually paired with a colon-carrying flag VALUE (the misroute
|
||||
/// stress: git re-parses `-pS`/`-wG`/… clusters, the colon token is a pickaxe/regex
|
||||
/// value, and there is NO blob) → never windowed.
|
||||
CommitMisroute,
|
||||
/// A bogus `rev:path` (nonexistent object) → git errors, never windowed.
|
||||
Bogus,
|
||||
/// THE BLOCKER: a colon-carrying short-flag CLUSTER (`-wG x:y`, `-pS url:1`, …)
|
||||
/// placed BEFORE a large UTF-8 blob. git consumes the colon token as the flag's
|
||||
/// value and dumps ONLY the blob, so it MUST still window (0 silent loss). The old
|
||||
/// walker knew only single-letter flags, so it read the colon value as the object,
|
||||
/// the probe rejected it, and the real blob fell through un-windowed.
|
||||
ClusterLargeUtf8,
|
||||
/// The same cluster before a Latin-1 blob. The old misroute sent it through the
|
||||
/// commit-diff path's lossy UTF-8 decode → `0xF1` became U+FFFD mojibake. Must pass
|
||||
/// through BYTE-IDENTICALLY to git.
|
||||
ClusterLatin1,
|
||||
/// A content-transforming flag (`--textconv`) before a large blob (MINOR 1). The
|
||||
/// `git show rev:path | tail` recovery hint omits the flag, so rtk must NOT window;
|
||||
/// it passes the bytes through byte-identically to `git show <same args>`.
|
||||
TextconvLargeUtf8,
|
||||
/// A trailing `-- <pathspec>` beside a large blob (MINOR 2). Also omitted from the
|
||||
/// hint, so rtk must NOT window; byte-identical passthrough.
|
||||
PathspecLargeUtf8,
|
||||
}
|
||||
|
||||
fn kind_object(kind: Kind) -> &'static str {
|
||||
match kind {
|
||||
Kind::LargeUtf8 => "HEAD:large.txt",
|
||||
Kind::Small => "HEAD:small.txt",
|
||||
Kind::Latin1 => "HEAD:latin1.pck",
|
||||
Kind::Utf16 => "HEAD:utf16.txt",
|
||||
Kind::Tree => "HEAD:dir",
|
||||
Kind::CommitMisroute => "HEAD",
|
||||
Kind::Bogus => "HEAD:does-not-exist.txt",
|
||||
Kind::ClusterLargeUtf8 | Kind::TextconvLargeUtf8 | Kind::PathspecLargeUtf8 => {
|
||||
"HEAD:large.txt"
|
||||
}
|
||||
Kind::ClusterLatin1 => "HEAD:latin1.pck",
|
||||
}
|
||||
}
|
||||
|
||||
// Valueless / colon-free flags that git ignores for a blob (still dumping the file), so
|
||||
// the blob stays the sole `rev:path` positional and must still window.
|
||||
const BLOB_SAFE_FLAGS: &[&str] = &[
|
||||
"-p",
|
||||
"-w",
|
||||
"-b",
|
||||
"--stat",
|
||||
"--numstat",
|
||||
"--shortstat",
|
||||
"--ignore-all-space",
|
||||
"--pretty=oneline",
|
||||
"--format=medium",
|
||||
];
|
||||
|
||||
// Colon-carrying flag VALUES: a cluster/flag consumes the NEXT token as its value, so a
|
||||
// colon there must not be read as a blob. These are the exact shapes KuSh's fuzzer hit.
|
||||
const COLON_VALUE_FLAGS: &[(&str, &str)] = &[
|
||||
("-pS", "url:1"),
|
||||
("-wG", "x:y"),
|
||||
("-pI", "a:b"),
|
||||
("-pwG", "q:r"),
|
||||
("-wpG", "m:n"),
|
||||
("-S", "needle:1"),
|
||||
("-G", "pat:2"),
|
||||
("-I", "re:3"),
|
||||
("--ignore-matching-lines", "a:b"),
|
||||
];
|
||||
|
||||
// The subset of `COLON_VALUE_FLAGS` the cluster-aware walker resolves WITHOUT needing a
|
||||
// long-flag table entry: short single-letter value flags and their clusters. For these,
|
||||
// the walker skips the colon value and the following blob is the sole positional, so a
|
||||
// large UTF-8 blob after one of them MUST window. (`--ignore-matching-lines` is a long
|
||||
// flag absent from the value table, so its space-form value stays a phantom positional
|
||||
// and the blob passes through byte-identically instead — correct, just uncompacted; it
|
||||
// is exercised via `CommitMisroute` and the byte-fidelity cross below, not here.)
|
||||
const WINDOWING_CLUSTER_FLAGS: &[(&str, &str)] = &[
|
||||
("-pS", "url:1"),
|
||||
("-wG", "x:y"),
|
||||
("-pI", "a:b"),
|
||||
("-pwG", "q:r"),
|
||||
("-wpG", "m:n"),
|
||||
("-S", "needle:1"),
|
||||
("-G", "pat:2"),
|
||||
("-I", "re:3"),
|
||||
];
|
||||
|
||||
fn build_invocation(rng: &mut Rng, kind: Kind) -> Vec<String> {
|
||||
let mut args: Vec<String> = Vec::new();
|
||||
match kind {
|
||||
Kind::CommitMisroute => {
|
||||
// A colon-carrying flag value with NO real blob — the misroute trap.
|
||||
let (flag, val) = *rng.pick(COLON_VALUE_FLAGS);
|
||||
args.push(flag.to_string());
|
||||
args.push(val.to_string());
|
||||
}
|
||||
Kind::LargeUtf8 | Kind::Small | Kind::Latin1 | Kind::Utf16 => {
|
||||
// Optionally sprinkle blob-safe flags before the object; they must not
|
||||
// change the blob classification.
|
||||
let n = rng.below(4);
|
||||
for _ in 0..n {
|
||||
args.push(rng.pick(BLOB_SAFE_FLAGS).to_string());
|
||||
}
|
||||
}
|
||||
Kind::Tree | Kind::Bogus => {
|
||||
if rng.chance(1, 2) {
|
||||
args.push(rng.pick(BLOB_SAFE_FLAGS).to_string());
|
||||
}
|
||||
}
|
||||
Kind::ClusterLargeUtf8 | Kind::ClusterLatin1 => {
|
||||
// A colon-carrying short-flag cluster the walker skips, then the blob.
|
||||
// Optionally sprinkle blob-safe flags around it — they must not change the
|
||||
// outcome. This is the exact cross that was NEVER generated before (the old
|
||||
// fuzzer only paired these clusters with a blob-less HEAD), so the blocker hid.
|
||||
if rng.chance(1, 2) {
|
||||
args.push(rng.pick(BLOB_SAFE_FLAGS).to_string());
|
||||
}
|
||||
let (flag, val) = *rng.pick(WINDOWING_CLUSTER_FLAGS);
|
||||
args.push(flag.to_string());
|
||||
args.push(val.to_string());
|
||||
}
|
||||
Kind::TextconvLargeUtf8 => {
|
||||
args.push("--textconv".to_string());
|
||||
}
|
||||
Kind::PathspecLargeUtf8 => {} // trailing `-- <path>` appended after the object
|
||||
}
|
||||
args.push(kind_object(kind).to_string());
|
||||
if let Kind::PathspecLargeUtf8 = kind {
|
||||
args.push("--".to_string());
|
||||
args.push("large.txt".to_string());
|
||||
}
|
||||
args
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn git_show_blob_classification_differential() {
|
||||
let repo = setup_repo();
|
||||
let (path, home) = (repo.path.as_path(), repo.home.as_path());
|
||||
|
||||
// Sanity-check the fixtures against ground truth before fuzzing.
|
||||
assert_eq!(
|
||||
cat_file_type(path, home, "HEAD:large.txt").as_deref(),
|
||||
Some("blob")
|
||||
);
|
||||
assert_eq!(
|
||||
cat_file_type(path, home, "HEAD:dir").as_deref(),
|
||||
Some("tree")
|
||||
);
|
||||
assert_eq!(cat_file_type(path, home, "HEAD").as_deref(), Some("commit"));
|
||||
assert_eq!(cat_file_type(path, home, "HEAD:does-not-exist.txt"), None);
|
||||
|
||||
let kinds = [
|
||||
Kind::LargeUtf8,
|
||||
Kind::Small,
|
||||
Kind::Latin1,
|
||||
Kind::Utf16,
|
||||
Kind::Tree,
|
||||
Kind::CommitMisroute,
|
||||
Kind::Bogus,
|
||||
Kind::ClusterLargeUtf8,
|
||||
Kind::ClusterLatin1,
|
||||
Kind::TextconvLargeUtf8,
|
||||
Kind::PathspecLargeUtf8,
|
||||
];
|
||||
|
||||
let mut rng = Rng(SEED);
|
||||
// Collect failures instead of panicking mid-loop, so the incidence is measured
|
||||
// across ALL invocations (KuSh: a measured incidence is what proves no class hides).
|
||||
let mut misroutes: Vec<String> = Vec::new();
|
||||
let mut silent_losses: Vec<String> = Vec::new();
|
||||
let mut fidelity_breaks: Vec<String> = Vec::new();
|
||||
|
||||
for _ in 0..ITERATIONS {
|
||||
let kind = *rng.pick(&kinds);
|
||||
let args = build_invocation(&mut rng, kind);
|
||||
let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
|
||||
let object = kind_object(kind);
|
||||
let truth = cat_file_type(path, home, object); // ground truth for the object
|
||||
let out = rtk_show(path, home, &arg_refs);
|
||||
let windowed = was_windowed(&out);
|
||||
|
||||
// 0 misroutes: rtk must never window anything git does not call a `blob`. The
|
||||
// only blob among our objects is the one the invocation targets, so a window
|
||||
// implies the targeted object is that blob (and truly a blob per cat-file).
|
||||
if windowed && truth.as_deref() != Some("blob") {
|
||||
misroutes.push(format!(
|
||||
"windowed a non-blob (type {truth:?}) for `git show {}`",
|
||||
args.join(" ")
|
||||
));
|
||||
}
|
||||
|
||||
match kind {
|
||||
// 0 silent losses: a large, recoverable UTF-8 blob must ALWAYS window.
|
||||
Kind::LargeUtf8 => {
|
||||
if !windowed {
|
||||
silent_losses.push(format!(
|
||||
"large UTF-8 blob not windowed for `git show {}`",
|
||||
args.join(" ")
|
||||
));
|
||||
} else {
|
||||
assert!(out.status.success(), "windowed blob show should exit 0");
|
||||
}
|
||||
}
|
||||
// Blobs rtk declines to window must be byte-identical to plain `git show`.
|
||||
Kind::Small | Kind::Latin1 | Kind::Utf16 => {
|
||||
assert!(
|
||||
!windowed,
|
||||
"small/latin1/utf16 blobs must not window: {args:?}"
|
||||
);
|
||||
let plain = git(path, home, &["show", object]);
|
||||
if out.stdout != plain.stdout {
|
||||
fidelity_breaks.push(format!(
|
||||
"`git show {}` differs from git (rtk {} vs git {} bytes)",
|
||||
args.join(" "),
|
||||
out.stdout.len(),
|
||||
plain.stdout.len()
|
||||
));
|
||||
}
|
||||
}
|
||||
// Trees, commit-misroutes and bogus objects must never window.
|
||||
Kind::Tree | Kind::CommitMisroute | Kind::Bogus => {
|
||||
assert!(!windowed, "non-blob must not window: {args:?}");
|
||||
}
|
||||
// BLOCKER: a colon-cluster before a large UTF-8 blob must STILL window — git
|
||||
// dumps only the blob, so failing to window is a silent savings loss. (Old
|
||||
// code misrouted this to the commit-diff path: not windowed → this fails.)
|
||||
Kind::ClusterLargeUtf8 => {
|
||||
if !windowed {
|
||||
silent_losses.push(format!(
|
||||
"cluster + large UTF-8 blob not windowed for `git show {}`",
|
||||
args.join(" ")
|
||||
));
|
||||
} else {
|
||||
assert!(out.status.success(), "windowed blob show should exit 0");
|
||||
}
|
||||
}
|
||||
// BLOCKER: a colon-cluster before a Latin-1 blob must pass through
|
||||
// byte-identically to git — the old misroute lossily decoded it to U+FFFD
|
||||
// mojibake (not byte-identical → this fails on old code).
|
||||
Kind::ClusterLatin1 => {
|
||||
assert!(!windowed, "latin-1 blob must never window: {args:?}");
|
||||
// Compare against git run with the SAME args, not just `git show object`:
|
||||
// the strongest invariant is "rtk == git for this exact command".
|
||||
let mut full: Vec<&str> = vec!["show"];
|
||||
full.extend(arg_refs.iter().copied());
|
||||
let plain = git(path, home, &full);
|
||||
if out.stdout != plain.stdout {
|
||||
fidelity_breaks.push(format!(
|
||||
"cluster + latin1 `git show {}` differs from git (rtk {} vs git {} bytes)",
|
||||
args.join(" "),
|
||||
out.stdout.len(),
|
||||
plain.stdout.len()
|
||||
));
|
||||
}
|
||||
}
|
||||
// MINOR 1/2: a content-transforming flag or a trailing pathspec makes the
|
||||
// recovery hint diverge from git's bytes, so rtk must NOT window; it passes
|
||||
// through byte-identically to git run with the SAME args.
|
||||
Kind::TextconvLargeUtf8 | Kind::PathspecLargeUtf8 => {
|
||||
assert!(
|
||||
!windowed,
|
||||
"transform-flag / trailing-pathspec must not window: {args:?}"
|
||||
);
|
||||
let mut full: Vec<&str> = vec!["show"];
|
||||
full.extend(arg_refs.iter().copied());
|
||||
let plain = git(path, home, &full);
|
||||
if out.stdout != plain.stdout {
|
||||
fidelity_breaks.push(format!(
|
||||
"`git show {}` differs from git (rtk {} vs git {} bytes)",
|
||||
args.join(" "),
|
||||
out.stdout.len(),
|
||||
plain.stdout.len()
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Report incidence (KuSh: the fuzzer establishes there are no other classes hiding).
|
||||
eprintln!(
|
||||
"differential fuzzer: {ITERATIONS} invocations — misroutes={}, silent_losses={}, fidelity_breaks={}",
|
||||
misroutes.len(),
|
||||
silent_losses.len(),
|
||||
fidelity_breaks.len()
|
||||
);
|
||||
assert!(misroutes.is_empty(), "misroutes: {misroutes:#?}");
|
||||
assert!(
|
||||
silent_losses.is_empty(),
|
||||
"silent losses: {silent_losses:#?}"
|
||||
);
|
||||
assert!(
|
||||
fidelity_breaks.is_empty(),
|
||||
"fidelity breaks: {fidelity_breaks:#?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// A companion check that the recovery hint reconstructs a windowed blob BYTE-for-byte:
|
||||
/// `head_shown` ++ `git show <rev:path> | tail -n +N` == full `git show <rev:path>`.
|
||||
#[test]
|
||||
fn windowed_blob_recovery_is_byte_exact() {
|
||||
let repo = setup_repo();
|
||||
let (path, home) = (repo.path.as_path(), repo.home.as_path());
|
||||
|
||||
let out = rtk_show(path, home, &["HEAD:large.txt"]);
|
||||
assert!(out.status.success());
|
||||
let shown = String::from_utf8(out.stdout).expect("windowed head is UTF-8");
|
||||
assert!(
|
||||
shown.contains("[see remaining: git "),
|
||||
"expected a windowed head"
|
||||
);
|
||||
|
||||
// The head is everything before the hint marker.
|
||||
let head = &shown[..shown.find("... (+").expect("truncation marker")];
|
||||
|
||||
// Extract N from `| tail -n +N]`.
|
||||
let n: usize = {
|
||||
let after = shown.split("| tail -n +").nth(1).expect("tail hint");
|
||||
after
|
||||
.trim_end_matches(|c: char| !c.is_ascii_digit())
|
||||
.chars()
|
||||
.take_while(|c| c.is_ascii_digit())
|
||||
.collect::<String>()
|
||||
.parse()
|
||||
.expect("N parses")
|
||||
};
|
||||
|
||||
let full = git(path, home, &["show", "HEAD:large.txt"]).stdout;
|
||||
let full = String::from_utf8(full).expect("blob is UTF-8");
|
||||
// Recovery: the shown head must be a byte-exact prefix, and lines from N onward are
|
||||
// exactly the remainder.
|
||||
assert!(
|
||||
full.starts_with(head),
|
||||
"shown head is not a byte-exact prefix of git's bytes"
|
||||
);
|
||||
let tail: String = full.lines().skip(n - 1).map(|l| format!("{l}\n")).collect();
|
||||
let reconstructed = format!("{head}{tail}");
|
||||
assert_eq!(
|
||||
reconstructed, full,
|
||||
"head + `tail -n +{n}` must reconstruct the blob byte-for-byte"
|
||||
);
|
||||
}
|
||||
|
||||
/// The BLOCKER, end-to-end: `-wG x:y HEAD:large.txt` (a colon-cluster whose value the
|
||||
/// walker skips) must window the real blob, and its hint — which names only the blob
|
||||
/// arg, not the cluster flags — must still reconstruct the blob byte-for-byte.
|
||||
#[test]
|
||||
fn cluster_flag_before_blob_windows_and_recovers_byte_exact() {
|
||||
let repo = setup_repo();
|
||||
let (path, home) = (repo.path.as_path(), repo.home.as_path());
|
||||
|
||||
let out = rtk_show(path, home, &["-wG", "x:y", "HEAD:large.txt"]);
|
||||
assert!(out.status.success());
|
||||
let shown = String::from_utf8(out.stdout).expect("windowed head is UTF-8");
|
||||
assert!(
|
||||
shown.contains("[see remaining: git "),
|
||||
"cluster + blob must still window (blocker regression)"
|
||||
);
|
||||
// The hint points at the blob arg alone — verify it names `HEAD:large.txt`, not the
|
||||
// `x:y` pickaxe value that the old walker mistook for the object.
|
||||
assert!(
|
||||
shown.contains("'HEAD:large.txt'"),
|
||||
"hint must target the real blob arg, not the flag value"
|
||||
);
|
||||
|
||||
let head = &shown[..shown.find("... (+").expect("truncation marker")];
|
||||
let n: usize = {
|
||||
let after = shown.split("| tail -n +").nth(1).expect("tail hint");
|
||||
after
|
||||
.chars()
|
||||
.take_while(|c| c.is_ascii_digit())
|
||||
.collect::<String>()
|
||||
.parse()
|
||||
.expect("N parses")
|
||||
};
|
||||
// git dumps ONLY the blob for this invocation (the colon token is `-G`'s value), so
|
||||
// the recovery target is a plain `git show HEAD:large.txt`.
|
||||
let full = String::from_utf8(git(path, home, &["show", "HEAD:large.txt"]).stdout)
|
||||
.expect("blob is UTF-8");
|
||||
assert!(
|
||||
full.starts_with(head),
|
||||
"shown head is not a byte-exact prefix of git's bytes"
|
||||
);
|
||||
let tail: String = full.lines().skip(n - 1).map(|l| format!("{l}\n")).collect();
|
||||
assert_eq!(
|
||||
format!("{head}{tail}"),
|
||||
full,
|
||||
"head + `tail -n +{n}` must reconstruct the blob byte-for-byte"
|
||||
);
|
||||
}
|
||||
@@ -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}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user