# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-causal-trace-divergence-when-reconstructing-emergent-multi-agent-behavior-from-partial-spans.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-causal-trace-divergence-when-reconstructing-emergent-multi-agent-behavior-from-partial-spans.warrant.json
# Markdown SHA-256:   4826a67c4ab288f0e060062ef3a547df5f95750fefe5c0a393dbf2c55a30c779
# Code AST SHA-256:   f100d51a99d6479b6a38ccb69a025b408e71e497e672e486ed784b7a615dd82c
# Verified Classes:   CausalFidelityError, ReconstructedEdge, TraceReport
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional

class CausalFidelityError(RuntimeError):
    """Raised when a reconstructed multi-agent trace cannot be certified as causal."""
    pass

@dataclass
class ReconstructedEdge:
    src: str
    dst: str
    slack_ms: float          # dst.start - src.end
    has_causal_token: bool   # message id / version vector / baton seq present
    cross_agent: bool

@dataclass
class TraceReport:
    orphan_spans: int
    clock_skew_ms: float
    edges: list[ReconstructedEdge]
    replay_reproduced: bool

def certify_causal_graph(report: TraceReport) -> str:
    # Orphans must never be silently reparented; they invalidate fidelity.
    if report.orphan_spans > 0:
        raise CausalFidelityError(
            f"{report.orphan_spans} orphan span(s) with dangling parent_span_id; "
            "reconstructor must not reparent by timestamp proximity"
        )

    # Cross-agent edges without a causal token and with slack inside the
    # skew envelope are ambiguous, not resolved.
    for e in report.edges:
        if e.cross_agent and not e.has_causal_token:
            if abs(e.slack_ms) <= report.clock_skew_ms:
                raise CausalFidelityError(
                    f"ambiguous cross-agent edge {e.src}->{e.dst} "
                    f"(slack={e.slack_ms}ms within skew={report.clock_skew_ms}ms, "
                    "no causal token); emit UNRESOLVED, not a resolved edge"
                )
        # Negative slack beyond the skew envelope indicates a phantom edge
        # produced by reparenting, not clock noise.
        if e.slack_ms < -report.clock_skew_ms:
            raise CausalFidelityError(
                f"phantom edge {e.src}->{e.dst}: slack {e.slack_ms}ms "
                f"exceeds skew envelope {-report.clock_skew_ms}ms"
            )

    # Ground-truth check: graph must regenerate observed outputs.
    if not report.replay_reproduced:
        raise CausalFidelityError(
            "replay failed to reproduce observed outputs from reconstructed "
            "parents; graph is plausible, not causal"
        )

    return "fidelity=certified"
