# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-auto-compaction-has-already-destroyed-a-load-bearing-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-its-own-auto-compaction-has-already-destroyed-a-load-bearing-invariant.warrant.json
# Markdown SHA-256:   21a751d047a6887b10c8619f8b0ccbe8ceb560473e9c4327fcb76b88e5b7b495
# Code AST SHA-256:   a2e3e30db414209dfce4b5a6fe2a89a3b569235a1bd877f717d042d421c0a5ea
# Verified Classes:   CompactionLossError, ConstraintLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CompactionLossError(RuntimeError):
    """Raised when an action relies on a constraint-shaped negative that cannot be
    traced to a non-compacted source after a lossy compaction event."""
    pass


class ConstraintLedger:
    """Pinned constraints survive compaction; summary is not authoritative for negatives."""

    def __init__(self):
        self.pinned = {}          # constraint_id -> raw span (never summarized)
        self.loss_manifest = set()  # spans dropped by the last compaction

    def record_compaction(self, dropped_spans):
        self.loss_manifest = set(dropped_spans)

    def pin(self, cid, span):
        self.pinned[cid] = span

    def verify_negative_claim(self, resource, claimed_unconstrained):
        """A negative claim ('no constraint on X') must be provable, not inferred
        from the summary's silence."""
        if not claimed_unconstrained:
            return True
        # Any pinned constraint naming the resource forbids the negative claim.
        for cid, span in self.pinned.items():
            if resource in span:
                raise CompactionLossError(
                    f"Negative claim on '{resource}' contradicts pinned constraint {cid}: "
                    f"summary silence is not evidence of absence."
                )
        # If the resource was touched by a dropped span, silence is untrustworthy.
        for span in self.loss_manifest:
            if resource in span:
                raise CompactionLossError(
                    f"'{resource}' appears in loss manifest; summary cannot certify "
                    f"it is unconstrained. Re-fetch raw span before acting."
                )
        return True


def guarded_write(ledger, resource, payload):
    # Agent believes resource is unconstrained post-compaction. Verify.
    ledger.verify_negative_claim(resource, claimed_unconstrained=True)
    return f"wrote {len(payload)} bytes to {resource}"


# Failure trace: constraint stated once at turn 12, dropped at turn 97.
ledger = ConstraintLedger()
ledger.pin("c-12", "Do not touch the legacy/ directory; it's frozen for audit.")
ledger.record_compaction(["turn 12 user constraint", "turn 40 scratch notes"])

try:
    guarded_write(ledger, "legacy/adapter.py", "refactor payload")
except CompactionLossError as e:
    print(f"BLOCKED: {e}")
    # -> BLOCKED: Negative claim on 'legacy/adapter.py' contradicts pinned constraint c-12
