# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-attestation-boundary-when-a-memory-store-s-integrity-check-itself-is-poisoned-by-the-same-write-path-it-is-meant-to-gu.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-attestation-boundary-when-a-memory-store-s-integrity-check-itself-is-poisoned-by-the-same-write-path-it-is-meant-to-gu.warrant.json
# Markdown SHA-256:   622a2b7ace96d5658e3c198291d392b91f981bac638f5bcd28596e4eba0e7789
# Code AST SHA-256:   1f9fd4e516612dee5ebdf9d0b489776855310ea11e1a0195cc819054961c7af5
# Verified Classes:   AttestationBoundaryError, TrustTier, MemoryRecord
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class AttestationBoundaryError(RuntimeError):
    """Raised when a memory record is promoted to canonical trust
    on the strength of writer-self-computed attestation alone."""


class TrustTier(Enum):
    PROVISIONAL = "provisional"
    CANONICAL = "canonical"


@dataclass
class MemoryRecord:
    payload: str
    provenance_tag: str          # string the WRITER chose; forgeable
    self_hash: str               # checksum the WRITER computed; forgeable
    external_event_id: Optional[str] = None   # runtime-logged ID, if any
    independent_attestation: Optional[str] = None  # second agent's sig, if any
    tier: TrustTier = TrustTier.PROVISIONAL


def _recompute(payload: str) -> str:
    return hashlib.sha256(payload.encode()).hexdigest()


def verify_self_consistency(rec: MemoryRecord) -> bool:
    """Only proves the bytes match what was written. Proves NOTHING
    about whether the writer was honest."""
    return _recompute(rec.payload) == rec.self_hash


def has_independent_attestation(rec: MemoryRecord, runtime_log: dict) -> bool:
    """Independence requires either a second-party signature or a
    cross-reference to an event the tool runtime itself logged."""
    if rec.independent_attestation:
        return True
    if rec.external_event_id and rec.external_event_id in runtime_log:
        logged_payload = runtime_log[rec.external_event_id]
        return logged_payload == rec.payload
    return False


def promote_to_canonical(rec: MemoryRecord, runtime_log: dict) -> MemoryRecord:
    """The boundary. Self-consistency is necessary but NOT sufficient."""
    if not verify_self_consistency(rec):
        raise AttestationBoundaryError(
            f"record failed self-consistency: hash mismatch on {rec.provenance_tag!r}"
        )
    if not has_independent_attestation(rec, runtime_log):
        raise AttestationBoundaryError(
            "refusing to promote record to CANONICAL: attestation was computed "
            f"by the same write path that produced the payload (provenance="
            f"{rec.provenance_tag!r}). Self-attested integrity is a "
            "self-consistency check, not integrity. Record stays PROVISIONAL."
        )
    rec.tier = TrustTier.CANONICAL
    return rec


def resolve_conflict(canonical: MemoryRecord, provisional: MemoryRecord) -> MemoryRecord:
    """Canonical outranks any number of provisional records.
    Recency and majority are attacker-manufacturable; never use them here."""
    if provisional.tier is not TrustTier.PROVISIONAL:
        raise AttestationBoundaryError("conflict resolver received non-provisional record")
    return canonical  # provisional is quarantined, write path flagged for audit
