# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-pruning-from-resurrecting-a-poisoned-litmus-confidence-score-across-agent-re-entry.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-speculative-branch-pruning-from-resurrecting-a-poisoned-litmus-confidence-score-across-agent-re-entry.warrant.json
# Markdown SHA-256:   cd7444d89312fefd9d1236c0a7aebb8631a85bb96e18294ed39f948620ffa7cd
# Code AST SHA-256:   7ef5b355fdc10d165a9bd85adc13298cfdb987eb0bb6e8b12cd424192fa27d13
# Verified Classes:   PruneLineageViolation, Witness, PruneLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class PruneLineageViolation(RuntimeError):
    """Raised when a re-entered branch's witnessed score does not respect
    the digest/nonce invariants established at prune time."""


@dataclass
class Witness:
    score: float
    branch_digest: str
    nonce: int
    prune_reason_fields: frozenset[str]


@dataclass
class PruneLedger:
    # branch_id -> list of witnesses in nonce order
    entries: dict[str, list[Witness]] = field(default_factory=dict)
    _nonce: int = 0

    def _next_nonce(self) -> int:
        self._nonce += 1
        return self._nonce

    @staticmethod
    def digest(state: dict[str, Any]) -> str:
        # Digest must cover every field the scorer reads.
        blob = json.dumps(state, sort_keys=True, separators=(",", ":")).encode()
        return hashlib.sha256(blob).hexdigest()

    def record_prune(
        self,
        branch_id: str,
        state: dict[str, Any],
        score: float,
        prune_reason_fields: set[str],
    ) -> Witness:
        w = Witness(
            score=score,
            branch_digest=self.digest(state),
            nonce=self._next_nonce(),
            prune_reason_fields=frozenset(prune_reason_fields),
        )
        self.entries.setdefault(branch_id, []).append(w)
        return w

    def admit_reentry(
        self,
        branch_id: str,
        state: dict[str, Any],
        new_score: float,
        scorer_is_deterministic: bool = True,
        tolerance: float = 1e-6,
    ) -> Witness:
        prior = self.entries.get(branch_id)
        if not prior:
            raise PruneLineageViolation(
                f"re-entry for {branch_id} with no recorded prune lineage"
            )
        last = prior[-1]
        new_digest = self.digest(state)

        if new_digest == last.branch_digest:
            # Same state: score must be reproducible.
            if scorer_is_deterministic and abs(new_score - last.score) > tolerance:
                raise PruneLineageViolation(
                    f"deterministic scorer diverged on identical digest for "
                    f"{branch_id}: {last.score} vs {new_score}"
                )
            return last

        # Digest changed. Identify which fields moved.
        # Caller is expected to pass only the delta-relevant state slice
        # in `state` for this check; here we compare recorded reason fields.
        changed_fields = set(state.keys())
        touched_reason = changed_fields & set(last.prune_reason_fields)
        if touched_reason:
            raise PruneLineageViolation(
                f"re-entry for {branch_id} mutated prune-reason fields "
                f"{sorted(touched_reason)}; escalate to fresh adjudication "
                f"with prior prune as negative prior, do not silently re-score"
            )

        w = Witness(
            score=new_score,
            branch_digest=new_digest,
            nonce=self._next_nonce(),
            prune_reason_fields=last.prune_reason_fields,
        )
        self.entries[branch_id].append(w)
        return w


def plan_with_pruning(
    branch_id: str,
    state: dict[str, Any],
    score: float,
    ledger: PruneLedger,
    threshold: float = 0.5,
    prune_reason_fields: set[str] | None = None,
) -> str:
    if branch_id not in ledger.entries:
        ledger.record_prune(
            branch_id, state, score, prune_reason_fields or set()
        )
        return "pruned" if score < threshold else "committed"

    # Re-entry path: enforce invariants before considering commit.
    ledger.admit_reentry(branch_id, state, score)
    if score < threshold:
        return "pruned"
    return "committed"
