diff --git a/capabilities/04-the-core-a-checked-entry-every-time/0137-one-strict-matcher-decides-whether-text-proves-a.md b/capabilities/04-the-core-a-checked-entry-every-time/0137-one-strict-matcher-decides-whether-text-proves-a.md new file mode 100644 index 0000000000..f45746e808 --- /dev/null +++ b/capabilities/04-the-core-a-checked-entry-every-time/0137-one-strict-matcher-decides-whether-text-proves-a.md @@ -0,0 +1 @@ +| One strict matcher decides whether text on a screen or page proves a value or a commit: `MATCH`, `MISMATCH` or `AMBIGUOUS`, and only `MATCH` passes. A value must be bound to its label at the start of its field, with nothing but unit words beside it, or be the whole field. A value merely found on the page, inside a longer token (`250` in `$1,250.00`, `John Smith` in `John Smith-Jones`), or under a label with two values never passes. A commit phrase must be new, plainly stated, and not next to a question, a negation or a control label. The launcher's transducer read-back and the kernel's read-back oracles use it; [the migration page](packages/types/docs/evidence-migration.md) lists the callers that don't yet | On main | Adversarial corpus with pinned verdicts, Hypothesis properties, a parity test against Flow's read-back matcher, and strict expected-failure tests for each caller not yet migrated | `openadapt_types/evidence.py`, `openadapt/transducer_obligations.py`, `openadapt_kernel/oracles.py` | diff --git a/openadapt/_evidence.py b/openadapt/_evidence.py new file mode 100644 index 0000000000..5d1a075cb2 --- /dev/null +++ b/openadapt/_evidence.py @@ -0,0 +1,738 @@ +"""Decide whether text on a screen or page proves a value or a commit. + +This is the one strict matcher OpenAdapt's verifiers share. It answers with +three verdicts, and only ``MATCH`` may count as proof: + +- ``MATCH``: the text shows the expected value as the whole field, or bound + to its label; +- ``MISMATCH``: the text is legible and doesn't show the value; +- ``AMBIGUOUS``: the text holds the value but doesn't prove the field holds + it. Examples are the value inside longer text, one label with two values, + and a date that reads two ways. Treat it like ``MISMATCH`` when deciding + whether to pass, and report it as unproven. + +Rules for :func:`match_field`: + +1. A value bound to its label (``Dose: 5 mg``) is tried before the whole + text. When the label is present, its bound value decides, and a second, + different value for the same label is ``AMBIGUOUS``. A label binds only at + the start of a line or after ``|``, ``;`` or a tab, with only punctuation + between. A word before it (``Previous Patient ID:``, ``Error: Claim + ID:``, ``Name: Jane Doe Previous MRN:``) may name another record, so the + label doesn't bind there. A single-line ``Patient: X DOB: Y`` therefore + binds ``Patient`` but not ``DOB``. +2. The bound value must be the value and nothing more, except unit words + after a number (``5 mg``, ``250.00 USD``). Anything else in it is + ``AMBIGUOUS``: a status (``CLM-1 not found``, ``(void)``), a comparator + (``<5``, ``5+``), a trailing sign or ``CR``/``DR``, or an aside + (``Jane Sample (not this patient)``). +3. Without a label binding, ``MATCH`` needs the whole text to equal the value + under its kind. A value found inside longer text, as whole tokens, is + ``AMBIGUOUS``. A value found only inside a longer token is ``MISMATCH``. +4. A token boundary excludes joining punctuation: ``-``, ``,``, ``.``, ``/`` + or ``@`` with a letter or digit on the far side, and ``:`` between digits. + So ``2026-11`` is not in ``2026-11-29`` and ``John Smith`` is not in + ``John Smith-Jones``. +5. Numbers compare as whole numeric tokens, with sign, currency and thousands + separators, by value. ``250`` never matches ``1,250.00`` and ``5`` never + matches ``50 mg``. A value with a leading zero (``007``) is an identifier + and compares as written. +6. Names and text compare as whole tokens, ignoring case and runs of spaces. + +Kinds (``kind=``): ``text``, ``name``, ``code`` (case, spaces, ``-``, ``.`` +and ``/`` ignored, but separators must line up when both sides have them), +``date``, ``number``, ``currency``, and ``auto``, which guesses +conservatively with :func:`infer_kind`. + +:func:`phrase_affirmed` checks a commit confirmation such as ``Saved`` or +``Signed`` across two frames. The phrase must be absent before and present +after, as whole tokens. A question mark, a modal, future or conditional form +(``should``, ``will``, ``must``, ``can``, ``to be``, ``are you sure``, ``if``, +``once``) or a negation or failure word (``Not``, ``Error``, ``rolled +back``, ``draft``, ``0 records``) on the phrase's line or the lines next to +it, a negation or failure word on any line that is new since the first +frame, or a control label (``Confirm``, ``Cancel``, ``OK``, ``Sign``) next to +the phrase makes it ``AMBIGUOUS``. + +The canonical copy is ``openadapt_types/evidence.py`` in the openadapt-types +package. The launcher (``openadapt/_evidence.py``) and the kernel +(``openadapt_kernel/_evidence.py``) carry byte-identical copies, so neither +needs a new dependency; a test fails when the copies drift. The corpus in +``packages/types/tests/evidence_corpus.json`` pins the verdicts. + +Standard library only: ``re``, ``datetime`` and ``decimal``. No model calls. +""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from datetime import date, datetime +from decimal import Decimal, InvalidOperation +from enum import Enum +from typing import Literal, Optional + +__all__ = [ + "EvidenceKind", + "FieldEvidence", + "Verdict", + "evaluate_field", + "has_negation_or_modal", + "infer_kind", + "match_field", + "occurrences", + "phrase_affirmed", +] + +EvidenceKind = Literal["auto", "text", "name", "code", "date", "number", "currency"] +_Resolved = Literal["text", "name", "code", "date", "number", "currency"] +_KINDS = frozenset({"auto", "text", "name", "code", "date", "number", "currency"}) + + +class Verdict(str, Enum): + """The answer for one value. Only ``MATCH`` may pass.""" + + MATCH = "match" + MISMATCH = "mismatch" + AMBIGUOUS = "ambiguous" + + @property + def passes(self) -> bool: + return self is Verdict.MATCH + + +@dataclass(frozen=True) +class FieldEvidence: + """A verdict with what it rests on. + + ``basis`` is ``label`` (the value bound to its label decided), ``whole`` + (the whole text equals the value), ``contained`` (the value is inside + longer text, never proof) or ``absent``. + """ + + verdict: Verdict + basis: Literal["label", "whole", "contained", "absent"] + kind: str + bound_values: tuple[str, ...] = () + + +# --- token boundaries ------------------------------------------------------- + +#: Punctuation that joins two tokens into one when a letter or digit is on +#: the far side: ``Smith-Jones``, ``1,250``, ``2026-11-29``, ``a/b``, ``x@y``. +_JOINERS = frozenset("-,./@") + + +def _wordish(ch: str) -> bool: + return ch.isalnum() or ch == "_" + + +def _left_ok(text: str, start: int) -> bool: + if start <= 0: + return True + prev = text[start - 1] + if _wordish(prev): + return False + if start >= 2 and _wordish(text[start - 2]): + if prev in _JOINERS: + return False + if ( + prev == ":" + and text[start - 2].isdigit() + and text[start : start + 1].isdigit() + ): + return False + return True + + +def _right_ok(text: str, end: int) -> bool: + if end >= len(text): + return True + nxt = text[end] + if _wordish(nxt): + return False + if end + 1 < len(text) and _wordish(text[end + 1]): + if nxt in _JOINERS: + return False + if nxt == ":" and text[end + 1].isdigit() and text[end - 1 : end].isdigit(): + return False + return True + + +def _phrase_regex(value: str) -> Optional[re.Pattern[str]]: + parts = value.split() + if not parts: + return None + return re.compile(r"\s+".join(re.escape(p) for p in parts), re.IGNORECASE) + + +def _spans(value: str, text: str) -> list[tuple[int, int]]: + """Where ``value`` appears in ``text`` as whole tokens (case ignored).""" + + pattern = _phrase_regex(value) + if pattern is None or not text: + return [] + found: list[tuple[int, int]] = [] + pos = 0 + while True: + m = pattern.search(text, pos) + if m is None: + return found + if ( + m.end() > m.start() + and _left_ok(text, m.start()) + and _right_ok(text, m.end()) + ): + found.append((m.start(), m.end())) + pos = m.start() + 1 + + +# --- normalization by kind (after Flow's readback_values) ------------------- + +_CODE_SEPARATORS = re.compile(r"[\s\-./]+") +_CODE_PARTS = re.compile(r"[^\s\-./]+") +_STRICT_AMOUNT = re.compile( + r"^(?P
[$€£¥]|USD|CAD|EUR|GBP)?\s?(?P\()?(?P[+-])?\s?"
+    r"(?P\d{1,3}(?:,\d{3})+(?:\.\d+)?|\d+(?:\.\d+)?|\d+,\d{2})"
+    r"(?P\))?\s?(?PUSD|CAD|EUR|GBP)?$",
+    re.IGNORECASE | re.ASCII,
+)
+_PLAIN_NUMBER = re.compile(r"^[+-]?(\d{1,3}(,\d{3})+|\d+)(\.\d+)?$", re.ASCII)
+_CURRENCY_NAMES = {"$": "USD", "€": "EUR", "£": "GBP", "¥": "JPY"}
+#: A numeric token inside longer text: optional currency and sign, digits
+#: with optional grouping and decimals, optional currency code.
+_NUMERIC_TOKEN = re.compile(
+    r"(?:[$€£¥]\s?)?[+-]?(?:[$€£¥]\s?)?\d+(?:,\d+)*(?:\.\d+)?"
+    r"(?:\s?(?:USD|CAD|EUR|GBP)(?![A-Za-z]))?",
+    re.ASCII,
+)
+_DATE_FORMATS = (
+    "%Y-%m-%d",
+    "%Y/%m/%d",
+    "%b %d, %Y",
+    "%B %d, %Y",
+    "%d %b %Y",
+    "%d %B %Y",
+    "%b %d %Y",
+    "%B %d %Y",
+    "%d-%b-%Y",
+    "%Y%m%d",
+)
+_DAY_MONTH = ("%d/%m/%Y", "%d-%m-%Y", "%d.%m.%Y")
+_MONTH_DAY = ("%m/%d/%Y", "%m-%d-%Y", "%m.%d.%Y")
+_ISO_WITH_TIME = re.compile(
+    r"^(\d{4}-\d{2}-\d{2})(?:[ T]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,6})?)?)?$"
+)
+_ISO_DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
+_NUMERIC_DATE = re.compile(r"^\d{1,2}[/.\-]\d{1,2}[/.\-]\d{4}$")
+_NAMED_DATE = re.compile(
+    r"^(?:\d{1,2}[ -])?[A-Za-z]{3,9}\.?[ -]\d{1,2}(?:,)?[ -]\d{4}$|"
+    r"^\d{1,2} [A-Za-z]{3,9} \d{4}$"
+)
+_MONEY = re.compile(
+    r"^[$€£¥]\s?-?[\d,]+(\.\d+)?$|^-?[\d,]+(\.\d+)?\s?(USD|CAD|EUR|GBP)$", re.ASCII
+)
+_CODE_SHAPE = re.compile(r"^(?=.*\d)[A-Za-z0-9][A-Za-z0-9\-./#]*$")
+
+
+def _text(value: str) -> str:
+    return " ".join(value.lower().split())
+
+
+def _code(value: str) -> str:
+    return _CODE_SEPARATORS.sub("", value.lower())
+
+
+def _code_edges(value: str) -> tuple[str, str]:
+    text = value.strip()
+    lead = re.match(r"^[\-./]*", text)
+    trail = re.search(r"[\-./]*$", text)
+    return (lead.group() if lead else "", trail.group() if trail else "")
+
+
+def _same_code_layout(a: str, b: str) -> bool:
+    """``AC1042`` is ``AC-1042``, but ``12-345`` is not ``123-45``."""
+
+    if _code_edges(a) != _code_edges(b):
+        return False
+    parts_a = _CODE_PARTS.findall(a.lower())
+    parts_b = _CODE_PARTS.findall(b.lower())
+    if len(parts_a) < 2 or len(parts_b) < 2:
+        return True
+    return parts_a == parts_b
+
+
+def _dates(value: str) -> set[date]:
+    """Every calendar date ``value`` can mean (``03/04/2026`` means two)."""
+
+    cleaned = " ".join(value.split())
+    stamped = _ISO_WITH_TIME.match(cleaned)
+    if stamped:
+        cleaned = stamped.group(1)
+    found: set[date] = set()
+    for layout in _DATE_FORMATS + _DAY_MONTH + _MONTH_DAY:
+        try:
+            found.add(datetime.strptime(cleaned, layout).date())
+        except ValueError:
+            continue
+    return found
+
+
+def _amount(value: str) -> Optional[Decimal]:
+    match = _STRICT_AMOUNT.match(value.strip())
+    if match is None or bool(match["open"]) != bool(match["close"]):
+        return None
+    if match["pre"] and match["post"]:
+        return None
+    num = match["num"]
+    if re.fullmatch(r"\d+,\d{2}", num):
+        num = num.replace(",", ".")
+    else:
+        num = num.replace(",", "")
+    try:
+        amount = Decimal(num)
+    except InvalidOperation:
+        return None
+    negative = match["sign"] == "-" or bool(match["open"])
+    return -amount if negative else amount
+
+
+def _currency(value: str) -> Optional[str]:
+    match = _STRICT_AMOUNT.match(value.strip())
+    if match is None:
+        return None
+    name = (match["pre"] or match["post"] or "").upper()
+    return _CURRENCY_NAMES.get(name, name) or None
+
+
+def _leading_zero(value: str) -> bool:
+    return re.match(r"^\(?[$€£¥]?\s?[+-]?0\d", value.strip()) is not None
+
+
+def infer_kind(value: str) -> _Resolved:
+    """Guess a value's kind from clear shapes only; anything else is text.
+
+    An ISO, numeric or month-name date is ``date``; an amount with a currency
+    symbol or code is ``currency``; a plain number without a leading zero is
+    ``number``; one token holding a digit (``MRN-104``, ``E11.9``, ``007``)
+    is ``code``.
+    """
+
+    stripped = " ".join(str(value).split())
+    if _ISO_DATE.match(stripped) or _NUMERIC_DATE.match(stripped):
+        return "date"
+    if _NAMED_DATE.match(stripped) and _dates(stripped):
+        return "date"
+    if _MONEY.match(stripped) and _amount(stripped) is not None:
+        return "currency"
+    if _PLAIN_NUMBER.match(stripped) and not _leading_zero(stripped):
+        return "number"
+    if " " not in stripped and _CODE_SHAPE.match(stripped):
+        return "code"
+    return "text"
+
+
+def _resolve(kind: str, expected: str) -> _Resolved:
+    if kind not in _KINDS:
+        raise ValueError(f"unknown evidence kind: {kind!r}")
+    if kind == "auto":
+        return infer_kind(expected)
+    return kind  # type: ignore[return-value]
+
+
+# --- comparing one whole value ----------------------------------------------
+
+
+def _same_number(observed: str, expected: str, kind: str) -> Verdict:
+    if _leading_zero(observed) or _leading_zero(expected):
+        # "007" is an identifier: its characters, not its value.
+        return (
+            Verdict.MATCH if observed.strip() == expected.strip() else Verdict.MISMATCH
+        )
+    want = _amount(expected)
+    seen = _amount(observed)
+    if want is None or seen is None:
+        return Verdict.MISMATCH
+    if kind == "number" and not _PLAIN_NUMBER.match(expected.strip()):
+        if _currency(expected) is None:
+            return Verdict.MISMATCH
+    names = {_currency(observed), _currency(expected)} - {None}
+    if seen != want or len(names) > 1:
+        return Verdict.MISMATCH
+    return Verdict.MATCH
+
+
+def _compare_whole(observed: str, expected: str, kind: _Resolved) -> Verdict:
+    """The whole of ``observed`` against ``expected``, normalized by kind."""
+
+    if not observed.strip() or not expected.strip():
+        return Verdict.MISMATCH
+    if kind == "date":
+        if _text(observed) == _text(expected):
+            return Verdict.MATCH  # the same characters, however they read
+        seen, want = _dates(observed), _dates(expected)
+        if not seen or not want or not seen & want:
+            return Verdict.MISMATCH
+        # A read that can mean the expected date or another proves nothing.
+        if len(seen) == 1 and len(want) == 1:
+            return Verdict.MATCH
+        return Verdict.AMBIGUOUS
+    if kind in ("number", "currency"):
+        return _same_number(observed, expected, kind)
+    if kind == "code":
+        seen_code, want_code = _code(observed), _code(expected)
+        if (
+            want_code
+            and seen_code == want_code
+            and _same_code_layout(observed, expected)
+        ):
+            return Verdict.MATCH
+        return Verdict.MISMATCH
+    if _text(observed) == _text(expected):
+        return Verdict.MATCH
+    return Verdict.MISMATCH
+
+
+def _numeric_tokens(text: str) -> list[str]:
+    """Every whole numeric token in ``text``: ``50`` in ``50 mg``, but not
+    ``250`` in ``1,250.00`` or ``11`` in ``2026-11-29``."""
+
+    return [token for token, _, _ in _numeric_spans(text)]
+
+
+def _numeric_spans(text: str) -> list[tuple[str, int, int]]:
+    out: list[tuple[str, int, int]] = []
+    for m in _NUMERIC_TOKEN.finditer(text):
+        token, start, end = m.group(), m.start(), m.end()
+        if (
+            start > 0
+            and end < len(text)
+            and text[start - 1] == "("
+            and text[end] == ")"
+        ):
+            token, start, end = f"({token})", start - 1, end + 1  # (250.00) is -250
+        if (
+            _left_ok(text, start)
+            and _right_ok(text, end)
+            and _amount(token) is not None
+        ):
+            out.append((token, start, end))
+    return out
+
+
+def _token_count(expected: str, text: str, kind: _Resolved) -> int:
+    """How many times ``expected`` appears in ``text`` as whole tokens."""
+
+    if kind in ("number", "currency"):
+        return sum(
+            1
+            for tok in _numeric_tokens(text)
+            if _same_number(tok, expected, kind).passes
+        )
+    if kind == "date":
+        want = _dates(expected)
+        tokens = sum(
+            1
+            for m in re.finditer(r"[^\W_]+(?:[-./][^\W_]+)*", text)
+            if want & _dates(m.group())
+        )
+        return max(tokens, len(_spans(expected, text)))
+    return len(_spans(expected, text))
+
+
+def occurrences(expected: str, text: str, *, kind: EvidenceKind = "auto") -> int:
+    """How many times ``expected`` appears in ``text`` as whole tokens.
+
+    This locates a value; it never proves a field holds the value.
+    """
+
+    return _token_count(str(expected), str(text or ""), _resolve(kind, str(expected)))
+
+
+# --- label binding ----------------------------------------------------------
+
+#: Where a bound value ends: a line break, a pipe, a semicolon, a tab, two
+#: spaces, or the next ``Label:`` / ``key=`` on the same line. A quoted value
+#: ends at its closing quote.
+_VALUE_END = re.compile(
+    r"[\r\n|;\t]| {2,}|\s+(?=[A-Za-z_][\w./#-]*\s?[:=](?:\s|$|[^=\s]))"
+)
+
+
+def _label_pattern(label: str) -> Optional[re.Pattern[str]]:
+    clean = " ".join(label.strip().rstrip(":=#").split())
+    if not clean:
+        return None
+    body = r"\s+".join(re.escape(p) for p in clean.split())
+    # "