# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-inherit-a-delegated-warrant-the-accountability-trace-break-at-the-federation-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-inherit-a-delegated-warrant-the-accountability-trace-break-at-the-federation-boundary.warrant.json
# Markdown SHA-256:   5f782c8285df95caef233c69e133b24eaabf81fe57260c29d4e87f72ca39486e
# Code AST SHA-256:   b11f386d3b245389783583b71ec11a86bc92eb3e89310c5b440d8148054bf3fc
# Verified Classes:   ProvenanceBreak, Hop, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class ProvenanceBreak(RuntimeError):
    """Raised when a delegated warrant cannot be attributed to a named principal
    at execution time from immutable, execution-bound chain material."""
    pass


@dataclass(frozen=True)
class Hop:
    issuer: str
    parent_hash: str
    scope_delta: str
    ts: int


@dataclass(frozen=True)
class Warrant:
    capability: str
    scope: str
    chain_commitment: Optional[str]   # Merkle root or inline-chain hash; None => unattributable
    delegation_depth: int
    chain_material: Optional[tuple]   # tuple[Hop, ...] retrieved from content-addressed store


def _root(chain: tuple) -> str:
    h = hashlib.sha256()
    for hop in chain:
        h.update(f"{hop.issuer}|{hop.parent_hash}|{hop.scope_delta}|{hop.ts}".encode())
    return h.hexdigest()


def verify_and_attribute(warrant: Warrant, known_keys: dict) -> str:
    """Return the named originating principal, or raise ProvenanceBreak.

    Enforces the execution-time invariant: capability is not inherited unless
    accountability is reconstructable from immutable material right now.
    """
    if warrant.chain_commitment is None:
        raise ProvenanceBreak(
            f"warrant for {warrant.capability} carries no chain commitment; "
            "capability without reconstructable provenance is an unattributable grant"
        )

    if not warrant.chain_material:
        raise ProvenanceBreak(
            "chain commitment present but chain material unavailable from "
            "content-addressed store; refusing deferred reconstruction"
        )

    chain = tuple(warrant.chain_material)

    if len(chain) != warrant.delegation_depth:
        raise ProvenanceBreak(
            f"delegation_depth={warrant.delegation_depth} disagrees with "
            f"actual chain length={len(chain)}; depth field is untrustworthy"
        )

    if _root(chain) != warrant.chain_commitment:
        raise ProvenanceBreak(
            "recomputed chain root does not match warrant commitment; "
            "chain material has been altered or substituted"
        )

    # Walk from origin outward; each hop must be signed by a key its parent attested.
    origin = chain[0].issuer
    for i, hop in enumerate(chain):
        expected_parent = "ROOT" if i == 0 else chain[i - 1].issuer
        if hop.parent_hash != expected_parent:
            raise ProvenanceBreak(
                f"hop {i} ({hop.issuer}) claims parent {hop.parent_hash}, "
                f"but chain attests {expected_parent}; key-substitution suspected"
            )
        if hop.issuer not in known_keys:
            raise ProvenanceBreak(
                f"hop {i} issuer {hop.issuer} has no attested key; "
                "cannot verify signature, cannot name principal"
            )

    return origin


def execute_delegated(warrant: Warrant, known_keys: dict) -> str:
    principal = verify_and_attribute(warrant, known_keys)
    # Only reached when provenance is pinned to immutable material.
    return principal
