Skip to main content

lean_ctx_ext/core/
compress_preview.rs

1// SPDX-License-Identifier: Apache-2.0
2//! compress_preview — a read-only "what would compression do to this?" inspector
3//! (#984, Headroom #1267).
4//!
5//! Returns the original alongside the exact bytes lean-ctx would emit, with token
6//! and byte accounting plus the line diff. It deliberately calls the **production**
7//! compressors — [`compressor::aggressive_compress`] for the file-read path and
8//! the shell engine's `compress_if_beneficial` for command output — so the
9//! preview is always what the agent would actually receive, never a re-derivation
10//! that could drift from the real pipeline (#498).
11
12use crate::core::compressor;
13use crate::core::tokens::count_tokens;
14
15/// Which production compressor a preview runs through.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum Pipeline {
18    /// The `ctx_read` aggressive arm: strips comments/blank lines and losslessly
19    /// compacts JSON/CSV. The file extension selects the language-specific rules.
20    Read,
21    /// The `ctx_shell` output pass: the ~95-pattern beneficial compressor.
22    Shell,
23}
24
25impl Pipeline {
26    /// Stable label used in [`Preview::render`] (no spaces that would break a
27    /// machine split on the header line).
28    pub fn label(self) -> &'static str {
29        match self {
30            Pipeline::Read => "read/aggressive",
31            Pipeline::Shell => "shell",
32        }
33    }
34}
35
36/// A computed preview: the original, the compressed form lean-ctx would emit, and
37/// the token/byte accounting for both.
38pub struct Preview {
39    pub pipeline: Pipeline,
40    pub original: String,
41    pub compressed: String,
42    pub original_tokens: usize,
43    pub compressed_tokens: usize,
44}
45
46impl Preview {
47    pub fn original_bytes(&self) -> usize {
48        self.original.len()
49    }
50
51    pub fn compressed_bytes(&self) -> usize {
52        self.compressed.len()
53    }
54
55    /// Tokens removed. Saturating: a pipeline never inflates in practice, but the
56    /// accounting stays honest (never negative) if a pathological input did.
57    pub fn saved_tokens(&self) -> usize {
58        self.original_tokens.saturating_sub(self.compressed_tokens)
59    }
60
61    /// Compressed-to-original token ratio in `[0.0, 1.0]` (1.0 = no change, also
62    /// the empty-input convention). Lower is better.
63    pub(crate) fn token_ratio(&self) -> f64 {
64        if self.original_tokens == 0 {
65            return 1.0;
66        }
67        self.compressed_tokens as f64 / self.original_tokens as f64
68    }
69
70    /// Percent of tokens saved, rounded to one decimal (derived from the ratio).
71    pub fn saved_pct(&self) -> f64 {
72        ((1.0 - self.token_ratio()) * 1000.0).round() / 10.0
73    }
74
75    /// Line-level diff original→compressed via the shared differ.
76    pub fn diff(&self) -> String {
77        compressor::diff_content(&self.original, &self.compressed)
78    }
79
80    /// Human-readable report: an accounting header followed by the diff.
81    /// Deterministic (no timestamps/counters) so the output is cache-stable (#498).
82    pub fn render(&self) -> String {
83        let mut out = String::new();
84        out.push_str("compress preview — pipeline: ");
85        out.push_str(self.pipeline.label());
86        out.push('\n');
87        out.push_str(&format!(
88            "tokens: {} -> {}  (-{}, {:.1}% saved)\n",
89            self.original_tokens,
90            self.compressed_tokens,
91            self.saved_tokens(),
92            self.saved_pct(),
93        ));
94        out.push_str(&format!(
95            "bytes:  {} -> {}\n",
96            self.original_bytes(),
97            self.compressed_bytes(),
98        ));
99        out.push_str("-- diff (original -> compressed) --\n");
100        out.push_str(&self.diff());
101        if !out.ends_with('\n') {
102            out.push('\n');
103        }
104        out
105    }
106}
107
108/// Preview the read/aggressive pipeline for `content`, with an optional file
109/// extension that drives language-specific comment stripping and the JSON/CSV
110/// crushers.
111pub fn preview_read(content: &str, ext: Option<&str>) -> Preview {
112    let compressed = compressor::aggressive_compress(content, ext);
113    finish(Pipeline::Read, content, compressed)
114}
115
116/// Preview the shell pipeline for `output` produced by `command` (the command
117/// steers build/test-aware verbatim preservation).
118pub fn preview_shell(command: &str, output: &str) -> Preview {
119    let compressed = crate::shell::compress::engine::compress_if_beneficial_pub(command, output);
120    finish(Pipeline::Shell, output, compressed)
121}
122
123fn finish(pipeline: Pipeline, original: &str, compressed: String) -> Preview {
124    Preview {
125        pipeline,
126        original_tokens: count_tokens(original),
127        compressed_tokens: count_tokens(&compressed),
128        original: original.to_string(),
129        compressed,
130    }
131}
132
133/// Lowercased extension (no leading dot) of `path`, for [`preview_read`].
134pub fn ext_of(path: &str) -> Option<String> {
135    std::path::Path::new(path)
136        .extension()
137        .and_then(|e| e.to_str())
138        .map(str::to_ascii_lowercase)
139}
140
141#[cfg(test)]
142mod tests {
143    use super::*;
144
145    #[test]
146    fn read_preview_strips_comments_and_saves_tokens() {
147        let src = "// a leading comment\nfn main() {\n    // inner note\n    let x = 1;\n}\n";
148        let p = preview_read(src, Some("rs"));
149        assert_eq!(p.pipeline, Pipeline::Read);
150        assert!(
151            !p.compressed.contains("leading comment") && !p.compressed.contains("inner note"),
152            "comments must be stripped: {}",
153            p.compressed
154        );
155        assert!(p.compressed_tokens < p.original_tokens, "tokens must drop");
156        assert!(p.saved_tokens() > 0);
157        assert!(p.token_ratio() < 1.0);
158        assert!(p.saved_pct() > 0.0);
159    }
160
161    #[test]
162    fn read_preview_compacts_pretty_json() {
163        let json =
164            "{\n  \"name\": \"lean-ctx\",\n  \"nested\": {\n    \"a\": 1,\n    \"b\": 2\n  }\n}\n";
165        let p = preview_read(json, Some("json"));
166        // Structured compaction strips insignificant whitespace losslessly.
167        assert!(!p.compressed.contains("\n  "), "json must be compacted");
168        assert!(p.compressed_tokens < p.original_tokens);
169    }
170
171    #[test]
172    fn no_change_input_reports_no_savings_and_clean_diff() {
173        let src = "let x = 1;";
174        let p = preview_read(src, Some("rs"));
175        assert_eq!(
176            p.compressed, p.original,
177            "already-minimal input is unchanged"
178        );
179        assert_eq!(p.saved_tokens(), 0);
180        assert!((p.token_ratio() - 1.0).abs() < f64::EPSILON);
181        assert_eq!(p.saved_pct(), 0.0);
182        assert_eq!(p.diff(), "(no changes)");
183    }
184
185    #[test]
186    fn shell_preview_compresses_repetitive_output() {
187        let output = "Compiling foo\n".repeat(40);
188        let p = preview_shell("cargo build", &output);
189        assert_eq!(p.pipeline, Pipeline::Shell);
190        assert!(
191            p.compressed_tokens <= p.original_tokens,
192            "shell compression never inflates"
193        );
194    }
195
196    #[test]
197    fn render_is_deterministic_and_self_describing() {
198        let src = "// c\nfn a() {}\n";
199        let p = preview_read(src, Some("rs"));
200        let a = p.render();
201        let b = p.render();
202        assert_eq!(a, b, "render must be deterministic (#498)");
203        assert!(a.contains("pipeline: read/aggressive"));
204        assert!(a.contains("tokens:"));
205        assert!(a.contains("bytes:"));
206    }
207
208    #[test]
209    fn ext_of_extracts_lowercased_extension() {
210        assert_eq!(ext_of("/a/b/File.RS").as_deref(), Some("rs"));
211        assert_eq!(ext_of("data.JSON").as_deref(), Some("json"));
212        assert_eq!(ext_of("Makefile"), None);
213        assert_eq!(ext_of("-"), None);
214    }
215}