# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-policy-downgrade-when-capability-negotiation-silently-widens-its-own-write-surface.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-policy-downgrade-when-capability-negotiation-silently-widens-its-own-write-surface.warrant.json
# Markdown SHA-256:   9acb1e4779fdcfeb163b5a1506ce505dc916d9e492916d7c47e4a45ded5d015a
# Code AST SHA-256:   19350bb39d73d1557b74151f2e4993a29ca09ff6720a9ed4780a68dfe6559fcf
# Verified Classes:   FederatedEnvelopeError, AgentCard, LocalPolicy
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class FederatedEnvelopeError(RuntimeError):
    """Raised when a negotiated federation envelope cannot be proven monotonically narrowing."""
    pass


@dataclass
class AgentCard:
    peer_id: str
    write_scope: Optional[list[str]] = None      # None == field omitted on the wire
    egress_allowlist: Optional[list[str]] = None
    tools: list[str] = field(default_factory=list)


@dataclass
class LocalPolicy:
    write_scope: list[str]
    egress_allowlist: list[str]
    can_attach_signed_warrant: bool


def negotiate(local: LocalPolicy, peer: AgentCard, relay_peers: list[AgentCard]) -> dict:
    # Rule 1: omission is never defaulted to a local value.
    omitted = []
    if peer.write_scope is None:
        omitted.append("write_scope")
    if peer.egress_allowlist is None:
        omitted.append("egress_allowlist")

    # Rule 4: transitive peers must be in scope; a relay peer with an
    # unconstrained egress widens the effective envelope.
    unconstrained_relays = [
        r.peer_id for r in relay_peers if r.egress_allowlist is None
    ]

    if omitted:
        # Rule 2: omission is only tolerable if we can transmit the
        # constraint as an enforceable obligation to the far side.
        if not local.can_attach_signed_warrant:
            raise FederatedEnvelopeError(
                f"peer {peer.peer_id} omitted {omitted} and local runtime "
                f"cannot attach a signed warrant; envelope would silently widen"
            )
        if unconstrained_relays:
            raise FederatedEnvelopeError(
                f"peer {peer.peer_id} omitted {omitted} while relay peers "
                f"{unconstrained_relays} have unconstrained egress; "
                f"transitive write surface cannot be bounded"
            )

    # Rule 3: content-addressed envelope key, never peer-id-only.
    bundle = repr((peer.peer_id, peer.write_scope, peer.egress_allowlist, peer.tools))
    envelope = {
        "peer": peer.peer_id,
        "write_scope": local.write_scope,       # enforced locally
        "egress_allowlist": local.egress_allowlist,
        "warrant_required": bool(omitted),
        "envelope_hash": hashlib.sha256(bundle.encode()).hexdigest(),
    }
    return envelope


def apply_envelope(cache: dict, envelope: dict) -> None:
    key = envelope["envelope_hash"]
    if key not in cache:
        # fresh application; stale envelopes keyed by peer id are never reused
        cache[key] = envelope
    else:
        raise FederatedEnvelopeError(
            f"replayed envelope {key[:12]} already applied; "
            f"refusing to double-apply a federation policy"
        )


# Drill reproduction: A restrictive, B permissive (omits write_scope), C relay.
local_a = LocalPolicy(
    write_scope=["/sandbox/a"],
    egress_allowlist=["https://a.internal"],
    can_attach_signed_warrant=False,
)
peer_b = AgentCard(peer_id="org-b", tools=["fs.write", "http.post"])
peer_c = AgentCard(peer_id="org-c", tools=["http.post"])  # egress omitted

try:
    env = negotiate(local_a, peer_b, relay_peers=[peer_c])
    apply_envelope({}, env)
except FederatedEnvelopeError as e:
    # Expected: refusal, not a silent widened envelope.
    print(f"federation refused: {e}")
