# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-capability-that-is-technically-satisfiable-but-provenance-incomplete.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-capability-that-is-technically-satisfiable-but-provenance-incomplete.warrant.json
# Markdown SHA-256:   929e6682e265a09556fcd0796776a1d7bece36dcb9a891f55c6518615727abcf
# Code AST SHA-256:   0cb2ae9602b0b86258e3d019f08a360efce68efee7e2be77260f90afb79b9af0
# Verified Classes:   ProvenanceIncompleteError, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ProvenanceIncompleteError(RuntimeError):
    """Raised when a delegated warrant is scope-valid but its provenance
    chain cannot be reconstructed as a connected, hash-linked, root-anchored,
    intent-bearing path."""


@dataclass(frozen=True)
class Warrant:
    issuer: str
    scope: frozenset
    budget: int
    intent_id: str
    provenance: tuple = field(default_factory=tuple)  # tuple of parent content-hashes

    def content_hash(self) -> str:
        blob = repr((self.issuer, sorted(self.scope), self.budget,
                     self.intent_id, self.provenance)).encode()
        return hashlib.sha256(blob).hexdigest()


def attenuate(parent: Warrant, *, issuer: str, scope: frozenset, budget: int) -> Warrant:
    # Scope/budget monotonicity is checked by the caller; linkage is computed here,
    # never supplied by the agent, so re-rooting is impossible.
    if not scope <= parent.scope:
        raise ProvenanceIncompleteError(f"scope escalation: {scope} not subset of {parent.scope}")
    if budget > parent.budget:
        raise ProvenanceIncompleteError(f"budget escalation: {budget} > {parent.budget}")
    return Warrant(
        issuer=issuer,
        scope=scope,
        budget=budget,
        intent_id=parent.intent_id,          # preserved, not re-typed
        provenance=parent.provenance + (parent.content_hash(),),  # append H(parent)
    )


def verify_chain(leaf: Warrant, known_parent_hashes: set[str]) -> None:
    """Reconstruct the path. known_parent_hashes is the set of content-hashes
    the verifier has independently seen (e.g. from the root grantor's registry)."""
    if not leaf.intent_id:
        raise ProvenanceIncompleteError("empty intent_id: warrant anchors to nothing")
    if not leaf.provenance:
        raise ProvenanceIncompleteError("no provenance links: self-rooted warrant")
    for parent_hash in leaf.provenance:
        if parent_hash not in known_parent_hashes:
            raise ProvenanceIncompleteError(
                f"dangling provenance edge: parent {parent_hash[:12]}… unverifiable; "
                f"chain cannot be joined to a root intent"
            )


def execute_read(warrant: Warrant, resource: str, known_parent_hashes: set[str]) -> str:
    # Gate 1: scope (least privilege)
    if resource not in warrant.scope:
        raise PermissionError(f"{resource} outside attenuated scope")
    # Gate 2: provenance (attribution) — the non-obvious gate
    verify_chain(warrant, known_parent_hashes)
    # Gate 3: budget is enforced by the caller's ledger, elided here
    return f"read {resource} under intent {warrant.intent_id}"
