# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-bilateral-policy-negotiation-has-silently-diverged-from-selective-disclosure-the-residency-tainted-context-envelope.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-bilateral-policy-negotiation-has-silently-diverged-from-selective-disclosure-the-residency-tainted-context-envelope.warrant.json
# Markdown SHA-256:   f67e3306d8438af6bdbf698b84d416c4b7e5f35f6d34afa173070b4e998e906a
# Code AST SHA-256:   eb4a58c4f6bf7ee57559a3ce0068cedfd22473c04fc5b52f579f29e833ea1587
# Verified Classes:   ClassificationDivergenceError, UndeclaredReferenceError, NegotiationArtifact, ContextEnvelope
# Defensive Guards:   7 fail-closed invariants (zero external deps)

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


class ClassificationDivergenceError(RuntimeError):
    """Raised when disclosing and receiving engines disagree on envelope classification."""
    pass


class UndeclaredReferenceError(RuntimeError):
    """Raised when free-text reference extraction finds references not in the manifest."""
    pass


@dataclass
class NegotiationArtifact:
    field_manifest: list[str]
    derivation_rules_hash: str
    policy_version: str
    classification_authority: str  # "authoritative" | "advisory"
    rederivation_scope: str        # "none" | "field" | "full"
    declared_references: dict[str, list[str]] = field(default_factory=dict)


@dataclass
class ContextEnvelope:
    header: dict
    body: dict
    provenance: dict


def compute_classification_provenance_hash(
    manifest: list[str], rules_hash: str, policy_version: str
) -> str:
    payload = json.dumps(
        {"manifest": sorted(manifest), "rules": rules_hash, "policy": policy_version},
        sort_keys=True,
    ).encode()
    return hashlib.sha256(payload).hexdigest()


def admit_envelope(
    envelope: ContextEnvelope,
    artifact: NegotiationArtifact,
    receiver_rules_hash: str,
    receiver_policy_version: str,
    extract_references,  # callable: (text) -> list[str]
) -> None:
    if artifact.classification_authority not in ("authoritative", "advisory"):
        raise ClassificationDivergenceError(
            f"missing or invalid classification_authority: {artifact.classification_authority!r}"
        )
    if artifact.rederivation_scope not in ("none", "field", "full"):
        raise ClassificationDivergenceError(
            f"missing or invalid rederivation_scope: {artifact.rederivation_scope!r}"
        )

    sender_hash = envelope.header.get("classification_provenance_hash")
    expected_sender_hash = compute_classification_provenance_hash(
        artifact.field_manifest, artifact.derivation_rules_hash, artifact.policy_version
    )
    if sender_hash != expected_sender_hash:
        raise ClassificationDivergenceError(
            "envelope header hash does not match negotiation artifact; "
            "envelope may have been re-classified after negotiation"
        )

    receiver_hash = compute_classification_provenance_hash(
        artifact.field_manifest, receiver_rules_hash, receiver_policy_version
    )
    if receiver_hash != sender_hash:
        raise ClassificationDivergenceError(
            "derivation rules or policy version diverged between sender and receiver; "
            "renegotiation required before disclosure"
        )

    if artifact.rederivation_scope == "full":
        for fname, text in envelope.body.items():
            if not isinstance(text, str):
                continue
            extracted = set(extract_references(text))
            declared = set(artifact.declared_references.get(fname, []))
            undeclared = extracted - declared
            if undeclared:
                raise UndeclaredReferenceError(
                    f"field {fname!r} references undeclared fields {sorted(undeclared)}; "
                    "residency inheritance cannot be computed safely"
                )
    elif artifact.rederivation_scope == "field":
        # Partial re-derivation: field-level classification only.
        # This is the configuration in which divergence is exploitable.
        # We refuse to admit rather than silently produce a mixed envelope.
        raise ClassificationDivergenceError(
            "rederivation_scope='field' cannot bound free-text residency inheritance; "
            "upgrade to 'full' or pass envelope as opaque references"
        )


def federated_handoff(
    envelope: ContextEnvelope,
    artifact: NegotiationArtifact,
    receiver_rules_hash: str,
    receiver_policy_version: str,
    extract_references,
) -> None:
    try:
        admit_envelope(
            envelope, artifact, receiver_rules_hash, receiver_policy_version, extract_references
        )
    except (ClassificationDivergenceError, UndeclaredReferenceError) as exc:
        # Surface to negotiation layer; do not deliver partial envelope.
        raise ClassificationDivergenceError(
            f"handoff aborted, negotiation reopened: {exc}"
        ) from exc
    # Only reached when full re-derivation passed and hashes matched.
    deliver(envelope)
