# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-contract-drift-during-runtime-capability-negotiation-between-two-agents-that-synthesize-an-interface-on-the.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-and-survive-contract-drift-during-runtime-capability-negotiation-between-two-agents-that-synthesize-an-interface-on-the.warrant.json
# Markdown SHA-256:   0b26d7268fd57096e7e070f0bfb1052fc49f34481253a9b84c0717aaee1b355e
# Code AST SHA-256:   3578d770c8921d7291c1462e50e5532c2f676912275a5c824ea540fae25ada39
# Verified Classes:   ContractDriftError, PredicateKind, Postcondition, Contract
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import Callable


class ContractDriftError(RuntimeError):
    """Raised when a MECHANICAL postcondition is evaluated by judgment at replay,
    or when negotiation proceeds with unbacked mechanical guarantees."""


class PredicateKind(Enum):
    MECHANICAL = "mechanical"   # evaluable by deterministic code
    JUDGMENT = "judgment"       # requires probabilistic assessment


@dataclass(frozen=True)
class Postcondition:
    name: str
    kind: PredicateKind
    predicate: Callable[[str, str], bool] | None = None  # (input, output) -> bool
    # Binding: MECHANICAL predicates MUST carry executable code.
    # A MECHANICAL predicate with predicate=None is a synthesis-time defect.


@dataclass
class Contract:
    postconditions: list[Postcondition] = field(default_factory=list)

    def mechanical(self) -> list[Postcondition]:
        return [p for p in self.postconditions if p.kind is PredicateKind.MECHANICAL]


def negotiate(
    proposed: list[Postcondition],
    callee_enforceable: set[str],
) -> Contract:
    """Synthesize a contract, demoting unbacked mechanical predicates.

    Invariant: after negotiation, every MECHANICAL postcondition is both
    constructible (has code) and capability-backed (callee declares it can
    enforce it). Anything else is demoted to JUDGMENT and recorded as soft.
    """
    final: list[Postcondition] = []
    for p in proposed:
        if p.kind is PredicateKind.MECHANICAL:
            if p.predicate is None:
                # Cannot construct code -> must demote before execution.
                final.append(Postcondition(p.name, PredicateKind.JUDGMENT))
                continue
            if p.name not in callee_enforceable:
                # Callee cannot enforce -> demote, record softened guarantee.
                final.append(Postcondition(p.name, PredicateKind.JUDGMENT))
                continue
        final.append(p)
    return Contract(final)


def verify(contract: Contract, input_text: str, output_text: str) -> dict[str, bool]:
    """Post-hoc conformance check. MECHANICAL predicates run code; JUDGMENT
    predicates are flagged as soft (and here, conservatively marked unknown)."""
    verdicts: dict[str, bool] = {}
    for p in contract.postconditions:
        if p.kind is PredicateKind.MECHANICAL:
            if p.predicate is None:
                # A MECHANICAL predicate reached replay without code.
                # This means negotiation was bypassed -> hard error.
                raise ContractDriftError(
                    f"Mechanical postcondition {p.name!r} has no executable "
                    f"predicate at replay; contract integrity violated."
                )
            verdicts[p.name] = bool(p.predicate(input_text, output_text))
        else:
            # Soft guarantee: do not silently certify. Mark unknown.
            verdicts[p.name] = False
    return verdicts


def run_pipeline(
    input_text: str,
    output_text: str,
    proposed: list[Postcondition],
    callee_enforceable: set[str],
) -> dict[str, bool]:
    contract = negotiate(proposed, callee_enforceable)
    verdicts = verify(contract, input_text, output_text)
    # Enforce: any MECHANICAL predicate that failed is a hard stop.
    mechanical_names = {p.name for p in contract.mechanical()}
    for name in mechanical_names:
        if not verdicts.get(name, False):
            raise ContractDriftError(
                f"Mechanical postcondition {name!r} failed post-hoc conformance."
            )
    return verdicts


if __name__ == "__main__":
    # The observed case: verbatim-echo invariant proposed as MECHANICAL,
    # but callee never declared the capability to enforce substring checks.
    proposed = [
        Postcondition("length_ratio", PredicateKind.MECHANICAL,
                      lambda i, o: len(o) <= 0.3 * len(i)),
        Postcondition("no_pii", PredicateKind.MECHANICAL,
                      lambda i, o: "@" not in o),
        Postcondition("no_verbatim_echo", PredicateKind.MECHANICAL,
                      lambda i, o: not any(
                          i[j:j + 40] in o for j in range(0, max(0, len(i) - 40))
                      )),
    ]
    # Callee honestly declares it can only enforce length and PII.
    enforceable = {"length_ratio", "no_pii"}
    bad_output = "Short summary. " + "x" * 187  # violates echo invariant
    try:
        run_pipeline("A" * 500, bad_output, proposed, enforceable)
    except ContractDriftError as e:
        # After negotiation, no_verbatim_echo was demoted to JUDGMENT (soft),
        # so the mechanical check does not fire on it -- but the soft
        # predicate is marked False (unknown), preventing a false pass.
        print(f"drift contained: {e}")
