# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-and-the-summarizer-silently-drops-the-referent-of-an-unresolved-anaphor.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-its-own-context-and-the-summarizer-silently-drops-the-referent-of-an-unresolved-anaphor.warrant.json
# Markdown SHA-256:   784a08c701b323b993dba42a2ad5a14f5a8b88ca189d8c69746d41f2b01207e3
# Code AST SHA-256:   9d4bea024293c3e7bd3c05aeb66a8a05546d910a7f80e02ee223ef1427348231
# Verified Classes:   ReferentLossError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ReferentLossError(RuntimeError):
    """Raised when compaction would retire a span whose bindings are not
    externally preserved, or when post-compaction bindings diverge from the
    pre-compaction snapshot."""
    pass


def compact_with_binding_guard(
    live_context: str,
    working_set: dict,          # {"target": "svc-beta", "rejected": [], ...}
    planned_next_steps: list,   # e.g. ["inspect_dependencies(target)", ...]
    summarizer,
) -> dict:
    # Pre-condition: every entity the next steps touch must be bound in the
    # externalized working set, not merely pronoun-referenced in prose.
    required = set()
    for step in planned_next_steps:
        for token in ("target", "service", "candidate", "config"):
            if token in step:
                required.add(token)
    missing = [k for k in required if k not in working_set or not working_set[k]]
    if missing:
        raise ReferentLossError(
            f"refusing to compact: next steps reference {missing} "
            f"but working_set has no explicit binding; externalize first"
        )

    snapshot = dict(working_set)

    # The summarizer narrates; it is forbidden to restate bindings.
    summary = summarizer(
        live_context,
        instruction="Narrate progress only. Do NOT restate entity names, "
                    "ordinals, or decisions; those are supplied separately.",
    )

    # Post-condition: bindings must be identical. The summary is additive.
    post = dict(snapshot)  # structured state passed through verbatim
    if post != snapshot:
        raise ReferentLossError(
            f"binding divergence after compaction: {snapshot} -> {post}"
        )

    # Tail isolation: the retained tail must not introduce competing referents
    # that the summary's vague descriptions could resolve against.
    tail = live_context[-2000:]
    for value in snapshot.values():
        if isinstance(value, str) and value and value in tail and value not in summary:
            # tail mentions a candidate the summary does not re-bind by name
            raise ReferentLossError(
                f"tail contains competing referent {value!r} not re-bound in summary"
            )

    return {"summary": summary, "working_set": post}
