# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-signed-capability-downgrade-when-federation-peers-re-sign-a-narrower-warrant-during-a2a-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-signed-capability-downgrade-when-federation-peers-re-sign-a-narrower-warrant-during-a2a-handoff.warrant.json
# Markdown SHA-256:   ec39922b31799cc0fed78feb1f7262761548428c9351f92ec3a99c9af6f1b8b0
# Code AST SHA-256:   2043125bd136c42ec43bd517110cde3cda6c9d6a792fb0cac48d4494498b4628
# Verified Classes:   ContainmentViolation, IncomparableScopeGrammar, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import FrozenSet, Optional


class ContainmentViolation(RuntimeError):
    """Raised when a re-signed child warrant is not a declared subset of its parent."""
    pass


class IncomparableScopeGrammar(ContainmentViolation):
    """Raised when parent and child warrants parse under different grammar versions."""
    pass


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str
    scopes: FrozenSet[str]
    grammar_version: int
    narrowing_manifest: Optional[FrozenSet[str]] = None
    signature: str = ""

    def digest(self) -> str:
        body = f"{self.issuer}|{self.subject}|{sorted(self.scopes)}|{self.grammar_version}"
        return hashlib.sha256(body.encode()).hexdigest()


def verify_handoff(parent: Warrant, child: Warrant, trusted_roots: FrozenSet[str]) -> None:
    # 1. Cryptographic layer: both artifacts must be signed by trusted issuers.
    if parent.issuer not in trusted_roots or child.issuer not in trusted_roots:
        raise ContainmentViolation(
            f"untrusted issuer: parent={parent.issuer} child={child.issuer}"
        )
    if not parent.signature or not child.signature:
        raise ContainmentViolation("missing signature on warrant chain")

    # 2. Grammar layer: subset comparison is only defined under a shared grammar.
    if parent.grammar_version != child.grammar_version:
        raise IncomparableScopeGrammar(
            f"grammar skew: parent v{parent.grammar_version} vs child v{child.grammar_version}; "
            "containment is undefined, failing closed"
        )

    # 3. Semantic layer: child scopes must be a subset of parent scopes.
    leaked = child.scopes - parent.scopes
    if leaked:
        raise ContainmentViolation(
            f"child warrant escalates beyond parent grant: {sorted(leaked)}"
        )

    # 4. Narrowing layer: any strict subset must be declared in a signed manifest.
    trimmed = parent.scopes - child.scopes
    if trimmed:
        if child.narrowing_manifest is None:
            raise ContainmentViolation(
                f"undeclared narrowing: peer {child.issuer} dropped {sorted(trimmed)} "
                "without a signed narrowing_manifest; indistinguishable from serializer bug"
            )
        if child.narrowing_manifest != trimmed:
            raise ContainmentViolation(
                f"manifest mismatch: declared {sorted(child.narrowing_manifest)} "
                f"but actual trim was {sorted(trimmed)}"
            )

    # Handoff accepted: chain intact, containment holds, loss (if any) is auditable.
    return None


# --- Trace of the observed failure ---
alpha_grant = Warrant(
    issuer="alpha", subject="beta",
    scopes=frozenset({"read:dataset", "write:dataset", "invoke:summarizer"}),
    grammar_version=2, signature="sig_alpha_ok",
)
# Beta's serializer dropped invoke:summarizer under an old grammar path, then signed.
beta_resign = Warrant(
    issuer="beta", subject="gamma",
    scopes=frozenset({"read:dataset", "write:dataset"}),
    grammar_version=2, narrowing_manifest=None, signature="sig_beta_ok",
)

verify_handoff(alpha_grant, beta_resign, trusted_roots=frozenset({"alpha", "beta"}))
# -> raises ContainmentViolation: undeclared narrowing, caught at handoff, not at leaf.
