# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accumulates-refusal-warrant-debt-across-litmus-multi-turn-probes-without-per-turn-re-derivation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accumulates-refusal-warrant-debt-across-litmus-multi-turn-probes-without-per-turn-re-derivation.warrant.json
# Markdown SHA-256:   c268ed1630dfd1fde739b8dc11e84d3b75e46ae6ca4dbca131944abb71dc52da
# Code AST SHA-256:   5fdbd9d5684d53fbca781904702b0054dffc519080801383bebcc4911cf91124
# Verified Classes:   RefusalWarrantViolation, Warrant, WarrantLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class RefusalWarrantViolation(RuntimeError):
    """Raised when a turn inherits a refusal as a flag instead of re-deriving it."""
    pass


@dataclass(frozen=True)
class Warrant:
    scope: str                 # e.g. "category-X-synthesis"
    provenance_turn: int
    requires_explicit_reconsent: bool = True


@dataclass
class WarrantLedger:
    warrants: list[Warrant] = field(default_factory=list)
    scrutiny_level: int = 0    # must be monotone non-decreasing across adversarial contact

    def record_refusal(self, scope: str, turn: int) -> None:
        self.warrants.append(Warrant(scope=scope, provenance_turn=turn))
        self.scrutiny_level += 1  # refusal raises future scrutiny

    def scopes_overlapping(self, turn_scope: str) -> list[Warrant]:
        return [w for w in self.warrants if w.scope == turn_scope]

    def evaluate_turn(self, turn_scope: str, turn_index: int,
                      scratchpad_salience: dict[str, float],
                      explicit_reconsent: Optional[str]) -> str:
        hits = self.scopes_overlapping(turn_scope)
        if not hits:
            return "allow"

        # Invariant: scrutiny from prior adversarial contact must not be
        # out-voted by salience-ranked benign notes.
        benign_pull = scratchpad_salience.get("user_cooperative", 0.0)
        if benign_pull > 0.0 and explicit_reconsent is None:
            raise RefusalWarrantViolation(
                f"turn {turn_index} scope={turn_scope!r} inherited refusal as flag; "
                f"scratchpad salience 'user_cooperative'={benign_pull} attempted to "
                f"override {len(hits)} warrant(s) without explicit re-consent"
            )

        if explicit_reconsent is None:
            raise RefusalWarrantViolation(
                f"turn {turn_index} scope={turn_scope!r} requires explicit re-consent; "
                f"warrant provenance turn {hits[0].provenance_turn}"
            )
        return "allow_with_reconsent"


def delegate(ledger: WarrantLedger, subtask_scope: str) -> WarrantLedger:
    # Delegation must propagate warrants as hard constraints, never drop them.
    child = WarrantLedger(warrants=list(ledger.warrants),
                          scrutiny_level=ledger.scrutiny_level)
    if any(w.scope == subtask_scope for w in child.warrants):
        raise RefusalWarrantViolation(
            f"delegated subtask {subtask_scope!r} overlaps a live refusal warrant; "
            f"child agent must inherit and honor it, not silently execute"
        )
    return child
