# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-warrant-whose-provenance-chain-crosses-an-unsigned-orchestrator-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-delegated-warrant-whose-provenance-chain-crosses-an-unsigned-orchestrator-hop.warrant.json
# Markdown SHA-256:   f98335c985b1b35c0e330c145f85ea6a0a65ec63f634073440d2b59d62aa3438
# Code AST SHA-256:   bf70761df253a05d51a33b9ad2824fc1a1595f02d48e8b2e9a7c969588aed834
# Verified Classes:   ProvenanceChainError, Hop
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class ProvenanceChainError(RuntimeError):
    """Raised when a delegated warrant's provenance chain cannot be trusted."""
    pass


@dataclass(frozen=True)
class Hop:
    hop_id: str
    parent_digest: Optional[str]   # digest of the previous envelope
    scope: str
    intent: str
    signature: Optional[str]        # None => unsigned / deferred hop
    sig_status: str                 # "signed" | "deferred" | "missing"


def _digest(hop: Hop) -> str:
    payload = f"{hop.hop_id}|{hop.parent_digest}|{hop.scope}|{hop.intent}"
    return hashlib.sha256(payload.encode()).hexdigest()


def verify_chain(chain: list[Hop], pinned_anchors: dict[str, str]) -> bool:
    """
    Enforce chain-link integrity: every hop must be signed AND must commit
    to the digest of its parent envelope. Endpoint validity is insufficient.
    """
    if not chain:
        raise ProvenanceChainError("empty provenance chain")

    prev_digest: Optional[str] = None
    for i, hop in enumerate(chain):
        # 1. Every hop must carry a signature; deferred/missing is a forgeable seam.
        if hop.sig_status != "signed" or hop.signature is None:
            raise ProvenanceChainError(
                f"hop {hop.hop_id} (index {i}) is unsigned "
                f"(status={hop.sig_status!r}); seam is forgeable"
            )

        # 2. The signature must commit to the parent digest, not intent alone.
        expected_parent = prev_digest
        if hop.parent_digest != expected_parent:
            raise ProvenanceChainError(
                f"hop {hop.hop_id} parent_digest mismatch: "
                f"claimed={hop.parent_digest!r} expected={expected_parent!r}"
            )

        # 3. Key must resolve against a pinned anchor, not live mutable state.
        if hop.hop_id not in pinned_anchors:
            raise ProvenanceChainError(
                f"hop {hop.hop_id} has no pinned trust anchor; "
                f"validity would depend on live registry state"
            )

        prev_digest = _digest(hop)

    return True


def execute_delegated(chain: list[Hop], anchors: dict[str, str]) -> str:
    try:
        verify_chain(chain, anchors)
    except ProvenanceChainError as exc:
        # Fail closed: do not execute on an unverified warrant.
        return f"REFUSED: {exc}"
    return "EXECUTED"
