# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-federated-policy-grant-as-non-transitive-across-a-trust-boundary-handoff-and-how-does-the-grant-s-provenanc.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-federated-policy-grant-as-non-transitive-across-a-trust-boundary-handoff-and-how-does-the-grant-s-provenanc.warrant.json
# Markdown SHA-256:   c26cb39490d459781c7d823b02835fdf7835717065506bd9d814bb69b5ed5e08
# Code AST SHA-256:   4f55b0b7e033452614d1ad77c42cd67eaeb8f8c9cadbbc188ec0d43bebe6c9e5
# Verified Classes:   DelegationBudgetViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class DelegationBudgetViolation(RuntimeError):
    """Raised when a federated grant is forwarded beyond its delegation budget
    or presented by a subject outside its subject_set."""
    pass


def forward_grant(grant: dict, presenter_id: str, callee_id: str) -> dict:
    """Derive a child grant for callee_id from grant presented by presenter_id.

    Enforces the non-transitivity invariant: a grant may be forwarded only if
    it carries a positive delegation budget, the presenter is an authorized
    subject, and the provenance chain is monotonic.
    """
    budget = grant.get("delegation_budget")
    subject_set = grant.get("subject_set", [])
    chain = grant.get("provenance_chain", [])

    if budget is None:
        # Field absent: cannot distinguish "unbounded" from "stripped".
        # Fail closed — usable in place only.
        raise DelegationBudgetViolation(
            f"grant {grant.get('id')} has no delegation_budget; "
            f"refusing to forward from {presenter_id} to {callee_id}"
        )

    if budget <= 0:
        raise DelegationBudgetViolation(
            f"grant {grant.get('id')} exhausted delegation budget "
            f"(budget={budget}); re-mint required before forwarding to {callee_id}"
        )

    if presenter_id not in subject_set:
        raise DelegationBudgetViolation(
            f"presenter {presenter_id} not in subject_set {subject_set} "
            f"for grant {grant.get('id')}"
        )

    if chain:
        last_index = chain[-1].get("hop_index", -1)
        if any(hop.get("parent_grant_hash") != (chain[i]["grant_hash"] if i > 0 else grant.get("root_hash"))
               for i, hop in enumerate(chain)):
            raise DelegationBudgetViolation(
                f"provenance chain for grant {grant.get('id')} is broken or non-monotonic"
            )

    child = dict(grant)
    child["delegation_budget"] = budget - 1
    child["subject_set"] = [callee_id]  # narrow, never widen
    child["provenance_chain"] = chain + [{
        "signer": presenter_id,
        "hop_index": (chain[-1]["hop_index"] + 1) if chain else 0,
        "parent_grant_hash": grant.get("grant_hash"),
        "grant_hash": _hash(child),
    }]
    return child


def _hash(grant: dict) -> str:
    import hashlib, json
    body = {k: v for k, v in grant.items() if k != "grant_hash"}
    return hashlib.sha256(json.dumps(body, sort_keys=True).encode()).hexdigest()
