# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-audit-grade-provenance-when-a-delegation-warrant-s-attenuation-proof-is-re-derived-instead-of-forwarded.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-audit-grade-provenance-when-a-delegation-warrant-s-attenuation-proof-is-re-derived-instead-of-forwarded.warrant.json
# Markdown SHA-256:   5e623817aaa1d4ce8c00de91272b5d7ea6cbd2bdfc521ff2511a3c1f0ec1d674
# Code AST SHA-256:   197dd3bd8e83ccb93216beed716b5ac5869aaab0b59b5d6446761a427cf1bf57
# Verified Classes:   ProvenanceChainBroken, AttenuationNotCanonical, Warrant
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ProvenanceChainBroken(RuntimeError):
    """Raised when a delegation warrant cannot be reconstructed to its root."""
    pass


class AttenuationNotCanonical(ProvenanceChainBroken):
    """Raised when a child scope is not a provable subset of its parent."""
    pass


@dataclass
class Warrant:
    issuer: str
    subject: str
    scope: frozenset
    parent_bytes: Optional[bytes]          # exact parent warrant bytes, or None at root
    parent_hash: Optional[str]             # sha256 of parent_bytes, or None at root
    transformations: list = field(default_factory=list)  # signed, replayable ops

    def commitment(self) -> str:
        payload = self.issuer.encode() + self.subject.encode()
        payload += b"|" + b",".join(sorted(self.scope)).encode()
        payload += b"|" + (self.parent_hash or "").encode()
        return hashlib.sha256(payload).hexdigest()


def verify_chain(leaf: Warrant, root_key: str) -> None:
    """Reconstruct the full chain from leaf to root and verify every hop.

    Invariant: every non-root warrant MUST carry parent_bytes (or a hash
    commitment whose preimage is supplied) AND every scope transition MUST be
    expressible as a canonical meet. A parent_id-only reference is a chain
    break, not a warning.
    """
    node = leaf
    depth = 0
    while node.parent_bytes is not None or node.parent_hash is not None:
        depth += 1
        if depth > 64:
            raise ProvenanceChainBroken(
                f"delegation chain exceeded max depth at {node.subject}"
            )

        # Rule 1: proof-carrying attenuation — parent bytes must be present.
        if node.parent_bytes is None:
            raise ProvenanceChainBroken(
                f"warrant for {node.subject} references parent by id/hash only; "
                f"chain is not reconstructable without issuer-local state"
            )

        # Rule 2: hash commitment must match the forwarded bytes.
        actual = hashlib.sha256(node.parent_bytes).hexdigest()
        if node.parent_hash is not None and node.parent_hash != actual:
            raise ProvenanceChainBroken(
                f"parent hash mismatch at {node.subject}: "
                f"claimed {node.parent_hash[:12]}, got {actual[:12]}"
            )

        parent = _decode(node.parent_bytes)

        # Rule 3: child scope must be a canonical subset of parent scope.
        # No enumeration, no globbing against live state — pure set meet.
        if not node.scope.issubset(parent.scope):
            leaked = node.scope - parent.scope
            raise AttenuationNotCanonical(
                f"{node.subject} claims authority {sorted(leaked)} not granted "
                f"by {parent.subject}; re-derivation against ambient state "
                f"produced non-canonical attenuation"
            )

        # Rule 4: every transformation must be replayable from the parent.
        for op in node.transformations:
            if not op.get("canonical", False):
                raise AttenuationNotCanonical(
                    f"non-canonical transformation {op.get('name')} at "
                    f"{node.subject}; scope cannot be replayed by an auditor"
                )

        node = parent

    if node.issuer != root_key:
        raise ProvenanceChainBroken(
            f"chain terminates at {node.issuer}, not trusted root {root_key}"
        )


def _decode(raw: bytes) -> Warrant:
    # Placeholder for canonical deserialization; must be byte-stable across
    # issuer and auditor, or Rule 3 becomes unverifiable.
    raise ProvenanceChainBroken("decoder unavailable in this record")
