# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-signed-delegation-receipt-has-silently-lost-its-non-repudiation-guarantee-across-a-re-delegation-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-signed-delegation-receipt-has-silently-lost-its-non-repudiation-guarantee-across-a-re-delegation-chain.warrant.json
# Markdown SHA-256:   94159d27d213bcfab4c7df5185ae86c8f6e62d7cfe2acbfd9456d67afb8e48bd
# Code AST SHA-256:   210886e2199fb8dd74670dd98c79a6876f7404784d80a0fffb78b18d4d4a1819
# Verified Classes:   ScopeDriftError, StaleAncestryError, Receipt
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ScopeDriftError(RuntimeError):
    """Raised when a delegation chain's claimed authority exceeds its received authority."""
    pass


class StaleAncestryError(RuntimeError):
    """Raised when parent_receipt_hash resolves to a receipt from a different task."""
    pass


@dataclass(frozen=True)
class Receipt:
    signer: str
    delegatee: str
    task_id: str
    nonce: str
    granted_scope: frozenset
    received_scope: frozenset
    parent_receipt_hash: Optional[str]
    signature_valid: bool


def verify_chain(root_warrant_scope: frozenset, receipts: list) -> bool:
    """
    Authority-level verification. Signature validity is necessary, not sufficient.
    Fails closed on scope widening or stale ancestry.
    """
    if not receipts:
        raise ScopeDriftError("empty chain: cannot establish non-repudiation")

    prev_hash = None
    prev_scope = root_warrant_scope
    prev_task = None

    for i, r in enumerate(receipts):
        if not r.signature_valid:
            raise ScopeDriftError(f"hop {i}: invalid signature on receipt {r.signer}->{r.delegatee}")

        # Ancestry freshness: parent hash must match and task_id must be consistent.
        if i > 0:
            if r.parent_receipt_hash != prev_hash:
                raise StaleAncestryError(
                    f"hop {i}: parent_receipt_hash mismatch (expected {prev_hash!r}, got {r.parent_receipt_hash!r})"
                )
            if r.task_id != prev_task:
                raise StaleAncestryError(
                    f"hop {i}: task_id {r.task_id!r} does not match ancestor task {prev_task!r} "
                    f"(stale receipt from prior task with same principal)"
                )

        # Claim locality: received_scope must equal what parent actually granted.
        if r.received_scope != prev_scope:
            raise ScopeDriftError(
                f"hop {i}: received_scope {sorted(r.received_scope)} != parent granted {sorted(prev_scope)}"
            )

        # Scope monotonicity: the critical invariant.
        widened = r.granted_scope - r.received_scope
        if widened:
            raise ScopeDriftError(
                f"hop {i}: scope widening detected — {r.signer} granted {sorted(widened)} "
                f"which it never received (signature was valid; claim was false)"
            )

        prev_hash = f"hash({r.signer}->{r.delegatee}:{r.task_id}:{r.nonce})"
        prev_scope = r.granted_scope
        prev_task = r.task_id

    return True


# Replay of the observed incident.
root = frozenset({"read:dataset_7", "summarize"})
chain = [
    Receipt("A", "B", "task-42", "n1",
            frozenset({"read:dataset_7", "summarize", "write:dataset_7"}),
            frozenset({"read:dataset_7", "summarize"}),
            "hash(P->A:task-42:n0)", True),
    Receipt("B", "C", "task-42", "n2",
            frozenset({"read:dataset_7", "summarize", "write:dataset_7", "export:dataset_7"}),
            frozenset({"read:dataset_7", "summarize", "write:dataset_7"}),
            "hash(A->B:task-42:n1)", True),
]

try:
    verify_chain(root, chain)
except ScopeDriftError as e:
    # Correct outcome: signatures all valid, chain rejected on authority grounds.
    print(f"REJECTED (fail-closed): {e}")
