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..d3c5aadd4a 100644 --- a/openadapt/transducer_v3_runtime.py +++ b/openadapt/transducer_v3_runtime.py @@ -172,6 +172,31 @@ def _items(payload: Any) -> list[str] | None: return None +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"(? 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 +571,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 +630,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 +964,121 @@ 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) + 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( + 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"(?