Skip to main content

lean_ctx/core/
output_echo.rs

1//! Output-echo detection (#501).
2//!
3//! lean-ctx aggressively optimizes the *input* side, but never looked at the
4//! agent's *output* — although output tokens cost 4-5x more. The most common
5//! waste pattern is the code echo: the agent re-quotes file content that is
6//! already in context. The `afterAgentResponse` hook delivers the reply text;
7//! this module measures which share of its code lines were echoed from
8//! recently read files (context radar tail) and feeds three consumers:
9//!
10//! 1. rolling stats (`~/.lean-ctx/output_echo.json`) for `ctx_metrics`,
11//!    `ctx_session output_stats` and the dashboard,
12//! 2. an automatic `LlmFeedbackEvent` so the LLM feedback store receives
13//!    continuous data instead of voluntary `ctx_feedback` calls,
14//! 3. a stable, cache-friendly CEP nudge the MCP server appends to a tool
15//!    result when echo stays high (cooldown-limited).
16
17use std::collections::HashSet;
18use std::path::PathBuf;
19
20use serde::{Deserialize, Serialize};
21
22const STATS_FILE: &str = "output_echo.json";
23/// Rolling window of analyzed responses.
24const MAX_REPORTS: usize = 50;
25/// Echo lines shorter than this are noise (`}`, `);`, `end`).
26const MIN_LINE_CHARS: usize = 12;
27/// Nudge when the average echo ratio of the recent window exceeds this.
28const NUDGE_THRESHOLD: f64 = 0.30;
29/// Responses considered for the nudge decision.
30const NUDGE_WINDOW: usize = 5;
31/// Minimum analyzed responses between two nudges.
32const NUDGE_COOLDOWN: usize = 20;
33/// How much of the radar tail to scan for source content (bytes).
34const RADAR_TAIL_BYTES: u64 = 262_144;
35/// Cap on source documents compared against.
36const MAX_SOURCES: usize = 20;
37
38#[derive(Debug, Clone, Serialize, Deserialize, Default)]
39pub struct EchoReport {
40    pub response_lines: usize,
41    pub code_lines: usize,
42    pub echoed_lines: usize,
43    pub echo_ratio: f64,
44    pub recorded_unix: u64,
45}
46
47#[derive(Debug, Clone, Serialize, Deserialize, Default)]
48pub struct EchoStats {
49    pub reports: Vec<EchoReport>,
50    /// Index (count of analyzed responses) at the last nudge.
51    pub last_nudge_at: u64,
52    /// Total responses analyzed over the lifetime of the store.
53    pub total_analyzed: u64,
54}
55
56impl EchoStats {
57    pub fn avg_ratio(&self, window: usize) -> f64 {
58        let recent: Vec<&EchoReport> = self.reports.iter().rev().take(window).collect();
59        if recent.is_empty() {
60            return 0.0;
61        }
62        recent.iter().map(|r| r.echo_ratio).sum::<f64>() / recent.len() as f64
63    }
64
65    /// Per-day `(YYYY-MM-DD, avg_echo_ratio, samples)` over the last `days`
66    /// days, ascending by day — the dashboard's learning trend (#507).
67    /// Days are UTC, consistent with the ledger's day slices.
68    pub fn daily_trend(&self, days: u32) -> Vec<(String, f64, u64)> {
69        use std::collections::BTreeMap;
70        let cutoff = now_unix().saturating_sub(u64::from(days) * 86_400);
71        let mut by_day: BTreeMap<String, (f64, u64)> = BTreeMap::new();
72        for r in &self.reports {
73            if r.recorded_unix < cutoff {
74                continue;
75            }
76            let Some(dt) = lean_ctx_time::UtcDateTime::from_timestamp(r.recorded_unix as i64, 0)
77            else {
78                continue;
79            };
80            let day = dt.format("%Y-%m-%d").to_string();
81            let entry = by_day.entry(day).or_default();
82            entry.0 += r.echo_ratio;
83            entry.1 += 1;
84        }
85        by_day
86            .into_iter()
87            .map(|(d, (sum, n))| (d, sum / n as f64, n))
88            .collect()
89    }
90}
91
92fn stats_path() -> PathBuf {
93    crate::core::data_dir::lean_ctx_data_dir()
94        .unwrap_or_else(|_| PathBuf::from("."))
95        .join(STATS_FILE)
96}
97
98fn now_unix() -> u64 {
99    std::time::SystemTime::now()
100        .duration_since(std::time::UNIX_EPOCH)
101        .map_or(0, |d| d.as_secs())
102}
103
104pub fn load_stats() -> EchoStats {
105    std::fs::read_to_string(stats_path())
106        .ok()
107        .and_then(|raw| serde_json::from_str(&raw).ok())
108        .unwrap_or_default()
109}
110
111fn save_stats(stats: &EchoStats) {
112    let path = stats_path();
113    if let Some(parent) = path.parent() {
114        let _ = std::fs::create_dir_all(parent);
115    }
116    if let Ok(json) = serde_json::to_string(stats) {
117        let tmp = path.with_extension("tmp");
118        if std::fs::write(&tmp, json).is_ok() {
119            let _ = std::fs::rename(&tmp, &path);
120        }
121    }
122}
123
124/// Normalize a line for comparison: trim + collapse internal whitespace.
125fn normalize_line(line: &str) -> String {
126    let mut out = String::with_capacity(line.len());
127    let mut last_space = false;
128    for c in line.trim().chars() {
129        if c.is_whitespace() {
130            if !last_space {
131                out.push(' ');
132            }
133            last_space = true;
134        } else {
135            out.push(c);
136            last_space = false;
137        }
138    }
139    out
140}
141
142/// Extract the code lines of a markdown response: fenced blocks plus
143/// 4-space-indented lines. Prose is never counted as echo.
144fn code_lines_of_response(response: &str) -> Vec<String> {
145    let mut lines = Vec::new();
146    let mut in_fence = false;
147    for raw in response.lines() {
148        let trimmed = raw.trim_start();
149        if trimmed.starts_with("```") {
150            in_fence = !in_fence;
151            continue;
152        }
153        if in_fence || raw.starts_with("    ") {
154            let norm = normalize_line(raw);
155            if norm.chars().count() >= MIN_LINE_CHARS {
156                lines.push(norm);
157            }
158        }
159    }
160    lines
161}
162
163/// Pure analysis: which share of the response's code lines appear verbatim
164/// in any source document (recently read file contents)?
165pub(crate) fn analyze(response: &str, sources: &[String]) -> EchoReport {
166    let code_lines = code_lines_of_response(response);
167    let response_lines = response.lines().count();
168
169    if code_lines.is_empty() {
170        return EchoReport {
171            response_lines,
172            code_lines: 0,
173            echoed_lines: 0,
174            echo_ratio: 0.0,
175            recorded_unix: now_unix(),
176        };
177    }
178
179    let mut source_set: HashSet<String> = HashSet::new();
180    for src in sources.iter().take(MAX_SOURCES) {
181        for line in src.lines() {
182            let norm = normalize_line(line);
183            if norm.chars().count() >= MIN_LINE_CHARS {
184                source_set.insert(norm);
185            }
186        }
187    }
188
189    let echoed = code_lines
190        .iter()
191        .filter(|l| source_set.contains(*l))
192        .count();
193    let ratio = echoed as f64 / code_lines.len() as f64;
194
195    EchoReport {
196        response_lines,
197        code_lines: code_lines.len(),
198        echoed_lines: echoed,
199        echo_ratio: ratio,
200        recorded_unix: now_unix(),
201    }
202}
203
204/// Read the tail of the context radar log and collect recently delivered
205/// content (file reads, MCP tool results, shell output) as echo sources,
206/// plus the token sum of events since the last user message (turn input
207/// approximation for the feedback event).
208fn radar_tail_sources() -> (Vec<String>, u64) {
209    let data_dir =
210        crate::core::data_dir::lean_ctx_data_dir().unwrap_or_else(|_| PathBuf::from("."));
211    let path = data_dir.join("context_radar.jsonl");
212    let Ok(file) = std::fs::File::open(&path) else {
213        return (Vec::new(), 0);
214    };
215    use std::io::{Read, Seek, SeekFrom};
216    let mut file = file;
217    let len = file.metadata().map_or(0, |m| m.len());
218    let start = len.saturating_sub(RADAR_TAIL_BYTES);
219    if file.seek(SeekFrom::Start(start)).is_err() {
220        return (Vec::new(), 0);
221    }
222    let mut raw = String::new();
223    if file.read_to_string(&mut raw).is_err() {
224        return (Vec::new(), 0);
225    }
226
227    let mut sources: Vec<String> = Vec::new();
228    let mut turn_tokens: u64 = 0;
229    // Skip the first (possibly truncated) line when we started mid-file.
230    let skip_first = start > 0;
231    for (i, line) in raw.lines().enumerate() {
232        if skip_first && i == 0 {
233            continue;
234        }
235        let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else {
236            continue;
237        };
238        let event_type = v.get("event_type").and_then(|e| e.as_str()).unwrap_or("");
239        let tokens = v
240            .get("tokens")
241            .and_then(serde_json::Value::as_u64)
242            .unwrap_or(0);
243        match event_type {
244            "user_message" => turn_tokens = 0,
245            "agent_response" | "thinking" => {}
246            _ => turn_tokens = turn_tokens.saturating_add(tokens),
247        }
248        if matches!(event_type, "file_read" | "mcp_call" | "shell")
249            && let Some(content) = v.get("content").and_then(|c| c.as_str())
250            && !content.is_empty()
251        {
252            sources.push(content.to_string());
253        }
254    }
255    if sources.len() > MAX_SOURCES {
256        let excess = sources.len() - MAX_SOURCES;
257        sources.drain(..excess);
258    }
259    (sources, turn_tokens)
260}
261
262/// Hook entry point: analyze an agent response against the radar tail,
263/// persist rolling stats and emit the automatic feedback event.
264pub fn analyze_and_record(response: &str) {
265    let (sources, turn_input_tokens) = radar_tail_sources();
266    let report = analyze(response, &sources);
267
268    let mut stats = load_stats();
269    stats.total_analyzed = stats.total_analyzed.saturating_add(1);
270    stats.reports.push(report.clone());
271    if stats.reports.len() > MAX_REPORTS {
272        let excess = stats.reports.len() - MAX_REPORTS;
273        stats.reports.drain(..excess);
274    }
275    save_stats(&stats);
276
277    emit_feedback_event(response, turn_input_tokens);
278}
279
280/// Automatic `LlmFeedbackEvent` (#501): the LLM feedback store used to
281/// depend on voluntary `ctx_feedback` calls that practically never happened.
282/// Mode attribution comes from the session's `files_touched.last_mode`
283/// aggregation — a session-window approximation, honest and available.
284fn emit_feedback_event(response: &str, turn_input_tokens: u64) {
285    let output_tokens = crate::core::tokens::count_tokens(response) as u64;
286    if output_tokens == 0 {
287        return;
288    }
289
290    let session = crate::core::session::SessionState::load_latest();
291    let modes: Option<std::collections::BTreeMap<String, u64>> = session.as_ref().map(|s| {
292        let mut m = std::collections::BTreeMap::new();
293        for f in &s.files_touched {
294            if !f.last_mode.is_empty() {
295                *m.entry(f.last_mode.clone()).or_insert(0) += u64::from(f.read_count.max(1));
296            }
297        }
298        m
299    });
300    let modes = modes.filter(|m| !m.is_empty());
301
302    let model = crate::core::host_state::load_detected_model().map(|(name, _)| name);
303
304    let ev = crate::core::llm_feedback::LlmFeedbackEvent {
305        agent_id: "output_echo_auto".to_string(),
306        intent: session
307            .as_ref()
308            .and_then(|s| s.task.as_ref())
309            .and_then(|t| t.intent.clone()),
310        model,
311        llm_input_tokens: turn_input_tokens.max(1),
312        llm_output_tokens: output_tokens,
313        latency_ms: None,
314        note: None,
315        ctx_read_last_mode: None,
316        ctx_read_modes: modes,
317        timestamp: lean_ctx_time::UtcDateTime::now().to_rfc3339(),
318    };
319
320    let _ = crate::core::llm_feedback::LlmFeedbackStore::record(ev);
321}
322
323/// CEP nudge for the MCP server to append to a tool result. Stable text in
324/// 10%-steps (prompt-cache friendly, #498), cooldown-limited. Consuming the
325/// nudge advances the cooldown marker.
326pub fn take_pending_nudge() -> Option<String> {
327    let mut stats = load_stats();
328    if stats.reports.len() < NUDGE_WINDOW {
329        return None;
330    }
331    if stats.total_analyzed.saturating_sub(stats.last_nudge_at) < NUDGE_COOLDOWN as u64 {
332        return None;
333    }
334    let avg = stats.avg_ratio(NUDGE_WINDOW);
335    if avg < NUDGE_THRESHOLD {
336        return None;
337    }
338    let rounded = ((avg * 10.0).round() * 10.0) as u32;
339    stats.last_nudge_at = stats.total_analyzed;
340    save_stats(&stats);
341    Some(format!(
342        "\n[CEP: ~{rounded}% of your recent replies echoed file content already in context — reference lines (F1:42-58) instead of re-quoting]"
343    ))
344}
345
346/// Average echo ratio over the rolling window — CEP score input.
347pub fn current_avg_ratio() -> f64 {
348    load_stats().avg_ratio(MAX_REPORTS)
349}
350
351#[cfg(test)]
352mod tests {
353    use super::*;
354
355    fn file_content() -> String {
356        (0..30)
357            .map(|i| format!("pub fn compute_value_{i}(input: u32) -> u32 {{ input * {i} }}"))
358            .collect::<Vec<_>>()
359            .join("\n")
360    }
361
362    #[test]
363    fn echo_detected_for_quoted_file_content() {
364        let src = file_content();
365        let quoted: Vec<&str> = src.lines().take(10).collect();
366        let response = format!(
367            "Here is the relevant code:\n\n```rust\n{}\n```\n",
368            quoted.join("\n")
369        );
370        let report = analyze(&response, &[src]);
371        assert_eq!(report.code_lines, 10);
372        assert_eq!(report.echoed_lines, 10);
373        assert!(report.echo_ratio > 0.99);
374    }
375
376    #[test]
377    fn prose_response_has_zero_echo() {
378        let src = file_content();
379        let response = "The cache works by storing entries keyed by path. \
380                        No code needed here — the fix is a one-line change.";
381        let report = analyze(response, &[src]);
382        assert_eq!(report.code_lines, 0);
383        assert!(report.echo_ratio.abs() < f64::EPSILON);
384    }
385
386    #[test]
387    fn daily_trend_groups_by_utc_day_and_averages() {
388        let now = now_unix();
389        // Anchor both "today" samples to the start of the current UTC day. A naive
390        // `now` / `now - 60` pair straddles midnight when the suite runs within 60s
391        // of a UTC day rollover, yielding a spurious third day (flaky in CI).
392        let day = now - (now % 86_400);
393        let stats = EchoStats {
394            reports: vec![
395                // Two samples on the same UTC day (today): avg of 0.2 and 0.6 = 0.4.
396                EchoReport {
397                    echo_ratio: 0.2,
398                    recorded_unix: day + 100,
399                    ..Default::default()
400                },
401                EchoReport {
402                    echo_ratio: 0.6,
403                    recorded_unix: day + 200,
404                    ..Default::default()
405                },
406                // One sample two UTC days ago.
407                EchoReport {
408                    echo_ratio: 1.0,
409                    recorded_unix: day - 2 * 86_400 + 100,
410                    ..Default::default()
411                },
412                // Outside the 14-day window — must be excluded.
413                EchoReport {
414                    echo_ratio: 1.0,
415                    recorded_unix: day - 30 * 86_400,
416                    ..Default::default()
417                },
418            ],
419            ..Default::default()
420        };
421        let trend = stats.daily_trend(14);
422        assert_eq!(trend.len(), 2, "two distinct days inside the window");
423        // Ascending by day: the older day first.
424        assert_eq!(trend[0].2, 1, "older day has one sample");
425        assert!((trend[0].1 - 1.0).abs() < f64::EPSILON);
426        assert_eq!(trend[1].2, 2, "today has two samples");
427        assert!((trend[1].1 - 0.4).abs() < 1e-9);
428    }
429
430    #[test]
431    fn short_lines_are_ignored() {
432        let src = "}\n);\nend\nfn x() {}\n".to_string();
433        let response = "```rust\n}\n);\nend\n```\n";
434        let report = analyze(response, &[src]);
435        assert_eq!(report.code_lines, 0, "sub-12-char lines never count");
436    }
437
438    #[test]
439    fn novel_code_is_not_echo() {
440        let src = file_content();
441        let response = "```rust\npub fn completely_new_function(a: u64) -> u64 { a + 42 }\nlet result = completely_new_function(7);\n```";
442        let report = analyze(response, &[src]);
443        assert_eq!(report.echoed_lines, 0);
444        assert!(report.echo_ratio.abs() < f64::EPSILON);
445    }
446
447    #[test]
448    fn whitespace_differences_still_match() {
449        let src = "pub fn   spaced_out(value:    u32)   -> u32 { value }".to_string();
450        let response = "```rust\npub fn spaced_out(value: u32) -> u32 { value }\n```";
451        let report = analyze(response, &[src]);
452        assert_eq!(report.echoed_lines, 1);
453    }
454
455    #[test]
456    fn avg_ratio_windows_correctly() {
457        let mut stats = EchoStats::default();
458        for ratio in [0.0, 0.2, 0.4, 0.6, 0.8] {
459            stats.reports.push(EchoReport {
460                response_lines: 10,
461                code_lines: 10,
462                echoed_lines: (ratio * 10.0) as usize,
463                echo_ratio: ratio,
464                recorded_unix: 0,
465            });
466        }
467        assert!((stats.avg_ratio(5) - 0.4).abs() < 1e-9);
468        assert!((stats.avg_ratio(2) - 0.7).abs() < 1e-9);
469    }
470
471    #[test]
472    fn indented_code_outside_fences_counts() {
473        let src = "    let total = items.iter().map(|i| i.price).sum::<f64>();".to_string();
474        let response = "The sum is computed like this:\n\n    let total = items.iter().map(|i| i.price).sum::<f64>();\n";
475        let report = analyze(response, &[src]);
476        assert_eq!(report.code_lines, 1);
477        assert_eq!(report.echoed_lines, 1);
478    }
479}