# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-context-compaction-has-silently-discarded-a-task-critical-invariant-rather-than-merely-compressing-redundant-his.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-context-compaction-has-silently-discarded-a-task-critical-invariant-rather-than-merely-compressing-redundant-his.warrant.json
# Markdown SHA-256:   faa719ede2273569f26f8613fd9e1c5d0e551255a9a3853a8e860a09a300b5bc
# Code AST SHA-256:   926b4c50fc8d87e19d7c6399647dabb69f30a061f9f15e2544d6415902548844
# Verified Classes:   InvariantLossError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class InvariantLossError(RuntimeError):
    """Raised when downstream trace structure indicates a pinned invariant was dropped."""
    pass


# Facts that MUST survive compaction: referenced >1x and load-bearing.
PINNED_INVARIANTS = {
    "target_file": "src/ingest/parser.py",
    "schema_version": "v3",
    "forbidden_paths": ("migrations/",),
    "rejected_approach": "regex-based tokenizer (fails on unicode)",
}


def audit_post_compaction(trace, pinned=PINNED_INVARIANTS):
    """
    Inspect the tool-call trace *after* a compaction boundary.
    Detect structural signals of invariant loss without reading summary text.
    """
    seen_values = {}
    for call in trace:
        # Signal 1: re-derivation of an established constant.
        if call.op == "derive" and call.key in pinned:
            if call.key in seen_values and seen_values[call.key] != call.value:
                raise InvariantLossError(
                    f"Invariant '{call.key}' re-derived to {call.value!r} "
                    f"after compaction; pinned value was {pinned[call.key]!r}. "
                    f"Re-inject pinned block before continuing."
                )
            seen_values[call.key] = call.value

        # Signal 3: prohibition drift.
        if call.op == "write":
            for forbidden in pinned["forbidden_paths"]:
                if call.path.startswith(forbidden):
                    raise InvariantLossError(
                        f"Write to forbidden path '{call.path}' after compaction; "
                        f"prohibition was not preserved. Abort and re-inject constraints."
                    )

        # Signal 2: reversal of a settled decision.
        if call.op == "plan" and pinned["rejected_approach"] in call.text:
            raise InvariantLossError(
                "Rejected approach reappeared in plan after compaction; "
                "the rejection predicate was dropped by summarization."
            )

    return True
