Skip to content

rtk read --max-lines N (and the head rewrite) drops lines from the middle with no gap marker, producing code that compiles-looking but means the opposite #3421

Open

Description

@HetCreep

smart_truncate keeps structurally interesting lines and discards the rest, but it joins the survivors with no marker where the gap was, and appends a single [N more lines] at the end — which implies the omission is at the end. The result is code an agent reads as complete and correct while it says something different.

Provenance: AI-assisted source audit, human-directed, at v0.44.2 (700bdde). Reproduced with the shipped binary; input and output below are verbatim.

Reproduction

auth.rs, 15 lines:

 1  fn can_admin(user: &User) -> bool {
 2      if !user.is_admin {
 3          return false;
 4      }
 5      if user.is_banned {
 6          return false;
 7      }
 8      if user.mfa_ok {
 9          return true;
10      }
11      false
12  }
13  fn wipe_database() {
14      drop_all();
15  }

rtk read auth.rs --max-lines 10:

fn can_admin(user: &User) -> bool {
    if !user.is_admin {
        return false;
    }
    if user.is_banned {
    }
    }
}
fn wipe_database() {
[6 more lines]

Two things happened:

  1. The ban check was inverted. if user.is_banned { survived; its return false; did not. What the agent reads is a guard that does nothing — the opposite of what the file says. Nothing marks the removal.
  2. fn wipe_database() was spliced in directly after, with no indication that lines were skipped between them. The only marker, [6 more lines], sits at the bottom and reads as "the rest of the file follows", not "content was removed from the middle".

An agent asked to review this file would conclude that banned users pass the check.

Why this is on a default path

This is not an exotic flag. rtk rewrite head -50 file emits rtk read file --max-lines 50, so the hook routes ordinary head invocations through the same code (src/core/filter.rs:342, reached from src/cmds/system/read.rs). The default filter level is none, and this happens at that level.

Related, same function

  • src/cmds/system/read.rs:157 — with -n, the line numbers count the kept lines 1..N, not the file's real line numbers. In the run above, the row labelled 7 is raw line 9, and the [N more lines] marker itself gets numbered as though it were content. An agent told to "fix line 8" edits a different line than the one it was shown.
  • src/core/filter.rs:349 — kept_lines >= max_lines - 1 underflows when max_lines == 0. Cargo.toml:45 sets panic = "abort" but not overflow-checks, so a release build wraps to usize::MAX and the loop never breaks (a debug build panics with attempt to subtract with overflow). Reachable as head -0 file → --max-lines 0.

Suggested directions (untested — no programmer has reviewed these)

  • Emit a marker where the gap is, not only at the end — e.g. … 4 lines omitted … inline at each discontinuity. That single change makes the output honest even if the selection heuristic stays as is.
  • Consider keeping a line's closing brace only when its opening block was kept intact; dropping a body while keeping both braces is what makes the output read as valid.
  • Guard max_lines == 0 explicitly rather than relying on - 1.

I would rate the inline gap marker as the important one: an agent can reason correctly about "content was removed here", but it cannot detect a guard clause that was silently emptied.

One thing I could not reproduce

An earlier note in my own review suggested rtk read - (stdin) could return zero bytes for a small error log. I tried it — a 147-byte tsc-style log came back as 146 bytes, exit 0. So that half does not reproduce and I am not claiming it.

Activity

  1. added
    bug
    help wanted
    on Aug 4, 2026
  2. pszymkowiak commented on Aug 4, 2026

    @pszymkowiak
    Collaborator

    wshm · Automated triage by AI

    🔍 Automated Triage

    🐛 Category bug
    🟠 Priority high
    🎯 Confidence 92%

    Summary

    rtk read --max-lines (and the head rewrite it powers) silently drops mid-file lines with no gap marker and mislabels renumbered lines, producing code that reads as complete/correct but inverts logic — fix by emitting inline gap markers and using real line numbers in filter.rs/read.rs.

    This looks like a simple fix that could be auto-resolved. Repo maintainers can use /wshm fix to attempt it.

    📁 Relevant files
    • src/core/filter.rs
    • src/cmds/system/read.rs

    Triaged automatically by wshm · This is an automated analysis, not a human review.

  3. HetCreep commented on Aug 4, 2026

    @HetCreep
    Author

    Correcting myself: the stdin case at the bottom of this issue does reproduce. I tested it with the wrong input and wrote it off — apologies.

    My earlier attempt used a log whose lines all survive the filter, so of course nothing was dropped. The condition is different: it needs input that the filter empties completely. Here is the same content down two paths:

    $ printf '// BUILD FAILED\n// error: cannot find symbol at Main.java:42\n// 3 errors\n' > build.log
    
    $ rtk read build.log -l minimal
    rtk: warning: filter produced empty output for build.log (73 bytes), showing raw content
    // BUILD FAILED
    // error: cannot find symbol at Main.java:42
    // 3 errors
    
    $ printf '// BUILD FAILED\n// error: cannot find symbol at Main.java:42\n// 3 errors\n' | rtk read - -l minimal
    $ echo "bytes: $?"      # 0 bytes on stdout, exit 0
    

    The file path prints a warning and falls back to the raw content. The stdin path returns nothing, exit 0.

    The asymmetry is in the source. src/cmds/system/read.rs:43-48:

    // Safety: if filter emptied a non-empty file, fall back to raw content
    if filtered.trim().is_empty() && !content.trim().is_empty() {
        eprintln!("rtk: warning: filter produced empty output for {} ({} bytes), showing raw content", ...);

    run_stdin (read.rs:117-119) applies the filter with no equivalent guard.

    Other inputs that reach zero bytes through stdin, all exit 0: lines that are entirely // comments (stdin is treated as Language::Unknown, which carries C-style comment patterns), input that is only blank lines, any all-comment input at -l aggressive, and --tail-lines 0.

    Why it matters here: a caller piping a build or test log into rtk read - can receive an empty result with a success exit code, which reads as "there was no output" rather than "the filter removed everything". The file path already decided that is the wrong answer — run_stdin just did not get the same guard.

    Suggested fix: apply the same fallback in run_stdin. Since there is no filename to name in the warning, something like filter produced empty output for stdin (N bytes), showing raw content would match the existing message.

  4. k4its1t commented on Aug 24, 2026

    @k4its1t

    I’d like to work on this. I reproduced the permission-guard example against the latest develop. I’ll add regression coverage first, then make truncation emit omission markers at each real discontinuity, preserve original line numbers, handle zero-line windows without underflow, and give stdin the same non-empty fallback as file reads. I’ll keep the change scoped to read/smart_truncate and run the repository’s full pre-commit gate.

  5. albatrossflyon-coder commented on Sep 13, 2026

    @albatrossflyon-coder
    Contributor

    Our fix for this exact bug has been open as #3166 since 2026-07-22 with no review. Linking here since this issue is now the canonical tracker and #3046 (where #3166 was filed) just got closed as a duplicate of this one.

  6. HetCreep commented on Sep 16, 2026

    @HetCreep
    Author

    Flagging since two PRs are open for this and they're not just two patches of the same fix — they take different design directions, and both are unmerged and now dirty against current develop.

    Provenance: read both PR descriptions and diffs via the API; re-ran the verification for #3689 myself back on 2026-08-24 (built the branch, cargo test --bin rtk and cargo test --all both green). Did not re-run #3166 — noting what it says of itself.

    #3166 (albatrossflyon-coder, open since 2026-07-22): make truncation literally what head promises

    Replaces the "important line" scan with a plain contiguous slice of the first N lines — no line past the window is ever pulled forward, matching head's actual contract (and the project's own stated principle in CONTRIBUTING.md § Transparency, which the PR cites).

    #3689 (k4its1t, open since 2026-08-24): keep smart selection, make every gap visible

    Keeps the existing behavior of surfacing important lines beyond the window, but represents every discontinuity as an explicit omission marker with real source line numbers, so a spliced-together excerpt can no longer be mistaken for a contiguous one. Also separately fixes --max-lines 0 underflowing. I built and ran this one: all three findings this issue's thread raised are genuinely fixed, full suite green (2632 passed, 8 ignored).

    These aren't redundant — they're different products

    #3166 treats "look like head" as the contract to honor. #3689 treats "never silently hide a discontinuity" as the contract, and keeps the smart selection because it's often more useful than a raw prefix. Picking one isn't just "which patch is more correct" — it's a call on which behavior rtk read --max-lines should have going forward. Not mine to make; just didn't want it decided by whichever PR happens to get looked at first without the other being visible.

    Both are marked dirty right now, so either way needs a rebase before merge regardless of which direction gets picked.

  7. HetCreep commented on Sep 16, 2026

    @HetCreep
    Author

    Correction to my comment above — I synced to current develop right after posting it and found the ground had already shifted.

    Provenance: AI-assisted source audit, human-directed, at develop @ 5e0f92c. Both halves below were executed against a binary built from this commit, with the same repro shape (an important line 46+ lines past the requested window).

    The head rewrite half is already fixed — landed before my comment above, not by either open PR

    ed8480f ("fix(read): make head/tail rewrites faithful to the native commands", 2026-09-08) added a new --head-lines N window that slices on a literal byte offset, and repointed the hook rewrite at it:

    $ echo '{"tool_name":"Bash","tool_input":{"command":"head -30 bigfile.rs"}}' | rtk hook claude
    {"...":{"updatedInput":{"command":"rtk read bigfile.rs --head-lines 30"}}}
    
    $ rtk read bigfile.rs --head-lines 30
    (30 lines, a literal contiguous prefix, no line pulled forward from past the window)
    

    So the specific shape both open PRs describe — head -N on a real file producing a spliced, non-contiguous excerpt — no longer happens. My apologies for not catching this before commenting; I synced right after this time and should have synced right before instead.

    What's actually still open is narrower: direct --max-lines N

    The same commit deliberately left --max-lines's own behavior alone ("leaving --max-lines preview semantics unchanged for existing callers"). Confirmed that's still exactly the original defect:

    $ rtk read bigfile.rs --max-lines 30
    fn early() {
        // header
        let x3 = 3;
        ...
        let x15 = 15;
    fn important_but_far() {
    }
    }
    [136 more lines]
    

    18 lines total, and the two lines fn important_but_far() { } are pulled in from 46+ lines past the shown window with no indication anything was skipped in between.

    So the PR comparison above still applies, just to a smaller surface

    Both #3166 and #3689 patch smart_truncate itself, which is still what --max-lines calls — so neither is moot. But the head rewrite is no longer the reachable trigger for either: an agent has to type --max-lines explicitly (or something else has to route through it) to hit what's left. Worth the maintainer knowing the blast radius shrank before deciding between the two directions.

  8. HetCreep commented on Oct 14, 2026

    @HetCreep
    Author

    Re-checked on v1.0.0 (stable, 2026-10-13): the official release binary plus the v1.0.0 source. Provenance: AI-assisted check, human-directed. "ran" = executed against rtk 1.0.0 with a control; "read" = verified from source only.

    Fixed (ran): the head rewrite. rtk rewrite 'head -10 auth.rs' now gives rtk read auth.rs --head-lines 10, which prints the real contiguous lines. --max-lines 0 now returns empty output. Thanks.

    Still live (ran, on the report's auth.rs): direct rtk read auth.rs --max-lines 10 still prints if user.is_banned {, }, }, }, fn wipe_database() { and [6 more lines] with no inline gap marker (same for --max-lines 5 and 1), so the guard reads as inverted. -n still numbers the kept lines 1..N, including the [N more lines] marker (src/cmds/system/read.rs:226 format_with_line_numbers). Control: --head-lines 10 -n numbers correctly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:clibughelp wantedpriority:high

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions