# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-preserve-trace-parent-continuity-when-a-federated-agent-handoff-crosses-a-trust-boundary-that-strips-the-w3c-traceparent-header.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-preserve-trace-parent-continuity-when-a-federated-agent-handoff-crosses-a-trust-boundary-that-strips-the-w3c-traceparent-header.warrant.json
# Markdown SHA-256:   06bc2583184e61a04b1cd7782c1a5e4254032730c9518f1f18dc1cf00d5b1a0c
# Code AST SHA-256:   60606a5cf05aeee1380f7dbb10dda02d05a2859a35ab04f44150f7b903bb17ac
# Verified Classes:   TraceLinkageError, HandoffEnvelope
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class TraceLinkageError(RuntimeError):
    """Raised when a federated handoff cannot establish causal linkage."""


@dataclass
class HandoffEnvelope:
    traceparent: Optional[str]          # transport header, may be stripped
    linkage_token: Optional[dict]       # application-layer metadata
    peer_declares_linkage_ext: bool     # from agent card


def establish_peer_span(envelope: HandoffEnvelope) -> dict:
    """Decide the peer's span shape at a federation ingress.

    Continuation (traceparent) and linkage (metadata token) are treated as
    independent concerns. Refused continuation MUST still yield a link.
    """
    has_continuation = envelope.traceparent is not None
    has_linkage = envelope.linkage_token is not None

    if has_continuation:
        # Trusting domain: adopt as parent, no link needed.
        return {"parent": envelope.traceparent, "links": [], "continuation": "accepted"}

    # Continuation refused or absent. Now the linkage token decides.
    if has_linkage:
        token = envelope.linkage_token
        required = {"trace_id", "span_id", "origin_domain", "handoff_nonce"}
        missing = required - token.keys()
        if missing:
            raise TraceLinkageError(
                f"malformed linkage token, missing {sorted(missing)}"
            )
        return {
            "parent": None,
            "links": [{
                "trace_id": token["trace_id"],
                "span_id": token["span_id"],
                "attributes": {"origin_domain": token["origin_domain"]},
            }],
            "continuation": "refused",
        }

    # No continuation AND no linkage token. Distinguish expected from violation.
    if envelope.peer_declares_linkage_ext:
        # Peer advertises the extension but sent no token: token was stripped
        # or serialization dropped it. This is a contract violation.
        raise TraceLinkageError(
            "peer declares trace-linkage/v1 but handoff carried no linkage token; "
            "continuation refused and causal chain would be orphaned"
        )

    # Peer never claimed support: absence is expected, quarantine the span.
    return {"parent": None, "links": [], "continuation": "unsupported"}
