Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions openadapt/simplex_transducer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
167 changes: 167 additions & 0 deletions openadapt/transducer_v3_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"(?<![\w.-]){re.escape(value)}(?![\w-]|\.\w)", text) is not None


#: 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."""
Expand All @@ -197,6 +222,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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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"(?<![\w.-]){re.escape(want)}(?![\w-]|\.\w)")
return any(w.confirmed and token.search(_norm_text(w.value)) for w in writes)

# -- done gate --------------------------------------------------------
def readback(
self, state: EpisodeState, observation: Any, task: Any
Expand Down Expand Up @@ -1057,6 +1208,22 @@ def pre_done(
is_toast=bool(back.get("is_toast")),
completeness_auditor=self.completeness_auditor,
)
if (
not diff.all_verified
and self.completeness_auditor is None
and ep.identity_seen
and diff.missing_obligations
):
if all(
self._met_by_saved_writes(ob, ep.writes)
for ob in diff.missing_obligations
):
self._verified(
state, commit_idx, 1, "persisted_state_reacquisition",
"Every compiled field obligation is the pinned identity or a "
"write confirmed on a saved screen of the pinned record.",
) # fmt: skip
return action
if not diff.all_verified:
held = self._hold(
state, observation, task, history, budget,
Expand Down
110 changes: 110 additions & 0 deletions tests/test_transducer_v3_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,3 +248,113 @@ def kwargs(url, dom, shot, action, **options):
{"action": "click", "selector": "Open", "value": ""},
**expected,
)


# -- field-bound read-back: a save confirmed where its values reappear ----------

_FB_TASK = {
"instruction": (
"For Ada Quill, date of birth 1959-08-03, enter the comments exactly as: "
'"CPT 29881; units 1" and the start date 2026-12-16. Save it.'
)
}
_FB_PINNED = {"patient": "Ada Quill", "date_of_birth": "1959-08-03"}


def _fb_dom(comments="", start="", *, reopened=False):
return [
{"selector": "[f.c]", "tag": "input", "text": "Comments", "value": comments,
"reopened": reopened},
{"selector": "[f.s]", "tag": "input", "text": "From:", "value": start,
"reopened": reopened},
{"selector": "[f.save]", "tag": "button", "text": "Save", "value": ""},
] # fmt: skip


def _fb_obs(dom, readback):
return _observation(dom_elements=dom, readback_text=readback)


_FB_FILL = {
"type": "fill_form",
"raw_action": {
"form_plan": {
"fields": [
{
"selector": "[f.c]",
"name": "Comments",
"value": "CPT 29881; units 1",
},
{"selector": "[f.s]", "name": "From", "value": "2026-12-16"},
]
}
},
}
_FB_SAVE = {"type": "click", "target_name": "[f.save]", "is_commit": True}
_FB_EDIT = {"type": "click", "target_name": "[f.edit]"}
_HEADER = "Ada Quill DOB: 1959-08-03"
# The record view after the save cuts each value short, as some apps do.
_TRUNCATED = f"{_HEADER}\nComments: CPT 29881;\nFrom: 2026-12-16"


def _fb_run(after_save_dom, after_save_readback, *before_reopen):
# before_reopen actions run on the record view right after the save.
actions = [_FB_FILL, _FB_SAVE, *before_reopen, _FB_EDIT, {"type": "done"}]
wrapped, _ = _wrap(
*actions,
*([{"type": "done"}] * 4),
pinned=_FB_PINNED,
config=SupervisorConfig(enable_obligation_compiler=True),
)
wrapped.act(_fb_obs(_fb_dom(), _HEADER), _FB_TASK)
wrapped.act(_fb_obs(_fb_dom("CPT 29881; units 1", "2026-12-16"), _HEADER), _FB_TASK)
for _ in range(len(before_reopen) + 1):
wrapped.act(_fb_obs(_fb_dom(), _TRUNCATED), _FB_TASK)
for _ in range(5):
wrapped.act(_fb_obs(after_save_dom, after_save_readback), _FB_TASK)
receipt = wrapped.last_receipt
if receipt is not None:
break
return wrapped.last_receipt


def test_save_confirmed_in_reopened_untouched_form_verifies():
reopened = _fb_dom("CPT 29881; units 1", "2026-12-16", reopened=True)
receipt = _fb_run(reopened, _HEADER)
assert receipt is not None and receipt.outcome == ReceiptOutcome.VERIFIED


def test_reopened_form_on_another_record_does_not_verify():
reopened = _fb_dom("CPT 29881; units 1", "2026-12-16", reopened=True)
receipt = _fb_run(reopened, "Ada Quill DOB: 1966-04-24")
assert receipt is None or receipt.outcome != ReceiptOutcome.VERIFIED


def test_form_without_reload_evidence_does_not_verify():
# A failed save that leaves the typed values in the form.
echoed = _fb_dom("CPT 29881; units 1", "2026-12-16", reopened=False)
receipt = _fb_run(echoed, _HEADER)
assert receipt is None or receipt.outcome != ReceiptOutcome.VERIFIED


def test_longer_saved_value_does_not_meet_a_shorter_one():
reopened = _fb_dom("CPT 29881; units 12", "2026-12-16", reopened=True)
receipt = _fb_run(reopened, _HEADER)
assert receipt is None or receipt.outcome != ReceiptOutcome.VERIFIED


def test_value_typed_after_the_save_does_not_confirm_it():
retype = {"type": "type", "target_name": "[f.c]", "text": "CPT 29881; units 1"}
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