From 98bae2765f9538862063f097f429c6daf300e3a4 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 27 Nov 2026 19:33:08 -0500 Subject: [PATCH 1/2] feat(sdk): add 2-line openadapt.wrap Python SDK Add openadapt.wrap_sdk (lazy-exported as openadapt.wrap, WrapResult, WrapBlockedError, WrapVerificationError, WrapReceipt, and WrapLedger) using only the Python standard library at import time: - Wrap sync functions, async coroutines, callable instances, and agent objects exposing .run or .step while preserving signatures via functools.wraps. - Enforce operator-pinned keys and required identity_keys before executing wrapped callables. - Track in-memory or file-backed uncertain writes and idempotent request_id replays with explicit .release(key) recovery. - Verify post-action outcomes via same_screen callables by default or openadapt.verify.Contract when supplied, attaching SHA-256 and optional Ed25519 receipts. --- README.md | 16 + openadapt/__init__.py | 36 + openadapt/wrap_sdk.py | 2100 ++++++++++++++++++++++++++++++++++ tests/test_openadapt_wrap.py | 539 +++++++++ 4 files changed, 2691 insertions(+) create mode 100644 openadapt/wrap_sdk.py create mode 100644 tests/test_openadapt_wrap.py diff --git a/README.md b/README.md index 6b7630e71f..750bf725be 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,22 @@ brew install openadaptai/tap/openadapt For browser workflows with zero CLI setup, install the 1-click Chrome extension: **[OpenAdapt Co-Pilot on the Chrome Web Store](https://chromewebstore.google.com/detail/openadapt-co-pilot/bcpliibliddclnibacbjbmbpgffkjefd)**. +### Wrap Any Python Agent or Tool in 2 Lines + +Add pinned record checks, duplicate-submit protection on uncertain writes, same-screen verification, and SHA-256 or Ed25519 receipts to any Python function, Playwright helper, MCP tool, or agent with zero YAML files: + +```python +import openadapt + +safe_save = openadapt.wrap( + save_chart_note, + pinned={"patient_id": "PT-104"}, + check=lambda out, *a, **kw: out.get("saved") is True, +) +safe_save(patient_id="PT-104", note="Follow-up scheduled") +print(safe_save.last_receipt["outcome"], safe_save.last_receipt["checked_how"]) # confirmed same_screen +``` + ### Try It in 30 Seconds Run the local smoke test against a bundled demo server (no account or API key required), or trigger a deliberate drift to inspect a halted run and its signed receipt: diff --git a/openadapt/__init__.py b/openadapt/__init__.py index 7244776cce..fb9705c45d 100644 --- a/openadapt/__init__.py +++ b/openadapt/__init__.py @@ -120,6 +120,32 @@ def __getattr__(name: str): "Install with: pip install openadapt-kernel" ) + # Lightweight 2-line Python SDK wrapper (stdlib-only at import time) + if name in ( + "wrap", + "WrapResult", + "WrapReceipt", + "WrapError", + "WrapBlockedError", + "WrapVerificationError", + "WrapLedger", + "WrapOutcome", + "verify_wrap_receipt", + ): + from openadapt.wrap_sdk import ( # noqa: F401 + WrapBlockedError, + WrapError, + WrapLedger, + WrapOutcome, + WrapReceipt, + WrapResult, + WrapVerificationError, + verify_wrap_receipt, + wrap, + ) + + return locals()[name] + # Demo library lives in openadapt-evals if name == "DemoLibrary": try: @@ -137,6 +163,16 @@ def __getattr__(name: str): __all__ = [ "__version__", + # 2-line Python SDK wrapper + "wrap", + "WrapResult", + "WrapReceipt", + "WrapError", + "WrapBlockedError", + "WrapVerificationError", + "WrapLedger", + "WrapOutcome", + "verify_wrap_receipt", # From kernel (canonical runtime) "CommitInterceptor", "ObligationLedger", diff --git a/openadapt/wrap_sdk.py b/openadapt/wrap_sdk.py new file mode 100644 index 0000000000..2355f1aea3 --- /dev/null +++ b/openadapt/wrap_sdk.py @@ -0,0 +1,2100 @@ +"""Two-line Python SDK wrapper for action functions, tools, and agents. + +``openadapt.wrap`` adds identity pinning, uncertain-write retry protection, +post-action verification (defaulting to ``same_screen`` with no reload or API +requirement, or delegating to an ``openadapt.verify.Contract`` when supplied), +and SHA-256 or Ed25519 receipts to any Python callable or agent object without +requiring YAML configuration files. + +Example:: + + import openadapt + + safe_save = openadapt.wrap( + save_chart_note, + check=lambda out, *a, **kw: out.get("saved") is True, + pinned={"patient_id": "PT-104"}, + ) +""" + +from __future__ import annotations + +import asyncio +import base64 +import enum +import functools +import hashlib +import inspect +import json +import os +import tempfile +import threading +from collections.abc import Iterator, Mapping, Sequence +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from types import MappingProxyType +from typing import Any, Callable, Literal, TypeVar + +__all__ = [ + "VALID_CHECKED_HOW", + "WrapBlockedError", + "WrapError", + "WrapLedger", + "WrapOutcome", + "WrapReceipt", + "WrapResult", + "WrapVerificationError", + "WrappedAgentProxy", + "verify_wrap_receipt", + "wrap", +] + +F = TypeVar("F", bound=Callable[..., Any]) + +RECEIPT_SCHEMA = "openadapt.wrap_receipt/v1" +SIGNING_DOMAIN = b"openadapt.wrap_receipt/v1\n" + +VALID_CHECKED_HOW: tuple[str, ...] = ( + "same_screen", + "reopened", + "separate_session", + "system_of_record", + "unchecked", +) + + +class WrapOutcome(str, enum.Enum): + """Outcome recorded on a ``WrapReceipt``.""" + + CONFIRMED = "confirmed" + REFUTED = "refuted" + UNCERTAIN = "uncertain" + BLOCKED = "blocked" + UNCHECKED = "unchecked" + + +class _BlockMode(str, enum.Enum): + RAISE = "raise" + RETURN = "return" + + +class _LedgerState(str, enum.Enum): + IN_FLIGHT = "in_flight" + CONFIRMED = "confirmed" + UNCHECKED = "unchecked" + UNCERTAIN = "uncertain" + REFUTED = "refuted" + + +_OUTCOME_TOKENS: dict[str, WrapOutcome] = { + "confirmed": WrapOutcome.CONFIRMED, + "ok": WrapOutcome.CONFIRMED, + "true": WrapOutcome.CONFIRMED, + "refuted": WrapOutcome.REFUTED, + "false": WrapOutcome.REFUTED, + "uncertain": WrapOutcome.UNCERTAIN, + "unknown": WrapOutcome.UNCERTAIN, + "blocked": WrapOutcome.BLOCKED, + "unchecked": WrapOutcome.UNCHECKED, +} + +_MODE_TOKENS: dict[str, _BlockMode] = { + "raise": _BlockMode.RAISE, + "return": _BlockMode.RETURN, +} + +_CONTRACT_CHECKED_HOW: dict[str, str] = { + "sql": "system_of_record", + "database": "system_of_record", + "rest": "system_of_record", + "graphql": "system_of_record", + "fhir": "system_of_record", + "file": "system_of_record", + "fs": "system_of_record", + "document": "system_of_record", + "email": "system_of_record", + "ui_readback": "separate_session", + "fresh_session": "separate_session", + "onscreen": "same_screen", + "desktop_readback": "same_screen", +} + + +def _utc_now_iso() -> str: + return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + + +def _to_json_safe(value: Any) -> tuple[Any, bool]: + """Convert *value* into deterministic JSON-compatible data. + + Returns ``(converted_value, exact)`` where ``exact`` is ``True`` only when + primitive JSON types were preserved losslessly for cross-process replay. + """ + if value is None or isinstance(value, (str, int, float, bool)): + return value, True + if isinstance(value, (list, tuple)): + items = [] + exact = isinstance(value, list) + for item in value: + conv, item_exact = _to_json_safe(item) + items.append(conv) + exact = exact and item_exact + return items, exact + if isinstance(value, Mapping): + out: dict[str, Any] = {} + exact = type(value) is dict + for k, v in value.items(): + if not isinstance(k, str): + exact = False + conv, item_exact = _to_json_safe(v) + out[str(k)] = conv + exact = exact and item_exact + return out, exact + if isinstance(value, Path): + return value.as_posix(), False + if isinstance(value, enum.Enum): + conv, _ = _to_json_safe(value.value) + return conv, False + return repr(value), False + + +def _canonical_bytes(payload: Any) -> bytes: + safe, _ = _to_json_safe(payload) + return json.dumps( + safe, + sort_keys=True, + separators=(",", ":"), + ensure_ascii=True, + ).encode("utf-8") + + +def _sha256_hex(payload: Any) -> str: + if isinstance(payload, bytes): + return hashlib.sha256(payload).hexdigest() + return hashlib.sha256(_canonical_bytes(payload)).hexdigest() + + +def _values_equal(left: Any, right: Any) -> bool: + """Compare values without treating ``bool`` as ``int`` (``True != 1``).""" + if isinstance(left, bool) or isinstance(right, bool): + return type(left) is type(right) and left == right + if isinstance(left, (list, tuple)) and isinstance(right, (list, tuple)): + if len(left) != len(right): + return False + return all(_values_equal(a, b) for a, b in zip(left, right)) + if isinstance(left, Mapping) and isinstance(right, Mapping): + if set(left.keys()) != set(right.keys()): + return False + return all(_values_equal(left[k], right[k]) for k in left) + return bool(left == right) + + +def _load_signing_key(signing_key: Any) -> Any: + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + + if isinstance(signing_key, Ed25519PrivateKey): + return signing_key + if isinstance(signing_key, (bytes, bytearray)): + raw = bytes(signing_key) + if len(raw) == 32: + return Ed25519PrivateKey.from_private_bytes(raw) + return serialization.load_pem_private_key(raw, password=None) + if isinstance(signing_key, Path) or ( + isinstance(signing_key, str) and Path(signing_key).is_file() + ): + pem = Path(signing_key).read_bytes() + return serialization.load_pem_private_key(pem, password=None) + if isinstance(signing_key, str): + stripped = signing_key.strip() + if len(stripped) == 64: + try: + return Ed25519PrivateKey.from_private_bytes(bytes.fromhex(stripped)) + except ValueError: + pass + return serialization.load_pem_private_key( + stripped.encode("utf-8"), password=None + ) + raise TypeError( + "signing_key must be an Ed25519PrivateKey, 32-byte seed, 64-char hex seed, or PEM path" + ) + + +def _load_public_key(public_key: Any) -> Any: + from cryptography.hazmat.primitives import serialization + from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey + + if isinstance(public_key, Ed25519PublicKey): + return public_key + if isinstance(public_key, (bytes, bytearray)): + raw = bytes(public_key) + if len(raw) == 32: + return Ed25519PublicKey.from_public_bytes(raw) + return serialization.load_pem_public_key(raw) + if isinstance(public_key, str): + stripped = public_key.strip() + if len(stripped) == 64: + try: + return Ed25519PublicKey.from_public_bytes(bytes.fromhex(stripped)) + except ValueError: + pass + try: + decoded = base64.b64decode(stripped, validate=True) + if len(decoded) == 32: + return Ed25519PublicKey.from_public_bytes(decoded) + except ValueError: + pass + return serialization.load_pem_public_key(stripped.encode("utf-8")) + raise TypeError( + "public_key must be an Ed25519PublicKey, 32-byte key, hex/base64 string, or PEM" + ) + + +@dataclass(frozen=True) +class WrapReceipt(Mapping[str, Any]): + """Tamper-evident receipt attached as ``wrapped.last_receipt``. + + Supports both attribute access (``receipt.outcome``, ``receipt.sha256``) and + mapping lookup (``receipt["outcome"]``, ``receipt.get("checked_how")``). + """ + + schema: str + outcome: str + checked_how: str + timestamp: str + action: str + request_key: str + arguments_sha256: str + dispatched: bool + replayed: bool + identity: Mapping[str, Any] + declared_by: Mapping[str, str] + reason: str + contract_receipt_sha256: str | None + sha256: str + signature: str | None = None + public_key: str | None = None + + @property + def ok(self) -> bool: + """True when the action succeeded and was not blocked, refuted, or uncertain.""" + return self.outcome in ( + WrapOutcome.CONFIRMED.value, + WrapOutcome.UNCHECKED.value, + ) + + @property + def verified(self) -> bool: + """True only when a post-action check or contract confirmed the outcome.""" + return ( + self.outcome == WrapOutcome.CONFIRMED.value + and self.checked_how != "unchecked" + ) + + def payload_for_digest(self) -> dict[str, Any]: + """Return the canonical dictionary covered by ``sha256`` and ``signature``.""" + return { + "schema": self.schema, + "outcome": self.outcome, + "checked_how": self.checked_how, + "timestamp": self.timestamp, + "action": self.action, + "request_key": self.request_key, + "arguments_sha256": self.arguments_sha256, + "dispatched": self.dispatched, + "replayed": self.replayed, + "identity": dict(self.identity), + "declared_by": dict(self.declared_by), + "reason": self.reason, + "contract_receipt_sha256": self.contract_receipt_sha256, + } + + def to_dict(self) -> dict[str, Any]: + """Serialize the full receipt including digest and optional signature.""" + body = self.payload_for_digest() + body["sha256"] = self.sha256 + body["signature"] = self.signature + body["public_key"] = self.public_key + return body + + def verify(self, public_key: Any = None) -> bool: + """Verify ``sha256`` integrity and optional Ed25519 ``signature``.""" + return verify_wrap_receipt(self, public_key=public_key) + + def __getitem__(self, key: str) -> Any: + return self.to_dict()[key] + + def __iter__(self) -> Iterator[str]: + return iter(self.to_dict()) + + def __len__(self) -> int: + return len(self.to_dict()) + + +def _build_receipt( + *, + outcome: WrapOutcome, + checked_how: str, + action: str, + request_key: str, + arguments_sha256: str, + dispatched: bool, + replayed: bool = False, + identity: Mapping[str, Any] | None = None, + declared_by: Mapping[str, str] | None = None, + reason: str = "", + contract_receipt_sha256: str | None = None, + signing_key: Any = None, +) -> WrapReceipt: + safe_identity, _ = _to_json_safe(dict(identity or {})) + safe_declared = {str(k): str(v) for k, v in (declared_by or {}).items()} + timestamp = _utc_now_iso() + payload = { + "schema": RECEIPT_SCHEMA, + "outcome": outcome.value, + "checked_how": checked_how, + "timestamp": timestamp, + "action": action, + "request_key": request_key, + "arguments_sha256": arguments_sha256, + "dispatched": dispatched, + "replayed": replayed, + "identity": safe_identity, + "declared_by": safe_declared, + "reason": reason, + "contract_receipt_sha256": contract_receipt_sha256, + } + canonical = _canonical_bytes(payload) + digest = hashlib.sha256(canonical).hexdigest() + signature_b64: str | None = None + public_hex: str | None = None + if signing_key is not None: + from cryptography.hazmat.primitives import serialization + + priv = _load_signing_key(signing_key) + sig_bytes = priv.sign(SIGNING_DOMAIN + canonical) + signature_b64 = base64.b64encode(sig_bytes).decode("ascii") + pub_bytes = priv.public_key().public_bytes( + encoding=serialization.Encoding.Raw, + format=serialization.PublicFormat.Raw, + ) + public_hex = pub_bytes.hex() + return WrapReceipt( + schema=RECEIPT_SCHEMA, + outcome=outcome.value, + checked_how=checked_how, + timestamp=timestamp, + action=action, + request_key=request_key, + arguments_sha256=arguments_sha256, + dispatched=dispatched, + replayed=replayed, + identity=MappingProxyType(dict(safe_identity)), + declared_by=MappingProxyType(safe_declared), + reason=reason, + contract_receipt_sha256=contract_receipt_sha256, + sha256=digest, + signature=signature_b64, + public_key=public_hex, + ) + + +def verify_wrap_receipt( + receipt: WrapReceipt | Mapping[str, Any], + *, + public_key: Any = None, +) -> bool: + """Verify the SHA-256 digest (and Ed25519 signature when present or required).""" + data = receipt.to_dict() if isinstance(receipt, WrapReceipt) else dict(receipt) + claimed_sha = data.get("sha256") + if not isinstance(claimed_sha, str) or len(claimed_sha) != 64: + return False + payload = { + "schema": data.get("schema"), + "outcome": data.get("outcome"), + "checked_how": data.get("checked_how"), + "timestamp": data.get("timestamp"), + "action": data.get("action"), + "request_key": data.get("request_key"), + "arguments_sha256": data.get("arguments_sha256"), + "dispatched": data.get("dispatched"), + "replayed": data.get("replayed"), + "identity": data.get("identity") or {}, + "declared_by": data.get("declared_by") or {}, + "reason": data.get("reason") or "", + "contract_receipt_sha256": data.get("contract_receipt_sha256"), + } + canonical = _canonical_bytes(payload) + if hashlib.sha256(canonical).hexdigest() != claimed_sha: + return False + signature = data.get("signature") + if public_key is None and signature is None: + return True + if not isinstance(signature, str) or not signature: + return False + key_source = public_key if public_key is not None else data.get("public_key") + if key_source is None: + return False + from cryptography.exceptions import InvalidSignature + + try: + pub = _load_public_key(key_source) + sig_bytes = base64.b64decode(signature, validate=True) + pub.verify(sig_bytes, SIGNING_DOMAIN + canonical) + except (InvalidSignature, ValueError, TypeError): + return False + return True + + +@dataclass(frozen=True) +class WrapResult: + """Envelope returned when ``return_receipt=True`` (or ``on_block="return"``).""" + + value: Any + receipt: WrapReceipt + blocked: bool = False + + @property + def ok(self) -> bool: + return not self.blocked and self.receipt.ok + + @property + def verified(self) -> bool: + return not self.blocked and self.receipt.verified + + @property + def outcome(self) -> str: + return self.receipt.outcome + + def to_dict(self) -> dict[str, Any]: + safe_val, _ = _to_json_safe(self.value) + return { + "ok": self.ok, + "verified": self.verified, + "blocked": self.blocked, + "outcome": self.outcome, + "value": safe_val, + "receipt": self.receipt.to_dict(), + } + + +class WrapError(RuntimeError): + """Base exception for ``openadapt.wrap`` refusals and verification failures.""" + + def __init__( + self, + reason: str, + *, + code: str, + key: str = "", + receipt: WrapReceipt | None = None, + ) -> None: + super().__init__(reason) + self.reason = reason + self.code = code + self.key = key + self.receipt = receipt + + +class WrapBlockedError(WrapError): + """Raised before executing the wrapped callable when a guard blocks the write.""" + + +class WrapVerificationError(WrapError): + """Raised after execution when post-action verification is refuted or uncertain.""" + + def __init__( + self, + reason: str, + *, + code: str, + key: str = "", + receipt: WrapReceipt | None = None, + value: Any = None, + ) -> None: + super().__init__(reason, code=code, key=key, receipt=receipt) + self.value = value + + +@dataclass +class _LedgerEntry: + key: str + action: str + arguments_sha256: str + state: _LedgerState + has_live_value: bool = False + live_value: Any = None + json_value: Any = None + json_exact: bool = False + checked_how: str = "unchecked" + reason: str = "" + updated_at: str = "" + + def to_json(self) -> dict[str, Any]: + return { + "key": self.key, + "action": self.action, + "arguments_sha256": self.arguments_sha256, + "state": self.state.value, + "json_value": self.json_value, + "json_exact": self.json_exact, + "checked_how": self.checked_how, + "reason": self.reason, + "updated_at": self.updated_at, + } + + @classmethod + def from_json(cls, raw: Mapping[str, Any]) -> _LedgerEntry: + raw_state = str(raw.get("state") or _LedgerState.UNCERTAIN.value) + try: + state = _LedgerState(raw_state) + except ValueError: + state = _LedgerState.UNCERTAIN + if state is _LedgerState.IN_FLIGHT: + # An in-flight attempt from a previous process never recorded its end; + # treat it as uncertain until an operator releases the key. + state = _LedgerState.UNCERTAIN + return cls( + key=str(raw.get("key") or ""), + action=str(raw.get("action") or ""), + arguments_sha256=str(raw.get("arguments_sha256") or ""), + state=state, + has_live_value=False, + live_value=None, + json_value=raw.get("json_value"), + json_exact=bool(raw.get("json_exact", False)), + checked_how=str(raw.get("checked_how") or "unchecked"), + reason=str(raw.get("reason") or ""), + updated_at=str(raw.get("updated_at") or ""), + ) + + +class WrapLedger: + """Thread-safe uncertain-write and idempotent-request ledger. + + Operates in memory by default, or persists entries atomically to a local + JSON file when ``path`` is supplied. + """ + + def __init__(self, path: str | Path | None = None) -> None: + self.path = Path(path).expanduser() if path is not None else None + self._lock = threading.RLock() + self._entries: dict[str, _LedgerEntry] = {} + if self.path is not None and self.path.exists(): + self._load() + + def _load(self) -> None: + assert self.path is not None + raw = json.loads(self.path.read_text(encoding="utf-8")) + entries = raw.get("entries", {}) if isinstance(raw, Mapping) else {} + if not isinstance(entries, Mapping): + raise ValueError(f"corrupt wrap ledger at {self.path}") + for key, item in entries.items(): + if isinstance(item, Mapping): + self._entries[str(key)] = _LedgerEntry.from_json(item) + + def _persist(self) -> None: + if self.path is None: + return + self.path.parent.mkdir(parents=True, exist_ok=True) + body = json.dumps( + { + "schema": "openadapt.wrap_ledger/v1", + "entries": {k: v.to_json() for k, v in sorted(self._entries.items())}, + }, + indent=2, + sort_keys=True, + ).encode("utf-8") + fd, tmp_name = tempfile.mkstemp( + dir=str(self.path.parent), + prefix=f".{self.path.name}.", + suffix=".tmp", + ) + try: + with os.fdopen(fd, "wb") as handle: + handle.write(body) + handle.flush() + os.fsync(handle.fileno()) + try: + os.chmod(tmp_name, 0o600) + except OSError: + pass + os.replace(tmp_name, self.path) + except BaseException: + try: + os.unlink(tmp_name) + except OSError: + pass + raise + + def preflight( + self, + *, + key: str, + action: str, + arguments_sha256: str, + deduplicate_completed: bool, + block_uncertain: bool, + ) -> tuple[str, _LedgerEntry | None]: + """Inspect and reserve *key* prior to action dispatch. + + Returns ``(decision, entry)`` where ``decision`` is one of: + ``"proceed"``, ``"replay"``, ``"conflict"``, ``"in_flight"``, + ``"uncertain_latched"``, or ``"refuted_latched"``. + """ + with self._lock: + existing = self._entries.get(key) + if existing is not None: + if ( + deduplicate_completed + and existing.arguments_sha256 != arguments_sha256 + ): + return "conflict", existing + if existing.state is _LedgerState.IN_FLIGHT and deduplicate_completed: + return "in_flight", existing + if existing.state is _LedgerState.UNCERTAIN and block_uncertain: + return "uncertain_latched", existing + if existing.state is _LedgerState.REFUTED and block_uncertain: + return "refuted_latched", existing + if deduplicate_completed and existing.state in ( + _LedgerState.CONFIRMED, + _LedgerState.UNCHECKED, + ): + if existing.has_live_value or existing.json_exact: + return "replay", existing + if deduplicate_completed or self.path is not None: + self._entries[key] = _LedgerEntry( + key=key, + action=action, + arguments_sha256=arguments_sha256, + state=_LedgerState.IN_FLIGHT, + updated_at=_utc_now_iso(), + ) + self._persist() + return "proceed", None + + def record_completed( + self, + *, + key: str, + action: str, + arguments_sha256: str, + outcome: WrapOutcome, + checked_how: str, + value: Any, + keep_completed: bool, + ) -> None: + with self._lock: + if not keep_completed: + if ( + key in self._entries + and self._entries[key].state is _LedgerState.IN_FLIGHT + ): + self._entries.pop(key, None) + self._persist() + return + state = ( + _LedgerState.CONFIRMED + if outcome is WrapOutcome.CONFIRMED + else _LedgerState.UNCHECKED + ) + json_val, exact = _to_json_safe(value) + self._entries[key] = _LedgerEntry( + key=key, + action=action, + arguments_sha256=arguments_sha256, + state=state, + has_live_value=True, + live_value=value, + json_value=json_val, + json_exact=exact, + checked_how=checked_how, + updated_at=_utc_now_iso(), + ) + self._persist() + + def record_non_confirmed( + self, + *, + key: str, + action: str, + arguments_sha256: str, + state: _LedgerState, + checked_how: str, + reason: str, + latch: bool, + ) -> None: + with self._lock: + if not latch: + if ( + key in self._entries + and self._entries[key].state is _LedgerState.IN_FLIGHT + ): + self._entries.pop(key, None) + self._persist() + return + self._entries[key] = _LedgerEntry( + key=key, + action=action, + arguments_sha256=arguments_sha256, + state=state, + checked_how=checked_how, + reason=reason, + updated_at=_utc_now_iso(), + ) + self._persist() + + def release(self, key: str | None = None, *, action: str | None = None) -> int: + """Clear latched uncertain or refuted entries so a reconciled retry can run.""" + with self._lock: + if key is not None: + removed = 1 if self._entries.pop(key, None) is not None else 0 + if removed: + self._persist() + return removed + to_delete = [ + k + for k, entry in self._entries.items() + if entry.state + in ( + _LedgerState.UNCERTAIN, + _LedgerState.REFUTED, + _LedgerState.IN_FLIGHT, + ) + and (action is None or entry.action == action) + ] + for k in to_delete: + self._entries.pop(k, None) + if to_delete: + self._persist() + return len(to_delete) + + +def _resolve_ledger(ledger: WrapLedger | str | Path | None) -> WrapLedger: + if ledger is None: + return WrapLedger() + if isinstance(ledger, WrapLedger): + return ledger + if isinstance(ledger, (str, Path)): + return WrapLedger(ledger) + raise TypeError("ledger must be a WrapLedger, file path, or None") + + +def _callable_check_arity( + check_fn: Callable[..., Any], +) -> Literal["zero", "one", "full"]: + try: + sig = inspect.signature(check_fn) + except (TypeError, ValueError): + return "one" + pos_count = 0 + for param in sig.parameters.values(): + if param.kind in ( + inspect.Parameter.VAR_POSITIONAL, + inspect.Parameter.VAR_KEYWORD, + ): + return "full" + if param.kind in ( + inspect.Parameter.POSITIONAL_ONLY, + inspect.Parameter.POSITIONAL_OR_KEYWORD, + ): + pos_count += 1 + if pos_count == 0: + return "zero" + if pos_count == 1: + return "one" + return "full" + + +def _interpret_check_output( + raw: Any, + default_checked_how: str, +) -> tuple[WrapOutcome, str, str]: + """Normalize a ``check(...)`` return value into ``(outcome, checked_how, reason)``.""" + if isinstance(raw, bool): + if raw: + return WrapOutcome.CONFIRMED, default_checked_how, "" + return ( + WrapOutcome.REFUTED, + default_checked_how, + "post-action check returned False", + ) + + if isinstance(raw, str): + token = raw.strip().lower() + mapped = _OUTCOME_TOKENS.get(token) + if mapped is WrapOutcome.CONFIRMED: + return WrapOutcome.CONFIRMED, default_checked_how, "" + if mapped is WrapOutcome.REFUTED: + return ( + WrapOutcome.REFUTED, + default_checked_how, + f"post-action check returned {raw!r}", + ) + if mapped is WrapOutcome.UNCERTAIN: + return ( + WrapOutcome.UNCERTAIN, + default_checked_how, + "post-action check returned uncertain", + ) + return ( + WrapOutcome.UNCERTAIN, + default_checked_how, + f"unrecognized post-action check status {raw!r}", + ) + + if isinstance(raw, Mapping): + how = str(raw.get("checked_how") or default_checked_how) + if how not in VALID_CHECKED_HOW: + return ( + WrapOutcome.UNCERTAIN, + default_checked_how, + f"invalid checked_how {how!r}", + ) + reason = str(raw.get("reason") or raw.get("detail") or "") + if "outcome" in raw: + token = str(raw.get("outcome") or "").strip().lower() + mapped = _OUTCOME_TOKENS.get(token, WrapOutcome.UNCERTAIN) + if mapped is WrapOutcome.CONFIRMED and how == "unchecked": + return ( + WrapOutcome.UNCERTAIN, + "unchecked", + reason or "unchecked cannot certify a confirmed write", + ) + if mapped in ( + WrapOutcome.CONFIRMED, + WrapOutcome.REFUTED, + WrapOutcome.UNCERTAIN, + ): + if not reason and mapped is not WrapOutcome.CONFIRMED: + reason = f"post-action check reported {mapped.value}" + return mapped, how, reason + return ( + WrapOutcome.UNCERTAIN, + how, + reason or f"unsupported check outcome {raw.get('outcome')!r}", + ) + if "ok" in raw: + ok_val = raw.get("ok") + if ok_val is True: + if how == "unchecked": + return ( + WrapOutcome.UNCERTAIN, + "unchecked", + reason or "unchecked cannot certify a confirmed write", + ) + return WrapOutcome.CONFIRMED, how, reason + if ok_val is False: + return ( + WrapOutcome.REFUTED, + how, + reason or "post-action check mapping reported ok=False", + ) + return ( + WrapOutcome.UNCERTAIN, + how, + reason or f"post-action check ok={ok_val!r} is uncertain", + ) + return ( + WrapOutcome.UNCERTAIN, + how, + reason or "post-action check mapping must include 'ok' or 'outcome'", + ) + + return ( + WrapOutcome.UNCERTAIN, + default_checked_how, + f"post-action check must return bool, status string, or Mapping, got {type(raw).__name__}", + ) + + +def _run_sync_check( + check_fn: Callable[..., Any], + arity: Literal["zero", "one", "full"], + value: Any, + call_args: tuple[Any, ...], + call_kwargs: Mapping[str, Any], + default_checked_how: str, +) -> tuple[Any, str, str, Exception | None]: + try: + if arity == "zero": + raw = check_fn() + elif arity == "one": + raw = check_fn(value) + else: + raw = check_fn(value, *call_args, **call_kwargs) + except AssertionError as exc: + return ( + WrapOutcome.REFUTED, + default_checked_how, + str(exc) or "post-action check assertion failed", + exc, + ) + except Exception as exc: + return ( + "unknown", + default_checked_how, + f"post-action check raised {type(exc).__name__}: {exc}", + exc, + ) + if inspect.isawaitable(raw): + close = getattr(raw, "close", None) + if callable(close): + close() + raise TypeError( + "async check callable requires wrapping an async coroutine function" + ) + outcome, how, reason = _interpret_check_output(raw, default_checked_how) + return outcome, how, reason, None + + +async def _run_async_check( + check_fn: Callable[..., Any], + arity: Literal["zero", "one", "full"], + value: Any, + call_args: tuple[Any, ...], + call_kwargs: Mapping[str, Any], + default_checked_how: str, +) -> tuple[Any, str, str, Exception | None]: + try: + if arity == "zero": + raw = check_fn() + elif arity == "one": + raw = check_fn(value) + else: + raw = check_fn(value, *call_args, **call_kwargs) + if inspect.isawaitable(raw): + raw = await raw + except AssertionError as exc: + return ( + WrapOutcome.REFUTED, + default_checked_how, + str(exc) or "post-action check assertion failed", + exc, + ) + except Exception as exc: + return ( + "unknown", + default_checked_how, + f"post-action check raised {type(exc).__name__}: {exc}", + exc, + ) + outcome, how, reason = _interpret_check_output(raw, default_checked_how) + return outcome, how, reason, None + + +def _normalize_check_tuple( + raw_tuple: tuple[Any, str, str, Exception | None], +) -> tuple[WrapOutcome, str, str, Exception | None]: + raw_outcome, how, reason, err = raw_tuple + if isinstance(raw_outcome, WrapOutcome): + return raw_outcome, how, reason, err + return WrapOutcome.UNCERTAIN, how, reason, err + + +class _ContractBridge: + """Lazy bridge to ``openadapt_flow.verifier`` when ``contract=`` is supplied.""" + + def __init__( + self, + contract_spec: Any, + *, + agent_id: str, + workdir: str | Path | None, + ) -> None: + from openadapt_flow.verifier import Contract, MemoryLedger + + if isinstance(contract_spec, Contract): + self.contract = contract_spec + elif isinstance(contract_spec, (str, Path)): + self.contract = Contract.load(contract_spec) + elif isinstance(contract_spec, Mapping): + self.contract = Contract.from_dict(contract_spec) + else: + raise TypeError( + "contract must be a verify.yaml path, Mapping, or openadapt.verify.Contract" + ) + self.agent_id = agent_id + self.workdir = Path(workdir).expanduser() if workdir is not None else None + self.ledger = MemoryLedger() + self.params = tuple(self.contract.params) + kind = str(self.contract.config.verifier.kind).replace("-", "_") + self.checked_how = _CONTRACT_CHECKED_HOW.get(kind, "system_of_record") + + def begin( + self, + flat_args: Mapping[str, Any], + pinned: Mapping[str, Any], + explicit_request_id: str | None, + ) -> Any: + from openadapt_flow.verifier import ( + Actor, + VerifierError, + WriteBlocked, + begin_write, + ) + + values: dict[str, Any] = {} + declared_by: dict[str, str] = {} + for param_name in self.params: + if param_name in pinned: + values[param_name] = pinned[param_name] + declared_by[param_name] = "operator" + elif param_name in flat_args: + values[param_name] = flat_args[param_name] + declared_by[param_name] = "caller" + else: + raise WrapBlockedError( + f"missing required contract parameter {param_name!r}", + code="missing_contract_param", + ) + try: + return begin_write( + self.contract, + values, + actor=Actor("agent", self.agent_id), + ledger=self.ledger, + write_key=explicit_request_id, + workdir=self.workdir, + declared_by=declared_by, + ) + except (WriteBlocked, VerifierError) as exc: + raise WrapBlockedError( + str(exc), + code="contract_preflight_blocked", + key=getattr(exc, "key", "") or (explicit_request_id or ""), + ) from exc + + def verify( + self, pending: Any, *, attempted: bool + ) -> tuple[WrapOutcome, str, str | None]: + from openadapt_flow.verifier import Outcome, verify_write + + write_res = verify_write(pending, write_attempted=attempted) + receipt_sha = write_res.receipt_sha256 or None + if write_res.outcome is Outcome.CONFIRMED: + return WrapOutcome.CONFIRMED, "", receipt_sha + if write_res.outcome is Outcome.REFUTED: + return ( + WrapOutcome.REFUTED, + write_res.reason or "contract read-back refuted the write", + receipt_sha, + ) + return ( + WrapOutcome.UNCERTAIN, + write_res.reason or "contract read-back was uncertain", + receipt_sha, + ) + + +def _is_async_callable(fn: Any) -> bool: + if inspect.iscoroutinefunction(fn): + return True + if not inspect.isfunction(fn) and not inspect.ismethod(fn): + dunder_call = getattr(fn, "__call__", None) + if dunder_call is not None and inspect.iscoroutinefunction(dunder_call): + return True + return False + + +class _InvocationPlan: + """Prepared arguments, identity bindings, and ledger keys for one call.""" + + __slots__ = ( + "arguments_sha256", + "call_args", + "call_kwargs", + "declared_by", + "explicit_request_id", + "flat_args", + "identity", + "request_key", + ) + + def __init__( + self, + *, + call_args: tuple[Any, ...], + call_kwargs: dict[str, Any], + flat_args: dict[str, Any], + identity: dict[str, Any], + declared_by: dict[str, str], + explicit_request_id: str | None, + request_key: str, + arguments_sha256: str, + ) -> None: + self.call_args = call_args + self.call_kwargs = call_kwargs + self.flat_args = flat_args + self.identity = identity + self.declared_by = declared_by + self.explicit_request_id = explicit_request_id + self.request_key = request_key + self.arguments_sha256 = arguments_sha256 + + +class _CallableGuard: + """Core commit-boundary guard shared by sync and async callable wrappers.""" + + def __init__( + self, + fn: Callable[..., Any], + *, + action_name: str, + check_fn: Callable[..., Any] | None, + checked_how: str | None, + pinned: Mapping[str, Any], + identity_keys: tuple[str, ...], + contract_bridge: _ContractBridge | None, + ledger: WrapLedger, + idempotent: bool, + block_uncertain_retries: bool, + return_receipt: bool, + block_mode: _BlockMode, + unverified_mode: _BlockMode, + signing_key: Any, + on_receipt: Callable[[WrapReceipt], None] | None = None, + ) -> None: + self.fn = fn + self.action_name = action_name + self.check_fn = check_fn + self.check_arity = ( + _callable_check_arity(check_fn) if check_fn is not None else "one" + ) + self.contract_bridge = contract_bridge + if checked_how is not None: + self.default_checked_how = checked_how + elif contract_bridge is not None: + self.default_checked_how = contract_bridge.checked_how + elif check_fn is not None: + self.default_checked_how = "same_screen" + else: + self.default_checked_how = "unchecked" + self.pinned = dict(pinned) + self.identity_keys = identity_keys + self.ledger = ledger + self.idempotent = idempotent + self.block_uncertain_retries = block_uncertain_retries + self.return_receipt = return_receipt + self.block_mode = block_mode + self.unverified_mode = unverified_mode + self.signing_key = signing_key + self.on_receipt = on_receipt + self.last_receipt: WrapReceipt | None = None + + try: + self.signature: inspect.Signature | None = inspect.signature(fn) + except (TypeError, ValueError): + self.signature = None + + self.has_var_keyword = False + self.param_names: frozenset[str] = frozenset() + self.required_missing_pins: dict[str, Any] = {} + if self.signature is not None: + names: list[str] = [] + for p_name, param in self.signature.parameters.items(): + if param.kind is inspect.Parameter.VAR_KEYWORD: + self.has_var_keyword = True + else: + names.append(p_name) + if ( + p_name in self.pinned + and param.default is inspect.Parameter.empty + and param.kind + in ( + inspect.Parameter.POSITIONAL_OR_KEYWORD, + inspect.Parameter.KEYWORD_ONLY, + ) + ): + self.required_missing_pins[p_name] = self.pinned[p_name] + self.param_names = frozenset(names) + + def _emit_receipt(self, receipt: WrapReceipt) -> WrapReceipt: + self.last_receipt = receipt + if self.on_receipt is not None: + self.on_receipt(receipt) + return receipt + + def _refuse( + self, + *, + reason: str, + code: str, + request_key: str, + arguments_sha256: str, + identity: Mapping[str, Any], + declared_by: Mapping[str, str], + cause: BaseException | None = None, + ) -> Any: + receipt = self._emit_receipt( + _build_receipt( + outcome=WrapOutcome.BLOCKED, + checked_how="unchecked", + action=self.action_name, + request_key=request_key, + arguments_sha256=arguments_sha256, + dispatched=False, + identity=identity, + declared_by=declared_by, + reason=reason, + signing_key=self.signing_key, + ) + ) + if self.block_mode is _BlockMode.RETURN: + if self.return_receipt: + return WrapResult(value=None, receipt=receipt, blocked=True) + return { + "ok": False, + "verified": False, + "blocked": True, + "code": code, + "outcome": receipt.outcome, + "reason": reason, + "request_key": request_key, + "receipt": receipt.to_dict(), + } + err = WrapBlockedError(reason, code=code, key=request_key, receipt=receipt) + if cause is not None: + raise err from cause + raise err + + def _prepare_call( + self, args: tuple[Any, ...], kwargs: dict[str, Any] + ) -> _InvocationPlan: + working_kwargs = dict(kwargs) + explicit_request_id: str | None = None + if "request_id" in working_kwargs: + raw_req = working_kwargs["request_id"] + if raw_req is not None: + if not isinstance(raw_req, str) or not raw_req.strip(): + raise ValueError("request_id must be a non-empty string") + explicit_request_id = raw_req.strip() + if not self.has_var_keyword and "request_id" not in self.param_names: + working_kwargs.pop("request_id", None) + + extra_pinned_supplied: dict[str, Any] = {} + if not self.has_var_keyword and self.signature is not None: + for p_key in list(working_kwargs): + if p_key in self.pinned and p_key not in self.param_names: + extra_pinned_supplied[p_key] = working_kwargs.pop(p_key) + + flat_args: dict[str, Any] = {} + explicit_supplied: dict[str, Any] = dict(extra_pinned_supplied) + call_args = args + call_kwargs = working_kwargs + + if self.signature is not None: + partial = self.signature.bind_partial(*call_args, **call_kwargs) + for b_name, b_val in partial.arguments.items(): + param = self.signature.parameters[b_name] + if param.kind is inspect.Parameter.VAR_KEYWORD: + explicit_supplied.update(b_val) + elif param.kind is not inspect.Parameter.VAR_POSITIONAL: + explicit_supplied[b_name] = b_val + + for req_pin, pin_val in self.required_missing_pins.items(): + if req_pin not in explicit_supplied and req_pin not in call_kwargs: + call_kwargs[req_pin] = pin_val + + bound = self.signature.bind(*call_args, **call_kwargs) + bound.apply_defaults() + for b_name, b_val in bound.arguments.items(): + param = self.signature.parameters[b_name] + if param.kind is inspect.Parameter.VAR_KEYWORD: + flat_args.update(b_val) + elif param.kind is inspect.Parameter.VAR_POSITIONAL: + flat_args[b_name] = list(b_val) + else: + flat_args[b_name] = b_val + else: + if call_args: + flat_args["_args"] = list(call_args) + flat_args.update(call_kwargs) + explicit_supplied.update(call_kwargs) + + canonical_arg_payload = { + "action": self.action_name, + "arguments": flat_args, + "pinned": self.pinned, + } + arguments_sha256 = _sha256_hex(canonical_arg_payload) + request_key = explicit_request_id or arguments_sha256 + + identity: dict[str, Any] = {} + declared_by: dict[str, str] = {} + for k, pin_val in self.pinned.items(): + identity[k] = pin_val + declared_by[k] = "operator" + for id_key in self.identity_keys: + if id_key not in identity and id_key in flat_args: + identity[id_key] = flat_args[id_key] + declared_by[id_key] = "caller" + + # 1. Enforce operator-pinned keys before any side effect can execute. + for pin_key, expected_val in self.pinned.items(): + if pin_key in explicit_supplied and not _values_equal( + explicit_supplied[pin_key], expected_val + ): + observed_identity = dict(identity) + observed_identity[pin_key] = explicit_supplied[pin_key] + raise _PreCallRefusal( + reason=( + f"pinned key {pin_key!r} mismatch: operator pinned " + f"{expected_val!r}, caller supplied {explicit_supplied[pin_key]!r}" + ), + code="pinned_mismatch", + request_key=request_key, + arguments_sha256=arguments_sha256, + identity=observed_identity, + declared_by=declared_by, + ) + if pin_key in flat_args and not _values_equal( + flat_args[pin_key], expected_val + ): + raise _PreCallRefusal( + reason=( + f"pinned key {pin_key!r} mismatch: operator pinned " + f"{expected_val!r}, default resolved to {flat_args[pin_key]!r}" + ), + code="pinned_mismatch", + request_key=request_key, + arguments_sha256=arguments_sha256, + identity=identity, + declared_by=declared_by, + ) + + # 2. Require non-empty values for every configured identity key. + for id_key in self.identity_keys: + val = identity.get(id_key, flat_args.get(id_key)) + if val is None or (isinstance(val, str) and not val.strip()): + raise _PreCallRefusal( + reason=f"required identity key {id_key!r} is missing or empty", + code="missing_identity", + request_key=request_key, + arguments_sha256=arguments_sha256, + identity=identity, + declared_by=declared_by, + ) + + return _InvocationPlan( + call_args=call_args, + call_kwargs=call_kwargs, + flat_args=flat_args, + identity=identity, + declared_by=declared_by, + explicit_request_id=explicit_request_id, + request_key=request_key, + arguments_sha256=arguments_sha256, + ) + + def _preflight_ledger(self, plan: _InvocationPlan) -> tuple[bool, Any]: + deduplicate = self.idempotent or (plan.explicit_request_id is not None) + decision, entry = self.ledger.preflight( + key=plan.request_key, + action=self.action_name, + arguments_sha256=plan.arguments_sha256, + deduplicate_completed=deduplicate, + block_uncertain=self.block_uncertain_retries, + ) + if decision == "proceed": + return False, None + if decision == "replay" and entry is not None: + cached_val = entry.live_value if entry.has_live_value else entry.json_value + replay_outcome = ( + WrapOutcome.CONFIRMED + if entry.state is _LedgerState.CONFIRMED + else WrapOutcome.UNCHECKED + ) + receipt = self._emit_receipt( + _build_receipt( + outcome=replay_outcome, + checked_how=entry.checked_how, + action=self.action_name, + request_key=plan.request_key, + arguments_sha256=plan.arguments_sha256, + dispatched=False, + replayed=True, + identity=plan.identity, + declared_by=plan.declared_by, + signing_key=self.signing_key, + ) + ) + if self.return_receipt: + return True, WrapResult(value=cached_val, receipt=receipt) + return True, cached_val + + reasons = { + "conflict": ( + "request_id_conflict", + f"request_id {plan.request_key!r} was already used with different arguments", + ), + "in_flight": ( + "in_flight_duplicate", + f"write {plan.request_key!r} is already in progress; refusing duplicate dispatch", + ), + "uncertain_latched": ( + "uncertain_write_blocked", + f"earlier write {plan.request_key!r} had an uncertain outcome; " + "inspect the target record and call .release(key) before retrying", + ), + "refuted_latched": ( + "refuted_write_blocked", + f"earlier write {plan.request_key!r} failed post-action verification; " + "inspect the target record and call .release(key) before retrying", + ), + } + code, reason = reasons.get( + decision, + ("ledger_blocked", f"write {plan.request_key!r} blocked by ledger"), + ) + return True, self._refuse( + reason=reason, + code=code, + request_key=plan.request_key, + arguments_sha256=plan.arguments_sha256, + identity=plan.identity, + declared_by=plan.declared_by, + ) + + def _record_midflight_exception( + self, + plan: _InvocationPlan, + exc: BaseException, + pending_contract: Any, + ) -> None: + contract_sha: str | None = None + if self.contract_bridge is not None and pending_contract is not None: + c_outcome, c_reason, contract_sha = self.contract_bridge.verify( + pending_contract, attempted=True + ) + reason = f"action raised {type(exc).__name__}: {exc}" + ( + f" ({c_reason})" if c_reason else "" + ) + latch_state = ( + _LedgerState.REFUTED + if c_outcome is WrapOutcome.REFUTED + else _LedgerState.UNCERTAIN + ) + rec_outcome = ( + WrapOutcome.REFUTED + if c_outcome is WrapOutcome.REFUTED + else WrapOutcome.UNCERTAIN + ) + how = self.contract_bridge.checked_how + else: + reason = f"action raised {type(exc).__name__}: {exc}" + latch_state = _LedgerState.UNCERTAIN + rec_outcome = WrapOutcome.UNCERTAIN + how = "unchecked" + + self.ledger.record_non_confirmed( + key=plan.request_key, + action=self.action_name, + arguments_sha256=plan.arguments_sha256, + state=latch_state, + checked_how=how, + reason=reason, + latch=self.block_uncertain_retries + or self.idempotent + or (plan.explicit_request_id is not None), + ) + self._emit_receipt( + _build_receipt( + outcome=rec_outcome, + checked_how=how, + action=self.action_name, + request_key=plan.request_key, + arguments_sha256=plan.arguments_sha256, + dispatched=True, + identity=plan.identity, + declared_by=plan.declared_by, + reason=reason, + contract_receipt_sha256=contract_sha, + signing_key=self.signing_key, + ) + ) + + def _finalize_post_action( + self, + *, + plan: _InvocationPlan, + value: Any, + outcome: WrapOutcome, + checked_how: str, + reason: str, + contract_sha: str | None, + check_err: Exception | None, + ) -> Any: + deduplicate = self.idempotent or (plan.explicit_request_id is not None) + if outcome in (WrapOutcome.CONFIRMED, WrapOutcome.UNCHECKED): + self.ledger.record_completed( + key=plan.request_key, + action=self.action_name, + arguments_sha256=plan.arguments_sha256, + outcome=outcome, + checked_how=checked_how, + value=value, + keep_completed=deduplicate, + ) + receipt = self._emit_receipt( + _build_receipt( + outcome=outcome, + checked_how=checked_how, + action=self.action_name, + request_key=plan.request_key, + arguments_sha256=plan.arguments_sha256, + dispatched=True, + identity=plan.identity, + declared_by=plan.declared_by, + reason=reason, + contract_receipt_sha256=contract_sha, + signing_key=self.signing_key, + ) + ) + if self.return_receipt: + return WrapResult(value=value, receipt=receipt) + return value + + latch_state = ( + _LedgerState.REFUTED + if outcome is WrapOutcome.REFUTED + else _LedgerState.UNCERTAIN + ) + self.ledger.record_non_confirmed( + key=plan.request_key, + action=self.action_name, + arguments_sha256=plan.arguments_sha256, + state=latch_state, + checked_how=checked_how, + reason=reason, + latch=self.block_uncertain_retries or deduplicate, + ) + receipt = self._emit_receipt( + _build_receipt( + outcome=outcome, + checked_how=checked_how, + action=self.action_name, + request_key=plan.request_key, + arguments_sha256=plan.arguments_sha256, + dispatched=True, + identity=plan.identity, + declared_by=plan.declared_by, + reason=reason, + contract_receipt_sha256=contract_sha, + signing_key=self.signing_key, + ) + ) + if self.unverified_mode is _BlockMode.RETURN: + if self.return_receipt: + return WrapResult(value=value, receipt=receipt, blocked=False) + return value + + code = ( + "verification_refuted" + if outcome is WrapOutcome.REFUTED + else "verification_uncertain" + ) + err = WrapVerificationError( + reason or f"post-action verification {outcome.value}", + code=code, + key=plan.request_key, + receipt=receipt, + value=value, + ) + if check_err is not None: + raise err from check_err + raise err + + def call_sync(self, *args: Any, **kwargs: Any) -> Any: + try: + plan = self._prepare_call(args, kwargs) + except _PreCallRefusal as stop: + return self._refuse( + reason=stop.reason, + code=stop.code, + request_key=stop.request_key, + arguments_sha256=stop.arguments_sha256, + identity=stop.identity, + declared_by=stop.declared_by, + ) + + short_circuit, early_return = self._preflight_ledger(plan) + if short_circuit: + return early_return + + pending_contract: Any = None + if self.contract_bridge is not None: + try: + pending_contract = self.contract_bridge.begin( + plan.flat_args, self.pinned, plan.explicit_request_id + ) + except WrapBlockedError as exc: + self.ledger.release(plan.request_key) + return self._refuse( + reason=exc.reason, + code=exc.code, + request_key=plan.request_key, + arguments_sha256=plan.arguments_sha256, + identity=plan.identity, + declared_by=plan.declared_by, + cause=exc.__cause__, + ) + + try: + value = self.fn(*plan.call_args, **plan.call_kwargs) + if inspect.isawaitable(value): + close = getattr(value, "close", None) + if callable(close): + close() + raise TypeError( + f"{self.action_name} returned an awaitable; define it with async def" + ) + except BaseException as exc: + self._record_midflight_exception(plan, exc, pending_contract) + raise + + outcome = WrapOutcome.UNCHECKED + how = self.default_checked_how + reason = "" + contract_sha: str | None = None + check_err: Exception | None = None + + if self.contract_bridge is not None and pending_contract is not None: + outcome, reason, contract_sha = self.contract_bridge.verify( + pending_contract, attempted=True + ) + how = self.default_checked_how + + if self.check_fn is not None and ( + self.contract_bridge is None or outcome is WrapOutcome.CONFIRMED + ): + c_outcome, c_how, c_reason, check_err = _normalize_check_tuple( + _run_sync_check( + self.check_fn, + self.check_arity, + value, + plan.call_args, + plan.call_kwargs, + "same_screen" + if self.default_checked_how == "unchecked" + else self.default_checked_how, + ) + ) + outcome = c_outcome + if self.contract_bridge is None: + how = c_how + if c_reason: + reason = c_reason + + return self._finalize_post_action( + plan=plan, + value=value, + outcome=outcome, + checked_how=how, + reason=reason, + contract_sha=contract_sha, + check_err=check_err, + ) + + async def call_async(self, *args: Any, **kwargs: Any) -> Any: + try: + plan = self._prepare_call(args, kwargs) + except _PreCallRefusal as stop: + return self._refuse( + reason=stop.reason, + code=stop.code, + request_key=stop.request_key, + arguments_sha256=stop.arguments_sha256, + identity=stop.identity, + declared_by=stop.declared_by, + ) + + short_circuit, early_return = self._preflight_ledger(plan) + if short_circuit: + return early_return + + pending_contract: Any = None + if self.contract_bridge is not None: + try: + pending_contract = await asyncio.to_thread( + self.contract_bridge.begin, + plan.flat_args, + self.pinned, + plan.explicit_request_id, + ) + except WrapBlockedError as exc: + self.ledger.release(plan.request_key) + return self._refuse( + reason=exc.reason, + code=exc.code, + request_key=plan.request_key, + arguments_sha256=plan.arguments_sha256, + identity=plan.identity, + declared_by=plan.declared_by, + cause=exc.__cause__, + ) + + try: + value = await self.fn(*plan.call_args, **plan.call_kwargs) + except BaseException as exc: + if self.contract_bridge is not None and pending_contract is not None: + await asyncio.to_thread( + self._record_midflight_exception, plan, exc, pending_contract + ) + else: + self._record_midflight_exception(plan, exc, None) + raise + + outcome = WrapOutcome.UNCHECKED + how = self.default_checked_how + reason = "" + contract_sha: str | None = None + check_err: Exception | None = None + + if self.contract_bridge is not None and pending_contract is not None: + outcome, reason, contract_sha = await asyncio.to_thread( + self.contract_bridge.verify, pending_contract, attempted=True + ) + how = self.default_checked_how + + if self.check_fn is not None and ( + self.contract_bridge is None or outcome is WrapOutcome.CONFIRMED + ): + c_outcome, c_how, c_reason, check_err = _normalize_check_tuple( + await _run_async_check( + self.check_fn, + self.check_arity, + value, + plan.call_args, + plan.call_kwargs, + "same_screen" + if self.default_checked_how == "unchecked" + else self.default_checked_how, + ) + ) + outcome = c_outcome + if self.contract_bridge is None: + how = c_how + if c_reason: + reason = c_reason + + return self._finalize_post_action( + plan=plan, + value=value, + outcome=outcome, + checked_how=how, + reason=reason, + contract_sha=contract_sha, + check_err=check_err, + ) + + +class _PreCallRefusal(Exception): + def __init__( + self, + *, + reason: str, + code: str, + request_key: str, + arguments_sha256: str, + identity: Mapping[str, Any], + declared_by: Mapping[str, str], + ) -> None: + super().__init__(reason) + self.reason = reason + self.code = code + self.request_key = request_key + self.arguments_sha256 = arguments_sha256 + self.identity = identity + self.declared_by = declared_by + + +def _build_wrapped_callable( + fn: Callable[..., Any], + *, + action_name: str, + check_fn: Callable[..., Any] | None, + checked_how: str | None, + pinned: Mapping[str, Any], + identity_keys: tuple[str, ...], + contract_bridge: _ContractBridge | None, + ledger: WrapLedger, + idempotent: bool, + block_uncertain_retries: bool, + return_receipt: bool, + block_mode: _BlockMode, + unverified_mode: _BlockMode, + signing_key: Any, + on_receipt: Callable[[WrapReceipt], None] | None = None, +) -> Callable[..., Any]: + assigned = tuple(a for a in functools.WRAPPER_ASSIGNMENTS if hasattr(fn, a)) + + def _attach_wrapper_attrs(wrapper: Any, guard: _CallableGuard) -> Any: + if not hasattr(fn, "__name__"): + wrapper.__name__ = action_name.rsplit(".", 1)[-1] + if not hasattr(fn, "__qualname__"): + wrapper.__qualname__ = action_name + if guard.signature is not None: + wrapper.__signature__ = guard.signature + wrapper.__wrapped__ = fn + wrapper.ledger = ledger + wrapper.pinned = MappingProxyType(dict(pinned)) + wrapper.identity_keys = identity_keys + wrapper.last_receipt = None + wrapper.release = lambda key=None: ledger.release( + key, action=None if key is not None else action_name + ) + return wrapper + + if _is_async_callable(fn): + + @functools.wraps(fn, assigned=assigned) + async def _async_wrapped(*args: Any, **kwargs: Any) -> Any: + return await guard.call_async(*args, **kwargs) + + def _update_async_receipt(receipt: WrapReceipt) -> None: + _async_wrapped.last_receipt = receipt # type: ignore[attr-defined] + if on_receipt is not None: + on_receipt(receipt) + + guard = _CallableGuard( + fn, + action_name=action_name, + check_fn=check_fn, + checked_how=checked_how, + pinned=pinned, + identity_keys=identity_keys, + contract_bridge=contract_bridge, + ledger=ledger, + idempotent=idempotent, + block_uncertain_retries=block_uncertain_retries, + return_receipt=return_receipt, + block_mode=block_mode, + unverified_mode=unverified_mode, + signing_key=signing_key, + on_receipt=_update_async_receipt, + ) + return _attach_wrapper_attrs(_async_wrapped, guard) + + @functools.wraps(fn, assigned=assigned) + def _sync_wrapped(*args: Any, **kwargs: Any) -> Any: + return guard.call_sync(*args, **kwargs) + + def _update_sync_receipt(receipt: WrapReceipt) -> None: + _sync_wrapped.last_receipt = receipt # type: ignore[attr-defined] + if on_receipt is not None: + on_receipt(receipt) + + guard = _CallableGuard( + fn, + action_name=action_name, + check_fn=check_fn, + checked_how=checked_how, + pinned=pinned, + identity_keys=identity_keys, + contract_bridge=contract_bridge, + ledger=ledger, + idempotent=idempotent, + block_uncertain_retries=block_uncertain_retries, + return_receipt=return_receipt, + block_mode=block_mode, + unverified_mode=unverified_mode, + signing_key=signing_key, + on_receipt=_update_sync_receipt, + ) + return _attach_wrapper_attrs(_sync_wrapped, guard) + + +class WrappedAgentProxy: + """Non-mutating proxy wrapping an agent or runner object's ``.run`` / ``.step``.""" + + def __init__( + self, + target: Any, + *, + base_name: str, + check_fn: Callable[..., Any] | None, + checked_how: str | None, + pinned: Mapping[str, Any], + identity_keys: tuple[str, ...], + contract_bridge: _ContractBridge | None, + ledger: WrapLedger, + idempotent: bool, + block_uncertain_retries: bool, + return_receipt: bool, + block_mode: _BlockMode, + unverified_mode: _BlockMode, + signing_key: Any, + ) -> None: + object.__setattr__(self, "__wrapped__", target) + object.__setattr__(self, "ledger", ledger) + object.__setattr__(self, "pinned", MappingProxyType(dict(pinned))) + object.__setattr__(self, "identity_keys", identity_keys) + object.__setattr__(self, "last_receipt", None) + + wrapped_methods: list[str] = [] + + def _record_agent_receipt(receipt: WrapReceipt) -> None: + object.__setattr__(self, "last_receipt", receipt) + + for method_name in ("run", "arun", "step", "astep"): + raw_method = getattr(target, method_name, None) + if callable(raw_method): + wrapped_methods.append(method_name) + wrapped_fn = _build_wrapped_callable( + raw_method, + action_name=f"{base_name}.{method_name}", + check_fn=check_fn, + checked_how=checked_how, + pinned=pinned, + identity_keys=identity_keys, + contract_bridge=contract_bridge, + ledger=ledger, + idempotent=idempotent, + block_uncertain_retries=block_uncertain_retries, + return_receipt=return_receipt, + block_mode=block_mode, + unverified_mode=unverified_mode, + signing_key=signing_key, + on_receipt=_record_agent_receipt, + ) + object.__setattr__(self, method_name, wrapped_fn) + + if not wrapped_methods: + raise TypeError( + "openadapt.wrap target must be callable or expose a callable .run or .step method" + ) + object.__setattr__(self, "_wrapped_methods", tuple(wrapped_methods)) + + def release(self, key: str | None = None) -> int: + """Release a latched uncertain or refuted write key on this wrapped agent.""" + return self.ledger.release(key) + + def __getattr__(self, item: str) -> Any: + return getattr(object.__getattribute__(self, "__wrapped__"), item) + + def __repr__(self) -> str: + inner = object.__getattribute__(self, "__wrapped__") + return f"WrappedAgentProxy({inner!r})" + + +def wrap( + target: Any = None, + *, + check: Callable[..., Any] | None = None, + expect: Callable[..., Any] | None = None, + checked_how: str | None = None, + pinned: Mapping[str, Any] | None = None, + identity_keys: Sequence[str] = (), + contract: Any = None, + ledger: WrapLedger | str | Path | None = None, + idempotent: bool = False, + block_uncertain_retries: bool = True, + return_receipt: bool = False, + on_block: Literal["raise", "return"] = "raise", + on_unverified: Literal["raise", "return"] | None = None, + signing_key: Any = None, + agent_id: str = "agent", + workdir: str | Path | None = None, + name: str | None = None, +) -> Any: + """Wrap a Python function, coroutine, tool, or agent with commit-boundary checks. + + Supports both direct calls (``safe_fn = openadapt.wrap(fn, ...)``) and + decorator syntax (``@openadapt.wrap`` or ``@openadapt.wrap(pinned=...)``). + """ + if check is not None and expect is not None: + raise ValueError("pass either check= or expect=, not both") + resolved_check = check if check is not None else expect + if resolved_check is not None and not callable(resolved_check): + raise TypeError("check must be callable or None") + + if checked_how is not None: + if checked_how not in VALID_CHECKED_HOW: + raise ValueError( + f"checked_how must be one of {VALID_CHECKED_HOW}, got {checked_how!r}" + ) + if resolved_check is not None and checked_how == "unchecked": + raise ValueError( + "checked_how cannot be 'unchecked' when a post-action check is supplied" + ) + + if isinstance(identity_keys, (str, bytes)): + raise TypeError( + "identity_keys must be a sequence of parameter names, not a string" + ) + resolved_identity_keys = tuple(dict.fromkeys(str(k) for k in identity_keys)) + resolved_pinned = dict(pinned or {}) + + block_mode = _MODE_TOKENS.get(str(on_block).strip().lower()) + if block_mode is None: + raise ValueError("on_block must be 'raise' or 'return'") + + if on_unverified is None: + unverified_mode = ( + _BlockMode.RETURN + if (return_receipt or block_mode is _BlockMode.RETURN) + else _BlockMode.RAISE + ) + else: + maybe_mode = _MODE_TOKENS.get(str(on_unverified).strip().lower()) + if maybe_mode is None: + raise ValueError("on_unverified must be 'raise' or 'return'") + unverified_mode = maybe_mode + + if signing_key is not None: + signing_key = _load_signing_key(signing_key) + + resolved_ledger = _resolve_ledger(ledger) + contract_bridge = ( + _ContractBridge(contract, agent_id=agent_id, workdir=workdir) + if contract is not None + else None + ) + + def _apply(obj: Any) -> Any: + if callable(obj) and not inspect.isclass(obj): + action_name = ( + name + or getattr(obj, "__qualname__", None) + or getattr(obj, "__name__", None) + or type(obj).__qualname__ + ) + return _build_wrapped_callable( + obj, + action_name=action_name, + check_fn=resolved_check, + checked_how=checked_how, + pinned=resolved_pinned, + identity_keys=resolved_identity_keys, + contract_bridge=contract_bridge, + ledger=resolved_ledger, + idempotent=idempotent, + block_uncertain_retries=block_uncertain_retries, + return_receipt=return_receipt, + block_mode=block_mode, + unverified_mode=unverified_mode, + signing_key=signing_key, + ) + base_name = name or type(obj).__qualname__ + return WrappedAgentProxy( + obj, + base_name=base_name, + check_fn=resolved_check, + checked_how=checked_how, + pinned=resolved_pinned, + identity_keys=resolved_identity_keys, + contract_bridge=contract_bridge, + ledger=resolved_ledger, + idempotent=idempotent, + block_uncertain_retries=block_uncertain_retries, + return_receipt=return_receipt, + block_mode=block_mode, + unverified_mode=unverified_mode, + signing_key=signing_key, + ) + + if target is not None: + return _apply(target) + return _apply diff --git a/tests/test_openadapt_wrap.py b/tests/test_openadapt_wrap.py new file mode 100644 index 0000000000..e36e30dca2 --- /dev/null +++ b/tests/test_openadapt_wrap.py @@ -0,0 +1,539 @@ +"""Unit tests for the lightweight ``openadapt.wrap`` Python SDK.""" + +from __future__ import annotations + +import asyncio +import inspect +import sqlite3 +import subprocess +import sys +from pathlib import Path +from typing import Any + +import pytest + +import openadapt +from openadapt import ( + WrapBlockedError, + WrapLedger, + WrapReceipt, + WrapResult, + WrapVerificationError, + verify_wrap_receipt, +) + + +def test_lazy_export_and_stdlib_only_import() -> None: + """openadapt.wrap works with openadapt_flow blocked at import time.""" + code = ( + "import sys\n" + "sys.modules['openadapt_flow'] = None\n" + "import openadapt\n" + "assert 'openadapt.wrap_sdk' not in sys.modules\n" + "fn = openadapt.wrap(lambda x: {'x': x}, check=lambda r: r['x'] == 7)\n" + "assert fn(7) == {'x': 7}\n" + "assert fn.last_receipt.outcome == 'confirmed'\n" + "assert fn.last_receipt.checked_how == 'same_screen'\n" + ) + proc = subprocess.run( + [sys.executable, "-c", code], + cwd=str(Path(__file__).resolve().parents[1]), + capture_output=True, + text=True, + check=False, + ) + assert proc.returncode == 0, proc.stderr + + +def test_signature_and_metadata_preserved_for_sync_and_async() -> None: + """functools.wraps and __signature__ preserve exact tool inspection metadata.""" + + def save_chart_note( + patient_id: str, + note: str, + *, + urgent: bool = False, + ) -> dict[str, Any]: + """Save a clinical note to the active chart.""" + return {"saved": True, "patient_id": patient_id, "urgent": urgent} + + @openadapt.wrap + def bare_decorated(a: int, b: str = "x") -> str: + """Bare decorator form.""" + return f"{a}:{b}" + + @openadapt.wrap( + pinned={"patient_id": "PT-104"}, + check=lambda out, *a, **kw: out.get("saved") is True, + ) + async def async_save_chart(patient_id: str, note: str) -> dict[str, Any]: + """Async decorator form.""" + await asyncio.sleep(0) + return {"saved": True, "patient_id": patient_id, "note": note} + + wrapped = openadapt.wrap( + save_chart_note, + pinned={"patient_id": "PT-104"}, + check=lambda out: out["saved"] is True, + ) + + assert wrapped.__name__ == "save_chart_note" + assert wrapped.__doc__ == "Save a clinical note to the active chart." + assert inspect.signature(wrapped) == inspect.signature(save_chart_note) + assert bare_decorated.__name__ == "bare_decorated" + assert inspect.signature(bare_decorated) == inspect.signature( + bare_decorated.__wrapped__ + ) + assert inspect.iscoroutinefunction(async_save_chart) + assert inspect.signature(async_save_chart) == inspect.signature( + async_save_chart.__wrapped__ + ) + + out = wrapped("PT-104", "Follow-up in 2 weeks", urgent=True) + assert out == {"saved": True, "patient_id": "PT-104", "urgent": True} + assert isinstance(wrapped.last_receipt, WrapReceipt) + assert wrapped.last_receipt.outcome == "confirmed" + assert wrapped.last_receipt["checked_how"] == "same_screen" + assert wrapped.last_receipt.verified is True + + assert bare_decorated(3) == "3:x" + assert bare_decorated.last_receipt.outcome == "unchecked" + assert bare_decorated.last_receipt.checked_how == "unchecked" + assert bare_decorated.last_receipt.verified is False + assert bare_decorated.last_receipt.ok is True + + async_out = asyncio.run(async_save_chart("PT-104", "Vitals stable")) + assert async_out["saved"] is True + assert async_save_chart.last_receipt.outcome == "confirmed" + assert async_save_chart.last_receipt.checked_how == "same_screen" + + +def test_pinned_identity_mismatch_blocks_before_side_effect() -> None: + """Conflicting pinned values refuse before executing the wrapped function.""" + calls: list[tuple[str, str]] = [] + + def submit_order(patient_id: str, medication: str) -> dict[str, Any]: + calls.append((patient_id, medication)) + return {"submitted": True} + + safe_submit = openadapt.wrap( + submit_order, + pinned={"patient_id": "PT-104"}, + check=lambda r: r["submitted"] is True, + ) + + # Positional mismatch + with pytest.raises(WrapBlockedError, match="patient_id") as exc_info: + safe_submit("PT-999", "amoxicillin") + assert calls == [] + assert exc_info.value.code == "pinned_mismatch" + assert safe_submit.last_receipt is not None + assert safe_submit.last_receipt.outcome == "blocked" + assert safe_submit.last_receipt.dispatched is False + + # Keyword mismatch + with pytest.raises(WrapBlockedError, match="patient_id"): + safe_submit(patient_id="PT-205", medication="amoxicillin") + assert calls == [] + + # Omitted required pinned arg is filled from operator pin + result = safe_submit(medication="amoxicillin") + assert result == {"submitted": True} + assert calls == [("PT-104", "amoxicillin")] + assert safe_submit.last_receipt.declared_by["patient_id"] == "operator" + + +def test_bool_vs_int_pinned_strictness_and_on_block_return() -> None: + """True != 1 in pinned checks, and on_block='return' avoids raising.""" + executed = False + + def toggle_flag(enabled: bool) -> dict[str, Any]: + nonlocal executed + executed = True + return {"enabled": enabled} + + guarded = openadapt.wrap( + toggle_flag, + pinned={"enabled": True}, + on_block="return", + ) + refusal = guarded(1) # type: ignore[arg-type] + assert executed is False + assert refusal["ok"] is False + assert refusal["blocked"] is True + assert refusal["code"] == "pinned_mismatch" + + +def test_identity_keys_reject_blank_values() -> None: + """Configured identity_keys must be non-empty before dispatch.""" + side_effects: list[str] = [] + + def post_claim(claim_id: str, amount: int) -> dict[str, Any]: + side_effects.append(claim_id) + return {"posted": True} + + safe_post = openadapt.wrap( + post_claim, + identity_keys=("claim_id",), + check=lambda r: r["posted"], + ) + + with pytest.raises(WrapBlockedError) as exc_info: + safe_post(" ", 150) + assert exc_info.value.code == "missing_identity" + assert side_effects == [] + + ok = safe_post("CLM-88", 150) + assert ok == {"posted": True} + assert safe_post.last_receipt.identity["claim_id"] == "CLM-88" + assert safe_post.last_receipt.declared_by["claim_id"] == "caller" + + +def test_uncertain_midflight_exception_latches_until_release() -> None: + """Mid-flight exceptions latch the write key to block blind duplicate retries.""" + attempts = 0 + + def flaky_portal_submit(patient_id: str, note: str) -> dict[str, Any]: + nonlocal attempts + attempts += 1 + if attempts == 1: + raise TimeoutError("gateway timed out after POST") + return {"saved": True} + + safe_submit = openadapt.wrap( + flaky_portal_submit, + pinned={"patient_id": "PT-104"}, + check=lambda r: r["saved"] is True, + ) + + with pytest.raises(TimeoutError, match="gateway timed out"): + safe_submit("PT-104", "Discharge summary") + assert attempts == 1 + assert safe_submit.last_receipt.outcome == "uncertain" + assert safe_submit.last_receipt.dispatched is True + latched_key = safe_submit.last_receipt.request_key + + # Blind duplicate retry is blocked before flaky_portal_submit runs again + with pytest.raises(WrapBlockedError) as blocked: + safe_submit("PT-104", "Discharge summary") + assert attempts == 1 + assert blocked.value.code == "uncertain_write_blocked" + + # Releasing the key allows the operator-reconciled retry + assert safe_submit.release(latched_key) == 1 + res = safe_submit("PT-104", "Discharge summary") + assert res == {"saved": True} + assert attempts == 2 + assert safe_submit.last_receipt.outcome == "confirmed" + + +def test_uncertain_check_and_observation_error_latch_until_release() -> None: + """check() returning 'uncertain' or raising an observation error latches retries.""" + calls = 0 + mode = "uncertain_token" + + def save_record(record_id: str) -> dict[str, Any]: + nonlocal calls + calls += 1 + return {"record_id": record_id} + + def verify_screen(result: dict[str, Any]) -> Any: + if mode == "uncertain_token": + return "uncertain" + if mode == "dom_error": + raise RuntimeError("toast detached during DOM read") + return {"ok": True, "checked_how": "reopened"} + + wrapped = openadapt.wrap(save_record, check=verify_screen) + + with pytest.raises(WrapVerificationError) as err1: + wrapped("REC-1") + assert err1.value.code == "verification_uncertain" + assert wrapped.last_receipt.outcome == "uncertain" + assert calls == 1 + + with pytest.raises(WrapBlockedError): + wrapped("REC-1") + assert calls == 1 + + wrapped.release() + mode = "dom_error" + with pytest.raises(WrapVerificationError) as err2: + wrapped("REC-1") + assert err2.value.code == "verification_uncertain" + assert calls == 2 + + wrapped.release() + mode = "ok" + assert wrapped("REC-1") == {"record_id": "REC-1"} + assert calls == 3 + assert wrapped.last_receipt.outcome == "confirmed" + assert wrapped.last_receipt.checked_how == "reopened" + + +def test_idempotent_request_id_replays_without_double_execution( + tmp_path: Path, +) -> None: + """Explicit request_id caches confirmed results and rejects payload conflicts.""" + ledger_file = tmp_path / "wrap_ledger.json" + executions = 0 + + def create_invoice(account_id: str, cents: int) -> dict[str, Any]: + nonlocal executions + executions += 1 + return {"invoice_id": f"INV-{executions}", "cents": cents} + + wrapped = openadapt.wrap( + create_invoice, + ledger=ledger_file, + check=lambda r: r["cents"] > 0, + ) + + first = wrapped("ACC-1", 5000, request_id="req-inv-001") + assert first == {"invoice_id": "INV-1", "cents": 5000} + assert executions == 1 + assert wrapped.last_receipt.replayed is False + assert wrapped.last_receipt.dispatched is True + + # Retry in the same process returns cached result without calling create_invoice + second = wrapped("ACC-1", 5000, request_id="req-inv-001") + assert second == first + assert executions == 1 + assert wrapped.last_receipt.replayed is True + assert wrapped.last_receipt.dispatched is False + + # Retry from a new wrapper instance backed by the same ledger file also replays + reloaded = openadapt.wrap( + create_invoice, + ledger=ledger_file, + check=lambda r: r["cents"] > 0, + ) + third = reloaded("ACC-1", 5000, request_id="req-inv-001") + assert third == first + assert executions == 1 + assert reloaded.last_receipt.replayed is True + + # Reusing the same request_id for a different payload blocks immediately + with pytest.raises(WrapBlockedError) as conflict: + reloaded("ACC-1", 9999, request_id="req-inv-001") + assert conflict.value.code == "request_id_conflict" + assert executions == 1 + + +def test_return_receipt_and_refutation_behavior() -> None: + """return_receipt=True returns WrapResult with verified/ok flags.""" + + def save_draft(text: str) -> dict[str, Any]: + return {"saved": bool(text)} + + wrapped = openadapt.wrap( + save_draft, + check=lambda out: out["saved"] is True, + return_receipt=True, + ) + + good = wrapped("hello") + assert isinstance(good, WrapResult) + assert good.ok is True + assert good.verified is True + assert good.outcome == "confirmed" + assert good.value == {"saved": True} + + bad = wrapped("") + assert isinstance(bad, WrapResult) + assert bad.ok is False + assert bad.verified is False + assert bad.outcome == "refuted" + assert bad.receipt.reason == "post-action check returned False" + + +def test_receipt_sha256_and_ed25519_signature() -> None: + """Receipts carry deterministic SHA-256 digests and optional Ed25519 signatures.""" + from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + + signing_key = Ed25519PrivateKey.generate() + wrong_key = Ed25519PrivateKey.generate().public_key() + + safe_fn = openadapt.wrap( + lambda item_id: {"saved": True, "item_id": item_id}, + pinned={"item_id": "ITM-42"}, + check=lambda r: r["saved"] is True, + signing_key=signing_key, + ) + + out = safe_fn("ITM-42") + assert out["saved"] is True + receipt = safe_fn.last_receipt + assert len(receipt.sha256) == 64 + assert receipt.signature is not None + assert receipt.public_key is not None + assert receipt.verify() is True + assert verify_wrap_receipt(receipt, public_key=signing_key.public_key()) is True + assert verify_wrap_receipt(receipt, public_key=wrong_key) is False + + tampered = receipt.to_dict() + tampered["checked_how"] = "system_of_record" + assert verify_wrap_receipt(tampered) is False + + +def test_wrap_agent_runner_proxy_without_mutating_target() -> None: + """Non-callable agent objects with .run / .step are wrapped via a clean proxy.""" + + class MiniBrowserAgent: + def __init__(self) -> None: + self.runs: list[str] = [] + + def run(self, task: str, *, patient_id: str) -> dict[str, Any]: + self.runs.append(f"{patient_id}:{task}") + return {"done": True, "patient_id": patient_id} + + async def astep(self, action: str, *, patient_id: str) -> dict[str, Any]: + await asyncio.sleep(0) + self.runs.append(f"step:{patient_id}:{action}") + return {"done": True, "patient_id": patient_id} + + raw_agent = MiniBrowserAgent() + safe_agent = openadapt.wrap( + raw_agent, + pinned={"patient_id": "PT-104"}, + check=lambda r: r["done"] is True, + ) + + # Underlying instance is not mutated + assert "last_receipt" not in raw_agent.__dict__ + assert safe_agent.runs == [] + + with pytest.raises(WrapBlockedError): + safe_agent.run("update allergies", patient_id="PT-888") + assert raw_agent.runs == [] + + res = safe_agent.run("update allergies", patient_id="PT-104") + assert res["done"] is True + assert safe_agent.last_receipt.outcome == "confirmed" + assert ( + safe_agent.last_receipt.action + == "test_wrap_agent_runner_proxy_without_mutating_target..MiniBrowserAgent.run" + ) + + step_res = asyncio.run(safe_agent.astep("click save", patient_id="PT-104")) + assert step_res["done"] is True + assert len(raw_agent.runs) == 2 + + +def test_contract_integration_routes_through_verifier( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Passing contract= verifies writes against the system of record via verifier.py.""" + from openadapt.verify import Contract + + monkeypatch.setenv("OPENADAPT_LEDGER_DIR", str(tmp_path / "ledger")) + monkeypatch.setenv("OPENADAPT_SEAL_HOME", str(tmp_path / "seal")) + + db_path = tmp_path / "records.sqlite" + with sqlite3.connect(db_path) as conn: + conn.execute( + "CREATE TABLE notes (id INTEGER PRIMARY KEY AUTOINCREMENT, patient_id TEXT NOT NULL, body TEXT NOT NULL)" + ) + conn.commit() + + contract = Contract.from_dict( + { + "schema_version": "openadapt.verify/v1", + "verifier": { + "kind": "sql", + "sqlite_database": str(db_path), + "sql_query": "SELECT * FROM notes", + "timeout_s": 0.2, + "poll_interval_s": 0.05, + }, + "record": { + "name": "notes", + "match": ["patient_id"], + "fields": {"patient_id": "patient_id", "body": "body"}, + }, + "frame": {"identity_field": "id"}, + }, + name="save_note", + ) + + should_write = True + + def write_note(patient_id: str, body: str) -> dict[str, Any]: + if should_write: + with sqlite3.connect(db_path) as conn: + conn.execute( + "INSERT INTO notes (patient_id, body) VALUES (?, ?)", + (patient_id, body), + ) + conn.commit() + return {"submitted": True} + + safe_write = openadapt.wrap( + write_note, + contract=contract, + pinned={"patient_id": "PT-104"}, + workdir=tmp_path / "verify_work", + ) + + res = safe_write("PT-104", "Labs reviewed") + assert res == {"submitted": True} + assert safe_write.last_receipt.outcome == "confirmed" + assert safe_write.last_receipt.checked_how == "system_of_record" + assert safe_write.last_receipt.contract_receipt_sha256 is not None + + # Silent write drop is caught by the SQL contract read-back + should_write = False + unpinned_write = openadapt.wrap( + write_note, + contract=contract, + workdir=tmp_path / "verify_work_2", + ) + with pytest.raises(WrapVerificationError): + unpinned_write("PT-205", "Dropped note") + assert unpinned_write.last_receipt.outcome in ("refuted", "uncertain") + assert unpinned_write.last_receipt.checked_how == "system_of_record" + + +def test_shared_ledger_across_functions() -> None: + """A shared WrapLedger instance isolates or shares request keys cleanly.""" + shared = WrapLedger() + calls: list[str] = [] + + @openadapt.wrap(ledger=shared, idempotent=True, check=lambda r: r is True) + def step_one(record_id: str) -> bool: + calls.append(f"one:{record_id}") + return True + + @openadapt.wrap(ledger=shared, idempotent=True, check=lambda r: r is True) + def step_two(record_id: str) -> bool: + calls.append(f"two:{record_id}") + return True + + assert step_one("R-1") is True + assert step_two("R-1") is True + # Distinct function identities do not collide when request_id is omitted + assert calls == ["one:R-1", "two:R-1"] + # Calling step_one("R-1") again replays from idempotent cache + assert step_one("R-1") is True + assert calls == ["one:R-1", "two:R-1"] + + +def test_callable_agent_instance_and_expect_predicate() -> None: + """Callable agent instances and expect= predicates work with zero-arg or 1-arg checks.""" + screen_state = {"banner": "Saved chart PT-104"} + + class AsyncCallableAgent: + async def __call__(self, prompt: str, *, patient_id: str) -> str: + await asyncio.sleep(0) + return f"ran:{patient_id}:{prompt}" + + wrapped_agent = openadapt.wrap( + AsyncCallableAgent(), + pinned={"patient_id": "PT-104"}, + expect=lambda: "PT-104" in screen_state["banner"], + ) + assert wrapped_agent.__name__ == "AsyncCallableAgent" + out = asyncio.run(wrapped_agent("summarize visit", patient_id="PT-104")) + assert out == "ran:PT-104:summarize visit" + assert wrapped_agent.last_receipt.outcome == "confirmed" + assert wrapped_agent.last_receipt.checked_how == "same_screen" From 45668f75e8009afddea4b7dae8fb7439c108ca43 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 27 Nov 2026 19:45:17 -0500 Subject: [PATCH 2/2] fix(sdk): harden async check validation, ledger rollback, and proxy release scoping --- openadapt/wrap_sdk.py | 216 +++++++++++++++++++++++++---------- tests/test_openadapt_wrap.py | 112 ++++++++++++++++++ 2 files changed, 270 insertions(+), 58 deletions(-) diff --git a/openadapt/wrap_sdk.py b/openadapt/wrap_sdk.py index 2355f1aea3..14a3d7f8ff 100644 --- a/openadapt/wrap_sdk.py +++ b/openadapt/wrap_sdk.py @@ -29,7 +29,7 @@ import os import tempfile import threading -from collections.abc import Iterator, Mapping, Sequence +from collections.abc import Collection, Iterator, Mapping, Sequence from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path @@ -530,6 +530,7 @@ class _LedgerEntry: checked_how: str = "unchecked" reason: str = "" updated_at: str = "" + previous: _LedgerEntry | None = None def to_json(self) -> dict[str, Any]: return { @@ -670,10 +671,23 @@ def preflight( arguments_sha256=arguments_sha256, state=_LedgerState.IN_FLIGHT, updated_at=_utc_now_iso(), + previous=existing, ) self._persist() return "proceed", None + def abort_in_flight(self, key: str) -> None: + """Roll back an IN_FLIGHT reservation when preflight aborts before dispatch.""" + with self._lock: + current = self._entries.get(key) + if current is None or current.state is not _LedgerState.IN_FLIGHT: + return + if current.previous is not None: + self._entries[key] = current.previous + else: + self._entries.pop(key, None) + self._persist() + def record_completed( self, *, @@ -745,7 +759,13 @@ def record_non_confirmed( ) self._persist() - def release(self, key: str | None = None, *, action: str | None = None) -> int: + def release( + self, + key: str | None = None, + *, + action: str | None = None, + actions: Collection[str] | None = None, + ) -> int: """Clear latched uncertain or refuted entries so a reconciled retry can run.""" with self._lock: if key is not None: @@ -753,6 +773,7 @@ def release(self, key: str | None = None, *, action: str | None = None) -> int: if removed: self._persist() return removed + allowed_actions = set(actions) if actions is not None else None to_delete = [ k for k, entry in self._entries.items() @@ -763,6 +784,7 @@ def release(self, key: str | None = None, *, action: str | None = None) -> int: _LedgerState.IN_FLIGHT, ) and (action is None or entry.action == action) + and (allowed_actions is None or entry.action in allowed_actions) ] for k in to_delete: self._entries.pop(k, None) @@ -942,9 +964,15 @@ def _run_sync_check( close = getattr(raw, "close", None) if callable(close): close() - raise TypeError( + err = TypeError( "async check callable requires wrapping an async coroutine function" ) + return ( + "unknown", + default_checked_how, + f"post-action check returned awaitable: {err}", + err, + ) outcome, how, reason = _interpret_check_output(raw, default_checked_how) return outcome, how, reason, None @@ -1154,11 +1182,14 @@ def __init__( block_mode: _BlockMode, unverified_mode: _BlockMode, signing_key: Any, - on_receipt: Callable[[WrapReceipt], None] | None = None, + on_receipt: Callable[[WrapReceipt | None], None] | None = None, ) -> None: self.fn = fn self.action_name = action_name self.check_fn = check_fn + self.check_is_async = bool( + check_fn is not None and _is_async_callable(check_fn) + ) self.check_arity = ( _callable_check_arity(check_fn) if check_fn is not None else "one" ) @@ -1210,6 +1241,11 @@ def __init__( self.required_missing_pins[p_name] = self.pinned[p_name] self.param_names = frozenset(names) + def _clear_receipt(self) -> None: + self.last_receipt = None + if self.on_receipt is not None: + self.on_receipt(None) + def _emit_receipt(self, receipt: WrapReceipt) -> WrapReceipt: self.last_receipt = receipt if self.on_receipt is not None: @@ -1274,13 +1310,20 @@ def _prepare_call( working_kwargs.pop("request_id", None) extra_pinned_supplied: dict[str, Any] = {} + extra_identity_supplied: dict[str, Any] = {} if not self.has_var_keyword and self.signature is not None: for p_key in list(working_kwargs): - if p_key in self.pinned and p_key not in self.param_names: - extra_pinned_supplied[p_key] = working_kwargs.pop(p_key) + if p_key not in self.param_names: + if p_key in self.pinned: + extra_pinned_supplied[p_key] = working_kwargs.pop(p_key) + elif p_key in self.identity_keys: + extra_identity_supplied[p_key] = working_kwargs.pop(p_key) flat_args: dict[str, Any] = {} - explicit_supplied: dict[str, Any] = dict(extra_pinned_supplied) + explicit_supplied: dict[str, Any] = { + **extra_pinned_supplied, + **extra_identity_supplied, + } call_args = args call_kwargs = working_kwargs @@ -1313,24 +1356,29 @@ def _prepare_call( flat_args.update(call_kwargs) explicit_supplied.update(call_kwargs) + identity: dict[str, Any] = {} + declared_by: dict[str, str] = {} + for k, pin_val in self.pinned.items(): + identity[k] = pin_val + declared_by[k] = "operator" + for id_key in self.identity_keys: + if id_key not in identity: + if id_key in flat_args: + identity[id_key] = flat_args[id_key] + declared_by[id_key] = "caller" + elif id_key in extra_identity_supplied: + identity[id_key] = extra_identity_supplied[id_key] + declared_by[id_key] = "caller" + canonical_arg_payload = { "action": self.action_name, "arguments": flat_args, "pinned": self.pinned, + "identity": identity, } arguments_sha256 = _sha256_hex(canonical_arg_payload) request_key = explicit_request_id or arguments_sha256 - identity: dict[str, Any] = {} - declared_by: dict[str, str] = {} - for k, pin_val in self.pinned.items(): - identity[k] = pin_val - declared_by[k] = "operator" - for id_key in self.identity_keys: - if id_key not in identity and id_key in flat_args: - identity[id_key] = flat_args[id_key] - declared_by[id_key] = "caller" - # 1. Enforce operator-pinned keys before any side effect can execute. for pin_key, expected_val in self.pinned.items(): if pin_key in explicit_supplied and not _values_equal( @@ -1607,6 +1655,11 @@ def _finalize_post_action( raise err def call_sync(self, *args: Any, **kwargs: Any) -> Any: + self._clear_receipt() + if self.check_is_async: + raise TypeError( + "async check callable requires wrapping an async coroutine function" + ) try: plan = self._prepare_call(args, kwargs) except _PreCallRefusal as stop: @@ -1630,7 +1683,7 @@ def call_sync(self, *args: Any, **kwargs: Any) -> Any: plan.flat_args, self.pinned, plan.explicit_request_id ) except WrapBlockedError as exc: - self.ledger.release(plan.request_key) + self.ledger.abort_in_flight(plan.request_key) return self._refuse( reason=exc.reason, code=exc.code, @@ -1643,17 +1696,28 @@ def call_sync(self, *args: Any, **kwargs: Any) -> Any: try: value = self.fn(*plan.call_args, **plan.call_kwargs) - if inspect.isawaitable(value): - close = getattr(value, "close", None) - if callable(close): - close() - raise TypeError( - f"{self.action_name} returned an awaitable; define it with async def" - ) except BaseException as exc: self._record_midflight_exception(plan, exc, pending_contract) raise + if inspect.iscoroutine(value): + value.close() + self.ledger.abort_in_flight(plan.request_key) + if self.contract_bridge is not None and pending_contract is not None: + self.contract_bridge.verify(pending_contract, attempted=False) + raise TypeError( + f"{self.action_name} returned an unawaited coroutine; define it with async def" + ) + if inspect.isawaitable(value): + close = getattr(value, "close", None) + if callable(close): + close() + awaitable_err = TypeError( + f"{self.action_name} returned an awaitable; define it with async def" + ) + self._record_midflight_exception(plan, awaitable_err, pending_contract) + raise awaitable_err + outcome = WrapOutcome.UNCHECKED how = self.default_checked_how reason = "" @@ -1682,7 +1746,7 @@ def call_sync(self, *args: Any, **kwargs: Any) -> Any: ) ) outcome = c_outcome - if self.contract_bridge is None: + if self.contract_bridge is None or c_outcome is not WrapOutcome.CONFIRMED: how = c_how if c_reason: reason = c_reason @@ -1698,6 +1762,7 @@ def call_sync(self, *args: Any, **kwargs: Any) -> Any: ) async def call_async(self, *args: Any, **kwargs: Any) -> Any: + self._clear_receipt() try: plan = self._prepare_call(args, kwargs) except _PreCallRefusal as stop: @@ -1724,7 +1789,7 @@ async def call_async(self, *args: Any, **kwargs: Any) -> Any: plan.explicit_request_id, ) except WrapBlockedError as exc: - self.ledger.release(plan.request_key) + self.ledger.abort_in_flight(plan.request_key) return self._refuse( reason=exc.reason, code=exc.code, @@ -1774,7 +1839,7 @@ async def call_async(self, *args: Any, **kwargs: Any) -> Any: ) ) outcome = c_outcome - if self.contract_bridge is None: + if self.contract_bridge is None or c_outcome is not WrapOutcome.CONFIRMED: how = c_how if c_reason: reason = c_reason @@ -1826,8 +1891,19 @@ def _build_wrapped_callable( block_mode: _BlockMode, unverified_mode: _BlockMode, signing_key: Any, - on_receipt: Callable[[WrapReceipt], None] | None = None, + on_receipt: Callable[[WrapReceipt | None], None] | None = None, + allow_sync_with_async_check: bool = False, ) -> Callable[..., Any]: + is_async_fn = _is_async_callable(fn) + if ( + not is_async_fn + and check_fn is not None + and _is_async_callable(check_fn) + and not allow_sync_with_async_check + ): + raise TypeError( + "async check callable requires wrapping an async coroutine function" + ) assigned = tuple(a for a in functools.WRAPPER_ASSIGNMENTS if hasattr(fn, a)) def _attach_wrapper_attrs(wrapper: Any, guard: _CallableGuard) -> Any: @@ -1847,13 +1923,13 @@ def _attach_wrapper_attrs(wrapper: Any, guard: _CallableGuard) -> Any: ) return wrapper - if _is_async_callable(fn): + if is_async_fn: @functools.wraps(fn, assigned=assigned) async def _async_wrapped(*args: Any, **kwargs: Any) -> Any: return await guard.call_async(*args, **kwargs) - def _update_async_receipt(receipt: WrapReceipt) -> None: + def _update_async_receipt(receipt: WrapReceipt | None) -> None: _async_wrapped.last_receipt = receipt # type: ignore[attr-defined] if on_receipt is not None: on_receipt(receipt) @@ -1881,7 +1957,7 @@ def _update_async_receipt(receipt: WrapReceipt) -> None: def _sync_wrapped(*args: Any, **kwargs: Any) -> Any: return guard.call_sync(*args, **kwargs) - def _update_sync_receipt(receipt: WrapReceipt) -> None: + def _update_sync_receipt(receipt: WrapReceipt | None) -> None: _sync_wrapped.last_receipt = receipt # type: ignore[attr-defined] if on_receipt is not None: on_receipt(receipt) @@ -1933,43 +2009,67 @@ def __init__( object.__setattr__(self, "identity_keys", identity_keys) object.__setattr__(self, "last_receipt", None) - wrapped_methods: list[str] = [] - - def _record_agent_receipt(receipt: WrapReceipt) -> None: - object.__setattr__(self, "last_receipt", receipt) - + candidate_methods: list[tuple[str, Callable[..., Any]]] = [] for method_name in ("run", "arun", "step", "astep"): raw_method = getattr(target, method_name, None) if callable(raw_method): - wrapped_methods.append(method_name) - wrapped_fn = _build_wrapped_callable( - raw_method, - action_name=f"{base_name}.{method_name}", - check_fn=check_fn, - checked_how=checked_how, - pinned=pinned, - identity_keys=identity_keys, - contract_bridge=contract_bridge, - ledger=ledger, - idempotent=idempotent, - block_uncertain_retries=block_uncertain_retries, - return_receipt=return_receipt, - block_mode=block_mode, - unverified_mode=unverified_mode, - signing_key=signing_key, - on_receipt=_record_agent_receipt, - ) - object.__setattr__(self, method_name, wrapped_fn) + candidate_methods.append((method_name, raw_method)) - if not wrapped_methods: + if not candidate_methods: raise TypeError( "openadapt.wrap target must be callable or expose a callable .run or .step method" ) + + has_async_method = any(_is_async_callable(m) for _, m in candidate_methods) + if ( + check_fn is not None + and _is_async_callable(check_fn) + and not has_async_method + ): + raise TypeError( + "async check callable requires wrapping an async coroutine function" + ) + + wrapped_methods: list[str] = [] + action_names: list[str] = [] + + def _record_agent_receipt(receipt: WrapReceipt | None) -> None: + object.__setattr__(self, "last_receipt", receipt) + + for method_name, raw_method in candidate_methods: + wrapped_methods.append(method_name) + action_name = f"{base_name}.{method_name}" + action_names.append(action_name) + wrapped_fn = _build_wrapped_callable( + raw_method, + action_name=action_name, + check_fn=check_fn, + checked_how=checked_how, + pinned=pinned, + identity_keys=identity_keys, + contract_bridge=contract_bridge, + ledger=ledger, + idempotent=idempotent, + block_uncertain_retries=block_uncertain_retries, + return_receipt=return_receipt, + block_mode=block_mode, + unverified_mode=unverified_mode, + signing_key=signing_key, + on_receipt=_record_agent_receipt, + allow_sync_with_async_check=has_async_method, + ) + object.__setattr__(self, method_name, wrapped_fn) + object.__setattr__(self, "_wrapped_methods", tuple(wrapped_methods)) + object.__setattr__(self, "_action_names", frozenset(action_names)) def release(self, key: str | None = None) -> int: """Release a latched uncertain or refuted write key on this wrapped agent.""" - return self.ledger.release(key) + action_names = object.__getattribute__(self, "_action_names") + return self.ledger.release( + key, + actions=None if key is not None else action_names, + ) def __getattr__(self, item: str) -> Any: return getattr(object.__getattribute__(self, "__wrapped__"), item) diff --git a/tests/test_openadapt_wrap.py b/tests/test_openadapt_wrap.py index e36e30dca2..e3678456ba 100644 --- a/tests/test_openadapt_wrap.py +++ b/tests/test_openadapt_wrap.py @@ -537,3 +537,115 @@ async def __call__(self, prompt: str, *, patient_id: str) -> str: assert out == "ran:PT-104:summarize visit" assert wrapped_agent.last_receipt.outcome == "confirmed" assert wrapped_agent.last_receipt.checked_how == "same_screen" + + +def test_async_check_on_sync_target_and_dynamic_awaitable_handling() -> None: + """Async checks reject sync targets up front and latch safely on dynamic awaitables.""" + calls: list[str] = [] + + def sync_write(record_id: str) -> bool: + calls.append(record_id) + return True + + async def async_check(_out: Any) -> bool: + await asyncio.sleep(0) + return True + + with pytest.raises(TypeError, match="async check callable"): + openadapt.wrap(sync_write, check=async_check) + assert calls == [] + + # Dynamic awaitable returned from a non-async check after sync_write ran + # must latch UNCERTAIN and emit a fresh uncertain receipt rather than leaving + # IN_FLIGHT stuck or last_receipt stale. + def sneaky_check(_out: Any) -> Any: + return async_check(_out) + + guarded = openadapt.wrap(sync_write, check=sneaky_check, idempotent=True) + with pytest.raises(WrapVerificationError) as exc_info: + guarded("R-100") + assert calls == ["R-100"] + assert exc_info.value.code == "verification_uncertain" + assert guarded.last_receipt is not None + assert guarded.last_receipt.outcome == "uncertain" + assert guarded.last_receipt.dispatched is True + + # Retry is blocked by the uncertain latch rather than stuck in_flight + with pytest.raises(WrapBlockedError) as retry_exc: + guarded("R-100") + assert retry_exc.value.code == "uncertain_write_blocked" + + +def test_unstarted_coroutine_from_sync_wrapper_does_not_latch_dispatched() -> None: + """A sync wrapper returning an unawaited coroutine closes it without latching uncertain.""" + + async def inner_coro(x: int) -> int: + return x + 1 + + # Sync lambda returning a coroutine object + bad_sync = openadapt.wrap(lambda x: inner_coro(x), idempotent=True) + with pytest.raises(TypeError, match="unawaited coroutine"): + bad_sync(5) + assert bad_sync.last_receipt is None + + +def test_stale_last_receipt_cleared_on_bind_errors_and_extra_identity_kwargs() -> None: + """Argument binding errors clear last_receipt, and zero-arg UI helpers accept identity_keys.""" + clicks: list[str] = [] + + def click_apply() -> dict[str, bool]: + clicks.append("clicked") + return {"applied": True} + + safe_click = openadapt.wrap( + click_apply, + identity_keys=["patient_id"], + idempotent=True, + check=lambda r: r["applied"] is True, + ) + + assert safe_click(patient_id="PT-104") == {"applied": True} + assert safe_click.last_receipt is not None + assert safe_click.last_receipt.identity["patient_id"] == "PT-104" + first_key = safe_click.last_receipt.request_key + + # Distinct identity_key on zero-arg helper gets a distinct request_key + assert safe_click(patient_id="PT-205") == {"applied": True} + assert safe_click.last_receipt is not None + assert safe_click.last_receipt.request_key != first_key + assert len(clicks) == 2 + + # Invalid call clears stale last_receipt before raising TypeError / ValueError + with pytest.raises(ValueError, match="request_id"): + safe_click(patient_id="PT-205", request_id=" ") + assert safe_click.last_receipt is None + + +def test_agent_proxy_release_scopes_to_agent_actions_on_shared_ledger() -> None: + """WrappedAgentProxy.release() only clears its own actions in a shared ledger.""" + shared = WrapLedger() + + class FailingAgent: + def run(self, task: str) -> dict[str, bool]: + return {"ok": False} + + @openadapt.wrap(ledger=shared, check=lambda r: r["ok"] is True) + def other_tool(item: str) -> dict[str, bool]: + return {"ok": False} + + wrapped_agent = openadapt.wrap( + FailingAgent(), + ledger=shared, + check=lambda r: r["ok"] is True, + ) + + with pytest.raises(WrapVerificationError): + other_tool("item-1") + with pytest.raises(WrapVerificationError): + wrapped_agent.run("task-1") + + assert wrapped_agent.release() == 1 + # other_tool remains latched in the shared ledger + with pytest.raises(WrapBlockedError) as blocked_other: + other_tool("item-1") + assert blocked_other.value.code == "refuted_write_blocked"