# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-and-prunes-the-evidence-it-was-about-to-verify.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-and-prunes-the-evidence-it-was-about-to-verify.warrant.json
# Markdown SHA-256:   41d1312fb91acd39e46c703c08c649c6b978d4a2d846d3eeb305195e90405a19
# Code AST SHA-256:   16afe64f4de1a4ccdc21fcb8a9f27b03c59d5d640fe9a1e4ca3f990e21ae8339
# Verified Classes:   SelfCertifiedAmnesiaError, DigestField, Digest
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class SelfCertifiedAmnesiaError(RuntimeError):
    """Raised when a verification step attempts to certify a value whose only
    in-context representation is a model-authored rewrite with no provenance."""
    pass


@dataclass
class DigestField:
    name: str
    value: str
    # Provenance: tool-call index + content hash of the raw output it came from.
    # None means the field was model-authored with no re-derivable source.
    source_call_index: Optional[int] = None
    source_hash: Optional[str] = None
    demoted: bool = False  # True => unverified-paraphrase


@dataclass
class Digest:
    fields: dict = field(default_factory=dict)

    def add(self, f: DigestField) -> None:
        if f.source_call_index is None or f.source_hash is None:
            f.demoted = True
        self.fields[f.name] = f


def re_fetch(call_index: int) -> str:
    """Stand-in for idempotent tool replay. Returns raw output for a call."""
    raise NotImplementedError("wire to trace log")


def hash_raw(raw: str) -> str:
    return hashlib.sha256(raw.encode()).hexdigest()


def verify_field(digest: Digest, name: str, expected: str) -> bool:
    f = digest.fields.get(name)
    if f is None:
        raise SelfCertifiedAmnesiaError(f"field {name!r} absent from digest")

    # Invariant: a demoted field may never be certified.
    if f.demoted:
        raise SelfCertifiedAmnesiaError(
            f"field {name!r} is an unverified-paraphrase (no provenance); "
            f"cannot certify value {f.value!r} against expected {expected!r}"
        )

    # Resolve to the source artifact, not the rewrite.
    try:
        raw = re_fetch(f.source_call_index)
    except NotImplementedError:
        raise SelfCertifiedAmnesiaError(
            f"field {name!r} cites call {f.source_call_index} but replay is "
            f"unavailable; value {f.value!r} cannot be certified"
        )

    if hash_raw(raw) != f.source_hash:
        raise SelfCertifiedAmnesiaError(
            f"provenance hash mismatch for {name!r}: rewrite diverged from source"
        )

    # Compare against the source-derived value, not the digest's paraphrase.
    return expected in raw


def reconcile(digest: Digest, claims: dict) -> dict:
    results = {}
    for name, expected in claims.items():
        results[name] = verify_field(digest, name, expected)
    return results


# --- Failure trace reproduction ---
d = Digest()
# Summarizer emitted USD/paid with no provenance pointer:
d.add(DigestField(name="currency", value="USD"))
d.add(DigestField(name="status", value="paid"))

# Verifier tries to certify against the rewrite -> must refuse, not pass.
try:
    reconcile(d, {"currency": "EUR", "status": "pending"})
except SelfCertifiedAmnesiaError as e:
    # Correct behavior: the agent surfaces uncertainty and re-fetches.
    print(f"BLOCKED: {e}")
