# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-capability-advertisement-drift-when-a-federated-peer-s-declared-capability-envelope-silently-diverges-from-its.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-bound-capability-advertisement-drift-when-a-federated-peer-s-declared-capability-envelope-silently-diverges-from-its.warrant.json
# Markdown SHA-256:   c4e00ef695324e20c73be09eed4a18a30373fe14b258758e6413303f3761956b
# Code AST SHA-256:   c9e4f2ddbc26fa8688a8a37fa3f0bd010acc045459ea3c26e06cd5884adc6658
# Verified Classes:   CapabilityDriftError, CanaryStarvationError, CapabilityEnvelope, ContinuityWitness
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class CapabilityDriftError(RuntimeError):
    """Raised when a peer's behavioral witness breaches the advertised envelope."""
    pass


class CanaryStarvationError(CapabilityDriftError):
    """Raised when the canary set is too small to detect the tolerance breach."""
    pass


@dataclass
class CapabilityEnvelope:
    name: str
    quality_floor: float          # advertised, from signed manifest
    tolerance: float = 0.05       # consumer-side epsilon band
    min_canary_n: int = 40        # statistical power floor for the window

    def lower_bound(self) -> float:
        return self.quality_floor - self.tolerance


@dataclass
class ContinuityWitness:
    envelope: CapabilityEnvelope
    canary_results: list[bool] = field(default_factory=list)

    def record(self, correct: bool) -> None:
        self.canary_results.append(correct)

    def accuracy(self) -> float:
        if not self.canary_results:
            return float("nan")
        return sum(self.canary_results) / len(self.canary_results)

    def check(self) -> None:
        n = len(self.canary_results)
        if n < self.envelope.min_canary_n:
            raise CanaryStarvationError(
                f"capability={self.envelope.name!r} canary_n={n} "
                f"< min_canary_n={self.envelope.min_canary_n}; "
                f"drift undetectable, settlement must be suspended"
            )
        acc = self.accuracy()
        lb = self.envelope.lower_bound()
        if acc < lb:
            raise CapabilityDriftError(
                f"capability={self.envelope.name!r} witness_acc={acc:.4f} "
                f"< lower_bound={lb:.4f} (floor={self.envelope.quality_floor}, "
                f"tol={self.envelope.tolerance}); "
                f"peer behavior diverged from signed advertisement"
            )


def settle_task(
    witness: ContinuityWitness,
    task_output: dict,
    replay_stable: Callable[[dict], bool],
    advertised_rate: float,
    degraded_rate: float,
) -> float:
    """
    Settlement gate. Note: replay_stable is checked for dispute resolution
    but is NOT the settlement gate. The continuity witness is.
    """
    # Replay-stability is necessary but insufficient: a degraded-but-deterministic
    # peer passes it trivially. Do not settle on it alone.
    if not replay_stable(task_output):
        return 0.0  # non-deterministic output: no settlement, escalate

    try:
        witness.check()
    except CapabilityDriftError:
        # Drift detected: settle at degraded rate, hold rebate claim open.
        return degraded_rate

    return advertised_rate
