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(rust): reformat/offload pipeline + log templates + diff noise (Phase 3g rework)

chopratejas01a423a3164e
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json
index 977997e8d..568f24331 100644
--- a/.claude-plugin/marketplace.json
+++ b/.claude-plugin/marketplace.json
@@ -5,14 +5,14 @@
},
"metadata": {
"description": "Headroom marketplace for Claude Code and GitHub Copilot CLI plugins.",
- "version": "0.16.0"
+ "version": "0.20.2"
},
"plugins": [
{
"name": "headroom",
"source": "./plugins/headroom-agent-hooks",
"description": "Headroom startup hooks for Claude Code and GitHub Copilot CLI.",
- "version": "0.16.0",
+ "version": "0.20.2",
"author": {
"name": "Headroom Contributors",
"url": "https://github.com/chopratejas/headroom"
diff --git a/.github/plugin/marketplace.json b/.github/plugin/marketplace.json
index 977997e8d..568f24331 100644
--- a/.github/plugin/marketplace.json
+++ b/.github/plugin/marketplace.json
@@ -5,14 +5,14 @@
},
"metadata": {
"description": "Headroom marketplace for Claude Code and GitHub Copilot CLI plugins.",
- "version": "0.16.0"
+ "version": "0.20.2"
},
"plugins": [
{
"name": "headroom",
"source": "./plugins/headroom-agent-hooks",
"description": "Headroom startup hooks for Claude Code and GitHub Copilot CLI.",
- "version": "0.16.0",
+ "version": "0.20.2",
"author": {
"name": "Headroom Contributors",
"url": "https://github.com/chopratejas/headroom"
diff --git a/Cargo.lock b/Cargo.lock
index 3e913e454..c80b2b6fd 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1330,6 +1330,7 @@ dependencies = [
"magika",
"md-5",
"proptest",
+ "rayon",
"regex",
"serde",
"serde_json",
@@ -1337,6 +1338,7 @@ dependencies = [
"thiserror 1.0.69",
"tiktoken-rs",
"tokenizers 0.21.4",
+ "toml",
"tracing",
"unidiff",
]
@@ -3233,6 +3235,15 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "serde_spanned"
+version = "0.6.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"
+dependencies = [
+ "serde",
+]
+
[[package]]
name = "serde_urlencoded"
version = "0.7.1"
@@ -3745,6 +3756,47 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "toml"
+version = "0.8.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc1beb996b9d83529a9e75c17a1686767d148d70663143c7854d8b4a09ced362"
+dependencies = [
+ "serde",
+ "serde_spanned",
+ "toml_datetime",
+ "toml_edit",
+]
+
+[[package]]
+name = "toml_datetime"
+version = "0.6.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22cddaf88f4fbc13c51aebbf5f8eceb5c7c5a9da2ac40a13519eb5b0a0e8f11c"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "toml_edit"
+version = "0.22.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a"
+dependencies = [
+ "indexmap",
+ "serde",
+ "serde_spanned",
+ "toml_datetime",
+ "toml_write",
+ "winnow",
+]
+
+[[package]]
+name = "toml_write"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d99f8c9a7727884afe522e9bd5edbfc91a3312b36a77b5fb8926e4c31a41801"
+
[[package]]
name = "tower"
version = "0.5.3"
@@ -4542,6 +4594,15 @@ version = "0.53.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
+[[package]]
+name = "winnow"
+version = "0.7.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"
+dependencies = [
+ "memchr",
+]
+
[[package]]
name = "wiremock"
version = "0.6.5"
diff --git a/crates/headroom-core/Cargo.toml b/crates/headroom-core/Cargo.toml
index 7fef62082..37521a0ea 100644
--- a/crates/headroom-core/Cargo.toml
+++ b/crates/headroom-core/Cargo.toml
@@ -76,6 +76,18 @@ unidiff = "0.4"
# happen as a post-filter on the byte offsets the automaton returns.
# Default features (std, perf-literal) keep the build small.
aho-corasick = "1"
+# `rayon` powers the pipeline orchestrator's parallel reformat-vs-bloat
+# evaluation: while a worker thread runs the structural reformat passes,
+# another set of threads run the per-offload bloat estimators in parallel.
+# Reformat completion + all bloat estimates need to be ready before the
+# orchestrator can decide which offloads to actually execute, so two-phase
+# join semantics (`rayon::join` + `par_iter`) are exactly what we need.
+rayon = "1"
+# `toml` reads the default pipeline configuration shipped at
+# `config/pipeline.toml`. The defaults embed via `include_str!` so a
+# stock binary needs no external file; production deployments override
+# by loading their own TOML at startup.
+toml = "0.8"
[dev-dependencies]
proptest = "1"
diff --git a/crates/headroom-core/config/pipeline.toml b/crates/headroom-core/config/pipeline.toml
new file mode 100644
index 000000000..650ef2eed
--- /dev/null
+++ b/crates/headroom-core/config/pipeline.toml
@@ -0,0 +1,135 @@
+# Compression pipeline default configuration.
+#
+# This file is embedded into the headroom-core binary via `include_str!`
+# at build time, so a stock binary needs no external file. Production
+# deployments override these defaults by loading their own TOML at
+# startup via `PipelineConfig::from_str` or `from_file`.
+#
+# All thresholds chosen CONSERVATIVELY. The pipeline is on the hot
+# path of every Claude Code / Codex / agent tool-call response — bias
+# toward "don't fire CCR unless we're sure" to avoid forcing
+# unnecessary retrieval round trips. A retrieval round trip costs
+# tokens (the marker text), latency (the tool call), and risk (the
+# LLM might not retrieve when it should).
+
+[pipeline]
+# Below this fraction of input bytes (after reformat), we consider
+# the reformat phase to have "succeeded" and skip offloads UNLESS the
+# bloat estimator demands them. 0.5 = "if reformat shrunk us to half
+# the original, that's enough for now."
+reformat_target_ratio = 0.5
+
+# Bloat threshold above which we ALWAYS run the offload, regardless
+# of reformat success. 0.5 = "if a domain-specific estimator says
+# half this content is bloat, CCR offload is worth the retrieval
+# cost." Conservative — most real-world tool outputs sit below 0.5.
+bloat_threshold = 0.5
+
+# After reformat, if (output_len / input_len) > this, we run offload
+# transforms even if their bloat estimate is below `bloat_threshold`.
+# Captures the "reformat barely helped, content might still be
+# salvageable via offload" case. 0.85 = "if reformat saved less than
+# 15% of bytes, try offload as a fallback."
+offload_fallback_ratio = 0.85
+
+# ─── Per-domain bloat estimator config ──────────────────────────────
+#
+# Each domain has its own structural-only signal for "this content
+# would benefit from CCR offload." The estimators MUST be cheap (no
+# full compression pass) so they run in parallel with the reformat
+# phase via rayon::join.
+
+[bloat.log]
+# Inputs shorter than this in lines never trigger offload; the
+# overhead of CCR retrieval would outweigh any savings. Matches
+# LogCompressorConfig::min_lines_for_ccr.
+min_lines = 50
+# How many lines to sample when scoring importance density on long
+# logs. Sampling beats full-scan because per-line keyword detection
+# costs aho-corasick + word-boundary checks per call. 100 samples
+# on a 10k-line log gives <1% error vs full scan.
+sample_size = 100
+# Lines with priority strictly above this are "high-priority" — the
+# rest count as dilution. Calibrated against the signals trait's
+# priority scale (errors return ~0.9, warnings ~0.7, info ~0.0).
+high_priority_threshold = 0.4
+# Weighted combination of two signals, summing to ≤ 1.0. The repetition
+# weight catches "log full of identical INFO heartbeats"; the priority
+# dilution weight catches "log full of unique-but-irrelevant lines
+# burying a few errors." Production tuning may shift these.
+uniqueness_weight = 0.5
+priority_dilution_weight = 0.5
+
+[bloat.diff]
+# Inputs shorter than this in lines never trigger offload.
+min_lines = 50
+# Below this context-to-change ratio, we consider the diff dense and
+# don't offload. Above, the diff is mostly context — high bloat.
+# 0.6 = "60% of relevant lines are context" is the threshold.
+normal_context_ratio = 0.6
+
+[bloat.search]
+# Inputs with fewer matches never trigger offload.
+min_matches = 10
+# Average matches per file at which we hit "fully clustered"
+# bloat = 1.0. 10 matches/file means the result set is mostly
+# repeated hits in the same files — ideal CCR candidate.
+cluster_threshold = 10.0
+
+# ─── Reformat configs ───────────────────────────────────────────────
+#
+# Reformats pack input denser without losing information. Configs here
+# tune the structural-only knobs each reformat exposes.
+
+[reformat.log_template]
+# Don't bother template-mining inputs shorter than this. The cost of
+# the bucket walk + table emission isn't worth it on small logs.
+min_lines = 20
+# Minimum consecutive lines that share a template before we collapse
+# them into a "[Template: ...] (Nx)" block + variant table. Smaller
+# values catch more — but 3 is the floor below which the dedup overhead
+# (template header + brackets) exceeds the savings.
+min_run = 3
+# Two lines are "same template" if at least this fraction of their
+# tokens match positionally (after token-count match). 0.4 = Drain's
+# published default — matches `<TS> INFO worker-<N> processing job <N>`
+# style families (where 3 of 6 tokens are constants) while rejecting
+# genuinely different shapes. Pairs with `min_constant_tokens` so a
+# template with too few anchor tokens won't be promoted regardless of
+# how high the similarity score happens to land.
+similarity_threshold = 0.4
+# Floor on the number of constant tokens a template must have. A
+# "template" of all-`<*>` tokens carries no readable signal — emit
+# verbatim instead. 2 = "must share at least 2 anchor tokens."
+min_constant_tokens = 2
+
+# ─── Diff-noise offload config ─────────────────────────────────────
+#
+# Drop hunks for files that match these glob-like suffixes (literal
+# filename-suffix match, no globbing). Lockfiles dominate diff size in
+# JS/Python/Ruby/Go projects but carry near-zero semantic value for
+# LLM consumption — the version bump in the manifest already captures
+# what the LLM needs to know.
+
+[offload.diff_noise]
+# Inputs shorter than this never trigger noise offload.
+min_lines = 30
+# Lockfile filename suffixes (case-sensitive). Match is "path ENDS
+# WITH this suffix and the next char is `/` or start-of-path." Add
+# project-specific lock files here without code changes.
+lockfile_suffixes = [
+ "Cargo.lock",
+ "package-lock.json",
+ "yarn.lock",
+ "pnpm-lock.yaml",
+ "poetry.lock",
+ "Pipfile.lock",
+ "Gemfile.lock",
+ "go.sum",
+ "composer.lock",
+]
+# Drop hunks where every change is whitespace-only (added/removed
+# blank lines, trailing whitespace, indentation-only changes). These
+# show up in formatter / linter commits and carry no signal the LLM
+# needs to reason about.
+drop_whitespace_only_hunks = true
diff --git a/crates/headroom-core/src/transforms/mod.rs b/crates/headroom-core/src/transforms/mod.rs
index ffd77550a..93274a4df 100644
--- a/crates/headroom-core/src/transforms/mod.rs
+++ b/crates/headroom-core/src/transforms/mod.rs
@@ -41,9 +41,9 @@ pub use log_compressor::{
};
pub use magika_detector::{magika_detect, map_magika_label, MagikaDetectorError};
pub use pipeline::{
- CompressionContext, CompressionPipeline, CompressionPipelineBuilder, JsonMinifier,
- LineImportanceFilter, LineImportanceFilterConfig, LosslessTransform, LossyTransform,
- PipelineConfig, PipelineResult, TransformError, TransformResult,
+ CompressionContext, CompressionPipeline, CompressionPipelineBuilder, DiffNoise, DiffOffload,
+ JsonMinifier, LogOffload, LogTemplate, OffloadOutput, OffloadTransform, PipelineConfig,
+ PipelineResult, ReformatOutput, ReformatTransform, TransformError,
};
pub use search_compressor::{
FileMatches, SearchCompressionResult, SearchCompressor, SearchCompressorConfig,
diff --git a/crates/headroom-core/src/transforms/pipeline/config.rs b/crates/headroom-core/src/transforms/pipeline/config.rs
new file mode 100644
index 000000000..0591a1f45
--- /dev/null
+++ b/crates/headroom-core/src/transforms/pipeline/config.rs
@@ -0,0 +1,314 @@
+//! Pipeline configuration — TOML-backed defaults plus runtime overrides.
+//!
+//! # Why a config file
+//!
+//! The orchestrator and every offload bloat estimator carry tunable
+//! thresholds (savings ratios, sample sizes, weighting between bloat
+//! signals). Hardcoding them in Rust means a tuning change ships as a
+//! binary release. Putting them in TOML — embedded into the binary at
+//! build time, override-loadable at startup — gives ops a knob without
+//! losing the "stock binary works" property.
+//!
+//! Defaults live in `crates/headroom-core/config/pipeline.toml` and are
+//! pulled in via `include_str!`. `PipelineConfig::default()` deserializes
+//! that string; `PipelineConfig::from_toml_str` accepts an override TOML.
+//! All thresholds are intentionally conservative — Claude Code, Codex,
+//! and similar tool-driven agents sit on the hot path of every
+//! compressed response, and a wrongly-fired CCR offload costs both
+//! latency (retrieval round trip) and accuracy (LLM may not retrieve
+//! when it should).
+//!
+//! # Schema
+//!
+//! ```toml
+//! [pipeline]
+//! reformat_target_ratio = 0.5
+//! bloat_threshold = 0.5
+//! offload_fallback_ratio = 0.85
+//!
+//! [bloat.log]
+//! min_lines = 50
+//! sample_size = 100
+//! high_priority_threshold = 0.4
+//! uniqueness_weight = 0.5
+//! priority_dilution_weight = 0.5
+//!
+//! [bloat.diff]
+//! min_lines = 50
+//! normal_context_ratio = 0.6
+//!
+//! [bloat.search]
+//! min_matches = 10
+//! cluster_threshold = 10.0
+//! ```
+
+use serde::Deserialize;
+
+/// Embedded default configuration. Built into the binary so a stock
+/// install needs no external file.
+const DEFAULT_TOML: &str = include_str!("../../../config/pipeline.toml");
+
+/// Top-level config, deserialized from TOML.
+#[derive(Debug, Clone, Deserialize)]
+pub struct PipelineConfig {
+ pub pipeline: OrchestratorConfig,
+ pub bloat: BloatConfigs,
+ pub reformat: ReformatConfigs,
+ pub offload: OffloadConfigs,
+}
+
+impl PipelineConfig {
+ /// Load the embedded defaults. Panics only if the embedded TOML is
+ /// malformed — caught at build time by `from_default_str_does_not_panic`.
+ pub fn from_default_str() -> Self {
+ toml::from_str(DEFAULT_TOML)
+ .expect("embedded config/pipeline.toml must parse — checked by tests")
+ }
+
+ /// Parse a caller-supplied TOML string. Used by production deployments
+ /// that ship their own override file.
+ ///
+ /// Named `from_toml_str` rather than `from_str` to avoid colliding
+ /// with the [`std::str::FromStr`] trait method (and the corresponding
+ /// clippy lint), since this fallible parse doesn't need the `FromStr`
+ /// surface at any callsite today.
+ pub fn from_toml_str(s: &str) -> Result<Self, ConfigError> {
+ toml::from_str(s).map_err(ConfigError::from)
+ }
+
+ /// Read and parse a TOML file. Convenience wrapper.
+ pub fn from_file(path: impl AsRef<std::path::Path>) -> Result<Self, ConfigError> {
+ let text = std::fs::read_to_string(path).map_err(ConfigError::Io)?;
+ Self::from_toml_str(&text)
+ }
+}
+
+impl Default for PipelineConfig {
+ fn default() -> Self {
+ Self::from_default_str()
+ }
+}
+
+/// Orchestrator-level knobs.
+#[derive(Debug, Clone, Copy, Deserialize)]
+pub struct OrchestratorConfig {
+ /// After reformat, if `output_len / input_len <= this`, we treat
+ /// the reformat as sufficient and skip offloads UNLESS bloat
+ /// estimation demands them.
+ pub reformat_target_ratio: f64,
+ /// Bloat score above which the orchestrator runs offload regardless
+ /// of reformat outcome.
+ pub bloat_threshold: f32,
+ /// After reformat, if `output_len / input_len > this`, we run
+ /// offloads even when bloat is below threshold (the "reformat
+ /// barely helped" fallback path).
+ pub offload_fallback_ratio: f64,
+}
+
+/// Per-domain bloat-estimator knobs.
+#[derive(Debug, Clone, Copy, Deserialize)]
+pub struct BloatConfigs {
+ pub log: LogBloatConfig,
+ pub diff: DiffBloatConfig,
+ pub search: SearchBloatConfig,
+}
+
+/// Log-domain bloat estimator config.
+///
+/// The estimator combines two structural signals weighted to sum to ≤ 1.0:
+/// - **Repetition** (`uniqueness_weight`): `1 − unique_lines / sample_size`.
+/// Catches "log full of identical INFO heartbeats."
+/// - **Priority dilution** (`priority_dilution_weight`):
+/// `(low_priority_lines / sample_size)`, where low-priority is
+/// `priority ≤ high_priority_threshold`. Catches "log full of unique
+/// noise burying a few errors."
+#[derive(Debug, Clone, Copy, Deserialize)]
+pub struct LogBloatConfig {
+ pub min_lines: usize,
+ pub sample_size: usize,
+ pub high_priority_threshold: f32,
+ pub uniqueness_weight: f32,
+ pub priority_dilution_weight: f32,
+}
+
+/// Diff-domain bloat estimator config.
+///
+/// Bloat is high when context lines dominate change lines: a diff of
+/// 200 lines that only changes 3 of them is mostly noise the LLM
+/// doesn't need on the wire.
+#[derive(Debug, Clone, Copy, Deserialize)]
+pub struct DiffBloatConfig {
+ pub min_lines: usize,
+ /// Below this fraction of `context / (context + change)` the diff
+ /// is considered dense; above, it's mostly context (high bloat).
+ pub normal_context_ratio: f64,
+}
+
+/// Search-domain bloat estimator config.
+///
+/// Bloat is high when matches cluster heavily into a few files
+/// (`avg_matches_per_file` is large) — the LLM rarely needs all
+/// 50 hits in `utils.py` and one summary keeps the signal.
+#[derive(Debug, Clone, Copy, Deserialize)]
+pub struct SearchBloatConfig {
+ pub min_matches: usize,
+ pub cluster_threshold: f32,
+}
+
+/// Reformat-transform configs (one struct per reformat).
+#[derive(Debug, Clone, Deserialize)]
+pub struct ReformatConfigs {
+ pub log_template: LogTemplateConfig,
+}
+
+/// Knobs for the [`crate::transforms::pipeline::reformats::LogTemplate`]
+/// miner. See module docs for the algorithm; the relevant tunables are:
+///
+/// - `min_lines` — short logs aren't worth the bucket walk.
+/// - `min_run` — minimum consecutive same-template lines that justify
+/// collapsing into a template block.
+/// - `similarity_threshold` — fraction of positions that must match
+/// for two same-length lines to be considered the same template.
+/// - `min_constant_tokens` — a template with too few anchor tokens
+/// carries no readable signal; emit verbatim instead.
+#[derive(Debug, Clone, Copy, Deserialize)]
+pub struct LogTemplateConfig {
+ pub min_lines: usize,
+ pub min_run: usize,
+ pub similarity_threshold: f32,
+ pub min_constant_tokens: usize,
+}
+
+/// Offload-transform configs (one struct per offload that needs them).
+#[derive(Debug, Clone, Deserialize)]
+pub struct OffloadConfigs {
+ pub diff_noise: DiffNoiseConfig,
+}
+
+/// Knobs for the [`crate::transforms::pipeline::offloads::DiffNoise`]
+/// offload. Lockfile suffixes are matched against the new-file path
+/// at the end of each `diff --git` header.
+#[derive(Debug, Clone, Deserialize)]
+pub struct DiffNoiseConfig {
+ pub min_lines: usize,
+ pub lockfile_suffixes: Vec<String>,
+ pub drop_whitespace_only_hunks: bool,
+}
+
+#[derive(Debug, thiserror::Error)]
+pub enum ConfigError {
+ #[error("invalid pipeline config TOML: {0}")]
+ Parse(#[from] toml::de::Error),
+ #[error("could not read pipeline config file: {0}")]
+ Io(std::io::Error),
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn from_default_str_does_not_panic() {
+ // Embedded TOML must always deserialize cleanly.
+ let _ = PipelineConfig::from_default_str();
+ }
+
+ #[test]
+ fn defaults_match_documented_thresholds() {
+ let cfg = PipelineConfig::default();
+ assert_eq!(cfg.pipeline.reformat_target_ratio, 0.5);
+ assert_eq!(cfg.pipeline.bloat_threshold, 0.5);
+ assert_eq!(cfg.pipeline.offload_fallback_ratio, 0.85);
+ assert_eq!(cfg.bloat.log.min_lines, 50);
+ assert_eq!(cfg.bloat.log.sample_size, 100);
+ assert_eq!(cfg.bloat.diff.min_lines, 50);
+ assert_eq!(cfg.bloat.search.min_matches, 10);
+ }
+
+ #[test]
+ fn bloat_log_weights_sum_to_at_most_one() {
+ let cfg = PipelineConfig::default();
+ let total = cfg.bloat.log.uniqueness_weight + cfg.bloat.log.priority_dilution_weight;
+ assert!(
+ total <= 1.0001,
+ "log bloat weights must sum to ≤ 1.0, got {total}"
+ );
+ }
+
+ #[test]
+ fn from_toml_str_overrides_defaults() {
+ let toml = r#"
+ [pipeline]
+ reformat_target_ratio = 0.3
+ bloat_threshold = 0.7
+ offload_fallback_ratio = 0.9
+
+ [bloat.log]
+ min_lines = 25
+ sample_size = 50
+ high_priority_threshold = 0.6
+ uniqueness_weight = 0.4
+ priority_dilution_weight = 0.6
+
+ [bloat.diff]
+ min_lines = 30
+ normal_context_ratio = 0.7
+
+ [bloat.search]
+ min_matches = 5
+ cluster_threshold = 20.0
+
+ [reformat.log_template]
+ min_lines = 10
+ min_run = 5
+ similarity_threshold = 0.8
+ min_constant_tokens = 3
+
+ [offload.diff_noise]
+ min_lines = 20
+ lockfile_suffixes = ["custom.lock"]
+ drop_whitespace_only_hunks = false
+ "#;
+ let cfg = PipelineConfig::from_toml_str(toml).expect("override parses");
+ assert_eq!(cfg.pipeline.reformat_target_ratio, 0.3);
+ assert_eq!(cfg.bloat.log.min_lines, 25);
+ assert_eq!(cfg.bloat.search.cluster_threshold, 20.0);
+ assert_eq!(cfg.reformat.log_template.min_run, 5);
+ assert_eq!(
+ cfg.offload.diff_noise.lockfile_suffixes,
+ vec!["custom.lock"]
+ );
+ }
+
+ #[test]
+ fn defaults_carry_reformat_and_offload_sections() {
+ let cfg = PipelineConfig::default();
+ assert_eq!(cfg.reformat.log_template.min_lines, 20);
+ assert_eq!(cfg.reformat.log_template.min_run, 3);
+ assert!(!cfg.offload.diff_noise.lockfile_suffixes.is_empty());
+ assert!(cfg
+ .offload
+ .diff_noise
+ .lockfile_suffixes
+ .iter()
+ .any(|s| s == "Cargo.lock"));
+ }
+
+ #[test]
+ fn malformed_toml_returns_error() {
+ let r = PipelineConfig::from_toml_str("this is not toml = [unterminated");
+ assert!(r.is_err(), "malformed TOML should fail loudly");
+ }
+
+ #[test]
+ fn missing_section_returns_error() {
+ // Only `[pipeline]` — missing `[bloat.*]` sections.
+ let toml = r#"
+ [pipeline]
+ reformat_target_ratio = 0.5
+ bloat_threshold = 0.5
+ offload_fallback_ratio = 0.85
+ "#;
+ assert!(PipelineConfig::from_toml_str(toml).is_err());
+ }
+}
diff --git a/crates/headroom-core/src/transforms/pipeline/json_minifier.rs b/crates/headroom-core/src/transforms/pipeline/json_minifier.rs
deleted file mode 100644
index d7a27b60d..000000000
--- a/crates/headroom-core/src/transforms/pipeline/json_minifier.rs
+++ /dev/null
@@ -1,179 +0,0 @@
-//! `JsonMinifier` — round-trip whitespace removal for JSON content.
-//!
-//! Smallest useful lossless transform: parse with `serde_json`, write
-//! with `serde_json::to_string` (which omits all decorative
-//! whitespace). The bytes saved depends on how indented the source is
-//! — pretty-printed JSON typically shrinks by ~25–35%, already-
-//! compact JSON saves ~0%. The orchestrator's
-//! [`min_savings_ratio`] gate rejects no-savings runs automatically.
-//!
-//! [`min_savings_ratio`]: super::orchestrator::PipelineConfig::min_savings_ratio
-//!
-//! # Why not strip whitespace by hand
-//!
-//! Hand-rolled minification has to handle string literals, escape
-//! sequences, and Unicode separator characters correctly. `serde_json`
-//! already does that — and a parse-then-serialize roundtrip
-//! validates the input as a side effect, which means downstream
-//! consumers can trust the output is well-formed. The cost is one
-//! `Value` allocation per call, which is dwarfed by the I/O the proxy
-//! is already doing on the same payload.
-//!
-//! # No regex
-//!
-//! Pure `serde_json`. No regex, no hand-rolled scanner.
-
-use crate::transforms::pipeline::traits::{LosslessTransform, TransformError, TransformResult};
-use crate::transforms::ContentType;
-
-/// Minify any JSON document by parse-then-serialize round-trip.
-#[derive(Debug, Default, Clone, Copy)]
-pub struct JsonMinifier;
-
-impl JsonMinifier {
- pub const NAME: &'static str = "json_minifier";
-
- /// The content types this transform claims. Static slice — the
- /// applicability is fixed by the implementation, not configured
- /// per instance.
- const APPLIES_TO: &'static [ContentType] = &[ContentType::JsonArray];
-}
-
-impl LosslessTransform for JsonMinifier {
- fn name(&self) -> &'static str {
- Self::NAME
- }
-
- fn applies_to(&self) -> &[ContentType] {
- Self::APPLIES_TO
- }
-
- fn apply(&self, content: &str) -> Result<TransformResult, TransformError> {
- if content.is_empty() {
- return Err(TransformError::skipped(Self::NAME, "empty input"));
- }
- // `from_str` validates the input as a side effect of building
- // the in-memory tree. Any structural error becomes
- // InvalidInput so the orchestrator can move on.
- let value: serde_json::Value = serde_json::from_str(content).map_err(|e| {
- TransformError::invalid_input(Self::NAME, format!("not valid json: {e}"))
- })?;
- let minified = serde_json::to_string(&value)
- .map_err(|e| TransformError::internal(Self::NAME, format!("serialize failed: {e}")))?;
- Ok(TransformResult::from_lengths(content.len(), minified, true))
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- fn run(input: &str) -> Result<TransformResult, TransformError> {
- JsonMinifier.apply(input)
- }
-
- #[test]
- fn name_matches_telemetry_convention() {
- // Lowercase snake_case so the strategy-stats JSONB nest stays
- // clean.
- assert_eq!(JsonMinifier.name(), "json_minifier");
- }
-
- #[test]
- fn applies_to_json_array() {
- assert_eq!(JsonMinifier.applies_to(), &[ContentType::JsonArray]);
- }
-
- #[test]
- fn pretty_printed_json_shrinks() {
- let pretty = r#"{
- "name": "Alice",
- "age": 30,
- "tags": [
- "engineer",
- "manager"
- ]
-}"#;
- let result = run(pretty).expect("valid json should compress");
- assert!(result.bytes_saved > 0);
- assert!(result.structure_preserved);
- assert!(!result.output.contains('\n'));
- assert!(!result.output.contains(" "));
- // Round-trips back to the same logical value.
- let v_in: serde_json::Value = serde_json::from_str(pretty).unwrap();
- let v_out: serde_json::Value = serde_json::from_str(&result.output).unwrap();
- assert_eq!(v_in, v_out);
- }
-
- #[test]
- fn already_compact_json_returns_zero_savings() {
- let compact = r#"{"a":1,"b":[1,2,3]}"#;
- let result = run(compact).expect("compact json is still valid");
- // serde_json's canonical form may match the input byte-for-byte
- // here; the important contract is bytes_saved == 0 (orchestrator
- // will reject this in is_acceptable).
- assert_eq!(result.bytes_saved, 0);
- }
-
- #[test]
- fn empty_string_is_skipped_not_invalid() {
- let err = run("").expect_err("empty input is a skip, not an error");
- assert!(matches!(err, TransformError::Skipped { .. }));
- }
-
- #[test]
- fn malformed_json_is_invalid_input() {
- let err = run("{not json").expect_err("garbage is invalid input");
- assert!(matches!(err, TransformError::InvalidInput { .. }));
- }
-
- #[test]
- fn nested_arrays_round_trip() {
- let nested = r#"{
- "users": [
- {"id": 1, "name": "a"},
- {"id": 2, "name": "b"}
- ]
-}"#;
- let result = run(nested).unwrap();
- let parsed: serde_json::Value = serde_json::from_str(&result.output).unwrap();
- assert_eq!(parsed["users"][0]["id"], 1);
- assert_eq!(parsed["users"][1]["name"], "b");
- assert!(result.bytes_saved > 0);
- }
-
- #[test]
- fn unicode_strings_preserved() {
- let input = r#"{ "greeting": "héllo wörld 🌍" }"#;
- let result = run(input).unwrap();
- let parsed: serde_json::Value = serde_json::from_str(&result.output).unwrap();
- assert_eq!(parsed["greeting"], "héllo wörld 🌍");
- }
-
- #[test]
- fn structure_preserved_flag_is_always_true() {
- // Lossless by construction.
- let result = run(r#"{"a": 1}"#).unwrap();
- assert!(result.structure_preserved);
- assert!(result.reversible_via.is_none());
- }
-
- #[test]
- fn deeply_nested_does_not_blow_up() {
- // 50 levels of nesting — well under any reasonable parse limit
- // but enough to catch a recursion bug if we ever introduce one.
- let mut s = String::new();
- for _ in 0..50 {
- s.push('[');
- }
- s.push('1');
- for _ in 0..50 {
- s.push(']');
- }
- let result = run(&s).unwrap();
- // Parsing+serializing a deeply nested array doesn't add or
- // remove much — important is that we don't panic or fail.
- let parsed: serde_json::Value = serde_json::from_str(&result.output).unwrap();
- assert!(parsed.is_array());
- }
-}
diff --git a/crates/headroom-core/src/transforms/pipeline/line_importance_filter.rs b/crates/headroom-core/src/transforms/pipeline/line_importance_filter.rs
deleted file mode 100644
index 6c9caa3d6..000000000
--- a/crates/headroom-core/src/transforms/pipeline/line_importance_filter.rs
+++ /dev/null
@@ -1,359 +0,0 @@
-//! `LineImportanceFilter` — drop low-priority lines using the signals
-//! trait from Phase 3e.1.
-//!
-//! Smallest useful lossy transform: walk lines, score each via a
-//! [`LineImportanceDetector`] (the trait shipped in Phase 3e.1), keep
-//! lines whose `priority` is at or above a threshold, plus unconditional
-//! anchors at the head and tail. Gaps between kept lines collapse into
-//! `[... N lines omitted ...]` markers so the downstream LLM has a
-//! visible signal that bytes were dropped.
-//!
-//! # Why this is lossy
-//!
-//! Dropped lines are gone — the filter does not emit a CCR retrieval
-//! handle in PR1 (CCR offload moves into the pipeline in PR3). The
-//! omission markers carry coarse "something was here" signal but not
-//! the original bytes. Hence `structure_preserved = false` and
-//! `confidence = 0.7` (calibrated from the detector's own confidence
-//! aggregate; tuned later in PR4 once we have a labeled corpus).
-//!
-//! # No regex
-//!
-//! Walks `str::lines()`. The detector itself is aho-corasick + ASCII
-//! word-boundary post-filter, also no regex.
-
-use crate::signals::{ImportanceContext, LineImportanceDetector};
-use crate::transforms::pipeline::traits::{
- CompressionContext, LossyTransform, TransformError, TransformResult,
-};
-use crate::transforms::ContentType;
-
-/// Configuration knobs for [`LineImportanceFilter`].
-#[derive(Debug, Clone)]
-pub struct LineImportanceFilterConfig {
- /// Minimum priority for a line to survive the filter. Lines with
- /// `priority < min_priority` get dropped (unless they're inside
- /// the head/tail anchor windows). Default `0.4` — picked to keep
- /// warning/importance lines (priority 0.5) and drop neutral lines
- /// (priority 0.0) without aggressively trimming borderline cases.
- pub min_priority: f32,
- /// Always keep the first N lines. Header context, banner, summary
- /// — losing these breaks the LLM's ability to interpret what
- /// follows.
- pub keep_first: usize,
- /// Always keep the last N lines. Trailing summaries, exit codes,
- /// totals — same logic as the head anchor.
- pub keep_last: usize,
- /// Importance context to pass to the detector. Different contexts
- /// fire different keyword sets (markdown structure matters in
- /// `Text`, doesn't in `Diff`).
- pub context: ImportanceContext,
-}
-
-impl Default for LineImportanceFilterConfig {
- fn default() -> Self {
- Self {
- min_priority: 0.4,
- keep_first: 5,
- keep_last: 5,
- context: ImportanceContext::Text,
- }
- }
-}
-
-/// Drop low-priority lines, keep anchors at head/tail.
-pub struct LineImportanceFilter {
- detector: Box<dyn LineImportanceDetector>,
- applies_to: Vec<ContentType>,
- config: LineImportanceFilterConfig,
-}
-
-impl LineImportanceFilter {
- pub const NAME: &'static str = "line_importance_filter";
-
- /// Build a filter with the given detector and the default config.
- /// `applies_to` defaults to the broad set of line-based content
- /// types — caller can narrow via [`with_applies_to`].
- ///
- /// [`with_applies_to`]: Self::with_applies_to
- pub fn new(detector: Box<dyn LineImportanceDetector>) -> Self {
- Self {
- detector,
- applies_to: vec![
- ContentType::PlainText,
- ContentType::BuildOutput,
- ContentType::SearchResults,
- ],
- config: LineImportanceFilterConfig::default(),
- }
- }
-
- pub fn with_config(mut self, config: LineImportanceFilterConfig) -> Self {
- self.config = config;
- self
- }
-
- pub fn with_applies_to(mut self, types: Vec<ContentType>) -> Self {
- self.applies_to = types;
- self
- }
-}
-
-impl LossyTransform for LineImportanceFilter {
- fn name(&self) -> &'static str {
- Self::NAME
- }
-
- fn applies_to(&self) -> &[ContentType] {
- &self.applies_to
- }
-
- fn apply(
- &self,
- content: &str,
- _ctx: &CompressionContext,
- ) -> Result<TransformResult, TransformError> {
- if content.is_empty() {
- return Err(TransformError::skipped(Self::NAME, "empty input"));
- }
-
- // `str::lines` iterates without retaining line terminators; we
- // collect once because the keep-decision per line depends on
- // the total count (head/tail anchors).
- let lines: Vec<&str> = content.lines().collect();
- let n = lines.len();
- if n == 0 {
- return Err(TransformError::skipped(Self::NAME, "no lines"));
- }
-
- // Score each line and decide keep-or-drop.
- let mut keep = vec![false; n];
- let head_end = self.config.keep_first.min(n);
- let tail_start = n.saturating_sub(self.config.keep_last);
- for (i, line) in lines.iter().enumerate() {
- if i < head_end || i >= tail_start {
- keep[i] = true;
- continue;
- }
- let signal = self.detector.score(line, self.config.context);
- if signal.priority >= self.config.min_priority {
- keep[i] = true;
- }
- }
-
- // Build output, collapsing dropped runs into omission markers.
- let mut out = String::with_capacity(content.len());
- let mut last_kept: Option<usize> = None;
- for (i, line) in lines.iter().enumerate() {
- if !keep[i] {
- continue;
- }
- if let Some(prev) = last_kept {
- let gap = i - prev - 1;
- if gap > 0 {
- if !out.is_empty() {
- out.push('\n');
- }
- out.push_str(&format!("[... {gap} lines omitted ...]"));
- }
- }
- if !out.is_empty() {
- out.push('\n');
- }
- out.push_str(line);
- last_kept = Some(i);
- }
- if let Some(prev) = last_kept {
- let gap = n - prev - 1;
- if gap > 0 {
- out.push('\n');
- out.push_str(&format!("[... {gap} lines omitted ...]"));
- }
- }
-
- // Bytes-saved is computed against the original content, not
- // the line-iterated reconstruction (which can differ by the
- // trailing newline). We account for that by using the
- // input length directly.
- let bytes_saved = content.len().saturating_sub(out.len());
- Ok(TransformResult {
- output: out,
- bytes_saved,
- structure_preserved: false,
- reversible_via: None,
- })
- }
-
- fn confidence(&self) -> f32 {
- // Calibrated 0.7: the detector is reliable on keyword signals
- // (priority 0.5+) but has no view into semantic relevance to
- // the user's query — that's what PR4 ProseFieldCompressor
- // adds. 0.7 is "decent extractive baseline."
- 0.7
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use crate::signals::{ImportanceCategory, ImportanceSignal};
-
- /// Test detector with deterministic priorities — keyed on a
- /// substring match. Avoids spinning up the real keyword detector
- /// for unit tests.
- struct StubDetector {
- priority_keyword: &'static str,
- priority: f32,
- }
- impl LineImportanceDetector for StubDetector {
- fn score(&self, line: &str, _ctx: ImportanceContext) -> ImportanceSignal {
- if line.contains(self.priority_keyword) {
- ImportanceSignal::matched(ImportanceCategory::Importance, self.priority, 0.9)
- } else {
- ImportanceSignal::neutral()
- }
- }
- }
-
- fn run(filter: &LineImportanceFilter, content: &str) -> TransformResult {
- filter
- .apply(content, &CompressionContext::default())
- .expect("test inputs are well-formed")
- }
-
- fn filter_keep_keyword() -> LineImportanceFilter {
- LineImportanceFilter::new(Box::new(StubDetector {
- priority_keyword: "KEEP",
- priority: 0.9,
- }))
- .with_config(LineImportanceFilterConfig {
- min_priority: 0.5,
- keep_first: 1,
- keep_last: 1,
- context: ImportanceContext::Text,
- })
- }
-
- #[test]
- fn name_matches_telemetry_convention() {
- let f = filter_keep_keyword();
- assert_eq!(f.name(), "line_importance_filter");
- }
-
- #[test]
- fn applies_to_default_set_includes_plain_text_logs_and_search() {
- let f = filter_keep_keyword();
- let types = f.applies_to();
- assert!(types.contains(&ContentType::PlainText));
- assert!(types.contains(&ContentType::BuildOutput));
- assert!(types.contains(&ContentType::SearchResults));
- }
-
- #[test]
- fn drops_low_priority_lines_keeps_high_priority() {
- let f = filter_keep_keyword();
- let input = (0..20)
- .map(|i| {
- if i == 10 {
- "KEEP this line".into()
- } else {
- format!("noise {i}")
- }
- })
- .collect::<Vec<_>>()
- .join("\n");
- let result = run(&f, &input);
- assert!(result.output.contains("KEEP this line"));
- assert!(result.output.contains("[... ") && result.output.contains("lines omitted ...]"));
- assert!(result.bytes_saved > 0);
- assert!(!result.structure_preserved);
- }
-
- #[test]
- fn always_keeps_first_and_last_anchor_windows() {
- let f = filter_keep_keyword();
- let lines: Vec<String> = (0..20).map(|i| format!("plain line {i}")).collect();
- let input = lines.join("\n");
- let result = run(&f, &input);
- // First line and last line must survive even when nothing
- // matches the keyword.
- assert!(result.output.contains("plain line 0"));
- assert!(result.output.contains("plain line 19"));
- }
-
- #[test]
- fn empty_input_returns_skipped_error() {
- let f = filter_keep_keyword();
- let err = f
- .apply("", &CompressionContext::default())
- .expect_err("empty input is a skip");
- assert!(matches!(err, TransformError::Skipped { .. }));
- }
-
- #[test]
- fn single_line_input_passes_through() {
- let f = filter_keep_keyword();
- let result = run(&f, "only one line");
- // Head anchor keeps it; no gap markers possible.
- assert_eq!(result.output, "only one line");
- assert_eq!(result.bytes_saved, 0);
- }
-
- #[test]
- fn omission_markers_count_dropped_lines_correctly() {
- // 5 lines: keep 1st (head anchor), drop middle 3 (no keyword),
- // keep last (tail anchor). Expect ONE marker reporting 3
- // omitted lines.
- let f = filter_keep_keyword();
- let input = ["first", "drop a", "drop b", "drop c", "last"].join("\n");
- let result = run(&f, &input);
- assert!(result.output.starts_with("first"));
- assert!(result.output.ends_with("last"));
- assert!(result.output.contains("[... 3 lines omitted ...]"));
- }
-
- #[test]
- fn confidence_is_calibrated_constant_in_pr1() {
- let f = filter_keep_keyword();
- assert!((f.confidence() - 0.7).abs() < f32::EPSILON);
- }
-
- #[test]
- fn structure_preserved_flag_is_always_false() {
- let f = filter_keep_keyword();
- let result = run(&f, "first\nKEEP me\nlast");
- assert!(!result.structure_preserved);
- }
-
- #[test]
- fn anchor_windows_overlap_safely_on_short_input() {
- // 3 lines, keep_first=5, keep_last=5 — windows fully overlap,
- // every line should survive without panicking on the index
- // arithmetic.
- let f = LineImportanceFilter::new(Box::new(StubDetector {
- priority_keyword: "_",
- priority: 0.9,
- }))
- .with_config(LineImportanceFilterConfig {
- min_priority: 0.5,
- keep_first: 5,
- keep_last: 5,
- context: ImportanceContext::Text,
- });
- let result = run(&f, "a\nb\nc");
- assert_eq!(result.output, "a\nb\nc");
- }
-
- #[test]
- fn applies_to_can_be_narrowed() {
- let f = filter_keep_keyword().with_applies_to(vec![ContentType::SearchResults]);
- assert_eq!(f.applies_to(), &[ContentType::SearchResults]);
- }
-
- #[test]
- fn unicode_lines_handled_safely() {
- let f = filter_keep_keyword();
- let result = run(&f, "first\nKEEP héllo wörld 🌍\nlast");
- assert!(result.output.contains("héllo wörld 🌍"));
- }
-}
diff --git a/crates/headroom-core/src/transforms/pipeline/mod.rs b/crates/headroom-core/src/transforms/pipeline/mod.rs
index eae75b220..f29c5ee99 100644
--- a/crates/headroom-core/src/transforms/pipeline/mod.rs
+++ b/crates/headroom-core/src/transforms/pipeline/mod.rs
@@ -1,66 +1,101 @@
-//! Compression pipeline — formal orchestrator for lossless → lossy → CCR.
+//! Compression pipeline — formal orchestrator for reformat + bloat-gated CCR offload.
//!
-//! # Why this module exists
+//! # The architecture in one paragraph
//!
-//! Before Phase 3g each compressor (SmartCrusher, DiffCompressor,
-//! LogCompressor, SearchCompressor, TagProtector) carried its own
-//! ad-hoc decision tree: parse, score, drop, optionally emit a CCR
-//! marker. SmartCrusher's 3c.2 refactor made the decision explicit
-//! inside that one transform; the rest still decide privately. That
-//! makes the system hard to reason about (which transforms ran in
-//! what order, how much each saved, why CCR fired or didn't) and
-//! impossible to extend without copying the same scaffolding.
+//! With CCR (Compress-Cache-Retrieve), no transform here destroys
+//! information. Bytes drop from the wire, but the original payload is
+//! stashed in a [`crate::ccr::CcrStore`] keyed by a hash. The LLM
+//! retrieves any dropped piece via a tool call. So we don't have
+//! "lossless" vs "lossy" — we have two distinct *mechanisms*:
//!
-//! This module replaces that scaffolding with two traits and an
-//! orchestrator:
+//! * [`ReformatTransform`] — pack denser without dropping anything.
+//! Output bytes are semantically equivalent to input bytes
+//! (`JsonMinifier` removes whitespace; future entries: log RLE,
+//! schema extraction, comment stripping).
+//! * [`OffloadTransform`] — drop bytes from the wire, stash the
+//! original via CCR, emit a retrieval marker. Required to expose a
+//! cheap, **domain-specific** [`estimate_bloat`] method so the
+//! orchestrator can decide whether the offload is worth the
+//! retrieval round trip.
//!
-//! * [`LosslessTransform`] — preserves all information; can run
-//! first and stop early if structural compression suffices.
-//! * [`LossyTransform`] — drops bytes deliberately. Runs only after
-//! the lossless pass. Reports a calibrated `confidence` so callers
-//! and telemetry can tell which transforms were trusted vs taken
-//! on faith.
-//! * [`CompressionPipeline`] — content-type-keyed dispatch over the
-//! two transform sets, with budget gates between phases.
+//! [`CompressionPipeline`] dispatches both kinds by content type. It
+//! runs the reformat phase serially while running per-offload bloat
+//! estimators in parallel via `rayon::join` — so large inputs don't
+//! pay a sequential cost for the gating decision.
//!
-//! # The pipeline contract
+//! # Why parallel + domain-specific bloat
//!
-//! ```text
-//! input → DetectContentType (Magika, already shipped)
-//! → LosslessTransforms[content_type] stop if structural compression suffices
-//! → BudgetCheck
-//! → LossyTransforms[content_type] includes ProseFieldCompressor (Phase 3g PR4)
-//! → BudgetCheck
-//! → CCR for everything beyond budget (Phase 3g PR3+)
-//! ```
+//! Different content shapes have different "is this bloaty?" signals.
+//! A generic byte-redundancy heuristic (zlib over a sample) misses
+//! domain semantics: a log full of unique-but-irrelevant lines doesn't
+//! compress with zlib but should still trigger CCR. Each
+//! [`OffloadTransform`] carries its own structural estimator —
+//! [`crate::transforms::pipeline::offloads::LogOffload`] looks at line
+//! repetition + priority dilution; `DiffOffload` looks at the
+//! context-to-change ratio; `SearchOffload` looks at how matches
+//! cluster across files.
//!
-//! PR1 ships traits + orchestrator + one real impl per trait
-//! ([`JsonMinifier`] for lossless, [`LineImportanceFilter`] for lossy).
-//! PR2 wraps existing structural transforms (Diff/Log/Search/Tag) in
-//! the trait shape. PR3 refactors SmartCrusher to use the orchestrator
-//! and starts retiring Python orchestration glue. PR4 adds
-//! ProseFieldCompressor (the parser/model boundary primitive). PR5
-//! migrates the remaining compressors and lets us delete the Python
-//! `ContentRouter` strategy dispatch.
+//! Estimators MUST be cheap (under O(n) on input length, no
+//! allocations beyond the structural read). They run in parallel with
+//! the reformat phase via `rayon::par_iter` — so a 100-offload pipeline
+//! over a 1MB log doesn't pay 100× the scan cost.
//!
//! # No regex
//!
-//! By project convention (and feedback memory), nothing in this module
-//! uses the `regex` crate. JsonMinifier is `serde_json` round-trip;
-//! LineImportanceFilter walks `str::lines()` and consumes the existing
-//! `signals::LineImportanceDetector` trait (which uses aho-corasick
-//! plus an ASCII word-boundary post-filter, also no regex).
+//! Per project convention. JsonMinifier is `serde_json` round-trip;
+//! offload bloat estimators are byte-prefix checks and
+//! `signals::LineImportanceDetector` lookups (which use aho-corasick +
+//! ASCII word boundary).
+//!
+//! # Coverage today vs deferred
+//!
+//! Reformats:
+//! - [`reformats::JsonMinifier`] — JSON whitespace stripping.
+//! - [`reformats::LogTemplate`] — Drain-style template miner for
+//! build/log output. Lossless — emits `[Template Tn: ...] (Nx)` +
+//! variant table, every original line reconstructible.
+//!
+//! Offloads:
+//! - [`offloads::LogOffload`] — wraps the existing `LogCompressor`,
+//! gates on per-line bloat heuristic.
+//! - [`offloads::DiffOffload`] — wraps the existing `DiffCompressor`,
+//! gates on context-to-change ratio. Stores under the cache_key the
+//! wrapped compressor mints (closes a leak in the parity-bound port).
+//! - [`offloads::DiffNoise`] — drops lockfile + whitespace-only hunks
+//! via CCR. Runs alongside `DiffOffload`; both are useful for
+//! different shapes of diff bloat.
+//! - `SearchOffload` exists at `offloads::search_offload::SearchOffload`
+//! but is NOT in the default re-exports — modern agents use scoped
+//! `rg`/`grep`, the marginal value didn't justify default registration.
+//!
+//! Deferred to later PRs:
+//! - **JSON Offload** — already lives at
+//! `crate::transforms::smart_crusher::SmartCrusher`. Phase 3g PR3
+//! refactors it to implement the [`OffloadTransform`] contract so
+//! the orchestrator dispatches JSON arrays through it.
+//! - **ProseFieldCompressor** — Phase 3g PR4. Compresses prose-shaped
+//! string fields inside structured payloads.
+//!
+//! [`estimate_bloat`]: traits::OffloadTransform::estimate_bloat
-pub mod json_minifier;
-pub mod line_importance_filter;
+pub mod config;
+pub mod offloads;
pub mod orchestrator;
+pub mod reformats;
pub mod traits;
-pub use json_minifier::JsonMinifier;
-pub use line_importance_filter::{LineImportanceFilter, LineImportanceFilterConfig};
-pub use orchestrator::{
- CompressionPipeline, CompressionPipelineBuilder, PipelineConfig, PipelineResult,
+pub use config::{
+ BloatConfigs, ConfigError, DiffBloatConfig, DiffNoiseConfig, LogBloatConfig, LogTemplateConfig,
+ OffloadConfigs, OrchestratorConfig, PipelineConfig, ReformatConfigs, SearchBloatConfig,
};
+// `SearchOffload` is intentionally NOT in the top-level re-export
+// (deprecated from default pipeline; reach via the explicit module
+// path if you want to opt in). See `offloads::search_offload` head
+// docs for rationale.
+pub use offloads::{DiffNoise, DiffOffload, LogOffload};
+pub use orchestrator::{CompressionPipeline, CompressionPipelineBuilder, PipelineResult};
+pub use reformats::{JsonMinifier, LogTemplate};
pub use traits::{
- CompressionContext, LosslessTransform, LossyTransform, TransformError, TransformResult,
+ CompressionContext, OffloadOutput, OffloadTransform, ReformatOutput, ReformatTransform,
+ TransformError,
};
diff --git a/crates/headroom-core/src/transforms/pipeline/offloads/diff_noise.rs b/crates/headroom-core/src/transforms/pipeline/offloads/diff_noise.rs
new file mode 100644
index 000000000..b3ccad1d5
--- /dev/null
+++ b/crates/headroom-core/src/transforms/pipeline/offloads/diff_noise.rs
@@ -0,0 +1,524 @@
+//! `DiffNoise` — drop hunks the LLM doesn't need (lockfiles + whitespace-only).
+//!
+//! # What this offload removes
+//!
+//! Real-world `git diff` output is dominated by two categories of bytes
+//! the LLM rarely needs:
+//!
+//! 1. **Lockfile churn.** A `npm install foo` commit re-shuffles
+//! thousands of lines in `package-lock.json` while changing one line
+//! in `package.json`. The LLM only needs to know "we bumped a
+//! dependency" — the manifest line carries that, the lockfile is
+//! noise. Same for `Cargo.lock`, `yarn.lock`, `poetry.lock`,
+//! `go.sum`, etc.
+//! 2. **Whitespace-only changes.** Reformat / lint-fix commits churn
+//! huge amounts of bytes without changing semantics. Detected by
+//! pairing `-` lines against `+` lines: if every pair, when
+//! whitespace-collapsed, is equal, the hunk is whitespace-only.
+//!
+//! Both categories are **dropped from the wire and stashed via CCR** so
+//! the LLM can retrieve the original on demand. Strict accuracy: bytes
+//! removed are recoverable through the cache key.
+//!
+//! # Why this is an Offload (not a Reformat)
+//!
+//! The dropped bytes are *gone* from the wire output. Even though they
+//! carry near-zero semantic value for typical LLM tasks, calling that
+//! "lossless" would misrepresent the contract. CCR is exactly the
+//! mechanism for "drop bytes, keep retrievable" — that's an Offload.
+//!
+//! # Bloat heuristic
+//!
+//! Score = fraction of input bytes that fall inside a droppable
+//! section. Computed cheaply over a single pass:
+//!
+//! - For each file header, if filename matches a configured lockfile
+//! suffix, count its hunk bytes as droppable.
+//! - For each non-lockfile hunk, if `drop_whitespace_only_hunks` is on
+//! AND the hunk is whitespace-only, count its bytes as droppable.
+//!
+//! The orchestrator gates `apply` on this score clearing the
+//! configurable threshold.
+//!
+//! # No regex
+//!
+//! Lockfile matching is suffix comparison via `str::ends_with` against
+//! the post-`b/` path of the `diff --git` header. Hunk parsing is
+//! prefix matching on `@@`, `diff --git`, `+++`, `---`. Whitespace
+//! comparison strips ASCII whitespace by hand.
+
+use crate::ccr::CcrStore;
+use crate::transforms::pipeline::config::DiffNoiseConfig;
+use crate::transforms::pipeline::traits::{
+ CompressionContext, OffloadOutput, OffloadTransform, TransformError,
+};
+use crate::transforms::ContentType;
+
+use md5::{Digest, Md5};
+
+const NAME: &str = "diff_noise";
+const CONFIDENCE: f32 = 0.9;
+
+pub struct DiffNoise {
+ config: DiffNoiseConfig,
+}
+
+impl DiffNoise {
+ pub fn new(config: DiffNoiseConfig) -> Self {
+ Self { config }
+ }
+}
+
+impl OffloadTransform for DiffNoise {
+ fn name(&self) -> &'static str {
+ NAME
+ }
+
+ fn applies_to(&self) -> &[ContentType] {
+ &[ContentType::GitDiff]
+ }
+
+ fn estimate_bloat(&self, content: &str) -> f32 {
+ if content.is_empty() {
+ return 0.0;
+ }
+ let total_lines = content.lines().count();
+ if total_lines < self.config.min_lines {
+ return 0.0;
+ }
+ let segments = parse_segments(content);
+ if segments.is_empty() {
+ return 0.0;
+ }
+
+ let mut droppable_bytes = 0usize;
+ let mut total_bytes = 0usize;
+ for seg in &segments {
+ let body_bytes: usize = seg
+ .body_lines
+ .iter()
+ .map(|l| l.len() + 1 /* the '\n' */)
+ .sum();
+ total_bytes += body_bytes;
+ let droppable = self.is_lockfile(&seg.new_path)
+ || (self.config.drop_whitespace_only_hunks && seg.body_is_whitespace_only());
+ if droppable {
+ droppable_bytes += body_bytes;
+ }
+ }
+ if total_bytes == 0 {
+ return 0.0;
+ }
+ (droppable_bytes as f32 / total_bytes as f32).clamp(0.0, 1.0)
+ }
+
+ fn apply(
+ &self,
+ content: &str,
+ _ctx: &CompressionContext,
+ store: &dyn CcrStore,
+ ) -> Result<OffloadOutput, TransformError> {
+ let segments = parse_segments(content);
+ if segments.is_empty() {
+ return Err(TransformError::skipped(NAME, "no diff sections"));
+ }
+
+ let mut output = String::with_capacity(content.len());
+ let mut dropped_any = false;
+ for seg in &segments {
+ // Always emit the segment's pre-body lines verbatim
+ // (`diff --git`, `index`, `+++`, `---`, mode lines, etc.)
+ // so the LLM sees that the file changed.
+ for h in &seg.header_lines {
+ output.push_str(h);
+ output.push('\n');
+ }
+ let drop_lockfile = self.is_lockfile(&seg.new_path);
+ let drop_whitespace =
+ self.config.drop_whitespace_only_hunks && seg.body_is_whitespace_only();
+ if drop_lockfile || drop_whitespace {
+ let reason = if drop_lockfile {
+ "lockfile"
+ } else {
+ "whitespace-only"
+ };
+ output.push_str("[diff_noise: ");
+ output.push_str(reason);
+ output.push_str(" hunks dropped (");
+ let body_lines = seg.body_lines.len();
+ output.push_str(&body_lines.to_string());
+ output.push_str(" lines)]\n");
+ dropped_any = true;
+ } else {
+ for b in &seg.body_lines {
+ output.push_str(b);
+ output.push('\n');
+ }
+ }
+ }
+
+ // Pre-diff content (anything before the first `diff --git`)
+ // gets prepended verbatim. parse_segments doesn't claim those
+ // lines so we splice them in by walking the input again.
+ let pre_diff = leading_pre_diff_lines(content);
+ if !pre_diff.is_empty() {
+ let mut prefixed = String::with_capacity(pre_diff.len() + output.len());
+ prefixed.push_str(&pre_diff);
+ prefixed.push_str(&output);
+ output = prefixed;
+ }
+
+ if !dropped_any || output.len() >= content.len() {
+ return Err(TransformError::skipped(NAME, "no droppable hunks"));
+ }
+
+ // CCR: hash original, stash, append marker.
+ let key = md5_hex_24(content);
+ store.put(&key, content);
+ output.push_str(&format!("\n[diff_noise CCR: hash={key}]"));
+
+ Ok(OffloadOutput::from_lengths(content.len(), output, key))
+ }
+
+ fn confidence(&self) -> f32 {
+ CONFIDENCE
+ }
+}
+
+impl DiffNoise {
+ fn is_lockfile(&self, path: &str) -> bool {
+ if path.is_empty() {
+ return false;
+ }
+ for suffix in &self.config.lockfile_suffixes {
+ // Match if the path ENDS WITH this suffix at a path-segment
+ // boundary (so `Cargo.lock` matches `crates/foo/Cargo.lock`
+ // but not `MyCargo.lock` — defensive against accidentally
+ // dropping a user-named file).
+ if path.ends_with(suffix.as_str()) {
+ let prefix_len = path.len() - suffix.len();
+ if prefix_len == 0 {
+ return true;
+ }
+ let prev_byte = path.as_bytes()[prefix_len - 1];
+ if prev_byte == b'/' || prev_byte == b'\\' {
+ return true;
+ }
+ }
+ }
+ false
+ }
+}
+
+/// One file's segment of a diff: the pre-body header lines (`diff
+/// --git`, `index ...`, `+++/---`) and the body (every line until the
+/// next `diff --git` or EOF), plus the parsed-out new file path.
+struct Segment<'a> {
+ new_path: String,
+ header_lines: Vec<&'a str>,
+ body_lines: Vec<&'a str>,
+}
+
+impl<'a> Segment<'a> {
+ /// True if every `+` and `-` line in the body, when ASCII-whitespace-
+ /// stripped and paired up in order, leaves equal token sequences.
+ /// Approach: collect the pluses and the minuses, strip-and-compare.
+ /// Order-aware so that `swapping two lines` doesn't accidentally
+ /// pass.
+ fn body_is_whitespace_only(&self) -> bool {
+ let mut adds: Vec<String> = Vec::new();
+ let mut subs: Vec<String> = Vec::new();
+ let mut saw_change = false;
+ for line in &self.body_lines {
+ let bytes = line.as_bytes();
+ match bytes.first() {
+ Some(b'+') if !line.starts_with("+++") => {
+ saw_change = true;
+ adds.push(strip_ws(&line[1..]));
+ }
+ Some(b'-') if !line.starts_with("---") => {
+ saw_change = true;
+ subs.push(strip_ws(&line[1..]));
+ }
+ _ => {}
+ }
+ }
+ if !saw_change {
+ return false;
+ }
+ adds == subs
+ }
+}
+
+fn strip_ws(s: &str) -> String {
+ s.chars().filter(|c| !c.is_ascii_whitespace()).collect()
+}
+
+/// Walk the input and emit one [`Segment`] per `diff --git` header.
+/// Lines before the first header are NOT included (caller picks them
+/// up via [`leading_pre_diff_lines`]).
+fn parse_segments(content: &str) -> Vec<Segment<'_>> {
+ let mut segments: Vec<Segment<'_>> = Vec::new();
+ let mut current: Option<Segment<'_>> = None;
+ let mut in_body = false;
+
+ for line in content.lines() {
+ if line.starts_with("diff --git") {
+ if let Some(s) = current.take() {
+ segments.push(s);
+ }
+ current = Some(Segment {
+ new_path: parse_new_path(line),
+ header_lines: vec![line],
+ body_lines: Vec::new(),
+ });
+ in_body = false;
+ continue;
+ }
+ let Some(seg) = current.as_mut() else {
+ continue; // pre-diff prelude — handled separately
+ };
+ if !in_body {
+ // Treat everything until the first `@@` as header.
+ if line.starts_with("@@") {
+ in_body = true;
+ seg.body_lines.push(line);
+ continue;
+ }
+ seg.header_lines.push(line);
+ } else {
+ seg.body_lines.push(line);
+ }
+ }
+ if let Some(s) = current.take() {
+ segments.push(s);
+ }
+ segments
+}
+
+/// Lines from the start of `content` up to (but not including) the
+/// first `diff --git`. Returned as one string with original newlines
+/// re-attached, ready to be prepended to the rebuilt diff output.
+fn leading_pre_diff_lines(content: &str) -> String {
+ let mut out = String::new();
+ for line in content.lines() {
+ if line.starts_with("diff --git") {
+ break;
+ }
+ out.push_str(line);
+ out.push('\n');
+ }
+ out
+}
+
+/// Parse the new-file path from a `diff --git a/X b/Y` header. Returns
+/// the `Y` segment (after the last ` b/`); empty string if not found.
+fn parse_new_path(header: &str) -> String {
+ if let Some(idx) = header.rfind(" b/") {
+ return header[idx + 3..].to_string();
+ }
+ String::new()
+}
+
+/// MD5 of `content`, hex-encoded, truncated to 24 chars (matches the
+/// CCR convention used by other compressors).
+fn md5_hex_24(content: &str) -> String {
+ let mut h = Md5::new();
+ h.update(content.as_bytes());
+ let digest = h.finalize();
+ let mut hex = String::with_capacity(32);
+ for b in digest.iter() {
+ hex.push_str(&format!("{:02x}", b));
+ }
+ hex.truncate(24);
+ hex
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::ccr::InMemoryCcrStore;
+ use crate::transforms::pipeline::config::PipelineConfig;
+
+ fn cfg() -> DiffNoiseConfig {
+ PipelineConfig::default().offload.diff_noise
+ }
+
+ fn offload() -> DiffNoise {
+ DiffNoise::new(cfg())
+ }
+
+ fn build_diff(files: &[(&str, &[&str])]) -> String {
+ let mut s = String::new();
+ for (path, body) in files {
+ s.push_str(&format!("diff --git a/{path} b/{path}\n"));
+ s.push_str(&format!("--- a/{path}\n+++ b/{path}\n"));
+ s.push_str("@@ -1 +1 @@\n");
+ for b in *body {
+ s.push_str(b);
+ s.push('\n');
+ }
+ }
+ s
+ }
+
+ #[test]
+ fn name_and_applies_to() {
+ let o = offload();
+ assert_eq!(o.name(), "diff_noise");
+ assert_eq!(o.applies_to(), &[ContentType::GitDiff]);
+ }
+
+ #[test]
+ fn estimate_bloat_below_min_lines_zero() {
+ // Only ~6 lines.
+ let diff = build_diff(&[("Cargo.lock", &["-old", "+new"])]);
+ assert_eq!(offload().estimate_bloat(&diff), 0.0);
+ }
+
+ #[test]
+ fn estimate_bloat_lockfile_dominates_scores_high() {
+ // Tiny manifest change + huge lockfile churn.
+ let big_lock_body: Vec<String> = (0..200)
+ .flat_map(|i| vec![format!("-old{i}"), format!("+new{i}")])
+ .collect();
+ let body_refs: Vec<&str> = big_lock_body.iter().map(|s| s.as_str()).collect();
+ let diff = build_diff(&[
+ ("Cargo.lock", &body_refs),
+ ("Cargo.toml", &["-foo = \"1\"", "+foo = \"2\""]),
+ ]);
+ let score = offload().estimate_bloat(&diff);
+ assert!(
+ score > 0.9,
+ "lockfile-dominated diff should score high, got {score}"
+ );
+ }
+
+ #[test]
+ fn estimate_bloat_no_noise_zero() {
+ let body: Vec<String> = (0..40)
+ .flat_map(|i| vec![format!("-old line {i}"), format!("+new line {i}")])
+ .collect();
+ let body_refs: Vec<&str> = body.iter().map(|s| s.as_str()).collect();
+ let diff = build_diff(&[("src/main.rs", &body_refs)]);
+ let score = offload().estimate_bloat(&diff);
+ assert_eq!(score, 0.0, "real code diff should not be flagged");
+ }
+
+ #[test]
+ fn estimate_bloat_whitespace_only_hunk_scores_high() {
+ // Hunk where every change is just trailing whitespace removal.
+ let body: Vec<String> = (0..40)
+ .flat_map(|i| vec![format!("-line {i} "), format!("+line {i}")])
+ .collect();
+ let body_refs: Vec<&str> = body.iter().map(|s| s.as_str()).collect();
+ let diff = build_diff(&[("src/main.rs", &body_refs)]);
+ let score = offload().estimate_bloat(&diff);
+ assert!(
+ score > 0.5,
+ "whitespace-only hunk should score high, got {score}"
+ );
+ }
+
+ #[test]
+ fn apply_drops_lockfile_and_stores_original() {
+ let big_lock_body: Vec<String> = (0..200)
+ .flat_map(|i| vec![format!("-old{i}"), format!("+new{i}")])
+ .collect();
+ let body_refs: Vec<&str> = big_lock_body.iter().map(|s| s.as_str()).collect();
+ let diff = build_diff(&[
+ ("Cargo.lock", &body_refs),
+ ("Cargo.toml", &["-foo = \"1\"", "+foo = \"2\""]),
+ ]);
+ let store = InMemoryCcrStore::new();
+ let r = offload()
+ .apply(&diff, &CompressionContext::default(), &store)
+ .expect("must compress");
+ assert!(r.bytes_saved > 0);
+ assert!(r.output.contains("[diff_noise: lockfile hunks dropped"));
+ // Real code should survive untouched.
+ assert!(r.output.contains("foo = \"2\""));
+ // Original recoverable.
+ assert_eq!(store.get(&r.cache_key).as_deref(), Some(diff.as_str()));
+ }
+
+ #[test]
+ fn apply_drops_whitespace_only_hunk() {
+ let body: Vec<String> = (0..40)
+ .flat_map(|i| vec![format!("-line {i} "), format!("+line {i}")])
+ .collect();
+ let body_refs: Vec<&str> = body.iter().map(|s| s.as_str()).collect();
+ let diff = build_diff(&[("src/main.rs", &body_refs)]);
+ let store = InMemoryCcrStore::new();
+ let r = offload()
+ .apply(&diff, &CompressionContext::default(), &store)
+ .expect("must compress");
+ assert!(r
+ .output
+ .contains("[diff_noise: whitespace-only hunks dropped"));
+ assert!(r.bytes_saved > 0);
+ }
+
+ #[test]
+ fn apply_skipped_when_no_droppable_hunks() {
+ let body: Vec<String> = (0..40)
+ .flat_map(|i| vec![format!("-old line {i}"), format!("+new line {i}")])
+ .collect();
+ let body_refs: Vec<&str> = body.iter().map(|s| s.as_str()).collect();
+ let diff = build_diff(&[("src/main.rs", &body_refs)]);
+ let store = InMemoryCcrStore::new();
+ let err = offload()
+ .apply(&diff, &CompressionContext::default(), &store)
+ .expect_err("nothing droppable");
+ match err {
+ TransformError::Skipped { .. } => {}
+ _ => panic!("expected Skipped, got {err:?}"),
+ }
+ assert_eq!(store.len(), 0);
+ }
+
+ #[test]
+ fn lockfile_path_match_is_path_segment_aware() {
+ // `MyCargo.lock` — should NOT match because there's no `/`
+ // before `Cargo.lock`.
+ let o = offload();
+ assert!(o.is_lockfile("Cargo.lock"));
+ assert!(o.is_lockfile("crates/foo/Cargo.lock"));
+ assert!(!o.is_lockfile("MyCargo.lock"));
+ assert!(!o.is_lockfile("FakeCargo.lockfile"));
+ }
+
+ #[test]
+ fn handles_diff_with_leading_commit_message() {
+ // git format-patch style — commit message header before the diff.
+ let mut diff = String::new();
+ diff.push_str("From abc123 Mon Sep 17 2025\n");
+ diff.push_str("Subject: bump deps\n\n");
+ diff.push_str("commit body line\n\n");
+ let lock: Vec<String> = (0..40)
+ .flat_map(|i| vec![format!("-old{i}"), format!("+new{i}")])
+ .collect();
+ let lock_refs: Vec<&str> = lock.iter().map(|s| s.as_str()).collect();
+ diff.push_str(&build_diff(&[("yarn.lock", &lock_refs)]));
+ let store = InMemoryCcrStore::new();
+ let r = offload()
+ .apply(&diff, &CompressionContext::default(), &store)
+ .expect("compresses");
+ // Pre-diff prelude must survive.
+ assert!(r.output.contains("Subject: bump deps"));
+ assert!(r.output.contains("[diff_noise: lockfile hunks dropped"));
+ }
+
+ #[test]
+ fn empty_input_is_safe() {
+ assert_eq!(offload().estimate_bloat(""), 0.0);
+ let store = InMemoryCcrStore::new();
+ let err = offload()
+ .apply("", &CompressionContext::default(), &store)
+ .expect_err("must skip");
+ match err {
+ TransformError::Skipped { .. } => {}
+ _ => panic!("expected Skipped"),
+ }
+ }
+}
diff --git a/crates/headroom-core/src/transforms/pipeline/offloads/diff_offload.rs b/crates/headroom-core/src/transforms/pipeline/offloads/diff_offload.rs
new file mode 100644
index 000000000..c9effe69e
--- /dev/null
+++ b/crates/headroom-core/src/transforms/pipeline/offloads/diff_offload.rs
@@ -0,0 +1,278 @@
+//! `DiffOffload` — wraps [`DiffCompressor`] as an [`OffloadTransform`].
+//!
+//! # Bloat heuristic — context-to-change ratio
+//!
+//! A unified diff is bloaty when most of its lines are context: a
+//! 200-line diff that changes only 3 lines is 197 lines of noise.
+//! The estimator walks the input, counts:
+//!
+//! * `change` lines — start with `+` or `-` (excluding the per-file
+//! `+++`/`---` headers).
+//! * `context` lines — start with ` ` (a single space) inside any
+//! hunk.
+//!
+//! Score = `(context / (context + change) − normal_context_ratio) /
+//! (1 − normal_context_ratio)`, clamped to [0.0, 1.0]. Below
+//! the configured `normal_context_ratio` the diff is dense enough that
+//! offload isn't worth the retrieval cost (score 0); at 100% context
+//! it scores 1.0.
+//!
+//! No regex — pure byte-prefix checks. Cost: O(n) over the input
+//! (single pass, no allocations).
+//!
+//! # Bug-fix-on-port
+//!
+//! [`DiffCompressor`] emits a `cache_key` in its output marker without
+//! actually persisting the original to any store (it never sees one).
+//! That's a leak the existing parity-bound port couldn't fix without
+//! breaking byte equality. As an [`OffloadTransform`] consumer we close
+//! the leak by storing the original payload under the same key after
+//! the compressor returns. The trait contract is that
+//! `cache_key MUST resolve in store`; this wrapper is what makes that
+//! true for the diff path.
+//!
+//! [`DiffCompressor`]: crate::transforms::diff_compressor::DiffCompressor
+//! [`OffloadTransform`]: crate::transforms::pipeline::traits::OffloadTransform
+
+use crate::ccr::CcrStore;
+use crate::transforms::diff_compressor::{DiffCompressor, DiffCompressorConfig};
+use crate::transforms::pipeline::config::DiffBloatConfig;
+use crate::transforms::pipeline::traits::{
+ CompressionContext, OffloadOutput, OffloadTransform, TransformError,
+};
+use crate::transforms::ContentType;
+
+const NAME: &str = "diff_offload";
+/// Confidence is high — DiffCompressor has 20+ parity fixtures.
+const CONFIDENCE: f32 = 0.85;
+
+pub struct DiffOffload {
+ compressor: DiffCompressor,
+ bloat: DiffBloatConfig,
+}
+
+impl DiffOffload {
+ pub fn new(bloat: DiffBloatConfig) -> Self {
+ Self::with_compressor(DiffCompressor::new(DiffCompressorConfig::default()), bloat)
+ }
+
+ pub fn with_compressor(compressor: DiffCompressor, bloat: DiffBloatConfig) -> Self {
+ Self { compressor, bloat }
+ }
+}
+
+impl OffloadTransform for DiffOffload {
+ fn name(&self) -> &'static str {
+ NAME
+ }
+
+ fn applies_to(&self) -> &[ContentType] {
+ &[ContentType::GitDiff]
+ }
+
+ fn estimate_bloat(&self, content: &str) -> f32 {
+ if content.is_empty() {
+ return 0.0;
+ }
+ let mut total_lines = 0usize;
+ let mut change = 0usize;
+ let mut context = 0usize;
+ let mut in_hunk = false;
+
+ for line in content.lines() {
+ total_lines += 1;
+ // Hunk header signals "the next ` `/`+`/`-` lines are part
+ // of a real hunk." Bare prefix checks — no regex.
+ if line.starts_with("@@") {
+ in_hunk = true;
+ continue;
+ }
+ // File-level headers can carry `+++`/`---` prefixes; those
+ // aren't change lines. Reset hunk state on a new file
+ // header (begins with `diff --git`).
+ if line.starts_with("diff --git") {
+ in_hunk = false;
+ continue;
+ }
+ if line.starts_with("+++") || line.starts_with("---") {
+ continue;
+ }
+ if !in_hunk {
+ continue;
+ }
+ match line.as_bytes().first() {
+ Some(b'+') | Some(b'-') => change += 1,
+ Some(b' ') => context += 1,
+ _ => {}
+ }
+ }
+
+ if total_lines < self.bloat.min_lines {
+ return 0.0;
+ }
+ let denom = (context + change) as f64;
+ if denom == 0.0 {
+ return 0.0;
+ }
+ let ratio = context as f64 / denom;
+ let normal = self.bloat.normal_context_ratio;
+ if ratio <= normal {
+ return 0.0;
+ }
+ // Map (normal, 1.0] → (0, 1] linearly.
+ let span = 1.0 - normal;
+ if span <= 0.0 {
+ // Degenerate config: treat any context as full bloat.
+ return 1.0;
+ }
+ ((ratio - normal) / span).clamp(0.0, 1.0) as f32
+ }
+
+ fn apply(
+ &self,
+ content: &str,
+ ctx: &CompressionContext,
+ store: &dyn CcrStore,
+ ) -> Result<OffloadOutput, TransformError> {
+ let result = self.compressor.compress(content, &ctx.query);
+
+ let Some(key) = result.cache_key else {
+ return Err(TransformError::skipped(
+ NAME,
+ "diff compressor did not emit a cache_key",
+ ));
+ };
+
+ // Bug-fix-on-port: DiffCompressor mints a key but never stores.
+ // Persist the original here so the trait contract (key resolves
+ // in store) holds.
+ store.put(&key, content);
+
+ Ok(OffloadOutput::from_lengths(
+ content.len(),
+ result.compressed,
+ key,
+ ))
+ }
+
+ fn confidence(&self) -> f32 {
+ CONFIDENCE
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::ccr::InMemoryCcrStore;
+ use crate::transforms::pipeline::config::PipelineConfig;
+
+ fn default_bloat() -> DiffBloatConfig {
+ PipelineConfig::default().bloat.diff
+ }
+
+ fn offload() -> DiffOffload {
+ DiffOffload::new(default_bloat())
+ }
+
+ fn build_diff(num_files: usize, context_per_file: usize, changes_per_file: usize) -> String {
+ let mut s = String::new();
+ for f in 0..num_files {
+ s.push_str(&format!(
+ "diff --git a/file{f}.txt b/file{f}.txt\n--- a/file{f}.txt\n+++ b/file{f}.txt\n@@ -1,{} +1,{} @@\n",
+ context_per_file + changes_per_file,
+ context_per_file + changes_per_file
+ ));
+ for _ in 0..context_per_file {
+ s.push_str(" context line\n");
+ }
+ for c in 0..changes_per_file {
+ s.push_str(&format!("-removed line {c}\n"));
+ s.push_str(&format!("+added line {c}\n"));
+ }
+ }
+ s
+ }
+
+ #[test]
+ fn name_and_applies_to() {
+ let o = offload();
+ assert_eq!(o.name(), "diff_offload");
+ assert_eq!(o.applies_to(), &[ContentType::GitDiff]);
+ }
+
+ #[test]
+ fn estimate_bloat_empty_input_is_zero() {
+ assert_eq!(offload().estimate_bloat(""), 0.0);
+ }
+
+ #[test]
+ fn estimate_bloat_below_min_lines_is_zero() {
+ let small = build_diff(1, 5, 1); // ~13 lines
+ assert_eq!(offload().estimate_bloat(&small), 0.0);
+ }
+
+ #[test]
+ fn estimate_bloat_dense_diff_scores_zero() {
+ // Lots of changes, little context — below `normal_context_ratio=0.6`.
+ let diff = build_diff(2, 5, 60); // 120 changes, 10 context
+ let score = offload().estimate_bloat(&diff);
+ assert_eq!(score, 0.0, "dense diff should score zero, got {score}");
+ }
+
+ #[test]
+ fn estimate_bloat_context_heavy_diff_scores_high() {
+ // Mostly context, few changes — far above 0.6.
+ // 200 context lines, 5 changes each side = 200 / (200+10) ≈ 0.95.
+ let diff = build_diff(1, 200, 5);
+ let score = offload().estimate_bloat(&diff);
+ assert!(
+ score > 0.7,
+ "context-heavy diff should score high, got {score}"
+ );
+ }
+
+ #[test]
+ fn estimate_bloat_at_threshold_scores_zero() {
+ // Exactly normal_context_ratio worth of context — maps to 0.
+ // Construct: 60 context, 20 changes-per-side (total 40 changes)
+ // → context / (context+change) = 60/100 = 0.6 = threshold.
+ let diff = build_diff(1, 60, 20);
+ // Make sure it clears min_lines.
+ let score = offload().estimate_bloat(&diff);
+ assert_eq!(score, 0.0, "at threshold should be zero, got {score}");
+ }
+
+ #[test]
+ fn estimate_bloat_safe_on_huge_inputs() {
+ let diff = build_diff(50, 100, 50); // many files, big hunks
+ let _ = offload().estimate_bloat(&diff);
+ }
+
+ #[test]
+ fn apply_emits_key_and_persists_original() {
+ let diff = build_diff(1, 200, 5);
+ let store = InMemoryCcrStore::new();
+ let r = offload()
+ .apply(&diff, &CompressionContext::default(), &store)
+ .expect("should compress");
+ assert!(!r.cache_key.is_empty());
+ // Bug-fix verification: DiffCompressor itself wouldn't have
+ // stored, but our wrapper must.
+ assert_eq!(store.get(&r.cache_key).as_deref(), Some(diff.as_str()));
+ }
+
+ #[test]
+ fn apply_skipped_when_compressor_declines_ccr() {
+ // Below DiffCompressor's `min_lines_for_ccr=50`.
+ let diff = build_diff(1, 5, 2);
+ let store = InMemoryCcrStore::new();
+ let err = offload()
+ .apply(&diff, &CompressionContext::default(), &store)
+ .expect_err("must skip");
+ match err {
+ TransformError::Skipped { transform, .. } => assert_eq!(transform, "diff_offload"),
+ _ => panic!("expected Skipped, got {err:?}"),
+ }
+ assert_eq!(store.len(), 0);
+ }
+}
diff --git a/crates/headroom-core/src/transforms/pipeline/offloads/log_offload.rs b/crates/headroom-core/src/transforms/pipeline/offloads/log_offload.rs
new file mode 100644
index 000000000..e23bd6a78
--- /dev/null
+++ b/crates/headroom-core/src/transforms/pipeline/offloads/log_offload.rs
@@ -0,0 +1,284 @@
+//! `LogOffload` — wraps [`LogCompressor`] as an [`OffloadTransform`].
+//!
+//! # Bloat heuristic — why these signals
+//!
+//! Logs are bloaty in two distinct ways the orchestrator should both
+//! recognize:
+//!
+//! 1. **Repetition.** The same INFO heartbeat fired 800 times.
+//! Detected by counting unique lines in a sample and computing
+//! `1 − unique/total`. Cheap (a `HashSet<&str>`); high signal.
+//! 2. **Priority dilution.** Unique-but-irrelevant lines burying a
+//! handful of errors. Detected by running each sampled line
+//! through a [`LineImportanceDetector`] and counting how many score
+//! *below* a configured high-priority threshold.
+//!
+//! Both pass through the same sample (default 100 lines). Each
+//! contributes a 0.0–1.0 sub-score; the final bloat score is a weighted
+//! sum of the two (weights sum ≤ 1.0). High repetition AND high
+//! dilution → high bloat → orchestrator runs offload.
+//!
+//! Cost: O(sample_size) hash-set inserts + O(sample_size) detector
+//! calls. KeywordDetector is aho-corasick + word-boundary, so per-line
+//! cost is O(line length). Plenty cheap to run in parallel with the
+//! reformat phase.
+//!
+//! [`LogCompressor`]: crate::transforms::log_compressor::LogCompressor
+//! [`OffloadTransform`]: crate::transforms::pipeline::traits::OffloadTransform
+//! [`LineImportanceDetector`]: crate::signals::LineImportanceDetector
+
+use std::collections::HashSet;
+
+use crate::ccr::CcrStore;
+use crate::signals::{ImportanceContext, KeywordDetector, LineImportanceDetector};
+use crate::transforms::log_compressor::{LogCompressor, LogCompressorConfig};
+use crate::transforms::pipeline::config::LogBloatConfig;
+use crate::transforms::pipeline::traits::{
+ CompressionContext, OffloadOutput, OffloadTransform, TransformError,
+};
+use crate::transforms::ContentType;
+
+const NAME: &str = "log_offload";
+/// Confidence is high — LogCompressor has 50+ parity fixtures and
+/// shadow-validated against Python.
+const CONFIDENCE: f32 = 0.85;
+
+pub struct LogOffload {
+ compressor: LogCompressor,
+ bloat: LogBloatConfig,
+ detector: Box<dyn LineImportanceDetector>,
+ /// Bias passed to the underlying compressor's adaptive sizer.
+ /// Empty `query` in the orchestrator's `CompressionContext` maps
+ /// to `0.0`; supplying a query nudges adaptive sizing slightly
+ /// looser. Matches the existing search/log Python behavior.
+ bias: f64,
+}
+
+impl LogOffload {
+ /// Default constructor: stock LogCompressor, KeywordDetector, default
+ /// bloat config. Used by the orchestrator's typical wiring.
+ pub fn new(bloat: LogBloatConfig) -> Self {
+ Self::with_compressor(
+ LogCompressor::new(LogCompressorConfig::default()),
+ bloat,
+ Box::new(KeywordDetector::new()),
+ )
+ }
+
+ /// Custom constructor — used when an integration test needs a
+ /// stub detector or a tweaked compressor config.
+ pub fn with_compressor(
+ compressor: LogCompressor,
+ bloat: LogBloatConfig,
+ detector: Box<dyn LineImportanceDetector>,
+ ) -> Self {
+ Self {
+ compressor,
+ bloat,
+ detector,
+ bias: 0.0,
+ }
+ }
+
+ /// Override the adaptive-sizer bias passed to the underlying
+ /// compressor. Defaults to 0.0; values around 0.1–0.3 nudge the
+ /// algorithm to keep more lines.
+ pub fn with_bias(mut self, bias: f64) -> Self {
+ self.bias = bias;
+ self
+ }
+}
+
+impl OffloadTransform for LogOffload {
+ fn name(&self) -> &'static str {
+ NAME
+ }
+
+ fn applies_to(&self) -> &[ContentType] {
+ &[ContentType::BuildOutput]
+ }
+
+ fn estimate_bloat(&self, content: &str) -> f32 {
+ if content.is_empty() {
+ return 0.0;
+ }
+ // Cheap line walk, bounded by `sample_size`. We don't allocate
+ // the full Vec<&str> — we iterate lazily and stop after the
+ // sample fills.
+ let mut unique: HashSet<&str> = HashSet::with_capacity(self.bloat.sample_size);
+ let mut sampled = 0usize;
+ let mut low_priority = 0usize;
+
+ for line in content.lines() {
+ if sampled >= self.bloat.sample_size {
+ break;
+ }
+ sampled += 1;
+ unique.insert(line);
+ let signal = self.detector.score(line, ImportanceContext::Log);
+ if signal.priority <= self.bloat.high_priority_threshold {
+ low_priority += 1;
+ }
+ }
+
+ // Below the configured min-lines floor, offload isn't worth
+ // it regardless — return 0.0 so the orchestrator skips us.
+ // Use the actual line count, not the sample count, so very
+ // long but uniform logs still float above the floor.
+ let total_lines = content.lines().count();
+ if total_lines < self.bloat.min_lines {
+ return 0.0;
+ }
+ if sampled == 0 {
+ return 0.0;
+ }
+
+ let repetition = 1.0 - (unique.len() as f32 / sampled as f32);
+ let dilution = low_priority as f32 / sampled as f32;
+ let score = repetition * self.bloat.uniqueness_weight
+ + dilution * self.bloat.priority_dilution_weight;
+ score.clamp(0.0, 1.0)
+ }
+
+ fn apply(
+ &self,
+ content: &str,
+ _ctx: &CompressionContext,
+ store: &dyn CcrStore,
+ ) -> Result<OffloadOutput, TransformError> {
+ let (result, stats) = self
+ .compressor
+ .compress_with_store(content, self.bias, Some(store));
+
+ // The trait contract says `cache_key` is required. If the
+ // underlying compressor decided post-hoc that the offload
+ // wasn't worth it (compression ratio above its own threshold,
+ // or input was too short for CCR), we surface that as a Skip
+ // — NOT a fabricated key. Keeps the trait contract honest.
+ let Some(key) = result.cache_key else {
+ let reason = stats.ccr_skip_reason.unwrap_or("no cache_key emitted");
+ return Err(TransformError::skipped(NAME, reason));
+ };
+
+ Ok(OffloadOutput::from_lengths(
+ content.len(),
+ result.compressed,
+ key,
+ ))
+ }
+
+ fn confidence(&self) -> f32 {
+ CONFIDENCE
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::ccr::InMemoryCcrStore;
+ use crate::transforms::pipeline::config::PipelineConfig;
+
+ fn default_bloat() -> LogBloatConfig {
+ PipelineConfig::default().bloat.log
+ }
+
+ fn offload() -> LogOffload {
+ LogOffload::new(default_bloat())
+ }
+
+ #[test]
+ fn name_and_applies_to() {
+ let o = offload();
+ assert_eq!(o.name(), "log_offload");
+ assert_eq!(o.applies_to(), &[ContentType::BuildOutput]);
+ }
+
+ #[test]
+ fn estimate_bloat_empty_input_is_zero() {
+ assert_eq!(offload().estimate_bloat(""), 0.0);
+ }
+
+ #[test]
+ fn estimate_bloat_below_min_lines_is_zero() {
+ // 5 lines is well below default min_lines=50; should score 0.
+ let log = "INFO: starting\nERROR: oh no\nINFO: heartbeat\nINFO: done\nINFO: bye";
+ assert_eq!(offload().estimate_bloat(log), 0.0);
+ }
+
+ #[test]
+ fn estimate_bloat_high_repetition_scores_high() {
+ // 100 identical INFO heartbeats — pure repetition bloat.
+ let line = "INFO: heartbeat received from worker-7";
+ let log: Vec<&str> = (0..100).map(|_| line).collect();
+ let log = log.join("\n");
+ let score = offload().estimate_bloat(&log);
+ // Repetition is 0.99 (1/100 unique), dilution is 1.0 (no high-
+ // priority signals), default weights 0.5+0.5 → score ≈ 0.995.
+ assert!(score > 0.8, "expected high score, got {score}");
+ }
+
+ #[test]
+ fn estimate_bloat_unique_errors_score_low() {
+ // 100 unique error lines — high dilution score 0 (all errors),
+ // repetition score 0 (all unique). Should be near zero.
+ let lines: Vec<String> = (0..100)
+ .map(|i| format!("ERROR: failure number {i} at module x"))
+ .collect();
+ let log = lines.join("\n");
+ let score = offload().estimate_bloat(&log);
+ assert!(score < 0.3, "expected low score, got {score}");
+ }
+
+ #[test]
+ fn estimate_bloat_priority_dilution_alone_scores_meaningfully() {
+ // 100 unique INFO lines — repetition ≈ 0, dilution ≈ 1.0.
+ // Default weights → score ≈ 0.5.
+ let lines: Vec<String> = (0..100)
+ .map(|i| format!("INFO: routine event #{i}"))
+ .collect();
+ let log = lines.join("\n");
+ let score = offload().estimate_bloat(&log);
+ assert!((0.3..=0.7).contains(&score), "expected ~0.5, got {score}");
+ }
+
+ #[test]
+ fn estimate_bloat_safe_on_huge_inputs() {
+ // 100k lines — sample bounding must keep this cheap. Test
+ // exists to flush out accidental O(n²) regressions.
+ let lines: Vec<String> = (0..100_000).map(|i| format!("line {i}")).collect();
+ let log = lines.join("\n");
+ // Should complete near-instantly; we don't assert a deadline,
+ // just that the call returns without explosion.
+ let _ = offload().estimate_bloat(&log);
+ }
+
+ #[test]
+ fn apply_emits_cache_key_and_stores_original_for_repetitive_log() {
+ let line = "INFO: heartbeat\n";
+ let log: String = line.repeat(200);
+ let store = InMemoryCcrStore::new();
+ let r = offload()
+ .apply(&log, &CompressionContext::default(), &store)
+ .expect("offload should produce a key on bloaty input");
+ assert!(!r.cache_key.is_empty());
+ assert_eq!(store.get(&r.cache_key).as_deref(), Some(log.as_str()));
+ assert!(r.bytes_saved > 0);
+ }
+
+ #[test]
+ fn apply_returns_skipped_when_underlying_compressor_declines_ccr() {
+ // 5-line log: below LogCompressor's `min_lines_for_ccr=50`.
+ // Compressor passes through unchanged with `cache_key=None`.
+ // Our wrapper must surface that as `Skipped`, not fabricate a key.
+ let log = "INFO: a\nINFO: b\nINFO: c\nINFO: d\nINFO: e";
+ let store = InMemoryCcrStore::new();
+ let err = offload()
+ .apply(log, &CompressionContext::default(), &store)
+ .expect_err("must skip");
+ match err {
+ TransformError::Skipped { transform, .. } => assert_eq!(transform, "log_offload"),
+ _ => panic!("expected Skipped, got {err:?}"),
+ }
+ assert_eq!(store.len(), 0, "no payload should have been stored");
+ }
+}
diff --git a/crates/headroom-core/src/transforms/pipeline/offloads/mod.rs b/crates/headroom-core/src/transforms/pipeline/offloads/mod.rs
new file mode 100644
index 000000000..f80948a7d
--- /dev/null
+++ b/crates/headroom-core/src/transforms/pipeline/offloads/mod.rs
@@ -0,0 +1,32 @@
+//! Offload transforms — drop bytes from the wire, stash original via CCR.
+//!
+//! Every transform here implements [`super::traits::OffloadTransform`].
+//! The output is a SUBSET of the input plus a retrieval marker; the
+//! original payload sits in a [`crate::ccr::CcrStore`] keyed by the
+//! returned `cache_key`. The LLM retrieves any dropped piece by
+//! issuing a tool call against the runtime layer, which queries the
+//! same store.
+//!
+//! # Per-domain bloat
+//!
+//! Each offload carries a cheap, structural [`estimate_bloat`] method
+//! the orchestrator runs in parallel with the reformat phase. The
+//! estimate is the gating signal: if it falls below a configurable
+//! threshold AND reformat shrunk enough on its own, the orchestrator
+//! skips this offload entirely (no parse, no store write, no marker).
+//!
+//! [`estimate_bloat`]: super::traits::OffloadTransform::estimate_bloat
+
+pub mod diff_noise;
+pub mod diff_offload;
+pub mod log_offload;
+pub mod search_offload;
+
+pub use diff_noise::DiffNoise;
+pub use diff_offload::DiffOffload;
+pub use log_offload::LogOffload;
+// `SearchOffload` is intentionally NOT re-exported here. The
+// orchestrator-default registration omits it; keep the type accessible
+// via the explicit module path for opt-in callers, but discourage new
+// adoption (see `search_offload.rs` head docs for rationale).
+pub use search_offload::SearchOffload;
diff --git a/crates/headroom-core/src/transforms/pipeline/offloads/search_offload.rs b/crates/headroom-core/src/transforms/pipeline/offloads/search_offload.rs
new file mode 100644
index 000000000..5600f7fa2
--- /dev/null
+++ b/crates/headroom-core/src/transforms/pipeline/offloads/search_offload.rs
@@ -0,0 +1,331 @@
+//! `SearchOffload` — wraps [`SearchCompressor`] as an [`OffloadTransform`].
+//!
+//! # Status: not registered in the default pipeline (2026-04-30)
+//!
+//! Modern coding agents (Claude Code, Codex, etc.) drive `rg` / `grep`
+//! with sensible scoping, so broad noisy search output is rare in
+//! practice. When it does happen, the LLM benefits from seeing the
+//! match clustering directly — compressing it adds maintenance burden
+//! for marginal token savings. The type stays accessible at
+//! `crate::transforms::pipeline::offloads::search_offload::SearchOffload`
+//! for callers who want to opt in, but the orchestrator's default wiring
+//! omits it. Re-evaluate once usage telemetry shows real demand.
+//!
+//! # Bloat heuristic — match clustering
+//!
+//! Search output (grep / ripgrep) is bloaty when matches cluster
+//! heavily into a few files: 50 hits in `utils.py` and one hit
+//! elsewhere is mostly redundant — the LLM only needs a representative
+//! sample plus a count. The estimator computes:
+//!
+//! 1. `total` — count of lines that look like a `file:line:` match.
+//! 2. `unique_files` — distinct file prefixes among those matches.
+//! 3. `avg = total / unique_files`.
+//! 4. `score = (avg − 1) / cluster_threshold`, clamped to [0.0, 1.0].
+//!
+//! `cluster_threshold = 10.0` means "10 matches per file on average is
+//! 100% bloat" (the offload should fire). Below `min_matches`, score 0
+//! regardless — too small to bother with retrieval round trip.
+//!
+//! No regex — pure byte scan: walk lines, find the first colon (or
+//! Windows drive-letter colon) that's followed by digits and another
+//! colon, treat what's before as the file. Cost: O(n) over input.
+//!
+//! [`SearchCompressor`]: crate::transforms::search_compressor::SearchCompressor
+//! [`OffloadTransform`]: crate::transforms::pipeline::traits::OffloadTransform
+
+use std::collections::HashSet;
+
+use crate::ccr::CcrStore;
+use crate::transforms::pipeline::config::SearchBloatConfig;
+use crate::transforms::pipeline::traits::{
+ CompressionContext, OffloadOutput, OffloadTransform, TransformError,
+};
+use crate::transforms::search_compressor::{SearchCompressor, SearchCompressorConfig};
+use crate::transforms::ContentType;
+
+const NAME: &str = "search_offload";
+/// Confidence is high — SearchCompressor has parity fixtures.
+const CONFIDENCE: f32 = 0.85;
+
+pub struct SearchOffload {
+ compressor: SearchCompressor,
+ bloat: SearchBloatConfig,
+ /// Bias for the underlying compressor's adaptive sizer.
+ bias: f64,
+}
+
+impl SearchOffload {
+ pub fn new(bloat: SearchBloatConfig) -> Self {
+ Self::with_compressor(
+ SearchCompressor::new(SearchCompressorConfig::default()),
+ bloat,
+ )
+ }
+
+ pub fn with_compressor(compressor: SearchCompressor, bloat: SearchBloatConfig) -> Self {
+ Self {
+ compressor,
+ bloat,
+ bias: 0.0,
+ }
+ }
+
+ pub fn with_bias(mut self, bias: f64) -> Self {
+ self.bias = bias;
+ self
+ }
+}
+
+impl OffloadTransform for SearchOffload {
+ fn name(&self) -> &'static str {
+ NAME
+ }
+
+ fn applies_to(&self) -> &[ContentType] {
+ &[ContentType::SearchResults]
+ }
+
+ fn estimate_bloat(&self, content: &str) -> f32 {
+ if content.is_empty() {
+ return 0.0;
+ }
+ let mut total = 0usize;
+ let mut files: HashSet<&str> = HashSet::new();
+
+ for line in content.lines() {
+ if let Some(file) = extract_file_prefix(line) {
+ total += 1;
+ files.insert(file);
+ }
+ }
+
+ if total < self.bloat.min_matches || files.is_empty() {
+ return 0.0;
+ }
+ let avg = total as f32 / files.len() as f32;
+ if avg <= 1.0 {
+ return 0.0;
+ }
+ let score = (avg - 1.0) / self.bloat.cluster_threshold;
+ score.clamp(0.0, 1.0)
+ }
+
+ fn apply(
+ &self,
+ content: &str,
+ ctx: &CompressionContext,
+ store: &dyn CcrStore,
+ ) -> Result<OffloadOutput, TransformError> {
+ let (result, stats) =
+ self.compressor
+ .compress_with_store(content, &ctx.query, self.bias, Some(store));
+
+ let Some(key) = result.cache_key else {
+ let reason = stats.ccr_skip_reason.unwrap_or("no cache_key emitted");
+ return Err(TransformError::skipped(NAME, reason));
+ };
+
+ Ok(OffloadOutput::from_lengths(
+ content.len(),
+ result.compressed,
+ key,
+ ))
+ }
+
+ fn confidence(&self) -> f32 {
+ CONFIDENCE
+ }
+}
+
+/// Extract the file prefix from a single grep-style match line. Returns
+/// `None` if the line doesn't look like a match. Handles:
+///
+/// * `path:42:content` — standard `grep -n`
+/// * `path-42-content` — ripgrep context lines (a separate non-match
+/// indicator; we treat them as matches for clustering purposes since
+/// they belong to the same file)
+/// * `C:\path:42:content` — Windows-style drive-prefixed paths (skip
+/// the drive colon when scanning for the line-number marker)
+///
+/// No regex — manual byte scan. Returns the file prefix as a borrowed
+/// `&str` over the input.
+fn extract_file_prefix(line: &str) -> Option<&str> {
+ let bytes = line.as_bytes();
+ if bytes.is_empty() {
+ return None;
+ }
+ // Skip a Windows-style drive prefix (`C:` or `c:`).
+ let scan_start =
+ if bytes.len() >= 2 && bytes[1] == b':' && (bytes[0] as char).is_ascii_alphabetic() {
+ 2
+ } else {
+ 0
+ };
+
+ let mut i = scan_start;
+ while i < bytes.len() {
+ let b = bytes[i];
+ if b == b':' || b == b'-' {
+ // Saw a separator. Need the next chars to be digits, then
+ // another matching separator.
+ let sep = b;
+ let mut j = i + 1;
+ let digit_start = j;
+ while j < bytes.len() && bytes[j].is_ascii_digit() {
+ j += 1;
+ }
+ if j > digit_start && j < bytes.len() && bytes[j] == sep {
+ // Found `<file><sep><digits><sep>`. File prefix is [0..i].
+ return Some(&line[..i]);
+ }
+ }
+ i += 1;
+ }
+ None
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::ccr::InMemoryCcrStore;
+ use crate::transforms::pipeline::config::PipelineConfig;
+
+ fn default_bloat() -> SearchBloatConfig {
+ PipelineConfig::default().bloat.search
+ }
+
+ fn offload() -> SearchOffload {
+ SearchOffload::new(default_bloat())
+ }
+
+ #[test]
+ fn name_and_applies_to() {
+ let o = offload();
+ assert_eq!(o.name(), "search_offload");
+ assert_eq!(o.applies_to(), &[ContentType::SearchResults]);
+ }
+
+ #[test]
+ fn extract_file_prefix_handles_grep() {
+ assert_eq!(
+ extract_file_prefix("src/utils.py:42:def foo():"),
+ Some("src/utils.py")
+ );
+ }
+
+ #[test]
+ fn extract_file_prefix_handles_ripgrep_context() {
+ assert_eq!(
+ extract_file_prefix("src/main.py-43-some context"),
+ Some("src/main.py")
+ );
+ }
+
+ #[test]
+ fn extract_file_prefix_handles_dashed_filenames() {
+ assert_eq!(
+ extract_file_prefix("pre-commit-config.yaml:7:line"),
+ Some("pre-commit-config.yaml")
+ );
+ }
+
+ #[test]
+ fn extract_file_prefix_handles_windows_paths() {
+ assert_eq!(
+ extract_file_prefix(r"C:\Users\foo\bar.py:42:line"),
+ Some(r"C:\Users\foo\bar.py")
+ );
+ }
+
+ #[test]
+ fn extract_file_prefix_rejects_non_matches() {
+ assert_eq!(extract_file_prefix(""), None);
+ assert_eq!(extract_file_prefix("just some text"), None);
+ assert_eq!(extract_file_prefix("file:notdigits:content"), None);
+ }
+
+ #[test]
+ fn estimate_bloat_empty_is_zero() {
+ assert_eq!(offload().estimate_bloat(""), 0.0);
+ }
+
+ #[test]
+ fn estimate_bloat_below_min_matches_is_zero() {
+ let s = "a.py:1:x\nb.py:2:y\nc.py:3:z";
+ assert_eq!(offload().estimate_bloat(s), 0.0);
+ }
+
+ #[test]
+ fn estimate_bloat_clustered_matches_score_high() {
+ // 100 matches in a single file — avg 100/1 = 100. Above
+ // cluster_threshold=10 → score saturates at 1.0.
+ let s: String = (0..100)
+ .map(|i| format!("utils.py:{}:line", i + 1))
+ .collect::<Vec<_>>()
+ .join("\n");
+ let score = offload().estimate_bloat(&s);
+ assert!(score > 0.9, "expected high score, got {score}");
+ }
+
+ #[test]
+ fn estimate_bloat_distributed_matches_score_low() {
+ // 20 matches across 20 files — avg 1.0. Score should be 0.
+ let s: String = (0..20)
+ .map(|i| format!("file{i}.py:1:line"))
+ .collect::<Vec<_>>()
+ .join("\n");
+ let score = offload().estimate_bloat(&s);
+ assert_eq!(score, 0.0);
+ }
+
+ #[test]
+ fn estimate_bloat_moderate_clustering() {
+ // 30 matches across 5 files — avg 6.0. Score = (6-1)/10 = 0.5.
+ let mut s = String::new();
+ for f in 0..5 {
+ for line in 0..6 {
+ s.push_str(&format!("file{f}.py:{}:line\n", line + 1));
+ }
+ }
+ let score = offload().estimate_bloat(&s);
+ assert!((0.4..=0.6).contains(&score), "expected ~0.5, got {score}");
+ }
+
+ #[test]
+ fn estimate_bloat_safe_on_huge_inputs() {
+ let s: String = (0..50_000)
+ .map(|i| format!("file{}.py:1:line", i % 100))
+ .collect::<Vec<_>>()
+ .join("\n");
+ let _ = offload().estimate_bloat(&s);
+ }
+
+ #[test]
+ fn apply_emits_cache_key_and_stores_original_for_clustered_input() {
+ let s: String = (0..100)
+ .map(|i| format!("utils.py:{}:def fn_{i}", i + 1))
+ .collect::<Vec<_>>()
+ .join("\n");
+ let store = InMemoryCcrStore::new();
+ let r = offload()
+ .apply(&s, &CompressionContext::default(), &store)
+ .expect("offload should produce a key on clustered input");
+ assert!(!r.cache_key.is_empty());
+ assert_eq!(store.get(&r.cache_key).as_deref(), Some(s.as_str()));
+ }
+
+ #[test]
+ fn apply_skipped_when_compressor_declines_ccr() {
+ // Single match — far below SearchCompressor's threshold.
+ let s = "only.py:1:trivial";
+ let store = InMemoryCcrStore::new();
+ let err = offload()
+ .apply(s, &CompressionContext::default(), &store)
+ .expect_err("must skip");
+ match err {
+ TransformError::Skipped { transform, .. } => assert_eq!(transform, "search_offload"),
+ _ => panic!("expected Skipped, got {err:?}"),
+ }
+ }
+}
diff --git a/crates/headroom-core/src/transforms/pipeline/orchestrator.rs b/crates/headroom-core/src/transforms/pipeline/orchestrator.rs
index 03ddd9fd7..da76ed8c7 100644
--- a/crates/headroom-core/src/transforms/pipeline/orchestrator.rs
+++ b/crates/headroom-core/src/transforms/pipeline/orchestrator.rs
@@ -1,111 +1,88 @@
-//! `CompressionPipeline` — content-type-keyed dispatch over lossless
-//! and lossy transforms.
+//! [`CompressionPipeline`] — content-type-keyed dispatch over reformat
+//! and offload transforms with **parallel** domain-specific bloat
+//! estimation.
//!
//! # Decision flow
//!
//! ```text
//! input + content_type
//! │
-//! ▼
-//! ┌────────────────────────────────────┐
-//! │ Lossless transforms for this type │ ──┐
-//! │ for each in registration order: │ │ stop early if
-//! │ try apply │ │ current_len/orig_len
-//! │ accept iff is_acceptable() │ │ falls below
-//! │ │ │ lossless_target_ratio
-//! └────────────────────────────────────┘ ──┘
+//! ▼ rayon::join (real parallelism)
+//! ┌──────────────────────────────┐ ┌────────────────────────────┐
+//! │ Reformat phase │ │ Per-offload bloat phase │
+//! │ serial over reformats │ │ par_iter over offloads │
+//! │ stop early if │ │ each calls estimate_bloat│
+//! │ output_len/orig_len ≤ │ │ │
+//! │ reformat_target_ratio │ │ returns (offload, score) │
+//! └──────────────────────────────┘ └────────────────────────────┘
+//! │ │
+//! ▼ ▼
+//! ┌──────────────────────────────────────────────────────┐
+//! │ Decide which offloads to run │
+//! │ │
+//! │ For each (offload, score): │
+//! │ run_it = score ≥ bloat_threshold │
+//! │ OR (reformat_ratio > offload_fallback_ratio │
+//! │ AND score > 0) │
+//! └──────────────────────────────────────────────────────┘
//! │
-//! ▼
+//! ▼ serial — each offload sees the previous one's output
//! ┌────────────────────────────────────┐
-//! │ Lossy transforms for this type │
-//! │ for each in registration order: │
-//! │ try apply │
-//! │ accept iff is_acceptable() │
-//! │ flag structure_preserved=false │
+//! │ Run gated offloads against `store` │
//! └────────────────────────────────────┘
//! │
-//! ▼ steps_applied[], bytes_saved, structure_preserved, reversible_via
+//! ▼ steps_applied[], bytes_saved, cache_keys[]
//! ```
//!
-//! Acceptance gate (`is_acceptable`):
-//! * Reject if output isn't strictly shorter than the input it just
-//! processed (a transform that grew the content gets discarded).
-//! * Reject if `bytes_saved / current_len < min_savings_ratio`. The
-//! default is 5% — transforms that move bytes by less than that
-//! aren't worth the runtime overhead they impose.
+//! # Why parallel?
+//!
+//! Reformat phase scans/parses input bytes (e.g. JSON parse).
+//! Bloat estimators also scan input bytes (line walks, hash sets,
+//! detector calls). On large inputs both touch the same cache lines —
+//! running them on different threads via `rayon::join` overlaps the
+//! scans without competing for memory bandwidth, since both are
+//! read-only over the same buffer.
//!
-//! Skip-further-lossless gate (`should_keep_running_lossless`):
-//! * If the running output is already at or below
-//! `lossless_target_ratio * original_len`, stop running additional
-//! lossless transforms and move straight to lossy. Default 0.5 —
-//! "we've cut input in half losslessly, no need to keep
-//! structural-pass churning."
+//! # The acceptance gate
//!
-//! Per-transform errors are logged at TRACE level and treated as
-//! skips. The pipeline never panics on a transform failure; the
-//! callers can rely on getting *some* output back, even if it's the
-//! original input verbatim (all transforms skipped).
+//! Both reformat outputs and offload outputs go through the same
+//! "did we save enough to keep this?" check. PipelineResult always
+//! returns *some* output — failures inside transforms are recorded as
+//! skips, not propagated. The orchestrator is on the hot path of every
+//! tool-call response and MUST NOT panic.
use std::collections::HashMap;
use std::sync::Arc;
+use rayon::prelude::*;
+
+use crate::ccr::CcrStore;
+use crate::transforms::pipeline::config::PipelineConfig;
use crate::transforms::pipeline::traits::{
- CompressionContext, LosslessTransform, LossyTransform, TransformResult,
+ CompressionContext, OffloadTransform, ReformatTransform, TransformError,
};
use crate::transforms::ContentType;
-/// Runtime knobs for the orchestrator. Defaults chosen empirically;
-/// callers can override per-pipeline.
-#[derive(Debug, Clone, Copy)]
-pub struct PipelineConfig {
- /// Minimum savings ratio (saved / current_len) for a transform's
- /// output to be accepted. Default 0.05 — transforms that move
- /// fewer than 5% of bytes don't earn the risk of having moved
- /// the wrong ones.
- pub min_savings_ratio: f64,
- /// Stop the lossless pass once the running output drops below
- /// this fraction of the original input length. Default 0.5 —
- /// once we've cut by half losslessly, downstream lossy passes
- /// can do the rest cheaper than another structural transform.
- pub lossless_target_ratio: f64,
-}
-
-impl Default for PipelineConfig {
- fn default() -> Self {
- Self {
- min_savings_ratio: 0.05,
- lossless_target_ratio: 0.5,
- }
- }
-}
-
/// Result returned by [`CompressionPipeline::run`].
#[derive(Debug, Clone, Default)]
pub struct PipelineResult {
- /// Final compressed output. Equal to the input if every transform
- /// skipped or was rejected.
+ /// Final output. Equal to the input if every stage skipped.
pub output: String,
- /// Total bytes removed across all accepted transforms.
+ /// Total bytes removed, summed across every accepted stage.
pub bytes_saved: usize,
- /// True iff every accepted transform preserved structure. A
- /// single accepted lossy transform flips this to false.
- pub structure_preserved: bool,
- /// Names of accepted transforms in execution order. Maps 1:1 to
- /// the per-strategy stats nest from Phase 3e.0.
+ /// Reformat names + offload names that were actually accepted, in
+ /// execution order. Maps 1:1 onto the per-strategy stats nest.
pub steps_applied: Vec<String>,
- /// Most recent CCR cache key emitted by an accepted transform.
- /// PR1 transforms never set this; the field exists for PR2/PR3
- /// integrations.
- pub reversible_via: Option<String>,
+ /// CCR cache keys produced by accepted offloads. Empty when only
+ /// reformats ran (or when nothing ran). Order matches
+ /// `steps_applied`'s offload entries — first offload key first.
+ pub cache_keys: Vec<String>,
}
-/// Sequential lossless-then-lossy pipeline keyed on `ContentType`.
-///
-/// Construct via [`builder`](Self::builder), then call
-/// [`run`](Self::run) on each input.
+/// Sequential reformat-then-parallel-bloat-then-gated-offload pipeline.
pub struct CompressionPipeline {
- lossless_by_type: HashMap<ContentType, Vec<Arc<dyn LosslessTransform>>>,
- lossy_by_type: HashMap<ContentType, Vec<Arc<dyn LossyTransform>>>,
+ reformats_by_type: HashMap<ContentType, Vec<Arc<dyn ReformatTransform>>>,
+ offloads_by_type: HashMap<ContentType, Vec<Arc<dyn OffloadTransform>>>,
config: PipelineConfig,
}
@@ -114,102 +91,98 @@ impl CompressionPipeline {
CompressionPipelineBuilder::default()
}
- /// Run the configured pipeline against `content`. Always returns a
- /// [`PipelineResult`] — failures inside individual transforms are
- /// recorded in tracing and turn into skips, never panics.
+ /// Run the pipeline. `store` receives offload payloads under their
+ /// `cache_key`s; reformat-only invocations don't touch it.
pub fn run(
&self,
content: &str,
content_type: ContentType,
ctx: &CompressionContext,
+ store: &dyn CcrStore,
) -> PipelineResult {
let original_len = content.len();
- let mut current = content.to_string();
- let mut total_saved: usize = 0;
- let mut structure_preserved = true;
- let mut steps: Vec<String> = Vec::new();
- let mut reversible: Option<String> = None;
-
- // Phase 1 — lossless. Run in registration order, stop if we've
- // hit the lossless target ratio.
- if let Some(lossless) = self.lossless_by_type.get(&content_type) {
- for transform in lossless {
- if !self.should_keep_running_lossless(current.len(), original_len) {
- tracing::trace!(
- target: "headroom::pipeline",
- transform = transform.name(),
- current_len = current.len(),
- original_len,
- "lossless target reached, stopping lossless phase"
- );
- break;
- }
- match transform.apply(&current) {
- Ok(result) => {
- if !self.is_acceptable(result.bytes_saved, current.len()) {
- tracing::trace!(
- target: "headroom::pipeline",
- transform = transform.name(),
- bytes_saved = result.bytes_saved,
- "lossless transform rejected: insufficient savings"
- );
- continue;
- }
- Self::accept(
- &mut current,
- &mut total_saved,
- &mut steps,
- &mut reversible,
- &mut structure_preserved,
- transform.name(),
- result,
- );
- }
- Err(e) => {
- tracing::trace!(
- target: "headroom::pipeline",
- transform = transform.name(),
- error = %e,
- "lossless transform errored"
- );
- }
- }
- }
+ if original_len == 0 {
+ return PipelineResult {
+ output: String::new(),
+ ..Default::default()
+ };
}
- // Phase 2 — lossy. Always runs (PR3 will gate this on token
- // budget once the tokenizer hookup lands).
- if let Some(lossy) = self.lossy_by_type.get(&content_type) {
- for transform in lossy {
- match transform.apply(&current, ctx) {
- Ok(result) => {
- if !self.is_acceptable(result.bytes_saved, current.len()) {
- tracing::trace!(
- target: "headroom::pipeline",
- transform = transform.name(),
- bytes_saved = result.bytes_saved,
- "lossy transform rejected: insufficient savings"
- );
- continue;
- }
- Self::accept(
- &mut current,
- &mut total_saved,
- &mut steps,
- &mut reversible,
- &mut structure_preserved,
- transform.name(),
- result,
- );
- }
- Err(e) => {
+ let empty_reformats: Vec<Arc<dyn ReformatTransform>> = Vec::new();
+ let empty_offloads: Vec<Arc<dyn OffloadTransform>> = Vec::new();
+ let reformats = self
+ .reformats_by_type
+ .get(&content_type)
+ .unwrap_or(&empty_reformats);
+ let offloads = self
+ .offloads_by_type
+ .get(&content_type)
+ .unwrap_or(&empty_offloads);
+
+ // Phase 1+2 — run reformat phase and bloat estimation in parallel.
+ // rayon::join takes two closures and runs them on different
+ // worker threads when work is plentiful; it serializes them on
+ // the calling thread when not. The pipeline doesn't care
+ // which way it falls; correctness is the same.
+ let (reformat_acc, bloat_scores) = rayon::join(
+ || self.run_reformats(content, reformats),
+ || self.estimate_bloats(content, offloads),
+ );
+
+ let mut steps: Vec<String> = reformat_acc.steps;
+ let mut total_saved: usize = reformat_acc.bytes_saved;
+ let mut current = reformat_acc.output;
+
+ // Compute the post-reformat ratio that gates fallback offloads.
+ let reformat_ratio = current.len() as f64 / original_len as f64;
+
+ // Phase 3 — decide and run offloads. Each offload sees the
+ // current (post-reformat, post-prior-offload) buffer.
+ let mut cache_keys: Vec<String> = Vec::new();
+ for (offload, score) in offloads.iter().zip(bloat_scores.iter()) {
+ let above_threshold = *score >= self.config.pipeline.bloat_threshold;
+ let reformat_underwhelmed =
+ reformat_ratio > self.config.pipeline.offload_fallback_ratio && *score > 0.0;
+ if !(above_threshold || reformat_underwhelmed) {
+ tracing::trace!(
+ target: "headroom::pipeline",
+ offload = offload.name(),
+ score,
+ reformat_ratio,
+ "offload skipped: bloat below threshold and reformat sufficient"
+ );
+ continue;
+ }
+ match offload.apply(&current, ctx, store) {
+ Ok(out) => {
+ if out.bytes_saved == 0 {
tracing::trace!(
target: "headroom::pipeline",
- transform = transform.name(),
- error = %e,
- "lossy transform errored"
+ offload = offload.name(),
+ "offload accepted but saved zero bytes — discarding"
);
+ continue;
}
+ total_saved = total_saved.saturating_add(out.bytes_saved);
+ current = out.output;
+ steps.push(offload.name().to_string());
+ cache_keys.push(out.cache_key);
+ }
+ Err(TransformError::Internal { message, .. }) => {
+ tracing::warn!(
+ target: "headroom::pipeline",
+ offload = offload.name(),
+ error = %message,
+ "offload internal error"
+ );
+ }
+ Err(e) => {
+ tracing::trace!(
+ target: "headroom::pipeline",
+ offload = offload.name(),
+ error = %e,
+ "offload skipped"
+ );
}
}
}
@@ -217,81 +190,107 @@ impl CompressionPipeline {
PipelineResult {
output: current,
bytes_saved: total_saved,
- structure_preserved,
steps_applied: steps,
- reversible_via: reversible,
+ cache_keys,
}
}
- /// Centralized accept logic. Updates the running output, savings,
- /// step list, reversibility handle, and structure flag as one
- /// step so the lossless and lossy phases share semantics.
- fn accept(
- current: &mut String,
- total_saved: &mut usize,
- steps: &mut Vec<String>,
- reversible: &mut Option<String>,
- structure_preserved: &mut bool,
- name: &'static str,
- result: TransformResult,
- ) {
- *total_saved = total_saved.saturating_add(result.bytes_saved);
- if !result.structure_preserved {
- *structure_preserved = false;
+ /// Run reformat transforms in registration order against `content`.
+ /// Stops once `current_len / original_len <= reformat_target_ratio`.
+ fn run_reformats(
+ &self,
+ content: &str,
+ reformats: &[Arc<dyn ReformatTransform>],
+ ) -> ReformatAccumulator {
+ let original_len = content.len();
+ let mut current = content.to_string();
+ let mut total_saved: usize = 0;
+ let mut steps: Vec<String> = Vec::new();
+
+ for transform in reformats {
+ // Stop-early gate: target reached.
+ let ratio = current.len() as f64 / original_len.max(1) as f64;
+ if ratio <= self.config.pipeline.reformat_target_ratio {
+ tracing::trace!(
+ target: "headroom::pipeline",
+ transform = transform.name(),
+ ratio,
+ "reformat target reached, skipping remaining reformats"
+ );
+ break;
+ }
+ match transform.apply(&current) {
+ Ok(out) => {
+ if out.bytes_saved == 0 {
+ continue;
+ }
+ total_saved = total_saved.saturating_add(out.bytes_saved);
+ current = out.output;
+ steps.push(transform.name().to_string());
+ }
+ Err(TransformError::Internal { message, .. }) => {
+ tracing::warn!(
+ target: "headroom::pipeline",
+ transform = transform.name(),
+ error = %message,
+ "reformat internal error"
+ );
+ }
+ Err(e) => {
+ tracing::trace!(
+ target: "headroom::pipeline",
+ transform = transform.name(),
+ error = %e,
+ "reformat skipped"
+ );
+ }
+ }
}
- if let Some(handle) = result.reversible_via {
- *reversible = Some(handle);
+
+ ReformatAccumulator {
+ output: current,
+ bytes_saved: total_saved,
+ steps,
}
- *current = result.output;
- steps.push(name.to_string());
}
- /// Acceptance gate — whether this transform's savings on the
- /// current state of the buffer are worth keeping.
- pub(crate) fn is_acceptable(&self, bytes_saved: usize, current_len: usize) -> bool {
- if bytes_saved == 0 || current_len == 0 {
- return false;
- }
- let ratio = bytes_saved as f64 / current_len as f64;
- ratio >= self.config.min_savings_ratio
+ /// Run every offload's bloat estimator in parallel. Returns scores
+ /// in the same order as the input slice.
+ fn estimate_bloats(&self, content: &str, offloads: &[Arc<dyn OffloadTransform>]) -> Vec<f32> {
+ offloads
+ .par_iter()
+ .map(|o| o.estimate_bloat(content))
+ .collect()
}
- /// Whether the lossless phase should keep running. False once
- /// `current_len / original_len <= lossless_target_ratio`.
- pub(crate) fn should_keep_running_lossless(
- &self,
- current_len: usize,
- original_len: usize,
- ) -> bool {
- if original_len == 0 {
- return false;
- }
- let ratio = current_len as f64 / original_len as f64;
- ratio > self.config.lossless_target_ratio
+ pub fn config(&self) -> &PipelineConfig {
+ &self.config
}
}
-/// Fluent builder for [`CompressionPipeline`]. The example in
-/// `issue #315` is the spec for this surface.
+struct ReformatAccumulator {
+ output: String,
+ bytes_saved: usize,
+ steps: Vec<String>,
+}
+
+/// Fluent builder for [`CompressionPipeline`].
#[derive(Default)]
pub struct CompressionPipelineBuilder {
- lossless_by_type: HashMap<ContentType, Vec<Arc<dyn LosslessTransform>>>,
- lossy_by_type: HashMap<ContentType, Vec<Arc<dyn LossyTransform>>>,
+ reformats_by_type: HashMap<ContentType, Vec<Arc<dyn ReformatTransform>>>,
+ offloads_by_type: HashMap<ContentType, Vec<Arc<dyn OffloadTransform>>>,
config: Option<PipelineConfig>,
}
impl CompressionPipelineBuilder {
- /// Register a lossless transform. The transform is added to the
- /// pipeline for every `ContentType` it self-declares via
- /// `applies_to()`. Order of registration is order of execution.
- pub fn with_lossless<T>(mut self, transform: T) -> Self
+ pub fn with_reformat<T>(mut self, transform: T) -> Self
where
- T: LosslessTransform + 'static,
+ T: ReformatTransform + 'static,
{
- let arc: Arc<dyn LosslessTransform> = Arc::new(transform);
+ let arc: Arc<dyn ReformatTransform> = Arc::new(transform);
let types: Vec<ContentType> = arc.applies_to().to_vec();
for ct in types {
- self.lossless_by_type
+ self.reformats_by_type
.entry(ct)
.or_default()
.push(arc.clone());
@@ -299,14 +298,17 @@ impl CompressionPipelineBuilder {
self
}
- pub fn with_lossy<T>(mut self, transform: T) -> Self
+ pub fn with_offload<T>(mut self, transform: T) -> Self
where
- T: LossyTransform + 'static,
+ T: OffloadTransform + 'static,
{
- let arc: Arc<dyn LossyTransform> = Arc::new(transform);
+ let arc: Arc<dyn OffloadTransform> = Arc::new(transform);
let types: Vec<ContentType> = arc.applies_to().to_vec();
for ct in types {
- self.lossy_by_type.entry(ct).or_default().push(arc.clone());
+ self.offloads_by_type
+ .entry(ct)
+ .or_default()
+ .push(arc.clone());
}
self
}
@@ -318,8 +320,8 @@ impl CompressionPipelineBuilder {
pub fn build(self) -> CompressionPipeline {
CompressionPipeline {
- lossless_by_type: self.lossless_by_type,
- lossy_by_type: self.lossy_by_type,
+ reformats_by_type: self.reformats_by_type,
+ offloads_by_type: self.offloads_by_type,
config: self.config.unwrap_or_default(),
}
}
@@ -328,363 +330,466 @@ impl CompressionPipelineBuilder {
#[cfg(test)]
mod tests {
use super::*;
- use crate::signals::{
- ImportanceCategory, ImportanceContext, ImportanceSignal, LineImportanceDetector,
- };
- use crate::transforms::pipeline::traits::{
- CompressionContext, LosslessTransform, LossyTransform, TransformError, TransformResult,
+ use crate::ccr::InMemoryCcrStore;
+ use crate::transforms::pipeline::offloads::{
+ DiffNoise, DiffOffload, LogOffload, SearchOffload,
};
- use crate::transforms::pipeline::{
- JsonMinifier, LineImportanceFilter, LineImportanceFilterConfig,
- };
-
- // ── Test helpers ─────────────────────────────────────────────────
-
- /// Trivial lossless transform that always saves exactly 1 byte
- /// (drops a trailing newline if present, otherwise reports
- /// bytes_saved == 0).
- struct TrivialLossless;
- impl LosslessTransform for TrivialLossless {
- fn name(&self) -> &'static str {
- "trivial_lossless"
- }
- fn applies_to(&self) -> &[ContentType] {
- &[ContentType::PlainText]
- }
- fn apply(&self, content: &str) -> Result<TransformResult, TransformError> {
- let trimmed = content.trim_end_matches('\n').to_string();
- Ok(TransformResult::from_lengths(content.len(), trimmed, true))
- }
- }
-
- /// Lossless transform that always errors. Used to verify the
- /// orchestrator continues past failures.
- struct AlwaysErrors;
- impl LosslessTransform for AlwaysErrors {
- fn name(&self) -> &'static str {
- "always_errors"
- }
- fn applies_to(&self) -> &[ContentType] {
- &[ContentType::PlainText]
- }
- fn apply(&self, _content: &str) -> Result<TransformResult, TransformError> {
- Err(TransformError::invalid_input("always_errors", "by design"))
- }
- }
-
- /// Stub detector for the LineImportanceFilter integration tests.
- struct StubDetector;
- impl LineImportanceDetector for StubDetector {
- fn score(&self, line: &str, _ctx: ImportanceContext) -> ImportanceSignal {
- if line.contains("KEEP") {
- ImportanceSignal::matched(ImportanceCategory::Importance, 0.9, 0.9)
- } else {
- ImportanceSignal::neutral()
- }
- }
- }
+ use crate::transforms::pipeline::reformats::{JsonMinifier, LogTemplate};
+ use crate::transforms::pipeline::traits::{OffloadOutput, ReformatOutput};
fn ctx() -> CompressionContext {
CompressionContext::default()
}
- // ── Empty-pipeline tests ─────────────────────────────────────────
+ fn store() -> InMemoryCcrStore {
+ InMemoryCcrStore::new()
+ }
+
+ // ── Empty pipeline ────────────────────────────────────────────────
#[test]
- fn empty_pipeline_passes_input_through_unchanged() {
+ fn empty_pipeline_passes_input_through() {
let p = CompressionPipeline::builder().build();
- let input = "hello world";
- let r = p.run(input, ContentType::PlainText, &ctx());
- assert_eq!(r.output, input);
+ let s = store();
+ let r = p.run("hello world", ContentType::PlainText, &ctx(), &s);
+ assert_eq!(r.output, "hello world");
assert_eq!(r.bytes_saved, 0);
assert!(r.steps_applied.is_empty());
- assert!(r.structure_preserved);
- assert!(r.reversible_via.is_none());
+ assert!(r.cache_keys.is_empty());
+ assert_eq!(s.len(), 0);
}
#[test]
- fn pipeline_with_no_applicable_transforms_passes_through() {
- // Register a JSON-only transform; run on plain text.
+ fn empty_input_returns_empty_output() {
let p = CompressionPipeline::builder()
- .with_lossless(JsonMinifier)
+ .with_reformat(JsonMinifier)
.build();
- let r = p.run("not json", ContentType::PlainText, &ctx());
- assert_eq!(r.output, "not json");
+ let s = store();
+ let r = p.run("", ContentType::JsonArray, &ctx(), &s);
+ assert!(r.output.is_empty());
assert!(r.steps_applied.is_empty());
}
- // ── Lossless phase ───────────────────────────────────────────────
+ // ── Reformat phase ────────────────────────────────────────────────
#[test]
- fn lossless_runs_when_applicable() {
+ fn reformat_runs_when_applicable() {
let p = CompressionPipeline::builder()
- .with_lossless(JsonMinifier)
+ .with_reformat(JsonMinifier)
.build();
- let pretty = r#"{
- "a": 1,
- "b": [1, 2, 3]
-}"#;
- let r = p.run(pretty, ContentType::JsonArray, &ctx());
+ let s = store();
+ let pretty = "{\n \"a\": 1,\n \"b\": 2\n}";
+ let r = p.run(pretty, ContentType::JsonArray, &ctx(), &s);
assert!(r.bytes_saved > 0);
assert_eq!(r.steps_applied, vec!["json_minifier".to_string()]);
- assert!(r.structure_preserved);
assert!(r.output.len() < pretty.len());
+ assert!(r.cache_keys.is_empty());
}
#[test]
- fn lossless_rejects_below_min_savings_ratio() {
- // Compact JSON minifies to itself → bytes_saved == 0 → rejected.
+ fn reformat_skipped_for_unrelated_content_type() {
let p = CompressionPipeline::builder()
- .with_lossless(JsonMinifier)
+ .with_reformat(JsonMinifier)
.build();
- let r = p.run(r#"{"a":1}"#, ContentType::JsonArray, &ctx());
- assert_eq!(r.bytes_saved, 0);
+ let s = store();
+ let r = p.run("not json", ContentType::PlainText, &ctx(), &s);
+ assert_eq!(r.output, "not json");
assert!(r.steps_applied.is_empty());
}
+ // ── Offload phase: bloat-gated ─────────────────────────────────────
+
+ /// A test-only offload that always succeeds. Its bloat estimator
+ /// returns whatever score the caller wires in.
+ struct TestOffload {
+ score: f32,
+ applies_to: Vec<ContentType>,
+ confidence_score: f32,
+ name: &'static str,
+ }
+ impl OffloadTransform for TestOffload {
+ fn name(&self) -> &'static str {
+ self.name
+ }
+ fn applies_to(&self) -> &[ContentType] {
+ &self.applies_to
+ }
+ fn estimate_bloat(&self, _content: &str) -> f32 {
+ self.score
+ }
+ fn apply(
+ &self,
+ content: &str,
+ _ctx: &CompressionContext,
+ store: &dyn CcrStore,
+ ) -> Result<OffloadOutput, TransformError> {
+ // Always halve; emit a cache_key derived from name.
+ let half = &content[..content.len() / 2];
+ let key = format!("test_{}_key", self.name);
+ store.put(&key, content);
+ Ok(OffloadOutput::from_lengths(
+ content.len(),
+ half.to_string(),
+ key,
+ ))
+ }
+ fn confidence(&self) -> f32 {
+ self.confidence_score
+ }
+ }
+
+ fn test_offload(name: &'static str, score: f32) -> TestOffload {
+ TestOffload {
+ score,
+ applies_to: vec![ContentType::PlainText],
+ confidence_score: 0.5,
+ name,
+ }
+ }
+
#[test]
- fn lossless_continues_past_error() {
+ fn offload_runs_when_bloat_above_threshold() {
let p = CompressionPipeline::builder()
- .with_lossless(AlwaysErrors)
- .with_lossless(TrivialLossless)
- .with_config(PipelineConfig {
- min_savings_ratio: 0.0, // accept any savings
- lossless_target_ratio: 0.0,
- })
+ .with_offload(test_offload("high_bloat", 0.9))
.build();
- let r = p.run("hello\n", ContentType::PlainText, &ctx());
- // Both transforms run; first errors and is recorded as skip,
- // second saves 1 byte. Without the per-error-recovery loop the
- // pipeline would short-circuit.
- assert_eq!(r.steps_applied, vec!["trivial_lossless".to_string()]);
- assert_eq!(r.bytes_saved, 1);
+ let s = store();
+ let r = p.run("x".repeat(100).as_str(), ContentType::PlainText, &ctx(), &s);
+ assert_eq!(r.steps_applied, vec!["high_bloat".to_string()]);
+ assert_eq!(r.cache_keys.len(), 1);
+ assert!(s.get(&r.cache_keys[0]).is_some());
}
#[test]
- fn lossless_stops_once_target_ratio_reached() {
- struct HalvesContent;
- impl LosslessTransform for HalvesContent {
- fn name(&self) -> &'static str {
- "halver"
- }
- fn applies_to(&self) -> &[ContentType] {
- &[ContentType::PlainText]
- }
- fn apply(&self, content: &str) -> Result<TransformResult, TransformError> {
- let half = &content[..content.len() / 2];
- Ok(TransformResult::from_lengths(
- content.len(),
- half.to_string(),
- true,
- ))
- }
- }
- // First halver: 100 → 50 bytes (ratio 0.5 — at the gate).
- // Second halver: should NOT run because ratio is now <= 0.5.
+ fn offload_skipped_when_bloat_below_threshold_and_reformat_was_enough() {
+ // No reformats, so reformat_ratio = 1.0, which IS above the
+ // default fallback ratio of 0.85. The test ensures even in
+ // that case we skip when score is too low.
let p = CompressionPipeline::builder()
- .with_lossless(HalvesContent)
- .with_lossless(HalvesContent)
+ .with_offload(test_offload("low_bloat", 0.0))
.build();
- let input = "x".repeat(100);
- let r = p.run(&input, ContentType::PlainText, &ctx());
- assert_eq!(r.steps_applied.len(), 1);
- assert_eq!(r.output.len(), 50);
+ let s = store();
+ let r = p.run("x".repeat(100).as_str(), ContentType::PlainText, &ctx(), &s);
+ assert!(
+ r.steps_applied.is_empty(),
+ "score 0.0 should never run: {:?}",
+ r.steps_applied
+ );
+ assert_eq!(s.len(), 0);
}
- // ── Lossy phase ──────────────────────────────────────────────────
+ /// A reformat that always halves input — used to drive
+ /// reformat_ratio below the fallback threshold.
+ struct AlwaysHalf;
+ impl ReformatTransform for AlwaysHalf {
+ fn name(&self) -> &'static str {
+ "always_half"
+ }
+ fn applies_to(&self) -> &[ContentType] {
+ &[ContentType::PlainText]
+ }
+ fn apply(&self, content: &str) -> Result<ReformatOutput, TransformError> {
+ let half = &content[..content.len() / 2];
+ Ok(ReformatOutput::from_lengths(
+ content.len(),
+ half.to_string(),
+ ))
+ }
+ }
#[test]
- fn lossy_runs_after_lossless() {
- let lif = LineImportanceFilter::new(Box::new(StubDetector)).with_config(
- LineImportanceFilterConfig {
- min_priority: 0.5,
- keep_first: 1,
- keep_last: 1,
- context: ImportanceContext::Text,
- },
- );
+ fn offload_skipped_when_reformat_already_sufficient_and_score_below_threshold() {
+ // Reformat halves input → ratio = 0.5, well below
+ // offload_fallback_ratio=0.85. With score 0.3 (below
+ // bloat_threshold=0.5) and "reformat sufficient", we skip.
let p = CompressionPipeline::builder()
- .with_lossless(JsonMinifier) // doesn't apply to plain text
- .with_lossy(lif)
+ .with_reformat(AlwaysHalf)
+ .with_offload(test_offload("midway", 0.3))
.build();
- let input = (0..20)
- .map(|i| {
- if i == 10 {
- "KEEP me".into()
- } else {
- format!("noise {i}")
- }
- })
- .collect::<Vec<_>>()
- .join("\n");
- let r = p.run(&input, ContentType::PlainText, &ctx());
- assert!(r.bytes_saved > 0);
- assert_eq!(r.steps_applied, vec!["line_importance_filter".to_string()]);
- assert!(!r.structure_preserved);
- assert!(r.output.contains("KEEP me"));
+ let s = store();
+ let r = p.run("x".repeat(100).as_str(), ContentType::PlainText, &ctx(), &s);
+ assert_eq!(r.steps_applied, vec!["always_half".to_string()]);
+ assert!(r.cache_keys.is_empty());
}
#[test]
- fn lossy_after_lossless_compounds_savings() {
- // Run JsonMinifier on JsonArray (saves whitespace), then a
- // hypothetical lossy on top. We just verify the orchestrator
- // accumulates bytes_saved across phases.
- struct JsonAsTextLossy;
- impl LossyTransform for JsonAsTextLossy {
- fn name(&self) -> &'static str {
- "json_truncator"
- }
- fn applies_to(&self) -> &[ContentType] {
- &[ContentType::JsonArray]
- }
- fn apply(
- &self,
- content: &str,
- _ctx: &CompressionContext,
- ) -> Result<TransformResult, TransformError> {
- let cut = content.len() / 2;
- Ok(TransformResult {
- output: format!("{}…", &content[..cut]),
- bytes_saved: content.len().saturating_sub(cut + 3),
- structure_preserved: false,
- reversible_via: None,
- })
- }
- fn confidence(&self) -> f32 {
- 0.4
- }
- }
+ fn offload_runs_as_fallback_when_reformat_underwhelms() {
+ // Reformat barely helps (no AlwaysHalf, score for offload
+ // = 0.2, BELOW bloat_threshold=0.5). reformat_ratio = 1.0,
+ // ABOVE offload_fallback_ratio=0.85, AND score > 0 → offload
+ // runs as a fallback.
let p = CompressionPipeline::builder()
- .with_lossless(JsonMinifier)
- .with_lossy(JsonAsTextLossy)
+ .with_offload(test_offload("fallback", 0.2))
.build();
- let pretty = r#"{
- "users": [{"id": 1}, {"id": 2}, {"id": 3}, {"id": 4}]
-}"#;
- let r = p.run(pretty, ContentType::JsonArray, &ctx());
+ let s = store();
+ let r = p.run("x".repeat(100).as_str(), ContentType::PlainText, &ctx(), &s);
+ assert_eq!(r.steps_applied, vec!["fallback".to_string()]);
+ }
+
+ #[test]
+ fn offload_above_threshold_runs_even_when_reformat_was_great() {
+ // Reformat halves (ratio=0.5, "sufficient"), but score=0.9 forces
+ // the offload anyway — high bloat means CCR still pays off.
+ let p = CompressionPipeline::builder()
+ .with_reformat(AlwaysHalf)
+ .with_offload(test_offload("forced", 0.9))
+ .build();
+ let s = store();
+ let r = p.run("x".repeat(100).as_str(), ContentType::PlainText, &ctx(), &s);
assert_eq!(
r.steps_applied,
- vec!["json_minifier".to_string(), "json_truncator".to_string()]
+ vec!["always_half".to_string(), "forced".to_string()]
);
- assert!(!r.structure_preserved);
- assert!(r.bytes_saved > 0);
+ assert_eq!(r.cache_keys.len(), 1);
+ }
+
+ // ── Bloat-estimation parallelism (smoke) ───────────────────────────
+
+ #[test]
+ fn parallel_bloat_estimation_returns_correct_scores_per_offload() {
+ // Two offloads, each with a distinct score. The orchestrator
+ // must pair score-with-offload correctly even when running them
+ // in parallel.
+ let p = CompressionPipeline::builder()
+ .with_offload(test_offload("alpha", 0.9))
+ .with_offload(test_offload("beta", 0.0))
+ .build();
+ let s = store();
+ let r = p.run("x".repeat(100).as_str(), ContentType::PlainText, &ctx(), &s);
+ // Only "alpha" should run (above threshold). "beta" with 0.0
+ // should not run even via fallback (score must be > 0).
+ assert_eq!(r.steps_applied, vec!["alpha".to_string()]);
}
- // ── Structure-preservation flag ─────────────────────────────────
+ // ── End-to-end with real offloads ──────────────────────────────────
#[test]
- fn structure_preserved_stays_true_when_only_lossless_runs() {
+ fn end_to_end_log_offload_compresses_repetitive_log() {
+ let cfg = PipelineConfig::default();
let p = CompressionPipeline::builder()
- .with_lossless(JsonMinifier)
+ .with_offload(LogOffload::new(cfg.bloat.log))
+ .with_config(cfg)
.build();
- let r = p.run(r#"{ "a": 1, "b": 2 }"#, ContentType::JsonArray, &ctx());
- assert!(r.structure_preserved);
+ let s = store();
+ let line = "INFO: heartbeat\n";
+ let log: String = line.repeat(200);
+ let r = p.run(&log, ContentType::BuildOutput, &ctx(), &s);
+ assert_eq!(r.steps_applied, vec!["log_offload".to_string()]);
+ assert_eq!(r.cache_keys.len(), 1);
+ assert_eq!(s.get(&r.cache_keys[0]).as_deref(), Some(log.as_str()));
+ assert!(r.bytes_saved > 0);
}
#[test]
- fn structure_preserved_flips_when_lossy_runs() {
- let lif = LineImportanceFilter::new(Box::new(StubDetector));
+ fn end_to_end_diff_offload_compresses_context_heavy_diff() {
+ let cfg = PipelineConfig::default();
let p = CompressionPipeline::builder()
- .with_lossy(lif)
- .with_config(PipelineConfig {
- min_savings_ratio: 0.0,
- lossless_target_ratio: 0.5,
- })
+ .with_offload(DiffOffload::new(cfg.bloat.diff))
+ .with_config(cfg)
.build();
- let many = (0..30)
- .map(|i| format!("plain line {i}"))
+ let s = store();
+ // Build a context-heavy diff: 100 context lines, 5 changes.
+ let mut diff = String::new();
+ diff.push_str(
+ "diff --git a/x.txt b/x.txt\n--- a/x.txt\n+++ b/x.txt\n@@ -1,105 +1,105 @@\n",
+ );
+ for _ in 0..100 {
+ diff.push_str(" context line\n");
+ }
+ for c in 0..5 {
+ diff.push_str(&format!("-old {c}\n"));
+ diff.push_str(&format!("+new {c}\n"));
+ }
+ let r = p.run(&diff, ContentType::GitDiff, &ctx(), &s);
+ assert_eq!(r.steps_applied, vec!["diff_offload".to_string()]);
+ assert_eq!(r.cache_keys.len(), 1);
+ assert!(s.get(&r.cache_keys[0]).is_some());
+ }
+
+ #[test]
+ fn end_to_end_search_offload_compresses_clustered_matches() {
+ let cfg = PipelineConfig::default();
+ let p = CompressionPipeline::builder()
+ .with_offload(SearchOffload::new(cfg.bloat.search))
+ .with_config(cfg)
+ .build();
+ let s = store();
+ let input: String = (0..100)
+ .map(|i| format!("utils.py:{}:def fn_{i}", i + 1))
.collect::<Vec<_>>()
.join("\n");
- let r = p.run(&many, ContentType::PlainText, &ctx());
- if !r.steps_applied.is_empty() {
- assert!(!r.structure_preserved);
- }
+ let r = p.run(&input, ContentType::SearchResults, &ctx(), &s);
+ assert_eq!(r.steps_applied, vec!["search_offload".to_string()]);
+ assert_eq!(r.cache_keys.len(), 1);
+ assert_eq!(s.get(&r.cache_keys[0]).as_deref(), Some(input.as_str()));
}
- // ── Acceptance gate edge cases ───────────────────────────────────
+ // ── Failure handling ───────────────────────────────────────────────
+
+ /// An offload whose `apply` always errors with `Internal`. Used to
+ /// verify the orchestrator doesn't propagate the panic and surfaces
+ /// it at WARN.
+ struct AlwaysInternalError;
+ impl OffloadTransform for AlwaysInternalError {
+ fn name(&self) -> &'static str {
+ "always_internal_err"
+ }
+ fn applies_to(&self) -> &[ContentType] {
+ &[ContentType::PlainText]
+ }
+ fn estimate_bloat(&self, _content: &str) -> f32 {
+ 0.9
+ }
+ fn apply(
+ &self,
+ _content: &str,
+ _ctx: &CompressionContext,
+ _store: &dyn CcrStore,
+ ) -> Result<OffloadOutput, TransformError> {
+ Err(TransformError::internal("always_internal_err", "by design"))
+ }
+ fn confidence(&self) -> f32 {
+ 0.5
+ }
+ }
#[test]
- fn is_acceptable_handles_zero_lengths() {
- let p = CompressionPipeline::builder().build();
- assert!(!p.is_acceptable(0, 100), "no savings → reject");
- assert!(!p.is_acceptable(50, 0), "current_len 0 → reject");
+ fn offload_internal_error_does_not_panic_and_yields_input() {
+ let p = CompressionPipeline::builder()
+ .with_offload(AlwaysInternalError)
+ .build();
+ let s = store();
+ let r = p.run("x".repeat(100).as_str(), ContentType::PlainText, &ctx(), &s);
+ assert!(r.steps_applied.is_empty());
+ assert_eq!(r.output.len(), 100);
+ assert_eq!(s.len(), 0);
}
+ // ── Builder behavior ───────────────────────────────────────────────
+
#[test]
- fn is_acceptable_uses_min_savings_ratio() {
+ fn builder_dispatches_by_applies_to() {
let p = CompressionPipeline::builder()
- .with_config(PipelineConfig {
- min_savings_ratio: 0.10,
- lossless_target_ratio: 0.5,
- })
+ .with_reformat(JsonMinifier)
+ .with_offload(LogOffload::new(PipelineConfig::default().bloat.log))
.build();
- assert!(!p.is_acceptable(5, 100), "5% < 10% threshold → reject");
- assert!(p.is_acceptable(15, 100), "15% > 10% threshold → accept");
+ assert_eq!(p.reformats_by_type[&ContentType::JsonArray].len(), 1);
+ assert_eq!(p.offloads_by_type[&ContentType::BuildOutput].len(), 1);
+ assert!(!p.reformats_by_type.contains_key(&ContentType::BuildOutput));
+ assert!(!p.offloads_by_type.contains_key(&ContentType::JsonArray));
}
#[test]
- fn should_keep_running_lossless_handles_zero_original() {
- let p = CompressionPipeline::builder().build();
- assert!(!p.should_keep_running_lossless(0, 0));
+ fn builder_preserves_registration_order_for_offloads() {
+ // Registration order is execution order — important when two
+ // offloads are eligible for the same content type and the first
+ // one already trims the buffer.
+ let p = CompressionPipeline::builder()
+ .with_offload(test_offload("first", 0.9))
+ .with_offload(test_offload("second", 0.9))
+ .build();
+ let s = store();
+ let r = p.run("x".repeat(100).as_str(), ContentType::PlainText, &ctx(), &s);
+ assert_eq!(
+ r.steps_applied,
+ vec!["first".to_string(), "second".to_string()]
+ );
}
- // ── Builder-side properties ──────────────────────────────────────
+ // ── End-to-end with new transforms ────────────────────────────────
#[test]
- fn builder_dispatches_by_applies_to() {
+ fn end_to_end_log_template_collapses_then_log_offload_can_run() {
+ // LogTemplate runs first (lossless reformat), then LogOffload
+ // sees the collapsed output and may further drop low-priority
+ // lines. Both should appear in steps_applied if both fire.
+ let cfg = PipelineConfig::default();
let p = CompressionPipeline::builder()
- .with_lossless(JsonMinifier)
- .with_lossless(TrivialLossless)
+ .with_reformat(LogTemplate::new(cfg.reformat.log_template))
+ .with_offload(LogOffload::new(cfg.bloat.log))
+ .with_config(cfg)
.build();
- // JsonMinifier registered for JsonArray; TrivialLossless for
- // PlainText. Each should be the only one available for its
- // own type.
- assert_eq!(p.lossless_by_type[&ContentType::JsonArray].len(), 1);
- assert_eq!(p.lossless_by_type[&ContentType::PlainText].len(), 1);
+ let s = store();
+ // 200 INFO lines, all same template — LogTemplate compresses
+ // hugely.
+ let mut log = String::new();
+ for i in 0..200 {
+ log.push_str(&format!(
+ "2025-01-15T12:34:{:02} INFO worker-{} processing job {}\n",
+ i % 60,
+ i,
+ 100 + i
+ ));
+ }
+ let r = p.run(&log, ContentType::BuildOutput, &ctx(), &s);
+ assert!(r.bytes_saved > 0);
+ assert!(
+ r.steps_applied.iter().any(|n| n == "log_template"),
+ "log_template must run first"
+ );
+ // Output is shorter than input. Token-level survival isn't
+ // asserted here — LogOffload may further drop bytes (including
+ // the template header) on its own gating logic. Lossless
+ // round-trip is asserted in the LogTemplate-alone test below.
+ assert!(r.output.len() < log.len());
}
#[test]
- fn builder_preserves_registration_order() {
- struct A;
- impl LosslessTransform for A {
- fn name(&self) -> &'static str {
- "a"
- }
- fn applies_to(&self) -> &[ContentType] {
- &[ContentType::PlainText]
- }
- fn apply(&self, content: &str) -> Result<TransformResult, TransformError> {
- Ok(TransformResult::from_lengths(
- content.len(),
- content.into(),
- true,
- ))
- }
- }
- struct B;
- impl LosslessTransform for B {
- fn name(&self) -> &'static str {
- "b"
- }
- fn applies_to(&self) -> &[ContentType] {
- &[ContentType::PlainText]
- }
- fn apply(&self, content: &str) -> Result<TransformResult, TransformError> {
- Ok(TransformResult::from_lengths(
- content.len(),
- content.into(),
- true,
- ))
- }
+ fn end_to_end_diff_noise_drops_lockfile_then_diff_offload_handles_rest() {
+ let cfg = PipelineConfig::default();
+ let p = CompressionPipeline::builder()
+ .with_offload(DiffNoise::new(cfg.offload.diff_noise.clone()))
+ .with_offload(DiffOffload::new(cfg.bloat.diff))
+ .with_config(cfg)
+ .build();
+ let s = store();
+
+ // Build: huge Cargo.lock churn + a small real change in src/main.rs.
+ let mut diff = String::new();
+ diff.push_str("diff --git a/Cargo.lock b/Cargo.lock\n");
+ diff.push_str("--- a/Cargo.lock\n+++ b/Cargo.lock\n@@ -1,400 +1,400 @@\n");
+ for i in 0..200 {
+ diff.push_str(&format!("-old{i}\n"));
+ diff.push_str(&format!("+new{i}\n"));
}
+ diff.push_str("diff --git a/src/main.rs b/src/main.rs\n");
+ diff.push_str("--- a/src/main.rs\n+++ b/src/main.rs\n@@ -1,3 +1,3 @@\n");
+ diff.push_str("-let x = 1;\n");
+ diff.push_str("+let x = 2;\n");
+ let r = p.run(&diff, ContentType::GitDiff, &ctx(), &s);
+
+ assert!(r.bytes_saved > 0);
+ assert!(
+ r.steps_applied.iter().any(|n| n == "diff_noise"),
+ "diff_noise should fire on lockfile-dominated diff: {:?}",
+ r.steps_applied
+ );
+ assert!(r.output.contains("[diff_noise: lockfile hunks dropped"));
+ assert!(r.output.contains("let x = 2;"), "real change must survive");
+ assert!(!r.cache_keys.is_empty());
+ }
+
+ #[test]
+ fn end_to_end_real_log_with_template_run_collapses_then_passes_through() {
+ // Just LogTemplate (no LogOffload) — verify reformat alone
+ // gives meaningful savings on a templated log.
+ let cfg = PipelineConfig::default();
let p = CompressionPipeline::builder()
- .with_lossless(A)
- .with_lossless(B)
+ .with_reformat(LogTemplate::new(cfg.reformat.log_template))
+ .with_config(cfg)
.build();
- let order: Vec<&str> = p.lossless_by_type[&ContentType::PlainText]
- .iter()
- .map(|t| t.name())
- .collect();
- assert_eq!(order, vec!["a", "b"]);
+ let s = store();
+ let mut log = String::new();
+ for i in 0..100 {
+ log.push_str(&format!(
+ "[2025-01-15 12:00:{:02}] INFO Connecting to db-{} on port 5432\n",
+ i % 60,
+ i % 8
+ ));
+ }
+ let r = p.run(&log, ContentType::BuildOutput, &ctx(), &s);
+ assert_eq!(r.steps_applied, vec!["log_template".to_string()]);
+ assert!(r.cache_keys.is_empty(), "reformat should not produce keys");
+ assert!(r.bytes_saved > 0);
+ assert!(r.output.contains("[Template T1:"));
}
}
diff --git a/crates/headroom-core/src/transforms/pipeline/reformats/json_minifier.rs b/crates/headroom-core/src/transforms/pipeline/reformats/json_minifier.rs
new file mode 100644
index 000000000..8989add80
--- /dev/null
+++ b/crates/headroom-core/src/transforms/pipeline/reformats/json_minifier.rs
@@ -0,0 +1,175 @@
+//! `JsonMinifier` — a [`ReformatTransform`] that strips insignificant
+//! whitespace from JSON via `serde_json` round-trip.
+//!
+//! Lossless by construction: parse to `serde_json::Value`, re-emit
+//! compactly, return whichever is shorter. No CCR involvement —
+//! reformat transforms never need it.
+//!
+//! [`ReformatTransform`]: crate::transforms::pipeline::traits::ReformatTransform
+
+use crate::transforms::pipeline::traits::{ReformatOutput, ReformatTransform, TransformError};
+use crate::transforms::ContentType;
+
+const NAME: &str = "json_minifier";
+
+/// Whitespace-stripping JSON minifier. Handles both arrays and objects
+/// since `JsonObject` and `JsonArray` are both registered content types.
+#[derive(Debug, Default, Clone, Copy)]
+pub struct JsonMinifier;
+
+impl ReformatTransform for JsonMinifier {
+ fn name(&self) -> &'static str {
+ NAME
+ }
+
+ fn applies_to(&self) -> &[ContentType] {
+ // The detector folds both arrays and objects into `JsonArray`
+ // (the umbrella tag for "JSON the structural layer recognized");
+ // the minifier itself doesn't care about top-level shape.
+ &[ContentType::JsonArray]
+ }
+
+ fn apply(&self, content: &str) -> Result<ReformatOutput, TransformError> {
+ let trimmed = content.trim();
+ if trimmed.is_empty() {
+ return Err(TransformError::skipped(NAME, "empty input"));
+ }
+
+ let value: serde_json::Value = serde_json::from_str(trimmed)
+ .map_err(|e| TransformError::invalid_input(NAME, e.to_string()))?;
+
+ let minified = serde_json::to_string(&value)
+ .map_err(|e| TransformError::internal(NAME, e.to_string()))?;
+
+ // Defensive: if minification grew the byte count (e.g. caller
+ // already passed compact JSON, or escaping rules added bytes),
+ // hand the original back so we never inflate the wire output.
+ if minified.len() >= content.len() {
+ return Ok(ReformatOutput::from_lengths(
+ content.len(),
+ content.to_string(),
+ ));
+ }
+
+ Ok(ReformatOutput::from_lengths(content.len(), minified))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn name_and_applies_to() {
+ let m = JsonMinifier;
+ assert_eq!(m.name(), "json_minifier");
+ assert_eq!(m.applies_to(), &[ContentType::JsonArray]);
+ }
+
+ #[test]
+ fn pretty_object_minifies() {
+ let pretty = "{\n \"a\": 1,\n \"b\": 2\n}";
+ let r = JsonMinifier.apply(pretty).expect("parses");
+ assert_eq!(r.output, r#"{"a":1,"b":2}"#);
+ assert!(r.bytes_saved > 0);
+ }
+
+ #[test]
+ fn pretty_array_minifies() {
+ let pretty = "[\n 1,\n 2,\n 3\n]";
+ let r = JsonMinifier.apply(pretty).expect("parses");
+ assert_eq!(r.output, "[1,2,3]");
+ assert!(r.bytes_saved > 0);
+ }
+
+ #[test]
+ fn already_compact_yields_zero_savings() {
+ let compact = r#"{"a":1,"b":2}"#;
+ let r = JsonMinifier.apply(compact).expect("parses");
+ assert_eq!(r.output, compact);
+ assert_eq!(r.bytes_saved, 0);
+ }
+
+ #[test]
+ fn invalid_json_errors_with_invalid_input() {
+ let bad = "{not: valid";
+ let err = JsonMinifier.apply(bad).expect_err("must fail");
+ match err {
+ TransformError::InvalidInput { transform, .. } => {
+ assert_eq!(transform, "json_minifier")
+ }
+ _ => panic!("expected InvalidInput, got {err:?}"),
+ }
+ }
+
+ #[test]
+ fn empty_input_skipped() {
+ let err = JsonMinifier.apply("").expect_err("empty must skip");
+ match err {
+ TransformError::Skipped { transform, .. } => assert_eq!(transform, "json_minifier"),
+ _ => panic!("expected Skipped, got {err:?}"),
+ }
+ }
+
+ #[test]
+ fn whitespace_only_skipped() {
+ let err = JsonMinifier
+ .apply(" \n\t ")
+ .expect_err("ws-only must skip");
+ match err {
+ TransformError::Skipped { .. } => {}
+ _ => panic!("expected Skipped"),
+ }
+ }
+
+ #[test]
+ fn nested_structure_round_trips_semantically() {
+ let pretty = r#"
+ {
+ "users": [
+ {"id": 1, "name": "alice", "active": true},
+ {"id": 2, "name": "bob", "active": false}
+ ],
+ "count": 2
+ }
+ "#;
+ let r = JsonMinifier.apply(pretty).expect("parses");
+ // Re-parse the output and verify structural equivalence.
+ let original_val: serde_json::Value = serde_json::from_str(pretty).unwrap();
+ let output_val: serde_json::Value = serde_json::from_str(&r.output).unwrap();
+ assert_eq!(original_val, output_val);
+ assert!(r.bytes_saved > 0);
+ }
+
+ #[test]
+ fn minifier_never_grows_output() {
+ // Defensive contract: even if a caller hands us compact JSON
+ // with embedded escaped strings that re-emit longer, we hand
+ // the original back rather than inflating.
+ let inputs = [
+ r#"{}"#,
+ r#"[]"#,
+ r#"null"#,
+ r#"42"#,
+ r#""string""#,
+ r#"{"k":"value with spaces"}"#,
+ ];
+ for input in inputs {
+ let r = JsonMinifier.apply(input).expect("valid");
+ assert!(
+ r.output.len() <= input.len(),
+ "minifier grew output for {input:?}: {} -> {}",
+ input.len(),
+ r.output.len()
+ );
+ }
+ }
+
+ #[test]
+ fn unicode_round_trips() {
+ let pretty = r#"{ "msg": "héllo 🌍 wörld" }"#;
+ let r = JsonMinifier.apply(pretty).expect("parses");
+ let v: serde_json::Value = serde_json::from_str(&r.output).unwrap();
+ assert_eq!(v["msg"], "héllo 🌍 wörld");
+ }
+}
diff --git a/crates/headroom-core/src/transforms/pipeline/reformats/log_template.rs b/crates/headroom-core/src/transforms/pipeline/reformats/log_template.rs
new file mode 100644
index 000000000..9e668abd9
--- /dev/null
+++ b/crates/headroom-core/src/transforms/pipeline/reformats/log_template.rs
@@ -0,0 +1,545 @@
+//! `LogTemplate` — order-preserving log-template miner (Drain-inspired).
+//!
+//! # Why this is a Reformat (and not an Offload)
+//!
+//! Logs are bloaty when the same template repeats with only timestamps,
+//! IDs, IPs, paths varying:
+//!
+//! ```text
+//! 2025-01-15T12:34:56 INFO worker-1 processing job 42
+//! 2025-01-15T12:34:57 INFO worker-2 processing job 43
+//! ... 798 more lines like this ...
+//! ```
+//!
+//! The information content is the *template* + the *variants*, not the
+//! repeated constant tokens. We collapse runs of consecutive same-
+//! template lines into one template header plus a compact variant
+//! table:
+//!
+//! ```text
+//! [Template T1: <TS> INFO worker-<*> processing job <*>] (800 occurrences)
+//! 12:34:56 1 42
+//! 12:34:57 2 43
+//! ...
+//! ```
+//!
+//! Every original line is reconstructible from `template + variants`,
+//! so this is **lossless** — no CCR retrieval needed. The win is the
+//! template prefix (often 30+ chars) emitted once instead of N times.
+//!
+//! Order is preserved: only *consecutive* runs collapse, so the
+//! temporal flow of the log stays intact for the LLM.
+//!
+//! # Algorithm (simplified Drain)
+//!
+//! 1. Walk lines in order. For each line, split on whitespace into
+//! tokens.
+//! 2. Open or extend a "run" of consecutive lines that share the same
+//! `(token_count, leading_token)` shape AND match the run's
+//! accumulated template at ≥ `similarity_threshold` of positions.
+//! 3. When a line breaks the run, flush the run:
+//! - If `run.len() ≥ min_run` AND the template has ≥
+//! `min_constant_tokens` constant positions, emit a
+//! `[Template T<n>: ...]` block + a variant table.
+//! - Otherwise emit the lines verbatim.
+//! 4. End-of-input flushes the final run.
+//!
+//! Cost: O(n × tokens_per_line). No regex. The token splitter walks
+//! ASCII whitespace; UTF-8 multi-byte chars in non-whitespace
+//! positions are passed through unchanged.
+//!
+//! # Conservatism for accuracy
+//!
+//! Defaults bias toward "emit verbatim if unsure":
+//! - `min_run = 3` — needs 3+ in a row before collapsing.
+//! - `similarity_threshold = 0.4` — Drain's published default; 40%
+//! positional match required (catches `<TS> INFO worker-<N>` style
+//! lines where 3 of 6 tokens are constants).
+//! - `min_constant_tokens = 2` — at least 2 anchor tokens, otherwise
+//! the "template" is just `<*> <*> <*>` and carries no signal.
+//!
+//! These are conservative on purpose. The pipeline is on the hot path
+//! of every Claude/Codex tool-call response; an over-aggressive miner
+//! that collapses heterogeneous lines would leak signal into the
+//! variant table where the LLM might miss it.
+
+use std::fmt::Write;
+
+use crate::transforms::pipeline::config::LogTemplateConfig;
+use crate::transforms::pipeline::traits::{ReformatOutput, ReformatTransform, TransformError};
+use crate::transforms::ContentType;
+
+const NAME: &str = "log_template";
+/// Sentinel for variable positions in template strings.
+const WILDCARD: &str = "<*>";
+
+pub struct LogTemplate {
+ config: LogTemplateConfig,
+}
+
+impl LogTemplate {
+ pub fn new(config: LogTemplateConfig) -> Self {
+ Self { config }
+ }
+}
+
+impl ReformatTransform for LogTemplate {
+ fn name(&self) -> &'static str {
+ NAME
+ }
+
+ fn applies_to(&self) -> &[ContentType] {
+ &[ContentType::BuildOutput]
+ }
+
+ fn apply(&self, content: &str) -> Result<ReformatOutput, TransformError> {
+ if content.is_empty() {
+ return Err(TransformError::skipped(NAME, "empty input"));
+ }
+ let lines: Vec<&str> = content.lines().collect();
+ if lines.len() < self.config.min_lines {
+ return Err(TransformError::skipped(NAME, "input below min_lines"));
+ }
+
+ let tokenized: Vec<Vec<&str>> = lines.iter().map(|l| tokenize(l)).collect();
+
+ // Walk lines, group into runs. A `Run` holds the original line
+ // indices + an accumulated "template" (per-position tokens that
+ // have stayed constant across the run; a `None` slot means
+ // "this position varies").
+ let mut output = String::with_capacity(content.len());
+ let mut next_template_id = 1usize;
+ let mut run: Option<Run> = None;
+
+ for (i, tokens) in tokenized.iter().enumerate() {
+ if tokens.is_empty() {
+ // Blank or whitespace-only line breaks any active run.
+ if let Some(r) = run.take() {
+ Self::flush_run(
+ &r,
+ &lines,
+ &tokenized,
+ &self.config,
+ &mut next_template_id,
+ &mut output,
+ );
+ }
+ output.push_str(lines[i]);
+ output.push('\n');
+ continue;
+ }
+ match run.as_mut() {
+ Some(r) if Self::extends_run(r, tokens, self.config.similarity_threshold) => {
+ r.indices.push(i);
+ Self::merge_into_template(&mut r.template, tokens);
+ }
+ _ => {
+ if let Some(r) = run.take() {
+ Self::flush_run(
+ &r,
+ &lines,
+ &tokenized,
+ &self.config,
+ &mut next_template_id,
+ &mut output,
+ );
+ }
+ run = Some(Run::start(i, tokens));
+ }
+ }
+ }
+ if let Some(r) = run.take() {
+ Self::flush_run(
+ &r,
+ &lines,
+ &tokenized,
+ &self.config,
+ &mut next_template_id,
+ &mut output,
+ );
+ }
+
+ // Trailing newline: if the input had one (split-lines drops it),
+ // restore it. Otherwise drop our final '\n' so we don't grow the
+ // output beyond input.
+ if content.ends_with('\n') {
+ // Output already ends in '\n' from the last push; nothing to do.
+ } else if output.ends_with('\n') {
+ output.pop();
+ }
+
+ if output.len() >= content.len() {
+ // Defensive: never inflate. Fall back to original.
+ return Ok(ReformatOutput::from_lengths(
+ content.len(),
+ content.to_string(),
+ ));
+ }
+ Ok(ReformatOutput::from_lengths(content.len(), output))
+ }
+}
+
+impl LogTemplate {
+ /// True if `tokens` matches the accumulated `run.template` at ≥
+ /// `sim_threshold` of positions AND token counts agree.
+ fn extends_run(run: &Run, tokens: &[&str], sim_threshold: f32) -> bool {
+ if tokens.len() != run.template.len() {
+ return false;
+ }
+ let len = tokens.len() as f32;
+ let mut matches = 0usize;
+ for (pos, tok) in tokens.iter().enumerate() {
+ match &run.template[pos] {
+ Some(constant) if constant == tok => matches += 1,
+ None => matches += 1, // already a wildcard; counts as match
+ _ => {}
+ }
+ }
+ (matches as f32 / len) >= sim_threshold
+ }
+
+ /// Update `template` in place: positions where `tokens[i] != template[i]`
+ /// become wildcards (`None`).
+ fn merge_into_template(template: &mut [Option<String>], tokens: &[&str]) {
+ for (pos, tok) in tokens.iter().enumerate() {
+ if let Some(constant) = &template[pos] {
+ if constant != tok {
+ template[pos] = None;
+ }
+ }
+ }
+ }
+
+ fn flush_run(
+ run: &Run,
+ lines: &[&str],
+ tokenized: &[Vec<&str>],
+ cfg: &LogTemplateConfig,
+ next_template_id: &mut usize,
+ out: &mut String,
+ ) {
+ let constant_count = run.template.iter().filter(|t| t.is_some()).count();
+ let varying_count = run.template.len() - constant_count;
+ let collapse = run.indices.len() >= cfg.min_run
+ && constant_count >= cfg.min_constant_tokens
+ && varying_count > 0;
+
+ if !collapse {
+ // Emit verbatim.
+ for &i in &run.indices {
+ out.push_str(lines[i]);
+ out.push('\n');
+ }
+ return;
+ }
+
+ // Emit "[Template T<id>: TOKEN <*> TOKEN ...] (N occurrences)"
+ let template_id = *next_template_id;
+ *next_template_id += 1;
+ out.push_str("[Template T");
+ let _ = write!(out, "{}", template_id);
+ out.push_str(": ");
+ for (pos, slot) in run.template.iter().enumerate() {
+ if pos > 0 {
+ out.push(' ');
+ }
+ match slot {
+ Some(constant) => out.push_str(constant),
+ None => out.push_str(WILDCARD),
+ }
+ }
+ out.push_str("] (");
+ let _ = write!(out, "{}", run.indices.len());
+ out.push_str(" occurrences)\n");
+
+ // Variant table: per line, emit only the variable-position
+ // tokens, space-separated.
+ for &i in &run.indices {
+ let toks = &tokenized[i];
+ let mut first = true;
+ for (pos, slot) in run.template.iter().enumerate() {
+ if slot.is_none() {
+ if !first {
+ out.push(' ');
+ }
+ out.push_str(toks[pos]);
+ first = false;
+ }
+ }
+ out.push('\n');
+ }
+ }
+}
+
+/// One in-flight collapse candidate: the original line indices it
+/// covers, plus the per-position token slots.
+struct Run {
+ indices: Vec<usize>,
+ /// `Some(token)` = constant at this position so far.
+ /// `None` = this position has varied → wildcard.
+ template: Vec<Option<String>>,
+}
+
+impl Run {
+ fn start(idx: usize, tokens: &[&str]) -> Self {
+ Self {
+ indices: vec![idx],
+ template: tokens.iter().map(|t| Some((*t).to_string())).collect(),
+ }
+ }
+}
+
+/// Whitespace-split tokenizer. Empty result = blank line.
+///
+/// Uses `str::split_whitespace` semantics: collapses runs of whitespace,
+/// trims leading/trailing whitespace. UTF-8 safe.
+fn tokenize(line: &str) -> Vec<&str> {
+ line.split_whitespace().collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::transforms::pipeline::config::PipelineConfig;
+
+ fn cfg() -> LogTemplateConfig {
+ PipelineConfig::default().reformat.log_template
+ }
+
+ fn reformat() -> LogTemplate {
+ LogTemplate::new(cfg())
+ }
+
+ #[test]
+ fn name_and_applies_to() {
+ let r = reformat();
+ assert_eq!(r.name(), "log_template");
+ assert_eq!(r.applies_to(), &[ContentType::BuildOutput]);
+ }
+
+ #[test]
+ fn empty_input_skipped() {
+ let err = reformat().apply("").expect_err("empty must skip");
+ match err {
+ TransformError::Skipped { transform, .. } => assert_eq!(transform, "log_template"),
+ _ => panic!("expected Skipped"),
+ }
+ }
+
+ #[test]
+ fn below_min_lines_skipped() {
+ let log = "INFO a\nINFO b\nINFO c\n";
+ let err = reformat().apply(log).expect_err("must skip");
+ match err {
+ TransformError::Skipped { .. } => {}
+ _ => panic!("expected Skipped"),
+ }
+ }
+
+ #[test]
+ fn templated_run_collapses() {
+ // 50 INFO lines with varying timestamp + worker + job — same
+ // template, should collapse.
+ let mut log = String::new();
+ for i in 0..50 {
+ log.push_str(&format!(
+ "2025-01-15T12:34:{:02} INFO worker-{} processing job {}\n",
+ i,
+ i,
+ 100 + i
+ ));
+ }
+ let r = reformat().apply(&log).expect("must collapse");
+ assert!(r.bytes_saved > 0);
+ assert!(
+ r.output.contains("[Template T1:"),
+ "expected template header, got: {}",
+ r.output.chars().take(200).collect::<String>()
+ );
+ assert!(r.output.contains("(50 occurrences)"));
+ // Variants should still be in output (lossless guarantee).
+ assert!(r.output.contains("worker-7"));
+ }
+
+ #[test]
+ fn order_preserved_across_two_templates() {
+ // Run 1 (12 lines), then run 2 (12 lines). Both collapse,
+ // total ≥ min_lines=20. Output must put run 1's template
+ // before run 2's.
+ let mut log = String::new();
+ for i in 0..12 {
+ log.push_str(&format!("INFO worker-{i} starting\n"));
+ }
+ for i in 0..12 {
+ log.push_str(&format!("WARN cache key-{i} expired\n"));
+ }
+ let r = reformat().apply(&log).expect("must collapse");
+ let t1_pos = r.output.find("[Template T1:").expect("T1 header");
+ let t2_pos = r.output.find("[Template T2:").expect("T2 header");
+ assert!(t1_pos < t2_pos, "templates must be in input order");
+ // T1 must reference INFO/starting; T2 must reference WARN/cache.
+ let t1_line = r.output[t1_pos..t2_pos].lines().next().unwrap();
+ assert!(t1_line.contains("INFO"));
+ assert!(t1_line.contains("starting"));
+ }
+
+ #[test]
+ fn lossless_round_trip_via_template_and_variants() {
+ // The flushed output must be reconstructible: each template
+ // line + its variant rows reproduces the original input lines.
+ let mut log = String::new();
+ for i in 0..25 {
+ log.push_str(&format!("TOK1 TOK2 var{i} TOK3\n"));
+ }
+ let r = reformat().apply(&log).expect("collapses");
+ // Reconstruct: parse "[Template T1: TOK1 TOK2 <*> TOK3] (10 occurrences)"
+ // followed by 10 variant lines, each one the variant token.
+ let mut iter = r.output.lines();
+ let header = iter.next().unwrap();
+ assert!(header.starts_with("[Template T1:"));
+ // Template format: "TOK1 TOK2 <*> TOK3"
+ let template_part = header
+ .trim_start_matches("[Template T1: ")
+ .split("] (")
+ .next()
+ .unwrap();
+ let template_tokens: Vec<&str> = template_part.split_whitespace().collect();
+ let var_pos = template_tokens
+ .iter()
+ .position(|t| *t == WILDCARD)
+ .expect("must have wildcard");
+
+ let mut reconstructed = Vec::new();
+ for variant_line in iter {
+ if variant_line.is_empty() {
+ continue;
+ }
+ let var_tokens: Vec<&str> = variant_line.split_whitespace().collect();
+ assert_eq!(var_tokens.len(), 1, "1 wildcard → 1 variant token");
+ let mut full = template_tokens.clone();
+ full[var_pos] = var_tokens[0];
+ reconstructed.push(full.join(" "));
+ }
+ let original: Vec<String> = log.lines().map(|s| s.to_string()).collect();
+ assert_eq!(reconstructed, original);
+ }
+
+ #[test]
+ fn short_run_below_min_run_is_emitted_verbatim() {
+ // A 2-line "templated" run that ought to NOT be collapsed
+ // (below min_run=3), interleaved with structurally-different
+ // lines that BREAK the run on either side. Pad with
+ // structurally-heterogeneous lines (different token counts)
+ // so we clear min_lines without accidentally creating other
+ // templates.
+ let mut log = String::new();
+ // Heterogeneous prefix: each line has a different token count.
+ for i in 0..10 {
+ let toks: Vec<String> = (0..(i + 1) % 5 + 2).map(|j| format!("p{i}q{j}")).collect();
+ log.push_str(&toks.join(" "));
+ log.push('\n');
+ }
+ // The 2-line "would-be template" we expect NOT to collapse.
+ log.push_str("AAA worker-1 BBB\n");
+ log.push_str("AAA worker-2 BBB\n");
+ // Heterogeneous suffix.
+ for i in 0..10 {
+ let toks: Vec<String> = (0..(i + 1) % 4 + 2).map(|j| format!("s{i}t{j}")).collect();
+ log.push_str(&toks.join(" "));
+ log.push('\n');
+ }
+ let r = reformat().apply(&log).expect("input large enough");
+ // Both AAA lines must survive verbatim (run len < min_run).
+ assert!(r.output.contains("AAA worker-1 BBB"));
+ assert!(r.output.contains("AAA worker-2 BBB"));
+ }
+
+ #[test]
+ fn all_unique_lines_are_emitted_verbatim() {
+ // 25 totally different lines — no template collapse possible.
+ let mut log = String::new();
+ for i in 0..25 {
+ log.push_str(&format!("event-{i} type-{i} status-{i}\n"));
+ }
+ // These all share token-count and "event-" prefix is varying.
+ // Similarity might trigger collapse — that's fine if it does
+ // (still lossless), but we mainly assert no panic + no
+ // information loss.
+ let r = reformat().apply(&log).expect("processes");
+ // Either way: every variant value must survive.
+ for i in 0..25 {
+ assert!(
+ r.output.contains(&format!("event-{i}")),
+ "missing event-{i} in output"
+ );
+ }
+ }
+
+ #[test]
+ fn blank_lines_break_runs() {
+ // Run, blank line, run — must produce TWO templates (or no
+ // collapse), never bridge the blank.
+ let mut log = String::new();
+ for i in 0..5 {
+ log.push_str(&format!("INFO worker-{i} ready\n"));
+ }
+ log.push('\n');
+ for i in 0..5 {
+ log.push_str(&format!("INFO worker-{i} ready\n"));
+ }
+ // Pad to clear min_lines.
+ for i in 0..15 {
+ log.push_str(&format!("misc-{i}\n"));
+ }
+ let r = reformat().apply(&log).expect("input large enough");
+ // Either both runs collapse separately (T1 and T2 in output)
+ // or neither does. They MUST NOT be combined into one run.
+ let t1_count = r.output.matches("[Template T1:").count();
+ let t2_count = r.output.matches("[Template T2:").count();
+ // Acceptable: 0/0 (no collapse), 1/1 (separate templates).
+ // Forbidden: 1/0 with "(10 occurrences)" — would mean we
+ // bridged the blank line.
+ if t1_count == 1 && t2_count == 0 {
+ assert!(
+ !r.output.contains("(10 occurrences)"),
+ "must not bridge the blank line"
+ );
+ }
+ }
+
+ #[test]
+ fn never_inflates_output() {
+ // Edge case: very heterogeneous logs where template overhead
+ // outweighs savings. Output must never exceed input length.
+ let mut log = String::new();
+ for i in 0..30 {
+ log.push_str(&format!("a{i}\n"));
+ }
+ let r = reformat().apply(&log).expect("processes");
+ assert!(r.output.len() <= log.len());
+ }
+
+ #[test]
+ fn unicode_tokens_survive() {
+ let mut log = String::new();
+ for i in 0..30 {
+ log.push_str(&format!("INFO 🔥 worker-{i} héllo wörld\n"));
+ }
+ let r = reformat().apply(&log).expect("processes utf8");
+ // Even if collapsed, 🔥 must appear in template (constant).
+ assert!(r.output.contains("🔥"));
+ assert!(r.output.contains("héllo") || r.output.contains("wörld"));
+ }
+
+ #[test]
+ fn template_with_no_constants_emits_verbatim() {
+ // 30 lines where every position varies — template would be
+ // all-wildcards, which violates min_constant_tokens=2.
+ let mut log = String::new();
+ for i in 0..30 {
+ log.push_str(&format!("{} {} {}\n", i, i + 1, i + 2));
+ }
+ let r = reformat().apply(&log).expect("processes");
+ assert!(!r.output.contains("[Template"));
+ }
+}
diff --git a/crates/headroom-core/src/transforms/pipeline/reformats/mod.rs b/crates/headroom-core/src/transforms/pipeline/reformats/mod.rs
new file mode 100644
index 000000000..a88634ed6
--- /dev/null
+++ b/crates/headroom-core/src/transforms/pipeline/reformats/mod.rs
@@ -0,0 +1,12 @@
+//! Reformat transforms — pack denser without dropping any information.
+//!
+//! Every transform here implements [`super::traits::ReformatTransform`].
+//! Output bytes are semantically equivalent to input bytes (the LLM
+//! reading them gets the same data, just with fewer characters). No
+//! CCR involvement; no marker emission.
+
+pub mod json_minifier;
+pub mod log_template;
+
+pub use json_minifier::JsonMinifier;
+pub use log_template::LogTemplate;
diff --git a/crates/headroom-core/src/transforms/pipeline/traits.rs b/crates/headroom-core/src/transforms/pipeline/traits.rs
index 3ea33f89a..a1087f45e 100644
--- a/crates/headroom-core/src/transforms/pipeline/traits.rs
+++ b/crates/headroom-core/src/transforms/pipeline/traits.rs
@@ -1,38 +1,68 @@
-//! Compression pipeline traits + supporting types.
+//! Compression pipeline traits — `Reformat` and `Offload`.
//!
-//! Two traits, one shared result type, one per-call context object,
-//! one error type. That's the entire surface — every piece earns its
-//! place by being needed by either an impl in this PR (JsonMinifier,
-//! LineImportanceFilter) or the orchestrator that runs them.
+//! # Why two traits, both lossless w.r.t. information
+//!
+//! With CCR (Compress-Cache-Retrieve), no transform in this pipeline
+//! destroys information. Bytes drop from the wire, but the original
+//! payload is stashed in a [`CcrStore`] keyed by a hash; the LLM can
+//! retrieve any dropped piece via a tool call. So calling transforms
+//! "lossy" misnames the architecture — they all preserve information,
+//! they just differ in *how* they shrink the wire output.
+//!
+//! Two distinct mechanisms, two traits:
+//!
+//! * [`ReformatTransform`] — pack denser without dropping anything.
+//! Output bytes, when read, are semantically equivalent to the
+//! input. Examples: `JsonMinifier` (whitespace), log RLE
+//! deduplication, code-comment stripping, schema extraction.
+//! **No CCR needed** — the LLM doesn't retrieve anything; the wire
+//! output carries everything already.
+//!
+//! * [`OffloadTransform`] — drop bytes from the wire, stash the
+//! original via a [`CcrStore`], emit a retrieval marker. Examples:
+//! line-importance filtering, diff hunk sampling, search match
+//! thinning. **CCR is required** — the trait method takes
+//! `&dyn CcrStore`, and `OffloadOutput::cache_key` is `String`
+//! (not `Option<String>`) so the contract is type-system-enforced.
+//!
+//! # Per-domain bloat estimation
+//!
+//! Different content shapes have different "bloat" signals — a
+//! generic byte-redundancy heuristic (zlib, etc.) misses domain
+//! semantics. So [`OffloadTransform`] carries an [`estimate_bloat`]
+//! method that runs a CHEAP structural read and returns a 0.0–1.0
+//! score representing how much THIS transform would benefit the
+//! input. The orchestrator gates `apply` on `estimate_bloat`
+//! clearing a configurable threshold, and runs estimates in parallel
+//! with the reformat phase via `rayon::join`.
+//!
+//! [`estimate_bloat`]: OffloadTransform::estimate_bloat
+use crate::ccr::CcrStore;
use crate::transforms::ContentType;
/// Errors a transform can return.
///
-/// `InvalidInput` is for malformed input the transform can't parse
-/// (e.g. JsonMinifier on non-JSON). `Skipped` is for "I ran cleanly
-/// but found nothing to do" — used when an early exit is the right
-/// call but isn't actually an error. `Internal` is for serializer /
-/// allocator / logic-bug failures the orchestrator should record but
-/// not crash on.
+/// All three variants signal "skip this transform, continue the
+/// pipeline" — the orchestrator never panics on a transform error.
+/// `Internal` surfaces to logs at WARN; the others at TRACE.
#[derive(Debug, thiserror::Error)]
pub enum TransformError {
- /// The transform couldn't parse the input. Orchestrator skips and
- /// tries the next transform.
+ /// The transform couldn't parse the input. Caller skips it.
#[error("invalid input for {transform}: {message}")]
InvalidInput {
transform: &'static str,
message: String,
},
- /// The transform decided not to run (e.g. empty input, content
- /// already minimal). Orchestrator skips silently.
+ /// Ran cleanly, found nothing to do (empty input, content
+ /// already minimal). Caller skips silently.
#[error("{transform} skipped: {message}")]
Skipped {
transform: &'static str,
message: String,
},
- /// Internal failure (serializer, allocator, logic bug). Surfaces
- /// to logs but does not abort the pipeline.
+ /// Internal failure (serializer, store write error, logic bug).
+ /// Caller surfaces to WARN logs but continues.
#[error("{transform} internal error: {message}")]
Internal {
transform: &'static str,
@@ -47,14 +77,12 @@ impl TransformError {
message: message.into(),
}
}
-
pub fn skipped(transform: &'static str, message: impl Into<String>) -> Self {
Self::Skipped {
transform,
message: message.into(),
}
}
-
pub fn internal(transform: &'static str, message: impl Into<String>) -> Self {
Self::Internal {
transform,
@@ -63,71 +91,52 @@ impl TransformError {
}
}
-/// Result of a single transform invocation.
-///
-/// Every successful run produces an owned `output` string and reports
-/// how much was saved. The orchestrator decides whether the savings
-/// pass its acceptance threshold; transforms that didn't actually
-/// shrink anything return `bytes_saved == 0` and the orchestrator
-/// rejects the result.
+/// Result of a [`ReformatTransform`] — output bytes are semantically
+/// equivalent to the input. No CCR handle, no tool call required.
#[derive(Debug, Clone)]
-pub struct TransformResult {
- /// Compressed (or pass-through) output. Always owned because
- /// transforms typically produce new strings; for the rare
- /// pass-through case the allocation is unavoidable but tiny.
+pub struct ReformatOutput {
pub output: String,
- /// `original.len() - output.len()`, clamped to 0. Negative
- /// "savings" (output longer than input) are normalized to 0 here
- /// and the orchestrator's [`is_acceptable`] check rejects them.
- ///
- /// [`is_acceptable`]: super::orchestrator::CompressionPipeline::is_acceptable
pub bytes_saved: usize,
- /// True iff the transform preserves structural invariants. JSON
- /// minification preserves shape → true. A code-comment stripper
- /// preserves the token stream's semantic meaning → true. Filtering
- /// out lines a relevance scorer ranked low → false (lines are
- /// gone, the LLM can't reconstruct them without CCR).
- ///
- /// Used by the orchestrator (and downstream PR3+ CCR-emission
- /// logic) to decide whether to attach a retrieval marker.
- pub structure_preserved: bool,
- /// CCR cache key when the transform deliberately offloaded
- /// content. `None` means the output is self-contained — no
- /// retrieval handle needed. PR1 transforms never set this; the
- /// field exists for PR2/PR3 wrappers around DiffCompressor /
- /// LogCompressor / SmartCrusher which do emit CCR markers.
- pub reversible_via: Option<String>,
}
-impl TransformResult {
- /// Construct a result whose `bytes_saved` is computed from the
- /// difference between input and output lengths.
- pub fn from_lengths(input_len: usize, output: String, structure_preserved: bool) -> Self {
- let bytes_saved = input_len.saturating_sub(output.len());
+impl ReformatOutput {
+ pub fn from_lengths(input_len: usize, output: String) -> Self {
Self {
+ bytes_saved: input_len.saturating_sub(output.len()),
output,
- bytes_saved,
- structure_preserved,
- reversible_via: None,
}
}
}
-/// Per-call context the orchestrator hands to each transform.
-///
-/// Holds anything a transform might need that *isn't* the input
-/// content — query for relevance scoring, target token budget for
-/// aggressiveness tuning. Transforms borrow the context for the
-/// duration of their `apply` call.
+/// Result of an [`OffloadTransform`] — output bytes are a SUBSET of
+/// the input, the original is in the supplied store, and `cache_key`
+/// is the lookup handle. Required, not optional.
+#[derive(Debug, Clone)]
+pub struct OffloadOutput {
+ pub output: String,
+ pub bytes_saved: usize,
+ /// Cache key under which the original payload is stored.
+ /// Required by trait contract.
+ pub cache_key: String,
+}
+
+impl OffloadOutput {
+ pub fn from_lengths(input_len: usize, output: String, cache_key: String) -> Self {
+ Self {
+ bytes_saved: input_len.saturating_sub(output.len()),
+ output,
+ cache_key,
+ }
+ }
+}
+
+/// Per-call context the orchestrator passes to each transform.
#[derive(Debug, Default, Clone)]
pub struct CompressionContext {
- /// The user's question for the LLM. Empty string means no query
- /// available; transforms must treat this as a generic compression
- /// pass (no relevance bias).
+ /// User question for relevance scoring inside offload transforms.
pub query: String,
- /// Token budget the orchestrator is targeting, in tokens (not
- /// bytes). `None` means "compress as much as is safe — caller
- /// will accept whatever comes out."
+ /// Token budget the orchestrator is targeting (None = no budget
+ /// signal; transforms apply their default aggressiveness).
pub token_budget: Option<usize>,
}
@@ -138,7 +147,6 @@ impl CompressionContext {
token_budget: None,
}
}
-
pub fn with_budget(token_budget: usize) -> Self {
Self {
query: String::new(),
@@ -147,94 +155,138 @@ impl CompressionContext {
}
}
-/// Compression that preserves all information (the LLM gets the same
-/// bytes back, just packed denser).
-///
-/// Examples (in this PR or PR2+): JSON minification, code-comment
-/// stripping, log RLE, HTML extraction. These run first — if the
-/// result fits the budget, no lossy work is needed.
-pub trait LosslessTransform: Send + Sync {
- /// Stable telemetry name, e.g. `"json_minifier"`. Used as the
- /// strategy key in the per-strategy stats nest landed in
- /// Phase 3e.0. Must match `^[a-z][a-z0-9_]*$` by convention so
- /// it composes cleanly into JSONB keys.
+/// A transform that packs the input denser without dropping
+/// information. The orchestrator runs reformats first because they
+/// don't need any CCR backing — surviving bytes round-trip
+/// semantically.
+pub trait ReformatTransform: Send + Sync {
+ /// Stable telemetry name (lowercase snake_case, no spaces).
+ /// Used as the strategy key in the per-strategy stats nest from
+ /// Phase 3e.0.
fn name(&self) -> &'static str;
- /// Content types this transform accepts. The orchestrator skips
- /// the transform when the input's detected type isn't in this
- /// slice. Returning a `&[ContentType]` borrowed from `&self`
- /// lets impls store either a static literal or an owned config-
- /// driven list.
+ /// Content types this transform accepts. Borrowed from `&self`
+ /// so impls can return either a `&'static` literal or a
+ /// runtime-configured slice.
fn applies_to(&self) -> &[ContentType];
- /// Run the transform. Returns `Err(TransformError)` for malformed
- /// input or internal failures (orchestrator skips); returns
- /// `Ok(TransformResult)` for successful runs even when nothing
- /// was saved (the orchestrator decides what to do based on
- /// `bytes_saved`).
- fn apply(&self, content: &str) -> Result<TransformResult, TransformError>;
+ /// Run the transform.
+ fn apply(&self, content: &str) -> Result<ReformatOutput, TransformError>;
}
-/// Compression that deliberately drops content to fit a budget.
+/// A transform that drops bytes from the wire and stashes the
+/// original via CCR. The trait carries a cheap, domain-specific
+/// [`estimate_bloat`] method so the orchestrator can decide whether
+/// running the full `apply` is worthwhile — the estimate is the
+/// gating signal.
+///
+/// Trait contract:
+/// 1. `estimate_bloat` returns a 0.0–1.0 score. It MUST be cheap
+/// (structural-only, no full compression pass) and MUST be safe
+/// to call on any input including the empty string.
+/// 2. If the orchestrator calls `apply`, it has already gated on
+/// `estimate_bloat ≥ threshold`. `apply` MUST emit a `cache_key`
+/// on success — return `Err(Skipped)` if the implementation
+/// decides post-hoc that the offload wasn't worth it.
+/// 3. `apply` MUST stash the payload in `store` before returning,
+/// and the returned `cache_key` MUST resolve in that store.
///
-/// Examples (in this PR or PR2+): line-importance filtering, prose-
-/// field compression via a small model, extractive summarization.
-/// These run after lossless and gate further passes on byte savings.
-pub trait LossyTransform: Send + Sync {
- /// Stable telemetry name (same convention as
- /// [`LosslessTransform::name`]).
+/// [`estimate_bloat`]: Self::estimate_bloat
+pub trait OffloadTransform: Send + Sync {
+ /// Stable telemetry name (lowercase snake_case).
fn name(&self) -> &'static str;
/// Content types this transform accepts.
fn applies_to(&self) -> &[ContentType];
- /// Run the transform. Same error semantics as
- /// [`LosslessTransform::apply`]. The `ctx` argument lets the
- /// transform read the query (for relevance) and budget (for
- /// aggressiveness) without taking on tokenizer or proxy state.
+ /// Cheap structural estimate of bloat in `content`, scoped to
+ /// THIS transform's domain. 0.0 = nothing here would benefit
+ /// from offload; 1.0 = entire input is offloadable. Runs in
+ /// parallel with the reformat phase via `rayon::join` — keep
+ /// it under O(n) on input length, no allocations beyond what's
+ /// needed for the structural read.
+ ///
+ /// MUST be safe on empty input (returns 0.0 by convention).
+ fn estimate_bloat(&self, content: &str) -> f32;
+
+ /// Run the offload. The orchestrator only calls this when
+ /// `estimate_bloat(content) ≥ threshold`. On success, the
+ /// returned `cache_key` MUST resolve to the original payload
+ /// in `store`.
fn apply(
&self,
content: &str,
ctx: &CompressionContext,
- ) -> Result<TransformResult, TransformError>;
+ store: &dyn CcrStore,
+ ) -> Result<OffloadOutput, TransformError>;
- /// Calibrated 0.0–1.0 quality score. Higher = more confident the
- /// output preserves enough information for the LLM to answer the
- /// query. The orchestrator records this in telemetry; selection
- /// between competing lossy transforms (PR4 ProseFieldCompressor
- /// vs LineImportanceFilter on the same content type) becomes a
- /// future extension. For now it's purely observational.
+ /// Calibrated 0.0–1.0 quality score for telemetry. Future PR4
+ /// may use it to select between competing offload transforms.
fn confidence(&self) -> f32;
}
#[cfg(test)]
mod tests {
use super::*;
+ use crate::ccr::InMemoryCcrStore;
- /// One throwaway impl per trait, used by orchestrator-level tests
- /// when they need a deterministic transform. Real impls live in
- /// sibling modules.
- pub struct AlwaysSavesNothing;
- impl LosslessTransform for AlwaysSavesNothing {
+ pub struct TestReformat;
+ impl ReformatTransform for TestReformat {
fn name(&self) -> &'static str {
- "test_no_op"
+ "test_reformat"
}
fn applies_to(&self) -> &[ContentType] {
&[ContentType::PlainText]
}
- fn apply(&self, content: &str) -> Result<TransformResult, TransformError> {
- Ok(TransformResult {
- output: content.to_string(),
- bytes_saved: 0,
- structure_preserved: true,
- reversible_via: None,
- })
+ fn apply(&self, content: &str) -> Result<ReformatOutput, TransformError> {
+ Ok(ReformatOutput::from_lengths(
+ content.len(),
+ content.to_string(),
+ ))
}
}
+ pub struct TestOffload {
+ bloat: f32,
+ }
+ impl OffloadTransform for TestOffload {
+ fn name(&self) -> &'static str {
+ "test_offload"
+ }
+ fn applies_to(&self) -> &[ContentType] {
+ &[ContentType::PlainText]
+ }
+ fn estimate_bloat(&self, _content: &str) -> f32 {
+ self.bloat
+ }
+ fn apply(
+ &self,
+ content: &str,
+ _ctx: &CompressionContext,
+ store: &dyn CcrStore,
+ ) -> Result<OffloadOutput, TransformError> {
+ let key = format!("test_key_{:024x}", content.len());
+ store.put(&key, content);
+ Ok(OffloadOutput::from_lengths(
+ content.len(),
+ content.to_string(),
+ key,
+ ))
+ }
+ fn confidence(&self) -> f32 {
+ 0.5
+ }
+ }
+
+ #[test]
+ fn reformat_output_clamps_negative_savings_to_zero() {
+ let r = ReformatOutput::from_lengths(10, "this is much longer than 10 bytes".into());
+ assert_eq!(r.bytes_saved, 0);
+ }
+
#[test]
- fn from_lengths_clamps_negative_savings_to_zero() {
- let r = TransformResult::from_lengths(10, "this is longer than 10 bytes".into(), true);
+ fn offload_output_clamps_negative_savings_to_zero() {
+ let r = OffloadOutput::from_lengths(10, "this is much longer".into(), "k".into());
assert_eq!(r.bytes_saved, 0);
}
@@ -247,22 +299,40 @@ mod tests {
}
#[test]
- fn compression_context_constructors_are_clean() {
+ fn compression_context_constructors() {
let q = CompressionContext::with_query("find errors");
assert_eq!(q.query, "find errors");
assert_eq!(q.token_budget, None);
let b = CompressionContext::with_budget(2048);
- assert_eq!(b.query, "");
+ assert!(b.query.is_empty());
assert_eq!(b.token_budget, Some(2048));
}
#[test]
- fn no_op_lossless_transform_is_a_real_impl() {
- let t = AlwaysSavesNothing;
- let r = t.apply("hello").expect("no-op never errors");
+ fn reformat_trait_smoke() {
+ let t = TestReformat;
+ let r = t.apply("hello").expect("reformat passes through");
+ assert_eq!(r.output, "hello");
assert_eq!(r.bytes_saved, 0);
- assert_eq!(t.applies_to(), &[ContentType::PlainText]);
- assert_eq!(t.name(), "test_no_op");
+ }
+
+ #[test]
+ fn offload_trait_writes_to_store_and_returns_required_cache_key() {
+ let store = InMemoryCcrStore::new();
+ let t = TestOffload { bloat: 0.9 };
+ let r = t
+ .apply("hello", &CompressionContext::default(), &store)
+ .expect("offload writes");
+ // Trait contract: cache_key is required and resolves in the store.
+ assert!(!r.cache_key.is_empty());
+ assert_eq!(store.get(&r.cache_key).as_deref(), Some("hello"));
+ }
+
+ #[test]
+ fn offload_estimate_bloat_is_safe_on_empty_input() {
+ let t = TestOffload { bloat: 0.0 };
+ // Should not panic.
+ let _score = t.estimate_bloat("");
}
}
diff --git a/plugins/headroom-agent-hooks/.claude-plugin/plugin.json b/plugins/headroom-agent-hooks/.claude-plugin/plugin.json
index bfab371cd..8853264fa 100644
--- a/plugins/headroom-agent-hooks/.claude-plugin/plugin.json
+++ b/plugins/headroom-agent-hooks/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "headroom",
- "version": "0.16.0",
+ "version": "0.20.2",
"description": "Headroom startup hooks for Claude Code and GitHub Copilot CLI.",
"author": {
"name": "Headroom Contributors",
diff --git a/plugins/headroom-agent-hooks/.github/plugin/plugin.json b/plugins/headroom-agent-hooks/.github/plugin/plugin.json
index 28da3916a..efbb4aa63 100644
--- a/plugins/headroom-agent-hooks/.github/plugin/plugin.json
+++ b/plugins/headroom-agent-hooks/.github/plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "headroom",
- "version": "0.16.0",
+ "version": "0.20.2",
"description": "Headroom startup hooks for Claude Code and GitHub Copilot CLI.",
"author": {
"name": "Headroom Contributors",