# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-trust-broker-attestation-collapse-during-cross-org-agent-federation-and-how-to-detect-it-before-task-delegation-commi.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-trust-broker-attestation-collapse-during-cross-org-agent-federation-and-how-to-detect-it-before-task-delegation-commi.warrant.json
# Markdown SHA-256:   dc027e8b5e85ff313c9f00cbc79c27ab220cc394549d5fb981fd211932fbceee
# Code AST SHA-256:   63218bc1895126d43a849386f26a0b1e5cea30bd61895064ab242a3130f494d3
# Verified Classes:   AttestationEnvelopeDrift, Attestation, PolicyEnvelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class AttestationEnvelopeDrift(RuntimeError):
    """Raised when a worker's presented attestation no longer matches the
    policy envelope the broker is enforcing, or when an amendment changes
    data_class/egress without advancing the required attestation epoch."""
    pass


@dataclass(frozen=True)
class Attestation:
    org: str
    epoch: int
    envelope_hash: str          # hash of the envelope this attestation was issued under
    caps: frozenset


@dataclass(frozen=True)
class PolicyEnvelope:
    epoch: int
    data_class: str             # "public" | "internal" | "restricted"
    egress: str                 # "none" | "brokered" | "direct"
    required_caps: frozenset

    def hash(self) -> str:
        payload = f"{self.epoch}|{self.data_class}|{self.egress}|{sorted(self.required_caps)}"
        return hashlib.sha256(payload.encode()).hexdigest()


CAPABILITY_AFFECTING_FIELDS = ("data_class", "egress")


def amend_envelope(old: PolicyEnvelope, new: PolicyEnvelope,
                   worker_attestation: Attestation) -> PolicyEnvelope:
    """Apply a policy amendment. If the amendment touches a capability-affecting
    field, the worker's attestation MUST be re-issued under the new envelope
    before any further dispatch is permitted."""
    changed = {f for f in CAPABILITY_AFFECTING_FIELDS
               if getattr(old, f) != getattr(new, f)}

    if changed:
        # Guardrail: an amendment that changes data_class or egress is
        # capability-affecting. The attestation must be re-bound.
        if worker_attestation.envelope_hash != new.hash():
            raise AttestationEnvelopeDrift(
                f"amendment changed {sorted(changed)} but attestation "
                f"(epoch={worker_attestation.epoch}, "
                f"envelope_hash={worker_attestation.envelope_hash[:12]}...) "
                f"was issued under envelope {old.hash()[:12]}..., "
                f"not the enforced {new.hash()[:12]}...; "
                f"re-attestation required before dispatch"
            )
    return new


def dispatch_call(envelope: PolicyEnvelope, attestation: Attestation,
                  call_envelope_hash: str) -> None:
    """Pre-dispatch gate: reject any call whose presented envelope hash
    diverges from the broker's enforced envelope."""
    if call_envelope_hash != envelope.hash():
        raise AttestationEnvelopeDrift(
            f"call presented envelope {call_envelope_hash[:12]}... but broker "
            f"enforces {envelope.hash()[:12]}... (policy epoch={envelope.epoch})"
        )
    if not envelope.required_caps.issubset(attestation.caps):
        raise AttestationEnvelopeDrift(
            f"attestation caps {sorted(attestation.caps)} do not cover "
            f"required {sorted(envelope.required_caps)}"
        )
