# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-taint-a-declassified-field-at-a2a-handoff-the-provenance-erasure-boundary-in-cross-agent-message-passing.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-taint-a-declassified-field-at-a2a-handoff-the-provenance-erasure-boundary-in-cross-agent-message-passing.warrant.json
# Markdown SHA-256:   281cc62f8529f1474c1deed8325f43b455982fe5ef89b7e21e3ef0b09edab5b2
# Code AST SHA-256:   c00cf916e241a15494ee06e43a0f24367efca261d41f982ac8608e7ae6b99fc6
# Verified Classes:   TaintErasureError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class TaintErasureError(RuntimeError):
    """Raised when a declassified field cannot be safely re-validated at a receiver boundary."""
    pass


def revalidate_handoff(field: dict, receiver_state: dict, trust_set: set[str]) -> dict:
    """
    Re-derive cleanliness of a field at the receiver. Fails closed.
    field: {sensitivity, provenance: [{level, issuer, rule, guard_predicate}]}
    receiver_state: {hop_count, destination, receiver_role, ...}
    """
    provenance = field.get("provenance") or []
    if not provenance:
        # No chain: cannot prove anything; treat as max taint.
        raise TaintErasureError("field has no provenance chain; refusing to treat as clean")

    chain_max = max(p["level"] for p in provenance)
    current = field.get("sensitivity")
    if current is None:
        raise TaintErasureError("missing sensitivity label on field")

    # Walk warrants; every declassification step must be re-evaluable and permit.
    for step in provenance:
        guard = step.get("guard_predicate")
        if guard is None:
            raise TaintErasureError(
                f"warrant from {step.get('issuer')} has no guard; non-re-evaluable"
            )
        if step.get("issuer") not in trust_set:
            raise TaintErasureError(
                f"warrant issuer {step.get('issuer')} not in receiver trust set"
            )
        try:
            permitted = bool(guard(receiver_state))
        except Exception as exc:
            raise TaintErasureError(
                f"guard from {step.get('issuer')} raised {exc!r}; cannot evaluate"
            ) from exc
        if not permitted:
            # Revert to chain-max, do not silently downgrade.
            return {"sensitivity": chain_max, "reverted": True,
                    "reason": f"guard failed at issuer {step.get('issuer')}"}

    # All guards permit under current receiver state.
    return {"sensitivity": current, "reverted": False, "reason": "all guards permit"}
