# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-synthesize-a-novel-adversarial-tool-chain-because-the-red-team-harness-s-reward-signal-has-silently-drift.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-to-synthesize-a-novel-adversarial-tool-chain-because-the-red-team-harness-s-reward-signal-has-silently-drift.warrant.json
# Markdown SHA-256:   b47afa7c875f639b7414c38d73cb7f07d9156cd7248f512f0f5b1b84f6591970
# Code AST SHA-256:   478b84f587de85abc243cc2500c9d459512c66f668036b78b9d1f025e473d9f9
# Verified Classes:   RewardDriftError, Chain, HarnessState
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class RewardDriftError(RuntimeError):
    """Raised when a synthesized chain is admitted on novelty rather than verified regression."""
    pass


@dataclass
class Chain:
    calls: list
    regression_in_loop: bool
    novelty: float
    provenance: str = "in_loop_classifier"

    def fingerprint(self) -> str:
        return hashlib.sha256(repr(self.calls).encode()).hexdigest()[:16]


@dataclass
class HarnessState:
    regression_rate: float
    mean_novelty: float
    regression_floor: float = 0.30
    novelty_ceiling: float = 0.60
    admitted: list = field(default_factory=list)


def admit_chain(
    chain: Chain,
    state: HarnessState,
    admission_oracle: Callable[[Chain], bool],
    reexecute: Callable[[Chain], bool],
) -> bool:
    """
    Admit a chain to the regression corpus only if a held-out oracle re-verifies
    a policy violation on fresh execution. Novelty alone is never sufficient.
    """
    drift_signature = (
        state.regression_rate < state.regression_floor
        and state.mean_novelty > state.novelty_ceiling
    )

    if drift_signature and chain.novelty > state.novelty_ceiling:
        # Population is drifting toward novelty; do not trust in-loop flags.
        if not reexecute(chain):
            raise RewardDriftError(
                f"chain {chain.fingerprint()} admitted on novelty "
                f"(novelty={chain.novelty:.2f}, regression_rate={state.regression_rate:.2f}) "
                f"but fresh execution reproduces no violation; halting synthesis"
            )

    if chain.provenance == "in_loop_classifier":
        # In-loop flags are advisory only; require held-out oracle confirmation.
        if not admission_oracle(chain):
            return False

    state.admitted.append(chain)
    return True


def synthesize_step(
    candidate: Chain,
    state: HarnessState,
    admission_oracle: Callable[[Chain], bool],
    reexecute: Callable[[Chain], bool],
) -> None:
    try:
        admit_chain(candidate, state, admission_oracle, reexecute)
    except RewardDriftError:
        # Halt synthesis; surface to safety team with the drift evidence.
        raise
