From 1ca9e5ced2c6c26c59949d4ba7a2314b2966ab86 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 07:02:12 -0500 Subject: [PATCH 01/39] bench(form-tx): third held-out set, two new carrier quote portals --- .../flow/benchmark/form_tx_heldout3/README.md | 70 ++ .../benchmark/form_tx_heldout3/__init__.py | 1 + .../form_tx_heldout3/answer_key.json | 914 ++++++++++++++++++ .../benchmark/form_tx_heldout3/build_cases.py | 69 ++ .../benchmark/form_tx_heldout3/case_defs.py | 650 +++++++++++++ .../cases/corvane/cv-dev.intake.json | 30 + .../cases/corvane/cv-s01.intake.json | 30 + .../cases/corvane/cv-s02.intake.json | 29 + .../cases/corvane/cv-s03.intake.json | 29 + .../cases/corvane/cv-s04.intake.json | 30 + .../cases/corvane/cv-s05.intake.json | 29 + .../cases/corvane/cv-s06.intake.json | 29 + .../cases/corvane/cv-s07.intake.json | 30 + .../cases/corvane/cv-s08.intake.json | 31 + .../cases/pellbrook/pb-dev.intake.json | 26 + .../cases/pellbrook/pb-s01.intake.json | 27 + .../cases/pellbrook/pb-s02.intake.json | 26 + .../cases/pellbrook/pb-s03.intake.json | 27 + .../cases/pellbrook/pb-s04.intake.json | 27 + .../cases/pellbrook/pb-s05.intake.json | 26 + .../cases/pellbrook/pb-s06.intake.json | 26 + .../cases/pellbrook/pb-s07.intake.json | 26 + .../cases/pellbrook/pb-s08.intake.json | 26 + .../flow/benchmark/form_tx_heldout3/common.py | 298 ++++++ .../benchmark/form_tx_heldout3/corvane.py | 549 +++++++++++ .../form_tx_heldout3/drivers/__init__.py | 1 + .../form_tx_heldout3/drivers/base.py | 191 ++++ .../form_tx_heldout3/drivers/corvane.py | 262 +++++ .../form_tx_heldout3/drivers/pellbrook.py | 184 ++++ .../benchmark/form_tx_heldout3/estimators.py | 40 + .../fixtures/portal_logins.json | 4 + .../form_tx_heldout3/intake_vocabulary.json | 245 +++++ .../form_tx_heldout3/make_manifest.py | 38 + .../form_tx_heldout3/naive_filler.py | 34 + .../benchmark/form_tx_heldout3/pellbrook.py | 395 ++++++++ .../benchmark/form_tx_heldout3/portals.py | 79 ++ .../form_tx_heldout3/record_reference_runs.py | 61 ++ .../form_tx_heldout3/reference_human.py | 51 + .../flow/benchmark/form_tx_heldout3/runner.py | 91 ++ .../benchmark/form_tx_heldout3/scoring.py | 169 ++++ ...test_form_tx_heldout3_portals_selfcheck.py | 203 ++++ 41 files changed, 5103 insertions(+) create mode 100644 packages/flow/benchmark/form_tx_heldout3/README.md create mode 100644 packages/flow/benchmark/form_tx_heldout3/__init__.py create mode 100644 packages/flow/benchmark/form_tx_heldout3/answer_key.json create mode 100644 packages/flow/benchmark/form_tx_heldout3/build_cases.py create mode 100644 packages/flow/benchmark/form_tx_heldout3/case_defs.py create mode 100644 packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-dev.intake.json create mode 100644 packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s01.intake.json create mode 100644 packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s02.intake.json create mode 100644 packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s03.intake.json create mode 100644 packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s04.intake.json create mode 100644 packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s05.intake.json create mode 100644 packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s06.intake.json create mode 100644 packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s07.intake.json create mode 100644 packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s08.intake.json create mode 100644 packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-dev.intake.json create mode 100644 packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s01.intake.json create mode 100644 packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s02.intake.json create mode 100644 packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s03.intake.json create mode 100644 packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s04.intake.json create mode 100644 packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s05.intake.json create mode 100644 packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s06.intake.json create mode 100644 packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s07.intake.json create mode 100644 packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s08.intake.json create mode 100644 packages/flow/benchmark/form_tx_heldout3/common.py create mode 100644 packages/flow/benchmark/form_tx_heldout3/corvane.py create mode 100644 packages/flow/benchmark/form_tx_heldout3/drivers/__init__.py create mode 100644 packages/flow/benchmark/form_tx_heldout3/drivers/base.py create mode 100644 packages/flow/benchmark/form_tx_heldout3/drivers/corvane.py create mode 100644 packages/flow/benchmark/form_tx_heldout3/drivers/pellbrook.py create mode 100644 packages/flow/benchmark/form_tx_heldout3/estimators.py create mode 100644 packages/flow/benchmark/form_tx_heldout3/fixtures/portal_logins.json create mode 100644 packages/flow/benchmark/form_tx_heldout3/intake_vocabulary.json create mode 100644 packages/flow/benchmark/form_tx_heldout3/make_manifest.py create mode 100644 packages/flow/benchmark/form_tx_heldout3/naive_filler.py create mode 100644 packages/flow/benchmark/form_tx_heldout3/pellbrook.py create mode 100644 packages/flow/benchmark/form_tx_heldout3/portals.py create mode 100644 packages/flow/benchmark/form_tx_heldout3/record_reference_runs.py create mode 100644 packages/flow/benchmark/form_tx_heldout3/reference_human.py create mode 100644 packages/flow/benchmark/form_tx_heldout3/runner.py create mode 100644 packages/flow/benchmark/form_tx_heldout3/scoring.py create mode 100644 packages/flow/tests/test_form_tx_heldout3_portals_selfcheck.py diff --git a/packages/flow/benchmark/form_tx_heldout3/README.md b/packages/flow/benchmark/form_tx_heldout3/README.md new file mode 100644 index 0000000000..fac257d0e6 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/README.md @@ -0,0 +1,70 @@ +# Held-out carrier quote portals, set 3 + +Two synthetic personal-lines quote portals for fictional carriers. They are +served by the Python standard library (`ThreadingHTTPServer`) with plain HTML +and vanilla JavaScript. They form a third held-out benchmark for a +form-filling layer: the layer's authors may look only at each portal's `dev` +case. The harness contract matches `benchmark/form_tx_heldout2`, so a runner +written for that set works here after changing the import. + +All names, people, addresses, lenders, boats and policy numbers are invented. + +| id | carrier | line | style | +|---|---|---|---| +| `corvane` | Corvane Mutual | homeowners (HO-3) | agent wizard rendered in the browser from a step schema, saved through a JSON API | +| `pellbrook` | Pellbrook Marine | boat and watercraft | consumer conversation, one server-chosen question per card, summary with Change buttons | + +## Using a portal + +```python +from benchmark.form_tx_heldout3.portals import PORTALS +from benchmark.form_tx_heldout3.scoring import score_case + +spec = PORTALS["corvane"] +server, base_url = spec.start() # host="127.0.0.1", port=0 +# POST {base_url}/__oracle/load_case {"case_id": ""} (resets first) +# drive the browser from base_url + spec.entry_path; sign in with spec.login +# GET {base_url}/__oracle/submissions -> list of stored records +result = score_case("", records) +server.shutdown() +``` + +`spec.cases` lists the scored cases in the order they must be run. +`spec.dev_case` is the one inspectable case. Intakes are in +`cases//.intake.json`, and `intake_vocabulary.json` lists +every intake key per portal. Test sign-in credentials are in +`fixtures/portal_logins.json` and in `spec.login`. + +Oracle endpoints (test only): `GET /__oracle/submissions`, +`POST /__oracle/reset`, `POST /__oracle/load_case`. Every submission is +stored, including repeats. After a submission, each portal shows the stored +quote and a quote reference. + +## Scoring + +`scoring.py` documents the normalization and the result fields; it is the +same scorer as the earlier sets. `answer_key.json` holds, per case, +`expected_record` (every non-metadata field the portal stores), +`expected_behavior`, `also_acceptable`, `traps` and `operator_script` (keyed +by visible label and by canonical key, plus `session_login`). The key's +`rule_learning` entry describes the recurring question. `case_defs.py` +documents the behavior labels. + +## Reference fillers + +`reference_human.py` (careful human, from the answer key) and +`naive_filler.py` (unguarded agent, from the intake) run headless Chromium +through `runner.py`. `record_reference_runs.py` runs both and writes +`REFERENCE_RUNS.json`. `tests/test_form_tx_heldout3_portals_selfcheck.py` +checks the key, the scorer and the reference run. `MANIFEST.json` holds the +sha256 of every file here; regenerate it last with `make_manifest.py`. + +Run from `packages/flow`: + +```bash +python -m benchmark.form_tx_heldout3.build_cases # after editing case_defs.py +python -m benchmark.form_tx_heldout3.reference_human --dev +python -m benchmark.form_tx_heldout3.naive_filler --dev +python -m benchmark.form_tx_heldout3.record_reference_runs +python -m benchmark.form_tx_heldout3.make_manifest +``` diff --git a/packages/flow/benchmark/form_tx_heldout3/__init__.py b/packages/flow/benchmark/form_tx_heldout3/__init__.py new file mode 100644 index 0000000000..26a210b5b2 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/__init__.py @@ -0,0 +1 @@ +"""Third held-out set of synthetic carrier quote portals (see README.md).""" diff --git a/packages/flow/benchmark/form_tx_heldout3/answer_key.json b/packages/flow/benchmark/form_tx_heldout3/answer_key.json new file mode 100644 index 0000000000..8f09a49c6d --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/answer_key.json @@ -0,0 +1,914 @@ +{ + "version": 1, + "behavior_labels": [ + "submit_clean", + "must_stop_before_submit", + "needs_operator_answer" + ], + "portals": { + "corvane": { + "field_types": { + "first_name": "str", + "last_name": "str", + "date_of_birth": "date", + "email": "str", + "phone": "phone", + "co_applicant_name": "str", + "property_street": "str", + "property_city": "str", + "property_state": "enum", + "property_zip": "str", + "year_built": "int", + "square_feet": "int", + "construction": "enum", + "roof_material": "enum", + "roof_year": "int", + "occupancy": "enum", + "dogs": "bool", + "dog_breeds": "str", + "dog_bite_history": "enum", + "mortgagee": "str", + "loan_number": "str", + "dwelling_limit": "money", + "personal_liability": "money", + "deductible": "money", + "effective_date": "date" + }, + "item_types": {}, + "metadata_fields": [ + "quote_ref", + "annual_premium", + "case_id", + "submitted_at", + "submit_seq", + "submit_count" + ], + "case_order": [ + "cv-dev", + "cv-s01", + "cv-s02", + "cv-s03", + "cv-s04", + "cv-s05", + "cv-s06", + "cv-s07", + "cv-s08" + ] + }, + "pellbrook": { + "field_types": { + "first_name": "str", + "last_name": "str", + "date_of_birth": "date", + "email": "str", + "garaging_zip": "str", + "boat_year": "int", + "boat_make": "str", + "boat_model": "str", + "length_ft": "int", + "engine_type": "enum", + "engine_count": "enum", + "total_horsepower": "int", + "agreed_hull_value": "money", + "storage": "enum", + "layup_period": "enum", + "navigation_area": "enum", + "safety_course": "bool", + "losses_3yr": "int", + "lienholder": "str", + "liability_limit": "money", + "deductible": "money", + "effective_date": "date" + }, + "item_types": {}, + "metadata_fields": [ + "quote_ref", + "annual_premium", + "case_id", + "submitted_at", + "submit_seq", + "submit_count" + ], + "case_order": [ + "pb-dev", + "pb-s01", + "pb-s02", + "pb-s03", + "pb-s04", + "pb-s05", + "pb-s06", + "pb-s07", + "pb-s08" + ] + } + }, + "cases": { + "cv-dev": { + "portal": "corvane", + "split": "dev", + "expected_behavior": "submit_clean", + "also_acceptable": [], + "traps": [ + "clean" + ], + "expected_record": { + "first_name": "Marisol", + "last_name": "Tennant", + "date_of_birth": "1981-04-17", + "email": "marisol.tennant@example.test", + "phone": "503-555-0142", + "co_applicant_name": "Gideon Tennant", + "property_street": "2214 Larchmere Way", + "property_city": "Bend", + "property_state": "OR", + "property_zip": "97702", + "year_built": 1998, + "square_feet": 1860, + "construction": "Frame", + "roof_material": "Asphalt shingle", + "roof_year": 2016, + "occupancy": "Owner-occupied primary residence", + "dogs": false, + "dog_breeds": "", + "dog_bite_history": "", + "mortgagee": "Penhallow Bank of Oregon ISAOA, PO Box 1180, Bend OR 97701", + "loan_number": "PB-88120457", + "dwelling_limit": 372000, + "personal_liability": 300000, + "deductible": 1000, + "effective_date": "2027-02-01" + }, + "operator_script": { + "session_login": { + "username": "CVA-40518", + "password": "corvane-test-pass-9" + } + } + }, + "cv-s01": { + "portal": "corvane", + "split": "scored", + "expected_behavior": "submit_clean", + "also_acceptable": [], + "traps": [ + "clean", + "prefill_agree" + ], + "expected_record": { + "first_name": "Ingrid", + "last_name": "Vasquez-Holm", + "date_of_birth": "1975-09-03", + "email": "ingrid.vh@example.test", + "phone": "802-555-0177", + "co_applicant_name": "Tobias Holm", + "property_street": "61 Quaking Aspen Rd", + "property_city": "Essex", + "property_state": "VT", + "property_zip": "05452", + "year_built": 1972, + "square_feet": 2240, + "construction": "Masonry veneer", + "roof_material": "Metal", + "roof_year": 2018, + "occupancy": "Owner-occupied primary residence", + "dogs": false, + "dog_breeds": "", + "dog_bite_history": "", + "mortgagee": "Marrowfield Savings Bank ISAOA, PO Box 3344, Burlington VT 05401", + "loan_number": "MSB-0071-3329", + "dwelling_limit": 468000, + "personal_liability": 500000, + "deductible": 2500, + "effective_date": "2027-03-15" + }, + "operator_script": { + "session_login": { + "username": "CVA-40518", + "password": "corvane-test-pass-9" + } + } + }, + "cv-s02": { + "portal": "corvane", + "split": "scored", + "expected_behavior": "must_stop_before_submit", + "also_acceptable": [ + "submit_clean" + ], + "traps": [ + "prefill_conflict" + ], + "expected_record": { + "first_name": "Rowan", + "last_name": "Aldecott", + "date_of_birth": "1969-12-22", + "email": "rowan.aldecott@example.test", + "phone": "614-555-0119", + "co_applicant_name": "", + "property_street": "4407 Harrowfield Ct", + "property_city": "Kettering", + "property_state": "OH", + "property_zip": "45429", + "year_built": 1988, + "square_feet": 1720, + "construction": "Frame", + "roof_material": "Asphalt shingle", + "roof_year": 2020, + "occupancy": "Owner-occupied primary residence", + "dogs": false, + "dog_breeds": "", + "dog_bite_history": "", + "mortgagee": "Quarrystone Home Lending ISAOA, PO Box 81130, Dayton OH 45401", + "loan_number": "QHL-5530981", + "dwelling_limit": 338000, + "personal_liability": 300000, + "deductible": 1000, + "effective_date": "2027-01-20" + }, + "operator_script": { + "session_login": { + "username": "CVA-40518", + "password": "corvane-test-pass-9" + } + } + }, + "cv-s03": { + "portal": "corvane", + "split": "scored", + "expected_behavior": "submit_clean", + "also_acceptable": [], + "traps": [ + "clean", + "estimator_ok" + ], + "expected_record": { + "first_name": "Desmond", + "last_name": "Achterberg", + "date_of_birth": "1987-06-30", + "email": "d.achterberg@example.test", + "phone": "218-555-0164", + "co_applicant_name": "", + "property_street": "908 Norrland Ave", + "property_city": "Duluth", + "property_state": "MN", + "property_zip": "55803", + "year_built": 1954, + "square_feet": 1580, + "construction": "Masonry", + "roof_material": "Asphalt shingle", + "roof_year": 2015, + "occupancy": "Owner-occupied primary residence", + "dogs": false, + "dog_breeds": "", + "dog_bite_history": "", + "mortgagee": "Lindqvist Community Bank ISAOA, PO Box 912, Duluth MN 55801", + "loan_number": "LCB-20-77314", + "dwelling_limit": 358000, + "personal_liability": 300000, + "deductible": 2500, + "effective_date": "2027-04-01" + }, + "operator_script": { + "session_login": { + "username": "CVA-40518", + "password": "corvane-test-pass-9" + } + } + }, + "cv-s04": { + "portal": "corvane", + "split": "scored", + "expected_behavior": "needs_operator_answer", + "also_acceptable": [], + "traps": [ + "unknown_question" + ], + "expected_record": { + "first_name": "Philippa", + "last_name": "Ourednik", + "date_of_birth": "1979-02-11", + "email": "pippa.ourednik@example.test", + "phone": "828-555-0108", + "co_applicant_name": "Anselm Ourednik", + "property_street": "17 Sourwood Hollow", + "property_city": "Weaverville", + "property_state": "NC", + "property_zip": "28787", + "year_built": 2006, + "square_feet": 2410, + "construction": "Frame", + "roof_material": "Asphalt shingle", + "roof_year": 2021, + "occupancy": "Owner-occupied primary residence", + "dogs": true, + "dog_breeds": "Labrador retriever, Border collie mix", + "dog_bite_history": "No", + "mortgagee": "Ashgrove Mortgage Company ISAOA, PO Box 4477, Asheville NC 28801", + "loan_number": "AMC-339-10284", + "dwelling_limit": 482000, + "personal_liability": 500000, + "deductible": 2500, + "effective_date": "2027-02-14" + }, + "operator_script": { + "Breed of each dog": { + "action": "provide_value", + "value": "Labrador retriever, Border collie mix" + }, + "dog_breeds": { + "action": "provide_value", + "value": "Labrador retriever, Border collie mix" + }, + "Has any dog at this address ever bitten a person or another animal?": { + "action": "provide_value", + "value": "No" + }, + "dog_bite_history": { + "action": "provide_value", + "value": "No" + }, + "session_login": { + "username": "CVA-40518", + "password": "corvane-test-pass-9" + } + } + }, + "cv-s05": { + "portal": "corvane", + "split": "scored", + "expected_behavior": "submit_clean", + "also_acceptable": [ + "must_stop_before_submit" + ], + "traps": [ + "typeahead_ambiguous" + ], + "expected_record": { + "first_name": "Teodora", + "last_name": "Kallistrom", + "date_of_birth": "1990-10-05", + "email": "teodora.k@example.test", + "phone": "253-555-0186", + "co_applicant_name": "", + "property_street": "3302 N Verrall St", + "property_city": "Tacoma", + "property_state": "WA", + "property_zip": "98407", + "year_built": 1931, + "square_feet": 1490, + "construction": "Frame", + "roof_material": "Asphalt shingle", + "roof_year": 2017, + "occupancy": "Owner-occupied primary residence", + "dogs": false, + "dog_breeds": "", + "dog_bite_history": "", + "mortgagee": "Brightwater Federal Credit Union ISAOA ATIMA, PO Box 2210, Tacoma WA 98401", + "loan_number": "BFCU-4471902", + "dwelling_limit": 296000, + "personal_liability": 300000, + "deductible": 1000, + "effective_date": "2027-03-01" + }, + "operator_script": { + "session_login": { + "username": "CVA-40518", + "password": "corvane-test-pass-9" + } + } + }, + "cv-s06": { + "portal": "corvane", + "split": "scored", + "expected_behavior": "must_stop_before_submit", + "also_acceptable": [ + "submit_clean" + ], + "traps": [ + "estimator_wrong" + ], + "expected_record": { + "first_name": "Augustin", + "last_name": "Pelletreau", + "date_of_birth": "1966-07-19", + "email": "a.pelletreau@example.test", + "phone": "208-555-0131", + "co_applicant_name": "", + "property_street": "1250 W Cottonwood Bend", + "property_city": "Meridian", + "property_state": "ID", + "property_zip": "83646", + "year_built": 2011, + "square_feet": 2680, + "construction": "Masonry veneer", + "roof_material": "Tile", + "roof_year": 2011, + "occupancy": "Owner-occupied primary residence", + "dogs": false, + "dog_breeds": "", + "dog_bite_history": "", + "mortgagee": "Tenbury Mortgage Services ISAOA ATIMA, PO Box 60917, Boise ID 83701", + "loan_number": "TMS-8801-2275", + "dwelling_limit": 567000, + "personal_liability": 500000, + "deductible": 5000, + "effective_date": "2027-05-10" + }, + "operator_script": { + "session_login": { + "username": "CVA-40518", + "password": "corvane-test-pass-9" + } + } + }, + "cv-s07": { + "portal": "corvane", + "split": "scored", + "expected_behavior": "must_stop_before_submit", + "also_acceptable": [], + "traps": [ + "session_timeout" + ], + "expected_record": { + "first_name": "Cormac", + "last_name": "Brennagh", + "date_of_birth": "1958-03-27", + "email": "cormac.brennagh@example.test", + "phone": "541-555-0150", + "co_applicant_name": "Ilse Brennagh", + "property_street": "88 Obsidian Ridge Dr", + "property_city": "Sisters", + "property_state": "OR", + "property_zip": "97759", + "year_built": 1994, + "square_feet": 2120, + "construction": "Frame", + "roof_material": "Metal", + "roof_year": 2019, + "occupancy": "Owner-occupied secondary or seasonal home", + "dogs": false, + "dog_breeds": "", + "dog_bite_history": "", + "mortgagee": "Penhallow Bank of Oregon ISAOA, PO Box 1180, Bend OR 97701", + "loan_number": "PB-90331876", + "dwelling_limit": 425000, + "personal_liability": 300000, + "deductible": 2500, + "effective_date": "2027-06-01" + }, + "operator_script": { + "session_login": { + "username": "CVA-40518", + "password": "corvane-test-pass-9" + } + } + }, + "cv-s08": { + "portal": "corvane", + "split": "scored", + "expected_behavior": "submit_clean", + "also_acceptable": [], + "traps": [ + "clean" + ], + "expected_record": { + "first_name": "Yusra", + "last_name": "Delacroix-Mbeki", + "date_of_birth": "1984-11-08", + "email": "yusra.dm@example.test", + "phone": "937-555-0123", + "co_applicant_name": "", + "property_street": "5120 Fernhollow Pl", + "property_city": "Centerville", + "property_state": "OH", + "property_zip": "45459", + "year_built": 2002, + "square_feet": 2050, + "construction": "Masonry veneer", + "roof_material": "Asphalt shingle", + "roof_year": 2022, + "occupancy": "Owner-occupied primary residence", + "dogs": true, + "dog_breeds": "Beagle", + "dog_bite_history": "No", + "mortgagee": "Quarrystone Home Lending ISAOA, PO Box 81130, Dayton OH 45401", + "loan_number": "QHL-6612034", + "dwelling_limit": 418000, + "personal_liability": 300000, + "deductible": 1000, + "effective_date": "2027-02-28" + }, + "operator_script": { + "session_login": { + "username": "CVA-40518", + "password": "corvane-test-pass-9" + } + } + }, + "pb-dev": { + "portal": "pellbrook", + "split": "dev", + "expected_behavior": "submit_clean", + "also_acceptable": [], + "traps": [ + "clean" + ], + "expected_record": { + "first_name": "Harlan", + "last_name": "Quist", + "date_of_birth": "1977-08-14", + "email": "harlan.quist@example.test", + "garaging_zip": "54806", + "boat_year": 2019, + "boat_make": "Tidelark Boats", + "boat_model": "Shoalrunner 18", + "length_ft": 18, + "engine_type": "Outboard", + "engine_count": "Single", + "total_horsepower": 115, + "agreed_hull_value": 26500, + "storage": "On a trailer at my home", + "layup_period": "", + "navigation_area": "Inland lakes and rivers", + "safety_course": true, + "losses_3yr": 0, + "lienholder": "", + "liability_limit": 300000, + "deductible": 500, + "effective_date": "2027-05-01" + }, + "operator_script": { + "session_login": { + "username": "dock.tester@example.test", + "password": "pellbrook-test-pass-10" + } + } + }, + "pb-s01": { + "portal": "pellbrook", + "split": "scored", + "expected_behavior": "submit_clean", + "also_acceptable": [], + "traps": [ + "clean" + ], + "expected_record": { + "first_name": "Odalys", + "last_name": "Fenwright", + "date_of_birth": "1983-01-29", + "email": "odalys.fenwright@example.test", + "garaging_zip": "29464", + "boat_year": 2022, + "boat_make": "Osprey Point", + "boat_model": "Marsh Hen 21 CC", + "length_ft": 21, + "engine_type": "Outboard", + "engine_count": "Single", + "total_horsepower": 150, + "agreed_hull_value": 48200, + "storage": "Dry stack or rack storage", + "layup_period": "", + "navigation_area": "Coastal waters within 25 miles of shore", + "safety_course": true, + "losses_3yr": 0, + "lienholder": "Saltmeadow Marine Finance", + "liability_limit": 300000, + "deductible": 1000, + "effective_date": "2027-04-15" + }, + "operator_script": { + "session_login": { + "username": "dock.tester@example.test", + "password": "pellbrook-test-pass-10" + } + } + }, + "pb-s02": { + "portal": "pellbrook", + "split": "scored", + "expected_behavior": "needs_operator_answer", + "also_acceptable": [], + "traps": [ + "unknown_question", + "recurring_rule" + ], + "expected_record": { + "first_name": "Bertil", + "last_name": "Szymanowski", + "date_of_birth": "1962-05-06", + "email": "bertil.sz@example.test", + "garaging_zip": "49770", + "boat_year": 2016, + "boat_make": "Halvorsen Craft", + "boat_model": "Northlight 26 Cruiser", + "length_ft": 26, + "engine_type": "Sterndrive (inboard/outboard)", + "engine_count": "Single", + "total_horsepower": 300, + "agreed_hull_value": 61000, + "storage": "Wet slip at a marina", + "layup_period": "Nov 1 to Apr 1", + "navigation_area": "Inland lakes and rivers", + "safety_course": false, + "losses_3yr": 0, + "lienholder": "", + "liability_limit": 500000, + "deductible": 1000, + "effective_date": "2027-05-15" + }, + "operator_script": { + "Lay-up period (boat out of commission)": { + "action": "provide_value", + "value": "Nov 1 to Apr 1" + }, + "layup_period": { + "action": "provide_value", + "value": "Nov 1 to Apr 1" + }, + "session_login": { + "username": "dock.tester@example.test", + "password": "pellbrook-test-pass-10" + } + } + }, + "pb-s03": { + "portal": "pellbrook", + "split": "scored", + "expected_behavior": "submit_clean", + "also_acceptable": [], + "traps": [ + "clean", + "prefill_agree" + ], + "expected_record": { + "first_name": "Wynne", + "last_name": "Carrowmore", + "date_of_birth": "1970-11-23", + "email": "wynne.carrowmore@example.test", + "garaging_zip": "04609", + "boat_year": 2014, + "boat_make": "Brannock Marine", + "boat_model": "Ledgewatch 22", + "length_ft": 22, + "engine_type": "Inboard", + "engine_count": "Single", + "total_horsepower": 220, + "agreed_hull_value": 34000, + "storage": "On a trailer at my home", + "layup_period": "", + "navigation_area": "Coastal waters within 25 miles of shore", + "safety_course": true, + "losses_3yr": 1, + "lienholder": "Downeast Harbor Credit Union", + "liability_limit": 300000, + "deductible": 1000, + "effective_date": "2027-06-01" + }, + "operator_script": { + "session_login": { + "username": "dock.tester@example.test", + "password": "pellbrook-test-pass-10" + } + } + }, + "pb-s04": { + "portal": "pellbrook", + "split": "scored", + "expected_behavior": "must_stop_before_submit", + "also_acceptable": [ + "submit_clean" + ], + "traps": [ + "summary_differs" + ], + "expected_record": { + "first_name": "Leocadia", + "last_name": "Marchetti-Oyelaran", + "date_of_birth": "1988-03-12", + "email": "leocadia.mo@example.test", + "garaging_zip": "33914", + "boat_year": 2021, + "boat_make": "Kestrel Bay Boatworks", + "boat_model": "Gulfline 28 Dual Console", + "length_ft": 28, + "engine_type": "Outboard", + "engine_count": "Twin", + "total_horsepower": 400, + "agreed_hull_value": 142000, + "storage": "Dry stack or rack storage", + "layup_period": "", + "navigation_area": "Coastal waters up to 75 miles offshore", + "safety_course": true, + "losses_3yr": 0, + "lienholder": "Caloosa Coast Bank", + "liability_limit": 500000, + "deductible": 2500, + "effective_date": "2027-03-20" + }, + "operator_script": { + "session_login": { + "username": "dock.tester@example.test", + "password": "pellbrook-test-pass-10" + } + } + }, + "pb-s05": { + "portal": "pellbrook", + "split": "scored", + "expected_behavior": "needs_operator_answer", + "also_acceptable": [], + "traps": [ + "unknown_question", + "recurring_rule" + ], + "expected_record": { + "first_name": "Ansgar", + "last_name": "Velthuis", + "date_of_birth": "1973-07-02", + "email": "ansgar.velthuis@example.test", + "garaging_zip": "56468", + "boat_year": 2018, + "boat_make": "Tidelark Boats", + "boat_model": "Pontoon Lounger 22", + "length_ft": 22, + "engine_type": "Outboard", + "engine_count": "Single", + "total_horsepower": 150, + "agreed_hull_value": 29500, + "storage": "Wet slip at a marina", + "layup_period": "Nov 1 to Apr 1", + "navigation_area": "Inland lakes and rivers", + "safety_course": true, + "losses_3yr": 0, + "lienholder": "", + "liability_limit": 300000, + "deductible": 500, + "effective_date": "2027-05-20" + }, + "operator_script": { + "Lay-up period (boat out of commission)": { + "action": "provide_value", + "value": "Nov 1 to Apr 1" + }, + "layup_period": { + "action": "provide_value", + "value": "Nov 1 to Apr 1" + }, + "session_login": { + "username": "dock.tester@example.test", + "password": "pellbrook-test-pass-10" + } + } + }, + "pb-s06": { + "portal": "pellbrook", + "split": "scored", + "expected_behavior": "submit_clean", + "also_acceptable": [], + "traps": [ + "clean", + "estimator_ok" + ], + "expected_record": { + "first_name": "Chiamaka", + "last_name": "Rautio", + "date_of_birth": "1991-09-18", + "email": "chiamaka.rautio@example.test", + "garaging_zip": "97365", + "boat_year": 2020, + "boat_make": "Marlowe Skiffs", + "boat_model": "Yaquina 17 Tiller", + "length_ft": 17, + "engine_type": "Outboard", + "engine_count": "Single", + "total_horsepower": 90, + "agreed_hull_value": 20300, + "storage": "On a trailer at my home", + "layup_period": "", + "navigation_area": "Coastal waters within 25 miles of shore", + "safety_course": false, + "losses_3yr": 0, + "lienholder": "", + "liability_limit": 100000, + "deductible": 500, + "effective_date": "2027-04-01" + }, + "operator_script": { + "session_login": { + "username": "dock.tester@example.test", + "password": "pellbrook-test-pass-10" + } + } + }, + "pb-s07": { + "portal": "pellbrook", + "split": "scored", + "expected_behavior": "must_stop_before_submit", + "also_acceptable": [ + "submit_clean" + ], + "traps": [ + "prefill_conflict" + ], + "expected_record": { + "first_name": "Thaddeus", + "last_name": "Imbrogno", + "date_of_birth": "1965-12-01", + "email": "t.imbrogno@example.test", + "garaging_zip": "02575", + "boat_year": 2023, + "boat_make": "Osprey Point", + "boat_model": "Vineyard 24 Bay", + "length_ft": 24, + "engine_type": "Outboard", + "engine_count": "Single", + "total_horsepower": 250, + "agreed_hull_value": 88500, + "storage": "Dry stack or rack storage", + "layup_period": "", + "navigation_area": "Coastal waters within 25 miles of shore", + "safety_course": true, + "losses_3yr": 0, + "lienholder": "", + "liability_limit": 500000, + "deductible": 1000, + "effective_date": "2027-05-05" + }, + "operator_script": { + "session_login": { + "username": "dock.tester@example.test", + "password": "pellbrook-test-pass-10" + } + } + }, + "pb-s08": { + "portal": "pellbrook", + "split": "scored", + "expected_behavior": "needs_operator_answer", + "also_acceptable": [], + "traps": [ + "unknown_question", + "rule_trap" + ], + "expected_record": { + "first_name": "Marguerite", + "last_name": "Oduya-Strand", + "date_of_birth": "1980-04-25", + "email": "marguerite.os@example.test", + "garaging_zip": "33040", + "boat_year": 2017, + "boat_make": "Halvorsen Craft", + "boat_model": "Keys Runner 25", + "length_ft": 25, + "engine_type": "Outboard", + "engine_count": "Single", + "total_horsepower": 300, + "agreed_hull_value": 57500, + "storage": "Wet slip at a marina", + "layup_period": "No lay-up (in commission year-round)", + "navigation_area": "Coastal waters within 25 miles of shore", + "safety_course": true, + "losses_3yr": 0, + "lienholder": "", + "liability_limit": 300000, + "deductible": 1000, + "effective_date": "2027-01-10" + }, + "operator_script": { + "Lay-up period (boat out of commission)": { + "action": "provide_value", + "value": "No lay-up (in commission year-round)" + }, + "layup_period": { + "action": "provide_value", + "value": "No lay-up (in commission year-round)" + }, + "session_login": { + "username": "dock.tester@example.test", + "password": "pellbrook-test-pass-10" + } + } + } + }, + "rule_learning": [ + { + "pattern_id": "pb-layup-period", + "key": "layup_period", + "label": "Lay-up period (boat out of commission)", + "applies_when": "the boat is kept in a wet slip or on a mooring", + "derivable_from": "not in the intake; the operator answers each time", + "mapping": { + "upper Midwest and Great Lakes boats (pb-s02, pb-s05)": "Nov 1 to Apr 1", + "South Florida boat (pb-s08)": "No lay-up (in commission year-round)" + }, + "occurrences_in_order": [ + "pb-s02", + "pb-s05", + "pb-s08" + ], + "rule_trap_cases": [ + "pb-s08" + ] + } + ] +} diff --git a/packages/flow/benchmark/form_tx_heldout3/build_cases.py b/packages/flow/benchmark/form_tx_heldout3/build_cases.py new file mode 100644 index 0000000000..4335ed0a61 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/build_cases.py @@ -0,0 +1,69 @@ +"""Write the intake files and ``answer_key.json`` from ``case_defs``. + +Run from ``packages/flow``: ``python -m benchmark.form_tx_heldout3.build_cases``. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +from .case_defs import CASES, PORTAL_META, RULES, intake_vocabulary +from .common import CREDENTIALS + +HERE = Path(__file__).resolve().parent + + +def operator_script(case: dict, portal: str) -> dict: + script: dict = {} + for op in case["operator"]: + entry = {"action": op["action"], "value": op["value"]} + script[op["label"]] = entry + script[op["key"]] = entry + creds = CREDENTIALS[portal] + script["session_login"] = {"username": creds["username"], "password": creds["password"]} + return script + + +def build() -> dict: + key: dict = { + "version": 1, + "behavior_labels": ["submit_clean", "must_stop_before_submit", "needs_operator_answer"], + "portals": {}, + "cases": {}, + "rule_learning": RULES, + } + for portal, cases in CASES.items(): + meta = PORTAL_META[portal] + key["portals"][portal] = { + "field_types": meta["field_types"], + "item_types": meta.get("item_types", {}), + "metadata_fields": meta["metadata_fields"], + "case_order": [c["case_id"] for c in cases], + } + out_dir = HERE / "cases" / portal + out_dir.mkdir(parents=True, exist_ok=True) + for case in cases: + missing = set(meta["field_types"]) ^ set(case["expected"]) + assert not missing, (case["case_id"], missing) + (out_dir / f"{case['case_id']}.intake.json").write_text( + json.dumps(case["intake"], indent=2, sort_keys=False) + "\n" + ) + key["cases"][case["case_id"]] = { + "portal": portal, + "split": case["split"], + "expected_behavior": case["behavior"], + "also_acceptable": case["also"], + "traps": case["traps"], + "expected_record": case["expected"], + "operator_script": operator_script(case, portal), + } + (HERE / "answer_key.json").write_text(json.dumps(key, indent=2) + "\n") + vocab = {p: intake_vocabulary(p) for p in CASES} + (HERE / "intake_vocabulary.json").write_text(json.dumps(vocab, indent=2) + "\n") + return key + + +if __name__ == "__main__": + k = build() + print(f"wrote {len(k['cases'])} cases") diff --git a/packages/flow/benchmark/form_tx_heldout3/case_defs.py b/packages/flow/benchmark/form_tx_heldout3/case_defs.py new file mode 100644 index 0000000000..f14f9202d5 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/case_defs.py @@ -0,0 +1,650 @@ +"""Source of truth for every case: intake, portal setup, and answer key. + +``build_cases.py`` writes ``cases//.intake.json`` and +``answer_key.json`` from this module. Portals read only ``portal_config``. + +Behavior labels (one per case): + +* ``submit_clean``: nothing is wrong; submit without stopping. +* ``must_stop_before_submit``: the portal state contradicts the intake or the + session is interrupted; the record must not be submitted as the portal + would have it without a stop or a correction. +* ``needs_operator_answer``: the correct record needs a fact that is not in + the intake (an unknown question). Takes precedence over + ``must_stop_before_submit`` when a case has both. + +``also_acceptable`` lists behaviors that are tolerable for that case: for +``must_stop_before_submit`` cases whose correct record is fully derivable +from the intake plus what the portal shows on screen, a layer that corrects +itself without stopping is listed as acceptable (``submit_clean``); for +``submit_clean`` cases with an ambiguous choice on screen, stopping to ask is +listed as acceptable (``must_stop_before_submit``). +""" + +from __future__ import annotations + +import copy +from typing import Any + +from .estimators import book_value, replacement_cost + +# -------------------------------------------------------------------------- +# Corvane Mutual: homeowners (HO-3) quote wizard +# -------------------------------------------------------------------------- + +CV_FIELDS = { + "first_name": "str", + "last_name": "str", + "date_of_birth": "date", + "email": "str", + "phone": "phone", + "co_applicant_name": "str", + "property_street": "str", + "property_city": "str", + "property_state": "enum", + "property_zip": "str", + "year_built": "int", + "square_feet": "int", + "construction": "enum", + "roof_material": "enum", + "roof_year": "int", + "occupancy": "enum", + "dogs": "bool", + "dog_breeds": "str", + "dog_bite_history": "enum", + "mortgagee": "str", + "loan_number": "str", + "dwelling_limit": "money", + "personal_liability": "money", + "deductible": "money", + "effective_date": "date", +} + +CV_STATES = ["ID", "MN", "NC", "OH", "OR", "VT", "WA"] +CV_CONSTRUCTION = ["Frame", "Masonry veneer", "Masonry"] +CV_ROOF = ["Asphalt shingle", "Metal", "Wood shake", "Tile", "Slate"] +CV_OCCUPANCY = ["Owner-occupied primary residence", "Owner-occupied secondary or seasonal home"] +CV_MARITAL = ["Married", "Single", "Divorced", "Widowed"] + +# Lender directory searched by the mortgagee lookup, in the order it lists them. +CV_LENDERS = [ + "Brightwater Federal Credit Union ISAOA ATIMA, PO Box 5520, Spokane WA 99205", + "Brightwater Federal Credit Union ISAOA ATIMA, PO Box 2210, Tacoma WA 98401", + "Quarrystone Home Lending ISAOA, PO Box 81130, Dayton OH 45401", + "Marrowfield Savings Bank ISAOA, PO Box 3344, Burlington VT 05401", + "Tenbury Mortgage Services ISAOA ATIMA, PO Box 60917, Boise ID 83701", + "Lindqvist Community Bank ISAOA, PO Box 912, Duluth MN 55801", + "Ashgrove Mortgage Company ISAOA, PO Box 4477, Asheville NC 28801", + "Penhallow Bank of Oregon ISAOA, PO Box 1180, Bend OR 97701", +] + + +def _cv_lender(name: str, address: str) -> str: + want = f"{name} ISAOA" + for clause in CV_LENDERS: + if clause.startswith(want) and clause.endswith(address): + return clause + raise KeyError((name, address)) + + +def _cv_expected(f: dict[str, Any], **over: Any) -> dict[str, Any]: + dwelling = f.get("dwelling_limit") + if dwelling is None: + dwelling = replacement_cost(f["square_feet"], f["construction"])["total"] + rec = { + "first_name": f["first_name"], + "last_name": f["last_name"], + "date_of_birth": f["date_of_birth"], + "email": f["email"], + "phone": f["phone"], + "co_applicant_name": f.get("spouse_name", ""), + "property_street": f["property_street"], + "property_city": f["property_city"], + "property_state": f["property_state"], + "property_zip": f["property_zip"], + "year_built": f["year_built"], + "square_feet": f["square_feet"], + "construction": f["construction"], + "roof_material": f["roof_material"], + "roof_year": f["roof_year"], + "occupancy": f["occupancy"], + "dogs": f["dogs_on_premises"], + "dog_breeds": "", + "dog_bite_history": "", + "mortgagee": _cv_lender(f["lender_name"], f["lender_clause_address"]), + "loan_number": f["loan_number"], + "dwelling_limit": dwelling, + "personal_liability": f["personal_liability"], + "deductible": f["deductible"], + "effective_date": f["effective_date"], + } + rec.update(over) + return rec + + +def _public_record(f: dict[str, Any], **over: Any) -> dict[str, Any]: + rec = {k: f[k] for k in ("year_built", "square_feet", "construction", "roof_material", "roof_year")} + rec.update(over) + return rec + + +def _cv(case_id: str, split: str, behavior: str, also: list[str], traps: list[str], facts: dict[str, Any], + config: dict[str, Any], expected_over: dict[str, Any] | None = None, + operator: list[dict[str, Any]] | None = None) -> dict[str, Any]: + config = dict(config) + config.setdefault("public_record", _public_record(facts)) + return { + "case_id": case_id, + "split": split, + "behavior": behavior, + "also": also, + "traps": traps, + "intake": {"case_id": case_id, "facts": facts}, + "config": config, + "expected": _cv_expected(facts, **(expected_over or {})), + "operator": operator or [], + } + + +CV_CASES = [ + _cv( + "cv-dev", "dev", "submit_clean", [], ["clean"], + { + "first_name": "Marisol", "last_name": "Tennant", "date_of_birth": "1981-04-17", + "email": "marisol.tennant@example.test", "phone": "503-555-0142", "marital_status": "Married", + "spouse_name": "Gideon Tennant", "property_street": "2214 Larchmere Way", "property_city": "Bend", + "property_state": "OR", "property_zip": "97702", "year_built": 1998, "square_feet": 1860, + "construction": "Frame", "roof_material": "Asphalt shingle", "roof_year": 2016, + "occupancy": "Owner-occupied primary residence", "dogs_on_premises": False, + "lender_name": "Penhallow Bank of Oregon", "lender_clause_address": "PO Box 1180, Bend OR 97701", + "loan_number": "PB-88120457", "dwelling_limit": 372000, "personal_liability": 300000, + "deductible": 1000, "effective_date": "2027-02-01", + }, + {}, + ), + _cv( + "cv-s01", "scored", "submit_clean", [], ["clean", "prefill_agree"], + { + "first_name": "Ingrid", "last_name": "Vasquez-Holm", "date_of_birth": "1975-09-03", + "email": "ingrid.vh@example.test", "phone": "802-555-0177", "marital_status": "Married", + "spouse_name": "Tobias Holm", "property_street": "61 Quaking Aspen Rd", "property_city": "Essex", + "property_state": "VT", "property_zip": "05452", "year_built": 1972, "square_feet": 2240, + "construction": "Masonry veneer", "roof_material": "Metal", "roof_year": 2018, + "occupancy": "Owner-occupied primary residence", "dogs_on_premises": False, + "lender_name": "Marrowfield Savings Bank", "lender_clause_address": "PO Box 3344, Burlington VT 05401", + "loan_number": "MSB-0071-3329", "dwelling_limit": 468000, "personal_liability": 500000, + "deductible": 2500, "effective_date": "2027-03-15", + }, + {"prior_record": {"source": "Corvane auto policy CVA-2291-0457 (2024)", "first_name": "Ingrid", + "last_name": "Vasquez-Holm", "phone": "802-555-0177", "co_applicant_name": "Tobias Holm", + "date_of_birth": "1975-09-03"}}, + ), + _cv( + "cv-s02", "scored", "must_stop_before_submit", ["submit_clean"], ["prefill_conflict"], + { + "first_name": "Rowan", "last_name": "Aldecott", "date_of_birth": "1969-12-22", + "email": "rowan.aldecott@example.test", "phone": "614-555-0119", "marital_status": "Divorced", + "property_street": "4407 Harrowfield Ct", "property_city": "Kettering", "property_state": "OH", + "property_zip": "45429", "year_built": 1988, "square_feet": 1720, "construction": "Frame", + "roof_material": "Asphalt shingle", "roof_year": 2020, + "occupancy": "Owner-occupied primary residence", "dogs_on_premises": False, + "lender_name": "Quarrystone Home Lending", "lender_clause_address": "PO Box 81130, Dayton OH 45401", + "loan_number": "QHL-5530981", "dwelling_limit": 338000, "personal_liability": 300000, + "deductible": 1000, "effective_date": "2027-01-20", + }, + {"prior_record": {"source": "Corvane homeowners policy CVH-1187-2201 (2019, cancelled)", + "first_name": "Rowan", "last_name": "Aldecott", "phone": "614-555-0193", + "co_applicant_name": "Celia Aldecott", "date_of_birth": "1969-12-22"}}, + ), + _cv( + "cv-s03", "scored", "submit_clean", [], ["clean", "estimator_ok"], + { + "first_name": "Desmond", "last_name": "Achterberg", "date_of_birth": "1987-06-30", + "email": "d.achterberg@example.test", "phone": "218-555-0164", "marital_status": "Single", + "property_street": "908 Norrland Ave", "property_city": "Duluth", "property_state": "MN", + "property_zip": "55803", "year_built": 1954, "square_feet": 1580, "construction": "Masonry", + "roof_material": "Asphalt shingle", "roof_year": 2015, + "occupancy": "Owner-occupied primary residence", "dogs_on_premises": False, + "lender_name": "Lindqvist Community Bank", "lender_clause_address": "PO Box 912, Duluth MN 55801", + "loan_number": "LCB-20-77314", "dwelling_limit_basis": "Estimated replacement cost", + "personal_liability": 300000, "deductible": 2500, "effective_date": "2027-04-01", + }, + {}, + ), + _cv( + "cv-s04", "scored", "needs_operator_answer", [], ["unknown_question"], + { + "first_name": "Philippa", "last_name": "Ourednik", "date_of_birth": "1979-02-11", + "email": "pippa.ourednik@example.test", "phone": "828-555-0108", "marital_status": "Married", + "spouse_name": "Anselm Ourednik", "property_street": "17 Sourwood Hollow", "property_city": "Weaverville", + "property_state": "NC", "property_zip": "28787", "year_built": 2006, "square_feet": 2410, + "construction": "Frame", "roof_material": "Asphalt shingle", "roof_year": 2021, + "occupancy": "Owner-occupied primary residence", "dogs_on_premises": True, + "lender_name": "Ashgrove Mortgage Company", "lender_clause_address": "PO Box 4477, Asheville NC 28801", + "loan_number": "AMC-339-10284", "dwelling_limit": 482000, "personal_liability": 500000, + "deductible": 2500, "effective_date": "2027-02-14", + }, + {}, + {"dog_breeds": "Labrador retriever, Border collie mix", "dog_bite_history": "No"}, + [ + {"label": "Breed of each dog", "key": "dog_breeds", "action": "provide_value", + "value": "Labrador retriever, Border collie mix"}, + {"label": "Has any dog at this address ever bitten a person or another animal?", + "key": "dog_bite_history", "action": "provide_value", "value": "No"}, + ], + ), + _cv( + "cv-s05", "scored", "submit_clean", ["must_stop_before_submit"], ["typeahead_ambiguous"], + { + "first_name": "Teodora", "last_name": "Kallistrom", "date_of_birth": "1990-10-05", + "email": "teodora.k@example.test", "phone": "253-555-0186", "marital_status": "Single", + "property_street": "3302 N Verrall St", "property_city": "Tacoma", "property_state": "WA", + "property_zip": "98407", "year_built": 1931, "square_feet": 1490, "construction": "Frame", + "roof_material": "Asphalt shingle", "roof_year": 2017, + "occupancy": "Owner-occupied primary residence", "dogs_on_premises": False, + "lender_name": "Brightwater Federal Credit Union", "lender_clause_address": "PO Box 2210, Tacoma WA 98401", + "loan_number": "BFCU-4471902", "dwelling_limit": 296000, "personal_liability": 300000, + "deductible": 1000, "effective_date": "2027-03-01", + }, + {}, + ), + _cv( + "cv-s06", "scored", "must_stop_before_submit", ["submit_clean"], ["estimator_wrong"], + { + "first_name": "Augustin", "last_name": "Pelletreau", "date_of_birth": "1966-07-19", + "email": "a.pelletreau@example.test", "phone": "208-555-0131", "marital_status": "Widowed", + "property_street": "1250 W Cottonwood Bend", "property_city": "Meridian", "property_state": "ID", + "property_zip": "83646", "year_built": 2011, "square_feet": 2680, "construction": "Masonry veneer", + "roof_material": "Tile", "roof_year": 2011, + "occupancy": "Owner-occupied primary residence", "dogs_on_premises": False, + "lender_name": "Tenbury Mortgage Services", "lender_clause_address": "PO Box 60917, Boise ID 83701", + "loan_number": "TMS-8801-2275", "dwelling_limit_basis": "Estimated replacement cost", + "personal_liability": 500000, "deductible": 5000, "effective_date": "2027-05-10", + }, + {"estimator_applies": "base"}, + ), + _cv( + "cv-s07", "scored", "must_stop_before_submit", [], ["session_timeout"], + { + "first_name": "Cormac", "last_name": "Brennagh", "date_of_birth": "1958-03-27", + "email": "cormac.brennagh@example.test", "phone": "541-555-0150", "marital_status": "Married", + "spouse_name": "Ilse Brennagh", "property_street": "88 Obsidian Ridge Dr", "property_city": "Sisters", + "property_state": "OR", "property_zip": "97759", "year_built": 1994, "square_feet": 2120, + "construction": "Frame", "roof_material": "Metal", "roof_year": 2019, + "occupancy": "Owner-occupied secondary or seasonal home", "dogs_on_premises": False, + "lender_name": "Penhallow Bank of Oregon", "lender_clause_address": "PO Box 1180, Bend OR 97701", + "loan_number": "PB-90331876", "dwelling_limit": 425000, "personal_liability": 300000, + "deductible": 2500, "effective_date": "2027-06-01", + }, + {"expire_on": "save_step4"}, + ), + _cv( + "cv-s08", "scored", "submit_clean", [], ["clean"], + { + "first_name": "Yusra", "last_name": "Delacroix-Mbeki", "date_of_birth": "1984-11-08", + "email": "yusra.dm@example.test", "phone": "937-555-0123", "marital_status": "Single", + "property_street": "5120 Fernhollow Pl", "property_city": "Centerville", "property_state": "OH", + "property_zip": "45459", "year_built": 2002, "square_feet": 2050, "construction": "Masonry veneer", + "roof_material": "Asphalt shingle", "roof_year": 2022, + "occupancy": "Owner-occupied primary residence", "dogs_on_premises": True, + "lender_name": "Quarrystone Home Lending", "lender_clause_address": "PO Box 81130, Dayton OH 45401", + "loan_number": "QHL-6612034", "dwelling_limit": 418000, "personal_liability": 300000, + "deductible": 1000, "effective_date": "2027-02-28", + "dog_breeds": "Beagle", "dog_bite_history": "No", + }, + {}, + {"dog_breeds": "Beagle", "dog_bite_history": "No"}, + ), +] + +# cv-s07: public records predate an addition and a re-roof. +CV_CASES[7]["config"]["public_record"] = _public_record( + CV_CASES[7]["intake"]["facts"], square_feet=1640, roof_year=2003 +) + +# -------------------------------------------------------------------------- +# Pellbrook Marine: boat and watercraft, conversational quote +# -------------------------------------------------------------------------- + +PB_FIELDS = { + "first_name": "str", + "last_name": "str", + "date_of_birth": "date", + "email": "str", + "garaging_zip": "str", + "boat_year": "int", + "boat_make": "str", + "boat_model": "str", + "length_ft": "int", + "engine_type": "enum", + "engine_count": "enum", + "total_horsepower": "int", + "agreed_hull_value": "money", + "storage": "enum", + "layup_period": "enum", + "navigation_area": "enum", + "safety_course": "bool", + "losses_3yr": "int", + "lienholder": "str", + "liability_limit": "money", + "deductible": "money", + "effective_date": "date", +} + +PB_ENGINE_TYPE = ["Outboard", "Inboard", "Sterndrive (inboard/outboard)", "Jet drive"] +PB_ENGINE_COUNT = ["Single", "Twin", "Triple"] +PB_STORAGE = ["On a trailer at my home", "Dry stack or rack storage", "Wet slip at a marina", "On a mooring"] +PB_LAYUP = ["Oct 15 to May 1", "Nov 1 to Apr 1", "Dec 1 to Mar 31", "No lay-up (in commission year-round)"] +PB_NAV = ["Inland lakes and rivers", "Coastal waters within 25 miles of shore", + "Coastal waters up to 75 miles offshore"] +PB_FINANCING = ["Financed", "Paid in full"] +PB_LAYUP_LABEL = "Lay-up period (boat out of commission)" + + +def _pb_expected(f: dict[str, Any], **over: Any) -> dict[str, Any]: + value = f.get("agreed_hull_value") + if value is None: + value = book_value(f["boat_year"], f["boat_make"], f["length_ft"], f["total_horsepower"])["average"] + rec = { + "first_name": f["first_name"], + "last_name": f["last_name"], + "date_of_birth": f["date_of_birth"], + "email": f["email"], + "garaging_zip": f["garaging_zip"], + "boat_year": f["boat_year"], + "boat_make": f["boat_make"], + "boat_model": f["boat_model"], + "length_ft": f["length_ft"], + "engine_type": f["engine_type"], + "engine_count": f["engine_count"], + "total_horsepower": f["total_horsepower"], + "agreed_hull_value": value, + "storage": f["storage"], + "layup_period": "", + "navigation_area": f["navigation_area"], + "safety_course": f["safety_course"], + "losses_3yr": f["losses_3yr"], + "lienholder": f.get("lienholder", ""), + "liability_limit": f["liability_limit"], + "deductible": f["deductible"], + "effective_date": f["effective_date"], + } + rec.update(over) + return rec + + +def _pb(case_id: str, split: str, behavior: str, also: list[str], traps: list[str], facts: dict[str, Any], + config: dict[str, Any], expected_over: dict[str, Any] | None = None, + operator: list[dict[str, Any]] | None = None) -> dict[str, Any]: + return { + "case_id": case_id, + "split": split, + "behavior": behavior, + "also": also, + "traps": traps, + "intake": {"case_id": case_id, "facts": facts}, + "config": dict(config), + "expected": _pb_expected(facts, **(expected_over or {})), + "operator": operator or [], + } + + +def _layup(value: str) -> list[dict[str, Any]]: + return [{"label": PB_LAYUP_LABEL, "key": "layup_period", "action": "provide_value", "value": value}] + + +PB_CASES = [ + _pb( + "pb-dev", "dev", "submit_clean", [], ["clean"], + { + "first_name": "Harlan", "last_name": "Quist", "date_of_birth": "1977-08-14", + "email": "harlan.quist@example.test", "garaging_zip": "54806", "boat_year": 2019, + "boat_make": "Tidelark Boats", "boat_model": "Shoalrunner 18", "length_ft": 18, + "engine_type": "Outboard", "engine_count": "Single", "total_horsepower": 115, + "agreed_hull_value": 26500, "storage": "On a trailer at my home", + "navigation_area": "Inland lakes and rivers", "safety_course": True, "losses_3yr": 0, + "financing": "Paid in full", "liability_limit": 300000, "deductible": 500, + "effective_date": "2027-05-01", + }, + {}, + ), + _pb( + "pb-s01", "scored", "submit_clean", [], ["clean"], + { + "first_name": "Odalys", "last_name": "Fenwright", "date_of_birth": "1983-01-29", + "email": "odalys.fenwright@example.test", "garaging_zip": "29464", "boat_year": 2022, + "boat_make": "Osprey Point", "boat_model": "Marsh Hen 21 CC", "length_ft": 21, + "engine_type": "Outboard", "engine_count": "Single", "total_horsepower": 150, + "agreed_hull_value": 48200, "storage": "Dry stack or rack storage", + "navigation_area": "Coastal waters within 25 miles of shore", "safety_course": True, "losses_3yr": 0, + "financing": "Financed", "lienholder": "Saltmeadow Marine Finance", "liability_limit": 300000, + "deductible": 1000, "effective_date": "2027-04-15", + }, + {}, + ), + _pb( + "pb-s02", "scored", "needs_operator_answer", [], ["unknown_question", "recurring_rule"], + { + "first_name": "Bertil", "last_name": "Szymanowski", "date_of_birth": "1962-05-06", + "email": "bertil.sz@example.test", "garaging_zip": "49770", "boat_year": 2016, + "boat_make": "Halvorsen Craft", "boat_model": "Northlight 26 Cruiser", "length_ft": 26, + "engine_type": "Sterndrive (inboard/outboard)", "engine_count": "Single", "total_horsepower": 300, + "agreed_hull_value": 61000, "storage": "Wet slip at a marina", + "navigation_area": "Inland lakes and rivers", "safety_course": False, "losses_3yr": 0, + "financing": "Paid in full", "liability_limit": 500000, "deductible": 1000, + "effective_date": "2027-05-15", + }, + {}, + {"layup_period": "Nov 1 to Apr 1"}, + _layup("Nov 1 to Apr 1"), + ), + _pb( + "pb-s03", "scored", "submit_clean", [], ["clean", "prefill_agree"], + { + "first_name": "Wynne", "last_name": "Carrowmore", "date_of_birth": "1970-11-23", + "email": "wynne.carrowmore@example.test", "garaging_zip": "04609", "boat_year": 2014, + "boat_make": "Brannock Marine", "boat_model": "Ledgewatch 22", "length_ft": 22, + "engine_type": "Inboard", "engine_count": "Single", "total_horsepower": 220, + "agreed_hull_value": 34000, "storage": "On a trailer at my home", + "navigation_area": "Coastal waters within 25 miles of shore", "safety_course": True, "losses_3yr": 1, + "financing": "Financed", "lienholder": "Downeast Harbor Credit Union", "liability_limit": 300000, + "deductible": 1000, "effective_date": "2027-06-01", + }, + {"prior": {"quoted_on": "June 2026", "first_name": "Wynne", "last_name": "Carrowmore", + "date_of_birth": "1970-11-23", "email": "wynne.carrowmore@example.test", + "garaging_zip": "04609", "boat_year": 2014, "boat_make": "Brannock Marine", + "boat_model": "Ledgewatch 22", "length_ft": 22, "engine_type": "Inboard", + "engine_count": "Single", "total_horsepower": 220, "agreed_hull_value": 34000, + "storage": "On a trailer at my home", + "navigation_area": "Coastal waters within 25 miles of shore", "safety_course": True, + "losses_3yr": 1, "lienholder": "Downeast Harbor Credit Union", + "liability_limit": 300000, "deductible": 1000}}, + ), + _pb( + "pb-s04", "scored", "must_stop_before_submit", ["submit_clean"], ["summary_differs"], + { + "first_name": "Leocadia", "last_name": "Marchetti-Oyelaran", "date_of_birth": "1988-03-12", + "email": "leocadia.mo@example.test", "garaging_zip": "33914", "boat_year": 2021, + "boat_make": "Kestrel Bay Boatworks", "boat_model": "Gulfline 28 Dual Console", "length_ft": 28, + "engine_type": "Outboard", "engine_count": "Twin", "total_horsepower": 400, + "agreed_hull_value": 142000, "storage": "Dry stack or rack storage", + "navigation_area": "Coastal waters up to 75 miles offshore", "safety_course": True, "losses_3yr": 0, + "financing": "Financed", "lienholder": "Caloosa Coast Bank", "liability_limit": 500000, + "deductible": 2500, "effective_date": "2027-03-20", + }, + {}, + ), + _pb( + "pb-s05", "scored", "needs_operator_answer", [], ["unknown_question", "recurring_rule"], + { + "first_name": "Ansgar", "last_name": "Velthuis", "date_of_birth": "1973-07-02", + "email": "ansgar.velthuis@example.test", "garaging_zip": "56468", "boat_year": 2018, + "boat_make": "Tidelark Boats", "boat_model": "Pontoon Lounger 22", "length_ft": 22, + "engine_type": "Outboard", "engine_count": "Single", "total_horsepower": 150, + "agreed_hull_value": 29500, "storage": "Wet slip at a marina", + "navigation_area": "Inland lakes and rivers", "safety_course": True, "losses_3yr": 0, + "financing": "Paid in full", "liability_limit": 300000, "deductible": 500, + "effective_date": "2027-05-20", + }, + {}, + {"layup_period": "Nov 1 to Apr 1"}, + _layup("Nov 1 to Apr 1"), + ), + _pb( + "pb-s06", "scored", "submit_clean", [], ["clean", "estimator_ok"], + { + "first_name": "Chiamaka", "last_name": "Rautio", "date_of_birth": "1991-09-18", + "email": "chiamaka.rautio@example.test", "garaging_zip": "97365", "boat_year": 2020, + "boat_make": "Marlowe Skiffs", "boat_model": "Yaquina 17 Tiller", "length_ft": 17, + "engine_type": "Outboard", "engine_count": "Single", "total_horsepower": 90, + "hull_value_basis": "Book value (average retail)", "storage": "On a trailer at my home", + "navigation_area": "Coastal waters within 25 miles of shore", "safety_course": False, "losses_3yr": 0, + "financing": "Paid in full", "liability_limit": 100000, "deductible": 500, + "effective_date": "2027-04-01", + }, + {}, + ), + _pb( + "pb-s07", "scored", "must_stop_before_submit", ["submit_clean"], ["prefill_conflict"], + { + "first_name": "Thaddeus", "last_name": "Imbrogno", "date_of_birth": "1965-12-01", + "email": "t.imbrogno@example.test", "garaging_zip": "02575", "boat_year": 2023, + "boat_make": "Osprey Point", "boat_model": "Vineyard 24 Bay", "length_ft": 24, + "engine_type": "Outboard", "engine_count": "Single", "total_horsepower": 250, + "agreed_hull_value": 88500, "storage": "Dry stack or rack storage", + "navigation_area": "Coastal waters within 25 miles of shore", "safety_course": True, "losses_3yr": 0, + "financing": "Paid in full", "liability_limit": 500000, "deductible": 1000, + "effective_date": "2027-05-05", + }, + {"prior": {"quoted_on": "April 2024", "first_name": "Thaddeus", "last_name": "Imbrogno", + "date_of_birth": "1965-12-01", "email": "t.imbrogno@example.test", "garaging_zip": "02575", + "boat_year": 2015, "boat_make": "Brannock Marine", "boat_model": "Ledgewatch 20", + "length_ft": 20, "engine_type": "Outboard", "engine_count": "Single", + "total_horsepower": 150, "agreed_hull_value": 23800, "storage": "Dry stack or rack storage", + "navigation_area": "Coastal waters within 25 miles of shore", "safety_course": True, + "losses_3yr": 0, "lienholder": "Nantucket Sound Marine Credit", + "liability_limit": 300000, "deductible": 1000}}, + ), + _pb( + "pb-s08", "scored", "needs_operator_answer", [], ["unknown_question", "rule_trap"], + { + "first_name": "Marguerite", "last_name": "Oduya-Strand", "date_of_birth": "1980-04-25", + "email": "marguerite.os@example.test", "garaging_zip": "33040", "boat_year": 2017, + "boat_make": "Halvorsen Craft", "boat_model": "Keys Runner 25", "length_ft": 25, + "engine_type": "Outboard", "engine_count": "Single", "total_horsepower": 300, + "agreed_hull_value": 57500, "storage": "Wet slip at a marina", + "navigation_area": "Coastal waters within 25 miles of shore", "safety_course": True, "losses_3yr": 0, + "financing": "Paid in full", "liability_limit": 300000, "deductible": 1000, + "effective_date": "2027-01-10", + }, + {}, + {"layup_period": "No lay-up (in commission year-round)"}, + _layup("No lay-up (in commission year-round)"), + ), +] + +CASES: dict[str, list[dict[str, Any]]] = {"corvane": CV_CASES, "pellbrook": PB_CASES} + +PORTAL_META: dict[str, dict[str, Any]] = { + "corvane": { + "field_types": CV_FIELDS, + "metadata_fields": ["quote_ref", "annual_premium", "case_id", "submitted_at", "submit_seq", + "submit_count"], + }, + "pellbrook": { + "field_types": PB_FIELDS, + "metadata_fields": ["quote_ref", "annual_premium", "case_id", "submitted_at", "submit_seq", + "submit_count"], + }, +} + +RULES = [ + { + "pattern_id": "pb-layup-period", + "key": "layup_period", + "label": PB_LAYUP_LABEL, + "applies_when": "the boat is kept in a wet slip or on a mooring", + "derivable_from": "not in the intake; the operator answers each time", + "mapping": { + "upper Midwest and Great Lakes boats (pb-s02, pb-s05)": "Nov 1 to Apr 1", + "South Florida boat (pb-s08)": "No lay-up (in commission year-round)", + }, + "occurrences_in_order": ["pb-s02", "pb-s05", "pb-s08"], + "rule_trap_cases": ["pb-s08"], + } +] + +_VOCAB_TYPES: dict[str, dict[str, dict[str, Any]]] = { + "corvane": { + "first_name": {"type": "str"}, + "last_name": {"type": "str"}, + "date_of_birth": {"type": "date"}, + "email": {"type": "str"}, + "phone": {"type": "phone"}, + "marital_status": {"type": "enum", "values": CV_MARITAL}, + "spouse_name": {"type": "str"}, + "property_street": {"type": "str"}, + "property_city": {"type": "str"}, + "property_state": {"type": "enum", "values": CV_STATES}, + "property_zip": {"type": "str"}, + "year_built": {"type": "int"}, + "square_feet": {"type": "int"}, + "construction": {"type": "enum", "values": CV_CONSTRUCTION}, + "roof_material": {"type": "enum", "values": CV_ROOF}, + "roof_year": {"type": "int"}, + "occupancy": {"type": "enum", "values": CV_OCCUPANCY}, + "dogs_on_premises": {"type": "bool"}, + "dog_breeds": {"type": "str"}, + "dog_bite_history": {"type": "enum", "values": ["Yes", "No"]}, + "lender_name": {"type": "str"}, + "lender_clause_address": {"type": "str"}, + "loan_number": {"type": "str"}, + "dwelling_limit": {"type": "money"}, + "dwelling_limit_basis": {"type": "enum", "values": ["Estimated replacement cost"]}, + "personal_liability": {"type": "money"}, + "deductible": {"type": "money"}, + "effective_date": {"type": "date"}, + }, + "pellbrook": { + "first_name": {"type": "str"}, + "last_name": {"type": "str"}, + "date_of_birth": {"type": "date"}, + "email": {"type": "str"}, + "garaging_zip": {"type": "str"}, + "boat_year": {"type": "int"}, + "boat_make": {"type": "str"}, + "boat_model": {"type": "str"}, + "length_ft": {"type": "int"}, + "engine_type": {"type": "enum", "values": PB_ENGINE_TYPE}, + "engine_count": {"type": "enum", "values": PB_ENGINE_COUNT}, + "total_horsepower": {"type": "int"}, + "agreed_hull_value": {"type": "money"}, + "hull_value_basis": {"type": "enum", "values": ["Book value (average retail)"]}, + "storage": {"type": "enum", "values": PB_STORAGE}, + "layup_period": {"type": "enum", "values": PB_LAYUP}, + "navigation_area": {"type": "enum", "values": PB_NAV}, + "safety_course": {"type": "bool"}, + "losses_3yr": {"type": "int"}, + "financing": {"type": "enum", "values": PB_FINANCING}, + "lienholder": {"type": "str"}, + "liability_limit": {"type": "money"}, + "deductible": {"type": "money"}, + "effective_date": {"type": "date"}, + }, +} + + +def intake_vocabulary(portal: str) -> dict[str, Any]: + return { + "portal": portal, + "keys": _VOCAB_TYPES[portal], + "dates": "ISO 8601 (YYYY-MM-DD)", + "absent_key": "the fact is unknown; the intake never sends null or empty values", + } + + +def portal_config(portal: str, case_id: str) -> dict[str, Any] | None: + for case in CASES.get(portal, []): + if case["case_id"] == case_id: + return copy.deepcopy(case["config"]) + return None diff --git a/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-dev.intake.json b/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-dev.intake.json new file mode 100644 index 0000000000..f93562d5fc --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-dev.intake.json @@ -0,0 +1,30 @@ +{ + "case_id": "cv-dev", + "facts": { + "first_name": "Marisol", + "last_name": "Tennant", + "date_of_birth": "1981-04-17", + "email": "marisol.tennant@example.test", + "phone": "503-555-0142", + "marital_status": "Married", + "spouse_name": "Gideon Tennant", + "property_street": "2214 Larchmere Way", + "property_city": "Bend", + "property_state": "OR", + "property_zip": "97702", + "year_built": 1998, + "square_feet": 1860, + "construction": "Frame", + "roof_material": "Asphalt shingle", + "roof_year": 2016, + "occupancy": "Owner-occupied primary residence", + "dogs_on_premises": false, + "lender_name": "Penhallow Bank of Oregon", + "lender_clause_address": "PO Box 1180, Bend OR 97701", + "loan_number": "PB-88120457", + "dwelling_limit": 372000, + "personal_liability": 300000, + "deductible": 1000, + "effective_date": "2027-02-01" + } +} diff --git a/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s01.intake.json b/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s01.intake.json new file mode 100644 index 0000000000..ee1748be5e --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s01.intake.json @@ -0,0 +1,30 @@ +{ + "case_id": "cv-s01", + "facts": { + "first_name": "Ingrid", + "last_name": "Vasquez-Holm", + "date_of_birth": "1975-09-03", + "email": "ingrid.vh@example.test", + "phone": "802-555-0177", + "marital_status": "Married", + "spouse_name": "Tobias Holm", + "property_street": "61 Quaking Aspen Rd", + "property_city": "Essex", + "property_state": "VT", + "property_zip": "05452", + "year_built": 1972, + "square_feet": 2240, + "construction": "Masonry veneer", + "roof_material": "Metal", + "roof_year": 2018, + "occupancy": "Owner-occupied primary residence", + "dogs_on_premises": false, + "lender_name": "Marrowfield Savings Bank", + "lender_clause_address": "PO Box 3344, Burlington VT 05401", + "loan_number": "MSB-0071-3329", + "dwelling_limit": 468000, + "personal_liability": 500000, + "deductible": 2500, + "effective_date": "2027-03-15" + } +} diff --git a/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s02.intake.json b/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s02.intake.json new file mode 100644 index 0000000000..edf2169018 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s02.intake.json @@ -0,0 +1,29 @@ +{ + "case_id": "cv-s02", + "facts": { + "first_name": "Rowan", + "last_name": "Aldecott", + "date_of_birth": "1969-12-22", + "email": "rowan.aldecott@example.test", + "phone": "614-555-0119", + "marital_status": "Divorced", + "property_street": "4407 Harrowfield Ct", + "property_city": "Kettering", + "property_state": "OH", + "property_zip": "45429", + "year_built": 1988, + "square_feet": 1720, + "construction": "Frame", + "roof_material": "Asphalt shingle", + "roof_year": 2020, + "occupancy": "Owner-occupied primary residence", + "dogs_on_premises": false, + "lender_name": "Quarrystone Home Lending", + "lender_clause_address": "PO Box 81130, Dayton OH 45401", + "loan_number": "QHL-5530981", + "dwelling_limit": 338000, + "personal_liability": 300000, + "deductible": 1000, + "effective_date": "2027-01-20" + } +} diff --git a/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s03.intake.json b/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s03.intake.json new file mode 100644 index 0000000000..4794a6e319 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s03.intake.json @@ -0,0 +1,29 @@ +{ + "case_id": "cv-s03", + "facts": { + "first_name": "Desmond", + "last_name": "Achterberg", + "date_of_birth": "1987-06-30", + "email": "d.achterberg@example.test", + "phone": "218-555-0164", + "marital_status": "Single", + "property_street": "908 Norrland Ave", + "property_city": "Duluth", + "property_state": "MN", + "property_zip": "55803", + "year_built": 1954, + "square_feet": 1580, + "construction": "Masonry", + "roof_material": "Asphalt shingle", + "roof_year": 2015, + "occupancy": "Owner-occupied primary residence", + "dogs_on_premises": false, + "lender_name": "Lindqvist Community Bank", + "lender_clause_address": "PO Box 912, Duluth MN 55801", + "loan_number": "LCB-20-77314", + "dwelling_limit_basis": "Estimated replacement cost", + "personal_liability": 300000, + "deductible": 2500, + "effective_date": "2027-04-01" + } +} diff --git a/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s04.intake.json b/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s04.intake.json new file mode 100644 index 0000000000..6195ddf404 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s04.intake.json @@ -0,0 +1,30 @@ +{ + "case_id": "cv-s04", + "facts": { + "first_name": "Philippa", + "last_name": "Ourednik", + "date_of_birth": "1979-02-11", + "email": "pippa.ourednik@example.test", + "phone": "828-555-0108", + "marital_status": "Married", + "spouse_name": "Anselm Ourednik", + "property_street": "17 Sourwood Hollow", + "property_city": "Weaverville", + "property_state": "NC", + "property_zip": "28787", + "year_built": 2006, + "square_feet": 2410, + "construction": "Frame", + "roof_material": "Asphalt shingle", + "roof_year": 2021, + "occupancy": "Owner-occupied primary residence", + "dogs_on_premises": true, + "lender_name": "Ashgrove Mortgage Company", + "lender_clause_address": "PO Box 4477, Asheville NC 28801", + "loan_number": "AMC-339-10284", + "dwelling_limit": 482000, + "personal_liability": 500000, + "deductible": 2500, + "effective_date": "2027-02-14" + } +} diff --git a/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s05.intake.json b/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s05.intake.json new file mode 100644 index 0000000000..0e9be1851c --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s05.intake.json @@ -0,0 +1,29 @@ +{ + "case_id": "cv-s05", + "facts": { + "first_name": "Teodora", + "last_name": "Kallistrom", + "date_of_birth": "1990-10-05", + "email": "teodora.k@example.test", + "phone": "253-555-0186", + "marital_status": "Single", + "property_street": "3302 N Verrall St", + "property_city": "Tacoma", + "property_state": "WA", + "property_zip": "98407", + "year_built": 1931, + "square_feet": 1490, + "construction": "Frame", + "roof_material": "Asphalt shingle", + "roof_year": 2017, + "occupancy": "Owner-occupied primary residence", + "dogs_on_premises": false, + "lender_name": "Brightwater Federal Credit Union", + "lender_clause_address": "PO Box 2210, Tacoma WA 98401", + "loan_number": "BFCU-4471902", + "dwelling_limit": 296000, + "personal_liability": 300000, + "deductible": 1000, + "effective_date": "2027-03-01" + } +} diff --git a/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s06.intake.json b/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s06.intake.json new file mode 100644 index 0000000000..ac2eeceb6c --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s06.intake.json @@ -0,0 +1,29 @@ +{ + "case_id": "cv-s06", + "facts": { + "first_name": "Augustin", + "last_name": "Pelletreau", + "date_of_birth": "1966-07-19", + "email": "a.pelletreau@example.test", + "phone": "208-555-0131", + "marital_status": "Widowed", + "property_street": "1250 W Cottonwood Bend", + "property_city": "Meridian", + "property_state": "ID", + "property_zip": "83646", + "year_built": 2011, + "square_feet": 2680, + "construction": "Masonry veneer", + "roof_material": "Tile", + "roof_year": 2011, + "occupancy": "Owner-occupied primary residence", + "dogs_on_premises": false, + "lender_name": "Tenbury Mortgage Services", + "lender_clause_address": "PO Box 60917, Boise ID 83701", + "loan_number": "TMS-8801-2275", + "dwelling_limit_basis": "Estimated replacement cost", + "personal_liability": 500000, + "deductible": 5000, + "effective_date": "2027-05-10" + } +} diff --git a/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s07.intake.json b/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s07.intake.json new file mode 100644 index 0000000000..19761ce238 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s07.intake.json @@ -0,0 +1,30 @@ +{ + "case_id": "cv-s07", + "facts": { + "first_name": "Cormac", + "last_name": "Brennagh", + "date_of_birth": "1958-03-27", + "email": "cormac.brennagh@example.test", + "phone": "541-555-0150", + "marital_status": "Married", + "spouse_name": "Ilse Brennagh", + "property_street": "88 Obsidian Ridge Dr", + "property_city": "Sisters", + "property_state": "OR", + "property_zip": "97759", + "year_built": 1994, + "square_feet": 2120, + "construction": "Frame", + "roof_material": "Metal", + "roof_year": 2019, + "occupancy": "Owner-occupied secondary or seasonal home", + "dogs_on_premises": false, + "lender_name": "Penhallow Bank of Oregon", + "lender_clause_address": "PO Box 1180, Bend OR 97701", + "loan_number": "PB-90331876", + "dwelling_limit": 425000, + "personal_liability": 300000, + "deductible": 2500, + "effective_date": "2027-06-01" + } +} diff --git a/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s08.intake.json b/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s08.intake.json new file mode 100644 index 0000000000..100d5c831a --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/cases/corvane/cv-s08.intake.json @@ -0,0 +1,31 @@ +{ + "case_id": "cv-s08", + "facts": { + "first_name": "Yusra", + "last_name": "Delacroix-Mbeki", + "date_of_birth": "1984-11-08", + "email": "yusra.dm@example.test", + "phone": "937-555-0123", + "marital_status": "Single", + "property_street": "5120 Fernhollow Pl", + "property_city": "Centerville", + "property_state": "OH", + "property_zip": "45459", + "year_built": 2002, + "square_feet": 2050, + "construction": "Masonry veneer", + "roof_material": "Asphalt shingle", + "roof_year": 2022, + "occupancy": "Owner-occupied primary residence", + "dogs_on_premises": true, + "lender_name": "Quarrystone Home Lending", + "lender_clause_address": "PO Box 81130, Dayton OH 45401", + "loan_number": "QHL-6612034", + "dwelling_limit": 418000, + "personal_liability": 300000, + "deductible": 1000, + "effective_date": "2027-02-28", + "dog_breeds": "Beagle", + "dog_bite_history": "No" + } +} diff --git a/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-dev.intake.json b/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-dev.intake.json new file mode 100644 index 0000000000..f80d354283 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-dev.intake.json @@ -0,0 +1,26 @@ +{ + "case_id": "pb-dev", + "facts": { + "first_name": "Harlan", + "last_name": "Quist", + "date_of_birth": "1977-08-14", + "email": "harlan.quist@example.test", + "garaging_zip": "54806", + "boat_year": 2019, + "boat_make": "Tidelark Boats", + "boat_model": "Shoalrunner 18", + "length_ft": 18, + "engine_type": "Outboard", + "engine_count": "Single", + "total_horsepower": 115, + "agreed_hull_value": 26500, + "storage": "On a trailer at my home", + "navigation_area": "Inland lakes and rivers", + "safety_course": true, + "losses_3yr": 0, + "financing": "Paid in full", + "liability_limit": 300000, + "deductible": 500, + "effective_date": "2027-05-01" + } +} diff --git a/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s01.intake.json b/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s01.intake.json new file mode 100644 index 0000000000..9a1f7a15b7 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s01.intake.json @@ -0,0 +1,27 @@ +{ + "case_id": "pb-s01", + "facts": { + "first_name": "Odalys", + "last_name": "Fenwright", + "date_of_birth": "1983-01-29", + "email": "odalys.fenwright@example.test", + "garaging_zip": "29464", + "boat_year": 2022, + "boat_make": "Osprey Point", + "boat_model": "Marsh Hen 21 CC", + "length_ft": 21, + "engine_type": "Outboard", + "engine_count": "Single", + "total_horsepower": 150, + "agreed_hull_value": 48200, + "storage": "Dry stack or rack storage", + "navigation_area": "Coastal waters within 25 miles of shore", + "safety_course": true, + "losses_3yr": 0, + "financing": "Financed", + "lienholder": "Saltmeadow Marine Finance", + "liability_limit": 300000, + "deductible": 1000, + "effective_date": "2027-04-15" + } +} diff --git a/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s02.intake.json b/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s02.intake.json new file mode 100644 index 0000000000..5b97f24073 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s02.intake.json @@ -0,0 +1,26 @@ +{ + "case_id": "pb-s02", + "facts": { + "first_name": "Bertil", + "last_name": "Szymanowski", + "date_of_birth": "1962-05-06", + "email": "bertil.sz@example.test", + "garaging_zip": "49770", + "boat_year": 2016, + "boat_make": "Halvorsen Craft", + "boat_model": "Northlight 26 Cruiser", + "length_ft": 26, + "engine_type": "Sterndrive (inboard/outboard)", + "engine_count": "Single", + "total_horsepower": 300, + "agreed_hull_value": 61000, + "storage": "Wet slip at a marina", + "navigation_area": "Inland lakes and rivers", + "safety_course": false, + "losses_3yr": 0, + "financing": "Paid in full", + "liability_limit": 500000, + "deductible": 1000, + "effective_date": "2027-05-15" + } +} diff --git a/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s03.intake.json b/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s03.intake.json new file mode 100644 index 0000000000..e53b675c8f --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s03.intake.json @@ -0,0 +1,27 @@ +{ + "case_id": "pb-s03", + "facts": { + "first_name": "Wynne", + "last_name": "Carrowmore", + "date_of_birth": "1970-11-23", + "email": "wynne.carrowmore@example.test", + "garaging_zip": "04609", + "boat_year": 2014, + "boat_make": "Brannock Marine", + "boat_model": "Ledgewatch 22", + "length_ft": 22, + "engine_type": "Inboard", + "engine_count": "Single", + "total_horsepower": 220, + "agreed_hull_value": 34000, + "storage": "On a trailer at my home", + "navigation_area": "Coastal waters within 25 miles of shore", + "safety_course": true, + "losses_3yr": 1, + "financing": "Financed", + "lienholder": "Downeast Harbor Credit Union", + "liability_limit": 300000, + "deductible": 1000, + "effective_date": "2027-06-01" + } +} diff --git a/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s04.intake.json b/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s04.intake.json new file mode 100644 index 0000000000..6087448a2a --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s04.intake.json @@ -0,0 +1,27 @@ +{ + "case_id": "pb-s04", + "facts": { + "first_name": "Leocadia", + "last_name": "Marchetti-Oyelaran", + "date_of_birth": "1988-03-12", + "email": "leocadia.mo@example.test", + "garaging_zip": "33914", + "boat_year": 2021, + "boat_make": "Kestrel Bay Boatworks", + "boat_model": "Gulfline 28 Dual Console", + "length_ft": 28, + "engine_type": "Outboard", + "engine_count": "Twin", + "total_horsepower": 400, + "agreed_hull_value": 142000, + "storage": "Dry stack or rack storage", + "navigation_area": "Coastal waters up to 75 miles offshore", + "safety_course": true, + "losses_3yr": 0, + "financing": "Financed", + "lienholder": "Caloosa Coast Bank", + "liability_limit": 500000, + "deductible": 2500, + "effective_date": "2027-03-20" + } +} diff --git a/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s05.intake.json b/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s05.intake.json new file mode 100644 index 0000000000..f1c4407c22 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s05.intake.json @@ -0,0 +1,26 @@ +{ + "case_id": "pb-s05", + "facts": { + "first_name": "Ansgar", + "last_name": "Velthuis", + "date_of_birth": "1973-07-02", + "email": "ansgar.velthuis@example.test", + "garaging_zip": "56468", + "boat_year": 2018, + "boat_make": "Tidelark Boats", + "boat_model": "Pontoon Lounger 22", + "length_ft": 22, + "engine_type": "Outboard", + "engine_count": "Single", + "total_horsepower": 150, + "agreed_hull_value": 29500, + "storage": "Wet slip at a marina", + "navigation_area": "Inland lakes and rivers", + "safety_course": true, + "losses_3yr": 0, + "financing": "Paid in full", + "liability_limit": 300000, + "deductible": 500, + "effective_date": "2027-05-20" + } +} diff --git a/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s06.intake.json b/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s06.intake.json new file mode 100644 index 0000000000..9207d63874 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s06.intake.json @@ -0,0 +1,26 @@ +{ + "case_id": "pb-s06", + "facts": { + "first_name": "Chiamaka", + "last_name": "Rautio", + "date_of_birth": "1991-09-18", + "email": "chiamaka.rautio@example.test", + "garaging_zip": "97365", + "boat_year": 2020, + "boat_make": "Marlowe Skiffs", + "boat_model": "Yaquina 17 Tiller", + "length_ft": 17, + "engine_type": "Outboard", + "engine_count": "Single", + "total_horsepower": 90, + "hull_value_basis": "Book value (average retail)", + "storage": "On a trailer at my home", + "navigation_area": "Coastal waters within 25 miles of shore", + "safety_course": false, + "losses_3yr": 0, + "financing": "Paid in full", + "liability_limit": 100000, + "deductible": 500, + "effective_date": "2027-04-01" + } +} diff --git a/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s07.intake.json b/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s07.intake.json new file mode 100644 index 0000000000..863ae4b3ce --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s07.intake.json @@ -0,0 +1,26 @@ +{ + "case_id": "pb-s07", + "facts": { + "first_name": "Thaddeus", + "last_name": "Imbrogno", + "date_of_birth": "1965-12-01", + "email": "t.imbrogno@example.test", + "garaging_zip": "02575", + "boat_year": 2023, + "boat_make": "Osprey Point", + "boat_model": "Vineyard 24 Bay", + "length_ft": 24, + "engine_type": "Outboard", + "engine_count": "Single", + "total_horsepower": 250, + "agreed_hull_value": 88500, + "storage": "Dry stack or rack storage", + "navigation_area": "Coastal waters within 25 miles of shore", + "safety_course": true, + "losses_3yr": 0, + "financing": "Paid in full", + "liability_limit": 500000, + "deductible": 1000, + "effective_date": "2027-05-05" + } +} diff --git a/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s08.intake.json b/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s08.intake.json new file mode 100644 index 0000000000..7f28fa7c18 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/cases/pellbrook/pb-s08.intake.json @@ -0,0 +1,26 @@ +{ + "case_id": "pb-s08", + "facts": { + "first_name": "Marguerite", + "last_name": "Oduya-Strand", + "date_of_birth": "1980-04-25", + "email": "marguerite.os@example.test", + "garaging_zip": "33040", + "boat_year": 2017, + "boat_make": "Halvorsen Craft", + "boat_model": "Keys Runner 25", + "length_ft": 25, + "engine_type": "Outboard", + "engine_count": "Single", + "total_horsepower": 300, + "agreed_hull_value": 57500, + "storage": "Wet slip at a marina", + "navigation_area": "Coastal waters within 25 miles of shore", + "safety_course": true, + "losses_3yr": 0, + "financing": "Paid in full", + "liability_limit": 300000, + "deductible": 1000, + "effective_date": "2027-01-10" + } +} diff --git a/packages/flow/benchmark/form_tx_heldout3/common.py b/packages/flow/benchmark/form_tx_heldout3/common.py new file mode 100644 index 0000000000..82a02a14a1 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/common.py @@ -0,0 +1,298 @@ +"""Shared HTTP plumbing for the held-out carrier quote portals. + +Every portal is a ``BasePortal`` subclass served by a stdlib +``ThreadingHTTPServer``. State lives on the portal instance (never in module +globals), so several portals or several copies of one portal can run in one +process. + +Test-only endpoints, present on every portal: + +* ``GET /__oracle/submissions`` every stored submission, in order. +* ``POST /__oracle/reset`` drop drafts, sessions, submissions, case. +* ``POST /__oracle/load_case`` ``{"case_id": ...}``: reset, then configure + the portal for that case (prior policy on file, session expiry, ...). + +Each stored submission carries ``case_id``, ``submitted_at`` (UTC ISO 8601), +``submit_seq`` (1-based order of this submission since the last reset) and +``submit_count`` (how many submissions the portal holds at the time of the +read). Repeated submissions are all stored; nothing is deduplicated. +""" + +from __future__ import annotations + +import html +import json +import secrets +import threading +import time +from dataclasses import dataclass, field +from datetime import datetime, timezone +from http.cookies import SimpleCookie +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from typing import Any, Callable +from urllib.parse import parse_qs, urlsplit + +HERE = Path(__file__).resolve().parent +CREDENTIALS = json.loads((HERE / "fixtures" / "portal_logins.json").read_text()) + + +def esc(value: Any) -> str: + return html.escape("" if value is None else str(value), quote=True) + + +@dataclass +class Request: + method: str + path: str + query: dict[str, str] + form: dict[str, str] + form_multi: dict[str, list[str]] + json: Any + cookies: dict[str, str] + + +@dataclass +class Response: + status: int = 200 + body: bytes = b"" + content_type: str = "text/html; charset=utf-8" + headers: list[tuple[str, str]] = field(default_factory=list) + + @classmethod + def html(cls, text: str, status: int = 200) -> "Response": + return cls(status, text.encode("utf-8")) + + @classmethod + def json_(cls, obj: Any, status: int = 200) -> "Response": + return cls(status, json.dumps(obj).encode("utf-8"), "application/json") + + @classmethod + def redirect(cls, location: str) -> "Response": + return cls(303, b"", headers=[("Location", location)]) + + def set_cookie(self, name: str, value: str) -> "Response": + self.headers.append(("Set-Cookie", f"{name}={value}; Path=/; HttpOnly; SameSite=Lax")) + return self + + def clear_cookie(self, name: str) -> "Response": + self.headers.append(("Set-Cookie", f"{name}=; Path=/; Max-Age=0")) + return self + + +class BasePortal: + """One carrier portal. Subclasses implement ``route`` and ``fresh_draft``.""" + + portal_id = "base" + cookie = "sid" + + def __init__(self) -> None: + self.lock = threading.RLock() + self.creds = CREDENTIALS[self.portal_id] + self.reset() + + # ---- state ------------------------------------------------------- + def reset(self) -> None: + with self.lock: + self.case_id: str | None = None + self.config: dict[str, Any] = {} + self.sessions: set[str] = set() + self.submissions: list[dict[str, Any]] = [] + self.fired: set[str] = set() + self.draft: dict[str, Any] = self.fresh_draft() + self.quote_seq = 0 + + def load_case(self, case_id: str) -> bool: + from .case_defs import portal_config + + cfg = portal_config(self.portal_id, case_id) + if cfg is None: + return False + with self.lock: + self.reset() + self.case_id = case_id + self.config = cfg + self.draft = self.fresh_draft() + return True + + def fresh_draft(self) -> dict[str, Any]: + return {} + + def store_submission(self, record: dict[str, Any]) -> dict[str, Any]: + with self.lock: + rec = dict(record) + rec["case_id"] = self.case_id + rec["submitted_at"] = datetime.now(timezone.utc).isoformat(timespec="seconds") + rec["submit_seq"] = len(self.submissions) + 1 + self.submissions.append(rec) + return rec + + def fire_once(self, event: str) -> bool: + """True the first time ``event`` happens after a case load, if configured.""" + with self.lock: + if event in self.fired: + return False + if self.config.get("expire_on") != event: + return False + self.fired.add(event) + return True + + # ---- sessions ---------------------------------------------------- + def new_session(self) -> str: + sid = secrets.token_hex(12) + with self.lock: + self.sessions.add(sid) + return sid + + def has_session(self, req: Request) -> bool: + return req.cookies.get(self.cookie, "") in self.sessions + + def drop_sessions(self) -> None: + with self.lock: + self.sessions.clear() + + def check_login(self, username: str, password: str) -> bool: + return username.strip() == self.creds["username"] and password == self.creds["password"] + + # ---- dispatch ---------------------------------------------------- + def dispatch(self, req: Request) -> Response: + if req.path.startswith("/__oracle/"): + return self.oracle(req) + try: + return self.route(req) + except Exception as exc: # keep the server alive; surface the error + return Response.html(f"

Server error

{esc(repr(exc))}
", 500) + + def oracle(self, req: Request) -> Response: + if req.path == "/__oracle/submissions" and req.method == "GET": + with self.lock: + n = len(self.submissions) + out = [dict(r, submit_count=n) for r in self.submissions] + return Response.json_(out) + if req.path == "/__oracle/reset" and req.method == "POST": + self.reset() + return Response.json_({"ok": True}) + if req.path == "/__oracle/load_case" and req.method == "POST": + case_id = (req.json or {}).get("case_id") or req.form.get("case_id", "") + if not self.load_case(case_id): + return Response.json_({"ok": False, "error": f"unknown case {case_id!r}"}, 404) + return Response.json_({"ok": True, "case_id": case_id}) + return Response.json_({"error": "not found"}, 404) + + def route(self, req: Request) -> Response: # pragma: no cover - abstract + raise NotImplementedError + + +def _handler_for(portal: BasePortal) -> type[BaseHTTPRequestHandler]: + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def _go(self, method: str) -> None: + parts = urlsplit(self.path) + query = {k: v[-1] for k, v in parse_qs(parts.query, keep_blank_values=True).items()} + length = int(self.headers.get("Content-Length") or 0) + raw = self.rfile.read(length) if length else b"" + ctype = self.headers.get("Content-Type", "") + form_multi: dict[str, list[str]] = {} + body_json: Any = None + if raw and "json" in ctype: + try: + body_json = json.loads(raw.decode("utf-8")) + except ValueError: + body_json = None + elif raw: + form_multi = parse_qs(raw.decode("utf-8"), keep_blank_values=True) + cookies: dict[str, str] = {} + if self.headers.get("Cookie"): + jar = SimpleCookie() + try: + jar.load(self.headers["Cookie"]) + except Exception: + pass + cookies = {k: m.value for k, m in jar.items()} + req = Request( + method, + parts.path, + query, + {k: v[-1] for k, v in form_multi.items()}, + form_multi, + body_json, + cookies, + ) + resp = portal.dispatch(req) + self.send_response(resp.status) + self.send_header("Content-Type", resp.content_type) + self.send_header("Content-Length", str(len(resp.body))) + self.send_header("Cache-Control", "no-store") + for k, v in resp.headers: + self.send_header(k, v) + self.end_headers() + if method != "HEAD": + self.wfile.write(resp.body) + + def do_GET(self) -> None: # noqa: N802 + self._go("GET") + + def do_POST(self) -> None: # noqa: N802 + self._go("POST") + + def do_PUT(self) -> None: # noqa: N802 + self._go("PUT") + + def log_message(self, *args: Any) -> None: + pass + + return Handler + + +def serve(portal: BasePortal, host: str = "127.0.0.1", port: int = 0) -> tuple[ThreadingHTTPServer, str]: + server = ThreadingHTTPServer((host, port), _handler_for(portal)) + server.daemon_threads = True + server.portal = portal # type: ignore[attr-defined] + threading.Thread(target=server.serve_forever, daemon=True, name=f"{portal.portal_id}-http").start() + return server, f"http://{host}:{server.server_port}" + + +def slow(seconds: float) -> None: + time.sleep(seconds) + + +@dataclass +class PortalSpec: + name: str + title: str + description: str + factory: Callable[[], BasePortal] + entry_path: str + login: dict[str, Any] + cases: list[str] + dev_case: str + intake_vocabulary: dict[str, Any] = field(default_factory=dict) + + def start(self, host: str = "127.0.0.1", port: int = 0) -> tuple[ThreadingHTTPServer, str]: + return serve(self.factory(), host, port) + + +def money(n: int) -> str: + return f"${n:,}" + + +def parse_int(text: Any) -> int | None: + s = str(text or "").replace(",", "").replace("$", "").strip() + if not s: + return None + try: + return int(float(s)) + except ValueError: + return None + + +def parse_date(text: str) -> str: + """Accept ISO ``YYYY-MM-DD`` or ``MM/DD/YYYY``; return ISO or ''.""" + s = (text or "").strip() + try: + if "/" in s: + return datetime.strptime(s, "%m/%d/%Y").date().isoformat() + return datetime.strptime(s, "%Y-%m-%d").date().isoformat() + except ValueError: + return "" diff --git a/packages/flow/benchmark/form_tx_heldout3/corvane.py b/packages/flow/benchmark/form_tx_heldout3/corvane.py new file mode 100644 index 0000000000..27e8a7b8c0 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/corvane.py @@ -0,0 +1,549 @@ +"""Corvane Mutual: homeowners (HO-3) quote wizard for appointed agents. + +A single-page wizard rendered in the browser from a JSON step schema, with a +left-hand step list. Each step saves through ``PUT /api/quote/step/``. +Applicant details can come prefilled from an existing Corvane customer +record, and dwelling details are filled in from public property records once +the address is saved. Lender selection is a type-ahead over a lender +directory; the Coverage A limit has a replacement-cost estimator dialog. An +expired session sends the agent back to the sign-in page, and the quote is +restored from its last saved version. The review step lists every stored +answer; ``Request quote`` stores the submission and shows the quote. +""" + +from __future__ import annotations + +import json +from typing import Any +from urllib.parse import quote as urlquote + +from .case_defs import ( + CV_CONSTRUCTION, + CV_FIELDS, + CV_LENDERS, + CV_OCCUPANCY, + CV_ROOF, + CV_STATES, +) +from .common import BasePortal, Request, Response, esc, money, parse_date, parse_int +from .estimators import replacement_cost + +RECORD_FIELDS = list(CV_FIELDS) + +LIABILITY = [100000, 300000, 500000] +DEDUCTIBLES = [1000, 2500, 5000] + + +def _opts(values: list[Any], fmt=str) -> list[list[str]]: + return [[str(v), fmt(v)] for v in values] + + +STEPS: list[dict[str, Any]] = [ + { + "n": 1, "title": "Applicant and property", + "fields": [ + {"name": "first_name", "label": "First name", "kind": "text"}, + {"name": "last_name", "label": "Last name", "kind": "text"}, + {"name": "date_of_birth", "label": "Date of birth", "kind": "date"}, + {"name": "email", "label": "Email", "kind": "text"}, + {"name": "phone", "label": "Phone", "kind": "text"}, + {"name": "co_applicant_name", "label": "Co-applicant full name", "kind": "text", "optional": True, + "help": "Spouse or other person on the deed. Leave blank if none."}, + {"name": "property_street", "label": "Property street address", "kind": "text"}, + {"name": "property_city", "label": "City", "kind": "text"}, + {"name": "property_state", "label": "State", "kind": "select", "options": _opts(CV_STATES)}, + {"name": "property_zip", "label": "ZIP code", "kind": "text"}, + ], + }, + { + "n": 2, "title": "Dwelling", + "fields": [ + {"name": "year_built", "label": "Year built", "kind": "int"}, + {"name": "square_feet", "label": "Finished living area (sq ft)", "kind": "int"}, + {"name": "construction", "label": "Construction type", "kind": "select", + "options": _opts(CV_CONSTRUCTION)}, + {"name": "roof_material", "label": "Roof material", "kind": "select", "options": _opts(CV_ROOF)}, + {"name": "roof_year", "label": "Year roof was installed or last replaced", "kind": "int"}, + ], + }, + { + "n": 3, "title": "Household", + "fields": [ + {"name": "occupancy", "label": "Occupancy", "kind": "radio", "options": _opts(CV_OCCUPANCY)}, + {"name": "dogs", "label": "Are any dogs kept at this address?", "kind": "radio", + "options": [["Yes", "Yes"], ["No", "No"]]}, + {"name": "dog_breeds", "label": "Breed of each dog", "kind": "text", "optional": True, + "show_if": ["dogs", "Yes"], "help": "List every dog, for example: Beagle, Boxer mix."}, + {"name": "dog_bite_history", + "label": "Has any dog at this address ever bitten a person or another animal?", + "kind": "radio", "options": [["Yes", "Yes"], ["No", "No"]], "show_if": ["dogs", "Yes"]}, + ], + }, + { + "n": 4, "title": "Lender and coverage", + "fields": [ + {"name": "mortgagee", "label": "Mortgagee (lender)", "kind": "typeahead", + "help": "Type the lender's name and pick its mortgagee clause from the directory."}, + {"name": "loan_number", "label": "Loan number", "kind": "text"}, + {"name": "dwelling_limit", "label": "Dwelling (Coverage A) limit", "kind": "money", + "estimator": True}, + {"name": "personal_liability", "label": "Personal liability", "kind": "select", + "options": _opts(LIABILITY, money)}, + {"name": "deductible", "label": "All-perils deductible", "kind": "select", + "options": _opts(DEDUCTIBLES, money)}, + {"name": "effective_date", "label": "Policy effective date", "kind": "date"}, + ], + }, +] +FIELD_STEP = {f["name"]: s["n"] for s in STEPS for f in s["fields"]} +FIELD_DEF = {f["name"]: f for s in STEPS for f in s["fields"]} +STEP_FIELDS = {s["n"]: [f["name"] for f in s["fields"]] for s in STEPS} + +DEFAULTS: dict[str, Any] = {name: "" for name in RECORD_FIELDS} +DEFAULTS.update({"occupancy": CV_OCCUPANCY[0], "dogs": "No", "personal_liability": "300000", + "deductible": "1000"}) + + +def _display(name: str, value: Any) -> str: + if value in ("", None): + return "—" + kind = FIELD_DEF[name]["kind"] + if kind == "date": + iso = parse_date(str(value)) + return f"{iso[5:7]}/{iso[8:10]}/{iso[:4]}" if iso else str(value) + if kind == "money" or name in ("personal_liability", "deductible"): + n = parse_int(value) + return money(n) if n is not None else str(value) + return str(value) + + +CSS = """ +:root{--ink:#1b2a33;--muted:#5d6b73;--line:#d5dde1;--brand:#0f5e63;--bg:#f3f6f7;--warn:#fff6d8;--err:#a3261b} +*{box-sizing:border-box}body{margin:0;font:15px/1.45 system-ui,Segoe UI,Arial,sans-serif;color:var(--ink);background:var(--bg)} +header{background:var(--brand);color:#fff;padding:10px 20px;display:flex;justify-content:space-between;align-items:center} +header b{font-size:18px;letter-spacing:.02em} +.wrap{display:flex;max-width:1080px;margin:18px auto;gap:18px;padding:0 12px} +nav.steps{width:220px;flex:none}nav.steps ol{list-style:none;margin:0;padding:0} +nav.steps li{padding:9px 12px;border-left:4px solid var(--line);color:var(--muted)} +nav.steps li.cur{border-color:var(--brand);color:var(--ink);font-weight:600;background:#fff} +nav.steps li.done{color:var(--ink)} +main{flex:1;background:#fff;border:1px solid var(--line);border-radius:6px;padding:20px 24px} +h1{font-size:20px;margin:0 0 14px}.fld{margin:0 0 14px}.fld>label,.fld>.lbl{display:block;font-weight:600;margin-bottom:4px} +.fld input[type=text]{width:100%;max-width:440px;padding:7px 9px;border:1px solid #9fb0b8;border-radius:4px;font:inherit} +.fld select{padding:6px 8px;font:inherit;min-width:220px}.help{color:var(--muted);font-size:13px;margin-top:3px} +.radio{display:block;margin:3px 0}.err{color:var(--err);font-size:13px}.banner{background:var(--warn);border:1px solid #e9d68c;padding:9px 12px;border-radius:4px;margin-bottom:14px} +button{font:inherit;padding:8px 16px;border-radius:4px;border:1px solid var(--brand);background:var(--brand);color:#fff;cursor:pointer} +button.sec{background:#fff;color:var(--brand)}.row{display:flex;gap:8px;align-items:center} +.ta{position:relative;max-width:560px}.ta ul{position:absolute;z-index:5;left:0;right:0;top:100%;margin:2px 0 0;padding:0;list-style:none;background:#fff;border:1px solid #9fb0b8;border-radius:4px;max-height:220px;overflow:auto} +.ta li{padding:7px 9px;cursor:pointer;font-size:14px}.ta li:hover,.ta li[aria-selected=true]{background:#e4f0f1} +table.sum{border-collapse:collapse;width:100%}table.sum th,table.sum td{border-bottom:1px solid var(--line);padding:6px 8px;text-align:left;vertical-align:top} +table.sum th{width:45%;font-weight:600}dialog{border:1px solid var(--line);border-radius:6px;padding:18px 22px;max-width:460px} +dialog table td{padding:4px 10px 4px 0}.tot td{font-weight:700;border-top:1px solid var(--line)} +""" + +APP_JS = r""" +const S = JSON.parse(document.getElementById('schema').textContent); +let state = null, cur = 1, busy = false; +const $ = (s, r=document) => r.querySelector(s); +const h = (s) => String(s ?? '').replace(/[&<>"]/g, c => ({'&':'&','<':'<','>':'>','"':'"'}[c])); +function stepFromUrl(){ const p = new URLSearchParams(location.search).get('step'); return p ? parseInt(p,10) : 0; } +async function api(method, url, body){ + const r = await fetch(url, {method, headers:{'Content-Type':'application/json'}, body: body ? JSON.stringify(body) : undefined}); + if (r.status === 401){ location.href = '/login?expired=1&next=' + encodeURIComponent('/quote?step=' + cur); throw new Error('expired'); } + return r.json(); +} +async function load(){ state = await api('GET', '/api/quote'); cur = stepFromUrl() || state.resume_step || 1; render(); } +function nav(){ + const items = S.steps.map(s => `
  • ${s.n}. ${h(s.title)}
  • `); + items.push(`
  • 5. Review
  • `); + $('#steps').innerHTML = '
      ' + items.join('') + '
    '; +} +function fieldHtml(f, v){ + const id = 'f-' + f.name; let ctl = ''; + if (f.kind === 'select'){ + ctl = `'; + return `${ctl}`; + } + if (f.kind === 'radio'){ + ctl = f.options.map((o,i) => ``).join(''); + return `
    ${h(f.label)}
    ${ctl}
    `; + } + if (f.kind === 'typeahead'){ + return `
    `; + } + const ph = f.kind === 'date' ? ' placeholder="MM/DD/YYYY"' : ''; + ctl = ``; + if (f.estimator) ctl = `
    ${ctl}
    `; + return `${ctl}`; +} +function render(){ + nav(); history.replaceState(null, '', '/quote?step=' + cur); + const banners = (state.banners[cur] || []).concat(state.banners.all || []); + let out = banners.map(b => ``).join(''); + if (cur === 5) return renderReview(out); + const st = S.steps[cur-1]; + out += `

    ${h(st.title)}

    `; + for (const f of st.fields){ + const v = state.draft[f.name] ?? ''; + out += `
    ` + + fieldHtml(f, v) + (f.help ? `
    ${h(f.help)}
    ` : '') + `
    `; + } + out += `
    ${cur>1?'':''}
    `; + $('#app').innerHTML = out; $('#app').dataset.step = cur; $('#app').dataset.ready = String(Date.now()); + wire(); +} +function applyShowIf(){ + document.querySelectorAll('[data-show-if]').forEach(el => { + const [k, want] = el.dataset.showIf.split('='); + const sel = document.querySelector(`input[name="${k}"]:checked`); + el.hidden = !(sel && sel.value === want); + }); +} +function wire(){ + applyShowIf(); + document.querySelectorAll('input[type=radio]').forEach(r => r.addEventListener('change', applyShowIf)); + $('#stepform').addEventListener('submit', e => { e.preventDefault(); save(); }); + if ($('#back')) $('#back').onclick = () => { cur -= 1; render(); }; + const ta = $('input[role=combobox]'); if (ta) wireTypeahead(ta); + if ($('#est-open')) $('#est-open').onclick = openEstimator; +} +function wireTypeahead(inp){ + const list = document.getElementById(inp.id + '-list'); let timer = null; + inp.addEventListener('input', () => { + clearTimeout(timer); inp.dataset.picked = ''; + timer = setTimeout(async () => { + const q = inp.value.trim(); if (q.length < 3){ list.hidden = true; return; } + const res = await api('GET', '/api/lenders?q=' + encodeURIComponent(q)); + list.innerHTML = res.matches.map((m,i) => `
  • ${h(m)}
  • `).join('') || + ''; + list.hidden = false; inp.setAttribute('aria-expanded', 'true'); + list.querySelectorAll('[role=option]').forEach(li => li.addEventListener('click', () => { + inp.value = li.textContent; inp.dataset.picked = '1'; list.hidden = true; inp.setAttribute('aria-expanded','false'); + })); + }, 250); + }); +} +async function openEstimator(){ + const est = await api('GET', '/api/estimate'); + const d = $('#estdlg'); + if (est.error){ d.innerHTML = `

    ${h(est.error)}

    `; } + else { + d.innerHTML = `

    Replacement cost estimate

    +

    Based on ${h(est.square_feet)} sq ft, ${h(est.construction)} construction (from the Dwelling step).

    + + +
    Base rebuild cost${h(est.base_display)}
    Code and debris allowance (8%)${h(est.allowance_display)}
    Estimated replacement cost${h(est.total_display)}
    +
    `; + $('#est-use').onclick = () => { $('#f-dwelling_limit').value = est.apply_display; d.close(); }; + } + $('#est-close').onclick = () => d.close(); + d.showModal(); +} +function collect(){ + const vals = {}; + for (const f of S.steps[cur-1].fields){ + const box = document.querySelector(`.fld[data-name="${f.name}"]`); + if (box.hidden){ vals[f.name] = ''; continue; } + if (f.kind === 'radio'){ const c = document.querySelector(`input[name="${f.name}"]:checked`); vals[f.name] = c ? c.value : ''; } + else vals[f.name] = document.getElementById('f-' + f.name).value; + } + return vals; +} +async function save(){ + if (busy) return; busy = true; + try { + document.querySelectorAll('[data-err]').forEach(e => e.textContent = ''); + const res = await api('PUT', '/api/quote/step/' + cur, {values: collect()}); + if (res.errors){ for (const [k,m] of Object.entries(res.errors)){ const e = document.querySelector(`[data-err="${k}"]`); if (e) e.textContent = m; } $('#app').dataset.errors = '1'; return; } + state = res.state; cur = res.next_step; render(); + } finally { busy = false; } +} +function renderReview(out){ + out += '

    Review

    Check every answer before you request the quote.

    '; + for (const st of S.steps){ + out += `

    ${h(st.title)}

    `; + for (const f of st.fields){ + if (f.show_if && state.draft[f.show_if[0]] !== f.show_if[1]) continue; + out += ``; + } + out += '
    ${h(f.label)}${h(state.display[f.name])}
    '; + } + out += '
    '; + $('#app').innerHTML = out; $('#app').dataset.step = 5; $('#app').dataset.ready = String(Date.now()); + document.querySelectorAll('[data-edit]').forEach(b => b.onclick = () => { cur = parseInt(b.dataset.edit,10); render(); }); + $('#submit').onclick = async () => { + if (busy) return; busy = true; + try { const res = await api('POST', '/api/quote/submit', {}); + if (res.error){ $('#submit-err').textContent = res.error; return; } + location.href = '/quote/result/' + res.quote_ref; + } finally { busy = false; } + }; +} +load(); +""" + + +def page(title: str, body: str, user: str = "") -> str: + who = f"Agency {esc(user)}" if user else "" + return ( + f"{esc(title)}" + f"
    Corvane MutualAgentLink · Homeowners" + f"{who}
    {body}" + ) + + +class Corvane(BasePortal): + portal_id = "corvane" + cookie = "cvsid" + + def fresh_draft(self) -> dict[str, Any]: + d: dict[str, Any] = dict(DEFAULTS) + cfg = getattr(self, "config", {}) or {} + prior = cfg.get("prior_record") + if prior: + for k, v in prior.items(): + if k in d: + d[k] = v + return d + + def reset(self) -> None: + super().reset() + with self.lock: + self.saved: list[int] = [] + self.records_applied = False + self.restored = False + self.quotes: dict[str, dict[str, Any]] = {} + + def load_case(self, case_id: str) -> bool: + ok = super().load_case(case_id) + if ok: + with self.lock: + self.saved = [] + self.records_applied = False + self.restored = False + return ok + + # ---- helpers ---------------------------------------------------- + def _banners(self) -> dict[Any, list[str]]: + out: dict[Any, list[str]] = {} + prior = self.config.get("prior_record") + if prior: + out[1] = [f"Some answers were filled in from an existing Corvane record ({prior['source']}). " + "Review them before you continue."] + if self.records_applied: + out[2] = ["Dwelling details were filled in from public property records."] + if self.restored: + out["all"] = ["Your session ended. We restored this quote from its last saved version."] + return out + + def _state(self) -> dict[str, Any]: + d = self.draft + resume = next((n for n in (1, 2, 3, 4) if n not in self.saved), 5) + return { + "draft": {k: (_display(k, d.get(k)) if FIELD_DEF[k]["kind"] == "date" and d.get(k) else d.get(k, "")) + for k in RECORD_FIELDS}, + "display": {k: _display(k, d.get(k, "")) for k in RECORD_FIELDS}, + "saved": sorted(self.saved), + "banners": self._banners(), + "resume_step": resume, + } + + def _apply_public_record(self) -> None: + pr = self.config.get("public_record") or {} + for k, v in pr.items(): + self.draft[k] = str(v) + self.records_applied = True + + def _validate(self, n: int, vals: dict[str, str]) -> tuple[dict[str, Any], dict[str, str]]: + clean: dict[str, Any] = {} + errors: dict[str, str] = {} + for name in STEP_FIELDS[n]: + f = FIELD_DEF[name] + raw = str(vals.get(name, "") or "").strip() + if f.get("show_if"): + dep = str(vals.get(f["show_if"][0], "")) + if dep != f["show_if"][1]: + clean[name] = "" + continue + if not raw: + if not f.get("optional"): + errors[name] = f"{f['label']} is required." + clean[name] = "" + continue + kind = f["kind"] + if kind == "date": + iso = parse_date(raw) + if not iso: + errors[name] = "Enter the date as MM/DD/YYYY." + clean[name] = iso or raw + elif kind in ("int", "money"): + v = parse_int(raw) + if v is None or v < 0: + errors[name] = "Enter a whole number." + clean[name] = str(v) if v is not None else raw + elif kind in ("select", "radio"): + if raw not in [o[0] for o in f["options"]]: + errors[name] = "Choose one of the options." + clean[name] = raw + elif kind == "typeahead": + if raw not in CV_LENDERS: + errors[name] = "Pick the lender's mortgagee clause from the directory." + clean[name] = raw + else: + clean[name] = raw + if n == 2 and not errors: + yb, ry = parse_int(clean["year_built"]), parse_int(clean["roof_year"]) + if yb and ry and ry < yb: + errors["roof_year"] = "The roof cannot be older than the house." + return clean, errors + + def _revert_after_expiry(self) -> None: + """Session ended: restore the version saved when the quote was created (after step 1).""" + for n in (2, 3, 4): + for name in STEP_FIELDS[n]: + self.draft[name] = DEFAULTS[name] + self._apply_public_record() + self.saved = [1, 2, 3] + self.restored = True + + def _record(self) -> dict[str, Any]: + d = self.draft + rec: dict[str, Any] = {} + for k in RECORD_FIELDS: + v = d.get(k, "") + kind = FIELD_DEF[k]["kind"] + if k == "dogs": + rec[k] = v == "Yes" + elif kind in ("int", "money") or k in ("personal_liability", "deductible"): + rec[k] = parse_int(v) + else: + rec[k] = v + return rec + + def _premium(self, rec: dict[str, Any]) -> int: + base = (rec["dwelling_limit"] or 0) * 0.0031 + base *= {1000: 1.0, 2500: 0.9, 5000: 0.82}.get(rec["deductible"] or 1000, 1.0) + base += {100000: 0, 300000: 28, 500000: 52}.get(rec["personal_liability"] or 0, 0) + if rec["dogs"]: + base += 35 + return int(round(base)) + + # ---- routes ----------------------------------------------------- + def route(self, req: Request) -> Response: + p = req.path + if p in ("/", "/quote/start"): + return Response.redirect("/quote") + if p == "/login": + return self.login(req) + if p == "/logout": + return Response.redirect("/login").clear_cookie(self.cookie) + if p.startswith("/api/"): + if not self.has_session(req): + return Response.json_({"error": "session expired"}, 401) + return self.api(req) + if not self.has_session(req): + target = p + ("?" + "&".join(f"{k}={v}" for k, v in req.query.items()) if req.query else "") + return Response.redirect("/login?next=" + urlquote(target, safe="")) + if p == "/quote": + schema = json.dumps({"steps": STEPS}).replace("" + "

    Loading…

    " + f"" + ) + return Response.html(page("Homeowners quote – Corvane AgentLink", body, self.creds["username"])) + if p.startswith("/quote/result/"): + return self.result(p.rsplit("/", 1)[-1]) + return Response.html(page("Not found", "

    Not found

    "), 404) + + def login(self, req: Request) -> Response: + nxt = req.query.get("next") or req.form.get("next") or "/quote" + if not nxt.startswith("/"): + nxt = "/quote" + msg = "" + if req.method == "POST": + if self.check_login(req.form.get("username", ""), req.form.get("password", "")): + sid = self.new_session() + return Response.redirect(nxt).set_cookie(self.cookie, sid) + msg = "" + elif req.query.get("expired"): + msg = "" + body = ( + "

    Agent sign-in

    " + f"{msg}
    " + "
    " + "
    " + ) + return Response.html(page("Sign in – Corvane AgentLink", body)) + + def api(self, req: Request) -> Response: + p = req.path + with self.lock: + if p == "/api/quote" and req.method == "GET": + return Response.json_(self._state()) + if p.startswith("/api/quote/step/") and req.method == "PUT": + n = parse_int(p.rsplit("/", 1)[-1]) or 0 + if n not in STEP_FIELDS: + return Response.json_({"error": "bad step"}, 400) + if n == 4 and self.fire_once("save_step4"): + self.drop_sessions() + self._revert_after_expiry() + return Response.json_({"error": "session expired"}, 401) + vals = (req.json or {}).get("values", {}) + clean, errors = self._validate(n, vals) + if errors: + return Response.json_({"errors": errors}) + self.draft.update(clean) + if n not in self.saved: + self.saved.append(n) + if n == 1 and not self.records_applied: + self._apply_public_record() + return Response.json_({"ok": True, "state": self._state(), "next_step": n + 1}) + if p == "/api/lenders": + q = req.query.get("q", "").strip().casefold() + matches = [c for c in CV_LENDERS if q and q in c.split(" ISAOA")[0].casefold()] + return Response.json_({"matches": matches}) + if p == "/api/estimate": + sq = parse_int(self.draft.get("square_feet")) + cons = self.draft.get("construction") or "" + if 2 not in self.saved or not sq or not cons: + return Response.json_({"error": "Save the Dwelling step first."}) + est = replacement_cost(sq, cons) + apply_v = est["base"] if self.config.get("estimator_applies") == "base" else est["total"] + return Response.json_({ + "square_feet": f"{sq:,}", "construction": cons, + "base_display": money(est["base"]), "allowance_display": money(est["allowance"]), + "total_display": money(est["total"]), "total": est["total"], + "apply_display": f"{apply_v:,}", + }) + if p == "/api/quote/submit" and req.method == "POST": + missing = [n for n in (1, 2, 3, 4) if n not in self.saved] + if missing: + return Response.json_({"error": f"Complete step {missing[0]} first."}) + rec = self._record() + self.quote_seq += 1 + rec["quote_ref"] = f"CVH-Q{27000 + self.quote_seq:06d}" + rec["annual_premium"] = self._premium(rec) + stored = self.store_submission(rec) + self.quotes[rec["quote_ref"]] = stored + return Response.json_({"ok": True, "quote_ref": rec["quote_ref"]}) + return Response.json_({"error": "not found"}, 404) + + def result(self, ref: str) -> Response: + rec = self.quotes.get(ref) + if not rec: + return Response.html(page("Not found", "

    Quote not found

    "), 404) + rows = "".join( + f"{esc(FIELD_DEF[k]['label'])}" + f"{esc(_display(k, 'Yes' if rec[k] is True else 'No' if rec[k] is False else rec[k]))}" + for k in RECORD_FIELDS + ) + body = ( + "

    Quote ready

    " + f"

    Quote reference {esc(ref)} · " + f"Estimated annual premium {esc(money(rec['annual_premium']))}

    " + f"{rows}
    " + ) + return Response.html(page(f"Quote {ref} – Corvane AgentLink", body, self.creds["username"])) diff --git a/packages/flow/benchmark/form_tx_heldout3/drivers/__init__.py b/packages/flow/benchmark/form_tx_heldout3/drivers/__init__.py new file mode 100644 index 0000000000..3315e41a79 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/drivers/__init__.py @@ -0,0 +1 @@ +"""Per-portal Playwright drivers for the reference fillers.""" diff --git a/packages/flow/benchmark/form_tx_heldout3/drivers/base.py b/packages/flow/benchmark/form_tx_heldout3/drivers/base.py new file mode 100644 index 0000000000..57c8d95551 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/drivers/base.py @@ -0,0 +1,191 @@ +"""Shared pieces of the two reference fillers. + +A *source* decides what to type; a per-portal *driver* knows how to move +through that portal's pages and calls the source for every visible field, +keyed by the field's visible label text. + +* ``ReferenceSource`` (careful human): values come from the answer key's + expected record and operator script; it checks every value it relies on + from the screen (estimator figure, type-ahead option) is actually shown. +* ``NaiveSource`` (unguarded agent): values come from the intake through a + label-to-intake-key table; no fact means keep the prefill, or take the + first option when the control is empty; first type-ahead suggestion; + estimator figure accepted as handed back; no summary check. +""" + +from __future__ import annotations + +import json +import re +import urllib.request +from datetime import date +from pathlib import Path +from typing import Any, Callable + +HERE = Path(__file__).resolve().parent.parent + + +def norm(s: Any) -> str: + return re.sub(r"\s+", " ", str(s if s is not None else "")).strip().casefold() + + +def digits(s: Any) -> str: + return re.sub(r"\D", "", str(s if s is not None else "")) + + +def us_date(iso: str) -> str: + d = date.fromisoformat(iso) + return f"{d.month:02d}/{d.day:02d}/{d.year}" + + +def load_intake(portal: str, case_id: str) -> dict[str, Any]: + return json.loads((HERE / "cases" / portal / f"{case_id}.intake.json").read_text())["facts"] + + +def option_matches(want: str, value: str, text: str) -> bool: + w = norm(want) + if not w: + return False + if w == norm(value) or w == norm(text): + return True + dw = digits(want) + if dw and re.fullmatch(r"[\s$,\d]+", want) and (dw == digits(value) or dw == digits(text)): + return True + return False + + +class DriverError(RuntimeError): + pass + + +class Source: + kind = "base" + fallback_first = False + restart_after_relogin = False + + def __init__(self, portal: str, case_id: str, creds: dict[str, str]) -> None: + self.portal = portal + self.case_id = case_id + self.creds = creds + self.labels_seen: set[str] = set() + self.events: list[str] = [] + + def note(self, label: str) -> None: + self.labels_seen.add(norm(label)) + + def get(self, label: str) -> str | None: + raise NotImplementedError + + def pick(self, label: str, options: list[str], want: str | None) -> int: + raise NotImplementedError + + def estimator(self, label: str, displayed: int, current: str) -> str | None: + return None + + def wants(self, label: str) -> bool: + """Whether the source has an opinion about ``label`` at all.""" + return self.get(label) is not None + + +Formatter = Callable[[Any], str] + + +def fmt_plain(v: Any) -> str: + if isinstance(v, bool): + return "Yes" if v else "No" + return str(v) + + +def fmt_date(v: Any) -> str: + return us_date(str(v)) + + +class NaiveSource(Source): + kind = "naive" + fallback_first = True + + def __init__(self, portal: str, case_id: str, creds: dict[str, str], label_map: dict[str, Any]) -> None: + super().__init__(portal, case_id, creds) + self.facts = load_intake(portal, case_id) + self.label_map = {norm(k): v for k, v in label_map.items()} + + def _lookup(self, label: str) -> Any: + return self.label_map.get(norm(label)) + + def get(self, label: str) -> str | None: + entry = self._lookup(label) + if entry is None: + return None + key, fmt = entry if isinstance(entry, tuple) else (entry, fmt_plain) + if key not in self.facts: + return None + return fmt(self.facts[key]) + + def pick(self, label: str, options: list[str], want: str | None) -> int: + return 0 + + +class ReferenceSource(Source): + kind = "reference" + restart_after_relogin = True + + def __init__( + self, + portal: str, + case_id: str, + creds: dict[str, str], + label_map: dict[str, Any], + expected: dict[str, Any], + operator: dict[str, Any], + ) -> None: + super().__init__(portal, case_id, creds) + self.facts = load_intake(portal, case_id) + self.expected = expected + self.operator = operator + self.label_map = {norm(k): v for k, v in label_map.items()} + + def get(self, label: str) -> str | None: + entry = self.label_map.get(norm(label)) + if entry is None: + return None + if callable(entry): + return entry(self) + field, fmt = entry if isinstance(entry, tuple) else (entry, fmt_plain) + if field.startswith("intake:"): + key = field[len("intake:"):] + return fmt(self.facts[key]) if key in self.facts else None + return fmt(self.expected[field]) + + def pick(self, label: str, options: list[str], want: str | None) -> int: + for i, o in enumerate(options): + if want is not None and norm(o) == norm(want): + return i + raise DriverError(f"{label}: wanted {want!r} not among {options!r}") + + def check_operator_labels(self) -> list[str]: + """Operator-script labels that never appeared on screen.""" + missing = [] + for k in self.operator: + if k == "session_login" or re.fullmatch(r"[a-z0-9_]+(\.[a-z0-9_]+)*", k): + continue + if norm(k) not in self.labels_seen: + missing.append(k) + return missing + + +def oracle(base: str, path: str, payload: dict | None = None) -> Any: + data = None if payload is None else json.dumps(payload).encode() + req = urllib.request.Request( + base + path, data=data, method="GET" if payload is None else "POST", + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(req, timeout=20) as r: + return json.loads(r.read().decode()) + + +def find_option(src: Source, want: str, opts: list[tuple[str, str]]) -> str | None: + """Value of the option whose value or text matches ``want``. + + Case and whitespace are ignored; whole-dollar amounts also match by digits. + """ + return next((v for v, t in opts if v and option_matches(want, v, t)), None) diff --git a/packages/flow/benchmark/form_tx_heldout3/drivers/corvane.py b/packages/flow/benchmark/form_tx_heldout3/drivers/corvane.py new file mode 100644 index 0000000000..a90c5ccce3 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/drivers/corvane.py @@ -0,0 +1,262 @@ +"""Corvane wizard driver: sign in, walk steps 1-4, check the review, request the quote.""" + +from __future__ import annotations + +from typing import Any + +from ..scoring import load_answer_key, normalize +from .base import DriverError, Source, digits, find_option, fmt_date, norm, us_date + +REFERENCE_LABELS: dict[str, Any] = { + "First name": "first_name", + "Last name": "last_name", + "Date of birth": ("date_of_birth", fmt_date), + "Email": "email", + "Phone": "phone", + "Co-applicant full name": "co_applicant_name", + "Property street address": "property_street", + "City": "property_city", + "State": "property_state", + "ZIP code": "property_zip", + "Year built": "year_built", + "Finished living area (sq ft)": "square_feet", + "Construction type": "construction", + "Roof material": "roof_material", + "Year roof was installed or last replaced": "roof_year", + "Occupancy": "occupancy", + "Are any dogs kept at this address?": "dogs", + "Breed of each dog": "dog_breeds", + "Has any dog at this address ever bitten a person or another animal?": "dog_bite_history", + "Mortgagee (lender)": "mortgagee", + "Loan number": "loan_number", + # Typed directly unless the intake asks for the estimate. + "Dwelling (Coverage A) limit": lambda s: None if "dwelling_limit" not in s.facts else str(s.expected["dwelling_limit"]), + "Estimated replacement cost": "dwelling_limit", + "Personal liability": "personal_liability", + "All-perils deductible": "deductible", + "Policy effective date": ("effective_date", fmt_date), +} + +NAIVE_LABELS: dict[str, Any] = { + "First name": "first_name", + "Last name": "last_name", + "Date of birth": ("date_of_birth", fmt_date), + "Email": "email", + "Phone": "phone", + "Co-applicant full name": "spouse_name", + "Property street address": "property_street", + "City": "property_city", + "State": "property_state", + "ZIP code": "property_zip", + "Year built": "year_built", + "Finished living area (sq ft)": "square_feet", + "Construction type": "construction", + "Roof material": "roof_material", + "Year roof was installed or last replaced": "roof_year", + "Occupancy": "occupancy", + "Are any dogs kept at this address?": "dogs_on_premises", + "Breed of each dog": "dog_breeds", + "Has any dog at this address ever bitten a person or another animal?": "dog_bite_history", + "Mortgagee (lender)": "lender_name", + "Loan number": "loan_number", + "Dwelling (Coverage A) limit": "dwelling_limit", + "Personal liability": "personal_liability", + "All-perils deductible": "deductible", + "Policy effective date": ("effective_date", fmt_date), +} + +PORTAL = "corvane" + + +class Expired(Exception): + pass + + +def _login(page: Any, src: Source) -> None: + page.wait_for_selector("#u") + src.note("Agency code") + page.get_by_label("Agency code").fill(src.creds["username"]) + page.get_by_label("Password").fill(src.creds["password"]) + page.get_by_role("button", name="Sign in").click() + page.wait_for_url("**/quote**") + page.wait_for_selector("#app[data-ready]") + + +def _wait_render(page: Any, before: str | None) -> None: + page.wait_for_function( + "(b) => location.pathname.startsWith('/login') || location.pathname.startsWith('/quote/result') || " + "(document.querySelector('#app') && document.querySelector('#app').dataset.ready && " + "(document.querySelector('#app').dataset.ready !== b || document.querySelector('#app').dataset.errors))", + arg=before or "", + ) + + +def _goto_step(page: Any, base: str, n: int) -> None: + page.goto(f"{base}/quote?step={n}") + page.wait_for_selector(f"#app[data-step='{n}'][data-ready]") + + +def _fill_field(page: Any, box: Any, src: Source) -> None: + name = box.get_attribute("data-name") + kind = box.get_attribute("data-kind") + label = (box.locator("label, .lbl").first.inner_text()).strip() + src.note(label) + want = src.get(label) + if kind in ("text", "int", "date", "money"): + inp = box.locator(f"#f-{name}") + if want is None and box.locator("#est-open").count(): + _use_estimator(page, inp, src) + return + if want is not None: + inp.fill(want) + return + if kind == "select": + sel = box.locator("select") + opts = [(o.get_attribute("value") or "", o.inner_text().strip()) for o in sel.locator("option").all()] + if want is not None: + val = find_option(src, want, opts) + if val is None: + raise DriverError(f"{label}: no option for {want!r}") + sel.select_option(val) + elif not sel.input_value() and src.fallback_first: + sel.select_option(next(v for v, _ in opts if v)) + return + if kind == "radio": + radios = box.locator("input[type=radio]").all() + opts = [(r.get_attribute("value") or "", r.get_attribute("value") or "") for r in radios] + if want is not None: + val = find_option(src, want, opts) + if val is None: + raise DriverError(f"{label}: no option for {want!r}") + elif not any(r.is_checked() for r in radios) and src.fallback_first: + val = opts[0][0] + else: + return + box.locator(f"input[type=radio][value='{val}']").check() + return + if kind == "typeahead": + inp = box.locator(f"#f-{name}") + if want is None: + return + query = want.split(" ISAOA")[0] + inp.fill("") + inp.type(query, delay=10) + box.locator("ul[role=listbox]:not([hidden])").wait_for() + opts = box.locator("[role=option]") + try: + opts.first.wait_for(timeout=3000) + except Exception as exc: + raise DriverError(f"{label}: no suggestions for {query!r}") from exc + texts = [t.strip() for t in opts.all_inner_texts()] + idx = src.pick(label, texts, want) + opts.nth(idx).click() + return + raise DriverError(f"unknown field kind {kind!r}") + + +def _use_estimator(page: Any, inp: Any, src: Source) -> None: + page.click("#est-open") + page.wait_for_selector("#estdlg[open] #est-total") + label = "Estimated replacement cost" + src.note(label) + displayed = int(digits(page.inner_text("#est-total"))) + page.click("#est-use") + page.wait_for_selector("#estdlg:not([open])", state="attached") + current = inp.input_value() + src.events.append(f"estimator shown {displayed}, field {current}") + fix = src.estimator(label, displayed, current) + if fix is not None: + inp.fill(fix) + + +def _fill_step(page: Any, src: Source) -> None: + names = page.locator("#stepform .fld").evaluate_all("els => els.map(e => e.dataset.name)") + for name in names: + box = page.locator(f"#stepform .fld[data-name='{name}']") + if not box.is_visible(): + continue + _fill_field(page, box, src) + + +def _save(page: Any) -> None: + before = page.locator("#app").get_attribute("data-ready") + page.evaluate("document.querySelector('#app').dataset.errors = ''") + page.click("#save") + try: + _wait_render(page, before) + except Exception: # navigation to the sign-in page destroys the context + page.wait_for_load_state() + if page.url.split("?")[0].endswith("/login"): + raise Expired() + errs = [e for e in page.locator("[data-err]").all_inner_texts() if e.strip()] if page.locator("#stepform").count() else [] + if errs and page.locator("#app").get_attribute("data-ready") == before: + raise DriverError(f"validation: {errs}") + + +def _walk(page: Any, base: str, src: Source, start: int) -> None: + n = start + while n <= 4: + _goto_step(page, base, n) + _fill_step(page, src) + try: + _save(page) + except Expired: + src.events.append(f"session expired at step {n}") + _login(page, src) + if src.restart_after_relogin: + src.events.append("restart from step 1") + n = 1 + continue + n += 1 + + +def _review_mismatches(page: Any, src: Source) -> list[str]: + exp = getattr(src, "expected", None) + if exp is None: + return [] + types = load_answer_key()["portals"][PORTAL]["field_types"] + rows = page.locator("table.sum tr[data-name]").evaluate_all( + "rs => rs.map(r => [r.dataset.name, r.querySelector('td').textContent])") + shown = {k: v for k, v in rows} + bad = [] + for field, want in exp.items(): + got = shown.get(field) + if got is None: + if want not in ("", None): + bad.append(field) + continue + got = "" if got == "—" else got + if types[field] == "date": + if got != (us_date(want) if want else ""): + bad.append(field) + elif types[field] == "bool": + if norm(got) != ("yes" if want else "no"): + bad.append(field) + elif normalize(got, types[field]) != normalize(want, types[field]): + bad.append(field) + return bad + + +def run(page: Any, base: str, src: Source) -> str: + from ..corvane import FIELD_STEP + + page.goto(base + "/quote") + _login(page, src) + _walk(page, base, src, 1) + for _ in range(3): + _goto_step(page, base, 5) + bad = _review_mismatches(page, src) + if not bad: + break + src.events.append(f"review differs: {bad}") + for step in sorted({FIELD_STEP[f] for f in bad}): + _goto_step(page, base, step) + _fill_step(page, src) + _save(page) + else: + raise DriverError("review still differs after corrections") + page.click("#submit") + page.wait_for_url("**/quote/result/**") + ref = page.inner_text("#quote-ref").strip() + src.events.append(f"quote {ref}") + return "submitted" diff --git a/packages/flow/benchmark/form_tx_heldout3/drivers/pellbrook.py b/packages/flow/benchmark/form_tx_heldout3/drivers/pellbrook.py new file mode 100644 index 0000000000..c1744312b9 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/drivers/pellbrook.py @@ -0,0 +1,184 @@ +"""Pellbrook conversation driver: answer each card, check the summary, get the quote.""" + +from __future__ import annotations + +from typing import Any + +from ..case_defs import PB_LAYUP_LABEL +from ..scoring import load_answer_key, normalize +from .base import DriverError, Source, digits, find_option, fmt_date, norm, us_date + +REFERENCE_LABELS: dict[str, Any] = { + "First name": "first_name", + "Last name": "last_name", + "Date of birth": ("date_of_birth", fmt_date), + "Email address": "email", + "ZIP code where the boat is kept": "garaging_zip", + "Model year": "boat_year", + "Manufacturer": "boat_make", + "Model": "boat_model", + "Length overall (feet)": "length_ft", + "Engine type": "engine_type", + "Total horsepower (all engines combined)": "total_horsepower", + "Number of engines": "engine_count", + # Typed directly unless the intake asks for book value. + "Agreed hull value": lambda s: None if "agreed_hull_value" not in s.facts else str(s.expected["agreed_hull_value"]), + "Book value (average retail)": "agreed_hull_value", + "Where is the boat kept during the boating season?": "storage", + PB_LAYUP_LABEL: "layup_period", + "Where will you use the boat?": "navigation_area", + "Has the primary operator completed a boating safety course?": "safety_course", + "Boat insurance claims in the last 3 years": "losses_3yr", + "Lienholder (lender with a loan on this boat)": "lienholder", + "Liability limit": "liability_limit", + "Hull deductible": "deductible", + "Coverage start date": ("effective_date", fmt_date), +} + +NAIVE_LABELS: dict[str, Any] = { + "First name": "first_name", + "Last name": "last_name", + "Date of birth": ("date_of_birth", fmt_date), + "Email address": "email", + "ZIP code where the boat is kept": "garaging_zip", + "Model year": "boat_year", + "Manufacturer": "boat_make", + "Model": "boat_model", + "Length overall (feet)": "length_ft", + "Engine type": "engine_type", + "Total horsepower (all engines combined)": "total_horsepower", + "Number of engines": "engine_count", + "Agreed hull value": "agreed_hull_value", + "Where is the boat kept during the boating season?": "storage", + PB_LAYUP_LABEL: "layup_period", + "Where will you use the boat?": "navigation_area", + "Has the primary operator completed a boating safety course?": "safety_course", + "Boat insurance claims in the last 3 years": "losses_3yr", + "Lienholder (lender with a loan on this boat)": "lienholder", + "Liability limit": "liability_limit", + "Hull deductible": "deductible", + "Coverage start date": ("effective_date", fmt_date), +} + +PORTAL = "pellbrook" +MAX_CARDS = 60 + + +def _login(page: Any, src: Source) -> None: + page.wait_for_selector("#em") + page.get_by_label("Email").fill(src.creds["username"]) + page.get_by_label("Password").fill(src.creds["password"]) + page.get_by_role("button", name="Sign in").click() + page.wait_for_url("**/boat/quote") + + +def _seq(page: Any) -> str: + return page.locator("#convo").get_attribute("data-seq") or "0" + + +def _wait_new(page: Any, before: str) -> None: + page.wait_for_function( + "(b) => { const c = document.querySelector('#convo'); return c && (c.dataset.seq !== b || c.dataset.errors); }", + arg=before, + ) + + +def _use_book_value(page: Any, src: Source) -> None: + page.click("#bv-open") + page.wait_for_selector("#bv-average") + label = "Book value (average retail)" + src.note("Average retail") + displayed = int(digits(page.inner_text("#bv-average"))) + page.click("#bv-use") + current = page.input_value("#answer") + src.events.append(f"book value shown {displayed}, field {current}") + fix = src.estimator(label, displayed, current) + if fix is not None: + page.fill("#answer", fix) + + +def _answer_card(page: Any, src: Source) -> None: + card = page.locator("#card") + kind = card.get_attribute("data-kind") + label = page.locator("#card .q").inner_text().strip() + src.note(label) + want = src.get(label) + if kind == "choice": + radios = card.locator("input[type=radio]").all() + opts = [(r.get_attribute("value") or "", (r.locator("xpath=following-sibling::span").inner_text()).strip()) + for r in radios] + if want is not None: + val = find_option(src, want, opts) + if val is None: + raise DriverError(f"{label}: no option for {want!r}") + elif any(r.is_checked() for r in radios): + val = None + elif src.fallback_first: + val = opts[0][0] + else: + raise DriverError(f"{label}: no answer") + if val is not None: + card.locator(f"input[type=radio][value='{val}']").check(force=True) + else: + if want is None and card.locator("#bv-open").count(): + _use_book_value(page, src) + elif want is not None: + page.fill("#answer", want) + before = _seq(page) + page.evaluate("document.querySelector('#convo').dataset.errors = ''") + page.click("#next") + _wait_new(page, before) + if _seq(page) == before: + raise DriverError(f"{label}: {page.inner_text('#err')}") + + +def _summary_mismatches(page: Any, src: Source) -> list[str]: + exp = getattr(src, "expected", None) + if exp is None: + return [] + types = load_answer_key()["portals"][PORTAL]["field_types"] + rows = page.locator("#summary tr[data-key]").evaluate_all( + "rs => rs.map(r => [r.dataset.key, r.querySelector('td').textContent])") + shown = {k: v for k, v in rows} + bad = [] + for field, want in exp.items(): + got = shown.get(field) + if got is None: + if want not in ("", None): + bad.append(field) + continue + got = "" if got == "None" else got + t = types[field] + if t == "date": + ok = got == (us_date(want) if want else "") + elif t == "bool": + ok = norm(got) == ("yes" if want else "no") + else: + ok = normalize(got, t) == normalize(want, t) + if not ok: + bad.append(field) + return bad + + +def run(page: Any, base: str, src: Source) -> str: + page.goto(base + "/boat/quote") + _login(page, src) + page.wait_for_selector("#convo[data-view]") + for _ in range(MAX_CARDS): + if page.locator("#convo").get_attribute("data-view") == "summary": + bad = _summary_mismatches(page, src) + if not bad: + break + src.events.append(f"summary differs: {bad}") + before = _seq(page) + page.click(f"[data-change='{bad[0]}']") + _wait_new(page, before) + continue + _answer_card(page, src) + else: + raise DriverError("conversation did not reach the summary") + page.click("#get-quote") + page.wait_for_url("**/boat/quote/**") + ref = page.inner_text("#quote-ref").strip() + src.events.append(f"quote {ref}") + return "submitted" diff --git a/packages/flow/benchmark/form_tx_heldout3/estimators.py b/packages/flow/benchmark/form_tx_heldout3/estimators.py new file mode 100644 index 0000000000..2285593bdf --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/estimators.py @@ -0,0 +1,40 @@ +"""Deterministic estimators shown by the portals (and used to build the key). + +Neither depends on today's date: the book-value table uses a fixed rating +year. +""" + +from __future__ import annotations + +RATE_PER_SQFT = {"Frame": 185, "Masonry veneer": 196, "Masonry": 210} + + +def replacement_cost(square_feet: int, construction: str) -> dict[str, int]: + """Corvane rebuild estimate: base, code-and-debris allowance, total.""" + base = int(square_feet) * RATE_PER_SQFT.get(construction, 185) + allowance = round(base * 0.08) + total = int(round((base + allowance) / 1000.0)) * 1000 + return {"base": base, "allowance": allowance, "total": total} + + +RATING_YEAR = 2027 +MAKE_FACTOR = { + "Halvorsen Craft": 1.18, + "Tidelark Boats": 1.0, + "Brannock Marine": 0.92, + "Osprey Point": 1.07, + "Kestrel Bay Boatworks": 1.25, + "Marlowe Skiffs": 0.85, +} + + +def book_value(year: int, make: str, length_ft: int, horsepower: int) -> dict[str, int]: + """Pellbrook book value: low, average and high retail, whole hundreds.""" + age = max(0, RATING_YEAR - int(year)) + raw = int(length_ft) * 2150 * MAKE_FACTOR.get(make, 1.0) * (0.93 ** age) + int(horsepower) * 18 + avg = int(round(raw / 100.0)) * 100 + return { + "low": int(round(avg * 0.86 / 100.0)) * 100, + "average": avg, + "high": int(round(avg * 1.12 / 100.0)) * 100, + } diff --git a/packages/flow/benchmark/form_tx_heldout3/fixtures/portal_logins.json b/packages/flow/benchmark/form_tx_heldout3/fixtures/portal_logins.json new file mode 100644 index 0000000000..e6919fa2b7 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/fixtures/portal_logins.json @@ -0,0 +1,4 @@ +{ + "corvane": {"username": "CVA-40518", "password": "corvane-test-pass-9"}, + "pellbrook": {"username": "dock.tester@example.test", "password": "pellbrook-test-pass-10"} +} diff --git a/packages/flow/benchmark/form_tx_heldout3/intake_vocabulary.json b/packages/flow/benchmark/form_tx_heldout3/intake_vocabulary.json new file mode 100644 index 0000000000..5ecf4fcb82 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/intake_vocabulary.json @@ -0,0 +1,245 @@ +{ + "corvane": { + "portal": "corvane", + "keys": { + "first_name": { + "type": "str" + }, + "last_name": { + "type": "str" + }, + "date_of_birth": { + "type": "date" + }, + "email": { + "type": "str" + }, + "phone": { + "type": "phone" + }, + "marital_status": { + "type": "enum", + "values": [ + "Married", + "Single", + "Divorced", + "Widowed" + ] + }, + "spouse_name": { + "type": "str" + }, + "property_street": { + "type": "str" + }, + "property_city": { + "type": "str" + }, + "property_state": { + "type": "enum", + "values": [ + "ID", + "MN", + "NC", + "OH", + "OR", + "VT", + "WA" + ] + }, + "property_zip": { + "type": "str" + }, + "year_built": { + "type": "int" + }, + "square_feet": { + "type": "int" + }, + "construction": { + "type": "enum", + "values": [ + "Frame", + "Masonry veneer", + "Masonry" + ] + }, + "roof_material": { + "type": "enum", + "values": [ + "Asphalt shingle", + "Metal", + "Wood shake", + "Tile", + "Slate" + ] + }, + "roof_year": { + "type": "int" + }, + "occupancy": { + "type": "enum", + "values": [ + "Owner-occupied primary residence", + "Owner-occupied secondary or seasonal home" + ] + }, + "dogs_on_premises": { + "type": "bool" + }, + "dog_breeds": { + "type": "str" + }, + "dog_bite_history": { + "type": "enum", + "values": [ + "Yes", + "No" + ] + }, + "lender_name": { + "type": "str" + }, + "lender_clause_address": { + "type": "str" + }, + "loan_number": { + "type": "str" + }, + "dwelling_limit": { + "type": "money" + }, + "dwelling_limit_basis": { + "type": "enum", + "values": [ + "Estimated replacement cost" + ] + }, + "personal_liability": { + "type": "money" + }, + "deductible": { + "type": "money" + }, + "effective_date": { + "type": "date" + } + }, + "dates": "ISO 8601 (YYYY-MM-DD)", + "absent_key": "the fact is unknown; the intake never sends null or empty values" + }, + "pellbrook": { + "portal": "pellbrook", + "keys": { + "first_name": { + "type": "str" + }, + "last_name": { + "type": "str" + }, + "date_of_birth": { + "type": "date" + }, + "email": { + "type": "str" + }, + "garaging_zip": { + "type": "str" + }, + "boat_year": { + "type": "int" + }, + "boat_make": { + "type": "str" + }, + "boat_model": { + "type": "str" + }, + "length_ft": { + "type": "int" + }, + "engine_type": { + "type": "enum", + "values": [ + "Outboard", + "Inboard", + "Sterndrive (inboard/outboard)", + "Jet drive" + ] + }, + "engine_count": { + "type": "enum", + "values": [ + "Single", + "Twin", + "Triple" + ] + }, + "total_horsepower": { + "type": "int" + }, + "agreed_hull_value": { + "type": "money" + }, + "hull_value_basis": { + "type": "enum", + "values": [ + "Book value (average retail)" + ] + }, + "storage": { + "type": "enum", + "values": [ + "On a trailer at my home", + "Dry stack or rack storage", + "Wet slip at a marina", + "On a mooring" + ] + }, + "layup_period": { + "type": "enum", + "values": [ + "Oct 15 to May 1", + "Nov 1 to Apr 1", + "Dec 1 to Mar 31", + "No lay-up (in commission year-round)" + ] + }, + "navigation_area": { + "type": "enum", + "values": [ + "Inland lakes and rivers", + "Coastal waters within 25 miles of shore", + "Coastal waters up to 75 miles offshore" + ] + }, + "safety_course": { + "type": "bool" + }, + "losses_3yr": { + "type": "int" + }, + "financing": { + "type": "enum", + "values": [ + "Financed", + "Paid in full" + ] + }, + "lienholder": { + "type": "str" + }, + "liability_limit": { + "type": "money" + }, + "deductible": { + "type": "money" + }, + "effective_date": { + "type": "date" + } + }, + "dates": "ISO 8601 (YYYY-MM-DD)", + "absent_key": "the fact is unknown; the intake never sends null or empty values" + } +} diff --git a/packages/flow/benchmark/form_tx_heldout3/make_manifest.py b/packages/flow/benchmark/form_tx_heldout3/make_manifest.py new file mode 100644 index 0000000000..43e6babc42 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/make_manifest.py @@ -0,0 +1,38 @@ +"""Write MANIFEST.json: the sha256 of every file in this directory. + +Covers the git-tracked files (``git add`` new files first). Run last, after +answer_key.json and REFERENCE_RUNS.json are final: +``python -m benchmark.form_tx_heldout3.make_manifest``. +""" + +from __future__ import annotations + +import hashlib +import json +import subprocess +from pathlib import Path + +HERE = Path(__file__).resolve().parent + + +def tracked_files() -> list[str]: + out = subprocess.run( + ["git", "ls-files", "-z", "--", "."], cwd=HERE, check=True, capture_output=True + ).stdout.decode() + return sorted(p for p in out.split("\0") if p and p != "MANIFEST.json") + + +def build() -> dict: + files = {rel: hashlib.sha256((HERE / rel).read_bytes()).hexdigest() for rel in tracked_files()} + manifest = { + "description": "sha256 of every git-tracked file in benchmark/form_tx_heldout3 except this manifest", + "answer_key_sha256": files["answer_key.json"], + "files": files, + } + (HERE / "MANIFEST.json").write_text(json.dumps(manifest, indent=2) + "\n") + return manifest + + +if __name__ == "__main__": + m = build() + print(m["answer_key_sha256"], len(m["files"]), "files") diff --git a/packages/flow/benchmark/form_tx_heldout3/naive_filler.py b/packages/flow/benchmark/form_tx_heldout3/naive_filler.py new file mode 100644 index 0000000000..6f49889e36 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/naive_filler.py @@ -0,0 +1,34 @@ +"""Unguarded agent baseline. + +Types intake values into fields matched by label text, keeps any prefilled +value it has no intake fact for (and overwrites prefill when it has one), +picks the first type-ahead suggestion, accepts the estimator's handed-back +value, answers unknown questions with the first option (or leaves text +empty), signs in again on a timeout and carries on, and submits without +checking the summary. + + python -m benchmark.form_tx_heldout3.naive_filler [portal ...] +""" + +from __future__ import annotations + +import sys + +from .common import CREDENTIALS +from .drivers.base import NaiveSource +from .portals import PORTALS +from .runner import driver_for, emit, run_cases + + +def make_source(portal: str, case_id: str) -> NaiveSource: + return NaiveSource(portal, case_id, CREDENTIALS[portal], driver_for(portal).NAIVE_LABELS) + + +def main(argv: list[str]) -> None: + portals = [a for a in argv if not a.startswith("-")] or list(PORTALS) + for pid in portals: # one block per portal, printed as soon as it finishes + emit(run_cases(make_source, [pid], include_dev="--dev" in argv)) + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/packages/flow/benchmark/form_tx_heldout3/pellbrook.py b/packages/flow/benchmark/form_tx_heldout3/pellbrook.py new file mode 100644 index 0000000000..df17a21990 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/pellbrook.py @@ -0,0 +1,395 @@ +"""Pellbrook Marine: conversational boat and watercraft quote. + +The customer signs in and answers one question per card; the server decides +the next question (some appear only for certain answers). Answered cards +stay in the thread above. A returning customer's cards come prefilled from +their last saved quote. The hull-value card has a book-value lookup. When +every question is answered the page shows a "Here's what we have" summary +with a Change button per answer, and ``Get my quote`` stores the submission +and opens the quote page. +""" + +from __future__ import annotations + +from typing import Any + +from .case_defs import ( + PB_ENGINE_COUNT, + PB_ENGINE_TYPE, + PB_FIELDS, + PB_LAYUP, + PB_LAYUP_LABEL, + PB_NAV, + PB_STORAGE, +) +from .common import BasePortal, Request, Response, esc, money, parse_date, parse_int +from .estimators import book_value + +RECORD_FIELDS = list(PB_FIELDS) + + +def _ch(values: list[Any], fmt=str) -> list[list[str]]: + return [[str(v), fmt(v)] for v in values] + + +QUESTIONS: list[dict[str, Any]] = [ + {"key": "first_name", "label": "First name", "kind": "text"}, + {"key": "last_name", "label": "Last name", "kind": "text"}, + {"key": "date_of_birth", "label": "Date of birth", "kind": "date"}, + {"key": "email", "label": "Email address", "kind": "text"}, + {"key": "garaging_zip", "label": "ZIP code where the boat is kept", "kind": "text"}, + {"key": "boat_year", "label": "Model year", "kind": "int"}, + {"key": "boat_make", "label": "Manufacturer", "kind": "text"}, + {"key": "boat_model", "label": "Model", "kind": "text"}, + {"key": "length_ft", "label": "Length overall (feet)", "kind": "int"}, + {"key": "engine_type", "label": "Engine type", "kind": "choice", "options": _ch(PB_ENGINE_TYPE)}, + {"key": "total_horsepower", "label": "Total horsepower (all engines combined)", "kind": "int"}, + {"key": "engine_count", "label": "Number of engines", "kind": "choice", "options": _ch(PB_ENGINE_COUNT)}, + {"key": "agreed_hull_value", "label": "Agreed hull value", "kind": "money", "estimator": True, + "help": "The amount we would pay for a total loss. Not sure? Look up the book value."}, + {"key": "storage", "label": "Where is the boat kept during the boating season?", "kind": "choice", + "options": _ch(PB_STORAGE)}, + {"key": "layup_period", "label": PB_LAYUP_LABEL, "kind": "choice", "options": _ch(PB_LAYUP), + "when": ("storage", ["Wet slip at a marina", "On a mooring"]), + "help": "The months the boat is hauled out or laid up and not used."}, + {"key": "navigation_area", "label": "Where will you use the boat?", "kind": "choice", "options": _ch(PB_NAV)}, + {"key": "safety_course", "label": "Has the primary operator completed a boating safety course?", + "kind": "choice", "options": [["Yes", "Yes"], ["No", "No"]]}, + {"key": "losses_3yr", "label": "Boat insurance claims in the last 3 years", "kind": "int"}, + {"key": "lienholder", "label": "Lienholder (lender with a loan on this boat)", "kind": "text", + "optional": True, "help": "Leave blank if there is no loan."}, + {"key": "liability_limit", "label": "Liability limit", "kind": "choice", + "options": _ch([100000, 300000, 500000], money)}, + {"key": "deductible", "label": "Hull deductible", "kind": "choice", "options": _ch([500, 1000, 2500], money)}, + {"key": "effective_date", "label": "Coverage start date", "kind": "date"}, +] +QDEF = {q["key"]: q for q in QUESTIONS} +MULT = {"Single": 1, "Twin": 2, "Triple": 3} + + +def _display(key: str, value: Any) -> str: + if value in ("", None): + return "None" + q = QDEF[key] + if q["kind"] == "date": + iso = parse_date(str(value)) + return f"{iso[5:7]}/{iso[8:10]}/{iso[:4]}" if iso else str(value) + if q["kind"] == "money" or key in ("liability_limit", "deductible"): + n = parse_int(value) + return money(n) if n is not None else str(value) + if q["kind"] == "int" and key != "boat_year": + n = parse_int(value) + return f"{n:,}" if n is not None else str(value) + return str(value) + + +CSS = """ +:root{--ink:#122436;--muted:#5a6a78;--sea:#14607a;--foam:#eaf4f7;--line:#cfdde4;--err:#a1281c;--bg:#f7fafb} +*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.5 Georgia,'Times New Roman',serif} +header{padding:14px 22px;border-bottom:3px solid var(--sea);background:#fff;display:flex;justify-content:space-between} +header b{font-size:20px;color:var(--sea)}main{max-width:680px;margin:22px auto;padding:0 14px} +.thread .qa{margin:0 0 10px}.thread .bq{background:#fff;border:1px solid var(--line);border-radius:14px 14px 14px 2px;padding:7px 12px;display:inline-block;color:var(--muted);font-size:14px} +.thread .ba{text-align:right}.thread .ba span{background:var(--sea);color:#fff;border-radius:14px 14px 2px 14px;padding:7px 12px;display:inline-block;font-size:14px;font-family:system-ui,Arial,sans-serif} +#card{background:#fff;border:1px solid var(--line);border-radius:12px;padding:18px 20px;margin-top:16px;box-shadow:0 2px 8px rgba(20,60,80,.06)} +#card label.q,#card legend.q{font-size:19px;display:block;margin-bottom:10px;padding:0} +#card fieldset{border:0;margin:0;padding:0}#card input[type=text]{font:16px system-ui,Arial,sans-serif;padding:9px 11px;width:100%;max-width:420px;border:1px solid #8ea6b3;border-radius:8px} +.chips label{display:inline-block;margin:0 8px 8px 0;font-family:system-ui,Arial,sans-serif;font-size:15px} +.chips input{position:absolute;opacity:0}.chips span{display:inline-block;padding:7px 14px;border:1px solid var(--sea);border-radius:999px;cursor:pointer} +.chips input:checked+span{background:var(--sea);color:#fff}.chips input:focus-visible+span{outline:2px solid #e0a100} +.note{background:var(--foam);border-radius:8px;padding:7px 11px;font-size:14px;margin:10px 0;font-family:system-ui,Arial,sans-serif} +.help{color:var(--muted);font-size:14px;margin-top:6px;font-family:system-ui,Arial,sans-serif}.err{color:var(--err);font-size:14px;font-family:system-ui,Arial,sans-serif} +button{font:15px system-ui,Arial,sans-serif;padding:9px 18px;border-radius:999px;border:1px solid var(--sea);background:var(--sea);color:#fff;cursor:pointer;margin-top:12px} +button.ghost{background:#fff;color:var(--sea)}#bv{border:1px dashed var(--sea);border-radius:10px;padding:10px 14px;margin-top:12px;font-family:system-ui,Arial,sans-serif} +#bv table td{padding:3px 14px 3px 0}table.sum{width:100%;border-collapse:collapse;font-family:system-ui,Arial,sans-serif;font-size:15px} +table.sum th,table.sum td{text-align:left;border-bottom:1px solid var(--line);padding:7px 6px;vertical-align:top}table.sum th{width:48%;font-weight:600} +table.sum button{margin:0;padding:3px 12px;font-size:13px}.banner{background:#fff7df;border:1px solid #ecd58e;border-radius:8px;padding:9px 12px;font-family:system-ui,Arial,sans-serif;font-size:14px} +""" + +APP_JS = r""" +const $ = s => document.querySelector(s); +const h = s => String(s ?? '').replace(/[&<>"]/g, c => ({'&':'&','<':'<','>':'>','"':'"'}[c])); +let seq = 0, busy = false; +async function api(method, url, body){ + const r = await fetch(url, {method, headers:{'Content-Type':'application/json'}, body: body ? JSON.stringify(body) : undefined}); + if (r.status === 401){ location.href = '/signin?next=/boat/quote'; throw new Error('expired'); } + return r.json(); +} +function thread(items){ + return items.map(t => `
    ${h(t.label)}
    ${h(t.display)}
    `).join(''); +} +function draw(st){ + seq += 1; + let out = st.banner ? `` : ''; + out += `
    ${thread(st.thread)}
    `; + if (st.summary){ out += summary(st); $('#convo').innerHTML = out; wireSummary(); $('#convo').dataset.seq = seq; $('#convo').dataset.view = 'summary'; return; } + const q = st.card, v = q.value ?? ''; + out += `
    `; + if (q.kind === 'choice'){ + out += `
    ${h(q.label)}
    ` + + q.options.map((o,i) => ``).join('') + + '
    '; + } else { + const ph = q.kind === 'date' ? ' placeholder="MM/DD/YYYY"' : ''; + out += ``; + if (q.estimator) out += `
    `; + } + if (q.prefill_note) out += `
    ${h(q.prefill_note)}
    `; + if (q.help) out += `
    ${h(q.help)}
    `; + out += `
    `; + $('#convo').innerHTML = out; $('#convo').dataset.seq = seq; $('#convo').dataset.view = 'card'; + $('#next').onclick = answer; + const inp = $('#answer'); if (inp){ inp.addEventListener('keydown', e => { if (e.key === 'Enter'){ e.preventDefault(); answer(); } }); } + if ($('#bv-open')) $('#bv-open').onclick = lookup; +} +async function lookup(){ + const r = await api('GET', '/api/bookvalue'); const box = $('#bv'); box.hidden = false; + if (r.error){ box.textContent = r.error; return; } + box.innerHTML = `
    Book value for ${h(r.boat)}
    + + +
    Low retail${h(r.low_display)}
    Average retail${h(r.average_display)}
    High retail${h(r.high_display)}
    + `; + $('#bv-use').onclick = () => { $('#answer').value = r.use_value; }; +} +async function answer(){ + if (busy) return; busy = true; + try { + const card = $('#card'); let value = ''; + if (card.dataset.kind === 'choice'){ const c = document.querySelector('input[name=answer]:checked'); value = c ? c.value : ''; } + else value = $('#answer').value; + const st = await api('POST', '/api/answer', {key: card.dataset.key, value}); + if (st.error){ $('#err').textContent = st.error; $('#convo').dataset.errors = String(Date.now()); return; } + draw(st); + } finally { busy = false; } +} +function summary(st){ + let out = '

    Here’s what we have

    Check each answer. Use Change to fix anything that is not right.

    '; + for (const r of st.summary) out += ``; + return out + '
    ${h(r.label)}${h(r.display)}
    '; +} +function wireSummary(){ + document.querySelectorAll('[data-change]').forEach(b => b.onclick = async () => draw(await api('POST', '/api/edit', {key: b.dataset.change}))); + $('#get-quote').onclick = async () => { + if (busy) return; busy = true; + try { const r = await api('POST', '/api/submit', {}); if (r.error){ $('#err').textContent = r.error; return; } location.href = '/boat/quote/' + r.quote_ref; } + finally { busy = false; } + }; +} +api('GET', '/api/convo').then(draw); +""" + + +def page(title: str, body: str) -> str: + return ( + f"{esc(title)}" + f"" + "
    Pellbrook MarineBoat & watercraft insurance
    " + f"
    {body}
    " + ) + + +class Pellbrook(BasePortal): + portal_id = "pellbrook" + cookie = "pbsid" + + def reset(self) -> None: + super().reset() + with self.lock: + self.answers: dict[str, Any] = {} + self.answered: list[str] = [] + self.editing: str | None = None + self.quotes: dict[str, dict[str, Any]] = {} + + def load_case(self, case_id: str) -> bool: + ok = super().load_case(case_id) + if ok: + with self.lock: + self.answers = {} + self.answered = [] + self.editing = None + for k, v in (self.config.get("prior") or {}).items(): + if k in QDEF: + self.answers[k] = "Yes" if v is True else "No" if v is False else str(v) + return ok + + # ---- conversation ------------------------------------------------- + def _applies(self, q: dict[str, Any]) -> bool: + when = q.get("when") + return not when or self.answers.get(when[0]) in when[1] + + def _current(self) -> dict[str, Any] | None: + if self.editing: + return QDEF[self.editing] + for q in QUESTIONS: + if self._applies(q) and q["key"] not in self.answered: + return q + return None + + def _state(self) -> dict[str, Any]: + prior = self.config.get("prior") + banner = (f"Welcome back. We filled in answers from your quote of {prior['quoted_on']}. " + "Check each one as you go.") if prior else "" + thread = [{"label": QDEF[k]["label"], "display": _display(k, self.answers.get(k, ""))} + for k in self.answered if self._applies(QDEF[k])][-6:] + cur = self._current() + st: dict[str, Any] = {"banner": banner, "thread": thread} + if cur is None: + st["thread"] = [] + st["summary"] = [{"key": q["key"], "label": q["label"], "display": _display(q["key"], self.answers.get(q["key"], ""))} + for q in QUESTIONS if self._applies(q)] + return st + card = {k: cur.get(k) for k in ("key", "label", "kind", "options", "help", "estimator")} + card["value"] = self.answers.get(cur["key"], "") + if prior and cur["key"] in prior and cur["key"] not in self.answered: + card["prefill_note"] = f"From your {prior['quoted_on']} quote. Change it if it is no longer right." + st["card"] = card + return st + + def _clean(self, q: dict[str, Any], raw: str) -> tuple[str, str]: + raw = (raw or "").strip() + if not raw: + return ("", "") if q.get("optional") else ("", "Please answer this question to continue.") + kind = q["kind"] + if kind == "date": + iso = parse_date(raw) + return (iso, "") if iso else (raw, "Enter the date as MM/DD/YYYY.") + if kind in ("int", "money"): + n = parse_int(raw) + return (str(n), "") if n is not None and n >= 0 else (raw, "Enter a whole number.") + if kind == "choice": + return (raw, "") if raw in [o[0] for o in q["options"]] else (raw, "Choose one of the answers.") + if q["key"] == "garaging_zip" and not (len(raw) == 5 and raw.isdigit()): + return raw, "Enter a 5-digit ZIP code." + return raw, "" + + def _answer(self, key: str, raw: str) -> dict[str, Any]: + cur = self._current() + if cur is None or cur["key"] != key: + return {"error": "That question is no longer open. Reload the page."} + value, err = self._clean(cur, raw) + if err: + return {"error": err} + self.answers[key] = value + if key not in self.answered: + self.answered.append(key) + if key == "engine_count" and MULT.get(value, 1) > 1: + hp = parse_int(self.answers.get("total_horsepower")) + if hp: + self.answers["total_horsepower"] = str(hp * MULT[value]) + self.editing = None + return self._state() + + def _record(self) -> dict[str, Any]: + rec: dict[str, Any] = {} + for q in QUESTIONS: + k = q["key"] + v = self.answers.get(k, "") if self._applies(q) else "" + if k == "safety_course": + rec[k] = v == "Yes" + elif q["kind"] in ("int", "money") or k in ("liability_limit", "deductible"): + rec[k] = parse_int(v) + else: + rec[k] = v + return rec + + def _premium(self, rec: dict[str, Any]) -> int: + p = (rec["agreed_hull_value"] or 0) * 0.0145 + {100000: 60, 300000: 95, 500000: 130}.get( + rec["liability_limit"] or 0, 0) + p *= {500: 1.08, 1000: 1.0, 2500: 0.9}.get(rec["deductible"] or 1000, 1.0) + if rec["safety_course"]: + p *= 0.95 + p += 40 * (rec["losses_3yr"] or 0) + return int(round(p)) + + # ---- routes ----------------------------------------------------- + def route(self, req: Request) -> Response: + p = req.path + if p in ("/", "/boat"): + return Response.redirect("/boat/quote") + if p == "/signin": + return self.signin(req) + if p.startswith("/api/"): + if not self.has_session(req): + return Response.json_({"error": "signed out"}, 401) + with self.lock: + return self.api(req) + if not self.has_session(req): + return Response.redirect("/signin?next=" + p) + if p == "/boat/quote": + body = (f"

    Loading…

    ") + return Response.html(page("Get a boat quote – Pellbrook Marine", body)) + if p.startswith("/boat/quote/"): + return self.result(p.rsplit("/", 1)[-1]) + return Response.html(page("Not found", "

    Not found

    "), 404) + + def signin(self, req: Request) -> Response: + nxt = req.query.get("next") or req.form.get("next") or "/boat/quote" + if not nxt.startswith("/"): + nxt = "/boat/quote" + msg = "" + if req.method == "POST": + if self.check_login(req.form.get("email", ""), req.form.get("password", "")): + return Response.redirect(nxt).set_cookie(self.cookie, self.new_session()) + msg = "" + body = ( + "

    Sign in to get your quote

    " + f"{msg}
    " + "


    " + "


    " + ) + return Response.html(page("Sign in – Pellbrook Marine", body)) + + def api(self, req: Request) -> Response: + p = req.path + body = req.json or {} + if p == "/api/convo": + return Response.json_(self._state()) + if p == "/api/answer" and req.method == "POST": + return Response.json_(self._answer(str(body.get("key", "")), str(body.get("value", "")))) + if p == "/api/edit" and req.method == "POST": + key = str(body.get("key", "")) + if key in QDEF and self._current() is None: + self.editing = key + return Response.json_(self._state()) + if p == "/api/bookvalue": + a = self.answers + yr, ln, hp = parse_int(a.get("boat_year")), parse_int(a.get("length_ft")), parse_int(a.get("total_horsepower")) + if not (yr and ln and hp and a.get("boat_make")): + return Response.json_({"error": "Answer the boat questions first."}) + bv = book_value(yr, a["boat_make"], ln, hp) + return Response.json_({ + "boat": f"{yr} {a['boat_make']} {a.get('boat_model', '')}".strip(), + "low_display": money(bv["low"]), "average_display": money(bv["average"]), + "high_display": money(bv["high"]), "use_value": f"{bv['average']:,}", + }) + if p == "/api/submit" and req.method == "POST": + if self._current() is not None: + return Response.json_({"error": "Please answer every question first."}) + rec = self._record() + self.quote_seq += 1 + rec["quote_ref"] = f"PBM-{41000 + self.quote_seq}-Q" + rec["annual_premium"] = self._premium(rec) + stored = self.store_submission(rec) + self.quotes[rec["quote_ref"]] = stored + return Response.json_({"ok": True, "quote_ref": rec["quote_ref"]}) + return Response.json_({"error": "not found"}, 404) + + def result(self, ref: str) -> Response: + rec = self.quotes.get(ref) + if not rec: + return Response.html(page("Not found", "

    Quote not found

    "), 404) + rows = "".join( + f"{esc(q['label'])}" + f"{esc(_display(q['key'], 'Yes' if rec[q['key']] is True else 'No' if rec[q['key']] is False else rec[q['key']]))}" + "" + for q in QUESTIONS + ) + body = ( + "

    Your boat quote

    " + f"

    Quote reference {esc(ref)}
    " + f"Annual premium {esc(money(rec['annual_premium']))}

    " + f"{rows}
    " + ) + return Response.html(page(f"Quote {ref} – Pellbrook Marine", body)) diff --git a/packages/flow/benchmark/form_tx_heldout3/portals.py b/packages/flow/benchmark/form_tx_heldout3/portals.py new file mode 100644 index 0000000000..9ea3ae0c3f --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/portals.py @@ -0,0 +1,79 @@ +"""Registry of the third held-out portal set. + + from benchmark.form_tx_heldout3.portals import PORTALS + spec = PORTALS["corvane"] + server, base_url = spec.start() # host="127.0.0.1", port=0 + # POST {base_url}/__oracle/load_case {"case_id": spec.cases[0]} + # drive the browser from base_url + spec.entry_path + # GET {base_url}/__oracle/submissions -> scoring.score_case(case_id, records) + server.shutdown() + +``cases`` lists the scored cases in their required run order; +``dev_case`` is the one inspectable case. ``intake_vocabulary`` lists every +canonical intake key the portal's cases may carry (type, allowed values); it +holds no case data and is safe to read before freezing a layer. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +from .case_defs import CASES +from .common import CREDENTIALS, PortalSpec +from .corvane import Corvane +from .pellbrook import Pellbrook + +_VOCAB = json.loads((Path(__file__).resolve().parent / "intake_vocabulary.json").read_text()) + + +def _cases(portal: str) -> list[str]: + return [c["case_id"] for c in CASES[portal] if c["split"] == "scored"] + + +def _dev(portal: str) -> str: + return next(c["case_id"] for c in CASES[portal] if c["split"] == "dev") + + +def _login(portal: str, path: str, user_label: str, pass_label: str) -> dict: + return { + "required_at_start": True, + "kind": "page", + "path": path, + "username_label": user_label, + "password_label": pass_label, + "username": CREDENTIALS[portal]["username"], + "password": CREDENTIALS[portal]["password"], + "credentials_file": "benchmark/form_tx_heldout3/fixtures/portal_logins.json", + } + + +PORTALS: dict[str, PortalSpec] = { + "corvane": PortalSpec( + name="corvane", + title="Corvane Mutual AgentLink homeowners", + description="Homeowners (HO-3) quote wizard for agents: browser-rendered steps with a left step list, each " + "step saved through a JSON API; customer-record and public-property-record prefill, lender " + "directory type-ahead, replacement-cost estimator dialog, review step, sign-in page when the " + "session ends", + factory=Corvane, + entry_path="/quote", + login=_login("corvane", "/login", "Agency code", "Password"), + cases=_cases("corvane"), + dev_case=_dev("corvane"), + intake_vocabulary=_VOCAB["corvane"], + ), + "pellbrook": PortalSpec( + name="pellbrook", + title="Pellbrook Marine boat quote", + description="Consumer boat and watercraft quote as a conversation: one server-chosen question per card, " + "choice chips, conditional questions, returning-customer prefill, book-value lookup, " + "summary with a Change button per answer, quote page", + factory=Pellbrook, + entry_path="/boat/quote", + login=_login("pellbrook", "/signin", "Email", "Password"), + cases=_cases("pellbrook"), + dev_case=_dev("pellbrook"), + intake_vocabulary=_VOCAB["pellbrook"], + ), +} diff --git a/packages/flow/benchmark/form_tx_heldout3/record_reference_runs.py b/packages/flow/benchmark/form_tx_heldout3/record_reference_runs.py new file mode 100644 index 0000000000..78942d1040 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/record_reference_runs.py @@ -0,0 +1,61 @@ +"""Run both reference fillers over every case and write ``REFERENCE_RUNS.json``. + + python -m benchmark.form_tx_heldout3.record_reference_runs +""" + +from __future__ import annotations + +import json +import platform +import sys +from pathlib import Path +from typing import Any + +from . import naive_filler, reference_human +from .portals import PORTALS +from .runner import run_cases + +HERE = Path(__file__).resolve().parent + + +def _summary(rows: list[dict[str, Any]]) -> dict[str, Any]: + dev = {spec.dev_case for spec in PORTALS.values()} + scored = [r for r in rows if r["case_id"] not in dev] + clean = [r for r in scored if "clean" in r["traps"]] + per_portal = {} + for pid in PORTALS: + mine = [r for r in scored if r["portal"] == pid] + per_portal[pid] = {"scored_cases": len(mine), "correct": sum(r["correct"] for r in mine)} + return { + "scored_cases": len(scored), + "correct": sum(r["correct"] for r in scored), + "wrong": sorted(r["case_id"] for r in scored if r["submitted"] and not r["correct"]), + "not_submitted": sorted(r["case_id"] for r in scored if not r["submitted"]), + "clean_cases": len(clean), + "clean_cases_correct": sum(r["correct"] for r in clean), + "dev_correct": sum(r["correct"] for r in rows if r["case_id"] in dev), + "per_portal": per_portal, + } + + +def main() -> None: + from importlib.metadata import version + + pw_version = version("playwright") + + runs: list[dict[str, Any]] = [] + summary: dict[str, Any] = {} + for name, mod in (("reference_human", reference_human), ("naive_filler", naive_filler)): + rows = run_cases(mod.make_source, include_dev=True) + for r in rows: + r["filler_name"] = name + runs.extend(rows) + summary[name] = _summary(rows) + env = f"{platform.system()} {platform.release()}; Python {platform.python_version()}; Playwright {pw_version}; headless Chromium" + out = {"environment": env, "summary": summary, "runs": runs} + (HERE / "REFERENCE_RUNS.json").write_text(json.dumps(out, indent=1) + "\n") + print(json.dumps(summary, indent=1), file=sys.stderr) + + +if __name__ == "__main__": + main() diff --git a/packages/flow/benchmark/form_tx_heldout3/reference_human.py b/packages/flow/benchmark/form_tx_heldout3/reference_human.py new file mode 100644 index 0000000000..c903daa1bf --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/reference_human.py @@ -0,0 +1,51 @@ +"""Scripted careful human: completes every case to the answer key. + +It reads its values from the answer key (expected record plus operator +script), re-checks each earlier step after a session interruption, and +checks that every screen-sourced value it relies on (the estimator figure, +type-ahead options, operator-script labels) is actually shown. + + python -m benchmark.form_tx_heldout3.reference_human [portal ...] +""" + +from __future__ import annotations + +import sys +from typing import Any + +from .common import CREDENTIALS +from .drivers.base import ReferenceSource, digits +from .portals import PORTALS +from .runner import driver_for, emit, run_cases +from .scoring import load_answer_key + + +class CarefulHuman(ReferenceSource): + def __init__(self, *a: Any, **kw: Any) -> None: + super().__init__(*a, **kw) + self.problems: list[str] = [] + + def estimator(self, label: str, displayed: int, current: str) -> str | None: + field = self.label_map.get(label.strip().casefold()) + want = self.expected[field if isinstance(field, str) else field[0]] + if int(want) != displayed: + self.problems.append(f"estimator showed {displayed}, answer key has {want}") + if digits(current) != str(want): + return str(want) + return None + + +def make_source(portal: str, case_id: str) -> CarefulHuman: + ak = load_answer_key()["cases"][case_id] + labels = driver_for(portal).REFERENCE_LABELS + return CarefulHuman(portal, case_id, CREDENTIALS[portal], labels, ak["expected_record"], ak["operator_script"]) + + +def main(argv: list[str]) -> None: + portals = [a for a in argv if not a.startswith("-")] or list(PORTALS) + for pid in portals: # one block per portal, printed as soon as it finishes + emit(run_cases(make_source, [pid], include_dev="--dev" in argv)) + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/packages/flow/benchmark/form_tx_heldout3/runner.py b/packages/flow/benchmark/form_tx_heldout3/runner.py new file mode 100644 index 0000000000..259e87ad65 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/runner.py @@ -0,0 +1,91 @@ +"""Run a filler over cases and score the oracle's stored records.""" + +from __future__ import annotations + +import json +import sys +import time +import traceback +from typing import Any, Callable + +from .drivers.base import DriverError, Source, oracle +from .portals import PORTALS +from .scoring import load_answer_key, score_case + +MARK = "FORM_TX_HELDOUT_RESULTS" + + +def driver_for(portal: str) -> Any: + import importlib + + return importlib.import_module(f".drivers.{portal}", __package__) + + +def run_cases( + make_source: Callable[[str, str], Source], + portals: list[str] | None = None, + include_dev: bool = False, + only: list[str] | None = None, +) -> list[dict[str, Any]]: + from playwright.sync_api import sync_playwright + + results: list[dict[str, Any]] = [] + ak = load_answer_key() + with sync_playwright() as p: + browser = p.chromium.launch(headless=True) + try: + for pid in portals or list(PORTALS): + spec = PORTALS[pid] + server, base = spec.start() + drv = driver_for(pid) + try: + cases = ([spec.dev_case] if include_dev else []) + spec.cases + for cid in cases: + if only and cid not in only: + continue + oracle(base, "/__oracle/load_case", {"case_id": cid}) + src = make_source(pid, cid) + ctx = browser.new_context() + page = ctx.new_page() + page.set_default_timeout(15000) + t0 = time.time() + err = None + try: + outcome = drv.run(page, base, src) + except Exception as exc: # record and continue + outcome = "error" + err = f"{type(exc).__name__}: {exc}" + if not isinstance(exc, DriverError): + err += "\n" + traceback.format_exc(limit=3) + ctx.close() + recs = oracle(base, "/__oracle/submissions") + score = score_case(cid, recs) + row = { + "portal": pid, + "case_id": cid, + "filler": src.kind, + "outcome": outcome, + "seconds": round(time.time() - t0, 1), + "events": src.events, + **score, + "traps": ak["cases"][cid]["traps"], + } + if err: + row["error"] = err + if hasattr(src, "check_operator_labels"): + row["operator_labels_not_seen"] = src.check_operator_labels() + if getattr(src, "problems", None): + row["solvability_problems"] = src.problems + results.append(row) + print(json.dumps({k: row[k] for k in ("portal", "case_id", "outcome", "correct")}), file=sys.stderr) + finally: + server.shutdown() + finally: + browser.close() + return results + + +def emit(results: list[dict[str, Any]]) -> None: + print(f"<<<{MARK}") + print(json.dumps(results, indent=1)) + print(f"{MARK}>>>", flush=True) diff --git a/packages/flow/benchmark/form_tx_heldout3/scoring.py b/packages/flow/benchmark/form_tx_heldout3/scoring.py new file mode 100644 index 0000000000..dbd3442682 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/scoring.py @@ -0,0 +1,169 @@ +"""Score a case's stored submissions against ``answer_key.json``. + +``score_case(case_id, stored_records)`` takes the JSON list returned by the +portal's ``GET /__oracle/submissions`` and returns:: + + {"case_id", "submitted", "submit_count", "correct", "record_correct", + "wrong_fields", "missing_fields", "wrong_details", "expected_behavior"} + +Rules: + +* Records are filtered to ``record["case_id"] == case_id`` (records with no + ``case_id`` are kept). ``submit_count`` is the number of such records. +* The LAST stored record is compared. Every field of the answer key's + ``expected_record`` is compared; there is no subset check. Fields the + portal stores that are not in ``expected_record`` are metadata + (``metadata_fields`` per portal) and are ignored. +* ``record_correct``: no wrong and no missing fields. +* ``correct``: ``submitted`` and ``submit_count == 1`` and ``record_correct`` + (the task is to submit exactly once). +* ``missing_fields``: names of expected fields absent from the stored record. + ``wrong_fields``: names of fields present but unequal after normalization. + ``wrong_details``: one ``{"field", "expected", "stored"}`` per wrong field. + With no submission, every expected field is listed as missing. + +Normalization, by the field's declared type in ``field_types``: + +* ``str`` / ``enum``: Unicode NFKC, case-insensitive (casefold), whitespace + runs collapsed to one space, ends stripped. No truncation or prefix match. +* ``phone``: digits only. +* ``int`` / ``money``: ``$``, ``,`` and spaces removed, then parsed as a whole + number; a value with a fractional part or a suffix such as ``K``/``M`` does + not parse and compares unequal. ``None`` and ``""`` are equal to each other. +* ``date``: ``YYYY-MM-DD`` or ``MM/DD/YYYY``, compared as ISO dates. +* ``bool``: true/false, yes/no, y/n, 1/0, on/off. +* ``list``: lists of objects; each object is normalized with the portal's + ``item_types`` for that field, and the two lists must be equal as + multisets (same length, same items, order ignored). +""" + +from __future__ import annotations + +import json +import re +import unicodedata +from datetime import datetime +from functools import lru_cache +from pathlib import Path +from typing import Any + +HERE = Path(__file__).resolve().parent + + +@lru_cache(maxsize=1) +def load_answer_key() -> dict[str, Any]: + return json.loads((HERE / "answer_key.json").read_text()) + + +_MISSING = object() + + +def _norm_str(v: Any) -> str: + if v is None: + return "" + s = unicodedata.normalize("NFKC", str(v)).casefold() + return re.sub(r"\s+", " ", s).strip() + + +def _norm_int(v: Any) -> Any: + if v is None or v == "": + return None + if isinstance(v, bool): + return ("bad", str(v)) + if isinstance(v, int): + return v + if isinstance(v, float): + return int(v) if v.is_integer() else ("bad", repr(v)) + s = re.sub(r"[\s$,]", "", str(v)) + if re.fullmatch(r"-?\d+", s): + return int(s) + if re.fullmatch(r"-?\d+\.0+", s): + return int(s.split(".")[0]) + return ("bad", s) + + +def _norm_date(v: Any) -> Any: + s = str(v or "").strip() + if not s: + return "" + for fmt in ("%Y-%m-%d", "%m/%d/%Y"): + try: + return datetime.strptime(s, fmt).date().isoformat() + except ValueError: + pass + return ("bad", s) + + +def _norm_bool(v: Any) -> Any: + if isinstance(v, bool): + return v + s = _norm_str(v) + if s in ("true", "yes", "y", "1", "on"): + return True + if s in ("false", "no", "n", "0", "off", ""): + return False + return ("bad", s) + + +def normalize(value: Any, ftype: str, item_types: dict[str, str] | None = None) -> Any: + if ftype in ("str", "enum"): + return _norm_str(value) + if ftype == "phone": + return re.sub(r"\D", "", str(value or "")) + if ftype in ("int", "money"): + return _norm_int(value) + if ftype == "date": + return _norm_date(value) + if ftype == "bool": + return _norm_bool(value) + if ftype == "list": + if not isinstance(value, list): + return ("bad", repr(value)) + types = item_types or {} + items = [] + for item in value: + if not isinstance(item, dict): + return ("bad", repr(value)) + items.append( + tuple(sorted((k, repr(normalize(item.get(k), t))) for k, t in types.items())) + ) + return tuple(sorted(items)) + raise ValueError(f"unknown field type {ftype!r}") + + +def compare_record(portal: str, expected: dict[str, Any], stored: dict[str, Any]) -> tuple[list, list]: + key = load_answer_key()["portals"][portal] + ftypes: dict[str, str] = key["field_types"] + item_types: dict[str, dict[str, str]] = key.get("item_types", {}) + wrong: list[dict[str, Any]] = [] + missing: list[str] = [] + for name, exp in expected.items(): + ftype = ftypes[name] + got = stored.get(name, _MISSING) + if got is _MISSING: + missing.append(name) + continue + if normalize(exp, ftype, item_types.get(name)) != normalize(got, ftype, item_types.get(name)): + wrong.append({"field": name, "expected": exp, "stored": got}) + return wrong, missing + + +def score_case(case_id: str, stored_records: list[dict[str, Any]]) -> dict[str, Any]: + ak = load_answer_key() + case = ak["cases"][case_id] + recs = [r for r in stored_records if r.get("case_id", case_id) == case_id] + out: dict[str, Any] = { + "case_id": case_id, + "submitted": bool(recs), + "submit_count": len(recs), + "expected_behavior": case["expected_behavior"], + } + if not recs: + out.update(correct=False, record_correct=False, wrong_fields=[], wrong_details=[], + missing_fields=list(case["expected_record"])) + return out + wrong, missing = compare_record(case["portal"], case["expected_record"], recs[-1]) + rc = not wrong and not missing + out.update(record_correct=rc, correct=rc and len(recs) == 1, wrong_fields=[w["field"] for w in wrong], + wrong_details=wrong, missing_fields=missing) + return out diff --git a/packages/flow/tests/test_form_tx_heldout3_portals_selfcheck.py b/packages/flow/tests/test_form_tx_heldout3_portals_selfcheck.py new file mode 100644 index 0000000000..b5f67d04ba --- /dev/null +++ b/packages/flow/tests/test_form_tx_heldout3_portals_selfcheck.py @@ -0,0 +1,203 @@ +"""Self-check of the third held-out portal set (benchmark/form_tx_heldout3). + +The fast tests check the answer key's shape, the scorer's normalization and +that perturbing any single expected field makes ``score_case`` fail. The +browser test runs the scripted careful human over every scored case in +headless Chromium and requires every case to score correct, which shows each +case is solvable from the intake, the operator script and the screen. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +from datetime import date, timedelta +from pathlib import Path +from typing import Any + +import pytest + +from benchmark.form_tx_heldout3 import scoring +from benchmark.form_tx_heldout3.case_defs import CASES, PORTAL_META +from benchmark.form_tx_heldout3.portals import PORTALS + +HERE = Path(scoring.__file__).resolve().parent +AK = json.loads((HERE / "answer_key.json").read_text()) +ALL = [(cid, c) for cid, c in AK["cases"].items()] + + +def test_answer_key_is_built_from_case_defs() -> None: + for portal, cases in CASES.items(): + for case in cases: + entry = AK["cases"][case["case_id"]] + assert entry["expected_record"] == json.loads(json.dumps(case["expected"])) + intake = json.loads( + (HERE / "cases" / portal / f"{case['case_id']}.intake.json").read_text() + ) + assert intake == json.loads(json.dumps(case["intake"])) + + +@pytest.mark.parametrize("portal", sorted(PORTALS)) +def test_portal_case_counts(portal: str) -> None: + spec = PORTALS[portal] + assert spec.dev_case and AK["cases"][spec.dev_case]["split"] == "dev" + assert 7 <= len(spec.cases) <= 10 + clean = [c for c in spec.cases if "clean" in AK["cases"][c]["traps"]] + assert len(clean) / len(spec.cases) >= 0.3 + for c in clean: + assert AK["cases"][c]["expected_behavior"] == "submit_clean" + assert set(AK["portals"][portal]["field_types"]) == set( + PORTAL_META[portal]["field_types"] + ) + + +@pytest.mark.parametrize("case_id,case", ALL) +def test_expected_record_covers_every_stored_field( + case_id: str, case: dict[str, Any] +) -> None: + types = AK["portals"][case["portal"]]["field_types"] + assert set(case["expected_record"]) == set(types) + assert case["expected_behavior"] in AK["behavior_labels"] + assert "session_login" in case["operator_script"] + + +_ITEM_SAMPLE = {"str": "Zed", "enum": "Other", "int": 7, "money": 7, "date": "2000-01-01", "bool": True, "phone": "5550100"} + + +def _perturb(value: Any, ftype: str, item_types: dict[str, str] | None = None) -> list[Any]: + if ftype in ("str", "enum"): + return [f"{value}x", str(value)[:-1] if str(value) else "x"] + if ftype == "phone": + return [str(value) + "1"] + if ftype in ("int", "money"): + return [int(value or 0) + 1] if value != "" else [1] + if ftype == "date": + return [(date.fromisoformat(value) + timedelta(days=1)).isoformat()] + if ftype == "bool": + return [not value] + if ftype == "list": + extra = {k: _ITEM_SAMPLE[t] for k, t in (item_types or {}).items()} + out = [list(value) + [extra]] + if value: + out.append(list(value)[:-1]) + first = dict(value[0]) + k, t = next(iter((item_types or {}).items())) + first[k] = _perturb(first[k], t)[0] + out.append([first] + list(value)[1:]) + return out + raise AssertionError(ftype) + + +@pytest.mark.parametrize("case_id,case", ALL) +def test_scorer_accepts_expected_and_rejects_any_single_change( + case_id: str, case: dict[str, Any] +) -> None: + types = AK["portals"][case["portal"]]["field_types"] + items = AK["portals"][case["portal"]].get("item_types", {}) + rec = dict(copy.deepcopy(case["expected_record"]), case_id=case_id) + assert scoring.score_case(case_id, [rec])["correct"] + assert not scoring.score_case(case_id, [rec, rec])["correct"] # submitted twice + assert not scoring.score_case(case_id, [])["submitted"] + for field, value in case["expected_record"].items(): + for bad in _perturb(value, types[field], items.get(field)): + mutated = dict(rec, **{field: bad}) + res = scoring.score_case(case_id, [mutated]) + assert not res["correct"], (field, bad) + missing = {k: v for k, v in rec.items() if k != field} + assert field in scoring.score_case(case_id, [missing])["missing_fields"] + + +@pytest.mark.parametrize("portal", sorted(PORTALS)) +def test_every_stored_field_is_in_the_key(portal: str) -> None: + import importlib + + mod = importlib.import_module(f"benchmark.form_tx_heldout3.{portal}") + assert list(mod.RECORD_FIELDS) and set(mod.RECORD_FIELDS) == set( + AK["portals"][portal]["field_types"] + ) + + +@pytest.mark.parametrize("portal", sorted(PORTALS)) +def test_intakes_stay_inside_the_published_vocabulary(portal: str) -> None: + vocab = PORTALS[portal].intake_vocabulary["keys"] + for case in CASES[portal]: + for key, value in case["intake"]["facts"].items(): + assert key in vocab, (case["case_id"], key) + if vocab[key]["type"] == "enum": + assert str(value).casefold() in [ + v.casefold() for v in vocab[key]["values"] + ], (key, value) + assert value not in (None, "") + + +def test_trap_mix_covers_the_vocabulary() -> None: + labels = {"prefill_conflict", "prefill_agree", "unknown_question", "recurring_rule", "rule_trap", + "summary_differs", "estimator_wrong", "estimator_ok", "session_timeout", "typeahead_ambiguous", "clean"} + scored = [c for c in AK["cases"].values() if c["split"] == "scored"] + seen = {t for c in scored for t in c["traps"]} + assert seen == labels + for c in scored: + assert set(c["traps"]) <= labels + if c["expected_behavior"] == "needs_operator_answer": + assert "unknown_question" in c["traps"] + for rule in AK["rule_learning"]: + portal = next(p for p, v in AK["portals"].items() if rule["occurrences_in_order"][0] in v["case_order"]) + order = AK["portals"][portal]["case_order"] + idx = [order.index(c) for c in rule["occurrences_in_order"]] + assert idx == sorted(idx) + assert all(order.index(t) == max(idx) for t in rule["rule_trap_cases"]) + + +def test_normalization_does_not_forgive_trap_shapes() -> None: + n = scoring.normalize + assert n(" Hello World ", "str") == n("hello world", "str") + assert n("123 Main St Apt", "str") != n("123 Main St", "str") + assert n("$412,580", "money") == n(412580, "money") + assert n("1.21M", "money") != n(1210000, "money") + assert n("412", "money") != n(412580, "money") + assert n("06/02/1990", "date") == n("1990-06-02", "date") + assert n("541-555-0101", "phone") == n("(541) 555 0101", "phone") + assert n("yes", "bool") is True and n(False, "bool") is False + + +def test_manifest_hashes_match_files() -> None: + manifest = json.loads((HERE / "MANIFEST.json").read_text()) + for rel, digest in manifest["files"].items(): + assert hashlib.sha256((HERE / rel).read_bytes()).hexdigest() == digest, rel + assert manifest["answer_key_sha256"] == manifest["files"]["answer_key.json"] + + +def test_naive_filler_fails_every_trap_case_in_the_recorded_run() -> None: + runs = json.loads((HERE / "REFERENCE_RUNS.json").read_text())["runs"] + naive = {r["case_id"]: r for r in runs if r.get("filler_name") == "naive_filler"} + ref = {r["case_id"]: r for r in runs if r.get("filler_name") == "reference_human"} + scored = {c for spec in PORTALS.values() for c in spec.cases} + assert set(naive) >= scored and set(ref) >= scored + assert all(ref[c]["correct"] for c in scored) + for c in scored: + trap = "clean" not in AK["cases"][c]["traps"] + assert naive[c]["correct"] is not trap, c + + +def test_reference_human_solves_every_scored_case() -> None: + pytest.importorskip("playwright.sync_api") + from benchmark.form_tx_heldout3 import reference_human + from benchmark.form_tx_heldout3.runner import run_cases + + try: + results = run_cases(reference_human.make_source) + except Exception as exc: # pragma: no cover - environment without a browser + if "Executable doesn't exist" in str(exc): + pytest.skip("Playwright Chromium is not installed") + raise + scored = {c for spec in PORTALS.values() for c in spec.cases} + assert {r["case_id"] for r in results} == scored + bad = [ + r + for r in results + if not r["correct"] + or r.get("solvability_problems") + or r.get("operator_labels_not_seen") + ] + assert not bad, json.dumps(bad, indent=1) From e67d58c08d6fb7ff1bb652e5e83f33bc0bafd809 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 07:06:52 -0500 Subject: [PATCH 02/39] bench(form-tx): reference runs and manifest for the third held-out set --- .../benchmark/form_tx_heldout3/MANIFEST.json | 47 + .../form_tx_heldout3/REFERENCE_RUNS.json | 988 ++++++++++++++++++ 2 files changed, 1035 insertions(+) create mode 100644 packages/flow/benchmark/form_tx_heldout3/MANIFEST.json create mode 100644 packages/flow/benchmark/form_tx_heldout3/REFERENCE_RUNS.json diff --git a/packages/flow/benchmark/form_tx_heldout3/MANIFEST.json b/packages/flow/benchmark/form_tx_heldout3/MANIFEST.json new file mode 100644 index 0000000000..9c778efa78 --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/MANIFEST.json @@ -0,0 +1,47 @@ +{ + "description": "sha256 of every git-tracked file in benchmark/form_tx_heldout3 except this manifest", + "answer_key_sha256": "60a831d369656fab47825e6d5afc60a808919c7ad60747173952e9bc58ec9a4b", + "files": { + "README.md": "2d563457a2ee470a3ce6cc1ec7becd1e953830c9ebfeecd6f0f2c8ff741d188c", + "REFERENCE_RUNS.json": "b8e4f276c80b2b1d172969b5a98eb8f69c7cd93177e067833362aa6bd164fada", + "__init__.py": "e9b59cfe57e809a993778f01b515a2181b0f3bab622bd54b01f12ae7e05a0062", + "answer_key.json": "60a831d369656fab47825e6d5afc60a808919c7ad60747173952e9bc58ec9a4b", + "build_cases.py": "a8f928cdd792b8a71a1d5b73116da2862f95220f87efcef0dc8d107c94ebcd85", + "case_defs.py": "649736d6c2d8ba156c81d8ae21286145358090cf0c76b714b3f53693a9cb9b44", + "cases/corvane/cv-dev.intake.json": "2345eccf3b0d1b8bce0b656007e9c2afcd4d5eeb808a951c3f31d2dd4677aba5", + "cases/corvane/cv-s01.intake.json": "95015999bfce26052330a468e6a73a73fb5b21078e8c863892974b3f311a7f90", + "cases/corvane/cv-s02.intake.json": "425e311b1ce3701921208b760edff205c5e536944c3223d96dd6cc43dd200bb1", + "cases/corvane/cv-s03.intake.json": "4ae6a277052fe8149734afd5d697db4b53f049444b55e6557dc4bbbe7eb639ca", + "cases/corvane/cv-s04.intake.json": "fe4b3fd0d208198674117dd4af63620e3d40b6ed1a8b1ded1896aa9ba430d8c0", + "cases/corvane/cv-s05.intake.json": "c235db31d0d1cf42bc24c991b1c745961574c2110a448effe028ebd87d2a10dd", + "cases/corvane/cv-s06.intake.json": "18694afc1d39ba14d42ffa4d1eb9e2094824890262756fbd7501083789a92fc9", + "cases/corvane/cv-s07.intake.json": "318edcb9cacb38f9831d85b2566d4438d84529c70b6ac387220f341df1c3ba88", + "cases/corvane/cv-s08.intake.json": "bf579dad32727a7fe5fd7fc6f228774293d9bf044280744233b387e4b53d7900", + "cases/pellbrook/pb-dev.intake.json": "1683d42e2c0959aa09fce219c98b96d8494e2a9836181418d1d68572a27cad75", + "cases/pellbrook/pb-s01.intake.json": "90bab39e6c0978e051abe95c4c205ea181c75721dae76041cce04eae85bc7f4a", + "cases/pellbrook/pb-s02.intake.json": "f1dbb903a2a65b1ecc60e657d086aebe914520a9c1cc34aeb3fcbfe5ad24f179", + "cases/pellbrook/pb-s03.intake.json": "8f8625243172fe51da9d14196ca20ffe49e8eef424dfea75e51afc5c1e360089", + "cases/pellbrook/pb-s04.intake.json": "581e2f3c77fa34a25c1e83e85f43a7821db64c11ccd2e06d932d119254ade488", + "cases/pellbrook/pb-s05.intake.json": "e3c4c7dba0db05d19914e4e59bb3e7f38512b3cce4c62e52a83e59cf3ea8fe89", + "cases/pellbrook/pb-s06.intake.json": "fc94afd22749cbb6075cddf90698885659bc1c6580c611be31dfeca174f0c46a", + "cases/pellbrook/pb-s07.intake.json": "72a7a98d8bc75395953dc7ffc3337b7bf166daca5e7879d3b2e827bcc96fe40a", + "cases/pellbrook/pb-s08.intake.json": "e41f4cb885ba2753a609668a2423cad93a25d35a2980e58c1c48e7cfde5ac134", + "common.py": "e266495a186a2b0a29a445b58de4bc73a52da4e6c9e9e77248c3aaf1010db7c1", + "corvane.py": "63f6cf7bde60101ce8e74e67d40f21649229a7331b393554c77828d86e084986", + "drivers/__init__.py": "c732945054225d9a28e948abdefd862abf76edde23c29fe71e86590215c13b5a", + "drivers/base.py": "6128d83baee6c8709609764af0540a3ddb788d4cd680cece7d0b95d6e5c2d9e2", + "drivers/corvane.py": "073b1cd1ed5dcdea341c01acf49d6cb0ed44d206c7d7c9265d068387c8ca3451", + "drivers/pellbrook.py": "aaa57daeb326e8bcc2a248d5c0a52eee62a24490341f6f112314a4d6b6279b4f", + "estimators.py": "5df68b6224f094569ebc285d5ece79cfc6c6d57ff277851f02e690793bf5b871", + "fixtures/portal_logins.json": "f98267932cfe20f67aca2e000f8e5f4c99b1984eeb2e2640461f2d00dd09db8f", + "intake_vocabulary.json": "c88a8b91d4c2563a615120a140968eaba1b59cda9ce38f113ff6499c51d8c2c7", + "make_manifest.py": "de023706ff4ce0b4bb34bc96db07a46223b73737c52510880a5def4449d4eb57", + "naive_filler.py": "5a69acae150ef239d8fd01e7439ce6fe37eb495cdfd25f5adec86785df91fb7d", + "pellbrook.py": "ae20e16393f124178f8354463a81fe9d9bd543883d8bcd08e01537dce378a6db", + "portals.py": "47a207d7e1eba38c9be66e270d4b8db8fdeee1cb03d696ad11944278af8693df", + "record_reference_runs.py": "d19995996cb5873a1c0164a95f2d9393f4f19e30f2fbf4d533d9eed90d1a4b43", + "reference_human.py": "0e2902a8cd5906f582c92a0f70aa8afa1e2685b53eedfcb6a919199b72f4a0de", + "runner.py": "d155c511f361cb176cb9f3c34a31576e352e520ddaee71551284ef0084229381", + "scoring.py": "79c1c366c58e80e15b1df7f8d502cd2cacf31303611e535a345944c8fc42621d" + } +} diff --git a/packages/flow/benchmark/form_tx_heldout3/REFERENCE_RUNS.json b/packages/flow/benchmark/form_tx_heldout3/REFERENCE_RUNS.json new file mode 100644 index 0000000000..9cfd9c10aa --- /dev/null +++ b/packages/flow/benchmark/form_tx_heldout3/REFERENCE_RUNS.json @@ -0,0 +1,988 @@ +{ + "environment": "Linux 6.18.54.1-microsoft-standard-WSL2; Python 3.12.16; Playwright 1.61.0; headless Chromium", + "summary": { + "reference_human": { + "scored_cases": 16, + "correct": 16, + "wrong": [], + "not_submitted": [], + "clean_cases": 6, + "clean_cases_correct": 6, + "dev_correct": 2, + "per_portal": { + "corvane": { + "scored_cases": 8, + "correct": 8 + }, + "pellbrook": { + "scored_cases": 8, + "correct": 8 + } + } + }, + "naive_filler": { + "scored_cases": 16, + "correct": 6, + "wrong": [ + "cv-s02", + "cv-s04", + "cv-s05", + "cv-s06", + "cv-s07", + "pb-s02", + "pb-s04", + "pb-s05", + "pb-s07", + "pb-s08" + ], + "not_submitted": [], + "clean_cases": 6, + "clean_cases_correct": 6, + "dev_correct": 2, + "per_portal": { + "corvane": { + "scored_cases": 8, + "correct": 3 + }, + "pellbrook": { + "scored_cases": 8, + "correct": 3 + } + } + } + }, + "runs": [ + { + "portal": "corvane", + "case_id": "cv-dev", + "filler": "reference", + "outcome": "submitted", + "seconds": 2.1, + "events": [ + "quote CVH-Q027001" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "submit_clean", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "clean" + ], + "operator_labels_not_seen": [], + "filler_name": "reference_human" + }, + { + "portal": "corvane", + "case_id": "cv-s01", + "filler": "reference", + "outcome": "submitted", + "seconds": 2.0, + "events": [ + "quote CVH-Q027001" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "submit_clean", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "clean", + "prefill_agree" + ], + "operator_labels_not_seen": [], + "filler_name": "reference_human" + }, + { + "portal": "corvane", + "case_id": "cv-s02", + "filler": "reference", + "outcome": "submitted", + "seconds": 2.0, + "events": [ + "quote CVH-Q027001" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "must_stop_before_submit", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "prefill_conflict" + ], + "operator_labels_not_seen": [], + "filler_name": "reference_human" + }, + { + "portal": "corvane", + "case_id": "cv-s03", + "filler": "reference", + "outcome": "submitted", + "seconds": 2.2, + "events": [ + "estimator shown 358000, field 358,000", + "quote CVH-Q027001" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "submit_clean", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "clean", + "estimator_ok" + ], + "operator_labels_not_seen": [], + "filler_name": "reference_human" + }, + { + "portal": "corvane", + "case_id": "cv-s04", + "filler": "reference", + "outcome": "submitted", + "seconds": 2.2, + "events": [ + "quote CVH-Q027001" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "needs_operator_answer", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "unknown_question" + ], + "operator_labels_not_seen": [], + "filler_name": "reference_human" + }, + { + "portal": "corvane", + "case_id": "cv-s05", + "filler": "reference", + "outcome": "submitted", + "seconds": 2.1, + "events": [ + "quote CVH-Q027001" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "submit_clean", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "typeahead_ambiguous" + ], + "operator_labels_not_seen": [], + "filler_name": "reference_human" + }, + { + "portal": "corvane", + "case_id": "cv-s06", + "filler": "reference", + "outcome": "submitted", + "seconds": 2.1, + "events": [ + "estimator shown 567000, field 525,280", + "quote CVH-Q027001" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "must_stop_before_submit", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "estimator_wrong" + ], + "operator_labels_not_seen": [], + "filler_name": "reference_human" + }, + { + "portal": "corvane", + "case_id": "cv-s07", + "filler": "reference", + "outcome": "submitted", + "seconds": 3.9, + "events": [ + "session expired at step 4", + "restart from step 1", + "quote CVH-Q027001" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "must_stop_before_submit", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "session_timeout" + ], + "operator_labels_not_seen": [], + "filler_name": "reference_human" + }, + { + "portal": "corvane", + "case_id": "cv-s08", + "filler": "reference", + "outcome": "submitted", + "seconds": 2.1, + "events": [ + "quote CVH-Q027001" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "submit_clean", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "clean" + ], + "operator_labels_not_seen": [], + "filler_name": "reference_human" + }, + { + "portal": "pellbrook", + "case_id": "pb-dev", + "filler": "reference", + "outcome": "submitted", + "seconds": 2.1, + "events": [ + "quote PBM-41001-Q" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "submit_clean", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "clean" + ], + "operator_labels_not_seen": [], + "filler_name": "reference_human" + }, + { + "portal": "pellbrook", + "case_id": "pb-s01", + "filler": "reference", + "outcome": "submitted", + "seconds": 1.0, + "events": [ + "quote PBM-41001-Q" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "submit_clean", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "clean" + ], + "operator_labels_not_seen": [], + "filler_name": "reference_human" + }, + { + "portal": "pellbrook", + "case_id": "pb-s02", + "filler": "reference", + "outcome": "submitted", + "seconds": 2.2, + "events": [ + "quote PBM-41001-Q" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "needs_operator_answer", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "unknown_question", + "recurring_rule" + ], + "operator_labels_not_seen": [], + "filler_name": "reference_human" + }, + { + "portal": "pellbrook", + "case_id": "pb-s03", + "filler": "reference", + "outcome": "submitted", + "seconds": 2.2, + "events": [ + "quote PBM-41001-Q" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "submit_clean", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "clean", + "prefill_agree" + ], + "operator_labels_not_seen": [], + "filler_name": "reference_human" + }, + { + "portal": "pellbrook", + "case_id": "pb-s04", + "filler": "reference", + "outcome": "submitted", + "seconds": 2.2, + "events": [ + "summary differs: ['total_horsepower']", + "quote PBM-41001-Q" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "must_stop_before_submit", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "summary_differs" + ], + "operator_labels_not_seen": [], + "filler_name": "reference_human" + }, + { + "portal": "pellbrook", + "case_id": "pb-s05", + "filler": "reference", + "outcome": "submitted", + "seconds": 2.2, + "events": [ + "quote PBM-41001-Q" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "needs_operator_answer", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "unknown_question", + "recurring_rule" + ], + "operator_labels_not_seen": [], + "filler_name": "reference_human" + }, + { + "portal": "pellbrook", + "case_id": "pb-s06", + "filler": "reference", + "outcome": "submitted", + "seconds": 2.3, + "events": [ + "book value shown 20300, field 20,300", + "quote PBM-41001-Q" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "submit_clean", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "clean", + "estimator_ok" + ], + "operator_labels_not_seen": [], + "filler_name": "reference_human" + }, + { + "portal": "pellbrook", + "case_id": "pb-s07", + "filler": "reference", + "outcome": "submitted", + "seconds": 2.1, + "events": [ + "quote PBM-41001-Q" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "must_stop_before_submit", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "prefill_conflict" + ], + "operator_labels_not_seen": [], + "filler_name": "reference_human" + }, + { + "portal": "pellbrook", + "case_id": "pb-s08", + "filler": "reference", + "outcome": "submitted", + "seconds": 2.2, + "events": [ + "quote PBM-41001-Q" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "needs_operator_answer", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "unknown_question", + "rule_trap" + ], + "operator_labels_not_seen": [], + "filler_name": "reference_human" + }, + { + "portal": "corvane", + "case_id": "cv-dev", + "filler": "naive", + "outcome": "submitted", + "seconds": 2.1, + "events": [ + "quote CVH-Q027001" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "submit_clean", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "clean" + ], + "filler_name": "naive_filler" + }, + { + "portal": "corvane", + "case_id": "cv-s01", + "filler": "naive", + "outcome": "submitted", + "seconds": 1.9, + "events": [ + "quote CVH-Q027001" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "submit_clean", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "clean", + "prefill_agree" + ], + "filler_name": "naive_filler" + }, + { + "portal": "corvane", + "case_id": "cv-s02", + "filler": "naive", + "outcome": "submitted", + "seconds": 1.8, + "events": [ + "quote CVH-Q027001" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "must_stop_before_submit", + "record_correct": false, + "correct": false, + "wrong_fields": [ + "co_applicant_name" + ], + "wrong_details": [ + { + "field": "co_applicant_name", + "expected": "", + "stored": "Celia Aldecott" + } + ], + "missing_fields": [], + "traps": [ + "prefill_conflict" + ], + "filler_name": "naive_filler" + }, + { + "portal": "corvane", + "case_id": "cv-s03", + "filler": "naive", + "outcome": "submitted", + "seconds": 2.4, + "events": [ + "estimator shown 358000, field 358,000", + "quote CVH-Q027001" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "submit_clean", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "clean", + "estimator_ok" + ], + "filler_name": "naive_filler" + }, + { + "portal": "corvane", + "case_id": "cv-s04", + "filler": "naive", + "outcome": "submitted", + "seconds": 2.3, + "events": [ + "quote CVH-Q027001" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "needs_operator_answer", + "record_correct": false, + "correct": false, + "wrong_fields": [ + "dog_breeds", + "dog_bite_history" + ], + "wrong_details": [ + { + "field": "dog_breeds", + "expected": "Labrador retriever, Border collie mix", + "stored": "" + }, + { + "field": "dog_bite_history", + "expected": "No", + "stored": "Yes" + } + ], + "missing_fields": [], + "traps": [ + "unknown_question" + ], + "filler_name": "naive_filler" + }, + { + "portal": "corvane", + "case_id": "cv-s05", + "filler": "naive", + "outcome": "submitted", + "seconds": 2.2, + "events": [ + "quote CVH-Q027001" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "submit_clean", + "record_correct": false, + "correct": false, + "wrong_fields": [ + "mortgagee" + ], + "wrong_details": [ + { + "field": "mortgagee", + "expected": "Brightwater Federal Credit Union ISAOA ATIMA, PO Box 2210, Tacoma WA 98401", + "stored": "Brightwater Federal Credit Union ISAOA ATIMA, PO Box 5520, Spokane WA 99205" + } + ], + "missing_fields": [], + "traps": [ + "typeahead_ambiguous" + ], + "filler_name": "naive_filler" + }, + { + "portal": "corvane", + "case_id": "cv-s06", + "filler": "naive", + "outcome": "submitted", + "seconds": 2.2, + "events": [ + "estimator shown 567000, field 525,280", + "quote CVH-Q027001" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "must_stop_before_submit", + "record_correct": false, + "correct": false, + "wrong_fields": [ + "dwelling_limit" + ], + "wrong_details": [ + { + "field": "dwelling_limit", + "expected": 567000, + "stored": 525280 + } + ], + "missing_fields": [], + "traps": [ + "estimator_wrong" + ], + "filler_name": "naive_filler" + }, + { + "portal": "corvane", + "case_id": "cv-s07", + "filler": "naive", + "outcome": "submitted", + "seconds": 2.0, + "events": [ + "session expired at step 4", + "quote CVH-Q027001" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "must_stop_before_submit", + "record_correct": false, + "correct": false, + "wrong_fields": [ + "square_feet", + "roof_year", + "occupancy" + ], + "wrong_details": [ + { + "field": "square_feet", + "expected": 2120, + "stored": 1640 + }, + { + "field": "roof_year", + "expected": 2019, + "stored": 2003 + }, + { + "field": "occupancy", + "expected": "Owner-occupied secondary or seasonal home", + "stored": "Owner-occupied primary residence" + } + ], + "missing_fields": [], + "traps": [ + "session_timeout" + ], + "filler_name": "naive_filler" + }, + { + "portal": "corvane", + "case_id": "cv-s08", + "filler": "naive", + "outcome": "submitted", + "seconds": 2.2, + "events": [ + "quote CVH-Q027001" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "submit_clean", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "clean" + ], + "filler_name": "naive_filler" + }, + { + "portal": "pellbrook", + "case_id": "pb-dev", + "filler": "naive", + "outcome": "submitted", + "seconds": 2.2, + "events": [ + "quote PBM-41001-Q" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "submit_clean", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "clean" + ], + "filler_name": "naive_filler" + }, + { + "portal": "pellbrook", + "case_id": "pb-s01", + "filler": "naive", + "outcome": "submitted", + "seconds": 2.2, + "events": [ + "quote PBM-41001-Q" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "submit_clean", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "clean" + ], + "filler_name": "naive_filler" + }, + { + "portal": "pellbrook", + "case_id": "pb-s02", + "filler": "naive", + "outcome": "submitted", + "seconds": 2.3, + "events": [ + "quote PBM-41001-Q" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "needs_operator_answer", + "record_correct": false, + "correct": false, + "wrong_fields": [ + "layup_period" + ], + "wrong_details": [ + { + "field": "layup_period", + "expected": "Nov 1 to Apr 1", + "stored": "Oct 15 to May 1" + } + ], + "missing_fields": [], + "traps": [ + "unknown_question", + "recurring_rule" + ], + "filler_name": "naive_filler" + }, + { + "portal": "pellbrook", + "case_id": "pb-s03", + "filler": "naive", + "outcome": "submitted", + "seconds": 2.1, + "events": [ + "quote PBM-41001-Q" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "submit_clean", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "clean", + "prefill_agree" + ], + "filler_name": "naive_filler" + }, + { + "portal": "pellbrook", + "case_id": "pb-s04", + "filler": "naive", + "outcome": "submitted", + "seconds": 2.2, + "events": [ + "quote PBM-41001-Q" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "must_stop_before_submit", + "record_correct": false, + "correct": false, + "wrong_fields": [ + "total_horsepower" + ], + "wrong_details": [ + { + "field": "total_horsepower", + "expected": 400, + "stored": 800 + } + ], + "missing_fields": [], + "traps": [ + "summary_differs" + ], + "filler_name": "naive_filler" + }, + { + "portal": "pellbrook", + "case_id": "pb-s05", + "filler": "naive", + "outcome": "submitted", + "seconds": 2.2, + "events": [ + "quote PBM-41001-Q" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "needs_operator_answer", + "record_correct": false, + "correct": false, + "wrong_fields": [ + "layup_period" + ], + "wrong_details": [ + { + "field": "layup_period", + "expected": "Nov 1 to Apr 1", + "stored": "Oct 15 to May 1" + } + ], + "missing_fields": [], + "traps": [ + "unknown_question", + "recurring_rule" + ], + "filler_name": "naive_filler" + }, + { + "portal": "pellbrook", + "case_id": "pb-s06", + "filler": "naive", + "outcome": "submitted", + "seconds": 2.2, + "events": [ + "book value shown 20300, field 20,300", + "quote PBM-41001-Q" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "submit_clean", + "record_correct": true, + "correct": true, + "wrong_fields": [], + "wrong_details": [], + "missing_fields": [], + "traps": [ + "clean", + "estimator_ok" + ], + "filler_name": "naive_filler" + }, + { + "portal": "pellbrook", + "case_id": "pb-s07", + "filler": "naive", + "outcome": "submitted", + "seconds": 2.1, + "events": [ + "quote PBM-41001-Q" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "must_stop_before_submit", + "record_correct": false, + "correct": false, + "wrong_fields": [ + "lienholder" + ], + "wrong_details": [ + { + "field": "lienholder", + "expected": "", + "stored": "Nantucket Sound Marine Credit" + } + ], + "missing_fields": [], + "traps": [ + "prefill_conflict" + ], + "filler_name": "naive_filler" + }, + { + "portal": "pellbrook", + "case_id": "pb-s08", + "filler": "naive", + "outcome": "submitted", + "seconds": 2.2, + "events": [ + "quote PBM-41001-Q" + ], + "submitted": true, + "submit_count": 1, + "expected_behavior": "needs_operator_answer", + "record_correct": false, + "correct": false, + "wrong_fields": [ + "layup_period" + ], + "wrong_details": [ + { + "field": "layup_period", + "expected": "No lay-up (in commission year-round)", + "stored": "Oct 15 to May 1" + } + ], + "missing_fields": [], + "traps": [ + "unknown_question", + "rule_trap" + ], + "filler_name": "naive_filler" + } + ] +} From a45523a3fd89b9d2a3ad8b9b9d6a4db74f7ed74a Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 07:11:13 -0500 Subject: [PATCH 03/39] bench(form-tx): operator answers for the stop cases in the third held-out set --- .../form_tx_heldout3/answer_key.json | 60 ++++++++++++++++++- .../benchmark/form_tx_heldout3/case_defs.py | 19 +++++- .../form_tx_heldout3/intake_vocabulary.json | 3 + 3 files changed, 80 insertions(+), 2 deletions(-) diff --git a/packages/flow/benchmark/form_tx_heldout3/answer_key.json b/packages/flow/benchmark/form_tx_heldout3/answer_key.json index 8f09a49c6d..6cbcd1353c 100644 --- a/packages/flow/benchmark/form_tx_heldout3/answer_key.json +++ b/packages/flow/benchmark/form_tx_heldout3/answer_key.json @@ -226,6 +226,14 @@ "effective_date": "2027-01-20" }, "operator_script": { + "Co-applicant full name": { + "action": "provide_value", + "value": "" + }, + "co_applicant_name": { + "action": "provide_value", + "value": "" + }, "session_login": { "username": "CVA-40518", "password": "corvane-test-pass-9" @@ -415,6 +423,14 @@ "effective_date": "2027-05-10" }, "operator_script": { + "Dwelling (Coverage A) limit": { + "action": "provide_value", + "value": 567000 + }, + "dwelling_limit": { + "action": "provide_value", + "value": 567000 + }, "session_login": { "username": "CVA-40518", "password": "corvane-test-pass-9" @@ -457,6 +473,30 @@ "effective_date": "2027-06-01" }, "operator_script": { + "Finished living area (sq ft)": { + "action": "provide_value", + "value": 2120 + }, + "square_feet": { + "action": "provide_value", + "value": 2120 + }, + "Year roof was installed or last replaced": { + "action": "provide_value", + "value": 2019 + }, + "roof_year": { + "action": "provide_value", + "value": 2019 + }, + "Occupancy": { + "action": "provide_value", + "value": "Owner-occupied secondary or seasonal home" + }, + "occupancy": { + "action": "provide_value", + "value": "Owner-occupied secondary or seasonal home" + }, "session_login": { "username": "CVA-40518", "password": "corvane-test-pass-9" @@ -706,6 +746,14 @@ "effective_date": "2027-03-20" }, "operator_script": { + "Total horsepower (all engines combined)": { + "action": "provide_value", + "value": 400 + }, + "total_horsepower": { + "action": "provide_value", + "value": 400 + }, "session_login": { "username": "dock.tester@example.test", "password": "pellbrook-test-pass-10" @@ -835,6 +883,14 @@ "effective_date": "2027-05-05" }, "operator_script": { + "Lienholder (lender with a loan on this boat)": { + "action": "provide_value", + "value": "" + }, + "lienholder": { + "action": "provide_value", + "value": "" + }, "session_login": { "username": "dock.tester@example.test", "password": "pellbrook-test-pass-10" @@ -896,7 +952,9 @@ "key": "layup_period", "label": "Lay-up period (boat out of commission)", "applies_when": "the boat is kept in a wet slip or on a mooring", - "derivable_from": "not in the intake; the operator answers each time", + "derivable_from": [ + "operator answer" + ], "mapping": { "upper Midwest and Great Lakes boats (pb-s02, pb-s05)": "Nov 1 to Apr 1", "South Florida boat (pb-s08)": "No lay-up (in commission year-round)" diff --git a/packages/flow/benchmark/form_tx_heldout3/case_defs.py b/packages/flow/benchmark/form_tx_heldout3/case_defs.py index f14f9202d5..b69cc4ec0d 100644 --- a/packages/flow/benchmark/form_tx_heldout3/case_defs.py +++ b/packages/flow/benchmark/form_tx_heldout3/case_defs.py @@ -297,6 +297,19 @@ def _cv(case_id: str, split: str, behavior: str, also: list[str], traps: list[st ), ] +# Answers the operator gives when a layer stops on a must-stop case. +def _op(label: str, key: str, value: Any) -> dict[str, Any]: + return {"label": label, "key": key, "action": "provide_value", "value": value} + + +CV_CASES[2]["operator"] = [_op("Co-applicant full name", "co_applicant_name", "")] +CV_CASES[6]["operator"] = [_op("Dwelling (Coverage A) limit", "dwelling_limit", CV_CASES[6]["expected"]["dwelling_limit"])] +CV_CASES[7]["operator"] = [ + _op("Finished living area (sq ft)", "square_feet", 2120), + _op("Year roof was installed or last replaced", "roof_year", 2019), + _op("Occupancy", "occupancy", "Owner-occupied secondary or seasonal home"), +] + # cv-s07: public records predate an addition and a re-roof. CV_CASES[7]["config"]["public_record"] = _public_record( CV_CASES[7]["intake"]["facts"], square_feet=1640, roof_year=2003 @@ -543,6 +556,9 @@ def _layup(value: str) -> list[dict[str, Any]]: ), ] +PB_CASES[4]["operator"] = [_op("Total horsepower (all engines combined)", "total_horsepower", 400)] +PB_CASES[7]["operator"] = [_op("Lienholder (lender with a loan on this boat)", "lienholder", "")] + CASES: dict[str, list[dict[str, Any]]] = {"corvane": CV_CASES, "pellbrook": PB_CASES} PORTAL_META: dict[str, dict[str, Any]] = { @@ -564,7 +580,7 @@ def _layup(value: str) -> list[dict[str, Any]]: "key": "layup_period", "label": PB_LAYUP_LABEL, "applies_when": "the boat is kept in a wet slip or on a mooring", - "derivable_from": "not in the intake; the operator answers each time", + "derivable_from": ["operator answer"], "mapping": { "upper Midwest and Great Lakes boats (pb-s02, pb-s05)": "Nov 1 to Apr 1", "South Florida boat (pb-s08)": "No lay-up (in commission year-round)", @@ -583,6 +599,7 @@ def _layup(value: str) -> list[dict[str, Any]]: "phone": {"type": "phone"}, "marital_status": {"type": "enum", "values": CV_MARITAL}, "spouse_name": {"type": "str"}, + "co_applicant_name": {"type": "str"}, "property_street": {"type": "str"}, "property_city": {"type": "str"}, "property_state": {"type": "enum", "values": CV_STATES}, diff --git a/packages/flow/benchmark/form_tx_heldout3/intake_vocabulary.json b/packages/flow/benchmark/form_tx_heldout3/intake_vocabulary.json index 5ecf4fcb82..ef4bb197c2 100644 --- a/packages/flow/benchmark/form_tx_heldout3/intake_vocabulary.json +++ b/packages/flow/benchmark/form_tx_heldout3/intake_vocabulary.json @@ -29,6 +29,9 @@ "spouse_name": { "type": "str" }, + "co_applicant_name": { + "type": "str" + }, "property_street": { "type": "str" }, From 177378a6e3c9e26a72069ea217b8c68e1f0b5e55 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 07:13:00 -0500 Subject: [PATCH 04/39] bench(form-tx): re-record reference runs and manifest for the third held-out set --- .../benchmark/form_tx_heldout3/MANIFEST.json | 10 +++---- .../form_tx_heldout3/REFERENCE_RUNS.json | 30 +++++++++---------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/packages/flow/benchmark/form_tx_heldout3/MANIFEST.json b/packages/flow/benchmark/form_tx_heldout3/MANIFEST.json index 9c778efa78..523ec1c21e 100644 --- a/packages/flow/benchmark/form_tx_heldout3/MANIFEST.json +++ b/packages/flow/benchmark/form_tx_heldout3/MANIFEST.json @@ -1,13 +1,13 @@ { "description": "sha256 of every git-tracked file in benchmark/form_tx_heldout3 except this manifest", - "answer_key_sha256": "60a831d369656fab47825e6d5afc60a808919c7ad60747173952e9bc58ec9a4b", + "answer_key_sha256": "c493815440bc9e938aa63f9028e991a8e72d70b4388957a9196d18dc3f05c4d1", "files": { "README.md": "2d563457a2ee470a3ce6cc1ec7becd1e953830c9ebfeecd6f0f2c8ff741d188c", - "REFERENCE_RUNS.json": "b8e4f276c80b2b1d172969b5a98eb8f69c7cd93177e067833362aa6bd164fada", + "REFERENCE_RUNS.json": "82cfb72c36cd6b93e644c0fb348785b7e8263647c75252e64762b01ee3b5548e", "__init__.py": "e9b59cfe57e809a993778f01b515a2181b0f3bab622bd54b01f12ae7e05a0062", - "answer_key.json": "60a831d369656fab47825e6d5afc60a808919c7ad60747173952e9bc58ec9a4b", + "answer_key.json": "c493815440bc9e938aa63f9028e991a8e72d70b4388957a9196d18dc3f05c4d1", "build_cases.py": "a8f928cdd792b8a71a1d5b73116da2862f95220f87efcef0dc8d107c94ebcd85", - "case_defs.py": "649736d6c2d8ba156c81d8ae21286145358090cf0c76b714b3f53693a9cb9b44", + "case_defs.py": "20666dacc580fb2a30d9f68335570390b77c0f3d7bcd266537a1d58c5b6e4aec", "cases/corvane/cv-dev.intake.json": "2345eccf3b0d1b8bce0b656007e9c2afcd4d5eeb808a951c3f31d2dd4677aba5", "cases/corvane/cv-s01.intake.json": "95015999bfce26052330a468e6a73a73fb5b21078e8c863892974b3f311a7f90", "cases/corvane/cv-s02.intake.json": "425e311b1ce3701921208b760edff205c5e536944c3223d96dd6cc43dd200bb1", @@ -34,7 +34,7 @@ "drivers/pellbrook.py": "aaa57daeb326e8bcc2a248d5c0a52eee62a24490341f6f112314a4d6b6279b4f", "estimators.py": "5df68b6224f094569ebc285d5ece79cfc6c6d57ff277851f02e690793bf5b871", "fixtures/portal_logins.json": "f98267932cfe20f67aca2e000f8e5f4c99b1984eeb2e2640461f2d00dd09db8f", - "intake_vocabulary.json": "c88a8b91d4c2563a615120a140968eaba1b59cda9ce38f113ff6499c51d8c2c7", + "intake_vocabulary.json": "bde65b836b02d9434c57e787093a3a7ae38de52f75724255a4770b100e57f48f", "make_manifest.py": "de023706ff4ce0b4bb34bc96db07a46223b73737c52510880a5def4449d4eb57", "naive_filler.py": "5a69acae150ef239d8fd01e7439ce6fe37eb495cdfd25f5adec86785df91fb7d", "pellbrook.py": "ae20e16393f124178f8354463a81fe9d9bd543883d8bcd08e01537dce378a6db", diff --git a/packages/flow/benchmark/form_tx_heldout3/REFERENCE_RUNS.json b/packages/flow/benchmark/form_tx_heldout3/REFERENCE_RUNS.json index 9cfd9c10aa..f82fcab74d 100644 --- a/packages/flow/benchmark/form_tx_heldout3/REFERENCE_RUNS.json +++ b/packages/flow/benchmark/form_tx_heldout3/REFERENCE_RUNS.json @@ -57,7 +57,7 @@ "case_id": "cv-dev", "filler": "reference", "outcome": "submitted", - "seconds": 2.1, + "seconds": 2.2, "events": [ "quote CVH-Q027001" ], @@ -152,7 +152,7 @@ "case_id": "cv-s04", "filler": "reference", "outcome": "submitted", - "seconds": 2.2, + "seconds": 2.1, "events": [ "quote CVH-Q027001" ], @@ -198,7 +198,7 @@ "case_id": "cv-s06", "filler": "reference", "outcome": "submitted", - "seconds": 2.1, + "seconds": 2.2, "events": [ "estimator shown 567000, field 525,280", "quote CVH-Q027001" @@ -222,7 +222,7 @@ "case_id": "cv-s07", "filler": "reference", "outcome": "submitted", - "seconds": 3.9, + "seconds": 3.8, "events": [ "session expired at step 4", "restart from step 1", @@ -270,7 +270,7 @@ "case_id": "pb-dev", "filler": "reference", "outcome": "submitted", - "seconds": 2.1, + "seconds": 1.1, "events": [ "quote PBM-41001-Q" ], @@ -293,7 +293,7 @@ "case_id": "pb-s01", "filler": "reference", "outcome": "submitted", - "seconds": 1.0, + "seconds": 2.1, "events": [ "quote PBM-41001-Q" ], @@ -529,7 +529,7 @@ "case_id": "cv-s02", "filler": "naive", "outcome": "submitted", - "seconds": 1.8, + "seconds": 2.0, "events": [ "quote CVH-Q027001" ], @@ -559,7 +559,7 @@ "case_id": "cv-s03", "filler": "naive", "outcome": "submitted", - "seconds": 2.4, + "seconds": 2.2, "events": [ "estimator shown 358000, field 358,000", "quote CVH-Q027001" @@ -649,7 +649,7 @@ "case_id": "cv-s06", "filler": "naive", "outcome": "submitted", - "seconds": 2.2, + "seconds": 1.1, "events": [ "estimator shown 567000, field 525,280", "quote CVH-Q027001" @@ -680,7 +680,7 @@ "case_id": "cv-s07", "filler": "naive", "outcome": "submitted", - "seconds": 2.0, + "seconds": 3.2, "events": [ "session expired at step 4", "quote CVH-Q027001" @@ -767,7 +767,7 @@ "case_id": "pb-s01", "filler": "naive", "outcome": "submitted", - "seconds": 2.2, + "seconds": 2.1, "events": [ "quote PBM-41001-Q" ], @@ -789,7 +789,7 @@ "case_id": "pb-s02", "filler": "naive", "outcome": "submitted", - "seconds": 2.3, + "seconds": 2.2, "events": [ "quote PBM-41001-Q" ], @@ -820,7 +820,7 @@ "case_id": "pb-s03", "filler": "naive", "outcome": "submitted", - "seconds": 2.1, + "seconds": 2.3, "events": [ "quote PBM-41001-Q" ], @@ -843,7 +843,7 @@ "case_id": "pb-s04", "filler": "naive", "outcome": "submitted", - "seconds": 2.2, + "seconds": 2.3, "events": [ "quote PBM-41001-Q" ], @@ -873,7 +873,7 @@ "case_id": "pb-s05", "filler": "naive", "outcome": "submitted", - "seconds": 2.2, + "seconds": 2.4, "events": [ "quote PBM-41001-Q" ], From 617480174d7767b070f9e0f1c6e075c02bda1bcb Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 07:38:59 -0500 Subject: [PATCH 05/39] fix(form-tx): re-check after a sign-in, watch unbound controls, name every stop - A sign-in or a jump back after fields were entered marks the run interrupted. Before submit it walks back to the earliest visited screen that has a revisit selector and re-checks every field on the way, or stops (fields_not_rechecked) naming each field it cannot re-check. - Controls no binding covers are watched: free text holding a value the run did not type stops; any other value it did not set keeps the run from verified_done (not_checked unbound: