# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-federated-capability-grant-that-translated-cleanly-but-widened-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-federated-capability-grant-that-translated-cleanly-but-widened-scope.warrant.json
# Markdown SHA-256:   fa0104637f27e914b9e0f45dd65219556caf33fea52297dae2ce057b05db4aec
# Code AST SHA-256:   2944596b5a137d259a74790c17d4cff51eb74fcc6a7c364a8121038b141be775
# Verified Classes:   TranslationWideningError, Constraint, Grant, TranslationWitness
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class TranslationWideningError(RuntimeError):
    """Raised when a translated capability grant's effective scope is not a
    proven subset of the source grant's effective scope."""
    pass


@dataclass
class Constraint:
    name: str
    value: object
    # True if the target dialect's default (when this constraint is absent)
    # is at least as restrictive as this constraint's value.
    target_default_is_narrower: bool = False


@dataclass
class Grant:
    capability: str
    constraints: dict[str, Constraint] = field(default_factory=dict)
    issuer: str = ""

    def hash(self) -> str:
        payload = f"{self.capability}|{sorted(self.constraints)}|{self.issuer}"
        return "sha256:" + hashlib.sha256(payload.encode()).hexdigest()


@dataclass
class TranslationWitness:
    source_hash: str
    translated_hash: str
    subset_proven: bool
    unmapped_widening: list[str] = field(default_factory=list)


def translate_grant(
    source: Grant,
    target_dialect_primitives: set[str],
) -> tuple[Grant, TranslationWitness]:
    translated = Grant(capability=source.capability, issuer=source.issuer)
    widening: list[str] = []

    for name, c in source.constraints.items():
        if name in target_dialect_primitives:
            translated.constraints[name] = c
        else:
            # Unmapped. Safe only if the target's absence-default is narrower.
            if not c.target_default_is_narrower:
                widening.append(name)

    witness = TranslationWitness(
        source_hash=source.hash(),
        translated_hash=translated.hash(),
        subset_proven=not widening,
        unmapped_widening=widening,
    )

    if widening:
        # Fail closed: do NOT return a grant the receiver might execute.
        raise TranslationWideningError(
            f"translation of {source.capability} from {source.issuer} widens scope on "
            f"unmapped constraints {widening}; target default is wider than source bound. "
            f"source={witness.source_hash} translated={witness.translated_hash}"
        )
    return translated, witness


def pre_execution_check(grant: Grant, witness: Optional[TranslationWitness]) -> None:
    if witness is None:
        raise TranslationWideningError(
            f"grant {grant.hash()} has no translation_witness; cannot prove subset-hood"
        )
    if not witness.subset_proven:
        raise TranslationWideningError(
            f"grant {grant.hash()} carries witness with subset_proven=False: "
            f"widening on {witness.unmapped_widening}"
        )
    if witness.translated_hash != grant.hash():
        raise TranslationWideningError(
            f"witness hash {witness.translated_hash} does not match grant {grant.hash()}"
        )
