# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-aaif-credential-whose-scope-chain-is-nominally-valid-but-whose-attenuation-proof-is-non-mono.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-aaif-credential-whose-scope-chain-is-nominally-valid-but-whose-attenuation-proof-is-non-mono.warrant.json
# Markdown SHA-256:   1ad14a8810f147509492c5629a089b2db4edeefb5303618bc6ae32b72daf9c78
# Code AST SHA-256:   9351515f25f4f85a78e542d72e7fa4615e2b330e11ebd49ea5423ea7460b6f3d
# Verified Classes:   AttenuationNonMonotone, Hop
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class AttenuationNonMonotone(RuntimeError):
    """Raised when a delegated AAIF chain's attenuation is not provably monotone."""

    def __init__(self, hop_index: int, dropped_conjunct: str, detail: str):
        self.hop_index = hop_index
        self.dropped_conjunct = dropped_conjunct
        self.detail = detail
        super().__init__(
            f"hop {hop_index}: constraint not entailed by parent; "
            f"lost conjunct {dropped_conjunct!r} ({detail})"
        )


@dataclass
class Hop:
    index: int
    scope: frozenset[str]
    constraint: frozenset[str]          # conjunctive predicate atoms
    attenuation_proof: Optional[str]    # machine-checkable proof blob
    widening_warrant: Optional[str]     # root-signed, only legal widening


def _entails(parent: frozenset[str], child: frozenset[str]) -> bool:
    # Child constraint must be implied by parent: every atom in child
    # must already be present (or derivable) in parent. Dropping an atom
    # from parent is a widening, not an attenuation.
    return child.issubset(parent)


def verify_chain(chain: list[Hop], requested_op: str, op_params: frozenset[str]) -> frozenset[str]:
    """Return the recomputed transitive constraint, or raise on non-monotone attenuation."""
    if not chain:
        raise AttenuationNonMonotone(0, "<empty>", "no hops to verify")

    transitive = chain[0].constraint
    for i in range(1, len(chain)):
        parent, child = chain[i - 1], chain[i]

        # 1. Permission-set subset at this hop.
        if not child.scope.issubset(parent.scope):
            raise AttenuationNonMonotone(i, "<scope>", "child scope exceeds parent scope")

        # 2. Constraint entailment, not mere subset-at-leaf.
        if not _entails(parent.constraint, child.constraint):
            if child.widening_warrant is None:
                lost = parent.constraint - child.constraint
                raise AttenuationNonMonotone(
                    i, ", ".join(sorted(lost)), "no widening warrant present"
                )
            # Widening is legal only with a root-signed warrant.
            if not child.widening_warrant.startswith("root-sig:"):
                raise AttenuationNonMonotone(i, ", ".join(sorted(lost)), "unsigned widening")

        # 3. Attenuation proof must be machine-checkable and valid; unknown == invalid.
        if child.attenuation_proof is None or not child.attenuation_proof.startswith("valid:"):
            raise AttenuationNonMonotone(i, "<proof>", "attenuation proof absent or unknown")

        transitive = transitive & child.constraint  # conjunction across hops

    # 4. Terminal operation must satisfy the recomputed transitive conjunction.
    if not op_params.issubset(transitive):
        raise AttenuationNonMonotone(
            len(chain) - 1, "<op>", f"operation {requested_op!r} violates transitive constraint"
        )
    return transitive
