# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-cross-org-federation-policy-negotiation-has-silently-degraded-into-unilateral-enforcement.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-cross-org-federation-policy-negotiation-has-silently-degraded-into-unilateral-enforcement.warrant.json
# Markdown SHA-256:   3bb3d7c56d05217de7245619bec72641110813e19563a76fda45239425d36203
# Code AST SHA-256:   9f48bc8909fc0ab0f83023a53121be5ed6c71c450869f504fc5910bd3a92dbfe
# Verified Classes:   Phase, PolicyDegradationError, Clause
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import IntEnum


class Phase(IntEnum):
    PRE_TRANSFER = 0
    PRE_EXECUTION = 1
    AT_REST = 2
    POST_AUDIT = 3


class PolicyDegradationError(RuntimeError):
    """Raised when a provider's echoed clause enforces later than required
    without verified audit reciprocity and provider-side liability."""


@dataclass
class Clause:
    field: str
    phase: Phase
    liability_owner: str  # org id
    audit_reciprocity_verified: bool = False


def validate_negotiated_clause(
    consumer_org: str,
    provider_org: str,
    required: Clause,
    echoed: Clause,
) -> None:
    # Field coverage must match; if not, this is explicit rejection, handled elsewhere.
    if required.field != echoed.field:
        raise PolicyDegradationError(
            f"field mismatch: required={required.field} echoed={echoed.field}"
        )

    # Phase monotonicity: earlier-or-equal enforcement is safe.
    if echoed.phase <= required.phase:
        return

    # Provider enforces later than required: only legitimate if the provider
    # bears liability AND the consumer can observe the post-hoc audit.
    if echoed.liability_owner != provider_org:
        raise PolicyDegradationError(
            f"liability inversion on field={required.field}: "
            f"phase={echoed.phase.name} > required={required.phase.name}, "
            f"but liability_owner={echoed.liability_owner!r} != provider={provider_org!r}"
        )
    if not echoed.audit_reciprocity_verified:
        raise PolicyDegradationError(
            f"unobservable postcondition on field={required.field}: "
            f"phase={echoed.phase.name} > required={required.phase.name}, "
            f"audit reciprocity unverified for provider={provider_org!r}"
        )
    # Otherwise: accept with downgraded trust tag (caller logs phase gap).
