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..79429c6c59 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 == ReceiptOutcome.VERIFIED.value + 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 27303226c6..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, @@ -881,16 +884,21 @@ 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) - if v3 is not None: - ep = v3._episodes.get((run_id, task_id)) - if ep is not None and getattr(ep, "obligations", 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) + # 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 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( @@ -914,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, @@ -924,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) @@ -933,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 79b65a8c30..7bc7c8bb44 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 + if ob.kind not in _FREE_TEXT_KINDS or len(words) > 4: + return False + head, modifiers = words[-1], set(words[:-1]) + return ( + head in _KIND_LABEL_WORDS["phrase"] and not modifiers & _OTHER_RECORD_MODIFIERS + ) def _abbreviated_label(label: str) -> str: @@ -318,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) @@ -335,6 +371,93 @@ def _value_in_text(ob: CompiledFieldObligation, text: str) -> bool: return results[0].verdict is Verdict.MATCH +_FIELD_LINE_RE = re.compile( + r"^[ \t]*(?P