# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-hierarchical-summarization-from-silently-dropping-the-tool-call-witness-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-hierarchical-summarization-from-silently-dropping-the-tool-call-witness-chain.warrant.json
# Markdown SHA-256:   8adcb557000c286dd67b880b78a34a7923f95f56de09e4a3a2dadc148d1d2ffc
# Code AST SHA-256:   c453b627fb002b362c1ba1a43a30161a3ff6071a6b5fab03ba80f70db52bcaa0
# Verified Classes:   WitnessChainBroken, Witness, Summary, WitnessStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class WitnessChainBroken(RuntimeError):
    """Raised when a compaction fold drops a tool-witness pointer that a
    retained summary depends on. This is a correctness fault, not a budget
    warning: the agent can no longer distinguish verified facts from
    summarized recollection."""


@dataclass
class Witness:
    call_id: str
    args_digest: str
    result_digest: str
    retry_count: int = 0


@dataclass
class Summary:
    text: str
    pointers: set[str] = field(default_factory=set)  # call_ids referenced as fact


class WitnessStore:
    def __init__(self) -> None:
        self._w: dict[str, Witness] = {}

    def record(self, call_id: str, args: str, result: str, retry_count: int = 0) -> None:
        self._w[call_id] = Witness(
            call_id,
            hashlib.sha256(args.encode()).hexdigest(),
            hashlib.sha256(result.encode()).hexdigest(),
            retry_count,
        )

    def resolve(self, call_id: str) -> Witness | None:
        return self._w.get(call_id)


def fold(children: list[Summary], parent: Summary, store: WitnessStore) -> Summary:
    """Fold child summaries into a parent. Enforces the witness-hoisting
    invariant: every pointer a child asserts as fact must survive into the
    parent (inline or via sidecar) AND resolve to a live witness."""
    required: set[str] = set()
    for c in children:
        required |= c.pointers

    for cid in required:
        if store.resolve(cid) is None:
            raise WitnessChainBroken(
                f"pointer {cid} referenced by a child summary has no live "
                f"witness; fact must be demoted to 'unverified recollection'"
            )
        if cid not in parent.pointers:
            raise WitnessChainBroken(
                f"fold elided witness pointer {cid}; parent summary would "
                f"assert an unwitnessed fact (silent provenance loss)"
            )
    return parent


def check_contradiction(new: Witness, prior_id: str, store: WitnessStore) -> bool:
    """Diff a new tool result against a prior *witnessed* value. Refuses to
    compare against a summary, because paraphrase may have normalized the
    operand and hidden the discrepancy."""
    prior = store.resolve(prior_id)
    if prior is None:
        raise WitnessChainBroken(
            f"cannot diff against {prior_id}: witness evicted, comparison "
            f"operand is only a summary and is not trustworthy"
        )
    return prior.result_digest != new.result_digest


# --- reproduction of the observed failure ---
store = WitnessStore()
store.record("call_8841", args="ledger?period=Q2", result='{"bal":41220}', retry_count=1)

leaf = Summary(text="ledger balance retrieved: $41,220", pointers={"call_8841"})
# A naive cluster summarizer paraphrases and drops the pointer:
cluster = Summary(text="verified account reconciliation for period Q2", pointers=set())

try:
    fold([leaf], cluster, store)  # raises: pointer elided
except WitnessChainBroken as e:
    print("BLOCKED:", e)

# And the later contradiction check cannot proceed without a witness:
try:
    check_contradiction(
        Witness("call_9102", "x", hashlib.sha256(b'{"bal":41880}').hexdigest()),
        prior_id="call_8841_evicted",
        store=store,
    )
except WitnessChainBroken as e:
    print("BLOCKED:", e)
