# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-clean-trace-context-silently-sever-the-audit-chain-during-agent-incident-replay.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-clean-trace-context-silently-sever-the-audit-chain-during-agent-incident-replay.warrant.json
# Markdown SHA-256:   5a4d2a330b4762bb15c034ebec9923b501327f39f61579d294941525c5e03741
# Code AST SHA-256:   66c23a30eb73a2bf7dde7a4a1a3d4457e7f347ca9aeac14f59c5c59bd79b1fdd
# Verified Classes:   TaintContinuityError, Span
# Defensive Guards:   6 fail-closed invariants (zero external deps)

# Operational guard for the trace/taint continuity seam.
# Enforces: transport continuity does NOT imply semantic (taint) continuity.

from dataclasses import dataclass, field
from typing import Optional


class TaintContinuityError(RuntimeError):
    """Raised when a span shares a trace but lacks an inherited taint label,
    i.e. the semantic audit chain was severed at a context-constructing boundary."""
    pass


@dataclass
class Span:
    trace_id: str
    span_id: str
    parent_id: Optional[str]
    taint: Optional[str] = None          # None == label was dropped, NOT "clean"
    origin_span_id: Optional[str] = None # set only on the span where taint originated


IRREVERSIBLE_ACTIONS = {"delete", "transfer_funds", "send_email_external", "execute_shell"}


def assert_taint_continuity(span: Span, ancestors: dict[str, Span]) -> str:
    """Walk parent chain from `span` back to its taint origin.
    Returns the resolved taint. Raises if the channel was severed."""
    if span.taint is None:
        # A span with no label is UNKNOWN, never implicitly clean.
        raise TaintContinuityError(
            f"span {span.span_id} in trace {span.trace_id} has no taint label; "
            f"treating as 'unknown' and refusing to resolve to 'clean'"
        )
    if span.origin_span_id is not None:
        return span.taint

    # Must reach a labelled ancestor with no gap.
    cur = span
    while cur.parent_id is not None:
        parent = ancestors.get(cur.parent_id)
        if parent is None:
            raise TaintContinuityError(
                f"trace {span.trace_id}: parent {cur.parent_id} of {cur.span_id} "
                f"missing from context; cannot prove taint continuity"
            )
        if parent.taint is None:
            raise TaintContinuityError(
                f"trace {span.trace_id}: taint channel severed at span {parent.span_id} "
                f"(re-rooted context dropped baggage); downstream taint unprovable"
            )
        if parent.origin_span_id is not None:
            return parent.taint
        cur = parent
    raise TaintContinuityError(
        f"trace {span.trace_id}: no taint origin reachable from {span.span_id}"
    )


def gate_action(span: Span, ancestors: dict[str, Span], action: str) -> str:
    """Gate an action on resolved taint. Unknown taint blocks irreversible actions."""
    try:
        taint = assert_taint_continuity(span, ancestors)
    except TaintContinuityError:
        if action in IRREVERSIBLE_ACTIONS:
            raise  # fail closed: quarantine, do not execute
        return "quarantine"  # reversible action: degrade to quarantine, still visible
    if taint == "untrusted" and action in IRREVERSIBLE_ACTIONS:
        raise TaintContinuityError(
            f"action '{action}' on span {span.span_id} blocked: taint=untrusted"
        )
    return "allow"
