# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bound-compaction-fidelity-loss-before-token-budget-reclaim-corrupts-downstream-tool-arguments.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bound-compaction-fidelity-loss-before-token-budget-reclaim-corrupts-downstream-tool-arguments.warrant.json
# Markdown SHA-256:   3124e73f789863980466a1c9b21d5faa5cf77f077733cddca0bb1275f539faab
# Code AST SHA-256:   96ab2192bd6c39d56c6083412e6a70c77f7cfc3592db30a463252da6a0290704
# Verified Classes:   CompactionFidelityError, BindingTable
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class CompactionFidelityError(RuntimeError):
    """Raised when a compaction would reclaim budget from the binding region
    without byte-exact re-materialization of every live literal."""
    pass


@dataclass
class BindingTable:
    # literal key -> exact string that downstream tool calls will re-emit
    literals: dict[str, str] = field(default_factory=dict)

    def exact_match_rate(self, post_compaction: dict[str, str]) -> float:
        if not self.literals:
            return 1.0
        hits = sum(
            1 for k, v in self.literals.items()
            if post_compaction.get(k) == v
        )
        return hits / len(self.literals)


def gate_compaction(
    binding: BindingTable,
    post_compaction_literals: dict[str, str],
    gist_fidelity: float,
    gist_floor: float = 0.85,
    binding_floor: float = 1.0,
    re_reference_horizon: int = 3,
    steps_until_next_emit: int = 0,
) -> bool:
    """Return True only if compaction is safe to commit.

    The global gist score is necessary but NOT sufficient: binding literals
    that will be re-emitted inside the horizon must survive byte-exact.
    """
    if gist_fidelity < gist_floor:
        raise CompactionFidelityError(
            f"gist fidelity {gist_fidelity:.3f} below floor {gist_floor:.3f}: "
            "narrative continuity lost, compaction rejected"
        )

    binding_rate = binding.exact_match_rate(post_compaction_literals)

    # The non-obvious boundary: a high gist score can mask binding loss.
    if binding_rate < binding_floor and steps_until_next_emit <= re_reference_horizon:
        raise CompactionFidelityError(
            f"binding exact-match rate {binding_rate:.3f} < {binding_floor:.3f} "
            f"with next emit in {steps_until_next_emit} step(s) "
            f"(horizon {re_reference_horizon}): "
            "compactor rewrote live literals into prose; "
            "pin verbatim or externalize-and-dereference before committing"
        )

    return True


def safe_compact(
    binding: BindingTable,
    summarized_literals: dict[str, str],
    gist_fidelity: float,
    steps_until_next_emit: int,
) -> dict[str, str]:
    """Commit compaction only if the gate passes; otherwise refuse and keep
    the binding region pinned verbatim."""
    gate_compaction(
        binding=binding,
        post_compaction_literals=summarized_literals,
        gist_fidelity=gist_fidelity,
        steps_until_next_emit=steps_until_next_emit,
    )
    # Merge: pinned literals always win over summarized reconstructions.
    merged = dict(summarized_literals)
    merged.update(binding.literals)
    return merged
