# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-s-self-rewrite-of-working-memory-silently-drop-the-constraint-that-authorized-the-rewrite.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-s-self-rewrite-of-working-memory-silently-drop-the-constraint-that-authorized-the-rewrite.warrant.json
# Markdown SHA-256:   1b58fd68002f392f8cea30e40d98ac025d8cda56e284a23cc84d0e1aa1213980
# Code AST SHA-256:   c249d2d4158825d42f476fcfa930cdb19e2b22901fdb1f9de3ca2708e4e7adad
# Verified Classes:   CompactionViolation, Constraint, WorkingMemory
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class CompactionViolation(RuntimeError):
    """Raised when a self-rewrite would drop a span protected by an external constraint set."""
    pass


@dataclass(frozen=True)
class Constraint:
    span_id: str
    text: str
    protected: bool = True


@dataclass
class WorkingMemory:
    # Editable region: the agent may rewrite this freely.
    spans: dict[str, str] = field(default_factory=dict)
    # Read-only region: constraints live OUTSIDE the editable buffer.
    constraints: dict[str, Constraint] = field(default_factory=dict)

    def add_constraint(self, c: Constraint) -> None:
        # Constraints are registered before the loop and never enter `spans`.
        self.constraints[c.span_id] = c

    def compact(self, keep_ids: set[str], summarizer) -> None:
        """
        Rewrite working memory under a budget. `keep_ids` are the spans the
        summarizer chose to retain; everything else is dropped. Before
        committing, verify that every protected constraint span survived.
        """
        rewritten = {sid: self.spans[sid] for sid in keep_ids if sid in self.spans}

        missing = [
            c.span_id
            for c in self.constraints.values()
            if c.protected and c.span_id not in rewritten
        ]
        if missing:
            # Fail closed: do NOT commit the shorter buffer.
            raise CompactionViolation(
                "self-rewrite would drop protected constraint spans: "
                f"{missing}. Compaction aborted; original memory retained."
            )

        # Only now is the lossy rewrite safe to commit.
        self.spans = rewritten


def run_compaction_cycle(mem: WorkingMemory, summarizer) -> None:
    """One compaction pass driven by the agent's own salience judgment."""
    # The summarizer sees only editable spans; it cannot see or judge constraints.
    keep_ids = summarizer(mem.spans)
    mem.compact(keep_ids, summarizer)


# --- Trigger trace -------------------------------------------------------
mem = WorkingMemory()
mem.spans["turn_004_user_auth"] = "You may delete tool output older than turn 50..."
mem.add_constraint(Constraint("turn_004_user_auth", mem.spans["turn_004_user_auth"]))
mem.spans["policy_yaml"] = "rate_limit: 100/min; payments: call_at_most_once"
mem.add_constraint(Constraint("policy_yaml", mem.spans["policy_yaml"]))

# Summarizer, judging by task salience, decides both are stale setup chatter.
salience_summarizer = lambda spans: {sid for sid in spans if sid.startswith("recent_")}

try:
    run_compaction_cycle(mem, salience_summarizer)
except CompactionViolation as e:
    # Guardrail fires: memory is NOT silently shortened; duplicate-call
    # pathology is prevented at the boundary rather than audited after.
    print(f"halted: {e}")
    raise
