# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-warrant-attenuation-forgery-in-a-delegated-agent-chain-when-the-signing-key-is-shared-across-a-tool-sandbox.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-warrant-attenuation-forgery-in-a-delegated-agent-chain-when-the-signing-key-is-shared-across-a-tool-sandbox.warrant.json
# Markdown SHA-256:   cf80e4a53a310bfd28c87106630f4d555304fd1a12d3fb48fa324c5eda6711f7
# Code AST SHA-256:   05cb9fabe073ee6f2b6dab3c0d8c752467399afa712dc49afdba203981d77027
# Verified Classes:   WarrantProvenanceError, Warrant, WarrantVerifier
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class WarrantProvenanceError(RuntimeError):
    """Raised when a delegated warrant cannot be attributed to the delegating instance."""
    pass


@dataclass
class Warrant:
    subject: str
    capabilities: frozenset
    parent_hash: str | None
    signing_key_id: str
    delegatee_key_id: str | None
    nonce: int = 0

    def digest(self) -> str:
        payload = f"{self.subject}|{sorted(self.capabilities)}|{self.parent_hash}|{self.nonce}"
        return hashlib.sha256(payload.encode()).hexdigest()


class WarrantVerifier:
    def __init__(self, trusted_keys: dict, cache_enabled: bool = True):
        self.trusted_keys = trusted_keys
        self.cache_enabled = cache_enabled
        self._cache: dict = {}

    def verify(self, child: Warrant, parent: Warrant | None) -> bool:
        if child.signing_key_id not in self.trusted_keys:
            raise WarrantProvenanceError(
                f"signing key {child.signing_key_id!r} not trusted"
            )

        if parent is not None:
            # Provenance invariant: the child must be signed by the key the
            # parent explicitly delegated to. Shared sandbox keys violate this.
            if parent.delegatee_key_id != child.signing_key_id:
                raise WarrantProvenanceError(
                    f"provenance mismatch: parent delegated to "
                    f"{parent.delegatee_key_id!r} but child signed by "
                    f"{child.signing_key_id!r}"
                )
            # Attenuation must be monotonic: child capabilities subset of parent.
            if not child.capabilities.issubset(parent.capabilities):
                raise WarrantProvenanceError(
                    f"attenuation violation: {sorted(child.capabilities)} not "
                    f"subset of {sorted(parent.capabilities)}"
                )

        if not self.cache_enabled:
            return True

        # Cache key MUST include the child's capability digest, not just the
        # parent hash and signing key, or sibling children collide.
        cache_key = (child.parent_hash, child.signing_key_id, child.digest())
        if cache_key in self._cache:
            return self._cache[cache_key]
        self._cache[cache_key] = True
        return True


def delegate(parent: Warrant, child_caps: frozenset, child_signing_key_id: str,
             nonce: int) -> Warrant:
    if not child_caps.issubset(parent.capabilities):
        raise WarrantProvenanceError(
            f"cannot delegate {sorted(child_caps)} from parent grant "
            f"{sorted(parent.capabilities)}"
        )
    return Warrant(
        subject="child",
        capabilities=child_caps,
        parent_hash=parent.digest(),
        signing_key_id=child_signing_key_id,
        delegatee_key_id=None,
        nonce=nonce,
    )


def detect_shared_key_forgery(verifier: WarrantVerifier, forged: Warrant,
                              parent: Warrant) -> None:
    try:
        verifier.verify(forged, parent)
    except WarrantProvenanceError:
        return  # correctly rejected
    raise WarrantProvenanceError(
        f"forged warrant {forged.digest()[:12]} accepted under shared key "
        f"{forged.signing_key_id!r}; provenance check missing"
    )
