# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-memory-write-whose-provenance-hash-was-computed-over-the-post-sanitization-payload-instead-of-the-raw-tool-outp.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-trusts-a-memory-write-whose-provenance-hash-was-computed-over-the-post-sanitization-payload-instead-of-the-raw-tool-outp.warrant.json
# Markdown SHA-256:   2854f37912290768efcf609b8945157caa4b03e08167499fc1a3263672da83e2
# Code AST SHA-256:   3b42943c8d463d67765cb0abf64f4973a5b7ff9c1d03ce7c04491e02d2ef697b
# Verified Classes:   ProvenanceTautologyError, MemoryWrite
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class ProvenanceTautologyError(RuntimeError):
    """Raised when a memory write claims verification but its hash was
    computed over post-transform bytes with no anchored raw input."""
    pass


@dataclass
class MemoryWrite:
    raw_tool_output: Optional[bytes]
    stored_payload: bytes
    transform_manifest: list
    h_raw: Optional[str] = None
    h_stored: Optional[str] = None
    provenance_tier: str = "unanchored"  # "anchored" | "unanchored" | "degraded"
    anomaly_score: float = 0.0
    hash_continuity_weight: float = 0.30


def _sha(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()


def _apply_manifest(raw: bytes, manifest: list) -> bytes:
    out = raw
    for step in manifest:
        if step == "strip_zero_width":
            out = bytes(c for c in out if c not in (0xE2, 0x80, 0x8B, 0x8C, 0x8D))
        elif step == "truncate_4k":
            out = out[:4096]
        else:
            raise ProvenanceTautologyError(f"unknown transform step: {step!r}")
    return out


def audit_write(w: MemoryWrite) -> MemoryWrite:
    w.h_stored = _sha(w.stored_payload)

    if w.raw_tool_output is None:
        # No anchor: hash-continuity is a tautology, must degrade trust.
        w.provenance_tier = "degraded"
        w.anomaly_score = max(w.anomaly_score, 0.55)
        return w

    w.h_raw = _sha(w.raw_tool_output)

    try:
        reconstructed = _apply_manifest(w.raw_tool_output, w.transform_manifest)
    except ProvenanceTautologyError:
        w.provenance_tier = "degraded"
        w.anomaly_score = max(w.anomaly_score, 0.70)
        return w

    if reconstructed != w.stored_payload:
        # Stored bytes are not a deterministic function of the anchor:
        # either the manifest is incomplete or the payload was tampered.
        raise ProvenanceTautologyError(
            f"stored payload does not reconstruct from anchored raw input; "
            f"h_raw={w.h_raw[:12]} h_stored={w.h_stored[:12]} "
            f"manifest={w.transform_manifest}"
        )

    w.provenance_tier = "anchored"
    # Hash-continuity now anchors to H_raw, not H_stored, so it can fail.
    if w.h_raw != w.h_stored:
        w.anomaly_score += w.hash_continuity_weight  # expected: transform applied
    return w


def store(w: MemoryWrite) -> MemoryWrite:
    audited = audit_write(w)
    if audited.provenance_tier == "anchored" and audited.h_raw == audited.h_stored:
        # Bytes survived transform unchanged; hash-continuity is a real signal.
        audited.anomaly_score += audited.hash_continuity_weight
    if audited.provenance_tier == "degraded" and audited.anomaly_score < 0.5:
        raise ProvenanceTautologyError(
            "degraded-provenance write scored as trusted; "
            "hash-continuity feature is tautological for this write"
        )
    return audited
