# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-decide-that-a-trace-anomaly-warrants-a-context-reset-rather-than-a-retry-forever-loop.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-decide-that-a-trace-anomaly-warrants-a-context-reset-rather-than-a-retry-forever-loop.warrant.json
# Markdown SHA-256:   617d90873e0d6bbb5a8377023c27404ed4e6419f512059550870717631bc394b
# Code AST SHA-256:   cf8b53440d3ca91c97f0422fe09034cc5bffa0b9f1f56f0979dacd1d8f94f2f7
# Verified Classes:   ContextResetMisattribution, Span, Attempt
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ContextResetMisattribution(RuntimeError):
    """Raised when the controller would retry a provably non-productive loop."""
    pass


@dataclass
class Span:
    kind: str            # "tool" | "model"
    signature: str       # normalized (tool, args_hash, error_class) or narration hash
    tool_derived: bool
    tokens: int


@dataclass
class Attempt:
    spans: list[Span] = field(default_factory=list)

    def tool_novelty(self, prior: Optional["Attempt"]) -> int:
        if prior is None:
            return sum(s.tokens for s in self.spans if s.tool_derived)
        prior_hashes = {hashlib.sha1(s.signature.encode()).hexdigest()
                        for s in prior.spans if s.tool_derived}
        return sum(s.tokens for s in self.spans
                   if s.tool_derived
                   and hashlib.sha1(s.signature.encode()).hexdigest() not in prior_hashes)


def decide(action: str,
           attempts: list[Attempt],
           poison_in_immutable: bool,
           reset_count: int,
           checkpoint_ok: bool) -> str:
    """Return 'retry' | 'reset' | 'abort'. Raise on misattribution."""
    if len(attempts) < 2:
        return "retry"

    cur, prev = attempts[-1], attempts[-2]
    cur_sig = cur.spans[-1].signature if cur.spans else ""
    prev_sig = prev.spans[-1].signature if prev.spans else ""
    same_signature = cur_sig == prev_sig
    novelty = cur.tool_novelty(prev)

    if poison_in_immutable:
        return "abort"

    if same_signature and novelty == 0:
        if reset_count >= 2:
            raise ContextResetMisattribution(
                f"post-reset signature {cur_sig!r} recurred after {reset_count} resets; "
                "poison survives rehydration — abort required, not reset"
            )
        if not checkpoint_ok:
            raise ContextResetMisattribution(
                f"reset demanded for {cur_sig!r} but no valid checkpoint; "
                "would discard tool-derived state and re-inject poison"
            )
        return "reset"

    if same_signature and novelty > 0:
        return "retry"   # genuine tool-derived exploration

    return "retry"       # changing signature: exploratory
