# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-scope-attenuation-forgery-when-a-delegated-aaif-credential-is-re-signed-by-an-intermediate-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-scope-attenuation-forgery-when-a-delegated-aaif-credential-is-re-signed-by-an-intermediate-agent.warrant.json
# Markdown SHA-256:   7bcb6d1c4585b812a74e4611259fb4bbdbc0ef17121ce71d1586cc5b9954d806
# Code AST SHA-256:   aab1103b0dc9703c777b6c9b53f287128129c85d997507b3a2322d8267f7cbd6
# Verified Classes:   ScopeAttenuationForgery, GrantState, Credential
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class ScopeAttenuationForgery(RuntimeError):
    """Raised when a delegated credential's declared parent_scope exceeds
    the parent's authoritative grant at the child's issuance time."""


@dataclass
class GrantState:
    scope: frozenset
    epoch: int
    effective_at: float


@dataclass
class Credential:
    issuer: str
    subject: str
    parent_scope: frozenset
    child_scope: frozenset
    issuance_timestamp: float
    signature_valid: bool = True


def resolve_grant(issuer: str, at_time: float) -> Optional[GrantState]:
    # Authoritative lookup against the issuer's grant log. Returns None if
    # the issuer's state is unreachable or the epoch is unknown.
    ...


def verify_chain(chain: list[Credential], root_scope: frozenset) -> frozenset:
    """Root-forward verification. Returns the effective leaf scope or raises."""
    effective = frozenset(root_scope)

    for hop in chain:
        if not hop.signature_valid:
            raise ScopeAttenuationForgery(
                f"signature invalid at hop {hop.issuer}->{hop.subject}"
            )

        # Local containment is necessary but NOT sufficient.
        if not hop.child_scope <= hop.parent_scope:
            raise ScopeAttenuationForgery(
                f"local containment violated at {hop.subject}"
            )

        # Reconcile the declared parent_scope against authoritative state.
        state = resolve_grant(hop.issuer, hop.issuance_timestamp)
        if state is None:
            # Unverifiable widening claim: forbid for mutating scopes.
            if any(s.startswith("write:") or s.startswith("admin:")
                   for s in hop.child_scope):
                raise ScopeAttenuationForgery(
                    f"cannot resolve grant for {hop.issuer}; "
                    f"refusing privileged scope {hop.child_scope}"
                )
            # Read-only degrade: intersect with root, trust nothing wider.
            effective = effective & hop.child_scope
            continue

        # The declared parent_scope must be a subset of the parent's
        # actual grant at signing time.
        if not hop.parent_scope <= state.scope:
            raise ScopeAttenuationForgery(
                f"declared parent_scope {hop.parent_scope} exceeds "
                f"authoritative grant {state.scope} for {hop.issuer} "
                f"at t={hop.issuance_timestamp}"
            )

        # Child must be signed against the current epoch, not a superseded one.
        if hop.issuance_timestamp < state.effective_at:
            raise ScopeAttenuationForgery(
                f"child signed against superseded grant epoch {state.epoch}"
            )

        # Transitive narrowing: intersect forward, never widen.
        effective = effective & hop.child_scope

    return effective
