diff --git a/capabilities/04-the-core-a-checked-entry-every-time/0318-checkbox-attestations-declared-in-pack-data-a.md b/capabilities/04-the-core-a-checked-entry-every-time/0318-checkbox-attestations-declared-in-pack-data-a.md new file mode 100644 index 0000000000..d0098374e0 --- /dev/null +++ b/capabilities/04-the-core-a-checked-entry-every-time/0318-checkbox-attestations-declared-in-pack-data-a.md @@ -0,0 +1 @@ +| Checkbox attestations declared in pack data: a declared box is ticked only on a person's grant for its pinned statement digest, never through an intake value or derived fact; an undeclared box, changed wording, a missing grant or an attestation bound to a field stops the run before anything is ticked | On main ([#2501](https://github.com/OpenAdaptAI/OpenAdapt/pull/2501)) | Synthetic: a web form, an EMR-like chart dialog, a SaaS switch (headless Chromium) and a spreadsheet-like grid dialog with no browser | `openadapt_flow.gui.attestations`, `packages/flow/tests/gui` | diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index c75eb8811d..b2d403f417 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -15,6 +15,15 @@ +## Unreleased + +- Checkbox attestations (`openadapt_flow.gui.attestations`) are declared in + pack data with the digest of their statement and ticked only on an + `AttestationGrant` from the person who attests. A grant is its own type, so + no intake value or derived fact can tick one. An undeclared box, changed + wording, a missing grant or an attestation bound to a field stops the run + before any box is ticked. + ## v4.0.0 (2026-11-24) ### Breaking Changes diff --git a/packages/flow/docs/FAIL_CLOSED.md b/packages/flow/docs/FAIL_CLOSED.md index fc9ec70c56..f7cc47c3ab 100644 --- a/packages/flow/docs/FAIL_CLOSED.md +++ b/packages/flow/docs/FAIL_CLOSED.md @@ -293,6 +293,8 @@ Done: - [x] `tx/wire_tap.relay_redirect_location` (C6): registered after #2470. - [x] `gui.steps.judge_step` (C3 C5): new. A commit holds only on exactly the demonstrated writes; an unlisted step role is not checked. +- [x] `gui.attestations.judge_attestations` (C1 C2 C5): new. The plan's boxes + are the obligations; a box the plan never saw is unexpected. Next, most bug-prone first: diff --git a/packages/flow/openadapt_flow/gui/__init__.py b/packages/flow/openadapt_flow/gui/__init__.py index bbcddd672a..65a3e2124b 100644 --- a/packages/flow/openadapt_flow/gui/__init__.py +++ b/packages/flow/openadapt_flow/gui/__init__.py @@ -8,6 +8,8 @@ - :mod:`openadapt_flow.gui.steps`: a link, a tab or a button can be a step, and the step that commits is the one the demonstration showed writing. +- :mod:`openadapt_flow.gui.attestations`: a checkbox that states something + is ticked only on a person's grant, never through a fact. Per-app facts (which control, which words, how many writes) are pack data, learned from a demonstration or declared by the pack author. The engine holds diff --git a/packages/flow/openadapt_flow/gui/attestations.py b/packages/flow/openadapt_flow/gui/attestations.py new file mode 100644 index 0000000000..d66183d805 --- /dev/null +++ b/packages/flow/openadapt_flow/gui/attestations.py @@ -0,0 +1,562 @@ +"""Checkbox attestations: declared in pack data, ticked only on a person's grant. + +Some checkboxes are not data. "I confirm the information above is true", "I +attest that I reviewed this list", "I understand this cannot be undone": a +tick there is a statement someone makes. Packs used to bind such a box to an +intake fact (``confirm_details: true``) or a derived flag, so the run ticked +it on its own. This module separates the two: + +- An :class:`AttestationSpec` is pack data: which box, and the SHA-256 of its + statement as the demonstration showed it (:func:`statement_digest`). +- An :class:`AttestationGrant` is given to the run by the person who + attests, for one statement digest. It is its own type: an intake value, a + derived fact, a bool or a mapping is refused (:func:`plan_checkboxes` + raises ``TypeError``), so nothing can tick an attestation through a fact. +- :func:`check_pack` refuses a pack whose field bindings name a declared + attestation. + +:func:`plan_checkboxes` decides, for every checkbox or switch on the screen: + +- ``field``: a field binding covers it; it is not an attestation. +- ``tick``: it matches exactly one declared attestation whose statement still + hashes to the pinned digest, the run holds a grant for that digest, and the + box is not ticked yet. +- ``leave``: the pack lists it as knowingly left alone (``ignored``), and it + shows the state the pack declared. +- ``stop``: anything else. An undeclared checkbox, a changed statement, a + missing or mismatched grant, an attestation bound to a field, a box ticked + before the run touched it, two specs matching one box, or one spec + matching several boxes (one grant covers one box). The run stops + before acting on any box. + +:func:`judge_attestations` is a verdict site. Its obligations are the plan's +boxes (other than ``field`` ones), fixed before any tick, and it settles them +against a fresh read: each must show the planned state with the same +statement, and a box the plan never saw is unexpected. + +Words are never matched against a list: an attestation is whatever the pack +declares, and the engine knows no "I agree" vocabulary. +""" + +from __future__ import annotations + +import hashlib +from dataclasses import dataclass +from enum import Enum +from typing import Any, Iterable, Literal, Mapping, Optional, Sequence + +from openadapt_flow.gui.model import ( + Actuator, + Control, + ControlSpec, + DemoStep, + Screen, + norm, +) +from openadapt_flow.verdict import ( + Obligations, + Observed, + Result, + Settlement, + Status, + Subject, + settle, +) +from openadapt_flow.verdict_sites import verdict_site + +__all__ = [ + "AttestationCandidate", + "AttestationGrant", + "AttestationPlan", + "AttestationSpec", + "BoxDecision", + "BoxPlan", + "IgnoredBox", + "PackError", + "apply_attestations", + "check_pack", + "judge_attestations", + "learn_attestations", + "judge_screen", + "plan_checkboxes", + "plan_rows", + "statement_digest", + "statement_of", +] + +BOX_ROLES = frozenset({"checkbox", "switch"}) +#: Longest statement read from a container; a longer one is not read whole. +STATEMENT_CAP = 2000 + + +def statement_digest(text: str) -> str: + """SHA-256 of a statement after :func:`~openadapt_flow.gui.model.norm`.""" + + return hashlib.sha256(norm(text).encode("utf-8")).hexdigest() + + +@dataclass(frozen=True) +class AttestationSpec: + """Pack data: one attestation box and the digest of its statement. + + ``statement_from`` says where the statement is: the box's own label + (``name``), or the text of the innermost container around it + (``container``), for a box labelled "I agree" under a paragraph.""" + + attestation_id: str + control: ControlSpec + statement_sha256: str + statement_from: Literal["name", "container"] = "name" + + def __post_init__(self) -> None: + if self.control.role not in BOX_ROLES: + raise ValueError("an attestation is a checkbox or a switch") + if len(self.statement_sha256) != 64: + raise ValueError("statement_sha256 is a SHA-256 hex digest") + if self.statement_from not in ("name", "container"): + raise ValueError(f"unknown statement source {self.statement_from!r}") + + +def statement_of(ctrl: Control, source: str = "name") -> Optional[str]: + """The statement a box carries: its label, or its innermost container's + text. None when there is none, or it may have been cut short.""" + + if source == "name": + return ctrl.name or None + if source != "container" or not ctrl.containers: + return None + text = ctrl.containers[-1].text + if not text or len(text) >= STATEMENT_CAP: + return None + return text + + +@dataclass(frozen=True) +class AttestationGrant: + """A person's attestation for one run: this statement, by this person. + + Built from the run request by whoever collects the attestation, never + from intake values.""" + + attestation_id: str + statement_sha256: str + granted_by: str + + def __post_init__(self) -> None: + if not self.granted_by.strip(): + raise ValueError("a grant names the person who attests") + + +@dataclass(frozen=True) +class IgnoredBox: + """A checkbox the pack knowingly leaves alone, and the state it must show.""" + + control: ControlSpec + checked: bool = False + + +class PackError(ValueError): + """The pack binds a declared attestation to a field.""" + + +def check_pack( + attestations: Sequence[AttestationSpec], + field_controls: Iterable[ControlSpec], +) -> None: + """Refuse a pack whose field bindings name a declared attestation's box + (same role and name). Raises :class:`PackError`.""" + + declared = {(a.control.role, norm(a.control.name)): a for a in attestations} + for spec in field_controls: + hit = declared.get((spec.role, norm(spec.name))) + if hit is not None: + raise PackError( + f"attestation {hit.attestation_id!r} is bound to a field; " + "an attestation is ticked only on a grant" + ) + ids = [a.attestation_id for a in attestations] + if len(ids) != len(set(ids)): + raise PackError("two attestations share an id") + + +class BoxDecision(str, Enum): + FIELD = "field" + TICK = "tick" + LEAVE = "leave" + STOP = "stop" + + +@dataclass(frozen=True) +class BoxPlan: + handle: str + name: str + decision: BoxDecision + digest: str + #: The state the box must show after the plan is applied (None: a field's). + want_checked: Optional[bool] + attestation_id: Optional[str] = None + granted_by: str = "" + reason: str = "" + statement_from: str = "name" + + +@dataclass(frozen=True) +class AttestationPlan: + boxes: tuple[BoxPlan, ...] + run_id: str = "" + + @property + def stops(self) -> tuple[BoxPlan, ...]: + return tuple(b for b in self.boxes if b.decision is BoxDecision.STOP) + + @property + def ticks(self) -> tuple[BoxPlan, ...]: + return tuple(b for b in self.boxes if b.decision is BoxDecision.TICK) + + +def _stop(ctrl: Control, reason: str, att: Optional[str] = None) -> BoxPlan: + return BoxPlan( + ctrl.handle, + ctrl.name, + BoxDecision.STOP, + statement_digest(ctrl.name), + None, + att, + reason=reason, + ) + + +def _grants_by_id(grants: Iterable[object]) -> dict[str, AttestationGrant]: + out: dict[str, AttestationGrant] = {} + for grant in grants: + if not isinstance(grant, AttestationGrant): + raise TypeError( + "attestations are ticked only on an AttestationGrant, " + f"not on {type(grant).__name__}" + ) + if grant.attestation_id in out: + raise ValueError(f"two grants for {grant.attestation_id!r}") + out[grant.attestation_id] = grant + return out + + +def plan_checkboxes( + screen: Screen, + *, + attestations: Sequence[AttestationSpec], + grants: Iterable[object] = (), + bound: Iterable[str] = (), + ignored: Sequence[IgnoredBox] = (), + run_id: str = "", +) -> AttestationPlan: + """Decide every checkbox and switch on ``screen`` (see the module doc). + + ``bound`` holds the handles the pack's field bindings resolved to on this + screen. ``grants`` must all be :class:`AttestationGrant`.""" + + by_id = _grants_by_id(grants) + bound_set = set(bound) + boxes: list[BoxPlan] = [] + # One grant covers one box: a spec that names several boxes on the + # screen (two identical "I agree" boxes) stops on every one of them. + matches = { + a.attestation_id: sum( + 1 for c in screen.controls if c.role in BOX_ROLES and a.control.matches(c) + ) + for a in attestations + } + for ctrl in screen.controls: + if ctrl.role not in BOX_ROLES: + continue + specs = [a for a in attestations if a.control.matches(ctrl)] + if ctrl.handle in bound_set: + if specs: + boxes.append( + _stop( + ctrl, + "a declared attestation is bound to a field", + specs[0].attestation_id, + ) + ) + else: + boxes.append( + BoxPlan( + ctrl.handle, + ctrl.name, + BoxDecision.FIELD, + statement_digest(ctrl.name), + None, + ) + ) + continue + if len(specs) > 1: + boxes.append(_stop(ctrl, "two declared attestations match this box")) + continue + if specs and matches[specs[0].attestation_id] > 1: + boxes.append( + _stop( + ctrl, + "the attestation's spec matches more than one box", + specs[0].attestation_id, + ) + ) + continue + if not specs: + leave = [i for i in ignored if i.control.matches(ctrl)] + if len(leave) == 1 and ctrl.checked is leave[0].checked: + boxes.append( + BoxPlan( + ctrl.handle, + ctrl.name, + BoxDecision.LEAVE, + statement_digest(ctrl.name), + leave[0].checked, + ) + ) + elif len(leave) == 1: + boxes.append( + _stop( + ctrl, "a box the pack leaves alone is not in its declared state" + ) + ) + else: + boxes.append(_stop(ctrl, "a checkbox the pack does not declare")) + continue + spec = specs[0] + statement = statement_of(ctrl, spec.statement_from) + digest = statement_digest(statement or "") + grant = by_id.get(spec.attestation_id) + if statement is None: + boxes.append( + _stop( + ctrl, "the statement could not be read whole", spec.attestation_id + ) + ) + elif digest != spec.statement_sha256: + boxes.append( + _stop( + ctrl, + "the statement differs from the declared one", + spec.attestation_id, + ) + ) + elif grant is None: + boxes.append( + _stop( + ctrl, + "no one attested this statement for this run", + spec.attestation_id, + ) + ) + elif grant.statement_sha256 != digest: + boxes.append( + _stop( + ctrl, "the grant is for a different statement", spec.attestation_id + ) + ) + elif ctrl.checked is not False: + boxes.append( + _stop( + ctrl, + "the box was ticked before the run touched it", + spec.attestation_id, + ) + ) + elif ctrl.disabled or ctrl.readonly: + boxes.append(_stop(ctrl, "the box cannot be ticked", spec.attestation_id)) + else: + boxes.append( + BoxPlan( + ctrl.handle, + ctrl.name, + BoxDecision.TICK, + digest, + True, + spec.attestation_id, + grant.granted_by, + statement_from=spec.statement_from, + ) + ) + return AttestationPlan(tuple(boxes), run_id) + + +def apply_attestations(actuator: Actuator, plan: AttestationPlan) -> Screen: + """Tick the plan's ``tick`` boxes and return a fresh read. Refuses a plan + with any ``stop``: nothing is ticked.""" + + if plan.stops: + raise ValueError(f"the plan stops: {plan.stops[0].reason}") + for box in plan.ticks: + actuator.set_checked(box.handle, True) + return actuator.observe() + + +# -- the verdict ------------------------------------------------------------------ + + +def _obs_of(screen: Screen, plan: AttestationPlan) -> list[dict[str, Any]]: + """A fresh read of every box, bound to the run that read it. Each box's + statement is read from where the plan read it.""" + + source = {b.handle: b.statement_from for b in plan.boxes} + return [ + { + "handle": c.handle, + "statement": statement_of(c, source.get(c.handle, "name")), + "checked": c.checked, + "run_id": plan.run_id, + } + for c in screen.controls + if c.role in BOX_ROLES + ] + + +@dataclass(frozen=True) +class AttestationVerdict: + settlement: Settlement + status: Status + + +@verdict_site("gui.attestations.judge", classes="C1 C2 C5") +def judge_attestations( + plan: Sequence[Mapping[str, Any]], + after: Sequence[Mapping[str, Any]], + *, + run_id: str, + complete: bool = True, +) -> AttestationVerdict: + """Settle the plan's boxes against a fresh read of the screen. + + ``plan`` rows carry ``handle``, ``decision``, ``digest`` and + ``want_checked``; ``after`` rows carry ``handle``, ``statement``, + ``checked`` and ``run_id``. ``field`` rows are a binding's business and are left out. + A ``stop`` row is an obligation that can never hold. A box must show the + planned state with a statement that still hashes to the planned digest; + a read whose ``checked`` is not a bool is not checked, and a box the plan + never saw is unexpected. ``complete=False`` (a capped read) can refute, + never hold.""" + + planned = [p for p in plan if p.get("decision") != BoxDecision.FIELD.value] + fields = { + p.get("handle") for p in plan if p.get("decision") == BoxDecision.FIELD.value + } + obligations = Obligations.fix( + ( + Subject(run_id=run_id, surface="gui", key=str(p.get("handle")), field="box") + for p in planned + ), + source="attestation plan", + ) + by_handle = {str(p.get("handle")): p for p in planned} + results = [] + for row in after: + handle = str(row.get("handle")) + if handle in fields: + continue + subject = Subject( + run_id=str(row.get("run_id") or ""), surface="gui", key=handle, field="box" + ) + obs = Observed(dict(row), complete=complete is True) + want = by_handle.get(handle) + if want is None: + results.append(Result.refuted(subject, obs, "a box the plan never saw")) + continue + checked = row.get("checked") + decision = want.get("decision") + if decision not in (BoxDecision.TICK.value, BoxDecision.LEAVE.value): + results.append( + Result.not_checked(subject, f"the plan stops here: {decision!r}") + ) + elif not isinstance(checked, bool): + results.append(Result.not_checked(subject, "the box's state was not read")) + elif not isinstance(row.get("statement"), str): + results.append(Result.not_checked(subject, "the statement was not read")) + elif statement_digest(row["statement"]) != want.get("digest"): + results.append(Result.refuted(subject, obs, "the statement changed")) + elif checked is not want.get("want_checked"): + results.append( + Result.refuted(subject, obs, "the box does not show the planned state") + ) + elif complete is not True: + results.append(Result.not_checked(subject, "the screen was read in part")) + else: + results.append(Result.held(subject, obs, "as planned")) + settlement = settle(obligations, results) + status = settlement.label(precedence=(Status.REFUTED, Status.NOT_CHECKED)) + # A box seen in the wrong state stays refuted even when another read of + # it disagrees (the two are then "conflicting" in the settlement). + seen_wrong = [r for r in results if r.status is Status.REFUTED] + if status is not Status.HELD and seen_wrong: + status = Status.REFUTED + return AttestationVerdict(settlement, status) + + +def plan_rows(plan: AttestationPlan) -> list[dict[str, Any]]: + """The plan as the rows :func:`judge_attestations` reads.""" + + return [ + { + "handle": b.handle, + "decision": b.decision.value, + "digest": b.digest, + "want_checked": b.want_checked, + } + for b in plan.boxes + ] + + +def judge_screen(plan: AttestationPlan, after: Screen) -> AttestationVerdict: + """:func:`judge_attestations` on a fresh :class:`Screen`.""" + + return judge_attestations( + plan_rows(plan), + _obs_of(after, plan), + run_id=plan.run_id, + complete=after.complete, + ) + + +# -- from a demonstration ---------------------------------------------------------- + + +@dataclass(frozen=True) +class AttestationCandidate: + """A box the demonstration ticked that no field binding covers. A + suggestion: the pack author decides whether it is an attestation.""" + + control: ControlSpec + statement_sha256: str + name: str + + +def learn_attestations( + demo: Sequence[DemoStep], bound: Iterable[str] = () +) -> tuple[tuple[AttestationCandidate, ...], tuple[IgnoredBox, ...]]: + """Suggest attestations (boxes the demo ticked, not bound) and boxes to + leave alone (boxes the demo saw but never touched, with the state they + showed). Nothing here goes into a pack without the author.""" + + bound_set = set(bound) + ticked: dict[str, Control] = {} + seen: dict[str, Control] = {} + for step in demo: + for ctrl in step.before.controls: + if ctrl.role in BOX_ROLES: + seen.setdefault(ctrl.handle, ctrl) + if step.action == "check" and step.target.role in BOX_ROLES: + ticked[step.target.handle] = step.target + candidates = tuple( + AttestationCandidate( + ControlSpec(c.role, c.name, tuple(x.name for x in c.containers if x.name)), + statement_digest(c.name), + c.name, + ) + for h, c in ticked.items() + if h not in bound_set + ) + leave = tuple( + IgnoredBox(ControlSpec(c.role, c.name), bool(c.checked)) + for h, c in seen.items() + if h not in ticked and h not in bound_set and c.name + ) + return candidates, leave diff --git a/packages/flow/openadapt_flow/gui/dom.py b/packages/flow/openadapt_flow/gui/dom.py index 27c30b52b0..03edbe7e27 100644 --- a/packages/flow/openadapt_flow/gui/dom.py +++ b/packages/flow/openadapt_flow/gui/dom.py @@ -137,6 +137,9 @@ if (el.tagName === 'INPUT') return clean(el.value); return clean(el.textContent) || clean(el.getAttribute('title')); } + // ARIA widgets other than native inputs take their name from content. + if (!['INPUT', 'SELECT', 'TEXTAREA'].includes(el.tagName) + && ['checkbox', 'switch', 'radio'].includes(role)) return clean(el.textContent); return clean(el.getAttribute('title')) || clean(el.getAttribute('placeholder')) || clean(el.getAttribute('name')); }; @@ -164,7 +167,7 @@ for (const [sel, kind] of KINDS) { if (n.matches(sel)) { out.unshift({handle: path(n), kind, name: containerName(n, kind), - text: clean(n.innerText).slice(0, 300)}); + text: clean(n.innerText).slice(0, 2000)}); break; } } diff --git a/packages/flow/tests/failopen/sites/gui_attestations.py b/packages/flow/tests/failopen/sites/gui_attestations.py new file mode 100644 index 0000000000..1b177f2c72 --- /dev/null +++ b/packages/flow/tests/failopen/sites/gui_attestations.py @@ -0,0 +1,133 @@ +"""gui.attestations.judge (C1 C2 C5): every planned box shows the planned state +with the statement it had when it was planned. + +The obligations are the plan's boxes, fixed before any tick. A box the plan +never saw is unexpected, a statement that hashes differently is refuted, an +unread state is not checked, and an empty plan never passes. +""" + +from __future__ import annotations + +import copy +from typing import Any + +from openadapt_flow.gui.attestations import judge_attestations, statement_digest +from openadapt_flow.verdict import Status +from tests.failopen.harness import Seed, SiteSpec, index, key, register + +RUN = "run-1" + + +def _row(handle: str, statement: str, decision: str, want: bool) -> dict[str, Any]: + return { + "handle": handle, + "decision": decision, + "digest": statement_digest(statement), + "want_checked": want, + } + + +def _seen(handle: str, statement: str, checked: Any) -> dict[str, Any]: + return {"handle": handle, "statement": statement, "checked": checked, "run_id": RUN} + + +def _good() -> dict[str, Any]: + return { + "plan": [ + _row("#a", "I confirm this is true", "tick", True), + _row("#b", "Send me offers", "leave", False), + ], + "after": [ + _seen("#a", "I confirm this is true", True), + _seen("#b", "Send me offers", False), + ], + "complete": True, + } + + +def _run(ev: dict[str, Any]) -> Any: + return judge_attestations( + ev["plan"], ev["after"], run_id=RUN, complete=ev.get("complete") + ) + + +def _bad(item: dict[str, Any]) -> dict[str, Any]: + out = copy.deepcopy(item) + out["checked"] = not out["checked"] if isinstance(out["checked"], bool) else False + return out + + +def _inflate(ev: dict[str, Any], n: int) -> dict[str, Any]: + plan = [_row(f"#{i}", f"s{i}", "tick", True) for i in range(n)] + after = [_seen(f"#{i}", f"s{i}", i != n - 1) for i in range(n)] + return {**ev, "plan": plan, "after": after} + + +register( + SiteSpec( + id="gui.attestations.judge", + classes="C1 C2 C5", + target="openadapt_flow.gui.attestations:judge_attestations", + run=_run, + is_pass=lambda out: out.status is Status.HELD, + level=lambda out: out.status, + seeds=lambda: [ + Seed(_good(), True), + Seed( + { + **_good(), + "after": [ + _seen("#a", "I confirm this is true", False), + _seen("#b", "Send me offers", False), + ], + }, + False, + "the attestation is not ticked", + ), + Seed( + { + **_good(), + "after": [ + _seen("#a", "I confirm this and more", True), + _seen("#b", "Send me offers", False), + ], + }, + False, + "the statement changed", + ), + Seed( + { + **_good(), + "plan": [ + _row("#a", "I confirm this is true", "stop", True), + _row("#b", "Send me offers", "leave", False), + ], + }, + False, + "the plan stopped on a box", + ), + Seed( + { + **_good(), + "after": _good()["after"] + [_seen("#c", "New terms", False)], + }, + False, + "a box the plan never saw", + ), + ], + items=key("after"), + plan=key("plan"), + bad_item=_bad, + inflate=_inflate, + fields=index(key("after"), 0), + values=( + key("checked", "after", 0), + key("statement", "after", 0), + key("digest", "plan", 0), + key("want_checked", "plan", 0), + key("decision", "plan", 0), + ), + subject=key("run_id", "after", 0), + partial=lambda ev: [("complete", {**ev, "complete": False})], + ) +) diff --git a/packages/flow/tests/gui/test_gui_attestations.py b/packages/flow/tests/gui/test_gui_attestations.py new file mode 100644 index 0000000000..c6bdf37b6d --- /dev/null +++ b/packages/flow/tests/gui/test_gui_attestations.py @@ -0,0 +1,452 @@ +"""Checkbox attestations on four kinds of app. + +- a web form (membership application) with a declaration and a marketing box; +- an EMR-like chart where a medication review must be attested in a dialog; +- a SaaS danger zone where the attestation is a switch; +- a spreadsheet-like grid whose "final totals" box sits in a dialog. + +An attestation is ticked only on a person's grant for the pinned statement; +an undeclared box, a changed statement, a box bound to a fact or a missing +grant stops the run before anything is ticked. +""" + +from __future__ import annotations + +from typing import Any + +import pytest + +from openadapt_flow.gui.attestations import ( + AttestationGrant, + AttestationSpec, + BoxDecision, + IgnoredBox, + PackError, + apply_attestations, + check_pack, + judge_attestations, + judge_screen, + learn_attestations, + plan_checkboxes, + statement_digest, +) +from openadapt_flow.gui.dom import PageActuator +from openadapt_flow.gui.model import ControlSpec, Recorder, match_one +from openadapt_flow.verdict import Status +from tests.gui import _apps +from tests.gui._grid import GridApp, Sheet + +TRUE = "I confirm the information I have given is true and complete" + + +def _membership( + statement: str = TRUE, extra: str = "", agree: bool = False +) -> _apps.App: + box = ( + f'

{statement}

' + if agree + else f'' + ) + + def form(app: _apps.App, path: str, method: str, f: dict) -> tuple[int, str]: + return 200, _apps.page( + "Apply", + f"""

Membership application

+ +
Declaration{box}
+{extra} +
""", + ) + + def apply(app: _apps.App, path: str, method: str, f: dict) -> tuple[int, str]: + app.state["applied"] = {k: v[0] for k, v in f.items()} + return 200, _apps.page("Thanks", "

Application received

") + + return _apps.App("join.test", {("GET", "/apply"): form, ("POST", "/apply"): apply}) + + +DECL = AttestationSpec( + "declaration", + ControlSpec("checkbox", TRUE, ("Declaration",)), + statement_digest(TRUE), +) +MARKETING = IgnoredBox( + ControlSpec("checkbox", "Send me news and offers"), checked=False +) +GRANT = AttestationGrant("declaration", statement_digest(TRUE), granted_by="applicant") + + +def _open(page: Any, app: _apps.App) -> PageActuator: + act = PageActuator(page) + page.goto(f"{app.origin}/apply") + return act + + +# -- web form -------------------------------------------------------------------- + + +def test_web_form_declaration_is_ticked_on_a_grant_and_read_back(page) -> None: + app = _membership() + with _apps.serve(page, app): + act = _open(page, app) + screen = act.observe() + name = match_one(ControlSpec("textbox", "Full name"), screen).handle + act.set_text(name, "Cy Sample") + plan = plan_checkboxes( + act.observe(), + attestations=[DECL], + grants=[GRANT], + ignored=[MARKETING], + run_id="r1", + ) + assert [b.decision for b in plan.boxes] == [BoxDecision.TICK, BoxDecision.LEAVE] + after = apply_attestations(act, plan) + verdict = judge_screen(plan, after) + assert verdict.status is Status.HELD, verdict.settlement + act.click(match_one(ControlSpec("button", "Submit application"), after).handle) + assert app.state["applied"] == {"name": "Cy Sample", "dec": "on"} + + +@pytest.mark.parametrize( + ("kwargs", "reason"), + [ + ({"grants": []}, "no one attested"), + ( + {"grants": [AttestationGrant("declaration", "0" * 64, "applicant")]}, + "different statement", + ), + ({"ignored": []}, "does not declare"), + ], +) +def test_web_form_without_a_matching_grant_or_declaration_stops( + page, kwargs, reason +) -> None: + app = _membership() + with _apps.serve(page, app): + act = _open(page, app) + args = { + "attestations": [DECL], + "grants": [GRANT], + "ignored": [MARKETING], + **kwargs, + } + plan = plan_checkboxes(act.observe(), **args) + assert plan.stops and reason in plan.stops[0].reason + with pytest.raises(ValueError): + apply_attestations(act, plan) + assert all( + c.checked is False for c in act.observe().controls if c.role == "checkbox" + ) + + +def test_web_form_changed_wording_or_a_new_box_stops(page) -> None: + reworded = _membership(TRUE + ", and I accept the new terms") + with _apps.serve(page, reworded): + act = _open(page, reworded) + # The spec names the box by its old words, so a reworded box is a + # box the pack does not declare. + plan = plan_checkboxes( + act.observe(), attestations=[DECL], grants=[GRANT], ignored=[MARKETING] + ) + assert [b.reason for b in plan.stops] == [ + "a checkbox the pack does not declare" + ] + # A box labelled "I agree" pins the paragraph around it: new words there + # are a different statement. + agree_text = f"Declaration {TRUE} I agree" + agree = AttestationSpec( + "declaration", + ControlSpec("checkbox", "I agree", ("Declaration",)), + statement_digest(agree_text), + statement_from="container", + ) + grant = AttestationGrant("declaration", agree.statement_sha256, "applicant") + same = _membership(agree=True) + with _apps.serve(page, same): + act = _open(page, same) + plan = plan_checkboxes( + act.observe(), attestations=[agree], grants=[grant], ignored=[MARKETING] + ) + assert not plan.stops, plan.stops + assert judge_screen(plan, apply_attestations(act, plan)).status is Status.HELD + changed = _membership(TRUE + " and I accept the new fees", agree=True) + with _apps.serve(page, changed): + act = _open(page, changed) + plan = plan_checkboxes( + act.observe(), attestations=[agree], grants=[grant], ignored=[MARKETING] + ) + assert [b.reason for b in plan.stops] == [ + "the statement differs from the declared one" + ] + added = _membership( + extra='' + ) + with _apps.serve(page, added): + act = _open(page, added) + plan = plan_checkboxes( + act.observe(), attestations=[DECL], grants=[GRANT], ignored=[MARKETING] + ) + assert [b.name for b in plan.stops] == ["I agree to binding arbitration"] + + +def test_a_grant_must_be_a_grant_not_a_fact() -> None: + with pytest.raises(TypeError): + plan_checkboxes(_membership_screen(), attestations=[DECL], grants=[True]) + with pytest.raises(TypeError): + plan_checkboxes( + _membership_screen(), attestations=[DECL], grants=[{"declaration": True}] + ) + + +def _membership_screen(): + from openadapt_flow.gui.model import Container, Control, Screen + + return Screen( + controls=( + Control( + "#dec", + "checkbox", + TRUE, + checked=False, + containers=(Container("fs", "group", "Declaration"),), + ), + ) + ) + + +def test_web_form_demo_suggests_the_declaration_and_the_box_left_alone(page) -> None: + app = _membership() + with _apps.serve(page, app): + act = _open(page, app) + rec = Recorder(act) + s = act.observe() + rec.set_text( + match_one(ControlSpec("textbox", "Full name"), s).handle, "Dee Sample" + ) + rec.set_checked("#dec", True) + rec.click( + match_one(ControlSpec("button", "Submit application"), act.observe()).handle + ) + candidates, leave = learn_attestations(rec.steps) + assert [(c.name, c.control.containers) for c in candidates] == [ + (TRUE, ("Declaration",)) + ] + assert candidates[0].statement_sha256 == DECL.statement_sha256 + assert [(i.control.name, i.checked) for i in leave] == [ + ("Send me news and offers", False) + ] + + +# -- EMR-like chart: an attestation bound to a fact is refused -------------------- + + +def _chart() -> _apps.App: + def chart(app: _apps.App, path: str, method: str, f: dict) -> tuple[int, str]: + return 200, _apps.page( + "Chart", + """

Chart: Test Patient B

+ +
""", + ) + + return _apps.App( + "chart.test", + {("GET", "/chart"): chart, ("POST", "/review"): lambda a, p, m, f: (200, "{}")}, + ) + + +REVIEW = "I attest that I reviewed this medication list with the patient" +REVIEW_SPEC = AttestationSpec( + "med_review", ControlSpec("checkbox", REVIEW), statement_digest(REVIEW) +) + + +def test_emr_attestation_bound_to_a_fact_is_refused_by_pack_check_and_plan( + page, +) -> None: + with pytest.raises(PackError): + check_pack( + [REVIEW_SPEC], + [ControlSpec("textbox", "Note"), ControlSpec("checkbox", REVIEW)], + ) + check_pack([REVIEW_SPEC], [ControlSpec("textbox", "Note")]) + app = _chart() + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/chart") + act.click( + match_one(ControlSpec("button", "Review medications"), act.observe()).handle + ) + screen = act.observe() + box = match_one(ControlSpec("checkbox", REVIEW, dialog=True), screen) + grant = AttestationGrant( + "med_review", REVIEW_SPEC.statement_sha256, "clinician 4" + ) + bound = plan_checkboxes( + screen, attestations=[REVIEW_SPEC], grants=[grant], bound=[box.handle] + ) + assert [b.reason for b in bound.stops] == [ + "a declared attestation is bound to a field" + ] + plan = plan_checkboxes( + screen, attestations=[REVIEW_SPEC], grants=[grant], run_id="r2" + ) + after = apply_attestations(act, plan) + assert judge_screen(plan, after).status is Status.HELD + assert plan.ticks[0].granted_by == "clinician 4" + + +# -- SaaS: a switch --------------------------------------------------------------- + + +DANGER = "I understand this permanently deletes every project in the workspace" + + +def _danger_zone(prechecked: bool = False) -> _apps.App: + state = "true" if prechecked else "false" + + def page_(app: _apps.App, path: str, method: str, f: dict) -> tuple[int, str]: + return 200, _apps.page( + "Danger zone", + f"""

Danger zone

+{DANGER} +
""", + ) + + return _apps.App("app.test", {("GET", "/danger"): page_}) + + +DANGER_SPEC = AttestationSpec( + "delete_ack", ControlSpec("switch", DANGER), statement_digest(DANGER) +) + + +def test_saas_switch_attestation_ticks_on_grant_and_refuses_a_prechecked_one( + page, +) -> None: + grant = AttestationGrant( + "delete_ack", DANGER_SPEC.statement_sha256, "workspace owner" + ) + app = _danger_zone() + with _apps.serve(page, app): + act = PageActuator(page) + page.goto(f"{app.origin}/danger") + plan = plan_checkboxes( + act.observe(), attestations=[DANGER_SPEC], grants=[grant] + ) + assert [b.decision for b in plan.boxes] == [BoxDecision.TICK] + act.click(plan.ticks[0].handle) # a switch is toggled by a click + assert judge_screen(plan, act.observe()).status is Status.HELD + pre = _danger_zone(prechecked=True) + with _apps.serve(page, pre): + act = PageActuator(page) + page.goto(f"{pre.origin}/danger") + plan = plan_checkboxes( + act.observe(), attestations=[DANGER_SPEC], grants=[grant] + ) + assert [b.reason for b in plan.stops] == [ + "the box was ticked before the run touched it" + ] + + +# -- grid: a box in a dialog, no browser -------------------------------------------- + + +FINAL = "These totals are final for the quarter" + + +class _ClosingGrid(GridApp): + def tree(self) -> dict[str, Any]: + self.dialog = { + "role": "dialog", + "name": "Close quarter", + "handle": "dlg", + "children": [ + { + "role": "check box", + "name": FINAL, + "handle": "chk:final", + "checked": self.checks.get("chk:final", False), + }, + { + "role": "check box", + "name": "Email the summary to me", + "handle": "chk:email", + "checked": self.checks.get("chk:email", False), + }, + ], + } + return super().tree() + + +def test_grid_dialog_attestation_settles_against_a_fresh_read() -> None: + grid = _ClosingGrid([Sheet("Q3", ("Item", "Amount"), [["Rent", "1300"]])]) + spec = AttestationSpec( + "final", + ControlSpec("checkbox", FINAL, ("Close quarter",)), + statement_digest(FINAL), + ) + grant = AttestationGrant("final", spec.statement_sha256, "controller") + leave = IgnoredBox(ControlSpec("checkbox", "Email the summary to me")) + plan = plan_checkboxes( + grid.observe(), + attestations=[spec], + grants=[grant], + ignored=[leave], + run_id="g1", + ) + after = apply_attestations(grid, plan) + assert judge_screen(plan, after).status is Status.HELD + # Someone ticks the box the pack leaves alone after the plan: refuted. + grid.checks["chk:email"] = True + assert judge_screen(plan, grid.observe()).status is Status.REFUTED + + +def test_judge_refuses_empty_unexpected_and_unread_boxes() -> None: + row = { + "handle": "a", + "decision": "tick", + "digest": statement_digest("x"), + "want_checked": True, + } + good = [{"handle": "a", "statement": "x", "checked": True, "run_id": "r"}] + assert judge_attestations([row], good, run_id="r").status is Status.HELD + assert judge_attestations([], [], run_id="r").status is not Status.HELD + extra = good + [{"handle": "b", "statement": "y", "checked": False, "run_id": "r"}] + assert judge_attestations([row], extra, run_id="r").status is not Status.HELD + unread = [{**good[0], "checked": None}] + assert judge_attestations([row], unread, run_id="r").status is Status.NOT_CHECKED + other_run = [{**good[0], "run_id": "q"}] + assert judge_attestations([row], other_run, run_id="r").status is not Status.HELD + assert ( + judge_attestations([row], good, run_id="r", complete=False).status + is not Status.HELD + ) + + +def test_one_spec_matching_two_identical_boxes_stops_on_both(page) -> None: + twin = _membership( + extra=f''.replace( + "