# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-emits-an-inherited-trace-context-across-an-mcp-tool-call-boundary-and-the-child-span-silently-forks-the-causal-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-emits-an-inherited-trace-context-across-an-mcp-tool-call-boundary-and-the-child-span-silently-forks-the-causal-chain.warrant.json
# Markdown SHA-256:   8e73ebe52f259f7ef081d882867ab8a982f2f65713f2f65ddc0da8bd026747d1
# Code AST SHA-256:   03dfce2472856ee4e7858ac1233242b352b53ec58bf64b316444a3a129fabe11
# Verified Classes:   TraceContextForkError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class TraceContextForkError(RuntimeError):
    """Raised when an agent instance re-emits its inherited span_id as its own,
    forking the causal chain instead of continuing it."""
    pass


def stamp_outbound_traceparent(inbound_traceparent: str, instance_span_id: str) -> str:
    """Build the outbound traceparent for a model-authored tool call.

    The runtime—not the model—owns parent_span_id. The inbound span_id becomes
    the parent; the instance mints a fresh span_id for itself.
    """
    parts = inbound_traceparent.strip().split("-")
    if len(parts) != 4:
        raise TraceContextForkError(f"malformed traceparent: {inbound_traceparent!r}")
    version, trace_id, inbound_span_id, flags = parts

    if not trace_id or len(trace_id) != 32:
        raise TraceContextForkError(f"invalid trace_id in {inbound_traceparent!r}")

    # The fork guard: the instance must not adopt the inbound span_id as its own.
    if instance_span_id == inbound_span_id:
        raise TraceContextForkError(
            f"instance re-emitted inherited span_id {inbound_span_id!r}; "
            "causal chain would fork into siblings"
        )

    # Outbound parent is the instance's own span, not the orchestrator's.
    return f"{version}-{trace_id}-{instance_span_id}-{flags}"


def validate_continuation(inbound: str, model_emitted: str, instance_span_id: str) -> None:
    """Assert the model did not silently echo the inbound header."""
    in_span = inbound.split("-")[2]
    out_span = model_emitted.split("-")[2]
    if out_span == in_span:
        raise TraceContextForkError(
            "model echoed inbound span_id verbatim; runtime must override "
            "before dispatch to MCP/A2A peer"
        )
    if out_span != instance_span_id:
        raise TraceContextForkError(
            f"model emitted span_id {out_span!r} != runtime-assigned {instance_span_id!r}"
        )
