From fcea79b5edd0202fa9f86fefc5242330757e3745 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 22:20:28 -0500 Subject: [PATCH 1/3] refactor(form-tx): move the primary entity kinds to a JSON word list The entity kinds that name the person a form is about (applicant, insured, self, ...) are domain words. They now ship as form_tx/presets/words/primary_entity_kinds.json (openadapt.form-word-list/v1), and reconciler._PRIMARY_ENTITY_KINDS loads them. The frozenset is equal to the old one; a test reads the old constant from history and compares. --- .../form_tx/presets/__init__.py | 34 ++++++++- .../presets/words/primary_entity_kinds.json | 13 ++++ .../flow/openadapt_flow/form_tx/reconciler.py | 14 +--- packages/flow/tests/test_form_tx_presets.py | 73 +++++++++++++++++++ 4 files changed, 122 insertions(+), 12 deletions(-) create mode 100644 packages/flow/openadapt_flow/form_tx/presets/words/primary_entity_kinds.json diff --git a/packages/flow/openadapt_flow/form_tx/presets/__init__.py b/packages/flow/openadapt_flow/form_tx/presets/__init__.py index 57c67ebcd6..b9a4aed723 100644 --- a/packages/flow/openadapt_flow/form_tx/presets/__init__.py +++ b/packages/flow/openadapt_flow/form_tx/presets/__init__.py @@ -1,11 +1,15 @@ """Domain presets for ``form_tx`` pack induction, kept as data. -A preset is a canonical domain schema (the fields a kind of form asks for, +A domain preset is a canonical domain schema (the fields a kind of form asks for, with label synonyms) used by ``induce_form_pack`` and the ``--domain`` flag. It is vocabulary for one kind of form, so it lives here as JSON (``openadapt.form-domain-preset/v1``), not in the engine's code. The ``build_*_domain_schema`` functions in ``pack_compiler`` load these files and return the same objects they used to build. + +A word list (``openadapt.form-word-list/v1``, ``presets/words/*.json``) holds +the words one rule looks for, such as the entity kinds that name the person a +form is about. The module constants that used to hold them load these files. """ from __future__ import annotations @@ -18,10 +22,18 @@ if TYPE_CHECKING: from openadapt_flow.form_tx.pack_compiler import CanonicalDomainSchema -__all__ = ["PRESET_SCHEMA", "load_domain_schema", "preset_names"] +__all__ = [ + "PRESET_SCHEMA", + "WORD_LIST_SCHEMA", + "load_domain_schema", + "load_words", + "preset_names", +] PRESET_SCHEMA = "openadapt.form-domain-preset/v1" +WORD_LIST_SCHEMA = "openadapt.form-word-list/v1" _DIR = Path(__file__).resolve().parent +_WORDS = _DIR / "words" def preset_names() -> tuple[str, ...]: @@ -49,3 +61,21 @@ def load_domain_schema(name: str) -> "CanonicalDomainSchema": from openadapt_flow.form_tx.pack_compiler import CanonicalDomainSchema return CanonicalDomainSchema.model_validate(_raw(name)) + + +def load_words(name: str) -> tuple[str, ...]: + """The words of word list ``name`` (``presets/words/.json``), in order.""" + + names = {p.stem for p in _WORDS.glob("*.json")} + if name not in names: + raise ValueError(f"unknown form_tx word list {name!r}") + data = json.loads((_WORDS / f"{name}.json").read_text(encoding="utf-8")) + words = data.get("words") if isinstance(data, dict) else None + if ( + data.get("schema") != WORD_LIST_SCHEMA + or data.get("name") != name + or not isinstance(words, list) + or not all(isinstance(w, str) for w in words) + ): + raise ValueError(f"word list {name!r} is not {WORD_LIST_SCHEMA}") + return tuple(words) diff --git a/packages/flow/openadapt_flow/form_tx/presets/words/primary_entity_kinds.json b/packages/flow/openadapt_flow/form_tx/presets/words/primary_entity_kinds.json new file mode 100644 index 0000000000..6ca7a2c001 --- /dev/null +++ b/packages/flow/openadapt_flow/form_tx/presets/words/primary_entity_kinds.json @@ -0,0 +1,13 @@ +{ + "schema": "openadapt.form-word-list/v1", + "name": "primary_entity_kinds", + "about": "Entity kinds a dossier uses for the person the form is about. An entity table also expects these entities when they carry the table's key fields.", + "words": [ + "primary_applicant", + "primary_insured", + "applicant", + "insured", + "primary", + "self" + ] +} diff --git a/packages/flow/openadapt_flow/form_tx/reconciler.py b/packages/flow/openadapt_flow/form_tx/reconciler.py index dd8b83a539..29d069e90c 100644 --- a/packages/flow/openadapt_flow/form_tx/reconciler.py +++ b/packages/flow/openadapt_flow/form_tx/reconciler.py @@ -26,6 +26,7 @@ values_equivalent, ) from openadapt_flow.form_tx.judge import SummaryJudge +from openadapt_flow.form_tx.presets import load_words from openadapt_flow.form_tx.receipt import issue_form_tx_receipt from openadapt_flow.form_tx.surface import ( AmbiguousAnchorError, @@ -68,16 +69,9 @@ "ReconcilerSession", ] -_PRIMARY_ENTITY_KINDS = frozenset( - { - "primary_applicant", - "primary_insured", - "applicant", - "insured", - "primary", - "self", - } -) +#: Entity kinds that name the person the form is about (data: +#: ``presets/words/primary_entity_kinds.json``). +_PRIMARY_ENTITY_KINDS = frozenset(load_words("primary_entity_kinds")) _DEFAULT_PLACEHOLDERS: tuple[str, ...] = ( "", "-- Select --", diff --git a/packages/flow/tests/test_form_tx_presets.py b/packages/flow/tests/test_form_tx_presets.py index 78217b9775..4a1faaf0cd 100644 --- a/packages/flow/tests/test_form_tx_presets.py +++ b/packages/flow/tests/test_form_tx_presets.py @@ -79,3 +79,76 @@ def test_an_unknown_preset_is_refused() -> None: load_domain_schema("no_such_preset") with pytest.raises(ValueError): load_domain_schema("../pack_compiler") + + +# -- word lists ------------------------------------------------------------------ + + +def _old_constant(sha: str, source: str, name: str) -> object: + """A module constant's value at ``sha``: a literal, or frozenset(literal).""" + + import ast + + got = subprocess.run( + ["git", "-C", str(ROOT), "show", f"{sha}:{source}"], + capture_output=True, + text=True, + ) + if got.returncode != 0: + pytest.skip("no git history for the commit before the move") + for node in ast.parse(got.stdout).body: + targets = ( + [node.target] + if isinstance(node, ast.AnnAssign) + else getattr(node, "targets", []) + ) + if any(getattr(t, "id", None) == name for t in targets): + value = node.value + if ( + isinstance(value, ast.Call) + and getattr(value.func, "id", "") == "frozenset" + ): + return frozenset(ast.literal_eval(value.args[0])) + return ast.literal_eval(value) # type: ignore[arg-type] + raise AssertionError(f"{name} not found in {source} at {sha}") + + +def _primary_entity_kinds() -> object: + from openadapt_flow.form_tx import reconciler + + return reconciler._PRIMARY_ENTITY_KINDS + + +#: word list: (current value, the commit before the move, file, constant) +MOVED_WORDS = { + "primary_entity_kinds": ( + _primary_entity_kinds, + "2f506d6c463aef8098fc8fcc2fd5bc46e55c1829", + "packages/flow/openadapt_flow/form_tx/reconciler.py", + "_PRIMARY_ENTITY_KINDS", + ), +} + + +@pytest.mark.parametrize("words", sorted(MOVED_WORDS)) +def test_the_constant_equals_the_old_one(words: str) -> None: + current, sha, source, name = MOVED_WORDS[words] + old = _old_constant(sha, source, name) + now = current() + assert type(now) is type(old) + assert now == old + + +@pytest.mark.parametrize("words", sorted(MOVED_WORDS)) +def test_each_word_list_ships_as_json(words: str) -> None: + from openadapt_flow.form_tx.presets import load_words + + assert load_words(words) + assert words not in preset_names() + + +def test_an_unknown_word_list_is_refused() -> None: + from openadapt_flow.form_tx.presets import load_words + + with pytest.raises(ValueError): + load_words("no_such_list") From 7b5268163a9a3993485a6ef2d978cac2fa6ebcc0 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 22:25:16 -0500 Subject: [PATCH 2/3] fix(form-tx): refuse a word list that is not an object; cache load_words From review: a JSON list or string raised AttributeError instead of ValueError. load_words is now cached like the preset loader, and a test feeds it six malformed files. --- .../form_tx/presets/__init__.py | 4 ++- packages/flow/tests/test_form_tx_presets.py | 26 +++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/packages/flow/openadapt_flow/form_tx/presets/__init__.py b/packages/flow/openadapt_flow/form_tx/presets/__init__.py index b9a4aed723..f327c04b90 100644 --- a/packages/flow/openadapt_flow/form_tx/presets/__init__.py +++ b/packages/flow/openadapt_flow/form_tx/presets/__init__.py @@ -63,6 +63,7 @@ def load_domain_schema(name: str) -> "CanonicalDomainSchema": return CanonicalDomainSchema.model_validate(_raw(name)) +@lru_cache(maxsize=None) def load_words(name: str) -> tuple[str, ...]: """The words of word list ``name`` (``presets/words/.json``), in order.""" @@ -72,7 +73,8 @@ def load_words(name: str) -> tuple[str, ...]: data = json.loads((_WORDS / f"{name}.json").read_text(encoding="utf-8")) words = data.get("words") if isinstance(data, dict) else None if ( - data.get("schema") != WORD_LIST_SCHEMA + not isinstance(data, dict) + or data.get("schema") != WORD_LIST_SCHEMA or data.get("name") != name or not isinstance(words, list) or not all(isinstance(w, str) for w in words) diff --git a/packages/flow/tests/test_form_tx_presets.py b/packages/flow/tests/test_form_tx_presets.py index 4a1faaf0cd..e0a8af7972 100644 --- a/packages/flow/tests/test_form_tx_presets.py +++ b/packages/flow/tests/test_form_tx_presets.py @@ -152,3 +152,29 @@ def test_an_unknown_word_list_is_refused() -> None: with pytest.raises(ValueError): load_words("no_such_list") + + +@pytest.mark.parametrize( + "content", + [ + "[]", + '"words"', + '{"schema": "other/v1", "name": "bad", "words": []}', + '{"schema": "openadapt.form-word-list/v1", "name": "other", "words": []}', + '{"schema": "openadapt.form-word-list/v1", "name": "bad", "words": [1]}', + '{"schema": "openadapt.form-word-list/v1", "name": "bad", "words": "a"}', + ], +) +def test_a_malformed_word_list_is_refused( + content: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from openadapt_flow.form_tx import presets + + (tmp_path / "bad.json").write_text(content, encoding="utf-8") + monkeypatch.setattr(presets, "_WORDS", tmp_path) + presets.load_words.cache_clear() + try: + with pytest.raises(ValueError): + presets.load_words("bad") + finally: + presets.load_words.cache_clear() From 97fd2028793fec094f1b943bac05febaf5ae24d0 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 22:43:20 -0500 Subject: [PATCH 3/3] feat(form-tx): a pack can override the primary entity kinds FormPack.primary_entity_kinds (optional) replaces the engine's default list for that pack; None keeps the default from presets/words. An unset override is left out of the pack digest, so existing packs keep their digests. A test runs one dossier against a pack with the default, the same list and an empty list, and checks the empty list makes the applicant's row a conflict. --- .../flow/openadapt_flow/form_tx/reconciler.py | 10 ++-- packages/flow/openadapt_flow/form_tx/types.py | 16 ++++++- .../test_form_tx_reconciler_and_receipts.py | 48 +++++++++++++++++++ 3 files changed, 69 insertions(+), 5 deletions(-) diff --git a/packages/flow/openadapt_flow/form_tx/reconciler.py b/packages/flow/openadapt_flow/form_tx/reconciler.py index 29d069e90c..4965dbcf2c 100644 --- a/packages/flow/openadapt_flow/form_tx/reconciler.py +++ b/packages/flow/openadapt_flow/form_tx/reconciler.py @@ -526,15 +526,17 @@ def _check_entity_table_conflicts( pack = session.pack dossier = session.dossier + primary_kinds = ( + frozenset(pack.primary_entity_kinds) + if pack.primary_entity_kinds is not None + else _PRIMARY_ENTITY_KINDS + ) for spec in pack.entity_tables: expected_entities: list[DossierEntity] = list( dossier.entities_of_kind(spec.entity_kind) ) for ent in dossier.entities: - if ( - ent.entity_kind in _PRIMARY_ENTITY_KINDS - and ent not in expected_entities - ): + if ent.entity_kind in primary_kinds and ent not in expected_entities: if all(kf in ent.fields for kf in spec.key_fields): expected_entities.append(ent) diff --git a/packages/flow/openadapt_flow/form_tx/types.py b/packages/flow/openadapt_flow/form_tx/types.py index 02744081f3..75919c3e7e 100644 --- a/packages/flow/openadapt_flow/form_tx/types.py +++ b/packages/flow/openadapt_flow/form_tx/types.py @@ -394,9 +394,23 @@ class FormPack(BaseModel): screens: tuple[WizardScreenSpec, ...] = () summary_check: Optional[SummaryCheckSpec] = None max_commit_mutations: int = Field(default=1, ge=0, le=10) + # Overrides of the engine's default word lists (``form_tx/presets/words``). + # None keeps the default. An entity table also expects a dossier entity of + # one of these kinds when it carries the table's key fields. + primary_entity_kinds: Optional[tuple[str, ...]] = None def digest(self) -> str: - return canonical_sha256(self) + # An override left unset is not hashed, so a pack written before the + # field existed keeps its digest. + data = self.model_dump(mode="json") + for name in _UNHASHED_WHEN_UNSET: + if data.get(name) is None: + data.pop(name, None) + return canonical_sha256(data) + + +#: FormPack fields left out of the digest while they are None. +_UNHASHED_WHEN_UNSET = ("primary_entity_kinds",) class ObservedOption(BaseModel): diff --git a/packages/flow/tests/test_form_tx_reconciler_and_receipts.py b/packages/flow/tests/test_form_tx_reconciler_and_receipts.py index e7dd28296b..8d888eb728 100644 --- a/packages/flow/tests/test_form_tx_reconciler_and_receipts.py +++ b/packages/flow/tests/test_form_tx_reconciler_and_receipts.py @@ -1342,6 +1342,54 @@ def test_ppr_conditional_cascade_human_resume_popup_summary_and_receipt() -> Non assert pii_token not in serialized_receipt +def test_a_pack_can_override_the_primary_entity_kinds() -> None: + """The engine's default list (presets/words/primary_entity_kinds.json) + lets the dossier's primary applicant ground its own table row. A pack + that names no primary kinds makes that row an unlisted entity.""" + grounded_row = {"first_name": "Elena", "last_name": "Vance"} + dossier = _build_dossier(has_pool="No") + + default_pack = _build_pack() + assert default_pack.primary_entity_kinds is None + surface = FakeStatefulFormSurface(entity_rows=[grounded_row]) + reconciler = FormReconciler(surface) + done = reconciler.run_until_halt_or_done( + reconciler.create_session(default_pack, dossier) + ) + assert done.outcome == FormTxOutcome.VERIFIED_DONE + + same = default_pack.model_copy( + update={"primary_entity_kinds": ("primary_applicant",)} + ) + surface = FakeStatefulFormSurface(entity_rows=[grounded_row]) + reconciler = FormReconciler(surface) + assert ( + reconciler.run_until_halt_or_done( + reconciler.create_session(same, dossier) + ).outcome + == FormTxOutcome.VERIFIED_DONE + ) + + none = default_pack.model_copy(update={"primary_entity_kinds": ()}) + surface = FakeStatefulFormSurface(entity_rows=[grounded_row]) + reconciler = FormReconciler(surface) + halted = reconciler.run_until_halt_or_done(reconciler.create_session(none, dossier)) + assert halted.outcome == FormTxOutcome.HALTED_NEEDS_HUMAN + assert halted.halts[0].kind == FormHaltKind.PREFILL_ENTITY_CONFLICT + + +def test_an_unset_override_keeps_the_pack_digest() -> None: + from openadapt_flow.form_tx.types import canonical_sha256 + + pack = _build_pack() + old_style = pack.model_dump(mode="json") + old_style.pop("primary_entity_kinds") + assert pack.digest() == canonical_sha256(old_style) + assert ( + pack.model_copy(update={"primary_entity_kinds": ()}).digest() != pack.digest() + ) + + def test_entity_table_prefill_conflict_dismiss_accept_and_broken_dismiss() -> None: grounded_row = {"first_name": "Elena", "last_name": "Vance"} unlisted_spouse = {"first_name": "Marcus", "last_name": "Vance"}