# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-transitive-trust-anchor-decay-when-a-federated-peer-re-signs-a-delegated-capability-under-a-rotated-policy-e.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-contain-transitive-trust-anchor-decay-when-a-federated-peer-re-signs-a-delegated-capability-under-a-rotated-policy-e.warrant.json
# Markdown SHA-256:   706b5011364f009fe0b4660aede8986c1f6710999c9bab822c4395ac82763ce8
# Code AST SHA-256:   a7a04cddeb6e478b35e70708878224ee9d0729f3113a50646237f61fbd7a8fda
# Verified Classes:   TrustDecayError, ScopeDelta, AnchorState, Hop, PeerEpochManifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from enum import Enum


class TrustDecayError(RuntimeError):
    """Raised when a federated chain verifies cryptographically but its
    stamped policy epochs are stale in a scope-narrowing way."""


class ScopeDelta(Enum):
    PRESERVING = "preserving"
    WIDENING = "widening"
    NARROWING = "narrowing"


class AnchorState(Enum):
    CURRENT = "current"
    GRACE = "grace"        # still trusted, flagged retiring
    RETIRED = "retired"    # past grace, must reject


@dataclass
class Hop:
    signer: str
    stamped_epoch: int
    anchor_state: AnchorState
    scope_delta_vs_current: ScopeDelta


@dataclass
class PeerEpochManifest:
    signer: str
    current_epoch: int
    fetched_at: float

    def is_fresh(self, ttl_seconds: float = 30.0) -> bool:
        return (time.time() - self.fetched_at) <= ttl_seconds


def admit_federated_capability(
    chain: list[Hop],
    manifests: dict[str, PeerEpochManifest],
    manifest_ttl: float = 30.0,
) -> bool:
    """Admit a delegated capability only if every hop is signature-valid
    (assumed pre-checked) AND epoch-current OR scope-preserving.

    Fails closed on stale manifests: a peer directory outage blocks
    admission rather than silently admitting a stale narrowing grant.
    """
    for hop in chain:
        if hop.anchor_state is AnchorState.RETIRED:
            raise TrustDecayError(
                f"hop {hop.signer}: anchor retired, chain rejected"
            )

        manifest = manifests.get(hop.signer)
        if manifest is None or not manifest.is_fresh(manifest_ttl):
            raise TrustDecayError(
                f"hop {hop.signer}: epoch manifest missing or stale; "
                f"cannot prove scope-preservation, failing closed"
            )

        epoch_current = hop.stamped_epoch == manifest.current_epoch

        if epoch_current:
            continue  # no decay possible

        # Stale epoch: only safe if the newer epoch did not narrow scope.
        if hop.scope_delta_vs_current is ScopeDelta.NARROWING:
            if hop.anchor_state is AnchorState.GRACE:
                raise TrustDecayError(
                    f"hop {hop.signer}: stamped epoch {hop.stamped_epoch} "
                    f"< current {manifest.current_epoch} with scope-narrowing "
                    f"delta under grace-window anchor; "
                    f"verified-but-stale grant, re-negotiation required"
                )
            # narrowing + current anchor is an inconsistency; reject too
            raise TrustDecayError(
                f"hop {hop.signer}: narrowing epoch delta on non-grace anchor"
            )

        # PRESERVING or WIDENING under stale epoch: not over-privileged.
        # Accept, but this is where a caller would emit a decay telemetry event.

    return True


def _example() -> None:
    chain = [
        Hop("A-root", stamped_epoch=7, anchor_state=AnchorState.CURRENT,
            scope_delta_vs_current=ScopeDelta.PRESERVING),
        Hop("B-root-v3", stamped_epoch=41, anchor_state=AnchorState.GRACE,
            scope_delta_vs_current=ScopeDelta.NARROWING),
        Hop("C-root", stamped_epoch=3, anchor_state=AnchorState.CURRENT,
            scope_delta_vs_current=ScopeDelta.PRESERVING),
    ]
    manifests = {
        "A-root": PeerEpochManifest("A-root", 7, time.time()),
        "B-root-v3": PeerEpochManifest("B-root-v3", 42, time.time()),
        "C-root": PeerEpochManifest("C-root", 3, time.time()),
    }
    # Raises TrustDecayError on the B hop: epoch 41 < 42, narrowing, grace.
    admit_federated_capability(chain, manifests)


if __name__ == "__main__":
    _example()
