Skip to main content

lean_ctx_ext/core/
output_echo.rs

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