# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rehydrates-a-compacted-transcript-from-summaries-that-dropped-the-negation-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rehydrates-a-compacted-transcript-from-summaries-that-dropped-the-negation-scope.warrant.json
# Markdown SHA-256:   6c5f16f33a41ed9775e0aae586f8233d9ecac36bc8a9e4ba0b2f38e2d975e795
# Code AST SHA-256:   f377f4f622dc1945908feb802dfcbb2f4c5694b87ae7efe829e5f5b792063340
# Verified Classes:   OperatorFidelityViolation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class OperatorFidelityViolation(RuntimeError):
    """Raised when an action is authorized by a summary that may have
    dropped, inverted, or re-scoped an operator-bearing clause."""
    pass


# Clauses whose polarity/scope must survive compaction verbatim.
OPERATOR_MARKERS = ("not", "never", "must", "may not", "without", "only",
                    "unless", "do not", "prohibited", "required")


def clause_is_operator_bearing(text: str) -> bool:
    low = text.lower()
    return any(marker in low for marker in OPERATOR_MARKERS)


def authorize_action(action: dict, justification_chain: list[dict]) -> None:
    """
    action: {"tool": str, "args": dict, "gated_by_policy": bool}
    justification_chain: ordered evidence the agent used, each item:
        {"kind": "source" | "summary", "text": str, "span_id": str,
         "source_retained": bool, "operator_fidelity_verified": bool}
    """
    if not action.get("gated_by_policy"):
        return  # topical use only; summary authority is acceptable

    # The action is gated by a policy. Its authority must be a verbatim source.
    terminal = justification_chain[-1] if justification_chain else None
    if terminal is None:
        raise OperatorFidelityViolation(
            f"action {action['tool']} is policy-gated but has no cited authority"
        )

    if terminal["kind"] == "summary":
        if not terminal.get("source_retained"):
            raise OperatorFidelityViolation(
                f"policy-gated action {action['tool']} authorized by summary "
                f"{terminal['span_id']} whose source was discarded at compaction; "
                f"operator polarity is unrecoverable — rehydration cannot be trusted"
            )
        if not terminal.get("operator_fidelity_verified"):
            raise OperatorFidelityViolation(
                f"policy-gated action {action['tool']} authorized by summary "
                f"{terminal['span_id']} with UNVERIFIED operator fidelity; "
                f"re-anchor to source span before acting"
            )
        # Fidelity verified and source retained: re-anchor to the source turn.
        raise OperatorFidelityViolation(
            f"summary {terminal['span_id']} passed fidelity check but action must "
            f"cite the source span directly, not the summary; rehydrate source first"
        )

    # terminal["kind"] == "source": verify the source itself carries the operator.
    if clause_is_operator_bearing(terminal["text"]):
        return  # authoritative, verbatim, operator intact
    raise OperatorFidelityViolation(
        f"cited source {terminal['span_id']} for policy-gated action "
        f"{action['tool']} contains no operator-bearing clause; "
        f"justification likely derived from a lossy summary"
    )


# --- trace of the observed failure, now bounded ---
summary_evidence = {
    "kind": "summary",
    "text": "Tier-2 refunds permitted with manager override token; "
            "agent may proceed on judgment for small amounts.",
    "span_id": "S@turn44",
    "source_retained": False,          # turn 12 was discarded
    "operator_fidelity_verified": False,
}

try:
    authorize_action(
        action={"tool": "issue_refund", "args": {"amount": 75}, "gated_by_policy": True},
        justification_chain=[summary_evidence],
    )
except OperatorFidelityViolation as e:
    # This is the guardrail firing: the turn-59 refund is refused,
    # forcing rehydration of the (retained) source before any action.
    print(f"BLOCKED: {e}")
