# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-traceparent-across-an-org-boundary-and-the-span-link-attribution-silently-disagrees-with-the-peer-s-aud.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-traceparent-across-an-org-boundary-and-the-span-link-attribution-silently-disagrees-with-the-peer-s-aud.warrant.json
# Markdown SHA-256:   10a5c8bbead13873de80801ae8734f371a3be7fb9743b6d30117598e854c79e9
# Code AST SHA-256:   79eaf8a8e073b01de674e22c882cec47c152ccd1049bd676a4445dcf2f7a829a
# Verified Classes:   TraceContinuityViolation, TraceParent, CheckpointState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass


class TraceContinuityViolation(RuntimeError):
    """Raised when a resumed or handed-off agent instance propagates a
    trace context that cannot be proven to continue the prior causal line."""


@dataclass
class TraceParent:
    version: str
    trace_id: str
    span_id: str
    flags: str

    @classmethod
    def parse(cls, header: str) -> "TraceParent":
        m = re.fullmatch(r"([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})", header.strip())
        if not m:
            raise TraceContinuityViolation(f"malformed traceparent: {header!r}")
        return cls(*m.groups())


@dataclass
class CheckpointState:
    prior_trace_id: str
    prior_span_id: str
    task_id: str
    continuation_link: str | None  # signed link to pre-checkpoint span, if any


def validate_resume_continuation(
    inbound: TraceParent,
    checkpoint: CheckpointState,
    peer_expected_task: str,
) -> None:
    """Peer-side guard: an inbound context after a lifecycle event is only a
    continuation if it either preserves the prior trace_id or carries a
    verifiable continuation link into it. Otherwise it is a new causal root
    and must not be joined to the prior audit record."""
    if checkpoint.task_id != peer_expected_task:
        raise TraceContinuityViolation(
            f"task mismatch: checkpoint={checkpoint.task_id} peer={peer_expected_task}"
        )

    same_trace = inbound.trace_id == checkpoint.prior_trace_id
    has_link = bool(checkpoint.continuation_link)

    if not same_trace and not has_link:
        # The instance regenerated identity with no continuation proof.
        # This is the silent-correlation-break defect.
        raise TraceContinuityViolation(
            "trace_id changed across lifecycle boundary with no continuation "
            f"link: prior={checkpoint.prior_trace_id} inbound={inbound.trace_id}. "
            "Classify inbound as new causal root; do not join to prior task."
        )

    if same_trace and inbound.span_id == checkpoint.prior_span_id:
        # Reusing the exact span_id across a restart is also a violation:
        # two distinct executions share one span identity.
        raise TraceContinuityViolation(
            f"span_id {inbound.span_id} reused across resume; resume must emit "
            "a fresh INTERNAL span with a links entry to the prior span."
        )


def resume_and_propagate(
    checkpoint: CheckpointState,
    new_span_id: str,
    peer_task: str,
) -> TraceParent:
    """Origin-side correct path: rehydrate prior trace_id, emit fresh span_id,
    attach continuation link, then validate before propagating."""
    if checkpoint.continuation_link is None:
        raise TraceContinuityViolation(
            "refusing to resume-propagate without a continuation link; "
            "peer cannot verify causal continuation"
        )
    outbound = TraceParent(
        version="00",
        trace_id=checkpoint.prior_trace_id,
        span_id=new_span_id,
        flags="01",
    )
    validate_resume_continuation(outbound, checkpoint, peer_task)
    return outbound
