Compare commits
42
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8a7106c8f2 | ||
|
|
76f3b24074 | ||
|
|
057f3a2361 | ||
|
|
d92c5d264a | ||
|
|
12e57e870f | ||
|
|
d813919a24 | ||
|
|
33185101fc | ||
|
|
a919335519 | ||
|
|
d85fe3384b | ||
|
|
9c1cf2f403 | ||
|
|
13004e8b63 | ||
|
|
2425ad68e5 | ||
|
|
8465ca953f | ||
|
|
1177c9c873 | ||
|
|
7571c8e101 | ||
|
|
62f4452276 | ||
|
|
1481bc5909 | ||
|
|
7dbef2ce00 | ||
|
|
374fe64cfb | ||
|
|
09b3ff9424 | ||
|
|
d44fd3e034 | ||
|
|
7217562355 | ||
|
|
e918661440 | ||
|
|
46b923f066 | ||
|
|
3f58018f4a | ||
|
|
9cf9ccc1ac | ||
|
|
eefeae4565 | ||
|
|
deda44f736 | ||
|
|
158c74527f | ||
|
|
d9ef47f998 | ||
|
|
402c48e669 | ||
|
|
41a6c6bf6d | ||
|
|
e1f2845df0 | ||
|
|
09979cf297 | ||
|
|
d16fc6dacb | ||
|
|
45d8dcaf3d | ||
|
|
e51be7a022 | ||
|
|
bff0258424 | ||
|
|
d1b37ced01 | ||
|
|
b812a0e924 | ||
|
|
51939a50de | ||
|
|
927daef49b |
No files matched your search
@@ -52,7 +52,7 @@ PRs target the **`develop`** branch, not `main`. All commits require a DCO sign-
|
||||
|
||||
rtk routes CLI commands via a Clap `Commands` enum in `main.rs` to specialized filter modules in `src/cmds/*/`, each executing the underlying command and compressing output. Token savings are tracked in SQLite via `src/core/tracking.rs`.
|
||||
|
||||
For full details see [ARCHITECTURE.md](../ARCHITECTURE.md) and [docs/TECHNICAL.md](../docs/TECHNICAL.md). Module responsibilities are documented in each folder's `README.md` and each file's `//!` doc header.
|
||||
For full details see [ARCHITECTURE.md](../docs/contributing/ARCHITECTURE.md) and [docs/contributing/TECHNICAL.md](../docs/contributing/TECHNICAL.md). Module responsibilities are documented in each folder's `README.md` and each file's `//!` doc header.
|
||||
|
||||
## Key Conventions
|
||||
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "0.34.1"
|
||||
".": "0.35.0"
|
||||
}
|
||||
@@ -5,6 +5,85 @@ 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).
|
||||
|
||||
## [0.35.0](https://github.com/rtk-ai/rtk/compare/v0.34.3...v0.35.0) (2026-04-06)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* **aws:** expand CLI filters from 8 to 25 subcommands ([402c48e](https://github.com/rtk-ai/rtk/commit/402c48e66988e638a5b4f4dd193238fc1d0fe18f))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **cmd:** read/cat multiple file and consistent behavior ([3f58018](https://github.com/rtk-ai/rtk/commit/3f58018f4af1d7206457929cf80bb4534203c3ee))
|
||||
* **docs:** clean some docs + disclaimer ([deda44f](https://github.com/rtk-ai/rtk/commit/deda44f73607981f3d27ecc6341ce927aab34d37))
|
||||
* **gh:** pass through gh pr merge instead of canned response ([#938](https://github.com/rtk-ai/rtk/issues/938)) ([8465ca9](https://github.com/rtk-ai/rtk/commit/8465ca953fa9d70dcc971a941c19465d456eb7d4))
|
||||
* **gh:** pass through gh pr merge instead of canned response ([#938](https://github.com/rtk-ai/rtk/issues/938)) ([e1f2845](https://github.com/rtk-ai/rtk/commit/e1f2845df06a8d8b8325945dc4940ec5f530e4cc))
|
||||
* **git:** inherit stdin for commit and push to preserve SSH signing ([#733](https://github.com/rtk-ai/rtk/issues/733)) ([eefeae4](https://github.com/rtk-ai/rtk/commit/eefeae45656ff2607c3f519c8eae235e3f0fe411))
|
||||
* **git:** inherit stdin for commit and push to preserve SSH signing ([#733](https://github.com/rtk-ai/rtk/issues/733)) ([6cee6c6](https://github.com/rtk-ai/rtk/commit/6cee6c60b80f914ed9505e3925d85cadec43ab97))
|
||||
* **git:** preserve full diff hunk headers ([62f4452](https://github.com/rtk-ai/rtk/commit/62f445227679f3df293fe35e9b18cc5ab39d7963))
|
||||
* **git:** preserve full diff hunk headers ([09b3ff9](https://github.com/rtk-ai/rtk/commit/09b3ff9424e055f5fe25e535e5b60e077f8344f9))
|
||||
* **go:** avoid false build errors from download logs ([9c1cf2f](https://github.com/rtk-ai/rtk/commit/9c1cf2f403534fa7874638b1b983c2d7f918a185))
|
||||
* **go:** avoid false build errors from download logs ([d44fd3e](https://github.com/rtk-ai/rtk/commit/d44fd3e034208e3bcd59c2c46f7720eec4f10c98))
|
||||
* **go:** cover more build failure shapes ([2425ad6](https://github.com/rtk-ai/rtk/commit/2425ad68e5386d19e5ec9ff1ca151a6d2c9a56d3))
|
||||
* **go:** preserve failing test location context ([1481bc5](https://github.com/rtk-ai/rtk/commit/1481bc590924031456a6022510275c29c09e330e))
|
||||
* **go:** preserve failing test location context ([374fe64](https://github.com/rtk-ai/rtk/commit/374fe64cfbedcd676733973e81a63a6dfecbb1b7))
|
||||
* **go:** restore build error coverage ([1177c9c](https://github.com/rtk-ai/rtk/commit/1177c9c873ac63b6c0bcc9e1b664a705baa0ad7a))
|
||||
* **grep:** close subprocess stdin to prevent memory leak ([#897](https://github.com/rtk-ai/rtk/issues/897)) ([7217562](https://github.com/rtk-ai/rtk/commit/72175623551f40b581b4a7f6ed966c1e4a9c7358))
|
||||
* **grep:** close subprocess stdin to prevent memory leak ([#897](https://github.com/rtk-ai/rtk/issues/897)) ([09979cf](https://github.com/rtk-ai/rtk/commit/09979cf29701a1b775bcac761d24ec0e055d1bec))
|
||||
* **hook_check:** detect missing integrations ([9cf9ccc](https://github.com/rtk-ai/rtk/commit/9cf9ccc1ac39f8bba37e932c7d318a3aa7a34ae9))
|
||||
* **init:** remove opt-out instruction from telemetry message ([7571c8e](https://github.com/rtk-ai/rtk/commit/7571c8e101c41ee64c51e2bd64697f85f9142423))
|
||||
* **init:** remove telemetry info lines from init output ([7dbef2c](https://github.com/rtk-ai/rtk/commit/7dbef2ce00824d26f2057e4c3c76e429e2e23088))
|
||||
* **main:** kill zombie processes + path for rtk md ([d16fc6d](https://github.com/rtk-ai/rtk/commit/d16fc6dacbfec912c21522939b15b7bbd9719487))
|
||||
* **main:** kill zombie processes + path for rtk md + missing intergrations ([a919335](https://github.com/rtk-ai/rtk/commit/a919335519ed4a5259a212e56407cb312aa99bac))
|
||||
* **merge:** changelog conflicts ([d92c5d2](https://github.com/rtk-ai/rtk/commit/d92c5d264a49483c8d6079e04d946a79bc990a74))
|
||||
* **proxy:** kill child process on SIGINT/SIGTERM to prevent orphans ([d813919](https://github.com/rtk-ai/rtk/commit/d813919a24546e044e7844fc7ed05fef4ec24033))
|
||||
* **proxy:** kill child process on SIGINT/SIGTERM to prevent orphans ([3318510](https://github.com/rtk-ai/rtk/commit/33185101fc122d0c11a25a4e02ac9f3a7dc7e3bb))
|
||||
* **review:** address ChildGuard disarm, stdin dedup, hook masking ([d85fe33](https://github.com/rtk-ai/rtk/commit/d85fe3384b87c16fafd25ec7bcadbff6e69f3f1f))
|
||||
* **security:** default to ask when no permission rule matches ([#886](https://github.com/rtk-ai/rtk/issues/886)) ([158c745](https://github.com/rtk-ai/rtk/commit/158c74527f6591d372e40a78cd604d73a20649a9))
|
||||
* **security:** default to ask when no permission rule matches ([#886](https://github.com/rtk-ai/rtk/issues/886)) ([41a6c6b](https://github.com/rtk-ai/rtk/commit/41a6c6bf6da78a4754794fdc6a1469df2e327920))
|
||||
* **tracking:** use std::env::temp_dir() for compatibility (instead of unix tmp) ([e918661](https://github.com/rtk-ai/rtk/commit/e918661440d7b50321f0535032f52c5e87aaf3cb))
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Features
|
||||
|
||||
* **aws:** expand CLI filters from 8 to 25 subcommands — CloudWatch Logs, CloudFormation events, Lambda, IAM, DynamoDB (with type unwrapping), ECS tasks, EC2 security groups, S3API objects, S3 sync/cp, EKS, SQS, Secrets Manager ([#885](https://github.com/rtk-ai/rtk/pull/885))
|
||||
* **aws:** add shared runner `run_aws_filtered()` eliminating per-handler boilerplate
|
||||
* **tee:** add `force_tee_hint()` — truncated output saves full data to file with recovery hint
|
||||
|
||||
## [0.34.3](https://github.com/rtk-ai/rtk/compare/v0.34.2...v0.34.3) (2026-04-02)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **automod:** add auto discovery for cmds ([234909d](https://github.com/rtk-ai/rtk/commit/234909d2c754ade2fdc939b0a1435a8e34ffc305))
|
||||
* **ci:** fix validate-docs.sh broken module count check ([bbe3da6](https://github.com/rtk-ai/rtk/commit/bbe3da642b5fc4b065b13a65647ea0ebf5264e65))
|
||||
* **cleaning:** constant extract ([aabc016](https://github.com/rtk-ai/rtk/commit/aabc0167bc013fd2d0c61a687580f6e69305500a))
|
||||
* **cmds:** migrate remaining exit_code to exit_code_from_output ([ba9fa34](https://github.com/rtk-ai/rtk/commit/ba9fa345f3d1d14bd0af236ec9aa8a9a0e5581d6))
|
||||
* **cmds:** more covering for run_filtered ([e48485a](https://github.com/rtk-ai/rtk/commit/e48485adc6a33d12b70664598020595cf7dfcd7e))
|
||||
* **docs:** add documentation ([2f7278a](https://github.com/rtk-ai/rtk/commit/2f7278ac5992bf2e84b763fb05642d89900ba495))
|
||||
* **docs:** add maintainers docs ([14265b4](https://github.com/rtk-ai/rtk/commit/14265b48c3a15e459a31da11250a51ab5830a508))
|
||||
* **refacto-p1:** unified cmds execution flow (+ rm dead code) ([75bd607](https://github.com/rtk-ai/rtk/commit/75bd607d55235f313855f5fe8c9eceafd73700a7))
|
||||
* **refacto-p2:** more standardize ([47a76ea](https://github.com/rtk-ai/rtk/commit/47a76ea35ed2fe02a3600792163f727fa3a94ff2))
|
||||
* **refacto-p2:** more standardize ([92c671a](https://github.com/rtk-ai/rtk/commit/92c671a175a5e2bf09720fd1a8591140bcb473a0))
|
||||
* **refacto:** wrappers for standardization, exit codes lexer tokenizer, constants, code clean ([bff0258](https://github.com/rtk-ai/rtk/commit/bff02584243f1b73418418b0c05365acf56fbb36))
|
||||
* **registry:** quoted env prefix + inline regex cleanup + routing docs ([f3217a4](https://github.com/rtk-ai/rtk/commit/f3217a467b543a3181605b257162f2b3ab5d5df0))
|
||||
* **review:** address PR [#910](https://github.com/rtk-ai/rtk/issues/910) review feedback ([0a8b8fd](https://github.com/rtk-ai/rtk/commit/0a8b8fd0693fa504f376146cbbcafe9ddf4632c8))
|
||||
* **review:** PR [#934](https://github.com/rtk-ai/rtk/issues/934) ([5bd35a3](https://github.com/rtk-ai/rtk/commit/5bd35a33ad6abe5278749726bed19912664531c2))
|
||||
* **review:** PR [#934](https://github.com/rtk-ai/rtk/issues/934) ([bae7930](https://github.com/rtk-ai/rtk/commit/bae79301194bbb48d1cbb39554096c3225f7cb73))
|
||||
* **rules:** add wc RtkRule with pattern field for develop compat ([d75e864](https://github.com/rtk-ai/rtk/commit/d75e864f20451a5e17918c75f2ea32672f65e1f4))
|
||||
* **standardize:** git+kube sub wrappers run_filtered ([7fd221f](https://github.com/rtk-ai/rtk/commit/7fd221f44660bcf411aa333d2c35a49ff89e7961))
|
||||
* **standardize:** merge pattern into rues ([08aabb9](https://github.com/rtk-ai/rtk/commit/08aabb95c3ae6e0b734f696264e1e1a8c0f0b22e))
|
||||
|
||||
## [0.34.2](https://github.com/rtk-ai/rtk/compare/v0.34.1...v0.34.2) (2026-03-30)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* **emots:** replace 📊 with "Summary:" ([495a152](https://github.com/rtk-ai/rtk/commit/495a152059feabc7b516b96e804757608b87a10a))
|
||||
* **refacto-codebase:** technical docs & sub folders ([927daef](https://github.com/rtk-ai/rtk/commit/927daef49b8f771d195201d196378e27e0ee8a2b))
|
||||
|
||||
## [0.34.1](https://github.com/rtk-ai/rtk/compare/v0.34.0...v0.34.1) (2026-03-28)
|
||||
|
||||
|
||||
|
||||
@@ -70,8 +70,8 @@ cargo generate-rpm # RPM package (needs cargo-generate-rpm, after rel
|
||||
rtk uses a **command proxy architecture**: `main.rs` routes CLI commands via a Clap `Commands` enum to specialized filter modules in `src/cmds/*/`, each of which executes the underlying command and compresses its output. Token savings are tracked in SQLite via `src/core/tracking.rs`.
|
||||
|
||||
For the full architecture, component details, and module development patterns, see:
|
||||
- [ARCHITECTURE.md](ARCHITECTURE.md) — System design, module organization, filtering strategies, error handling
|
||||
- [docs/TECHNICAL.md](docs/TECHNICAL.md) — End-to-end flow, folder map, hook system, filter pipeline
|
||||
- [ARCHITECTURE.md](docs/contributing/ARCHITECTURE.md) — System design, module organization, filtering strategies, error handling
|
||||
- [docs/contributing/TECHNICAL.md](docs/contributing/TECHNICAL.md) — End-to-end flow, folder map, hook system, filter pipeline
|
||||
|
||||
Module responsibilities are documented in each folder's `README.md` and each file's `//!` doc header. Browse `src/cmds/*/` to discover available filters.
|
||||
|
||||
|
||||
+5
-5
@@ -7,7 +7,7 @@
|
||||
- [Report an Issue](../../issues/new)
|
||||
- [Open Pull Requests](../../pulls)
|
||||
- [Start a Discussion](../../discussions)
|
||||
- [Technical Documentation](docs/TECHNICAL.md) — Architecture, end-to-end flow, folder map, how to write tests
|
||||
- [Technical Documentation](docs/contributing/TECHNICAL.md) — Architecture, end-to-end flow, folder map, how to write tests
|
||||
|
||||
---
|
||||
|
||||
@@ -203,7 +203,7 @@ your branch --> develop (review + CI + integration testing) --> version branch -
|
||||
|
||||
Every change **must** include tests. We follow **TDD (Red-Green-Refactor)**: write a failing test first, implement the minimum to pass, then refactor.
|
||||
|
||||
For how to write tests (fixtures, snapshots, token savings verification), see [docs/TECHNICAL.md — Testing](docs/TECHNICAL.md#testing).
|
||||
For how to write tests (fixtures, snapshots, token savings verification), see [docs/contributing/TECHNICAL.md — Testing](docs/contributing/TECHNICAL.md#testing).
|
||||
|
||||
### Test Types
|
||||
|
||||
@@ -242,12 +242,12 @@ Every change **must** include documentation updates. Use this table to find whic
|
||||
| New Rust filter (`src/cmds/`) | Ecosystem `README.md` (e.g., `src/cmds/git/README.md`), [README.md](README.md) command list, [CHANGELOG.md](CHANGELOG.md) |
|
||||
| New TOML filter (`src/filters/`) | [src/filters/README.md](src/filters/README.md) if naming conventions change, [README.md](README.md) command list, [CHANGELOG.md](CHANGELOG.md) |
|
||||
| New rewrite pattern | `src/discover/rules.rs` — see [Adding a New Command Filter](src/cmds/README.md#adding-a-new-command-filter) |
|
||||
| Core infrastructure (`src/core/`) | [src/core/README.md](src/core/README.md), [docs/TECHNICAL.md](docs/TECHNICAL.md) if flow changes |
|
||||
| Core infrastructure (`src/core/`) | [src/core/README.md](src/core/README.md), [docs/contributing/TECHNICAL.md](docs/contributing/TECHNICAL.md) if flow changes |
|
||||
| Hook system (`src/hooks/`) | [src/hooks/README.md](src/hooks/README.md), [hooks/README.md](hooks/README.md) for agent-facing docs |
|
||||
| Architecture or design change | [ARCHITECTURE.md](ARCHITECTURE.md), [docs/TECHNICAL.md](docs/TECHNICAL.md) |
|
||||
| Architecture or design change | [ARCHITECTURE.md](docs/contributing/ARCHITECTURE.md), [docs/contributing/TECHNICAL.md](docs/contributing/TECHNICAL.md) |
|
||||
| Bug fix or breaking change | [CHANGELOG.md](CHANGELOG.md) |
|
||||
|
||||
**Navigation**: [CONTRIBUTING.md](CONTRIBUTING.md) (you are here) → [docs/TECHNICAL.md](docs/TECHNICAL.md) (architecture + flow) → each folder's `README.md` (implementation details).
|
||||
**Navigation**: [CONTRIBUTING.md](CONTRIBUTING.md) (you are here) → [docs/contributing/TECHNICAL.md](docs/contributing/TECHNICAL.md) (architecture + flow) → each folder's `README.md` (implementation details).
|
||||
|
||||
Keep documentation concise and practical -- examples over explanations.
|
||||
|
||||
|
||||
Generated
+2
-1
@@ -903,7 +903,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rtk"
|
||||
version = "0.34.1"
|
||||
version = "0.35.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"automod",
|
||||
@@ -916,6 +916,7 @@ dependencies = [
|
||||
"hostname",
|
||||
"ignore",
|
||||
"lazy_static",
|
||||
"libc",
|
||||
"quick-xml",
|
||||
"regex",
|
||||
"rusqlite",
|
||||
|
||||
+4
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "rtk"
|
||||
version = "0.34.1"
|
||||
version = "0.35.0"
|
||||
edition = "2021"
|
||||
authors = ["Patrick Szymkowiak"]
|
||||
description = "Rust Token Killer - High-performance CLI proxy to minimize LLM token consumption"
|
||||
@@ -35,6 +35,9 @@ quick-xml = "0.37"
|
||||
which = "8"
|
||||
automod = "1"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[build-dependencies]
|
||||
toml = "0.8"
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# Disclaimer
|
||||
|
||||
## No Warranty
|
||||
|
||||
This software is provided "AS IS", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose, and non-infringement. The entire risk as to the quality and performance of the software is with you.
|
||||
|
||||
## Limitation of Liability
|
||||
|
||||
In no event shall the authors or copyright holders be liable for any claim, damages, or other liability, whether in an action of contract, tort, or otherwise, arising from, out of, or in connection with the software or the use or other dealings in the software. This includes, without limitation, any direct, indirect, incidental, special, exemplary, or consequential damages (including but not limited to loss of data, loss of profits, or business interruption).
|
||||
|
||||
## Precompiled Binaries
|
||||
|
||||
Precompiled binaries are provided solely for convenience and are covered by the same license as the source code (Apache License 2.0). They are provided without warranties or conditions of any kind. You are responsible for verifying the integrity and suitability of any binary before use. Always verify checksums when available.
|
||||
|
||||
## Third-Party Dependencies
|
||||
|
||||
This software incorporates third-party open-source components, each governed by their respective licenses. The authors make no representations or warranties regarding these dependencies and accept no liability for any issues arising from their use.
|
||||
|
||||
## Use at Your Own Risk
|
||||
|
||||
This software interacts with your development environment, file system, and external commands. It is your responsibility to ensure that its use is appropriate for your environment and complies with any applicable policies, regulations, or agreements. The authors are not responsible for any unintended side effects resulting from its use.
|
||||
|
||||
## Telemetry
|
||||
|
||||
This software collects anonymous, aggregate usage metrics by default and can be disabled at any time. No personally identifiable information, source code, file paths, command arguments, or secrets are collected. See the README for full details and opt-out instructions.
|
||||
|
||||
---
|
||||
|
||||
See [LICENSE](LICENSE) for the full terms of the Apache License 2.0 under which this software is distributed.
|
||||
@@ -18,7 +18,7 @@
|
||||
<a href="https://www.rtk-ai.app">Website</a> •
|
||||
<a href="#installation">Install</a> •
|
||||
<a href="docs/TROUBLESHOOTING.md">Troubleshooting</a> •
|
||||
<a href="ARCHITECTURE.md">Architecture</a> •
|
||||
<a href="docs/contributing/ARCHITECTURE.md">Architecture</a> •
|
||||
<a href="https://discord.gg/RySmvNF5kF">Discord</a>
|
||||
</p>
|
||||
|
||||
@@ -201,6 +201,18 @@ rtk bundle install # Ruby gems (strip Using lines)
|
||||
rtk prisma generate # Schema generation (no ASCII art)
|
||||
```
|
||||
|
||||
### AWS
|
||||
```bash
|
||||
rtk aws sts get-caller-identity # One-line identity
|
||||
rtk aws ec2 describe-instances # Compact instance list
|
||||
rtk aws lambda list-functions # Name/runtime/memory (strips secrets)
|
||||
rtk aws logs get-log-events # Timestamped messages only
|
||||
rtk aws cloudformation describe-stack-events # Failures first
|
||||
rtk aws dynamodb scan # Unwraps type annotations
|
||||
rtk aws iam list-roles # Strips policy documents
|
||||
rtk aws s3 ls # Truncated with tee recovery
|
||||
```
|
||||
|
||||
### Containers
|
||||
```bash
|
||||
rtk docker ps # Compact container list
|
||||
@@ -419,6 +431,7 @@ Blocked on upstream BeforeToolCallback support ([mistral-vibe#531](https://githu
|
||||
| `rspec` / `bundle exec rspec` | `rtk rspec` |
|
||||
| `rubocop` / `bundle exec rubocop` | `rtk rubocop` |
|
||||
| `bundle install/update` | `rtk bundle ...` |
|
||||
| `aws sts/ec2/lambda/...` | `rtk aws ...` |
|
||||
| `docker ps/images/logs` | `rtk docker ...` |
|
||||
| `kubectl get/logs` | `rtk kubectl ...` |
|
||||
| `curl` | `rtk curl` |
|
||||
@@ -466,7 +479,7 @@ brew uninstall rtk # If installed via Homebrew
|
||||
|
||||
- **[TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md)** - Fix common issues
|
||||
- **[INSTALL.md](INSTALL.md)** - Detailed installation guide
|
||||
- **[ARCHITECTURE.md](ARCHITECTURE.md)** - Technical architecture
|
||||
- **[ARCHITECTURE.md](docs/contributing/ARCHITECTURE.md)** - Technical architecture
|
||||
- **[SECURITY.md](SECURITY.md)** - Security policy and PR review process
|
||||
- **[AUDIT_GUIDE.md](docs/AUDIT_GUIDE.md)** - Token savings analytics guide
|
||||
|
||||
@@ -501,3 +514,7 @@ Join the community on [Discord](https://discord.gg/RySmvNF5kF).
|
||||
## License
|
||||
|
||||
MIT License - see [LICENSE](LICENSE) for details.
|
||||
|
||||
## Disclaimer
|
||||
|
||||
See [DISCLAIMER.md](DISCLAIMER.md).
|
||||
+6
-2
@@ -18,7 +18,7 @@
|
||||
<a href="https://www.rtk-ai.app">Sitio web</a> •
|
||||
<a href="#instalacion">Instalar</a> •
|
||||
<a href="docs/TROUBLESHOOTING.md">Solucion de problemas</a> •
|
||||
<a href="ARCHITECTURE.md">Arquitectura</a> •
|
||||
<a href="docs/contributing/ARCHITECTURE.md">Arquitectura</a> •
|
||||
<a href="https://discord.gg/RySmvNF5kF">Discord</a>
|
||||
</p>
|
||||
|
||||
@@ -146,7 +146,7 @@ rtk discover # Descubrir ahorros perdidos
|
||||
|
||||
- **[TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md)** - Resolver problemas comunes
|
||||
- **[INSTALL.md](INSTALL.md)** - Guia de instalacion detallada
|
||||
- **[ARCHITECTURE.md](ARCHITECTURE.md)** - Arquitectura tecnica
|
||||
- **[ARCHITECTURE.md](docs/contributing/ARCHITECTURE.md)** - Arquitectura tecnica
|
||||
|
||||
## Contribuir
|
||||
|
||||
@@ -157,3 +157,7 @@ Unete a la comunidad en [Discord](https://discord.gg/RySmvNF5kF).
|
||||
## Licencia
|
||||
|
||||
Licencia MIT - ver [LICENSE](LICENSE) para detalles.
|
||||
|
||||
## Descargo de responsabilidad
|
||||
|
||||
Ver [DISCLAIMER.md](DISCLAIMER.md).
|
||||
+6
-2
@@ -18,7 +18,7 @@
|
||||
<a href="https://www.rtk-ai.app">Site web</a> •
|
||||
<a href="#installation">Installer</a> •
|
||||
<a href="docs/TROUBLESHOOTING.md">Depannage</a> •
|
||||
<a href="ARCHITECTURE.md">Architecture</a> •
|
||||
<a href="docs/contributing/ARCHITECTURE.md">Architecture</a> •
|
||||
<a href="https://discord.gg/RySmvNF5kF">Discord</a>
|
||||
</p>
|
||||
|
||||
@@ -184,7 +184,7 @@ mode = "failures"
|
||||
|
||||
- **[TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md)** - Resoudre les problemes courants
|
||||
- **[INSTALL.md](INSTALL.md)** - Guide d'installation detaille
|
||||
- **[ARCHITECTURE.md](ARCHITECTURE.md)** - Architecture technique
|
||||
- **[ARCHITECTURE.md](docs/contributing/ARCHITECTURE.md)** - Architecture technique
|
||||
|
||||
## Contribuer
|
||||
|
||||
@@ -195,3 +195,7 @@ Rejoignez la communaute sur [Discord](https://discord.gg/RySmvNF5kF).
|
||||
## Licence
|
||||
|
||||
Licence MIT - voir [LICENSE](LICENSE) pour les details.
|
||||
|
||||
## Avertissement
|
||||
|
||||
Voir [DISCLAIMER.md](DISCLAIMER.md).
|
||||
+6
-2
@@ -18,7 +18,7 @@
|
||||
<a href="https://www.rtk-ai.app">ウェブサイト</a> •
|
||||
<a href="#インストール">インストール</a> •
|
||||
<a href="docs/TROUBLESHOOTING.md">トラブルシューティング</a> •
|
||||
<a href="ARCHITECTURE.md">アーキテクチャ</a> •
|
||||
<a href="docs/contributing/ARCHITECTURE.md">アーキテクチャ</a> •
|
||||
<a href="https://discord.gg/RySmvNF5kF">Discord</a>
|
||||
</p>
|
||||
|
||||
@@ -146,7 +146,7 @@ rtk discover # 見逃した節約機会を発見
|
||||
|
||||
- **[TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md)** - よくある問題の解決
|
||||
- **[INSTALL.md](INSTALL.md)** - 詳細インストールガイド
|
||||
- **[ARCHITECTURE.md](ARCHITECTURE.md)** - 技術アーキテクチャ
|
||||
- **[ARCHITECTURE.md](docs/contributing/ARCHITECTURE.md)** - 技術アーキテクチャ
|
||||
|
||||
## コントリビュート
|
||||
|
||||
@@ -157,3 +157,7 @@ rtk discover # 見逃した節約機会を発見
|
||||
## ライセンス
|
||||
|
||||
MIT ライセンス - 詳細は [LICENSE](LICENSE) を参照。
|
||||
|
||||
## 免責事項
|
||||
|
||||
詳細は [DISCLAIMER.md](DISCLAIMER.md) を参照。
|
||||
+6
-2
@@ -18,7 +18,7 @@
|
||||
<a href="https://www.rtk-ai.app">웹사이트</a> •
|
||||
<a href="#설치">설치</a> •
|
||||
<a href="docs/TROUBLESHOOTING.md">문제 해결</a> •
|
||||
<a href="ARCHITECTURE.md">아키텍처</a> •
|
||||
<a href="docs/contributing/ARCHITECTURE.md">아키텍처</a> •
|
||||
<a href="https://discord.gg/RySmvNF5kF">Discord</a>
|
||||
</p>
|
||||
|
||||
@@ -146,7 +146,7 @@ rtk discover # 놓친 절약 기회 발견
|
||||
|
||||
- **[TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md)** - 일반적인 문제 해결
|
||||
- **[INSTALL.md](INSTALL.md)** - 상세 설치 가이드
|
||||
- **[ARCHITECTURE.md](ARCHITECTURE.md)** - 기술 아키텍처
|
||||
- **[ARCHITECTURE.md](docs/contributing/ARCHITECTURE.md)** - 기술 아키텍처
|
||||
|
||||
## 기여
|
||||
|
||||
@@ -157,3 +157,7 @@ rtk discover # 놓친 절약 기회 발견
|
||||
## 라이선스
|
||||
|
||||
MIT 라이선스 - 자세한 내용은 [LICENSE](LICENSE)를 참조하세요.
|
||||
|
||||
## 면책 조항
|
||||
|
||||
자세한 내용은 [DISCLAIMER.md](DISCLAIMER.md)를 참조하세요.
|
||||
+6
-2
@@ -18,7 +18,7 @@
|
||||
<a href="https://www.rtk-ai.app">官网</a> •
|
||||
<a href="#安装">安装</a> •
|
||||
<a href="docs/TROUBLESHOOTING.md">故障排除</a> •
|
||||
<a href="ARCHITECTURE.md">架构</a> •
|
||||
<a href="docs/contributing/ARCHITECTURE.md">架构</a> •
|
||||
<a href="https://discord.gg/RySmvNF5kF">Discord</a>
|
||||
</p>
|
||||
|
||||
@@ -154,7 +154,7 @@ rtk discover # 发现遗漏的节省机会
|
||||
|
||||
- **[TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md)** - 解决常见问题
|
||||
- **[INSTALL.md](INSTALL.md)** - 详细安装指南
|
||||
- **[ARCHITECTURE.md](ARCHITECTURE.md)** - 技术架构
|
||||
- **[ARCHITECTURE.md](docs/contributing/ARCHITECTURE.md)** - 技术架构
|
||||
|
||||
## 贡献
|
||||
|
||||
@@ -165,3 +165,7 @@ rtk discover # 发现遗漏的节省机会
|
||||
## 许可证
|
||||
|
||||
MIT 许可证 - 详见 [LICENSE](LICENSE)。
|
||||
|
||||
## 免责声明
|
||||
|
||||
详见 [DISCLAIMER.md](DISCLAIMER.md)。
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
# RTK Roadmap -
|
||||
|
||||
Stability & Reliability
|
||||
|
||||
Critical Fixes: Resolve bugs and stabilize Vitest/pnpm support.
|
||||
|
||||
Fork Strategy: Establish the fork as the new standard if upstream remains inactive.
|
||||
|
||||
Pro Tooling: Add a configuration file (TOML) and structured logging.
|
||||
|
||||
Easy Install: Launch a Homebrew formula and pre-compiled binaries for one-click setup.
|
||||
|
||||
Early Adoption: Prove token savings on real projects to onboard the first 5 teams.
|
||||
|
||||
---
|
||||
@@ -1,6 +1,6 @@
|
||||
# rtk Architecture Documentation
|
||||
|
||||
> **Deep reference** for RTK's system design, filtering taxonomy, performance characteristics, and architecture decisions. For a guided tour of the end-to-end flow, start with [docs/TECHNICAL.md](docs/TECHNICAL.md).
|
||||
> **Deep reference** for RTK's system design, filtering taxonomy, performance characteristics, and architecture decisions. For a guided tour of the end-to-end flow, start with [TECHNICAL.md](TECHNICAL.md).
|
||||
|
||||
**rtk (Rust Token Killer)** is a high-performance CLI proxy that minimizes LLM token consumption through intelligent output filtering and compression.
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
|
||||
## System Overview
|
||||
|
||||
> For the proxy pattern diagram and key components table, see [docs/TECHNICAL.md](docs/TECHNICAL.md#2-architecture-overview).
|
||||
> For the proxy pattern diagram and key components table, see [TECHNICAL.md](TECHNICAL.md#2-architecture-overview).
|
||||
|
||||
### Design Principles
|
||||
|
||||
@@ -38,7 +38,7 @@
|
||||
|
||||
### Hook Architecture (v0.9.5+)
|
||||
|
||||
> For the hook interception diagram and agent-specific JSON formats, see [docs/TECHNICAL.md](docs/TECHNICAL.md#32-hook-interception-command-rewriting) and [hooks/README.md](hooks/README.md).
|
||||
> For the hook interception diagram and agent-specific JSON formats, see [TECHNICAL.md](TECHNICAL.md#32-hook-interception-command-rewriting) and [hooks/README.md](hooks/README.md).
|
||||
|
||||
Two hook strategies:
|
||||
|
||||
@@ -159,7 +159,7 @@ Database: ~/.local/share/rtk/history.db
|
||||
|
||||
### Module Map
|
||||
|
||||
> For the full file-level module tree, see [docs/TECHNICAL.md](docs/TECHNICAL.md#4-folder-map) and each folder's README.
|
||||
> For the full file-level module tree, see [TECHNICAL.md](TECHNICAL.md#4-folder-map) and each folder's README.
|
||||
|
||||
**Token savings by ecosystem:**
|
||||
|
||||
@@ -1034,7 +1034,7 @@ Overhead Sources:
|
||||
|
||||
## Resources
|
||||
|
||||
- **[docs/TECHNICAL.md](docs/TECHNICAL.md)**: Guided tour of end-to-end flow
|
||||
- **[TECHNICAL.md](TECHNICAL.md)**: Guided tour of end-to-end flow
|
||||
- **[CONTRIBUTING.md](CONTRIBUTING.md)**: Design philosophy, contribution workflow, checklist
|
||||
- **CLAUDE.md**: Quick reference for AI agents (dev commands, build verification)
|
||||
- **README.md**: User guide, installation, examples
|
||||
@@ -3,7 +3,7 @@
|
||||
> **Start here** for a guided tour of how RTK works end-to-end.
|
||||
>
|
||||
> - [CONTRIBUTING.md](../CONTRIBUTING.md) — Design philosophy, PR process, branch naming, testing requirements
|
||||
> - [ARCHITECTURE.md](../ARCHITECTURE.md) — Deep reference: filtering taxonomy, performance benchmarks, architecture decisions
|
||||
> - [ARCHITECTURE.md](ARCHITECTURE.md) — Deep reference: filtering taxonomy, performance benchmarks, architecture decisions
|
||||
> - Each folder has its own `README.md` with implementation details and file descriptions
|
||||
|
||||
---
|
||||
@@ -1,102 +0,0 @@
|
||||
# How a TOML filter goes from file to execution
|
||||
|
||||
This document explains what happens between "I created `src/filters/my-tool.toml`" and "RTK filters the output of `my-tool`".
|
||||
|
||||
## Build pipeline
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A[["📄 src/filters/my-tool.toml\n(new file)"]] --> B
|
||||
|
||||
subgraph BUILD ["🔨 cargo build"]
|
||||
B["build.rs\n① ls src/filters/*.toml\n② sort alphabetically\n③ concat → schema_version = 1 + all files"] --> C
|
||||
C{"TOML valid?\nDuplicate names?"} -->|"❌ panic! (build fails)"| D[["🛑 Error message\npoints to bad file"]]
|
||||
C -->|"✅ ok"| E[["OUT_DIR/builtin_filters.toml\n(generated file)"]]
|
||||
E --> F["rustc\ninclude_str!(concat!(env!(OUT_DIR),\n'/builtin_filters.toml'))"]
|
||||
F --> G[["🦀 rtk binary\nBUILTIN_TOML embedded"]]
|
||||
end
|
||||
|
||||
subgraph TESTS ["🧪 cargo test"]
|
||||
H["test_builtin_filter_count\nassert_eq!(filters.len(), N)"] -->|"❌ count wrong"| I[["FAIL\n'Expected N, got N+1'\nUpdate the count'"]]
|
||||
J["test_builtin_all_expected_\nfilters_present\nassert!(names.contains('my-tool'))"] -->|"❌ name missing"| K[["FAIL\n'my-tool is missing—\nwas its .toml deleted?'"]]
|
||||
L["test_builtin_all_filters_\nhave_inline_tests\nassert!(tested.contains(name))"] -->|"❌ no tests"| M[["FAIL\n'Add tests.my-tool\nentries'"]]
|
||||
end
|
||||
|
||||
subgraph VERIFY ["✅ rtk verify"]
|
||||
N["runs [[tests.my-tool]]\ninput → filter → compare expected"]
|
||||
N -->|"❌ mismatch"| O[["FAIL\nshows actual vs expected"]]
|
||||
N -->|"✅ pass"| P[["60/60 tests passed"]]
|
||||
end
|
||||
|
||||
G --> H
|
||||
G --> J
|
||||
G --> L
|
||||
G --> N
|
||||
|
||||
subgraph RUNTIME ["⚡ rtk my-tool --verbose"]
|
||||
Q["Claude Code hook\nmy-tool ... → rtk my-tool ..."] --> R
|
||||
R["TomlFilterRegistry::load()\n① .rtk/filters.toml (project)\n② ~/.config/rtk/filters.toml (user)\n③ BUILTIN_TOML (binary)\n④ passthrough"] --> S
|
||||
S{"match_command\n'^my-tool\\b'\nmatches?"} -->|"No match"| T[["exec raw\n(passthrough)"]]
|
||||
S -->|"✅ match"| U["exec command\ncapture stdout"]
|
||||
U --> V
|
||||
|
||||
subgraph PIPELINE ["8-stage filter pipeline"]
|
||||
V["strip_ansi"] --> W["replace"]
|
||||
W --> X{"match_output\nshort-circuit?"}
|
||||
X -->|"✅ pattern matched"| Y[["emit message\nstop pipeline"]]
|
||||
X -->|"no match"| Z["strip/keep_lines"]
|
||||
Z --> AA["truncate_lines_at"]
|
||||
AA --> AB["tail_lines"]
|
||||
AB --> AC["max_lines"]
|
||||
AC --> AD{"output\nempty?"}
|
||||
AD -->|"yes"| AE[["emit on_empty"]]
|
||||
AD -->|"no"| AF[["print filtered\noutput + exit code"]]
|
||||
end
|
||||
end
|
||||
|
||||
G --> Q
|
||||
|
||||
style BUILD fill:#1e3a5f,color:#fff
|
||||
style TESTS fill:#1a3a1a,color:#fff
|
||||
style VERIFY fill:#2d1b69,color:#fff
|
||||
style RUNTIME fill:#3a1a1a,color:#fff
|
||||
style PIPELINE fill:#4a2a00,color:#fff
|
||||
style D fill:#8b0000,color:#fff
|
||||
style I fill:#8b0000,color:#fff
|
||||
style K fill:#8b0000,color:#fff
|
||||
style M fill:#8b0000,color:#fff
|
||||
style O fill:#8b0000,color:#fff
|
||||
```
|
||||
|
||||
## Step-by-step summary
|
||||
|
||||
| Step | Who | What happens | Fails if |
|
||||
|------|-----|--------------|----------|
|
||||
| 1 | Contributor | Creates `src/filters/my-tool.toml` | — |
|
||||
| 2 | `build.rs` | Concatenates all `.toml` files alphabetically | TOML syntax error, duplicate filter name |
|
||||
| 3 | `rustc` | Embeds result in binary via `BUILTIN_TOML` const | — |
|
||||
| 4 | `cargo test` | 3 guards check count, names, inline test presence | Count not updated, name not in list, no `[[tests.*]]` |
|
||||
| 5 | `rtk verify` | Runs each `[[tests.my-tool]]` entry | Filter logic doesn't match expected output |
|
||||
| 6 | Runtime | Hook rewrites command, registry looks up filter, pipeline runs | No match → passthrough (not an error) |
|
||||
|
||||
## Filter lookup priority at runtime
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
CMD["rtk my-tool args"] --> P1
|
||||
P1{"1. .rtk/filters.toml\n(project-local)"}
|
||||
P1 -->|"✅ match"| WIN["apply filter"]
|
||||
P1 -->|"no match"| P2
|
||||
P2{"2. ~/.config/rtk/filters.toml\n(user-global)\n(macOS alt: ~/Library/Application Support/rtk/filters.toml)"}
|
||||
P2 -->|"✅ match"| WIN
|
||||
P2 -->|"no match"| P3
|
||||
P3{"3. BUILTIN_TOML\n(binary)"}
|
||||
P3 -->|"✅ match"| WIN
|
||||
P3 -->|"no match"| P4[["exec raw\n(passthrough)"]]
|
||||
```
|
||||
|
||||
First match wins. A project filter with the same name as a built-in shadows the built-in and triggers a warning:
|
||||
|
||||
```
|
||||
[rtk] warning: filter 'make' is shadowing a built-in filter
|
||||
```
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 239 KiB |
@@ -429,4 +429,4 @@ print(f'rtk estimate: {len(text) // 4}')
|
||||
|
||||
- [README.md](../README.md) - Full rtk documentation
|
||||
- [CLAUDE.md](../CLAUDE.md) - Claude Code integration guide
|
||||
- [ARCHITECTURE.md](../ARCHITECTURE.md) - Technical architecture
|
||||
- [ARCHITECTURE.md](../contributing/ARCHITECTURE.md) - Technical architecture
|
||||
File renamed without changes.
File renamed without changes.
@@ -1,6 +1,6 @@
|
||||
# Analytics
|
||||
|
||||
> See also [docs/TECHNICAL.md](../../docs/TECHNICAL.md) for the full architecture overview
|
||||
> See also [docs/contributing/TECHNICAL.md](../../docs/contributing/TECHNICAL.md) for the full architecture overview
|
||||
|
||||
## Scope
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# Cloud and Infrastructure
|
||||
|
||||
> Part of [`src/cmds/`](../README.md) — see also [docs/TECHNICAL.md](../../../docs/TECHNICAL.md)
|
||||
> Part of [`src/cmds/`](../README.md) — see also [docs/contributing/TECHNICAL.md](../../../docs/contributing/TECHNICAL.md)
|
||||
|
||||
## Specifics
|
||||
|
||||
- `aws_cmd.rs` forces `--output json` for structured parsing
|
||||
- `aws_cmd.rs` — 25 specialized filters covering STS, S3, EC2, ECS, RDS, CloudFormation, CloudWatch Logs, Lambda, IAM, DynamoDB, EKS, SQS, Secrets Manager. Forces `--output json` for structured parsing, uses `force_tee_hint()` for truncation recovery, strips Lambda secrets. Shared runner `run_aws_filtered()` handles boilerplate for JSON-based filters; text-based filters (S3 ls, S3 sync/cp) have dedicated runners
|
||||
- `container.rs` handles both Docker and Kubernetes; `DockerCommands` and `KubectlCommands` sub-enums in `main.rs` route to `container::run()` -- uses passthrough for unknown subcommands
|
||||
- `curl_cmd.rs` auto-detects JSON responses and shows schema (structure without values)
|
||||
- `wget_cmd.rs` wraps wget with output filtering
|
||||
|
||||
+2156
-155
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
||||
# .NET Ecosystem
|
||||
|
||||
> Part of [`src/cmds/`](../README.md) — see also [docs/TECHNICAL.md](../../../docs/TECHNICAL.md)
|
||||
> Part of [`src/cmds/`](../README.md) — see also [docs/contributing/TECHNICAL.md](../../../docs/contributing/TECHNICAL.md)
|
||||
|
||||
## Specifics
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Git and VCS
|
||||
|
||||
> Part of [`src/cmds/`](../README.md) — see also [docs/TECHNICAL.md](../../../docs/TECHNICAL.md)
|
||||
> Part of [`src/cmds/`](../README.md) — see also [docs/contributing/TECHNICAL.md](../../../docs/contributing/TECHNICAL.md)
|
||||
|
||||
## Specifics
|
||||
|
||||
|
||||
+7
-25
@@ -785,31 +785,13 @@ fn pr_create(args: &[String], _verbose: u8) -> Result<i32> {
|
||||
}
|
||||
|
||||
fn pr_merge(args: &[String], _verbose: u8) -> Result<i32> {
|
||||
let pr_num = args
|
||||
.iter()
|
||||
.find(|a| !a.starts_with('-'))
|
||||
.map(|s| s.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let mut cmd = resolved_command("gh");
|
||||
cmd.args(["pr", "merge"]);
|
||||
for arg in args {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
runner::run_filtered(
|
||||
cmd,
|
||||
"gh",
|
||||
"pr merge",
|
||||
move |_stdout| {
|
||||
let detail = if !pr_num.is_empty() {
|
||||
format!("#{}", pr_num)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
ok_confirmation("merged", &detail)
|
||||
},
|
||||
RunOptions::stdout_only().early_exit_on_failure(),
|
||||
)
|
||||
// gh pr merge is a destructive action — pass through the real output
|
||||
// so the user (or AI agent) sees exactly what happened.
|
||||
run_passthrough("gh", "pr", &{
|
||||
let mut a = vec!["merge".to_string()];
|
||||
a.extend_from_slice(args);
|
||||
a
|
||||
})
|
||||
}
|
||||
|
||||
/// Flags that change `gh pr diff` output from unified diff to a different format.
|
||||
|
||||
+21
-2
@@ -330,8 +330,9 @@ pub(crate) fn compact_diff(diff: &str, max_lines: usize) -> String {
|
||||
}
|
||||
in_hunk = true;
|
||||
hunk_shown = 0;
|
||||
let hunk_info = line.split("@@").nth(1).unwrap_or("").trim();
|
||||
result.push(format!(" @@ {} @@", hunk_info));
|
||||
// Preserve the full unified diff hunk header, including trailing
|
||||
// function / symbol context after the second @@ marker.
|
||||
result.push(format!(" {}", line));
|
||||
} else if in_hunk {
|
||||
if line.starts_with('+') && !line.starts_with("+++") {
|
||||
added += 1;
|
||||
@@ -1744,6 +1745,24 @@ mod tests {
|
||||
assert!(result.contains("+"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_compact_diff_preserves_full_hunk_header_context() {
|
||||
let diff = r#"diff --git a/foo.rs b/foo.rs
|
||||
--- a/foo.rs
|
||||
+++ b/foo.rs
|
||||
@@ -10,3 +10,4 @@ fn important_context() {
|
||||
fn main() {
|
||||
+ println!("hello");
|
||||
}
|
||||
"#;
|
||||
let result = compact_diff(diff, 100);
|
||||
assert!(
|
||||
result.contains("@@ -10,3 +10,4 @@ fn important_context() {"),
|
||||
"Expected full hunk header with trailing context, got:\n{}",
|
||||
result
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_compact_diff_increased_hunk_limit() {
|
||||
// Build a hunk with 25 changed lines — should NOT be truncated with limit 30
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Go Ecosystem
|
||||
|
||||
> Part of [`src/cmds/`](../README.md) — see also [docs/TECHNICAL.md](../../../docs/TECHNICAL.md)
|
||||
> Part of [`src/cmds/`](../README.md) — see also [docs/contributing/TECHNICAL.md](../../../docs/contributing/TECHNICAL.md)
|
||||
|
||||
## Specifics
|
||||
|
||||
|
||||
+254
-33
@@ -439,25 +439,8 @@ fn filter_go_test_json(output: &str) -> String {
|
||||
for (test, outputs) in &pkg_result.failed_tests {
|
||||
result.push_str(&format!(" [FAIL] {}\n", test));
|
||||
|
||||
// Show failure output (limit to key lines)
|
||||
let relevant_lines: Vec<&String> = outputs
|
||||
.iter()
|
||||
.filter(|line| {
|
||||
let lower = line.to_lowercase();
|
||||
!line.trim().is_empty()
|
||||
&& !line.starts_with("=== RUN")
|
||||
&& !line.starts_with("--- FAIL")
|
||||
&& (lower.contains("error")
|
||||
|| lower.contains("expected")
|
||||
|| lower.contains("got")
|
||||
|| lower.contains("panic")
|
||||
|| line.trim().starts_with("at "))
|
||||
})
|
||||
.take(5)
|
||||
.collect();
|
||||
|
||||
for line in relevant_lines {
|
||||
result.push_str(&format!(" {}\n", truncate(line, 100)));
|
||||
for line in select_go_test_failure_lines(outputs) {
|
||||
result.push_str(&format!(" {}\n", truncate(&line, 100)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -465,26 +448,86 @@ fn filter_go_test_json(output: &str) -> String {
|
||||
result.trim().to_string()
|
||||
}
|
||||
|
||||
fn select_go_test_failure_lines(outputs: &[String]) -> Vec<String> {
|
||||
let mut relevant = Vec::new();
|
||||
let mut keep_next_context_line = false;
|
||||
|
||||
for line in outputs {
|
||||
let trimmed = line.trim();
|
||||
|
||||
if trimmed.is_empty()
|
||||
|| trimmed.starts_with("=== RUN")
|
||||
|| trimmed.starts_with("--- FAIL")
|
||||
|| trimmed.starts_with("--- PASS")
|
||||
{
|
||||
keep_next_context_line = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
let is_location = is_go_test_location_line(trimmed);
|
||||
let is_failure = is_go_test_failure_line(trimmed);
|
||||
|
||||
if is_location || is_failure || keep_next_context_line {
|
||||
relevant.push(trimmed.to_string());
|
||||
keep_next_context_line = is_location;
|
||||
} else {
|
||||
keep_next_context_line = false;
|
||||
}
|
||||
|
||||
if relevant.len() >= 5 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if relevant.is_empty() {
|
||||
if let Some(line) = outputs.iter().map(|line| line.trim()).find(|line| {
|
||||
!line.is_empty()
|
||||
&& !line.starts_with("=== RUN")
|
||||
&& !line.starts_with("--- FAIL")
|
||||
&& !line.starts_with("--- PASS")
|
||||
}) {
|
||||
relevant.push(line.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
relevant
|
||||
}
|
||||
|
||||
fn is_go_test_location_line(line: &str) -> bool {
|
||||
if let Some((_, rest)) = line.split_once(".go:") {
|
||||
rest.chars()
|
||||
.next()
|
||||
.map(|c| c.is_ascii_digit())
|
||||
.unwrap_or(false)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn is_go_test_failure_line(line: &str) -> bool {
|
||||
let lower = line.to_lowercase();
|
||||
|
||||
lower.starts_with("panic:")
|
||||
|| lower.starts_with("error:")
|
||||
|| lower.contains(" error:")
|
||||
|| lower.contains("expected")
|
||||
|| lower.contains("got")
|
||||
|| lower.contains("want")
|
||||
|| lower.contains("actual")
|
||||
|| lower.contains("assert")
|
||||
|| lower.contains("mismatch")
|
||||
|| lower.contains("unexpected")
|
||||
|| lower.contains("fatal")
|
||||
|| line.starts_with("at ")
|
||||
}
|
||||
|
||||
/// Filter go build output - show only errors
|
||||
fn filter_go_build(output: &str) -> String {
|
||||
let mut errors: Vec<String> = Vec::new();
|
||||
|
||||
for line in output.lines() {
|
||||
let trimmed = line.trim();
|
||||
let lower = trimmed.to_lowercase();
|
||||
|
||||
// Skip package markers (# package/name lines without errors)
|
||||
if trimmed.starts_with('#') && !lower.contains("error") {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Collect error lines (file:line:col format or error keywords)
|
||||
if !trimmed.is_empty()
|
||||
&& (lower.contains("error")
|
||||
|| trimmed.contains(".go:")
|
||||
|| lower.contains("undefined")
|
||||
|| lower.contains("cannot"))
|
||||
{
|
||||
if is_go_build_error_line(trimmed) {
|
||||
errors.push(trimmed.to_string());
|
||||
}
|
||||
}
|
||||
@@ -508,6 +551,63 @@ fn filter_go_build(output: &str) -> String {
|
||||
result.trim().to_string()
|
||||
}
|
||||
|
||||
fn is_go_build_error_line(line: &str) -> bool {
|
||||
let trimmed = line.trim();
|
||||
if trimmed.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let lower = trimmed.to_lowercase();
|
||||
|
||||
// Go download/progress lines often contain package names like pkg/errors,
|
||||
// xerrors, or multierror. These are not compilation failures.
|
||||
if lower.starts_with("go: downloading ")
|
||||
|| lower.starts_with("go: finding ")
|
||||
|| lower.starts_with("go: extracting ")
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Package headers are context, not errors by themselves.
|
||||
if trimmed.starts_with('#') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Canonical compiler/config error locations: file:line:col: ...
|
||||
let is_go_config_location = !lower.starts_with("go: ")
|
||||
&& (lower.contains("go.mod:")
|
||||
|| lower.contains("go.work:")
|
||||
|| lower.contains("go.sum:"));
|
||||
if trimmed.contains(".go:") || is_go_config_location {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Some compiler/module failures do not include a file.go:line:col location.
|
||||
let non_file_error_prefixes = [
|
||||
"undefined: ",
|
||||
"cannot use ",
|
||||
"cannot find package ",
|
||||
"no required module provides package ",
|
||||
"missing go.sum entry for module providing package ",
|
||||
"found packages ",
|
||||
"go: go.mod file not found in current directory or any parent directory",
|
||||
"go: cannot load module ",
|
||||
"go: build failed",
|
||||
"go: error ",
|
||||
"error: ",
|
||||
"go: updates to go.mod needed",
|
||||
"go: inconsistent vendoring",
|
||||
"no go files in ",
|
||||
];
|
||||
|
||||
non_file_error_prefixes
|
||||
.iter()
|
||||
.any(|prefix| lower.starts_with(prefix))
|
||||
|| lower.contains("import cycle not allowed")
|
||||
|| lower.contains("build constraints exclude all go files")
|
||||
|| lower.contains("function main is undeclared in the main package")
|
||||
}
|
||||
|
||||
/// Filter go vet output - show issues
|
||||
fn filter_go_vet(output: &str) -> String {
|
||||
let mut issues: Vec<String> = Vec::new();
|
||||
@@ -581,6 +681,20 @@ mod tests {
|
||||
assert!(result.contains("expected 5, got 3"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_go_test_preserves_file_location_and_followup_context() {
|
||||
let output = r#"{"Time":"2024-01-01T10:00:00Z","Action":"run","Package":"example.com/foo","Test":"TestFail"}
|
||||
{"Time":"2024-01-01T10:00:01Z","Action":"output","Package":"example.com/foo","Test":"TestFail","Output":"=== RUN TestFail\n"}
|
||||
{"Time":"2024-01-01T10:00:02Z","Action":"output","Package":"example.com/foo","Test":"TestFail","Output":" foo_test.go:42:\n"}
|
||||
{"Time":"2024-01-01T10:00:03Z","Action":"output","Package":"example.com/foo","Test":"TestFail","Output":" values differ after normalization\n"}
|
||||
{"Time":"2024-01-01T10:00:04Z","Action":"fail","Package":"example.com/foo","Test":"TestFail","Elapsed":0.5}
|
||||
{"Time":"2024-01-01T10:00:04Z","Action":"fail","Package":"example.com/foo","Elapsed":0.5}"#;
|
||||
|
||||
let result = filter_go_test_json(output);
|
||||
assert!(result.contains("foo_test.go:42:"));
|
||||
assert!(result.contains("values differ after normalization"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_go_build_success() {
|
||||
let output = "";
|
||||
@@ -601,6 +715,113 @@ main.go:15:2: cannot use x (type int) as type string"#;
|
||||
assert!(result.contains("cannot use x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_go_build_ignores_download_lines_with_error_in_package_names() {
|
||||
let output = r#"go: downloading github.com/go-errors/errors v1.5.1
|
||||
go: finding module for package example.com/foo
|
||||
go: extracting github.com/pkg/errors v0.9.1
|
||||
go: downloading github.com/pkg/errors v0.9.1
|
||||
go: downloading github.com/hashicorp/go-multierror v1.1.1
|
||||
go: downloading golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2"#;
|
||||
|
||||
let result = filter_go_build(output);
|
||||
assert_eq!(result, "Go build: Success");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_go_build_error_line_recognizes_real_compiler_errors() {
|
||||
assert!(is_go_build_error_line("undefined: missingFunc"));
|
||||
assert!(is_go_build_error_line(
|
||||
"cannot find package \"foo/bar\""
|
||||
));
|
||||
assert!(is_go_build_error_line(
|
||||
"found packages a (a.go) and b (b.go) in /tmp/rtk-go-build-probe-mix"
|
||||
));
|
||||
assert!(is_go_build_error_line(
|
||||
"imports example.com/cycle/a: import cycle not allowed"
|
||||
));
|
||||
assert!(is_go_build_error_line(
|
||||
"package example.com/buildtag: build constraints exclude all Go files in /tmp/rtk-go-build-probe-buildtag"
|
||||
));
|
||||
assert!(is_go_build_error_line(
|
||||
"go.mod:3: invalid go version 'not-a-version': must match format 1.23.0"
|
||||
));
|
||||
assert!(is_go_build_error_line(
|
||||
"go.work:1: invalid go version 'not-a-version': must match format 1.23.0"
|
||||
));
|
||||
assert!(is_go_build_error_line(
|
||||
"go: go.mod file not found in current directory or any parent directory; see 'go help modules'"
|
||||
));
|
||||
assert!(is_go_build_error_line("no Go files in /tmp/example"));
|
||||
assert!(is_go_build_error_line(
|
||||
"go: cannot load module missing listed in go.work file: open missing/go.mod: no such file or directory"
|
||||
));
|
||||
assert!(is_go_build_error_line(
|
||||
"runtime.main_main·f: function main is undeclared in the main package"
|
||||
));
|
||||
assert!(is_go_build_error_line(
|
||||
"main.go:10:5: undefined: missingFunc"
|
||||
));
|
||||
assert!(is_go_build_error_line("error: failed to load module"));
|
||||
assert!(!is_go_build_error_line(
|
||||
"go: downloading github.com/pkg/errors v0.9.1"
|
||||
));
|
||||
assert!(!is_go_build_error_line(
|
||||
"go: finding module for package example.com/foo"
|
||||
));
|
||||
assert!(!is_go_build_error_line(
|
||||
"go: extracting github.com/pkg/errors v0.9.1"
|
||||
));
|
||||
assert!(!is_go_build_error_line("# example.com/foo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_go_build_preserves_non_file_error_shapes() {
|
||||
let output = r#"undefined: missingFunc
|
||||
cannot find package "foo/bar"
|
||||
found packages a (a.go) and b (b.go) in /tmp/rtk-go-build-probe-mix
|
||||
imports example.com/cycle/a: import cycle not allowed
|
||||
package example.com/buildtag: build constraints exclude all Go files in /tmp/rtk-go-build-probe-buildtag
|
||||
runtime.main_main·f: function main is undeclared in the main package"#;
|
||||
|
||||
let result = filter_go_build(output);
|
||||
assert!(result.contains("6 errors"));
|
||||
assert!(result.contains("undefined: missingFunc"));
|
||||
assert!(result.contains("cannot find package \"foo/bar\""));
|
||||
assert!(result.contains("found packages a (a.go) and b (b.go)"));
|
||||
assert!(result.contains("import cycle not allowed"));
|
||||
assert!(result.contains("build constraints exclude all Go files"));
|
||||
assert!(result.contains("function main is undeclared in the main package"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_go_build_preserves_go_config_parse_errors() {
|
||||
let output = r#"go: errors parsing go.mod:
|
||||
go.mod:3: invalid go version 'not-a-version': must match format 1.23.0
|
||||
go: errors parsing go.work:
|
||||
go.work:1: invalid go version 'not-a-version': must match format 1.23.0"#;
|
||||
|
||||
let result = filter_go_build(output);
|
||||
assert!(result.contains("2 errors"));
|
||||
assert!(result.contains("go.mod:3: invalid go version"));
|
||||
assert!(result.contains("go.work:1: invalid go version"));
|
||||
assert!(!result.contains("go: errors parsing go.mod:"));
|
||||
assert!(!result.contains("go: errors parsing go.work:"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_go_build_preserves_module_root_and_workspace_errors() {
|
||||
let output = r#"go: go.mod file not found in current directory or any parent directory; see 'go help modules'
|
||||
no Go files in /tmp/example
|
||||
go: cannot load module missing listed in go.work file: open missing/go.mod: no such file or directory"#;
|
||||
|
||||
let result = filter_go_build(output);
|
||||
assert!(result.contains("3 errors"));
|
||||
assert!(result.contains("go.mod file not found in current directory or any parent directory"));
|
||||
assert!(result.contains("no Go files in /tmp/example"));
|
||||
assert!(result.contains("go: cannot load module missing listed in go.work file"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_go_vet_no_issues() {
|
||||
let output = "";
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# JavaScript / TypeScript / Node
|
||||
|
||||
> Part of [`src/cmds/`](../README.md) — see also [docs/TECHNICAL.md](../../../docs/TECHNICAL.md)
|
||||
> Part of [`src/cmds/`](../README.md) — see also [docs/contributing/TECHNICAL.md](../../../docs/contributing/TECHNICAL.md)
|
||||
|
||||
## Specifics
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Python Ecosystem
|
||||
|
||||
> Part of [`src/cmds/`](../README.md) — see also [docs/TECHNICAL.md](../../../docs/TECHNICAL.md)
|
||||
> Part of [`src/cmds/`](../README.md) — see also [docs/contributing/TECHNICAL.md](../../../docs/contributing/TECHNICAL.md)
|
||||
|
||||
## Specifics
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Ruby on Rails
|
||||
|
||||
> Part of [`src/cmds/`](../README.md) — see also [docs/TECHNICAL.md](../../../docs/TECHNICAL.md)
|
||||
> Part of [`src/cmds/`](../README.md) — see also [docs/contributing/TECHNICAL.md](../../../docs/contributing/TECHNICAL.md)
|
||||
|
||||
## Specifics
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Rust Ecosystem
|
||||
|
||||
> Part of [`src/cmds/`](../README.md) — see also [docs/TECHNICAL.md](../../../docs/TECHNICAL.md)
|
||||
> Part of [`src/cmds/`](../README.md) — see also [docs/contributing/TECHNICAL.md](../../../docs/contributing/TECHNICAL.md)
|
||||
|
||||
## Specifics
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# System and Generic Utilities
|
||||
|
||||
> Part of [`src/cmds/`](../README.md) — see also [docs/TECHNICAL.md](../../../docs/TECHNICAL.md)
|
||||
> Part of [`src/cmds/`](../README.md) — see also [docs/contributing/TECHNICAL.md](../../../docs/contributing/TECHNICAL.md)
|
||||
|
||||
## Specifics
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ use crate::core::utils::{exit_code_from_output, resolved_command};
|
||||
use anyhow::{Context, Result};
|
||||
use regex::Regex;
|
||||
use std::collections::HashMap;
|
||||
use std::process::Stdio;
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn run(
|
||||
@@ -28,7 +29,9 @@ pub fn run(
|
||||
let rg_pattern = pattern.replace(r"\|", "|");
|
||||
|
||||
let mut rg_cmd = resolved_command("rg");
|
||||
rg_cmd.args(["-n", "--no-heading", &rg_pattern, path]);
|
||||
rg_cmd
|
||||
.args(["-n", "--no-heading", &rg_pattern, path])
|
||||
.stdin(Stdio::null());
|
||||
|
||||
if let Some(ft) = file_type {
|
||||
rg_cmd.arg("--type").arg(ft);
|
||||
@@ -47,6 +50,7 @@ pub fn run(
|
||||
.or_else(|_| {
|
||||
resolved_command("grep")
|
||||
.args(["-rn", pattern, path])
|
||||
.stdin(Stdio::null())
|
||||
.output()
|
||||
})
|
||||
.context("grep/rg failed")?;
|
||||
|
||||
+72
-2
@@ -70,7 +70,7 @@ pub fn run(
|
||||
} else {
|
||||
filtered.clone()
|
||||
};
|
||||
println!("{}", rtk_output);
|
||||
print!("{}", rtk_output);
|
||||
timer.track(
|
||||
&format!("cat {}", file.display()),
|
||||
"rtk read",
|
||||
@@ -134,7 +134,7 @@ pub fn run_stdin(
|
||||
} else {
|
||||
filtered.clone()
|
||||
};
|
||||
println!("{}", rtk_output);
|
||||
print!("{}", rtk_output);
|
||||
|
||||
timer.track("cat - (stdin)", "rtk read -", &content, &rtk_output);
|
||||
Ok(())
|
||||
@@ -226,4 +226,74 @@ fn main() {{
|
||||
assert!(output.starts_with("a\n"));
|
||||
assert!(output.contains("more lines"));
|
||||
}
|
||||
|
||||
fn rtk_bin() -> std::path::PathBuf {
|
||||
std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("target")
|
||||
.join("debug")
|
||||
.join("rtk")
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn test_read_two_valid_files_concatenated() {
|
||||
let bin = rtk_bin();
|
||||
assert!(bin.exists(), "Run `cargo build` first");
|
||||
|
||||
let mut f1 = NamedTempFile::with_suffix(".txt").unwrap();
|
||||
let mut f2 = NamedTempFile::with_suffix(".txt").unwrap();
|
||||
writeln!(f1, "alpha\nbravo").unwrap();
|
||||
writeln!(f2, "charlie\ndelta").unwrap();
|
||||
|
||||
let output = std::process::Command::new(&bin)
|
||||
.args(["read", &f1.path().to_string_lossy(), &f2.path().to_string_lossy()])
|
||||
.output()
|
||||
.expect("failed to run rtk read");
|
||||
|
||||
assert!(output.status.success());
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
assert!(stdout.contains("alpha"), "first file content missing");
|
||||
assert!(stdout.contains("charlie"), "second file content missing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn test_read_valid_and_nonexistent() {
|
||||
let bin = rtk_bin();
|
||||
assert!(bin.exists(), "Run `cargo build` first");
|
||||
|
||||
let mut f1 = NamedTempFile::with_suffix(".txt").unwrap();
|
||||
writeln!(f1, "valid content").unwrap();
|
||||
|
||||
let output = std::process::Command::new(&bin)
|
||||
.args(["read", &f1.path().to_string_lossy(), "/tmp/rtk_nonexistent_file.txt"])
|
||||
.output()
|
||||
.expect("failed to run rtk read");
|
||||
|
||||
assert!(!output.status.success(), "should exit non-zero on missing file");
|
||||
let stdout = String::from_utf8_lossy(&output.stdout);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
assert!(stdout.contains("valid content"), "valid file should still be printed");
|
||||
assert!(stderr.contains("rtk_nonexistent_file"), "should report missing file on stderr");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn test_read_stdin_dedup_warning() {
|
||||
let bin = rtk_bin();
|
||||
assert!(bin.exists(), "Run `cargo build` first");
|
||||
|
||||
let output = std::process::Command::new(&bin)
|
||||
.args(["read", "-", "-"])
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.output()
|
||||
.expect("failed to run rtk read");
|
||||
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
assert!(
|
||||
stderr.contains("stdin specified more than once"),
|
||||
"should warn about duplicate stdin, got stderr: {}",
|
||||
stderr
|
||||
);
|
||||
}
|
||||
}
|
||||
+3
-1
@@ -1,6 +1,6 @@
|
||||
# Core Infrastructure
|
||||
|
||||
> See also [docs/TECHNICAL.md](../../docs/TECHNICAL.md) for the full architecture overview
|
||||
> See also [docs/contributing/TECHNICAL.md](../../docs/contributing/TECHNICAL.md) for the full architecture overview
|
||||
|
||||
## Scope
|
||||
|
||||
@@ -119,5 +119,7 @@ Consumers must call `timer.track()` on **all** code paths — success, failure,
|
||||
|
||||
Consumers that parse structured output (JSON, NDJSON, state machines) should call `tee::tee_and_hint()` to save raw output for LLM recovery on failure. Tee must be called before `std::process::exit()`.
|
||||
|
||||
For truncation recovery on **success** (e.g., list truncated at 20 items), use `tee::force_tee_hint()` which bypasses the tee mode check and writes regardless of exit code. This ensures LLMs always have a `[full output: ...]` recovery path instead of burning tokens working around missing data.
|
||||
|
||||
## Adding New Functionality
|
||||
Place new infrastructure code here if it meets **all** of these criteria: (1) it has no dependencies on command modules or hooks, (2) it is used by two or more other modules, and (3) it provides a general-purpose utility rather than command-specific logic. Follow the existing pattern of lazy-initialized resources (`lazy_static!` for regex, on-demand config loading) to preserve the <10ms startup target. Add `#[cfg(test)] mod tests` with unit tests in the same file.
|
||||
@@ -184,6 +184,44 @@ pub fn tee_and_hint(raw: &str, command_slug: &str, exit_code: i32) -> Option<Str
|
||||
Some(format_hint(&path))
|
||||
}
|
||||
|
||||
/// Force tee output regardless of exit code (used when filters truncate).
|
||||
/// Always writes file if size >= MIN_TEE_SIZE and tee is enabled.
|
||||
/// Returns hint string if file was written, None if skipped/disabled.
|
||||
///
|
||||
/// Used by AWS filters when FilterResult.truncated = true, ensuring
|
||||
/// the LLM has access to full untruncated output via the hint path.
|
||||
pub fn force_tee_hint(raw: &str, command_slug: &str) -> Option<String> {
|
||||
// Check RTK_TEE=0 env override (disable)
|
||||
if std::env::var("RTK_TEE").ok().as_deref() == Some("0") {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Skip if output too small
|
||||
if raw.len() < MIN_TEE_SIZE {
|
||||
return None;
|
||||
}
|
||||
|
||||
let config = Config::load().ok()?;
|
||||
|
||||
// Respect enabled flag but ignore mode (force tee)
|
||||
if !config.tee.enabled {
|
||||
return None;
|
||||
}
|
||||
|
||||
let tee_dir = get_tee_dir(&config)?;
|
||||
let tee_dir = std::fs::create_dir_all(&tee_dir).ok().and(Some(tee_dir))?;
|
||||
|
||||
let path = write_tee_file(
|
||||
raw,
|
||||
command_slug,
|
||||
&tee_dir,
|
||||
config.tee.max_file_size,
|
||||
config.tee.max_files,
|
||||
)?;
|
||||
|
||||
Some(format_hint(&path))
|
||||
}
|
||||
|
||||
/// TeeMode controls when tee writes files.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
@@ -400,4 +438,22 @@ directory = "/tmp/rtk-tee"
|
||||
let mode: TeeMode = serde_json::from_str(r#""never""#).unwrap();
|
||||
assert_eq!(mode, TeeMode::Never);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_force_tee_hint_skip_small_output() {
|
||||
// force_tee_hint should respect MIN_TEE_SIZE
|
||||
let small_output = "short error";
|
||||
let hint = force_tee_hint(small_output, "test_cmd");
|
||||
assert!(hint.is_none(), "Should skip output < MIN_TEE_SIZE");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_force_tee_hint_respects_env_disable() {
|
||||
// When RTK_TEE=0, force_tee_hint should return None
|
||||
std::env::set_var("RTK_TEE", "0");
|
||||
let large_output = "x".repeat(1000);
|
||||
let hint = force_tee_hint(&large_output, "test_cmd");
|
||||
std::env::remove_var("RTK_TEE");
|
||||
assert!(hint.is_none(), "Should respect RTK_TEE=0");
|
||||
}
|
||||
}
|
||||
@@ -1290,11 +1290,11 @@ mod tests {
|
||||
fn test_custom_db_path_env() {
|
||||
use std::env;
|
||||
|
||||
let custom_path = "/tmp/rtk_test_custom.db";
|
||||
env::set_var("RTK_DB_PATH", custom_path);
|
||||
let custom_path = env::temp_dir().join("rtk_test_custom.db");
|
||||
env::set_var("RTK_DB_PATH", &custom_path);
|
||||
|
||||
let db_path = get_db_path().expect("Failed to get db path");
|
||||
assert_eq!(db_path, PathBuf::from(custom_path));
|
||||
assert_eq!(db_path, custom_path);
|
||||
|
||||
env::remove_var("RTK_DB_PATH");
|
||||
}
|
||||
|
||||
@@ -368,6 +368,42 @@ pub fn tool_exists(name: &str) -> bool {
|
||||
which::which(name).is_ok()
|
||||
}
|
||||
|
||||
/// Extract short name from AWS ARN.
|
||||
/// Example: `arn:aws:ecs:region:acct:service/cluster/name` -> `name`
|
||||
/// For simple ARNs like `arn:aws:iam::123:user/alice`, returns `alice`.
|
||||
pub fn shorten_arn(arn: &str) -> &str {
|
||||
// ARNs use "/" or ":" as separators. Try "/" first (service/cluster/name pattern),
|
||||
// then fall back to ":" for Lambda/IAM ARNs.
|
||||
let slash_result = arn.rsplit('/').next().unwrap_or(arn);
|
||||
// If rsplit('/') returned the whole string (no '/' found), try ':'
|
||||
if slash_result == arn {
|
||||
arn.rsplit(':').next().unwrap_or(arn)
|
||||
} else {
|
||||
slash_result
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert bytes to human-readable format (KB, MB, GB, TB).
|
||||
/// Used for S3 object sizes.
|
||||
pub fn human_bytes(bytes: u64) -> String {
|
||||
const KB: u64 = 1024;
|
||||
const MB: u64 = KB * 1024;
|
||||
const GB: u64 = MB * 1024;
|
||||
const TB: u64 = GB * 1024;
|
||||
|
||||
if bytes >= TB {
|
||||
format!("{:.1} TB", bytes as f64 / TB as f64)
|
||||
} else if bytes >= GB {
|
||||
format!("{:.1} GB", bytes as f64 / GB as f64)
|
||||
} else if bytes >= MB {
|
||||
format!("{:.1} MB", bytes as f64 / MB as f64)
|
||||
} else if bytes >= KB {
|
||||
format!("{:.1} KB", bytes as f64 / KB as f64)
|
||||
} else {
|
||||
format!("{} B", bytes)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -748,4 +784,82 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ===== AWS helper function tests =====
|
||||
|
||||
#[test]
|
||||
fn test_shorten_arn_ecs_service() {
|
||||
assert_eq!(
|
||||
shorten_arn("arn:aws:ecs:us-east-1:123:service/cluster/api-service"),
|
||||
"api-service"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_shorten_arn_iam_user() {
|
||||
assert_eq!(shorten_arn("arn:aws:iam::123456789012:user/alice"), "alice");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_shorten_arn_lambda() {
|
||||
assert_eq!(
|
||||
shorten_arn("arn:aws:lambda:us-west-2:123:function:my-function"),
|
||||
"my-function"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_shorten_arn_fallback() {
|
||||
// Non-ARN string - return as-is
|
||||
assert_eq!(shorten_arn("simple-name"), "simple-name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_human_bytes_bytes() {
|
||||
assert_eq!(human_bytes(0), "0 B");
|
||||
assert_eq!(human_bytes(512), "512 B");
|
||||
assert_eq!(human_bytes(1023), "1023 B");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_human_bytes_kb() {
|
||||
assert_eq!(human_bytes(1024), "1.0 KB");
|
||||
assert_eq!(human_bytes(2048), "2.0 KB");
|
||||
assert_eq!(human_bytes(1536), "1.5 KB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_human_bytes_mb() {
|
||||
assert_eq!(human_bytes(1_048_576), "1.0 MB");
|
||||
assert_eq!(human_bytes(5_242_880), "5.0 MB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_human_bytes_gb() {
|
||||
assert_eq!(human_bytes(1_073_741_824), "1.0 GB");
|
||||
assert_eq!(human_bytes(2_147_483_648), "2.0 GB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_human_bytes_tb() {
|
||||
assert_eq!(human_bytes(1_099_511_627_776), "1.0 TB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_count_tokens_basic() {
|
||||
assert_eq!(count_tokens("hello world"), 2);
|
||||
assert_eq!(count_tokens("one two three four"), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_count_tokens_empty() {
|
||||
assert_eq!(count_tokens(""), 0);
|
||||
assert_eq!(count_tokens(" "), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_count_tokens_multiple_spaces() {
|
||||
assert_eq!(count_tokens("hello world"), 2);
|
||||
assert_eq!(count_tokens(" hello world "), 2);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
# Discover — History Analysis & Command Rewrite
|
||||
|
||||
> Full rewrite pipeline diagram: [docs/TECHNICAL.md](../../docs/TECHNICAL.md#32-hook-interception-command-rewriting)
|
||||
> Full rewrite pipeline diagram: [docs/contributing/TECHNICAL.md](../../docs/contributing/TECHNICAL.md#32-hook-interception-command-rewriting)
|
||||
|
||||
## What This Module Does
|
||||
|
||||
|
||||
@@ -1174,19 +1174,31 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_rewrite_rtk_disabled_warns_on_stderr() {
|
||||
// RTK_DISABLED=1 should still return None (no rewrite)
|
||||
// and emit a warning on stderr (tested via subprocess below)
|
||||
assert_eq!(rewrite_command("RTK_DISABLED=1 git status", &[]), None);
|
||||
}
|
||||
|
||||
// Verify warning via subprocess: `rtk rewrite "RTK_DISABLED=1 git status"`
|
||||
// should exit non-zero AND print warning to stderr
|
||||
#[test]
|
||||
fn test_rewrite_rtk_disabled_subprocess_warns() {
|
||||
let rtk_bin = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("target")
|
||||
.join("debug")
|
||||
.join("rtk");
|
||||
if !rtk_bin.exists() {
|
||||
return; // Binary not built — skip subprocess check
|
||||
return;
|
||||
}
|
||||
let rtk_mtime = std::fs::metadata(&rtk_bin)
|
||||
.ok()
|
||||
.and_then(|m| m.modified().ok());
|
||||
let test_mtime = std::env::current_exe()
|
||||
.ok()
|
||||
.and_then(|p| std::fs::metadata(p).ok())
|
||||
.and_then(|m| m.modified().ok());
|
||||
if let (Some(rtk_t), Some(test_t)) = (rtk_mtime, test_mtime) {
|
||||
if rtk_t < test_t {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let output = std::process::Command::new(&rtk_bin)
|
||||
.args(["rewrite", "RTK_DISABLED=1 git status"])
|
||||
.output()
|
||||
|
||||
+16
-1
@@ -332,7 +332,22 @@ pub const RULES: &[RtkRule] = &[
|
||||
rewrite_prefixes: &["aws"],
|
||||
category: "Infra",
|
||||
savings_pct: 80.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_savings: &[
|
||||
("sts", 80.0),
|
||||
("s3", 60.0),
|
||||
("ec2", 85.0),
|
||||
("ecs", 90.0),
|
||||
("rds", 80.0),
|
||||
("cloudformation", 90.0),
|
||||
("logs", 88.0),
|
||||
("lambda", 90.0),
|
||||
("iam", 85.0),
|
||||
("dynamodb", 70.0),
|
||||
("s3api", 75.0),
|
||||
("eks", 87.0),
|
||||
("sqs", 78.0),
|
||||
("secretsmanager", 75.0),
|
||||
],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Built-in Filters
|
||||
|
||||
> See also [docs/TECHNICAL.md](../../docs/TECHNICAL.md) for the full architecture overview
|
||||
> See also [docs/contributing/TECHNICAL.md](../../docs/contributing/TECHNICAL.md) for the full architecture overview
|
||||
|
||||
Each `.toml` file in this directory defines one filter and its inline tests.
|
||||
Files are concatenated alphabetically by `build.rs` into a single TOML blob embedded in the binary.
|
||||
|
||||
+34
-1
@@ -1,6 +1,6 @@
|
||||
# Hook System
|
||||
|
||||
> See also [docs/TECHNICAL.md](../../docs/TECHNICAL.md) for the full architecture overview | [hooks/](../../hooks/README.md) for deployed hook artifacts
|
||||
> See also [docs/contributing/TECHNICAL.md](../../docs/contributing/TECHNICAL.md) for the full architecture overview | [hooks/](../../hooks/README.md) for deployed hook artifacts
|
||||
|
||||
## Scope
|
||||
|
||||
@@ -61,6 +61,39 @@ Controls how `rtk init` modifies agent settings files:
|
||||
|
||||
All file operations use atomic writes (tempfile + rename) to prevent corruption on crash. Settings files are backed up to `.bak` before modification. All operations are idempotent -- running `rtk init` multiple times is safe.
|
||||
|
||||
## Permission Model
|
||||
|
||||
RTK enforces a permission precedence that matches Claude Code's least-privilege default:
|
||||
|
||||
```
|
||||
Deny > Ask > Allow (explicit) > Default (ask)
|
||||
```
|
||||
|
||||
Rules are loaded from all Claude Code `settings.json` files (project + global, including `.local` variants). Only `Bash(...)` rules are extracted; other scopes (Read, Write) are ignored.
|
||||
|
||||
| Verdict | Trigger | rewrite_cmd exit | Hook behavior |
|
||||
|---------|---------|-----------------|---------------|
|
||||
| Deny | `permissions.deny` rule matched | 2 | Passthrough — host tool handles denial |
|
||||
| Ask | `permissions.ask` rule matched | 3 | Rewrite + let host tool prompt user |
|
||||
| Allow | `permissions.allow` rule matched | 0 | Rewrite + auto-allow |
|
||||
| Default | No rule matched | 3 | Rewrite + let host tool prompt user |
|
||||
|
||||
### Per-tool support
|
||||
|
||||
| Tool | ask support | Behavior on Default |
|
||||
|------|------------|-------------------|
|
||||
| Claude Code (rtk-rewrite.sh) | Yes | `permissionDecision: "ask"` — user prompted |
|
||||
| Copilot VS Code (rtk hook copilot) | Yes | `permissionDecision: "ask"` — user prompted |
|
||||
| Gemini CLI (rtk hook gemini) | No (allow/deny only) | allow (limitation — no ask mode in Gemini) |
|
||||
| Copilot CLI (rtk hook copilot) | No updatedInput | deny-with-suggestion (unchanged) |
|
||||
| Codex | ask parsed but no-op | allow (limitation — fails open) |
|
||||
|
||||
### Implementation
|
||||
|
||||
- `permissions.rs` — loads deny/ask/allow rules, evaluates precedence, returns `PermissionVerdict`
|
||||
- `rewrite_cmd.rs` — maps verdict to exit code (consumed by shell hook)
|
||||
- `hook_cmd.rs` — maps verdict to JSON `permissionDecision` field (Copilot/Gemini)
|
||||
|
||||
## Exit Code Contract
|
||||
|
||||
Hook processors in `hook_cmd.rs` must return `Ok(())` on every path — success, no-match, parse error, and unexpected input. Returning `Err` propagates to `main()` and exits non-zero, which blocks the agent's command from executing. This violates the non-blocking guarantee documented in `hooks/README.md`.
|
||||
|
||||
@@ -7,3 +7,8 @@ pub const SETTINGS_LOCAL_JSON: &str = "settings.local.json";
|
||||
pub const HOOKS_JSON: &str = "hooks.json";
|
||||
pub const PRE_TOOL_USE_KEY: &str = "PreToolUse";
|
||||
pub const BEFORE_TOOL_KEY: &str = "BeforeTool";
|
||||
|
||||
pub const OPENCODE_PLUGIN_PATH: &str = ".config/opencode/plugins/rtk.ts";
|
||||
pub const CURSOR_DIR: &str = ".cursor";
|
||||
pub const CODEX_DIR: &str = ".codex";
|
||||
pub const GEMINI_DIR: &str = ".gemini";
|
||||
+97
-19
@@ -1,6 +1,9 @@
|
||||
//! Detects whether RTK hooks are installed and warns if they are outdated.
|
||||
|
||||
use super::constants::{CLAUDE_DIR, HOOKS_SUBDIR, REWRITE_HOOK_FILE};
|
||||
use super::constants::{
|
||||
CLAUDE_DIR, CODEX_DIR, CURSOR_DIR, GEMINI_DIR, GEMINI_HOOK_FILE, HOOKS_SUBDIR,
|
||||
OPENCODE_PLUGIN_PATH, REWRITE_HOOK_FILE,
|
||||
};
|
||||
use crate::core::constants::RTK_DATA_DIR;
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -90,6 +93,21 @@ pub fn parse_hook_version(content: &str) -> u8 {
|
||||
0 // No version tag = version 0 (outdated)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn other_integration_installed(home: &std::path::Path) -> bool {
|
||||
let paths = [
|
||||
home.join(OPENCODE_PLUGIN_PATH),
|
||||
home.join(CURSOR_DIR)
|
||||
.join(HOOKS_SUBDIR)
|
||||
.join(REWRITE_HOOK_FILE),
|
||||
home.join(CODEX_DIR).join("AGENTS.md"),
|
||||
home.join(GEMINI_DIR)
|
||||
.join(HOOKS_SUBDIR)
|
||||
.join(GEMINI_HOOK_FILE),
|
||||
];
|
||||
paths.iter().any(|p| p.exists())
|
||||
}
|
||||
|
||||
fn hook_installed_path() -> Option<PathBuf> {
|
||||
let home = dirs::home_dir()?;
|
||||
let path = home
|
||||
@@ -146,33 +164,93 @@ mod tests {
|
||||
assert_eq!(s.clone(), HookStatus::Missing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_other_integration_none() {
|
||||
let tmp = tempfile::tempdir().expect("tempdir");
|
||||
assert!(!other_integration_installed(tmp.path()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_other_integration_opencode() {
|
||||
let tmp = tempfile::tempdir().expect("tempdir");
|
||||
let path = tmp.path().join(OPENCODE_PLUGIN_PATH);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&path, b"plugin").unwrap();
|
||||
assert!(other_integration_installed(tmp.path()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_other_integration_cursor() {
|
||||
let tmp = tempfile::tempdir().expect("tempdir");
|
||||
let path = tmp
|
||||
.path()
|
||||
.join(CURSOR_DIR)
|
||||
.join(HOOKS_SUBDIR)
|
||||
.join(REWRITE_HOOK_FILE);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&path, b"hook").unwrap();
|
||||
assert!(other_integration_installed(tmp.path()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_other_integration_codex() {
|
||||
let tmp = tempfile::tempdir().expect("tempdir");
|
||||
let path = tmp.path().join(CODEX_DIR).join("AGENTS.md");
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&path, b"agents").unwrap();
|
||||
assert!(other_integration_installed(tmp.path()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_other_integration_gemini() {
|
||||
let tmp = tempfile::tempdir().expect("tempdir");
|
||||
let path = tmp
|
||||
.path()
|
||||
.join(GEMINI_DIR)
|
||||
.join(HOOKS_SUBDIR)
|
||||
.join(GEMINI_HOOK_FILE);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(&path, b"hook").unwrap();
|
||||
assert!(other_integration_installed(tmp.path()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_other_integration_empty_dirs_not_enough() {
|
||||
let tmp = tempfile::tempdir().expect("tempdir");
|
||||
std::fs::create_dir_all(tmp.path().join(CURSOR_DIR).join(HOOKS_SUBDIR)).unwrap();
|
||||
std::fs::create_dir_all(tmp.path().join(CODEX_DIR)).unwrap();
|
||||
std::fs::create_dir_all(tmp.path().join(GEMINI_DIR)).unwrap();
|
||||
assert!(!other_integration_installed(tmp.path()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_status_returns_valid_variant() {
|
||||
// Skip on machines without Claude Code or without hook
|
||||
let home = match dirs::home_dir() {
|
||||
Some(h) => h,
|
||||
None => return,
|
||||
};
|
||||
if !home
|
||||
let s = status();
|
||||
let has_claude_hook = home
|
||||
.join(".claude")
|
||||
.join("hooks")
|
||||
.join("rtk-rewrite.sh")
|
||||
.exists()
|
||||
{
|
||||
// No hook — status should be Missing (if .claude exists) or Ok (if not)
|
||||
let s = status();
|
||||
if home.join(".claude").exists() {
|
||||
assert_eq!(s, HookStatus::Missing);
|
||||
} else {
|
||||
assert_eq!(s, HookStatus::Ok);
|
||||
}
|
||||
return;
|
||||
.exists();
|
||||
let has_claude_dir = home.join(".claude").exists();
|
||||
let has_other = other_integration_installed(&home);
|
||||
|
||||
match (has_claude_hook, has_claude_dir, has_other) {
|
||||
(true, _, _) => assert!(
|
||||
s == HookStatus::Ok || s == HookStatus::Outdated,
|
||||
"Expected Ok or Outdated when Claude hook exists, got {:?}",
|
||||
s
|
||||
),
|
||||
(false, true, _) => assert_eq!(
|
||||
s,
|
||||
HookStatus::Missing,
|
||||
"Expected Missing when .claude/ exists but hook absent, got {:?}",
|
||||
s
|
||||
),
|
||||
(false, false, _) => assert_eq!(s, HookStatus::Ok),
|
||||
}
|
||||
let s = status();
|
||||
assert!(
|
||||
s == HookStatus::Ok || s == HookStatus::Outdated,
|
||||
"Expected Ok or Outdated when hook exists, got {:?}",
|
||||
s
|
||||
);
|
||||
}
|
||||
}
|
||||
+22
-1
@@ -6,6 +6,7 @@ use serde_json::{json, Value};
|
||||
use std::io::{self, Read};
|
||||
|
||||
use crate::discover::registry::rewrite_command;
|
||||
use crate::hooks::permissions::{check_command, PermissionVerdict};
|
||||
|
||||
// ── Copilot hook (VS Code + Copilot CLI) ──────────────────────
|
||||
|
||||
@@ -111,10 +112,24 @@ fn handle_vscode(cmd: &str) -> Result<()> {
|
||||
None => return Ok(()),
|
||||
};
|
||||
|
||||
let verdict = check_command(cmd);
|
||||
|
||||
// Deny: pass through without rewrite — let the host tool handle it.
|
||||
if verdict == PermissionVerdict::Deny {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Allow (explicit rule matched): auto-allow the rewritten command.
|
||||
// Ask/Default (no allow rule matched): rewrite but let the host tool prompt.
|
||||
let decision = match verdict {
|
||||
PermissionVerdict::Allow => "allow",
|
||||
_ => "ask",
|
||||
};
|
||||
|
||||
let output = json!({
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": PRE_TOOL_USE_KEY,
|
||||
"permissionDecision": "allow",
|
||||
"permissionDecision": decision,
|
||||
"permissionDecisionReason": "RTK auto-rewrite",
|
||||
"updatedInput": { "command": rewritten }
|
||||
}
|
||||
@@ -170,6 +185,12 @@ pub fn run_gemini() -> Result<()> {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Check deny rules — Gemini CLI only supports allow/deny (no ask mode).
|
||||
if check_command(cmd) == PermissionVerdict::Deny {
|
||||
println!(r#"{{"decision":"deny","reason":"Blocked by RTK permission rule"}}"#);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Delegate to the single source of truth for command rewriting
|
||||
match rewrite_command(cmd, &[]) {
|
||||
Some(rewritten) => print_rewrite(&rewritten),
|
||||
|
||||
+35
-23
@@ -11,7 +11,6 @@ use super::constants::{
|
||||
REWRITE_HOOK_FILE, SETTINGS_JSON,
|
||||
};
|
||||
use super::integrity;
|
||||
use crate::core::config;
|
||||
|
||||
// Embedded hook script (guards before set -euo pipefail)
|
||||
const REWRITE_HOOK: &str = include_str!("../../hooks/claude/rtk-rewrite.sh");
|
||||
@@ -293,14 +292,6 @@ pub fn run(
|
||||
}
|
||||
|
||||
println!();
|
||||
let env_disabled = std::env::var("RTK_TELEMETRY_DISABLED").unwrap_or_default() == "1";
|
||||
let config_disabled = matches!(config::telemetry_enabled(), Some(false));
|
||||
if env_disabled || config_disabled {
|
||||
println!(" [info] Anonymous telemetry is disabled");
|
||||
} else {
|
||||
println!(" [info] Anonymous telemetry is enabled by default (opt-out: RTK_TELEMETRY_DISABLED=1)");
|
||||
}
|
||||
println!(" [info] See: https://github.com/rtk-ai/rtk#privacy--telemetry");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -1273,15 +1264,24 @@ fn run_codex_mode(global: bool, verbose: u8) -> Result<()> {
|
||||
}
|
||||
}
|
||||
|
||||
// ISSUE #892: In global mode, use absolute path so @RTK.md resolves
|
||||
// from any CWD (worktrees, nested projects). Codex resolves @ references
|
||||
// relative to CWD, not the AGENTS.md file location.
|
||||
let rtk_md_ref = if global {
|
||||
format!("@{}", rtk_md_path.display())
|
||||
} else {
|
||||
RTK_MD_REF.to_string()
|
||||
};
|
||||
|
||||
write_if_changed(&rtk_md_path, RTK_SLIM_CODEX, RTK_MD, verbose)?;
|
||||
let added_ref = patch_agents_md(&agents_md_path, verbose)?;
|
||||
let added_ref = patch_agents_md(&agents_md_path, &rtk_md_ref, verbose)?;
|
||||
|
||||
println!("\nRTK configured for Codex CLI.\n");
|
||||
println!(" RTK.md: {}", rtk_md_path.display());
|
||||
if added_ref {
|
||||
println!(" AGENTS.md: @RTK.md reference added");
|
||||
println!(" AGENTS.md: {} reference added", rtk_md_ref);
|
||||
} else {
|
||||
println!(" AGENTS.md: @RTK.md reference already present");
|
||||
println!(" AGENTS.md: {} reference already present", rtk_md_ref);
|
||||
}
|
||||
if global {
|
||||
println!(
|
||||
@@ -1410,8 +1410,8 @@ fn patch_claude_md(path: &Path, verbose: u8) -> Result<bool> {
|
||||
Ok(migrated)
|
||||
}
|
||||
|
||||
/// Patch AGENTS.md: add @RTK.md, migrate old inline block if present
|
||||
fn patch_agents_md(path: &Path, verbose: u8) -> Result<bool> {
|
||||
/// Patch AGENTS.md: add @RTK.md (or absolute path), migrate old inline block if present
|
||||
fn patch_agents_md(path: &Path, rtk_md_ref: &str, verbose: u8) -> Result<bool> {
|
||||
let mut content = if path.exists() {
|
||||
fs::read_to_string(path)
|
||||
.with_context(|| format!("Failed to read AGENTS.md: {}", path.display()))?
|
||||
@@ -1431,9 +1431,21 @@ fn patch_agents_md(path: &Path, verbose: u8) -> Result<bool> {
|
||||
}
|
||||
}
|
||||
|
||||
if content.contains(RTK_MD_REF) {
|
||||
// ISSUE #892: Check for both relative and absolute @RTK.md references
|
||||
if content.contains(RTK_MD_REF) || content.contains(rtk_md_ref) {
|
||||
if verbose > 0 {
|
||||
eprintln!("@RTK.md reference already present in AGENTS.md");
|
||||
eprintln!("{} reference already present in AGENTS.md", rtk_md_ref);
|
||||
}
|
||||
// ISSUE #892: Migrate old relative @RTK.md to absolute path if needed
|
||||
if rtk_md_ref != RTK_MD_REF && content.contains(RTK_MD_REF) && !content.contains(rtk_md_ref)
|
||||
{
|
||||
content = content.replace(RTK_MD_REF, rtk_md_ref);
|
||||
atomic_write(path, &content)
|
||||
.with_context(|| format!("Failed to write AGENTS.md: {}", path.display()))?;
|
||||
if verbose > 0 {
|
||||
eprintln!("Migrated {} to {}", RTK_MD_REF, rtk_md_ref);
|
||||
}
|
||||
return Ok(true);
|
||||
}
|
||||
if migrated {
|
||||
atomic_write(path, &content)
|
||||
@@ -1443,15 +1455,15 @@ fn patch_agents_md(path: &Path, verbose: u8) -> Result<bool> {
|
||||
}
|
||||
|
||||
let new_content = if content.is_empty() {
|
||||
"@RTK.md\n".to_string()
|
||||
format!("{}\n", rtk_md_ref)
|
||||
} else {
|
||||
format!("{}\n\n@RTK.md\n", content.trim())
|
||||
format!("{}\n\n{}\n", content.trim(), rtk_md_ref)
|
||||
};
|
||||
|
||||
atomic_write(path, &new_content)
|
||||
.with_context(|| format!("Failed to write AGENTS.md: {}", path.display()))?;
|
||||
if verbose > 0 {
|
||||
eprintln!("Added @RTK.md reference to AGENTS.md");
|
||||
eprintln!("Added {} reference to AGENTS.md", rtk_md_ref);
|
||||
}
|
||||
|
||||
Ok(true)
|
||||
@@ -2603,8 +2615,8 @@ More notes
|
||||
let agents_md = temp.path().join("AGENTS.md");
|
||||
|
||||
fs::write(&agents_md, "# Team rules\n").unwrap();
|
||||
let first_added = patch_agents_md(&agents_md, 0).unwrap();
|
||||
let second_added = patch_agents_md(&agents_md, 0).unwrap();
|
||||
let first_added = patch_agents_md(&agents_md, RTK_MD_REF, 0).unwrap();
|
||||
let second_added = patch_agents_md(&agents_md, RTK_MD_REF, 0).unwrap();
|
||||
|
||||
assert!(first_added);
|
||||
assert!(!second_added);
|
||||
@@ -2662,7 +2674,7 @@ More notes
|
||||
let temp = TempDir::new().unwrap();
|
||||
let agents_md = temp.path().join("AGENTS.md");
|
||||
|
||||
let added = patch_agents_md(&agents_md, 0).unwrap();
|
||||
let added = patch_agents_md(&agents_md, RTK_MD_REF, 0).unwrap();
|
||||
|
||||
assert!(added);
|
||||
let content = fs::read_to_string(&agents_md).unwrap();
|
||||
@@ -2679,7 +2691,7 @@ More notes
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let added = patch_agents_md(&agents_md, 0).unwrap();
|
||||
let added = patch_agents_md(&agents_md, RTK_MD_REF, 0).unwrap();
|
||||
|
||||
assert!(added);
|
||||
let content = fs::read_to_string(&agents_md).unwrap();
|
||||
|
||||
+103
-30
@@ -5,22 +5,24 @@ use std::path::PathBuf;
|
||||
/// Verdict from checking a command against Claude Code's permission rules.
|
||||
#[derive(Debug, PartialEq, Eq, Clone)]
|
||||
pub enum PermissionVerdict {
|
||||
/// No deny/ask rules matched — safe to auto-allow.
|
||||
/// An explicit allow rule matched — safe to auto-allow.
|
||||
Allow,
|
||||
/// A deny rule matched — pass through to Claude Code's native deny handling.
|
||||
Deny,
|
||||
/// An ask rule matched — rewrite the command but let Claude Code prompt the user.
|
||||
Ask,
|
||||
/// No rule matched — default to ask (matches Claude Code's least-privilege default).
|
||||
Default,
|
||||
}
|
||||
|
||||
/// Check `cmd` against Claude Code's deny/ask permission rules.
|
||||
/// Check `cmd` against Claude Code's deny/ask/allow permission rules.
|
||||
///
|
||||
/// Returns `Allow` when no rules match (preserves existing behavior),
|
||||
/// `Deny` when a deny rule matches, or `Ask` when an ask rule matches.
|
||||
/// Deny takes priority over Ask if both match the same command.
|
||||
/// Precedence: Deny > Ask > Allow > Default (ask).
|
||||
/// Returns `Default` when no rules match — callers should treat this as ask
|
||||
/// to match Claude Code's least-privilege default.
|
||||
pub fn check_command(cmd: &str) -> PermissionVerdict {
|
||||
let (deny_rules, ask_rules) = load_deny_ask_rules();
|
||||
check_command_with_rules(cmd, &deny_rules, &ask_rules)
|
||||
let (deny_rules, ask_rules, allow_rules) = load_permission_rules();
|
||||
check_command_with_rules(cmd, &deny_rules, &ask_rules, &allow_rules)
|
||||
}
|
||||
|
||||
/// Internal implementation allowing tests to inject rules without file I/O.
|
||||
@@ -28,9 +30,11 @@ pub(crate) fn check_command_with_rules(
|
||||
cmd: &str,
|
||||
deny_rules: &[String],
|
||||
ask_rules: &[String],
|
||||
allow_rules: &[String],
|
||||
) -> PermissionVerdict {
|
||||
let segments = split_compound_command(cmd);
|
||||
let mut any_ask = false;
|
||||
let mut any_allow = false;
|
||||
|
||||
for segment in &segments {
|
||||
let segment = segment.trim();
|
||||
@@ -38,6 +42,7 @@ pub(crate) fn check_command_with_rules(
|
||||
continue;
|
||||
}
|
||||
|
||||
// Deny takes highest priority
|
||||
for pattern in deny_rules {
|
||||
if command_matches_pattern(segment, pattern) {
|
||||
return PermissionVerdict::Deny;
|
||||
@@ -52,16 +57,28 @@ pub(crate) fn check_command_with_rules(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !any_allow && !any_ask {
|
||||
for pattern in allow_rules {
|
||||
if command_matches_pattern(segment, pattern) {
|
||||
any_allow = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Precedence: Deny > Ask > Allow > Default (ask)
|
||||
if any_ask {
|
||||
PermissionVerdict::Ask
|
||||
} else {
|
||||
} else if any_allow {
|
||||
PermissionVerdict::Allow
|
||||
} else {
|
||||
PermissionVerdict::Default
|
||||
}
|
||||
}
|
||||
|
||||
/// Load deny and ask Bash rules from all Claude Code settings files.
|
||||
/// Load deny, ask, and allow Bash rules from all Claude Code settings files.
|
||||
///
|
||||
/// Files read (in order, later files do not override earlier ones — all are merged):
|
||||
/// 1. `$PROJECT_ROOT/.claude/settings.json`
|
||||
@@ -70,9 +87,10 @@ pub(crate) fn check_command_with_rules(
|
||||
/// 4. `~/.claude/settings.local.json`
|
||||
///
|
||||
/// Missing files and malformed JSON are silently skipped.
|
||||
fn load_deny_ask_rules() -> (Vec<String>, Vec<String>) {
|
||||
fn load_permission_rules() -> (Vec<String>, Vec<String>, Vec<String>) {
|
||||
let mut deny_rules = Vec::new();
|
||||
let mut ask_rules = Vec::new();
|
||||
let mut allow_rules = Vec::new();
|
||||
|
||||
for path in get_settings_paths() {
|
||||
let Ok(content) = std::fs::read_to_string(&path) else {
|
||||
@@ -87,9 +105,10 @@ fn load_deny_ask_rules() -> (Vec<String>, Vec<String>) {
|
||||
|
||||
append_bash_rules(permissions.get("deny"), &mut deny_rules);
|
||||
append_bash_rules(permissions.get("ask"), &mut ask_rules);
|
||||
append_bash_rules(permissions.get("allow"), &mut allow_rules);
|
||||
}
|
||||
|
||||
(deny_rules, ask_rules)
|
||||
(deny_rules, ask_rules, allow_rules)
|
||||
}
|
||||
|
||||
/// Extract Bash-scoped patterns from a JSON array and append them to `target`.
|
||||
@@ -293,31 +312,28 @@ mod tests {
|
||||
let deny = vec!["git push --force".to_string()];
|
||||
let ask = vec!["git push --force".to_string()];
|
||||
assert_eq!(
|
||||
check_command_with_rules("git push --force", &deny, &ask),
|
||||
check_command_with_rules("git push --force", &deny, &ask, &[]),
|
||||
PermissionVerdict::Deny
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_non_bash_rules_ignored() {
|
||||
// Non-Bash rules (e.g. Read, Write) must not match Bash commands.
|
||||
// In load_deny_ask_rules, only Bash( rules are kept — we verify that
|
||||
// extract_bash_pattern returns the original string for non-Bash rules.
|
||||
assert_eq!(extract_bash_pattern("Read(**/.env*)"), "Read(**/.env*)");
|
||||
|
||||
// With empty rule sets (what you get after filtering out non-Bash rules),
|
||||
// verdict is always Allow.
|
||||
// With empty rule sets, verdict is Default (not Allow).
|
||||
assert_eq!(
|
||||
check_command_with_rules("cat .env", &[], &[]),
|
||||
PermissionVerdict::Allow
|
||||
check_command_with_rules("cat .env", &[], &[], &[]),
|
||||
PermissionVerdict::Default
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_empty_permissions() {
|
||||
// No rules at all → Default (ask), not Allow.
|
||||
assert_eq!(
|
||||
check_command_with_rules("git push --force", &[], &[]),
|
||||
PermissionVerdict::Allow
|
||||
check_command_with_rules("git push --force", &[], &[], &[]),
|
||||
PermissionVerdict::Default
|
||||
);
|
||||
}
|
||||
|
||||
@@ -348,7 +364,7 @@ mod tests {
|
||||
fn test_compound_command_deny() {
|
||||
let deny = vec!["git push --force".to_string()];
|
||||
assert_eq!(
|
||||
check_command_with_rules("git status && git push --force", &deny, &[]),
|
||||
check_command_with_rules("git status && git push --force", &deny, &[], &[]),
|
||||
PermissionVerdict::Deny
|
||||
);
|
||||
}
|
||||
@@ -357,7 +373,7 @@ mod tests {
|
||||
fn test_compound_command_ask() {
|
||||
let ask = vec!["git push".to_string()];
|
||||
assert_eq!(
|
||||
check_command_with_rules("git status && git push origin main", &[], &ask),
|
||||
check_command_with_rules("git status && git push origin main", &[], &ask, &[]),
|
||||
PermissionVerdict::Ask
|
||||
);
|
||||
}
|
||||
@@ -366,9 +382,8 @@ mod tests {
|
||||
fn test_compound_command_deny_overrides_ask() {
|
||||
let deny = vec!["git push --force".to_string()];
|
||||
let ask = vec!["git status".to_string()];
|
||||
// deny in compound cmd takes priority even if ask also matches a segment
|
||||
assert_eq!(
|
||||
check_command_with_rules("git status && git push --force", &deny, &ask),
|
||||
check_command_with_rules("git status && git push --force", &deny, &ask, &[]),
|
||||
PermissionVerdict::Deny
|
||||
);
|
||||
}
|
||||
@@ -377,7 +392,7 @@ mod tests {
|
||||
fn test_ask_verdict() {
|
||||
let ask = vec!["git push".to_string()];
|
||||
assert_eq!(
|
||||
check_command_with_rules("git push origin main", &[], &ask),
|
||||
check_command_with_rules("git push origin main", &[], &ask, &[]),
|
||||
PermissionVerdict::Ask
|
||||
);
|
||||
}
|
||||
@@ -441,12 +456,12 @@ mod tests {
|
||||
fn test_deny_with_leading_wildcard() {
|
||||
let deny = vec!["* --force".to_string()];
|
||||
assert_eq!(
|
||||
check_command_with_rules("git push --force", &deny, &[]),
|
||||
check_command_with_rules("git push --force", &deny, &[], &[]),
|
||||
PermissionVerdict::Deny
|
||||
);
|
||||
assert_eq!(
|
||||
check_command_with_rules("git push", &deny, &[]),
|
||||
PermissionVerdict::Allow
|
||||
check_command_with_rules("git push", &deny, &[], &[]),
|
||||
PermissionVerdict::Default
|
||||
);
|
||||
}
|
||||
|
||||
@@ -455,8 +470,66 @@ mod tests {
|
||||
fn test_deny_star_colon_star() {
|
||||
let deny = vec!["*:*".to_string()];
|
||||
assert_eq!(
|
||||
check_command_with_rules("rm -rf /", &deny, &[]),
|
||||
check_command_with_rules("rm -rf /", &deny, &[], &[]),
|
||||
PermissionVerdict::Deny
|
||||
);
|
||||
}
|
||||
|
||||
// --- Allow rules tests ---
|
||||
|
||||
#[test]
|
||||
fn test_explicit_allow_rule() {
|
||||
let allow = vec!["git status".to_string()];
|
||||
assert_eq!(
|
||||
check_command_with_rules("git status", &[], &[], &allow),
|
||||
PermissionVerdict::Allow
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_allow_wildcard() {
|
||||
let allow = vec!["git *".to_string()];
|
||||
assert_eq!(
|
||||
check_command_with_rules("git log --oneline", &[], &[], &allow),
|
||||
PermissionVerdict::Allow
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deny_overrides_allow() {
|
||||
let deny = vec!["git push --force".to_string()];
|
||||
let allow = vec!["git *".to_string()];
|
||||
assert_eq!(
|
||||
check_command_with_rules("git push --force", &deny, &[], &allow),
|
||||
PermissionVerdict::Deny
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ask_overrides_allow() {
|
||||
let ask = vec!["git push".to_string()];
|
||||
let allow = vec!["git *".to_string()];
|
||||
assert_eq!(
|
||||
check_command_with_rules("git push origin main", &[], &ask, &allow),
|
||||
PermissionVerdict::Ask
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_rules_returns_default() {
|
||||
assert_eq!(
|
||||
check_command_with_rules("cargo test", &[], &[], &[]),
|
||||
PermissionVerdict::Default
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_default_not_allow_when_unmatched() {
|
||||
// Commands not in any list should get Default, not Allow
|
||||
let allow = vec!["git *".to_string()];
|
||||
assert_eq!(
|
||||
check_command_with_rules("cargo build", &[], &[], &allow),
|
||||
PermissionVerdict::Default
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,7 @@ pub fn run(cmd: &str) -> anyhow::Result<()> {
|
||||
let _ = std::io::stdout().flush();
|
||||
Ok(())
|
||||
}
|
||||
PermissionVerdict::Ask => {
|
||||
PermissionVerdict::Ask | PermissionVerdict::Default => {
|
||||
print!("{}", rewritten);
|
||||
let _ = std::io::stdout().flush();
|
||||
std::process::exit(3);
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
# Learn — CLI Correction Detection
|
||||
|
||||
> See also [docs/TECHNICAL.md](../../docs/TECHNICAL.md) for the full architecture overview
|
||||
> See also [docs/contributing/TECHNICAL.md](../../docs/contributing/TECHNICAL.md) for the full architecture overview
|
||||
|
||||
## Purpose
|
||||
|
||||
|
||||
+98
-24
@@ -84,8 +84,9 @@ enum Commands {
|
||||
|
||||
/// Read file with intelligent filtering
|
||||
Read {
|
||||
/// File to read
|
||||
file: PathBuf,
|
||||
/// 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,
|
||||
@@ -1245,26 +1246,44 @@ fn run_cli() -> Result<i32> {
|
||||
|
||||
Commands::Tree { args } => tree::run(&args, cli.verbose)?,
|
||||
|
||||
// ISSUE #989: support multiple files (cat file1 file2 → rtk read file1 file2)
|
||||
Commands::Read {
|
||||
file,
|
||||
files,
|
||||
level,
|
||||
max_lines,
|
||||
tail_lines,
|
||||
line_numbers,
|
||||
} => {
|
||||
if file == Path::new("-") {
|
||||
read::run_stdin(level, max_lines, tail_lines, line_numbers, cli.verbose)?;
|
||||
let mut had_error = false;
|
||||
let mut stdin_seen = false;
|
||||
for file in &files {
|
||||
let result = if file == Path::new("-") {
|
||||
if stdin_seen {
|
||||
eprintln!("rtk: warning: stdin specified more than once");
|
||||
continue;
|
||||
}
|
||||
stdin_seen = true;
|
||||
read::run_stdin(level, max_lines, tail_lines, line_numbers, cli.verbose)
|
||||
} else {
|
||||
read::run(
|
||||
file,
|
||||
level,
|
||||
max_lines,
|
||||
tail_lines,
|
||||
line_numbers,
|
||||
cli.verbose,
|
||||
)
|
||||
};
|
||||
if let Err(e) = result {
|
||||
eprintln!("cat: {}: {}", file.display(), e.root_cause());
|
||||
had_error = true;
|
||||
}
|
||||
}
|
||||
if had_error {
|
||||
1
|
||||
} else {
|
||||
read::run(
|
||||
&file,
|
||||
level,
|
||||
max_lines,
|
||||
tail_lines,
|
||||
line_numbers,
|
||||
cli.verbose,
|
||||
)?;
|
||||
0
|
||||
}
|
||||
0
|
||||
}
|
||||
|
||||
Commands::Smart {
|
||||
@@ -1932,6 +1951,7 @@ fn run_cli() -> Result<i32> {
|
||||
Commands::Proxy { args } => {
|
||||
use std::io::{Read, Write};
|
||||
use std::process::Stdio;
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::thread;
|
||||
|
||||
if args.is_empty() {
|
||||
@@ -1967,22 +1987,67 @@ fn run_cli() -> Result<i32> {
|
||||
eprintln!("Proxy mode: {} {}", cmd_name, cmd_args.join(" "));
|
||||
}
|
||||
|
||||
let mut child = core::utils::resolved_command(cmd_name.as_ref())
|
||||
.args(&cmd_args)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.context(format!("Failed to execute command: {}", cmd_name))?;
|
||||
// ISSUE #897: Kill proxy child on SIGINT/SIGTERM to prevent orphan
|
||||
// processes. Drop-based ChildGuard doesn't run on signals with
|
||||
// panic=abort, so we register a signal handler that kills the child
|
||||
// PID stored in this atomic.
|
||||
static PROXY_CHILD_PID: AtomicU32 = AtomicU32::new(0);
|
||||
|
||||
let stdout_pipe = child
|
||||
#[cfg(unix)]
|
||||
{
|
||||
unsafe extern "C" fn handle_signal(sig: libc::c_int) {
|
||||
let pid = PROXY_CHILD_PID.load(Ordering::SeqCst);
|
||||
if pid != 0 {
|
||||
libc::kill(pid as libc::pid_t, libc::SIGTERM);
|
||||
libc::waitpid(pid as libc::pid_t, std::ptr::null_mut(), 0);
|
||||
}
|
||||
// Re-raise with default handler so parent sees correct exit status
|
||||
libc::signal(sig, libc::SIG_DFL);
|
||||
libc::raise(sig);
|
||||
}
|
||||
unsafe {
|
||||
libc::signal(libc::SIGINT, handle_signal as libc::sighandler_t);
|
||||
libc::signal(libc::SIGTERM, handle_signal as libc::sighandler_t);
|
||||
}
|
||||
}
|
||||
|
||||
struct ChildGuard(Option<std::process::Child>);
|
||||
impl Drop for ChildGuard {
|
||||
fn drop(&mut self) {
|
||||
if let Some(mut child) = self.0.take() {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
PROXY_CHILD_PID.store(0, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
let mut child = ChildGuard(Some(
|
||||
core::utils::resolved_command(cmd_name.as_ref())
|
||||
.args(&cmd_args)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.context(format!("Failed to execute command: {}", cmd_name))?,
|
||||
));
|
||||
|
||||
// Store child PID for signal handler before anything can fail
|
||||
if let Some(ref inner) = child.0 {
|
||||
PROXY_CHILD_PID.store(inner.id(), Ordering::SeqCst);
|
||||
}
|
||||
|
||||
let inner = child.0.as_mut().context("Child process missing")?;
|
||||
let stdout_pipe = inner
|
||||
.stdout
|
||||
.take()
|
||||
.context("Failed to capture child stdout")?;
|
||||
let stderr_pipe = child
|
||||
let stderr_pipe = inner
|
||||
.stderr
|
||||
.take()
|
||||
.context("Failed to capture child stderr")?;
|
||||
|
||||
const CAP: usize = 1_048_576;
|
||||
|
||||
let stdout_handle = thread::spawn(move || -> std::io::Result<Vec<u8>> {
|
||||
let mut reader = stdout_pipe;
|
||||
let mut captured = Vec::new();
|
||||
@@ -1993,7 +2058,10 @@ fn run_cli() -> Result<i32> {
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
captured.extend_from_slice(&buf[..count]);
|
||||
if captured.len() < CAP {
|
||||
let take = count.min(CAP - captured.len());
|
||||
captured.extend_from_slice(&buf[..take]);
|
||||
}
|
||||
let mut out = std::io::stdout().lock();
|
||||
out.write_all(&buf[..count])?;
|
||||
out.flush()?;
|
||||
@@ -2012,7 +2080,10 @@ fn run_cli() -> Result<i32> {
|
||||
if count == 0 {
|
||||
break;
|
||||
}
|
||||
captured.extend_from_slice(&buf[..count]);
|
||||
if captured.len() < CAP {
|
||||
let take = count.min(CAP - captured.len());
|
||||
captured.extend_from_slice(&buf[..take]);
|
||||
}
|
||||
let mut err = std::io::stderr().lock();
|
||||
err.write_all(&buf[..count])?;
|
||||
err.flush()?;
|
||||
@@ -2022,6 +2093,9 @@ fn run_cli() -> Result<i32> {
|
||||
});
|
||||
|
||||
let status = child
|
||||
.0
|
||||
.take()
|
||||
.context("Child process missing")?
|
||||
.wait()
|
||||
.context(format!("Failed waiting for command: {}", cmd_name))?;
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Parser Infrastructure
|
||||
|
||||
> See also [docs/TECHNICAL.md](../../docs/TECHNICAL.md) for the full architecture overview
|
||||
> See also [docs/contributing/TECHNICAL.md](../../docs/contributing/TECHNICAL.md) for the full architecture overview
|
||||
|
||||
## Overview
|
||||
|
||||
|
||||
Reference in new issue
Block a user