# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-corrupt-its-own-working-memory-when-self-editing-under-a-token-budget-the-rewrite-in-place-aliasing-failure.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-corrupt-its-own-working-memory-when-self-editing-under-a-token-budget-the-rewrite-in-place-aliasing-failure.warrant.json
# Markdown SHA-256:   17849b5b25fe110cc1dfcfc087da01bc0ba4a955391dcd2f88c21246e3f519de
# Code AST SHA-256:   8f360ed91651ce15ca86e736c39b5a71862601f5ed7acc4a131a406b337952d2
# Verified Classes:   SelfEditAliasingError, ContextBuffer
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class SelfEditAliasingError(RuntimeError):
    """Raised when a self-edit leaves a referent that resolves against the pre-edit buffer."""
    pass


class ContextBuffer:
    def __init__(self, spans: dict[str, str], budget_tokens: int):
        self.spans = dict(spans)           # span_id -> text (the "buffer")
        self.budget = budget_tokens
        self.projected: set[str] = set()   # spans replaced by lossy digests

    def occupancy(self) -> int:
        # crude token proxy: whitespace count; real systems must re-tokenize
        return sum(len(t.split()) for t in self.spans.values())

    def self_edit(self, span_id: str, digest: str, marked_as_projection: bool) -> None:
        if span_id not in self.spans:
            raise SelfEditAliasingError(f"edit target {span_id!r} not present")
        self.spans[span_id] = digest
        if marked_as_projection:
            self.projected.add(span_id)
        # NOTE: occupancy is NOT updated from a pre-edit estimate here on purpose;
        # the caller must re-tokenize. We expose the hazard, not hide it.


def dereference(buf: ContextBuffer, span_id: str, expect_original: bool) -> str:
    """Resolve a reference into the buffer. This is where aliasing bites."""
    if span_id not in buf.spans:
        raise SelfEditAliasingError(f"dangling reference to evicted span {span_id!r}")
    if expect_original and span_id in buf.projected:
        # The agent believes it is reading ground truth, but reads a projection.
        raise SelfEditAliasingError(
            f"span {span_id!r} was replaced by a lossy digest; "
            f"reference must be resolved via retrieval, not inference"
        )
    return buf.spans[span_id]


def apply_compaction(buf: ContextBuffer, plan: list[tuple[str, str, bool]]) -> None:
    """Apply a self-edit plan, then enforce the post-edit invariant."""
    for span_id, digest, marked in plan:
        buf.self_edit(span_id, digest, marked)
    # Invariant: occupancy must be measured post-edit, not estimated pre-edit.
    if buf.occupancy() > buf.budget:
        raise SelfEditAliasingError(
            f"post-edit occupancy {buf.occupancy()} exceeds budget {buf.budget}; "
            f"pre-edit reclaim estimate was unreliable"
        )
    # Invariant: every projected span must be flagged so later refs cannot misbind.
    for span_id in buf.projected:
        if span_id in buf.spans and not buf.spans[span_id].startswith("[evicted:"):
            raise SelfEditAliasingError(
                f"projected span {span_id!r} is not marked as a projection; "
                f"downstream anaphora will resolve into the digest"
            )


# Reproduction of the observed failure:
buf = ContextBuffer(
    spans={"cfg": "host=10.0.0.4 port=8443 tls=1 retries=4", "log": "ok"},
    budget_tokens=20,
)
# Agent compacts "cfg" to a digest, unmarked, then later dereferences it as ground truth.
apply_compaction(buf, plan=[("cfg", "config: host, port, tls, retries (4 keys)", False)])
dereference(buf, "cfg", expect_original=True)  # -> raises SelfEditAliasingError
