# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-memory-the-write-time-grounding-audit-and-the-poisoned-consistency-window.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-its-own-memory-the-write-time-grounding-audit-and-the-poisoned-consistency-window.warrant.json
# Markdown SHA-256:   35969e99803e941a0c7efd1ca143e95b31384bae453da766bbe8ea910654062b
# Code AST SHA-256:   014b44bcc2a70148aed6e56ee7729f96d0369b3e567869cb55bcade142bd5c5b
# Verified Classes:   UngroundedMemoryError, ScopeLaunderingError, MemoryRecord, Excerpt, GroundingAuditor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class UngroundedMemoryError(RuntimeError):
    """Raised when a memory record cannot be re-verified against a retained excerpt."""
    pass


class ScopeLaunderingError(RuntimeError):
    """Raised when a candidate record's claim scope exceeds any contiguous excerpt span."""
    pass


@dataclass
class MemoryRecord:
    record_id: str
    claim: str
    grounding_ref: Optional[str]          # id of retained excerpt; None == ungrounded
    derived_from: list[str] = field(default_factory=list)
    status: str = "unverified"            # "verified" | "unverified"


@dataclass
class Excerpt:
    excerpt_id: str
    text: str
    imperative_spans: list[tuple[int, int]] = field(default_factory=list)


class GroundingAuditor:
    def __init__(self, excerpts: dict[str, Excerpt]):
        self.excerpts = excerpts

    def _contiguous_support(self, claim: str, excerpt: Excerpt) -> bool:
        # Simplified: require the claim's key clause to appear as one contiguous,
        # non-imperative span. Real impl uses span alignment + scope parsing.
        key = claim.split(";")[0].strip().lower()
        if key not in excerpt.text.lower():
            return False
        for start, end in excerpt.imperative_spans:
            if excerpt.text[start:end].lower() in key:
                return False  # imperative absorbed into factual claim
        return True

    def audit_write(self, record: MemoryRecord) -> MemoryRecord:
        if record.grounding_ref is None:
            raise UngroundedMemoryError(
                f"record {record.record_id} has no grounding_ref; cannot commit as verified"
            )
        excerpt = self.excerpts.get(record.grounding_ref)
        if excerpt is None:
            raise UngroundedMemoryError(
                f"grounding excerpt {record.grounding_ref} expired; "
                f"record {record.record_id} demoted to unverified"
            )
        if not self._contiguous_support(record.claim, excerpt):
            raise ScopeLaunderingError(
                f"record {record.record_id} claim scope exceeds contiguous excerpt span; "
                f"likely scope-laundering of injected clause"
            )
        record.status = "verified"
        return record

    def audit_store(self, records: list[MemoryRecord]) -> list[MemoryRecord]:
        # Consistency audit is DEMOTION-ONLY: it may flag ungrounded clusters,
        # never promote. A cluster whose members share one ungrounded ancestor
        # is internally consistent by construction and must be distrusted.
        demoted = []
        for r in records:
            if r.grounding_ref is None or r.grounding_ref not in self.excerpts:
                r.status = "unverified"
                demoted.append(r)
        return demoted


def commit_candidate(record: MemoryRecord, auditor: GroundingAuditor) -> MemoryRecord:
    """Entry point: refuse to commit a record the auditor cannot ground."""
    try:
        return auditor.audit_write(record)
    except (UngroundedMemoryError, ScopeLaunderingError) as exc:
        raise UngroundedMemoryError(
            f"refusing to commit {record.record_id}: {exc}"
        ) from exc
