# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-attenuated-capability-drift-when-chaining-delegated-attestation-credentials-across-trust-domains.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-attenuated-capability-drift-when-chaining-delegated-attestation-credentials-across-trust-domains.warrant.json
# Markdown SHA-256:   03cb0f284c07fd740b12546d4ad259a7a249574e239d96a18ada21964ec4e5f5
# Code AST SHA-256:   73a1e91629acbcd75f1291d54e09e241b46b25bfd3ddb84d988b4a4a337a73fd
# Verified Classes:   AttenuationViolation, Scope, Credential
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class AttenuationViolation(RuntimeError):
    """Raised when a delegated credential's scope is not provably a subset of its parent's."""


@dataclass(frozen=True)
class Scope:
    registry_id: str          # root-pinned vocabulary the predicate is drawn from
    predicates: FrozenSet[str]


@dataclass(frozen=True)
class Credential:
    issuer: str
    subject: str
    scope: Scope
    ttl_seconds: int
    subsumption_proof: str | None   # derivation in registry_id vocabulary, or None


def verify_chain(root_registry_id: str, chain: list[Credential]) -> None:
    """Enforce monotonic attenuation across a delegated credential chain.

    Cryptographic signature checks are assumed to have passed upstream.
    This function enforces the *semantic* invariant that signatures cannot.
    """
    if not chain:
        raise AttenuationViolation("empty credential chain")

    for i, cred in enumerate(chain):
        if cred.scope.registry_id != root_registry_id:
            # Foreign vocabulary: cannot prove subsumption, must fail closed.
            raise AttenuationViolation(
                f"hop {i} ({cred.subject}) uses registry {cred.scope.registry_id!r}, "
                f"root pinned {root_registry_id!r}; subsumption unprovable"
            )
        if i == 0:
            continue

        parent, child = chain[i - 1], cred

        # TTL attenuation is necessary but never sufficient.
        if child.ttl_seconds > parent.ttl_seconds:
            raise AttenuationViolation(
                f"hop {i} TTL {child.ttl_seconds}s exceeds parent {parent.ttl_seconds}s"
            )

        # Byte-identical scope is trivially attenuating.
        if child.scope == parent.scope:
            continue

        # Otherwise require a carried subsumption proof in the pinned registry.
        if child.subsumption_proof is None:
            raise AttenuationViolation(
                f"hop {i} ({child.subject}) widens or re-expresses scope without a "
                f"subsumption proof in registry {root_registry_id!r}"
            )

        if not _check_subsumption(child.subsumption_proof, parent.scope, child.scope):
            raise AttenuationViolation(
                f"hop {i} ({child.subject}) subsumption proof does not establish "
                f"eff(child) subset-of eff(parent)"
            )


def _check_subsumption(proof: str, parent: Scope, child: Scope) -> bool:
    # Stub: real implementation replays the derivation against the pinned
    # registry's subset relation. Returning False on any doubt is the point.
    return False


def self_issue(parent: Credential, requested: Scope, ttl_seconds: int,
               root_registry_id: str) -> Credential:
    """An executing instance issuing a downstream credential to a helper."""
    if requested.registry_id != root_registry_id:
        raise AttenuationViolation(
            f"refusing self-issue: requested scope uses {requested.registry_id!r}, "
            f"not root registry {root_registry_id!r}"
        )
    if requested != parent.scope:
        # Non-identical scope requires a proof we do not have at issue time.
        raise AttenuationViolation(
            "refusing self-issue: requested scope differs from received scope "
            "and no subsumption proof can be produced against the pinned registry; "
            "request explicit re-delegation from the parent"
        )
    return Credential(
        issuer=parent.subject,
        subject="helper",
        scope=requested,
        ttl_seconds=min(ttl_seconds, parent.ttl_seconds),
        subsumption_proof=None,
    )
