Compare commits

...
Author SHA1 Message Date
Nicolas Le Cam d402152ffa Merge pull request #1422 from JackDanger/fix/suppress-hook-warn-during-init
fix: suppress hook warning during rtk init and verify
2026-09-14 01:20:47 +02:00
Nicolas Le CamandClaude Opus 5 06d538728c test: cover which commands get the daily hook reminder
Pins both directions: the commands that report hook state themselves stay
quiet, and the filtered commands still warn. Also pins the reason the
suppression is worth having — `maybe_warn` touches the once-a-day marker, so
warning on a meta command would leave the next filtered command silent.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-14 01:01:14 +02:00
Nicolas Le Cam cfe248c1f6 Merge pull request #3941 from iliaal/fix/faithful-head-tail-windows
fix(read): make head/tail rewrites faithful to the native commands
2026-09-14 00:59:57 +02:00
Nicolas Le CamandClaude Opus 5 784d347011 test(read): isolate the rewrite test from the developer's rtk config
`rewritten_head_spellings_match_native_on_non_utf8_files` isolates
`CLAUDE_CONFIG_DIR` but reads the ambient `XDG_CONFIG_HOME`, so a config
carrying `exclude_commands = ["head", "tail"]` suppresses the rewrite and
the exit-code-3 assertion fails. Clean runners have no such config, so the
test passes in CI and fails only for the developers most likely to have
opted out of these very rewrites.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-14 00:45:35 +02:00
Nicolas Le CamandClaude Opus 5 e224b159af docs(read): point the head/tail rewrite docs at --head-lines
The pipeline diagram, the discover walkthrough and the `rtk read` option
table still described the `--max-lines` mapping this branch replaced, and
the repo's own suggest hook still proposed `--max-lines N` for `head -N`
— the mapping this branch exists to correct.

Drop the `head -` disjunct in the rewrite guard: every string with that
prefix also has the `head ` prefix that sits next to it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-14 00:45:35 +02:00
Nicolas Le Cam 2ff2f71711 Merge pull request #1298 from rtk-ai/fix/tracking-weighted-aggregations
fix(tracking): weighted savings rate in low_savings_commands and avg_savings_per_command
2026-09-14 00:37:18 +02:00
Nicolas Le CamandClaude Fable 5.1 cb5e5994e1 fix(tracking): align the telemetry rates with rtk gain and pin them in memory
`get_by_command` moved to the volume-weighted rate while this branch was
open (#891), summing every call and guarding the division at group level.
The two telemetry queries now use the same shape: the row-level
`WHERE input_tokens > 0` is gone, so a call with no input that still
printed something counts against its command exactly as it does in the
By Command table, and `HAVING SUM(input_tokens) > 0` keeps commands that
never had any input out of both, as before.

`low_savings_commands` lists net-regressing commands: `sav > 0.0` became
`sav <> 0.0`, so only exact 0% stays with `passthrough_top`. A command
that emits more than it saves is the filter to fix first, and with the
weighted rate the old bound also dropped commands the unweighted query
used to list.

The two regression tests opened the on-disk tracker, so every `cargo test`
wrote ten synthetic rows (one at 100k input tokens) into whichever history
database `Tracker::new()` resolves to, on a developer machine the real one.
They now use `Tracker::new_in_memory()` like the rest of the module, and
`test_avg_savings_per_command_inner_weighted` only asserted a `0..=100`
range that the unweighted query also satisfied. Both tests now assert the
exact weighted figures, check each listed rate against `get_summary()`,
and fail when either query goes back to `AVG`, to the row filter, or to
the positive bound.

Tests are numbered 18 and 19 after the ones develop already carries as
14-17. The `low_savings_commands` doc no longer points at a PR, and both
telemetry field tables describe the new semantics.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-13 21:05:32 +02:00
Nicolas Le Cam 4b6c0f00ef Merge remote-tracking branch 'upstream/develop' into pr-1298-merge 2026-09-13 20:35:13 +02:00
Nicolas Le Cam b6a171242c Merge pull request #891 from rtk-ai/fix/gain-weighted-avg
fix(gain): use weighted savings rate in per-command stats
2026-09-13 20:30:32 +02:00
Ilia Alshanetsky 23a1be622f test(read): isolate rewrite permission settings 2026-09-13 12:35:05 -04:00
Ilia Alshanetsky 6f4913b37b fix(read): preserve non-UTF-8 head and tail windows 2026-09-13 12:27:47 -04:00
Nicolas Le CamandClaude Opus 5 9573488935 test(tracking): cover the weighted rate with isolated in-memory cases
Move the weighted-rate regression test off the real tracking database, which
it wrote two rows into on every run, and onto an in-memory tracker. Add the
long-tailed pair that pins the weighted rate against the mean of percentages,
the same assertion through get_summary(), and a zero-input group: without the
CASE guard that last one fails on a NULL rate, and no other test covers it.

Name the 4th field of GainSummary::by_command for what it now holds, and state
the rate formula on the CommandStats warning in percentage order, with the zero
guard, so that following it verbatim cannot reintroduce the NULL.

Head the column Total% rather than Rate, keeping the shape of the Avg% it
replaces and naming the total the figure is now taken over.

Drop the hand-written CHANGELOG entry: release-please generates it from the
commit subject, and CONTRIBUTING.md asks for that file to be left alone.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-13 17:51:27 +02:00
Nicolas Le Cam 86668b065a Merge remote-tracking branch 'upstream/develop' into pr-891 2026-09-13 17:25:52 +02:00
Nicolas Le Cam d0c2985155 Merge pull request #1122 from carlosdagos/fix/gh-pr-no-early-exit
fix(gh): don't early exit on failure for "pr checks"
2026-09-13 15:17:12 +02:00
Nicolas Le CamandClaude Opus 5 d105227193 fix(gh): account for every check bucket in the pr checks summary
Filtering a failing `gh pr checks` makes the summary the only thing the user
sees, so a bucket it does not count disappears. `parse_pr_check_line` dropped
every row that was not pass/fail/pending, which turned a cancelled run -- the
usual outcome when a new push supersedes CI -- into "Passed: 0, Failed: 0",
and left 5 of PR 3982's 15 checks out of the totals.

Count the remaining buckets and report them, so the summary always adds up to
the checks gh listed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-13 15:04:33 +02:00
Nicolas Le Cam 83b1957cca Merge remote-tracking branch 'upstream/develop' into pr-1122-clean 2026-09-13 15:04:33 +02:00
Ilia Alshanetsky ed8480f3e2 fix(read): make head/tail rewrites faithful to the native commands
The hook rewrites `head -N FILE` to `rtk read FILE --max-lines N`, but
`--max-lines` routes through smart_truncate, which keeps a non-important
line only while kept_lines < max_lines / 2. Every rewritten `head -N`
therefore showed about half the requested lines, and `head -1` showed
none at all. Bare `head FILE` rewrote to an unbounded read of the whole
file, which a test asserted as intended.

Add `--head-lines N` for an exact first-N-lines window and point the
head rewrites at it, leaving `--max-lines` preview semantics unchanged
for existing callers. Both windows now slice on byte offsets at the Nth
newline instead of round-tripping through lines(), so CRLF endings and
an unterminated final line survive. The shipped `--tail-lines` path had
the same normalization loss. `--max-lines 0` returned a marker with no
content and underflowed max_lines - 1 on usize; it now returns empty,
matching `--tail-lines 0`.

Gate the rewrites on is_single_file_operand, an allowlist of characters
that cannot change an operand's word count or turn it into an option. A
whitespace-delimited token is not a shell operand: `head -n 1 *.rs`
expanded to sixteen files and lost the `==> name <==` banners,
`head -n 1 --help` printed rtk's own help, and a leading `#` opened a
comment that swallowed the appended flags. Uncertain operands stay with
the native binary, which costs coverage on quoted literals such as
'literal*.txt' and keeps behavior correct.

Separate a stripped trailing redirect from the appended flag value.
`head -n 1 a>b` produced `--head-lines 1>b`, which the shell reads as an
fd-1 redirect, leaving the flag without a value and the redirect target
empty.
2026-09-08 10:31:59 -04:00
Jack DangerandClaude Sonnet 4.6 3b4ab8735a fix: suppress hook warning during rtk init and verify
Running `rtk init -g` showed a spurious "No hook installed" warning
because maybe_warn() ran before the init completed. Skip the warning
for Init and Verify commands — they manage the hook themselves.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-20 12:50:15 -07:00
Florian BRUNIAUXandClaude Sonnet 4.6 0f45992a0d fix(tracking): use weighted savings rate in low_savings_commands and avg_savings_per_command
AVG(savings_pct) over rows produces an unweighted mean: a handful of 0%-savings
passthrough calls dilute a filter that genuinely performs well on high-volume
invocations. Same root cause as PR #891 (get_by_command).

Changes:
- low_savings_commands: AVG(savings_pct) → SUM(saved)*100/SUM(input). A command
  with 1 big call (95%) + 4 small calls (0%) now shows 94.6%, not 19%. Filters
  correctly excluded from the "needs improvement" list shipped in telemetry.
- avg_savings_per_command: inner per-command rate is now weighted (SUM/SUM);
  outer average across command names stays unweighted (intentional, each filter
  counts once). Documented in TELEMETRY.md.
- Two regression tests added (conn.execute direct inserts for DB isolation).
- docs/TELEMETRY.md updated to reflect the weighted formula.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Florian BRUNIAUX <florian@bruniaux.com>
2026-04-14 11:44:00 +02:00
Florian BRUNIAUX de0450d26f docs(changelog): add entry for gain weighted savings rate fix
Signed-off-by: Florian BRUNIAUX <florian@bruniaux.com>
2026-04-13 14:57:33 +02:00
Florian BRUNIAUXandClaude Sonnet 4.6 f3e0094183 fix(gain): use weighted savings rate in per-command stats
AVG(savings_pct) produced a simple unweighted mean that diluted the
reported rate for high-volume commands — grep showed 14.8% while the
true weighted rate was 98.6%, a 84-point gap.

Replace AVG(savings_pct) with SUM(saved_tokens)*100.0/SUM(input_tokens)
in the per-command SQL query so the rate reflects actual byte savings
rather than an average of per-invocation percentages.

Also:
- Rename "Avg%" column header to "Rate" (more accurate label)
- Add doc warning on CommandStats type alias against using AVG()
- Add regression test proving weighted != unweighted on skewed data

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Signed-off-by: Florian BRUNIAUX <florian@bruniaux.com>
2026-04-13 14:54:43 +02:00
Carlos D ecdf332a3d fix(gh): don't early exit on failure for "pr checks"
if there are failing checks in the PR, then `gh` will return a status of
`1` and `rtk` will refuse to parse the output due to using
`early_exit_on_failure`.

remove the use of `early_exit_on_failure` so it can still parse the
output.

now if there is an error, we will still get the summarised output with
all `0`s, and we'll also pass through the stderr.

example if a repository does not exist:

```
CI Checks Summary:
  [ok] Passed: 0
  [FAIL] Failed: 0
GraphQL: Could not resolve to a Repository with the name 'some-org/some-repo'. (repository)
```

with the error passed through to the output regardless, the error
handling downstream by the LLM should still work well.
2026-04-10 11:36:21 +10:00
16 changed files with 1269 additions and 69 deletions

No files matched your search

+3 -3
View File
@@ -85,15 +85,15 @@ elif echo "$FIRST_CMD" | grep -qE '^find\s+'; then
elif echo "$FIRST_CMD" | grep -qE '^diff\s+'; then
SUGGESTION=$(echo "$CMD" | sed 's/^diff /rtk diff /')
elif echo "$FIRST_CMD" | grep -qE '^head\s+'; then
# Suggest rtk read with --max-lines transformation
# Suggest rtk read with --head-lines transformation
if echo "$FIRST_CMD" | grep -qE '^head\s+-[0-9]+\s+'; then
LINES=$(echo "$FIRST_CMD" | sed -E 's/^head +-([0-9]+) +.+$/\1/')
FILE=$(echo "$FIRST_CMD" | sed -E 's/^head +-[0-9]+ +(.+)$/\1/')
SUGGESTION="rtk read $FILE --max-lines $LINES"
SUGGESTION="rtk read $FILE --head-lines $LINES"
elif echo "$FIRST_CMD" | grep -qE '^head\s+--lines=[0-9]+\s+'; then
LINES=$(echo "$FIRST_CMD" | sed -E 's/^head +--lines=([0-9]+) +.+$/\1/')
FILE=$(echo "$FIRST_CMD" | sed -E 's/^head +--lines=[0-9]+ +(.+)$/\1/')
SUGGESTION="rtk read $FILE --max-lines $LINES"
SUGGESTION="rtk read $FILE --head-lines $LINES"
fi
# --- JS/TS tooling ---
+2 -2
View File
@@ -62,8 +62,8 @@ This data directly drives our roadmap. For example, if telemetry shows that 40%
|-------|---------|---------|
| `passthrough_top` | `["git:15", "npm:8"]` | Top 5 commands with 0% savings — these need filters |
| `parse_failures_24h` | `3` | Filter fragility — high count means filters are breaking |
| `low_savings_commands` | `["rtk docker ps:25%"]` | Commands averaging <30% savings — filters to improve |
| `avg_savings_per_command` | `68.5` | Unweighted average (vs global which is volume-biased) |
| `low_savings_commands` | `["rtk docker ps:25%"]` | Commands with weighted savings rate <30%, net-negative ones included — filters to improve. Rate is `SUM(saved)/SUM(input)` over every call of the command, the same figure as the `rtk gain` By Command table, so high-volume calls are not diluted by passthrough calls. Exact 0% is left to `passthrough_top`. |
| `avg_savings_per_command` | `68.5` | Unweighted average across distinct command names (each filter counts once regardless of invocation volume). Each command's individual rate is weighted by volume before the outer average; commands that never had any input are skipped. |
| `recall_mode` | `sqlite` | Which recovery mode is active (`sqlite`/`tee`/`disabled`) |
| `recall_stats` | `[{"filter":"grep","mode":"sqlite","elisions":142,"recalls":9}]` | Per-filter counters: how often elided output is retrieved — calibrates filter caps. Filter names come from a fixed allowlist of rtk filter families; anything else is folded into `other`. No hashes, no paths, no command arguments, no output content. |
+1 -1
View File
@@ -166,7 +166,7 @@ rewrite_segment(seg, excluded) [src/discover/registry.rs]
| Step 4 — Already RTK → return as-is
|
| Step 5 — Special cases (short-circuit before classification)
| head -N / --lines=N → rewrite_line_range() → "rtk read file --max-lines N"
| head -N / -n N / --lines[= ]N / bare → rewrite_line_range() → "rtk read file --head-lines N"
| tail -N / -n N / --lines N → rewrite_line_range() → "rtk read file --tail-lines N"
| head/tail with unsupported flag (-c, -f) → None (skip rewrite)
| cat with incompatible flag (-A, -v, -e) → None (skip rewrite)
+2 -2
View File
@@ -67,8 +67,8 @@ This data directly drives our roadmap. For example, if telemetry shows that 40%
|-------|---------|---------|
| `passthrough_top` | `["git:15", "npm:8"]` | Top 5 commands with 0% bash output reduction — these need filters |
| `parse_failures_24h` | `3` | Filter fragility — high count means filters are breaking |
| `low_savings_commands` | `["rtk <cmd>:25%"]` | Commands averaging <30% bash output reduction — filters to improve. The example is a placeholder, not a measured value |
| `avg_savings_per_command` | `68.5` | Unweighted average (vs global which is volume-biased) |
| `low_savings_commands` | `["rtk <cmd>:25%"]` | Commands with a weighted bash output reduction <30%, net-negative ones included — filters to improve. The rate is `SUM(saved)/SUM(input)` over every call of the command, the same figure as the `rtk gain` By Command table, so high-volume calls are not diluted by passthrough calls. Exact 0% is left to `passthrough_top`. The example is a placeholder, not a measured value |
| `avg_savings_per_command` | `68.5` | Unweighted average across distinct command names (each filter counts once regardless of invocation volume); each command's own rate is weighted by volume before the outer average, and commands that never had any input are skipped |
### Ecosystem distribution
+3 -1
View File
@@ -130,7 +130,9 @@ rtk read - [options] # Lecture depuis stdin
| Option | Court | Defaut | Description |
|--------|-------|--------|-------------|
| `--level` | `-l` | `minimal` | Niveau de filtrage : `none`, `minimal`, `aggressive` |
| `--max-lines` | `-m` | illimite | Nombre maximum de lignes |
| `--max-lines` | `-m` | illimite | Apercu structurel plafonne a N lignes (signatures et imports, pas les N premieres) |
| `--head-lines` | | illimite | Garde seulement les N premieres lignes, a l'octet pres |
| `--tail-lines` | | illimite | Garde seulement les N dernieres lignes, a l'octet pres |
| `--line-numbers` | `-n` | non | Afficher les numeros de ligne |
**Niveaux de filtrage :**
+1 -1
View File
@@ -220,7 +220,7 @@ pub fn run(
println!("{}", "─".repeat(table_width));
println!(
"{:>3} {:<cmd_width$} {:>count_width$} {:>saved_width$} {:>6} {:>time_width$} {:<impact_width$}",
"#", "Command", "Count", "Saved", "Avg%", "Time", "Impact",
"#", "Command", "Count", "Saved", "Total%", "Time", "Impact",
cmd_width = cmd_width, count_width = count_width,
saved_width = saved_width, time_width = time_width,
impact_width = impact_width
+14 -4
View File
@@ -462,9 +462,7 @@ fn pr_checks(args: &[String], _verbose: u8, _ultra_compact: bool) -> Result<i32>
"gh",
&label,
format_pr_checks,
RunOptions::stdout_only()
.early_exit_on_failure()
.no_trailing_newline(),
RunOptions::stdout_only().no_trailing_newline(),
)
}
@@ -507,6 +505,11 @@ fn format_pr_checks(stdout: &str) -> String {
.filter(|check| check.2 == PrCheckStatus::Pending)
.count();
let other = checks
.iter()
.filter(|check| check.2 == PrCheckStatus::Other)
.count();
let mut out = String::new();
out.push_str("CI Checks Summary:\n");
out.push_str(&format!(" [ok] Passed: {}\n", passed));
@@ -514,6 +517,9 @@ fn format_pr_checks(stdout: &str) -> String {
if pending > 0 {
out.push_str(&format!(" [pending] Pending: {}\n", pending));
}
if other > 0 {
out.push_str(&format!(" [skip] Skipped/cancelled: {}\n", other));
}
let failed_checks = checks
.iter()
.filter(|check| check.2 == PrCheckStatus::Failed)
@@ -532,6 +538,7 @@ enum PrCheckStatus {
Passed,
Failed,
Pending,
Other,
}
fn parse_pr_check_line(line: &str) -> Option<(&str, &str, PrCheckStatus)> {
@@ -541,7 +548,10 @@ fn parse_pr_check_line(line: &str) -> Option<(&str, &str, PrCheckStatus)> {
"pass" => PrCheckStatus::Passed,
"fail" => PrCheckStatus::Failed,
"pending" | "*" => PrCheckStatus::Pending,
_ => return None,
// skipping, cancelled, and whatever a later gh adds. Counted rather than
// dropped, so the totals add up to the checks gh listed and a cancelled
// run cannot read as "nothing wrong".
_ => PrCheckStatus::Other,
};
let link = fields.nth(1).unwrap_or("").trim();
+262 -22
View File
@@ -5,12 +5,14 @@ use crate::core::guard::never_worse;
use crate::core::tracking;
use anyhow::{Context, Result};
use std::fs;
use std::io::{self, Read as IoRead, Write};
use std::path::Path;
pub fn run(
file: &Path,
level: FilterLevel,
max_lines: Option<usize>,
head_lines: Option<usize>,
tail_lines: Option<usize>,
line_numbers: bool,
verbose: u8,
@@ -22,8 +24,25 @@ pub fn run(
}
// Read file content
let content = fs::read_to_string(file)
let bytes = fs::read(file)
.with_context(|| format!("Failed to read file: {}", file.display()))?;
if level == FilterLevel::None && !line_numbers {
if let Some(window) = byte_line_window(&bytes, head_lines, tail_lines) {
io::stdout()
.lock()
.write_all(window)
.context("Failed to write line window")?;
timer.track(
&format!("cat {}", file.display()),
"rtk read",
&String::from_utf8_lossy(&bytes),
&String::from_utf8_lossy(window),
);
return Ok(());
}
}
let content = String::from_utf8(bytes)
.with_context(|| format!("Failed to decode file: {}", file.display()))?;
// Detect language from extension
let lang = file
@@ -64,7 +83,7 @@ pub fn run(
);
}
filtered = apply_line_window(&filtered, max_lines, tail_lines, &lang);
filtered = apply_line_window(&filtered, max_lines, head_lines, tail_lines, &lang);
let (raw, rtk_output) = if line_numbers {
(
@@ -88,12 +107,11 @@ pub fn run(
pub fn run_stdin(
level: FilterLevel,
max_lines: Option<usize>,
head_lines: Option<usize>,
tail_lines: Option<usize>,
line_numbers: bool,
verbose: u8,
) -> Result<()> {
use std::io::{self, Read as IoRead};
let timer = tracking::TimedExecution::start();
if verbose > 0 {
@@ -101,11 +119,27 @@ pub fn run_stdin(
}
// Read from stdin
let mut content = String::new();
let mut bytes = Vec::new();
io::stdin()
.lock()
.read_to_string(&mut content)
.read_to_end(&mut bytes)
.context("Failed to read from stdin")?;
if level == FilterLevel::None && !line_numbers {
if let Some(window) = byte_line_window(&bytes, head_lines, tail_lines) {
io::stdout()
.lock()
.write_all(window)
.context("Failed to write line window")?;
timer.track(
"cat - (stdin)",
"rtk read -",
&String::from_utf8_lossy(&bytes),
&String::from_utf8_lossy(window),
);
return Ok(());
}
}
let content = String::from_utf8(bytes).context("Failed to decode stdin")?;
// No file extension, so use Unknown language
let lang = Language::Unknown;
@@ -132,7 +166,7 @@ pub fn run_stdin(
);
}
filtered = apply_line_window(&filtered, max_lines, tail_lines, &lang);
filtered = apply_line_window(&filtered, max_lines, head_lines, tail_lines, &lang);
let (raw, rtk_output) = if line_numbers {
(
@@ -162,20 +196,12 @@ fn format_with_line_numbers(content: &str) -> String {
fn apply_line_window(
content: &str,
max_lines: Option<usize>,
head_lines: Option<usize>,
tail_lines: Option<usize>,
lang: &Language,
) -> String {
if let Some(tail) = tail_lines {
if tail == 0 {
return String::new();
}
let lines: Vec<&str> = content.lines().collect();
let start = lines.len().saturating_sub(tail);
let mut result = lines[start..].join("\n");
if content.ends_with('\n') {
result.push('\n');
}
return result;
if let Some(window) = byte_line_window(content.as_bytes(), head_lines, tail_lines) {
return String::from_utf8_lossy(window).into_owned();
}
if let Some(max) = max_lines {
@@ -185,6 +211,61 @@ fn apply_line_window(
content.to_string()
}
/// First `n` lines, sliced on byte offsets rather than round-tripped through
/// `lines()`, so CRLF endings and an unterminated final line survive verbatim.
/// `\n` is ASCII, so valid UTF-8 input also stays valid after slicing.
fn head_window(content: &[u8], n: usize) -> &[u8] {
if n == 0 {
return &[];
}
let mut seen = 0;
for (idx, &byte) in content.iter().enumerate() {
if byte == b'\n' {
seen += 1;
if seen == n {
return &content[..=idx];
}
}
}
content
}
/// Last `n` lines, byte-sliced for the same fidelity reasons as `head_window`.
/// A trailing newline terminates the final line instead of starting a new one,
/// so it is excluded before counting separators backwards — otherwise `n` would
/// select one line too few for newline-terminated input.
fn tail_window(content: &[u8], n: usize) -> &[u8] {
if n == 0 {
return &[];
}
let search_end = match content.last() {
Some(b'\n') => content.len() - 1,
_ => content.len(),
};
let mut seen = 0;
for idx in (0..search_end).rev() {
if content[idx] == b'\n' {
seen += 1;
if seen == n {
return &content[idx + 1..];
}
}
}
content
}
fn byte_line_window(
content: &[u8],
head_lines: Option<usize>,
tail_lines: Option<usize>,
) -> Option<&[u8]> {
if let Some(head) = head_lines {
Some(head_window(content, head))
} else {
tail_lines.map(|tail| tail_window(content, tail))
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -203,7 +284,7 @@ fn main() {{
)?;
// Just verify it doesn't panic
run(file.path(), FilterLevel::Minimal, None, None, false, 0)?;
run(file.path(), FilterLevel::Minimal, None, None, None, false, 0)?;
Ok(())
}
@@ -217,21 +298,180 @@ fn main() {{
#[test]
fn test_apply_line_window_tail_lines() {
let input = "a\nb\nc\nd\n";
let output = apply_line_window(input, None, Some(2), &Language::Unknown);
let output = apply_line_window(input, None, None, Some(2), &Language::Unknown);
assert_eq!(output, "c\nd\n");
}
#[test]
fn test_apply_line_window_tail_lines_no_trailing_newline() {
let input = "a\nb\nc\nd";
let output = apply_line_window(input, None, Some(2), &Language::Unknown);
let output = apply_line_window(input, None, None, Some(2), &Language::Unknown);
assert_eq!(output, "c\nd");
}
#[test]
fn test_head_window_matches_native_head() {
let input = "1\n2\n3\n4\n5\n";
assert_eq!(
apply_line_window(input, None, Some(3), None, &Language::Unknown),
"1\n2\n3\n"
);
}
/// The defect this window exists to fix: `--max-lines N` keeps only about
/// N/2 lines, so it could never stand in for `head -N`.
#[test]
fn test_head_window_keeps_all_n_lines_unlike_max_lines() {
let input = (1..=200)
.map(|n| n.to_string())
.collect::<Vec<_>>()
.join("\n")
+ "\n";
let head = apply_line_window(&input, None, Some(10), None, &Language::Unknown);
assert_eq!(head.lines().count(), 10);
assert_eq!(head.lines().last(), Some("10"));
}
#[test]
fn test_head_window_single_line() {
let input = "1\n2\n3\n";
assert_eq!(
apply_line_window(input, None, Some(1), None, &Language::Unknown),
"1\n"
);
}
#[test]
fn test_head_window_zero_is_empty() {
assert_eq!(
apply_line_window("a\nb\n", None, Some(0), None, &Language::Unknown),
""
);
}
#[test]
fn test_head_window_n_exceeds_line_count() {
let input = "a\nb\n";
assert_eq!(
apply_line_window(input, None, Some(99), None, &Language::Unknown),
input
);
}
#[test]
fn test_head_window_empty_input() {
assert_eq!(apply_line_window("", None, Some(5), None, &Language::Unknown), "");
}
#[test]
fn test_head_window_unterminated_final_line() {
assert_eq!(
apply_line_window("a\nb\nc", None, Some(3), None, &Language::Unknown),
"a\nb\nc"
);
}
#[test]
fn test_head_window_preserves_crlf() {
assert_eq!(
apply_line_window("a\r\nb\r\nc\r\n", None, Some(2), None, &Language::Unknown),
"a\r\nb\r\n"
);
}
#[test]
fn test_tail_window_preserves_crlf() {
assert_eq!(
apply_line_window("a\r\nb\r\nc\r\n", None, None, Some(2), &Language::Unknown),
"b\r\nc\r\n"
);
}
/// Without discounting the terminal newline, counting separators backwards
/// selects one line too few for newline-terminated input.
#[test]
fn test_tail_window_unterminated_single_line() {
assert_eq!(
apply_line_window("a\nb\nc", None, None, Some(1), &Language::Unknown),
"c"
);
}
#[test]
fn test_tail_window_n_exceeds_line_count() {
let input = "a\nb\n";
assert_eq!(
apply_line_window(input, None, None, Some(99), &Language::Unknown),
input
);
}
#[test]
fn test_tail_window_empty_input() {
assert_eq!(apply_line_window("", None, None, Some(5), &Language::Unknown), "");
}
#[test]
fn test_max_lines_zero_is_empty() {
assert_eq!(
apply_line_window("a\nb\nc\n", Some(0), None, None, &Language::Unknown),
""
);
}
#[test]
fn test_head_window_mixed_line_endings() {
assert_eq!(
apply_line_window("a\r\nb\nc\r\n", None, Some(2), None, &Language::Unknown),
"a\r\nb\n"
);
}
#[test]
fn test_tail_window_mixed_line_endings() {
assert_eq!(
apply_line_window("a\r\nb\nc\r\n", None, None, Some(2), &Language::Unknown),
"b\nc\r\n"
);
}
#[test]
fn test_windows_preserve_multibyte_utf8() {
let input = "héllo\n日本語\nثالث\n";
assert_eq!(
apply_line_window(input, None, Some(2), None, &Language::Unknown),
"héllo\n日本語\n"
);
assert_eq!(
apply_line_window(input, None, None, Some(2), &Language::Unknown),
"日本語\nثالث\n"
);
}
#[test]
fn test_windows_on_blank_lines_only() {
assert_eq!(
apply_line_window("\n\n\n", None, Some(2), None, &Language::Unknown),
"\n\n"
);
assert_eq!(
apply_line_window("\n\n\n", None, None, Some(2), &Language::Unknown),
"\n\n"
);
}
#[test]
fn test_tail_window_zero_is_empty() {
assert_eq!(
apply_line_window("a\nb\n", None, None, Some(0), &Language::Unknown),
""
);
}
#[test]
fn test_apply_line_window_max_lines_still_works() {
let input = "a\nb\nc\nd\n";
let output = apply_line_window(input, Some(2), None, &Language::Unknown);
let output = apply_line_window(input, Some(2), None, None, &Language::Unknown);
assert!(output.starts_with("a\n"));
assert!(output.contains("more lines"));
}
+7 -1
View File
@@ -318,6 +318,12 @@ pub fn get_filter(level: FilterLevel) -> Box<dyn FilterStrategy> {
}
pub fn smart_truncate(content: &str, max_lines: usize, _lang: &Language) -> String {
// A zero budget shows nothing, matching `--tail-lines 0`/`--head-lines 0`.
// Returning early also keeps `max_lines - 1` below from underflowing.
if max_lines == 0 {
return String::new();
}
let lines: Vec<&str> = content.lines().collect();
if lines.len() <= max_lines {
return content.to_string();
@@ -346,7 +352,7 @@ pub fn smart_truncate(content: &str, max_lines: usize, _lang: &Language) -> Stri
// Non-important lines beyond max_lines/2 are silently skipped —
// no inline markers that could be mistaken for file content.
if kept_lines >= max_lines - 1 {
if kept_lines + 1 >= max_lines {
break;
}
}
+294 -10
View File
@@ -202,7 +202,7 @@ pub struct GainSummary {
pub total_time_ms: u64,
/// Average execution time per command (milliseconds)
pub avg_time_ms: u64,
/// Top 10 commands by tokens saved: (cmd, count, saved, avg_pct, avg_time_ms)
/// Top 10 commands by tokens saved: (cmd, count, saved, weighted_rate, avg_time_ms)
pub by_command: Vec<(String, usize, usize, f64, u64)>,
/// Last 30 days of activity: (date, saved_tokens)
pub by_day: Vec<(String, usize)>,
@@ -295,7 +295,16 @@ pub struct MonthStats {
pub avg_time_ms: u64,
}
/// Type alias for command statistics tuple: (command, count, saved_tokens, avg_savings_pct, avg_time_ms)
/// Type alias for command statistics tuple: (command, count, saved_tokens, weighted_savings_rate, avg_time_ms)
///
/// # Warning
/// The 4th field is a **weighted** savings rate: `SUM(saved_tokens) / SUM(input_tokens) * 100.0`,
/// guarded so that a group whose every row has zero input reports 0.0 rather than NULL.
/// Do NOT aggregate this column with `AVG()` — that would produce an unweighted mean that
/// under-weights high-volume commands. Always recompute it as
/// `CASE WHEN SUM(input_tokens) > 0 THEN SUM(saved_tokens) / SUM(input_tokens) * 100.0 ELSE 0.0 END`
/// instead. `saved_tokens` is signed, so the rate can be negative where the 3rd field, being
/// unsigned, is clamped to 0.
type CommandStats = (String, usize, usize, f64, u64);
/// Current tracking-DB schema version, stored in the SQLite `user_version` pragma.
@@ -893,7 +902,9 @@ impl Tracker {
) -> Result<Vec<CommandStats>> {
let (project_exact, project_glob) = project_filter_params(project_path); // added
let mut stmt = self.conn.prepare(
"SELECT rtk_cmd, COUNT(*), SUM(saved_tokens), AVG(savings_pct), AVG(exec_time_ms)
"SELECT rtk_cmd, COUNT(*), SUM(saved_tokens),
CASE WHEN SUM(input_tokens) > 0 THEN SUM(saved_tokens) * 100.0 / SUM(input_tokens) ELSE 0.0 END,
AVG(exec_time_ms)
FROM commands
WHERE (?1 IS NULL OR project_path = ?1 OR project_path GLOB ?2)
GROUP BY rtk_cmd
@@ -1312,12 +1323,21 @@ impl Tracker {
}
/// Count commands with low savings (<30%) — filters that need improvement.
///
/// Uses the same weighted rate as `get_by_command`, `SUM(saved_tokens) / SUM(input_tokens)`
/// over every call of the command, so that a handful of 0%-savings passthrough calls don't
/// dilute a filter that genuinely performs well on high-volume invocations, and so that the
/// figure sent here is the one `rtk gain` prints for the same command. A net-regressing
/// command (negative rate) is listed: it is the filter most in need of improvement. Exact
/// 0% is left out, `passthrough_top` already reports it, and a command whose calls never
/// had any input carries no signal, so it is skipped rather than reported as 0%.
pub fn low_savings_commands(&self, limit: usize) -> Result<Vec<(String, f64)>> {
let mut stmt = self.conn.prepare(
"SELECT rtk_cmd, AVG(savings_pct) as avg_sav FROM commands
WHERE input_tokens > 0
"SELECT rtk_cmd,
SUM(saved_tokens) * 100.0 / SUM(input_tokens) AS sav
FROM commands
GROUP BY rtk_cmd
HAVING avg_sav < 30.0 AND avg_sav > 0.0
HAVING SUM(input_tokens) > 0 AND sav < 30.0 AND sav <> 0.0
ORDER BY COUNT(*) DESC LIMIT ?1",
)?;
let rows = stmt.query_map(params![limit as i64], |row| {
@@ -1329,7 +1349,15 @@ impl Tracker {
Ok(rows.filter_map(|r| r.ok()).collect())
}
/// Average savings percentage per command (unweighted — each command name counts once).
/// Average savings percentage per command (unweighted across command names — each distinct
/// command counts once, regardless of how many times it was invoked).
///
/// The *inner* rate per command is weighted by volume (`SUM(saved)/SUM(input)`) so that
/// passthrough calls don't dilute a command's own rate. The *outer* average across command
/// names stays unweighted — this is intentional: it gives equal weight to every filter
/// instead of being dominated by the most-called one. Documented in `docs/TELEMETRY.md`.
/// A command whose calls never had any input carries no signal about its filter and is
/// skipped, not counted as 0%.
///
/// Keeps the honest signed value: a command whose filter consistently emits
/// more than it saves yields a negative average, mirroring `overall_savings_pct`
@@ -1338,10 +1366,12 @@ impl Tracker {
/// not on a `0..=100` floor.
pub fn avg_savings_per_command(&self) -> Result<f64> {
let avg: f64 = self.conn.query_row(
"SELECT COALESCE(AVG(avg_sav), 0.0) FROM (
SELECT rtk_cmd, AVG(savings_pct) as avg_sav
FROM commands WHERE input_tokens > 0
"SELECT COALESCE(AVG(cmd_rate), 0.0) FROM (
SELECT rtk_cmd,
SUM(saved_tokens) * 100.0 / SUM(input_tokens) AS cmd_rate
FROM commands
GROUP BY rtk_cmd
HAVING SUM(input_tokens) > 0
)",
[],
|row| row.get(0),
@@ -2535,4 +2565,258 @@ mod tests {
assert_eq!(categorize_command(cmd), "js", "{cmd}");
}
}
// 14. get_by_command uses weighted savings rate, not unweighted average
//
// Regression test for: AVG(savings_pct) gave wrong results when small invocations
// with 0% savings diluted the average of high-volume commands.
//
// Setup: one small command (10% savings) + one large command (95% savings).
// Unweighted avg would be ~52.5%. Weighted rate must be ~95%.
//
// Rows carry a project path so the project-filtered form of the query is the one
// under test.
#[test]
fn test_get_by_command_weighted_savings_rate() {
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
let cmd_name = "weighted_test";
let project = "/tmp/rtk_weighted_test";
// Override project_path by inserting directly via conn
let saved_small = 10_i64; // 100 in - 90 out = 10 saved → 10%
let saved_large = 95_000_i64; // 100_000 in - 5_000 out = 95_000 saved → 95%
tracker
.conn
.execute(
"INSERT INTO commands (timestamp, original_cmd, rtk_cmd, project_path, input_tokens, output_tokens, saved_tokens, savings_pct, exec_time_ms)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
rusqlite::params![
chrono::Utc::now().to_rfc3339(),
cmd_name, cmd_name, project,
100_i64, 90_i64, saved_small, 10.0_f64, 5_i64
],
)
.expect("Failed to insert small invocation");
tracker
.conn
.execute(
"INSERT INTO commands (timestamp, original_cmd, rtk_cmd, project_path, input_tokens, output_tokens, saved_tokens, savings_pct, exec_time_ms)
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
rusqlite::params![
chrono::Utc::now().to_rfc3339(),
cmd_name, cmd_name, project,
100_000_i64, 5_000_i64, saved_large, 95.0_f64, 10_i64
],
)
.expect("Failed to insert large invocation");
let by_cmd = tracker
.get_by_command(Some(project))
.expect("Failed to get by_command stats");
let entry = by_cmd
.iter()
.find(|(name, _, _, _, _)| name == cmd_name)
.expect("Test command not found in by_command stats");
let (_name, _count, _saved, rate, _time) = entry;
// Weighted rate = (10 + 95_000) / (100 + 100_000) * 100.0 ≈ 94.9%
// Unweighted avg would be (10.0 + 95.0) / 2 = 52.5%
// The gap proves the fix works.
assert!(
*rate > 90.0,
"Expected weighted rate >90%, got {:.1}% — unweighted avg would be ~52.5%",
rate
);
}
// 15. The weighted rate tracks SUM(saved_tokens), not the mean of per-call percentages
//
// A long-tailed pair under one rtk_cmd: a 1M-token call saving 90% and a 100-token
// call saving 10%. The mean of the two percentages is 50%; the weighted rate is
// ~89.99% and is the figure consistent with the Saved column in the same row.
#[test]
fn test_weighted_rate_via_get_by_command() {
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
tracker
.record("grep huge", "rtk grep", 1_000_000, 100_000, 50)
.expect("record huge");
tracker
.record("grep tiny", "rtk grep", 100, 90, 5)
.expect("record tiny");
let by_command = tracker.get_by_command(None).expect("get_by_command");
let (_cmd, count, saved, pct, _avg_time) = by_command
.iter()
.find(|(cmd, ..)| cmd == "rtk grep")
.expect("rtk grep row not found");
assert_eq!(*count, 2);
assert_eq!(*saved, 900_010);
let expected = 900_010.0 / 1_000_100.0 * 100.0;
assert!(
(pct - expected).abs() < 0.01,
"expected weighted rate ~{expected:.2}, got {pct:.2}"
);
assert!(
(pct - 50.0).abs() > 1.0,
"mean-of-percentages regression: got {pct:.2}"
);
}
// 16. The rate reaches the gain summary through get_summary(), not only get_by_command
#[test]
fn test_weighted_rate_via_get_summary() {
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
tracker
.record("large grep", "rtk grep", 1000, 100, 10)
.expect("Failed to record large command");
tracker
.record("small grep", "rtk grep", 10, 9, 20)
.expect("Failed to record small command");
let summary = tracker.get_summary().expect("Failed to get summary");
let (_, count, saved, savings_pct, _) = summary
.by_command
.iter()
.find(|(command, _, _, _, _)| command == "rtk grep")
.expect("rtk grep stats not found");
assert_eq!(*count, 2);
assert_eq!(*saved, 901);
let expected_pct = 901.0 / 1010.0 * 100.0;
assert!(
(savings_pct - expected_pct).abs() < 1e-10,
"expected weighted rate {expected_pct}, got {savings_pct}"
);
}
// 17. A group whose every call has zero input reports 0%, not a division by zero
#[test]
fn test_by_command_zero_input_has_zero_savings_percentage() {
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
tracker
.record("interactive command", "rtk proxy", 0, 0, 5)
.expect("Failed to record passthrough command");
let summary = tracker.get_summary().expect("Failed to get summary");
let (_, _, _, savings_pct, _) = summary
.by_command
.iter()
.find(|(command, _, _, _, _)| command == "rtk proxy")
.expect("rtk proxy stats not found");
assert_eq!(*savings_pct, 0.0);
}
// 18. low_savings_commands reports the same weighted rate as the `rtk gain` By Command
// table, including net-regressing commands, and nothing for commands without input.
//
// `rtk ls -R`: one 95% call plus four 0% passthrough calls. Unweighted AVG(savings_pct)
// over those five rows is 19%, under the 30% threshold, so the command would reach
// telemetry as low-savings while `get_by_command` shows it at ~94.6% in the same
// `rtk gain` run. Weighted, 95_000 / 100_400 ≈ 94.6%: not listed.
// `rtk grep`: 25% on one call, then a call with no input that still printed 10 tokens.
// Every row counts, as in `get_by_command`: (250 - 10) / 1_000 = 24%, listed at 24.
// `rtk read`: emits more than it saves, -50%. Listed: it is the filter to fix first.
// `rtk proxy`: never had any input. Nothing to say about its filter, not listed.
#[test]
fn test_low_savings_commands_matches_gain_weighted_rate() {
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
tracker
.record("ls -R big", "rtk ls -R", 100_000, 5_000, 10)
.expect("record big call");
for _ in 0..4 {
tracker
.record("ls -R empty", "rtk ls -R", 100, 100, 5)
.expect("record passthrough call");
}
tracker
.record("grep x", "rtk grep", 1_000, 750, 5)
.expect("record 25% call");
tracker
.record("grep none", "rtk grep", 0, 10, 5)
.expect("record no-input call");
tracker
.record("read big.json", "rtk read", 100, 150, 5)
.expect("record regressing call");
tracker
.record("interactive", "rtk proxy", 0, 0, 5)
.expect("record zero-input call");
let low = tracker
.low_savings_commands(10)
.expect("low_savings_commands");
let listed: Vec<(&str, f64)> = low.iter().map(|(n, r)| (n.as_str(), *r)).collect();
assert_eq!(
listed.len(),
2,
"expected `rtk grep` (24%) and `rtk read` (-50%); ~94.6% weighted must not be \
listed (unweighted AVG(savings_pct) would put it at 19%), got {listed:?}"
);
assert_eq!(listed[0].0, "rtk grep");
assert!((listed[0].1 - 24.0).abs() < 1e-9, "got {listed:?}");
assert_eq!(listed[1].0, "rtk read");
assert!((listed[1].1 - (-50.0)).abs() < 1e-9, "got {listed:?}");
// The figure sent to telemetry is the one `rtk gain` prints for the same command.
let summary = tracker.get_summary().expect("get_summary");
for (name, rate) in &low {
let (_, _, _, gain_rate, _) = summary
.by_command
.iter()
.find(|(command, _, _, _, _)| command == name)
.unwrap_or_else(|| panic!("{name} missing from by_command"));
assert!(
(gain_rate - rate).abs() < 1e-9,
"{name}: telemetry says {rate}, rtk gain says {gain_rate}"
);
}
}
// 19. avg_savings_per_command weights each command's own rate by volume (every call
// counted, as in test 18), then averages the per-command rates without weighting: each
// command name counts once, and a command that never had any input is not counted.
//
// Same rows as test 18: `rtk ls -R` ≈ 94.6% (19% if the inner aggregate were
// AVG(savings_pct)), `rtk grep` 24%, `rtk read` -50%, `rtk proxy` skipped.
#[test]
fn test_avg_savings_per_command_inner_rate_is_weighted() {
let tracker = Tracker::new_in_memory().expect("Failed to create tracker");
tracker
.record("ls -R big", "rtk ls -R", 100_000, 5_000, 10)
.expect("record big call");
for _ in 0..4 {
tracker
.record("ls -R empty", "rtk ls -R", 100, 100, 5)
.expect("record passthrough call");
}
tracker
.record("grep x", "rtk grep", 1_000, 750, 5)
.expect("record 25% call");
tracker
.record("grep none", "rtk grep", 0, 10, 5)
.expect("record no-input call");
tracker
.record("read big.json", "rtk read", 100, 150, 5)
.expect("record regressing call");
tracker
.record("interactive", "rtk proxy", 0, 0, 5)
.expect("record zero-input call");
let avg = tracker
.avg_savings_per_command()
.expect("avg_savings_per_command");
let ls_rate = 95_000.0 * 100.0 / 100_400.0;
let expected = (ls_rate + 24.0 - 50.0) / 3.0;
assert!(
(avg - expected).abs() < 1e-6,
"expected ({ls_rate:.1} + 24 - 50) / 3 = {expected:.1}%, got {avg:.1}% \
(an unweighted inner AVG(savings_pct) would give (19 + 12.5 - 50) / 3 = -6.2%)"
);
}
}
+1 -1
View File
@@ -26,7 +26,7 @@ When a hook sends `cargo fmt --all && cargo test 2>&1 | tail -20`:
**Per-segment rewriting** — Each segment goes through:
1. Strip trailing redirects (`2>&1`, `>/dev/null`) — matched via lexer tokens, set aside, re-appended after rewriting
2. Short-circuit special cases — `head -20 file` → `rtk read file --max-lines 20`, `tail -n 5 file` → `rtk read file --tail-lines 5`. These can't go through generic prefix replacement because it would produce `rtk read -20 file` (wrong flag position)
2. Short-circuit special cases — `head -20 file` → `rtk read file --head-lines 20`, `tail -n 5 file` → `rtk read file --tail-lines 5`. These can't go through generic prefix replacement because it would produce `rtk read -20 file` (wrong flag position)
3. Classify the command — strip env prefixes (`FOO="bar baz"`), normalize paths (`/usr/bin/grep` → `grep`), strip git global opts (`git -C /tmp` → `git`), then match against 60+ regex patterns from `rules.rs`
4. Apply the rewrite — find the matching rule, replace the command prefix with `rtk <cmd>`, re-prepend the env prefix, re-append the redirect suffix
+263 -15
View File
@@ -80,10 +80,67 @@ static GIT_GLOBAL_OPT: LazyLock<Regex> = LazyLock::new(|| {
// Issue #1362: each capture expects a SINGLE file argument (`\S+$`). Multi-file
// invocations like `head -3 a b c` fail to match so the segment is passed through
// to the native `head`/`tail` binary — which already handles multi-file with
// `==> name <==` banners that `rtk read --max-lines` cannot reproduce.
// `==> name <==` banners that a single `rtk read` window cannot reproduce.
static HEAD_N: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^head\s+-(\d+)\s+(\S+)$").unwrap());
static HEAD_LINES: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^head\s+--lines=(\d+)\s+(\S+)$").unwrap());
// `-n N` and `--lines N` are the spellings `tail` already accepted below; `head`
// silently fell through to no rewrite at all without them.
static HEAD_N_SPACE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^head\s+-n\s+(\d+)\s+(\S+)$").unwrap());
static HEAD_LINES_SPACE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^head\s+--lines\s+(\d+)\s+(\S+)$").unwrap());
// Bare `head FILE` means ten lines, not the whole file. Restricted to a single
// operand: multi-file and optioned forms stay with the native binary.
static HEAD_BARE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^head\s+(\S+)$").unwrap());
/// Re-attach a trailing redirect to a rewritten head/tail command.
///
/// `head -n 1 f>out` strips to a suffix with no leading space, and these
/// rewrites end in a bare number, so plain concatenation yields
/// `--head-lines 1>out` — which the shell reads as an fd-1 redirect, leaving
/// `--head-lines` with no value. A separating space keeps the flag intact.
///
/// Deliberately not applied to the shared prefix rewrites: those keep the
/// original argument/redirect boundary, where inserting a space could split a
/// descriptor-duplication form such as `1>&2` and demote the descriptor number
/// into an argument.
fn join_redirect_suffix(rewritten: &str, redirect_suffix: &str) -> String {
if redirect_suffix.is_empty() || redirect_suffix.starts_with(char::is_whitespace) {
format!("{}{}", rewritten, redirect_suffix)
} else {
format!("{} {}", rewritten, redirect_suffix)
}
}
/// Whether an operand is safe to hand to `rtk read` as one concrete file.
///
/// One whitespace-delimited token is not one shell operand: `*.rs`, `{a,b}` and
/// `$FILES` each expand to several at execution time, and `rtk read`
/// concatenates files where `head`/`tail` print `==> name <==` banners.
///
/// The token is raw shell source, not the argument the callee receives, so
/// character-class blocklists kept missing cases: `'--'` and `\--help` hide an
/// option behind a quote or backslash, and a leading `#` opens a comment that
/// swallows the flags this rewrite appends. Hence an allowlist: only characters
/// that cannot change the operand's word count or turn it into an option are
/// accepted, and anything else is left to the native binary. `~` is the one
/// shell-active character kept, because tilde expansion yields exactly one word
/// and the operand is passed through unchanged. Unicode alphanumerics stay
/// eligible so non-ASCII filenames still route.
///
/// The cost is deliberate: a quoted literal like `'literal*.txt'` also stays
/// native even though the quoting would prevent expansion. Losing a rewrite is
/// recoverable; changing what the user's command does is not.
fn is_single_file_operand(operand: &str) -> bool {
if operand.is_empty() || operand.starts_with('-') {
return false;
}
operand.chars().all(|c| {
c.is_alphanumeric()
|| matches!(c, '.' | '_' | '/' | '-' | '~' | '+' | '@' | ':' | ',' | '=')
})
}
static TAIL_N: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^tail\s+-(\d+)\s+(\S+)$").unwrap());
static TAIL_N_SPACE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"^tail\s+-n\s+(\d+)\s+(\S+)$").unwrap());
@@ -1242,14 +1299,23 @@ fn rewrite_compound(
}
fn rewrite_line_range(cmd: &str) -> Option<String> {
for re in [&*HEAD_N, &*HEAD_LINES] {
for re in [&*HEAD_N, &*HEAD_LINES, &*HEAD_N_SPACE, &*HEAD_LINES_SPACE] {
if let Some(caps) = re.captures(cmd) {
let n = caps.get(1)?.as_str();
let file = caps.get(2)?.as_str();
return Some(format!("rtk read {} --max-lines {}", file, n));
if is_single_file_operand(file) {
return Some(format!("rtk read {} --head-lines {}", file, n));
}
return None;
}
}
if cmd.starts_with("head -") {
if let Some(caps) = HEAD_BARE.captures(cmd) {
let file = caps.get(1)?.as_str();
if is_single_file_operand(file) {
return Some(format!("rtk read {} --head-lines 10", file));
}
}
if cmd.starts_with("head") {
return None;
}
for re in [
@@ -1261,7 +1327,10 @@ fn rewrite_line_range(cmd: &str) -> Option<String> {
if let Some(caps) = re.captures(cmd) {
let n = caps.get(1)?.as_str();
let file = caps.get(2)?.as_str();
return Some(format!("rtk read {} --tail-lines {}", file, n));
if is_single_file_operand(file) {
return Some(format!("rtk read {} --tail-lines {}", file, n));
}
return None;
}
}
None
@@ -1578,7 +1647,7 @@ fn rewrite_segment_inner(
}
if context == RewriteContext::Normal
&& (cmd_part.starts_with("head -") || cmd_part.starts_with("tail "))
&& (cmd_part.starts_with("head ") || cmd_part.starts_with("tail "))
{
// head/tail rewrite to `rtk read`, so honour exclude_commands here too:
// this branch returns before the checks below. Any env prefix has already
@@ -1586,7 +1655,7 @@ fn rewrite_segment_inner(
if is_excluded(cmd_part, excluded) {
return None;
}
return rewrite_line_range(cmd_part).map(|r| format!("{}{}", r, redirect_suffix));
return rewrite_line_range(cmd_part).map(|r| join_redirect_suffix(&r, redirect_suffix));
}
// Most cat flags (-v, -A, -e, -t, -s, -b, --show-all, etc.) have different
@@ -3832,7 +3901,7 @@ mod tests {
// A non-excluded inner command still rewrites through the wrapper.
assert_eq!(
rewrite_command_no_prefixes("uv run head -20 src/main.rs", &["cat".to_string()]),
Some("uv run rtk read src/main.rs --max-lines 20".into())
Some("uv run rtk read src/main.rs --head-lines 20".into())
);
}
@@ -3840,33 +3909,211 @@ mod tests {
fn test_head_tail_rewrite_when_not_excluded() {
assert_eq!(
rewrite_command_no_prefixes("head -20 src/main.rs", &["cat".to_string()]),
Some("rtk read src/main.rs --max-lines 20".into())
Some("rtk read src/main.rs --head-lines 20".into())
);
}
#[test]
fn test_rewrite_head_numeric_flag() {
// head -20 file → rtk read file --max-lines 20 (not rtk read -20 file)
// head -20 file → rtk read file --head-lines 20 (not rtk read -20 file)
assert_eq!(
rewrite_command_no_prefixes("head -20 src/main.rs", &[]),
Some("rtk read src/main.rs --max-lines 20".into())
Some("rtk read src/main.rs --head-lines 20".into())
);
}
/// A single token that the shell expands into several operands must stay
/// native: `rtk read` concatenates files, losing `head`'s `==> name <==`
/// banners. Covers the newly added `-n N` / `--lines N` routes, which had
/// no matcher at all before and so were native by accident.
#[test]
fn test_rewrite_head_expanding_operand_stays_native() {
for cmd in [
"head src/core/*.rs",
"head -1 src/core/*.rs",
"head -n 1 src/core/*.rs",
"head --lines 1 src/core/*.rs",
"head --lines=1 src/core/*.rs",
"head -n 1 src/core/{a,b}.rs",
"head -n 1 $FILES",
"head -n 1 src/core/?.rs",
] {
assert_eq!(
rewrite_command_no_prefixes(cmd, &[]),
None,
"expanding operand must stay native: {}",
cmd
);
}
}
/// `head -n 1 --help` must reach `head`, not print `rtk read`'s help. The
/// quoted and escaped spellings matter as much as the bare one: the matcher
/// sees shell source, so `'--'` and `\--help` slip past a leading-`-` test
/// while still reaching the tool as options.
#[test]
fn test_rewrite_head_option_operand_stays_native() {
for cmd in [
"head -n 1 --help",
"head --lines 1 --version",
"head --help",
"head -n 1 '--'",
"head -n 1 \"--\"",
"head -n 1 '--help'",
"head -n 1 \"--help\"",
"head -n 1 \\--help",
"head '--'",
"head -n 1 #comment",
"head #comment",
"head -n 1 a|b",
"head -n 1 (x)",
] {
assert_eq!(
rewrite_command_no_prefixes(cmd, &[]),
None,
"option-like operand must stay native: {}",
cmd
);
}
}
/// The same expansion hazard applied to `tail`, which shared the code path.
#[test]
fn test_rewrite_tail_expanding_operand_stays_native() {
for cmd in [
"tail -20 src/core/*.rs",
"tail -n 20 src/core/*.rs",
"tail --lines 20 $FILES",
"tail -n 1 '--'",
"tail -n 1 \\--help",
"tail -n 1 #comment",
] {
assert_eq!(
rewrite_command_no_prefixes(cmd, &[]),
None,
"expanding operand must stay native: {}",
cmd
);
}
}
/// `;` and `&` are operators the lexer splits on before the operand is ever
/// examined, so the trailing text is a separate command and the real operand
/// is just `f`. These rewrite, and should: the allowlist only has to judge
/// characters that survive segmentation.
#[test]
fn test_rewrite_head_operand_after_operator_split() {
assert_eq!(
rewrite_command_no_prefixes("head -n 1 f;rm", &[]),
Some("rtk read f --head-lines 1; rm".into())
);
assert_eq!(
rewrite_command_no_prefixes("head -n 1 a&b", &[]),
Some("rtk read a --head-lines 1 & b".into())
);
}
/// A trailing redirect is stripped before the operand is judged, so `a>b`
/// rewrites with operand `a` — but the suffix must not fuse onto the numeric
/// flag value, or the shell reads `1>b` as an fd-1 redirect and
/// `--head-lines` loses its argument.
#[test]
fn test_rewrite_head_redirect_suffix_keeps_flag_value() {
assert_eq!(
rewrite_command_no_prefixes("head -n 1 a>b", &[]),
Some("rtk read a --head-lines 1 >b".into())
);
assert_eq!(
rewrite_command_no_prefixes("tail -n 1 a>b", &[]),
Some("rtk read a --tail-lines 1 >b".into())
);
// An already-spaced suffix must not gain a second space.
assert_eq!(
rewrite_command_no_prefixes("head -n 1 a > b", &[]),
Some("rtk read a --head-lines 1 > b".into())
);
}
/// Shapes the allowlist must keep accepting, including a non-ASCII name.
#[test]
fn test_rewrite_head_accepts_ordinary_paths() {
for (cmd, want) in [
(
"head -10 /tmp/seq.txt",
"rtk read /tmp/seq.txt --head-lines 10",
),
("head ./a-b_c.txt", "rtk read ./a-b_c.txt --head-lines 10"),
("head ~/x.txt", "rtk read ~/x.txt --head-lines 10"),
(
"head /tmp/a.b.c-d_e.txt",
"rtk read /tmp/a.b.c-d_e.txt --head-lines 10",
),
(
"head src/日本語.rs",
"rtk read src/日本語.rs --head-lines 10",
),
] {
assert_eq!(
rewrite_command_no_prefixes(cmd, &[]),
Some(want.into()),
"must still rewrite: {}",
cmd
);
}
}
#[test]
fn test_rewrite_tail_plain_operand_still_rewrites() {
assert_eq!(
rewrite_command_no_prefixes("tail -20 src/main.rs", &[]),
Some("rtk read src/main.rs --tail-lines 20".into())
);
}
#[test]
fn test_rewrite_head_n_space_flag() {
assert_eq!(
rewrite_command_no_prefixes("head -n 50 src/lib.rs", &[]),
Some("rtk read src/lib.rs --head-lines 50".into())
);
}
#[test]
fn test_rewrite_head_lines_space_flag() {
assert_eq!(
rewrite_command_no_prefixes("head --lines 50 src/lib.rs", &[]),
Some("rtk read src/lib.rs --head-lines 50".into())
);
}
/// Multi-file and optioned bare forms stay native: the rewrite emits one
/// path (see `is_single_file_operand`), and `head` prints `==> name <==`
/// banners for several files, which a concatenated read cannot reproduce.
#[test]
fn test_rewrite_head_bare_multifile_stays_native() {
assert_eq!(rewrite_command_no_prefixes("head a.txt b.txt", &[]), None);
}
#[test]
fn test_rewrite_head_unsupported_option_stays_native() {
assert_eq!(rewrite_command_no_prefixes("head -c 10 f.bin", &[]), None);
}
#[test]
fn test_rewrite_head_lines_long_flag() {
assert_eq!(
rewrite_command_no_prefixes("head --lines=50 src/lib.rs", &[]),
Some("rtk read src/lib.rs --max-lines 50".into())
Some("rtk read src/lib.rs --head-lines 50".into())
);
}
#[test]
fn test_rewrite_head_no_flag_still_rewrites() {
// plain `head file` → `rtk read file` (no numeric flag)
// plain `head file` means ten lines, so the rewrite must bound the read
// rather than dumping the whole file.
assert_eq!(
rewrite_command_no_prefixes("head src/main.rs", &[]),
Some("rtk read src/main.rs".into())
Some("rtk read src/main.rs --head-lines 10".into())
);
}
@@ -3926,7 +4173,8 @@ mod tests {
// --- Issue #1362: head/tail with multiple files falls back to native command ---
//
// `rtk read <file> --max-lines N` only accepts a single positional file path in
// The head/tail rewrite emits a single positional path (see
// `is_single_file_operand`), even though `rtk read` itself accepts several, in
// a shape that maps cleanly to `head -N`. Rewriting `head -N a b c` to
// `rtk read a b c --max-lines N` previously produced a command where `rtk read`
// would concatenate the files without the `==> name <==` banners that native
+23 -6
View File
@@ -111,11 +111,16 @@ enum Commands {
/// Filter: none (default, full content), minimal, aggressive
#[arg(short, long, default_value = "none")]
level: core::filter::FilterLevel,
/// Max lines
#[arg(short, long, conflicts_with = "tail_lines")]
/// Structural preview capped at N lines (keeps signatures and imports;
/// not the first N lines — use --head-lines for that)
#[arg(short, long, conflicts_with_all = ["head_lines", "tail_lines"])]
max_lines: Option<usize>,
/// Keep only the first N lines (byte-exact at the default --level none
/// with -n off; --level and -n still transform the window)
#[arg(long, conflicts_with_all = ["max_lines", "tail_lines"])]
head_lines: Option<usize>,
/// Keep only last N lines
#[arg(long, conflicts_with = "max_lines")]
#[arg(long, conflicts_with_all = ["max_lines", "head_lines"])]
tail_lines: Option<usize>,
/// Show line numbers
#[arg(short = 'n', long)]
@@ -1857,8 +1862,11 @@ fn run_cli() -> Result<i32> {
};
// Warn if installed hook is outdated/missing (1/day, non-blocking).
// Skip for Gain — it shows its own inline hook warning.
if !matches!(cli.command, Commands::Gain { .. }) {
// Skip for Gain (shows its own inline warning), Init/Verify (manage the hook themselves).
if !matches!(
cli.command,
Commands::Gain { .. } | Commands::Init { .. } | Commands::Verify { .. }
) {
hooks::hook_check::maybe_warn();
}
@@ -1879,6 +1887,7 @@ fn run_cli() -> Result<i32> {
files,
level,
max_lines,
head_lines,
tail_lines,
line_numbers,
} => {
@@ -1891,12 +1900,20 @@ fn run_cli() -> Result<i32> {
continue;
}
stdin_seen = true;
read::run_stdin(level, max_lines, tail_lines, line_numbers, cli.verbose)
read::run_stdin(
level,
max_lines,
head_lines,
tail_lines,
line_numbers,
cli.verbose,
)
} else {
read::run(
file,
level,
max_lines,
head_lines,
tail_lines,
line_numbers,
cli.verbose,
+139
View File
@@ -0,0 +1,139 @@
//! `gh pr checks` exits non-zero as a normal result: 1 when a check failed, 8 while
//! checks are still pending. Its stdout is complete and valid in both cases, so
//! skipping the filter there dropped the whole table on the user exactly when they
//! were asking why CI was red. These pin that the summary survives a non-zero exit
//! without swallowing the exit code, the diagnostics on stderr, or a check row.
#![cfg(unix)]
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::process::{Command, Output};
/// Writes an executable `name` in `dir` that runs `body`.
fn fake_tool(dir: &Path, name: &str, body: &str) {
let path = dir.join(name);
fs::write(&path, format!("#!/bin/sh\n{}\n", body)).expect("write fake tool");
fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).expect("chmod fake tool");
}
/// Runs rtk with `dir` first on PATH, so the fake tool shadows any real one.
fn rtk_with(dir: &Path, args: &[&str]) -> Output {
let path = format!(
"{}:{}",
dir.display(),
std::env::var("PATH").unwrap_or_default()
);
Command::new(env!("CARGO_BIN_EXE_rtk"))
.args(args)
.env("PATH", path)
.output()
.expect("run rtk")
}
/// A `gh` whose `pr checks` prints `table` and exits `code`, the way it does when
/// checks failed (1) or are still running (8).
fn fake_gh(dir: &Path, table: &str, code: i32) {
let path = dir.join("checks.txt");
fs::write(&path, table).expect("write table");
fake_tool(dir, "gh", &format!("cat {}\nexit {}", path.display(), code));
}
/// Rows as `gh` 2.46 prints them: tab-separated name, state, elapsed, url, description.
const RED_TABLE: &str = "doc review\tfail\t13s\thttps://example.test/job/1\t\n\
fmt\tfail\t7s\thttps://example.test/job/2\t\n\
Analyze (rust)\tpass\t4m17s\thttps://example.test/job/3\t\n\
check\tpass\t5s\thttps://example.test/job/4\t\n";
#[test]
fn failing_checks_are_summarised_not_dumped_raw() {
let dir = tempfile::tempdir().expect("tempdir");
fake_gh(dir.path(), RED_TABLE, 1);
let out = rtk_with(dir.path(), &["gh", "pr", "checks", "123"]);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
stdout.contains("CI Checks Summary:"),
"filter must run on a non-zero exit, got:\n{stdout}"
);
assert!(stdout.contains("Passed: 2"), "got:\n{stdout}");
assert!(stdout.contains("Failed: 2"), "got:\n{stdout}");
assert!(
stdout.contains("doc review") && stdout.contains("fmt"),
"the failed checks are the reason the user ran this, got:\n{stdout}"
);
}
#[test]
fn a_red_run_still_propagates_the_exit_code() {
let dir = tempfile::tempdir().expect("tempdir");
fake_gh(dir.path(), RED_TABLE, 1);
let out = rtk_with(dir.path(), &["gh", "pr", "checks", "123"]);
assert_eq!(out.status.code(), Some(1), "gh's exit code must survive");
}
#[test]
fn pending_checks_are_counted_and_exit_eight_survives() {
let dir = tempfile::tempdir().expect("tempdir");
fake_gh(
dir.path(),
"test (ubuntu)\tpending\t0\thttps://example.test/job/5\t\n\
test (macos)\tpending\t0\thttps://example.test/job/6\t\n\
test (windows)\tpending\t0\thttps://example.test/job/7\t\n\
clippy\tpass\t31s\thttps://example.test/job/8\t\n",
8,
);
let out = rtk_with(dir.path(), &["gh", "pr", "checks", "123"]);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(stdout.contains("Pending: 3"), "got:\n{stdout}");
assert_eq!(out.status.code(), Some(8), "gh exits 8 while checks pend");
}
#[test]
fn a_cancelled_run_does_not_read_as_nothing_wrong() {
let dir = tempfile::tempdir().expect("tempdir");
fake_gh(
dir.path(),
"build\tcancelled\t45s\thttps://example.test/job/1\t\n\
test (ubuntu)\tcancelled\t44s\thttps://example.test/job/2\t\n\
Security Scan\tskipping\t0\thttps://example.test/job/3\t\n",
1,
);
let out = rtk_with(dir.path(), &["gh", "pr", "checks", "123"]);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(
stdout.contains("Skipped/cancelled: 3"),
"a cancelled run must not summarise to all zeros, got:\n{stdout}"
);
assert_eq!(out.status.code(), Some(1));
}
#[test]
fn an_error_with_empty_stdout_does_not_become_an_all_zero_summary() {
let dir = tempfile::tempdir().expect("tempdir");
fake_tool(
dir.path(),
"gh",
"echo 'GraphQL: Could not resolve to a Repository' >&2\nexit 1",
);
let out = rtk_with(dir.path(), &["gh", "pr", "checks", "123"]);
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
!stdout.contains("Passed: 0"),
"a failed lookup must not read as a PR with zero checks, got:\n{stdout}"
);
assert!(
stderr.contains("Could not resolve to a Repository"),
"the real diagnostic must reach the user, got:\n{stderr}"
);
assert_eq!(out.status.code(), Some(1));
}
+79
View File
@@ -0,0 +1,79 @@
//! The "hook missing/outdated" reminder is a once-a-day nudge, so where it is
//! spent matters: a command the user ran to inspect or install the hook would
//! both duplicate that command's own reporting and burn the daily marker,
//! leaving the next filtered command silent.
//!
//! Unix only: the check resolves the Claude directory through the home
//! directory, and only Unix takes that from `$HOME`.
#![cfg(unix)]
use std::path::Path;
use std::process::Command;
const REMINDER: &str = "No hook installed";
/// Runs `rtk <args>` against a home directory whose Claude config directory
/// exists but registers no hook, and returns stderr.
fn run(home: &Path, args: &[&str]) -> String {
let out = Command::new(env!("CARGO_BIN_EXE_rtk"))
.args(args)
.env("HOME", home)
.env("RTK_DB_PATH", home.join("rtk.db"))
.output()
.expect("run rtk");
String::from_utf8_lossy(&out.stderr).into_owned()
}
fn fresh_home() -> tempfile::TempDir {
let home = tempfile::tempdir().expect("tempdir");
// Absent, the status check reports "not applicable"; present-but-empty is
// what makes a missing hook detectable.
std::fs::create_dir_all(home.path().join(".claude")).expect("claude dir");
home
}
#[test]
fn commands_that_report_hook_state_do_not_repeat_the_reminder() {
for args in [
vec!["init", "-g"],
vec!["verify"],
vec!["verify", "--filter", "cargo"],
vec!["gain"],
] {
let home = fresh_home();
let stderr = run(home.path(), &args);
assert!(
!stderr.contains(&format!("[rtk] /!\\ {REMINDER}")),
"rtk {} must not print the daily reminder: {stderr}",
args.join(" ")
);
}
}
#[test]
fn filtered_commands_still_get_the_reminder() {
for args in [vec!["ls"], vec!["git", "status"]] {
let home = fresh_home();
let stderr = run(home.path(), &args);
assert!(
stderr.contains(REMINDER),
"rtk {} must still warn: {stderr}",
args.join(" ")
);
}
}
#[test]
fn a_meta_command_leaves_the_daily_reminder_for_the_next_filtered_command() {
// The regression this guards: `maybe_warn` touches the once-a-day marker,
// so warning on a meta command would spend the reminder there and leave
// the next filtered command — the one that should have been hooked —
// silent for 24 hours.
let home = fresh_home();
run(home.path(), &["verify", "--filter", "cargo"]);
let stderr = run(home.path(), &["ls"]);
assert!(
stderr.contains(REMINDER),
"the reminder must survive a preceding meta command: {stderr}"
);
}
+175
View File
@@ -0,0 +1,175 @@
use std::fs;
use std::io::Write;
use std::process::{Command, Output, Stdio};
fn read_stdin(input: &[u8], args: &[&str]) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_rtk"))
.args(["read", "-"])
.args(args)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("run rtk read from stdin");
child
.stdin
.take()
.expect("piped stdin")
.write_all(input)
.expect("write stdin");
child.wait_with_output().expect("wait for rtk read")
}
#[test]
fn read_windows_preserve_non_utf8_files() {
let dir = tempfile::tempdir().expect("create test directory");
let file = dir.path().join("binary.log");
fs::write(&file, b"\xff\xfe bad\nline2\nline3\n").expect("write binary file");
for (flag, expected) in [
("--head-lines", b"\xff\xfe bad\nline2\n".as_slice()),
("--tail-lines", b"line2\nline3\n".as_slice()),
] {
let output = Command::new(env!("CARGO_BIN_EXE_rtk"))
.arg("read")
.arg(&file)
.args([flag, "2"])
.output()
.expect("run rtk read");
assert!(output.status.success(), "{flag}: {:?}", output.stderr);
assert_eq!(output.stdout, expected, "{flag}");
}
}
#[test]
fn read_windows_preserve_binary_boundaries_for_files_and_stdin() {
let dir = tempfile::tempdir().expect("create test directory");
let file = dir.path().join("binary.log");
for input in [
b"\xff\r\nvalid\n\0\xfe".as_slice(),
b"\xff\r\nvalid\n\0\xfe\n".as_slice(),
] {
fs::write(&file, input).expect("write binary file");
let last = if input.ends_with(b"\n") {
b"\0\xfe\n".as_slice()
} else {
b"\0\xfe".as_slice()
};
for (flag, count, expected) in [
("--head-lines", "0", b"".as_slice()),
("--tail-lines", "0", b"".as_slice()),
("--head-lines", "1", b"\xff\r\n".as_slice()),
("--tail-lines", "1", last),
("--head-lines", "99", input),
("--tail-lines", "99", input),
] {
let from_file = Command::new(env!("CARGO_BIN_EXE_rtk"))
.arg("read")
.arg(&file)
.args([flag, count])
.output()
.expect("run rtk read");
let from_stdin = read_stdin(input, &[flag, count]);
for output in [from_file, from_stdin] {
assert!(
output.status.success(),
"{flag} {count}: {:?}",
output.stderr
);
assert_eq!(output.stdout, expected, "{flag} {count}");
}
}
}
}
#[test]
fn read_windows_accept_invalid_bytes_outside_the_selected_window() {
for (input, flag) in [
(b"valid\n\xff\n".as_slice(), "--head-lines"),
(b"\xff\nvalid\n".as_slice(), "--tail-lines"),
] {
let output = read_stdin(input, &[flag, "1"]);
assert!(output.status.success(), "{flag}: {:?}", output.stderr);
assert_eq!(output.stdout, b"valid\n");
}
}
#[test]
fn read_windows_still_apply_text_filtering_and_line_numbers() {
let input = b"// comment\nfn alpha() {}\nfn beta() {}\nfn gamma() {}\n";
for (args, expected) in [
(
["--head-lines", "1", "--level", "minimal"].as_slice(),
"fn alpha() {}\n",
),
(
["--tail-lines", "1", "--level", "minimal"].as_slice(),
"fn gamma() {}",
),
(
["--head-lines", "1", "--line-numbers"].as_slice(),
"1 │ // comment\n",
),
(
["--tail-lines", "1", "--line-numbers"].as_slice(),
"1 │ fn gamma() {}\n",
),
] {
let output = read_stdin(input, args);
assert!(output.status.success(), "{args:?}: {:?}", output.stderr);
assert_eq!(output.stdout, expected.as_bytes(), "{args:?}");
}
}
#[cfg(unix)]
#[test]
fn rewritten_head_spellings_match_native_on_non_utf8_files() {
let dir = tempfile::tempdir().expect("create test directory");
let claude_dir = dir.path().join(".claude");
fs::create_dir(&claude_dir).expect("create isolated Claude config directory");
let config_dir = dir.path().join("config");
fs::create_dir(&config_dir).expect("create isolated rtk config directory");
let file = dir.path().join("binary.log");
fs::write(&file, b"\xff\xfe bad\nline2\nline3\n").expect("write binary file");
for flags in ["-2", "-n 2", "--lines 2", "--lines=2", ""] {
let command = format!("head {flags} {}", file.display());
let rewrite = Command::new(env!("CARGO_BIN_EXE_rtk"))
.current_dir(dir.path())
.env("CLAUDE_CONFIG_DIR", &claude_dir)
.env("XDG_CONFIG_HOME", &config_dir)
.args(["rewrite", &command])
.output()
.expect("rewrite head command");
assert_eq!(
rewrite.status.code(),
Some(3),
"{command}: {:?}",
rewrite.stderr
);
let rewritten = String::from_utf8(rewrite.stdout).expect("UTF-8 command");
let count = if flags.is_empty() { "10" } else { "2" };
assert_eq!(
rewritten.trim(),
format!("rtk read {} --head-lines {count}", file.display())
);
let actual = Command::new(env!("CARGO_BIN_EXE_rtk"))
.args(
rewritten
.trim()
.strip_prefix("rtk ")
.expect("rtk rewrite prefix")
.split_whitespace(),
)
.output()
.expect("execute rewritten head");
let native = Command::new("head")
.args(flags.split_whitespace())
.arg(&file)
.output()
.expect("run native head");
assert!(native.status.success(), "{command}: {:?}", native.stderr);
assert_eq!(actual.status.code(), native.status.code(), "{command}");
assert_eq!(actual.stdout, native.stdout, "{command}");
}
}