# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-lossy-context-compaction-has-orphaned-a-provenance-pointer-before-rehydration-dereferences-it.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-lossy-context-compaction-has-orphaned-a-provenance-pointer-before-rehydration-dereferences-it.warrant.json
# Markdown SHA-256:   f26da66f491ed85f1088cf8e3c7861b34b5e1eae118fc781dd79e740f7458423
# Code AST SHA-256:   11d1facbde381bb976c647ba4ec237cb7fffdb2ffecc3f3789fa69d9d02ffb2c
# Verified Classes:   ProvenanceDriftError, ProvenancePointer
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ProvenanceDriftError(RuntimeError):
    """Raised when a rehydration pointer's version token no longer matches its source."""
    pass


@dataclass(frozen=True)
class ProvenancePointer:
    artifact_id: str
    span: tuple[int, int]
    version_token: str  # captured at mint (compaction) time


def _hash_span(source: str, span: tuple[int, int]) -> str:
    start, end = span
    return "sha256:" + hashlib.sha256(source[start:end].encode()).hexdigest()


def rehydrate(pointer: ProvenancePointer, current_source: str, *, mode: str) -> str:
    """
    Dereference a provenance pointer against current source state.

    mode: "audit"  -> refuse on drift (claim about the past)
          "act"    -> return current bytes, tagged stale
    """
    start, end = pointer.span
    if end > len(current_source):
        raise ProvenanceDriftError(
            f"span {pointer.span} exceeds source length {len(current_source)} "
            f"for {pointer.artifact_id}; source shrank since mint"
        )

    observed = _hash_span(current_source, pointer.span)
    drifted = observed != pointer.version_token

    if drifted and mode == "audit":
        raise ProvenanceDriftError(
            f"stale pointer for {pointer.artifact_id}{pointer.span}: "
            f"minted {pointer.version_token}, observed {observed}; "
            f"refusing to feed drifted bytes to an audit claim"
        )

    body = current_source[start:end]
    return f"[stale=true minted={pointer.version_token} observed={observed}]\n{body}" if drifted else body


# --- trace of the observed failure ---
original = "def tokenize(s):\n    return s.split()\n" + "x" * 40
ptr = ProvenancePointer("src/parser.py", (0, 26), _hash_span(original, (0, 26)))

# agent edits inside the span between compaction and rehydration
mutated = "def tokenize(s):\n    return list(s)\n" + "x" * 40

# audit-mode dereference must fail loudly, not return the mutated bytes
try:
    rehydrate(ptr, mutated, mode="audit")
    raise AssertionError("expected ProvenanceDriftError")
except ProvenanceDriftError as e:
    print("drift detected:", e)

# act-mode is permitted but must be visibly tagged
print(rehydrate(ptr, mutated, mode="act"))
