tokitai-dl 0.1.2

Vendored, additive bridge between tokitai-operator (verified DL kernels) and god-graph (DL model analysis). 100% non-invasive position was deliberately broken in 0.1.1 — see ADR-0004 for the rationale.
Documentation
//! Bridge between god-graph's [`TopologyDefect`] and tokitai's
//! [`TheorySupportMatrixRow`].
//!
//! god-graph's CAD-LLM optimizer emits [`TopologyDefect`] reports for
//! issues like isolated nodes, missing residual connections, blocked
//! gradient flow, etc. tokitai exposes a `TheorySupportMatrix` whose
//! rows are the source-of-truth for `docs/theory_support_matrix.md`.
//!
//! The bridge turns each [`TopologyDefect`] into a stand-alone
//! `TheorySupportMatrixRow` whose `non_claims` vector contains the
//! defect description. The downstream user can then call
//! `support_matrix.register_row(...)` (or splice the row into their
//! own matrix) to register the defect as a non-claim.
//!
//! This module is gated on both the `graph` and the `operator`
//! features.

use god_graph::transformer::optimization::constraints::{DefectType, Severity, TopologyDefect};
use tokitai_operator::verify::support_matrix::{SupportStatus, TheorySupportMatrixRow};

use crate::BridgeError;

/// Convert a god-graph [`TopologyDefect`] into a tokitai
/// [`TheorySupportMatrixRow`].
///
/// The row's `domain` is `"topology_defect"`, `operator` is the
/// defect kind's stable identifier, `backend` is `"god_graph_cad_llm"`,
/// `support_status` is [`SupportStatus::Unsupported`] (the defect
/// represents a capability gap, not a supported path),
/// `non_claims` contains the human-readable defect description, and
/// `lowering_rule_id` is a synthesized string of the form
/// `god_graph.cad_llm.<defect_kind>` for traceability. All other
/// fields are populated with neutral placeholders that downstream
/// code can overwrite if it has better metadata.
///
/// # Errors
///
/// Currently always returns `Ok`. We keep the `Result` return type so
/// future `DefectType` variants (e.g. `Custom(String)`) can fail
/// without breaking the public signature.
///
/// # Example
///
/// ```rust
/// # #[cfg(all(feature = "graph", feature = "operator"))]
/// # fn demo() {
/// use god_graph::transformer::optimization::constraints::{DefectType, Severity, TopologyDefect};
/// use tokitai_dl::cad_bridge::defect_to_non_claims_row;
///
/// let defect = TopologyDefect {
///     defect_type: DefectType::MissingResidual,
///     location: 4,
///     severity: Severity::Error,
///     description: "layer 4 has no residual connection".to_string(),
///     suggested_fix: Some("insert a residual sum".to_string()),
/// };
/// let row = defect_to_non_claims_row(&defect).unwrap();
/// assert_eq!(row.domain, "topology_defect");
/// assert_eq!(row.operator, "missing_residual");
/// assert_eq!(row.backend, "god_graph_cad_llm");
/// # }
/// ```
pub fn defect_to_non_claims_row(
    defect: &TopologyDefect,
) -> Result<TheorySupportMatrixRow, BridgeError> {
    let defect_kind = defect_kind_label(&defect.defect_type);
    let severity = severity_label(defect.severity);
    let description = if defect.description.is_empty() {
        format!("{} @ node {}", defect_kind, defect.location)
    } else {
        defect.description.clone()
    };
    let suggested = defect
        .suggested_fix
        .clone()
        .map(|f| format!(" suggested_fix={f}"));

    let mut non_claims = vec![format!(
        "{severity} {defect_kind}: {description}{}",
        suggested.as_deref().unwrap_or("")
    )];
    // Always add a stable "what is missing" non-claim so the row is
    // self-describing in the support matrix markdown.
    non_claims.push(format!(
        "god_graph CAD-LLM defect type={} at node {}",
        defect_kind, defect.location
    ));

    Ok(TheorySupportMatrixRow {
        domain: "topology_defect".to_string(),
        operator: defect_kind.to_string(),
        theory_constraints: vec![format!("god_graph.cad_llm.{defect_kind}")],
        theorem_packages: vec!["none".to_string()],
        backend: "god_graph_cad_llm".to_string(),
        backend_capability: format!(
            "god_graph CAD-LLM defect detector; severity={severity}; location=node {}",
            defect.location
        ),
        lowering_rule_id: Some(format!("god_graph.cad_llm.{defect_kind}")),
        support_status: SupportStatus::Unsupported,
        fallback_mode: "no fallback; the defect is an observation, not a path".to_string(),
        public_api: "src/transformer/optimization/constraints.rs (TopologyValidator)".to_string(),
        tests: vec!["tests/cad_bridge.rs".to_string()],
        non_claims,
    })
}

fn defect_kind_label(kind: &DefectType) -> &'static str {
    match kind {
        DefectType::IsolatedNode => "isolated_node",
        DefectType::DisconnectedComponent => "disconnected_component",
        DefectType::UnexpectedCycle => "unexpected_cycle",
        DefectType::MissingResidual => "missing_residual",
        DefectType::UnbalancedAttention => "unbalanced_attention",
        DefectType::BlockedGradientFlow => "blocked_gradient_flow",
        DefectType::Custom(_) => "custom",
    }
}

fn severity_label(s: Severity) -> &'static str {
    match s {
        Severity::Info => "info",
        Severity::Warning => "warning",
        Severity::Error => "error",
        Severity::Critical => "critical",
    }
}