# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-capability-escalation-when-federated-agent-peers-renegotiate-policy-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-capability-escalation-when-federated-agent-peers-renegotiate-policy-mid-handoff.warrant.json
# Markdown SHA-256:   222d46488af437b6155c9d9940ed99ca51b7000c5fa9622da93f401c4db0aae0
# Code AST SHA-256:   c8a8eecf738fb0a9f68a107fd6fbe220e50adee7a43755454c3d9fe9e76a920a
# Verified Classes:   CapabilityEscalationError, Warrant, Manifest, EpochBridge
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class CapabilityEscalationError(RuntimeError):
    """Raised when a handoff would re-anchor a warrant across policy epochs
    without a signed bridge, opening a silent-escalation path."""
    pass


@dataclass(frozen=True)
class Warrant:
    grant: frozenset[str]
    anchor: str            # hash of originating principal's authorization
    anchor_epoch: str
    depth_remaining: int


@dataclass(frozen=True)
class Manifest:
    capabilities: frozenset[str]
    epoch: str


@dataclass(frozen=True)
class EpochBridge:
    from_epoch: str
    to_epoch: str
    binds_anchor: str
    signature: str


def _valid_bridge(bridge: EpochBridge, carried: Warrant, receiver_epoch: str) -> bool:
    # A bridge is valid only if it binds the *same* anchor and spans the gap.
    return (
        bridge.from_epoch == carried.anchor_epoch
        and bridge.to_epoch == receiver_epoch
        and bridge.binds_anchor == carried.anchor
        and bool(bridge.signature)
    )


def handoff(
    carried: Warrant,
    manifest: Manifest,
    bridge: EpochBridge | None,
) -> Warrant:
    if carried.depth_remaining <= 0:
        raise CapabilityEscalationError(
            f"delegation depth exhausted at anchor {carried.anchor[:12]}"
        )

    if carried.anchor_epoch == manifest.epoch:
        effective_anchor = carried.anchor
        effective_epoch = carried.anchor_epoch
    else:
        if bridge is None or not _valid_bridge(bridge, carried, manifest.epoch):
            # Fail closed: never re-anchor from the receiver's manifest.
            raise CapabilityEscalationError(
                f"epoch mismatch {carried.anchor_epoch}->{manifest.epoch} "
                f"with no bridge binding anchor {carried.anchor[:12]}; "
                f"refusing handoff (would enable silent capability escalation)"
            )
        effective_anchor = bridge.binds_anchor
        effective_epoch = bridge.to_epoch

    # Manifest is a FILTER only; carried grant is the sole origin of authority.
    new_grant = carried.grant & manifest.capabilities
    if not new_grant:
        raise CapabilityEscalationError(
            "intersection empty: receiver manifest grants no carried capability"
        )

    return Warrant(
        grant=new_grant,
        anchor=effective_anchor,
        anchor_epoch=effective_epoch,
        depth_remaining=carried.depth_remaining - 1,
    )


def demo() -> None:
    w0 = Warrant(
        grant=frozenset({"read:dataset", "summarize", "write:report"}),
        anchor=hashlib.sha256(b"origin-authz").hexdigest(),
        anchor_epoch="E1",
        depth_remaining=2,
    )
    w_manifest = Manifest(
        capabilities=frozenset(
            {"read:dataset", "summarize", "write:report",
             "delete:dataset", "export:external"}
        ),
        epoch="E2",
    )

    # No bridge: must fail closed rather than re-anchor to E2.
    try:
        handoff(w0, w_manifest, bridge=None)
    except CapabilityEscalationError as e:
        print(f"[refused as expected] {e}")

    # With a signed bridge binding the SAME anchor, handoff proceeds,
    # and the carried grant (not the manifest) remains the ceiling.
    bridge = EpochBridge(
        from_epoch="E1", to_epoch="E2",
        binds_anchor=w0.anchor, signature="sig:O->E1->E2",
    )
    w1 = handoff(w0, w_manifest, bridge=bridge)
    assert "delete:dataset" not in w1.grant
    assert w1.anchor == w0.anchor and w1.depth_remaining == 1
    print(f"[bridged ok] grant={sorted(w1.grant)} anchor_epoch={w1.anchor_epoch}")


if __name__ == "__main__":
    demo()
