# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-self-editing-context-window-as-a-lossy-non-idempotent-transaction-rather-than-a-cache-eviction.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-self-editing-context-window-as-a-lossy-non-idempotent-transaction-rather-than-a-cache-eviction.warrant.json
# Markdown SHA-256:   656881a881bc6cf13d174daa4bb0b58979f16818710d13d7019b6673ef44ea0e
# Code AST SHA-256:   e367057ca733c293047716a03e1ec39b39270805c87ebca04b4a95ef6f5aef51
# Verified Classes:   SelfEditProvenanceError, ToolOutcome, ContextEdit
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class SelfEditProvenanceError(RuntimeError):
    """Raised when a self-edit would destroy outcome polarity the plan still depends on."""
    pass


@dataclass
class ToolOutcome:
    call_id: str
    tool: str
    outcome: str          # "success" | "failure" | "partial"
    artifact_ref: Optional[str] = None


@dataclass
class ContextEdit:
    pruned_call_ids: set
    retained_dependencies: dict   # retained_step -> set of call_ids it depends on
    summary_text: str
    source_log_hash: str = ""


def validate_self_edit(
    edit: ContextEdit,
    outcome_log: list,
    require_polarity: bool = True,
) -> ContextEdit:
    """
    Enforce the invariant: a self-edit may not prune a tool outcome that a
    retained step depends on for polarity (success/failure), unless that
    outcome is externalized in a verifiable manifest.
    """
    log_index = {o.call_id: o for o in outcome_log}

    # 1. Every retained dependency that lands in the pruned set must be
    #    resolvable to a durable outcome record, not just to summary prose.
    for step, deps in edit.retained_dependencies.items():
        for dep in deps:
            if dep in edit.pruned_call_ids:
                if dep not in log_index:
                    raise SelfEditProvenanceError(
                        f"retained step {step!r} depends on pruned call {dep!r} "
                        f"with no durable outcome record; polarity is unrecoverable"
                    )
                if require_polarity and log_index[dep].outcome not in (
                    "success", "failure", "partial"
                ):
                    raise SelfEditProvenanceError(
                        f"pruned call {dep!r} has undefined outcome polarity"
                    )

    # 2. Bind the summary to the log it was derived from so drift is detectable.
    canonical = json.dumps(
        [{"id": o.call_id, "out": o.outcome} for o in sorted(
            (log_index[c] for c in edit.pruned_call_ids if c in log_index),
            key=lambda o: o.call_id,
        )],
        sort_keys=True,
    ).encode()
    expected_hash = hashlib.sha256(canonical).hexdigest()

    if edit.source_log_hash and edit.source_log_hash != expected_hash:
        raise SelfEditProvenanceError(
            "summary source_log_hash does not match pruned outcome log; "
            "summary has drifted from ground truth"
        )
    edit.source_log_hash = expected_hash
    return edit
