# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-drift-introduced-by-hierarchical-context-compaction-before-it-corrupts-downstream-tool-calls.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-drift-introduced-by-hierarchical-context-compaction-before-it-corrupts-downstream-tool-calls.warrant.json
# Markdown SHA-256:   e09f2bb995640a5a667947b0251a05dc9ec1fb30beb7ed1fcd568a4b7599baed
# Code AST SHA-256:   dda8ef69a4b134e79f5b269c6c9d90dfabbdcd7f9d8209add280a33347e5bbdd
# Verified Classes:   CompactionDriftError, Assertion, RootSummary
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional

CONCLUSION_TOKENS = {"healthy", "verified", "complete", "safe", "ready", "done"}


class CompactionDriftError(RuntimeError):
    """Raised when a gate-bearing summary assertion lacks provenance."""
    pass


@dataclass
class Assertion:
    text: str
    provenance: Optional[str]          # tool-call ID + field path, or None
    inferred: bool = False
    gate_bearing: bool = False


@dataclass
class RootSummary:
    narrative: list[str] = field(default_factory=list)
    gates: list[Assertion] = field(default_factory=list)


def audit_compaction(summary: RootSummary, raw_store_has) -> RootSummary:
    """
    Enforce provenance-completeness on the gate slice before re-injection.
    raw_store_has(handle) -> bool: whether the raw span is still resident.
    """
    for a in summary.gates:
        if not a.gate_bearing:
            continue
        low = a.text.lower()
        asserts_conclusion = any(tok in low for tok in CONCLUSION_TOKENS)
        if not asserts_conclusion:
            continue
        if a.provenance is None:
            # abstractive upgrade with no handle: cannot verify, must not gate
            if not a.inferred:
                raise CompactionDriftError(
                    f"gate assertion {a.text!r} asserts a conclusion "
                    f"with no provenance handle; refusing to re-inject"
                )
        elif not raw_store_has(a.provenance):
            # handle points at evicted raw span: demote to INFERRED
            a.inferred = True
            a.gate_bearing = False
    return summary


def gate_action(summary: RootSummary, precondition_text: str) -> bool:
    for a in summary.gates:
        if precondition_text.lower() in a.text.lower():
            if a.inferred or a.provenance is None:
                raise CompactionDriftError(
                    f"action gated on unverified assertion {a.text!r}; "
                    f"issue a fresh tool call before proceeding"
                )
            return True
    raise CompactionDriftError(
        f"no gate-bearing assertion matches precondition {precondition_text!r}"
    )
