# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-capability-delegation-scope-widening-across-administrative-domains-in-cross-org-agent-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-capability-delegation-scope-widening-across-administrative-domains-in-cross-org-agent-federation.warrant.json
# Markdown SHA-256:   22635ad967420bc4685ab7d96d04298ddabb49db8bca228380e704b76b36bce0
# Code AST SHA-256:   dfb6e4acf047e61248deafc2623789a8da7cc49d8865a5bf30082a08f8da08d2
# Verified Classes:   UnmappedConstraintError, LossBudgetExceededError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class UnmappedConstraintError(RuntimeError):
    """Raised when a delegation's constraints cannot be equivalently translated
    at an administrative-domain boundary and lossy translation is not permitted."""
    pass


class LossBudgetExceededError(RuntimeError):
    """Raised when cumulative loss across a re-delegation chain exceeds the
    delegator's declared allowlist."""
    pass


def translate_and_grant(inbound_token, local_policy_engine, accumulator):
    """
    Translate an inbound capability at a domain boundary.
    Fails closed on any unmapped constraint unless lossy_ok and the dropped
    classes are explicitly allowlisted. Appends a warrant edge on success.
    """
    loss_contract = inbound_token.get("lossy_ok", False)  # absent => fail closed
    allowlist = set(inbound_token.get("lossy_allowlist", []))

    translated_scope, unmapped = local_policy_engine.translate(inbound_token["scope"])

    if unmapped:
        if not loss_contract:
            raise UnmappedConstraintError(
                f"delegation from {inbound_token['issuer']} dropped constraints "
                f"{sorted(unmapped)} but lossy_ok is false; refusing grant"
            )
        not_allowed = set(unmapped) - allowlist
        if not_allowed:
            raise UnmappedConstraintError(
                f"dropped constraints {sorted(not_allowed)} not in delegator allowlist "
                f"{sorted(allowlist)}; refusing grant"
            )
        # cumulative loss must remain within the ORIGINAL allowlist
        cumulative = accumulator.cumulative_loss() | set(unmapped)
        if not cumulative.issubset(allowlist):
            raise LossBudgetExceededError(
                f"cumulative loss {sorted(cumulative)} exceeds original allowlist "
                f"{sorted(allowlist)} across chain {accumulator.chain_id()}"
            )

    # semantic monotonicity: translated authority must be a subset of inbound
    if not local_policy_engine.is_semantic_subset(translated_scope, inbound_token["scope"]):
        raise UnmappedConstraintError(
            "translation widened effective authority; subset check failed "
            f"for scope {translated_scope}"
        )

    accumulator.append_edge(
        issuer=inbound_token["issuer"],
        translated_scope=translated_scope,
        loss=set(unmapped),
    )
    return local_policy_engine.materialize(translated_scope)
