Compare commits

...
Author SHA1 Message Date
aesoft 0b28e47af7 Update README.md 2026-07-06 21:01:19 +02:00
aesoft aee61f2f3f chore(docs): add core contributor 2026-07-06 20:58:27 +02:00
aesoft 6871e55358 Merge pull request #2836 from guyoron1/fix/grep-context-separator
fix(grep): preserve -- separator between non-adjacent match blocks
2026-07-06 09:57:21 +02:00
guyoron1 34a0f0e5c0 fix(grep): only insert -- separator when context flags are active
Native grep only prints -- between non-adjacent match blocks when
-A/-B/-C context is requested. The grouped output path was inserting
-- on any line-number gap unconditionally, so `rtk grep -rn todo`
invented separators between every match that grep never emits.

Gate the insertion on has_context_flag() which checks for -A/-B/-C
and their long-form equivalents.
2026-07-06 09:21:11 +03:00
guyoron1 cae9b710d4 fix(grep): preserve -- separator between non-adjacent match blocks
When context flags (-A/-B/-C) are used, grep prints -- between
non-adjacent match blocks. parse_match_line() returned None for
this separator, and both output paths silently dropped it, merging
distinct matches into one contiguous block.

Fixes #2795
2026-07-06 09:21:03 +03:00
aesoft 31f9d43d81 Merge pull request #2748 from rtk-ai/feat/toml-filters-in-hook
feat(hook): wire TOML filters + better tee tail hint
2026-07-03 16:51:04 +02:00
aesoft 1b38eece9b Merge pull request #2801 from rtk-ai/fix/git-stash-show-diffstat
fix(git): compact git stash show instead of forcing -p
2026-07-03 15:22:20 +02:00
aesoft e20076433e Merge pull request #2789 from rtk-ai/fix/analytics-utf8-char-boundary-panic
fix(analytics): truncate display strings on UTF-8 char boundaries
2026-07-03 12:24:31 +02:00
Adrien Eppling c9468ee178 fix(analytics): floor prefix slices to char boundary instead of full-string fallback 2026-07-03 12:18:58 +02:00
Adrien Eppling 47b22e03a4 fix(analytics): truncate display strings on UTF-8 char boundaries
rtk gain --history panicked with "byte index 22 is not a char
boundary" when a tracked command contained non-ASCII text (Cyrillic,
CJK, emoji). The same byte-slicing pattern existed in the --failures
display (top commands, recent failures, timestamp prefix) and in the
session id column of rtk session, all reproduced as real panics.

Replace the ad-hoc byte-based truncations with the shared char-safe
core::utils::truncate() helper, and use .get(..n).unwrap_or() for the
timestamp and session id prefix slices so they fall back to the full
string instead of panicking. Output is byte-identical to the previous
behavior for pure-ASCII data.

Fixes #2787
2026-07-02 15:28:41 +02:00
Adrien Eppling 2d487cb947 fix(trust): surface parse errors, skip already-trusted files, fail loudly when non-interactive 2026-07-02 13:35:54 +02:00
Adrien Eppling 315a94398e fix(filter): address review findings in the TOML filter path
Recoverable loss for a fired head/max cut (never a bare marker), schema-gate the hook match set, parse-error probe for trust; + tests.
2026-07-02 13:35:53 +02:00
Adrien Eppling 34c0bcf2da perf(hook): match TOML filters with a match-only RegexSet
The rewrite path only needs a yes/no match, not the full compiled pipeline find_matching_filter forces on every not-in-RULES command (~10ms/call saved; selection still uses find_matching_filter in run_fallback).
2026-07-01 16:35:08 +02:00
Adrien Eppling a4872d9bbf fix(gain): note untrusted custom filters so they can be re-trusted 2026-07-01 15:55:45 +02:00
Adrien Eppling bbeee4c85e docs(trust): fix README to match silent skip; note global-filter migration 2026-07-01 15:41:54 +02:00
Adrien Eppling a9c33e2987 fix(trust): label detected filters as project- or global-scoped 2026-07-01 15:11:17 +02:00
Adrien Eppling e0a83ac824 feat(trust): rtk trust uses the same opt-in prompt as init
Concise filter list + [y/N] (--yes for non-interactive); drops the full-file dump and silent auto-trust. Shared prompt helper with init.
2026-07-01 14:46:38 +02:00
Adrien Eppling 9d3b678242 fix(trust): skip untrusted filters silently on the command path
The warning printed to stderr on every rewritten command, adding tokens; trust is surfaced only in `rtk init`/`rtk trust`.
2026-07-01 14:46:37 +02:00
Adrien Eppling 84f952881b docs: document custom filters + trust in the config guide
Move the user-facing trust docs into docs/guide (config) and out of CODING_PRACTICES.
2026-07-01 13:31:51 +02:00
Adrien Eppling 1130a7cafd feat(trust): gate custom filters (project + user-global) + init opt-in flags
Trust-gate both filter files; `rtk init` prompts to enable detected filters, or --trust-filters/--no-trust-filters for scripts.
2026-07-01 13:18:35 +02:00
Adrien EpplingandClaude Opus 4.8 73b8cb3069 feat(hook): wire TOML filters into the rewrite path + reversible truncation
Wire TOML-covered commands into the transparent hook rewrite path, and make
TOML truncation reversible via the shared tee hints.

Part 1 — hook wiring (#2179):
The hook's rewrite decision only consulted the static RULES table, so a command
covered solely by a TOML filter (jj, jq, just, ssh, ty, nx, turbo, …) was passed
through unfiltered by the hook even though `rtk <cmd>` filtered it directly.
`rewrite_segment_inner` now consults the TOML registry on a RULES miss
(Unsupported) and rewrites to `rtk <cmd>`, which re-enters via run_fallback →
the TOML tier. Guards: honors RTK_NO_TOML, respects the exclude list, never
rewrites Ignored (denylisted) commands, and a collision guard
(is_rtk_reserved_command) prevents rewriting to a name Clap would route to its
own subcommand. RTK_META_COMMANDS moved to core::constants as the shared source.

Part 2 — reversibility:
TOML truncation on success previously dropped lines with a bare "... omitted"
marker and no recovery pointer. apply_filter_with_info now reports a Lossiness
(Tail / Whole / None); run_fallback emits the line-offset tail hint
(`[see remaining: tail -n +N …]`) for a contiguous tail-drop, the full-output
hint otherwise, and — when tee is unavailable — shows the full raw rather than an
unrecoverable marker. Fixes the symmetric <500B failure-path gap and an
inaccurate MIN_TEE_SIZE comment in curl_cmd.

All hosts (claude/gemini/copilot/cursor) and `rtk rewrite` are covered via the
shared rewrite_command. No hook JSON / integrity-hash changes. The mirrored RULES
rows are kept (they feed discover/session/gain metadata). Builds on the approach
of #2226.

Note: the TOML registry load now lands on the Unsupported hook hot path
(~3-8ms native, one-time per process); the Supported path is unaffected. A
match-only RegexSet to cut that cost is a documented follow-up.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 15:43:31 +02:00
15 changed files with 907 additions and 156 deletions

No files matched your search

+2
View File
@@ -489,6 +489,8 @@ export RTK_TELEMETRY_DISABLED=1 # Blocks telemetry regardless of consent
[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
+20 -2
View File
@@ -127,6 +127,24 @@ export RTK_TELEMETRY_DISABLED=1
enabled = false
```
## Per-project filters
## Custom filters
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.
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.
+19 -21
View File
@@ -2,7 +2,7 @@
use crate::core::display_helpers::{format_duration, print_period_table};
use crate::core::tracking::{DayStats, MonthStats, Tracker, WeekStats};
use crate::core::utils::format_tokens;
use crate::core::utils::{format_tokens, truncate};
use crate::hooks::hook_check;
use anyhow::{Context, Result};
use chrono::Local;
@@ -147,6 +147,18 @@ pub fn run(
eprintln!();
}
let untrusted_filters = crate::hooks::trust::untrusted_active_filter_count();
if untrusted_filters > 0 {
eprintln!(
"{}",
format!(
"[rtk] {untrusted_filters} untrusted custom filter(s) not applied — run `rtk trust`"
)
.yellow()
);
eprintln!();
}
if !summary.by_command.is_empty() {
// added: styled section header
println!("{}", styled("By Command", true));
@@ -246,11 +258,7 @@ pub fn run(
println!("──────────────────────────────────────────────────────────");
for rec in recent {
let time = rec.timestamp.with_timezone(&Local).format("%m-%d %H:%M");
let cmd_short = if rec.rtk_cmd.len() > 25 {
format!("{}...", &rec.rtk_cmd[..22])
} else {
rec.rtk_cmd.clone()
};
let cmd_short = truncate(&rec.rtk_cmd, 25);
// added: tier indicators by savings level
let sign = if rec.savings_pct >= 70.0 {
"▲"
@@ -707,11 +715,7 @@ fn show_failures(tracker: &Tracker) -> Result<()> {
println!("{}", styled("Top Commands (by frequency)", true));
println!("{}", "─".repeat(60));
for (cmd, count) in &summary.top_commands {
let cmd_display = if cmd.len() > 50 {
format!("{}...", &cmd[..47])
} else {
cmd.clone()
};
let cmd_display = truncate(cmd, 50);
println!(" {:>4}x {}", count, cmd_display);
}
println!();
@@ -721,17 +725,11 @@ fn show_failures(tracker: &Tracker) -> Result<()> {
println!("{}", styled("Recent Failures (last 10)", true));
println!("{}", "─".repeat(60));
for rec in &summary.recent {
let ts_short = if rec.timestamp.len() >= 16 {
&rec.timestamp[..16]
} else {
&rec.timestamp
};
// ISSUE #2787: floor to the previous char boundary so the prefix
// never exceeds 16 bytes and never lands mid-character
let ts_short = &rec.timestamp[..rec.timestamp.floor_char_boundary(16)];
let status = if rec.fallback_succeeded { "ok" } else { "FAIL" };
let cmd_display = if rec.raw_command.len() > 40 {
format!("{}...", &rec.raw_command[..37])
} else {
rec.raw_command.clone()
};
let cmd_display = truncate(&rec.raw_command, 40);
println!(" {} [{}] {}", ts_short, status, cmd_display);
}
println!();
+1 -1
View File
@@ -110,7 +110,7 @@ pub fn run(_verbose: u8) -> Result<()> {
.file_stem()
.and_then(|s| s.to_str())
.unwrap_or("unknown");
let short_id = if id.len() > 8 { &id[..8] } else { id };
let short_id = &id[..id.floor_char_boundary(8)];
// Extract date from mtime
let date = fs::metadata(path)
+52
View File
@@ -339,6 +339,20 @@ fn has_short_flag(flags: &[String], ch: char) -> bool {
.any(|f| f.starts_with('-') && !f.starts_with("--") && f[1..].contains(ch))
}
fn has_context_flag(flags: &[String]) -> bool {
has_short_flag(flags, 'A')
|| has_short_flag(flags, 'B')
|| has_short_flag(flags, 'C')
|| flags.iter().any(|f| {
f == "--after-context"
|| f == "--before-context"
|| f == "--context"
|| f.starts_with("--after-context=")
|| f.starts_with("--before-context=")
|| f.starts_with("--context=")
})
}
pub fn run(
engine: Engine,
max_line_len: usize,
@@ -464,6 +478,9 @@ pub fn run(
let mut plain = String::new();
for line in raw_output.lines() {
let Some((file, line_num, is_match, content)) = parse_match_line(line) else {
if line == "--" {
plain.push_str("--\n");
}
continue;
};
let sep = if is_match { ':' } else { '-' };
@@ -479,6 +496,8 @@ pub fn run(
plain.push('\n');
}
let has_context = has_context_flag(&extra_args);
let per_file = config::limits().grep_max_per_file;
let mut files: Vec<_> = by_file.iter().collect();
files.sort_by_key(|(f, _)| *f);
@@ -496,10 +515,15 @@ pub fn run(
let file_display = compact_path(file);
let mut file_shown = 0;
let mut prev_line: usize = 0;
for (line_num, is_match, content) in entries.iter().take(per_file) {
if shown >= max_results {
break;
}
if has_context && prev_line > 0 && *line_num > prev_line + 1 {
body.push_str("--\n");
}
prev_line = *line_num;
let sep = if *is_match { ':' } else { '-' };
if show_file {
body.push_str(&file_display);
@@ -1376,4 +1400,32 @@ mod tests {
let stdout = "file.txt\x003-context_before\nfile.txt\x004:match\nfile.txt\x005-context_after\n";
assert_eq!(unparsed_signal(stdout), 0);
}
// --- has_context_flag ---
#[test]
fn test_has_context_flag_short() {
let f = |args: &[&str]| -> bool {
has_context_flag(&args.iter().map(|s| s.to_string()).collect::<Vec<_>>())
};
assert!(f(&["-A", "3"]));
assert!(f(&["-B", "2"]));
assert!(f(&["-C", "1"]));
assert!(!f(&["-rn"]));
assert!(!f(&["-i", "-w"]));
}
#[test]
fn test_has_context_flag_long() {
let f = |args: &[&str]| -> bool {
has_context_flag(&args.iter().map(|s| s.to_string()).collect::<Vec<_>>())
};
assert!(f(&["--after-context", "3"]));
assert!(f(&["--before-context", "2"]));
assert!(f(&["--context", "1"]));
assert!(f(&["--after-context=3"]));
assert!(f(&["--before-context=2"]));
assert!(f(&["--context=1"]));
assert!(!f(&["--color", "auto"]));
}
}
+25
View File
@@ -4,3 +4,28 @@ pub const CONFIG_TOML: &str = "config.toml";
pub const FILTERS_TOML: &str = "filters.toml";
pub const TRUSTED_FILTERS_JSON: &str = "trusted_filters.json";
pub const DEFAULT_HISTORY_DAYS: i64 = 90;
/// RTK-only subcommands that should never fall back to raw execution.
/// When adding a new RTK-only subcommand to `Commands`, add its clap name here.
pub const RTK_META_COMMANDS: &[&str] = &[
"gain",
"discover",
"learn",
"init",
"config",
"proxy",
"run",
"hook",
"hook-audit",
"pipe",
"cc-economics",
"verify",
"trust",
"untrust",
"session",
"rewrite",
"telemetry",
"smart",
"deps",
"json",
];
+316 -47
View File
@@ -22,7 +22,7 @@
/// 6. head/tail_lines — keep first/last N lines
/// 7. max_lines — absolute line cap
/// 8. on_empty — message if result is empty
use super::constants::{FILTERS_TOML, RTK_DATA_DIR};
use super::constants::RTK_META_COMMANDS;
use lazy_static::lazy_static;
use regex::{Regex, RegexSet};
use serde::Deserialize;
@@ -188,48 +188,11 @@ impl TomlFilterRegistry {
fn load() -> Self {
let mut filters = Vec::new();
// 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, verified_content) =
crate::hooks::trust::check_trust_with_content(project_filter_path)
.unwrap_or((crate::hooks::trust::TrustStatus::Untrusted, None));
match trust_status {
crate::hooks::trust::TrustStatus::Trusted
| crate::hooks::trust::TrustStatus::EnvOverride => {
if let Some(content) = verified_content {
match Self::parse_and_compile(&content, "project") {
Ok(f) => filters.extend(f),
Err(e) => eprintln!("[rtk] warning: .rtk/filters.toml: {}", e),
}
}
}
crate::hooks::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::hooks::trust::TrustStatus::ContentChanged { .. } => {
eprintln!("[rtk] WARNING: .rtk/filters.toml changed since trusted.");
eprintln!("[rtk] Filters NOT applied. Run `rtk trust` to re-review.");
}
}
for path in crate::hooks::trust::gated_filter_paths() {
Self::extend_with_trusted(&mut filters, &path);
}
// Priority 2: user-global ~/.config/rtk/filters.toml
if let Some(config_dir) = dirs::config_dir() {
let global_path = config_dir.join(RTK_DATA_DIR).join(FILTERS_TOML);
if let Ok(content) = std::fs::read_to_string(&global_path) {
match Self::parse_and_compile(&content, "user-global") {
Ok(f) => filters.extend(f),
Err(e) => eprintln!("[rtk] warning: {}: {}", global_path.display(), e),
}
}
}
// Priority 3: built-in (embedded at compile time)
let builtin = BUILTIN_TOML;
match Self::parse_and_compile(builtin, "builtin") {
match Self::parse_and_compile(BUILTIN_TOML, "builtin") {
Ok(f) => filters.extend(f),
Err(e) => eprintln!("[rtk] warning: builtin filters: {}", e),
}
@@ -237,6 +200,28 @@ impl TomlFilterRegistry {
TomlFilterRegistry { filters }
}
fn extend_with_trusted(filters: &mut Vec<CompiledFilter>, path: &std::path::Path) {
if !path.exists() {
return;
}
let label = path.display().to_string();
let (status, content) = crate::hooks::trust::check_trust_with_content(path)
.unwrap_or((crate::hooks::trust::TrustStatus::Untrusted, None));
match status {
crate::hooks::trust::TrustStatus::Trusted
| crate::hooks::trust::TrustStatus::EnvOverride => {
if let Some(content) = content {
match Self::parse_and_compile(&content, &label) {
Ok(f) => filters.extend(f),
Err(e) => eprintln!("[rtk] warning: {}: {}", label, e),
}
}
}
crate::hooks::trust::TrustStatus::Untrusted
| crate::hooks::trust::TrustStatus::ContentChanged { .. } => {}
}
}
fn parse_and_compile(content: &str, source: &str) -> Result<Vec<CompiledFilter>, String> {
let file: TomlFilterFile = toml::from_str(content)
.map_err(|e| format!("TOML parse error in {}: {}", source, e))?;
@@ -314,6 +299,10 @@ const RUST_HANDLED_COMMANDS: &[&str] = &[
"learn",
];
pub fn is_rtk_reserved_command(name: &str) -> bool {
RUST_HANDLED_COMMANDS.contains(&name) || RTK_META_COMMANDS.contains(&name)
}
fn compile_filter(name: String, def: TomlFilterDef) -> Result<CompiledFilter, String> {
// Mutual exclusion: strip and keep cannot both be set
if !def.strip_lines_matching.is_empty() && !def.keep_lines_matching.is_empty() {
@@ -410,6 +399,79 @@ lazy_static! {
static ref REGISTRY: TomlFilterRegistry = TomlFilterRegistry::load();
}
pub fn toml_disabled() -> bool {
std::env::var("RTK_NO_TOML").ok().as_deref() == Some("1")
}
pub fn active_filter_summaries(content: &str) -> Vec<(String, String)> {
toml::from_str::<TomlFilterFile>(content)
.map(|f| {
f.filters
.into_iter()
.map(|(name, def)| (name, def.match_command))
.collect()
})
.unwrap_or_default()
}
pub fn filter_parse_error(content: &str) -> Option<String> {
toml::from_str::<TomlFilterFile>(content)
.err()
.map(|e| e.to_string())
}
lazy_static! {
static ref MATCH_SET: RegexSet = build_match_set();
}
pub fn command_matches_filter(command: &str) -> bool {
MATCH_SET.is_match(command)
}
fn build_match_set() -> RegexSet {
let patterns = collect_match_patterns();
RegexSet::new(&patterns).unwrap_or_else(|_| {
let valid: Vec<String> = patterns
.into_iter()
.filter(|p| Regex::new(p).is_ok())
.collect();
RegexSet::new(&valid).unwrap_or_else(|_| RegexSet::empty())
})
}
fn collect_match_patterns() -> Vec<String> {
let mut patterns: Vec<String> = Vec::new();
for path in crate::hooks::trust::gated_filter_paths() {
if !path.exists() {
continue;
}
let (status, content) = crate::hooks::trust::check_trust_with_content(&path)
.unwrap_or((crate::hooks::trust::TrustStatus::Untrusted, None));
if matches!(
status,
crate::hooks::trust::TrustStatus::Trusted
| crate::hooks::trust::TrustStatus::EnvOverride
) {
if let Some(content) = content {
patterns.extend(match_patterns_in(&content));
}
}
}
patterns.extend(match_patterns_in(BUILTIN_TOML));
patterns
}
fn match_patterns_in(content: &str) -> Vec<String> {
match toml::from_str::<TomlFilterFile>(content) {
Ok(file) if file.schema_version == 1 => file
.filters
.into_values()
.map(|def| def.match_command)
.collect(),
_ => Vec::new(),
}
}
// ---------------------------------------------------------------------------
// Public API — pure functions (testable without global state)
// ---------------------------------------------------------------------------
@@ -435,6 +497,22 @@ pub fn find_filter_in<'a>(
/// 7. max_lines — absolute line cap
/// 8. on_empty — message if result is empty
pub fn apply_filter(filter: &CompiledFilter, stdout: &str) -> String {
apply_filter_with_info(filter, stdout).0
}
#[derive(Debug, PartialEq)]
pub enum Lossiness {
None,
/// `tail -n +{tail_offset}` over `tee_payload` reproduces the dropped lines,
/// up to the tee `max_file_size` cap (larger payloads are truncated in the tee file).
Tail {
tee_payload: String,
tail_offset: usize,
},
Whole,
}
pub fn apply_filter_with_info(filter: &CompiledFilter, stdout: &str) -> (String, Lossiness) {
let mut lines: Vec<String> = stdout.lines().map(String::from).collect();
// 1. strip_ansi
@@ -472,7 +550,7 @@ pub fn apply_filter(filter: &CompiledFilter, stdout: &str) -> String {
continue; // errors/warnings present — skip this rule
}
}
return rule.message.clone();
return (rule.message.clone(), Lossiness::Whole);
}
}
}
@@ -485,41 +563,60 @@ pub fn apply_filter(filter: &CompiledFilter, stdout: &str) -> String {
}
// 5. truncate_lines_at — uses utils::truncate (unicode-safe)
let mut intra_line_loss = false;
if let Some(max_chars) = filter.truncate_lines_at {
lines = lines
.into_iter()
.map(|l| crate::core::utils::truncate(&l, max_chars))
.map(|line| {
let truncated = crate::core::utils::truncate(&line, max_chars);
if truncated != line {
intra_line_loss = true;
}
truncated
})
.collect();
}
let snapshot_for_tail = !intra_line_loss
&& filter.tail_lines.is_none()
&& (filter.head_lines.is_some() || filter.max_lines.is_some());
let pre_cut = snapshot_for_tail.then(|| lines.clone());
// 6. head + tail
let total = lines.len();
let mut noncontiguous_drop = false;
let mut head_cut: Option<usize> = None;
if let (Some(head), Some(tail)) = (filter.head_lines, filter.tail_lines) {
if total > head + tail {
let mut result = lines[..head].to_vec();
result.push(format!("... ({} lines omitted)", total - head - tail));
result.extend_from_slice(&lines[total - tail..]);
lines = result;
noncontiguous_drop = true;
}
} else if let Some(head) = filter.head_lines {
if total > head {
lines.truncate(head);
lines.push(format!("... ({} lines omitted)", total - head));
head_cut = Some(head);
}
} else if let Some(tail) = filter.tail_lines {
if total > tail {
let omitted = total - tail;
lines = lines[omitted..].to_vec();
lines.insert(0, format!("... ({} lines omitted)", omitted));
noncontiguous_drop = true;
}
}
// 7. max_lines — absolute cap applied after head/tail (includes omit messages)
let mut max_cut: Option<usize> = None;
if let Some(max) = filter.max_lines {
if lines.len() > max {
let truncated = lines.len() - max;
let dropped = lines.len() - max;
lines.truncate(max);
lines.push(format!("... ({} lines truncated)", truncated));
lines.push(format!("... ({} lines truncated)", dropped));
max_cut = Some(max);
}
}
@@ -527,11 +624,30 @@ pub fn apply_filter(filter: &CompiledFilter, stdout: &str) -> String {
let result = lines.join("\n");
if result.trim().is_empty() {
if let Some(ref msg) = filter.on_empty {
return msg.clone();
return (msg.clone(), Lossiness::None);
}
}
result
let loss = if let Some(snapshot) = pre_cut {
match (head_cut, max_cut) {
(Some(_), Some(_)) => Lossiness::Whole,
(Some(head), None) => Lossiness::Tail {
tee_payload: snapshot.join("\n"),
tail_offset: head + 1,
},
(None, Some(max)) => Lossiness::Tail {
tee_payload: snapshot.join("\n"),
tail_offset: max + 1,
},
(None, None) => Lossiness::None,
}
} else if noncontiguous_drop || intra_line_loss || head_cut.is_some() || max_cut.is_some() {
Lossiness::Whole
} else {
Lossiness::None
};
(result, loss)
}
// ---------------------------------------------------------------------------
@@ -706,6 +822,159 @@ mod tests {
.expect("expected at least one filter")
}
#[test]
fn command_matches_filter_agrees_with_find_matching_filter() {
for cmd in ["jj log", "jq .", "frobnicate xyz", "cd /tmp"] {
assert_eq!(
command_matches_filter(cmd),
find_matching_filter(cmd).is_some(),
"match-set disagreed with registry for {cmd:?}"
);
}
}
#[test]
fn test_loss_tail_configured_unfired_max_fires_is_whole() {
let toml = "schema_version = 1\n[filters.f]\nmatch_command = \"^cmd\"\ntail_lines = 100\nmax_lines = 2\n";
let (out, loss) = apply_filter_with_info(&first_filter(toml), "a\nb\nc\nd\ne");
assert!(out.contains("lines truncated"));
assert_ne!(loss, Lossiness::None);
}
#[test]
fn test_match_patterns_in_honors_schema_version() {
let v1 = "schema_version = 1\n[filters.a]\nmatch_command = \"^aaa\"\n";
assert_eq!(match_patterns_in(v1), vec!["^aaa".to_string()]);
let v2 = "schema_version = 2\n[filters.a]\nmatch_command = \"^aaa\"\n";
assert!(match_patterns_in(v2).is_empty());
assert!(match_patterns_in("not valid toml {{{").is_empty());
}
#[test]
fn test_filter_parse_error() {
assert!(
filter_parse_error("schema_version = 1\n[filters.a]\nmatch_command = \"^a\"\n")
.is_none()
);
assert!(filter_parse_error("[filters.a]\nmatch_command = \"^a\"\n").is_some());
assert!(filter_parse_error("this is { not toml").is_some());
}
#[test]
fn test_is_rtk_reserved_command() {
assert!(is_rtk_reserved_command("git"));
assert!(is_rtk_reserved_command("cargo"));
assert!(is_rtk_reserved_command("json"));
assert!(is_rtk_reserved_command("rewrite"));
assert!(!is_rtk_reserved_command("jj"));
assert!(!is_rtk_reserved_command("jq"));
assert!(!is_rtk_reserved_command("just"));
assert!(!is_rtk_reserved_command("frobnicate"));
}
fn loss_of(toml: &str, input: &str) -> Lossiness {
apply_filter_with_info(&first_filter(toml), input).1
}
#[test]
fn test_loss_head_lines_is_tail() {
let toml = "schema_version = 1\n[filters.f]\nmatch_command = \"^cmd\"\nhead_lines = 2\n";
let (out, loss) = apply_filter_with_info(&first_filter(toml), "a\nb\nc\nd\ne");
assert!(out.starts_with("a\nb\n"));
match loss {
Lossiness::Tail {
tee_payload,
tail_offset,
} => {
assert_eq!(tail_offset, 3);
let recovered: Vec<&str> = tee_payload.lines().skip(tail_offset - 1).collect();
assert_eq!(recovered, vec!["c", "d", "e"]);
}
other => panic!("expected Tail, got {:?}", other),
}
}
#[test]
fn test_loss_max_lines_is_tail() {
let toml = "schema_version = 1\n[filters.f]\nmatch_command = \"^cmd\"\nmax_lines = 2\n";
match loss_of(toml, "a\nb\nc\nd\ne") {
Lossiness::Tail {
tee_payload,
tail_offset,
} => {
assert_eq!(tail_offset, 3);
let recovered: Vec<&str> = tee_payload.lines().skip(tail_offset - 1).collect();
assert_eq!(recovered, vec!["c", "d", "e"]);
}
other => panic!("expected Tail, got {:?}", other),
}
}
#[test]
fn test_loss_tail_lines_is_whole() {
let toml = "schema_version = 1\n[filters.f]\nmatch_command = \"^cmd\"\ntail_lines = 2\n";
assert_eq!(loss_of(toml, "a\nb\nc\nd\ne"), Lossiness::Whole);
}
#[test]
fn test_loss_head_then_max_is_whole() {
let toml = "schema_version = 1\n[filters.f]\nmatch_command = \"^cmd\"\nhead_lines = 2\nmax_lines = 2\n";
assert_eq!(loss_of(toml, "a\nb\nc\nd\ne"), Lossiness::Whole);
}
#[test]
fn test_loss_head_plus_tail_is_whole() {
let toml = "schema_version = 1\n[filters.f]\nmatch_command = \"^cmd\"\nhead_lines = 1\ntail_lines = 1\n";
assert_eq!(loss_of(toml, "a\nb\nc\nd\ne"), Lossiness::Whole);
}
#[test]
fn test_loss_truncate_lines_at_is_whole() {
let toml =
"schema_version = 1\n[filters.f]\nmatch_command = \"^cmd\"\ntruncate_lines_at = 3\n";
assert_eq!(loss_of(toml, "abcdefgh\nshort"), Lossiness::Whole);
}
#[test]
fn test_loss_match_output_is_whole() {
let toml = "schema_version = 1\n[filters.f]\nmatch_command = \"^cmd\"\n[[filters.f.match_output]]\npattern = \"ok\"\nmessage = \"all good\"\n";
let (out, loss) = apply_filter_with_info(&first_filter(toml), "everything ok here\nmore");
assert_eq!(out, "all good");
assert_eq!(loss, Lossiness::Whole);
}
#[test]
fn test_loss_strip_only_is_none() {
let toml = "schema_version = 1\n[filters.f]\nmatch_command = \"^cmd\"\nstrip_lines_matching = [\"^noise\"]\n";
let (out, loss) = apply_filter_with_info(&first_filter(toml), "keep\nnoise line\nkeep2");
assert_eq!(out, "keep\nkeep2");
assert_eq!(loss, Lossiness::None);
}
#[test]
fn test_loss_on_empty_is_none() {
let toml = "schema_version = 1\n[filters.f]\nmatch_command = \"^cmd\"\nstrip_lines_matching = [\".\"]\non_empty = \"nothing\"\n";
let (out, loss) = apply_filter_with_info(&first_filter(toml), "a\nb\nc");
assert_eq!(out, "nothing");
assert_eq!(loss, Lossiness::None);
}
#[test]
fn test_loss_no_truncation_is_none() {
let toml = "schema_version = 1\n[filters.f]\nmatch_command = \"^cmd\"\nhead_lines = 10\n";
assert_eq!(loss_of(toml, "a\nb\nc"), Lossiness::None);
}
#[test]
fn test_apply_filter_wrapper_matches_with_info() {
let toml = "schema_version = 1\n[filters.f]\nmatch_command = \"^cmd\"\nhead_lines = 2\n";
let f = first_filter(toml);
let input = "a\nb\nc\nd";
assert_eq!(apply_filter(&f, input), apply_filter_with_info(&f, input).0);
}
// --- Pipeline primitives (existing) ---
#[test]
+11
View File
@@ -639,6 +639,17 @@ mod tests {
assert!(result.ends_with("..."));
}
#[test]
fn test_truncate_multibyte_cyrillic_issue_2787() {
// Regression: `rtk gain --history` panicked slicing this at byte 22,
// which falls inside 'н' (Cyrillic chars are 2 bytes each)
let cmd = "rtk ls -la Ародинамический расчёт Новый";
let result = truncate(cmd, 25);
assert_eq!(result.chars().count(), 25);
assert!(result.ends_with("..."));
assert_eq!(result, "rtk ls -la Ародинамиче...");
}
// ===== resolve_binary tests (issue #212) =====
#[test]
+103 -1
View File
@@ -888,7 +888,25 @@ fn rewrite_segment_inner(
}
rtk_equivalent
}
_ => return None,
// TOML-only commands: consult the registry so the hook filters them too (#2179).
Classification::Unsupported { .. } => {
if crate::core::toml_filter::toml_disabled() {
return None;
}
let normalized = strip_absolute_path(cmd_part.trim());
if is_excluded(&normalized, excluded) {
return None;
}
let base = normalized.split_whitespace().next().unwrap_or("");
if crate::core::toml_filter::is_rtk_reserved_command(base) {
return None;
}
if crate::core::toml_filter::command_matches_filter(&normalized) {
return Some(format!("rtk {}{}", cmd_part, redirect_suffix));
}
return None;
}
Classification::Ignored => return None,
};
// Find the matching rule (rtk_cmd values are unique across all rules)
@@ -1447,6 +1465,90 @@ mod tests {
assert_eq!(rewrite_command_no_prefixes("cd /tmp", &[]), None);
}
#[test]
fn test_rewrite_toml_orphan_jj() {
assert_eq!(
rewrite_command_no_prefixes("jj log", &[]),
Some("rtk jj log".into())
);
}
#[test]
fn test_rewrite_toml_orphan_jq() {
assert_eq!(
rewrite_command_no_prefixes("jq .", &[]),
Some("rtk jq .".into())
);
}
#[test]
fn test_rewrite_toml_orphan_just() {
assert_eq!(
rewrite_command_no_prefixes("just build", &[]),
Some("rtk just build".into())
);
}
#[test]
fn test_rewrite_toml_absolute_path() {
assert_eq!(
rewrite_command_no_prefixes("/usr/bin/jj log", &[]),
Some("rtk /usr/bin/jj log".into())
);
}
#[test]
fn test_rewrite_toml_redirect_suffix_preserved() {
assert_eq!(
rewrite_command_no_prefixes("jj log 2>&1", &[]),
Some("rtk jj log 2>&1".into())
);
}
#[test]
fn test_rewrite_toml_in_pipe_left_only() {
assert_eq!(
rewrite_command_no_prefixes("jj log | head", &[]),
Some("rtk jj log | head".into())
);
}
#[test]
fn test_rewrite_toml_compound() {
assert_eq!(
rewrite_command_no_prefixes("jj diff && jq .", &[]),
Some("rtk jj diff && rtk jq .".into())
);
}
#[test]
fn test_rewrite_toml_env_prefix() {
assert_eq!(
rewrite_command_no_prefixes("FOO=bar jj log", &[]),
Some("FOO=bar rtk jj log".into())
);
}
#[test]
fn test_rewrite_toml_respects_exclude() {
let excluded = vec!["jj".to_string()];
assert_eq!(rewrite_command_no_prefixes("jj log", &excluded), None);
}
#[test]
fn test_rewrite_toml_exclude_matches_absolute_path() {
let excluded = vec!["jj".to_string()];
assert_eq!(
rewrite_command_no_prefixes("/usr/bin/jj log", &excluded),
None
);
}
#[test]
fn test_rewrite_toml_unknown_command_still_none() {
assert_eq!(rewrite_command_no_prefixes("frobnicate xyz", &[]), None);
}
#[test]
fn test_rewrite_with_env_prefix() {
assert_eq!(
+20
View File
@@ -120,3 +120,23 @@ First match wins. A project filter with the same name as a built-in shadows the
```
[rtk] warning: filter 'make' is shadowing a built-in filter
```
## Custom filters and trust
You can add your own filters in two places (both use the format above):
- **Project-local** — `.rtk/filters.toml` (committed with a repo, applies in that project)
- **User-global** — `~/.config/rtk/filters.toml` (applies in every project)
Because a filter can rewrite or hide the command output an agent sees, **custom filter files are not applied until you trust them**. An untrusted (or edited) filter file is skipped **silently** on the command path — RTK never prints a warning around a rewritten command. You discover and enable untrusted filters through commands you run deliberately:
```bash
rtk trust # lists each detected filter (labelled project/global) + a risk summary, then asks to confirm ([y/N], or --yes)
rtk untrust # revokes trust
```
- Trust is recorded as a SHA-256 of the file's contents, so **editing a trusted file requires re-running `rtk trust`** — a content change invalidates trust.
- `rtk init` detects existing custom filters and lets you enable them — an interactive `[y/N]`, or `--trust-filters` / `--no-trust-filters` for scripts. It stays silent for an empty template (comments only) and, when run non-interactively, leaves filters disabled.
- Built-in filters (this directory) are compiled into the binary and always trusted; only the on-disk project and user-global files are gated.
> **Honest limitation:** this is consent + tamper-evidence, not a sandbox. An attacker who can write your filter file can usually also write the trust store (`~/.local/share/rtk/trusted_filters.json`) and bypass the gate. It defends the common case — a filter dropped in by a script, a dotfile sync, or an untrusted repo — not a same-user attacker who specifically targets RTK.
+65
View File
@@ -79,6 +79,14 @@ pub enum PatchMode {
Skip, // --no-patch: manual instructions
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub enum FilterTrust {
#[default]
Ask,
Trust,
Skip,
}
/// Result of settings.json patching operation
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PatchResult {
@@ -1416,6 +1424,63 @@ fn generate_global_filters_template(ctx: InitContext) -> Result<()> {
Ok(())
}
pub fn finalize_filter_trust(global: bool, dry_run: bool, trust: FilterTrust) -> Result<()> {
let paths = crate::hooks::trust::gated_filter_paths();
let path = match if global { paths.get(1) } else { paths.first() } {
Some(p) => p,
None => return Ok(()),
};
if !path.exists() {
return Ok(());
}
let status = crate::hooks::trust::check_trust(path)
.unwrap_or(crate::hooks::trust::TrustStatus::Untrusted);
if matches!(
status,
crate::hooks::trust::TrustStatus::Trusted | crate::hooks::trust::TrustStatus::EnvOverride
) {
return Ok(());
}
let bytes = match fs::read(path) {
Ok(b) => b,
Err(_) => return Ok(()),
};
let content = String::from_utf8_lossy(&bytes);
let filters = crate::core::toml_filter::active_filter_summaries(&content);
if filters.is_empty() {
return Ok(());
}
if dry_run {
println!(
"[dry-run] {} untrusted custom filter(s) in {}",
filters.len(),
path.display()
);
return Ok(());
}
let scope = if global { "global" } else { "project" };
crate::hooks::trust::print_filter_notice(path, scope, &filters);
let enable = match trust {
FilterTrust::Trust => true,
FilterTrust::Skip => false,
FilterTrust::Ask => crate::hooks::trust::confirm_enable_at_tty()?,
};
if enable {
let hash = crate::hooks::integrity::compute_hash_bytes(&bytes);
crate::hooks::trust::trust_filter_with_hash(path, &hash)?;
eprintln!("Enabled. Revoke with `rtk untrust`.");
} else {
eprintln!("\x1b[33m Not enabled — run `rtk trust` to review and enable.\x1b[0m");
}
Ok(())
}
/// Hook-only mode: just the hook, no RTK.md
fn run_hook_only_mode(
global: bool,
+149 -45
View File
@@ -196,19 +196,56 @@ pub fn list_trusted() -> Result<HashMap<String, TrustEntry>> {
Ok(store.trusted)
}
pub fn gated_filter_paths() -> Vec<PathBuf> {
gated_filter_paths_labeled()
.into_iter()
.map(|(_, path)| path)
.collect()
}
pub fn gated_filter_paths_labeled() -> Vec<(&'static str, PathBuf)> {
let mut paths = vec![("project", PathBuf::from(".rtk/filters.toml"))];
if let Some(dir) = dirs::config_dir() {
paths.push((
"global",
dir.join(RTK_DATA_DIR)
.join(crate::core::constants::FILTERS_TOML),
));
}
paths
}
pub fn untrusted_active_filter_count() -> usize {
gated_filter_paths_labeled()
.into_iter()
.filter(|(_, path)| path.exists())
.filter(|(_, path)| {
!matches!(
check_trust(path).unwrap_or(TrustStatus::Untrusted),
TrustStatus::Trusted | TrustStatus::EnvOverride
)
})
.map(|(_, path)| {
std::fs::read_to_string(&path)
.map(|c| crate::core::toml_filter::active_filter_summaries(&c).len())
.unwrap_or(0)
})
.sum()
}
// ---------------------------------------------------------------------------
// CLI commands
// ---------------------------------------------------------------------------
/// Run `rtk trust` — review and trust project-local filters.
pub fn run_trust(list: bool) -> Result<()> {
pub fn run_trust(list: bool, yes: bool) -> Result<()> {
if list {
let trusted = list_trusted()?;
if trusted.is_empty() {
println!("No trusted project filters.");
println!("No trusted filters.");
return Ok(());
}
println!("Trusted project filters:");
println!("Trusted filters:");
println!("{}", "═".repeat(60));
for (path, entry) in &trusted {
let date = entry.trusted_at.get(..10).unwrap_or(&entry.trusted_at);
@@ -218,54 +255,110 @@ pub fn run_trust(list: bool) -> Result<()> {
return Ok(());
}
let filter_path = Path::new(".rtk/filters.toml");
if !filter_path.exists() {
anyhow::bail!("No .rtk/filters.toml found in current directory");
let interactive = std::io::IsTerminal::is_terminal(&std::io::stdin());
let mut found_any = false;
let mut enabled_any = false;
let mut had_error = false;
for (scope, filter_path) in gated_filter_paths_labeled() {
if !filter_path.exists() {
continue;
}
let bytes = std::fs::read(&filter_path)
.with_context(|| format!("Failed to read {}", filter_path.display()))?;
let content = String::from_utf8_lossy(&bytes);
if let Some(err) = crate::core::toml_filter::filter_parse_error(&content) {
had_error = true;
eprintln!(
" {} — invalid TOML, not loaded: {}",
filter_path.display(),
err
);
continue;
}
let filters = crate::core::toml_filter::active_filter_summaries(&content);
if filters.is_empty() {
continue;
}
found_any = true;
if matches!(
check_trust(&filter_path).unwrap_or(TrustStatus::Untrusted),
TrustStatus::Trusted | TrustStatus::EnvOverride
) {
eprintln!(" {} already trusted.", filter_path.display());
enabled_any = true;
continue;
}
print_filter_notice(&filter_path, scope, &filters);
print_risk_summary(&content);
if !(yes || confirm_enable_at_tty()?) {
eprintln!(" Not enabled — re-run `rtk trust --yes` to trust non-interactively.");
continue;
}
let hash = crate::hooks::integrity::compute_hash_bytes(&bytes);
trust_filter_with_hash(&filter_path, &hash)?;
enabled_any = true;
eprintln!(" Enabled — revoke with `rtk untrust`.");
}
// 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.");
if !found_any {
if had_error {
anyhow::bail!("Filter file present but not valid TOML — see the error above.");
}
anyhow::bail!("No custom filters found (.rtk/filters.toml or ~/.config/rtk/filters.toml)");
}
if !enabled_any {
if !interactive {
anyhow::bail!("Custom filters found but none enabled — re-run `rtk trust --yes`.");
}
return Ok(());
}
println!("Filters will now be applied.");
Ok(())
}
pub fn print_filter_notice(path: &Path, scope: &str, filters: &[(String, String)]) {
let yellow = "\x1b[33m";
let reset = "\x1b[0m";
eprintln!();
eprintln!(
"{yellow}Detected {} custom {scope} scoped toml filter(s) in {} — they rewrite matching command output:{reset}",
filters.len(),
path.display()
);
for (name, regex) in filters {
eprintln!("{yellow} {name:<20} {regex}{reset}");
}
}
pub fn confirm_enable_at_tty() -> Result<bool> {
use std::io::{self, BufRead, IsTerminal};
if !io::stdin().is_terminal() {
return Ok(false);
}
eprint!("\x1b[33m Enable these filters? [y/N] \x1b[0m");
let mut line = String::new();
io::stdin()
.lock()
.read_line(&mut line)
.context("Failed to read user input")?;
Ok(matches!(line.trim().to_lowercase().as_str(), "y" | "yes"))
}
/// 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.");
let mut revoked_any = false;
for filter_path in gated_filter_paths() {
if untrust_filter(&filter_path).unwrap_or(false) {
revoked_any = true;
println!("Trust revoked for {}", filter_path.display());
}
}
if !revoked_any {
println!("No trusted filters found to revoke.");
}
Ok(())
}
@@ -275,7 +368,7 @@ pub fn run_untrust() -> Result<()> {
// ---------------------------------------------------------------------------
fn print_risk_summary(content: &str) {
let filter_count = content.matches("[filters.").count();
let filter_count = crate::core::toml_filter::active_filter_summaries(content).len();
let has_replace = content.contains("replace");
let has_match_output = content.contains("match_output");
let has_dot_pattern = content.contains("pattern = \".\"") || content.contains("pattern = '.'");
@@ -389,6 +482,17 @@ mod tests {
Ok(removed)
}
#[test]
fn test_gated_filter_paths_covers_project_and_global() {
let paths = gated_filter_paths();
assert_eq!(paths[0], PathBuf::from(".rtk/filters.toml"));
if dirs::config_dir().is_some() {
assert_eq!(paths.len(), 2);
assert!(paths[1].ends_with("filters.toml"));
assert!(paths[1].is_absolute());
}
}
#[test]
fn test_untrusted_by_default() {
let temp = TempDir::new().unwrap();
+53 -39
View File
@@ -368,6 +368,14 @@ enum Commands {
#[arg(long = "no-patch", group = "patch")]
no_patch: bool,
/// Trust and enable detected custom filters without prompting
#[arg(long = "trust-filters", group = "trust")]
trust_filters: bool,
/// Leave detected custom filters disabled without prompting
#[arg(long = "no-trust-filters", group = "trust")]
no_trust_filters: bool,
/// Remove RTK artifacts for the selected assistant mode
#[arg(long)]
uninstall: bool,
@@ -644,9 +652,12 @@ enum Commands {
/// Trust project-local TOML filters in current directory
Trust {
/// List all trusted projects
/// List all trusted filter files
#[arg(long)]
list: bool,
/// Trust without prompting (for non-interactive use)
#[arg(long, short = 'y')]
yes: bool,
},
/// Revoke trust for project-local TOML filters
@@ -1225,32 +1236,6 @@ enum GoCommands {
Other(Vec<OsString>),
}
/// RTK-only subcommands that should never fall back to raw execution.
/// If Clap fails to parse these, show the Clap error directly.
/// When adding a new RTK-only subcommand to `Commands`, add its clap name here.
const RTK_META_COMMANDS: &[&str] = &[
"gain",
"discover",
"learn",
"init",
"config",
"proxy",
"run",
"hook",
"hook-audit",
"pipe",
"cc-economics",
"verify",
"trust",
"untrust",
"session",
"rewrite",
"telemetry",
"smart",
"deps",
"json",
];
fn run_fallback(parse_error: clap::Error) -> Result<i32> {
let args: Vec<String> = std::env::args().skip(1).collect();
@@ -1261,7 +1246,7 @@ fn run_fallback(parse_error: clap::Error) -> Result<i32> {
// RTK meta-commands should never fall back to raw execution.
// e.g. `rtk gain --badtypo` should show Clap's error, not try to run `gain` from $PATH.
if RTK_META_COMMANDS.contains(&args[0].as_str()) {
if core::constants::RTK_META_COMMANDS.contains(&args[0].as_str()) {
parse_error.exit();
}
@@ -1283,7 +1268,7 @@ fn run_fallback(parse_error: clap::Error) -> Result<i32> {
.collect::<Vec<_>>()
.join(" ")
};
let toml_match = if std::env::var("RTK_NO_TOML").ok().as_deref() == Some("1") {
let toml_match = if core::toml_filter::toml_disabled() {
None
} else {
core::toml_filter::find_matching_filter(&lookup_cmd)
@@ -1321,16 +1306,34 @@ fn run_fallback(parse_error: clap::Error) -> Result<i32> {
} else {
stdout_raw.to_string()
};
// Tee raw output BEFORE filtering on failure — lets LLM re-read if needed
let tee_hint = if !output.status.success() {
let success = output.status.success();
let (filtered, loss) =
core::toml_filter::apply_filter_with_info(filter, &combined_raw);
let lossy = !matches!(loss, core::toml_filter::Lossiness::None);
let hint = if !success {
core::tee::tee_and_hint(&combined_raw, &raw_command, exit_code)
} else {
None
match &loss {
core::toml_filter::Lossiness::None => None,
core::toml_filter::Lossiness::Tail {
tee_payload,
tail_offset,
} => {
core::tee::force_tee_tail_hint(tee_payload, &raw_command, *tail_offset)
}
core::toml_filter::Lossiness::Whole => {
core::tee::force_tee_hint(&combined_raw, &raw_command)
}
}
};
let filtered = core::toml_filter::apply_filter(filter, &combined_raw);
let shown =
core::runner::emit_guarded(&filtered, tee_hint.as_deref(), &combined_raw);
// Never emit an unrecoverable truncation marker: fall back to full raw.
let shown = if lossy && hint.is_none() {
core::runner::emit_guarded(&combined_raw, None, &combined_raw)
} else {
core::runner::emit_guarded(&filtered, hint.as_deref(), &combined_raw)
};
timer.track(
&raw_command,
@@ -1945,6 +1948,8 @@ fn run_cli() -> Result<i32> {
hook_only,
auto_patch,
no_patch,
trust_filters,
no_trust_filters,
uninstall,
codex,
copilot,
@@ -2030,6 +2035,14 @@ fn run_cli() -> Result<i32> {
patch_mode,
ctx,
)?;
let filter_trust = if trust_filters {
hooks::init::FilterTrust::Trust
} else if no_trust_filters || auto_patch {
hooks::init::FilterTrust::Skip
} else {
hooks::init::FilterTrust::Ask
};
hooks::init::finalize_filter_trust(global, dry_run, filter_trust)?;
}
0
}
@@ -2588,8 +2601,8 @@ fn run_cli() -> Result<i32> {
core::utils::exit_code_from_status(&status, &cmd_name)
}
Commands::Trust { list } => {
hooks::trust::run_trust(list)?;
Commands::Trust { list, yes } => {
hooks::trust::run_trust(list, yes)?;
0
}
@@ -2989,7 +3002,7 @@ mod tests {
fn test_meta_commands_reject_bad_flags() {
// 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 {
for cmd in core::constants::RTK_META_COMMANDS {
if matches!(*cmd, "proxy" | "run" | "rewrite" | "session") {
continue; // these use trailing_var_arg (accept any args by design)
}
@@ -3073,7 +3086,8 @@ mod tests {
.get_subcommands()
.map(|c| c.get_name().to_string())
.filter(|name| {
!RTK_META_COMMANDS.contains(&name.as_str()) && !PASSTHROUGH.contains(&name.as_str())
!core::constants::RTK_META_COMMANDS.contains(&name.as_str())
&& !PASSTHROUGH.contains(&name.as_str())
})
.collect();
+60
View File
@@ -83,6 +83,66 @@ fn count_output_has_no_nul_separator() {
);
}
#[test]
fn group_separator_between_non_adjacent_matches() {
let dir = tempfile::tempdir().unwrap();
let f = dir.path().join("sep.txt");
std::fs::write(
&f,
"alpha match here\nfiller 1\nfiller 2\nfiller 3\nfiller 4\nfiller 5\nbeta match here\n",
)
.unwrap();
let out = rtk()
.args(["grep", "-A1", "match", f.to_str().unwrap()])
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
stdout.contains("--"),
"missing group separator between non-adjacent match blocks:\n{stdout}"
);
assert!(
stdout.contains("alpha match here"),
"first match must be present:\n{stdout}"
);
assert!(
stdout.contains("beta match here"),
"second match must be present:\n{stdout}"
);
}
#[test]
fn no_separator_without_context_flag() {
let dir = tempfile::tempdir().unwrap();
let f = dir.path().join("nosep.txt");
std::fs::write(
&f,
"match line 1\nfiller\nfiller\nfiller\nmatch line 2\nfiller\nfiller\nmatch line 3\n",
)
.unwrap();
let out = rtk()
.args(["grep", "-n", "match", f.to_str().unwrap()])
.output()
.unwrap();
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
!stdout.contains("--"),
"plain grep without -A/-B/-C must not insert -- separators:\n{stdout}"
);
assert!(
stdout.contains("match line 1"),
"first match must be present:\n{stdout}"
);
assert!(
stdout.contains("match line 3"),
"third match must be present:\n{stdout}"
);
}
#[test]
fn only_matching_output_has_no_nul_separator() {
if !rg_available() {
+11
View File
@@ -94,6 +94,17 @@ fn context_flags_match_grep_n() {
assert_eq_grep_n(&["-C1", "MATCH", &f]);
}
#[test]
fn context_group_separator_matches_grep_n() {
let d = tempfile::tempdir().unwrap();
let f = write(
d.path(),
"sep.txt",
"match A\nfill1\nfill2\nfill3\nmatch B\n",
);
assert_eq_grep_n(&["-A1", "match", &f]);
}
// #1436: a single-file `-n` search with `::` content and a BRE pattern with
// literal `()` must equal grep exactly — no broadened matches, and no synthetic
// `[file]` bucket from splitting on `::`.