Skip to content

The platform for continuously improving AI agents.

62.4 KB
Raw Blame
use std::collections::{BTreeMap, HashSet};

use serde_json::{Value, json};
use trace_types::{
    SpanRecord, UsageTotals,
    semconv::{
        ERROR_TYPE, GEN_AI_INPUT_MESSAGES, GEN_AI_OPERATION_NAME, GEN_AI_OUTPUT_MESSAGES,
        GEN_AI_REQUEST_MODEL, GEN_AI_RESPONSE_FINISH_REASONS, GEN_AI_RESPONSE_MODEL,
        GEN_AI_TOOL_CALL_ARGUMENTS, GEN_AI_TOOL_CALL_RESULT, GEN_AI_TOOL_NAME,
        GEN_AI_USAGE_INPUT_TOKENS, GEN_AI_USAGE_OUTPUT_TOKENS, OVERMIND_EXPECTATIONS,
        OVERMIND_FEEDBACK_PREFIX, OVERMIND_INPUT, OVERMIND_OUTPUT, OVERMIND_SCORE_PREFIX,
        OVERMIND_SPAN_TYPE,
    },
};

use crate::model::{
    MAX_EVIDENCE_ITEMS, MAX_EXCERPT_CHARS, RecommendedAction, SignalCatalogItem, SignalDetails,
    SignalEvidence, SignalSeverity, clip_and_redact, find_secret_matches,
};

pub struct RuleContext<'a> {
    pub service_name: &'a str,
    pub group_key: &'a str,
    pub spans: &'a [&'a SpanRecord],
    pub params: &'a Value,
}

pub struct RuleHit {
    pub message: String,
    pub details: SignalDetails,
}

pub trait SignalRule: Send + Sync {
    fn catalog_item(&self) -> SignalCatalogItem;
    fn evaluate(&self, ctx: &RuleContext<'_>) -> Option<RuleHit>;
}

pub fn builtin_rules() -> Vec<Box<dyn SignalRule>> {
    vec![
        // Reliability
        Box::new(ErrorsRule),
        Box::new(ToolErrorsRule),
        Box::new(RateLimitOrTimeoutRule),
        Box::new(ToolLoopRule),
        // Performance
        Box::new(SlowTraceRule),
        Box::new(ExcessiveLlmCallsRule),
        // Cost
        Box::new(HighCostRule),
        Box::new(HighTokensRule),
        Box::new(ContextBloatRule),
        // Quality
        Box::new(EmptyOutputRule),
        Box::new(OutputTruncationRule),
        Box::new(LowScoreRule),
        Box::new(FailedExpectationsRule),
        Box::new(NegativeFeedbackRule),
        // Safety
        Box::new(SecretLeakRule),
        Box::new(SafetyOrRefusalRule),
    ]
}

pub fn catalog() -> Vec<SignalCatalogItem> {
    builtin_rules()
        .into_iter()
        .map(|r| r.catalog_item())
        .collect()
}

pub fn catalog_item(signal_type: &str) -> Option<SignalCatalogItem> {
    catalog()
        .into_iter()
        .find(|item| item.signal_type == signal_type)
}

pub fn is_builtin(signal_type: &str) -> bool {
    catalog_item(signal_type).is_some()
}

pub(crate) fn attr<'a>(span: &'a SpanRecord, key: &str) -> Option<&'a Value> {
    span.attributes.as_object()?.get(key)
}

pub(crate) fn attr_str<'a>(span: &'a SpanRecord, key: &str) -> Option<&'a str> {
    attr(span, key)
        .and_then(Value::as_str)
        .map(str::trim)
        .filter(|s| !s.is_empty())
}

pub(crate) fn value_as_non_empty_text(value: &Value) -> Option<String> {
    match value {
        Value::Null => None,
        Value::String(s) => {
            let trimmed = s.trim();
            if trimmed.is_empty() || trimmed == "[]" || trimmed == "{}" {
                None
            } else {
                Some(s.clone())
            }
        }
        Value::Array(items) if items.is_empty() => None,
        Value::Object(map) if map.is_empty() => None,
        other => Some(other.to_string()),
    }
}

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

pub(crate) fn value_as_i64(value: &Value) -> Option<i64> {
    match value {
        Value::Number(num) => num
            .as_i64()
            .or_else(|| num.as_f64().filter(|f| f.is_finite()).map(|f| f.round() as i64)),
        Value::String(s) => s
            .trim()
            .parse::<i64>()
            .ok()
            .or_else(|| {
                s.trim()
                    .parse::<f64>()
                    .ok()
                    .filter(|f| f.is_finite())
                    .map(|f| f.round() as i64)
            }),
        _ => None,
    }
}

pub(crate) fn span_input_text(span: &SpanRecord) -> Option<String> {
    attr(span, OVERMIND_INPUT)
        .and_then(value_as_non_empty_text)
        .or_else(|| attr(span, GEN_AI_INPUT_MESSAGES).and_then(value_as_non_empty_text))
}

pub(crate) fn span_output_text(span: &SpanRecord) -> Option<String> {
    attr(span, OVERMIND_OUTPUT)
        .and_then(value_as_non_empty_text)
        .or_else(|| attr(span, GEN_AI_OUTPUT_MESSAGES).and_then(value_as_non_empty_text))
}

pub(crate) fn span_input_tokens(span: &SpanRecord) -> Option<i64> {
    attr(span, GEN_AI_USAGE_INPUT_TOKENS)
        .and_then(value_as_i64)
        .or_else(|| {
            span.usage
                .slice
                .as_ref()
                .and_then(|s| s.get(GEN_AI_USAGE_INPUT_TOKENS))
                .and_then(value_as_i64)
        })
}

pub(crate) fn span_output_tokens(span: &SpanRecord) -> Option<i64> {
    attr(span, GEN_AI_USAGE_OUTPUT_TOKENS)
        .and_then(value_as_i64)
        .or_else(|| {
            span.usage
                .slice
                .as_ref()
                .and_then(|s| s.get(GEN_AI_USAGE_OUTPUT_TOKENS))
                .and_then(value_as_i64)
        })
}

pub(crate) fn span_model(span: &SpanRecord) -> Option<&str> {
    span.usage
        .model
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .or_else(|| attr_str(span, GEN_AI_RESPONSE_MODEL))
        .or_else(|| attr_str(span, GEN_AI_REQUEST_MODEL))
}

fn span_status(code: i32) -> &'static str {
    match code {
        2 => "error",
        1 => "ok",
        _ => "unset",
    }
}

pub(crate) fn is_error_span(span: &SpanRecord) -> bool {
    span.status_code == 2 || attr(span, ERROR_TYPE).and_then(value_as_non_empty_text).is_some()
}

pub(crate) fn is_tool_span(span: &SpanRecord) -> bool {
    attr_str(span, OVERMIND_SPAN_TYPE) == Some("tool")
        || attr_str(span, GEN_AI_OPERATION_NAME)
            .is_some_and(|op| op.eq_ignore_ascii_case("execute_tool"))
        || attr_str(span, GEN_AI_TOOL_NAME).is_some()
}

pub(crate) fn tool_name_for_span(span: &SpanRecord) -> Option<String> {
    attr_str(span, GEN_AI_TOOL_NAME)
        .map(ToString::to_string)
        .or_else(|| is_tool_span(span).then(|| span.name.clone()))
}

pub(crate) fn is_llm_span(span: &SpanRecord) -> bool {
    if let Some(st) = attr_str(span, OVERMIND_SPAN_TYPE) {
        return st.eq_ignore_ascii_case("llm");
    }
    if let Some(op) = attr_str(span, GEN_AI_OPERATION_NAME) {
        return matches!(
            op.to_ascii_lowercase().as_str(),
            "chat"
                | "generate_content"
                | "embeddings"
                | "llm"
                | "generation"
                | "completion"
                | "text_completion"
        );
    }
    attr_str(span, GEN_AI_REQUEST_MODEL).is_some()
        || attr_str(span, GEN_AI_RESPONSE_MODEL).is_some()
        || span.usage.total_tokens.is_some()
}

pub(crate) fn round2(val: f64) -> f64 {
    (val * 100.0).round() / 100.0
}

pub(crate) fn group_wall_clock_ms(spans: &[&SpanRecord]) -> Option<f64> {
    let min_start = spans.iter().map(|s| s.start_time_ns).min()?;
    let max_end = spans.iter().map(|s| s.end_time_ns).max()?;
    let wall_ns = (max_end - min_start)
        .max(spans.iter().map(|s| s.duration_ns).max().unwrap_or(0))
        .max(0);
    Some(round2(wall_ns as f64 / 1_000_000.0))
}

fn evidence_from_span(span: &SpanRecord, reason: Option<String>) -> SignalEvidence {
    let status_message = if span.status_message.trim().is_empty() {
        None
    } else {
        Some(clip_and_redact(&span.status_message, MAX_EXCERPT_CHARS))
    };
    SignalEvidence {
        span_id: span.span_id.clone(),
        trace_id: span.trace_id.clone(),
        name: span.name.clone(),
        span_type: attr_str(span, OVERMIND_SPAN_TYPE).map(ToString::to_string),
        status: span_status(span.status_code).to_string(),
        status_message,
        model: span_model(span).map(ToString::to_string),
        tool: attr_str(span, GEN_AI_TOOL_NAME).map(ToString::to_string),
        duration_ms: round2(span.duration_ns as f64 / 1_000_000.0),
        tokens: span.usage.total_tokens,
        cost: span.usage.cost,
        input: span_input_text(span).map(|s| clip_and_redact(&s, MAX_EXCERPT_CHARS)),
        output: span_output_text(span).map(|s| clip_and_redact(&s, MAX_EXCERPT_CHARS)),
        reason: reason.map(|r| clip_and_redact(&r, MAX_EXCERPT_CHARS)),
    }
}

fn unique_strings<'a>(iter: impl IntoIterator<Item = &'a str>) -> Vec<String> {
    let mut seen = HashSet::new();
    let mut out = Vec::new();
    for item in iter {
        if seen.insert(item) {
            out.push(item.to_string());
        }
    }
    out
}

pub(crate) fn build_details(
    ctx: &RuleContext<'_>,
    offending: &[(&SpanRecord, Option<String>)],
    why: String,
    parameters: Value,
    measurements: Value,
    recommended_actions: Vec<RecommendedAction>,
) -> SignalDetails {
    let group_trace_ids = unique_strings(ctx.spans.iter().map(|s| s.trace_id.as_str()));
    let trace_ids = unique_strings(offending.iter().map(|(s, _)| s.trace_id.as_str()));
    let span_ids = unique_strings(offending.iter().map(|(s, _)| s.span_id.as_str()));
    let evidence_truncated = offending.len() > MAX_EVIDENCE_ITEMS;
    let evidence = offending
        .iter()
        .take(MAX_EVIDENCE_ITEMS)
        .map(|(span, reason)| evidence_from_span(span, reason.clone()))
        .collect();

    SignalDetails {
        spans: ctx.spans.len(),
        group: ctx.group_key.to_string(),
        trace_ids,
        group_trace_ids,
        span_ids,
        why,
        parameters,
        measurements,
        evidence,
        evidence_truncated,
        recommended_actions,
    }
}

fn param_f64(params: &Value, key: &str, default: f64) -> f64 {
    params.get(key).and_then(Value::as_f64).unwrap_or(default)
}

fn param_i64(params: &Value, key: &str, default: i64) -> i64 {
    params
        .get(key)
        .and_then(|v| v.as_i64().or_else(|| v.as_f64().map(|f| f.round() as i64)))
        .unwrap_or(default)
}

fn builtin_catalog_item(
    signal_type: &str,
    title: &str,
    description: &str,
    category: &str,
    severity: SignalSeverity,
    default_params: Value,
    remedy: &str,
) -> SignalCatalogItem {
    SignalCatalogItem {
        signal_type: signal_type.into(),
        title: title.into(),
        description: description.into(),
        category: category.into(),
        severity,
        default_enabled: true,
        default_params,
        remedy: remedy.into(),
        is_custom: false,
        spec: None,
    }
}

fn extract_finish_reasons(span: &SpanRecord) -> Vec<String> {
    const KEYS: &[&str] = &[
        GEN_AI_RESPONSE_FINISH_REASONS,
        "gen_ai.response.finish_reason",
        "finish_reason",
        "finish_reasons",
    ];
    let mut out = Vec::new();
    for key in KEYS {
        let Some(val) = attr(span, key) else {
            continue;
        };
        collect_reason_strings(val, &mut out);
    }
    out
}

fn collect_reason_strings(val: &Value, out: &mut Vec<String>) {
    match val {
        Value::Array(items) => {
            for item in items {
                collect_reason_strings(item, out);
            }
        }
        Value::String(s) => {
            let trimmed = s.trim();
            if trimmed.is_empty() {
                return;
            }
            if trimmed.starts_with('[')
                && let Ok(parsed) = serde_json::from_str::<Value>(trimmed)
            {
                collect_reason_strings(&parsed, out);
                return;
            }
            for part in trimmed.split(',') {
                let cleaned = part.trim().trim_matches('"');
                if !cleaned.is_empty() && !out.iter().any(|existing| existing == cleaned) {
                    out.push(cleaned.to_string());
                }
            }
        }
        _ => {}
    }
}

fn error_texts_for_span(span: &SpanRecord) -> Vec<String> {
    let mut texts = Vec::new();
    let status_msg = span.status_message.trim();
    if !status_msg.is_empty() {
        texts.push(status_msg.to_string());
    }
    if let Some(err_type) = attr(span, ERROR_TYPE).and_then(value_as_non_empty_text) {
        texts.push(err_type);
    }
    if let Some(attrs) = span.attributes.as_object() {
        for (key, val) in attrs {
            if key == ERROR_TYPE {
                continue;
            }
            let lower = key.to_ascii_lowercase();
            if (lower.contains("error") || lower.contains("exception"))
                && let Some(text) = value_as_non_empty_text(val)
            {
                texts.push(text);
            }
        }
    }
    if let Some(events) = span.events.as_array() {
        for event in events {
            let is_exc = event
                .get("name")
                .and_then(Value::as_str)
                .is_some_and(|n| n.eq_ignore_ascii_case("exception") || n.contains("error"));
            if !is_exc {
                continue;
            }
            if let Some(e_attrs) = event.get("attributes").and_then(Value::as_object) {
                for key in ["exception.type", "exception.message", "error.type", "message"] {
                    if let Some(text) = e_attrs.get(key).and_then(value_as_non_empty_text) {
                        texts.push(text);
                    }
                }
            }
        }
    }
    texts
}

fn contains_http_status_code(text: &str, code: &str) -> bool {
    let bytes = text.as_bytes();
    let needle = code.as_bytes();
    if bytes.len() < needle.len() {
        return false;
    }
    let mut pos = 0;
    while let Some(idx) = text[pos..].find(code) {
        let start = pos + idx;
        let end = start + needle.len();
        let before_ok = start == 0 || !bytes[start - 1].is_ascii_digit();
        let after_ok = end == bytes.len() || !bytes[end].is_ascii_digit();
        if before_ok && after_ok {
            return true;
        }
        pos = start + 1;
    }
    false
}

fn is_feedback_metadata_key(key: &str) -> bool {
    let lower = key.to_ascii_lowercase();
    let leaf = lower.rsplit('.').next().unwrap_or(&lower);
    matches!(
        leaf,
        "id" | "user_id"
            | "userid"
            | "user"
            | "comment"
            | "reason"
            | "note"
            | "notes"
            | "source"
            | "timestamp"
            | "created_at"
            | "updated_at"
            | "label"
            | "category"
    ) || leaf.ends_with("_id")
}

// 1. errors
struct ErrorsRule;

impl SignalRule for ErrorsRule {
    fn catalog_item(&self) -> SignalCatalogItem {
        builtin_catalog_item(
            "errors",
            "Span errors",
            "Fires when any span finishes with ERROR status or sets error.type.",
            "reliability",
            SignalSeverity::High,
            json!({}),
            "Inspect failing spans, exception messages, and upstream tool or model errors.",
        )
    }

    fn evaluate(&self, ctx: &RuleContext<'_>) -> Option<RuleHit> {
        let mut offending = Vec::new();
        for span in ctx.spans {
            if !is_error_span(span) {
                continue;
            }
            let err_type = attr(span, ERROR_TYPE).and_then(value_as_non_empty_text);
            let reason = match (err_type, span.status_message.trim()) {
                (Some(t), msg) if !msg.is_empty() => Some(format!("{t}: {msg}")),
                (Some(t), _) => Some(t),
                (None, msg) if !msg.is_empty() => Some(msg.to_string()),
                (None, _) => Some("status_code=ERROR".to_string()),
            };
            offending.push((*span, reason));
        }
        if offending.is_empty() {
            return None;
        }

        let first = offending[0].0;
        let first_reason = offending[0].1.as_deref().unwrap_or("error");
        let count = offending.len();
        let message = if count == 1 {
            format!("{} failed: {}", first.name, clip_and_redact(first_reason, 120))
        } else {
            format!("{count} errored spans (first: {})", first.name)
        };
        let why = format!(
            "{count} of {} spans recorded an error status or error.type.",
            ctx.spans.len()
        );

        let details = build_details(
            ctx,
            &offending,
            why,
            json!({}),
            json!({
                "error_span_count": count,
                "total_span_count": ctx.spans.len(),
            }),
            vec![RecommendedAction {
                kind: "inspect_trace".into(),
                label: "Open trace and inspect failing span".into(),
            }],
        );
        Some(RuleHit { message, details })
    }
}

// 2. tool_errors
struct ToolErrorsRule;

impl SignalRule for ToolErrorsRule {
    fn catalog_item(&self) -> SignalCatalogItem {
        builtin_catalog_item(
            "tool_errors",
            "Tool execution errors",
            "Fires when a tool span finishes with ERROR status or sets error.type.",
            "reliability",
            SignalSeverity::High,
            json!({}),
            "Validate tool schemas, handle downstream failures gracefully, and return structured error feedback to the model.",
        )
    }

    fn evaluate(&self, ctx: &RuleContext<'_>) -> Option<RuleHit> {
        let mut offending = Vec::new();
        let mut tools = Vec::new();
        for span in ctx.spans {
            if !is_tool_span(span) || !is_error_span(span) {
                continue;
            }
            let tool = tool_name_for_span(span).unwrap_or_else(|| span.name.clone());
            if !tools.contains(&tool) {
                tools.push(tool.clone());
            }
            let err_type = attr(span, ERROR_TYPE).and_then(value_as_non_empty_text);
            let msg = span.status_message.trim();
            let detail = match (err_type, msg) {
                (Some(t), m) if !m.is_empty() => format!("{t}: {m}"),
                (Some(t), _) => t,
                (None, m) if !m.is_empty() => m.to_string(),
                (None, _) => "status_code=ERROR".to_string(),
            };
            offending.push((*span, Some(format!("tool `{tool}` failed: {detail}"))));
        }
        if offending.is_empty() {
            return None;
        }

        let count = offending.len();
        let first_tool = &tools[0];
        let message = if count == 1 {
            format!(
                "Tool `{first_tool}` failed: {}",
                clip_and_redact(offending[0].1.as_deref().unwrap_or("error"), 100)
            )
        } else {
            format!("{count} tool calls failed (including `{first_tool}`)")
        };
        let why = format!(
            "{count} tool span(s) failed across [{}].",
            tools.join(", ")
        );
        let details = build_details(
            ctx,
            &offending,
            why,
            json!({}),
            json!({
                "tool_error_count": count,
                "failed_tools": tools,
            }),
            vec![RecommendedAction {
                kind: "check_tool".into(),
                label: "Inspect failing tool arguments and error response".into(),
            }],
        );
        Some(RuleHit { message, details })
    }
}

// 3. rate_limit_or_timeout
struct RateLimitOrTimeoutRule;

impl SignalRule for RateLimitOrTimeoutRule {
    fn catalog_item(&self) -> SignalCatalogItem {
        builtin_catalog_item(
            "rate_limit_or_timeout",
            "Rate limit or timeout",
            "Fires on provider rate limits (429), upstream overload (503/504), or timeout failures.",
            "reliability",
            SignalSeverity::High,
            json!({}),
            "Add exponential backoff with jitter, configure fallback models/providers, or raise upstream timeout budgets.",
        )
    }

    fn evaluate(&self, ctx: &RuleContext<'_>) -> Option<RuleHit> {
        const SUBSTRINGS: &[(&str, &str)] = &[
            ("rate_limit", "rate_limit"),
            ("rate limit", "rate limit"),
            ("ratelimit", "rate_limit"),
            ("too many requests", "too many requests"),
            ("overloaded", "overloaded"),
            ("gateway timeout", "gateway timeout"),
            ("timed out", "timed out"),
            ("timeout", "timeout"),
            ("service unavailable", "service unavailable"),
            ("deadline exceeded", "deadline exceeded"),
        ];
        const HTTP_CODES: &[&str] = &["429", "503", "504"];

        let mut offending = Vec::new();
        let mut triggers = Vec::new();

        for span in ctx.spans {
            let mut span_match: Option<String> = None;

            for key in ["http.response.status_code", "http.status_code"] {
                if let Some(code) = attr(span, key).and_then(value_as_i64)
                    && matches!(code, 429 | 503 | 504)
                {
                    let label = format!("HTTP {code}");
                    if !triggers.contains(&label) {
                        triggers.push(label.clone());
                    }
                    span_match = Some(format!("{key}={code}"));
                    break;
                }
            }

            if span_match.is_none() {
                for text in error_texts_for_span(span) {
                    let lower = text.to_ascii_lowercase();
                    let matched_code = HTTP_CODES
                        .iter()
                        .copied()
                        .find(|code| contains_http_status_code(&text, code));
                    let matched_phrase = SUBSTRINGS
                        .iter()
                        .find_map(|(needle, label)| lower.contains(needle).then_some(*label));
                    if let Some(tag) = matched_code.or(matched_phrase) {
                        let tag_str = tag.to_string();
                        if !triggers.contains(&tag_str) {
                            triggers.push(tag_str);
                        }
                        span_match = Some(clip_and_redact(&text, 180));
                        break;
                    }
                }
            }

            if let Some(reason) = span_match {
                offending.push((*span, Some(reason)));
            }
        }

        if offending.is_empty() {
            return None;
        }

        let count = offending.len();
        let trigger_summary = triggers.join(", ");
        let message = if count == 1 {
            format!(
                "{} hit transient failure ({trigger_summary})",
                offending[0].0.name
            )
        } else {
            format!("{count} spans hit rate limit or timeout ({trigger_summary})")
        };
        let why = format!(
            "{count} span(s) encountered rate-limit, overload, or timeout indicators [{trigger_summary}]."
        );
        let details = build_details(
            ctx,
            &offending,
            why,
            json!({}),
            json!({
                "matched_span_count": count,
                "triggers": triggers,
            }),
            vec![RecommendedAction {
                kind: "add_retry".into(),
                label: "Configure retry backoff or fallback provider".into(),
            }],
        );
        Some(RuleHit { message, details })
    }
}

// 4. tool_loop
struct ToolLoopRule;

impl SignalRule for ToolLoopRule {
    fn catalog_item(&self) -> SignalCatalogItem {
        builtin_catalog_item(
            "tool_loop",
            "Repeated tool calls",
            "Fires when the same tool is invoked at least max_repeats times in one run.",
            "reliability",
            SignalSeverity::High,
            json!({ "max_repeats": 3 }),
            "Add retry bounds, return actionable tool errors, or clarify tool instructions.",
        )
    }

    fn evaluate(&self, ctx: &RuleContext<'_>) -> Option<RuleHit> {
        let max_repeats = param_i64(ctx.params, "max_repeats", 3).max(2) as usize;
        let mut by_tool: BTreeMap<String, Vec<&SpanRecord>> = BTreeMap::new();

        for span in ctx.spans {
            if let Some(name) = tool_name_for_span(span) {
                by_tool.entry(name).or_default().push(*span);
            }
        }

        let mut looping: Vec<(String, Vec<&SpanRecord>)> = by_tool
            .into_iter()
            .filter(|(_, spans)| spans.len() >= max_repeats)
            .collect();
        if looping.is_empty() {
            return None;
        }
        looping.sort_by(|a, b| b.1.len().cmp(&a.1.len()).then_with(|| a.0.cmp(&b.0)));

        let (top_tool, top_count) = (looping[0].0.clone(), looping[0].1.len());
        let mut offending = Vec::new();
        let mut counts = serde_json::Map::new();
        for (tool, spans) in &looping {
            counts.insert(tool.clone(), json!(spans.len()));
            for (idx, span) in spans.iter().enumerate() {
                offending.push((
                    *span,
                    Some(format!("tool `{tool}` call #{} of {}", idx + 1, spans.len())),
                ));
            }
        }

        let message = format!("Tool `{top_tool}` called {top_count} times (limit {max_repeats})");
        let why = format!(
            "Tool `{top_tool}` repeated {top_count} times in {}, meeting or exceeding max_repeats={max_repeats}.",
            ctx.group_key
        );
        let details = build_details(
            ctx,
            &offending,
            why,
            json!({ "max_repeats": max_repeats }),
            json!({
                "top_tool": top_tool,
                "max_tool_calls": top_count,
                "tool_counts": counts,
            }),
            vec![RecommendedAction {
                kind: "check_tool".into(),
                label: "Inspect repeated tool arguments and results".into(),
            }],
        );
        Some(RuleHit { message, details })
    }
}

// 5. slow_trace
struct SlowTraceRule;

impl SignalRule for SlowTraceRule {
    fn catalog_item(&self) -> SignalCatalogItem {
        builtin_catalog_item(
            "slow_trace",
            "Slow execution",
            "Fires when group wall-clock duration exceeds threshold_ms.",
            "performance",
            SignalSeverity::Medium,
            json!({ "threshold_ms": 5000 }),
            "Profile the slowest LLM and tool spans; parallelize independent calls or lower latency models.",
        )
    }

    fn evaluate(&self, ctx: &RuleContext<'_>) -> Option<RuleHit> {
        let threshold_ms = param_f64(ctx.params, "threshold_ms", 5000.0);
        let duration_ms = group_wall_clock_ms(ctx.spans)?;
        if duration_ms < threshold_ms {
            return None;
        }

        let mut ranked: Vec<&SpanRecord> = ctx.spans.to_vec();
        ranked.sort_by_key(|b| std::cmp::Reverse(b.duration_ns));
        let offending: Vec<(&SpanRecord, Option<String>)> = ranked
            .into_iter()
            .map(|s| {
                let ms = round2(s.duration_ns as f64 / 1_000_000.0);
                (s, Some(format!("span took {ms} ms")))
            })
            .collect();

        let message =
            format!("Wall-clock latency {duration_ms:.0} ms (threshold {threshold_ms:.0} ms)");
        let why = format!(
            "Group wall-clock duration reached {duration_ms:.1} ms across {} spans, exceeding {threshold_ms:.0} ms.",
            ctx.spans.len()
        );
        let details = build_details(
            ctx,
            &offending,
            why,
            json!({ "threshold_ms": threshold_ms }),
            json!({
                "duration_ms": duration_ms,
                "threshold_ms": threshold_ms,
                "slowest_span_ms": offending.first().map(|(s, _)| round2(s.duration_ns as f64 / 1_000_000.0)),
            }),
            vec![RecommendedAction {
                kind: "inspect_trace".into(),
                label: "Inspect waterfall for latency bottleneck".into(),
            }],
        );
        Some(RuleHit { message, details })
    }
}

// 6. excessive_llm_calls
struct ExcessiveLlmCallsRule;

impl SignalRule for ExcessiveLlmCallsRule {
    fn catalog_item(&self) -> SignalCatalogItem {
        builtin_catalog_item(
            "excessive_llm_calls",
            "Excessive LLM calls",
            "Fires when a trace or conversation makes at least max_calls LLM invocations.",
            "performance",
            SignalSeverity::Medium,
            json!({ "max_calls": 8 }),
            "Cap agent reasoning turns, batch tool calls, or consolidate multi-step prompts into fewer LLM rounds.",
        )
    }

    fn evaluate(&self, ctx: &RuleContext<'_>) -> Option<RuleHit> {
        let max_calls = param_i64(ctx.params, "max_calls", 8).max(1) as usize;
        let mut llm_spans: Vec<&SpanRecord> = ctx
            .spans
            .iter()
            .copied()
            .filter(|s| is_llm_span(s))
            .collect();
        if llm_spans.len() < max_calls {
            return None;
        }
        llm_spans.sort_by_key(|s| s.start_time_ns);
        let count = llm_spans.len();
        let offending: Vec<(&SpanRecord, Option<String>)> = llm_spans
            .into_iter()
            .enumerate()
            .map(|(idx, s)| {
                let model = span_model(s).unwrap_or("llm");
                (s, Some(format!("LLM call #{} of {count} ({model})", idx + 1)))
            })
            .collect();

        let message = format!("{count} LLM calls in one run (limit {max_calls})");
        let why = format!(
            "Trace/conversation invoked {count} LLM spans out of {} total spans, meeting or exceeding max_calls={max_calls}.",
            ctx.spans.len()
        );
        let details = build_details(
            ctx,
            &offending,
            why,
            json!({ "max_calls": max_calls }),
            json!({
                "llm_call_count": count,
                "max_calls": max_calls,
                "total_span_count": ctx.spans.len(),
            }),
            vec![RecommendedAction {
                kind: "bound_turns".into(),
                label: "Inspect turn loop and cap max reasoning steps".into(),
            }],
        );
        Some(RuleHit { message, details })
    }
}

// 7. high_cost
struct HighCostRule;

impl SignalRule for HighCostRule {
    fn catalog_item(&self) -> SignalCatalogItem {
        builtin_catalog_item(
            "high_cost",
            "High cost",
            "Fires when total cost across a trace or conversation reaches threshold_usd.",
            "cost",
            SignalSeverity::Medium,
            json!({ "threshold_usd": 0.05 }),
            "Check prompt size, repeated LLM steps, or route routine calls to a smaller model.",
        )
    }

    fn evaluate(&self, ctx: &RuleContext<'_>) -> Option<RuleHit> {
        let threshold_usd = param_f64(ctx.params, "threshold_usd", 0.05);
        let totals = UsageTotals::sum(ctx.spans.iter().copied());
        let total_cost = totals.total_cost?;
        if total_cost < threshold_usd {
            return None;
        }

        let mut cost_spans: Vec<&SpanRecord> = ctx
            .spans
            .iter()
            .copied()
            .filter(|s| s.usage.cost.is_some())
            .collect();
        cost_spans.sort_by(|a, b| {
            b.usage
                .cost
                .unwrap_or(0.0)
                .total_cmp(&a.usage.cost.unwrap_or(0.0))
        });

        let offending: Vec<(&SpanRecord, Option<String>)> = cost_spans
            .into_iter()
            .map(|s| {
                let c = s.usage.cost.unwrap_or(0.0);
                (s, Some(format!("span cost ${c:.4}")))
            })
            .collect();

        let message = format!("Total cost ${total_cost:.4} (threshold ${threshold_usd:.4})");
        let why = format!(
            "Summed span cost is ${total_cost:.4} across {} cost-reporting spans, exceeding ${threshold_usd:.4}.",
            offending.len()
        );
        let details = build_details(
            ctx,
            &offending,
            why,
            json!({ "threshold_usd": threshold_usd }),
            json!({
                "total_cost_usd": total_cost,
                "threshold_usd": threshold_usd,
                "total_tokens": totals.total_tokens,
            }),
            vec![RecommendedAction {
                kind: "optimize_prompt".into(),
                label: "Review highest-cost LLM calls".into(),
            }],
        );
        Some(RuleHit { message, details })
    }
}

// 8. high_tokens
struct HighTokensRule;

impl SignalRule for HighTokensRule {
    fn catalog_item(&self) -> SignalCatalogItem {
        builtin_catalog_item(
            "high_tokens",
            "High token usage",
            "Fires when total tokens across a trace or conversation reach threshold_tokens.",
            "cost",
            SignalSeverity::Medium,
            json!({ "threshold_tokens": 16000 }),
            "Trim retrieved context, summarize conversation history, or cap max output tokens.",
        )
    }

    fn evaluate(&self, ctx: &RuleContext<'_>) -> Option<RuleHit> {
        let threshold_tokens = param_i64(ctx.params, "threshold_tokens", 16_000);
        let totals = UsageTotals::sum(ctx.spans.iter().copied());
        let total_tokens = totals.total_tokens?;
        if total_tokens < threshold_tokens {
            return None;
        }

        let mut token_spans: Vec<&SpanRecord> = ctx
            .spans
            .iter()
            .copied()
            .filter(|s| s.usage.total_tokens.is_some())
            .collect();
        token_spans.sort_by_key(|b| std::cmp::Reverse(b.usage.total_tokens));

        let offending: Vec<(&SpanRecord, Option<String>)> = token_spans
            .into_iter()
            .map(|s| {
                let t = s.usage.total_tokens.unwrap_or(0);
                (s, Some(format!("{t} tokens")))
            })
            .collect();

        let message = format!("{total_tokens} tokens used (threshold {threshold_tokens})");
        let why = format!(
            "Total tokens reached {total_tokens} across {} LLM spans, exceeding {threshold_tokens}.",
            offending.len()
        );
        let details = build_details(
            ctx,
            &offending,
            why,
            json!({ "threshold_tokens": threshold_tokens }),
            json!({
                "total_tokens": total_tokens,
                "threshold_tokens": threshold_tokens,
                "total_cost_usd": totals.total_cost,
            }),
            vec![RecommendedAction {
                kind: "optimize_prompt".into(),
                label: "Inspect token-heavy prompts and completions".into(),
            }],
        );
        Some(RuleHit { message, details })
    }
}

// 9. context_bloat
struct ContextBloatRule;

impl SignalRule for ContextBloatRule {
    fn catalog_item(&self) -> SignalCatalogItem {
        builtin_catalog_item(
            "context_bloat",
            "Context bloat",
            "Fires when a single LLM span has input_tokens at or above threshold_input_tokens.",
            "cost",
            SignalSeverity::Medium,
            json!({ "threshold_input_tokens": 12000 }),
            "Prune conversation history, limit retrieved document chunks, or compact tool outputs before passing them back to the model.",
        )
    }

    fn evaluate(&self, ctx: &RuleContext<'_>) -> Option<RuleHit> {
        let threshold = param_i64(ctx.params, "threshold_input_tokens", 12_000).max(1);
        let mut bloated: Vec<(&SpanRecord, i64)> = ctx
            .spans
            .iter()
            .copied()
            .filter(|s| {
                matches!(attr_str(s, OVERMIND_SPAN_TYPE), None | Some("llm"))
            })
            .filter_map(|s| {
                let input = span_input_tokens(s)?;
                (input >= threshold).then_some((s, input))
            })
            .collect();
        if bloated.is_empty() {
            return None;
        }
        bloated.sort_by_key(|(_, input)| std::cmp::Reverse(*input));
        let max_input = bloated[0].1;
        let offending: Vec<(&SpanRecord, Option<String>)> = bloated
            .into_iter()
            .map(|(s, input)| (s, Some(format!("{input} input tokens (limit {threshold})"))))
            .collect();

        let message = format!(
            "Single LLM prompt reached {max_input} input tokens (threshold {threshold})"
        );
        let why = format!(
            "{} LLM span(s) exceeded {threshold} input tokens (peak {max_input}).",
            offending.len()
        );
        let details = build_details(
            ctx,
            &offending,
            why,
            json!({ "threshold_input_tokens": threshold }),
            json!({
                "max_input_tokens": max_input,
                "threshold_input_tokens": threshold,
                "bloated_span_count": offending.len(),
            }),
            vec![RecommendedAction {
                kind: "trim_context".into(),
                label: "Trim prompt history and retrieved chunks".into(),
            }],
        );
        Some(RuleHit { message, details })
    }
}

// 10. empty_output
struct EmptyOutputRule;

impl SignalRule for EmptyOutputRule {
    fn catalog_item(&self) -> SignalCatalogItem {
        builtin_catalog_item(
            "empty_output",
            "Empty output",
            "Fires when a non-errored LLM or agent span has input recorded but no output.",
            "quality",
            SignalSeverity::Medium,
            json!({}),
            "Check model finish reasons, token limits, or output instrumentation on the affected span.",
        )
    }

    fn evaluate(&self, ctx: &RuleContext<'_>) -> Option<RuleHit> {
        let mut offending = Vec::new();
        for span in ctx.spans {
            if is_error_span(span) {
                continue;
            }
            let span_type = attr_str(span, OVERMIND_SPAN_TYPE);
            let is_llm_or_agent = matches!(span_type, Some("llm" | "agent"))
                || attr_str(span, GEN_AI_REQUEST_MODEL).is_some()
                || attr_str(span, GEN_AI_RESPONSE_MODEL).is_some()
                || attr(span, GEN_AI_INPUT_MESSAGES).is_some();
            if !is_llm_or_agent {
                continue;
            }
            if span_input_text(span).is_some() && span_output_text(span).is_none() {
                offending.push((
                    *span,
                    Some("input present without gen_ai.output.messages or overmind.output".into()),
                ));
            }
        }
        if offending.is_empty() {
            return None;
        }

        let count = offending.len();
        let message = if count == 1 {
            format!("{} completed with empty output", offending[0].0.name)
        } else {
            format!("{count} spans completed with empty output")
        };
        let why = format!(
            "{count} non-errored LLM/agent span(s) recorded input but produced neither gen_ai.output.messages nor overmind.output."
        );
        let details = build_details(
            ctx,
            &offending,
            why,
            json!({}),
            json!({ "empty_output_spans": count }),
            vec![RecommendedAction {
                kind: "inspect_trace".into(),
                label: "Check finish_reasons and span output attributes".into(),
            }],
        );
        Some(RuleHit { message, details })
    }
}

// 11. output_truncation
struct OutputTruncationRule;

impl SignalRule for OutputTruncationRule {
    fn catalog_item(&self) -> SignalCatalogItem {
        builtin_catalog_item(
            "output_truncation",
            "Truncated output",
            "Fires when an LLM span hits its output token limit (finish reason length or max_tokens).",
            "quality",
            SignalSeverity::Medium,
            json!({}),
            "Raise max_tokens, ask for more concise responses, or handle continuation when finish_reason=length.",
        )
    }

    fn evaluate(&self, ctx: &RuleContext<'_>) -> Option<RuleHit> {
        let mut offending = Vec::new();
        let mut seen_reasons = Vec::new();

        for span in ctx.spans {
            let matched: Vec<String> = extract_finish_reasons(span)
                .into_iter()
                .filter(|r| {
                    let lower = r.to_ascii_lowercase();
                    lower == "length"
                        || lower == "max_tokens"
                        || lower == "max_output_tokens"
                        || lower.contains("max_tokens")
                })
                .collect();
            if !matched.is_empty() {
                for r in &matched {
                    if !seen_reasons.contains(r) {
                        seen_reasons.push(r.clone());
                    }
                }
                offending.push((
                    *span,
                    Some(format!("finish_reasons=[{}]", matched.join(", "))),
                ));
            }
        }

        if offending.is_empty() {
            return None;
        }

        let count = offending.len();
        let message = if count == 1 {
            format!(
                "{} output truncated ({})",
                offending[0].0.name,
                seen_reasons.join(", ")
            )
        } else {
            format!("{count} LLM responses truncated at token limit")
        };
        let why = format!(
            "{count} span(s) stopped due to output token limits [{}].",
            seen_reasons.join(", ")
        );
        let details = build_details(
            ctx,
            &offending,
            why,
            json!({}),
            json!({
                "truncated_span_count": count,
                "finish_reasons": seen_reasons,
            }),
            vec![RecommendedAction {
                kind: "increase_max_tokens".into(),
                label: "Increase max_tokens or tighten response format".into(),
            }],
        );
        Some(RuleHit { message, details })
    }
}

// 12. low_score
struct LowScoreRule;

impl SignalRule for LowScoreRule {
    fn catalog_item(&self) -> SignalCatalogItem {
        builtin_catalog_item(
            "low_score",
            "Low evaluation score",
            "Fires when a score attribute or overmind.score event falls below min_score.",
            "quality",
            SignalSeverity::High,
            json!({ "min_score": 0.7 }),
            "Inspect low-scoring outputs and rubric feedback to refine prompts or retrieval.",
        )
    }

    fn evaluate(&self, ctx: &RuleContext<'_>) -> Option<RuleHit> {
        let min_score = param_f64(ctx.params, "min_score", 0.7);
        let mut offending = Vec::new();
        let mut lowest: Option<f64> = None;

        for span in ctx.spans {
            let mut span_hits: Vec<String> = Vec::new();

            if let Some(attrs) = span.attributes.as_object() {
                for (key, val) in attrs {
                    if !(key == "score" || key.starts_with(OVERMIND_SCORE_PREFIX)) {
                        continue;
                    }
                    if let Some(score) = value_as_f64(val)
                        && score < min_score
                    {
                        lowest = Some(lowest.map_or(score, |cur| cur.min(score)));
                        span_hits.push(format!("{key}={score:.2}"));
                    }
                }
            }

            if let Some(events) = span.events.as_array() {
                for event in events {
                    if event.get("name").and_then(Value::as_str) != Some("overmind.score") {
                        continue;
                    }
                    let Some(e_attrs) = event.get("attributes").and_then(Value::as_object) else {
                        continue;
                    };
                    let note = e_attrs
                        .get("reason")
                        .and_then(Value::as_str)
                        .map(str::trim)
                        .filter(|s| !s.is_empty());
                    for (key, val) in e_attrs {
                        if !(key == "score" || key.starts_with(OVERMIND_SCORE_PREFIX)) {
                            continue;
                        }
                        if let Some(score) = value_as_f64(val)
                            && score < min_score
                        {
                            lowest = Some(lowest.map_or(score, |cur| cur.min(score)));
                            match note {
                                Some(r) => {
                                    span_hits.push(format!("overmind.score {key}={score:.2} ({r})"))
                                }
                                None => span_hits.push(format!("overmind.score {key}={score:.2}")),
                            }
                        }
                    }
                }
            }

            if !span_hits.is_empty() {
                offending.push((*span, Some(span_hits.join("; "))));
            }
        }

        let lowest_score = lowest?;
        let message = format!("Score {lowest_score:.2} below threshold {min_score:.2}");
        let why = format!(
            "Lowest recorded score was {lowest_score:.2} across {} span(s), below min_score={min_score:.2}.",
            offending.len()
        );
        let details = build_details(
            ctx,
            &offending,
            why,
            json!({ "min_score": min_score }),
            json!({
                "lowest_score": lowest_score,
                "min_score": min_score,
                "low_score_span_count": offending.len(),
            }),
            vec![RecommendedAction {
                kind: "review_eval".into(),
                label: "Review score reason and span output".into(),
            }],
        );
        Some(RuleHit { message, details })
    }
}

// 13. failed_expectations
struct FailedExpectationsRule;

impl SignalRule for FailedExpectationsRule {
    fn catalog_item(&self) -> SignalCatalogItem {
        builtin_catalog_item(
            "failed_expectations",
            "Failed expectations",
            "Fires when overmind.expectations contains any check with passed=false or status=failed.",
            "quality",
            SignalSeverity::High,
            json!({}),
            "Inspect failing expectation checks against the span output and adjust prompts, guardrails, or tool behavior.",
        )
    }

    fn evaluate(&self, ctx: &RuleContext<'_>) -> Option<RuleHit> {
        let mut offending = Vec::new();
        let mut total_failed = 0usize;

        for span in ctx.spans {
            let Some(raw) = attr(span, OVERMIND_EXPECTATIONS) else {
                continue;
            };
            let parsed_owned;
            let value = match raw {
                Value::String(s) => match serde_json::from_str::<Value>(s.trim()) {
                    Ok(v) => {
                        parsed_owned = v;
                        &parsed_owned
                    }
                    Err(_) => continue,
                },
                other => other,
            };

            let items: Vec<&Value> = match value {
                Value::Array(arr) => arr.iter().collect(),
                Value::Object(map) => {
                    if let Some(arr) = map
                        .get("items")
                        .or_else(|| map.get("expectations"))
                        .or_else(|| map.get("results"))
                        .and_then(Value::as_array)
                    {
                        arr.iter().collect()
                    } else {
                        vec![value]
                    }
                }
                _ => continue,
            };

            let mut failed_labels = Vec::new();
            for item in items {
                let Some(obj) = item.as_object() else {
                    continue;
                };
                let passed_false = match obj.get("passed") {
                    Some(Value::Bool(false)) => true,
                    Some(Value::String(s)) if s.trim().eq_ignore_ascii_case("false") => true,
                    _ => false,
                };
                let status_failed = obj
                    .get("status")
                    .and_then(Value::as_str)
                    .is_some_and(|s| {
                        matches!(
                            s.trim().to_ascii_lowercase().as_str(),
                            "failed" | "fail" | "error"
                        )
                    });
                if passed_false || status_failed {
                    total_failed += 1;
                    let name = obj
                        .get("name")
                        .or_else(|| obj.get("expectation"))
                        .or_else(|| obj.get("id"))
                        .and_then(Value::as_str)
                        .map(str::trim)
                        .filter(|s| !s.is_empty())
                        .unwrap_or("expectation");
                    let reason = obj
                        .get("reason")
                        .or_else(|| obj.get("message"))
                        .and_then(Value::as_str)
                        .map(str::trim)
                        .filter(|s| !s.is_empty());
                    match reason {
                        Some(r) => failed_labels.push(format!("{name} ({r})")),
                        None => failed_labels.push(format!("{name}: failed")),
                    }
                }
            }

            if !failed_labels.is_empty() {
                offending.push((*span, Some(failed_labels.join("; "))));
            }
        }

        if offending.is_empty() {
            return None;
        }

        let message = if total_failed == 1 {
            format!(
                "Expectation failed: {}",
                clip_and_redact(offending[0].1.as_deref().unwrap_or("failed"), 110)
            )
        } else {
            format!(
                "{total_failed} expectations failed across {} span(s)",
                offending.len()
            )
        };
        let why = format!(
            "{total_failed} expectation check(s) in overmind.expectations failed across {} span(s).",
            offending.len()
        );
        let details = build_details(
            ctx,
            &offending,
            why,
            json!({}),
            json!({
                "failed_expectation_count": total_failed,
                "failed_span_count": offending.len(),
            }),
            vec![RecommendedAction {
                kind: "review_expectations".into(),
                label: "Review failed expectations and span output".into(),
            }],
        );
        Some(RuleHit { message, details })
    }
}

// 14. negative_feedback
struct NegativeFeedbackRule;

fn is_negative_feedback_value(value: &Value) -> Option<String> {
    match value {
        Value::Bool(false) => Some("false".into()),
        Value::Number(num) => {
            let n = num.as_f64()?;
            (n.is_finite() && n < 0.5).then(|| format!("{n}"))
        }
        Value::String(s) => {
            let trimmed = s.trim();
            if trimmed.is_empty() {
                return None;
            }
            let lower = trimmed.to_ascii_lowercase();
            if matches!(
                lower.as_str(),
                "down"
                    | "thumbs_down"
                    | "thumbs-down"
                    | "thumb_down"
                    | "negative"
                    | "neg"
                    | "bad"
                    | "dislike"
                    | "false"
                    | "no"
            ) {
                return Some(trimmed.to_string());
            }
            if let Ok(n) = trimmed.parse::<f64>()
                && n.is_finite()
                && n < 0.5
            {
                return Some(trimmed.to_string());
            }
            None
        }
        _ => None,
    }
}

impl SignalRule for NegativeFeedbackRule {
    fn catalog_item(&self) -> SignalCatalogItem {
        builtin_catalog_item(
            "negative_feedback",
            "Negative user feedback",
            "Fires when overmind.feedback.* attributes or overmind.feedback events record negative sentiment or score < 0.5.",
            "quality",
            SignalSeverity::High,
            json!({}),
            "Review user feedback comments and full trace context to identify root causes and add regression evals.",
        )
    }

    fn evaluate(&self, ctx: &RuleContext<'_>) -> Option<RuleHit> {
        let mut offending = Vec::new();
        let mut total_hits = 0usize;

        for span in ctx.spans {
            let mut span_hits = Vec::new();

            if let Some(attrs) = span.attributes.as_object() {
                let comment = attrs
                    .get("overmind.feedback.comment")
                    .or_else(|| attrs.get("overmind.feedback.reason"))
                    .and_then(Value::as_str)
                    .map(str::trim)
                    .filter(|s| !s.is_empty());

                for (key, val) in attrs {
                    let is_fb = key == "overmind.feedback" || key.starts_with(OVERMIND_FEEDBACK_PREFIX);
                    if !is_fb || is_feedback_metadata_key(key) {
                        continue;
                    }
                    if let Some(obj) = val.as_object() {
                        for (sub_k, sub_v) in obj {
                            if is_feedback_metadata_key(sub_k) {
                                continue;
                            }
                            if let Some(matched) = is_negative_feedback_value(sub_v) {
                                total_hits += 1;
                                span_hits.push(format!("{key}.{sub_k}={matched}"));
                            }
                        }
                    } else if let Some(matched) = is_negative_feedback_value(val) {
                        total_hits += 1;
                        match comment {
                            Some(c) => span_hits.push(format!("{key}={matched} ({c})")),
                            None => span_hits.push(format!("{key}={matched}")),
                        }
                    }
                }
            }

            if let Some(events) = span.events.as_array() {
                for event in events {
                    let is_fb_event = event
                        .get("name")
                        .and_then(Value::as_str)
                        .is_some_and(|n| {
                            n == "overmind.feedback" || n.starts_with(OVERMIND_FEEDBACK_PREFIX)
                        });
                    if !is_fb_event {
                        continue;
                    }
                    let Some(e_attrs) = event.get("attributes").and_then(Value::as_object) else {
                        continue;
                    };
                    let note = e_attrs
                        .get("reason")
                        .or_else(|| e_attrs.get("comment"))
                        .and_then(Value::as_str)
                        .map(str::trim)
                        .filter(|s| !s.is_empty());
                    for (key, val) in e_attrs {
                        if is_feedback_metadata_key(key) {
                            continue;
                        }
                        if let Some(matched) = is_negative_feedback_value(val) {
                            total_hits += 1;
                            match note {
                                Some(r) => span_hits
                                    .push(format!("overmind.feedback {key}={matched} ({r})")),
                                None => span_hits.push(format!("overmind.feedback {key}={matched}")),
                            }
                        }
                    }
                }
            }

            if !span_hits.is_empty() {
                offending.push((*span, Some(span_hits.join("; "))));
            }
        }

        if offending.is_empty() {
            return None;
        }

        let message = if offending.len() == 1 {
            format!(
                "Negative feedback on {}: {}",
                offending[0].0.name,
                clip_and_redact(offending[0].1.as_deref().unwrap_or("negative"), 100)
            )
        } else {
            format!("Negative feedback recorded on {} spans", offending.len())
        };
        let why = format!(
            "Recorded {total_hits} negative feedback signal(s) across {} span(s).",
            offending.len()
        );
        let details = build_details(
            ctx,
            &offending,
            why,
            json!({}),
            json!({
                "negative_feedback_count": total_hits,
                "affected_span_count": offending.len(),
            }),
            vec![RecommendedAction {
                kind: "review_feedback".into(),
                label: "Inspect user feedback and conversation trace".into(),
            }],
        );
        Some(RuleHit { message, details })
    }
}

// 15. secret_leak
struct SecretLeakRule;

impl SignalRule for SecretLeakRule {
    fn catalog_item(&self) -> SignalCatalogItem {
        builtin_catalog_item(
            "secret_leak",
            "Potential secret leak",
            "Fires when API keys, GitHub tokens, AWS keys, or Bearer tokens appear in span output or messages.",
            "safety",
            SignalSeverity::High,
            json!({}),
            "Rotate exposed credentials immediately and scrub secrets before returning or logging model output.",
        )
    }

    fn evaluate(&self, ctx: &RuleContext<'_>) -> Option<RuleHit> {
        const FIELDS: &[&str] = &[
            GEN_AI_OUTPUT_MESSAGES,
            OVERMIND_OUTPUT,
            GEN_AI_INPUT_MESSAGES,
            OVERMIND_INPUT,
            GEN_AI_TOOL_CALL_RESULT,
            GEN_AI_TOOL_CALL_ARGUMENTS,
        ];

        let mut offending = Vec::new();
        let mut all_kinds = Vec::new();

        for span in ctx.spans {
            let mut span_kinds = Vec::new();
            let mut matched_fields = Vec::new();
            for field in FIELDS {
                let Some(text) = attr(span, field).and_then(value_as_non_empty_text) else {
                    continue;
                };
                let found = find_secret_matches(&text);
                if !found.is_empty() {
                    matched_fields.push(*field);
                    for kind in found {
                        if !span_kinds.contains(&kind) {
                            span_kinds.push(kind);
                        }
                        if !all_kinds.contains(&kind) {
                            all_kinds.push(kind);
                        }
                    }
                }
            }
            if !span_kinds.is_empty() {
                let reason = format!(
                    "matched {} in {}",
                    span_kinds.join(", "),
                    matched_fields.join(", ")
                );
                offending.push((*span, Some(reason)));
            }
        }

        if offending.is_empty() {
            return None;
        }

        let kinds_label = all_kinds.join(", ");
        let message = format!(
            "Secret pattern ({kinds_label}) detected in {} span(s)",
            offending.len()
        );
        let why = format!(
            "Detected credential pattern(s) [{kinds_label}] in span messages/output; evidence excerpts have been redacted."
        );
        let details = build_details(
            ctx,
            &offending,
            why,
            json!({}),
            json!({
                "matched_patterns": all_kinds,
                "matched_span_count": offending.len(),
            }),
            vec![RecommendedAction {
                kind: "rotate_secret".into(),
                label: "Rotate exposed credential and add output redaction".into(),
            }],
        );
        Some(RuleHit { message, details })
    }
}

// 16. safety_or_refusal
struct SafetyOrRefusalRule;

impl SignalRule for SafetyOrRefusalRule {
    fn catalog_item(&self) -> SignalCatalogItem {
        builtin_catalog_item(
            "safety_or_refusal",
            "Safety block or refusal",
            "Fires when a provider blocks a request for safety/content_filter reasons or returns a safety finish reason.",
            "safety",
            SignalSeverity::High,
            json!({}),
            "Review blocked prompts and provider safety thresholds; add user-facing handling for safety refusals.",
        )
    }

    fn evaluate(&self, ctx: &RuleContext<'_>) -> Option<RuleHit> {
        const FINISH_KEYWORDS: &[&str] = &[
            "content_filter",
            "safety",
            "refusal",
            "prohibited_content",
            "recitation",
            "blocklist",
            "spii",
        ];
        const ERROR_KEYWORDS: &[&str] = &[
            "safety",
            "content_filter",
            "content filter",
            "blocked",
            "refusal",
            "moderation",
            "prohibited_content",
        ];

        let mut offending = Vec::new();
        let mut triggers = Vec::new();

        for span in ctx.spans {
            let mut span_reasons = Vec::new();

            for reason in extract_finish_reasons(span) {
                let lower = reason.to_ascii_lowercase();
                if FINISH_KEYWORDS.iter().any(|kw| lower.contains(kw)) {
                    if !triggers.contains(&reason) {
                        triggers.push(reason.clone());
                    }
                    span_reasons.push(format!("finish_reason={reason}"));
                }
            }

            for text in error_texts_for_span(span) {
                let lower = text.to_ascii_lowercase();
                if let Some(kw) = ERROR_KEYWORDS.iter().find(|kw| lower.contains(**kw)) {
                    let kw_str = (*kw).to_string();
                    if !triggers.contains(&kw_str) {
                        triggers.push(kw_str);
                    }
                    span_reasons.push(clip_and_redact(&text, 180));
                    break;
                }
            }

            if !span_reasons.is_empty() {
                offending.push((*span, Some(span_reasons.join("; "))));
            }
        }

        if offending.is_empty() {
            return None;
        }

        let count = offending.len();
        let trigger_summary = triggers.join(", ");
        let message = if count == 1 {
            format!(
                "{} blocked by safety filter ({trigger_summary})",
                offending[0].0.name
            )
        } else {
            format!("{count} spans triggered safety block or refusal ({trigger_summary})")
        };
        let why = format!(
            "{count} span(s) hit safety filter or refusal indicators [{trigger_summary}]."
        );
        let details = build_details(
            ctx,
            &offending,
            why,
            json!({}),
            json!({
                "matched_span_count": count,
                "triggers": triggers,
            }),
            vec![RecommendedAction {
                kind: "review_safety".into(),
                label: "Inspect blocked prompt and provider safety policy".into(),
            }],
        );
        Some(RuleHit { message, details })
    }
}