# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-re-signed-skill-manifest-after-its-provenance-chain-is-truncated-at-the-third-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-re-signed-skill-manifest-after-its-provenance-chain-is-truncated-at-the-third-hop.warrant.json
# Markdown SHA-256:   896167dac7750046096c0bdfdf38fd060cfa312df32e8e228fffa223ae43504f
# Code AST SHA-256:   e7a8050807a4a63519c17fb82cb9783f80af1f1cbdc684d9ca5859342320da09
# Verified Classes:   ProvenanceChainError, Envelope
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence, Set

class ProvenanceChainError(RuntimeError):
    """Raised when a skill manifest's provenance chain is not a valid,
    connected, terminally-anchored, capability-monotone path from a trusted root."""

@dataclass(frozen=True)
class Envelope:
    issuer: str
    subject_digest: str          # digest of the artifact this envelope vouches for
    material_digest: str         # digest of the envelope below it (its input)
    capabilities: Set[str]
    issued_at: int

def verify_provenance_chain(
    chain: Sequence[Envelope],
    leaf_digest: str,
    trusted_roots: Set[str],
    min_hops: int = 3,
) -> None:
    # 1. Length floor: a privileged skill may not ride a short chain.
    if len(chain) < min_hops:
        raise ProvenanceChainError(
            f"chain has {len(chain)} hops, floor is {min_hops}; "
            f"truncation is indistinguishable from forgery"
        )

    # 2. Terminal anchoring: the trusted root must be LAST and must vouch
    #    for the preceding envelope, not for a decoy artifact.
    root = chain[-1]
    if root.issuer not in trusted_roots:
        raise ProvenanceChainError(
            f"terminal envelope issuer {root.issuer!r} is not a trusted root"
        )
    if root.subject_digest != chain[-2].material_digest:
        raise ProvenanceChainError(
            f"root anchors decoy {root.subject_digest[:8]}…, "
            f"not hop {len(chain)-1} material {chain[-2].material_digest[:8]}…"
        )

    # 3. Connectedness: every envelope's subject must equal the next-down
    #    envelope's material digest. A gap means truncation or substitution.
    for i in range(len(chain) - 1):
        lower, upper = chain[i], chain[i + 1]
        if upper.subject_digest != lower.material_digest:
            raise ProvenanceChainError(
                f"chain break at hop {i}: subject {upper.subject_digest[:8]}… "
                f"!= hop {i} material {lower.material_digest[:8]}…"
            )

    # 4. Leaf binding: the bottom envelope must vouch for the actual manifest.
    if chain[0].subject_digest != leaf_digest:
        raise ProvenanceChainError(
            f"leaf envelope subject {chain[0].subject_digest[:8]}… "
            f"does not match manifest digest {leaf_digest[:8]}…"
        )

    # 5. Capability monotonicity: leaf caps ⊆ every ancestor's caps.
    for i in range(len(chain) - 1):
        if not chain[i].capabilities.issubset(chain[i + 1].capabilities):
            extra = chain[i].capabilities - chain[i + 1].capabilities
            raise ProvenanceChainError(
                f"privilege escalation at hop {i}: {sorted(extra)} "
                f"granted at leaf but not by parent"
            )

    # 6. Freshness: no hop may predate its parent (replay guard).
    for i in range(len(chain) - 1):
        if chain[i].issued_at < chain[i + 1].issued_at:
            raise ProvenanceChainError(
                f"hop {i} issued before its parent; stale leaf under new root"
            )
