# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-derive-its-delegated-capability-scope-when-least-privilege-attenuation-is-enforced-across-a-multi-hop-agent-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-derive-its-delegated-capability-scope-when-least-privilege-attenuation-is-enforced-across-a-multi-hop-agent-chain.warrant.json
# Markdown SHA-256:   b26aa6ebd6d379a5ba2ebcaa4945274204a4afd4ee730c27a5b8653765c24cd9
# Code AST SHA-256:   2370ff5b5e99c7f7feb324fd9e4787ef531c4c4bd6e68538656a65cf987ca625
# Verified Classes:   AttenuationDriftError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class AttenuationDriftError(RuntimeError):
    """Raised when a delegated capability's scope is not a subset of the
    parent's *live* scope at delegation time, only of its issuance-time scope."""
    pass


def mint_delegated_scope(
    parent_token: dict,
    grant_store: dict,
    requested_scope: dict,
) -> dict:
    """
    Mint a child capability token. Enforces the live-attenuation invariant:
    child_scope must be a subset of the parent's CURRENT live scope, not the
    scope embedded in the parent token at issuance.
    """
    parent_id = parent_token["grant_id"]

    if parent_id not in grant_store:
        raise AttenuationDriftError(
            f"parent grant {parent_id!r} no longer exists in grant store; "
            f"cannot attenuate against a dead lineage"
        )

    live_parent_scope = grant_store[parent_id]["live_scope"]
    issuance_scope = parent_token["scope"]

    # The drift check: if the parent's live scope has shrunk below its
    # issuance scope, the child must be attenuated against the *live* scope.
    # A child that fits issuance_scope but not live_scope is over-privileged.
    for resource, perms in requested_scope.items():
        live_perms = set(live_parent_scope.get(resource, []))
        req_perms = set(perms)
        if not req_perms.issubset(live_perms):
            raise AttenuationDriftError(
                f"requested scope {resource}:{sorted(req_perms)} is not a subset "
                f"of parent live scope {resource}:{sorted(live_perms)} "
                f"(issuance scope was {resource}:{sorted(issuance_scope.get(resource, []))})"
            )

    child_token = {
        "grant_id": f"{parent_id}/child-{len(grant_store[parent_id].get('children', []))}",
        "lineage": parent_token["lineage"] + [parent_id],
        "scope": requested_scope,
        "parent_live_snapshot": live_parent_scope,
    }
    grant_store[child_token["grant_id"]] = {
        "live_scope": requested_scope,
        "children": [],
        "lineage": child_token["lineage"],
    }
    grant_store[parent_id].setdefault("children", []).append(child_token["grant_id"])
    return child_token


def revoke(grant_store: dict, grant_id: str) -> None:
    """
    Revoke a grant and cascade to all descendants by marking the lineage dead.
    Descendant tokens remain cryptographically valid but fail live validation.
    """
    if grant_id not in grant_store:
        raise AttenuationDriftError(f"cannot revoke unknown grant {grant_id!r}")
    grant_store[grant_id]["live_scope"] = {}
    grant_store[grant_id]["revoked"] = True
    for child_id in grant_store[grant_id].get("children", []):
        revoke(grant_store, child_id)
