From 52447d43495c04a65ebda0fad4cb13569bd47e25 Mon Sep 17 00:00:00 2001 From: fuxkCH Date: Fri, 10 Jul 2026 22:35:27 +0800 Subject: [PATCH 01/17] feat: add Windows native compatibility fork --- .github/workflows/next-release.yml | 2 +- CONTRIBUTING.md | 8 +- Cargo.lock | 97 +- Cargo.toml | 4 +- README.md | 531 +---- README_LOCAL.md | 52 + docs/guide/getting-started/configuration.md | 22 +- .../guide/getting-started/supported-agents.md | 23 +- ...x-windows-native-next-plan-review-codex.md | 283 +++ ...indows-native-next-plan-review-deepseek.md | 186 ++ ...odex-windows-native-next-plan-review-hy.md | 128 ++ ...ex-windows-native-next-plan-review-mimo.md | 384 ++++ docs/rtk-codex-windows-native-next-plan.md | 1786 +++++++++++++++++ docs/rtk-powershell-native-plan-review.md | 484 +++++ docs/rtk-powershell-native-plan.md | 1042 ++++++++++ docs/windows-native-baseline.md | 144 ++ ...\233\276-\347\256\200\345\214\226.mermaid" | 12 + ...6\265\201\347\250\213\345\233\276.mermaid" | 39 + hooks/codex/rtk-awareness.md | 22 +- scripts/benchmark.sh | 6 +- scripts/benchmark/run.ts | 2 +- scripts/test-all.sh | 6 +- scripts/windows-cargo.ps1 | 97 + src/analytics/gain.rs | 8 +- src/analytics/session_cmd.rs | 176 +- src/cmds/git/git.rs | 542 ++--- src/cmds/mod.rs | 1 - src/cmds/php/README.md | 15 - src/cmds/php/artisan_cmd.rs | 54 - src/cmds/php/ecs_cmd.rs | 81 - src/cmds/php/mod.rs | 1 - src/cmds/php/paratest_cmd.rs | 108 - src/cmds/php/pest_cmd.rs | 45 - src/cmds/php/php_cmd.rs | 114 -- src/cmds/php/phpstan_cmd.rs | 568 ------ src/cmds/php/phpunit_cmd.rs | 396 ---- src/cmds/php/pint_cmd.rs | 227 --- src/cmds/php/test_output.rs | 84 - src/cmds/php/utils.rs | 62 - src/cmds/rust/runner.rs | 6 +- src/cmds/system/df.rs | 184 ++ src/cmds/system/du.rs | 361 ++++ src/cmds/system/head_tail.rs | 239 +++ src/cmds/system/ls.rs | 429 +++- src/cmds/system/mkdir.rs | 104 + src/cmds/system/pipe_cmd.rs | 61 +- src/cmds/system/ps.rs | 98 + src/cmds/system/ps_cmdlet.rs | 168 ++ src/cmds/system/pwd.rs | 17 + src/cmds/system/search.rs | 475 ++++- src/cmds/system/touch.rs | 76 + src/cmds/system/tree.rs | 293 ++- src/cmds/system/wc_cmd.rs | 336 +++- src/cmds/system/which.rs | 38 + src/core/constants.rs | 7 + src/core/line_window.rs | 82 + src/core/mod.rs | 3 + src/core/runner.rs | 1 + src/core/stream.rs | 117 +- src/core/toml_filter.rs | 228 ++- src/core/utils.rs | 88 +- src/core/windows_shell.rs | 755 +++++++ src/discover/mod.rs | 73 +- src/discover/powershell_lexer.rs | 100 + src/discover/provider.rs | 734 ++++++- src/discover/ps_classify.rs | 603 ++++++ src/discover/registry.rs | 623 ++---- src/discover/report.rs | 16 +- src/discover/rules.rs | 123 +- src/filters/README.md | 20 - src/hooks/constants.rs | 19 - src/hooks/hook_check.rs | 30 +- src/hooks/hook_cmd.rs | 319 --- src/hooks/init.rs | 892 +------- src/hooks/integrity.rs | 41 +- src/hooks/mod.rs | 32 - src/hooks/permissions.rs | 147 +- src/hooks/trust.rs | 194 +- src/main.rs | 516 +++-- src/parser/mod.rs | 40 +- tests/fixtures/phpstan_raw.json | 380 ---- tests/fixtures/windows-native/empty.txt | 1 + .../fixtures/windows-native/grep-context.txt | 6 + tests/fixtures/windows-native/head-tail.txt | 12 + .../windows-native/quote-and-wildcard.txt | 5 + .../windows-native/scripts/argv-probe.cmd | 10 + .../windows-native/scripts/argv-probe.ps1 | 8 + .../unicode-\346\265\213\350\257\225.txt" | 2 + tests/windows_native_acceptance.ps1 | 326 +++ 89 files changed, 11603 insertions(+), 5677 deletions(-) create mode 100644 README_LOCAL.md create mode 100644 docs/rtk-codex-windows-native-next-plan-review-codex.md create mode 100644 docs/rtk-codex-windows-native-next-plan-review-deepseek.md create mode 100644 docs/rtk-codex-windows-native-next-plan-review-hy.md create mode 100644 docs/rtk-codex-windows-native-next-plan-review-mimo.md create mode 100644 docs/rtk-codex-windows-native-next-plan.md create mode 100644 docs/rtk-powershell-native-plan-review.md create mode 100644 docs/rtk-powershell-native-plan.md create mode 100644 docs/windows-native-baseline.md create mode 100644 "docs/\346\265\201\347\250\213\345\233\276-\347\256\200\345\214\226.mermaid" create mode 100644 "docs/\346\265\201\347\250\213\345\233\276.mermaid" create mode 100644 scripts/windows-cargo.ps1 delete mode 100644 src/cmds/php/README.md delete mode 100644 src/cmds/php/artisan_cmd.rs delete mode 100644 src/cmds/php/ecs_cmd.rs delete mode 100644 src/cmds/php/mod.rs delete mode 100644 src/cmds/php/paratest_cmd.rs delete mode 100644 src/cmds/php/pest_cmd.rs delete mode 100644 src/cmds/php/php_cmd.rs delete mode 100644 src/cmds/php/phpstan_cmd.rs delete mode 100644 src/cmds/php/phpunit_cmd.rs delete mode 100644 src/cmds/php/pint_cmd.rs delete mode 100644 src/cmds/php/test_output.rs delete mode 100644 src/cmds/php/utils.rs create mode 100644 src/cmds/system/df.rs create mode 100644 src/cmds/system/du.rs create mode 100644 src/cmds/system/head_tail.rs create mode 100644 src/cmds/system/mkdir.rs create mode 100644 src/cmds/system/ps.rs create mode 100644 src/cmds/system/ps_cmdlet.rs create mode 100644 src/cmds/system/pwd.rs create mode 100644 src/cmds/system/touch.rs create mode 100644 src/cmds/system/which.rs create mode 100644 src/core/line_window.rs create mode 100644 src/core/windows_shell.rs create mode 100644 src/discover/powershell_lexer.rs create mode 100644 src/discover/ps_classify.rs delete mode 100644 tests/fixtures/phpstan_raw.json create mode 100644 tests/fixtures/windows-native/empty.txt create mode 100644 tests/fixtures/windows-native/grep-context.txt create mode 100644 tests/fixtures/windows-native/head-tail.txt create mode 100644 tests/fixtures/windows-native/quote-and-wildcard.txt create mode 100644 tests/fixtures/windows-native/scripts/argv-probe.cmd create mode 100644 tests/fixtures/windows-native/scripts/argv-probe.ps1 create mode 100644 "tests/fixtures/windows-native/unicode-\346\265\213\350\257\225.txt" create mode 100644 tests/windows_native_acceptance.ps1 diff --git a/.github/workflows/next-release.yml b/.github/workflows/next-release.yml index 756c7c4279..e7535f8642 100644 --- a/.github/workflows/next-release.yml +++ b/.github/workflows/next-release.yml @@ -1,7 +1,7 @@ name: Update Next Release PR on: - pull_request_target: + pull_request: types: [closed] branches: [develop] diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 36ffd68cd1..b10b9e710b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -207,7 +207,7 @@ Documentation updates are required for new filters, new features, and changes th ### Contributor License Agreement (CLA) -All contributions require signing our **Contributor License Agreement (CLA)** before being merged. +All contributions require signing our [Contributor License Agreement (CLA)](CLA.md) before being merged. By signing, you certify that: - You have authored 100% of the contribution, or have the necessary rights to submit it. @@ -247,8 +247,8 @@ For how to write tests (fixtures, snapshots, token savings verification), see [d | Type | Where | Run With | |------|-------|----------| | **Unit tests** | `#[cfg(test)] mod tests` in each module | `cargo test` | -| **Snapshot tests** | `#[cfg(test)]` create snapshots for filters modules | `cargo test` | -| **Smoke tests** | `scripts/test-all.sh` | `bash scripts/test-all.sh` | +| **Snapshot tests** | `assert_snapshot!()` via `insta` crate | `cargo test` + `cargo insta review` | +| **Smoke tests** | `scripts/test-all.sh` (69 assertions) | `bash scripts/test-all.sh` | | **Integration tests** | `#[ignore]` tests requiring installed binary | `cargo test --ignored` | ### Pre-Commit Gate (mandatory) @@ -262,7 +262,7 @@ cargo fmt --all --check && cargo clippy --all-targets && cargo test ### PR Testing Checklist - [ ] Unit tests added/updated for changed code -- [ ] Snapshot tests for filters +- [ ] Snapshot tests reviewed (`cargo insta review`) - [ ] Token savings >=60% verified - [ ] Any truncated list has a recovery hint (`force_tee_tail_hint` or `force_tee_hint`) and uses a `CAP_*` from `src/core/truncate.rs` - [ ] Edge cases covered diff --git a/Cargo.lock b/Cargo.lock index b7380ea65e..1b644aed52 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -334,6 +334,12 @@ dependencies = [ "syn", ] +[[package]] +name = "either" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e" + [[package]] name = "env_home" version = "0.1.0" @@ -503,7 +509,7 @@ dependencies = [ "js-sys", "log", "wasm-bindgen", - "windows-core", + "windows-core 0.62.2", ] [[package]] @@ -745,6 +751,15 @@ dependencies = [ "simd-adler32", ] +[[package]] +name = "ntapi" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" +dependencies = [ + "winapi", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -836,6 +851,26 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + [[package]] name = "redox_users" version = "0.4.6" @@ -892,10 +927,11 @@ dependencies = [ [[package]] name = "rtk" -version = "0.42.4" +version = "0.43.1" dependencies = [ "anyhow", "automod", + "base64", "chrono", "clap", "colored", @@ -911,6 +947,7 @@ dependencies = [ "serde", "serde_json", "sha2", + "sysinfo", "tempfile", "toml", "ureq", @@ -1123,6 +1160,21 @@ dependencies = [ "syn", ] +[[package]] +name = "sysinfo" +version = "0.30.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a5b4ddaee55fb2bea2bf0e5000747e5f5c0de765e5a5ff87f4cd106439f4bb3" +dependencies = [ + "cfg-if", + "core-foundation-sys", + "libc", + "ntapi", + "once_cell", + "rayon", + "windows", +] + [[package]] name = "tempfile" version = "3.26.0" @@ -1425,6 +1477,22 @@ dependencies = [ "winsafe", ] +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + [[package]] name = "winapi-util" version = "0.1.11" @@ -1434,6 +1502,31 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e48a53791691ab099e5e2ad123536d0fff50652600abaf43bbf952894110d0be" +dependencies = [ + "windows-core 0.52.0", + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-core" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-core" version = "0.62.2" diff --git a/Cargo.toml b/Cargo.toml index 8ff5614d17..0a9f9d0629 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "rtk" -version = "0.42.4" +version = "0.43.1" edition = "2021" rust-version = "1.91" authors = ["Patrick Szymkowiak"] @@ -34,6 +34,8 @@ flate2 = "1.0" quick-xml = "0.37" which = "8" automod = "1" +sysinfo = "0.30" +base64 = "0.22" [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/README.md b/README.md index 9141e2a634..f00b30ff48 100644 --- a/README.md +++ b/README.md @@ -1,509 +1,52 @@ -

- RTK - Rust Token Killer -

+# RTK Local Repository Notes / RTK 本仓库说明 -

- High-performance CLI proxy that reduces LLM token consumption by 60-90% -

+This repository is a Windows-native compatibility fork/worktree of RTK. For the baseline project description, installation, general usage, and original command coverage, read the main repository README first: -

- CI - Release - License: Apache 2.0 - Discord - Homebrew -

+本仓库是 RTK 的 Windows native 兼容增强工作区/分支。基础项目介绍、安装方式、通用用法和原始命令覆盖范围,请先阅读主仓库 README: -

- Website • - Install • - Troubleshooting • - Architecture • - Discord -

+- Main README / 主仓库 README: https://github.com/fuxkCH/rtk#readme +- Local acceptance test / 本地验收测试: [`tests/windows_native_acceptance.ps1`](tests/windows_native_acceptance.ps1) +- Windows-native fixtures / Windows native 测试夹具: [`tests/fixtures/windows-native/`](tests/fixtures/windows-native/) -

- English • - Francais • - 中文 • - 日本語 • - 한국어 • - Espanol • - Português -

+## Feature Delta / 相对主仓库的功能变化 ---- +| Area | English | 中文 | +|---|---|---| +| Windows fallback transport | Adds a Windows fallback runner that preserves argv boundaries instead of rebuilding commands with unsafe string joins. Explicit shell hosts such as `powershell`, `pwsh`, and `cmd` run as direct argv calls. | 新增 Windows fallback runner,保留 argv 边界,避免用不安全的字符串拼接重构命令。`powershell`、`pwsh`、`cmd` 等显式 shell host 以直接 argv 方式执行。 | +| PowerShell cmdlet compatibility | Adds narrow, validated compatibility for common PowerShell shapes: `Get-Content`, `Select-String`, `Get-ChildItem`, and `Get-Command -CommandType Application`. Unsupported semantic shapes either use safe transport or fail closed instead of being guessed. | 新增常见 PowerShell 形态的窄口径兼容:`Get-Content`、`Select-String`、`Get-ChildItem`、`Get-Command -CommandType Application`。不安全或不等价的语义形态走安全 transport 或 fail-closed,不猜测执行。 | +| Windows native small commands | Adds or wires native RTK commands useful on Windows and for cross-platform agent habits: `which`, `pwd`, `head`, `tail`, `touch`, and `mkdir -p`. | 新增或接入 Windows 上常用、也符合跨平台 agent 习惯的小型 native 命令:`which`、`pwd`、`head`、`tail`、`touch`、`mkdir -p`。 | +| Existing Windows native baseline | Preserves and verifies the local Windows-native implementations for `ls`, `tree`, `wc`, Rust grep fallback, `ps`, `df`, and `du`. | 保留并验证本地已有 Windows-native 实现:`ls`、`tree`、`wc`、Rust grep fallback、`ps`、`df`、`du`。 | +| Grep fidelity | Ports separator-fidelity behavior into the Windows native grep fallback, including context group separators and no synthetic `--` when context is not requested. | 将 grep separator 保真逻辑应用到 Windows native grep fallback,包括 context 分组分隔符,以及非 context 模式不生成额外 `--`。 | +| Rewrite surface | Extends rewrite/classification support for Windows-friendly command forms while keeping unsafe PowerShell object/pipeline semantics out of semantic rewrites. | 扩展 rewrite/classification 对 Windows 常见命令形态的支持,同时避免把不安全的 PowerShell 对象/管道语义错误改写为 RTK 语义命令。 | +| Batch and script safety | Distinguishes `.ps1` transport from `.cmd`/`.bat` transport. `.ps1` arguments are preserved through `-File`; batch wrappers reject unsafe cmd metacharacters instead of pretending to provide exact native argv semantics. | 区分 `.ps1` transport 与 `.cmd`/`.bat` transport。`.ps1` 参数通过 `-File` 保真传递;batch wrapper 对不安全 cmd 元字符拒绝执行,不声称具备完全 native argv 语义。 | +| PowerShell encoded limits | Adds explicit rejection for oversized generated PowerShell transport source, with guidance to use `.ps1` / `-File` rather than truncating or partially executing. | 对过大的生成式 PowerShell transport source 显式拒绝,并提示使用 `.ps1` / `-File`,避免截断或部分执行。 | +| Codex analytics provider | Adds a Codex session provider for discover/session analytics, including SQLite/WAL-oriented diagnostics and safer row ordering. | 新增 Codex 会话 provider,用于 discover/session 分析,包含 SQLite/WAL 相关诊断和更安全的行排序。 | +| Upstream correctness reconciliation | Reconciles selected upstream correctness fixes without replacing local Windows-native modules wholesale: TOML lossiness fallback, custom-filter trust hardening, Cargo JSON diagnostics, UTF-8 analytics safety, ccusage `period` aliases, and Git checkout summaries. | 选择性吸收主仓库正确性修复,同时避免整文件覆盖本地 Windows-native 模块:TOML lossiness fallback、自定义 filter trust 加固、Cargo JSON diagnostics、UTF-8 analytics 安全、ccusage `period` 兼容、Git checkout 摘要等。 | +| Windows-native acceptance coverage | Adds a repository-level executable acceptance suite with fixed fixtures. The suite covers PowerShell cmdlets, native commands, rewrite behavior, fallback transport, `.ps1`/`.cmd` argv, UNC paths, `\\?\` extended-length paths, Unicode paths, and oversized implicit PowerShell transport rejection. | 新增仓库级 exe 验收套件与固定夹具。覆盖 PowerShell cmdlet、native 命令、rewrite 行为、fallback transport、`.ps1`/`.cmd` argv、UNC 路径、`\\?\` 长路径、Unicode 路径、以及过大的隐式 PowerShell transport 拒绝边界。 | -rtk filters and compresses command outputs before they reach your LLM context. Single Rust binary, 100+ supported commands, <10ms overhead. +## Current Verification / 当前验证状态 -## Token Savings (30-min Claude Code Session) +The Windows-native compatibility target has been verified locally with the debug executable: -| Operation | Frequency | Standard | rtk | Savings | -|-----------|-----------|----------|-----|---------| -| `ls` / `tree` | 10x | 2,000 | 400 | -80% | -| `cat` / `read` | 20x | 40,000 | 12,000 | -70% | -| `grep` / `rg` | 8x | 16,000 | 3,200 | -80% | -| `git status` | 10x | 3,000 | 600 | -80% | -| `git diff` | 5x | 10,000 | 2,500 | -75% | -| `git log` | 5x | 2,500 | 500 | -80% | -| `git add/commit/push` | 8x | 1,600 | 120 | -92% | -| `cargo test` / `npm test` | 5x | 25,000 | 2,500 | -90% | -| `ruff check` | 3x | 3,000 | 600 | -80% | -| `pytest` | 4x | 8,000 | 800 | -90% | -| `go test` | 3x | 6,000 | 600 | -90% | -| `docker ps` | 3x | 900 | 180 | -80% | -| **Total** | | **~118,000** | **~23,900** | **-80%** | - -> Estimates based on medium-sized TypeScript/Rust projects. Actual savings vary by project size. - -## Installation - -### Homebrew (recommended) - -```bash -brew install rtk -``` - -### Quick Install (Linux/macOS) - -```bash -curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/refs/heads/master/install.sh | sh -``` - -> Installs to `~/.local/bin`. Add to PATH if needed: -> ```bash -> echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc # or ~/.zshrc -> ``` - -### Cargo - -```bash -cargo install --git https://github.com/rtk-ai/rtk -``` - -### Pre-built Binaries - -Download from [releases](https://github.com/rtk-ai/rtk/releases): -- macOS: `rtk-x86_64-apple-darwin.tar.gz` / `rtk-aarch64-apple-darwin.tar.gz` -- Linux: `rtk-x86_64-unknown-linux-musl.tar.gz` / `rtk-aarch64-unknown-linux-gnu.tar.gz` -- Windows: `rtk-x86_64-pc-windows-msvc.zip` - -> **Windows users**: Extract the zip and place `rtk.exe` somewhere in your PATH (e.g. `C:\Users\\.local\bin`). Run RTK from **Command Prompt**, **PowerShell**, or **Windows Terminal** — do not double-click the `.exe` (it will flash and close). The full hook system works natively on Windows (and in [WSL](https://learn.microsoft.com/en-us/windows/wsl/install)). See [Windows setup](#windows) below for details. - -### Verify Installation - -```bash -rtk --version # Should show "rtk 0.28.2" -rtk gain # Should show token savings stats -``` - -> **Name collision warning**: Another project named "rtk" (Rust Type Kit) exists on crates.io. If `rtk gain` fails, you have the wrong package. Use `cargo install --git` above instead. - -## Quick Start - -```bash -# 1. Install for your AI tool -rtk init -g # Claude Code / Copilot (default) -rtk init -g --gemini # Gemini CLI -rtk init -g --codex # Codex (OpenAI) -rtk init -g --agent cursor # Cursor -rtk init -g --agent windsurf # Windsurf -rtk init --agent cline # Cline / Roo Code -rtk init --agent kilocode # Kilo Code -rtk init --agent antigravity # Google Antigravity -rtk init -g --agent pi # Pi -rtk init --agent hermes # Hermes -rtk init -g --agent droid # Factory Droid - -# 2. Restart your AI tool, then test -git status # Automatically rewritten to rtk git status -``` - -Hook-based agents rewrite Bash commands (e.g., `git status` -> `rtk git status`) before execution. Plugin-based agents, including Hermes, use their plugin API to rewrite commands before execution. The agent receives compact output without needing to call `rtk` explicitly. - -**Important:** the hook only runs on Bash tool calls. Claude Code built-in tools like `Read`, `Grep`, and `Glob` do not pass through the Bash hook, so they are not auto-rewritten. To get RTK's compact output for those workflows, use shell commands (`cat`/`head`/`tail`, `rg`/`grep`, `find`) or call `rtk read`, `rtk grep`, or `rtk find` directly. - -## How It Works - -``` - Without rtk: With rtk: - - Claude --git status--> shell --> git Claude --git status--> RTK --> git - ^ | ^ | | - | ~2,000 tokens (raw) | | ~200 tokens | filter | - +-----------------------------------+ +------- (filtered) ---+----------+ -``` - -Four strategies applied per command type: - -1. **Smart Filtering** - Removes noise (comments, whitespace, boilerplate) -2. **Grouping** - Aggregates similar items (files by directory, errors by type) -3. **Truncation** - Keeps relevant context, cuts redundancy -4. **Deduplication** - Collapses repeated log lines with counts - -## Commands - -### Files -```bash -rtk ls . # Token-optimized directory tree -rtk read file.rs # Smart file reading -rtk read file.rs -l aggressive # Signatures only (strips bodies) -rtk smart file.rs # 2-line heuristic code summary -rtk find "*.rs" . # Compact find results -rtk grep "pattern" . # Grouped search results -rtk diff file1 file2 # Condensed diff (exit 1 if files differ) -``` - -### Git -```bash -rtk git status # Compact status -rtk git log -n 10 # One-line commits -rtk git diff # Condensed diff -rtk git add # -> "ok" -rtk git commit -m "msg" # -> "ok abc1234" -rtk git push # -> "ok main" -rtk git pull # -> "ok 3 files +10 -2" -``` - -### GitHub CLI -```bash -rtk gh pr list # Compact PR listing -rtk gh pr view 42 # PR details + checks -rtk gh issue list # Compact issue listing -rtk gh run list # Workflow run status -``` - -### Test Runners -```bash -rtk jest # Jest compact (failures only) -rtk vitest # Vitest compact (failures only) -rtk playwright test # E2E results (failures only) -rtk pytest # Python tests (-90%) -rtk go test # Go tests (NDJSON, -90%) -rtk cargo test # Cargo tests (-90%) -rtk rake test # Ruby minitest (-90%) -rtk rspec # RSpec tests (JSON, -60%+) -rtk err # Filter errors only from any command -rtk test # Generic test wrapper - failures only (-90%) -``` - -### Build & Lint -```bash -rtk lint # ESLint grouped by rule/file -rtk lint biome # Supports other linters -rtk tsc # TypeScript errors grouped by file -rtk next build # Next.js build compact -rtk prettier --check . # Files needing formatting -rtk cargo build # Cargo build (-80%) -rtk cargo clippy # Cargo clippy (-80%) -rtk ruff check # Python linting (JSON, -80%) -rtk golangci-lint run # Go linting (JSON, -85%) -rtk rubocop # Ruby linting (JSON, -60%+) -``` - -### Package Managers -```bash -rtk pnpm list # Compact dependency tree -rtk uv run pytest # Preserve uv env, errors only -rtk pip list # Python packages (auto-detect uv) -rtk pip outdated # Outdated packages -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 -rtk docker images # Compact image list -rtk docker logs # Deduplicated logs -rtk docker compose ps # Compose services -rtk kubectl pods # Compact pod list -rtk kubectl logs # Deduplicated logs -rtk kubectl services # Compact service list -rtk oc get pods # OpenShift pod summary -rtk oc get services # OpenShift service list -rtk oc logs # Deduplicated logs -``` - -### Infrastructure as Code -```bash -rtk pulumi preview # Strip header/URL/duration noise -rtk pulumi up # Compact apply output -rtk pulumi destroy # Compact destroy output -rtk pulumi refresh # Drift summary -rtk pulumi stack # Stack metadata (strips owner/timestamps) -``` - -### Data & Analytics -```bash -rtk json config.json # Structure without values -rtk deps # Dependencies summary -rtk env -f AWS # Filtered env vars -rtk log app.log # Deduplicated logs -rtk curl # Truncate + save full output -rtk wget # Download, strip progress bars -rtk summary # Heuristic summary -rtk proxy # Raw passthrough + tracking -``` - -### Token Savings Analytics -```bash -rtk gain # Summary stats -rtk gain --graph # ASCII graph (last 30 days) -rtk gain --history # Recent command history -rtk gain --daily # Day-by-day breakdown -rtk gain --all --format json # JSON export for dashboards - -rtk discover # Find missed savings opportunities -rtk discover --all --since 7 # All projects, last 7 days - -rtk session # Show RTK adoption across recent sessions -``` - -## Global Flags - -```bash --u, --ultra-compact # ASCII icons, inline format (extra token savings) --v, --verbose # Increase verbosity (-v, -vv, -vvv) -``` - -## Examples - -**Directory listing:** -``` -# ls -la (45 lines, ~800 tokens) # rtk ls (12 lines, ~150 tokens) -drwxr-xr-x 15 user staff 480 ... my-project/ --rw-r--r-- 1 user staff 1234 ... +-- src/ (8 files) -... | +-- main.rs - +-- Cargo.toml -``` - -**Git operations:** -``` -# git push (15 lines, ~200 tokens) # rtk git push (1 line, ~10 tokens) -Enumerating objects: 5, done. ok main -Counting objects: 100% (5/5), done. -Delta compression using up to 8 threads -... -``` - -**Test output:** -``` -# cargo test (200+ lines on failure) # rtk test cargo test (~20 lines) -running 15 tests FAILED: 2/15 tests -test utils::test_parse ... ok test_edge_case: assertion failed -test utils::test_format ... ok test_overflow: panic at utils.rs:18 -... -``` - -## Auto-Rewrite Hook - -The most effective way to use rtk. The hook transparently intercepts Bash commands and rewrites them to rtk equivalents before execution. - -**Result**: 100% rtk adoption across all conversations and subagents, zero token overhead. - -**Scope note:** this only applies to Bash tool calls. Claude Code built-in tools such as `Read`, `Grep`, and `Glob` bypass the hook, so use shell commands or explicit `rtk` commands when you want RTK filtering there. - -### Setup - -```bash -rtk init -g # Install hook + RTK.md (recommended) -rtk init -g --opencode # OpenCode plugin (instead of Claude Code) -rtk init -g --auto-patch # Non-interactive (CI/CD) -rtk init -g --hook-only # Hook only, no RTK.md -rtk init --show # Verify installation -``` - -After install, **restart Claude Code**. - -## Windows - -RTK works fully on native Windows. Since **v0.37.2** the auto-rewrite hook runs as a **native binary command** (`rtk hook claude`) — no Unix shell, bash, or jq required — so commands are rewritten transparently on Command Prompt, PowerShell, and Windows Terminal, just like on Linux and macOS. - -### Native Windows +Windows native 兼容目标已使用本机 debug exe 验证: ```powershell -# 1. Download and extract rtk-x86_64-pc-windows-msvc.zip from releases -# 2. Add rtk.exe to your PATH (e.g. C:\Users\\.local\bin) -# 3. Initialize — installs the native binary hook -rtk init -g -``` - -**Upgrading from an older install?** If you set RTK up before v0.37.2 you may still have the legacy `rtk-rewrite.sh` shell hook (which does need a Unix shell). Re-run `rtk init -g` to migrate to the native binary hook. - -**Prerequisites**: some filters shell out to [ripgrep](https://github.com/BurntSushi/ripgrep) (`rg`). Install it and keep it on your PATH (e.g. `winget install BurntSushi.ripgrep.MSVC`) to avoid `Binary 'rg' not found on PATH` warnings. - -**Important**: Do not double-click `rtk.exe` — it is a CLI tool that prints usage and exits immediately. Always run it from a terminal (Command Prompt, PowerShell, or Windows Terminal). - -### WSL - -[WSL](https://learn.microsoft.com/en-us/windows/wsl/install) also works and behaves exactly like Linux: - -```bash -# Inside WSL -curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/refs/heads/master/install.sh | sh -rtk init -g +rtk proxy powershell -NoProfile -File scripts\windows-cargo.ps1 build --jobs 1 +rtk proxy powershell -NoProfile -ExecutionPolicy Bypass -File tests\windows_native_acceptance.ps1 +rtk proxy powershell -NoProfile -File scripts\windows-cargo.ps1 fmt --check +rtk proxy powershell -NoProfile -File scripts\windows-cargo.ps1 test --jobs 1 ``` -| Feature | Native Windows | WSL | -|---------|----------------|-----| -| Filters (cargo, git, etc.) | Full | Full | -| Auto-rewrite hook | Yes (native binary) | Yes | -| `rtk init -g` | Hook mode | Hook mode | -| `rtk gain` / analytics | Full | Full | - -## Supported AI Tools - -RTK supports 15 AI coding tools. Each integration rewrites shell commands to `rtk` equivalents for 60-90% token savings where the agent supports command interception. - -| Tool | Install | Method | -|------|---------|--------| -| **Claude Code** | `rtk init -g` | PreToolUse hook (native binary) | -| **GitHub Copilot (VS Code)** | `rtk init -g --copilot` | PreToolUse hook — transparent rewrite | -| **GitHub Copilot CLI** | `rtk init -g --copilot` | PreToolUse deny-with-suggestion (CLI limitation) | -| **Cursor** | `rtk init -g --agent cursor` | preToolUse hook (hooks.json) | -| **Gemini CLI** | `rtk init -g --gemini` | BeforeTool hook | -| **Codex** | `rtk init -g --codex` | AGENTS.md + RTK.md instructions | -| **Windsurf** | `rtk init -g --agent windsurf` | .windsurfrules (project-scoped) | -| **Cline / Roo Code** | `rtk init --agent cline` | .clinerules (project-scoped) | -| **OpenCode** | `rtk init -g --opencode` | Plugin TS (tool.execute.before) | -| **OpenClaw** | `openclaw plugins install ./openclaw` | Plugin TS (before_tool_call) | -| **Pi** | `rtk init -g --agent pi` (global) | TypeScript extension (tool_call) | -| **Hermes** | `rtk init --agent hermes` | Python plugin adapter (terminal command mutation via `rtk rewrite`) | -| **Mistral Vibe** | Planned ([#800](https://github.com/rtk-ai/rtk/issues/800)) | Blocked on upstream | -| **Kilo Code** | `rtk init --agent kilocode` | .kilocode/rules/rtk-rules.md (project-scoped) | -| **Google Antigravity** | `rtk init --agent antigravity` | .agents/rules/antigravity-rtk-rules.md (project-scoped) | -| **Factory Droid** | `rtk init -g --agent droid` (or per-project) | PreToolUse hook in `~/.factory/hooks.json` (matcher `Execute`) | - -For per-agent setup details, override controls, and graceful degradation, see the [Supported Agents guide](https://www.rtk-ai.app/guide/getting-started/supported-agents). The Hermes plugin source and tests live in `hooks/hermes/`; installed Hermes runtime files still live under `~/.hermes/plugins/rtk-rewrite/`. - -## Configuration - -`~/.config/rtk/config.toml` (macOS: `~/Library/Application Support/rtk/config.toml`): - -```toml -[hooks] -exclude_commands = ["curl", "playwright"] # skip rewrite for these - -[tee] -enabled = true # save raw output on failure (default: true) -mode = "failures" # "failures", "always", or "never" -``` - -When a command fails, RTK saves the full unfiltered output so the LLM can read it without re-executing: - -``` -FAILED: 2/15 tests -[full output: ~/.local/share/rtk/tee/1707753600_cargo_test.log] -``` - -For the full config reference (all sections, env vars, per-project filters), see the [Configuration guide](https://www.rtk-ai.app/guide/getting-started/configuration). - -### Uninstall - -```bash -rtk init -g --uninstall # Remove hook, RTK.md, settings.json entry -cargo uninstall rtk # Remove binary -brew uninstall rtk # If installed via Homebrew -``` - -## Documentation - -- **[rtk-ai.app/guide](https://www.rtk-ai.app/guide)** — full user guide (installation, supported agents, what gets optimized, analytics, configuration, troubleshooting) -- **[INSTALL.md](INSTALL.md)** — detailed installation reference -- **[ARCHITECTURE.md](docs/contributing/ARCHITECTURE.md)** — system design and technical decisions -- **[CONTRIBUTING.md](CONTRIBUTING.md)** — contribution guide -- **[SECURITY.md](SECURITY.md)** — security policy - -## Privacy & Telemetry - -RTK can collect **anonymous, aggregate usage metrics** once per day. Telemetry is **disabled by default** and requires **explicit opt-in consent** (GDPR Art. 6, 7) during `rtk init` or via `rtk telemetry enable`. This data helps us build a better product: identifying which commands need filters, which filters need improvement, and how much value RTK delivers. For the full list of fields, data handling, and contributor guidelines, see **[docs/TELEMETRY.md](docs/TELEMETRY.md)**. - -**What is collected and why:** - -| Category | Data | Why | -|----------|------|-----| -| Identity | Salted device hash (SHA-256, not reversible) | Count unique installations without tracking individuals | -| Environment | RTK version, OS, architecture, install method | Know which platforms to support and test | -| Usage volume | Command count (24h), total commands, tokens saved (24h/30d/total) | Measure adoption and value delivered | -| Quality | Top 5 passthrough commands (0% savings), parse failure count, commands with <30% savings | Identify missing filters and weak ones to improve | -| Ecosystem | Command category distribution (e.g. git 45%, cargo 20%, js 15%) | Prioritize filter development for popular ecosystems | -| Retention | Days since first use, active days in last 30 | Understand engagement and detect churn | -| Adoption | AI agent hook type (claude/gemini/codex), custom TOML filter count | Track integration coverage and DSL adoption | -| Configuration | Whether config.toml exists, number of excluded commands, project count | Understand user maturity and customization patterns | -| Features | Usage counts for meta-commands (gain, discover, proxy, verify) | Know which RTK features are valued vs unused | -| Economics | Estimated USD savings (based on API token pricing) | Quantify the value RTK provides to users | - -All data is **aggregate counts or anonymized command names** (first 3 words, no arguments). Top commands report only tool names (e.g. "git", "cargo"), never full command lines. - -**What is NOT collected:** source code, file paths, command arguments, secrets, environment variables, personal data, or repository contents. - -**Manage telemetry:** -```bash -rtk telemetry status # Check current consent state -rtk telemetry enable # Give consent (interactive prompt) -rtk telemetry disable # Withdraw consent — stops all collection immediately -rtk telemetry forget # Withdraw consent + delete all local data + request server-side erasure -``` - -**Override via environment:** -```bash -export RTK_TELEMETRY_DISABLED=1 # Blocks telemetry regardless of consent -``` - -## Star History - - - - - - Star History Chart - - - -## StarMapper - - - - - - StarMapper - - - -## Core team - -- **Patrick Szymkowiak** — Founder - [GitHub](https://github.com/pszymkowiak) · [LinkedIn](https://www.linkedin.com/in/patrick-szymkowiak/) -- **Florian Bruniaux** — Core contributor - [GitHub](https://github.com/FlorianBruniaux) · [LinkedIn](https://www.linkedin.com/in/florian-bruniaux-43408b83/) -- **Adrien Eppling** — Core contributor - [GitHub](https://github.com/aeppling) · [LinkedIn](https://www.linkedin.com/in/adrien-eppling/) -- **Nicolas Le Cam** — Core contributor - [Github](https://github.com/kush) · [LinkedIn](https://www.linkedin.com/in/nicolas-le-cam-386387160/) - -## Contributing - -Contributions welcome! Please open an issue or PR on [GitHub](https://github.com/rtk-ai/rtk). - -Join the community on [Discord](https://discord.gg/RySmvNF5kF). - -## License +Latest local result / 最新本地结果: -Apache License 2.0 - see [LICENSE](LICENSE) for details. +| Check | Result | +|---|---| +| Debug build / Debug 编译 | PASS | +| Windows native acceptance / Windows native 验收 | 83 passed, 0 skipped, 0 failed | +| Format check / 格式检查 | PASS | +| Rust tests / Rust 测试 | 2437 passed, 0 failed, 8 ignored | +| Integration tests / 集成测试 | 11 passed, 0 failed | -## Disclaimer +Non-Windows runtime CI is intentionally out of scope for this local Windows verification pass. Non-Windows behavior should be reviewed by comparing the platform-neutral diffs against the main repository and by running CI in the appropriate environment before release. -See [DISCLAIMER.md](DISCLAIMER.md). +非 Windows 运行时 CI 不属于本轮本机 Windows 验证范围。发布前应通过与主仓库的平台无关差异对比,以及在对应环境中运行 CI 来验证非 Windows 行为。 diff --git a/README_LOCAL.md b/README_LOCAL.md new file mode 100644 index 0000000000..f00b30ff48 --- /dev/null +++ b/README_LOCAL.md @@ -0,0 +1,52 @@ +# RTK Local Repository Notes / RTK 本仓库说明 + +This repository is a Windows-native compatibility fork/worktree of RTK. For the baseline project description, installation, general usage, and original command coverage, read the main repository README first: + +本仓库是 RTK 的 Windows native 兼容增强工作区/分支。基础项目介绍、安装方式、通用用法和原始命令覆盖范围,请先阅读主仓库 README: + +- Main README / 主仓库 README: https://github.com/fuxkCH/rtk#readme +- Local acceptance test / 本地验收测试: [`tests/windows_native_acceptance.ps1`](tests/windows_native_acceptance.ps1) +- Windows-native fixtures / Windows native 测试夹具: [`tests/fixtures/windows-native/`](tests/fixtures/windows-native/) + +## Feature Delta / 相对主仓库的功能变化 + +| Area | English | 中文 | +|---|---|---| +| Windows fallback transport | Adds a Windows fallback runner that preserves argv boundaries instead of rebuilding commands with unsafe string joins. Explicit shell hosts such as `powershell`, `pwsh`, and `cmd` run as direct argv calls. | 新增 Windows fallback runner,保留 argv 边界,避免用不安全的字符串拼接重构命令。`powershell`、`pwsh`、`cmd` 等显式 shell host 以直接 argv 方式执行。 | +| PowerShell cmdlet compatibility | Adds narrow, validated compatibility for common PowerShell shapes: `Get-Content`, `Select-String`, `Get-ChildItem`, and `Get-Command -CommandType Application`. Unsupported semantic shapes either use safe transport or fail closed instead of being guessed. | 新增常见 PowerShell 形态的窄口径兼容:`Get-Content`、`Select-String`、`Get-ChildItem`、`Get-Command -CommandType Application`。不安全或不等价的语义形态走安全 transport 或 fail-closed,不猜测执行。 | +| Windows native small commands | Adds or wires native RTK commands useful on Windows and for cross-platform agent habits: `which`, `pwd`, `head`, `tail`, `touch`, and `mkdir -p`. | 新增或接入 Windows 上常用、也符合跨平台 agent 习惯的小型 native 命令:`which`、`pwd`、`head`、`tail`、`touch`、`mkdir -p`。 | +| Existing Windows native baseline | Preserves and verifies the local Windows-native implementations for `ls`, `tree`, `wc`, Rust grep fallback, `ps`, `df`, and `du`. | 保留并验证本地已有 Windows-native 实现:`ls`、`tree`、`wc`、Rust grep fallback、`ps`、`df`、`du`。 | +| Grep fidelity | Ports separator-fidelity behavior into the Windows native grep fallback, including context group separators and no synthetic `--` when context is not requested. | 将 grep separator 保真逻辑应用到 Windows native grep fallback,包括 context 分组分隔符,以及非 context 模式不生成额外 `--`。 | +| Rewrite surface | Extends rewrite/classification support for Windows-friendly command forms while keeping unsafe PowerShell object/pipeline semantics out of semantic rewrites. | 扩展 rewrite/classification 对 Windows 常见命令形态的支持,同时避免把不安全的 PowerShell 对象/管道语义错误改写为 RTK 语义命令。 | +| Batch and script safety | Distinguishes `.ps1` transport from `.cmd`/`.bat` transport. `.ps1` arguments are preserved through `-File`; batch wrappers reject unsafe cmd metacharacters instead of pretending to provide exact native argv semantics. | 区分 `.ps1` transport 与 `.cmd`/`.bat` transport。`.ps1` 参数通过 `-File` 保真传递;batch wrapper 对不安全 cmd 元字符拒绝执行,不声称具备完全 native argv 语义。 | +| PowerShell encoded limits | Adds explicit rejection for oversized generated PowerShell transport source, with guidance to use `.ps1` / `-File` rather than truncating or partially executing. | 对过大的生成式 PowerShell transport source 显式拒绝,并提示使用 `.ps1` / `-File`,避免截断或部分执行。 | +| Codex analytics provider | Adds a Codex session provider for discover/session analytics, including SQLite/WAL-oriented diagnostics and safer row ordering. | 新增 Codex 会话 provider,用于 discover/session 分析,包含 SQLite/WAL 相关诊断和更安全的行排序。 | +| Upstream correctness reconciliation | Reconciles selected upstream correctness fixes without replacing local Windows-native modules wholesale: TOML lossiness fallback, custom-filter trust hardening, Cargo JSON diagnostics, UTF-8 analytics safety, ccusage `period` aliases, and Git checkout summaries. | 选择性吸收主仓库正确性修复,同时避免整文件覆盖本地 Windows-native 模块:TOML lossiness fallback、自定义 filter trust 加固、Cargo JSON diagnostics、UTF-8 analytics 安全、ccusage `period` 兼容、Git checkout 摘要等。 | +| Windows-native acceptance coverage | Adds a repository-level executable acceptance suite with fixed fixtures. The suite covers PowerShell cmdlets, native commands, rewrite behavior, fallback transport, `.ps1`/`.cmd` argv, UNC paths, `\\?\` extended-length paths, Unicode paths, and oversized implicit PowerShell transport rejection. | 新增仓库级 exe 验收套件与固定夹具。覆盖 PowerShell cmdlet、native 命令、rewrite 行为、fallback transport、`.ps1`/`.cmd` argv、UNC 路径、`\\?\` 长路径、Unicode 路径、以及过大的隐式 PowerShell transport 拒绝边界。 | + +## Current Verification / 当前验证状态 + +The Windows-native compatibility target has been verified locally with the debug executable: + +Windows native 兼容目标已使用本机 debug exe 验证: + +```powershell +rtk proxy powershell -NoProfile -File scripts\windows-cargo.ps1 build --jobs 1 +rtk proxy powershell -NoProfile -ExecutionPolicy Bypass -File tests\windows_native_acceptance.ps1 +rtk proxy powershell -NoProfile -File scripts\windows-cargo.ps1 fmt --check +rtk proxy powershell -NoProfile -File scripts\windows-cargo.ps1 test --jobs 1 +``` + +Latest local result / 最新本地结果: + +| Check | Result | +|---|---| +| Debug build / Debug 编译 | PASS | +| Windows native acceptance / Windows native 验收 | 83 passed, 0 skipped, 0 failed | +| Format check / 格式检查 | PASS | +| Rust tests / Rust 测试 | 2437 passed, 0 failed, 8 ignored | +| Integration tests / 集成测试 | 11 passed, 0 failed | + +Non-Windows runtime CI is intentionally out of scope for this local Windows verification pass. Non-Windows behavior should be reviewed by comparing the platform-neutral diffs against the main repository and by running CI in the appropriate environment before release. + +非 Windows 运行时 CI 不属于本轮本机 Windows 验证范围。发布前应通过与主仓库的平台无关差异对比,以及在对应环境中运行 CI 来验证非 Windows 行为。 diff --git a/docs/guide/getting-started/configuration.md b/docs/guide/getting-started/configuration.md index 2fedb1fd93..da76023911 100644 --- a/docs/guide/getting-started/configuration.md +++ b/docs/guide/getting-started/configuration.md @@ -127,24 +127,6 @@ export RTK_TELEMETRY_DISABLED=1 enabled = false ``` -## Custom filters +## Per-project filters -Add your own filters (or override built-ins) in either location: - -- **Project-local** — `.rtk/filters.toml` in your project root (committed with the repo) -- **User-global** — `~/.config/rtk/filters.toml` (applies to every project) - -See [`src/filters/README.md`](https://github.com/rtk-ai/rtk/blob/master/src/filters/README.md) for the full TOML DSL reference. - -### Trusting custom filters - -Because a filter can rewrite what your AI assistant sees, custom filter files are **not applied until you trust them**. An untrusted (or edited) filter file is skipped silently on the command path. You review and manage trust with explicit commands: - -```bash -rtk trust # shows each filter and asks to confirm (--yes to skip the prompt) -rtk untrust # revokes trust -``` - -`rtk init` also detects existing filters and lets you enable them — interactively, or non-interactively with `--trust-filters` / `--no-trust-filters`. Trust is tied to the file's contents (SHA-256), so editing a trusted file requires re-running `rtk trust`. - -> **Upgrading:** earlier versions applied `~/.config/rtk/filters.toml` without trust. After upgrading, the user-global file is gated like project filters — if you already relied on a global filter, run `rtk trust` once to re-enable it. +Create `.rtk/filters.toml` in your project root to add custom filters or override built-ins. See [`src/filters/README.md`](https://github.com/rtk-ai/rtk/blob/master/src/filters/README.md) for the full TOML DSL reference. diff --git a/docs/guide/getting-started/supported-agents.md b/docs/guide/getting-started/supported-agents.md index 1c594d1c5a..d5a0ad87c7 100644 --- a/docs/guide/getting-started/supported-agents.md +++ b/docs/guide/getting-started/supported-agents.md @@ -1,6 +1,6 @@ --- title: Supported Agents -description: How to integrate RTK with Claude Code, Cursor, Copilot, Cline, Windsurf, Codex, OpenCode, Hermes, Kilo Code, Antigravity, and Factory Droid +description: How to integrate RTK with Claude Code, Cursor, Copilot, Cline, Windsurf, Codex, OpenCode, Hermes, Kilo Code, and Antigravity sidebar: order: 3 --- @@ -37,7 +37,6 @@ Agent runs "cargo test" | OpenClaw | TypeScript plugin (`before_tool_call`) | Yes | | Pi | TypeScript extension (`tool_call` event) | Yes | | Hermes | Python plugin (`terminal` command mutation) | Yes | -| Factory Droid | Shell hook (`PreToolUse`, matcher `Execute`) | Yes | | Cline / Roo Code | Rules file (prompt-level) | N/A | | Windsurf | Rules file (prompt-level) | N/A | | Codex CLI | AGENTS.md instructions | N/A | @@ -138,26 +137,6 @@ Creates `~/.hermes/plugins/rtk-rewrite/` and enables it through `plugins.enabled The plugin fails open. If `rtk` is missing at load time, the hook is not registered. If `rtk rewrite` errors, the tool is not `terminal`, the payload has no string `command`, or the plugin raises an exception, Hermes runs the original command unchanged. The same `rtk rewrite` limitations apply: already-prefixed `rtk` commands, compound shell commands, heredocs, and commands without filters are not rewritten. -### Factory Droid - -```bash -rtk init -g --agent droid # user-scoped (~/.factory/hooks.json) -rtk init --agent droid # project-scoped (.factory/hooks.json, commit to share) -``` - -Installs a `PreToolUse` hook (matcher `Execute`) into Droid's canonical `hooks.json` — falling back to the `hooks` key of `settings.json` only when that file already carries live `PreToolUse` hooks. Respects `$FACTORY_HOME_OVERRIDE`. - -RTK honors Droid's own permission lists, never another agent's settings. Commands matching an explicit `commandDenylist` or `commandBlocklist` entry — read from all four settings scopes (`~/.factory/settings.json`, `~/.factory/settings.local.json`, `.factory/settings.json`, `.factory/settings.local.json`) — are left untouched so Droid's native confirmation or block fires on the original command. Every other command is rewritten via `updatedInput` with **no** permission decision: Droid's native flow (allowlist, autonomy level, other hooks) decides on the rewritten command. To auto-run rewritten read-only commands, add `rtk`-prefixed entries (e.g. `rtk git status`) to your `commandAllowlist`. - -Uninstall: - -```bash -rtk init --uninstall -g --agent droid -rtk init --uninstall --agent droid -``` - -Removes only RTK's hook entry; other hooks and settings are untouched. - ### Cline / Roo Code ```bash diff --git a/docs/rtk-codex-windows-native-next-plan-review-codex.md b/docs/rtk-codex-windows-native-next-plan-review-codex.md new file mode 100644 index 0000000000..a460d13466 --- /dev/null +++ b/docs/rtk-codex-windows-native-next-plan-review-codex.md @@ -0,0 +1,283 @@ +# RTK Codex Windows Native Next Plan Review (Codex) + +> Review date: 2026-07-10 +> +> Reviewed document: `docs/rtk-codex-windows-native-next-plan.md` +> +> Review scope: plan correctness, Windows argv and PowerShell transport safety, preservation of the existing local Windows-native commands, upstream absorption feasibility, and whether the proposed verification can prove the stated guarantees. + +## 1. Review Conclusion + +The plan has the right top-level priorities: preserve the existing Windows-native implementations, keep transport separate from semantic optimization, use direct argv for resolved executables, and selectively reconcile upstream rather than replacing local files wholesale. + +It is not ready for execution yet. The main blockers are: + +1. Raw PowerShell rewrite still depends on the existing Bash-oriented lexer and has no shell-correct rewrite renderer. +2. The Codex SQLite provider is modeled as file sessions even though the observed database stores row-level timestamps and thread IDs. +3. Upstream absorption is listed as a matrix but has no executable U0/U1/U2 tasks. +4. Several proposed compatibility mappings are not semantically equivalent (`Get-Command`, recursive `Get-ChildItem`, `head`, and `Get-Content -`). +5. The plan overstates what can be guaranteed for `.cmd` / `.bat` argv transport and introduces an unjustified `ExecutionPolicy Bypass` option. + +These issues should be corrected in the plan before implementation begins. + +## 2. Findings + +### [P0] F1: PowerShell rewrite incorrectly reuses the Bash-oriented lexer + +**Plan evidence:** + +- Section 3.2 says to use quote-aware tokens from `src/discover/lexer.rs`. +- Compound PowerShell pipelines are intended to be recognized before generic rewrite handling. + +**Code evidence:** + +- `src/discover/lexer.rs::tokenize_inner` treats backslash as an escape introducer outside single quotes. +- `src/discover/lexer.rs::shell_split` implements Bash-like backslash and quote behavior. +- PowerShell instead uses backtick escaping, doubled single quotes, different double-quote interpolation, here-strings, and other grammar that the existing lexer does not model. + +The plan also does not define how rewritten paths and patterns containing spaces, quotes, empty strings, trailing backslashes, or metacharacters are rendered back into a PowerShell command string. Parsing safely is not enough if the rewrite output is re-quoted incorrectly. + +**Required correction:** + +- Direct `rtk Get-*` invocation should parse existing argv without a shell lexer. +- Raw hook/rewrite input needs a dedicated conservative PowerShell tokenizer and renderer. +- Unsupported, ambiguous, or non-round-trippable input must return no rewrite. +- Add parse-render-parse tests for spaces, empty arguments, quotes, backticks, Unicode, UNC paths, and trailing backslashes. + +### [P0] F2: CodexProvider uses the wrong session and time-filter model + +**Plan evidence:** + +- The plan proposes `:` as `ExtractedCommand.session_id`. +- `since_days` is applied to candidate SQLite file modification time. +- It proposes keeping the current file-oriented `SessionProvider` trait unless a display name is needed. + +**Observed database evidence:** + +The local read-only `~/.codex/logs_2.sqlite` schema contains a `logs` table with, among other fields: + +```text +id INTEGER PRIMARY KEY AUTOINCREMENT +ts INTEGER NOT NULL +ts_nanos INTEGER NOT NULL +feedback_log_body TEXT +thread_id TEXT +process_uuid TEXT +``` + +Recent `ToolCall: shell_command` rows carry the actual Codex `thread_id` and row timestamp. + +Using database mtime for `since_days` is incorrect because an actively written database remains new while containing old history. Assigning every row a separate session ID destroys per-thread grouping and sequence analytics. + +The current `SessionProvider` contract returns `Vec` and then extracts a whole file. A single SQLite file containing many row-level sessions does not fit that model cleanly. + +**Required correction:** + +- Filter rows with `WHERE ts >= ?`. +- Group and identify sessions with `thread_id`. +- Order commands with `(ts, ts_nanos, id)`. +- Change or extend the provider abstraction so a provider can return logical sessions rather than only files. +- Define project filtering for Codex explicitly instead of silently inheriting Claude's path-based behavior. +- Do not automatically scan every `*.sqlite` under Codex home; unknown databases should be diagnostic candidates or explicit overrides. + +### [P0] F3: Upstream absorption has no executable implementation tasks + +The selective upstream matrix correctly classifies TOML, trust, grep, Cargo, analytics, signal propagation, checkout, hooks, Droid, and PHP. However, the detailed implementation section begins with C0.5 and contains no detailed B0, U0, U1, or U2 tasks. + +This leaves the implementer without: + +- exact local files and final upstream source state to reconcile; +- failing regression tests to restore first; +- focused verification commands; +- protected-file diff checks for each port; +- commit boundaries and dependencies between TOML restoration and C0.5 edits. + +This is especially blocking because TOML lossiness and trust hardening are declared prerequisites for C0.5. + +**Required correction:** add detailed tasks for B0, U0-TOML, U0-trust, U1-grep, U1-Cargo, U1-analytics/ccusage, and U2-checkout. Each task must list files, tests, expected failure, minimal port, verification, protected native regression gate, and commit boundary. + +The upstream matrix should also record conflict risk and a fallback implementation strategy. Based on the current local diff, the initial risk assessment is: + +| Absorption item | Conflict risk | Reason | Plan B | +|------|------|------|------| +| TOML lossiness / fallback guard | High | both `src/main.rs` fallback and `src/core/toml_filter.rs` diverge substantially | reimplement the final `Lossiness` contract against local filter types instead of copying upstream blocks | +| custom-filter trust hardening | High | local hook and trust files have broad edits and deleted upstream behavior | port behavior and tests one invariant at a time; do not restore whole hook files | +| grep separator fidelity | High | local `search.rs` contains the Windows Rust grep fallback absent upstream | transplant only separator logic and regression tests into the local parser/output pipeline | +| Cargo JSON fixes | High | local `cargo_cmd.rs` removed a large upstream JSON-diagnostic path | reconstruct the final typed-diagnostic behavior in a separate task rather than applying a large historical diff | +| analytics UTF-8 / ccusage | Medium | focused files but local analytics also diverges | port the final char-safe helpers and aliases manually with regression fixtures | +| Git checkout | Medium | touches git dispatch, registry, rules, and guards but not native system modules | implement checkout as a new local handler using upstream tests as the contract | + +High conflict risk must not block C0.5 indefinitely. Each U0 prerequisite needs a bounded behavior-level Plan B and a checkpoint that can stop source-level porting once the required invariant is restored locally. + +### [P0] F4: Unsupported cmdlet fallback contradicts the parameter-table design + +The plan says unsupported semantic shapes can continue through safe PowerShell transport, while the renderer keeps parameter tokens bare only if they are present in the C1 per-cmdlet table. + +Legitimate but non-optimized forms such as these are therefore undefined: + +```powershell +rtk Get-Content -Raw file.txt +rtk Get-Content -Tail 20 file.txt +rtk Select-String -Context 2 pattern file.txt +``` + +If the table contains only optimized parameters, these forms become `RejectAmbiguous` and lose current fallback behavior. If every dash-prefixed token is accepted as a parameter, a literal filename beginning with `-` can be reinterpreted. + +**Required correction:** separate the semantic rewrite allowlist from a broader, explicit transport parameter schema. If broad transport is intentionally not supported, document that these bare forms require explicit `powershell -Command` and remove the promise that all static unsupported cmdlets transparently fall back. + +### [P1] F5: Windows `rtk run` is redefined without a compatibility decision + +The current Windows implementation joins positional `rtk run` arguments and treats them as a PowerShell script. The plan changes positional form into literal invocation argv and rejects operators, pipelines, variables, and scriptblocks. + +This is safer, but it is a behavior change. It also creates different positional semantics on Windows and Unix while the plan claims Unix behavior remains frozen. In addition, a resolvable positional program should use the same `DirectExternal` path as fallback instead of being unnecessarily rendered through PowerShell. + +**Required correction:** decide and document the public `rtk run` contract before C0.5: + +- `run -c