# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-memory-write-whose-taint-label-is-unlabeled-but-inherited-from-a-tool-output-truncation-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-memory-write-whose-taint-label-is-unlabeled-but-inherited-from-a-tool-output-truncation-boundary.warrant.json
# Markdown SHA-256:   fa581388ae5bdd87d17c69a736fb18e2680bbd27ec6f7cadcdd910da2f17489e
# Code AST SHA-256:   98f14b6f80be9e298080fae360e0c08cd673bb00ccdbc0184c89ecf128c76713
# Verified Classes:   EnvelopeIntegrityError, Envelope, MemoryWrite
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class EnvelopeIntegrityError(RuntimeError):
    """Raised when a memory write's provenance envelope is not verifiably closed."""


@dataclass
class Envelope:
    label_id: str
    trust: str
    span_start: int
    span_end: int
    closing_sentinel_present: bool


@dataclass
class MemoryWrite:
    content: str
    envelope: Optional[Envelope]
    source_refetchable: bool


def admit_memory_write(write: MemoryWrite) -> str:
    env = write.envelope

    # Fail-closed: missing envelope is UBI (unlabeled-but-inherited), not clean.
    if env is None:
        raise EnvelopeIntegrityError(
            f"memory write has no provenance envelope; span length={len(write.content)}; "
            "treating as UNTRUSTED (fail-closed)"
        )

    # Envelope closure: opening record, span range, and closing sentinel must all agree.
    if not env.closing_sentinel_present:
        raise EnvelopeIntegrityError(
            f"envelope {env.label_id} missing closing sentinel; "
            f"span=[{env.span_start},{env.span_end}] content_len={len(write.content)}; "
            "truncation likely dropped the sentinel"
        )

    if env.span_end - env.span_start != len(write.content):
        raise EnvelopeIntegrityError(
            f"envelope {env.label_id} span range [{env.span_start},{env.span_end}] "
            f"does not match admitted content length {len(write.content)}; "
            "re-serialization laundered the taint"
        )

    if env.trust == "untrusted":
        if not write.source_refetchable:
            raise EnvelopeIntegrityError(
                f"untrusted span {env.label_id} from ephemeral source; "
                "quarantine mandatory because provenance cannot be re-established"
            )
        return "DERIVED_UNTRUSTED"

    return "CLEAN"
