From f8e40657b18a62825d3a4aaf7a3653035be520e4 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 19:24:20 -0500 Subject: [PATCH 1/2] fix(transducer): confirm saved values where they reappear, bound to the pinned record wrap verified a save only when every compiled value showed on one screen as non-editable text that its label vocabulary accepts. Real apps spread a record over screens, cut long values in summary views, and show the full saved value only when the record is reopened in its form. Labels such as From:, To: and DOB: never matched. On the OpenEMR prior-authorization dev split, every correct save the wrapped agent made ended unverified. wrap now remembers which field each typed value went into before a commit. After the commit, a write is confirmed on a screen whose saved text shows every pinned identity value, when either its full value appears verbatim in that saved text (six characters or more), or the same field shows the same value in a form the read-back provider marks reopened (loaded again after the save, untouched) and the agent has not typed into it since. At done, an obligation still missing from the current screen is met by a confirmed write that contains it as a whole token, or by a pinned identity value seen on a saved screen. Without pinned identity nothing changes. --- openadapt/simplex_transducer.py | 1 + openadapt/transducer_v3_runtime.py | 159 ++++++++++++++++++++++++++++ tests/test_transducer_v3_runtime.py | 100 +++++++++++++++++ 3 files changed, 260 insertions(+) diff --git a/openadapt/simplex_transducer.py b/openadapt/simplex_transducer.py index 0e0e823688..8f5803dbbf 100644 --- a/openadapt/simplex_transducer.py +++ b/openadapt/simplex_transducer.py @@ -3632,6 +3632,7 @@ def _act_supervised( state.step_count += 1 self._ingest_context(state, observation, task) self._v3.on_context(state, observation, task) + self._v3.observe_saved(state, observation, task) self._facts.on_observation(state, observation) # Native BenchmarkObservation surface guard: stream/VDI disconnect. diff --git a/openadapt/transducer_v3_runtime.py b/openadapt/transducer_v3_runtime.py index edfab0edcb..14eebb0364 100644 --- a/openadapt/transducer_v3_runtime.py +++ b/openadapt/transducer_v3_runtime.py @@ -172,6 +172,25 @@ def _items(payload: Any) -> list[str] | None: return None +def _norm_text(text: str) -> str: + return re.sub(r"\s+", " ", str(text)).strip().lower() + + +#: A saved value shorter than this is too easy to find by chance on a page, +#: so it confirms a write only in its own reopened field. +_MIN_VERBATIM_CHARS = 6 + + +@dataclass +class SavedWrite: + """A value the agent typed into one field before a commit.""" + + field_key: str + value: str + commit_index: int + confirmed: bool = False + + @dataclass class V3EpisodeState: """Per-``(run_id, task_id)`` state for the v3 hooks.""" @@ -197,6 +216,12 @@ class V3EpisodeState: # to: shell or file writes in the workspace, versus GUI / remote commits. workspace_commits: int = 0 non_workspace_commits: int = 0 + # Field-bound read-back: field key -> value typed since the latest commit; + # each commit turns them into writes that must reappear after the save. + drafts: dict[str, str] = field(default_factory=dict) + writes: list[SavedWrite] = field(default_factory=list) + typed_keys_since_commit: set[str] = field(default_factory=set) + identity_seen: bool = False class TransducerV3Hooks: @@ -540,6 +565,10 @@ def shell_gate( def note_commit(self, state: EpisodeState, action: Any) -> None: """Count a routed commit as a workspace write or a GUI/remote commit.""" ep = self.ep(state) + for key, value in ep.drafts.items(): + ep.writes.append(SavedWrite(key, value, state.next_commit_index)) + ep.drafts.clear() + ep.typed_keys_since_commit.clear() raw = _raw(action) or {} remote = ( raw.get("wire_mutation") is True @@ -595,6 +624,7 @@ def after_step( raw = _raw(action) if kind in _EDIT_ACTION_TYPES or raw.get("fs_write") is True: ep.mutated = True + self._note_drafts(ep, observation, action) if ep.obligations and kind in ("fill", "type", "input", "set_value"): text = _get(action, "text") or raw.get("value") or raw.get("text") or "" mark_drafted_from_action(ep.obligations, str(text)) @@ -928,6 +958,119 @@ def _abstain_egress( commit_index=state.next_commit_index, ) + # -- field-bound read-back --------------------------------------------- + @staticmethod + def _field_keys(observation: Any) -> dict[str, str]: + """selector -> field key (tag and visible label) for the screen's controls.""" + raw_obs = _get(observation, "raw_observation") + dom = raw_obs.get("dom_elements") if isinstance(raw_obs, Mapping) else None + keys: dict[str, str] = {} + for el in dom or []: + if not isinstance(el, Mapping): + continue + selector = str(el.get("selector") or "") + label = _norm_text(el.get("text") or el.get("name") or "") + if selector and label: + keys[selector] = f"{str(el.get('tag') or '').lower()}|{label}" + return keys + + def _note_drafts(self, ep: V3EpisodeState, observation: Any, action: Any) -> None: + """Remember which field each typed or selected value went into.""" + kind = _type(action) + raw = _raw(action) or {} + pairs: list[tuple[str, Any]] = [] + if kind in ("fill", "type", "input", "set_value", "select"): + target = ( + _get(action, "target_name") + or raw.get("target_name") + or raw.get("selector") + or (raw.get("parsed_json") or {}).get("target_name") + ) + value = ( + _get(action, "text") + or raw.get("value") + or raw.get("text") + or (raw.get("parsed_json") or {}).get("value") + or (raw.get("parsed_json") or {}).get("text") + ) + pairs.append((target, value)) + elif kind == "fill_form": + spec = ( + raw.get("form_plan") + if isinstance(raw.get("form_plan"), Mapping) + else {} + ) + for write in spec.get("fields", raw.get("fields")) or []: + if isinstance(write, Mapping): + pairs.append((write.get("selector"), write.get("value"))) + if not pairs: + return + keys = self._field_keys(observation) + for target, value in pairs: + key = keys.get(str(target or "")) + if key is None or value is None: + continue + ep.drafts[key] = str(value) + ep.typed_keys_since_commit.add(key) + + def observe_saved(self, state: EpisodeState, observation: Any, task: Any) -> None: + """Confirm writes that reappear on a saved screen of the pinned record. + + A careful operator checks each saved value where the app shows it, + often on more than one screen, and often by reopening the record. A + write is confirmed when, on a screen whose saved text shows every + pinned identity value, either its full value appears in that saved + text (values of at least ``_MIN_VERBATIM_CHARS`` characters), or the + same field shows the same value in a form the read-back provider marks + ``reopened`` (loaded again after the save and untouched since) and the + agent has not typed into that field since the save. + """ + ep = self.ep(state) + pins = [_norm_text(v) for v in self.owner.pinned.values() if str(v).strip()] + if not pins or not ep.writes: + return + back = self.readback(state, observation, task) + if back is None or back.get("is_toast") or back.get("is_editable"): + return + saved = _norm_text(back.get("readback_text") or "") + if not saved or not all(p in saved for p in pins): + return + ep.identity_seen = True + raw_obs = _get(observation, "raw_observation") + dom = raw_obs.get("dom_elements") if isinstance(raw_obs, Mapping) else None + reopened: dict[str, str] = {} + for el in dom or []: + if isinstance(el, Mapping) and el.get("reopened") is True: + label = _norm_text(el.get("text") or el.get("name") or "") + if label: + key = f"{str(el.get('tag') or '').lower()}|{label}" + reopened[key] = _norm_text(el.get("value") or "") + for w in ep.writes: + if w.confirmed or not w.value.strip(): + continue + value = _norm_text(w.value) + if ( + w.field_key not in ep.typed_keys_since_commit + and reopened.get(w.field_key) == value + ): + w.confirmed = True + elif len(value) >= _MIN_VERBATIM_CHARS and value in saved: + w.confirmed = True + + def _met_by_saved_writes( + self, ob: CompiledFieldObligation, writes: Sequence[SavedWrite] + ) -> bool: + """The obligation is a pinned identity value (the caller checks it was + seen on a saved screen), or its value sits whole inside a confirmed + write: ``units 1`` is not met by ``units 12``.""" + want = _norm_text(ob.expected_value) + if not want: + return False + if any(want == _norm_text(v) for v in self.owner.pinned.values()): + return True + token = re.compile(rf"(? Date: Tue, 1 Dec 2026 08:25:32 -0500 Subject: [PATCH 2/2] fix(transducer): confirm a verbatim write only as a whole token, never over a disagreeing reopened field Review (Grok) found that verbatim confirmation used an unanchored substring: a typed "CPT 29881; units 1" was confirmed by a screen showing "CPT 29881; units 12", and the run went VERIFIED. It also fell through to page text when the reopened form showed the field with a different value. A write now confirms from saved text only as a whole token (the boundary the obligation check already uses), and a reopened field that is on screen decides alone: a different value there is never overruled by page text elsewhere. Regression: the screen shows units 12 where units 1 was typed, on a summary and on a reopened form; the run ends unverified. --- openadapt/transducer_v3_runtime.py | 20 ++++++++++++++------ tests/test_transducer_v3_runtime.py | 10 ++++++++++ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/openadapt/transducer_v3_runtime.py b/openadapt/transducer_v3_runtime.py index 14eebb0364..d3c5aadd4a 100644 --- a/openadapt/transducer_v3_runtime.py +++ b/openadapt/transducer_v3_runtime.py @@ -176,6 +176,12 @@ def _norm_text(text: str) -> str: return re.sub(r"\s+", " ", str(text)).strip().lower() +def _whole_token(value: str, text: str) -> bool: + """``value`` appears in ``text`` as a whole token: ``units 1`` is not found + inside ``units 12``, nor ``PA1468922`` inside ``PA14689226``.""" + return re.search(rf"(? Non if w.confirmed or not w.value.strip(): continue value = _norm_text(w.value) - if ( - w.field_key not in ep.typed_keys_since_commit - and reopened.get(w.field_key) == value - ): - w.confirmed = True - elif len(value) >= _MIN_VERBATIM_CHARS and value in saved: + shown = reopened.get(w.field_key) + if shown is not None: + # The field itself is on screen in a reopened form: only an exact + # match there confirms it, and a different value there is never + # overruled by page text elsewhere. + if w.field_key not in ep.typed_keys_since_commit and shown == value: + w.confirmed = True + elif len(value) >= _MIN_VERBATIM_CHARS and _whole_token(value, saved): w.confirmed = True def _met_by_saved_writes( diff --git a/tests/test_transducer_v3_runtime.py b/tests/test_transducer_v3_runtime.py index 7a3603a43d..ff612ae139 100644 --- a/tests/test_transducer_v3_runtime.py +++ b/tests/test_transducer_v3_runtime.py @@ -348,3 +348,13 @@ def test_value_typed_after_the_save_does_not_confirm_it(): reopened = _fb_dom("CPT 29881; units 1", "2026-12-16", reopened=True) receipt = _fb_run(reopened, _HEADER, retype) assert receipt is None or receipt.outcome != ReceiptOutcome.VERIFIED + + +@pytest.mark.parametrize("reopened", [False, True]) +def test_longer_saved_value_on_screen_does_not_confirm_a_shorter_typed_one(reopened): + # Grok's case: the screen actually shows "units 12" where "units 1" was typed. + shown = "Comments: CPT 29881; units 12\nFrom: 2026-12-16" + dom = _fb_dom("CPT 29881; units 12", "2026-12-16", reopened=reopened) + receipt = _fb_run(dom, f"{_HEADER}\n{shown}") + assert receipt is not None # the run finished + assert receipt.outcome != ReceiptOutcome.VERIFIED