# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-brokered-capability-whose-policy-envelope-was-widened-by-an-intermediate-trust-domain.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-brokered-capability-whose-policy-envelope-was-widened-by-an-intermediate-trust-domain.warrant.json
# Markdown SHA-256:   3c094903224a39a4ec250e3be25f40a180f77c6a73e2538062914c342f9378d7
# Code AST SHA-256:   f8eaa20080234bb21f702023b899d1662ef2243211b1824fe773b406374afcc8
# Verified Classes:   EnvelopeWideningError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class EnvelopeWideningError(RuntimeError):
    """Raised when a brokered policy envelope is not provably a subset of the originator's grant."""
    pass


CLOSED_FIELDS = {"mode", "op", "dataset"}  # originator declares these closed; defaults must be restrictive


def accept_brokered_capability(origin_envelope: dict, hop_envelope: dict, originator_reachable: bool) -> dict:
    """
    Gate a brokered capability before execution.
    Returns the effective grant (intersection) or raises EnvelopeWideningError.
    """
    # 1. Closed-field divergence is always an escalation.
    for field in CLOSED_FIELDS:
        o = origin_envelope.get(field)
        h = hop_envelope.get(field)
        if o is None and h is not None:
            raise EnvelopeWideningError(
                f"broker introduced closed field {field!r}={h!r} absent from origin grant"
            )
        if o is not None and h is not None and o != h:
            raise EnvelopeWideningError(
                f"closed field {field!r} widened: origin={o!r} hop={h!r}"
            )

    # 2. Expiry must be monotonically non-increasing.
    if hop_envelope.get("expiry", 0) > origin_envelope.get("expiry", 0):
        raise EnvelopeWideningError(
            f"expiry extended across hop: origin={origin_envelope.get('expiry')} hop={hop_envelope.get('expiry')}"
        )

    # 3. Open fields: require originator-attested subset check, else fail closed.
    open_fields = set(hop_envelope) - CLOSED_FIELDS - {"expiry", "sig"}
    if open_fields:
        if not originator_reachable:
            raise EnvelopeWideningError(
                f"cannot verify subset of open fields {sorted(open_fields)}: originator unreachable"
            )
        # originator.narrower_than(hop_envelope, origin_envelope) must return True;
        # any False or timeout is treated as unverified.
        if not originator_narrower_than(hop_envelope, origin_envelope):
            raise EnvelopeWideningError(
                f"originator rejected subset claim for open fields {sorted(open_fields)}"
            )

    # 4. Effective grant is the intersection, never the hop envelope alone.
    return {**origin_envelope, **{k: v for k, v in hop_envelope.items() if k in open_fields}}


def originator_narrower_than(hop_envelope: dict, origin_envelope: dict) -> bool:
    # Placeholder: real implementation calls the originator's lattice oracle.
    # Returning False on any doubt is the safe default.
    return False
