# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-derive-its-capability-token-before-the-next-tool-call-rather-than-trusting-the-cached-grant.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-derive-its-capability-token-before-the-next-tool-call-rather-than-trusting-the-cached-grant.warrant.json
# Markdown SHA-256:   967685990ae47a06e54ee5610b4b235ca74e728fd0227cb9bb7b3cdbff2921bf
# Code AST SHA-256:   fd3181f5c54185b176fe4126c2a5818066b9e5c8c477d0b584a630d712be5b6a
# Verified Classes:   CapabilityScopeError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class CapabilityScopeError(RuntimeError):
    """Raised when a cached capability token does not provably cover the current operation."""
    pass


def authorize_call(cached_token: dict, operation: dict, now: float) -> dict:
    """
    Re-derive coverage of a cached capability token for a specific operation.
    Returns the token that authorizes the call, or raises CapabilityScopeError.
    """
    if cached_token is None:
        raise CapabilityScopeError("no cached token available for call")

    # 1. Expiry must exceed the call's expected duration, not just be in the future.
    remaining = cached_token["exp"] - now
    if remaining <= operation.get("latency_budget_s", 0.0):
        raise CapabilityScopeError(
            f"token expires in {remaining:.1f}s, below call budget "
            f"{operation.get('latency_budget_s')}s"
        )

    # 2. The token must not have been attenuated for a sibling subtask.
    if cached_token.get("attenuated_for") is not None:
        raise CapabilityScopeError(
            f"cached token is attenuated for {cached_token['attenuated_for']}, "
            f"cannot authorize {operation['resource']}"
        )

    # 3. Scope must provably cover the operation, including wildcard resource identity.
    required = operation["required_scope"]
    granted = cached_token["scope"]
    if not _scope_covers(granted, required, operation):
        raise CapabilityScopeError(
            f"scope {granted!r} does not cover {required!r} for "
            f"resource {operation['resource']!r}"
        )

    # 4. Provenance: record at call time which token authorized this call.
    return {
        "token_id": cached_token["id"],
        "authorized_at": now,
        "operation": operation["resource"],
    }


def _scope_covers(granted: list[str], required: str, operation: dict) -> bool:
    # Wildcard scope requires a call-time resource-identity check when the
    # resource set is mutable; otherwise a literal prefix match is insufficient.
    for grant in granted:
        if grant == required:
            return True
        if grant.endswith("*") and required.startswith(grant[:-1]):
            if operation.get("resource_mutable", False):
                if not operation.get("resource_owner_verified", False):
                    return False
            return True
    return False
