# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-capability-token-whose-scope-closure-was-computed-under-a-different-policy-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-capability-token-whose-scope-closure-was-computed-under-a-different-policy-epoch.warrant.json
# Markdown SHA-256:   60657b9a196d2be751aa9ccf8884c3f49768fe0ce8a5d2ad54aaf977e9899e54
# Code AST SHA-256:   79c198b462882020e7b2deec1824e1a0051e13a62f493cb395eb717a40d09cdc
# Verified Classes:   ScopeEpochDivergenceError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ScopeEpochDivergenceError(RuntimeError):
    """Raised when a delegated token's scope cannot be proven a semantic
    subset of its issuer's scope under a common policy epoch."""
    pass


def authorize_delegated_use(
    token_scope: str,
    token_epoch_hash: str | None,
    issuer_epoch_hash: str | None,
    live_expand,
    epoch_expand,
) -> bool:
    # Fast path: token is epoch-pinned and the issuer's epoch is known,
    # so the subset proof is evaluated under a single frozen table.
    if token_epoch_hash is not None and issuer_epoch_hash is not None:
        if token_epoch_hash != issuer_epoch_hash:
            # Delegation crossed an epoch boundary; the child's closure
            # was computed against a different expansion table than the
            # issuer's. Refuse rather than compare apples to oranges.
            raise ScopeEpochDivergenceError(
                f"token epoch {token_epoch_hash} != issuer epoch "
                f"{issuer_epoch_hash}; subset relation unprovable"
            )
        child = epoch_expand(token_scope, token_epoch_hash)
        parent = epoch_expand(token_scope, issuer_epoch_hash)
        return child <= parent

    # Unpinned token: we can only compare against the live policy, which
    # is exactly the check that fails to catch epoch-drift widening.
    # Refuse unless an explicit override registry says this scope is
    # monotone-stable across all known epochs.
    if token_epoch_hash is None and issuer_epoch_hash is None:
        live = live_expand(token_scope)
        if not _scope_is_monotone_stable(token_scope):
            raise ScopeEpochDivergenceError(
                f"scope {token_scope!r} has no epoch binding and is not "
                f"registered monotone-stable; refusing delegated use"
            )
        return True

    # One side pinned, one not: cannot form a common-epoch subset proof.
    raise ScopeEpochDivergenceError(
        "asymmetric epoch binding across delegation hop; "
        "cannot evaluate semantic subset"
    )


def _scope_is_monotone_stable(scope: str) -> bool:
    # Placeholder: consult the monotone-scope registry maintained by the
    # policy owner. Default deny.
    return False
