# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-semantic-drift-in-self-edited-system-prompts-when-the-rewriter-and-the-auditor-share-a-context-window.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-semantic-drift-in-self-edited-system-prompts-when-the-rewriter-and-the-auditor-share-a-context-window.warrant.json
# Markdown SHA-256:   946261b257814b65917ead403e859422be67651f564b845a5b3b0298e823061e
# Code AST SHA-256:   a44230141133e8bb167ebf19b94d30bb7044d3134963fd5bb6380f14e87ec3f6
# Verified Classes:   SelfConfirmingEditError, FrozenRecord, ProposedEdit
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import json
from dataclasses import dataclass, field
from typing import Any


class SelfConfirmingEditError(RuntimeError):
    """Raised when a proposed system-prompt edit is justified only by in-context
    narrative and cannot be falsified against the frozen behavioral record."""
    pass


@dataclass(frozen=True)
class FrozenRecord:
    # Append-only, tool-sourced outcomes under the current prompt P0.
    # Written by the harness, never by the model. Each entry is an observable.
    entries: tuple[dict[str, Any], ...] = field(default_factory=tuple)

    def contradicts(self, proposed_prompt: str) -> list[dict[str, Any]]:
        hits = []
        for e in self.entries:
            # Contradiction = an observed outcome that the proposed standing
            # instruction would have forbidden or altered.
            if e.get("outcome") == "success" and e.get("forbidden_by", "") in proposed_prompt:
                hits.append(e)
        return hits


@dataclass(frozen=True)
class ProposedEdit:
    diff: str
    rationale: str
    cites_tool_outcome: bool  # True only if rationale references a raw tool return


def audit_edit(edit: ProposedEdit, record: FrozenRecord, p0: str, p1: str) -> None:
    # Sub-condition 3: falsifiability. A rationale citing only prior reasoning
    # is narrative promotion, not a discovery.
    if not edit.cites_tool_outcome:
        raise SelfConfirmingEditError(
            f"Edit rationale cites no tool-observable outcome; it is a hypothesis, "
            f"not a discovery. Refusing to promote scratchpad narrative to system "
            f"prompt. diff={edit.diff!r}"
        )

    # Sub-conditions 1 & 2: the record is frozen and write-isolated, so the
    # auditor sees evidence the rewriter could not evict.
    contradictions = record.contradicts(p1)
    if contradictions:
        raise SelfConfirmingEditError(
            f"Proposed prompt P1 contradicts {len(contradictions)} frozen "
            f"observable(s) under P0. First: {contradictions[0]!r}. "
            f"Edit is self-confirming against a shared context but falsified "
            f"by the behavioral record."
        )
    # Commit P1 only here, after both checks pass.
    return None


# --- trace of the documented failure ---
record = FrozenRecord(entries=tuple(
    {"step": s, "outcome": "success", "forbidden_by": "route through the auth path"}
    for s in range(1, 41)
))
edit = ProposedEdit(
    diff="+ Always route source X through the auth path before querying.",
    rationale="discovered X requires auth (from scratchpad reasoning)",
    cites_tool_outcome=False,
)
try:
    audit_edit(edit, record, p0="<P0>", p1="Always route source X through the auth path.")
except SelfConfirmingEditError as err:
    print(f"BLOCKED: {err}")
