egrix 0.1.0

Find leaked credentials and suspicious network destinations in AI agent transcripts. Local, offline, redacted by default.
//! A readable excerpt of a transcript around one finding. Transcript lines are
//! large JSON records; this pulls out who spoke and what was said, and redacts
//! every secret before anything reaches the screen.

use crate::rules::RuleSet;
use anyhow::{Context, Result};
use serde_json::Value;
use std::path::Path;

const WIDTH: usize = 180;

pub struct ExcerptLine {
    pub number: usize,
    pub role: String,
    pub text: String,
    pub hit: bool,
}

/// `radius` lines before and after `line` (1-based), each reduced to its text.
/// `needle` is what to keep in view on long lines: a host, or a secret preview.
pub fn excerpt(file: &Path, line: usize, needle: &str, rules: &RuleSet, radius: usize) -> Result<Vec<ExcerptLine>> {
    let bytes = std::fs::read(file).with_context(|| format!("cannot read {}", file.display()))?;
    let content = String::from_utf8_lossy(&bytes);
    let first = line.saturating_sub(radius).max(1);
    Ok(content
        .lines()
        .enumerate()
        .skip(first - 1)
        .take(line - first + radius + 1)
        .map(|(i, raw)| {
            let (role, text) = flatten(raw);
            let text = rules.redact(&text).replace(['\n', '\r', '\t'], " ");
            ExcerptLine { number: i + 1, role, hit: i + 1 == line, text: window(&text, needle) }
        })
        .collect())
}

/// Role and readable text of one transcript line.
fn flatten(raw: &str) -> (String, String) {
    let Ok(value) = serde_json::from_str::<Value>(raw) else { return (String::new(), raw.to_string()) };
    let message = value.get("message").unwrap_or(&value);
    let role = ["role", "type", "kind"]
        .iter()
        .find_map(|k| message.get(k).or_else(|| value.get(k)).and_then(Value::as_str))
        .unwrap_or("")
        .to_string();
    let mut parts = Vec::new();
    collect(message, false, &mut parts);
    (role, if parts.is_empty() { raw.to_string() } else { parts.join(" ⏎ ") })
}

/// Strings under the keys that carry conversation content. Ids, timestamps and
/// other bookkeeping are left out.
fn collect(value: &Value, wanted: bool, out: &mut Vec<String>) {
    const KEYS: &[&str] = &[
        "text",
        "content",
        "command",
        "input",
        "output",
        "stdout",
        "stderr",
        "result",
        "prompt",
        "url",
        "query",
        "description",
        "file_path",
        "body",
    ];
    const SKIP: &[&str] = &["type", "id", "tool_use_id", "name", "role", "uuid", "signature"];
    match value {
        Value::String(s) if wanted && !s.trim().is_empty() => out.push(s.trim().to_string()),
        Value::Array(items) => items.iter().for_each(|v| collect(v, wanted, out)),
        Value::Object(map) => {
            map.iter().filter(|(k, _)| !SKIP.contains(&k.as_str())).for_each(|(k, v)| collect(v, wanted || KEYS.contains(&k.as_str()), out))
        }
        _ => {}
    }
}

/// At most `WIDTH` characters, centred on `needle` when the text holds it.
fn window(text: &str, needle: &str) -> String {
    let chars: Vec<char> = text.chars().collect();
    if chars.len() <= WIDTH {
        return text.to_string();
    }
    let at = text.to_lowercase().find(&needle.to_lowercase()).filter(|_| !needle.is_empty()).map_or(0, |b| text[..b].chars().count());
    let start = at.saturating_sub(WIDTH / 3).min(chars.len() - WIDTH);
    let body: String = chars[start..start + WIDTH].iter().collect();
    format!("{}{body}{}", if start > 0 { "…" } else { "" }, if start + WIDTH < chars.len() { "…" } else { "" })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn flattens_a_message_and_skips_bookkeeping() {
        let raw = r#"{"type":"assistant","uuid":"abc","cwd":"/x","message":{"role":"assistant","content":[{"type":"text","text":"hello"},{"type":"tool_use","input":{"command":"ls -la"}}]}}"#;
        assert_eq!(flatten(raw), ("assistant".into(), "hello ⏎ ls -la".into()));
        assert_eq!(flatten("plain log line").1, "plain log line");
    }

    #[test]
    fn window_keeps_the_needle_visible() {
        let text = format!("{}NEEDLE{}", "a".repeat(400), "b".repeat(400));
        let w = window(&text, "needle");
        assert!(w.contains("NEEDLE") && w.chars().count() <= WIDTH + 2);
        assert_eq!(window("short", "x"), "short");
    }
}