# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-compaction-fidelity-loss-in-an-agent-s-episodic-to-semantic-distillation-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-compaction-fidelity-loss-in-an-agent-s-episodic-to-semantic-distillation-boundary.warrant.json
# Markdown SHA-256:   727fb7d68c8f97bb06c399f3761288d7d290b9af8aa481e3d73184d9cfc4853f
# Code AST SHA-256:   df6873481a3c9f4a6bed87b88e5f93d68c28ca3a9175a53b08bb0f124a2cdb50
# Verified Classes:   CompactionFidelityError, EpisodicSpan, DistilledFact
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass, field
from typing import Optional


class CompactionFidelityError(RuntimeError):
    """Raised when a distilled fact silently substitutes for its episodic span."""


@dataclass
class EpisodicSpan:
    turn_indices: list[int]
    mutations: dict[str, int]          # key -> number of writes in span
    distinct_bindings: set[str]        # entities referenced under a predicate
    negation_tokens: set[str]          # e.g. {"not", "never", "except"}
    error_scope: set[str]              # e.g. {"5xx", "timeout"}


@dataclass
class DistilledFact:
    text: str
    provenance: list[int]
    keys_referenced: set[str]
    bindings_referenced: set[str]
    has_supersession_marker: bool
    carries_negation: bool
    carries_scope: bool


def audit_compaction(span: EpisodicSpan, fact: DistilledFact,
                     retained_trace: Optional[dict[int, str]] = None) -> None:
    # 1. Provenance must actually resolve against a retained trace.
    if retained_trace is not None:
        for idx in fact.provenance:
            if idx not in retained_trace:
                raise CompactionFidelityError(
                    f"provenance pointer {idx} does not resolve in retained trace"
                )

    # 2. Repeated mutation without supersession marker = silent last-writer collapse.
    for key, count in span.mutations.items():
        if count > 1 and key in fact.keys_referenced and not fact.has_supersession_marker:
            raise CompactionFidelityError(
                f"key '{key}' mutated {count}x in span but distilled fact has no "
                f"supersession marker; history erased"
            )

    # 3. Entity-binding cardinality collapse = substitution of a sibling binding.
    if len(span.distinct_bindings) > len(fact.bindings_referenced):
        missing = span.distinct_bindings - fact.bindings_referenced
        raise CompactionFidelityError(
            f"binding cardinality collapsed: span={sorted(span.distinct_bindings)} "
            f"fact={sorted(fact.bindings_referenced)} missing={sorted(missing)}"
        )

    # 4. Negation / scope qualifier dropped = constraint silently removed.
    if span.negation_tokens and not fact.carries_negation:
        raise CompactionFidelityError(
            f"span carried negation {span.negation_tokens} but fact carries none; "
            f"constraint removed"
        )
    if span.error_scope and not fact.carries_scope:
        raise CompactionFidelityError(
            f"span scoped to {span.error_scope} but fact carries no scope qualifier"
        )


# Failing example: authz mutation merged into auth, negation dropped.
span = EpisodicSpan(
    turn_indices=[7, 19, 28, 31],
    mutations={"auth": 2, "authz": 1},
    distinct_bindings={"auth", "authz"},
    negation_tokens={"not"},
    error_scope={"5xx"},
)
fact = DistilledFact(
    text="retry budget for auth service is 5",
    provenance=[7, 19, 28],
    keys_referenced={"auth"},
    bindings_referenced={"auth"},
    has_supersession_marker=False,
    carries_negation=False,
    carries_scope=False,
)

try:
    audit_compaction(span, fact)
except CompactionFidelityError as e:
    print(f"REJECTED: {e}")
