# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-brokered-capability-grant-that-its-own-policy-engine-would-have-denied-locally.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-brokered-capability-grant-that-its-own-policy-engine-would-have-denied-locally.warrant.json
# Markdown SHA-256:   5e29808349daea391297814655fa03510e8755b0fb8c1454b0920280d8fde7b2
# Code AST SHA-256:   6860a27869b0da18cd106911a76b462ab061ef0c2dbec807cf7030f948f626d5
# Verified Classes:   UnmappableConstraint, ResidualObligationUnenforceable, PolicyFragment, GrantToken
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class UnmappableConstraint(RuntimeError):
    """Raised when a policy predicate has no representation in the target dialect
    and the broker is not permitted to fail-open."""
    pass


class ResidualObligationUnenforceable(RuntimeError):
    """Raised when a broker would fail-open on translation loss but the origin
    agent has not advertised usage-time residual enforcement."""
    pass


@dataclass
class PolicyFragment:
    capability: str
    scope: frozenset
    predicates: dict            # e.g. {"purpose": "research-cohort"}


@dataclass
class GrantToken:
    capability: str
    scope: frozenset
    predicates: dict
    translation_loss: list = field(default_factory=list)   # predicate keys erased
    loss_ack: str | None = None                            # origin signature over loss

    def provenance_hash(self) -> str:
        h = hashlib.sha256()
        h.update(self.capability.encode())
        h.update(b"|".join(sorted(self.scope)).encode() if False else b"|".join(sorted(self.scope)))
        h.update(b"|".join(sorted(self.translation_loss)).encode())
        return h.hexdigest()


def translate(request: PolicyFragment, target_dialect_fields: set,
              origin_residual_enforcement: bool) -> GrantToken:
    """Translate an origin policy fragment into a target-dialect grant.
    Translation may only narrow; erased predicates become residual obligations."""
    erased = [k for k in request.predicates if k not in target_dialect_fields]

    if erased and not origin_residual_enforcement:
        # Fail-open would be unsound: origin cannot enforce residuals at usage time.
        raise ResidualObligationUnenforceable(
            f"predicates {erased} unmappable to target dialect and origin "
            f"advertises residual_enforcement=False; broker must fail-closed"
        )

    if erased and origin_residual_enforcement:
        # Fail-open permitted, but loss must be carried and acknowledged.
        return GrantToken(
            capability=request.capability,
            scope=request.scope,
            predicates={k: v for k, v in request.predicates.items()
                        if k in target_dialect_fields},
            translation_loss=erased,
        )

    return GrantToken(
        capability=request.capability,
        scope=request.scope,
        predicates=dict(request.predicates),
    )


def rebroke(grant: GrantToken, second_broker_dialect_fields: set) -> GrantToken:
    """A downstream broker must refuse to re-broker an unacknowledged lossy grant."""
    if grant.translation_loss and not grant.loss_ack:
        raise UnmappableConstraint(
            f"refusing to re-broker grant {grant.provenance_hash()[:12]}: "
            f"carries unresolved translation_loss={grant.translation_loss} "
            f"with no origin loss_ack"
        )
    return translate(
        PolicyFragment(grant.capability, grant.scope, grant.predicates),
        second_broker_dialect_fields,
        origin_residual_enforcement=True,
    )
