# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-delegates-a-capability-across-an-org-boundary-and-the-warrant-s-attenuation-lattice-disagrees-with-the-peer-s.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-delegates-a-capability-across-an-org-boundary-and-the-warrant-s-attenuation-lattice-disagrees-with-the-peer-s.warrant.json
# Markdown SHA-256:   c4c6e36c4c899b0d1a3353c1540081e29f4964a29ec6125d7e1ec224fbac3d28
# Code AST SHA-256:   fb4ea1ef0f701631a5eb167ae9494543b571b918ddedc37c85e5c3ca71c8ce7c
# Verified Classes:   AttenuationLatticeMismatch, Caveat, Warrant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Any


class AttenuationLatticeMismatch(RuntimeError):
    """Raised when a re-delegated warrant cannot be proven a subset of its
    parent under a single, pinned, type-preserving attenuation lattice."""


@dataclass(frozen=True)
class Caveat:
    key: str
    op: str          # "<=", "==", "in", ...
    value: Any       # MUST be type-preserving; never pre-stringified


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    issuer: str
    lattice_id: str          # pinned hash shared across the federation
    caveats: tuple[Caveat, ...]
    proof_of_parent: bytes | None  # witness that this ⊆ parent


PINNED_LATTICES = {
    # org -> set of lattice_id hashes it will accept for re-delegation
    "org-a": {"lattice-v3:9f2c..."},
    "org-b": {"lattice-v3:9f2c..."},
}


def canonical(c: Caveat) -> tuple[str, str, Any]:
    # Typed canonical form. Two caveats are equal iff these tuples are equal.
    # A string-only canonicalizer here is the bug that widens authority.
    return (c.key, c.op, c.value)


def verify_redelegation(
    parent: Warrant,
    child: Warrant,
    local_org: str,
    root_org: str,
) -> None:
    # 1. Shared, pinned lattice identity across the boundary.
    if child.lattice_id != parent.lattice_id:
        raise AttenuationLatticeMismatch(
            f"lattice drift: parent={parent.lattice_id} child={child.lattice_id}"
        )
    accepted = PINNED_LATTICES.get(root_org, set())
    if child.lattice_id not in accepted:
        raise AttenuationLatticeMismatch(
            f"{local_org} cannot re-delegate: lattice {child.lattice_id} "
            f"not pinned by root {root_org}"
        )

    # 2. Proof must be carried, not re-derived from raw claims.
    if child.proof_of_parent is None:
        raise AttenuationLatticeMismatch(
            f"warrant {child.warrant_id} lacks attenuation proof; "
            "root issuer cannot verify subset relation"
        )

    # 3. Type-preserving subset check: every parent caveat must be
    #    entailed by a child caveat under the SAME typed canonical form.
    child_set = {canonical(c) for c in child.caveats}
    for pc in parent.caveats:
        if canonical(pc) not in child_set:
            # A lossy serialization (e.g. int -> "<=500" string) lands here.
            raise AttenuationLatticeMismatch(
                f"caveat {pc.key}{pc.op}{pc.value!r} not preserved in "
                f"{child.warrant_id}; refusing re-delegation to avoid "
                "silent widening or unverifiable root rejection"
            )


def handle_cross_org_handoff(parent: Warrant, child: Warrant,
                             local_org: str, root_org: str) -> str:
    try:
        verify_redelegation(parent, child, local_org, root_org)
    except AttenuationLatticeMismatch:
        # Fail HERE, at the hop introducing ambiguity — not at the root.
        raise
    return f"redelegation {child.warrant_id} accepted under {child.lattice_id}"
