Skip to content

The platform for continuously improving AI agents.

41.6 KB
Raw Blame
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};

use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use sha2::{Digest, Sha256};
use trace_types::{
    SpanRecord,
    semconv::{
        GEN_AI_OPERATION_NAME, GEN_AI_REQUEST_MODEL, GEN_AI_RESPONSE_FINISH_REASONS,
        GEN_AI_RESPONSE_MODEL, GEN_AI_TOOL_NAME, GEN_AI_USAGE_INPUT_TOKENS,
        GEN_AI_USAGE_OUTPUT_TOKENS, GEN_AI_USAGE_TOTAL_TOKENS, OVERMIND_COST,
        OVERMIND_EXPECTATIONS, OVERMIND_FEEDBACK_PREFIX, OVERMIND_SCORE_PREFIX, OVERMIND_SPAN_TYPE,
        is_score_key,
    },
};

use crate::model::{EdgeKind, EvalKind, NodeCodeContext, NodeKind, PathStep, make_edge_id};

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExtractedNodeObs {
    pub node_id: String,
    pub label: String,
    pub kind: NodeKind,
    pub services: Vec<String>,
    pub span_count: u64,
    pub error_count: u64,
    pub total_duration_ms: f64,
    pub total_tokens: u64,
    pub total_cost_usd: f64,
    pub is_entry: bool,
    pub is_exit: bool,
    pub has_self_loop: bool,
    pub code_context: NodeCodeContext,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExtractedEdgeObs {
    pub edge_id: String,
    pub from_node_id: String,
    pub to_node_id: String,
    pub kind: EdgeKind,
    pub transition_count: u64,
    pub is_loop: bool,
    pub total_gap_ms: f64,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExtractedLlmCall {
    pub node_id: String,
    pub label: String,
    pub model: Option<String>,
    pub error: bool,
    pub duration_ms: f64,
    pub input_tokens: Option<u64>,
    pub output_tokens: Option<u64>,
    pub cost_usd: f64,
    pub finish_reasons: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExtractedToolCall {
    pub node_id: String,
    pub tool_name: String,
    pub error: bool,
    pub duration_ms: f64,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExtractedEval {
    pub name: String,
    pub kind: EvalKind,
    pub passed: Option<bool>,
    pub score: Option<f64>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExtractedTrace {
    pub trace_id: String,
    pub service_name: String,
    pub services: Vec<String>,
    pub root_span_name: String,
    pub start_time_ns: i64,
    pub end_time_ns: i64,
    pub duration_ms: f64,
    pub status_code: i32,
    pub span_count: u64,
    pub path_id: String,
    pub signature: String,
    pub collapsed_signature: String,
    pub steps: Vec<PathStep>,
    pub node_ids: Vec<String>,
    pub edge_ids: Vec<String>,
    pub has_loops: bool,
    pub loop_count: u32,
    pub max_depth: u32,
    pub total_tokens: u64,
    pub total_cost_usd: f64,
    pub output_label: Option<String>,
    pub nodes: Vec<ExtractedNodeObs>,
    pub edges: Vec<ExtractedEdgeObs>,
    pub llm_calls: Vec<ExtractedLlmCall>,
    pub tool_calls: Vec<ExtractedToolCall>,
    pub evals: Vec<ExtractedEval>,
    pub fingerprint: String,
}

struct WalkedSpan {
    span_idx: usize,
    depth: u32,
    parent_span_idx: Option<usize>,
    has_children: bool,
}

struct StepEntry {
    step: PathStep,
    span_idx: Option<usize>,
    parent_span_idx: Option<usize>,
    start_time_ns: i64,
    end_time_ns: i64,
}

#[derive(Default)]
struct NodeAccum {
    label: String,
    kind: Option<NodeKind>,
    services: BTreeSet<String>,
    span_count: u64,
    error_count: u64,
    total_duration_ms: f64,
    total_tokens: u64,
    total_cost_usd: f64,
    is_entry: bool,
    is_exit: bool,
    has_self_loop: bool,
    filepaths: BTreeSet<String>,
    functions: BTreeSet<String>,
    namespaces: BTreeSet<String>,
    capabilities: BTreeSet<String>,
    models: BTreeSet<String>,
    tools: BTreeSet<String>,
    span_types: BTreeSet<String>,
}

#[derive(Default)]
struct EdgeAccum {
    from_node_id: String,
    to_node_id: String,
    kind: Option<EdgeKind>,
    transition_count: u64,
    is_loop: bool,
    total_gap_ms: f64,
}

pub fn extract_trace(spans: &[SpanRecord]) -> Option<ExtractedTrace> {
    if spans.is_empty() {
        return None;
    }

    let trace_id = spans[0].trace_id.clone();

    // Map span_id -> index; if duplicate span_ids appear, prefer earliest start_time_ns.
    let mut id_to_idx: HashMap<&str, usize> = HashMap::with_capacity(spans.len());
    for (idx, span) in spans.iter().enumerate() {
        id_to_idx
            .entry(span.span_id.as_str())
            .and_modify(|existing| {
                if span.start_time_ns < spans[*existing].start_time_ns {
                    *existing = idx;
                }
            })
            .or_insert(idx);
    }

    // Build parent -> children adjacency list.
    let mut children_map: HashMap<usize, Vec<usize>> = HashMap::new();
    let mut parent_of: Vec<Option<usize>> = vec![None; spans.len()];
    let mut roots: Vec<usize> = Vec::new();

    for (idx, span) in spans.iter().enumerate() {
        let resolved_parent = span
            .parent_span_id
            .as_deref()
            .map(str::trim)
            .filter(|pid| !pid.is_empty() && *pid != span.span_id)
            .and_then(|pid| id_to_idx.get(pid).copied())
            .filter(|&pidx| pidx != idx);

        if let Some(pidx) = resolved_parent {
            parent_of[idx] = Some(pidx);
            children_map.entry(pidx).or_default().push(idx);
        } else {
            roots.push(idx);
        }
    }

    let sort_indices = |list: &mut Vec<usize>| {
        list.sort_by(|&a, &b| {
            spans[a]
                .start_time_ns
                .cmp(&spans[b].start_time_ns)
                .then_with(|| spans[a].span_id.cmp(&spans[b].span_id))
        });
    };

    sort_indices(&mut roots);
    for children in children_map.values_mut() {
        sort_indices(children);
    }

    // DFS pre-order traversal guarded against parent_span_id cycles.
    let mut walked: Vec<WalkedSpan> = Vec::with_capacity(spans.len());
    let mut visited_span_idxs: HashSet<usize> = HashSet::with_capacity(spans.len());

    fn dfs(
        idx: usize,
        depth: u32,
        parent_idx: Option<usize>,
        children_map: &HashMap<usize, Vec<usize>>,
        visited: &mut HashSet<usize>,
        out: &mut Vec<WalkedSpan>,
    ) {
        if !visited.insert(idx) {
            return;
        }
        let child_list = children_map.get(&idx);
        let has_children = child_list.is_some_and(|c| !c.is_empty());
        out.push(WalkedSpan {
            span_idx: idx,
            depth,
            parent_span_idx: parent_idx,
            has_children,
        });
        if let Some(children) = child_list {
            for &child in children {
                dfs(child, depth + 1, Some(idx), children_map, visited, out);
            }
        }
    }

    for &root_idx in &roots {
        dfs(
            root_idx,
            0,
            None,
            &children_map,
            &mut visited_span_idxs,
            &mut walked,
        );
    }

    // Fallback for any disconnected parent-cycle components so no span is ever dropped.
    if visited_span_idxs.len() < spans.len() {
        let mut remaining: Vec<usize> = (0..spans.len())
            .filter(|idx| !visited_span_idxs.contains(idx))
            .collect();
        sort_indices(&mut remaining);
        for idx in remaining {
            if !visited_span_idxs.contains(&idx) {
                dfs(idx, 0, None, &children_map, &mut visited_span_idxs, &mut walked);
            }
        }
    }

    // Canonicalize every walked span up front so we know which span is the last LLM span.
    let canonical_nodes: Vec<(String, String, NodeKind)> = walked
        .iter()
        .map(|w| canonicalize_span(&spans[w.span_idx]))
        .collect();

    let last_llm_walk_pos = canonical_nodes
        .iter()
        .rposition(|(_, _, kind)| *kind == NodeKind::Llm);

    let last_walk_pos = walked.len().saturating_sub(1);

    let mut span_idx_to_node_id: HashMap<usize, String> = HashMap::with_capacity(walked.len());
    for (w, (node_id, _, _)) in walked.iter().zip(canonical_nodes.iter()) {
        span_idx_to_node_id.insert(w.span_idx, node_id.clone());
    }

    // Build ordered execution steps (including emitted output steps) and collect per-span telemetry.
    let mut step_entries: Vec<StepEntry> = Vec::with_capacity(walked.len() + 2);
    let mut visited_node_ids: HashSet<String> = HashSet::new();
    let mut node_accums: BTreeMap<String, NodeAccum> = BTreeMap::new();
    let mut llm_calls: Vec<ExtractedLlmCall> = Vec::new();
    let mut tool_calls: Vec<ExtractedToolCall> = Vec::new();
    let mut evals: Vec<ExtractedEval> = Vec::new();
    let mut services_set: BTreeSet<String> = BTreeSet::new();
    let mut any_error_root = false;

    for (pos, w) in walked.iter().enumerate() {
        let span = &spans[w.span_idx];
        let (node_id, label, kind) = canonical_nodes[pos].clone();
        let duration_ms = span_duration_ms(span);
        let tokens = span_total_tokens(span);
        let cost_usd = span_cost_usd(span);
        let is_error = span.status_code == 2;
        if w.depth == 0 && is_error {
            any_error_root = true;
        }
        if !span.service_name.trim().is_empty() {
            services_set.insert(span.service_name.trim().to_string());
        }

        let is_loop_back = visited_node_ids.contains(&node_id);
        visited_node_ids.insert(node_id.clone());

        let step_index = step_entries.len() as u32;
        step_entries.push(StepEntry {
            step: PathStep {
                step_index,
                node_id: node_id.clone(),
                label: label.clone(),
                kind,
                depth: w.depth,
                is_loop_back,
            },
            span_idx: Some(w.span_idx),
            parent_span_idx: w.parent_span_idx,
            start_time_ns: span.start_time_ns,
            end_time_ns: span.end_time_ns.max(span.start_time_ns),
        });

        let entry = node_accums.entry(node_id.clone()).or_default();
        if entry.label.is_empty() {
            entry.label = label.clone();
            entry.kind = Some(kind);
        }
        if !span.service_name.trim().is_empty() {
            entry.services.insert(span.service_name.trim().to_string());
        }
        entry.span_count += 1;
        if is_error {
            entry.error_count += 1;
        }
        entry.total_duration_ms += duration_ms;
        entry.total_tokens += tokens;
        entry.total_cost_usd += cost_usd;
        collect_code_context(span, entry);

        // Collect LLM / tool summaries.
        if kind == NodeKind::Llm {
            let model = span_model(span);
            let input_tokens = span_attr_u64(span, GEN_AI_USAGE_INPUT_TOKENS);
            let output_tokens = span_attr_u64(span, GEN_AI_USAGE_OUTPUT_TOKENS);
            let finish_reasons = span_finish_reasons(span);
            llm_calls.push(ExtractedLlmCall {
                node_id: node_id.clone(),
                label: label.clone(),
                model,
                error: is_error,
                duration_ms,
                input_tokens,
                output_tokens,
                cost_usd,
                finish_reasons,
            });
        } else if kind == NodeKind::Tool {
            tool_calls.push(ExtractedToolCall {
                node_id: node_id.clone(),
                tool_name: label.clone(),
                error: is_error,
                duration_ms,
            });
        }

        // Collect evals/scores/expectations/feedback.
        extract_span_evals(span, &mut evals);

        // Determine if this span emits an Output node immediately after it.
        let output_label = resolve_span_output_label(
            span,
            kind,
            w.has_children,
            pos == last_walk_pos,
            Some(pos) == last_llm_walk_pos,
        );

        if let Some(out_label) = output_label {
            push_output_step(
                &out_label,
                w.depth,
                span,
                &mut visited_node_ids,
                &mut step_entries,
                &mut node_accums,
            );
        }
    }

    // If a root span errored and the trace did not already end with an output node, emit output:error.
    if any_error_root
        && step_entries
            .last()
            .is_some_and(|last| last.step.kind != NodeKind::Output)
    {
        let last_span_idx = walked[last_walk_pos].span_idx;
        let last_span = &spans[last_span_idx];
        let depth = walked[last_walk_pos].depth;
        push_output_step(
            "error",
            depth,
            last_span,
            &mut visited_node_ids,
            &mut step_entries,
            &mut node_accums,
        );
    }

    // Mark entry and exit nodes.
    if let Some(first) = step_entries.first()
        && let Some(node) = node_accums.get_mut(&first.step.node_id)
    {
        node.is_entry = true;
    }
    if let Some(last) = step_entries.last()
        && let Some(node) = node_accums.get_mut(&last.step.node_id)
    {
        node.is_exit = true;
    }

    // Build transition edges and structural parent -> child edges.
    let mut edge_accums: BTreeMap<String, EdgeAccum> = BTreeMap::new();
    let mut edge_order: Vec<String> = Vec::new();
    let mut edge_seen: HashSet<String> = HashSet::new();

    for i in 1..step_entries.len() {
        let prev = &step_entries[i - 1];
        let curr = &step_entries[i];

        let is_direct_child = curr.span_idx.is_some()
            && curr.parent_span_idx.is_some()
            && curr.parent_span_idx == prev.span_idx;

        let (kind, is_loop) = if curr.step.kind == NodeKind::Output {
            (EdgeKind::Output, curr.step.is_loop_back)
        } else if curr.step.is_loop_back {
            (EdgeKind::Loop, true)
        } else if is_direct_child {
            (EdgeKind::Child, false)
        } else {
            (EdgeKind::Next, false)
        };

        let gap_ms = if kind == EdgeKind::Child {
            (curr.start_time_ns - prev.start_time_ns).max(0) as f64 / 1_000_000.0
        } else {
            (curr.start_time_ns - prev.end_time_ns).max(0) as f64 / 1_000_000.0
        };

        record_edge(
            &prev.step.node_id,
            &curr.step.node_id,
            kind,
            is_loop,
            gap_ms,
            &mut edge_accums,
            &mut edge_order,
            &mut edge_seen,
            &mut node_accums,
        );

        // Emit structural parent -> child nesting edge when parent was not the immediately preceding step.
        if let (Some(curr_idx), Some(parent_idx)) = (curr.span_idx, curr.parent_span_idx)
            && prev.span_idx != Some(parent_idx)
            && let Some(parent_node_id) = span_idx_to_node_id.get(&parent_idx)
        {
            let parent_span = &spans[parent_idx];
            let curr_span = &spans[curr_idx];
            let child_gap_ms =
                (curr_span.start_time_ns - parent_span.start_time_ns).max(0) as f64 / 1_000_000.0;
            let is_self_child = parent_node_id == &curr.step.node_id;
            record_edge(
                parent_node_id,
                &curr.step.node_id,
                EdgeKind::Child,
                is_self_child,
                child_gap_ms,
                &mut edge_accums,
                &mut edge_order,
                &mut edge_seen,
                &mut node_accums,
            );
        }
    }

    let steps: Vec<PathStep> = step_entries.into_iter().map(|e| e.step).collect();
    let path_id = compute_path_id(&steps);
    let signature = build_signature(&steps);
    let collapsed_signature = build_collapsed_signature(&steps);

    let mut node_ids: Vec<String> = Vec::new();
    let mut node_seen: HashSet<&str> = HashSet::new();
    for step in &steps {
        if node_seen.insert(step.node_id.as_str()) {
            node_ids.push(step.node_id.clone());
        }
    }

    let loop_count = steps.iter().filter(|s| s.is_loop_back).count() as u32;
    let has_loops = loop_count > 0 || edge_accums.values().any(|e| e.is_loop);
    let max_depth = steps.iter().map(|s| s.depth).max().unwrap_or(0);

    let start_time_ns = spans.iter().map(|s| s.start_time_ns).min().unwrap_or(0);
    let end_time_ns = spans
        .iter()
        .map(|s| s.end_time_ns.max(s.start_time_ns))
        .max()
        .unwrap_or(start_time_ns);
    let sum_duration_ns: i64 = spans.iter().map(|s| s.duration_ns.max(0)).sum();
    let duration_ms = if end_time_ns > start_time_ns {
        (end_time_ns - start_time_ns) as f64 / 1_000_000.0
    } else {
        sum_duration_ns as f64 / 1_000_000.0
    };

    let root_span = &spans[walked[0].span_idx];
    let root_span_name = root_span.name.clone();
    let service_name = if !root_span.service_name.trim().is_empty() {
        root_span.service_name.trim().to_string()
    } else {
        services_set
            .iter()
            .next()
            .cloned()
            .unwrap_or_else(|| "unknown".to_string())
    };
    if services_set.is_empty() {
        services_set.insert(service_name.clone());
    }

    let status_code = if spans.iter().any(|s| s.status_code == 2) {
        2
    } else if spans.iter().any(|s| s.status_code == 1) {
        1
    } else {
        0
    };

    let total_tokens: u64 = spans.iter().map(span_total_tokens).sum();
    let total_cost_usd = round_usd(spans.iter().map(span_cost_usd).sum());
    let output_label = steps
        .iter()
        .rev()
        .find(|s| s.kind == NodeKind::Output)
        .map(|s| s.label.clone());

    let nodes: Vec<ExtractedNodeObs> = node_accums
        .into_iter()
        .map(|(node_id, acc)| ExtractedNodeObs {
            node_id,
            label: acc.label,
            kind: acc.kind.unwrap_or(NodeKind::Span),
            services: acc.services.into_iter().collect(),
            span_count: acc.span_count,
            error_count: acc.error_count,
            total_duration_ms: acc.total_duration_ms,
            total_tokens: acc.total_tokens,
            total_cost_usd: round_usd(acc.total_cost_usd),
            is_entry: acc.is_entry,
            is_exit: acc.is_exit,
            has_self_loop: acc.has_self_loop,
            code_context: NodeCodeContext {
                filepaths: acc.filepaths.into_iter().collect(),
                functions: acc.functions.into_iter().collect(),
                namespaces: acc.namespaces.into_iter().collect(),
                capabilities: acc.capabilities.into_iter().collect(),
                models: acc.models.into_iter().collect(),
                tools: acc.tools.into_iter().collect(),
                span_types: acc.span_types.into_iter().collect(),
            },
        })
        .collect();

    let edges: Vec<ExtractedEdgeObs> = edge_accums
        .into_iter()
        .map(|(edge_id, acc)| ExtractedEdgeObs {
            edge_id,
            from_node_id: acc.from_node_id,
            to_node_id: acc.to_node_id,
            kind: acc.kind.unwrap_or(EdgeKind::Next),
            transition_count: acc.transition_count,
            is_loop: acc.is_loop,
            total_gap_ms: acc.total_gap_ms,
        })
        .collect();

    let mut extracted = ExtractedTrace {
        trace_id,
        service_name,
        services: services_set.into_iter().collect(),
        root_span_name,
        start_time_ns,
        end_time_ns,
        duration_ms,
        status_code,
        span_count: spans.len() as u64,
        path_id,
        signature,
        collapsed_signature,
        steps,
        node_ids,
        edge_ids: edge_order,
        has_loops,
        loop_count,
        max_depth,
        total_tokens,
        total_cost_usd,
        output_label,
        nodes,
        edges,
        llm_calls,
        tool_calls,
        evals,
        fingerprint: String::new(),
    };

    extracted.fingerprint = compute_fingerprint(&extracted);
    Some(extracted)
}

#[allow(clippy::too_many_arguments)]
fn record_edge(
    from_node_id: &str,
    to_node_id: &str,
    kind: EdgeKind,
    is_loop: bool,
    gap_ms: f64,
    edge_accums: &mut BTreeMap<String, EdgeAccum>,
    edge_order: &mut Vec<String>,
    edge_seen: &mut HashSet<String>,
    node_accums: &mut BTreeMap<String, NodeAccum>,
) {
    let edge_id = make_edge_id(from_node_id, to_node_id, kind);
    if edge_seen.insert(edge_id.clone()) {
        edge_order.push(edge_id.clone());
    }
    let acc = edge_accums.entry(edge_id).or_default();
    if acc.from_node_id.is_empty() {
        acc.from_node_id = from_node_id.to_string();
        acc.to_node_id = to_node_id.to_string();
        acc.kind = Some(kind);
    }
    acc.transition_count += 1;
    acc.is_loop |= is_loop;
    acc.total_gap_ms += gap_ms;

    if from_node_id == to_node_id
        && let Some(node) = node_accums.get_mut(from_node_id)
    {
        node.has_self_loop = true;
    }
}

fn push_output_step(
    raw_label: &str,
    depth: u32,
    emitting_span: &SpanRecord,
    visited_node_ids: &mut HashSet<String>,
    step_entries: &mut Vec<StepEntry>,
    node_accums: &mut BTreeMap<String, NodeAccum>,
) {
    let label = raw_label.trim();
    if label.is_empty() {
        return;
    }
    let node_id = format!("output:{label}");
    let is_loop_back = visited_node_ids.contains(&node_id);
    visited_node_ids.insert(node_id.clone());

    let step_index = step_entries.len() as u32;
    let end_ns = emitting_span.end_time_ns.max(emitting_span.start_time_ns);
    step_entries.push(StepEntry {
        step: PathStep {
            step_index,
            node_id: node_id.clone(),
            label: label.to_string(),
            kind: NodeKind::Output,
            depth,
            is_loop_back,
        },
        span_idx: None,
        parent_span_idx: None,
        start_time_ns: end_ns,
        end_time_ns: end_ns,
    });

    let entry = node_accums.entry(node_id).or_default();
    if entry.label.is_empty() {
        entry.label = label.to_string();
        entry.kind = Some(NodeKind::Output);
    }
    if !emitting_span.service_name.trim().is_empty() {
        entry
            .services
            .insert(emitting_span.service_name.trim().to_string());
    }
    entry.span_count += 1;
    entry.is_exit = true;
    if label.eq_ignore_ascii_case("error") || emitting_span.status_code == 2 {
        entry.error_count += 1;
    }
}

pub fn canonicalize_span(span: &SpanRecord) -> (String, String, NodeKind) {
    let attrs = span.attributes.as_object();
    let span_name = {
        let trimmed = span.name.trim();
        if trimmed.is_empty() {
            "unnamed"
        } else {
            trimmed
        }
    };

    let span_type = attrs
        .and_then(|m| get_non_empty_str(m, OVERMIND_SPAN_TYPE))
        .map(str::to_ascii_lowercase);
    let op_name = attrs
        .and_then(|m| get_non_empty_str(m, GEN_AI_OPERATION_NAME))
        .map(str::to_ascii_lowercase);
    let tool_name = attrs.and_then(|m| get_non_empty_str(m, GEN_AI_TOOL_NAME));
    let has_model = span_model(span).is_some();

    if tool_name.is_some()
        || span_type.as_deref() == Some("tool")
        || matches!(
            op_name.as_deref(),
            Some("execute_tool" | "tool" | "tool_call")
        )
    {
        let label = tool_name.unwrap_or(span_name);
        return (format!("tool:{label}"), label.to_string(), NodeKind::Tool);
    }

    if span_type.as_deref() == Some("llm")
        || has_model
        || matches!(
            op_name.as_deref(),
            Some(
                "chat"
                    | "generate_content"
                    | "embeddings"
                    | "llm"
                    | "generation"
                    | "completion"
                    | "text_completion"
                    | "decisions"
            )
        )
    {
        return (
            format!("llm:{span_name}"),
            span_name.to_string(),
            NodeKind::Llm,
        );
    }

    if span_type.as_deref() == Some("agent")
        || matches!(
            op_name.as_deref(),
            Some("invoke_agent" | "agent" | "entry_point")
        )
    {
        return (
            format!("agent:{span_name}"),
            span_name.to_string(),
            NodeKind::Agent,
        );
    }

    if span_type.as_deref() == Some("retrieval")
        || matches!(op_name.as_deref(), Some("retriever" | "retrieval"))
    {
        return (
            format!("retrieval:{span_name}"),
            span_name.to_string(),
            NodeKind::Retrieval,
        );
    }

    if matches!(
        span_type.as_deref(),
        Some("chain" | "workflow" | "graph" | "task")
    ) || matches!(
        op_name.as_deref(),
        Some("chain" | "workflow" | "graph" | "task")
    ) {
        return (
            format!("chain:{span_name}"),
            span_name.to_string(),
            NodeKind::Chain,
        );
    }

    (
        format!("span:{span_name}"),
        span_name.to_string(),
        NodeKind::Span,
    )
}

fn resolve_span_output_label(
    span: &SpanRecord,
    kind: NodeKind,
    has_children: bool,
    is_last_span: bool,
    is_last_llm_span: bool,
) -> Option<String> {
    if let Some(attrs) = span.attributes.as_object() {
        for key in ["overmind.output.label", "overmind.outcome", "output.label"] {
            if let Some(label) = get_non_empty_str(attrs, key) {
                return Some(label.to_string());
            }
        }
    }

    let reasons = span_finish_reasons(span);
    let abnormal_reason = reasons.iter().find(|r| is_abnormal_finish_reason(r));
    let terminal_reason = reasons.iter().find(|r| is_terminal_finish_reason(r));

    if kind == NodeKind::Llm && !has_children {
        if let Some(reason) = abnormal_reason {
            return Some(reason.clone());
        }
        if (is_last_span || is_last_llm_span)
            && let Some(reason) = terminal_reason
        {
            return Some(reason.clone());
        }
    }

    if is_last_span {
        if span.status_code == 2 {
            return Some("error".to_string());
        }
        if let Some(reason) = abnormal_reason.or(terminal_reason) {
            return Some(reason.clone());
        }
    }

    None
}

fn is_abnormal_finish_reason(reason: &str) -> bool {
    matches!(
        reason,
        "length" | "max_tokens" | "content_filter" | "safety" | "refusal" | "error"
    )
}

fn is_terminal_finish_reason(reason: &str) -> bool {
    matches!(reason, "stop" | "end_turn" | "stop_sequence" | "completed")
}

fn collect_code_context(span: &SpanRecord, node: &mut NodeAccum) {
    let attrs = span.attributes.as_object();
    let res = span.resource_attrs.as_object();

    if let Some(m) = attrs {
        for key in ["code.filepath", "code.file.path"] {
            if let Some(v) = get_non_empty_str(m, key) {
                node.filepaths.insert(v.to_string());
            }
        }
        for key in ["code.function", "code.function.name"] {
            if let Some(v) = get_non_empty_str(m, key) {
                node.functions.insert(v.to_string());
            }
        }
        for key in ["code.namespace", "overmind.agent.name"] {
            if let Some(v) = get_non_empty_str(m, key) {
                node.namespaces.insert(v.to_string());
            }
        }
        if let Some(v) = get_non_empty_str(m, "overmind.capability.id") {
            node.capabilities.insert(v.to_string());
        }
        if let Some(v) = get_non_empty_str(m, GEN_AI_TOOL_NAME) {
            node.tools.insert(v.to_string());
        }
        if let Some(v) = get_non_empty_str(m, OVERMIND_SPAN_TYPE) {
            node.span_types.insert(v.to_ascii_lowercase());
        }
        for key in [GEN_AI_RESPONSE_MODEL, GEN_AI_REQUEST_MODEL] {
            if let Some(v) = get_non_empty_str(m, key) {
                node.models.insert(v.to_string());
            }
        }
    }

    if let Some(r) = res {
        if let Some(v) = get_non_empty_str(r, "overmind.capability.id") {
            node.capabilities.insert(v.to_string());
        }
        if let Some(v) = get_non_empty_str(r, "overmind.agent.name") {
            node.namespaces.insert(v.to_string());
        }
    }

    if let Some(model) = span
        .usage
        .model
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
    {
        node.models.insert(model.to_string());
    }
}

fn extract_span_evals(span: &SpanRecord, out: &mut Vec<ExtractedEval>) {
    if let Some(attrs) = span.attributes.as_object() {
        for (key, value) in attrs {
            if key == OVERMIND_EXPECTATIONS {
                extract_expectations_value(value, out);
                continue;
            }

            if let Some(rest) = key.strip_prefix(OVERMIND_SCORE_PREFIX) {
                let name = if rest.trim().is_empty() {
                    "score"
                } else {
                    rest.trim()
                };
                if let Some(score) = parse_f64(value) {
                    out.push(ExtractedEval {
                        name: name.to_string(),
                        kind: EvalKind::Score,
                        passed: None,
                        score: Some(score),
                    });
                } else if let Some(b) = value.as_bool() {
                    out.push(ExtractedEval {
                        name: name.to_string(),
                        kind: EvalKind::Score,
                        passed: Some(b),
                        score: None,
                    });
                }
                continue;
            }

            if let Some(rest) = key.strip_prefix(OVERMIND_FEEDBACK_PREFIX) {
                let field = rest.trim().to_ascii_lowercase();
                if is_feedback_metadata_key(&field) {
                    continue;
                }
                let name = if rest.trim().is_empty() {
                    "feedback"
                } else {
                    rest.trim()
                };
                if let Some((passed, score)) = parse_feedback_value(value) {
                    out.push(ExtractedEval {
                        name: name.to_string(),
                        kind: EvalKind::Feedback,
                        passed,
                        score,
                    });
                }
                continue;
            }

            let lower = key.to_ascii_lowercase();
            let is_numeric_score_attr = lower == "exgentic.reward"
                || lower == "reward"
                || lower == "score"
                || (is_score_key(&lower) && !lower.contains("feedback"));
            if is_numeric_score_attr && let Some(score) = parse_f64(value) {
                let name = key
                    .strip_prefix("eval.")
                    .unwrap_or(key.as_str())
                    .to_string();
                out.push(ExtractedEval {
                    name,
                    kind: EvalKind::Score,
                    passed: None,
                    score: Some(score),
                });
            }
        }
    }

    if let Some(events) = span.events.as_array() {
        for ev in events {
            let Some(obj) = ev.as_object() else {
                continue;
            };
            let ev_name = obj
                .get("name")
                .and_then(Value::as_str)
                .map(str::trim)
                .unwrap_or("");
            let ev_lower = ev_name.to_ascii_lowercase();
            let ev_attrs = obj.get("attributes").and_then(Value::as_object);

            if ev_lower == "overmind.score"
                || ev_lower.starts_with("overmind.score.")
                || ev_lower == "eval"
                || ev_lower == "score"
            {
                let Some(attrs) = ev_attrs else {
                    continue;
                };
                let score = attrs
                    .get("score")
                    .or_else(|| attrs.get("value"))
                    .and_then(parse_f64);
                let passed = attrs.get("passed").and_then(Value::as_bool);
                if score.is_some() || passed.is_some() {
                    let name = get_non_empty_str(attrs, "name")
                        .or_else(|| {
                            ev_name
                                .strip_prefix("overmind.score.")
                                .filter(|s| !s.is_empty())
                        })
                        .unwrap_or("score")
                        .to_string();
                    out.push(ExtractedEval {
                        name,
                        kind: EvalKind::Score,
                        passed,
                        score,
                    });
                }
            } else if ev_lower == "overmind.feedback" || ev_lower.starts_with("overmind.feedback.")
            {
                let Some(attrs) = ev_attrs else {
                    continue;
                };
                let score = attrs
                    .get("score")
                    .or_else(|| attrs.get("value"))
                    .and_then(parse_f64);
                let passed = attrs
                    .get("passed")
                    .and_then(Value::as_bool)
                    .or_else(|| {
                        attrs
                            .get("rating")
                            .or_else(|| attrs.get("thumbs"))
                            .and_then(parse_feedback_sentiment)
                    });
                if score.is_some() || passed.is_some() {
                    let name = get_non_empty_str(attrs, "name")
                        .or_else(|| {
                            ev_name
                                .strip_prefix("overmind.feedback.")
                                .filter(|s| !s.is_empty())
                        })
                        .unwrap_or("feedback")
                        .to_string();
                    out.push(ExtractedEval {
                        name,
                        kind: EvalKind::Feedback,
                        passed,
                        score,
                    });
                }
            } else if ev_lower == OVERMIND_EXPECTATIONS
                && let Some(attrs) = ev_attrs
                && let Some(val) = attrs.get("expectations").or_else(|| attrs.get("items"))
            {
                extract_expectations_value(val, out);
            }
        }
    }
}

fn extract_expectations_value(value: &Value, out: &mut Vec<ExtractedEval>) {
    let parsed_owned;
    let items = match value {
        Value::Array(arr) => arr,
        Value::String(s) => match serde_json::from_str::<Value>(s) {
            Ok(Value::Array(arr)) => {
                parsed_owned = arr;
                &parsed_owned
            }
            _ => return,
        },
        _ => return,
    };

    for item in items {
        let Some(obj) = item.as_object() else {
            continue;
        };
        let name = get_non_empty_str(obj, "name")
            .or_else(|| get_non_empty_str(obj, "id"))
            .unwrap_or("expectation")
            .to_string();
        let passed = obj.get("passed").and_then(Value::as_bool).or_else(|| {
            get_non_empty_str(obj, "status").and_then(|s| match s.to_ascii_lowercase().as_str() {
                "passed" | "pass" | "ok" | "true" | "success" => Some(true),
                "failed" | "fail" | "error" | "false" => Some(false),
                _ => None,
            })
        });
        let score = obj.get("score").and_then(parse_f64);
        if passed.is_some() || score.is_some() {
            out.push(ExtractedEval {
                name,
                kind: EvalKind::Expectation,
                passed,
                score,
            });
        }
    }
}

fn is_feedback_metadata_key(field: &str) -> bool {
    matches!(
        field,
        "comment" | "reason" | "user_id" | "user" | "timestamp" | "id" | "note" | "text" | "source"
    )
}

fn parse_feedback_value(value: &Value) -> Option<(Option<bool>, Option<f64>)> {
    match value {
        Value::Bool(b) => Some((Some(*b), None)),
        Value::Number(n) => n
            .as_f64()
            .filter(|f| f.is_finite())
            .map(|f| (None, Some(f))),
        Value::String(s) => {
            if let Some(sentiment) = parse_feedback_sentiment(value) {
                Some((Some(sentiment), None))
            } else {
                s.trim()
                    .parse::<f64>()
                    .ok()
                    .filter(|f| f.is_finite())
                    .map(|f| (None, Some(f)))
            }
        }
        _ => None,
    }
}

fn parse_feedback_sentiment(value: &Value) -> Option<bool> {
    match value {
        Value::Bool(b) => Some(*b),
        Value::String(s) => match s.trim().to_ascii_lowercase().as_str() {
            "thumbs_up" | "thumbsup" | "up" | "positive" | "good" | "like" | "pass" | "passed"
            | "yes" | "true" => Some(true),
            "thumbs_down" | "thumbsdown" | "down" | "negative" | "bad" | "dislike" | "fail"
            | "failed" | "no" | "false" => Some(false),
            _ => None,
        },
        _ => None,
    }
}

fn span_duration_ms(span: &SpanRecord) -> f64 {
    let ns = if span.duration_ns > 0 {
        span.duration_ns
    } else {
        (span.end_time_ns - span.start_time_ns).max(0)
    };
    ns as f64 / 1_000_000.0
}

fn span_total_tokens(span: &SpanRecord) -> u64 {
    if let Some(total) = span.usage.total_tokens {
        return total.max(0) as u64;
    }
    if let Some(total) = span_attr_u64(span, GEN_AI_USAGE_TOTAL_TOKENS) {
        return total;
    }
    let input = span_attr_u64(span, GEN_AI_USAGE_INPUT_TOKENS).unwrap_or(0);
    let output = span_attr_u64(span, GEN_AI_USAGE_OUTPUT_TOKENS).unwrap_or(0);
    input + output
}

fn span_cost_usd(span: &SpanRecord) -> f64 {
    if let Some(cost) = span.usage.cost
        && cost.is_finite()
        && cost >= 0.0
    {
        return cost;
    }
    span.attributes
        .as_object()
        .and_then(|m| m.get(OVERMIND_COST))
        .and_then(parse_f64)
        .filter(|c| *c >= 0.0)
        .unwrap_or(0.0)
}

fn span_model(span: &SpanRecord) -> Option<String> {
    if let Some(model) = span
        .usage
        .model
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
    {
        return Some(model.to_string());
    }
    let attrs = span.attributes.as_object()?;
    for key in [GEN_AI_RESPONSE_MODEL, GEN_AI_REQUEST_MODEL] {
        if let Some(v) = get_non_empty_str(attrs, key) {
            return Some(v.to_string());
        }
    }
    None
}

fn span_attr_u64(span: &SpanRecord, key: &str) -> Option<u64> {
    if let Some(slice) = span.usage.slice.as_ref().and_then(Value::as_object)
        && let Some(val) = slice.get(key).and_then(parse_f64)
        && val >= 0.0
    {
        return Some(val.round() as u64);
    }
    span.attributes
        .as_object()
        .and_then(|m| m.get(key))
        .and_then(parse_f64)
        .filter(|v| *v >= 0.0)
        .map(|v| v.round() as u64)
}

fn span_finish_reasons(span: &SpanRecord) -> Vec<String> {
    let Some(val) = span
        .attributes
        .as_object()
        .and_then(|m| m.get(GEN_AI_RESPONSE_FINISH_REASONS))
    else {
        return Vec::new();
    };
    let mut set = BTreeSet::new();
    match val {
        Value::String(s) => {
            let trimmed = s.trim();
            if !trimmed.is_empty() {
                set.insert(trimmed.to_ascii_lowercase());
            }
        }
        Value::Array(arr) => {
            for item in arr {
                if let Some(s) = item.as_str().map(str::trim).filter(|s| !s.is_empty()) {
                    set.insert(s.to_ascii_lowercase());
                }
            }
        }
        _ => {}
    }
    set.into_iter().collect()
}

fn get_non_empty_str<'a>(map: &'a Map<String, Value>, key: &str) -> Option<&'a str> {
    map.get(key)
        .and_then(Value::as_str)
        .map(str::trim)
        .filter(|s| !s.is_empty())
}

fn parse_f64(value: &Value) -> Option<f64> {
    let parsed = match value {
        Value::Number(n) => n.as_f64()?,
        Value::String(s) => s.trim().parse::<f64>().ok()?,
        _ => return None,
    };
    parsed.is_finite().then_some(parsed)
}

fn step_display_token(step: &PathStep) -> String {
    match step.kind {
        NodeKind::Tool => {
            if step.label.starts_with("tool:") {
                step.label.clone()
            } else {
                format!("tool:{}", step.label)
            }
        }
        NodeKind::Output => {
            if step.label.starts_with("output:") {
                step.label.clone()
            } else {
                format!("output:{}", step.label)
            }
        }
        _ => step.label.clone(),
    }
}

pub fn build_signature(steps: &[PathStep]) -> String {
    steps
        .iter()
        .map(step_display_token)
        .collect::<Vec<_>>()
        .join(" -> ")
}

pub fn build_collapsed_signature(steps: &[PathStep]) -> String {
    let mut parts: Vec<String> = Vec::new();
    let mut i = 0;
    while i < steps.len() {
        let node_id = &steps[i].node_id;
        let mut count = 1;
        while i + count < steps.len() && steps[i + count].node_id == *node_id {
            count += 1;
        }
        let token = step_display_token(&steps[i]);
        if count > 1 {
            parts.push(format!("{token}+"));
        } else {
            parts.push(token);
        }
        i += count;
    }
    parts.join(" -> ")
}

pub fn compute_path_id(steps: &[PathStep]) -> String {
    let mut joined = String::new();
    for (idx, step) in steps.iter().enumerate() {
        if idx > 0 {
            joined.push('\x1f');
        }
        joined.push_str(&step.node_id);
    }
    sha256_hex(&joined)
}

fn compute_fingerprint(trace: &ExtractedTrace) -> String {
    let serialized = serde_json::to_string(trace).unwrap_or_default();
    sha256_hex(&serialized)
}

pub(crate) fn sha256_hex(input: &str) -> String {
    let digest = Sha256::digest(input.as_bytes());
    let mut out = String::with_capacity(64);
    for b in digest {
        use std::fmt::Write as _;
        let _ = write!(&mut out, "{b:02x}");
    }
    out
}

pub(crate) fn round_usd(value: f64) -> f64 {
    (value * 1e6).round() / 1e6
}