# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-drops-w3c-traceparent-baggage-at-an-organizational-boundary-and-the-downstream-auditor-silently-re-roots-the-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-drops-w3c-traceparent-baggage-at-an-organizational-boundary-and-the-downstream-auditor-silently-re-roots-the-trace.warrant.json
# Markdown SHA-256:   cc233c3aeb7123eff445673732cbeb512d8310d34a62032e6fa79c5401cd3e28
# Code AST SHA-256:   34deec531f5fb8842192d3293bf5ce2e17000e11fb6ca2018ec27774460844bb
# Verified Classes:   BaggageContinuityError, ExtractedHop
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import Mapping, Optional


class BaggageContinuityError(RuntimeError):
    """Raised when a trace is structurally continuous but a required
    security-bearing baggage key did not survive the organizational hop.

    This is deliberately NOT a parse error: the traceparent was valid and
    the child span would have been well-formed. The failure is semantic.
    """


@dataclass(frozen=True)
class ExtractedHop:
    trace_id: str
    parent_span_id: str
    baggage: Mapping[str, str]
    signed_warrant_token: Optional[str]


REQUIRED_SECURITY_KEYS = ("warrant.id", "auditor.nonce", "replay.epoch")


def extract_strict(hop: ExtractedHop, verify_token) -> Mapping[str, str]:
    """Extract-time gate. Must run before any side-effecting agent work.

    Invariant: a valid span context with missing security baggage is a
    propagation failure, never a first run.
    """
    if not hop.trace_id or not hop.parent_span_id:
        # No span context at all: a new root is legitimate, caller decides.
        raise BaggageContinuityError(
            "no valid traceparent; refusing to silently re-root across org boundary"
        )

    missing = [k for k in REQUIRED_SECURITY_KEYS if k not in hop.baggage]
    if missing:
        # The dangerous branch: trace looks continuous, warrant is gone.
        raise BaggageContinuityError(
            f"trace {hop.trace_id} continuous but missing security baggage {missing}; "
            "refusing hop (do NOT mint a replacement nonce)"
        )

    if not hop.signed_warrant_token:
        raise BaggageContinuityError(
            f"trace {hop.trace_id} carries baggage but no signed warrant token; "
            "baggage values are unauthenticated claims"
        )

    claims = verify_token(hop.signed_warrant_token)
    for key in REQUIRED_SECURITY_KEYS:
        if claims.get(key) != hop.baggage[key]:
            raise BaggageContinuityError(
                f"trace {hop.trace_id}: baggage {key}={hop.baggage[key]!r} "
                f"disagrees with signed warrant {claims.get(key)!r}"
            )
    return dict(hop.baggage)


def auditor_replay(hop: ExtractedHop, verify_token, reexecute) -> str:
    """Auditor entrypoint. The absence branch is a hard error by design."""
    baggage = extract_strict(hop, verify_token)
    nonce = baggage["auditor.nonce"]
    result = reexecute(baggage["warrant.id"], nonce)
    return result
