Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(search): stop a context line's body from becoming its line marker (#3788)

ANIRUDDHA ADAKf3f2e0077ae6
diff --git a/crates/headroom-core/src/transforms/search_compressor.rs b/crates/headroom-core/src/transforms/search_compressor.rs
index a6e4f329c..8a2002c64 100644
--- a/crates/headroom-core/src/transforms/search_compressor.rs
+++ b/crates/headroom-core/src/transforms/search_compressor.rs
@@ -648,7 +648,10 @@ impl SearchCompressor {
/// practically never contains one (the Windows drive colon is
/// already skipped above), so the leftmost is the right one. The
/// no-whitespace guard keeps a `foo.rs:12:` reference *inside the
-/// body* of a `-`-separated context line from hijacking the parse.
+/// body* of a `-`-separated context line from hijacking the parse. A
+/// whitespace-free body reference (`a:7:b`) still slips past it, so
+/// [`parse_match_line`] hands priority back to the dash tier for that
+/// one shape; see the comment there.
/// 2. **Dash tier** — `-` is grep's *context*-line separator, and unlike
/// `:` it appears inside real paths (`2026-05-03`, `CVE-2021-44228`,
/// `20240101-002-add_users.sql`), so the leftmost triplet is often
@@ -684,9 +687,50 @@ impl SearchCompressor {
/// Only reached when neither tier matched (e.g. a path containing a
/// space), so behaviour for those lines is exactly as before.
fn parse_match_line(line: &str) -> Option<(&str, u64, &str)> {
- scan_match_line(line, ScanTier::Colon)
- .or_else(|| scan_match_line(line, ScanTier::Dash))
- .or_else(|| scan_match_line(line, ScanTier::Permissive))
+ let colon = scan_marker(line, ScanTier::Colon);
+ let dash = scan_marker(line, ScanTier::Dash);
+
+ // The colon tier keeps priority: `path:line:content` is what grep emits for
+ // matches and a path practically never contains a colon. It yields in
+ // exactly one shape — a `-`-separated context line whose body carries a
+ // whitespace-free `name:N:` reference (`app.py-476-a:7:b`). The dash tier
+ // *positively confirmed* a boundary before the colon marker, so that colon
+ // triplet is body text, not a marker.
+ //
+ // Without the hand-off the body's number is read as the line number, the
+ // path swallows the real `-N-`, and the model is shown a file that does not
+ // exist holding content attributed to a line it never came from
+ // (issue #3545). The whitespace guard inside the colon tier cannot catch
+ // this, because the body ahead of the reference need not contain any.
+ //
+ // The `true` in the dash arm is load-bearing, and it is the *whole* test.
+ // A confirmed boundary means the dash tier saw the path end there — either
+ // the segment carried an extension (`app.py-476-`) or nothing after the
+ // marker looked like path structure (`CHANGELOG-12-`) — so the bytes from
+ // the closing dash onwards are body text and may look like anything. Bodies
+ // routinely carry a filename-style reference of their own
+ // (`app.py-476-foo.rs:12:ref`), and an extension dot there says nothing
+ // about where the path ended.
+ //
+ // The rows that must keep the colon tier are the ones where the dash tier
+ // could *not* confirm: `logs/2026-05-03/app.log:12:ERROR` and
+ // `migrations/20240101-002-add_users.sql:12:SELECT` both leave the digits
+ // inside the path, so the flag is false and the hand-off never applies. See
+ // [`path_continues`], which is what decides the flag.
+ let dash_overrides = match (colon, dash) {
+ (Some((colon_marker, _)), Some((dash_marker, true))) => colon_marker.0 > dash_marker.2,
+ _ => false,
+ };
+
+ let marker = if dash_overrides {
+ dash
+ } else {
+ colon
+ .or(dash)
+ .or_else(|| scan_marker(line, ScanTier::Permissive))
+ };
+
+ build_match(line, marker?.0)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -752,7 +796,22 @@ fn path_continues(rest: &str) -> bool {
.is_some_and(|tok| tok.contains('/') || tok.contains('\\') || has_extension_dot(tok))
}
-fn scan_match_line(line: &str, tier: ScanTier) -> Option<(&str, u64, &str)> {
+/// Byte offsets of one `<sep><digits><sep>` marker: where the path ends, where
+/// the digits start, and where the closing separator sits.
+type Marker = (usize, usize, usize);
+
+/// Assemble `(file, line_number, content)` from a marker's byte offsets.
+fn build_match(line: &str, marker: Marker) -> Option<(&str, u64, &str)> {
+ let (path_end, digits_start, digits_end) = marker;
+ let line_no = line[digits_start..digits_end].parse::<u64>().ok()?;
+ Some((&line[..path_end], line_no, &line[digits_end + 1..]))
+}
+
+/// Scan `line` under `tier`, returning the marker it settled on plus whether
+/// that marker was a *positively confirmed* boundary (`chosen`) rather than the
+/// leftmost fallback (`first`). Callers need that flag to tell a proven boundary
+/// from a guess.
+fn scan_marker(line: &str, tier: ScanTier) -> Option<(Marker, bool)> {
let bytes = line.as_bytes();
// Windows drive prefix: starts with [A-Za-z]:[\\/]
let scan_start = if bytes.len() >= 3
@@ -865,11 +924,7 @@ fn scan_match_line(line: &str, tier: ScanTier) -> Option<(&str, u64, &str)> {
// is genuinely ambiguous (`Makefile-7-include-2-src/foo.mk`). Fall back
// to the leftmost marker — precisely what the leftmost-wins rule this
// tier refines would have returned.
- let (path_end, digits_start, digits_end) = chosen.or(first)?;
- let line_no = std::str::from_utf8(&bytes[digits_start..digits_end])
- .ok()
- .and_then(|s| s.parse::<u64>().ok())?;
- Some((&line[..path_end], line_no, &line[digits_end + 1..]))
+ Some((chosen.or(first)?, chosen.is_some()))
}
// ─── Internals ──────────────────────────────────────────────────────────
@@ -918,6 +973,60 @@ mod tests {
assert!(cjk_bigrams("a认b证").is_empty()); // isolated CJK chars -> no pair
}
+ #[test]
+ fn dash_context_line_wins_over_a_colon_marker_in_its_body() {
+ // A whitespace-free `name:N:` reference in the body of a `-`-separated
+ // context line used to be read as the line-number marker: the path
+ // absorbed the real `-N-` and the body's number was reported as the
+ // line number, inventing both a file that does not exist and a
+ // line<->content pair that never existed (issue #3545).
+ assert_eq!(
+ parse_line("app/settings.py-476-a:7:b:8:c"),
+ Some(("app/settings.py".into(), 476, "a:7:b:8:c".into()))
+ );
+ // Extension-less paths reach the dash tier through its negative stop
+ // rather than the extension rule, and must keep resolving.
+ assert_eq!(
+ parse_line("CHANGELOG-12-a:99:b"),
+ Some(("CHANGELOG".into(), 12, "a:99:b".into()))
+ );
+ // A body reference that looks like a *filename* is the canonical form
+ // the hand-off used to miss. `app.py-476-foo.rs:12:ref` is a context
+ // row for `app.py` line 476 whose body is `foo.rs:12:ref`. The dash
+ // tier confirms the boundary (the segment carries an extension), so the
+ // extension dot inside the body must not veto it — before the fix the
+ // colon tier reclaimed the row as path `app.py-476-foo.rs`, line 12.
+ assert_eq!(
+ parse_line("app.py-476-foo.rs:12:ref"),
+ Some(("app.py".into(), 476, "foo.rs:12:ref".into()))
+ );
+ // Same shape behind a directory, and with a Windows separator in the
+ // body reference.
+ assert_eq!(
+ parse_line("pkg/server.ts-91-lib/index.js:7:import"),
+ Some(("pkg/server.ts".into(), 91, "lib/index.js:7:import".into()))
+ );
+ // The body may even be a bare path with no reference at all.
+ assert_eq!(
+ parse_line("app.py-476-./vendor/other.py"),
+ Some(("app.py".into(), 476, "./vendor/other.py".into()))
+ );
+ // A colon row whose *path* holds the dash triplet is untouched: the
+ // dash tier never confirmed a boundary there, so the colon tier wins.
+ assert_eq!(
+ parse_line("logs/2026-05-03/app.log:12:ERROR"),
+ Some(("logs/2026-05-03/app.log".into(), 12, "ERROR".into()))
+ );
+ assert_eq!(
+ parse_line("migrations/20240101-002-add_users.sql:12:SELECT"),
+ Some((
+ "migrations/20240101-002-add_users.sql".into(),
+ 12,
+ "SELECT".into()
+ ))
+ );
+ }
+
#[test]
fn dash_tier_does_not_run_past_the_path_into_the_body() {
// The dash tier keeps the *last* `-<digits>-` marker so that a
diff --git a/tests/test_search_compressor.py b/tests/test_search_compressor.py
index 962209c31..a40f246a9 100644
--- a/tests/test_search_compressor.py
+++ b/tests/test_search_compressor.py
@@ -112,6 +112,109 @@ more random text
assert len(file_matches) == 2
+class TestContextLineBodyReference:
+ """A ``name:N:`` reference in a context line's body must not become the marker.
+
+ ripgrep emits ``path-line-content`` for *context* lines and
+ ``path:line:content`` for *match* lines, and real bodies routinely carry
+ their own ``name:N:`` references. The colon tier used to claim such a
+ reference as the line-number marker whenever no whitespace preceded it,
+ which pushed the real ``-N-`` marker into the path and reported the body's
+ number as the line number -- inventing a file that does not exist and
+ pairing content with a line it never came from (issue #3545).
+ """
+
+ def test_body_reference_does_not_become_the_line_number(self):
+ content = "app/settings.py-476-a:7:b:8:c"
+ compressor = SearchCompressor()
+ file_matches = compressor._parse_search_results(content)
+
+ assert list(file_matches) == ["app/settings.py"]
+ matches = file_matches["app/settings.py"].matches
+ assert len(matches) == 1
+ assert matches[0].line_number == 476
+ assert matches[0].content == "a:7:b:8:c"
+
+ def test_extensionless_context_path_keeps_its_own_line_number(self):
+ content = "CHANGELOG-12-a:99:b"
+ compressor = SearchCompressor()
+ file_matches = compressor._parse_search_results(content)
+
+ assert list(file_matches) == ["CHANGELOG"]
+ matches = file_matches["CHANGELOG"].matches
+ assert len(matches) == 1
+ assert matches[0].line_number == 12
+ assert matches[0].content == "a:99:b"
+
+ def test_colon_row_with_dashed_path_is_unaffected(self):
+ """The dash marker sits in the *path* here, so the colon tier still wins."""
+ content = "logs/2026-05-03/app.log:12:ERROR"
+ compressor = SearchCompressor()
+ file_matches = compressor._parse_search_results(content)
+
+ assert list(file_matches) == ["logs/2026-05-03/app.log"]
+ matches = file_matches["logs/2026-05-03/app.log"].matches
+ assert len(matches) == 1
+ assert matches[0].line_number == 12
+ assert matches[0].content == "ERROR"
+
+ def test_filename_style_body_reference_keeps_the_context_coordinates(self):
+ """A body reference that looks like a *filename* must not take the row.
+
+ ``app.py-476-foo.rs:12:ref`` is a ripgrep context row for ``app.py``
+ line 476 whose body is ``foo.rs:12:ref``. The dash tier confirms the
+ boundary (the segment carries an extension), so the extension dot
+ inside the body says nothing about where the path ended. Before the
+ fix the colon tier reclaimed the row as the nonexistent path
+ ``app.py-476-foo.rs`` at line 12.
+ """
+ content = "app.py-476-foo.rs:12:ref"
+ compressor = SearchCompressor()
+ file_matches = compressor._parse_search_results(content)
+
+ assert list(file_matches) == ["app.py"]
+ matches = file_matches["app.py"].matches
+ assert len(matches) == 1
+ assert matches[0].line_number == 476
+ assert matches[0].content == "foo.rs:12:ref"
+
+ def test_filename_style_body_reference_behind_a_directory(self):
+ """Same shape with a directory component, which also looks path-like."""
+ content = "pkg/server.ts-91-lib/index.js:7:import"
+ compressor = SearchCompressor()
+ file_matches = compressor._parse_search_results(content)
+
+ assert list(file_matches) == ["pkg/server.ts"]
+ matches = file_matches["pkg/server.ts"].matches
+ assert len(matches) == 1
+ assert matches[0].line_number == 91
+ assert matches[0].content == "lib/index.js:7:import"
+
+ def test_bare_path_body_keeps_the_context_coordinates(self):
+ """The body needs no reference at all to be path-like."""
+ content = "app.py-476-./vendor/other.py"
+ compressor = SearchCompressor()
+ file_matches = compressor._parse_search_results(content)
+
+ assert list(file_matches) == ["app.py"]
+ matches = file_matches["app.py"].matches
+ assert len(matches) == 1
+ assert matches[0].line_number == 476
+ assert matches[0].content == "./vendor/other.py"
+
+ def test_many_context_rows_keep_their_own_coordinates(self):
+ """Every coordinate an agent would act on survives across many rows."""
+ content = "\n".join(f"pkg/mod/file.py-{476 + i * 7}-hits:{i}:of:9" for i in range(12))
+ compressor = SearchCompressor()
+ file_matches = compressor._parse_search_results(content)
+
+ assert list(file_matches) == ["pkg/mod/file.py"]
+ matches = file_matches["pkg/mod/file.py"].matches
+ assert [m.line_number for m in matches] == [476 + i * 7 for i in range(12)]
+ for i, match in enumerate(matches):
+ assert match.content == f"hits:{i}:of:9"
+
+
class TestFileGrouping:
"""Tests for grouping matches by file."""