use serde_json::Value;
use crate::align::{Change, Diff, FieldDiff, Inline, Op};
use crate::model::{Step, Trace};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReportFormat {
Human,
Summary,
Json,
}
#[derive(Clone, Copy, Debug)]
pub struct RenderOptions {
pub color: bool,
pub verbose: bool,
pub context: usize,
}
impl Default for RenderOptions {
fn default() -> Self {
RenderOptions {
color: false,
verbose: false,
context: 2,
}
}
}
pub fn render(diff: &Diff, a: &Trace, b: &Trace, fmt: ReportFormat, opts: RenderOptions) -> String {
match fmt {
ReportFormat::Human => human(diff, a, b, opts),
ReportFormat::Summary => summary(diff),
ReportFormat::Json => {
serde_json::to_string_pretty(diff).unwrap_or_else(|e| format!("{{\"error\":\"{e}\"}}"))
}
}
}
fn summary(diff: &Diff) -> String {
let s = diff.stats;
let fd = diff
.first_divergence
.map(|i| i.to_string())
.unwrap_or_else(|| "none".into());
format!(
"similarity={:.3} equal={} changed={} added={} removed={} first_divergence={}",
diff.similarity, s.equal, s.changed, s.inserted, s.deleted, fd
)
}
struct Paint {
on: bool,
}
impl Paint {
fn c(&self, code: &str, s: &str) -> String {
if self.on {
format!("\x1b[{code}m{s}\x1b[0m")
} else {
s.to_string()
}
}
fn red(&self, s: &str) -> String {
self.c("31", s)
}
fn green(&self, s: &str) -> String {
self.c("32", s)
}
fn yellow(&self, s: &str) -> String {
self.c("33", s)
}
fn cyan(&self, s: &str) -> String {
self.c("36", s)
}
fn dim(&self, s: &str) -> String {
self.c("2", s)
}
fn bold(&self, s: &str) -> String {
self.c("1", s)
}
}
fn human(diff: &Diff, a: &Trace, b: &Trace, opts: RenderOptions) -> String {
let p = Paint { on: opts.color };
let mut out = String::new();
let s = diff.stats;
out.push_str(&p.bold("veer"));
out.push_str(&p.dim(" (- left / + right)\n"));
out.push_str(&format!(
"similarity {} · {} equal, {} changed, {} added, {} removed\n",
p.bold(&format!("{:.3}", diff.similarity)),
s.equal,
p.yellow(&s.changed.to_string()),
p.green(&s.inserted.to_string()),
p.red(&s.deleted.to_string()),
));
match diff.first_divergence {
Some(i) => out.push_str(&p.dim(&format!("first divergence at op {i}\n"))),
None => {
out.push_str(&p.green("traces are identical after normalization\n"));
return out;
}
}
out.push('\n');
let visible = compute_visibility(&diff.ops, opts);
let mut hidden_run = 0usize;
for (k, op) in diff.ops.iter().enumerate() {
if !visible[k] {
hidden_run += 1;
continue;
}
if hidden_run > 0 {
out.push_str(&p.dim(&format!(" … {hidden_run} unchanged …\n")));
hidden_run = 0;
}
render_op(&mut out, &p, op, a, b);
}
if hidden_run > 0 {
out.push_str(&p.dim(&format!(" … {hidden_run} unchanged …\n")));
}
out
}
fn compute_visibility(ops: &[Op], opts: RenderOptions) -> Vec<bool> {
let mut visible = vec![opts.verbose; ops.len()];
for (k, op) in ops.iter().enumerate() {
if !op.is_equal() {
let lo = k.saturating_sub(opts.context);
let hi = (k + opts.context + 1).min(ops.len());
for slot in visible.iter_mut().take(hi).skip(lo) {
*slot = true;
}
}
}
visible
}
fn render_op(out: &mut String, p: &Paint, op: &Op, a: &Trace, b: &Trace) {
match op {
Op::Equal { a: i, .. } => {
out.push_str(&p.dim(&format!(" = {}\n", a.steps[*i].label())));
}
Op::Insert { b: j } => {
out.push_str(&p.green(&format!(" + {}\n", preview(&b.steps[*j]))));
}
Op::Delete { a: i } => {
out.push_str(&p.red(&format!(" - {}\n", preview(&a.steps[*i]))));
}
Op::Change {
a: i,
similarity,
fields,
..
} => {
out.push_str(&p.yellow(&format!(
" ~ {} ({})\n",
a.steps[*i].label(),
p.dim(&format!("similarity {similarity:.2}"))
)));
for f in fields {
render_field(out, p, f);
}
}
}
}
fn render_field(out: &mut String, p: &Paint, f: &FieldDiff) {
let path = p.cyan(&f.path);
match &f.change {
Change::Added { value } => {
out.push_str(&format!(
" {path}: {}\n",
p.green(&format!("+ {value}"))
));
}
Change::Removed { value } => {
out.push_str(&format!(
" {path}: {}\n",
p.red(&format!("- {value}"))
));
}
Change::Modified { old, new, inline } => {
if let Some(inline) = inline {
out.push_str(&format!(" {path}: {}\n", render_inline(p, inline)));
} else {
out.push_str(&format!(
" {path}: {} {} {}\n",
p.red(old),
p.dim("→"),
p.green(new)
));
}
}
}
}
fn render_inline(p: &Paint, inline: &[Inline]) -> String {
let mut parts = Vec::with_capacity(inline.len());
for token in inline {
match token {
Inline::Equal(w) => parts.push(w.clone()),
Inline::Delete(w) => parts.push(p.red(&format!("[-{w}-]"))),
Inline::Insert(w) => parts.push(p.green(&format!("{{+{w}+}}"))),
}
}
parts.join(" ")
}
fn preview(step: &Step) -> String {
let mut s = step.label();
if let Some(content) = &step.content {
s.push_str(&format!(" {:?}", truncate(content, 80)));
} else if let Some(args) = &step.args {
s.push_str(&format!(" {}", truncate(&compact(args), 80)));
}
s
}
fn compact(v: &Value) -> String {
serde_json::to_string(v).unwrap_or_default()
}
fn truncate(s: &str, max: usize) -> String {
let count = s.chars().count();
if count <= max {
s.to_string()
} else {
let head: String = s.chars().take(max).collect();
format!("{head}…")
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::Config;
use crate::model::StepKind;
use serde_json::json;
fn diff_of(a: Trace, b: Trace) -> (Diff, Trace, Trace) {
let cfg = Config::default();
let mut na = a;
let mut nb = b;
cfg.normalizer.apply(&mut na);
cfg.normalizer.apply(&mut nb);
let d = crate::align::align(&na, &nb, &cfg);
(d, na, nb)
}
#[test]
fn summary_reports_counts() {
let a = Trace::from_steps(vec![Step::new(StepKind::Message).with_content("hi")]);
let b = Trace::from_steps(vec![
Step::new(StepKind::Message).with_content("hi"),
Step::new(StepKind::Message).with_content("bye"),
]);
let (d, _, _) = diff_of(a, b);
let s = summary(&d);
assert!(s.contains("added=1"), "{s}");
}
#[test]
fn human_shows_changed_arg_path() {
let a = Trace::from_steps(vec![
Step::new(StepKind::ToolCall)
.with_name("get_weather")
.with_args(json!({"city": "Paris"})),
]);
let b = Trace::from_steps(vec![
Step::new(StepKind::ToolCall)
.with_name("get_weather")
.with_args(json!({"city": "Berlin"})),
]);
let (d, na, nb) = diff_of(a, b);
let text = render(&d, &na, &nb, ReportFormat::Human, RenderOptions::default());
assert!(text.contains("args.city"), "{text}");
assert!(text.contains("Paris"));
assert!(text.contains("Berlin"));
}
#[test]
fn json_is_valid_and_has_ops() {
let a = Trace::from_steps(vec![Step::new(StepKind::Message).with_content("hi")]);
let b = Trace::from_steps(vec![Step::new(StepKind::Message).with_content("ho")]);
let (d, na, nb) = diff_of(a, b);
let text = render(&d, &na, &nb, ReportFormat::Json, RenderOptions::default());
let v: Value = serde_json::from_str(&text).unwrap();
assert!(v.get("ops").is_some());
assert!(v.get("similarity").is_some());
}
}