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())
+ # ": value", " = value", " # value", "\tvalue",
+ # '"": "value"', or the label alone on its line with the value
+ # below. Two spaces don't bind: a form heading row ("Policy Number Submit")
+ # would bind its next heading.
+ return re.compile(
+ rf"(? bool:
+ """Whether a label at ``start`` begins a field.
+
+ Only punctuation may come between the last hard separator (a line break,
+ ``|``, ``;``, a tab, or a JSON key's ``{`` / ``",``) and the label.
+ Anything else may be a modifier: ``Previous Patient ID:``, ``Error:
+ Claim ID:``, and also ``Name: Jane Doe Previous MRN:``, where the text
+ can't tell the end of one value from a modifier on the next label. So a
+ single-line ``Patient: X DOB: Y`` doesn't bind ``DOB``. After ``|``,
+ ``;`` or a tab, the cell before must be empty or a whole field (``Name:
+ Jane | MRN:``): a bare word (``Previous | MRN:``) or a heading with no
+ value (``Previous: | MRN:``) may name the next cell's record.
+ """
+
+ seps = list(_HARD_SEPARATOR.finditer(text, 0, start))
+ seg_start = seps[-1].end() if seps else 0
+ if re.search(r"[^\W_]", text[seg_start:start]):
+ return False
+ if seps and seps[-1].group() in "|;\t":
+ cell_start = seps[-2].end() if len(seps) > 1 else 0
+ cell = text[cell_start : seps[-1].start()]
+ if re.search(r"[^\W_]", cell) and not _FIELD_CELL.search(cell):
+ return False # "Previous | MRN: MRN-1", "Previous: | MRN: MRN-1"
+ return True
+
+
+def _bound_values(text: str, label: str) -> list[str]:
+ pattern = _label_pattern(label)
+ if pattern is None or not text:
+ return []
+ values: list[str] = []
+ for m in pattern.finditer(text):
+ if not _field_start(text, m.start()):
+ continue
+ if "\n" in m.group():
+ # The label alone on its line, the value on the next one.
+ line_start = text.rfind("\n", 0, m.start()) + 1
+ if text[line_start : m.start()].strip():
+ continue
+ rest = text[m.end() :]
+ if rest[:1] in ('"', "'") and rest.find(rest[0], 1) > 0:
+ value = rest[1 : rest.find(rest[0], 1)].strip() # a quoted value
+ else:
+ end = _VALUE_END.search(rest)
+ value = (rest[: end.start()] if end else rest).strip()
+ if value:
+ values.append(value)
+ return values
+
+
+#: Words that may follow a number in its field: units of measure, count and
+#: time, and currency codes. Nothing else may share the field with the value.
+_UNITS = frozenset(
+ {
+ "mg", "mcg", "ug", "µg", "g", "kg", "lb", "lbs", "oz", "ml", "l", "dl",
+ "cc", "u", "iu", "unit", "units", "mmol", "meq", "%", "tab", "tabs",
+ "tablet", "tablets", "cap", "caps", "capsule", "capsules", "dose",
+ "doses", "puff", "puffs", "drop", "drops", "h", "hr", "hrs", "hour",
+ "hours", "min", "mins", "minute", "minutes", "d", "day", "days", "wk",
+ "week", "weeks", "mo", "month", "months", "yr", "yrs", "year", "years",
+ "mm", "cm", "m", "km", "in", "ft", "m2", "mmhg", "bpm", "ea", "each",
+ "usd", "cad", "eur", "gbp",
+ }
+) # fmt: skip
+
+
+def _units_only(rest: str) -> bool:
+ """Whether ``rest`` holds only unit words (``mg``, ``mg/dL``, ``USD``)."""
+
+ rest = rest.strip()
+ if rest.endswith("."):
+ rest = rest[:-1]
+ return all(
+ part in _UNITS for tok in rest.lower().split() for part in tok.split("/")
+ )
+
+
+def _compare_bound(bound: str, expected: str, kind: _Resolved) -> Verdict:
+ """One bound value against ``expected``: the value and nothing more,
+ except unit words after a number."""
+
+ if kind in ("number", "currency"):
+ numbers = _numeric_spans(bound)
+ if not numbers:
+ return Verdict.MISMATCH
+ verdicts = [_same_number(tok, expected, kind) for tok, _, _ in numbers]
+ if len(numbers) > 1:
+ return Verdict.AMBIGUOUS if Verdict.MATCH in verdicts else Verdict.MISMATCH
+ _, start, end = numbers[0]
+ if verdicts[0] is Verdict.MATCH and not _units_only(
+ bound[:start] + " " + bound[end:]
+ ):
+ # "5 mg was not saved", "<5", "250.00 CR", "250.00-".
+ return Verdict.AMBIGUOUS
+ return verdicts[0]
+ whole = _compare_whole(bound, expected, kind)
+ if whole is not Verdict.MISMATCH:
+ return whole
+ if kind == "code" and len(expected.split()) == 1:
+ # "CLM-1." is the code; "CLM-1 not found" or "MRN-104 (Jane Doe)" is
+ # the code and something else in the field.
+ first, *rest = bound.split()
+ verdict = _compare_whole(first.strip(".,:;!?()[]{}\"'"), expected, kind)
+ if verdict is Verdict.MATCH and rest:
+ return Verdict.AMBIGUOUS
+ if verdict is Verdict.MATCH:
+ return verdict
+ if _token_count(expected, bound, kind):
+ return Verdict.AMBIGUOUS # "Jane Sample (not this patient)"
+ return Verdict.MISMATCH
+
+
+# --- public API -------------------------------------------------------------
+
+
+def evaluate_field(
+ expected: str,
+ observed_text: str,
+ *,
+ label: Optional[str] = None,
+ kind: EvidenceKind = "auto",
+) -> FieldEvidence:
+ """Judge one expected value against observed text, with the basis.
+
+ See the module docstring for the rules. ``observed_text`` may be one
+ field's read or a whole page.
+ """
+
+ expected = str(expected if expected is not None else "")
+ observed = str(observed_text if observed_text is not None else "")
+ resolved = _resolve(kind, expected)
+ if not expected.strip():
+ return FieldEvidence(Verdict.MISMATCH, "absent", resolved)
+ if label is not None and label.strip():
+ bound = _bound_values(observed, label)
+ if bound:
+ verdicts = {_compare_bound(b, expected, resolved) for b in bound}
+ if verdicts == {Verdict.MATCH}:
+ verdict = Verdict.MATCH
+ elif len({_text(b) for b in bound}) > 1:
+ verdict = Verdict.AMBIGUOUS # one label, two values
+ elif Verdict.AMBIGUOUS in verdicts:
+ verdict = Verdict.AMBIGUOUS
+ else:
+ verdict = Verdict.MISMATCH
+ return FieldEvidence(verdict, "label", resolved, tuple(bound))
+ whole = _compare_whole(observed, expected, resolved)
+ if whole is not Verdict.MISMATCH:
+ return FieldEvidence(whole, "whole", resolved)
+ if _token_count(expected, observed, resolved):
+ return FieldEvidence(Verdict.AMBIGUOUS, "contained", resolved)
+ return FieldEvidence(Verdict.MISMATCH, "absent", resolved)
+
+
+def match_field(
+ expected: str,
+ observed_text: str,
+ *,
+ label: Optional[str] = None,
+ kind: EvidenceKind = "auto",
+) -> Verdict:
+ """``MATCH``, ``MISMATCH`` or ``AMBIGUOUS``; only ``MATCH`` may pass."""
+
+ return evaluate_field(expected, observed_text, label=label, kind=kind).verdict
+
+
+#: A question, a modal or future form, a condition, or a request: the phrase
+#: is asked about, required or expected, not stated as done.
+_MODAL = re.compile(
+ r"\?|\b(?:should|will|would|shall|must|can|could|may(?!\s+\d)|might|need|needs|"
+ r"needed|to be|are you sure|going to|about to|ready to|pending|awaiting|"
+ r"waiting|required|requires|please|if|once|when|unless|until)\b",
+ re.IGNORECASE,
+)
+_NEGATION = re.compile(
+ r"\b(?:not|no|never|none|nothing|cannot|unable|fail|fails|failed|failure|"
+ r"without|error|errors|missing|invalid|rejected|denied|declined|void|"
+ r"voided|cancelled|canceled|reverted|rolled back|undone|discarded|aborted|"
+ r"draft|by another|undo|previously|before|outbox|queued)\b|n't\b|\b0\s+(?:of|records?|items?|rows?|changes?)\b",
+ re.IGNORECASE,
+)
+#: ``No.`` / ``No:`` / ``No #`` as the abbreviation of number, not a negation.
+_NUMBER_ABBREVIATION = re.compile(r"\bno\b\.?(?=\s*[:#=.]|\.)", re.IGNORECASE)
+
+
+def _abbreviations(text: str) -> str:
+ return _NUMBER_ABBREVIATION.sub("number", text)
+
+
+def has_negation_or_modal(text: str) -> bool:
+ """Whether ``text`` holds a negation or failure word (``not``, ``Error``,
+ ``rejected``, ``void``), or a question, modal, future or conditional form
+ (``?``, ``will``, ``pending``, ``if``). ``No.`` meaning number doesn't
+ count."""
+
+ cleaned = _abbreviations(str(text or ""))
+ return bool(_NEGATION.search(cleaned) or _MODAL.search(cleaned))
+
+
+_CONTROL = re.compile(r"\b(?:confirm|cancel|ok|sign|yes)\b", re.IGNORECASE)
+
+
+def _line_bounds(text: str, pos: int) -> tuple[int, int]:
+ start = text.rfind("\n", 0, pos) + 1
+ end = text.find("\n", pos)
+ return start, (len(text) if end == -1 else end)
+
+
+def _neighbour(text: str, line_start: int, line_end: int, up: bool) -> str:
+ if up:
+ if line_start == 0:
+ return ""
+ prev_start, _ = _line_bounds(text, line_start - 1)
+ return text[prev_start : line_start - 1]
+ if line_end >= len(text):
+ return ""
+ _, next_end = _line_bounds(text, line_end + 1)
+ return text[line_end + 1 : next_end]
+
+
+def phrase_affirmed(before_text: str, after_text: str, phrase: str) -> Verdict:
+ """Whether ``after_text`` affirms ``phrase`` as a new, plain statement.
+
+ ``MATCH`` only when the phrase is absent from ``before_text``, present in
+ ``after_text`` as whole tokens, and every appearance is a statement: no
+ question mark, modal or future form, or negation on its line or the lines
+ next to it, no control label (``Confirm``, ``Cancel``, ``OK``, ``Sign``,
+ ``Yes``) on those lines, and no negation or failure word on any line of
+ ``after_text`` that isn't in ``before_text`` (``Saved`` then ``Error:
+ record locked``).
+ """
+
+ before = str(before_text or "")
+ after = str(after_text or "")
+ if not str(phrase or "").strip():
+ return Verdict.MISMATCH
+ if _spans(phrase, before):
+ return Verdict.AMBIGUOUS # already there: it doesn't show this commit
+ spans = _spans(phrase, after)
+ if not spans:
+ return Verdict.MISMATCH
+ for start, end in spans:
+ line_start, line_end = _line_bounds(after, start)
+ same_line = after[line_start:start] + " " + after[end:line_end]
+ above = _neighbour(after, line_start, line_end, up=True)
+ below = _neighbour(after, line_start, line_end, up=False)
+ for context in (same_line, above, below):
+ if has_negation_or_modal(context) or _CONTROL.search(context):
+ return Verdict.AMBIGUOUS
+ old_lines = {_text(line) for line in before.splitlines()}
+ for line in after.splitlines():
+ if _text(line) not in old_lines and _NEGATION.search(_abbreviations(line)):
+ return Verdict.AMBIGUOUS # a failure shown with the phrase
+ return Verdict.MATCH
diff --git a/openadapt/transducer_form_batch.py b/openadapt/transducer_form_batch.py
index a1821285b6..4021168875 100644
--- a/openadapt/transducer_form_batch.py
+++ b/openadapt/transducer_form_batch.py
@@ -18,6 +18,7 @@
from pathlib import Path
from typing import Any
+from openadapt._evidence import occurrences
from openadapt.transducer_macros import (
ISOLATION_PERSISTENT,
CompiledCommitMacro,
@@ -256,9 +257,9 @@ class SopEvaluationResult:
def _rule_satisfied(rule: SopRule, text: str) -> bool:
if len(text.strip()) < rule.min_length:
return False
- low = text.lower()
for token in rule.required_tokens:
- if token.lower() not in low:
+ # Whole tokens (openadapt._evidence): "signed" is not in "unsigned".
+ if occurrences(token, text, kind="text") == 0:
return False
for pattern in rule.required_patterns:
try:
diff --git a/openadapt/transducer_obligations.py b/openadapt/transducer_obligations.py
index fcb2388dbe..79b65a8c30 100644
--- a/openadapt/transducer_obligations.py
+++ b/openadapt/transducer_obligations.py
@@ -15,6 +15,14 @@
from datetime import datetime, timezone
from typing import Any, Iterator
+from openadapt._evidence import (
+ EvidenceKind,
+ Verdict,
+ evaluate_field,
+ has_negation_or_modal,
+ occurrences,
+)
+
__all__ = [
"CompiledFieldObligation",
"MicroHandoffResolution",
@@ -77,24 +85,262 @@ class ObligationDiffResult:
_HCPCS_RE = re.compile(r"\b[A-V]\d{4}\b")
_ICD_RE = re.compile(r"\b[A-TV-Z]\d{2}(?:\.[0-9A-Za-z]{1,4})?\b")
-# Free-text kinds compare after whitespace/case normalisation.
-_LOOSE_KINDS = frozenset({"date", "phrase", "field"})
+#: How each obligation kind compares (``openadapt._evidence``). A kind not
+#: listed is guessed from the value's shape.
+_EVIDENCE_KINDS: dict[str, EvidenceKind] = {
+ "identifier": "code",
+ "cpt": "code",
+ "hcpcs": "code",
+ "icd10": "code",
+ "amount": "currency",
+ "date": "date",
+ "phrase": "text",
+ "narrative_criterion": "text",
+}
def _norm(text: str) -> str:
return " ".join(str(text).lower().split())
-def _is_loose(ob: CompiledFieldObligation) -> bool:
- return (not ob.exact_match) or ob.kind in _LOOSE_KINDS
+def _evidence_kind(ob: CompiledFieldObligation) -> EvidenceKind:
+ return _EVIDENCE_KINDS.get(ob.kind, "auto")
+
+
+def _labels(ob: CompiledFieldObligation) -> list[str]:
+ """The label as written and with ``_`` read as a space, without a
+ ``(document)`` source note."""
+
+ base = re.sub(r"\s*\([^)]*\)\s*$", "", ob.label or "").strip()
+ out: list[str] = []
+ for label in (base, base.replace("_", " ")):
+ if label and label not in out:
+ out.append(label)
+ return out
+
+
+#: Kinds whose label comes from the prompt ("date", "CPT code", an ID's own
+#: prefix), not from the page. Their value must be the whole value of some
+#: ``Label: value`` field on the page instead.
+_PROMPT_LABEL_KINDS = frozenset(
+ {
+ "identifier",
+ "cpt",
+ "hcpcs",
+ "icd10",
+ "amount",
+ "date",
+ "phrase",
+ "narrative_criterion",
+ }
+)
+#: A ``Label:`` / ``Label =`` on the page: up to four words, before a colon,
+#: an equals sign or a hash.
+_PAGE_LABEL_RE = re.compile(
+ r"(? bool:
+ """Every word of the page label names the obligation: a word of its kind
+ (``_KIND_LABEL_WORDS``), of its own label, or, for an ID, its prefix or
+ a listed name for it (``_PREFIX_WORDS``)."""
+
+ words = re.findall(r"[a-z]+", _abbreviated_label(label))
+ if not words:
+ return False
+ allowed = _KIND_LABEL_WORDS.get(ob.kind, frozenset()) | set(
+ re.findall(r"[a-z]+", (ob.label or "").lower())
+ )
+ prefix = _id_prefix(ob)
+ if prefix is not None:
+ allowed |= {prefix.lower()} | _PREFIX_WORDS.get(prefix, frozenset())
+ return set(words) <= allowed
+
+
+def _abbreviated_label(label: str) -> str:
+ """``Claim No.`` / ``Claim #`` read as ``claim number``."""
+
+ return re.sub(r"\bno\b\.?|#", " number ", label.lower())
+
+
+def _label_lines(label: str, text: str) -> list[str]:
+ pattern = re.compile(rf"(? bool:
+ """The value is the whole bound value of a ``Label: value`` field whose
+ label names the obligation (``Charge:`` for an amount, ``Visit date:`` for
+ a date, ``Claim ID:`` for ``CLM-1234``), on a line with no negation,
+ failure or modal word (``Error``, ``not found``, ``Unable``, ``pending``).
+
+ A page label is evidence of position, so it must also name what the value
+ is: ``Copay: $250.00`` doesn't verify a charge, and ``Due: 2026-11-29``
+ doesn't verify a visit date. An ID whose only label is its own prefix
+ (``CLM``) must be the value of the one field on the page that holds an
+ ID with that prefix: with two such fields (a worklist, a header for
+ another record) it can't verify.
+ """
+
+ kind = _evidence_kind(ob)
+ labels = dict.fromkeys(m.group(1).strip() for m in _PAGE_LABEL_RE.finditer(text))
+ results = {
+ label: evaluate_field(ob.expected_value, text, label=label, kind=kind)
+ for label in labels
+ }
+ prefix = _id_prefix(ob)
+ if prefix is not None:
+ carrying = [
+ label
+ for label, result in results.items()
+ if prefix
+ in {p for value in result.bound_values for p, _ in _structured_ids(value)}
+ ]
+ if len(carrying) != 1:
+ return False
+ results = {carrying[0]: results[carrying[0]]}
+ for label, result in results.items():
+ if result.basis != "label" or result.verdict is not Verdict.MATCH:
+ continue
+ if not _label_names_obligation(ob, label):
+ continue
+ lines = _label_lines(label, text)
+ refusing = [
+ line
+ for line in lines
+ if has_negation_or_modal(
+ re.sub(re.escape(ob.expected_value), " ", line, flags=re.IGNORECASE)
+ )
+ ]
+ if lines and not refusing:
+ return True
+ return False
+
+
+def _id_prefix(ob: CompiledFieldObligation) -> str | None:
+ """The prefix of a structured-ID obligation (``CLM`` for ``CLM-1234``)."""
+
+ if ob.kind != "identifier":
+ return None
+ match = _STRUCTURED_ID_RE.fullmatch(ob.expected_value.strip())
+ return match.group(1).upper() if match else None
+
+
+def _other_ids_with_prefix(ob: CompiledFieldObligation, text: str) -> bool:
+ """Another ID with the same prefix is on the page (a worklist, a header
+ for a different record): the read-back can't show which one was saved."""
+
+ match = _STRUCTURED_ID_RE.fullmatch(ob.expected_value.strip())
+ if match is None:
+ return False
+ prefix = match.group(1).upper()
+ want = ob.expected_value.strip().lower()
+ return any(
+ p == prefix and value.lower() != want for p, value in _structured_ids(text)
+ )
def _value_in_text(ob: CompiledFieldObligation, text: str) -> bool:
+ """True only when ``text`` proves the value (the shared strict matcher).
+
+ The value must be bound to the obligation's label (``Dose: 5 mg``), be
+ the whole read-back, or, for a kind whose label came from the prompt, be
+ the whole value of some ``Label: value`` field on the page. A value merely
+ found in longer text, a label with two values, a value inside a longer
+ token (``250`` in ``$1,250.00``) or an ID next to another ID with the
+ same prefix is not proof. Callers that only need to locate a value use
+ :func:`_value_located`.
+ """
+
if not ob.expected_value:
return False
- if _is_loose(ob):
- return _norm(ob.expected_value) in _norm(text)
- return ob.expected_value in text
+ if ob.kind == "identifier" and _other_ids_with_prefix(ob, text):
+ return False
+ kind = _evidence_kind(ob)
+ if ob.kind in _PROMPT_LABEL_KINDS:
+ # The prompt's label ("date") would bind inside "Service date".
+ whole = evaluate_field(ob.expected_value, text, kind=kind)
+ return whole.verdict is Verdict.MATCH or _labelled_by_page(ob, text)
+ results = [
+ evaluate_field(ob.expected_value, text, label=label, kind=kind)
+ for label in _labels(ob) or [None]
+ ]
+ bound = {r.verdict for r in results if r.basis == "label"}
+ if bound:
+ return bound == {Verdict.MATCH}
+ return results[0].verdict is Verdict.MATCH
+
+
+def _value_located(ob: CompiledFieldObligation, text: str) -> bool:
+ """The value appears in ``text`` as whole tokens. Locates, never proves."""
+
+ if not ob.expected_value:
+ return False
+ return occurrences(ob.expected_value, text, kind=_evidence_kind(ob)) > 0
def compile_obligations_from_spec(
@@ -259,7 +505,7 @@ def mark_drafted_from_action(
if ob.status in (
ObligationStatus.PENDING,
ObligationStatus.MISSING,
- ) and _value_in_text(ob, action_text_or_value or ""):
+ ) and _value_located(ob, action_text_or_value or ""):
ob.status = ObligationStatus.DRAFTED
marked.append(ob.field_id)
return marked
@@ -283,7 +529,11 @@ def diff_readback_against_obligations(
is_editable: bool = False,
is_toast: bool = False,
) -> ObligationDiffResult:
- """Compare a read-back to obligations; verified only at 100% coverage."""
+ """Compare a read-back to obligations; verified only at 100% coverage.
+
+ Each value must be proven by the shared strict matcher: bound to its
+ label or the whole read-back, never only found somewhere in the text.
+ """
required = [o for o in obligations if o.required]
if is_toast or is_editable:
what = "a toast" if is_toast else "an editable field"
diff --git a/packages/flow/tests/test_evidence_parity.py b/packages/flow/tests/test_evidence_parity.py
new file mode 100644
index 0000000000..9e7a22cf37
--- /dev/null
+++ b/packages/flow/tests/test_evidence_parity.py
@@ -0,0 +1,193 @@
+"""Flow's read-back matcher against the shared evidence corpus.
+
+``openadapt_types.evidence`` is the strict matcher every verifier shares; its
+semantics come from :func:`openadapt_flow.runtime.effects.readback_values.compare_value`.
+This module runs the shared adversarial corpus through ``compare_value`` and
+checks that Flow never passes a case the shared module refuses. The cases where
+the two disagree are listed here and in
+``packages/types/docs/evidence-migration.md``; a new disagreement fails.
+It also holds Hypothesis properties of the shared module.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+from hypothesis import given, settings
+from hypothesis import strategies as st
+from openadapt_types import evidence
+from openadapt_types.evidence import Verdict, match_field, phrase_affirmed
+
+from openadapt_flow.runtime.effects.readback_values import compare_value
+
+CORPUS_PATH = (
+ Path(__file__).resolve().parents[2] / "types" / "tests" / "evidence_corpus.json"
+)
+if not CORPUS_PATH.exists(): # an sdist outside the monorepo
+ pytest.skip("shared evidence corpus not available", allow_module_level=True)
+CASES = [
+ c
+ for c in json.loads(CORPUS_PATH.read_text(encoding="utf-8"))["cases"]
+ if c["fn"] == "match_field"
+]
+
+#: Flow passes, the shared module refuses. Each is a Flow follow-up, listed in
+#: packages/types/docs/evidence-migration.md.
+FLOW_LOOSER = {
+ "two-numbers-in-one-field": "compare_label_bound_value compares only the "
+ "first token of a value of three characters or fewer, so 'Dose: 5 mg then "
+ "10 mg' passes 5",
+ "bound-dose-not-saved": "the same first-token rule passes 'Dose: 5 mg was "
+ "not saved' for 5",
+ "bound-dose-rejected": "the same first-token rule passes 'Dose: 5 mg "
+ "(rejected)' for 5",
+ "label-after-previous": "Flow's label extraction binds a label after a "
+ "modifier word ('Previous Patient ID:')",
+ "label-after-former": "Flow binds 'Name' in 'Former Name:'",
+ "label-after-previous-name": "Flow binds 'Name' in 'Previous Name:'",
+ "label-after-error": "Flow binds 'Claim ID' in 'Error: Claim ID:'",
+ "label-after-error-dash": "Flow binds 'Claim ID' in 'Error - Claim ID:'",
+ **dict.fromkeys(
+ (
+ "label-after-another-field",
+ "modifier-after-field-mrn",
+ "modifier-after-field-claim",
+ "modifier-after-field-name",
+ "mother-name-after-field",
+ "status-before-label",
+ "modifier-two-spaces",
+ "modifier-cell-pipe",
+ "modifier-cell-tab",
+ "modifier-cell-semicolon",
+ "heading-two-spaces",
+ "heading-cell-pipe",
+ ),
+ "Flow binds a label after other words in its field or in the cell "
+ "before it ('Name: Jane Doe Previous MRN:', 'Previous | MRN:')",
+ ),
+}
+
+#: The shared module passes, Flow refuses (Flow is stricter here).
+SHARED_LOOSER = {
+ "labelled-name-then-next-label": "Flow's label extraction runs to the end of "
+ "the line, so a second label on it makes a mismatch",
+ "json-second-key": "Flow's label extraction doesn't read a quoted JSON key",
+ "labelled-total-by-value": "Flow's label extraction stops at the thousands comma",
+ "labelled-currency": "Flow's label extraction stops at the thousands comma",
+ "labelled-month-name-date": "Flow's label extraction stops at the comma",
+ "accounting-negative-match": "Flow's number kind needs a plain number",
+ "same-date-string-reads-two-ways": "Flow calls the same date string ambiguous "
+ "when it reads two ways",
+}
+
+
+def _flow_kind(case: dict) -> str:
+ kind = case["kind"]
+ if kind == "auto":
+ kind = evidence.infer_kind(case["expected"])
+ return "text" if kind == "name" else kind
+
+
+def _flow(case: dict) -> str:
+ return compare_value(
+ case["observed"],
+ case["expected"],
+ kind=_flow_kind(case), # type: ignore[arg-type]
+ source="structure",
+ exact=False,
+ label=case["label"],
+ )
+
+
+def _shared(case: dict) -> Verdict:
+ return match_field(
+ case["expected"], case["observed"], label=case["label"], kind=case["kind"]
+ )
+
+
+@pytest.mark.parametrize("case", CASES, ids=[c["id"] for c in CASES])
+def test_flow_never_passes_what_the_shared_module_refuses(case: dict) -> None:
+ flow, shared = _flow(case), _shared(case)
+ if flow == "match" and shared is not Verdict.MATCH:
+ assert case["id"] in FLOW_LOOSER, (
+ f"Flow passes {case['id']!r}, the shared module says {shared.value}"
+ )
+ if case["verdict"] != "match" and case["id"] not in FLOW_LOOSER:
+ assert flow != "match"
+
+
+def test_the_listed_disagreements_are_exactly_the_real_ones() -> None:
+ looser = {c["id"] for c in CASES if _flow(c) == "match" and not _shared(c).passes}
+ stricter = {c["id"] for c in CASES if _flow(c) != "match" and _shared(c).passes}
+ assert looser == set(FLOW_LOOSER)
+ assert stricter == set(SHARED_LOOSER)
+
+
+# --- properties of the shared module -----------------------------------------
+
+_word = st.text(alphabet="abcdefghijklmnopqrstuvwxyz", min_size=2, max_size=8)
+_code = st.from_regex(r"[A-Z]{2,4}-[0-9]{1,5}", fullmatch=True)
+
+
+@settings(max_examples=200, deadline=None)
+@given(st.integers(0, 10**7), st.integers(0, 10**7))
+def test_labelled_numbers_match_only_by_value(x: int, y: int) -> None:
+ verdict = match_field(str(x), f"Amount: ${y:,}.00", label="Amount", kind="number")
+ assert verdict.passes is (x == y)
+
+
+@settings(max_examples=200, deadline=None)
+@given(st.integers(1, 999), st.integers(1, 9999))
+def test_a_number_is_never_found_inside_a_larger_number(x: int, high: int) -> None:
+ bigger = int(f"{high}{x:03d}") # x is the low three digits of a larger number
+ for text in (f"Total ${bigger:,}.00", f"Total: {bigger}", f"Ref {bigger}"):
+ assert match_field(str(x), text).value == "mismatch", text
+
+
+@settings(max_examples=200, deadline=None)
+@given(_code, st.sampled_from("-./,"), st.text(alphabet="AZ09", min_size=1, max_size=4))
+def test_joining_punctuation_never_ends_a_token(
+ value: str, joiner: str, tail: str
+) -> None:
+ joined = f"{value}{joiner}{tail}"
+ assert match_field(value, joined).value == "mismatch"
+ assert match_field(value, f"ID: {joined}", label="ID").value == "mismatch"
+
+
+@settings(max_examples=200, deadline=None)
+@given(_code, _word, _word)
+def test_a_value_found_in_longer_text_is_never_proof(
+ value: str, before: str, after: str
+) -> None:
+ assert match_field(value, f"{before} {value} {after}") is Verdict.AMBIGUOUS
+
+
+@settings(max_examples=200, deadline=None)
+@given(_word, _code, _code)
+def test_one_label_two_values_is_ambiguous(label: str, a: str, b: str) -> None:
+ text = f"{label}: {a}\n{label}: {b}"
+ verdict = match_field(a, text, label=label, kind="code")
+ assert verdict is (Verdict.MATCH if a.lower() == b.lower() else Verdict.AMBIGUOUS)
+
+
+@settings(max_examples=200, deadline=None)
+@given(_word, _word)
+def test_a_phrase_already_on_screen_is_never_affirmed(phrase: str, extra: str) -> None:
+ before = f"{extra} {phrase}"
+ assert not phrase_affirmed(before, f"{before}\n{phrase}", phrase).passes
+
+
+@settings(max_examples=300, deadline=None)
+@given(
+ st.text(alphabet="aB1-. ", max_size=8),
+ st.text(alphabet="aB1-. ", max_size=8),
+ st.sampled_from(["text", "code"]),
+)
+def test_whole_field_flow_match_implies_shared_match(
+ observed: str, expected: str, kind: str
+) -> None:
+ flow = compare_value(observed, expected, kind=kind, source="structure", exact=True) # type: ignore[arg-type]
+ if flow == "match":
+ assert match_field(expected, observed, kind=kind) is Verdict.MATCH # type: ignore[arg-type]
diff --git a/packages/flow/tests/test_evidence_pending_callers.py b/packages/flow/tests/test_evidence_pending_callers.py
new file mode 100644
index 0000000000..486679eb9a
--- /dev/null
+++ b/packages/flow/tests/test_evidence_pending_callers.py
@@ -0,0 +1,155 @@
+"""Flow callers that still count loose text as proof, run on the shared corpus.
+
+Each case below is one ``packages/types/tests/evidence_corpus.json`` case
+whose verdict is not ``match``. The caller must refuse it. Cases a caller
+passes today are ``xfail(strict=True)`` with the change that fixes it: when
+the fix lands the case passes, the strict marker turns that into a failure,
+and whoever lands the fix deletes the marker. The list is in
+``packages/types/docs/evidence-migration.md``.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from pathlib import Path
+
+import pytest
+
+from openadapt_flow.guard import check_identity
+from openadapt_flow.runtime import worklist_copilot
+
+CORPUS_PATH = (
+ Path(__file__).resolve().parents[2] / "types" / "tests" / "evidence_corpus.json"
+)
+if not CORPUS_PATH.exists(): # an sdist outside the monorepo
+ pytest.skip("shared evidence corpus not available", allow_module_level=True)
+CORPUS = json.loads(CORPUS_PATH.read_text(encoding="utf-8"))["cases"]
+REFUSED_FIELDS = [
+ c
+ for c in CORPUS
+ if c["fn"] == "match_field" and c["verdict"] != "match" and c["expected"]
+]
+REFUSED_PHRASES = [
+ c for c in CORPUS if c["fn"] == "phrase_affirmed" and c["verdict"] != "match"
+]
+
+GUARD_STILL_LOOSE_REASON = (
+ "guard.check_identity accepts a value found in longer text or with words "
+ "around it; the field-bound identity guard (PR #2786, merged) still "
+ "passes this case, so no fix yet"
+)
+#: check_identity still passes these after PR #2786.
+GUARD_STILL_LOOSE = {
+ "bound-amount-failed",
+ "bound-amount-pending",
+ "bound-claim-not-found",
+ "bound-claim-void",
+ "bound-diagnosis-ruled-out",
+ "bound-dose-not-saved",
+ "bound-dose-rejected",
+ "code-then-second-code",
+ "comparator-plus-suffix",
+ "credit-suffix",
+ "debit-suffix",
+ "heading-cell-pipe",
+ "heading-two-spaces",
+ "label-after-another-field",
+ "label-after-error",
+ "label-after-error-dash",
+ "label-after-former",
+ "label-after-previous",
+ "label-after-previous-name",
+ "labelled-code-first-token",
+ "labelled-name-with-aside",
+ "modifier-after-field-claim",
+ "modifier-after-field-mrn",
+ "modifier-after-field-name",
+ "modifier-cell-pipe",
+ "modifier-cell-semicolon",
+ "modifier-cell-tab",
+ "modifier-two-spaces",
+ "mother-name-after-field",
+ "mrn-then-second-mrn",
+ "name-aside-another-patient",
+ "name-inside-page-text",
+ "short-code-in-prose",
+ "status-before-label",
+ "trailing-minus",
+ "two-numbers-in-one-field",
+}
+
+WORKLIST_REASON = (
+ "worklist_copilot._contains_affirmed_phrase ignores questions, modal, "
+ "future and conditional forms, control labels and text already on the "
+ "draft frame; no fix yet (PR #2778 changes the pixel observer around it, "
+ "not this helper)"
+)
+WORKLIST_PASSES_TODAY = {
+ "can-be-signed",
+ "conditional-if",
+ "conditional-once",
+ "confirm-dialog-question",
+ "future-tense",
+ "menu-item-in-both-frames",
+ "must-be-signed",
+ "negation-line-below",
+ "none-saved",
+ "nothing-saved",
+ "previous-signature-in-both-frames",
+ "saved-as-draft",
+ "saved-before",
+ "saved-by-another-user",
+ "saved-previously",
+ "saved-then-reverted",
+ "saved-then-rolled-back",
+ "saved-then-undo",
+ "saved-to-outbox",
+ "saved-zero-of-three",
+ "saved-zero-records",
+ "to-be-signed",
+ "toast-with-ok-button",
+}
+
+
+def _params(cases: list[dict], failing: dict[str, str]) -> list:
+ """One param per case; a case the caller passes today is a strict xfail."""
+ return [
+ pytest.param(
+ c,
+ id=c["id"],
+ marks=[pytest.mark.xfail(strict=True, reason=failing[c["id"]])]
+ if c["id"] in failing
+ else [],
+ )
+ for c in cases
+ ]
+
+
+@pytest.mark.parametrize(
+ "case",
+ _params(
+ REFUSED_FIELDS,
+ dict.fromkeys(GUARD_STILL_LOOSE, GUARD_STILL_LOOSE_REASON),
+ ),
+)
+def test_guard_check_identity_refuses(case: dict) -> None:
+ verdict, _ = check_identity(
+ {case["label"] or "value": case["expected"]}, case["observed"]
+ )
+ assert verdict != "verified"
+
+
+def _tokens(text: str) -> list[str]:
+ return re.findall(r"[0-9a-z]+", text.casefold())
+
+
+@pytest.mark.parametrize(
+ "case",
+ _params(REFUSED_PHRASES, dict.fromkeys(WORKLIST_PASSES_TODAY, WORKLIST_REASON)),
+)
+def test_worklist_affirmed_phrase_refuses(case: dict) -> None:
+ # The helper sees only the new frame's tokens; the caller compares frames.
+ assert not worklist_copilot._contains_affirmed_phrase(
+ _tokens(case["after"]), tuple(_tokens(case["phrase"]))
+ )
diff --git a/packages/kernel/CHANGELOG.md b/packages/kernel/CHANGELOG.md
index ad345abaef..2fc57845c3 100644
--- a/packages/kernel/CHANGELOG.md
+++ b/packages/kernel/CHANGELOG.md
@@ -1,5 +1,21 @@
# Changelog
+## Unreleased
+
+- `token_boundary_check`, and through it `verify_sqlite_ro`,
+ `verify_pdf_readback`, `verify_cross_tab_dom` and the non-DOM adapter, uses
+ the shared strict evidence matcher (`openadapt_kernel._evidence`, a copy of
+ `openadapt_types.evidence`). A value is cited only when it equals a
+ structured binding, is bound to its key or an alias, or is the whole text.
+ A value merely present in the text (`Member MEM-442`), inside a longer token
+ (`250` in `$1,250.00`), or under a key with two values is now missing. Only
+ the DOM bindings that name a key best count, and a select's option text is
+ a separate candidate. SQLite rows bind by column. A binding key names a
+ key only when its words are the key's words, so `Previous Member ID`,
+ `member_id_old` and `Member ID (previous)` are not `member_id`; an input's
+ name, id, test id and label are scored apart. Fields on one line need a
+ `|`, `;` or tab between them to bind.
+
## v0.2.0 (2026-11-29)
Breaking: autopilot now fails closed on any pack that is not signed and promoted.
diff --git a/packages/kernel/src/openadapt_kernel/_evidence.py b/packages/kernel/src/openadapt_kernel/_evidence.py
new file mode 100644
index 0000000000..5d1a075cb2
--- /dev/null
+++ b/packages/kernel/src/openadapt_kernel/_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())
+ # ": value", " = value", " # value", "\tvalue",
+ # '"": "value"', or the label alone on its line with the value
+ # below. Two spaces don't bind: a form heading row ("Policy Number Submit")
+ # would bind its next heading.
+ return re.compile(
+ rf"(? bool:
+ """Whether a label at ``start`` begins a field.
+
+ Only punctuation may come between the last hard separator (a line break,
+ ``|``, ``;``, a tab, or a JSON key's ``{`` / ``",``) and the label.
+ Anything else may be a modifier: ``Previous Patient ID:``, ``Error:
+ Claim ID:``, and also ``Name: Jane Doe Previous MRN:``, where the text
+ can't tell the end of one value from a modifier on the next label. So a
+ single-line ``Patient: X DOB: Y`` doesn't bind ``DOB``. After ``|``,
+ ``;`` or a tab, the cell before must be empty or a whole field (``Name:
+ Jane | MRN:``): a bare word (``Previous | MRN:``) or a heading with no
+ value (``Previous: | MRN:``) may name the next cell's record.
+ """
+
+ seps = list(_HARD_SEPARATOR.finditer(text, 0, start))
+ seg_start = seps[-1].end() if seps else 0
+ if re.search(r"[^\W_]", text[seg_start:start]):
+ return False
+ if seps and seps[-1].group() in "|;\t":
+ cell_start = seps[-2].end() if len(seps) > 1 else 0
+ cell = text[cell_start : seps[-1].start()]
+ if re.search(r"[^\W_]", cell) and not _FIELD_CELL.search(cell):
+ return False # "Previous | MRN: MRN-1", "Previous: | MRN: MRN-1"
+ return True
+
+
+def _bound_values(text: str, label: str) -> list[str]:
+ pattern = _label_pattern(label)
+ if pattern is None or not text:
+ return []
+ values: list[str] = []
+ for m in pattern.finditer(text):
+ if not _field_start(text, m.start()):
+ continue
+ if "\n" in m.group():
+ # The label alone on its line, the value on the next one.
+ line_start = text.rfind("\n", 0, m.start()) + 1
+ if text[line_start : m.start()].strip():
+ continue
+ rest = text[m.end() :]
+ if rest[:1] in ('"', "'") and rest.find(rest[0], 1) > 0:
+ value = rest[1 : rest.find(rest[0], 1)].strip() # a quoted value
+ else:
+ end = _VALUE_END.search(rest)
+ value = (rest[: end.start()] if end else rest).strip()
+ if value:
+ values.append(value)
+ return values
+
+
+#: Words that may follow a number in its field: units of measure, count and
+#: time, and currency codes. Nothing else may share the field with the value.
+_UNITS = frozenset(
+ {
+ "mg", "mcg", "ug", "µg", "g", "kg", "lb", "lbs", "oz", "ml", "l", "dl",
+ "cc", "u", "iu", "unit", "units", "mmol", "meq", "%", "tab", "tabs",
+ "tablet", "tablets", "cap", "caps", "capsule", "capsules", "dose",
+ "doses", "puff", "puffs", "drop", "drops", "h", "hr", "hrs", "hour",
+ "hours", "min", "mins", "minute", "minutes", "d", "day", "days", "wk",
+ "week", "weeks", "mo", "month", "months", "yr", "yrs", "year", "years",
+ "mm", "cm", "m", "km", "in", "ft", "m2", "mmhg", "bpm", "ea", "each",
+ "usd", "cad", "eur", "gbp",
+ }
+) # fmt: skip
+
+
+def _units_only(rest: str) -> bool:
+ """Whether ``rest`` holds only unit words (``mg``, ``mg/dL``, ``USD``)."""
+
+ rest = rest.strip()
+ if rest.endswith("."):
+ rest = rest[:-1]
+ return all(
+ part in _UNITS for tok in rest.lower().split() for part in tok.split("/")
+ )
+
+
+def _compare_bound(bound: str, expected: str, kind: _Resolved) -> Verdict:
+ """One bound value against ``expected``: the value and nothing more,
+ except unit words after a number."""
+
+ if kind in ("number", "currency"):
+ numbers = _numeric_spans(bound)
+ if not numbers:
+ return Verdict.MISMATCH
+ verdicts = [_same_number(tok, expected, kind) for tok, _, _ in numbers]
+ if len(numbers) > 1:
+ return Verdict.AMBIGUOUS if Verdict.MATCH in verdicts else Verdict.MISMATCH
+ _, start, end = numbers[0]
+ if verdicts[0] is Verdict.MATCH and not _units_only(
+ bound[:start] + " " + bound[end:]
+ ):
+ # "5 mg was not saved", "<5", "250.00 CR", "250.00-".
+ return Verdict.AMBIGUOUS
+ return verdicts[0]
+ whole = _compare_whole(bound, expected, kind)
+ if whole is not Verdict.MISMATCH:
+ return whole
+ if kind == "code" and len(expected.split()) == 1:
+ # "CLM-1." is the code; "CLM-1 not found" or "MRN-104 (Jane Doe)" is
+ # the code and something else in the field.
+ first, *rest = bound.split()
+ verdict = _compare_whole(first.strip(".,:;!?()[]{}\"'"), expected, kind)
+ if verdict is Verdict.MATCH and rest:
+ return Verdict.AMBIGUOUS
+ if verdict is Verdict.MATCH:
+ return verdict
+ if _token_count(expected, bound, kind):
+ return Verdict.AMBIGUOUS # "Jane Sample (not this patient)"
+ return Verdict.MISMATCH
+
+
+# --- public API -------------------------------------------------------------
+
+
+def evaluate_field(
+ expected: str,
+ observed_text: str,
+ *,
+ label: Optional[str] = None,
+ kind: EvidenceKind = "auto",
+) -> FieldEvidence:
+ """Judge one expected value against observed text, with the basis.
+
+ See the module docstring for the rules. ``observed_text`` may be one
+ field's read or a whole page.
+ """
+
+ expected = str(expected if expected is not None else "")
+ observed = str(observed_text if observed_text is not None else "")
+ resolved = _resolve(kind, expected)
+ if not expected.strip():
+ return FieldEvidence(Verdict.MISMATCH, "absent", resolved)
+ if label is not None and label.strip():
+ bound = _bound_values(observed, label)
+ if bound:
+ verdicts = {_compare_bound(b, expected, resolved) for b in bound}
+ if verdicts == {Verdict.MATCH}:
+ verdict = Verdict.MATCH
+ elif len({_text(b) for b in bound}) > 1:
+ verdict = Verdict.AMBIGUOUS # one label, two values
+ elif Verdict.AMBIGUOUS in verdicts:
+ verdict = Verdict.AMBIGUOUS
+ else:
+ verdict = Verdict.MISMATCH
+ return FieldEvidence(verdict, "label", resolved, tuple(bound))
+ whole = _compare_whole(observed, expected, resolved)
+ if whole is not Verdict.MISMATCH:
+ return FieldEvidence(whole, "whole", resolved)
+ if _token_count(expected, observed, resolved):
+ return FieldEvidence(Verdict.AMBIGUOUS, "contained", resolved)
+ return FieldEvidence(Verdict.MISMATCH, "absent", resolved)
+
+
+def match_field(
+ expected: str,
+ observed_text: str,
+ *,
+ label: Optional[str] = None,
+ kind: EvidenceKind = "auto",
+) -> Verdict:
+ """``MATCH``, ``MISMATCH`` or ``AMBIGUOUS``; only ``MATCH`` may pass."""
+
+ return evaluate_field(expected, observed_text, label=label, kind=kind).verdict
+
+
+#: A question, a modal or future form, a condition, or a request: the phrase
+#: is asked about, required or expected, not stated as done.
+_MODAL = re.compile(
+ r"\?|\b(?:should|will|would|shall|must|can|could|may(?!\s+\d)|might|need|needs|"
+ r"needed|to be|are you sure|going to|about to|ready to|pending|awaiting|"
+ r"waiting|required|requires|please|if|once|when|unless|until)\b",
+ re.IGNORECASE,
+)
+_NEGATION = re.compile(
+ r"\b(?:not|no|never|none|nothing|cannot|unable|fail|fails|failed|failure|"
+ r"without|error|errors|missing|invalid|rejected|denied|declined|void|"
+ r"voided|cancelled|canceled|reverted|rolled back|undone|discarded|aborted|"
+ r"draft|by another|undo|previously|before|outbox|queued)\b|n't\b|\b0\s+(?:of|records?|items?|rows?|changes?)\b",
+ re.IGNORECASE,
+)
+#: ``No.`` / ``No:`` / ``No #`` as the abbreviation of number, not a negation.
+_NUMBER_ABBREVIATION = re.compile(r"\bno\b\.?(?=\s*[:#=.]|\.)", re.IGNORECASE)
+
+
+def _abbreviations(text: str) -> str:
+ return _NUMBER_ABBREVIATION.sub("number", text)
+
+
+def has_negation_or_modal(text: str) -> bool:
+ """Whether ``text`` holds a negation or failure word (``not``, ``Error``,
+ ``rejected``, ``void``), or a question, modal, future or conditional form
+ (``?``, ``will``, ``pending``, ``if``). ``No.`` meaning number doesn't
+ count."""
+
+ cleaned = _abbreviations(str(text or ""))
+ return bool(_NEGATION.search(cleaned) or _MODAL.search(cleaned))
+
+
+_CONTROL = re.compile(r"\b(?:confirm|cancel|ok|sign|yes)\b", re.IGNORECASE)
+
+
+def _line_bounds(text: str, pos: int) -> tuple[int, int]:
+ start = text.rfind("\n", 0, pos) + 1
+ end = text.find("\n", pos)
+ return start, (len(text) if end == -1 else end)
+
+
+def _neighbour(text: str, line_start: int, line_end: int, up: bool) -> str:
+ if up:
+ if line_start == 0:
+ return ""
+ prev_start, _ = _line_bounds(text, line_start - 1)
+ return text[prev_start : line_start - 1]
+ if line_end >= len(text):
+ return ""
+ _, next_end = _line_bounds(text, line_end + 1)
+ return text[line_end + 1 : next_end]
+
+
+def phrase_affirmed(before_text: str, after_text: str, phrase: str) -> Verdict:
+ """Whether ``after_text`` affirms ``phrase`` as a new, plain statement.
+
+ ``MATCH`` only when the phrase is absent from ``before_text``, present in
+ ``after_text`` as whole tokens, and every appearance is a statement: no
+ question mark, modal or future form, or negation on its line or the lines
+ next to it, no control label (``Confirm``, ``Cancel``, ``OK``, ``Sign``,
+ ``Yes``) on those lines, and no negation or failure word on any line of
+ ``after_text`` that isn't in ``before_text`` (``Saved`` then ``Error:
+ record locked``).
+ """
+
+ before = str(before_text or "")
+ after = str(after_text or "")
+ if not str(phrase or "").strip():
+ return Verdict.MISMATCH
+ if _spans(phrase, before):
+ return Verdict.AMBIGUOUS # already there: it doesn't show this commit
+ spans = _spans(phrase, after)
+ if not spans:
+ return Verdict.MISMATCH
+ for start, end in spans:
+ line_start, line_end = _line_bounds(after, start)
+ same_line = after[line_start:start] + " " + after[end:line_end]
+ above = _neighbour(after, line_start, line_end, up=True)
+ below = _neighbour(after, line_start, line_end, up=False)
+ for context in (same_line, above, below):
+ if has_negation_or_modal(context) or _CONTROL.search(context):
+ return Verdict.AMBIGUOUS
+ old_lines = {_text(line) for line in before.splitlines()}
+ for line in after.splitlines():
+ if _text(line) not in old_lines and _NEGATION.search(_abbreviations(line)):
+ return Verdict.AMBIGUOUS # a failure shown with the phrase
+ return Verdict.MATCH
diff --git a/packages/kernel/src/openadapt_kernel/oracles.py b/packages/kernel/src/openadapt_kernel/oracles.py
index 43d0b6d8d1..f789c8f262 100644
--- a/packages/kernel/src/openadapt_kernel/oracles.py
+++ b/packages/kernel/src/openadapt_kernel/oracles.py
@@ -21,6 +21,7 @@
from typing import Any, Dict, List, Optional, Sequence
from urllib.parse import urlparse
+from openadapt_kernel._evidence import Verdict, evaluate_field, match_field
from openadapt_kernel.ledger import ReadBackProof
_STREAM_RE = re.compile(rb"stream\r?\n(.*?)\r?\nendstream", re.DOTALL)
@@ -40,9 +41,10 @@
return p ? (p.innerText || p.textContent || '').trim() : '';
};
for (const el of document.querySelectorAll('input,textarea,select')) {
- const val = el.tagName === 'SELECT' && el.selectedOptions && el.selectedOptions[0]
- ? `${el.value} ${el.selectedOptions[0].text || ''}`.trim() : String(el.value || '');
- bindings.push({key: [el.name, el.id, el.getAttribute('data-testid'), labelFor(el)].filter(Boolean).join(' '), val});
+ const opt = el.tagName === 'SELECT' && el.selectedOptions && el.selectedOptions[0];
+ const alt = opt ? String(opt.text || '').trim() : '';
+ const keys = [el.name, el.id, el.getAttribute('data-testid'), labelFor(el)].filter(Boolean);
+ bindings.push({key: keys.join(' '), keys, val: String(el.value || ''), alt});
}
for (const dt of document.querySelectorAll('dt')) {
const dd = dt.nextElementSibling;
@@ -91,22 +93,98 @@ def _key_aliases(key: str) -> List[str]:
return [a for a in out if a]
-def _field_bound_match(key: str, val: str, compact: str, field_bindings: Sequence[Dict[str, str]]) -> bool:
- v_re = rf"(?= 2}
+def _binding_key_score(key: str, binding_key: str) -> float:
+ """How well a binding's key names ``key``.
+
+ 2 when its words are exactly the key's words (``member_id``, ``Member
+ ID``). Otherwise, when every one of its words is one of the key's, the
+ share of the key's words it has, if at least half (``State`` for
+ ``state_code``). A word that isn't the key's names another field, before
+ or after it: ``Previous Member ID``, ``member_id_old`` and ``Member ID
+ (previous)`` are not ``member_id`` and score 0.
+ """
+ btoks = re.findall(r"[a-z0-9]+", binding_key.lower())
+ ktoks = re.findall(r"[a-z0-9]+", key.lower())
+ if not btoks or not ktoks:
+ return 0.0
+ if btoks == ktoks:
+ return 2.0
+ key_set = set(ktoks)
+ if not set(btoks) <= key_set:
+ return 0.0
+ share = len(set(btoks)) / len(key_set)
+ return share if share >= 0.5 else 0.0
+
+
+def _binding_keys(binding: Dict[str, Any]) -> List[str]:
+ """A binding's key names: ``keys`` when the page gave each one apart (an
+ input's name, id, test id and label), else ``key``."""
+ keys = binding.get("keys")
+ if isinstance(keys, (list, tuple)) and keys:
+ return [str(k) for k in keys if k]
+ return [str(binding.get("key") or "")]
+
+
+def _binding_verdict(key: str, val: str, field_bindings: Sequence[Dict[str, str]]) -> Optional[Verdict]:
+ """The verdict from structured key/value bindings, or None if none name ``key``.
+
+ Each binding's value is one whole field: it matches only when it equals the
+ expected value (a select's option text counts as its value). Two bindings
+ for the key with different values are ``AMBIGUOUS``.
+ """
+ scored: List[tuple[float, List[str]]] = []
for b in field_bindings:
- bk = str(b.get("key") or "")
- bv = " ".join(str(b.get("val") or "").split())
- if not bk or not bv:
- continue
- btoks = {t.lower() for t in re.findall(r"[a-z0-9]+", bk)}
- if (key.lower() in bk.lower() or (key_toks and len(key_toks & btoks) / len(key_toks) >= 0.5)) and re.search(v_re, bv):
- return True
- for alias in aliases:
- if re.search(rf"(? 1 else Verdict.MISMATCH
+
+
+def field_verdict(
+ key: str,
+ val: str,
+ text: str,
+ *,
+ field_bindings: Sequence[Dict[str, str]] = (),
+) -> Verdict:
+ """Judge one expected field with the shared strict matcher (``_evidence``).
+
+ Structured bindings decide first. Then the value bound to the key, or to
+ one of its aliases (``state_code`` -> ``State``), in ``text``. Without a
+ binding the whole text must equal the value; a value merely found in the
+ text is ``AMBIGUOUS`` and never cited.
+ """
+ bound = _binding_verdict(key, val, field_bindings)
+ if bound is not None:
+ return bound
+ results = [evaluate_field(val, text, label=alias) for alias in _key_aliases(key)]
+ labelled = [r for r in results if r.basis == "label"]
+ if labelled:
+ if all(r.verdict is Verdict.MATCH for r in labelled):
+ return Verdict.MATCH
+ return Verdict.AMBIGUOUS if any(
+ r.verdict is not Verdict.MISMATCH for r in labelled
+ ) else Verdict.MISMATCH
+ return evaluate_field(val, text).verdict
def token_boundary_check(
@@ -115,17 +193,22 @@ def token_boundary_check(
*,
field_bindings: Sequence[Dict[str, str]] = (),
) -> tuple[List[str], List[str]]:
- """Return (cited_values, missing_keys) with field-bound matching; bare 1-2 char values require binding."""
- compact = " ".join((text or "").split())
+ """Return (cited_values, missing_keys) under the shared strict matcher.
+
+ A value is cited only on ``MATCH``: bound to its key or an alias
+ (``State: CA``, ``quantity=1``), equal to a structured binding, or the
+ whole text. A value found inside longer text, a key with two values, or a
+ value inside a longer token (``250`` in ``$1,250.00``, ``John Smith`` in
+ ``John Smith-Jones``) is missing.
+ """
+ raw = text or ""
cited: List[str] = []
missing: List[str] = []
for key, val in expected_fields.items():
v = str(val).strip()
if not v:
continue
- if _field_bound_match(key, v, compact, field_bindings):
- cited.append(v)
- elif len(v) >= 3 and re.search(rf"(? 0),
diff --git a/packages/kernel/tests/test_evidence_vendored.py b/packages/kernel/tests/test_evidence_vendored.py
new file mode 100644
index 0000000000..79fa31aae1
--- /dev/null
+++ b/packages/kernel/tests/test_evidence_vendored.py
@@ -0,0 +1,59 @@
+"""The kernel's copy of the shared evidence matcher.
+
+``openadapt_kernel._evidence`` is a byte-identical copy of
+``openadapt_types/evidence.py`` (the kernel depends only on cryptography, so
+it vendors the stdlib-only module instead of depending on openadapt-types and
+pydantic). These tests run the shared adversarial corpus through the copy and
+through ``token_boundary_check``, and fail when the copy drifts.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import Any, Dict
+
+import pytest
+
+from openadapt_kernel import _evidence
+from openadapt_kernel.oracles import token_boundary_check
+
+MONOREPO = Path(__file__).resolve().parents[3]
+CANONICAL = MONOREPO / "packages" / "types" / "openadapt_types" / "evidence.py"
+CORPUS_PATH = MONOREPO / "packages" / "types" / "tests" / "evidence_corpus.json"
+
+if not CORPUS_PATH.exists(): # an sdist outside the monorepo
+ pytest.skip("shared evidence corpus not available", allow_module_level=True)
+
+CASES = json.loads(CORPUS_PATH.read_text(encoding="utf-8"))["cases"]
+FIELD_CASES = [c for c in CASES if c["fn"] == "match_field"]
+
+
+def test_vendored_copy_is_byte_identical() -> None:
+ assert Path(_evidence.__file__).read_bytes() == CANONICAL.read_bytes(), (
+ "copy packages/types/openadapt_types/evidence.py over openadapt_kernel/_evidence.py"
+ )
+
+
+@pytest.mark.parametrize("case", CASES, ids=[c["id"] for c in CASES])
+def test_corpus_through_the_vendored_copy(case: Dict[str, Any]) -> None:
+ if case["fn"] == "phrase_affirmed":
+ got = _evidence.phrase_affirmed(case["before"], case["after"], case["phrase"])
+ else:
+ got = _evidence.match_field(
+ case["expected"], case["observed"], label=case["label"], kind=case["kind"]
+ )
+ assert got.value == case["verdict"]
+
+
+@pytest.mark.parametrize(
+ "case", [c for c in FIELD_CASES if c["label"]], ids=lambda c: c["id"]
+)
+def test_token_boundary_check_cites_only_corpus_matches(case: Dict[str, Any]) -> None:
+ # The corpus label is the field key; the kernel guesses the kind.
+ cited, missing = token_boundary_check({case["label"]: case["expected"]}, case["observed"])
+ if not str(case["expected"]).strip():
+ assert cited == [] and missing == []
+ return
+ if case["verdict"] != "match":
+ assert cited == [] and missing == [case["label"]], case["id"]
diff --git a/packages/kernel/tests/test_kernel_runner_e2e.py b/packages/kernel/tests/test_kernel_runner_e2e.py
index 1b06c8f229..7e85cfa63b 100644
--- a/packages/kernel/tests/test_kernel_runner_e2e.py
+++ b/packages/kernel/tests/test_kernel_runner_e2e.py
@@ -22,7 +22,7 @@ def log_message(self, format: str, *args: Any) -> None:
def do_GET(self) -> None:
rows = "".join(
- f"REF={r['ref']} POLICY={r['policy_number']} ZIP={r['postal_code']} "
+ f"REF={r['ref']}; POLICY={r['policy_number']}; POSTAL_CODE={r['postal_code']} "
for r in saved_records
)
html = f"""
diff --git a/packages/kernel/tests/test_oracles_and_mcp.py b/packages/kernel/tests/test_oracles_and_mcp.py
index bbbd09914e..5496756d91 100644
--- a/packages/kernel/tests/test_oracles_and_mcp.py
+++ b/packages/kernel/tests/test_oracles_and_mcp.py
@@ -56,8 +56,8 @@ def test_sqlite_ro_oracle_verifies_and_refutes(tmp_path: Path) -> None:
def test_pdf_stream_oracle_reads_flate_and_blocks_invisible_3tr_spoof(tmp_path: Path) -> None:
# Real FlateDecode PDF stream containing visible text AND invisible 3 Tr spoofed text
content_stream = (
- b"BT /F1 12 Tf 0 Tr (Confirmation REF=PA-7741 Member MEM-442 Code D2740) Tj "
- b"3 Tr (SPOOFED_CODE D9999) Tj 0 Tr (Approved) Tj ET"
+ b"BT /F1 12 Tf 0 Tr (Approved) Tj 3 Tr (SPOOFED_CODE D9999) Tj "
+ b"0 Tr (Confirmation REF=PA-7741 | Member: MEM-442 | Code: D2740) Tj ET"
)
compressed = zlib.compress(content_stream)
pdf_bytes = b"%PDF-1.4\n1 0 obj\n<< /Filter /FlateDecode >>\nstream\n" + compressed + b"\nendstream\nendobj\n%%EOF"
@@ -76,6 +76,16 @@ def test_pdf_stream_oracle_reads_flate_and_blocks_invisible_3tr_spoof(tmp_path:
v_spoof = verify_pdf_readback(pdf_path, {"code": "D9999"})
assert v_spoof.verified is False
+ # A value merely present in the text, not bound to its label, is no proof.
+ unbound = zlib.compress(b"BT /F1 12 Tf 0 Tr (Confirmation Member MEM-442 Code D2740) Tj ET")
+ unbound_path = tmp_path / "unbound.pdf"
+ unbound_path.write_bytes(
+ b"%PDF-1.4\n1 0 obj\n<< /Filter /FlateDecode >>\nstream\n" + unbound + b"\nendstream\nendobj\n%%EOF"
+ )
+ v_unbound = verify_pdf_readback(unbound_path, {"member": "MEM-442", "code": "D2740"})
+ assert v_unbound.verified is False
+ assert v_unbound.missing_fields == ["member", "code"]
+
def test_runner_multi_window_child_popup_and_sqlite_cross_rail(tmp_path: Path) -> None:
db_path = tmp_path / "quotes.db"
@@ -240,3 +250,24 @@ def test_shadow_sync_and_stdio_mcp_server_roundtrip(tmp_path: Path) -> None:
qual_payload = json.loads(lines[1]["result"]["content"][0]["text"])
assert qual_payload["ok"] is True
assert qual_payload["report"]["qualified"] is True
+
+
+def test_field_verdict_refuses_a_modifier_or_a_status_in_the_field() -> None:
+ from openadapt_kernel._evidence import Verdict
+ from openadapt_kernel.oracles import field_verdict
+
+ previous = [{"key": "Previous Member ID", "val": "MEM-442"}]
+ assert field_verdict("member_id", "MEM-442", "", field_bindings=previous) is not Verdict.MATCH
+ assert field_verdict("member_id", "MEM-442", "Previous Member ID: MEM-442") is not Verdict.MATCH
+ assert field_verdict("code", "D2740", "Code: D2740 Approved") is not Verdict.MATCH
+ split = [{"key": "prev_member_id Previous Member ID", "keys": ["prev_member_id", "Previous Member ID"], "val": "MEM-442"}]
+ assert field_verdict("member_id", "MEM-442", "", field_bindings=split) is not Verdict.MATCH
+ for after in ("member_id_old", "Member ID (previous)", "Member Previous ID"):
+ binding = [{"key": after, "val": "MEM-442"}]
+ assert field_verdict("member_id", "MEM-442", "", field_bindings=binding) is not Verdict.MATCH, after
+ assert field_verdict("member_id", "MEM-442", "Name: Jane Doe Previous Member ID: MEM-442") is not Verdict.MATCH
+ state = [{"key": "State", "val": "CA"}]
+ assert field_verdict("state_code", "CA", "", field_bindings=state) is Verdict.MATCH
+ own = [{"key": "member_id Member ID", "keys": ["member_id", "Member ID"], "val": "MEM-442"}]
+ assert field_verdict("member_id", "MEM-442", "", field_bindings=own) is Verdict.MATCH
+ assert field_verdict("member_id", "MEM-442", "Member ID: MEM-442") is Verdict.MATCH
diff --git a/packages/kernel/tests/test_runtime_wiring_and_raw_demos.py b/packages/kernel/tests/test_runtime_wiring_and_raw_demos.py
index 21f24cdfc8..f4808a0050 100644
--- a/packages/kernel/tests/test_runtime_wiring_and_raw_demos.py
+++ b/packages/kernel/tests/test_runtime_wiring_and_raw_demos.py
@@ -262,7 +262,7 @@ def test_runner_bijective_symbols_ood_halt_and_canvas_servo(tmp_path: Path) -> N
' '
'Absenden 送信 '
""
- '
'
+ '
'
"