# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-treat-its-own-context-edits-as-untrusted-mutations-provenance-collapse-in-model-driven-pruning.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-treat-its-own-context-edits-as-untrusted-mutations-provenance-collapse-in-model-driven-pruning.warrant.json
# Markdown SHA-256:   c46623381f89fb25560a1bcaaa028ed59a5fdf329eacc1bb4aaa1acdf901702b
# Code AST SHA-256:   50384894a959cfbe2e1086bdb32ceb759f9a4ffb2523a9e15e3d76198a1bcfc9
# Verified Classes:   Provenance, ProvenanceCollapseError, Block, Context
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Optional

class Provenance(Enum):
    OBSERVED = "observed"   # verbatim tool/environment output
    DERIVED = "derived"     # model-authored summary of a prior block

class ProvenanceCollapseError(RuntimeError):
    """Raised when an edit would launder DERIVED content into OBSERVED status,
    or when a downstream step consumes a DERIVED block as fact without re-verification."""
    pass

@dataclass
class Block:
    block_id: str
    text: str
    provenance: Provenance
    source_ids: list[str] = field(default_factory=list)  # back-pointers to originals
    derivation_depth: int = 0  # 0 = observed, 1 = summary of observed, 2 = summary of summary

@dataclass
class Context:
    blocks: dict[str, Block] = field(default_factory=dict)

    def apply_self_edit(self, target_ids: list[str], summary_text: str,
                        new_id: str) -> Block:
        targets = [self.blocks[t] for t in target_ids]
        if not targets:
            raise ProvenanceCollapseError("edit targets empty; refusing no-op edit")

        # Depth of the new block is one more than the deepest thing it summarizes.
        depth = 1 + max(b.derivation_depth for b in targets)

        # Collect back-pointers: if any target is DERIVED, we must carry its
        # original source_ids forward, or we lose the trail to OBSERVED.
        sources: list[str] = []
        contains_derived = False
        for b in targets:
            if b.provenance is Provenance.DERIVED:
                contains_derived = True
                if not b.source_ids:
                    raise ProvenanceCollapseError(
                        f"target {b.block_id} is DERIVED but has no source back-pointers; "
                        "edit would be untraceable")
                sources.extend(b.source_ids)
            else:
                sources.append(b.block_id)

        # The new block is DERIVED by construction (model authored it).
        new_block = Block(
            block_id=new_id,
            text=summary_text,
            provenance=Provenance.DERIVED,
            source_ids=sorted(set(sources)),
            derivation_depth=depth,
        )

        # HARD INVARIANT: never allow depth > 2 without an explicit re-observation.
        # A summary of a summary of an observation is the drift threshold.
        if depth > 2:
            raise ProvenanceCollapseError(
                f"edit {new_id} would reach derivation depth {depth}; "
                "summarizing a summary of a summary is forbidden. "
                "Re-fetch the original OBSERVED block instead.")

        for t in target_ids:
            self.blocks.pop(t)
        self.blocks[new_id] = new_block
        return new_block

    def read_as_fact(self, block_id: str) -> str:
        b = self.blocks[block_id]
        if b.provenance is Provenance.DERIVED and b.derivation_depth >= 2:
            raise ProvenanceCollapseError(
                f"block {block_id} is DERIVED at depth {b.derivation_depth}; "
                "cannot be consumed as fact without re-verifying against "
                f"originals {b.source_ids}")
        return b.text


# --- trace of the observed failure ---
ctx = Context()
ctx.blocks["t2"] = Block("t2", "2019 policy: cap = 4.2 Mt ...", Provenance.OBSERVED)
ctx.blocks["t3"] = Block("t3", "other tool output ...", Provenance.OBSERVED)

# step 18: summarize t2..t11 -> s18 (depth 1, legal)
s18 = ctx.apply_self_edit(["t2", "t3"], "summary: 2019 policy capped at ~4.2 Mt", "s18")
assert s18.derivation_depth == 1

# step 26: model tries to summarize its own summary -> depth 2
s26 = ctx.apply_self_edit(["s18"], "summary: policy capped at 4.2 Mt", "s26")
assert s26.derivation_depth == 2

# step 31: downstream synthesis tries to cite s26 as fact -> BLOCKED
try:
    ctx.read_as_fact("s26")
except ProvenanceCollapseError as e:
    print("caught:", e)
    # correct recovery: re-fetch original, do not trust the summary chain

# step 40: model attempts a third-layer summary -> BLOCKED at edit time
try:
    ctx.apply_self_edit(["s26"], "summary of summary of summary", "s40")
except ProvenanceCollapseError as e:
    print("caught:", e)
