# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-lossy-auto-compaction-has-silently-broken-recall-guarantees.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-lossy-auto-compaction-has-silently-broken-recall-guarantees.warrant.json
# Markdown SHA-256:   6828f1b9b08b8a56caf31598e75c68c84b5930467584c2624d9312f44f5f063d
# Code AST SHA-256:   57e0fa79e12271fa343ee9f5554a1e8ece1d6499c4101c5a9b3fc6731ac97f27
# Verified Classes:   CompactionRecallBreach
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class CompactionRecallBreach(RuntimeError):
    """Raised when a compaction node cannot support the recall guarantee
    the agent is about to rely on."""
    pass


SATURATION_THRESHOLD = 0.95


def verify_compaction_node(node: dict, probe_fact_class: str) -> None:
    """
    node schema:
      {
        "summary_tokens": int,
        "budget": int,
        "fact_anchors": {fact_id: source_turn},   # may be empty
        "recompacted": bool,
        "probe_results": {fact_class: "exact" | "paraphrase_only" | "miss"},
      }
    """
    if node.get("recompacted"):
        raise CompactionRecallBreach(
            "node is a summary-of-summary; anchors cannot be trusted, "
            "re-hydrate from original spans or discard"
        )

    utilization = node["summary_tokens"] / node["budget"]
    if utilization >= SATURATION_THRESHOLD:
        raise CompactionRecallBreach(
            f"compaction SATURATED at {utilization:.3f} of budget; "
            f"loss set unbounded, no fact from this node may gate an "
            f"irreversible action"
        )

    if not node.get("fact_anchors"):
        raise CompactionRecallBreach(
            "summary carries zero fact_anchors; recall path is "
            "unaddressable and indistinguishable from fabrication"
        )

    probe = node["probe_results"].get(probe_fact_class)
    if probe != "exact":
        raise CompactionRecallBreach(
            f"canary probe for {probe_fact_class!r} returned {probe!r}; "
            f"paraphrase-only or miss cannot support consequential recall"
        )


def gate_action_on_recall(node: dict, fact_class: str, action_is_irreversible: bool) -> bool:
    try:
        verify_compaction_node(node, fact_class)
    except CompactionRecallBreach as breach:
        if action_is_irreversible:
            raise
        # reversible actions may proceed but must be flagged unverified
        return False
    return True
