# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-co-sign-a-delegated-capability-when-its-own-provenance-chain-contains-a-non-monotonic-trust-edge.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-co-sign-a-delegated-capability-when-its-own-provenance-chain-contains-a-non-monotonic-trust-edge.warrant.json
# Markdown SHA-256:   034973679fb7d2da64f1477ec093aa374e3ded84d9fe877b290b9a906a437876
# Code AST SHA-256:   88259dd7841e90a45628c19feabb7c9f3a40a85556c3f300b83d24e98daf8030
# Verified Classes:   NonMonotonicProvenanceError, DelegationEdge
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence


class NonMonotonicProvenanceError(RuntimeError):
    """Raised when a delegation chain verifies link-locally but is globally un-attributable."""


@dataclass(frozen=True)
class DelegationEdge:
    issuer: str
    subject: str
    epoch: int
    scope: frozenset


def chain_globally_valid(ancestry: Sequence[DelegationEdge]) -> bool:
    # Epochs must be non-decreasing root -> leaf.
    for parent, child in zip(ancestry, ancestry[1:]):
        if child.epoch < parent.epoch:
            return False
    # No issuer may reappear with a different (epoch, scope) pair.
    seen: dict[str, tuple[int, frozenset]] = {}
    for edge in ancestry:
        prior = seen.get(edge.issuer)
        if prior is not None and prior != (edge.epoch, edge.scope):
            return False
        seen[edge.issuer] = (edge.epoch, edge.scope)
    return True


def cosign(ancestry: Sequence[DelegationEdge], link_locally_valid: bool) -> None:
    if not link_locally_valid:
        raise ValueError("link-local signature/scope/expiry failure")  # ordinary rejection
    if not chain_globally_valid(ancestry):
        offending = next(
            (c for p, c in zip(ancestry, ancestry[1:]) if c.epoch < p.epoch),
            ancestry[-1],
        )
        raise NonMonotonicProvenanceError(
            f"refusing co-sign: non-monotonic trust edge at issuer={offending.issuer!r} "
            f"epoch={offending.epoch}; chain is locally valid but globally un-attributable"
        )
    # Only here does the co-signer commit its signature to the audit trail.
    return None
