# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-semantic-auto-compaction-before-summarizer-drift-silently-rewrites-its-own-task-state.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-semantic-auto-compaction-before-summarizer-drift-silently-rewrites-its-own-task-state.warrant.json
# Markdown SHA-256:   9b9f4ca37244d4183bae62aaf5d74acf532859a5852ffaf17ee1cb6f24eba3c8
# Code AST SHA-256:   7d085fd55b279c4dbd7e94a22304c0153545ee8cd4bff6015491a14114f061c4
# Verified Classes:   ProvenanceDepthExceeded
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class ProvenanceDepthExceeded(RuntimeError):
    """Raised when auto-compaction would summarize an already-derived block,
    collapsing provenance depth and enabling silent constraint drift."""
    pass


MAX_PROVENANCE_DEPTH = 1


def admit_for_compaction(segment: dict) -> None:
    """Gate a segment before it enters the summarizer.

    A segment is admissible only if its provenance chain terminates in raw
    source text (depth <= 1). Re-summarizing a summary (depth >= 2) is the
    exact mechanic that lets negations and numeric bounds decay undetected,
    because per-cycle similarity metrics stay high while fidelity against
    the original source collapses.
    """
    depth = segment.get("provenance_depth", 0)
    if depth > MAX_PROVENANCE_DEPTH:
        raise ProvenanceDepthExceeded(
            f"segment {segment.get('id')!r} has provenance depth {depth} "
            f"(>{MAX_PROVENANCE_DEPTH}); it is derived from a prior summary. "
            f"Refusing to re-summarize. Re-derive from the durable raw store "
            f"or freeze the constraint sidecar and compact only narrative residue."
        )
    # Admissible: summarize once from source, tag immutable, lift constraints
    # into a typed sidecar, and measure fidelity against the raw segment.
    segment["immutable"] = True


def compact_cycle(segments: list[dict]) -> list[dict]:
    """Run one compaction pass; any derived block halts the cycle."""
    admitted = []
    for seg in segments:
        admit_for_compaction(seg)  # raises ProvenanceDepthExceeded on drift risk
        admitted.append(seg)
    return admitted
