# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-declassification-witness-has-been-forged-across-a-multi-tool-chain-a-taint-label-continuity-failure-at-the-agent-to.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-declassification-witness-has-been-forged-across-a-multi-tool-chain-a-taint-label-continuity-failure-at-the-agent-to.warrant.json
# Markdown SHA-256:   0b111db610d081edc0a2488a1ebbb50f43d1a4c9dcb1eab9b75a71f074691635
# Code AST SHA-256:   818240ce6e75b64f111e52eb40ae541684f6e57b7c678151406a78079fcccc45
# Verified Classes:   DeclassificationWitnessError, Witness
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Mapping


class DeclassificationWitnessError(RuntimeError):
    """Raised when a tool return claims a label drop it cannot justify."""


# Sensitivity lattice, low to high.
LATTICE = ["public", "internal", "confidential"]

# Registered declassifiers: which transform may lower (L_in -> L_out).
# 'identity' is deliberately absent for every strict-lowering edge.
REGISTERED_DECLASSIFIERS: Mapping[tuple[str, str], set[str]] = {
    ("internal", "public"): {"abstractive_summary", "aggregate_count"},
    ("confidential", "internal"): {"aggregate_count"},
    ("confidential", "public"): set(),  # never directly declassifiable
}


@dataclass(frozen=True)
class Witness:
    input_ids: tuple[str, ...]
    transform: str
    output_hash: str  # content hash of the value being declassified


def _rank(label: str) -> int:
    return LATTICE.index(label)


def _hash(value: str) -> str:
    return hashlib.sha256(value.encode()).hexdigest()


def admit_tool_return(
    value: str,
    declared_label: str,
    consumed_labels: list[str],
    witness: Witness | None,
) -> str:
    """Return the admitted label or raise if the drop is unjustified.

    Invariant: L_out may be strictly below join(consumed_labels) only when
    a content-hash-bound, transform-registered witness earns that exact edge.
    """
    join_label = max(consumed_labels, key=_rank)

    # No lowering claimed: propagation path, admit as-is.
    if _rank(declared_label) >= _rank(join_label):
        return declared_label

    # Lowering claimed. Demand a non-vacuous, bound, registered witness.
    if witness is None:
        raise DeclassificationWitnessError(
            f"label drop {join_label}->{declared_label} with no witness"
        )

    if witness.output_hash != _hash(value):
        raise DeclassificationWitnessError(
            "witness output_hash does not match value (stale replay)"
        )

    if witness.transform == "identity":
        raise DeclassificationWitnessError(
            "identity transform cannot justify a strict label lowering"
        )

    allowed = REGISTERED_DECLASSIFIERS.get((join_label, declared_label), set())
    if witness.transform not in allowed:
        raise DeclassificationWitnessError(
            f"transform {witness.transform!r} not registered for "
            f"{join_label}->{declared_label}"
        )

    return declared_label


def enforce_chain(returns: list[dict]) -> list[str]:
    admitted: list[str] = []
    for r in returns:
        try:
            admitted.append(
                admit_tool_return(
                    r["value"], r["label"], r["consumed"], r.get("witness")
                )
            )
        except DeclassificationWitnessError:
            # Fail closed: quarantine, do not re-raise and continue.
            admitted.append("QUARANTINED")
    return admitted
