# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-auto-compaction-has-silently-promoted-a-hallucinated-summary-into-its-own-episodic-ground-truth.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-auto-compaction-has-silently-promoted-a-hallucinated-summary-into-its-own-episodic-ground-truth.warrant.json
# Markdown SHA-256:   3f0d7c6613c01b0bd9e8c8eb84eacdb5e6f3fb300679476742df499a7765c457
# Code AST SHA-256:   fed972118da7fdd13802d2e9b0b55d0d117435983699d11b11342cfe6f4c7cd3
# Verified Classes:   CompactionProvenanceError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CompactionProvenanceError(RuntimeError):
    """Raised when an irreversible action is justified only by derived (summarized) content."""
    pass


# A claim is either RAW (came from a tool result or user turn) or DERIVED
# (written by the model during a compaction step). Only RAW claims may gate
# irreversible actions.
RAW = "raw"
DERIVED = "derived"


def assert_commit_safe(justification: list[dict], action_is_irreversible: bool) -> None:
    """
    justification: list of {"claim": str, "provenance": RAW|DERIVED, "raw_ref": str|None}
    Raises if an irreversible action rests on any DERIVED claim without a raw_ref.
    """
    if not action_is_irreversible:
        return

    for j in justification:
        if j["provenance"] == DERIVED and not j.get("raw_ref"):
            raise CompactionProvenanceError(
                "Irreversible action justified by a compaction-derived claim "
                f"with no surviving raw span: {j['claim']!r}. "
                "Re-verify via a tool call before committing."
            )


def gate_summary_claims(summary_claims: list[dict]) -> list[dict]:
    """
    Given claims extracted from a compaction summary, return the subset that
    would allow skipping a tool call if true — these must be re-verified.
    """
    gating = [c for c in summary_claims if c.get("would_skip_tool_call")]
    for c in gating:
        c["provenance"] = DERIVED  # explicit: it came from a summary
    return gating


# Example: the agent is about to deploy, justified by a summary that claimed
# the migration test passed (it did not — it timed out).
justification = [
    {"claim": "migration test passed", "provenance": DERIVED, "raw_ref": None},
    {"claim": "target is prod-us-east", "provenance": RAW, "raw_ref": "tool_call_88"},
]

try:
    assert_commit_safe(justification, action_is_irreversible=True)
except CompactionProvenanceError as e:
    # Correct behavior: block the deploy and force a re-run of the test.
    print(f"BLOCKED: {e}")
    raise
