# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-federation-trust-anchor-has-silently-degraded-to-a-self-asserted-warrant-during-cross-org-capability-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-federation-trust-anchor-has-silently-degraded-to-a-self-asserted-warrant-during-cross-org-capability-negotiation.warrant.json
# Markdown SHA-256:   7a37a014c599ab4e8b0cac8a3b85c2a9730f488d32ad95c8ccc95e4127599b29
# Code AST SHA-256:   253a53b14b3b70f3be274f024506207227efd6aa9c2d3a3018b804fdea2523de
# Verified Classes:   WarrantNarrowingViolation, WarrantChainUnparseable, AnchorSchemaMismatch, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Any


class WarrantNarrowingViolation(RuntimeError):
    """Leaf warrant scope exceeds parent grant on a constrained dimension."""


class WarrantChainUnparseable(RuntimeError):
    """Parent grant present but not deserializable under verifier schema."""


class AnchorSchemaMismatch(RuntimeError):
    """Leaf anchor lacks a constraint key present in the parent anchor."""


@dataclass
class Warrant:
    scope: dict[str, Any]
    anchor_id: str
    parent: bytes | None


def derive_warrant(parent: Warrant, local_scope: dict[str, Any],
                   local_anchor_schema: set[str],
                   parent_anchor_schema: set[str]) -> Warrant:
    # 1. Parent must be parseable if present.
    if parent.parent is not None:
        try:
            _ = _parse_grant(parent.parent)
        except Exception as exc:
            raise WarrantChainUnparseable(
                f"parent grant for {parent.anchor_id} unparseable: {exc}"
            ) from exc

    # 2. Schema vocabulary must cover parent constraints.
    missing = parent_anchor_schema - local_anchor_schema
    if missing:
        raise AnchorSchemaMismatch(
            f"leaf anchor cannot express parent constraints: {sorted(missing)}"
        )

    # 3. Scope must be an intersection, not a widening.
    for key, parent_val in parent.scope.items():
        if key not in local_scope:
            continue
        if _exceeds(local_scope[key], parent_val):
            raise WarrantNarrowingViolation(
                f"scope[{key!r}] widened from {parent_val!r} to {local_scope[key]!r}"
            )

    return Warrant(scope=local_scope, anchor_id="derived", parent=parent.parent)


def _parse_grant(blob: bytes) -> dict[str, Any]:
    raise NotImplementedError  # schema-specific deserializer


def _exceeds(leaf: Any, parent: Any) -> bool:
    if isinstance(leaf, int) and isinstance(parent, int):
        return leaf > parent
    if isinstance(leaf, (set, list)) and isinstance(parent, (set, list)):
        return not set(leaf).issubset(set(parent))
    return leaf != parent
