From 67876171d285860b59cbce3bb13635bb442465fb Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 29 Nov 2026 21:58:10 -0500 Subject: [PATCH 1/3] fix(flow): readiness import reads minimized network captures Since #2480, network captures keep only declared fields by default and write `body_minimized` instead of `body`. `readiness import` still read `body`, found none, and refused every recorded task with `save_unreadable`. That included recordings made exactly as READINESS.md said, and four nightly readiness e2e tests failed. The importer now rebuilds the save from the kept fields. A field the comparison needs (the task's `fields`, else every field of the save) that was withheld refuses the task with `save_fields_withheld`, naming the field and the recording flag that keeps it, instead of comparing part of the save. Withheld session tokens and secrets are expected and are counted, as for a raw body. READINESS.md now says to record with `--identifier`/`--param` for the save's fields, and the e2e recorder declares them. --- packages/flow/docs/READINESS.md | 9 ++- .../openadapt_flow/readiness/reference.py | 58 ++++++++++++++++- packages/flow/tests/e2e/test_readiness_e2e.py | 8 ++- .../flow/tests/test_readiness_reference.py | 64 +++++++++++++++++++ 4 files changed, 134 insertions(+), 5 deletions(-) diff --git a/packages/flow/docs/READINESS.md b/packages/flow/docs/READINESS.md index 19a88c1829..10fa19b92a 100644 --- a/packages/flow/docs/READINESS.md +++ b/packages/flow/docs/READINESS.md @@ -5,9 +5,12 @@ a compiled program, is allowed to save anything: on the tasks your people already do, how often would it have saved exactly what they saved? 1. A person does 20 to 50 real tasks with the browser recording's network - capture on (`record --backend web --capture-network`, see - [BROWSER_RECORDING.md](BROWSER_RECORDING.md) and - [NETWORK_CAPTURE.md](NETWORK_CAPTURE.md)). + capture on, declaring each field the save carries + (`record --backend web --capture-network --identifier patient_id --param type --param note`, + see [BROWSER_RECORDING.md](BROWSER_RECORDING.md) and + [NETWORK_CAPTURE.md](NETWORK_CAPTURE.md)). Captures keep only declared + values, so `readiness import` refuses a task whose compared fields were + withheld (`save_fields_withheld`) instead of comparing part of the save. 2. `readiness import` turns each recorded task into a reference episode. 3. `readiness run` gives the candidate the same tasks on a guarded browser tab. It navigates and fills every field; the shadow hold stops it before diff --git a/packages/flow/openadapt_flow/readiness/reference.py b/packages/flow/openadapt_flow/readiness/reference.py index 5423265f6c..6c95d1f98f 100644 --- a/packages/flow/openadapt_flow/readiness/reference.py +++ b/packages/flow/openadapt_flow/readiness/reference.py @@ -269,15 +269,21 @@ def _from_network( return None rows = network_capture.load(recording) line = _save_line(rows, raw, app_origin) + body = line.get("body") + minimized = line.get("body_minimized") + secrets_withheld = 0 + if body is None and isinstance(minimized, Mapping): + body, secrets_withheld = _kept_body(minimized, raw) fields, withheld = parse_body_fields( method=str(line.get("method")), url=str(line.get("url")), content_type=str(line.get("request_type") or ""), - body=line.get("body"), + body=body, lens=lens, form_pairs=line.get("form"), body_omitted=bool(line.get("body_omitted") or line.get("request_truncated")), ) + withheld += secrets_withheld if any(f.name == "" for f in fields): raise ReferenceRefused( "save_unreadable", "the capture did not keep the save's body" @@ -324,6 +330,56 @@ def stamp(t: Optional[float]) -> Optional[str]: } +def _kept_body(minimized: Mapping[str, Any], raw: Mapping[str, Any]) -> tuple[str, int]: + """The save's body rebuilt from a minimized capture's kept fields. + + Since captures keep only declared fields by default, a save recorded + without declaring its fields has every value withheld (hashed). The + comparison needs the person's values, so a field it compares must have + been kept: the task's ``fields`` when it names them, else every field of + the save. A withheld one refuses the task, naming the field and the + recording flag that keeps it, instead of comparing part of the save. + Session tokens and secrets are never compared, so their being withheld + is expected; they are counted, as for a raw body. Returns the rebuilt + body and that count. + """ + from openadapt_flow.agent_guard.shadow_hold import is_withheld_name + from openadapt_flow.capture_privacy import restore_kept_json + + kept = { + str(item[0]).rsplit(".", 1)[-1].lower() + for item in minimized.get("kept") or [] + if isinstance(item, list) and len(item) == 2 + } + withheld_paths = [ + str(item[0]) + for item in minimized.get("withheld") or [] + if isinstance(item, list) and item + ] + secrets = [w for w in withheld_paths if is_withheld_name(w)] + withheld = [w for w in withheld_paths if not is_withheld_name(w)] + wanted = raw.get("fields") + if isinstance(wanted, list) and wanted: + needed = {str(name).lower() for name in wanted} + missing = sorted(n for n in needed if n not in kept) + else: + missing = sorted({w.rsplit(".", 1)[-1] for w in withheld}) + if missing or not kept: + names = ", ".join(missing) or "every field" + raise ReferenceRefused( + "save_fields_withheld", + f"the capture withheld the save's {names}; record with each field " + "declared (--param or --identifier), or with " + "--capture-network-bodies raw on a sealed recording", + ) + restored = restore_kept_json(minimized) + if not restored: + raise ReferenceRefused( + "save_unreadable", "the capture did not keep the save's body" + ) + return restored.decode("utf-8"), len(secrets) + + def network_capture_path(url: str) -> str: from urllib.parse import urlsplit diff --git a/packages/flow/tests/e2e/test_readiness_e2e.py b/packages/flow/tests/e2e/test_readiness_e2e.py index c73152238b..abfae94761 100644 --- a/packages/flow/tests/e2e/test_readiness_e2e.py +++ b/packages/flow/tests/e2e/test_readiness_e2e.py @@ -62,6 +62,10 @@ def write_sample(runs: Path, task_id: str, card_dir: Path, name: str) -> None: ) +# The fields the MockMed save carries (``POST /api/encounter``). +SAVE_FIELDS = ("patient_id", "type", "note") + + def _episode(i: int) -> dict[str, Any]: pid = list(PATIENTS)[i % 3] return { @@ -189,7 +193,9 @@ def _record_people(app_url: str, src: Path, n: int) -> None: rec = folder / "recording" rec.mkdir(parents=True) context = browser.new_context(viewport={"width": 1280, "height": 800}) - capture = NetworkCapture(context).start() + # Declare the save's fields, as `record --param` does: captures + # keep only declared values, and the comparison needs them. + capture = NetworkCapture(context, keep_fields=SAVE_FIELDS).start() t0 = time.monotonic() events: list[dict[str, Any]] = [] page = context.new_page() diff --git a/packages/flow/tests/test_readiness_reference.py b/packages/flow/tests/test_readiness_reference.py index 4e35d30fcd..2106ac7290 100644 --- a/packages/flow/tests/test_readiness_reference.py +++ b/packages/flow/tests/test_readiness_reference.py @@ -261,3 +261,67 @@ def test_readback_through_the_verify_config(tmp_path: Path) -> None: ] finally: app.stop() + + +def _minimized_save(kept: list[list[Any]], withheld: list[str]) -> dict[str, Any]: + """A save as the default (minimized) network capture writes it.""" + line = {k: v for k, v in _save().items() if k != "body"} + line["body_minimized"] = { + "schema": "openadapt.capture-minimized/1", + "format": "json", + "bytes": 90, + "hmac": "hmac-sha256:" + "0" * 64, + "kept": kept, + "withheld": [[name, "hmac-sha256:" + "1" * 64] for name in withheld], + } + return line + + +def test_import_reads_declared_fields_of_a_minimized_capture(tmp_path: Path) -> None: + folder = _task(tmp_path / "src" / "a") + _capture( + folder, + [ + _minimized_save( + [["patient_id", "p1"], ["type", "Triage"], ["note", "Cough, 3 days"]], + ["csrf_token"], + ) + ], + ) + result = import_episodes(tmp_path / "src", tmp_path / "eps", app_url=APP + "/") + assert result.imported == ["ref-task-0001"] and result.refused == [] + ep = json.loads( + (tmp_path / "eps" / "ref-task-0001" / "reference_episode.json").read_text() + ) + assert {f["name"]: f["value"] for f in ep["human_fields"]} == { + "patient_id": "p1", + "type": "Triage", + "note": "Cough, 3 days", + } + assert ep["withheld_fields"] == 1 # the session token, as with a raw body + + +def test_import_refuses_a_save_whose_fields_were_not_declared(tmp_path: Path) -> None: + folder = _task(tmp_path / "src" / "a") + _capture( + folder, + [_minimized_save([["patient_id", "p1"]], ["type", "note", "csrf_token"])], + ) + result = import_episodes(tmp_path / "src", tmp_path / "eps", app_url=APP + "/") + assert result.imported == [] + [refusal] = result.refused + assert refusal["code"] == "save_fields_withheld" + assert "note, type" in refusal["why"] and "--param" in refusal["why"] + + +def test_import_of_a_minimized_capture_needs_only_the_named_fields( + tmp_path: Path, +) -> None: + folder = _task(tmp_path / "src" / "a", fields=["note"]) + _capture( + folder, + [_minimized_save([["note", "Cough, 3 days"]], ["type", "csrf_token"])], + ) + result = import_episodes(tmp_path / "src", tmp_path / "eps", app_url=APP + "/") + # The task names the fields it compares; only those must have been kept. + assert result.refused == [] and result.imported == ["ref-task-0001"] From a1e5c015b49709f91cacf2737d0b20ae0a45eff7 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 00:02:28 -0500 Subject: [PATCH 2/3] fix(flow): compare full kept paths, read minimized form saves, refuse truncated bodies as unreadable Grok on #2785: - the task's fields were checked against the last segment of each kept path, so a kept meta.note satisfied a withheld note and the import silently dropped it. Fields are now compared by full path, the names parse_body_fields gives them, and a named field the save doesn't carry refuses. - form saves are minimized to form_minimized, which the importer never read: they are rebuilt from its kept pairs with the same refusal. - an opaque or truncated body kept nothing and now refuses as save_unreadable, not save_fields_withheld. --- .../openadapt_flow/readiness/reference.py | 82 +++++++++++++------ .../flow/tests/test_readiness_reference.py | 65 +++++++++++++++ 2 files changed, 121 insertions(+), 26 deletions(-) diff --git a/packages/flow/openadapt_flow/readiness/reference.py b/packages/flow/openadapt_flow/readiness/reference.py index 6c95d1f98f..5f9f4ecd60 100644 --- a/packages/flow/openadapt_flow/readiness/reference.py +++ b/packages/flow/openadapt_flow/readiness/reference.py @@ -270,17 +270,32 @@ def _from_network( rows = network_capture.load(recording) line = _save_line(rows, raw, app_origin) body = line.get("body") - minimized = line.get("body_minimized") + form_pairs = line.get("form") secrets_withheld = 0 - if body is None and isinstance(minimized, Mapping): - body, secrets_withheld = _kept_body(minimized, raw) + body_minimized = line.get("body_minimized") + form_minimized = line.get("form_minimized") + if body is None and form_pairs is None: + # A minimized capture (the default since captures keep only declared + # fields): rebuild the save from what it kept, or refuse. + from openadapt_flow.capture_privacy import restore_kept_json + + if isinstance(form_minimized, Mapping): + form_pairs, secrets_withheld = _kept_fields(form_minimized, raw) + elif isinstance(body_minimized, Mapping): + _kept, secrets_withheld = _kept_fields(body_minimized, raw) + restored = restore_kept_json(body_minimized) + if not restored: + raise ReferenceRefused( + "save_unreadable", "the capture did not keep the save's body" + ) + body = restored.decode("utf-8") fields, withheld = parse_body_fields( method=str(line.get("method")), url=str(line.get("url")), content_type=str(line.get("request_type") or ""), body=body, lens=lens, - form_pairs=line.get("form"), + form_pairs=form_pairs, body_omitted=bool(line.get("body_omitted") or line.get("request_truncated")), ) withheld += secrets_withheld @@ -290,6 +305,15 @@ def _from_network( ) wanted = raw.get("fields") if isinstance(wanted, list) and wanted: + present = {f.name.lower() for f in fields} + absent = sorted(str(n) for n in wanted if str(n).lower() not in present) + if absent: + # A compared field the save doesn't carry can't be compared. + raise ReferenceRefused( + "save_fields_withheld", + f"the save carries no {', '.join(absent)}; the comparison " + "needs every field the task names", + ) keep = set(map(str, wanted)) | set(raw["expected_record"]) fields = [f for f in fields if f.name in keep] started = _events_start(recording) @@ -330,27 +354,37 @@ def stamp(t: Optional[float]) -> Optional[str]: } -def _kept_body(minimized: Mapping[str, Any], raw: Mapping[str, Any]) -> tuple[str, int]: - """The save's body rebuilt from a minimized capture's kept fields. +def _kept_fields( + minimized: Mapping[str, Any], raw: Mapping[str, Any] +) -> tuple[list[list[Any]], int]: + """The kept ``[path, value]`` pairs of a minimized save, checked for use. Since captures keep only declared fields by default, a save recorded without declaring its fields has every value withheld (hashed). The - comparison needs the person's values, so a field it compares must have - been kept: the task's ``fields`` when it names them, else every field of - the save. A withheld one refuses the task, naming the field and the - recording flag that keeps it, instead of comparing part of the save. - Session tokens and secrets are never compared, so their being withheld - is expected; they are counted, as for a raw body. Returns the rebuilt - body and that count. + comparison needs the person's values, so every field it compares must + have been kept: the task's ``fields`` when it names them, else every + field of the save. Paths are compared in full (``meta.note`` is not + ``note``), the same names :func:`parse_body_fields` gives the fields. A + withheld one refuses the task, naming the field and the recording flag + that keeps it, instead of comparing part of the save. Session tokens and + secrets are never compared, so their being withheld is expected; they are + counted, as for a raw body. An opaque or truncated body kept nothing to + read and refuses as unreadable. """ from openadapt_flow.agent_guard.shadow_hold import is_withheld_name - from openadapt_flow.capture_privacy import restore_kept_json - kept = { - str(item[0]).rsplit(".", 1)[-1].lower() + if minimized.get("format") == "opaque" or ( + "kept" not in minimized and "withheld" not in minimized + ): + raise ReferenceRefused( + "save_unreadable", "the capture did not keep the save's body" + ) + kept = [ + [str(item[0]), item[1]] for item in minimized.get("kept") or [] if isinstance(item, list) and len(item) == 2 - } + ] + kept_paths = {path.lower() for path, _ in kept} withheld_paths = [ str(item[0]) for item in minimized.get("withheld") or [] @@ -360,10 +394,11 @@ def _kept_body(minimized: Mapping[str, Any], raw: Mapping[str, Any]) -> tuple[st withheld = [w for w in withheld_paths if not is_withheld_name(w)] wanted = raw.get("fields") if isinstance(wanted, list) and wanted: - needed = {str(name).lower() for name in wanted} - missing = sorted(n for n in needed if n not in kept) + missing = sorted( + str(name) for name in wanted if str(name).lower() not in kept_paths + ) else: - missing = sorted({w.rsplit(".", 1)[-1] for w in withheld}) + missing = sorted(set(withheld)) if missing or not kept: names = ", ".join(missing) or "every field" raise ReferenceRefused( @@ -372,12 +407,7 @@ def _kept_body(minimized: Mapping[str, Any], raw: Mapping[str, Any]) -> tuple[st "declared (--param or --identifier), or with " "--capture-network-bodies raw on a sealed recording", ) - restored = restore_kept_json(minimized) - if not restored: - raise ReferenceRefused( - "save_unreadable", "the capture did not keep the save's body" - ) - return restored.decode("utf-8"), len(secrets) + return kept, len(secrets) def network_capture_path(url: str) -> str: diff --git a/packages/flow/tests/test_readiness_reference.py b/packages/flow/tests/test_readiness_reference.py index 2106ac7290..7746fac69b 100644 --- a/packages/flow/tests/test_readiness_reference.py +++ b/packages/flow/tests/test_readiness_reference.py @@ -325,3 +325,68 @@ def test_import_of_a_minimized_capture_needs_only_the_named_fields( result = import_episodes(tmp_path / "src", tmp_path / "eps", app_url=APP + "/") # The task names the fields it compares; only those must have been kept. assert result.refused == [] and result.imported == ["ref-task-0001"] + + +def _real_minimized(line: dict[str, Any], keep: list[str]) -> dict[str, Any]: + """A save line as the default capture writes it, via the real minimizer.""" + from openadapt_flow.capture_privacy import BodyMinimizer, minimize_line + + return minimize_line(line, BodyMinimizer(keep_fields=keep)) + + +def test_a_withheld_field_is_not_satisfied_by_a_kept_field_of_the_same_leaf( + tmp_path: Path, +) -> None: + # meta.note is kept and the top-level note is withheld: "note" must refuse. + line = _save() + line["body"] = json.dumps( + {"patient_id": "p1", "type": "Triage", "note": "Cough", "meta": {"note": "x"}} + ) + folder = _task(tmp_path / "src" / "a", fields=["type", "note"]) + _capture(folder, [_real_minimized(line, ["patient_id", "type", "meta.note"])]) + result = import_episodes(tmp_path / "src", tmp_path / "eps", app_url=APP + "/") + assert result.imported == [] + [refusal] = result.refused + assert refusal["code"] == "save_fields_withheld" and "note" in refusal["why"] + + +def test_a_minimized_form_save_with_declared_fields_imports(tmp_path: Path) -> None: + line = {k: v for k, v in _save().items() if k != "body"} + line["request_type"] = "application/x-www-form-urlencoded" + line["form"] = [["patient_id", "p1"], ["type", "Triage"], ["note", "Cough, 3 days"]] + folder = _task(tmp_path / "src" / "a") + _capture(folder, [_real_minimized(line, ["patient_id", "type", "note"])]) + result = import_episodes(tmp_path / "src", tmp_path / "eps", app_url=APP + "/") + assert result.refused == [] and result.imported == ["ref-task-0001"] + ep = json.loads( + (tmp_path / "eps" / "ref-task-0001" / "reference_episode.json").read_text() + ) + assert {f["name"]: f["value"] for f in ep["human_fields"]} == { + "patient_id": "p1", + "type": "Triage", + "note": "Cough, 3 days", + } + + +def test_a_minimized_form_save_with_undeclared_fields_refuses(tmp_path: Path) -> None: + line = {k: v for k, v in _save().items() if k != "body"} + line["request_type"] = "application/x-www-form-urlencoded" + line["form"] = [["patient_id", "p1"], ["type", "Triage"], ["note", "Cough"]] + folder = _task(tmp_path / "src" / "a") + _capture(folder, [_real_minimized(line, ["patient_id"])]) + result = import_episodes(tmp_path / "src", tmp_path / "eps", app_url=APP + "/") + [refusal] = result.refused + assert refusal["code"] == "save_fields_withheld" + + +def test_a_truncated_minimized_body_is_unreadable_not_undeclared( + tmp_path: Path, +) -> None: + line = _save() + line["request_truncated"] = True + folder = _task(tmp_path / "src" / "a") + minimized = _real_minimized(line, ["patient_id", "type", "note"]) + _capture(folder, [minimized]) + result = import_episodes(tmp_path / "src", tmp_path / "eps", app_url=APP + "/") + [refusal] = result.refused + assert refusal["code"] == "save_unreadable", minimized.get("body_minimized") From 7ad0140fb6ed50055d7186134ce7f9e3d1207138 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 01:25:44 -0500 Subject: [PATCH 3/3] fix(flow): compare task field names exactly, as the filter does Grok on #2785: the presence check lower-cased names while the filter after it is case-sensitive, so a task naming "Note" passed the check and then silently dropped "note". JSON and form field names are case-sensitive; both checks now compare them exactly, and a differently cased name refuses. --- .../flow/openadapt_flow/readiness/reference.py | 12 ++++++------ packages/flow/tests/test_readiness_reference.py | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/packages/flow/openadapt_flow/readiness/reference.py b/packages/flow/openadapt_flow/readiness/reference.py index 5f9f4ecd60..4fe7bbd926 100644 --- a/packages/flow/openadapt_flow/readiness/reference.py +++ b/packages/flow/openadapt_flow/readiness/reference.py @@ -305,8 +305,10 @@ def _from_network( ) wanted = raw.get("fields") if isinstance(wanted, list) and wanted: - present = {f.name.lower() for f in fields} - absent = sorted(str(n) for n in wanted if str(n).lower() not in present) + # JSON and form field names are case-sensitive: compare them exactly, + # the same way the filter below keeps them. + present = {f.name for f in fields} + absent = sorted(str(n) for n in wanted if str(n) not in present) if absent: # A compared field the save doesn't carry can't be compared. raise ReferenceRefused( @@ -384,7 +386,7 @@ def _kept_fields( for item in minimized.get("kept") or [] if isinstance(item, list) and len(item) == 2 ] - kept_paths = {path.lower() for path, _ in kept} + kept_paths = {path for path, _ in kept} withheld_paths = [ str(item[0]) for item in minimized.get("withheld") or [] @@ -394,9 +396,7 @@ def _kept_fields( withheld = [w for w in withheld_paths if not is_withheld_name(w)] wanted = raw.get("fields") if isinstance(wanted, list) and wanted: - missing = sorted( - str(name) for name in wanted if str(name).lower() not in kept_paths - ) + missing = sorted(str(name) for name in wanted if str(name) not in kept_paths) else: missing = sorted(set(withheld)) if missing or not kept: diff --git a/packages/flow/tests/test_readiness_reference.py b/packages/flow/tests/test_readiness_reference.py index 7746fac69b..f8a79b7ca0 100644 --- a/packages/flow/tests/test_readiness_reference.py +++ b/packages/flow/tests/test_readiness_reference.py @@ -390,3 +390,20 @@ def test_a_truncated_minimized_body_is_unreadable_not_undeclared( result = import_episodes(tmp_path / "src", tmp_path / "eps", app_url=APP + "/") [refusal] = result.refused assert refusal["code"] == "save_unreadable", minimized.get("body_minimized") + + +@pytest.mark.parametrize("minimized", [False, True]) +def test_a_task_field_named_in_another_case_refuses_instead_of_dropping( + tmp_path: Path, minimized: bool +) -> None: + # The save carries "note"; the task names "Note". Field names are + # case-sensitive, so "Note" is absent: refuse, never compare without it. + folder = _task(tmp_path / "src" / "a", fields=["type", "Note"]) + line = _save() + if minimized: + line = _real_minimized(line, ["patient_id", "type", "note"]) + _capture(folder, [line]) + result = import_episodes(tmp_path / "src", tmp_path / "eps", app_url=APP + "/") + assert result.imported == [] + [refusal] = result.refused + assert refusal["code"] == "save_fields_withheld" and "Note" in refusal["why"]