Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1 +1 @@
| What `openadapt.wrap(agent)` counts as a verified save: the run's required values are only those the instruction asks to be written or set (`set X to 'v'`, `X should be 'v'`, `enter 'v' in X`, a numbered `X: v` list under a write request) plus the record they go to. Dates, amounts, IDs and phrases that the instruction or a pasted document only mention are tracked but never required, so they neither block nor grant `VERIFIED`. A save (a GUI or remote commit) is `VERIFIED` only when the verifier's read-back is a fresh view of the saved record, either a recorded server fetch (`fresh_view={"kind": "server_reload", "fetches": [...]}`) or a separate session, and the strict matcher proves every required value on it. A same-screen read, a toast, a wire receipt, facts proven across views or a bare `True` from a verifier no longer verify a save; `SupervisorConfig(require_fresh_view_for_saves=False)` restores the old rule. OpenAdapt checks the shape of the fetch evidence; the caller that reloads the record must observe the fetch | In PR | Unit tests (write-intent phrasings and pasted letters and forms; `5` against `Dose: 50 mg`; the wrong record; every entry point that can verify a save, crossed with no fresh view, a fresh mismatch and a fresh match). Not yet shown on a held-out real-app run | `openadapt.transducer_write_intents`, `openadapt.transducer_fresh_view`, `tests/test_transducer_fresh_view.py` |
| What `openadapt.wrap(agent)` counts as a verified save: the run's required values are only those the instruction asks to be written or set (`set X to 'v'`, `X should be 'v'`, `enter 'v' in X`, a numbered `X: v` list under a write request) plus the record they go to. Dates, amounts, IDs and phrases that the instruction or a pasted document only mention are tracked but never required, so they neither block nor grant `VERIFIED`. A save (a GUI or remote commit) is `VERIFIED` only when the verifier's read-back is a fresh view of the saved record that the runtime itself saw: while the runtime ran that check, the fetch observer attached at wrap time (`fetch_observer=`) recorded a server read answered 2xx and not from a cache (from another session, it counts as a separate session). The strict matcher must also prove every required value on that read-back. A `fresh_view` a verifier puts in its own result is ignored, and without an observer no save verifies. A same-screen read, a toast, a wire receipt, facts proven across views or a bare `True` from a verifier no longer verify a save; `SupervisorConfig(require_fresh_view_for_saves=False)` restores the old rule. The observer is supplied by the integrator (for example from the browser's network events), and the runtime asks it only about the window in which it ran the check | In PR | Unit tests (write-intent phrasings and pasted letters and forms; `5` against `Dose: 50 mg`; the wrong record; every entry point that can verify a save, crossed with no fresh view, a fresh mismatch and a fresh match; a fabricated fresh view, a read outside the check window, a cached or POST response). Shown on held-out tasks on a server-backed app before the observer rule; not yet rerun with it | `openadapt.transducer_write_intents`, `openadapt.transducer_fresh_view`, `tests/test_transducer_fresh_view.py` |
70 changes: 62 additions & 8 deletions openadapt/simplex_transducer.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import sys
import tempfile
import threading
import time
import uuid
import zlib
from collections.abc import Callable, Collection, Mapping, Sequence
Expand All @@ -34,7 +35,11 @@
is_non_gui_modality,
verifier_passed,
)
from openadapt.transducer_fresh_view import SaveEvidenceVerdict, evaluate_save_evidence
from openadapt.transducer_fresh_view import (
FetchObserver,
SaveEvidenceVerdict,
evaluate_save_evidence,
)
from openadapt.transducer_macros import MacroStore, StallRecoveryPlan
from openadapt.transducer_obligations import (
MicroHandoffResolution,
Expand Down Expand Up @@ -1686,6 +1691,8 @@ class EpisodeState:
form_latch: FormCommitLatch = field(default_factory=FormCommitLatch)
# Nesting depth of _route_action within one turn; bounds re-prompt loops.
route_depth: int = 0
# (start, end, result) of the latest check the runtime timed itself.
last_check: Any = field(default=None, repr=False)
# Latest commit index a fresh-view read-back verified (0: none), the
# verdict that did, and why the last read-back was refused.
save_evidence_commit: int = 0
Expand Down Expand Up @@ -1769,6 +1776,7 @@ def __init__(
sop_contract: Any = None,
dual_egress: Any = None,
compounding_handoff: Any = None,
fetch_observer: FetchObserver | None = None,
) -> None:
if not callable(getattr(agent, "act", None)):
raise TypeError(
Expand All @@ -1788,9 +1796,13 @@ def __init__(
)
if cartridge is not None:
self.cartridge_store.merge_cartridge(cartridge)
self.rung3_verifier = rung3_verifier
self.rung2_verifier = rung2_verifier
self.reopen_executor = reopen_executor
#: The runtime's own record of server reads (see
#: ``openadapt.transducer_fresh_view``). A save verifies only on a
#: fresh view this observer saw while the check ran.
self.fetch_observer = fetch_observer
self.rung3_verifier = self._timed_check(rung3_verifier)
self.rung2_verifier = self._timed_check(rung2_verifier)
self.reopen_executor = self._timed_check(reopen_executor)
self.pinned: dict[str, Any] = dict(pinned or {})
self._states_lock = threading.RLock()
self._states: dict[tuple[str, str], EpisodeState] = {}
Expand Down Expand Up @@ -3089,6 +3101,10 @@ def _evaluate_verification_frame(
value = _extract_attr_or_key(original, key, None)
if value is not None:
evidence[key] = value
last = state.last_check
if last is not None and last[2] is original:
with state._lock:
state.last_check = (last[0], last[1], evidence)
verdict = self._admit_save_evidence(state, evidence)
if not verdict.ok:
return False, f"Not verified: {verdict.reason}.", None
Expand All @@ -3114,14 +3130,52 @@ def _save_gate_applies(self, state: EpisodeState) -> bool:
ep = self._v3.ep(state)
return not self._v3._only_workspace_commits(state, ep)

@staticmethod
def _timed_check(fn: Any) -> Any:
"""Wrap a check so the runtime records when it ran and what it
returned; the fetch observer is asked about that window only."""

if fn is None:
return None

def timed(*args: Any, **kwargs: Any) -> Any:
start = time.time()
result = fn(*args, **kwargs)
end = time.time()
state = args[-1] if args else None
if isinstance(state, EpisodeState):
with state._lock:
state.last_check = (start, end, result)
return result

timed.__wrapped__ = fn # type: ignore[attr-defined]
return timed

def _observed_fetches(self, state: EpisodeState, result: Any) -> list[Any]:
"""Fetches the observer saw while the check that returned ``result``
ran. Empty when there is no observer, or ``result`` did not come from
a check the runtime timed (a read-back carried in an observation)."""

last = state.last_check
if self.fetch_observer is None or last is None or last[2] is not result:
return []
# An observer that raises stops the step: nothing is admitted.
return list(self.fetch_observer.fetches_between(last[0], last[1]))

def _admit_save_evidence(
self, state: EpisodeState, result: Any
) -> SaveEvidenceVerdict:
"""Judge ``result`` with :func:`evaluate_save_evidence` against the
episode's required obligations; on success, record that the latest
commit has fresh-view evidence."""

verdict = evaluate_save_evidence(self._v3.ep(state).obligations, result)
episode's required obligations and the fetches the runtime observed
while it was produced; on success, record that the latest commit has
fresh-view evidence."""

verdict = evaluate_save_evidence(
self._v3.ep(state).obligations,
result,
self._observed_fetches(state, result),
agent_session=str(getattr(self.fetch_observer, "agent_session", "") or ""),
)
with state._lock:
if verdict.ok:
state.save_evidence_commit = max(1, state.next_commit_index - 1)
Expand Down
113 changes: 73 additions & 40 deletions openadapt/transducer_fresh_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@
A save is VERIFIED only when the saved record was seen again in a fresh view
and that view shows every value the instruction asked to be written:

1. The view is fresh. Either the read-back records the server fetch that
produced it (``fresh_view={"kind": "server_reload", "fetches": [...]}``,
each fetch with a URL and a 2xx status), or it was read in a separate
session (``fresh_view={"kind": "separate_session", "session": "<id>"}``).
A same-screen read, an optimistic UI, a toast or a wire receipt is not a
fresh view. OpenAdapt checks the shape of this evidence, not how it was
gathered: the caller that reloads the record is the one that must observe
the fetch (for example from the browser's network events).
1. The view is fresh, and the runtime saw it happen. While the check that
produced the read-back ran, the runtime's own fetch observer (attached at
wrap time, ``fetch_observer=``) recorded at least one read (``GET``) the
server answered with a 2xx status, not from a cache. A fetch from a
session other than the agent's counts as a separate session. Anything a
caller puts in the read-back itself, such as a ``fresh_view`` entry, is
ignored: a same-screen read, an optimistic UI, a toast, a wire receipt or
a fabricated fetch list never makes a view fresh. Without an observer, no
save verifies.
2. The read-back is not an editable form or a toast, and the verifier that
produced it did not refuse (``verified`` is not ``False``).
3. At least one required ``write`` obligation exists, and every required
Expand All @@ -24,18 +25,20 @@

from collections.abc import Mapping, Sequence
from dataclasses import dataclass, field
from typing import Any, Literal
from typing import Any, Literal, Protocol, runtime_checkable

from openadapt.transducer_obligations import (
CompiledFieldObligation,
diff_readback_against_obligations,
)

__all__ = [
"FetchObserver",
"FreshView",
"ObservedFetch",
"SaveEvidenceVerdict",
"evaluate_save_evidence",
"fresh_view_of",
"fresh_view_from_observed",
]


Expand All @@ -45,6 +48,32 @@ class FreshView:
evidence: tuple[str, ...]


@dataclass(frozen=True)
class ObservedFetch:
"""One request the runtime's fetch observer saw, with its wall-clock time
(``time.time()``) and the session that sent it."""

method: str
url: str
status: int
at: float
from_cache: bool = False
session: str = ""


@runtime_checkable
class FetchObserver(Protocol):
"""Reports the requests it saw between two ``time.time()`` instants.

``agent_session`` names the agent's own session; a fetch from any other
session is a separate-session read.
"""

agent_session: str

def fetches_between(self, start: float, end: float) -> Sequence[ObservedFetch]: ...


@dataclass
class SaveEvidenceVerdict:
ok: bool
Expand All @@ -61,39 +90,43 @@ def _status_ok(status: Any) -> bool:
return False


def fresh_view_of(result: Any) -> FreshView | None:
"""The fresh view a read-back declares, or ``None`` when it declares none
or its evidence is malformed."""

if not isinstance(result, Mapping):
return None
view = result.get("fresh_view")
if not isinstance(view, Mapping):
def fresh_view_from_observed(
fetches: Sequence[ObservedFetch] | None, *, agent_session: str = ""
) -> FreshView | None:
"""A fresh view from fetches the runtime observed, or ``None``.

Only reads (``GET``) answered 2xx and not from a cache count. Any of them
from a session other than ``agent_session`` makes it a separate session.
"""

good = [
f
for f in fetches or ()
if isinstance(f, ObservedFetch)
and f.method.upper() == "GET"
and _status_ok(f.status)
and not f.from_cache
and f.url.strip()
]
if not good:
return None
kind = view.get("kind")
if kind == "server_reload":
fetches = view.get("fetches")
if not isinstance(fetches, Sequence) or isinstance(fetches, (str, bytes)):
return None
good = tuple(
f"{f.get('method') or 'GET'} {f.get('url')} {int(f.get('status'))}"
for f in fetches
if isinstance(f, Mapping)
and str(f.get("url") or "").strip()
and _status_ok(f.get("status"))
)
return FreshView("server_reload", good) if good else None
if kind == "separate_session":
session = str(view.get("session") or view.get("session_id") or "").strip()
return FreshView("separate_session", (session,)) if session else None
return None
evidence = tuple(f"{f.method.upper()} {f.url} {int(f.status)}" for f in good)
if any(f.session and f.session != agent_session for f in good):
return FreshView("separate_session", evidence)
return FreshView("server_reload", evidence)


def evaluate_save_evidence(
obligations: Sequence[CompiledFieldObligation], result: Any
obligations: Sequence[CompiledFieldObligation],
result: Any,
observed: Sequence[ObservedFetch] | None = None,
*,
agent_session: str = "",
) -> SaveEvidenceVerdict:
"""Whether ``result`` (a verifier's answer or a verification frame) may
verify a save against ``obligations``."""
verify a save against ``obligations``. ``observed`` holds the fetches the
runtime's observer saw while that check ran; a ``fresh_view`` entry in
``result`` is ignored."""

if not isinstance(result, Mapping):
return SaveEvidenceVerdict(
Expand All @@ -108,12 +141,12 @@ def evaluate_save_evidence(
return SaveEvidenceVerdict(False, "the read-back is a toast, not the record")
if result.get("is_editable") is True or result.get("editable") is True:
return SaveEvidenceVerdict(False, "the read-back is an editable form")
view = fresh_view_of(result)
view = fresh_view_from_observed(observed, agent_session=agent_session)
if view is None:
return SaveEvidenceVerdict(
False,
"the read-back is not a fresh view: no server fetch or separate session "
"was recorded for it",
"the read-back is not a fresh view: the runtime observed no server read "
"while the check ran",
)
text = result.get("readback_text")
if not isinstance(text, str) or not text.strip():
Expand Down
7 changes: 6 additions & 1 deletion openadapt/transducer_v3_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -944,7 +944,12 @@ def readback(
if text is None and self.owner.rung2_verifier is not None:
res = self.owner.rung2_verifier(observation, task, state)
if isinstance(res, Mapping) and res.get("readback_text") is not None:
return dict(res)
out = dict(res)
last = state.last_check
if last is not None and last[2] is res:
with state._lock:
state.last_check = (last[0], last[1], out) # same check
return out
if text is None:
return None
out = {
Expand Down
2 changes: 2 additions & 0 deletions openadapt/wrap_sdk.py
Original file line number Diff line number Diff line change
Expand Up @@ -2437,6 +2437,7 @@ def wrap(
sop_contract: Any = None,
dual_egress: Any = None,
compounding_handoff: Any = None,
fetch_observer: Any = None,
) -> Any:
"""Wrap a Python function, coroutine, tool, or agent with commit-boundary checks.

Expand Down Expand Up @@ -2538,6 +2539,7 @@ def _apply(obj: Any) -> Any:
rung3_verifier=rung3_verifier,
rung2_verifier=rung2_verifier,
reopen_executor=reopen_executor,
fetch_observer=fetch_observer,
pinned=resolved_pinned,
macro_store=macro_store,
regression_test_runner=regression_test_runner,
Expand Down
Loading
Loading