# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-hierarchical-context-budget-starvation-when-a-planner-s-compressed-handoff-silently-strips-the-critic-s-verification-pre.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-hierarchical-context-budget-starvation-when-a-planner-s-compressed-handoff-silently-strips-the-critic-s-verification-pre.warrant.json
# Markdown SHA-256:   bad75bc427a141213b02ae7b98110894a7071ee6a2bd42cc4d492acc0a39a34d
# Code AST SHA-256:   cf5ac985feae419754357ce5aae663186ec1af0267da70f741430fbf7276350e
# Verified Classes:   ProvenanceStarvationError, DerivedContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ProvenanceStarvationError(RuntimeError):
    """Raised when a role's derived context is missing its falsification set."""
    pass


@dataclass
class DerivedContext:
    role: str
    summarized_payload: str
    # Falsification ledger: verbatim constraints, never compressed.
    falsification_ledger: list[str] = field(default_factory=list)
    # Span hashes linking back to the source turn.
    source_anchors: list[str] = field(default_factory=list)


def build_handoff(
    role: str,
    summarized_payload: str,
    ledger: list[str],
    source_turn: str,
    min_anchors: int = 1,
) -> DerivedContext:
    """Construct a role's derived context, enforcing the provenance invariant."""
    # The ledger must survive compression untouched.
    if role == "critic" and not ledger:
        raise ProvenanceStarvationError(
            "critic handoff has empty falsification ledger; "
            "cannot verify negative constraints"
        )

    anchor = "sha256:" + hashlib.sha256(source_turn.encode()).hexdigest()[:16]
    anchors = [anchor] if source_turn else []

    if role == "critic" and len(anchors) < min_anchors:
        raise ProvenanceStarvationError(
            f"critic context has {len(anchors)} source anchors, "
            f"requires >= {min_anchors}; verification would be self-referential"
        )

    return DerivedContext(
        role=role,
        summarized_payload=summarized_payload,
        falsification_ledger=list(ledger),
        source_anchors=anchors,
    )


def provenance_coverage(ctx: DerivedContext) -> float:
    """Fraction of context that traces to source. 0.0 means narrating, not verifying."""
    total = len(ctx.summarized_payload.split()) + len(ctx.falsification_ledger)
    if total == 0:
        return 0.0
    anchored = len(ctx.falsification_ledger)
    return anchored / total


def gate_critic(ctx: DerivedContext, min_coverage: float = 0.05) -> None:
    if ctx.role != "critic":
        return
    cov = provenance_coverage(ctx)
    if cov < min_coverage:
        raise ProvenanceStarvationError(
            f"critic provenance coverage {cov:.3f} < {min_coverage}; "
            "approval would be coherence-only, not correctness"
        )
