From 0df6072278732da8d35a252e327f125a0418b09b Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 18:23:35 -0500 Subject: [PATCH 1/7] fix(transducer): keep step-cap VERIFIED blocked while compiled obligations are open finalize_on_step_cap looked up the v3 hooks as owner._v3_runtime, which never exists (the hooks live at owner._v3), so the open-obligation guard never ran. A passing end-state check could stamp VERIFIED at the step cap while every obligation compiled from the instruction was still unverified. --- openadapt/transducer_fact_ledger.py | 8 ++++--- tests/test_transducer_fact_ledger.py | 36 ++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/openadapt/transducer_fact_ledger.py b/openadapt/transducer_fact_ledger.py index 27303226c6..c5ebda5e58 100644 --- a/openadapt/transducer_fact_ledger.py +++ b/openadapt/transducer_fact_ledger.py @@ -881,10 +881,12 @@ def finalize_on_step_cap(self, observation: Any, task: Any) -> TransducerReceipt reason="Step cap reached before any save; nothing to verify.", ) # Never promote to VERIFIED at step cap if compiled obligations are still open. - v3 = getattr(owner, "_v3_runtime", None) + # The v3 hooks live at ``owner._v3``; each episode's compiled + # obligations hang off its state (``v3.ep(state)``). + v3 = getattr(owner, "_v3", None) if v3 is not None: - ep = v3._episodes.get((run_id, task_id)) - if ep is not None and getattr(ep, "obligations", None): + ep = v3.ep(state) + if getattr(ep, "obligations", None): from openadapt.transducer_obligations import ObligationStatus unmet = [ diff --git a/tests/test_transducer_fact_ledger.py b/tests/test_transducer_fact_ledger.py index 93e8c50e6a..15a9826cf3 100644 --- a/tests/test_transducer_fact_ledger.py +++ b/tests/test_transducer_fact_ledger.py @@ -551,3 +551,39 @@ def test_step_cap_after_resumed_commit_can_still_verify(tmp_path: Any) -> None: receipt = resumed.finalize_on_step_cap({"url": "https://a/form", "saved": 1}, task) assert receipt.outcome == "VERIFIED" assert receipt.commit_index == 1 + + +def test_step_cap_is_not_verified_while_compiled_obligations_are_open() -> None: + """A passing end-state check at the step cap must not stamp VERIFIED while + obligations compiled from the instruction are still unverified.""" + from openadapt.simplex_transducer import SupervisorConfig + + class _StubAgent: + def act(self, obs, task, history=None): + return {"type": "click", "target": "save", "is_commit": True} + + calls: list[int] = [] + + def _rung2(obs, task, state): + calls.append(state.step_count) + return True + + tr = SimplexTransducer( + _StubAgent(), + config=SupervisorConfig(enable_obligation_compiler=True), + rung2_verifier=_rung2, + ) + task = { + "run_id": "r1", + "task_id": "stepcap-open-obligations", + "instruction": "Close request REF-4471-09 dated 2031-05-14.", + } + tr.act({"dom": "
worklist
", "run_id": "r1"}, task) + state = tr.get_state("r1", "stepcap-open-obligations") + assert tr._v3.ep(state).obligations, "the instruction compiles obligations" + receipt = tr.finalize_on_step_cap( + {"dom": "
worklist
", "run_id": "r1"}, task + ) + assert receipt.outcome == "COMPLETED_UNVERIFIED" + assert "unverified obligation" in receipt.reason + assert calls == [] From 0e82d5e0c32e7db7f79f52d64c31d1c98c35cc02 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 18:23:38 -0500 Subject: [PATCH 2/7] fix(verify): let a quoted phrase verify under a compound free-text label A phrase obligation verified on a page field only when every word of the field's label was a free-text kind word, so 'Customer Details: ' or 'Clinical Notes: ' rejected correct saves. A compound label now names a phrase when its head noun (last word) is a free-text word and no word before it points at another record or an unsaved state ('Previous Notes', 'Draft Comment'). Amounts, dates, codes and IDs keep the full rule. Adds adversarial tests, including 5 against 'Dose: 50 mg'. --- openadapt/transducer_obligations.py | 36 +++++++++++++++++- tests/test_transducer_obligations.py | 55 ++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+), 2 deletions(-) diff --git a/openadapt/transducer_obligations.py b/openadapt/transducer_obligations.py index 79b65a8c30..51c635db48 100644 --- a/openadapt/transducer_obligations.py +++ b/openadapt/transducer_obligations.py @@ -204,10 +204,35 @@ def _labels(ob: CompiledFieldObligation) -> list[str]: } +#: Words in front of a free-text label's head noun that point at another +#: record or at text that isn't the saved value: ``Previous Notes``, ``Draft +#: Comment``, ``Expected Summary``. A label with one of them never names a +#: phrase obligation through its head noun. +_OTHER_RECORD_MODIFIERS = frozenset( + { + "previous", "prior", "old", "older", "original", "former", "last", + "earlier", "draft", "pending", "proposed", "suggested", "expected", + "example", "sample", "template", "default", "rejected", "deleted", + "archived", "superseded", "merged", "parent", "linked", "related", + "other", "unsaved", "new", + } +) # fmt: skip +_FREE_TEXT_KINDS = frozenset({"phrase", "narrative_criterion"}) + + def _label_names_obligation(ob: CompiledFieldObligation, label: str) -> bool: """Every word of the page label names the obligation: a word of its kind (``_KIND_LABEL_WORDS``), of its own label, or, for an ID, its prefix or - a listed name for it (``_PREFIX_WORDS``).""" + a listed name for it (``_PREFIX_WORDS``). + + A free-text obligation (a quoted phrase) is also named by a compound + field label whose head noun, its last word, is a free-text word + (``Customer Details``, ``Clinical Notes``, ``Appeal Reason``), as long as + no word before the head points at another record or an unsaved state + (``Previous Notes``, ``Draft Comment``). Free-text fields are usually + named for what they describe, so requiring every word to be a kind word + rejected correct saves. Amounts, dates, codes and IDs keep the full rule. + """ words = re.findall(r"[a-z]+", _abbreviated_label(label)) if not words: @@ -218,7 +243,14 @@ def _label_names_obligation(ob: CompiledFieldObligation, label: str) -> bool: prefix = _id_prefix(ob) if prefix is not None: allowed |= {prefix.lower()} | _PREFIX_WORDS.get(prefix, frozenset()) - return set(words) <= allowed + if set(words) <= allowed: + return True + return ( + ob.kind in _FREE_TEXT_KINDS + and len(words) <= 4 + and words[-1] in _KIND_LABEL_WORDS["phrase"] + and not set(words[:-1]) & _OTHER_RECORD_MODIFIERS + ) def _abbreviated_label(label: str) -> str: diff --git a/tests/test_transducer_obligations.py b/tests/test_transducer_obligations.py index 20dcf1ee63..5aeb720806 100644 --- a/tests/test_transducer_obligations.py +++ b/tests/test_transducer_obligations.py @@ -404,3 +404,58 @@ def test_page_labels_must_name_the_obligation_and_carry_no_failure(spec, readbac r = diff_readback_against_obligations(obs, readback) assert not r.all_verified assert all(o.status is not ObligationStatus.VERIFIED for o in obs) + + +_PHRASE = "Ships quarterly to three regional warehouses." + + +@pytest.mark.parametrize( + "readback", + [ + f"Customer Name: Acme\nCustomer Details: {_PHRASE}\nTerritory: All", + f"Clinical Notes: {_PHRASE}", + f"Appeal Reason: {_PHRASE}", + ], +) +def test_phrase_verifies_as_whole_value_of_compound_free_text_label(readback): + obs = compile_obligations_from_spec(f'Set the details field to: "{_PHRASE}" Save.') + assert [o.kind for o in obs] == ["phrase"] + assert diff_readback_against_obligations(obs, readback).all_verified + + +@pytest.mark.parametrize( + "readback", + [ + # A modifier that points at another record or an unsaved state. + f"Previous Notes: {_PHRASE}", + f"Draft Comment: {_PHRASE}", + f"Expected Summary: {_PHRASE}", + # A head noun that isn't a free-text word. + f"Customer Name: {_PHRASE}", + # Extra context inside the bound value, or a failure on the line. + f"Customer Details: {_PHRASE} (not saved)", + f"Customer Details: {_PHRASE} Error", + f"Error: Customer Details: {_PHRASE}", + # Only part of the phrase. + "Customer Details: Ships quarterly", + # One label, two different values. + f"Customer Details: {_PHRASE}\nCustomer Details: Something else", + ], +) +def test_phrase_compound_label_still_rejects_loose_reads(readback): + obs = compile_obligations_from_spec(f'Set the details field to: "{_PHRASE}" Save.') + assert not diff_readback_against_obligations(obs, readback).all_verified + + +def test_compound_label_rule_never_loosens_numbers(): + # The adversarial case behind the strict matcher: 5 never matches "50 mg". + dose = compile_obligations_from_spec("", {"dose": "5"}) + assert not diff_readback_against_obligations(dose, "Dose: 50 mg").all_verified + phrase = compile_obligations_from_spec('Record "5" in the notes.') + assert not diff_readback_against_obligations( + phrase, "Clinical Notes: 50 mg" + ).all_verified + amount = compile_obligations_from_spec("Charge $250.00.") + assert not diff_readback_against_obligations( + amount, "Charge Details: $1,250.00" + ).all_verified From 2706aa8f393d52703c630c28e4b5132bb5ef2cbd Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 1 Dec 2026 04:55:55 -0500 Subject: [PATCH 3/7] fix(verify): require only written values, and a fresh view of the saved record, to verify a save Obligations came from every date, amount, ID and quoted phrase in the instruction and in any document seen mid-episode, so facts the task never saves blocked correct runs, and any passing read-back (same screen, wire receipt, a bare True) could verify a save. - compile_write_obligations: only values the instruction asks to be written or set, plus the record they go to, are required. - Document facts are tracked with required=False and never block or verify. - A GUI or remote save is VERIFIED only when a read-back from a fresh view (a recorded server fetch or a separate session) proves every required value with the strict matcher. Every verification entry point goes through one check; _mark_verified and _emit_receipt refuse without it. - SupervisorConfig(require_fresh_view_for_saves=False) keeps the old rule. --- ...pt-wrap-agent-counts-as-a-verified-save.md | 1 + openadapt/simplex_transducer.py | 133 ++++- openadapt/transducer_fact_ledger.py | 18 +- openadapt/transducer_fresh_view.py | 144 ++++++ openadapt/transducer_obligations.py | 83 +++- openadapt/transducer_v3_runtime.py | 49 +- openadapt/transducer_write_intents.py | 328 +++++++++++++ tests/test_simplex_transducer.py | 45 +- tests/test_transducer_fact_ledger.py | 24 +- tests/test_transducer_fresh_view.py | 453 ++++++++++++++++++ tests/test_transducer_v3_runtime.py | 12 +- 11 files changed, 1248 insertions(+), 42 deletions(-) create mode 100644 capabilities/10-computer-use-agents/0105-what-openadapt-wrap-agent-counts-as-a-verified-save.md create mode 100644 openadapt/transducer_fresh_view.py create mode 100644 openadapt/transducer_write_intents.py create mode 100644 tests/test_transducer_fresh_view.py 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 new file mode 100644 index 0000000000..f3dc394b76 --- /dev/null +++ b/capabilities/10-computer-use-agents/0105-what-openadapt-wrap-agent-counts-as-a-verified-save.md @@ -0,0 +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` | diff --git a/openadapt/simplex_transducer.py b/openadapt/simplex_transducer.py index 0e0e823688..e2011e7d94 100644 --- a/openadapt/simplex_transducer.py +++ b/openadapt/simplex_transducer.py @@ -34,6 +34,7 @@ is_non_gui_modality, verifier_passed, ) +from openadapt.transducer_fresh_view import SaveEvidenceVerdict, evaluate_save_evidence from openadapt.transducer_macros import MacroStore, StallRecoveryPlan from openadapt.transducer_obligations import ( MicroHandoffResolution, @@ -888,6 +889,11 @@ class SupervisorConfig: qualification_id: str = "qual-default-01" minimum_effect_strength: str = "independent_session" enable_obligation_compiler: bool = False + #: A save (a GUI or remote commit) is VERIFIED only on a fresh view of the + #: saved record (a recorded server fetch or a separate session) that shows + #: every value the instruction asked to be written. See + #: ``openadapt.transducer_fresh_view``. + require_fresh_view_for_saves: bool = True def __post_init__(self) -> None: if self.isolation_mode not in ("iid_ephemeral", "continual_persistent"): @@ -918,6 +924,7 @@ def config_sha256(self) -> str: "workflow_version": self.workflow_version, "qualification_id": self.qualification_id, "minimum_effect_strength": self.minimum_effect_strength, + "require_fresh_view_for_saves": self.require_fresh_view_for_saves, } return _sha256_hex(payload) @@ -1679,6 +1686,11 @@ 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 + # 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 + save_evidence: Any = field(default=None, repr=False) + save_evidence_refusal: str = "" _lock: threading.RLock = field(default_factory=threading.RLock, repr=False) def record_entity(self, anchor: SpanAnchor) -> None: @@ -2903,6 +2915,22 @@ def _emit_receipt( commit_index: int, reason: str, ) -> TransducerReceipt: + if ( + outcome == "VERIFIED" + and self._save_gate_applies(state) + and not self._save_evidence_covers(state) + ): + why = state.save_evidence_refusal or ( + "no fresh view of the saved record (a recorded server fetch or a " + "separate session) showed every value the instruction asked to write" + ) + outcome = "COMPLETED_UNVERIFIED" + oracle_tier = 0 + observed_effect_strength = None + effect_passed = False + postcondition_passed = False + delivery_uncertain = True + reason = f"VERIFIED withheld: {why}. Withheld claim: {reason}" safe_reason = str(self.vault.redact(reason)) evidence_payload = { "run_id": state.run_id, @@ -2989,11 +3017,17 @@ def _non_terminal_statuses(self) -> set[str]: statuses.add(str(item).strip().lower()) return statuses - def _evaluate_verification_frame(self, frame: Any) -> tuple[bool, str, str | None]: + def _evaluate_verification_frame( + self, frame: Any, state: EpisodeState | None = None + ) -> tuple[bool, str, str | None]: """Verify non-editable, non-toast persisted delta + frame status. + With ``state`` and a save to verify, the frame must also pass the + fresh-view save check (:meth:`_admit_save_evidence`). + Returns ``(verified, reason, observed_effect_strength)``. """ + original = frame if not isinstance(frame, Mapping): # Support object attributes too frame = { @@ -3048,12 +3082,74 @@ def _evaluate_verification_frame(self, frame: Any) -> tuple[bool, str, str | Non if frame.get("separate_session") is True else "persisted_state_reacquisition" ) + if state is not None and self._save_gate_applies(state): + evidence = dict(original) if isinstance(original, Mapping) else dict(frame) + for key in ("readback_text", "fresh_view", "verified", "reason"): + if key not in evidence: + value = _extract_attr_or_key(original, key, None) + if value is not None: + evidence[key] = value + verdict = self._admit_save_evidence(state, evidence) + if not verdict.ok: + return False, f"Not verified: {verdict.reason}.", None + strength = ( + "independent_session" + if verdict.fresh_view is not None + and verdict.fresh_view.kind == "separate_session" + else "persisted_state_reacquisition" + ) return ( True, f"Verified persisted frame status={status_str or 'persisted'}.", strength, ) + # -- fresh-view save check --------------------------------------------- + def _save_gate_applies(self, state: EpisodeState) -> bool: + """A save is being verified: the episode made a GUI or remote commit + (not only workspace writes) and the fresh-view rule is on.""" + + if not self.config.require_fresh_view_for_saves or not state.saga_commits: + return False + ep = self._v3.ep(state) + return not self._v3._only_workspace_commits(state, ep) + + 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) + with state._lock: + if verdict.ok: + state.save_evidence_commit = max(1, state.next_commit_index - 1) + state.save_evidence = verdict + state.save_evidence_refusal = "" + else: + state.save_evidence_refusal = verdict.reason + return verdict + + def _admit_verifier_result(self, state: EpisodeState, result: Any) -> bool: + """A Rung 2 / Rung 3 verifier result counts: the verifier passed and, + for a save, its read-back passes the fresh-view save check.""" + + if not self._save_gate_applies(state): + return verifier_passed(result) + return self._admit_save_evidence(state, result).ok + + def _save_evidence_covers(self, state: EpisodeState) -> bool: + """Fresh-view evidence was admitted after the latest commit.""" + + return state.save_evidence_commit >= max(1, state.next_commit_index - 1) + + def _fresh_view_note(self, state: EpisodeState) -> str: + verdict = state.save_evidence + if not self._save_gate_applies(state) or verdict is None: + return "" + return f" ({verdict.reason})" + def _compile_reopen_path( self, state: EpisodeState, @@ -3116,7 +3212,7 @@ def _verify_before_done( # 1. Check Rung 3 / Rung 2 attached verifiers first if self.rung3_verifier is not None: res = self.rung3_verifier(observation, task, state) - ok = verifier_passed(res) + ok = self._admit_verifier_result(state, res) if ok: self._mark_verified(state, commit_idx, tier=2) self._emit_receipt( @@ -3130,13 +3226,14 @@ def _verify_before_done( effect_passed=True, delivery_uncertain=False, commit_index=commit_idx, - reason="Verified by attached Rung 3 system-of-record check.", + reason="Verified by attached Rung 3 system-of-record check." + + self._fresh_view_note(state), ) return action if self.rung2_verifier is not None: res = self.rung2_verifier(observation, task, state) - ok = verifier_passed(res) + ok = self._admit_verifier_result(state, res) if ok: self._mark_verified(state, commit_idx, tier=1) self._emit_receipt( @@ -3150,7 +3247,8 @@ def _verify_before_done( effect_passed=True, delivery_uncertain=False, commit_index=commit_idx, - reason="Verified by attached Rung 2 independent-session check.", + reason="Verified by attached Rung 2 independent-session check." + + self._fresh_view_note(state), ) return action @@ -3160,7 +3258,9 @@ def _verify_before_done( for path_key, steps in cart.reopen_paths.items(): frame = self.reopen_executor(steps, observation, state) if frame is not None: - ok, reason, strength = self._evaluate_verification_frame(frame) + ok, reason, strength = self._evaluate_verification_frame( + frame, state + ) if ok and strength is not None: tier: Literal[0, 1, 2, 3] = ( 1 if strength == "independent_session" else 0 @@ -3184,7 +3284,7 @@ def _verify_before_done( # 3. Check current observation if it already carries a reopened verification frame verif_frame = _extract_attr_or_key(observation, "verification_frame", None) if verif_frame is not None: - ok, reason, strength = self._evaluate_verification_frame(verif_frame) + ok, reason, strength = self._evaluate_verification_frame(verif_frame, state) if ok and strength is not None: tier = 1 if strength == "independent_session" else 0 self._mark_verified(state, commit_idx, tier=tier) @@ -3287,6 +3387,11 @@ def _verify_before_done( def _mark_verified( self, state: EpisodeState, commit_index: int, *, tier: int ) -> None: + if self._save_gate_applies(state) and not self._save_evidence_covers(state): + # Every path that verifies a save goes through here: without a + # fresh-view read-back admitted since the latest commit, nothing + # is marked verified. + return with state._lock: state.pending_verification = False for ob in state.accrued_obligations: @@ -3412,6 +3517,9 @@ def _reconcile_pending_commits( if self.rung3_verifier is not None: res = self.rung3_verifier(observation, task, state) matched = self._extract_verified_indices(res, pending) + if matched and self._save_gate_applies(state): + if not self._admit_save_evidence(state, res).ok: + matched = [] for idx in matched: self._mark_verified(state, idx, tier=2) verified_indices.append(idx) @@ -3420,6 +3528,9 @@ def _reconcile_pending_commits( if pending and self.rung2_verifier is not None: res = self.rung2_verifier(observation, task, state) matched = self._extract_verified_indices(res, pending) + if matched and self._save_gate_applies(state): + if not self._admit_save_evidence(state, res).ok: + matched = [] for idx in matched: self._mark_verified(state, idx, tier=1) verified_indices.append(idx) @@ -3432,7 +3543,9 @@ def _reconcile_pending_commits( for _path_key, steps in cart.reopen_paths.items(): frame = self.reopen_executor(steps, observation, state) if frame is not None: - ok, _reason, strength = self._evaluate_verification_frame(frame) + ok, _reason, strength = self._evaluate_verification_frame( + frame, state + ) if ok and strength is not None: tier = 1 if strength == "independent_session" else 0 for rec in list(pending): @@ -3446,7 +3559,9 @@ def _reconcile_pending_commits( if pending and include_verification_frame: verif_frame = _extract_attr_or_key(observation, "verification_frame", None) if verif_frame is not None: - ok, _reason, strength = self._evaluate_verification_frame(verif_frame) + ok, _reason, strength = self._evaluate_verification_frame( + verif_frame, state + ) if ok and strength is not None: tier = 1 if strength == "independent_session" else 0 reopen_steps = _extract_attr_or_key( diff --git a/openadapt/transducer_fact_ledger.py b/openadapt/transducer_fact_ledger.py index c5ebda5e58..d6fc711568 100644 --- a/openadapt/transducer_fact_ledger.py +++ b/openadapt/transducer_fact_ledger.py @@ -780,6 +780,9 @@ def facts_gate( owner = self.owner ledger = state.fact_ledger if not ledger.unproven_facts(required): + if owner._save_gate_applies(state): + # Facts proven across views are not a fresh read of the save. + return None owner._mark_verified(state, commit_idx, tier=0) self._emit_verified( state, @@ -884,7 +887,9 @@ def finalize_on_step_cap(self, observation: Any, task: Any) -> TransducerReceipt # The v3 hooks live at ``owner._v3``; each episode's compiled # obligations hang off its state (``v3.ep(state)``). v3 = getattr(owner, "_v3", None) - if v3 is not None: + # With the fresh-view rule on, a save verifies only when a fresh read + # proves every required obligation, which the checks below enforce. + if v3 is not None and not owner._save_gate_applies(state): ep = v3.ep(state) if getattr(ep, "obligations", None): from openadapt.transducer_obligations import ObligationStatus @@ -892,7 +897,8 @@ def finalize_on_step_cap(self, observation: Any, task: Any) -> TransducerReceipt unmet = [ o for o in ep.obligations - if getattr(o, "status", None) is not ObligationStatus.VERIFIED + if getattr(o, "required", True) + and getattr(o, "status", None) is not ObligationStatus.VERIFIED ] if unmet: return owner._emit_receipt( @@ -916,7 +922,9 @@ def finalize_on_step_cap(self, observation: Any, task: Any) -> TransducerReceipt (owner.rung2_verifier, 1, "Rung 2 independent-session"), ) for verifier, tier, label in oracles: - if verifier is not None and _ok(verifier(observation, task, state)): + if verifier is not None and owner._admit_verifier_result( + state, verifier(observation, task, state) + ): owner._mark_verified(state, commit_idx, tier=tier) return self._emit_verified( state, @@ -926,7 +934,7 @@ def finalize_on_step_cap(self, observation: Any, task: Any) -> TransducerReceipt ) frame = _get(observation, "verification_frame") if frame is not None: - frame_ok, why, strength = owner._evaluate_verification_frame(frame) + frame_ok, why, strength = owner._evaluate_verification_frame(frame, state) if frame_ok and strength is not None: tier = 1 if strength == "independent_session" else 0 owner._mark_verified(state, commit_idx, tier=tier) @@ -935,7 +943,7 @@ def finalize_on_step_cap(self, observation: Any, task: Any) -> TransducerReceipt ) required = required_fact_ids(task, observation) missing = state.fact_ledger.unproven_facts(required) - if required and not missing: + if required and not missing and not owner._save_gate_applies(state): owner._mark_verified(state, commit_idx, tier=0) return self._emit_verified( state, diff --git a/openadapt/transducer_fresh_view.py b/openadapt/transducer_fresh_view.py new file mode 100644 index 0000000000..d33c91d4e8 --- /dev/null +++ b/openadapt/transducer_fresh_view.py @@ -0,0 +1,144 @@ +"""Decide whether a read-back may verify a save. + +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). +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 + obligation (the written values and the identity of the record they go to) + is proven on the read-back by the shared strict matcher. Facts only + mentioned in the instruction or in a document are not required, so they + can neither block nor grant VERIFIED. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from typing import Any, Literal + +from openadapt.transducer_obligations import ( + CompiledFieldObligation, + diff_readback_against_obligations, +) + +__all__ = [ + "FreshView", + "SaveEvidenceVerdict", + "evaluate_save_evidence", + "fresh_view_of", +] + + +@dataclass(frozen=True) +class FreshView: + kind: Literal["server_reload", "separate_session"] + evidence: tuple[str, ...] + + +@dataclass +class SaveEvidenceVerdict: + ok: bool + reason: str + fresh_view: FreshView | None = None + verified_ids: list[str] = field(default_factory=list) + missing: list[str] = field(default_factory=list) + + +def _status_ok(status: Any) -> bool: + try: + return 200 <= int(status) < 300 + except (TypeError, ValueError): + 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): + 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 + + +def evaluate_save_evidence( + obligations: Sequence[CompiledFieldObligation], result: Any +) -> SaveEvidenceVerdict: + """Whether ``result`` (a verifier's answer or a verification frame) may + verify a save against ``obligations``.""" + + if not isinstance(result, Mapping): + return SaveEvidenceVerdict( + False, "the check returned no read-back of the saved record" + ) + if result.get("verified") is False: + why = str(result.get("reason") or "").strip() + return SaveEvidenceVerdict( + False, "the check refused" + (f": {why[:300]}" if why else "") + ) + if result.get("is_toast") is True: + 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) + 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", + ) + text = result.get("readback_text") + if not isinstance(text, str) or not text.strip(): + return SaveEvidenceVerdict(False, "the fresh view has no read-back text", view) + required = [o for o in obligations if o.required] + if not any(o.kind == "write" for o in required): + return SaveEvidenceVerdict( + False, + "the instruction names no value to write, so a read-back can't show the save", + view, + ) + diff = diff_readback_against_obligations(required, text) + if not diff.all_verified: + missing = [f"{o.label}: {o.expected_value}" for o in diff.missing_obligations] + return SaveEvidenceVerdict( + False, + "the fresh view doesn't show " + "; ".join(missing[:6]), + view, + list(diff.verified_ids), + missing, + ) + return SaveEvidenceVerdict( + True, + f"a fresh {view.kind.replace('_', ' ')} of the saved record shows all " + f"{len(required)} required value(s)", + view, + list(diff.verified_ids), + ) diff --git a/openadapt/transducer_obligations.py b/openadapt/transducer_obligations.py index 51c635db48..af9f445054 100644 --- a/openadapt/transducer_obligations.py +++ b/openadapt/transducer_obligations.py @@ -350,6 +350,10 @@ def _value_in_text(ob: CompiledFieldObligation, text: str) -> bool: if not ob.expected_value: return False + if ob.kind == "write": + return _write_value_proven(ob, text) + if ob.kind == "record_identity": + return _identity_proven(ob, text) if ob.kind == "identifier" and _other_ids_with_prefix(ob, text): return False kind = _evidence_kind(ob) @@ -367,6 +371,65 @@ def _value_in_text(ob: CompiledFieldObligation, text: str) -> bool: return results[0].verdict is Verdict.MATCH +_FIELD_LINE_RE = re.compile( + r"^[ \t]*(?P