diff --git a/openadapt/simplex_transducer.py b/openadapt/simplex_transducer.py index 8f5803dbbf..dbc3b4f768 100644 --- a/openadapt/simplex_transducer.py +++ b/openadapt/simplex_transducer.py @@ -3826,11 +3826,54 @@ def _route_action_inner( action = self._v3.egress_gate(state, action, observation, task, history) if self._is_commit_boundary(action): + unscoped = self._v3.unscoped_resume_duplicate(state, task, action) + if unscoped is not None: + return self._abstain_action( + state, + trap_code="RESUME_DUPLICATE_UNCERTAIN", + reason=( + f"These values were saved before the restart (commit " + f"#{unscoped}) and no record identity is pinned, so it " + "cannot be told whether saving again would duplicate the " + "record. Handing the item to a person instead of saving." + ), + commit_index=unscoped, + ) + dup = self._v3.duplicate_of(state, task, action) + if dup is not None: + ep = self._v3.ep(state) + if dup in ep.duplicate_warned: + return self._abstain_action( + state, + trap_code="DUPLICATE_SAVE", + reason=( + f"The same values were saved before (commit #{dup}); " + "saving them again could duplicate the record." + ), + commit_index=dup, + ) + ep.duplicate_warned.add(dup) + self._deliver_intervention( + state, + kind="DUPLICATE_SAVE", + hint=( + f"DUPLICATE_SAVE: these exact values were already sent in " + f"commit #{dup} and may already be stored. Do not save them " + "again. Open the record and check whether it is there; if it " + "is, finish or continue with what is left." + ), + delta_note=f"duplicate_of={dup}", + fast_forward_obs=observation, + ) + return self._reenter(state, observation, task, history) self._v3.note_commit(state, action) fp = _commit_fingerprint(action, observation=observation) safe_summary = { "type": _action_type_str(action), "raw_action": self.vault.redact(_action_raw_dict(action)), + "field_writes": self.vault.redact( + self._v3.field_writes_for(state, commit_index) + ), } existing_rec = self.wal.get(run_id, task_id, commit_index) if existing_rec is None: diff --git a/openadapt/transducer_fact_ledger.py b/openadapt/transducer_fact_ledger.py index 27303226c6..979049aebd 100644 --- a/openadapt/transducer_fact_ledger.py +++ b/openadapt/transducer_fact_ledger.py @@ -701,6 +701,9 @@ def latch_gate( raw = _get(action, "raw_action") if isinstance(raw, Mapping) and raw.get("allow_duplicate") is True: return action + v3 = getattr(owner, "_v3", None) + if v3 is not None and v3.repeat_allowed(state, task, action): + return action # the task names this content again: not a re-submit key = submit_control_key(action) text = " ".join([submit_text(action), *state.form_latch.typed()]) hit = state.form_latch.match(key, text) diff --git a/openadapt/transducer_v3_runtime.py b/openadapt/transducer_v3_runtime.py index d3c5aadd4a..f19bcde3d4 100644 --- a/openadapt/transducer_v3_runtime.py +++ b/openadapt/transducer_v3_runtime.py @@ -195,6 +195,14 @@ class SavedWrite: value: str commit_index: int confirmed: bool = False + # Typed into the form that the commit saved (after the last non-commit + # click), as opposed to a search box on the way there. + in_form: bool = True + # Rebuilt from the on-disk WAL after a restart. + restored: bool = False + # The screen at commit time showed every pinned identity value: the save + # belongs to the pinned record. + on_record: bool = False @dataclass @@ -228,6 +236,16 @@ class V3EpisodeState: writes: list[SavedWrite] = field(default_factory=list) typed_keys_since_commit: set[str] = field(default_factory=set) identity_seen: bool = False + # Keys typed since the last non-commit click: the form a commit saves. + # The current screen's controls: selector -> (field key, container). The + # container (frame or form, when the read-back provider reports one) tells + # which fields a save button submits. + screen_map: dict[str, tuple[str, str]] = field(default_factory=dict) + draft_containers: dict[str, str] = field(default_factory=dict) + writes_restored: bool = False + screen_on_record: bool = False + duplicate_warned: set[int] = field(default_factory=set) + reconciled_notified: set[int] = field(default_factory=set) class TransducerV3Hooks: @@ -571,9 +589,19 @@ 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) + form = self._form_of(ep, action) for key, value in ep.drafts.items(): - ep.writes.append(SavedWrite(key, value, state.next_commit_index)) + ep.writes.append( + SavedWrite( + key, + value, + state.next_commit_index, + in_form=key in form, + on_record=ep.screen_on_record, + ) + ) ep.drafts.clear() + ep.draft_containers.clear() ep.typed_keys_since_commit.clear() raw = _raw(action) or {} remote = ( @@ -965,21 +993,6 @@ def _abstain_egress( ) # -- 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) @@ -1011,14 +1024,243 @@ def _note_drafts(self, ep: V3EpisodeState, observation: Any, action: Any) -> Non pairs.append((write.get("selector"), write.get("value"))) if not pairs: return - keys = self._field_keys(observation) + smap = self._screen_map(observation) for target, value in pairs: - key = keys.get(str(target or "")) - if key is None or value is None: + hit = smap.get(str(target or "")) + if hit is None or value is None: continue + key, container = hit ep.drafts[key] = str(value) + ep.draft_containers[key] = container ep.typed_keys_since_commit.add(key) + @staticmethod + def _screen_map(observation: Any) -> dict[str, tuple[str, str]]: + """selector -> (field key, container) for the screen's controls.""" + raw_obs = _get(observation, "raw_observation") + dom = raw_obs.get("dom_elements") if isinstance(raw_obs, Mapping) else None + out: dict[str, tuple[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: + container = str( + el.get("container") or el.get("form") or el.get("frame") or "" + ) + out[selector] = ( + f"{str(el.get('tag') or '').lower()}|{label}", + container, + ) + return out + + def _form_of(self, ep: V3EpisodeState, action: Any) -> set[str]: + """Draft fields that a save submits: still on screen when the save is + clicked and, when the provider reports containers, in the save + control's container. A search box in another frame or form is not part + of the save; a click inside the form (a date picker, the next field) + does not take a field out of it.""" + raw = _raw(action) or {} + target = str( + _get(action, "target_name") + or raw.get("target_name") + or raw.get("selector") + or (raw.get("parsed_json") or {}).get("target_name") + or "" + ) + target_container = ep.screen_map.get(target, ("", ""))[1] + on_screen = {key: cont for key, cont in ep.screen_map.values()} + form: set[str] = set() + for key in ep.drafts: + if key not in on_screen: + continue + cont = ep.draft_containers.get(key, "") or on_screen[key] + if target_container and cont and cont != target_container: + continue + form.add(key) + return form + + # -- crash resume ------------------------------------------------------- + def field_writes_for( + self, state: EpisodeState, commit_index: int + ) -> list[dict[str, Any]]: + """The writes a commit saved, for the WAL, so a restart can confirm them.""" + ep = self.ep(state) + return [ + { + "field_key": w.field_key, + "value": w.value, + "in_form": w.in_form, + "on_record": w.on_record, + } + for w in ep.writes + if w.commit_index == commit_index and not w.restored + ] + + def _restore_writes(self, state: EpisodeState, ep: V3EpisodeState) -> None: + """After a restart, rebuild each earlier commit's writes from the WAL.""" + if ep.writes_restored or not state.loaded_from_cold_wal: + return + ep.writes_restored = True + for rec in state.saga_commits: + summary = ( + rec.action_summary if isinstance(rec.action_summary, Mapping) else {} + ) + for fw in summary.get("field_writes") or []: + if isinstance(fw, Mapping) and fw.get("field_key"): + ep.writes.append( + SavedWrite( + str(fw["field_key"]), + str(fw.get("value") or ""), + rec.commit_index, + in_form=bool(fw.get("in_form", True)), + restored=True, + on_record=bool(fw.get("on_record", False)), + ) + ) + + @staticmethod + def _form_groups( + ep: V3EpisodeState, *, on_record_only: bool = False + ) -> dict[tuple[int, bool], dict[str, str]]: + """(commit index, restored) -> {field key: value} of what that commit's form saved.""" + groups: dict[tuple[int, bool], dict[str, str]] = {} + for w in ep.writes: + if on_record_only and not w.on_record: + continue + if w.in_form and w.value.strip(): + groups.setdefault((w.commit_index, w.restored), {})[w.field_key] = ( + _norm_text(w.value) + ) + return groups + + def _reconcile_restored( + self, state: EpisodeState, ep: V3EpisodeState, observation: Any + ) -> None: + """A commit from before the restart whose saved values are all on screen + again (for the pinned record) is stored: mark it verified and say so.""" + for (idx, restored), _values in self._form_groups(ep).items(): + if not restored or idx in ep.reconciled_notified: + continue + group = [ + w + for w in ep.writes + if w.restored + and w.commit_index == idx + and w.in_form + and w.value.strip() + ] + if group and all(w.confirmed for w in group): + ep.reconciled_notified.add(idx) + self.owner._mark_verified(state, idx, tier=1) + self.owner._deliver_intervention( + state, + kind="COMMIT_ALREADY_SAVED", + hint=( + f"COMMIT_ALREADY_SAVED: the save from before the restart (commit " + f"#{idx}) is already stored for this record; its values are on " + "screen. Do not enter it again. Continue with what is left, or finish." + ), + delta_note=f"restored_commit_confirmed={idx}", + fast_forward_obs=observation, + ) + + def _current_form(self, ep: V3EpisodeState, action: Any) -> dict[str, str]: + form = self._form_of(ep, action) + return { + k: _norm_text(v) + for k, v in ep.drafts.items() + if k in form and str(v).strip() + } + + def _times_task_names( + self, state: EpisodeState, task: Any, values: Mapping[str, str] + ) -> int: + """How many times the instruction names this content (its longest value). + A task that wants two identical entries names the content twice.""" + longest = max(values.values(), key=len, default="") + if len(longest) < _MIN_VERBATIM_CHARS: + return 1 + return max(1, _norm_text(self._instruction(state, task)).count(longest)) + + def repeat_allowed( + self, state: EpisodeState, task: Any, action: Any = None + ) -> bool: + """The form about to be saved repeats earlier content the task asks for again.""" + ep = self.ep(state) + current = self._current_form(ep, action) + if not current: + return False + same = sum(1 for v in self._form_groups(ep).values() if v == current) + return 0 < same < self._times_task_names(state, task, current) + + def duplicate_of( + self, state: EpisodeState, task: Any = None, action: Any = None + ) -> int | None: + """The earlier commit, on the same pinned record, whose form saved exactly + the values about to be saved, beyond what the task asks for. + + Saving the same values again on the same record makes a second entry, + or re-saves one that exists. A commit from before a restart counts even + if it was never confirmed: it may already be stored. The same values on + another record, or repeats the task names, are not duplicates. Without a + pinned record identity there is no record to scope to, so nothing is + refused. + """ + ep = self.ep(state) + if not [v for v in self.owner.pinned.values() if str(v).strip()]: + return None + if not ep.screen_on_record: + return None + current = self._current_form(ep, action) + if not current: + return None + same = [ + idx + for (idx, _r), values in self._form_groups(ep, on_record_only=True).items() + if values == current + ] + if not same or len(same) < self._times_task_names(state, task, current): + return None + return same[0] + + def unscoped_resume_duplicate( + self, state: EpisodeState, task: Any = None, action: Any = None + ) -> int | None: + """Without a pinned record identity, a save after a restart whose values + equal a commit from before the restart cannot be scoped to a record: it + may duplicate that commit. Return that commit so the item goes to a + person instead of being saved.""" + ep = self.ep(state) + if [v for v in self.owner.pinned.values() if str(v).strip()]: + return None + if not any(w.restored for w in ep.writes): + return None + current = self._current_form(ep, action) + if not current: + return None + restored = { + idx: values + for (idx, was_restored), values in self._form_groups(ep).items() + if was_restored + } + for idx, values in restored.items(): + if values == current: + return idx + return None + + def has_duplicate_commits(self, state: EpisodeState, task: Any = None) -> bool: + """More commits on the pinned record carried identical values than the task names.""" + ep = self.ep(state) + groups = [v for v in self._form_groups(ep, on_record_only=True).values() if v] + for g in groups: + if sum(1 for h in groups if h == g) > self._times_task_names( + state, task, g + ): + return True + return False + def observe_saved(self, state: EpisodeState, observation: Any, task: Any) -> None: """Confirm writes that reappear on a saved screen of the pinned record. @@ -1032,14 +1274,18 @@ def observe_saved(self, state: EpisodeState, observation: Any, task: Any) -> Non agent has not typed into that field since the save. """ ep = self.ep(state) + ep.screen_map = self._screen_map(observation) + self._restore_writes(state, ep) pins = [_norm_text(v) for v in self.owner.pinned.values() if str(v).strip()] - if not pins or not ep.writes: + if not pins: return back = self.readback(state, observation, task) if back is None or back.get("is_toast") or back.get("is_editable"): + ep.screen_on_record = False return saved = _norm_text(back.get("readback_text") or "") - if not saved or not all(p in saved for p in pins): + ep.screen_on_record = bool(saved) and all(p in saved for p in pins) + if not ep.screen_on_record or not ep.writes: return ep.identity_seen = True raw_obs = _get(observation, "raw_observation") @@ -1064,6 +1310,7 @@ def observe_saved(self, state: EpisodeState, observation: Any, task: Any) -> Non w.confirmed = True elif len(value) >= _MIN_VERBATIM_CHARS and _whole_token(value, saved): w.confirmed = True + self._reconcile_restored(state, ep, observation) def _met_by_saved_writes( self, ob: CompiledFieldObligation, writes: Sequence[SavedWrite] @@ -1208,6 +1455,13 @@ def pre_done( is_toast=bool(back.get("is_toast")), completeness_auditor=self.completeness_auditor, ) + if self.has_duplicate_commits(state, task): + self._release_unverified( + state, + commit_idx, + "Two saves carried the same values: the record may be duplicated.", + ) + return action if ( not diff.all_verified and self.completeness_auditor is None diff --git a/tests/test_transducer_v3_runtime.py b/tests/test_transducer_v3_runtime.py index ff612ae139..41171a040c 100644 --- a/tests/test_transducer_v3_runtime.py +++ b/tests/test_transducer_v3_runtime.py @@ -350,6 +350,256 @@ def test_value_typed_after_the_save_does_not_confirm_it(): assert receipt is None or receipt.outcome != ReceiptOutcome.VERIFIED +# -- crash resume: confirm pre-crash saves from the WAL, refuse a duplicate ------- + + +def _crash_wrap(tmp_path, *actions): + from openadapt.simplex_transducer import WriteAheadSagaLog + + agent = Mock() + agent.act.side_effect = list(actions) + [{"type": "done"}] * 6 + wrapped = SimplexTransducer( + agent, + wal=WriteAheadSagaLog(tmp_path / "wal.jsonl"), + pinned=_FB_PINNED, + config=SupervisorConfig(enable_obligation_compiler=True), + ) + return wrapped, agent + + +def _first_session(tmp_path): + wrapped, _ = _crash_wrap(tmp_path, _FB_FILL, _FB_SAVE) + 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) + # the process dies here, after the save was sent + + +def test_commit_persists_the_values_it_saved(tmp_path): + import json as _json + + _first_session(tmp_path) + rows = [ + _json.loads(x) for x in (tmp_path / "wal.jsonl").read_text().splitlines() if x + ] + writes = [ + fw + for r in rows + for fw in (r.get("action_summary") or {}).get("field_writes") or [] + ] + assert {fw["value"] for fw in writes if fw["in_form"]} == { + "CPT 29881; units 1", + "2026-12-16", + } + + +def test_restart_confirms_the_pre_crash_save_on_screen(tmp_path): + _first_session(tmp_path) + wrapped, agent = _crash_wrap(tmp_path, _FB_EDIT) + reopened = _fb_dom("CPT 29881; units 1", "2026-12-16", reopened=True) + wrapped.act(_fb_obs(reopened, _HEADER), _FB_TASK) + state = wrapped.get_state("default-run", "default-task") + hints = [str(iv) for iv in state.intervention_log] + assert any("COMMIT_ALREADY_SAVED" in h for h in hints) + from openadapt.simplex_transducer import SagaState + + assert any( + c.state is SagaState.VERIFIED + for c in wrapped.wal.commits_for("default-run", "default-task") + ) + + +def test_restart_refuses_to_save_the_same_values_again(tmp_path): + _first_session(tmp_path) + # the fresh session repeats the whole item without checking first + wrapped, agent = _crash_wrap(tmp_path, _FB_FILL, _FB_SAVE, _FB_SAVE, _FB_SAVE) + wrapped.act(_fb_obs(_fb_dom(), _HEADER), _FB_TASK) + filled = _fb_dom("CPT 29881; units 1", "2026-12-16") + first = wrapped.act(_fb_obs(filled, _HEADER), _FB_TASK) + state = wrapped.get_state("default-run", "default-task") + assert any("DUPLICATE_SAVE" in str(iv) for iv in state.intervention_log) + assert not (isinstance(first, dict) and first.get("is_commit")) + second = wrapped.act(_fb_obs(filled, _HEADER), _FB_TASK) + assert getattr(second, "is_abstained", False) + assert second.raw_action["trap_code"] == "DUPLICATE_SAVE" + + +def test_identical_re_save_in_one_session_is_not_released(tmp_path): + # In one process the in-memory form latch already stops this; the WAL-based + # duplicate check is what covers it after a restart. + wrapped, _ = _crash_wrap(tmp_path, _FB_FILL, _FB_SAVE, _FB_FILL, _FB_SAVE, _FB_SAVE) + filled = _fb_dom("CPT 29881; units 1", "2026-12-16") + for dom in (_fb_dom(), filled, _fb_dom(), filled): + out = wrapped.act(_fb_obs(dom, _HEADER), _FB_TASK) + state = wrapped.get_state("default-run", "default-task") + hints = " ".join(str(iv) for iv in state.intervention_log) + assert "DUPLICATE_SAVE" in hints or "FORM_COMMIT_LATCHED" in hints + assert not (isinstance(out, dict) and out.get("is_commit")) + + +def _item_run(tmp_path, pinned, header, task): + from openadapt.simplex_transducer import WriteAheadSagaLog + + agent = Mock() + agent.act.side_effect = [_FB_FILL, _FB_SAVE, _FB_EDIT] + [{"type": "done"}] * 5 + wrapped = SimplexTransducer( + agent, + wal=WriteAheadSagaLog(tmp_path / "wal.jsonl"), # one WAL for the whole batch + pinned=pinned, + config=SupervisorConfig(enable_obligation_compiler=True), + ) + filled = _fb_dom("CPT 29881; units 1", "2026-12-16") + reopened = _fb_dom("CPT 29881; units 1", "2026-12-16", reopened=True) + wrapped.act(_fb_obs(_fb_dom(), header), task) + wrapped.act(_fb_obs(filled, header), task) + for _ in range(6): + wrapped.act(_fb_obs(reopened, header), task) + if wrapped.last_receipt is not None: + break + return wrapped.last_receipt + + +def test_same_values_on_two_records_both_verify(tmp_path): + # The same note on two patients, one task item per patient, one batch WAL. + a = {"task_id": "item-a", **_FB_TASK} + b = { + "task_id": "item-b", + "instruction": _FB_TASK["instruction"].replace( + "Ada Quill, date of birth 1959-08-03", "Bo Reyes, date of birth 1970-02-11" + ), + } + ra = _item_run(tmp_path, _FB_PINNED, _HEADER, a) + rb = _item_run( + tmp_path, + {"patient": "Bo Reyes", "date_of_birth": "1970-02-11"}, + "Bo Reyes DOB: 1970-02-11", + b, + ) + assert ra is not None and ra.outcome == ReceiptOutcome.VERIFIED + assert rb is not None and rb.outcome == ReceiptOutcome.VERIFIED + + +def test_task_that_names_two_identical_entries_verifies(tmp_path): + from openadapt.simplex_transducer import WriteAheadSagaLog + + task = { + "instruction": ( + "For Ada Quill, date of birth 1959-08-03, add two entries, each with the " + 'comments exactly as: "CPT 29881; units 1" and the start date 2026-12-16. ' + 'First entry: "CPT 29881; units 1". Second entry: "CPT 29881; units 1".' + ) + } + agent = Mock() + agent.act.side_effect = [_FB_FILL, _FB_SAVE, _FB_FILL, _FB_SAVE, _FB_EDIT] + [ + {"type": "done"} + ] * 5 + wrapped = SimplexTransducer( + agent, + wal=WriteAheadSagaLog(tmp_path / "wal.jsonl"), + pinned=_FB_PINNED, + config=SupervisorConfig(enable_obligation_compiler=True), + ) + filled = _fb_dom("CPT 29881; units 1", "2026-12-16") + reopened = _fb_dom("CPT 29881; units 1", "2026-12-16", reopened=True) + released = [] + for dom in (_fb_dom(), filled, _fb_dom(), filled): + released.append(wrapped.act(_fb_obs(dom, _HEADER), task)) + assert sum(1 for x in released if isinstance(x, dict) and x.get("is_commit")) == 2 + for _ in range(6): + wrapped.act(_fb_obs(reopened, _HEADER), task) + if wrapped.last_receipt is not None: + break + state = wrapped.get_state("default-run", "default-task") + assert not any("DUPLICATE_SAVE" in str(iv) or "FORM_COMMIT_LATCHED" in str(iv) + for iv in state.intervention_log) # fmt: skip + assert wrapped.last_receipt is not None + assert wrapped.last_receipt.outcome == ReceiptOutcome.VERIFIED + + +_FB_CLICK_IN_FORM = { + "type": "click", + "target_name": "[f.s]", +} # e.g. opens a date picker + + +def test_click_inside_the_form_keeps_fields_in_the_save_after_a_restart(tmp_path): + # fill, a non-save click on a form field, save; crash; the fresh session does the same + first, _ = _crash_wrap(tmp_path, _FB_FILL, _FB_CLICK_IN_FORM, _FB_SAVE) + filled = _fb_dom("CPT 29881; units 1", "2026-12-16") + for dom in (_fb_dom(), filled, filled): + first.act(_fb_obs(dom, _HEADER), _FB_TASK) + state = first.get_state("default-run", "default-task") + assert {w.value for w in first._v3.ep(state).writes if w.in_form} == { + "CPT 29881; units 1", + "2026-12-16", + } + again, _ = _crash_wrap( + tmp_path, _FB_FILL, _FB_CLICK_IN_FORM, _FB_SAVE, _FB_SAVE, _FB_SAVE + ) + for dom in (_fb_dom(), filled, filled): + out = again.act(_fb_obs(dom, _HEADER), _FB_TASK) + state = again.get_state("default-run", "default-task") + assert any("DUPLICATE_SAVE" in str(iv) for iv in state.intervention_log) + assert not (isinstance(out, dict) and out.get("is_commit")) + + +def test_type_a_click_b_type_b_keeps_both_fields(tmp_path): + type_a = {"type": "type", "target_name": "[f.c]", "text": "CPT 29881; units 1"} + type_b = {"type": "type", "target_name": "[f.s]", "text": "2026-12-16"} + wrapped, _ = _crash_wrap(tmp_path, type_a, _FB_CLICK_IN_FORM, type_b, _FB_SAVE) + for dom in ( + _fb_dom(), + _fb_dom("CPT 29881; units 1"), + _fb_dom("CPT 29881; units 1"), + _fb_dom("CPT 29881; units 1", "2026-12-16"), + ): + wrapped.act(_fb_obs(dom, _HEADER), _FB_TASK) + state = wrapped.get_state("default-run", "default-task") + assert {w.value for w in wrapped._v3.ep(state).writes if w.in_form} == { + "CPT 29881; units 1", + "2026-12-16", + } + + +def test_search_box_in_another_container_is_not_part_of_the_save(tmp_path): + search = {"type": "type", "target_name": "[m.q]", "text": "Quill"} + wrapped, _ = _crash_wrap(tmp_path, search, _FB_FILL, _FB_SAVE) + + def dom(c="", s=""): + rows = [dict(e, container="form") for e in _fb_dom(c, s)] + return rows + [{"selector": "[m.q]", "tag": "input", "text": "Search", + "value": "Quill", "container": "main"}] # fmt: skip + + for d in (dom(), dom(), dom("CPT 29881; units 1", "2026-12-16")): + wrapped.act(_fb_obs(d, _HEADER), _FB_TASK) + state = wrapped.get_state("default-run", "default-task") + in_form = {w.value for w in wrapped._v3.ep(state).writes if w.in_form} + assert in_form == {"CPT 29881; units 1", "2026-12-16"} + + +def test_unpinned_resumed_save_with_pre_crash_values_goes_to_a_person(tmp_path): + from openadapt.simplex_transducer import WriteAheadSagaLog + + def unpinned(*actions): + agent = Mock() + agent.act.side_effect = list(actions) + [{"type": "done"}] * 6 + return SimplexTransducer( + agent, + wal=WriteAheadSagaLog(tmp_path / "wal.jsonl"), + config=SupervisorConfig(enable_obligation_compiler=True), + ) + + filled = _fb_dom("CPT 29881; units 1", "2026-12-16") + first = unpinned(_FB_FILL, _FB_SAVE) + first.act(_fb_obs(_fb_dom(), _HEADER), _FB_TASK) + first.act(_fb_obs(filled, _HEADER), _FB_TASK) + # crash; the fresh session repeats the item with no record identity to scope to + again = unpinned(_FB_FILL, _FB_SAVE) + again.act(_fb_obs(_fb_dom(), _HEADER), _FB_TASK) + out = again.act(_fb_obs(filled, _HEADER), _FB_TASK) + assert getattr(out, "is_abstained", False) + assert out.raw_action["trap_code"] == "RESUME_DUPLICATE_UNCERTAIN" + + @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.