# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-context-budget-starvation-is-being-masked-by-compression-aware-routing-at-handoff-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-context-budget-starvation-is-being-masked-by-compression-aware-routing-at-handoff-boundaries.warrant.json
# Markdown SHA-256:   0b976cc936a1a49ee5e658464481745dd69aa2749644ed3df5a5d26cf0454006
# Code AST SHA-256:   25ddcc81e04a300b18f9dc7b02f02217bdd5d3468b1988a68e97a6d5de622ec0
# Verified Classes:   HandoffContinuityError, Handoff
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class HandoffContinuityError(RuntimeError):
    """Raised when a compressed handoff drops decision-relevant constraint state."""


@dataclass
class Handoff:
    source_agent: str
    target_agent: str
    payload: str
    constraints: list[str] = field(default_factory=list)  # negative/limit state
    compressed: bool = False
    manifest_digest: str | None = None


def emit_manifest(handoff: Handoff) -> str:
    """Digest of constraint state that must survive compression verbatim."""
    blob = "\n".join(sorted(handoff.constraints)).encode()
    return hashlib.sha256(blob).hexdigest()


def compress(handoff: Handoff, ratio: float) -> Handoff:
    """Saliency compression: keeps payload head, drops constraint block."""
    keep = max(1, int(len(handoff.payload) * ratio))
    return Handoff(
        source_agent=handoff.source_agent,
        target_agent=handoff.target_agent,
        payload=handoff.payload[:keep],
        constraints=[],  # saliency proxy discards constraints first
        compressed=True,
        manifest_digest=handoff.manifest_digest,
    )


def route(handoff: Handoff, budget_tokens: int) -> Handoff:
    """Compression-aware router: grants scope on compressed-size headroom."""
    if len(handoff.payload) <= budget_tokens:
        return handoff
    ratio = budget_tokens / len(handoff.payload)
    compressed = compress(handoff, ratio)
    if compressed.compressed and not compressed.constraints:
        # The compression layer reports success; the router must not trust it
        # blindly when the upstream handoff carried constraint state.
        if handoff.constraints:
            raise HandoffContinuityError(
                f"handoff {handoff.source_agent}->{handoff.target_agent} "
                f"compressed at ratio {ratio:.2f} dropped "
                f"{len(handoff.constraints)} constraint tokens; "
                f"manifest {handoff.manifest_digest[:8]} not preserved — "
                f"refusing to grant scope on lossy headroom"
            )
    return compressed


def verify_handoff(handoff: Handoff, echoed_manifest: str | None) -> None:
    """Downstream agent must echo the manifest; mismatch fails the handoff."""
    if handoff.manifest_digest is None:
        return
    if echoed_manifest != handoff.manifest_digest:
        raise HandoffContinuityError(
            f"manifest mismatch at {handoff.target_agent}: "
            f"expected {handoff.manifest_digest[:8]}, "
            f"got {(echoed_manifest or 'none')[:8]}"
        )
