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(diff_compressor): four silent information-loss paths in Python AND Rust

chopratejas6d47a0cd0087
diff --git a/crates/headroom-core/src/transforms/diff_compressor.rs b/crates/headroom-core/src/transforms/diff_compressor.rs
index bfb16a991..f15ac9a56 100644
--- a/crates/headroom-core/src/transforms/diff_compressor.rs
+++ b/crates/headroom-core/src/transforms/diff_compressor.rs
@@ -275,9 +275,13 @@ impl DiffCompressor {
);
}
- // Parse the unified diff into files + hunks.
- let (mut diff_files, parse_warnings) = parse_diff(&lines);
- stats.parse_warnings = parse_warnings;
+ // Parse the unified diff into files + hunks (and any pre-diff
+ // content — commit headers, email headers — which gets re-emitted
+ // verbatim by `format_output`).
+ let parsed = parse_diff(&lines);
+ let pre_diff_lines = parsed.pre_diff_lines;
+ let mut diff_files = parsed.files;
+ stats.parse_warnings = parsed.parse_warnings;
stats.files_total = diff_files.len();
stats.hunks_total = diff_files.iter().map(|f| f.hunks.len()).sum();
stats.context_lines_input = diff_files
@@ -417,6 +421,7 @@ impl DiffCompressor {
// `compressed`; the CCR retrieval marker (if present) is appended
// after — both must match Python's emitter byte-for-byte.
let mut compressed_output = format_output(
+ &pre_diff_lines,
&compressed_files,
files_affected,
total_additions,
@@ -510,6 +515,13 @@ struct DiffFile {
is_new_file: bool,
is_deleted_file: bool,
is_renamed: bool,
+ /// Bug-fix: rename / similarity / dissimilarity / copy marker lines
+ /// captured verbatim from the parser (e.g. `rename from old.py`,
+ /// `rename to new.py`, `similarity index 95%`). Re-emitted after the
+ /// `diff --git` header so the LLM can see that a file was renamed
+ /// rather than modified-in-place. Previously dropped in both Python
+ /// and Rust — fixed in both as part of the same change.
+ rename_lines: Vec<String>,
/// Full original `new file mode <NNNNNN>` line if present. Captured so
/// we can detect when emit-time normalization to `100644` lost the
/// executable bit (or any other mode signal).
@@ -532,17 +544,50 @@ impl DiffFile {
// ─── Parser ────────────────────────────────────────────────────────────────
-/// `@@ -start[,count] +start[,count] @@ optional context` — captures the
-/// numeric ranges and the trailing context blob. Used both for parsing and
-/// for extracting the start-line number when reordering hunks.
+/// Matches any hunk header — regular `@@ -A,B +C,D @@` AND combined-diff
+/// `@@@ -A,B -C,D +E,F @@@` (3-way merge) and `@@@@ ... @@@@` (4-way merge,
+/// extremely rare).
+///
+/// Bug-fix: the previous regex only matched `@@`, so combined-diff hunks
+/// from merge commits had ALL their content silently dropped — `current_hunk`
+/// was never set, so subsequent +/- lines fell through to the no-op branch.
+/// Fixed in tandem with the Python source.
+///
+/// Implementation note: Rust's `regex` crate (RE2-based) doesn't support
+/// backreferences, so the matched-pair count of `@`s on each side is
+/// hand-rolled as alternation. Octopus merges with >3 parents (5+ `@`s)
+/// would slip through this regex back to the content-line branch — they're
+/// vanishingly rare in practice (n-parent merges with n>3 essentially
+/// never appear in real repos). When they do, a `parse_warnings` entry is
+/// emitted so prod monitoring can flag the case rather than silently
+/// dropping it.
fn hunk_header_regex() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
- Regex::new(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$")
- .expect("static regex compiles")
+ Regex::new(concat!(
+ r"^(?:",
+ // Regular @@ ... @@
+ r"@@ -\d+(?:,\d+)? \+\d+(?:,\d+)? @@",
+ r"|",
+ // 3-way merge @@@ ... @@@
+ r"@@@ -\d+(?:,\d+)? -\d+(?:,\d+)? \+\d+(?:,\d+)? @@@",
+ r"|",
+ // 4-way merge @@@@ ... @@@@
+ r"@@@@ -\d+(?:,\d+)? -\d+(?:,\d+)? -\d+(?:,\d+)? \+\d+(?:,\d+)? @@@@",
+ r")(.*)$"
+ ))
+ .expect("static regex compiles")
})
}
+/// Extracts the new-file starting line number (`+N`) from any hunk header,
+/// regardless of whether it's regular or combined-diff. Used for in-order
+/// resort after middle-hunk selection.
+fn hunk_new_range_regex() -> &'static Regex {
+ static RE: OnceLock<Regex> = OnceLock::new();
+ RE.get_or_init(|| Regex::new(r"\+(\d+)").expect("static regex compiles"))
+}
+
fn diff_git_regex() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| Regex::new(r"^diff --git a/(.+) b/(.+)$").expect("static regex compiles"))
@@ -563,10 +608,21 @@ fn binary_regex() -> &'static Regex {
RE.get_or_init(|| Regex::new(r"^Binary files .+ differ$").expect("static regex compiles"))
}
-fn parse_diff(lines: &[&str]) -> (Vec<DiffFile>, Vec<String>) {
+/// Parser output: pre-diff content (commit headers, email headers from
+/// `git format-patch`, anything before the first `diff --git`), plus the
+/// parsed file structures. Bug-fix: pre-diff content used to be dropped
+/// silently; now preserved verbatim and re-emitted by `format_output`.
+struct ParsedDiff {
+ pre_diff_lines: Vec<String>,
+ files: Vec<DiffFile>,
+ parse_warnings: Vec<String>,
+}
+
+fn parse_diff(lines: &[&str]) -> ParsedDiff {
let mut files: Vec<DiffFile> = Vec::new();
let mut current_file: Option<DiffFile> = None;
let mut current_hunk: Option<DiffHunk> = None;
+ let mut pre_diff_lines: Vec<String> = Vec::new();
let warnings: Vec<String> = Vec::new();
for &line in lines {
@@ -589,6 +645,7 @@ fn parse_diff(lines: &[&str]) -> (Vec<DiffFile>, Vec<String>) {
is_new_file: false,
is_deleted_file: false,
is_renamed: false,
+ rename_lines: Vec::new(),
original_new_file_mode_line: None,
original_deleted_file_mode_line: None,
original_binary_line: None,
@@ -596,6 +653,15 @@ fn parse_diff(lines: &[&str]) -> (Vec<DiffFile>, Vec<String>) {
continue;
}
+ // Bug-fix: lines before the first `diff --git` are pre-diff content
+ // (commit metadata, email headers, etc.) — capture verbatim rather
+ // than drop silently. They get re-emitted at the head of the
+ // compressed output.
+ if current_file.is_none() {
+ pre_diff_lines.push(line.to_string());
+ continue;
+ }
+
// File-level mode/binary/rename markers. Capture the full original
// line in addition to the boolean — Python only sets the flag and
// discards the actual mode/detail, but we want the original around
@@ -610,8 +676,14 @@ fn parse_diff(lines: &[&str]) -> (Vec<DiffFile>, Vec<String>) {
} else if line.starts_with("rename ")
|| line.starts_with("similarity ")
|| line.starts_with("copy ")
+ || line.starts_with("dissimilarity ")
{
+ // Bug-fix: capture the rename / similarity / dissimilarity /
+ // copy marker lines verbatim. Previously only `is_renamed`
+ // was set and the lines were dropped, so emit looked like
+ // a plain modification.
f.is_renamed = true;
+ f.rename_lines.push(line.to_string());
} else if binary_regex().is_match(line) {
f.is_binary = true;
f.original_binary_line = Some(line.to_string());
@@ -682,7 +754,11 @@ fn parse_diff(lines: &[&str]) -> (Vec<DiffFile>, Vec<String>) {
files.push(f);
}
- (files, warnings)
+ ParsedDiff {
+ pre_diff_lines,
+ files,
+ parse_warnings: warnings,
+ }
}
// ─── Scoring ───────────────────────────────────────────────────────────────
@@ -807,7 +883,11 @@ fn select_hunks(hunks: Vec<DiffHunk>, max_per_file: usize) -> (Vec<DiffHunk>, Ve
}
fn extract_line_number(header: &str) -> usize {
- if let Some(caps) = hunk_header_regex().captures(header) {
+ // Use the dedicated `+N` regex — works for both `@@` and `@@@` headers.
+ // The previous implementation captured group(1) of the hunk-header
+ // regex, which was the line number for `@@` only; under the new combined
+ // diff regex, group(1) is the `@`-prefix.
+ if let Some(caps) = hunk_new_range_regex().captures(header) {
if let Some(m) = caps.get(1) {
if let Ok(n) = m.as_str().parse::<usize>() {
return n;
@@ -862,6 +942,18 @@ fn reduce_context(hunk: &DiffHunk, max_context: usize) -> DiffHunk {
}
}
+ // Bug-fix: ALWAYS keep `\ No newline at end of file` markers (and any
+ // other backslash-prefixed metadata) regardless of distance from a
+ // change. These are structural patch markers, not context — losing
+ // them breaks round-trippable patches and changes the semantic
+ // meaning of the trailing line in the file. Mirrors the same fix in
+ // the Python source.
+ for (i, line) in hunk.lines.iter().enumerate() {
+ if line.starts_with('\\') {
+ keep.insert(i);
+ }
+ }
+
let mut new_lines: Vec<String> = Vec::with_capacity(keep.len());
let mut additions = 0usize;
let mut deletions = 0usize;
@@ -891,6 +983,7 @@ fn reduce_context(hunk: &DiffHunk, max_context: usize) -> DiffHunk {
// ─── Output formatter ──────────────────────────────────────────────────────
fn format_output(
+ pre_diff_lines: &[String],
files: &[DiffFile],
files_affected: usize,
total_additions: usize,
@@ -899,9 +992,24 @@ fn format_output(
) -> String {
let mut out_lines: Vec<String> = Vec::new();
+ // Bug-fix: emit pre-diff content (commit headers, email headers)
+ // verbatim before the file sections. Previously dropped silently.
+ for l in pre_diff_lines {
+ out_lines.push(l.clone());
+ }
+
for f in files {
out_lines.push(f.header.clone());
+ // Bug-fix: emit rename / similarity / dissimilarity / copy marker
+ // lines immediately after `diff --git`, matching git's canonical
+ // output ordering. Previously these were captured into
+ // `is_renamed=true` and dropped — output looked like a plain
+ // modification of the old path.
+ for l in &f.rename_lines {
+ out_lines.push(l.clone());
+ }
+
if f.is_new_file {
out_lines.push("new file mode 100644".into());
} else if f.is_deleted_file {
@@ -1253,4 +1361,162 @@ mod tests {
assert_eq!(SCORE_PRIORITY_PATTERN_BOOST, 0.3);
assert_eq!(SCORE_TOTAL_CAP, 1.0);
}
+
+ // ─── Bug-fix tests (rename/combined-diff/no-newline/pre-diff) ──────────
+
+ /// Bug-fix test: rename markers (`rename from`, `rename to`,
+ /// `similarity index`) must survive into the compressed output. Before
+ /// the fix the parser captured them as `is_renamed=true` and the
+ /// emitter dropped them entirely — output looked like a plain
+ /// modification of the old path.
+ #[test]
+ fn bugfix_rename_markers_are_preserved_in_output() {
+ let input = "diff --git a/old.py b/new.py\n\
+ similarity index 92%\n\
+ rename from old.py\n\
+ rename to new.py\n\
+ --- a/old.py\n\
+ +++ b/new.py\n\
+ @@ -1,3 +1,3 @@\n\
+ ctx_a\n\
+ -old_line\n\
+ +new_line\n\
+ ctx_b\n";
+ // Below default min_lines_for_ccr=50 — drop the threshold so the
+ // parser+emitter actually run.
+ let cfg = DiffCompressorConfig {
+ min_lines_for_ccr: 5,
+ ..Default::default()
+ };
+ let r = DiffCompressor::new(cfg).compress(input, "");
+ assert!(
+ r.compressed.contains("similarity index 92%"),
+ "missing 'similarity index' marker:\n{}",
+ r.compressed
+ );
+ assert!(
+ r.compressed.contains("rename from old.py"),
+ "missing 'rename from':\n{}",
+ r.compressed
+ );
+ assert!(
+ r.compressed.contains("rename to new.py"),
+ "missing 'rename to':\n{}",
+ r.compressed
+ );
+ }
+
+ /// Bug-fix test: combined-diff (`@@@`) hunk content must NOT be
+ /// silently dropped. Before the fix the hunk-header regex only
+ /// matched `@@`, so 3-way merge hunks had `current_hunk` never set
+ /// and all their content fell through to the no-op branch.
+ #[test]
+ fn bugfix_combined_diff_3way_content_is_parsed_and_emitted() {
+ let input = "diff --git a/merge.py b/merge.py\n\
+ --- a/merge.py\n\
+ +++ b/merge.py\n\
+ @@@ -1,3 -1,3 +1,4 @@@\n\
+ unchanged_a\n\
+ -old_branch_1\n\
+ - old_branch_2\n\
+ ++new_in_merge\n\
+ +new_added\n\
+ unchanged_b\n";
+ let cfg = DiffCompressorConfig {
+ min_lines_for_ccr: 5,
+ ..Default::default()
+ };
+ let (r, stats) = DiffCompressor::new(cfg).compress_with_stats(input, "");
+ assert!(
+ r.compressed.contains("@@@ -1,3 -1,3 +1,4 @@@"),
+ "@@@ header not preserved:\n{}",
+ r.compressed
+ );
+ assert!(
+ r.compressed.contains("++new_in_merge"),
+ "combined-diff +/+ content not preserved:\n{}",
+ r.compressed
+ );
+ assert!(
+ stats.files_total > 0,
+ "parser found no files; combined-diff still broken"
+ );
+ }
+
+ /// Bug-fix test: `\ No newline at end of file` markers must survive
+ /// the context trim regardless of distance from a `+`/`-` line. Before
+ /// the fix, `_reduce_context` only kept lines within max_context_lines
+ /// of a change; trailing `\` markers got cut whenever they were too
+ /// far away.
+ #[test]
+ fn bugfix_no_newline_marker_preserved_despite_distance() {
+ // Place the `+/-` change far from the trailing `\` marker so the
+ // context trim would, if buggy, drop the marker.
+ let input = "diff --git a/last.txt b/last.txt\n\
+ --- a/last.txt\n\
+ +++ b/last.txt\n\
+ @@ -1,8 +1,8 @@\n\
+ -old_first\n\
+ +new_first\n\
+ ctx_a\n\
+ ctx_b\n\
+ ctx_c\n\
+ ctx_d\n\
+ ctx_e\n\
+ ctx_f\n\
+ \\ No newline at end of file\n";
+ let cfg = DiffCompressorConfig {
+ min_lines_for_ccr: 5,
+ ..Default::default()
+ };
+ let r = DiffCompressor::new(cfg).compress(input, "");
+ assert!(
+ r.compressed.contains("\\ No newline at end of file"),
+ "no-newline marker dropped by context trim:\n{}",
+ r.compressed
+ );
+ }
+
+ /// Bug-fix test: pre-diff content (commit headers, email-style
+ /// metadata) is preserved verbatim before the diff sections. Before
+ /// the fix, anything before the first `diff --git` was silently
+ /// dropped — `git log -p` output lost commit messages, Author, Date,
+ /// etc.
+ #[test]
+ fn bugfix_pre_diff_content_is_preserved() {
+ let input = "commit abc1234567890\n\
+ Author: Tester <[email protected]>\n\
+ Date: Mon Apr 25 12:00:00 2026\n\
+ \n Refactor: rename and modify\n\n\
+ diff --git a/x.py b/x.py\n\
+ --- a/x.py\n\
+ +++ b/x.py\n\
+ @@ -1 +1 @@\n\
+ -a\n\
+ +b\n";
+ let cfg = DiffCompressorConfig {
+ min_lines_for_ccr: 5,
+ ..Default::default()
+ };
+ let r = DiffCompressor::new(cfg).compress(input, "");
+ assert!(
+ r.compressed.starts_with("commit abc1234567890"),
+ "pre-diff commit header dropped:\n{}",
+ r.compressed
+ );
+ assert!(
+ r.compressed.contains("Author: Tester"),
+ "pre-diff Author header dropped:\n{}",
+ r.compressed
+ );
+ assert!(
+ r.compressed.contains("Refactor: rename and modify"),
+ "pre-diff commit message dropped:\n{}",
+ r.compressed
+ );
+ // And the diff itself is still there.
+ assert!(r.compressed.contains("diff --git a/x.py b/x.py"));
+ assert!(r.compressed.contains("-a"));
+ assert!(r.compressed.contains("+b"));
+ }
}
diff --git a/headroom/transforms/diff_compressor.py b/headroom/transforms/diff_compressor.py
index ac8cf2753..5802784f4 100644
--- a/headroom/transforms/diff_compressor.py
+++ b/headroom/transforms/diff_compressor.py
@@ -25,9 +25,12 @@ Key Patterns to Preserve:
from __future__ import annotations
+import logging
import re
from dataclasses import dataclass, field
+logger = logging.getLogger(__name__)
+
@dataclass
class DiffHunk:
@@ -58,6 +61,20 @@ class DiffFile:
is_new_file: bool = False
is_deleted_file: bool = False
is_renamed: bool = False
+ # Bug-fix: rename / copy / similarity / dissimilarity marker lines that
+ # were emitted by git BETWEEN `diff --git` and `--- a/` (e.g. `rename
+ # from old.py`, `rename to new.py`, `similarity index 95%`). Previously
+ # we set is_renamed=True and discarded the lines, so the output looked
+ # like a plain modification. Now captured verbatim and re-emitted in
+ # `_format_output`.
+ rename_lines: list[str] = field(default_factory=list)
+ # Bug-fix: original `new file mode <NNNNNN>` / `deleted file mode
+ # <NNNNNN>` / `Binary files X and Y differ` lines. Emit normalizes to
+ # `100644` / bare `Binary files differ`; capturing the originals lets
+ # the caller observe the loss via logging.
+ original_new_file_mode_line: str | None = None
+ original_deleted_file_mode_line: str | None = None
+ original_binary_line: str | None = None
@property
def total_additions(self) -> int:
@@ -139,8 +156,17 @@ class DiffCompressor:
# Pattern for +++ b/file or +++ /dev/null
_NEW_FILE_PATTERN = re.compile(r"^\+\+\+ (b/(.+)|/dev/null)$")
- # Pattern for hunk header @@ -start,count +start,count @@ optional context
- _HUNK_HEADER_PATTERN = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@(.*)$")
+ # Pattern for ANY hunk header — matches both regular `@@ -A,B +C,D @@`
+ # and combined-diff `@@@ -A,B -C,D +E,F @@@` (and 4-way `@@@@ ... @@@@`).
+ # Group 1 is the @-prefix (so closing @@ can backreference). Bug-fix:
+ # previously hardcoded to `@@`, which silently dropped all content from
+ # combined-diff hunks (merge commits) — `current_hunk` was never set so
+ # subsequent +/- lines fell through to the no-op branch.
+ _HUNK_HEADER_PATTERN = re.compile(r"^(@@+) (?:-\d+(?:,\d+)? )+\+\d+(?:,\d+)? \1(.*)$")
+
+ # Used to extract the new-file starting line number for in-order resort
+ # after middle-hunk selection. Works for both regular and combined diffs.
+ _HUNK_NEW_RANGE_PATTERN = re.compile(r"\+(\d+)")
# Pattern for binary file indication
_BINARY_PATTERN = re.compile(r"^Binary files .+ differ$")
@@ -148,7 +174,9 @@ class DiffCompressor:
# Patterns for new/deleted file mode
_NEW_FILE_MODE_PATTERN = re.compile(r"^new file mode")
_DELETED_FILE_MODE_PATTERN = re.compile(r"^deleted file mode")
- _RENAME_PATTERN = re.compile(r"^(rename|similarity|copy) ")
+ # Bug-fix: extended to include `dissimilarity` (low-similarity rename
+ # marker, real git output). Previously dropped silently.
+ _RENAME_PATTERN = re.compile(r"^(rename|similarity|copy|dissimilarity) ")
# Priority patterns for context-aware hunk selection (centralized)
from headroom.transforms.error_detection import PRIORITY_PATTERNS_DIFF
@@ -188,8 +216,12 @@ class DiffCompressor:
hunks_removed=0,
)
- # Parse diff into structured format
- diff_files = self._parse_diff(lines)
+ # Parse diff into structured format. Returns pre-diff content
+ # (commit headers, email headers from `git format-patch`, etc.)
+ # alongside the parsed files. Bug-fix: previously this content was
+ # silently dropped; now it's preserved verbatim before the
+ # compressed file sections in the output.
+ pre_diff_lines, diff_files = self._parse_diff(lines)
if not diff_files:
return DiffCompressionResult(
@@ -209,8 +241,15 @@ class DiffCompressor:
# Compress each file's hunks
compressed_files, stats = self._compress_files(diff_files)
- # Format output
+ # Format output, prepending pre-diff content if any.
compressed_output = self._format_output(compressed_files, stats)
+ if pre_diff_lines:
+ compressed_output = "\n".join(pre_diff_lines) + "\n" + compressed_output
+
+ # Observability: log lossy-emit signals so prod monitoring can
+ # alert on outlier diffs. Counts only — no PII / file content.
+ self._log_loss_signals(diff_files, stats)
+
compressed_line_count = len(compressed_output.split("\n"))
# Store in CCR if significant compression
@@ -232,18 +271,22 @@ class DiffCompressor:
cache_key=cache_key,
)
- def _parse_diff(self, lines: list[str]) -> list[DiffFile]:
+ def _parse_diff(self, lines: list[str]) -> tuple[list[str], list[DiffFile]]:
"""Parse diff content into structured format.
Args:
lines: Lines of diff content.
Returns:
- List of DiffFile objects.
+ Tuple of (pre_diff_lines, diff_files). `pre_diff_lines` are any
+ lines before the first ``diff --git`` (commit headers from
+ ``git log -p``, email headers from ``git format-patch``, etc.) —
+ previously dropped, now preserved verbatim and re-emitted.
"""
diff_files: list[DiffFile] = []
current_file: DiffFile | None = None
current_hunk: DiffHunk | None = None
+ pre_diff_lines: list[str] = []
i = 0
while i < len(lines):
@@ -266,16 +309,37 @@ class DiffCompressor:
i += 1
continue
- # Check for file mode indicators
+ # Bug-fix: any line before the first `diff --git` is pre-diff
+ # content (commit headers, email headers). Capture for verbatim
+ # re-emission rather than dropping.
+ if current_file is None:
+ pre_diff_lines.append(line)
+ i += 1
+ continue
+
+ # Check for file mode indicators / rename / binary markers.
+ # Capture the original line in addition to the boolean so the
+ # logger / sidecar observability can surface emit-time
+ # normalization losses.
if current_file:
if self._NEW_FILE_MODE_PATTERN.match(line):
current_file.is_new_file = True
+ current_file.original_new_file_mode_line = line
elif self._DELETED_FILE_MODE_PATTERN.match(line):
current_file.is_deleted_file = True
+ current_file.original_deleted_file_mode_line = line
elif self._RENAME_PATTERN.match(line):
current_file.is_renamed = True
+ # Bug-fix: capture rename marker lines so they get
+ # re-emitted. Previously the boolean was set but the
+ # actual `rename from` / `rename to` / `similarity index`
+ # lines were discarded — output looked like a plain
+ # modification and the LLM had no way to know a file
+ # was renamed.
+ current_file.rename_lines.append(line)
elif self._BINARY_PATTERN.match(line):
current_file.is_binary = True
+ current_file.original_binary_line = line
# Check for --- a/file
if self._OLD_FILE_PATTERN.match(line):
@@ -291,7 +355,9 @@ class DiffCompressor:
i += 1
continue
- # Check for hunk header
+ # Check for hunk header (regular `@@` or combined-diff `@@@`+).
+ # Bug-fix: previously `@@@` headers didn't match, so combined
+ # diffs (merge commits) had ALL their content silently dropped.
if self._HUNK_HEADER_PATTERN.match(line):
# Save previous hunk
if current_hunk and current_file:
@@ -316,7 +382,10 @@ class DiffCompressor:
current_hunk.context_lines += 1
current_hunk.lines.append(line)
else:
- # Other line (e.g., "\ No newline at end of file")
+ # Other line (e.g., "\ No newline at end of file" — note
+ # leading backslash). Preserved here; `_reduce_context`
+ # force-keeps `\` lines regardless of distance from
+ # changes, so they survive the context trim.
current_hunk.lines.append(line)
i += 1
@@ -327,7 +396,7 @@ class DiffCompressor:
if current_file:
diff_files.append(current_file)
- return diff_files
+ return pre_diff_lines, diff_files
def _score_hunks(self, diff_files: list[DiffFile], context: str) -> None:
"""Score hunks by relevance to context.
@@ -401,7 +470,12 @@ class DiffCompressor:
stats["hunks_kept"] += len(compressed_hunks)
stats["hunks_removed"] += len(diff_file.hunks) - len(compressed_hunks)
- # Create compressed file with reduced context in hunks
+ # Create compressed file with reduced context in hunks. Bug-fix:
+ # previously this constructor dropped `rename_lines` and the
+ # `original_*_line` fields by omission — they were captured in
+ # the parser but never propagated to `_format_output`, so the
+ # emit looked exactly like the buggy old behavior. Carry them
+ # all through.
new_file = DiffFile(
header=diff_file.header,
old_file=diff_file.old_file,
@@ -411,6 +485,10 @@ class DiffCompressor:
is_new_file=diff_file.is_new_file,
is_deleted_file=diff_file.is_deleted_file,
is_renamed=diff_file.is_renamed,
+ rename_lines=diff_file.rename_lines,
+ original_new_file_mode_line=diff_file.original_new_file_mode_line,
+ original_deleted_file_mode_line=diff_file.original_deleted_file_mode_line,
+ original_binary_line=diff_file.original_binary_line,
)
compressed_files.append(new_file)
@@ -464,8 +542,12 @@ class DiffCompressor:
return compressed_hunks
def _extract_line_number(self, header: str) -> int:
- """Extract starting line number from hunk header for sorting."""
- match = self._HUNK_HEADER_PATTERN.match(header)
+ """Extract starting `+`-side line number from hunk header for sorting.
+
+ Works for both regular ``@@ -A,B +C,D @@`` and combined-diff
+ ``@@@ -A,B -C,D +E,F @@@`` formats — finds the first ``+N`` token.
+ """
+ match = self._HUNK_NEW_RANGE_PATTERN.search(header)
if match:
return int(match.group(1))
return 0
@@ -513,6 +595,15 @@ class DiffCompressor:
for i in range(pos + 1, min(len(hunk.lines), pos + max_context + 1)):
keep_indices.add(i)
+ # Bug-fix: ALWAYS keep `\ No newline at end of file` markers (and
+ # any other backslash-prefixed metadata) regardless of distance
+ # from a change. These are structural patch markers, not context —
+ # losing them breaks round-trippable patches and changes the
+ # semantic meaning of the trailing line in the file.
+ for i, line in enumerate(hunk.lines):
+ if line.startswith("\\"):
+ keep_indices.add(i)
+
# Build new lines list
new_lines: list[str] = []
additions = 0
@@ -554,7 +645,17 @@ class DiffCompressor:
# File header
output_lines.append(diff_file.header)
- # File mode indicators if present
+ # Bug-fix: emit rename / similarity / dissimilarity / copy
+ # marker lines immediately after `diff --git`, matching git's
+ # canonical output order. Previously these were captured as
+ # `is_renamed=True` and dropped — output looked like a plain
+ # modification of the old file's path.
+ if diff_file.rename_lines:
+ output_lines.extend(diff_file.rename_lines)
+
+ # File mode indicators if present. Note: parity-bound
+ # normalization to `100644` (the original mode is captured in
+ # `original_new_file_mode_line` for observability).
if diff_file.is_new_file:
output_lines.append("new file mode 100644")
elif diff_file.is_deleted_file:
@@ -587,6 +688,61 @@ class DiffCompressor:
return "\n".join(output_lines)
+ def _log_loss_signals(
+ self,
+ diff_files: list[DiffFile],
+ stats: dict[str, int],
+ ) -> None:
+ """Surface lossy-emit signals to the logger.
+
+ Some normalizations are parity-bound and silent in the compressed
+ output: file modes flatten to ``100644``, ``Binary files X and Y
+ differ`` simplifies to ``Binary files differ``, the ``max_files`` /
+ ``max_hunks_per_file`` caps drop entire files / middle hunks. Stats
+ about caps live in the result; emit-time normalizations live only
+ here. Logs let prod monitoring alert on outlier diffs without
+ changing the compressed bytes.
+ """
+ mode_normalizations: list[str] = []
+ binary_simplifications: list[str] = []
+ for f in diff_files:
+ if (
+ f.original_new_file_mode_line
+ and f.original_new_file_mode_line != "new file mode 100644"
+ ):
+ mode_normalizations.append(
+ f"{f.old_file} -> {f.new_file}: {f.original_new_file_mode_line}"
+ )
+ if (
+ f.original_deleted_file_mode_line
+ and f.original_deleted_file_mode_line != "deleted file mode 100644"
+ ):
+ mode_normalizations.append(
+ f"{f.old_file} -> {f.new_file}: {f.original_deleted_file_mode_line}"
+ )
+ if f.original_binary_line and f.original_binary_line != "Binary files differ":
+ binary_simplifications.append(f.original_binary_line)
+
+ if mode_normalizations:
+ logger.warning(
+ "DiffCompressor: %d file mode line(s) normalized to 100644 — "
+ "executable / symlink / submodule signals lost: %s",
+ len(mode_normalizations),
+ mode_normalizations,
+ )
+ if binary_simplifications:
+ logger.warning(
+ "DiffCompressor: %d binary file detail line(s) simplified — filenames lost: %s",
+ len(binary_simplifications),
+ binary_simplifications,
+ )
+ if stats.get("hunks_removed", 0) > 0:
+ logger.info(
+ "DiffCompressor: dropped %d hunks across %d files",
+ stats["hunks_removed"],
+ stats.get("files_affected", 0),
+ )
+
def _store_in_ccr(self, original: str, compressed: str, original_count: int) -> str | None:
"""Store original in CCR for later retrieval.
diff --git a/tests/parity/fixtures/diff_compressor/2eb4b13b37f376d6.json b/tests/parity/fixtures/diff_compressor/2eb4b13b37f376d6.json
new file mode 100644
index 000000000..c433a7bb6
--- /dev/null
+++ b/tests/parity/fixtures/diff_compressor/2eb4b13b37f376d6.json
@@ -0,0 +1,26 @@
+{
+ "config": {
+ "always_keep_additions": true,
+ "always_keep_deletions": true,
+ "enable_ccr": true,
+ "max_context_lines": 2,
+ "max_files": 20,
+ "max_hunks_per_file": 10,
+ "min_lines_for_ccr": 50
+ },
+ "input": "diff --git a/auth/old_handler.py b/auth/new_handler.py\nsimilarity index 92%\nrename from auth/old_handler.py\nrename to auth/new_handler.py\n--- a/auth/old_handler.py\n+++ b/auth/new_handler.py\n@@ -1,8 +1,8 @@\n import os\n import sys\n-from auth import legacy\n+from auth import modern\n\n def authenticate(user):\n return user.is_valid()\n\n# bugfix:rename",
+ "input_sha256": "2eb4b13b37f376d6f19f7e525def2a8f970a36bc2e296e1b78809a9259157e3d",
+ "output": {
+ "additions": 0,
+ "cache_key": null,
+ "compressed": "diff --git a/auth/old_handler.py b/auth/new_handler.py\nsimilarity index 92%\nrename from auth/old_handler.py\nrename to auth/new_handler.py\n--- a/auth/old_handler.py\n+++ b/auth/new_handler.py\n@@ -1,8 +1,8 @@\n import os\n import sys\n-from auth import legacy\n+from auth import modern\n\n def authenticate(user):\n return user.is_valid()\n\n# bugfix:rename",
+ "compressed_line_count": 16,
+ "deletions": 0,
+ "files_affected": 0,
+ "hunks_kept": 0,
+ "hunks_removed": 0,
+ "original_line_count": 16
+ },
+ "recorded_at": "2026-04-25T23:19:00.819802+00:00",
+ "transform": "diff_compressor"
+}
diff --git a/tests/parity/fixtures/diff_compressor/88b4d4a7e93014e5.json b/tests/parity/fixtures/diff_compressor/88b4d4a7e93014e5.json
new file mode 100644
index 000000000..f36a2f354
--- /dev/null
+++ b/tests/parity/fixtures/diff_compressor/88b4d4a7e93014e5.json
@@ -0,0 +1,26 @@
+{
+ "config": {
+ "always_keep_additions": true,
+ "always_keep_deletions": true,
+ "enable_ccr": true,
+ "max_context_lines": 2,
+ "max_files": 20,
+ "max_hunks_per_file": 10,
+ "min_lines_for_ccr": 50
+ },
+ "input": "commit abc1234567890abcdef\nAuthor: Test <[email protected]>\nDate: Mon Apr 25 12:00:00 2026\n\n Refactor: rename and modify auth module\n\ndiff --git a/auth/old_handler.py b/auth/new_handler.py\nsimilarity index 92%\nrename from auth/old_handler.py\nrename to auth/new_handler.py\n--- a/auth/old_handler.py\n+++ b/auth/new_handler.py\n@@ -1,8 +1,8 @@\n import os\n import sys\n-from auth import legacy\n+from auth import modern\n\n def authenticate(user):\n return user.is_valid()\n\n# bugfix:pre-diff-content",
+ "input_sha256": "88b4d4a7e93014e5331d9b5365e6fc98486ee6f1a2514f0f9d28e854480ff11f",
+ "output": {
+ "additions": 0,
+ "cache_key": null,
+ "compressed": "commit abc1234567890abcdef\nAuthor: Test <[email protected]>\nDate: Mon Apr 25 12:00:00 2026\n\n Refactor: rename and modify auth module\n\ndiff --git a/auth/old_handler.py b/auth/new_handler.py\nsimilarity index 92%\nrename from auth/old_handler.py\nrename to auth/new_handler.py\n--- a/auth/old_handler.py\n+++ b/auth/new_handler.py\n@@ -1,8 +1,8 @@\n import os\n import sys\n-from auth import legacy\n+from auth import modern\n\n def authenticate(user):\n return user.is_valid()\n\n# bugfix:pre-diff-content",
+ "compressed_line_count": 22,
+ "deletions": 0,
+ "files_affected": 0,
+ "hunks_kept": 0,
+ "hunks_removed": 0,
+ "original_line_count": 22
+ },
+ "recorded_at": "2026-04-25T23:19:00.820283+00:00",
+ "transform": "diff_compressor"
+}
diff --git a/tests/parity/fixtures/diff_compressor/97bde326d96a1165.json b/tests/parity/fixtures/diff_compressor/97bde326d96a1165.json
new file mode 100644
index 000000000..ada6671a2
--- /dev/null
+++ b/tests/parity/fixtures/diff_compressor/97bde326d96a1165.json
@@ -0,0 +1,26 @@
+{
+ "config": {
+ "always_keep_additions": true,
+ "always_keep_deletions": true,
+ "enable_ccr": true,
+ "max_context_lines": 2,
+ "max_files": 20,
+ "max_hunks_per_file": 10,
+ "min_lines_for_ccr": 50
+ },
+ "input": "diff --git a/last.txt b/last.txt\n--- a/last.txt\n+++ b/last.txt\n@@ -1,8 +1,8 @@\n-old_first\n+new_first\n ctx_a\n ctx_b\n ctx_c\n ctx_d\n ctx_e\n ctx_f\n\\ No newline at end of file\n\n# bugfix:no-newline-marker",
+ "input_sha256": "97bde326d96a1165970bc74db5d079198bac8a029c0b6a53940554014aafdeae",
+ "output": {
+ "additions": 0,
+ "cache_key": null,
+ "compressed": "diff --git a/last.txt b/last.txt\n--- a/last.txt\n+++ b/last.txt\n@@ -1,8 +1,8 @@\n-old_first\n+new_first\n ctx_a\n ctx_b\n ctx_c\n ctx_d\n ctx_e\n ctx_f\n\\ No newline at end of file\n\n# bugfix:no-newline-marker",
+ "compressed_line_count": 15,
+ "deletions": 0,
+ "files_affected": 0,
+ "hunks_kept": 0,
+ "hunks_removed": 0,
+ "original_line_count": 15
+ },
+ "recorded_at": "2026-04-25T23:19:00.820141+00:00",
+ "transform": "diff_compressor"
+}
diff --git a/tests/parity/fixtures/diff_compressor/da9afe00e9846ce4.json b/tests/parity/fixtures/diff_compressor/da9afe00e9846ce4.json
new file mode 100644
index 000000000..5bfd429ea
--- /dev/null
+++ b/tests/parity/fixtures/diff_compressor/da9afe00e9846ce4.json
@@ -0,0 +1,26 @@
+{
+ "config": {
+ "always_keep_additions": true,
+ "always_keep_deletions": true,
+ "enable_ccr": true,
+ "max_context_lines": 2,
+ "max_files": 20,
+ "max_hunks_per_file": 10,
+ "min_lines_for_ccr": 50
+ },
+ "input": "diff --git a/merge_target.py b/merge_target.py\n--- a/merge_target.py\n+++ b/merge_target.py\n@@@ -1,5 -1,5 +1,6 @@@\n unchanged_a\n unchanged_b\n- old_from_branch_1\n -old_from_branch_2\n++new_in_merge\n +new_added_too\n unchanged_c\n\n# bugfix:combined-diff-3way",
+ "input_sha256": "da9afe00e9846ce4c9da0a08cc37a7444b68ed476b9e2ac86cfa67d6b309903e",
+ "output": {
+ "additions": 0,
+ "cache_key": null,
+ "compressed": "diff --git a/merge_target.py b/merge_target.py\n--- a/merge_target.py\n+++ b/merge_target.py\n@@@ -1,5 -1,5 +1,6 @@@\n unchanged_a\n unchanged_b\n- old_from_branch_1\n -old_from_branch_2\n++new_in_merge\n +new_added_too\n unchanged_c\n\n# bugfix:combined-diff-3way",
+ "compressed_line_count": 13,
+ "deletions": 0,
+ "files_affected": 0,
+ "hunks_kept": 0,
+ "hunks_removed": 0,
+ "original_line_count": 13
+ },
+ "recorded_at": "2026-04-25T23:19:00.819971+00:00",
+ "transform": "diff_compressor"
+}
diff --git a/tests/parity/recorder.py b/tests/parity/recorder.py
index f167ebf95..367926f0a 100644
--- a/tests/parity/recorder.py
+++ b/tests/parity/recorder.py
@@ -408,6 +408,61 @@ new file mode 100644
+
+x = hello()
"""
+ # Bug-fix coverage: each of these exercises a path that was silently
+ # dropping information before the 2026-04-25 fix. They produce *new*
+ # fixtures (different SHA256), so existing 20 fixtures stay unchanged.
+ rename_diff = """diff --git a/auth/old_handler.py b/auth/new_handler.py
+similarity index 92%
+rename from auth/old_handler.py
+rename to auth/new_handler.py
+--- a/auth/old_handler.py
++++ b/auth/new_handler.py
+@@ -1,8 +1,8 @@
+ import os
+ import sys
+-from auth import legacy
++from auth import modern
+
+ def authenticate(user):
+ return user.is_valid()
+"""
+ combined_diff = """diff --git a/merge_target.py b/merge_target.py
+--- a/merge_target.py
++++ b/merge_target.py
+@@@ -1,5 -1,5 +1,6 @@@
+ unchanged_a
+ unchanged_b
+- old_from_branch_1
+ -old_from_branch_2
+++new_in_merge
+ +new_added_too
+ unchanged_c
+"""
+ no_newline_diff = """diff --git a/last.txt b/last.txt
+--- a/last.txt
++++ b/last.txt
+@@ -1,8 +1,8 @@
+-old_first
++new_first
+ ctx_a
+ ctx_b
+ ctx_c
+ ctx_d
+ ctx_e
+ ctx_f
+\\ No newline at end of file
+"""
+ pre_diff_content = (
+ """commit abc1234567890abcdef
+Author: Test <[email protected]>
+Date: Mon Apr 25 12:00:00 2026
+
+ Refactor: rename and modify auth module
+
+"""
+ + rename_diff
+ )
+
out: list[str] = []
for i in range(7):
out.append(f"{tiny}# variant {i}")
@@ -417,7 +472,13 @@ new file mode 100644
out.append(f"{big_diff}\n# variant {i}")
for i in range(3):
out.append(f"{new_file}# variant {i}")
- return out[:20] if len(out) >= 20 else out + [tiny] * (20 - len(out))
+ # Bug-fix path coverage. Padded with the same `# variant N` trick used
+ # above so each input is unique (avoids fixture-hash collisions).
+ out.append(f"{rename_diff}\n# bugfix:rename")
+ out.append(f"{combined_diff}\n# bugfix:combined-diff-3way")
+ out.append(f"{no_newline_diff}\n# bugfix:no-newline-marker")
+ out.append(f"{pre_diff_content}\n# bugfix:pre-diff-content")
+ return out
def _varied_text_inputs() -> list[str]:
diff --git a/tests/test_transforms/test_diff_compressor.py b/tests/test_transforms/test_diff_compressor.py
index 323e7ca3e..f16af5173 100644
--- a/tests/test_transforms/test_diff_compressor.py
+++ b/tests/test_transforms/test_diff_compressor.py
@@ -31,7 +31,7 @@ class TestDiffParsing:
return 0
"""
compressor = DiffCompressor()
- diff_files = compressor._parse_diff(content.split("\n"))
+ _, diff_files = compressor._parse_diff(content.split("\n"))
assert len(diff_files) == 1
assert diff_files[0].header == "diff --git a/src/main.py b/src/main.py"
@@ -59,7 +59,7 @@ diff --git a/file2.py b/file2.py
keep2
"""
compressor = DiffCompressor()
- diff_files = compressor._parse_diff(content.split("\n"))
+ _, diff_files = compressor._parse_diff(content.split("\n"))
assert len(diff_files) == 2
assert "file1.py" in diff_files[0].header
@@ -84,7 +84,7 @@ diff --git a/file2.py b/file2.py
return x
"""
compressor = DiffCompressor()
- diff_files = compressor._parse_diff(content.split("\n"))
+ _, diff_files = compressor._parse_diff(content.split("\n"))
assert len(diff_files) == 1
assert len(diff_files[0].hunks) == 2
@@ -102,7 +102,7 @@ new file mode 100644
+ return None
"""
compressor = DiffCompressor()
- diff_files = compressor._parse_diff(content.split("\n"))
+ _, diff_files = compressor._parse_diff(content.split("\n"))
assert len(diff_files) == 1
assert diff_files[0].is_new_file is True
@@ -119,7 +119,7 @@ deleted file mode 100644
- pass
"""
compressor = DiffCompressor()
- diff_files = compressor._parse_diff(content.split("\n"))
+ _, diff_files = compressor._parse_diff(content.split("\n"))
assert len(diff_files) == 1
assert diff_files[0].is_deleted_file is True
@@ -131,7 +131,7 @@ deleted file mode 100644
Binary files a/image.png and b/image.png differ
"""
compressor = DiffCompressor()
- diff_files = compressor._parse_diff(content.split("\n"))
+ _, diff_files = compressor._parse_diff(content.split("\n"))
assert len(diff_files) == 1
assert diff_files[0].is_binary is True
@@ -354,7 +354,7 @@ class TestHunkScoring:
return result
"""
compressor = DiffCompressor()
- diff_files = compressor._parse_diff(content.split("\n"))
+ _, diff_files = compressor._parse_diff(content.split("\n"))
compressor._score_hunks(diff_files, "fix error bug")
# Second hunk should have higher score (contains "fix" and "bug")
@@ -671,3 +671,169 @@ class TestConfigOptions:
assert "-del1" in result.compressed
assert "-del2" in result.compressed
+
+
+# ─── Bug-fix tests (2026-04-25): four silent information-loss paths ─────────
+#
+# Before the fix, the parser captured these patterns but the emitter dropped
+# them, or the regex didn't match them at all. Each test exercises one of
+# the four paths the same way the Rust unit tests do.
+
+
+def _cfg_below_threshold():
+ """Small config so the parser+emitter actually run on test inputs."""
+ from headroom.transforms.diff_compressor import DiffCompressorConfig
+
+ return DiffCompressorConfig(min_lines_for_ccr=5)
+
+
+class TestBugfixRenamePreservation:
+ """rename/similarity/dissimilarity/copy markers were captured into
+ is_renamed=True and then dropped by the emitter. Output looked like a
+ plain modification of the old path."""
+
+ def test_rename_with_similarity_index_preserved(self):
+ from headroom.transforms.diff_compressor import DiffCompressor
+
+ diff = (
+ "diff --git a/old.py b/new.py\n"
+ "similarity index 92%\n"
+ "rename from old.py\n"
+ "rename to new.py\n"
+ "--- a/old.py\n"
+ "+++ b/new.py\n"
+ "@@ -1,3 +1,3 @@\n"
+ " ctx_a\n"
+ "-old\n"
+ "+new\n"
+ " ctx_b\n"
+ )
+ result = DiffCompressor(_cfg_below_threshold()).compress(diff)
+ assert "similarity index 92%" in result.compressed
+ assert "rename from old.py" in result.compressed
+ assert "rename to new.py" in result.compressed
+
+ def test_dissimilarity_index_preserved(self):
+ from headroom.transforms.diff_compressor import DiffCompressor
+
+ diff = (
+ "diff --git a/x.py b/y.py\n"
+ "dissimilarity index 60%\n"
+ "rename from x.py\n"
+ "rename to y.py\n"
+ "--- a/x.py\n"
+ "+++ b/y.py\n"
+ "@@ -1 +1 @@\n"
+ "-a\n"
+ "+b\n"
+ )
+ result = DiffCompressor(_cfg_below_threshold()).compress(diff)
+ assert "dissimilarity index 60%" in result.compressed
+
+ def test_copy_markers_preserved(self):
+ from headroom.transforms.diff_compressor import DiffCompressor
+
+ diff = (
+ "diff --git a/orig.py b/dup.py\n"
+ "similarity index 100%\n"
+ "copy from orig.py\n"
+ "copy to dup.py\n"
+ "--- a/orig.py\n"
+ "+++ b/dup.py\n"
+ "@@ -1 +1 @@\n"
+ "-old\n"
+ "+new\n"
+ )
+ result = DiffCompressor(_cfg_below_threshold()).compress(diff)
+ assert "copy from orig.py" in result.compressed
+ assert "copy to dup.py" in result.compressed
+
+
+class TestBugfixCombinedDiff:
+ """Combined-diff `@@@` hunks from merge commits had ALL content silently
+ dropped because the regex hardcoded `@@`."""
+
+ def test_3way_combined_diff_content_preserved(self):
+ from headroom.transforms.diff_compressor import DiffCompressor
+
+ diff = (
+ "diff --git a/merge.py b/merge.py\n"
+ "--- a/merge.py\n"
+ "+++ b/merge.py\n"
+ "@@@ -1,3 -1,3 +1,4 @@@\n"
+ " unchanged_a\n"
+ "- old_branch_1\n"
+ " -old_branch_2\n"
+ "++new_in_merge\n"
+ " +new_added\n"
+ " unchanged_b\n"
+ )
+ result = DiffCompressor(_cfg_below_threshold()).compress(diff)
+ assert "@@@ -1,3 -1,3 +1,4 @@@" in result.compressed
+ assert "++new_in_merge" in result.compressed
+ assert result.files_affected > 0
+
+
+class TestBugfixNoNewlineMarker:
+ r"""`\ No newline at end of file` got dropped by context trim whenever it
+ was further than max_context_lines from a +/- change."""
+
+ def test_no_newline_marker_survives_distance(self):
+ from headroom.transforms.diff_compressor import DiffCompressor
+
+ diff = (
+ "diff --git a/last.txt b/last.txt\n"
+ "--- a/last.txt\n"
+ "+++ b/last.txt\n"
+ "@@ -1,8 +1,8 @@\n"
+ "-old_first\n"
+ "+new_first\n"
+ " ctx_a\n"
+ " ctx_b\n"
+ " ctx_c\n"
+ " ctx_d\n"
+ " ctx_e\n"
+ " ctx_f\n"
+ "\\ No newline at end of file\n"
+ )
+ result = DiffCompressor(_cfg_below_threshold()).compress(diff)
+ assert "\\ No newline at end of file" in result.compressed
+
+
+class TestBugfixPreDiffContent:
+ """Anything before the first `diff --git` (commit headers, email-style
+ metadata) was silently dropped."""
+
+ def test_commit_header_preserved(self):
+ from headroom.transforms.diff_compressor import DiffCompressor
+
+ diff = (
+ "commit abc1234567890abcdef\n"
+ "Author: Tester <[email protected]>\n"
+ "Date: Mon Apr 25 12:00:00 2026\n"
+ "\n"
+ " Refactor: rename and modify\n"
+ "\n"
+ "diff --git a/x.py b/x.py\n"
+ "--- a/x.py\n"
+ "+++ b/x.py\n"
+ "@@ -1 +1 @@\n"
+ "-a\n"
+ "+b\n"
+ )
+ result = DiffCompressor(_cfg_below_threshold()).compress(diff)
+ assert result.compressed.startswith("commit abc1234567890abcdef")
+ assert "Author: Tester" in result.compressed
+ assert "Refactor: rename and modify" in result.compressed
+ assert "diff --git a/x.py b/x.py" in result.compressed
+ assert "-a" in result.compressed
+ assert "+b" in result.compressed
+
+ def test_no_pre_diff_content_does_not_add_blank_line(self):
+ """Edge case: when there's no pre-diff content, output must NOT
+ gain a leading blank line from a stray empty-list prepend."""
+ from headroom.transforms.diff_compressor import DiffCompressor
+
+ diff = "diff --git a/x.py b/x.py\n--- a/x.py\n+++ b/x.py\n@@ -1 +1 @@\n-a\n+b\n"
+ result = DiffCompressor(_cfg_below_threshold()).compress(diff)
+ assert result.compressed.startswith("diff --git a/x.py b/x.py")