# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-when-automatic-context-compaction-has-severed-a-causal-chain-across-a-summarization-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-when-automatic-context-compaction-has-severed-a-causal-chain-across-a-summarization-boundary.warrant.json
# Markdown SHA-256:   6494895ef8524df8c637a8fca6740df2c2bd347043b9df9682e50a2c15767e8c
# Code AST SHA-256:   8eced6ab11215538d605e4cc30b09e18002293f71c8a2a16d3e285184c5d4cc6
# Verified Classes:   CausalChainSevered, Decision, CompactionLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class CausalChainSevered(RuntimeError):
    """Raised when a post-compaction action reverses a pre-boundary decision
    whose rationale did not survive summarization."""
    pass


@dataclass
class Decision:
    artifact: str
    treatment: str          # "edit" | "skip" | "retry" | "defer"
    reason: str
    survived_compaction: bool


@dataclass
class CompactionLedger:
    decisions: dict[str, Decision] = field(default_factory=dict)

    def record(self, d: Decision) -> None:
        self.decisions[d.artifact] = d

    def lookup(self, artifact: str) -> Optional[Decision]:
        return self.decisions.get(artifact)


def gate_post_compaction_action(
    ledger: CompactionLedger,
    artifact: str,
    intended_treatment: str,
    cited_artifacts: list[str],
) -> None:
    """Enforce the invariant: an action on an artifact whose prior treatment
    was decided pre-boundary may not proceed unless the decision survived
    compaction or an explicit override is recorded."""
    prior = ledger.lookup(artifact)
    if prior is None:
        return  # no prior decision; safe to proceed

    if prior.treatment == intended_treatment:
        return  # continuation, not divergence

    # Intended treatment differs from the recorded decision.
    if not prior.survived_compaction:
        raise CausalChainSevered(
            f"Artifact {artifact!r}: prior treatment {prior.treatment!r} "
            f"(reason: {prior.reason!r}) did not survive compaction, but "
            f"post-boundary action intends {intended_treatment!r}. "
            f"Cited artifacts {cited_artifacts!r} include the gated artifact. "
            f"Re-read the pre-boundary decision record before proceeding."
        )

    # Decision survived; reversal is permitted only with explicit override.
    raise CausalChainSevered(
        f"Artifact {artifact!r}: reversing survived decision "
        f"{prior.treatment!r} -> {intended_treatment!r} requires an "
        f"explicit override record; none present."
    )


# Example: reproduces the observed failure and blocks it.
ledger = CompactionLedger()
ledger.record(Decision(
    artifact="b.py",
    treatment="skip",
    reason="generated file; matches header pattern; must not be edited",
    survived_compaction=False,   # summarizer dropped the rationale
))

gate_post_compaction_action(
    ledger,
    artifact="b.py",
    intended_treatment="edit",
    cited_artifacts=["b.py", "a.py"],
)
