# 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-tool-call-provenance-that-later-verification-depends-on.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rewrites-its-own-context-and-prunes-the-tool-call-provenance-that-later-verification-depends-on.warrant.json
# Markdown SHA-256:   8a3b793a61879301c683ab1e67f029b8bc76f5bcc0400662936dc687cf674195
# Code AST SHA-256:   89506815318d73b76103ca92b9fee748a39027e57f1a92127096df4d8d660220
# Verified Classes:   ProvenanceClosureError, EffectRecord, RewriteResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ProvenanceClosureError(RuntimeError):
    """Raised when a context rewrite drops an un-retired effect record."""
    pass


@dataclass
class EffectRecord:
    call_id: str
    args: dict
    result_token: str          # revision id / hash / handle — must survive verbatim
    retired: bool = False      # True only after a commit/verify step consumed it


@dataclass
class RewriteResult:
    narrative: str
    sealed_effects: dict = field(default_factory=dict)  # call_id -> EffectRecord


def rewrite_context(
    narrative_spans: list[str],
    effects: list[EffectRecord],
    summarize,                      # model-driven summarizer over narrative only
    policy_seed: Optional[int] = 0,
) -> RewriteResult:
    # 1. Seal every un-retired effect BEFORE the model sees anything.
    sealed = {e.call_id: e for e in effects if not e.retired}

    # 2. Model rewrites narrative only; sealed effects are never candidates.
    narrative = summarize(narrative_spans, seed=policy_seed)

    # 3. Reattach sealed references and assert closure.
    result = RewriteResult(narrative=narrative, sealed_effects=sealed)
    _assert_provenance_closure(result, effects)
    return result


def _assert_provenance_closure(result: RewriteResult, original: list[EffectRecord]) -> None:
    for e in original:
        if e.retired:
            continue
        if e.call_id not in result.sealed_effects:
            raise ProvenanceClosureError(
                f"un-retired effect {e.call_id} (token={e.result_token}) "
                f"missing after rewrite; resume/replay would be non-idempotent"
            )
        if result.sealed_effects[e.call_id].result_token != e.result_token:
            raise ProvenanceClosureError(
                f"effect {e.call_id} token mutated "
                f"{e.result_token!r} -> {result.sealed_effects[e.call_id].result_token!r}"
            )


def resume_from(result: RewriteResult, next_call_id: str, expected_token: str) -> None:
    # Idempotency check on resume depends entirely on the surviving token.
    rec = result.sealed_effects.get(next_call_id)
    if rec is None:
        raise ProvenanceClosureError(
            f"cannot resume {next_call_id}: provenance pruned; "
            f"expected token {expected_token!r} is unrecoverable"
        )
    if rec.result_token != expected_token:
        raise ProvenanceClosureError(
            f"resume precondition mismatch for {next_call_id}: "
            f"context holds {rec.result_token!r}, caller expects {expected_token!r}"
        )
