Skip to main content

lean_ctx/core/value/
format.rs

1//! Shared renderers for the value surface. Subtle by construction: one dim
2//! line, no exclamation, nothing when there is nothing measured to say.
3
4use crate::core::security_events::SecurityCounts;
5use crate::core::wrapped::format_tokens;
6
7use super::snapshot::ValueSnapshot;
8
9/// How a channel can render: colour (ANSI dim) and Unicode glyphs are
10/// independent — a Claude status line has colour but no TTY, a legacy Windows
11/// console has a TTY but no reliable glyphs.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub struct Style {
14    pub color: bool,
15    pub unicode: bool,
16}
17
18impl Style {
19    pub const PLAIN: Self = Self {
20        color: false,
21        unicode: true,
22    };
23
24    /// Colour unless `NO_COLOR` is set; ASCII when `LEAN_CTX_ASCII` is set.
25    /// TTY detection is the caller's job (status lines are not TTYs).
26    pub fn from_env() -> Self {
27        Self {
28            color: std::env::var_os("NO_COLOR").is_none(),
29            unicode: std::env::var_os("LEAN_CTX_ASCII").is_none(),
30        }
31    }
32
33    pub(crate) fn mark(self) -> &'static str {
34        if self.unicode { "◆" } else { "*" }
35    }
36
37    pub(crate) fn shield(self) -> &'static str {
38        if self.unicode { "⛨" } else { "sec" }
39    }
40
41    pub(crate) fn minus(self) -> &'static str {
42        if self.unicode { "−" } else { "-" }
43    }
44
45    pub(crate) fn sep(self) -> &'static str {
46        if self.unicode { " · " } else { " | " }
47    }
48}
49
50/// `◆ lean-ctx −1.2M tok · 41 cached · ⛨ 3` — or `None` when nothing measured
51/// happened yet (a zero would read like lean-ctx is not working).
52pub fn one_line(snap: &ValueSnapshot, style: Style) -> Option<String> {
53    if snap.is_empty() {
54        return None;
55    }
56    let mut parts = Vec::new();
57    if snap.tokens_saved > 0 {
58        parts.push(format!(
59            "{}{} tok",
60            style.minus(),
61            format_tokens(snap.tokens_saved)
62        ));
63    }
64    if snap.cache_hits > 0 {
65        parts.push(format!("{} cached", snap.cache_hits));
66    }
67    let security = snap.security.total();
68    if security > 0 {
69        parts.push(format!("{} {security}", style.shield()));
70    }
71    let body = format!("{} lean-ctx {}", style.mark(), parts.join(style.sep()));
72    Some(if style.color {
73        format!("\x1b[2m{body}\x1b[0m")
74    } else {
75        body
76    })
77}
78
79/// `◆ −1.2M tok ⛨ 3` for a shell prompt: the shortest honest form, never
80/// coloured (prompt escaping differs per shell, so the caller wraps it).
81pub fn compact(snap: &ValueSnapshot, style: Style) -> Option<String> {
82    if snap.is_empty() {
83        return None;
84    }
85    let mut out = style.mark().to_string();
86    if snap.tokens_saved > 0 {
87        out.push_str(&format!(
88            " {}{} tok",
89            style.minus(),
90            format_tokens(snap.tokens_saved)
91        ));
92    }
93    let security = snap.security.total();
94    if security > 0 {
95        out.push_str(&format!(" {} {security}", style.shield()));
96    }
97    // Only cache hits measured: nothing short enough to be worth a prompt slot.
98    (out.len() > style.mark().len()).then_some(out)
99}
100
101fn plural(n: u64, one: &str, many: &str) -> String {
102    format!("{n} {}", if n == 1 { one } else { many })
103}
104
105/// Human wording for a security tally, in the contract's words: secrets are
106/// *kept out of context*, commands and paths *blocked*, injections *flagged*.
107pub fn security_phrases(counts: &SecurityCounts) -> Vec<String> {
108    let mut out = Vec::new();
109    if counts.secrets_redacted > 0 {
110        out.push(format!(
111            "{} kept out of context",
112            plural(counts.secrets_redacted, "secret", "secrets")
113        ));
114    }
115    if counts.shell_blocked > 0 {
116        out.push(format!(
117            "{} blocked",
118            plural(counts.shell_blocked, "risky command", "risky commands")
119        ));
120    }
121    if counts.path_blocked > 0 {
122        out.push(format!(
123            "{} outside the project blocked",
124            plural(counts.path_blocked, "path", "paths")
125        ));
126    }
127    if counts.injection_flagged > 0 {
128        out.push(format!(
129            "{} flagged",
130            plural(
131                counts.injection_flagged,
132                "prompt-injection pattern",
133                "prompt-injection patterns"
134            )
135        ));
136    }
137    out
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143
144    fn snap(saved: u64, cache: u64, secrets: u64) -> ValueSnapshot {
145        let mut s = ValueSnapshot {
146            tokens_saved: saved,
147            tokens_input: saved * 2,
148            cache_hits: cache,
149            ..ValueSnapshot::default()
150        };
151        s.security.secrets_redacted = secrets;
152        s
153    }
154
155    #[test]
156    fn nothing_measured_renders_nothing() {
157        assert_eq!(one_line(&ValueSnapshot::default(), Style::PLAIN), None);
158    }
159
160    #[test]
161    fn plain_unicode_line() {
162        assert_eq!(
163            one_line(&snap(1_200_000, 41, 3), Style::PLAIN).unwrap(),
164            "◆ lean-ctx −1.2M tok · 41 cached · ⛨ 3"
165        );
166    }
167
168    #[test]
169    fn ascii_fallback_has_no_multibyte_glyphs() {
170        let style = Style {
171            color: false,
172            unicode: false,
173        };
174        let line = one_line(&snap(312_000, 0, 1), style).unwrap();
175        assert!(line.is_ascii(), "{line}");
176        assert_eq!(line, "* lean-ctx -312.0K tok | sec 1");
177    }
178
179    #[test]
180    fn color_is_dim_and_reset() {
181        let style = Style {
182            color: true,
183            unicode: true,
184        };
185        let line = one_line(&snap(5_000, 0, 0), style).unwrap();
186        assert!(line.starts_with("\x1b[2m") && line.ends_with("\x1b[0m"));
187    }
188
189    #[test]
190    fn compact_is_short_and_uncoloured() {
191        let style = Style {
192            color: true,
193            unicode: true,
194        };
195        assert_eq!(
196            compact(&snap(1_200_000, 41, 3), style).unwrap(),
197            "◆ −1.2M tok ⛨ 3"
198        );
199        let ascii = Style {
200            color: false,
201            unicode: false,
202        };
203        assert_eq!(compact(&snap(0, 0, 2), ascii).unwrap(), "* sec 2");
204        assert_eq!(compact(&snap(0, 9, 0), Style::PLAIN), None);
205        assert_eq!(compact(&ValueSnapshot::default(), Style::PLAIN), None);
206    }
207
208    #[test]
209    fn security_only_session_still_shows() {
210        let line = one_line(&snap(0, 0, 2), Style::PLAIN).unwrap();
211        assert_eq!(line, "◆ lean-ctx ⛨ 2");
212    }
213
214    #[test]
215    fn phrases_never_claim_neutralization() {
216        let counts = SecurityCounts {
217            secrets_redacted: 1,
218            shell_blocked: 2,
219            path_blocked: 1,
220            injection_flagged: 3,
221        };
222        let text = security_phrases(&counts).join(", ");
223        assert_eq!(
224            text,
225            "1 secret kept out of context, 2 risky commands blocked, \
226             1 path outside the project blocked, 3 prompt-injection patterns flagged"
227        );
228        assert!(!text.contains("neutraliz"));
229    }
230}