# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-when-lossy-context-compaction-has-silently-invalidated-an-agent-s-reversible-expansion-log.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-when-lossy-context-compaction-has-silently-invalidated-an-agent-s-reversible-expansion-log.warrant.json
# Markdown SHA-256:   3cb0987f28085c9f49e48c92adbef7dceddf45ec8a1ccaa3d46dc44cba7771a9
# Code AST SHA-256:   e73e7d185b7ae097676332d06b519fc74c8db09bb47d8c6cc1b1244ba885bfce
# Verified Classes:   CompactionIntegrityError, ExpansionSlot, ColdStore
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class CompactionIntegrityError(RuntimeError):
    """Raised when an expansion log slot no longer satisfies its recorded fidelity contract."""
    pass


@dataclass
class ExpansionSlot:
    slot_id: str
    span_ids: list[str]
    fidelity: str                      # "verbatim_recoverable" | "lossy" | "summary_only"
    original_sha256: dict[str, str] = field(default_factory=dict)  # span_id -> hex digest


@dataclass
class ColdStore:
    spans: dict[str, bytes] = field(default_factory=dict)

    def fetch(self, span_id: str) -> Optional[bytes]:
        return self.spans.get(span_id)


def expand_authoritative(slot: ExpansionSlot, store: ColdStore) -> dict[str, bytes]:
    """
    Expand a slot for authoritative use (exact identifiers, error classes, paths).
    Refuses to return content unless fidelity is verbatim_recoverable AND every
    returned span matches the checksum recorded at compaction time.
    """
    if slot.fidelity != "verbatim_recoverable":
        raise CompactionIntegrityError(
            f"slot {slot.slot_id} has fidelity={slot.fidelity!r}; "
            f"authoritative expansion forbidden"
        )

    recovered: dict[str, bytes] = {}
    for span_id in slot.span_ids:
        expected = slot.original_sha256.get(span_id)
        if expected is None:
            raise CompactionIntegrityError(
                f"slot {slot.slot_id} span {span_id} has no recorded checksum; "
                f"reversibility cannot be verified"
            )
        content = store.fetch(span_id)
        if content is None:
            raise CompactionIntegrityError(
                f"slot {slot.slot_id} span {span_id} evicted from cold store; "
                f"expansion log is a lying index"
            )
        actual = hashlib.sha256(content).hexdigest()
        if actual != expected:
            # This is the silent-rewrite case: bytes exist, but they are not
            # the original. A naive expander would return them with HTTP 200.
            raise CompactionIntegrityError(
                f"slot {slot.slot_id} span {span_id} checksum mismatch: "
                f"expected {expected[:12]}..., got {actual[:12]}...; "
                f"a downstream transform rewrote the span without downgrading fidelity"
            )
        recovered[span_id] = content

    return recovered
