diff --git a/capabilities/10-computer-use-agents/0105-what-openadapt-wrap-agent-counts-as-a-verified-save.md b/capabilities/10-computer-use-agents/0105-what-openadapt-wrap-agent-counts-as-a-verified-save.md index f3dc394b76..bf49bd43fa 100644 --- a/capabilities/10-computer-use-agents/0105-what-openadapt-wrap-agent-counts-as-a-verified-save.md +++ b/capabilities/10-computer-use-agents/0105-what-openadapt-wrap-agent-counts-as-a-verified-save.md @@ -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` | diff --git a/openadapt/simplex_transducer.py b/openadapt/simplex_transducer.py index 79429c6c59..8cca4d12f2 100644 --- a/openadapt/simplex_transducer.py +++ b/openadapt/simplex_transducer.py @@ -19,6 +19,7 @@ import sys import tempfile import threading +import time import uuid import zlib from collections.abc import Callable, Collection, Mapping, Sequence @@ -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, @@ -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 @@ -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( @@ -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] = {} @@ -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 @@ -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) diff --git a/openadapt/transducer_fresh_view.py b/openadapt/transducer_fresh_view.py index d33c91d4e8..5bcfd2e056 100644 --- a/openadapt/transducer_fresh_view.py +++ b/openadapt/transducer_fresh_view.py @@ -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": ""}``). - 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 @@ -24,7 +25,7 @@ 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, @@ -32,10 +33,12 @@ ) __all__ = [ + "FetchObserver", "FreshView", + "ObservedFetch", "SaveEvidenceVerdict", "evaluate_save_evidence", - "fresh_view_of", + "fresh_view_from_observed", ] @@ -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 @@ -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( @@ -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(): diff --git a/openadapt/transducer_v3_runtime.py b/openadapt/transducer_v3_runtime.py index cf557a88df..cc2f1c1926 100644 --- a/openadapt/transducer_v3_runtime.py +++ b/openadapt/transducer_v3_runtime.py @@ -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 = { diff --git a/openadapt/wrap_sdk.py b/openadapt/wrap_sdk.py index 8f266dea40..91ffcc640b 100644 --- a/openadapt/wrap_sdk.py +++ b/openadapt/wrap_sdk.py @@ -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. @@ -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, diff --git a/tests/test_transducer_fresh_view.py b/tests/test_transducer_fresh_view.py index 63194363a5..90777ca0d2 100644 --- a/tests/test_transducer_fresh_view.py +++ b/tests/test_transducer_fresh_view.py @@ -12,6 +12,7 @@ from __future__ import annotations +import time from pathlib import Path from typing import Any @@ -23,7 +24,11 @@ SimplexTransducer, SupervisorConfig, ) -from openadapt.transducer_fresh_view import evaluate_save_evidence, fresh_view_of +from openadapt.transducer_fresh_view import ( + ObservedFetch, + evaluate_save_evidence, + fresh_view_from_observed, +) from openadapt.transducer_obligations import ( CompiledFieldObligation, diff_readback_against_obligations, @@ -191,62 +196,62 @@ def _obligations(text: str = INSTRUCTION) -> list[CompiledFieldObligation]: return compile_write_obligations(text) +URL = "https://app.test/api/record/Delta%20Co" + + +def _seen( + *, session: str = "", method: str = "GET", status: int = 200, cached: bool = False +) -> list[ObservedFetch]: + return [ObservedFetch(method, URL, status, time.time(), cached, session)] + + @pytest.mark.parametrize( - "result, why", + "result, observed, why", [ - (True, "no read-back"), - ({"verified": True, "readback_text": MATCH}, "not a fresh view"), - ({"verified": False, "readback_text": MATCH, "fresh_view": FRESH}, "refused"), + (True, _seen(), "no read-back"), + ({"verified": True, "readback_text": MATCH}, None, "not a fresh view"), + # A caller-supplied fresh view, however well formed, is ignored. ( - {"readback_text": MATCH, "fresh_view": FRESH, "is_editable": True}, - "editable", - ), - ({"readback_text": MATCH, "fresh_view": FRESH, "is_toast": True}, "toast"), - ({"readback_text": MISMATCH, "fresh_view": FRESH}, "doesn't show"), - ({"readback_text": WRONG_RECORD, "fresh_view": FRESH}, "doesn't show"), - ( - { - "readback_text": MATCH, - "fresh_view": { - "kind": "server_reload", - "fetches": [{"url": "u", "status": 304}], - }, - }, + {"verified": True, "readback_text": MATCH, "fresh_view": FRESH}, + None, "not a fresh view", ), ( { "readback_text": MATCH, - "fresh_view": {"kind": "server_reload", "fetches": []}, + "fresh_view": {"kind": "separate_session", "session": "s"}, }, + [], "not a fresh view", ), - ( - {"readback_text": MATCH, "fresh_view": {"kind": "separate_session"}}, - "not a fresh view", - ), - ( - {"readback_text": MATCH, "fresh_view": {"kind": "same_screen"}}, - "not a fresh view", - ), + ({"readback_text": MATCH}, _seen(status=304), "not a fresh view"), + ({"readback_text": MATCH}, _seen(method="POST"), "not a fresh view"), + ({"readback_text": MATCH}, _seen(cached=True), "not a fresh view"), + ({"verified": False, "readback_text": MATCH}, _seen(), "refused"), + ({"readback_text": MATCH, "is_editable": True}, _seen(), "editable"), + ({"readback_text": MATCH, "is_toast": True}, _seen(), "toast"), + ({"readback_text": MISMATCH}, _seen(), "doesn't show"), + ({"readback_text": WRONG_RECORD}, _seen(), "doesn't show"), ], ) -def test_save_evidence_refusals(result: Any, why: str) -> None: - verdict = evaluate_save_evidence(_obligations(), result) +def test_save_evidence_refusals(result: Any, observed: Any, why: str) -> None: + verdict = evaluate_save_evidence(_obligations(), result, observed) assert not verdict.ok and why in verdict.reason -def test_save_evidence_accepts_a_fresh_reload_and_a_separate_session() -> None: - assert evaluate_save_evidence( - _obligations(), {"readback_text": MATCH, "fresh_view": FRESH} - ).ok - session = {"kind": "separate_session", "session": "audit-7"} +def test_save_evidence_accepts_an_observed_reload_and_a_separate_session() -> None: + verdict = evaluate_save_evidence(_obligations(), {"readback_text": MATCH}, _seen()) + assert verdict.ok and verdict.fresh_view.kind == "server_reload" verdict = evaluate_save_evidence( - _obligations(), {"readback_text": MATCH, "fresh_view": session} - ) - assert ( - verdict.ok and fresh_view_of({"fresh_view": session}).kind == "separate_session" + _obligations(), + {"readback_text": MATCH}, + _seen(session="audit-7"), + agent_session="agent", ) + assert verdict.ok and verdict.fresh_view.kind == "separate_session" + assert fresh_view_from_observed( + _seen(session="agent"), agent_session="agent" + ).kind == ("server_reload") def test_document_facts_alone_never_grant_verified() -> None: @@ -254,9 +259,7 @@ def test_document_facts_alone_never_grant_verified() -> None: [], "Authorization AUTH-48213 approved 2026-05-01." ) readback = "Authorization: AUTH-48213\nDate: 2026-05-01" - verdict = evaluate_save_evidence( - facts, {"readback_text": readback, "fresh_view": FRESH} - ) + verdict = evaluate_save_evidence(facts, {"readback_text": readback}, _seen()) assert not verdict.ok and "names no value to write" in verdict.reason @@ -266,29 +269,42 @@ def test_unsaved_document_fact_never_blocks() -> None: 'our motto is "quality first".' ) verdict = evaluate_save_evidence( - _obligations(text), {"readback_text": MATCH, "fresh_view": FRESH} + _obligations(text), {"readback_text": MATCH}, _seen() ) assert verdict.ok # -- every entry point that can verify a save ------------------------------------- +#: (verifier result, whether the runtime's observer sees a server read while +#: the check runs). EVIDENCE = { - "no_fresh_view": {"verified": True, "readback_text": MATCH}, - "fresh_mismatch": { - "verified": True, - "readback_text": MISMATCH, - "fresh_view": FRESH, - }, - "fresh_wrong_record": { - "verified": True, - "readback_text": WRONG_RECORD, - "fresh_view": FRESH, - }, - "fresh_match": {"verified": True, "readback_text": MATCH, "fresh_view": FRESH}, + "no_fresh_view": ({"verified": True, "readback_text": MATCH}, False), + "fabricated_fresh_view": ( + {"verified": True, "readback_text": MATCH, "fresh_view": FRESH}, + False, + ), + "fresh_mismatch": ({"verified": True, "readback_text": MISMATCH}, True), + "fresh_wrong_record": ({"verified": True, "readback_text": WRONG_RECORD}, True), + "fresh_match": ({"verified": True, "readback_text": MATCH}, True), } +class _Observer: + """Stands in for the runtime's network observer.""" + + agent_session = "agent" + + def __init__(self) -> None: + self.fetches: list[ObservedFetch] = [] + + def see(self) -> None: + self.fetches.append(ObservedFetch("GET", URL, 200, time.time())) + + def fetches_between(self, start: float, end: float) -> list[ObservedFetch]: + return [f for f in self.fetches if start <= f.at <= end] + + class _Agent: def __init__(self, actions: list[dict[str, Any]]) -> None: self.actions = list(actions) @@ -315,18 +331,25 @@ def _frame(evidence: dict[str, Any]) -> dict[str, Any]: } -def _run(entry: str, evidence: dict[str, Any], tmp_path: Path) -> list[str]: +def _run(entry: str, variant: str, tmp_path: Path) -> list[str]: + result, observe = EVIDENCE[variant] + observer = _Observer() calls = {"n": 0} + def answer() -> Any: + if observe: + observer.see() + return result + def late(_o: Any, _t: Any, _s: Any) -> Any: # Refuses at the first (mid-episode) call, answers at DONE. calls["n"] += 1 - return evidence if calls["n"] > 1 else {"verified": False} + return answer() if calls["n"] > 1 else {"verified": False} def always(_o: Any, _t: Any, _s: Any) -> Any: - return evidence + return answer() - options: dict[str, Any] = {} + options: dict[str, Any] = {"fetch_observer": observer} obs_done: dict[str, Any] = {"url": "https://app.test/record"} if entry == "rung2_done": options["rung2_verifier"] = late @@ -335,19 +358,22 @@ def always(_o: Any, _t: Any, _s: Any) -> Any: elif entry == "rung3_done": options["rung3_verifier"] = late elif entry == "verification_frame": - obs_done["verification_frame"] = _frame(evidence) + if observe: + observer.see() # seen, but not during a check the runtime ran + obs_done["verification_frame"] = _frame(result) elif entry == "reopen_executor": store = AtomicCartridgeStore(tmp_path / "cart.json") store.merge_cartridge( AppCartridge("default", reopen_paths={"rec": [{"op": "open"}]}) ) options["cartridge_store"] = store - options["reopen_executor"] = lambda _steps, _o, _s: _frame(evidence) - elif entry in ("step_cap_rung2", "step_cap_frame"): - if entry == "step_cap_rung2": - options["rung2_verifier"] = late - else: - obs_done["verification_frame"] = _frame(evidence) + options["reopen_executor"] = lambda _steps, _o, _s: _frame(answer()) + elif entry == "step_cap_rung2": + options["rung2_verifier"] = late + elif entry == "step_cap_frame": + if observe: + observer.see() + obs_done["verification_frame"] = _frame(result) tr = SimplexTransducer( _Agent([_commit(), {"type": "done"}, {"type": "done"}]), **options ) @@ -362,6 +388,7 @@ def always(_o: Any, _t: Any, _s: Any) -> Any: return [str(r.outcome) for r in tr.get_state("r", entry).receipts] +CARRIED_FRAMES = ("verification_frame", "step_cap_frame") ENTRIES = ( "rung2_done", "rung2_reconcile", @@ -378,8 +405,11 @@ def always(_o: Any, _t: Any, _s: Any) -> Any: def test_every_entry_point_verifies_only_on_a_fresh_matching_read( entry: str, variant: str, tmp_path: Path ) -> None: - outcomes = _run(entry, EVIDENCE[variant], tmp_path) - assert ("VERIFIED" in outcomes) is (variant == "fresh_match"), ( + outcomes = _run(entry, variant, tmp_path) + # A frame carried in an observation was not produced by a check the + # runtime ran, so no fetch can be tied to it: it never verifies a save. + expected = variant == "fresh_match" and entry not in CARRIED_FRAMES + assert ("VERIFIED" in outcomes) is expected, ( entry, variant, outcomes, @@ -437,7 +467,15 @@ def _claim(tr: SimplexTransducer, state: Any) -> str: def test_evidence_for_an_earlier_commit_does_not_cover_a_later_one() -> None: - answers = [EVIDENCE["fresh_match"]] + observer = _Observer() + answers = [EVIDENCE["fresh_match"][0]] + + def rung2(_o: Any, _t: Any, _s: Any) -> Any: + if answers: + observer.see() + return answers.pop(0) + return {"verified": False} + tr = SimplexTransducer( _Agent( [ @@ -451,9 +489,8 @@ def test_evidence_for_an_earlier_commit_does_not_cover_a_later_one() -> None: }, ] ), - rung2_verifier=lambda _o, _t, _s: ( - answers.pop(0) if answers else {"verified": False} - ), + rung2_verifier=rung2, + fetch_observer=observer, ) task = _task("two-commits") tr.act({"url": "https://app.test/record"}, task) @@ -483,6 +520,42 @@ def test_an_imperative_request_inside_a_document_compiles_and_can_only_block() - assert ("write", "Delivery Address", "9 Quay St") in [ (o.kind, o.label, o.expected_value) for o in obligations ] - assert not evaluate_save_evidence( - obligations, {"readback_text": MATCH, "fresh_view": FRESH} - ).ok + assert not evaluate_save_evidence(obligations, {"readback_text": MATCH}, _seen()).ok + + +def test_a_fabricated_fresh_view_is_refused_end_to_end() -> None: + """A verifier that invents a well-formed fresh view, with a matching + read-back, gets no VERIFIED: the runtime saw no server read.""" + + fabricated = { + "verified": True, + "readback_text": MATCH, + "fresh_view": {"kind": "separate_session", "session": "audit-1"}, + } + for observer in (None, _Observer()): + tr = SimplexTransducer( + _Agent([_commit(), {"type": "done"}, {"type": "done"}]), + rung2_verifier=lambda _o, _t, _s: fabricated, + fetch_observer=observer, + ) + task = _task("fabricated") + for _ in range(3): + tr.act({"url": "https://app.test/record"}, task) + state = tr.get_state("r", "fabricated") + assert "VERIFIED" not in [str(r.outcome) for r in state.receipts] + assert "observed no server read" in state.save_evidence_refusal + + +def test_a_read_outside_the_check_window_does_not_count() -> None: + observer = _Observer() + observer.fetches.append(ObservedFetch("GET", URL, 200, time.time() - 60)) + tr = SimplexTransducer( + _Agent([_commit(), {"type": "done"}, {"type": "done"}]), + rung2_verifier=lambda _o, _t, _s: {"verified": True, "readback_text": MATCH}, + fetch_observer=observer, + ) + task = _task("stale-read") + for _ in range(3): + tr.act({"url": "https://app.test/record"}, task) + outcomes = [str(r.outcome) for r in tr.get_state("r", "stale-read").receipts] + assert "VERIFIED" not in outcomes