Compare commits

...
Author SHA1 Message Date
Patrick szymkowiak a0662776a8 fix: propagate exit codes in git diff, status+args, commit, and branch
4 P1 bugs where git exit codes were swallowed:
- git diff: failure silently printed empty stat output
- git status (with args): failure was filtered instead of propagated
- git commit: failure printed "FAILED" but returned Ok(()) breaking pre-commit hooks
- git branch (list mode): failure was silently ignored

All now follow the established pattern: eprint stderr, track raw==raw, process::exit(code).

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-03-16 15:15:40 +01:00
patrick szymkowiak 0414020d57 fix: raise output caps for P0 bugs (#617, #618, #620) (#630)
* fix: raise output caps for grep, git status, and parser fallback (#617, #618, #620)

- grep: per-file match cap 10 → 25, global max 50 → 200
- git status: file list caps 5/5/3 → 15/15/10
- parser fallback: truncate 500 → 2000 chars across all modules

These P0 bugs caused LLM retry loops when RTK returned less signal
than the raw command, making RTK worse than not using it.

Fixes #617, #618, #620

Signed-off-by: Patrick <patrick@rtk.ai>
Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* fix: update README example and add truncation tests for modified/untracked

- parser/README.md: update example from 500 → 2000 to match code
- git.rs: add test_format_status_modified_truncation (cap 15)
- git.rs: add test_format_status_untracked_truncation (cap 10)

Signed-off-by: Patrick <patrick@rtk.ai>
Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* refactor: extract output caps into [limits] config section

Move hardcoded caps into config.toml so users can tune them:

  [limits]
  grep_max_results = 200      # global grep match limit
  grep_max_per_file = 25      # per-file match limit
  status_max_files = 15       # staged/modified file list cap
  status_max_untracked = 10   # untracked file list cap
  passthrough_max_chars = 2000 # parser fallback truncation

All 8 modules now read from config::limits() instead of hardcoded
values. Defaults unchanged from previous commit.

Signed-off-by: Patrick <patrick@rtk.ai>
Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

---------

Signed-off-by: Patrick <patrick@rtk.ai>
Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-03-16 14:58:14 +01:00
patrick szymkowiak 5b57c4204a fix: P1 exit codes, grep regex perf, SQLite WAL (#631)
* fix: P1 exit codes, grep regex perf, SQLite concurrency

Exit code propagation (same pattern as existing modules):
- wget_cmd: run() and run_stdout() now exit on failure
- container: docker_logs, kubectl_pods/services/logs now check
  status before parsing JSON (was showing "No pods found" on error)
- pnpm_cmd: replace bail!() with eprint + process::exit in
  run_list and run_install

Performance:
- grep_cmd: compile context regex once before loop instead of
  per-line in clean_line() (was N compilations per grep call)

Data integrity:
- tracking: add PRAGMA journal_mode=WAL and busy_timeout=5000
  to prevent SQLite corruption with concurrent Claude Code instances

Signed-off-by: Patrick <patrick@rtk.ai>
Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* fix: address review findings on P1 fixes

- tracking: WAL pragma non-fatal (NFS/read-only compat)
- wget: forward raw stderr on failure, track raw==raw (no fake savings)
- container: remove stderr shadow in docker_logs, add empty-stderr
  guard on all 4 new exit code paths for consistency with prisma pattern

Signed-off-by: Patrick <patrick@rtk.ai>
Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

---------

Signed-off-by: Patrick <patrick@rtk.ai>
Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-03-16 14:58:02 +01:00
patrick szymkowiak 3005ebd0ad fix: 6 critical bugs — exit codes, unwrap, lazy regex (#626)
* fix: 6 critical bugs from security audit — exit codes, unwrap, regex

- container.rs: propagate docker ps/images exit code on failure
- container.rs: replace double-unwrap with let-else for kubectl pods/services
- mypy_cmd.rs: guard process::exit with failure check (was exiting on success)
- log_cmd.rs: move 5 Regex::new() to lazy_static (compiled every call)
- prisma_cmd.rs: replace 3x bail! with stderr print + process::exit
- golangci_cmd.rs: propagate exit code > 1 (config/build errors)

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* fix: address code review findings on critical bugs PR

- prisma: print both stdout and stderr on failure (Prisma errors go to stdout)
- golangci: handle signal kill (code=None) as fatal exit 130, print stderr on exit >1
- container: call timer.track() before process::exit on docker ps/images failure

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

---------

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-03-16 13:00:10 +01:00
patrick szymkowiak 8d8e188705 fix: trust boundary followup — TOML key typo + missing meta commands (#625)
- Fix `[filter.` → `[filters.` in risk summary (matches actual TOML DSL format)
- Add trust, untrust, session, rewrite to RTK_META_COMMANDS array
- Update test to skip trailing_var_arg commands (rewrite, session)

Follows up on PR #623 (SA-2025-RTK-002 trust boundary).

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-03-16 12:21:28 +01:00
patrick szymkowiak 3faa782304 security: trust boundary for project-local TOML filters (SA-2025-RTK-002) (#623)
* security: trust boundary for project-local TOML filters (SA-2025-RTK-002)

.rtk/filters.toml was loaded silently from CWD with highest priority,
allowing an attacker to commit malicious filters to a public repo that
hide security vulnerabilities or rewrite command output via replace and
match_output primitives. CVSS 7.0.

Implementation:
- New src/trust.rs: SHA-256 trust store in ~/.local/share/rtk/
- Trust gate in toml_filter::load(): untrusted filters are SKIPPED
- rtk trust: review + trust project-local filters (stores hash)
- rtk untrust: revoke trust
- rtk trust --list: show all trusted projects
- Content change detection: modified filters auto-rejected
- RTK_TRUST_PROJECT_FILTERS=1 env var override for CI pipelines
- 9 unit tests covering all trust states

Security model: untrusted = skip (not "warn and load"). Zero attack
surface when untrusted. Re-review required on any content change.

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* security: harden trust boundary after code review audit

Address 3 critical and 4 important findings from security review:

Critical fixes:
- rtk verify: add trust gate before reading project-local filters
  (was executing untrusted filter regex via collect_test_outcomes)
- TOCTOU: read .rtk/filters.toml once in rtk trust, hash in-memory
  buffer (prevents file swap between display and hash storage)
- canonical_key: remove fallback path join, fail-closed if
  canonicalize fails (prevents symlink injection)

Important fixes:
- RTK_TRUST_PROJECT_FILTERS=1 now requires CI env var co-check
  (CI, GITHUB_ACTIONS, GITLAB_CI, JENKINS_URL, BUILDKITE)
  to prevent .envrc injection attacks
- Corrupt trust store now logs warning instead of silent fallback
- trusted_at date display uses safe .get(..10) instead of panicking slice

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* fix: rtk untrust graceful when .rtk/filters.toml missing

Previously rtk untrust failed with a canonicalize error if the filter
file had been deleted. Now falls back gracefully with "No trust entry
found" message.

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

---------

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-03-16 11:48:46 +01:00
patrick szymkowiak 8e85d676d7 fix: git log --oneline regression drops commits (#619)
* fix: git log --oneline regression drops commits

When user passes --oneline, --pretty, or --format, RTK correctly skips
injecting its custom format with ---END--- markers. However,
filter_log_output() still tried to split on ---END---, treating the
entire output as a single block and only preserving 2 lines.

Add user_format parameter to filter_log_output: when true, use simple
line-based truncation instead of ---END--- block splitting.

Fixes regression introduced in PR #546 (commit c3416eb).

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

* chore: add call-site analysis rule to code-reviewer agent

After the git log --oneline regression (PR #546), add a mandatory
review step: trace all callers of modified functions and verify every
input variant has a test. This prevents regressions where a function
is changed but only one code path is tested.

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>

---------

Signed-off-by: Patrick szymkowiak <patrick.szymkowiak@innovtech.eu>
2026-03-16 11:02:43 +01:00
21 changed files with 1033 additions and 146 deletions

No files matched your search

+29 -4
View File
@@ -32,10 +32,11 @@ main.rs (Commands enum + routing)
## Review Process
1. **Context**: Identify which module changed, what command it affects, token savings claim
2. **Static patterns**: Check for RTK anti-patterns (unwrap, non-lazy regex, async)
3. **Token savings**: Verify savings claim is tested with real fixture
4. **Cross-platform**: Shell escaping, path separators, ANSI codes
5. **Structured feedback**: 🔴 Critical → 🟡 Important → 🟢 Suggestions
2. **Call-site analysis**: Trace ALL callers of modified functions, list every input variant, verify each has a test
3. **Static patterns**: Check for RTK anti-patterns (unwrap, non-lazy regex, async)
4. **Token savings**: Verify savings claim is tested with real fixture
5. **Cross-platform**: Shell escaping, path separators, ANSI codes
6. **Structured feedback**: 🔴 Critical → 🟡 Important → 🟢 Suggestions
## RTK-Specific Red Flags
@@ -198,6 +199,29 @@ fix_here
| 🔴 | file.rs | 45 | lazy_static! |
```
## Call-Site Analysis (🔴 MANDATORY)
When reviewing a function change, **always trace upstream to every call site** and verify that all input variants are tested.
**Why this rule exists:** PR #546 modified `filter_log_output()` to split on `---END---` markers, but only tested the code path where RTK injects those markers. The other path (`--oneline`, `--pretty`, `--format`) never has `---END---` markers — the entire output became a single block, dropping all but 2 commits. This shipped to develop and was only caught during release review.
**Process:**
1. For every modified function, grep all call sites: `Grep pattern="function_name(" type="rust"`
2. For each call site, identify the `if/else` or `match` branch that leads to it
3. List every distinct input shape the function can receive
4. Verify a test exists for EACH input shape — not just the happy path
5. If a test is missing, flag it as 🔴 Critical
**Example (git log):**
```
run_log() has 2 paths:
- has_format_flag=false → injects ---END--- → filter_log_output sees blocks
- has_format_flag=true → no ---END--- → filter_log_output sees raw lines
Both paths MUST have tests.
```
**Rule of thumb:** If a function's caller has an `if/else` that changes the data flowing in, each branch needs its own test in the callee.
## Adversarial Questions for RTK
1. **Savings**: If I run `count_tokens(input)` vs `count_tokens(output)` — is savings ≥60%?
@@ -207,6 +231,7 @@ fix_here
5. **Cross-platform**: Will this regex work on Windows CRLF output?
6. **ANSI**: Does the filter handle ANSI escape codes in input?
7. **Fixture**: Is the test using real output from the actual command?
8. **Call sites**: Have ALL callers been traced? Does each input variant have a test?
## The New Dev Test (RTK variant)
+35
View File
@@ -16,6 +16,8 @@ pub struct Config {
pub telemetry: TelemetryConfig,
#[serde(default)]
pub hooks: HooksConfig,
#[serde(default)]
pub limits: LimitsConfig,
}
#[derive(Debug, Serialize, Deserialize, Default)]
@@ -94,6 +96,39 @@ impl Default for TelemetryConfig {
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct LimitsConfig {
/// Max total grep results to show (default: 200)
pub grep_max_results: usize,
/// Max matches per file in grep output (default: 25)
pub grep_max_per_file: usize,
/// Max staged/modified files shown in git status (default: 15)
pub status_max_files: usize,
/// Max untracked files shown in git status (default: 10)
pub status_max_untracked: usize,
/// Max chars for parser passthrough fallback (default: 2000)
pub passthrough_max_chars: usize,
}
impl Default for LimitsConfig {
fn default() -> Self {
Self {
grep_max_results: 200,
grep_max_per_file: 25,
status_max_files: 15,
status_max_untracked: 10,
passthrough_max_chars: 2000,
}
}
}
/// Get limits config. Falls back to defaults if config can't be loaded.
pub fn limits() -> LimitsConfig {
Config::load()
.map(|c| c.limits)
.unwrap_or_default()
}
/// Check if telemetry is enabled in config. Returns None if config can't be loaded.
pub fn telemetry_enabled() -> Option<bool> {
Config::load().ok().map(|c| c.telemetry.enabled)
+64 -10
View File
@@ -42,6 +42,13 @@ fn docker_ps(_verbose: u8) -> Result<()> {
.output()
.context("Failed to run docker ps")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
eprint!("{}", stderr);
timer.track("docker ps", "rtk docker ps", &raw, &raw);
std::process::exit(output.status.code().unwrap_or(1));
}
let stdout = String::from_utf8_lossy(&output.stdout);
let mut rtk = String::new();
@@ -95,6 +102,13 @@ fn docker_images(_verbose: u8) -> Result<()> {
.output()
.context("Failed to run docker images")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
eprint!("{}", stderr);
timer.track("docker images", "rtk docker images", &raw, &raw);
std::process::exit(output.status.code().unwrap_or(1));
}
let stdout = String::from_utf8_lossy(&output.stdout);
let lines: Vec<&str> = stdout.lines().collect();
let mut rtk = String::new();
@@ -169,6 +183,19 @@ fn docker_logs(args: &[String], _verbose: u8) -> Result<()> {
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
if !output.status.success() {
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track(
&format!("docker logs {}", container),
"rtk docker logs",
&raw,
&raw,
);
std::process::exit(output.status.code().unwrap_or(1));
}
let analyzed = crate::log_cmd::run_stdin_str(&raw);
let rtk = format!("🐳 Logs for {}:\n{}", container, analyzed);
println!("{}", rtk);
@@ -194,6 +221,15 @@ fn kubectl_pods(args: &[String], _verbose: u8) -> Result<()> {
let raw = String::from_utf8_lossy(&output.stdout).to_string();
let mut rtk = String::new();
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track("kubectl get pods", "rtk kubectl pods", &raw, &raw);
std::process::exit(output.status.code().unwrap_or(1));
}
let json: serde_json::Value = match serde_json::from_str(&raw) {
Ok(v) => v,
Err(_) => {
@@ -204,15 +240,12 @@ fn kubectl_pods(args: &[String], _verbose: u8) -> Result<()> {
}
};
let items = json["items"].as_array();
if items.is_none() || items.unwrap().is_empty() {
let Some(pods) = json["items"].as_array().filter(|a| !a.is_empty()) else {
rtk.push_str("☸️ No pods found");
println!("{}", rtk);
timer.track("kubectl get pods", "rtk kubectl pods", &raw, &rtk);
return Ok(());
}
let pods = items.unwrap();
};
let (mut running, mut pending, mut failed, mut restarts_total) = (0, 0, 0, 0i64);
let mut issues: Vec<String> = Vec::new();
@@ -295,6 +328,15 @@ fn kubectl_services(args: &[String], _verbose: u8) -> Result<()> {
let raw = String::from_utf8_lossy(&output.stdout).to_string();
let mut rtk = String::new();
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track("kubectl get svc", "rtk kubectl svc", &raw, &raw);
std::process::exit(output.status.code().unwrap_or(1));
}
let json: serde_json::Value = match serde_json::from_str(&raw) {
Ok(v) => v,
Err(_) => {
@@ -305,15 +347,12 @@ fn kubectl_services(args: &[String], _verbose: u8) -> Result<()> {
}
};
let items = json["items"].as_array();
if items.is_none() || items.unwrap().is_empty() {
let Some(services) = json["items"].as_array().filter(|a| !a.is_empty()) else {
rtk.push_str("☸️ No services found");
println!("{}", rtk);
timer.track("kubectl get svc", "rtk kubectl svc", &raw, &rtk);
return Ok(());
}
let services = items.unwrap();
};
rtk.push_str(&format!("☸️ {} services:\n", services.len()));
for svc in services.iter().take(15) {
@@ -373,6 +412,21 @@ fn kubectl_logs(args: &[String], _verbose: u8) -> Result<()> {
let output = cmd.output().context("Failed to run kubectl logs")?;
let raw = String::from_utf8_lossy(&output.stdout).to_string();
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track(
&format!("kubectl logs {}", pod),
"rtk kubectl logs",
&raw,
&raw,
);
std::process::exit(output.status.code().unwrap_or(1));
}
let analyzed = crate::log_cmd::run_stdin_str(&raw);
let rtk = format!("☸️ Logs for {}:\n{}", pod, analyzed);
println!("{}", rtk);
+178 -42
View File
@@ -1,3 +1,4 @@
use crate::config;
use crate::tracking;
use crate::utils::resolved_command;
use anyhow::{Context, Result};
@@ -111,6 +112,21 @@ fn run_diff(
let output = cmd.output().context("Failed to run git diff")?;
let stat_stdout = String::from_utf8_lossy(&output.stdout);
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
let raw = stat_stdout.to_string();
timer.track(
&format!("git diff {}", args.join(" ")),
&format!("rtk git diff {}", args.join(" ")),
&raw,
&raw,
);
std::process::exit(output.status.code().unwrap_or(1));
}
if verbose > 0 {
eprintln!("Git diff summary:");
}
@@ -411,7 +427,7 @@ fn run_log(
}
// Post-process: truncate long messages, cap lines only if RTK set the default
let filtered = filter_log_output(&stdout, limit, user_set_limit);
let filtered = filter_log_output(&stdout, limit, user_set_limit, has_format_flag);
println!("{}", filtered);
timer.track(
@@ -469,10 +485,28 @@ fn parse_user_limit(args: &[String]) -> Option<usize> {
/// so we skip line capping (git already returns exactly N commits) and use a
/// wider truncation threshold (120 chars) to preserve commit context that LLMs
/// need for rebase/squash operations.
fn filter_log_output(output: &str, limit: usize, user_set_limit: bool) -> String {
fn filter_log_output(
output: &str,
limit: usize,
user_set_limit: bool,
user_format: bool,
) -> String {
let truncate_width = if user_set_limit { 120 } else { 80 };
// Split output into commit blocks separated by ---END---
// When user specified their own format (--oneline, --pretty, --format),
// RTK did not inject ---END--- markers. Use simple line-based truncation.
if user_format {
let lines: Vec<&str> = output.lines().collect();
let max_lines = if user_set_limit { lines.len() } else { limit };
return lines
.iter()
.take(max_lines)
.map(|l| truncate_line(l, truncate_width))
.collect::<Vec<_>>()
.join("\n");
}
// RTK injected format: split output into commit blocks separated by ---END---
let commits: Vec<&str> = output.split("---END---").collect();
let max_commits = if user_set_limit { commits.len() } else { limit };
@@ -574,33 +608,46 @@ fn format_status_output(porcelain: &str) -> String {
}
// Build summary
let limits = config::limits();
let max_files = limits.status_max_files;
let max_untracked = limits.status_max_untracked;
if staged > 0 {
output.push_str(&format!("✅ Staged: {} files\n", staged));
for f in staged_files.iter().take(5) {
for f in staged_files.iter().take(max_files) {
output.push_str(&format!(" {}\n", f));
}
if staged_files.len() > 5 {
output.push_str(&format!(" ... +{} more\n", staged_files.len() - 5));
if staged_files.len() > max_files {
output.push_str(&format!(
" ... +{} more\n",
staged_files.len() - max_files
));
}
}
if modified > 0 {
output.push_str(&format!("📝 Modified: {} files\n", modified));
for f in modified_files.iter().take(5) {
for f in modified_files.iter().take(max_files) {
output.push_str(&format!(" {}\n", f));
}
if modified_files.len() > 5 {
output.push_str(&format!(" ... +{} more\n", modified_files.len() - 5));
if modified_files.len() > max_files {
output.push_str(&format!(
" ... +{} more\n",
modified_files.len() - max_files
));
}
}
if untracked > 0 {
output.push_str(&format!("❓ Untracked: {} files\n", untracked));
for f in untracked_files.iter().take(3) {
for f in untracked_files.iter().take(max_untracked) {
output.push_str(&format!(" {}\n", f));
}
if untracked_files.len() > 3 {
output.push_str(&format!(" ... +{} more\n", untracked_files.len() - 3));
if untracked_files.len() > max_untracked {
output.push_str(&format!(
" ... +{} more\n",
untracked_files.len() - max_untracked
));
}
}
@@ -662,6 +709,20 @@ fn run_status(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
if !output.status.success() {
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
let raw = stdout.to_string();
timer.track(
&format!("git status {}", args.join(" ")),
&format!("rtk git status {}", args.join(" ")),
&raw,
&raw,
);
std::process::exit(output.status.code().unwrap_or(1));
}
if verbose > 0 || !stderr.is_empty() {
eprint!("{}", stderr);
}
@@ -841,13 +902,14 @@ fn run_commit(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
"ok (nothing to commit)",
);
} else {
eprintln!("FAILED: git commit");
if !stderr.trim().is_empty() {
eprintln!("{}", stderr);
eprint!("{}", stderr);
}
if !stdout.trim().is_empty() {
eprintln!("{}", stdout);
eprint!("{}", stdout);
}
timer.track(&original_cmd, "rtk git commit", &raw_output, &raw_output);
std::process::exit(output.status.code().unwrap_or(1));
}
}
@@ -1085,6 +1147,20 @@ fn run_branch(args: &[String], verbose: u8, global_args: &[String]) -> Result<()
let stdout = String::from_utf8_lossy(&output.stdout);
let raw = stdout.to_string();
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track(
&format!("git branch {}", args.join(" ")),
&format!("rtk git branch {}", args.join(" ")),
&raw,
&raw,
);
std::process::exit(output.status.code().unwrap_or(1));
}
let filtered = filter_branch_output(&stdout);
println!("{}", filtered);
@@ -1672,23 +1748,48 @@ A added.rs
#[test]
fn test_format_status_output_truncation() {
// Test that >5 staged files show "... +N more"
let porcelain = r#"## main
M file1.rs
M file2.rs
M file3.rs
M file4.rs
M file5.rs
M file6.rs
M file7.rs
"#;
let result = format_status_output(porcelain);
assert!(result.contains("✅ Staged: 7 files"));
// Test that >15 staged files show "... +N more"
let mut porcelain = String::from("## main\n");
for i in 1..=20 {
porcelain.push_str(&format!("M file{}.rs\n", i));
}
let result = format_status_output(&porcelain);
assert!(result.contains("✅ Staged: 20 files"));
assert!(result.contains("file1.rs"));
assert!(result.contains("file5.rs"));
assert!(result.contains("... +2 more"));
assert!(!result.contains("file6.rs"));
assert!(!result.contains("file7.rs"));
assert!(result.contains("file15.rs"));
assert!(result.contains("... +5 more"));
assert!(!result.contains("file16.rs"));
assert!(!result.contains("file20.rs"));
}
#[test]
fn test_format_status_modified_truncation() {
// Test that >15 modified files show "... +N more"
let mut porcelain = String::from("## main\n");
for i in 1..=20 {
porcelain.push_str(&format!(" M file{}.rs\n", i));
}
let result = format_status_output(&porcelain);
assert!(result.contains("📝 Modified: 20 files"));
assert!(result.contains("file1.rs"));
assert!(result.contains("file15.rs"));
assert!(result.contains("... +5 more"));
assert!(!result.contains("file16.rs"));
}
#[test]
fn test_format_status_untracked_truncation() {
// Test that >10 untracked files show "... +N more"
let mut porcelain = String::from("## main\n");
for i in 1..=15 {
porcelain.push_str(&format!("?? file{}.rs\n", i));
}
let result = format_status_output(&porcelain);
assert!(result.contains("❓ Untracked: 15 files"));
assert!(result.contains("file1.rs"));
assert!(result.contains("file10.rs"));
assert!(result.contains("... +5 more"));
assert!(!result.contains("file11.rs"));
}
#[test]
@@ -1701,7 +1802,7 @@ M file7.rs
#[test]
fn test_filter_log_output() {
let output = "abc1234 This is a commit message (2 days ago) <author>\n\n---END---\ndef5678 Another commit (1 week ago) <other>\n\n---END---\n";
let result = filter_log_output(output, 10, false);
let result = filter_log_output(output, 10, false, false);
assert!(result.contains("abc1234"));
assert!(result.contains("def5678"));
assert_eq!(result.lines().count(), 2);
@@ -1711,7 +1812,7 @@ M file7.rs
fn test_filter_log_output_with_body() {
// Commit with body: first non-trailer body line should appear indented
let output = "abc1234 feat: add feature (2 days ago) <author>\nBREAKING CHANGE: removed old API\nSigned-off-by: Author <a@b.com>\n---END---\ndef5678 fix: typo (1 day ago) <other>\n\n---END---\n";
let result = filter_log_output(output, 10, false);
let result = filter_log_output(output, 10, false, false);
assert!(result.contains("abc1234"));
assert!(result.contains("BREAKING CHANGE: removed old API"));
assert!(!result.contains("Signed-off-by:"));
@@ -1725,7 +1826,7 @@ M file7.rs
fn test_filter_log_output_skips_trailers() {
// Body with only trailers should not produce a body line
let output = "abc1234 chore: bump (1 day ago) <bot>\nSigned-off-by: Bot <bot@ci>\nCo-authored-by: Human <h@b>\n---END---\n";
let result = filter_log_output(output, 10, false);
let result = filter_log_output(output, 10, false, false);
assert!(result.contains("abc1234"));
assert!(!result.contains("Signed-off-by:"));
assert!(!result.contains("Co-authored-by:"));
@@ -1735,7 +1836,7 @@ M file7.rs
#[test]
fn test_filter_log_output_truncate_long() {
let long_line = "abc1234 ".to_string() + &"x".repeat(100) + " (2 days ago) <author>";
let result = filter_log_output(&long_line, 10, false);
let result = filter_log_output(&long_line, 10, false, false);
assert!(result.chars().count() < long_line.chars().count());
assert!(result.contains("..."));
assert!(result.chars().count() <= 80);
@@ -1747,7 +1848,7 @@ M file7.rs
.map(|i| format!("hash{} message {} (1 day ago) <author>\n\n---END---", i, i))
.collect::<Vec<_>>()
.join("\n");
let result = filter_log_output(&output, 5, false);
let result = filter_log_output(&output, 5, false, false);
assert_eq!(result.lines().count(), 5);
}
@@ -1758,7 +1859,7 @@ M file7.rs
.map(|i| format!("hash{} message {} (1 day ago) <author>\n\n---END---", i, i))
.collect::<Vec<_>>()
.join("\n");
let result = filter_log_output(&output, 20, true);
let result = filter_log_output(&output, 20, true, false);
assert_eq!(
result.lines().count(),
20,
@@ -1773,8 +1874,8 @@ M file7.rs
assert!(line_90_chars.chars().count() > 80);
assert!(line_90_chars.chars().count() < 120);
let result_default = filter_log_output(&line_90_chars, 10, false);
let result_user = filter_log_output(&line_90_chars, 10, true);
let result_default = filter_log_output(&line_90_chars, 10, false, false);
let result_user = filter_log_output(&line_90_chars, 10, true, false);
// Default truncates at 80 chars
assert!(
@@ -1833,7 +1934,7 @@ M file7.rs
})
.collect::<Vec<_>>()
.join("\n");
let output = filter_log_output(&input, 10, false);
let output = filter_log_output(&input, 10, false, false);
let savings = 100.0 - (count_tokens(&output) as f64 / count_tokens(&input) as f64 * 100.0);
assert!(
savings >= 60.0,
@@ -1875,7 +1976,7 @@ no changes added to commit (use "git add" and/or "git commit -a")
fn test_filter_log_output_multibyte() {
// Thai characters: each is 3 bytes. A line with >80 bytes but few chars
let thai_msg = format!("abc1234 {} (2 days ago) <author>", "ก".repeat(30));
let result = filter_log_output(&thai_msg, 10, false);
let result = filter_log_output(&thai_msg, 10, false, false);
// Should not panic
assert!(result.contains("abc1234"));
// The line has 30 Thai chars + other text, so > 80 chars total
@@ -1887,7 +1988,7 @@ no changes added to commit (use "git add" and/or "git commit -a")
#[test]
fn test_filter_log_output_emoji() {
let emoji_msg = "abc1234 🎉🎊🎈🎁🎂🎄🎃🎆🎇✨🎉🎊🎈🎁🎂🎄🎃🎆🎇✨ (1 day ago) <user>";
let result = filter_log_output(emoji_msg, 10, false);
let result = filter_log_output(emoji_msg, 10, false, false);
// Should not panic
// 20 emoji + ~30 other chars = ~50 chars < 80, no truncation needed
assert!(result.contains("abc1234"));
@@ -1910,6 +2011,41 @@ no changes added to commit (use "git add" and/or "git commit -a")
assert!(result.contains("📌 main"));
}
/// Regression test: --oneline and other user format flags must preserve all commits.
/// Before fix, filter_log_output split on ---END--- which doesn't exist when
/// the user specifies their own format, resulting in only 2 commits surviving.
#[test]
fn test_filter_log_output_user_format_oneline() {
let oneline_output = "abc1234 feat: add feature\n\
def5678 fix: typo\n\
ghi9012 chore: bump deps\n\
jkl3456 docs: update readme\n\
mno7890 test: add tests\n";
let result = filter_log_output(oneline_output, 10, false, true);
// All 5 lines must survive — no ---END--- splitting
assert_eq!(result.lines().count(), 5);
assert!(result.contains("abc1234"));
assert!(result.contains("mno7890"));
}
#[test]
fn test_filter_log_output_user_format_with_limit() {
let oneline_output = "abc1234 feat: add feature\n\
def5678 fix: typo\n\
ghi9012 chore: bump deps\n\
jkl3456 docs: update readme\n\
mno7890 test: add tests\n";
// user_set_limit=true means respect all lines (no cap)
let result = filter_log_output(oneline_output, 3, true, true);
assert_eq!(result.lines().count(), 5);
// user_set_limit=false means cap at limit
let result = filter_log_output(oneline_output, 3, false, true);
assert_eq!(result.lines().count(), 3);
}
/// Regression test: `git branch <name>` must create, not list.
/// Before fix, positional args fell into list mode which added `-a`,
/// turning creation into a pattern-filtered listing (silent no-op).
+17 -4
View File
@@ -1,3 +1,4 @@
use crate::config;
use crate::tracking;
use crate::utils::{resolved_command, truncate};
use anyhow::{Context, Result};
@@ -78,9 +79,21 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
&filtered,
);
// golangci-lint returns exit code 1 when issues found (expected behavior)
// Don't exit with error code in that case
Ok(())
// golangci-lint: exit 0 = clean, exit 1 = lint issues, exit 2+ = config/build error
// None = killed by signal (OOM, SIGKILL) — always fatal
match output.status.code() {
Some(0) | Some(1) => Ok(()),
Some(code) => {
if !stderr.trim().is_empty() {
eprintln!("{}", stderr.trim());
}
std::process::exit(code);
}
None => {
eprintln!("golangci-lint: killed by signal");
std::process::exit(130);
}
}
}
/// Filter golangci-lint JSON output - group by linter and file
@@ -94,7 +107,7 @@ fn filter_golangci_json(output: &str) -> String {
return format!(
"golangci-lint (JSON parse failed: {})\n{}",
e,
truncate(output, 500)
truncate(output, config::limits().passthrough_max_chars)
);
}
};
+22 -15
View File
@@ -1,3 +1,4 @@
use crate::config;
use crate::tracking;
use crate::utils::resolved_command;
use anyhow::{Context, Result};
@@ -77,6 +78,13 @@ pub fn run(
let mut by_file: HashMap<String, Vec<(usize, String)>> = HashMap::new();
let mut total = 0;
// Compile context regex once (instead of per-line in clean_line)
let context_re = if context_only {
Regex::new(&format!("(?i).{{0,20}}{}.*", regex::escape(pattern))).ok()
} else {
None
};
for line in stdout.lines() {
let parts: Vec<&str> = line.splitn(3, ':').collect();
@@ -91,7 +99,7 @@ pub fn run(
};
total += 1;
let cleaned = clean_line(content, max_line_len, context_only, pattern);
let cleaned = clean_line(content, max_line_len, context_re.as_ref(), pattern);
by_file.entry(file).or_default().push((line_num, cleaned));
}
@@ -110,7 +118,8 @@ pub fn run(
let file_display = compact_path(file);
rtk_output.push_str(&format!("📄 {} ({}):\n", file_display, matches.len()));
for (line_num, content) in matches.iter().take(10) {
let per_file = config::limits().grep_max_per_file;
for (line_num, content) in matches.iter().take(per_file) {
rtk_output.push_str(&format!(" {:>4}: {}\n", line_num, content));
shown += 1;
if shown >= max_results {
@@ -118,8 +127,8 @@ pub fn run(
}
}
if matches.len() > 10 {
rtk_output.push_str(&format!(" +{}\n", matches.len() - 10));
if matches.len() > per_file {
rtk_output.push_str(&format!(" +{}\n", matches.len() - per_file));
}
rtk_output.push('\n');
}
@@ -143,16 +152,14 @@ pub fn run(
Ok(())
}
fn clean_line(line: &str, max_len: usize, context_only: bool, pattern: &str) -> String {
fn clean_line(line: &str, max_len: usize, context_re: Option<&Regex>, pattern: &str) -> String {
let trimmed = line.trim();
if context_only {
if let Ok(re) = Regex::new(&format!("(?i).{{0,20}}{}.*", regex::escape(pattern))) {
if let Some(m) = re.find(trimmed) {
let matched = m.as_str();
if matched.len() <= max_len {
return matched.to_string();
}
if let Some(re) = context_re {
if let Some(m) = re.find(trimmed) {
let matched = m.as_str();
if matched.len() <= max_len {
return matched.to_string();
}
}
}
@@ -216,7 +223,7 @@ mod tests {
#[test]
fn test_clean_line() {
let line = " const result = someFunction();";
let cleaned = clean_line(line, 50, false, "result");
let cleaned = clean_line(line, 50, None, "result");
assert!(!cleaned.starts_with(' '));
assert!(cleaned.len() <= 50);
}
@@ -240,7 +247,7 @@ mod tests {
fn test_clean_line_multibyte() {
// Thai text that exceeds max_len in bytes
let line = " สวัสดีครับ นี่คือข้อความที่ยาวมากสำหรับทดสอบ ";
let cleaned = clean_line(line, 20, false, "ครับ");
let cleaned = clean_line(line, 20, None, "ครับ");
// Should not panic
assert!(!cleaned.is_empty());
}
@@ -248,7 +255,7 @@ mod tests {
#[test]
fn test_clean_line_emoji() {
let line = "🎉🎊🎈🎁🎂🎄 some text 🎃🎆🎇✨";
let cleaned = clean_line(line, 15, false, "text");
let cleaned = clean_line(line, 15, None, "text");
assert!(!cleaned.is_empty());
}
+3 -2
View File
@@ -1,3 +1,4 @@
use crate::config;
use crate::mypy_cmd;
use crate::ruff_cmd;
use crate::tracking;
@@ -234,7 +235,7 @@ fn filter_eslint_json(output: &str) -> String {
return format!(
"ESLint output (JSON parse failed: {})\n{}",
e,
truncate(output, 500)
truncate(output, config::limits().passthrough_max_chars)
);
}
};
@@ -326,7 +327,7 @@ fn filter_pylint_json(output: &str) -> String {
return format!(
"Pylint output (JSON parse failed: {})\n{}",
e,
truncate(output, 500)
truncate(output, config::limits().passthrough_max_chars)
);
}
};
+16 -12
View File
@@ -1,11 +1,23 @@
use crate::tracking;
use anyhow::Result;
use lazy_static::lazy_static;
use regex::Regex;
use std::collections::HashMap;
use std::fs;
use std::io::{self, BufRead};
use std::path::Path;
lazy_static! {
static ref TIMESTAMP_RE: Regex =
Regex::new(r"^\d{4}[-/]\d{2}[-/]\d{2}[T ]\d{2}:\d{2}:\d{2}[.,]?\d*\s*").unwrap();
static ref UUID_RE: Regex =
Regex::new(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")
.unwrap();
static ref HEX_RE: Regex = Regex::new(r"0x[0-9a-fA-F]+").unwrap();
static ref NUM_RE: Regex = Regex::new(r"\b\d{4,}\b").unwrap();
static ref PATH_RE: Regex = Regex::new(r"/[\w./\-]+").unwrap();
}
/// Filter and deduplicate log output
pub fn run_file(file: &Path, verbose: u8) -> Result<()> {
let timer = tracking::TimedExecution::start();
@@ -58,22 +70,14 @@ fn analyze_logs(content: &str) -> String {
let mut unique_errors: Vec<String> = Vec::new();
let mut unique_warnings: Vec<String> = Vec::new();
// Patterns to normalize log messages
let timestamp_re =
Regex::new(r"^\d{4}[-/]\d{2}[-/]\d{2}[T ]\d{2}:\d{2}:\d{2}[.,]?\d*\s*").unwrap();
let uuid_re =
Regex::new(r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}")
.unwrap();
let hex_re = Regex::new(r"0x[0-9a-fA-F]+").unwrap();
let num_re = Regex::new(r"\b\d{4,}\b").unwrap();
let path_re = Regex::new(r"/[\w./\-]+").unwrap();
// Use module-level lazy_static regexes for normalization
for line in content.lines() {
let line_lower = line.to_lowercase();
// Normalize for deduplication
let normalized =
normalize_log_line(line, &timestamp_re, &uuid_re, &hex_re, &num_re, &path_re);
normalize_log_line(line, &TIMESTAMP_RE, &UUID_RE, &HEX_RE, &NUM_RE, &PATH_RE);
// Categorize
if line_lower.contains("error")
@@ -128,7 +132,7 @@ fn analyze_logs(content: &str) -> String {
let original = unique_errors
.iter()
.find(|e| {
&normalize_log_line(e, &timestamp_re, &uuid_re, &hex_re, &num_re, &path_re)
&normalize_log_line(e, &TIMESTAMP_RE, &UUID_RE, &HEX_RE, &NUM_RE, &PATH_RE)
== *normalized
})
.map(|s| s.as_str())
@@ -168,7 +172,7 @@ fn analyze_logs(content: &str) -> String {
let original = unique_warnings
.iter()
.find(|w| {
&normalize_log_line(w, &timestamp_re, &uuid_re, &hex_re, &num_re, &path_re)
&normalize_log_line(w, &TIMESTAMP_RE, &UUID_RE, &HEX_RE, &NUM_RE, &PATH_RE)
== *normalized
})
.map(|s| s.as_str())
+26 -3
View File
@@ -56,6 +56,7 @@ mod telemetry;
mod toml_filter;
mod tracking;
mod tree;
mod trust;
mod tsc_cmd;
mod utils;
mod verify_cmd;
@@ -305,7 +306,7 @@ enum Commands {
#[arg(short = 'l', long, default_value = "80")]
max_len: usize,
/// Max results to show
#[arg(short, long, default_value = "50")]
#[arg(short, long, default_value = "200")]
max: usize,
/// Show only match context (not full line)
#[arg(short, long)]
@@ -573,6 +574,16 @@ enum Commands {
args: Vec<OsString>,
},
/// Trust project-local TOML filters in current directory
Trust {
/// List all trusted projects
#[arg(long)]
list: bool,
},
/// Revoke trust for project-local TOML filters
Untrust,
/// Verify hook integrity and run TOML filter inline tests
Verify {
/// Run tests only for this filter name
@@ -1006,6 +1017,10 @@ const RTK_META_COMMANDS: &[&str] = &[
"hook-audit",
"cc-economics",
"verify",
"trust",
"untrust",
"session",
"rewrite",
];
fn run_fallback(parse_error: clap::Error) -> Result<()> {
@@ -2088,6 +2103,14 @@ fn main() -> Result<()> {
}
}
Commands::Trust { list } => {
trust::run_trust(list)?;
}
Commands::Untrust => {
trust::run_untrust()?;
}
Commands::Verify {
filter,
require_all,
@@ -2371,8 +2394,8 @@ mod tests {
// RTK meta-commands should produce parse errors (not fall through to raw execution).
// Skip "proxy" because it uses trailing_var_arg (accepts any args by design).
for cmd in RTK_META_COMMANDS {
if *cmd == "proxy" {
continue;
if matches!(*cmd, "proxy" | "rewrite" | "session") {
continue; // these use trailing_var_arg (accept any args by design)
}
let result = Cli::try_parse_from(["rtk", cmd, "--nonexistent-flag-xyz"]);
assert!(
+4 -1
View File
@@ -43,7 +43,10 @@ pub fn run(args: &[String], verbose: u8) -> Result<()> {
&filtered,
);
std::process::exit(output.status.code().unwrap_or(1));
if !output.status.success() {
std::process::exit(output.status.code().unwrap_or(1));
}
Ok(())
}
struct MypyError {
+1 -1
View File
@@ -70,7 +70,7 @@ impl OutputParser for VitestParser {
)
} else {
// Tier 3: Passthrough
ParseResult::Passthrough(truncate_output(input, 500))
ParseResult::Passthrough(truncate_output(input, 2000))
}
}
}
+7 -1
View File
@@ -89,12 +89,18 @@ pub trait OutputParser: Sized {
let result = Self::parse(input);
if result.tier() > max_tier {
// Force degradation to passthrough if exceeds max tier
return ParseResult::Passthrough(truncate_output(input, 500));
return ParseResult::Passthrough(truncate_passthrough(input));
}
result
}
}
/// Truncate output using configured passthrough limit
pub fn truncate_passthrough(output: &str) -> String {
let max_chars = crate::config::limits().passthrough_max_chars;
truncate_output(output, max_chars)
}
/// Truncate output to max length with ellipsis
pub fn truncate_output(output: &str, max_chars: usize) -> String {
let chars: Vec<char> = output.chars().collect();
+2 -2
View File
@@ -5,7 +5,7 @@ use regex::Regex;
use serde::Deserialize;
use crate::parser::{
emit_degradation_warning, emit_passthrough_warning, truncate_output, FormatMode, OutputParser,
emit_degradation_warning, emit_passthrough_warning, truncate_passthrough, FormatMode, OutputParser,
ParseResult, TestFailure, TestResult, TokenFormatter,
};
@@ -110,7 +110,7 @@ impl OutputParser for PlaywrightParser {
}
None => {
// Tier 3: Passthrough
ParseResult::Passthrough(truncate_output(input, 500))
ParseResult::Passthrough(truncate_passthrough(input))
}
}
}
+7 -5
View File
@@ -6,7 +6,7 @@ use std::collections::HashMap;
use std::ffi::OsString;
use crate::parser::{
emit_degradation_warning, emit_passthrough_warning, truncate_output, Dependency,
emit_degradation_warning, emit_passthrough_warning, truncate_passthrough, Dependency,
DependencyState, FormatMode, OutputParser, ParseResult, TokenFormatter,
};
@@ -75,7 +75,7 @@ impl OutputParser for PnpmListParser {
}
None => {
// Tier 3: Passthrough
ParseResult::Passthrough(truncate_output(input, 500))
ParseResult::Passthrough(truncate_passthrough(input))
}
}
}
@@ -202,7 +202,7 @@ impl OutputParser for PnpmOutdatedParser {
}
None => {
// Tier 3: Passthrough
ParseResult::Passthrough(truncate_output(input, 500))
ParseResult::Passthrough(truncate_passthrough(input))
}
}
}
@@ -307,7 +307,8 @@ fn run_list(depth: usize, args: &[String], verbose: u8) -> Result<()> {
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::bail!("pnpm list failed: {}", stderr);
eprint!("{}", stderr);
std::process::exit(output.status.code().unwrap_or(1));
}
let stdout = String::from_utf8_lossy(&output.stdout);
@@ -431,7 +432,8 @@ fn run_install(packages: &[String], args: &[String], verbose: u8) -> Result<()>
let stderr = String::from_utf8_lossy(&output.stderr);
if !output.status.success() {
anyhow::bail!("pnpm install failed: {}", stderr);
eprint!("{}", stderr);
std::process::exit(output.status.code().unwrap_or(1));
}
let combined = format!("{}{}", stdout, stderr);
+38 -20
View File
@@ -54,18 +54,24 @@ fn run_generate(args: &[String], verbose: u8) -> Result<()> {
.output()
.context("Failed to run prisma generate (try: npm install -g prisma)")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::bail!("prisma generate failed: {}", stderr);
}
let exit_code = output.status.code().unwrap_or(1);
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
if !output.status.success() {
if !stdout.trim().is_empty() {
eprint!("{}", stdout);
}
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track("prisma generate", "rtk prisma generate", &raw, &raw);
std::process::exit(exit_code);
}
let filtered = filter_prisma_generate(&raw);
println!("{}", filtered);
timer.track("prisma generate", "rtk prisma generate", &raw, &filtered);
Ok(())
@@ -105,15 +111,22 @@ fn run_migrate(subcommand: MigrateSubcommand, args: &[String], verbose: u8) -> R
let output = cmd.output().context("Failed to run prisma migrate")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::bail!("prisma migrate failed: {}", stderr);
}
let exit_code = output.status.code().unwrap_or(1);
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
if !output.status.success() {
if !stdout.trim().is_empty() {
eprint!("{}", stdout);
}
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track(cmd_name, &format!("rtk {}", cmd_name), &raw, &raw);
std::process::exit(exit_code);
}
let filtered = match subcommand {
MigrateSubcommand::Dev { .. } => filter_migrate_dev(&raw),
MigrateSubcommand::Status => filter_migrate_status(&raw),
@@ -121,7 +134,6 @@ fn run_migrate(subcommand: MigrateSubcommand, args: &[String], verbose: u8) -> R
};
println!("{}", filtered);
timer.track(cmd_name, &format!("rtk {}", cmd_name), &raw, &filtered);
Ok(())
@@ -143,18 +155,24 @@ fn run_db_push(args: &[String], verbose: u8) -> Result<()> {
let output = cmd.output().context("Failed to run prisma db push")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
anyhow::bail!("prisma db push failed: {}", stderr);
}
let exit_code = output.status.code().unwrap_or(1);
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let raw = format!("{}\n{}", stdout, stderr);
if !output.status.success() {
if !stdout.trim().is_empty() {
eprint!("{}", stdout);
}
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track("prisma db push", "rtk prisma db push", &raw, &raw);
std::process::exit(exit_code);
}
let filtered = filter_db_push(&raw);
println!("{}", filtered);
timer.track("prisma db push", "rtk prisma db push", &raw, &filtered);
Ok(())
+2 -1
View File
@@ -1,3 +1,4 @@
use crate::config;
use crate::tracking;
use crate::utils::{resolved_command, truncate};
use anyhow::{Context, Result};
@@ -121,7 +122,7 @@ pub fn filter_ruff_check_json(output: &str) -> String {
return format!(
"Ruff check (JSON parse failed: {})\n{}",
e,
truncate(output, 500)
truncate(output, config::limits().passthrough_max_chars)
);
}
};
+44 -13
View File
@@ -181,11 +181,29 @@ impl TomlFilterRegistry {
fn load() -> Self {
let mut filters = Vec::new();
// Priority 1: project-local .rtk/filters.toml
if let Ok(content) = std::fs::read_to_string(".rtk/filters.toml") {
match Self::parse_and_compile(&content, "project") {
Ok(f) => filters.extend(f),
Err(e) => eprintln!("[rtk] warning: .rtk/filters.toml: {}", e),
// Priority 1: project-local .rtk/filters.toml (trust-gated)
let project_filter_path = std::path::Path::new(".rtk/filters.toml");
if project_filter_path.exists() {
let trust_status = crate::trust::check_trust(project_filter_path)
.unwrap_or(crate::trust::TrustStatus::Untrusted);
match trust_status {
crate::trust::TrustStatus::Trusted | crate::trust::TrustStatus::EnvOverride => {
if let Ok(content) = std::fs::read_to_string(project_filter_path) {
match Self::parse_and_compile(&content, "project") {
Ok(f) => filters.extend(f),
Err(e) => eprintln!("[rtk] warning: .rtk/filters.toml: {}", e),
}
}
}
crate::trust::TrustStatus::Untrusted => {
eprintln!("[rtk] WARNING: untrusted project filters (.rtk/filters.toml)");
eprintln!("[rtk] Filters NOT applied. Run `rtk trust` to review and enable.");
}
crate::trust::TrustStatus::ContentChanged { .. } => {
eprintln!("[rtk] WARNING: .rtk/filters.toml changed since trusted.");
eprintln!("[rtk] Filters NOT applied. Run `rtk trust` to re-review.");
}
}
}
@@ -529,14 +547,27 @@ pub fn run_filter_tests(filter_name_opt: Option<&str>) -> VerifyResults {
&mut tested_filter_names,
);
if let Ok(content) = std::fs::read_to_string(".rtk/filters.toml") {
collect_test_outcomes(
&content,
filter_name_opt,
&mut outcomes,
&mut all_filter_names,
&mut tested_filter_names,
);
// Trust-gated: only verify project-local filters if trusted (SA-2025-RTK-002)
let project_path = std::path::Path::new(".rtk/filters.toml");
if project_path.exists() {
let trust_status =
crate::trust::check_trust(project_path).unwrap_or(crate::trust::TrustStatus::Untrusted);
match trust_status {
crate::trust::TrustStatus::Trusted | crate::trust::TrustStatus::EnvOverride => {
if let Ok(content) = std::fs::read_to_string(project_path) {
collect_test_outcomes(
&content,
filter_name_opt,
&mut outcomes,
&mut all_filter_names,
&mut tested_filter_names,
);
}
}
_ => {
eprintln!("[rtk] WARNING: untrusted project filters skipped in verify");
}
}
}
let filters_without_tests = all_filter_names
+6
View File
@@ -251,6 +251,12 @@ impl Tracker {
}
let conn = Connection::open(&db_path)?;
// WAL mode + busy_timeout for concurrent access (multiple Claude Code instances).
// Non-fatal: NFS/read-only filesystems may not support WAL.
let _ = conn.execute_batch(
"PRAGMA journal_mode=WAL;
PRAGMA busy_timeout=5000;",
);
conn.execute(
"CREATE TABLE IF NOT EXISTS commands (
id INTEGER PRIMARY KEY,
+510
View File
@@ -0,0 +1,510 @@
//! Trust boundary for project-local TOML filters (SA-2025-RTK-002).
//!
//! `.rtk/filters.toml` is loaded from CWD with highest priority. An attacker
//! can commit this file to a public repo to control what an LLM sees — hiding
//! malicious code, suppressing security scanner output, or rewriting command
//! output entirely via `replace` and `match_output` primitives.
//!
//! This module implements a trust-before-load model:
//! - Untrusted filters are **skipped** (not "loaded with warning")
//! - `rtk trust` stores the SHA-256 hash after user review
//! - Content changes invalidate trust (re-review required)
//! - `RTK_TRUST_PROJECT_FILTERS=1` overrides for CI pipelines
use crate::integrity;
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
#[derive(Serialize, Deserialize, Default)]
struct TrustStore {
version: u32,
trusted: HashMap<String, TrustEntry>,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct TrustEntry {
pub sha256: String,
pub trusted_at: String,
}
#[derive(Debug, PartialEq)]
pub enum TrustStatus {
Trusted,
Untrusted,
ContentChanged { expected: String, actual: String },
EnvOverride,
}
// ---------------------------------------------------------------------------
// Store path
// ---------------------------------------------------------------------------
fn store_path() -> Result<PathBuf> {
let data_dir = dirs::data_local_dir().context("Cannot determine local data directory")?;
Ok(data_dir.join("rtk").join("trusted_filters.json"))
}
fn read_store() -> Result<TrustStore> {
let path = store_path()?;
if !path.exists() {
return Ok(TrustStore::default());
}
let content = std::fs::read_to_string(&path)
.with_context(|| format!("Failed to read trust store: {}", path.display()))?;
serde_json::from_str(&content)
.with_context(|| format!("Failed to parse trust store: {}", path.display()))
}
fn write_store(store: &TrustStore) -> Result<()> {
let path = store_path()?;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)
.with_context(|| format!("Failed to create directory: {}", parent.display()))?;
}
let content = serde_json::to_string_pretty(store).context("Failed to serialize trust store")?;
std::fs::write(&path, content)
.with_context(|| format!("Failed to write trust store: {}", path.display()))
}
// ---------------------------------------------------------------------------
// Canonical path helper
// ---------------------------------------------------------------------------
fn canonical_key(filter_path: &Path) -> Result<String> {
// Resolve symlinks and produce an absolute path. No fallback — if we can't
// canonicalize, we can't safely key the trust entry (fail-closed).
let canonical = std::fs::canonicalize(filter_path)
.with_context(|| format!("Cannot resolve path: {}", filter_path.display()))?;
Ok(canonical.to_string_lossy().to_string())
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/// Check if a project-local filter file is trusted.
///
/// Priority: env var > hash match > untrusted.
/// All errors are soft — if anything fails, returns Untrusted (fail-secure).
pub fn check_trust(filter_path: &Path) -> Result<TrustStatus> {
// Fast path: env var override for CI pipelines only.
// Requires a known CI env var to be set to prevent .envrc injection attacks.
if std::env::var("RTK_TRUST_PROJECT_FILTERS").as_deref() == Ok("1") {
let in_ci = std::env::var("CI").is_ok()
|| std::env::var("GITHUB_ACTIONS").is_ok()
|| std::env::var("GITLAB_CI").is_ok()
|| std::env::var("JENKINS_URL").is_ok()
|| std::env::var("BUILDKITE").is_ok();
if in_ci {
return Ok(TrustStatus::EnvOverride);
}
eprintln!(
"[rtk] WARNING: RTK_TRUST_PROJECT_FILTERS=1 ignored (CI environment not detected)"
);
}
let key = canonical_key(filter_path)?;
let store = match read_store() {
Ok(s) => s,
Err(e) => {
eprintln!(
"[rtk] WARNING: trust store unreadable ({}), treating all filters as untrusted",
e
);
TrustStore::default()
}
};
let entry = match store.trusted.get(&key) {
Some(e) => e,
None => return Ok(TrustStatus::Untrusted),
};
let actual_hash = integrity::compute_hash(filter_path)
.with_context(|| format!("Failed to hash: {}", filter_path.display()))?;
if actual_hash == entry.sha256 {
Ok(TrustStatus::Trusted)
} else {
Ok(TrustStatus::ContentChanged {
expected: entry.sha256.clone(),
actual: actual_hash,
})
}
}
/// Store current SHA-256 hash as trusted (computes hash from file).
pub fn trust_filter(filter_path: &Path) -> Result<()> {
let hash = integrity::compute_hash(filter_path)
.with_context(|| format!("Failed to hash: {}", filter_path.display()))?;
trust_filter_with_hash(filter_path, &hash)
}
/// Store a pre-computed SHA-256 hash as trusted (avoids TOCTOU re-read).
pub fn trust_filter_with_hash(filter_path: &Path, hash: &str) -> Result<()> {
let key = canonical_key(filter_path)?;
let mut store = read_store().unwrap_or_default();
store.version = 1;
store.trusted.insert(
key,
TrustEntry {
sha256: hash.to_string(),
trusted_at: chrono::Utc::now().to_rfc3339(),
},
);
write_store(&store)
}
/// Remove trust entry for a filter path.
pub fn untrust_filter(filter_path: &Path) -> Result<bool> {
let key = canonical_key(filter_path)?;
let mut store = read_store().unwrap_or_default();
let removed = store.trusted.remove(&key).is_some();
if removed {
write_store(&store)?;
}
Ok(removed)
}
/// List all trusted projects.
pub fn list_trusted() -> Result<HashMap<String, TrustEntry>> {
let store = read_store().unwrap_or_default();
Ok(store.trusted)
}
// ---------------------------------------------------------------------------
// CLI commands
// ---------------------------------------------------------------------------
/// Run `rtk trust` — review and trust project-local filters.
pub fn run_trust(list: bool) -> Result<()> {
if list {
let trusted = list_trusted()?;
if trusted.is_empty() {
println!("No trusted project filters.");
return Ok(());
}
println!("Trusted project filters:");
println!("{}", "═".repeat(60));
for (path, entry) in &trusted {
let date = entry.trusted_at.get(..10).unwrap_or(&entry.trusted_at);
println!(" {} (trusted {})", path, date);
println!(" sha256:{}", entry.sha256);
}
return Ok(());
}
let filter_path = Path::new(".rtk/filters.toml");
if !filter_path.exists() {
anyhow::bail!("No .rtk/filters.toml found in current directory");
}
// Read ONCE to prevent TOCTOU: display + hash from same buffer
let content_bytes = std::fs::read(filter_path).context("Failed to read .rtk/filters.toml")?;
let content = String::from_utf8_lossy(&content_bytes);
println!("=== .rtk/filters.toml ===");
println!("{}", content);
println!("=========================");
println!();
// Risk summary
print_risk_summary(&content);
// Hash the in-memory buffer (not a second file read)
let hash = {
use sha2::{Digest, Sha256};
let mut h = Sha256::new();
h.update(&content_bytes);
format!("{:x}", h.finalize())
};
// Store trust with pre-computed hash
trust_filter_with_hash(filter_path, &hash)?;
println!();
println!(
"Trusted .rtk/filters.toml (sha256:{})",
hash.get(..16).unwrap_or(&hash)
);
println!("Project-local filters will now be applied.");
Ok(())
}
/// Run `rtk untrust` — revoke trust for project-local filters.
pub fn run_untrust() -> Result<()> {
let filter_path = Path::new(".rtk/filters.toml");
// If file doesn't exist, untrust by canonical path lookup won't work.
// Try anyway (file may have been deleted after trust), fallback gracefully.
let removed = untrust_filter(filter_path).unwrap_or(false);
if removed {
println!("Trust revoked for .rtk/filters.toml");
println!("Project-local filters will no longer be applied.");
} else {
println!("No trust entry found for current directory.");
}
Ok(())
}
// ---------------------------------------------------------------------------
// Risk analysis
// ---------------------------------------------------------------------------
fn print_risk_summary(content: &str) {
let filter_count = content.matches("[filters.").count();
let has_replace = content.contains("replace");
let has_match_output = content.contains("match_output");
let has_dot_pattern = content.contains("pattern = \".\"") || content.contains("pattern = '.'");
println!("Risk summary:");
println!(" Filters: {}", filter_count);
if has_replace {
println!(" ⚠ Contains 'replace' rules (can rewrite output)");
}
if has_match_output {
println!(" ⚠ Contains 'match_output' rules (can replace entire output)");
}
if has_dot_pattern {
println!(" ⚠ Contains catch-all pattern '.' (matches everything)");
}
if !has_replace && !has_match_output && !has_dot_pattern {
println!(" No high-risk patterns detected.");
}
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
/// Helper: create a temporary trust store in a temp dir.
/// Overrides the store path via a scoped env var (not possible with
/// the real function), so we test the logic by calling internal fns.
fn setup_test_env(temp: &TempDir) -> PathBuf {
let store_file = temp.path().join("trusted_filters.json");
store_file
}
fn check_trust_with_store(filter_path: &Path, store_file: &Path) -> Result<TrustStatus> {
// Note: env var check is NOT included here to avoid test interference.
// The env var path is tested separately in test_env_override.
let key = canonical_key(filter_path)?;
let store: TrustStore = if store_file.exists() {
let content = std::fs::read_to_string(store_file)?;
serde_json::from_str(&content)?
} else {
TrustStore::default()
};
let entry = match store.trusted.get(&key) {
Some(e) => e,
None => return Ok(TrustStatus::Untrusted),
};
let actual_hash = integrity::compute_hash(filter_path)?;
if actual_hash == entry.sha256 {
Ok(TrustStatus::Trusted)
} else {
Ok(TrustStatus::ContentChanged {
expected: entry.sha256.clone(),
actual: actual_hash,
})
}
}
fn trust_with_store(filter_path: &Path, store_file: &Path) -> Result<()> {
let key = canonical_key(filter_path)?;
let hash = integrity::compute_hash(filter_path)?;
let mut store: TrustStore = if store_file.exists() {
let content = std::fs::read_to_string(store_file)?;
serde_json::from_str(&content)?
} else {
TrustStore::default()
};
store.version = 1;
store.trusted.insert(
key,
TrustEntry {
sha256: hash,
trusted_at: chrono::Utc::now().to_rfc3339(),
},
);
if let Some(parent) = store_file.parent() {
std::fs::create_dir_all(parent)?;
}
let content = serde_json::to_string_pretty(&store)?;
std::fs::write(store_file, content)?;
Ok(())
}
fn untrust_with_store(filter_path: &Path, store_file: &Path) -> Result<bool> {
let key = canonical_key(filter_path)?;
let mut store: TrustStore = if store_file.exists() {
let content = std::fs::read_to_string(store_file)?;
serde_json::from_str(&content)?
} else {
return Ok(false);
};
let removed = store.trusted.remove(&key).is_some();
if removed {
let content = serde_json::to_string_pretty(&store)?;
std::fs::write(store_file, content)?;
}
Ok(removed)
}
#[test]
fn test_untrusted_by_default() {
let temp = TempDir::new().unwrap();
let filter = temp.path().join("filters.toml");
std::fs::write(&filter, "[filters.test]\nmatch_command = \"echo\"").unwrap();
let store_file = setup_test_env(&temp);
let status = check_trust_with_store(&filter, &store_file).unwrap();
assert_eq!(status, TrustStatus::Untrusted);
}
#[test]
fn test_trust_then_check() {
let temp = TempDir::new().unwrap();
let filter = temp.path().join("filters.toml");
std::fs::write(&filter, "[filters.test]\nmatch_command = \"echo\"").unwrap();
let store_file = setup_test_env(&temp);
trust_with_store(&filter, &store_file).unwrap();
let status = check_trust_with_store(&filter, &store_file).unwrap();
assert_eq!(status, TrustStatus::Trusted);
}
#[test]
fn test_content_change_detected() {
let temp = TempDir::new().unwrap();
let filter = temp.path().join("filters.toml");
std::fs::write(&filter, "[filters.test]\nmatch_command = \"echo\"").unwrap();
let store_file = setup_test_env(&temp);
trust_with_store(&filter, &store_file).unwrap();
// Modify the filter file
std::fs::write(
&filter,
"[filters.evil]\nmatch_command = \".*\"\nmatch_output = \"password\"",
)
.unwrap();
let status = check_trust_with_store(&filter, &store_file).unwrap();
match status {
TrustStatus::ContentChanged { expected, actual } => {
assert_ne!(expected, actual);
assert_eq!(expected.len(), 64);
assert_eq!(actual.len(), 64);
}
other => panic!("Expected ContentChanged, got {:?}", other),
}
}
#[test]
fn test_untrust_revokes() {
let temp = TempDir::new().unwrap();
let filter = temp.path().join("filters.toml");
std::fs::write(&filter, "[filters.test]\nmatch_command = \"echo\"").unwrap();
let store_file = setup_test_env(&temp);
trust_with_store(&filter, &store_file).unwrap();
let removed = untrust_with_store(&filter, &store_file).unwrap();
assert!(removed);
let status = check_trust_with_store(&filter, &store_file).unwrap();
assert_eq!(status, TrustStatus::Untrusted);
}
#[test]
fn test_env_override_with_ci() {
let temp = TempDir::new().unwrap();
let filter = temp.path().join("filters.toml");
std::fs::write(&filter, "[filters.test]\nmatch_command = \"echo\"").unwrap();
// Both env vars must be set: trust override + CI indicator
#[allow(deprecated)]
std::env::set_var("RTK_TRUST_PROJECT_FILTERS", "1");
#[allow(deprecated)]
std::env::set_var("CI", "true");
let status = check_trust(&filter).unwrap();
#[allow(deprecated)]
std::env::remove_var("RTK_TRUST_PROJECT_FILTERS");
#[allow(deprecated)]
std::env::remove_var("CI");
assert_eq!(status, TrustStatus::EnvOverride);
}
#[test]
fn test_env_override_without_ci_is_ignored() {
let temp = TempDir::new().unwrap();
let filter = temp.path().join("filters.toml");
std::fs::write(&filter, "[filters.test]\nmatch_command = \"echo\"").unwrap();
let store_file = setup_test_env(&temp);
// Trust override WITHOUT CI env → should be Untrusted, not EnvOverride
// (protects against .envrc injection)
// Note: we use check_trust_with_store which skips env var check,
// so this tests the store path when env var would be ignored
let status = check_trust_with_store(&filter, &store_file).unwrap();
assert_eq!(status, TrustStatus::Untrusted);
}
#[test]
fn test_missing_store_is_untrusted() {
let temp = TempDir::new().unwrap();
let filter = temp.path().join("filters.toml");
std::fs::write(&filter, "[filters.test]\nmatch_command = \"echo\"").unwrap();
let store_file = temp.path().join("nonexistent").join("store.json");
let status = check_trust_with_store(&filter, &store_file).unwrap();
assert_eq!(status, TrustStatus::Untrusted);
}
#[test]
fn test_risk_summary_detects_replace() {
let content = "[filters.evil]\nmatch_command = \"git\"\nreplace = [[\"secret\", \"\"]]";
// Just verify it doesn't panic — output goes to stdout
print_risk_summary(content);
}
#[test]
fn test_risk_summary_detects_match_output() {
let content = "[filters.evil]\nmatch_command = \"scan\"\nmatch_output = \"vulnerability\"";
print_risk_summary(content);
}
#[test]
fn test_canonical_key_works() {
let temp = TempDir::new().unwrap();
let filter = temp.path().join("filters.toml");
std::fs::write(&filter, "test").unwrap();
let key = canonical_key(&filter).unwrap();
assert!(key.contains("filters.toml"));
// Should be an absolute path
assert!(key.starts_with('/') || key.contains(':'));
}
}
+2 -2
View File
@@ -3,7 +3,7 @@ use regex::Regex;
use serde::Deserialize;
use crate::parser::{
emit_degradation_warning, emit_passthrough_warning, extract_json_object, truncate_output,
emit_degradation_warning, emit_passthrough_warning, extract_json_object, truncate_passthrough,
FormatMode, OutputParser, ParseResult, TestFailure, TestResult, TokenFormatter,
};
use crate::tracking;
@@ -88,7 +88,7 @@ impl OutputParser for VitestParser {
}
None => {
// Tier 3: Passthrough
ParseResult::Passthrough(truncate_output(input, 500))
ParseResult::Passthrough(truncate_passthrough(input))
}
}
}
+20 -8
View File
@@ -41,10 +41,16 @@ pub fn run(url: &str, args: &[String], verbose: u8) -> Result<()> {
println!("{}", msg);
timer.track(&format!("wget {}", url), "rtk wget", &raw_output, &msg);
} else {
let error = parse_error(&stderr, &stdout);
let msg = format!("⬇️ {} FAILED: {}", compact_url(url), error);
println!("{}", msg);
timer.track(&format!("wget {}", url), "rtk wget", &raw_output, &msg);
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track(
&format!("wget {}", url),
"rtk wget",
&raw_output,
&raw_output,
);
std::process::exit(output.status.code().unwrap_or(1));
}
Ok(())
@@ -103,10 +109,16 @@ pub fn run_stdout(url: &str, args: &[String], verbose: u8) -> Result<()> {
);
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
let error = parse_error(&stderr, "");
let msg = format!("⬇️ {} FAILED: {}", compact_url(url), error);
println!("{}", msg);
timer.track(&format!("wget -O - {}", url), "rtk wget -o", &stderr, &msg);
if !stderr.trim().is_empty() {
eprint!("{}", stderr);
}
timer.track(
&format!("wget -O - {}", url),
"rtk wget -o",
&stderr,
&stderr,
);
std::process::exit(output.status.code().unwrap_or(1));
}
Ok(())