# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-brokered-trust-chain-has-silently-degraded-to-policy-subsumption-in-cross-org-agent-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-brokered-trust-chain-has-silently-degraded-to-policy-subsumption-in-cross-org-agent-federation.warrant.json
# Markdown SHA-256:   b731ae5483368a84a66ac908d47b68eb47fe0dc8cd23dae977b436cb83f61057
# Code AST SHA-256:   6d0910fee013ddafb7e308499d4d5fbc1e7f4a402906e4784b289eb126da805f
# Verified Classes:   PolicySubsumptionError, PolicyAtom, NegotiatedTerm
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable


class PolicySubsumptionError(RuntimeError):
    """Raised when a brokered term cannot be grounded to a policy atom."""


@dataclass(frozen=True)
class PolicyAtom:
    org: str
    name: str
    effect: str  # "permit" | "deny" | "requires"


@dataclass(frozen=True)
class NegotiatedTerm:
    capability: str
    constraints: dict  # field -> value; value must be a PolicyAtom ref or literal


def ground_term(term: NegotiatedTerm, registries: dict[str, dict[str, PolicyAtom]]) -> list[PolicyAtom]:
    """Resolve every constraint field to a registry atom; reject free-text."""
    grounded: list[PolicyAtom] = []
    for field, value in term.constraints.items():
        if not isinstance(value, str):
            raise PolicySubsumptionError(
                f"constraint field {field!r} has non-string value {value!r}; "
                "cannot ground to registry atom"
            )
        # A grounded value must be an atom reference "org:name", not prose.
        if ":" not in value:
            raise PolicySubsumptionError(
                f"constraint field {field!r} = {value!r} is free-text, not an atom "
                "reference; this is the fingerprint of broker paraphrase "
                "(policy subsumption)"
            )
        org, name = value.split(":", 1)
        atom = registries.get(org, {}).get(name)
        if atom is None:
            raise PolicySubsumptionError(
                f"constraint field {field!r} references unknown atom {value!r}; "
                "broker emitted an ungrounded term"
            )
        grounded.append(atom)
    return grounded


def enforce_non_subsumption(
    term: NegotiatedTerm,
    registries: dict[str, dict[str, PolicyAtom]],
    conflicting_pair: Iterable[PolicyAtom] | None = None,
) -> list[PolicyAtom]:
    """Gate: emit only grounded terms, or refuse with cited conflict."""
    try:
        return ground_term(term, registries)
    except PolicySubsumptionError:
        if conflicting_pair is None:
            raise
        # Explicit refusal is the only permitted alternative to grounding.
        raise PolicySubsumptionError(
            "broker must emit refuse(conflict) citing "
            f"{[a.name for a in conflicting_pair]}, not a paraphrased term"
        )
