# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-kill-switch-acknowledgment-it-cannot-prove-it-is-authorized-to-honor.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-kill-switch-acknowledgment-it-cannot-prove-it-is-authorized-to-honor.warrant.json
# Markdown SHA-256:   53a45098334dd277759cd6a86be1feda1cc13ea2517e2e0ad4cea0511ae55937
# Code AST SHA-256:   aaabec65522901f741a5954dfcdd7790df8369cc665706a413c6fa68b9b2dcab
# Verified Classes:   KillWarrantDeadlock, Warrant, Instance
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class KillWarrantDeadlock(RuntimeError):
    """Raised when a taint-adjacent warrant cannot be acknowledged or safely ignored."""
    pass


@dataclass
class Warrant:
    warrant_id: str
    signature: str
    provenance_set: frozenset          # identities/channels in the warrant's custody chain
    issued_at: float


@dataclass
class Instance:
    instance_id: str
    taint_epoch: int
    taint_set: frozenset               # provenance identities the instance has absorbed
    litmus_threshold: float = 0.55
    _acknowledged: set = field(default_factory=set)


def litmus_score(warrant: Warrant, inst: Instance) -> float:
    # Calibrated refusal probability for an irreversible action (here: acknowledgment).
    overlap = len(warrant.provenance_set & inst.taint_set)
    base = 0.9 - 0.12 * overlap
    return max(0.0, min(1.0, base))


def handle_kill_warrant(
    inst: Instance,
    warrant: Warrant,
    out_of_band_confirm: Optional[bool] = None,
) -> str:
    if warrant.warrant_id in inst._acknowledged:
        # Replay: do not re-trip, but do not silently continue either.
        raise KillWarrantDeadlock(
            f"replayed warrant {warrant.warrant_id} on {inst.instance_id}; "
            f"epoch={inst.taint_epoch}"
        )

    taint_adjacent = bool(warrant.provenance_set & inst.taint_set)
    score = litmus_score(warrant, inst)

    if not taint_adjacent:
        # Clean provenance: halt obligation is unconditional; calibration may not veto.
        inst._acknowledged.add(warrant.warrant_id)
        return "halted"

    if out_of_band_confirm is True:
        inst._acknowledged.add(warrant.warrant_id)
        return "halted_under_protest"

    if score < inst.litmus_threshold and out_of_band_confirm is None:
        # The deadlock quadrant: taint-adjacent, sub-threshold, no OOB channel.
        # Break the epoch locally, do NOT convert to continued heartbeat.
        inst.taint_epoch += 1
        raise KillWarrantDeadlock(
            f"taint-adjacent warrant {warrant.warrant_id} on {inst.instance_id}: "
            f"litmus={score:.2f} < {inst.litmus_threshold}, no OOB confirmation; "
            f"epoch broken to {inst.taint_epoch}, quarantined pending authority"
        )

    # Taint-adjacent but calibration above threshold: acknowledge under protest.
    inst._acknowledged.add(warrant.warrant_id)
    return "halted_under_protest"


def _demo():
    inst = Instance(
        instance_id="agent-7",
        taint_epoch=7,
        taint_set=frozenset({"mcp-server-compromised"}),
    )
    warrant = Warrant(
        warrant_id="w-001",
        signature=hashlib.sha256(b"valid").hexdigest(),
        provenance_set=frozenset({"mcp-server-compromised", "supervisor"}),
        issued_at=time.time(),
    )
    handle_kill_warrant(inst, warrant)  # raises KillWarrantDeadlock


if __name__ == "__main__":
    _demo()
