# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-capability-re-derivation-after-taint-clearing-the-attenuation-join-divergence-in-layered-sandbox-stacks.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-capability-re-derivation-after-taint-clearing-the-attenuation-join-divergence-in-layered-sandbox-stacks.warrant.json
# Markdown SHA-256:   6f0c3292e08d2a8eb77a4a4381533302761907513e4f2d20b8c5e79a30f3e007
# Code AST SHA-256:   ec79d170c4d121fd44fac384d63de4de1933cdbb580382109dae4145402b09e8
# Verified Classes:   AttenuationJoinDivergence, Envelope
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class AttenuationJoinDivergence(RuntimeError):
    """Raised when a re-derived capability set exceeds the parent's effective set at handoff."""
    pass


@dataclass(frozen=True)
class Envelope:
    declared: FrozenSet[str]
    effective_at_handoff: FrozenSet[str]
    # None means "taint state not recorded" -> must be treated as TOP, not empty.
    taint_record: Optional[FrozenSet[str]]
    declass_witness: Optional[str] = None
    declass_content_hash: Optional[str] = None


def rederive_effective(env: Envelope, artifact_hash: str) -> FrozenSet[str]:
    """
    Re-derive the child's effective capability set at a handoff boundary.

    Invariant: result must be a subset of env.effective_at_handoff, UNLESS a
    declassification witness is present AND bound to this artifact's hash.
    """
    if env.taint_record is None:
        # Missing taint record is NOT clean. Fail closed: no re-widening.
        if env.declared != env.effective_at_handoff:
            raise AttenuationJoinDivergence(
                "taint record absent and declared != effective_at_handoff; "
                "refusing to re-widen capabilities without provenance"
            )
        return env.effective_at_handoff

    if env.taint_record:
        # Taint present: re-derivation may only narrow, never widen.
        widened = env.declared - env.effective_at_handoff
        if widened:
            raise AttenuationJoinDivergence(
                f"taint present but re-derivation would widen by {sorted(widened)}"
            )
        return env.effective_at_handoff

    # taint_record is empty set: taint was cleared. Require a bound witness.
    if env.declass_witness is None:
        raise AttenuationJoinDivergence(
            "empty taint record without declassification witness; "
            "cannot distinguish discharge from loss"
        )
    if env.declass_content_hash != artifact_hash:
        raise AttenuationJoinDivergence(
            f"declass witness {env.declass_witness!r} not bound to artifact "
            f"{artifact_hash!r} (witness hash {env.declass_content_hash!r})"
        )
    return env.declared


def guarded_handoff(env: Envelope, artifact_hash: str) -> FrozenSet[str]:
    effective = rederive_effective(env, artifact_hash)
    if not effective <= env.effective_at_handoff and env.declass_witness is None:
        raise AttenuationJoinDivergence(
            "post-condition: effective set exceeds handoff ceiling without witness"
        )
    return effective
