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,
}
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())
}
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").or_else(|| value.get("payload")).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(" ⏎ ") })
}
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",
"arguments",
];
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))
}
_ => {}
}
}
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 flattens_codex_rollout_lines_from_the_payload() {
let message = r#"{"timestamp":"2026-11-27T09:01:00Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"ship it"}]}}"#;
assert_eq!(flatten(message), ("user".into(), "ship it".into()));
let call = r#"{"type":"response_item","payload":{"type":"function_call","name":"shell","arguments":"{\"command\":[\"ls\"]}"}}"#;
assert!(flatten(call).1.contains("ls"), "{}", flatten(call).1);
}
#[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");
}
}