# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-commit-to-an-incompatible-tool-contract-when-the-peer-s-capability-advertisement-is-only-partially-observable.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-commit-to-an-incompatible-tool-contract-when-the-peer-s-capability-advertisement-is-only-partially-observable.warrant.json
# Markdown SHA-256:   cba4d0adfbc5225e7506c549d4032d8b5a69f848bac680d5e5c34512071e5090
# Code AST SHA-256:   f3236b6dae371c6a766862870837cb124c03def49a4b7af5b0bc18c76f5ca132
# Verified Classes:   ContractCommitError, Provenance, FieldCommit, ContractLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import Callable, Any

class ContractCommitError(RuntimeError):
    """Raised when an agent attempts to commit to a peer contract
    using a load-bearing field that was inferred rather than observed."""

class Provenance(Enum):
    OBSERVED = "observed"   # came from the peer's advertised schema
    ASSUMED  = "assumed"    # inferred from name/description/prior

@dataclass
class FieldCommit:
    name: str
    provenance: Provenance
    load_bearing: bool
    falsifier: Callable[[Any], bool] | None = None

@dataclass
class ContractLedger:
    peer: str
    fields: dict[str, FieldCommit] = field(default_factory=dict)

    def record(self, fc: FieldCommit) -> None:
        self.fields[fc.name] = fc

    def commit(self) -> None:
        """Validate the ledger before binding execution to the peer contract."""
        for fc in self.fields.values():
            if fc.provenance is Provenance.ASSUMED and fc.load_bearing:
                if fc.falsifier is None:
                    raise ContractCommitError(
                        f"peer={self.peer!r} field={fc.name!r}: "
                        "load-bearing field is ASSUMED with no falsifier; "
                        "refusing commitment (probe, or surface the gap)."
                    )
        # Commit is valid: every load-bearing assumption carries a falsifier
        # that will run against the peer's response before the result is trusted.

def negotiate_and_commit(manifest: dict, ledger: ContractLedger) -> None:
    # The manifest only exposes schema_hint (field names), not types/units.
    hint = manifest["tools"][0].get("schema_hint", "")
    for name in [h.strip() for h in hint.split(",") if h.strip()]:
        # `amount` is load-bearing (a unit) and only inferred -> must falsify.
        load_bearing = name in {"amount", "from", "to"}
        ledger.record(FieldCommit(
            name=name,
            provenance=Provenance.ASSUMED,
            load_bearing=load_bearing,
            falsifier=None,  # planner skipped describe_tool: no falsifier built
        ))
    ledger.commit()  # raises ContractCommitError on the `amount` field
