# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-trust-its-own-compacted-summary-the-reconstruction-consistency-invariant-for-lossy-context-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-trust-its-own-compacted-summary-the-reconstruction-consistency-invariant-for-lossy-context-compaction.warrant.json
# Markdown SHA-256:   9fcf12275112663703ba67dcc955cac10a5c03fa728514d76583474a41843e1f
# Code AST SHA-256:   0d58efc1aa85e4a74670dd58ea2ae38f789c505d8c0b5216356d08a52b465e34
# Verified Classes:   ReconstructionConsistencyError, Proposition, Substrate
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field
from typing import Optional


class ReconstructionConsistencyError(RuntimeError):
    """Raised when a summary proposition cannot be resolved to a live,
    pre-compaction substrate anchor and is being used to justify an
    irreversible action."""


@dataclass
class Proposition:
    text: str
    provenance_class: str          # "observed" | "inferred" | "asserted"
    anchor: Optional[str]          # substrate record id / hash
    observation_ts: float
    compaction_ts: float


@dataclass
class Substrate:
    records: dict = field(default_factory=dict)   # id -> (content, ts)

    def put(self, content: str) -> str:
        rid = hashlib.sha256(content.encode()).hexdigest()[:16]
        self.records[rid] = (content, time.time())
        return rid

    def resolve(self, rid: str) -> Optional[tuple]:
        return self.records.get(rid)


def verify_anchor(prop: Proposition, substrate: Substrate, summary_ids: set) -> bool:
    """An anchor is live only if it resolves to a substrate record that
    predates the compaction AND is not itself a summary document."""
    if prop.anchor is None:
        return False
    if prop.anchor in summary_ids:
        return False  # self-referential: the closed loop
    rec = substrate.resolve(prop.anchor)
    if rec is None:
        return False
    _, rec_ts = rec
    return rec_ts <= prop.compaction_ts


def gate_irreversible_action(prop: Proposition, substrate: Substrate,
                             summary_ids: set, action: str) -> None:
    """Refuse irreversible actions backed only by asserted / self-anchored
    propositions. Forces re-observation instead of trusting the summary."""
    if prop.provenance_class == "observed" and verify_anchor(prop, substrate, summary_ids):
        return
    if prop.provenance_class == "inferred" and verify_anchor(prop, substrate, summary_ids):
        return
    raise ReconstructionConsistencyError(
        f"Action '{action}' depends on proposition {prop.text!r} "
        f"(class={prop.provenance_class}, anchor={prop.anchor}) which has no "
        f"live pre-compaction substrate anchor. Re-observe before proceeding."
    )


# --- failure trace reproduction ---
if __name__ == "__main__":
    sub = Substrate()
    # the rejected edit is the substrate fact; it aged out of the summary
    rejected_id = sub.put('{"status":"rejected","reason":"wrong overload","file":"migrate_0042.py"}')

    # the summary sentence, anchored to itself (the closed loop)
    summary_doc_id = "summary_c3_migrate"
    summary_ids = {summary_doc_id}
    prop = Proposition(
        text="migrate_0042.py already updated to new RetryPolicy signature",
        provenance_class="asserted",
        anchor=summary_doc_id,          # self-referential
        observation_ts=time.time(),
        compaction_ts=time.time(),
    )

    try:
        gate_irreversible_action(prop, sub, summary_ids, "write_test_fixtures")
    except ReconstructionConsistencyError as e:
        print("GATE FIRED:", e)
        # correct recovery: re-observe substrate directly
        rec = sub.resolve(rejected_id)
        print("re-observed substrate:", rec[0])
