# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-self-rewritten-working-context-as-untrusted-derived-state-rather-than-authoritative-memory.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-self-rewritten-working-context-as-untrusted-derived-state-rather-than-authoritative-memory.warrant.json
# Markdown SHA-256:   57a99423e1e9c307cd78dc322c2e85fead34ecec28052aca270f4688dbb6bbb0
# Code AST SHA-256:   3c35f41600de55c6c0f060de8ea9e7496987a32308815976c740b004efb57d12
# Verified Classes:   EpistemicStatus, ContextLaunderingError, Claim, WorkingContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class EpistemicStatus(Enum):
    OBSERVED = "observed"   # came from a tool result / environment read
    INFERRED = "inferred"   # model's own conclusion, untested
    ASSUMED = "assumed"     # placeholder, neither observed nor tested


class ContextLaunderingError(RuntimeError):
    """Raised when a self-rewrite upgrades a claim's epistemic status or
    drops its provenance, making derived state authoritative-by-accident."""
    pass


@dataclass
class Claim:
    text: str
    status: EpistemicStatus
    provenance_ref: Optional[str]  # pointer into immutable log; None if self-authored


@dataclass
class WorkingContext:
    claims: list[Claim] = field(default_factory=list)
    provenance_retained: bool = True


def consolidate(
    pre: list[Claim],
    proposed: list[Claim],
    provenance_retained: bool,
) -> WorkingContext:
    """Apply a self-rewrite, enforcing the no-status-upgrade invariant.

    The rewrite may drop claims and merge text, but for every surviving claim
    the epistemic status must not be stronger than the strongest pre-rewrite
    claim it derives from, and OBSERVED claims must keep a provenance ref.
    """
    rank = {EpistemicStatus.ASSUMED: 0,
            EpistemicStatus.INFERRED: 1,
            EpistemicStatus.OBSERVED: 2}

    # Build the strongest status available for each surviving claim by
    # matching on text overlap is out of scope; here we require the rewrite
    # to be conservative: any claim asserted stronger than the max status
    # present pre-rewrite is a laundering event.
    max_pre = max((rank[c.status] for c in pre), default=0)

    for c in proposed:
        if rank[c.status] > max_pre:
            raise ContextLaunderingError(
                f"rewrite upgraded claim to {c.status.value} with no "
                f"pre-rewrite basis: {c.text!r}"
            )
        if c.status is EpistemicStatus.OBSERVED and c.provenance_ref is None:
            raise ContextLaunderingError(
                f"OBSERVED claim lost provenance ref during rewrite: {c.text!r}"
            )
        if not provenance_retained and c.status is EpistemicStatus.OBSERVED:
            # in-place truncation: cannot re-verify, so demote to INFERRED
            c.status = EpistemicStatus.INFERRED
            c.provenance_ref = None

    return WorkingContext(claims=proposed, provenance_retained=provenance_retained)


def use_claim_for_irreversible_action(ctx: WorkingContext, claim: Claim) -> None:
    """A load-bearing claim used for an irreversible action must be OBSERVED
    with live provenance, or the action is blocked."""
    if claim.status is not EpistemicStatus.OBSERVED:
        raise ContextLaunderingError(
            f"refusing irreversible action on {claim.status.value} claim: "
            f"{claim.text!r}; re-observe from provenance first"
        )
    if claim.provenance_ref is None or not ctx.provenance_retained:
        raise ContextLaunderingError(
            f"OBSERVED claim {claim.text!r} has no re-readable provenance; "
            f"treat as untrusted derived state and re-query"
        )
