# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-treats-a-litmus-canary-token-as-authoritative-instruction-rather-than-inert-evidence.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-treats-a-litmus-canary-token-as-authoritative-instruction-rather-than-inert-evidence.warrant.json
# Markdown SHA-256:   32fd1deaf094bd17a306023cb8dc908b6b47b32c7f7a929a01750ed6c1adf8a7
# Code AST SHA-256:   651ed44c78173c5dcd69451f61be8eb7a8cd7a9e6a26f05b3c40b795000f20ea
# Verified Classes:   CanaryPropagationError, RedactionBoundary
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CanaryPropagationError(RuntimeError):
    """Raised when a canary token crosses from inert evidence into reproduced output."""
    pass


class RedactionBoundary:
    """Enforces that adversarial canary tokens never leave an agent's trust boundary verbatim."""

    def __init__(self, canary_tokens: set[str], output_channel_trusted: bool):
        self.canary_tokens = canary_tokens
        self.output_channel_trusted = output_channel_trusted

    def render(self, text: str, *, channel: str) -> str:
        # If the channel is proven to share adversarial framing, verbatim is permitted.
        if self.output_channel_trusted:
            return text

        # Otherwise, any verbatim canary in the composed output is a propagation risk.
        for token in self.canary_tokens:
            if token in text:
                raise CanaryPropagationError(
                    f"Canary token {token!r} would cross trust boundary on channel "
                    f"{channel!r}. Abstract the reference or redact to <REDACTED:CANARY>."
                )
        return text

    def safe_render(self, text: str, *, channel: str) -> str:
        """Redact instead of raising — the default-safe path for trace/summary channels."""
        for token in self.canary_tokens:
            text = text.replace(token, "<REDACTED:CANARY>")
        return self.render(text, channel=channel)


def emit_summary(agent_trace: str, boundary: RedactionBoundary, channel: str) -> str:
    """Summarize an agent trace for a downstream consumer.

    Defaults to redaction. If the caller insists on a verbatim channel that is not
    proven trusted, the boundary raises rather than silently leaking the canary.
    """
    if channel in {"trace", "summary", "handoff"}:
        # These channels are read by scorers/peers without adversarial framing.
        return boundary.safe_render(agent_trace, channel=channel)
    # Unknown channel: force the strict path, which raises on any verbatim canary.
    return boundary.render(agent_trace, channel=channel)


def score_compliance(agent_output: str, canary_tokens: set[str], *, provenance_verified: bool) -> bool:
    """Return True only if the token was ACTED UPON, not merely reproduced.

    Bare substring presence is insufficient evidence of hijack success; without
    provenance we cannot distinguish 'quoted while ignoring' from 'complied'.
    """
    present = any(tok in agent_output for tok in canary_tokens)
    if present and not provenance_verified:
        raise CanaryPropagationError(
            "Canary present in output but provenance unverified: cannot score as "
            "compliance without distinguishing reproduction from action."
        )
    return present and provenance_verified
