From 6a5a08a5ec17455664bda14a4e3b8ebd8d476ee8 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 11:31:05 -0500 Subject: [PATCH 01/26] test(flow): reproduce remote-model fail-open and egress findings --- packages/flow/tests/test_model_failclosed.py | 296 +++++++++++++++++++ 1 file changed, 296 insertions(+) create mode 100644 packages/flow/tests/test_model_failclosed.py diff --git a/packages/flow/tests/test_model_failclosed.py b/packages/flow/tests/test_model_failclosed.py new file mode 100644 index 0000000000..d65489f755 --- /dev/null +++ b/packages/flow/tests/test_model_failclosed.py @@ -0,0 +1,296 @@ +"""Remote-model offload review (Nov 21): fail-open and egress reproductions. + +Each test pins the fail-closed behaviour the review asks for. On origin/main +576f87b41 they fail; the fixes on ``claude/model-failclosed`` make them pass. + +1. A model "yes" must never clear a failed postcondition, on any step. +2. A model component with no ``MAY_EGRESS`` marker counts as egress. +3. Identity-VLM calls count as model calls, and identity crops sent off the + box never produce ``external_network_calls == "none"``. +4. The VLM service passes ``VLM_VLLM_URL`` to the vLLM backend. +5. The regulated profile refuses a non-loopback cleartext (``http://``) + appliance. +6. A pinned model that is unavailable never falls back to another placement + or model. +""" + +from __future__ import annotations + +import io +from datetime import datetime, timezone +from types import SimpleNamespace + +import pytest +from PIL import Image + +from openadapt_flow.deployment import GroundingModelConfig, RuntimeSection +from openadapt_flow.ir import ( + Anchor, + Postcondition, + PostconditionKind, + Resolution, + RunReport, + Step, + StepResult, + Workflow, +) +from openadapt_flow.runtime.grounder import component_may_egress +from openadapt_flow.runtime.remote_vlm import ( + RemoteGrounder, + RemoteIdentityVLM, + RemoteStateVerifier, +) +from openadapt_flow.runtime.replayer import EgressNotPermitted, Replayer +from tests.test_drift_oracle import _check, _step, _Verifier, _Vision +from tests.test_replayer import FakeBackend + +# -------------------------------------------------------------------------- +# 1. Drift rescue: a model "yes" is a hint, never a pass. +# -------------------------------------------------------------------------- + + +def test_drift_yes_does_not_clear_failed_text_postcondition_on_navigation( + tmp_path, +): + pc = Postcondition( + kind=PostconditionKind.TEXT_PRESENT, text="Patient list", timeout_s=0.0 + ) + ok, failed, _result = _check(_Vision(present=set()), _Verifier("yes"), pc, tmp_path) + assert ok is False + assert failed + + +def test_drift_yes_does_not_clear_failed_region_postcondition_on_read_only( + tmp_path, +): + pc = Postcondition( + kind=PostconditionKind.REGION_STABLE, + region=(0, 0, 10, 10), + phash="ff", + timeout_s=0.0, + ) + step = _step(pc, intent="view the chart", label="Chart") + ok, failed, _result = _check( + _Vision(present=set()), _Verifier("yes"), pc, tmp_path, step=step + ) + assert ok is False + assert failed + + +# -------------------------------------------------------------------------- +# 2. Unmarked components count as egress. +# -------------------------------------------------------------------------- + + +class _UnmarkedGrounder: + """A third-party grounder that never declares ``MAY_EGRESS``.""" + + def locate(self, screen_png, intent, ocr_text=None): + return None + + +def test_unmarked_component_counts_as_egress(): + assert component_may_egress(_UnmarkedGrounder()) is True + + +def test_unmarked_grounder_requires_explicit_egress_optin(): + with pytest.raises(EgressNotPermitted): + Replayer(FakeBackend(), grounder=_UnmarkedGrounder()) + + +# -------------------------------------------------------------------------- +# 3. Identity-VLM calls are model calls; off-box crops are never "none". +# -------------------------------------------------------------------------- + + +def _crop_png() -> bytes: + buf = io.BytesIO() + Image.new("RGB", (40, 12), (250, 250, 250)).save(buf, format="PNG") + return buf.getvalue() + + +class _OffBoxIdentityVLM: + """An appliance identity VLM: crops leave the box on every call.""" + + MAY_EGRESS = True + + def __init__(self, verdict: str) -> None: + self.verdict = verdict + self.calls = 0 + + def same_or_different(self, recorded_png, live_png): + self.calls += 1 + return self.verdict + + +def _identity_step() -> tuple[Step, Workflow, Resolution]: + anchor = Anchor( + template="t.png", + region=(0, 0, 40, 12), + click_point=(20, 6), + # A glyph-confusable identifier, so the VLM tier is consulted. + context_text="Smith AC50061", + ) + step = Step( + id="open_record", + intent="open record", + action="click", + anchor=anchor, + risk="irreversible", + ) + workflow = Workflow(name="identity_vlm_egress", params={}, steps=[step]) + res = Resolution(rung="ocr", point=(20, 6), confidence=0.9, elapsed_ms=1.0) + return step, workflow, res + + +@pytest.mark.parametrize("verdict", ["different", "same"]) +def test_identity_vlm_call_counts_as_model_call(monkeypatch, tmp_path, verdict): + vlm = _OffBoxIdentityVLM(verdict) + rp = Replayer(FakeBackend(), identity_vlm=vlm, allow_model_grounding=True) + crop = _crop_png() + monkeypatch.setattr(rp, "_identifier_crops", lambda *a, **k: (crop, crop)) + step, workflow, res = _identity_step() + result = StepResult(step_id=step.id, intent=step.intent, ok=False) + rp._identity_gate_error(step, res, crop, {}, workflow, tmp_path, result) + assert vlm.calls == 1, "precondition: the identity VLM was consulted" + assert Replayer._result_model_calls(result) >= 1 + + +def test_off_box_identity_crops_never_report_no_external_calls(monkeypatch, tmp_path): + from openadapt_flow.execution_profiles import _external_network_call_state + + vlm = _OffBoxIdentityVLM("different") + rp = Replayer(FakeBackend(), identity_vlm=vlm, allow_model_grounding=True) + crop = _crop_png() + monkeypatch.setattr(rp, "_identifier_crops", lambda *a, **k: (crop, crop)) + step, workflow, res = _identity_step() + result = StepResult(step_id=step.id, intent=step.intent, ok=False) + rp._identity_gate_error(step, res, crop, {}, workflow, tmp_path, result) + assert vlm.calls == 1, "precondition: identity crops left the box" + + # A loopback web run (the bundled tutorial's shape) whose identity crops + # went to an off-box appliance. + report = RunReport( + workflow_name=workflow.name, + started_at=datetime.now(timezone.utc).isoformat(), + execution_origin="http://127.0.0.1:5001", + execution_entry_url="http://127.0.0.1:5001/", + execution_target_kind="web", + screenshots_may_leave_box=True, + steps=[result], + ) + report.model_calls = Replayer._result_model_calls(result) + assert _external_network_call_state(report) != "none" + + +# -------------------------------------------------------------------------- +# 4. The VLM service honours VLM_VLLM_URL. +# -------------------------------------------------------------------------- + + +def test_vlm_service_passes_vllm_url_to_backend(monkeypatch): + pytest.importorskip("fastapi") + import openadapt_flow.services.vlm_service.app as app_mod + from openadapt_flow.services.vlm_service.config import ServiceConfig + + seen: dict = {} + + def _capture(backend, model=None, **kwargs): + seen.update(backend=backend, model=model, **kwargs) + from openadapt_flow.services.vlm_service.backends import StubBackend + + return StubBackend() + + monkeypatch.setattr(app_mod, "build_backend", _capture) + monkeypatch.setenv("VLM_BACKEND", "vllm") + monkeypatch.setenv("VLM_VLLM_URL", "http://gpu-box.internal:9000/v1") + app_mod.create_app(ServiceConfig.from_env()) + assert seen.get("base_url") == "http://gpu-box.internal:9000/v1" + + +# -------------------------------------------------------------------------- +# 5 and 6. build_replayer wiring (no real Replayer, no real OCR rung). +# -------------------------------------------------------------------------- + + +@pytest.fixture() +def wiring(monkeypatch): + captured: dict = {} + + import openadapt_flow.runtime as rt + import openadapt_flow.runtime.grounder as gmod + + class _FakeReplayer: + def __init__(self, backend, **kwargs): + captured["replayer_kwargs"] = kwargs + + def _fake_build_grounder(fallback=None, **_kwargs): + captured["fallback"] = fallback + return fallback + + monkeypatch.setattr(rt, "Replayer", _FakeReplayer) + monkeypatch.setattr(gmod, "build_grounder", _fake_build_grounder) + monkeypatch.delenv("OPENADAPT_FLOW_VLM_URL", raising=False) + monkeypatch.delenv("OPENADAPT_FLOW_VLM_TOKEN", raising=False) + return captured + + +def _build(*, runtime_config, phi_mode, governed_authorization=None): + from openadapt_flow.deployment import build_replayer + + build_replayer( + object(), + allow_egress=True, + effect_verifier=None, + api_actuator=None, + durable=False, + use_structural=True, + runtime_config=runtime_config, + phi_mode=phi_mode, + governed_authorization=governed_authorization, + ) + + +def _wired_appliance_handles(captured: dict) -> list[str]: + kwargs = captured.get("replayer_kwargs") or {} + wired = [ + name + for name in ("identity_vlm", "state_verifier") + if isinstance( + kwargs.get(name), (RemoteIdentityVLM, RemoteStateVerifier) + ) + ] + if isinstance(captured.get("fallback"), RemoteGrounder): + wired.append("grounder") + return wired + + +def test_regulated_profile_refuses_cleartext_non_loopback_appliance( + wiring, monkeypatch +): + monkeypatch.setenv("OPENADAPT_FLOW_VLM_URL", "http://10.20.30.40:8000") + monkeypatch.setenv("OPENADAPT_FLOW_VLM_TOKEN", "t") + runtime = RuntimeSection(phi_grounding_allowlist=["10.20.30.40"]) + authorization = SimpleNamespace( + execution_profile="regulated", qualification_case_id=None + ) + _build( + runtime_config=runtime, + phi_mode=True, + governed_authorization=authorization, + ) + assert _wired_appliance_handles(wiring) == [] + + +def test_unavailable_pinned_model_never_falls_back_to_appliance(wiring, monkeypatch): + # The operator pinned an openai-compatible model, but it cannot be built + # (no base_url). The on-prem appliance is a different placement and + # model; it must not silently stand in for the pinned one. + monkeypatch.setenv("OPENADAPT_FLOW_VLM_URL", "https://vlm.internal:8443") + runtime = RuntimeSection( + grounding_model=GroundingModelConfig( + enabled=True, provider="openai_compatible", base_url="", model="pinned-m" + ) + ) + _build(runtime_config=runtime, phi_mode=False) + assert not isinstance(wiring.get("fallback"), RemoteGrounder) From f0078d67b7b0beb89726002d9288a5057edf206e Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 11:59:32 -0500 Subject: [PATCH 02/26] test(flow): format fail-open reproductions --- packages/flow/tests/test_model_failclosed.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/flow/tests/test_model_failclosed.py b/packages/flow/tests/test_model_failclosed.py index d65489f755..fe30d2d9c6 100644 --- a/packages/flow/tests/test_model_failclosed.py +++ b/packages/flow/tests/test_model_failclosed.py @@ -256,9 +256,7 @@ def _wired_appliance_handles(captured: dict) -> list[str]: wired = [ name for name in ("identity_vlm", "state_verifier") - if isinstance( - kwargs.get(name), (RemoteIdentityVLM, RemoteStateVerifier) - ) + if isinstance(kwargs.get(name), (RemoteIdentityVLM, RemoteStateVerifier)) ] if isinstance(captured.get("fallback"), RemoteGrounder): wired.append("grounder") From edbe4a6c8056248d457f41756bfbbf4a138ccb27 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 12:12:13 -0500 Subject: [PATCH 03/26] test(flow): keep drift reproductions valid once unmarked counts as egress --- packages/flow/tests/test_model_failclosed.py | 30 +++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/packages/flow/tests/test_model_failclosed.py b/packages/flow/tests/test_model_failclosed.py index fe30d2d9c6..d2e116ec80 100644 --- a/packages/flow/tests/test_model_failclosed.py +++ b/packages/flow/tests/test_model_failclosed.py @@ -41,7 +41,7 @@ RemoteStateVerifier, ) from openadapt_flow.runtime.replayer import EgressNotPermitted, Replayer -from tests.test_drift_oracle import _check, _step, _Verifier, _Vision +from tests.test_drift_oracle import _Backend, _png, _step, _Vision from tests.test_replayer import FakeBackend # -------------------------------------------------------------------------- @@ -49,6 +49,34 @@ # -------------------------------------------------------------------------- +class _Verifier: + """An appliance state-verifier (marked egress) with a scripted answer.""" + + MAY_EGRESS = True + + def __init__(self, answer: str) -> None: + self.answer = answer + self.calls = 0 + + def holds(self, screenshot, expected_state) -> bool: + self.calls += 1 + return self.answer == "yes" + + +def _check(vision, verifier, pc, tmp_path, step=None): + rp = Replayer( + _Backend(), + vision=vision, + state_verifier=verifier, + allow_model_grounding=True, + poll_interval_s=0.0, + ) + step = step if step is not None else _step(pc) + result = StepResult(step_id=step.id, intent=step.intent, ok=False) + ok, _frame, failed = rp._check_postconditions(step, _png(), tmp_path, {}, result) + return ok, failed, result + + def test_drift_yes_does_not_clear_failed_text_postcondition_on_navigation( tmp_path, ): From 7675ad7a929d8fb73168f36c545e1319e2505865 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 12:50:50 -0500 Subject: [PATCH 04/26] fix(flow): count a model component with no MAY_EGRESS marker as egress Fail-open class: unknown-treated-as-safe. component_may_egress read a missing marker as local, so an unmarked grounder, identity VLM or state verifier was wired without the egress opt-in. Only an explicit MAY_EGRESS = False is local now, as in seal_batch. MLXIdentityVLM runs in process and is marked False. --- packages/flow/openadapt_flow/runtime/grounder.py | 12 +++++++----- packages/flow/openadapt_flow/runtime/identity_vlm.py | 3 +++ 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/packages/flow/openadapt_flow/runtime/grounder.py b/packages/flow/openadapt_flow/runtime/grounder.py index c55325cfa4..f9a6769e83 100644 --- a/packages/flow/openadapt_flow/runtime/grounder.py +++ b/packages/flow/openadapt_flow/runtime/grounder.py @@ -82,19 +82,21 @@ def locate( # appliance). The replayer refuses to wire an egress-capable component unless the # operator explicitly opts in (``allow_model_grounding``), and the run report # flags any run where a screenshot could leave the box. Local, in-process -# grounders (Null / OCR-anchoring) carry ``MAY_EGRESS = False``. +# grounders (Null / OCR-anchoring) carry ``MAY_EGRESS = False``; a component +# without the marker is unknown, and unknown counts as egress. def component_may_egress(component: object) -> bool: """Whether a grounder / identity-VLM / state-verifier can send a screenshot - off the box. Reads the component's ``MAY_EGRESS`` marker (default False for - an unmarked stub / local component); a :class:`FallbackGrounder` is egress - if ANY chained grounder is.""" + off the box. Reads the component's ``MAY_EGRESS`` marker. Only an explicit + ``MAY_EGRESS = False`` makes a component local; an unmarked one may egress + (fail closed). A :class:`FallbackGrounder` is egress if ANY chained + grounder is.""" if component is None: return False if isinstance(component, FallbackGrounder): return any(component_may_egress(g) for g in component._grounders) - return bool(getattr(component, "MAY_EGRESS", False)) + return getattr(component, "MAY_EGRESS", True) is not False class NullGrounder: diff --git a/packages/flow/openadapt_flow/runtime/identity_vlm.py b/packages/flow/openadapt_flow/runtime/identity_vlm.py index ebad05e1fc..1ebdc617dc 100644 --- a/packages/flow/openadapt_flow/runtime/identity_vlm.py +++ b/packages/flow/openadapt_flow/runtime/identity_vlm.py @@ -36,6 +36,9 @@ class MLXIdentityVLM: O/0 collapse surface, ~0.8s/call). The model loads lazily on first call. """ + # In process: the crops never leave this machine. + MAY_EGRESS = False + def __init__(self, model_name: str = DEFAULT_MODEL) -> None: self.model_name = model_name self._comparator: Optional[Any] = None From b583ff187f1ddd8f5b2704ea7d2315462cc86ef5 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 12:50:51 -0500 Subject: [PATCH 05/26] fix(flow): count identity-VLM and abstaining grounder calls, ledger off-box frames Fail-open classes: uncounted-egress, unrecorded-egress. The identity VLM's calls were never counted, so a loopback web run whose identity crops went to an appliance reported external_network_calls "none". A remote grounder call counted only on a step that passed. runtime/model_egress.py wraps each model component the replayer is given. Before an off-box call it appends a line (frame SHA-256 and size, component, destination host, run, step, time; no pixels or text) to an append-only, fsynced, 0600 ledger beside the run directory (OPENADAPT_FLOW_EGRESS_LEDGER overrides). If the line can't be written the call isn't made and the component gives its fail-safe answer. Calls are counted onto the StepResult by placement: off-box identity-VLM and grounder calls go into model_calls, in-process identity-VLM calls into local_model_calls. The new StepResult fields are omitted from JSON when zero, so existing reports and receipts keep their bytes. --- packages/flow/openadapt_flow/ir.py | 15 +- .../openadapt_flow/runtime/model_egress.py | 235 ++++++++++++++++++ .../flow/openadapt_flow/runtime/replayer.py | 46 ++-- 3 files changed, 266 insertions(+), 30 deletions(-) create mode 100644 packages/flow/openadapt_flow/runtime/model_egress.py diff --git a/packages/flow/openadapt_flow/ir.py b/packages/flow/openadapt_flow/ir.py index 82a0f34235..eb79d9d360 100644 --- a/packages/flow/openadapt_flow/ir.py +++ b/packages/flow/openadapt_flow/ir.py @@ -5249,11 +5249,20 @@ class StepResult(BaseModel): "as proof that settled-state detection ran." ), ) - # Drift-oracle: postconditions that deterministically FAILED but were - # confirmed by the optional on-prem VLM state-verifier under render drift - # (recorded for audit; empty unless an appliance is configured). + # Drift-oracle hints: postconditions that deterministically FAILED and that + # the optional VLM state-verifier said hold. A hint only: the + # postcondition stays failed and the step halts for a person to review + # (recorded for audit; empty unless a state verifier is configured). postcondition_drift_rescues: list[str] = Field(default_factory=list) drift_oracle_calls: int = 0 # VLM state-verifier calls this step + # Model calls by placement (runtime.model_egress): identity-VLM calls that + # sent crops off the box, ones that ran in process, and off-box grounder + # calls (abstentions included). Omitted from the JSON when zero. + identity_vlm_calls: int = Field(default=0, ge=0, exclude_if=lambda v: v == 0) + local_identity_vlm_calls: int = Field( + default=0, ge=0, exclude_if=lambda v: v == 0 + ) + grounder_calls: int = Field(default=0, ge=0, exclude_if=lambda v: v == 0) #: The uniform page scale (for example 1.25 under 125% zoom) at which a #: ``region_stable`` check found its recorded content, when it was found #: only there. Set only when this step's own click showed the same scale. diff --git a/packages/flow/openadapt_flow/runtime/model_egress.py b/packages/flow/openadapt_flow/runtime/model_egress.py new file mode 100644 index 0000000000..e8afe3dff6 --- /dev/null +++ b/packages/flow/openadapt_flow/runtime/model_egress.py @@ -0,0 +1,235 @@ +"""Count model calls by placement and record every frame sent off the box. + +The replayer wraps each model component it is given (grounder, identity VLM, +state verifier) with :meth:`EgressRecorder.wrap`. A wrapped component that may +send a frame off the box (see +:func:`openadapt_flow.runtime.grounder.component_may_egress`) writes one line +to the local egress ledger **before** each call. If that line can't be +written, the call is not made and the component returns its fail-safe answer +(the grounder abstains, the identity VLM says "different", the state verifier +says no), so the step halts. Nothing leaves the box unrecorded, and a halted +run's frames are on the ledger, since each line is written when the frame is +sent. + +The ledger is append-only JSON lines, mode 0600, fsynced per line. A line +holds the frame's SHA-256 and size, the component, the destination host, the +run and the step, and the time. It never holds pixels or screen text. By +default it is ``egress-ledger.jsonl`` next to the run directory, so it covers +every run written under the same runs root; ``OPENADAPT_FLOW_EGRESS_LEDGER`` +names another file. + +Calls are also counted, by placement, onto the step's +:class:`~openadapt_flow.ir.StepResult`: off-box identity-VLM calls in +``identity_vlm_calls``, in-process ones in ``local_identity_vlm_calls``, and +off-box grounder calls (including ones where the grounder abstained) in +``grounder_calls``. The replayer folds the off-box counts into +``RunReport.model_calls`` and the in-process ones into ``local_model_calls``. +""" + +from __future__ import annotations + +import hashlib +import json +import os +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Optional +from urllib.parse import urlsplit + +LEDGER_ENV = "OPENADAPT_FLOW_EGRESS_LEDGER" +LEDGER_NAME = "egress-ledger.jsonl" + + +def append_ledger_line(path: Path, entry: dict[str, Any]) -> None: + """Append one JSON line to ``path`` and fsync it. Raises ``OSError``.""" + + path.parent.mkdir(parents=True, exist_ok=True) + data = (json.dumps(entry, sort_keys=True, separators=(",", ":")) + "\n").encode() + fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600) + try: + while data: + written = os.write(fd, data) + if written <= 0: + raise OSError("the egress ledger append made no progress") + data = data[written:] + os.fsync(fd) + finally: + os.close(fd) + + +def _destination(component: Any) -> str: + """The host a component sends to, or ``"unknown"``.""" + + for holder in (component, getattr(component, "_client", None)): + for name in ("base_url", "_base_url"): + url = getattr(holder, name, None) + if isinstance(url, str) and url: + host = urlsplit(url if "//" in url else f"//{url}").hostname + if host: + return host + return "unknown" + + +class EgressRecorder: + """Per-replayer ledger writer and placement-aware call counter.""" + + def __init__(self) -> None: + self.ledger_path: Optional[Path] = None + self.run_ref: Optional[str] = None + self.step_id: Optional[str] = None + #: Every ledger line this recorder made, also when no run is bound + #: (a replayer driven outside ``run``, as unit tests do). + self.entries: list[dict[str, Any]] = [] + self._pending = { + "identity_vlm_calls": 0, + "local_identity_vlm_calls": 0, + "grounder_calls": 0, + } + + def bind_run(self, run_dir: Path, run_id: Optional[str] = None) -> None: + """Point the ledger at this run (call before the run sends anything).""" + + override = os.environ.get(LEDGER_ENV, "").strip() + run_dir = Path(run_dir) + self.ledger_path = Path(override) if override else run_dir.parent / LEDGER_NAME + self.run_ref = run_id or run_dir.name + + def admit(self, kind: str, component: Any, *frames: bytes) -> bool: + """Record a frame about to leave the box. False means: don't send.""" + + entry = { + "at": datetime.now(timezone.utc).isoformat(), + "run": self.run_ref, + "step": self.step_id, + "component": kind, + "destination": _destination(component), + "frames": [ + {"sha256": hashlib.sha256(f).hexdigest(), "bytes": len(f)} + for f in frames + if isinstance(f, (bytes, bytearray)) + ], + } + if self.ledger_path is not None: + try: + append_ledger_line(self.ledger_path, entry) + except OSError: + return False + self.entries.append(entry) + return True + + def count(self, field: str) -> None: + self._pending[field] += 1 + + def drain(self, result: Any) -> None: + """Move the calls counted since the last drain onto ``result``.""" + + if result is None: + return + for field, n in self._pending.items(): + if n: + setattr(result, field, getattr(result, field) + n) + self._pending[field] = 0 + + def wrap(self, kind: str, component: Any) -> Any: + """``component`` wrapped for recording, or as is when nothing to do.""" + + from openadapt_flow.runtime.grounder import ( + FallbackGrounder, + component_may_egress, + ) + + if component is None: + return None + if isinstance(component, FallbackGrounder): + return FallbackGrounder( + [self.wrap(kind, g) for g in component._grounders] + ) + off_box = component_may_egress(component) + if kind == "identity_vlm": + return _IdentityVLM(self, component, off_box) + if not off_box: + return component + if kind == "grounder": + return _Grounder(self, component) + return _StateVerifier(self, component) + + +class _Wrapped: + MAY_EGRESS: bool + + def __init__(self, recorder: EgressRecorder, inner: Any) -> None: + self._recorder = recorder + self._inner = inner + + def __getattr__(self, name: str) -> Any: + return getattr(self._inner, name) + + +class _Grounder(_Wrapped): + MAY_EGRESS = True + + def locate(self, screen_png: bytes, intent: str, ocr_text: Optional[str] = None): + if not self._recorder.admit("grounder", self._inner, screen_png): + return None + self._recorder.count("grounder_calls") + return self._inner.locate(screen_png, intent, ocr_text) + + +class _IdentityVLM(_Wrapped): + def __init__(self, recorder: EgressRecorder, inner: Any, off_box: bool) -> None: + super().__init__(recorder, inner) + self.MAY_EGRESS = off_box + + def same_or_different(self, recorded_png: bytes, live_png: bytes) -> str: + if self.MAY_EGRESS: + if not self._recorder.admit( + "identity_vlm", self._inner, recorded_png, live_png + ): + return "different" + self._recorder.count("identity_vlm_calls") + else: + self._recorder.count("local_identity_vlm_calls") + return self._inner.same_or_different(recorded_png, live_png) + + +class _StateVerifier(_Wrapped): + MAY_EGRESS = True + + def holds(self, screenshot: bytes, expected_state: str) -> bool: + if not self._recorder.admit("state_verifier", self._inner, screenshot): + return False + return self._inner.holds(screenshot, expected_state) + + +def _grounder_resolution(result: Any, local: bool) -> bool: + res = getattr(result, "resolution", None) + return bool( + result.ok + and res is not None + and res.rung == "grounder" + and (res.grounder_model == "local") is local + ) + + +def model_calls_off_box(result: Any) -> int: + """Model calls on ``result`` that may have sent a frame off the box. + + Drift-oracle calls, off-box identity-VLM calls, and grounder calls. The + recorder counts every off-box grounder call, including abstentions and + calls on failed steps; a result built elsewhere (no recorder count) still + counts its grounder resolution, as before. + """ + + return int( + result.drift_oracle_calls + + result.identity_vlm_calls + + max(result.grounder_calls, int(_grounder_resolution(result, local=False))) + ) + + +def model_calls_in_process(result: Any) -> int: + """Model calls on ``result`` that ran in process (no frame left the box).""" + + return int( + _grounder_resolution(result, local=True) + result.local_identity_vlm_calls + ) diff --git a/packages/flow/openadapt_flow/runtime/replayer.py b/packages/flow/openadapt_flow/runtime/replayer.py index 4e7c5054da..d2dc11fe43 100644 --- a/packages/flow/openadapt_flow/runtime/replayer.py +++ b/packages/flow/openadapt_flow/runtime/replayer.py @@ -194,6 +194,11 @@ runtime_param_text, runtime_params_for_gui, ) +from openadapt_flow.runtime.model_egress import ( + EgressRecorder, + model_calls_in_process, + model_calls_off_box, +) from openadapt_flow.runtime.dialog_delivery import ( _DIALOG_WAIT_S as _DIALOG_WAIT_S, ) @@ -607,7 +612,9 @@ def __init__( # is always populated by the time replay runs; typed Any (a namespace-like # facade exposing find_template/ocr/wait_settled/...). self.vision: Any = vision - self.grounder = grounder + # Frames sent off the box are ledgered and counted by placement. + self._egress = EgressRecorder() + self.grounder = self._egress.wrap("grounder", grounder) # Whether the deterministic structural ACTION rung (top of the ladder) # may run. True (default) = product behavior: on a structure-bearing # backend, resolve the recorded target as a DOM/UIA element. Set False @@ -800,7 +807,7 @@ def __init__( # OFF by default like the grounder: an IdentityVLM verifier or None. # When None the ladder runs structured-text + pixel-compare + OCR + # halt with no model dependency. - self.identity_vlm = identity_vlm + self.identity_vlm = self._egress.wrap("identity_vlm", identity_vlm) # Optional complete known-ID list (runtime.known_ids): lifts a # look-alike identifier abstain only when no listed twin exists. self.known_ids = known_ids @@ -812,12 +819,10 @@ def __init__( self._identity_input_looks = False self._identity_look_bindings: dict[str, looks_mod.LookBinding] = {} # Optional VLM drift-oracle (state-verifier), OFF by default. When set, - # it may CONFIRM a render-drift-sensitive postcondition that - # deterministically false-failed (the same heal-under-drift the - # resolution ladder does for click targets). VETO-SAFE: it only ever - # rescues on a confident "yes"; "no"/"uncertain"/outage keep the halt, - # and it never touches structural or text_absent postconditions. - self.state_verifier = state_verifier + # it is asked about a render-drift-sensitive postcondition that failed + # deterministically. Its "yes" is a hint for the person who reviews + # the halt; the postcondition stays failed. + self.state_verifier = self._egress.wrap("state_verifier", state_verifier) self.poll_interval_s = poll_interval_s if not math.isfinite(settle_readiness_timeout_s) or ( settle_readiness_timeout_s <= 0 @@ -1212,6 +1217,7 @@ def run( before they are written, and durable checkpoints use the same key. No plaintext of the bundle or of the live screen reaches the disk. """ + self._egress.bind_run(run_dir, run_id) return run_with_output( self, workflow, @@ -3605,28 +3611,11 @@ def _account_result( @staticmethod def _result_model_calls(result: StepResult) -> int: - return int( - result.drift_oracle_calls - + ( - 1 - if ( - result.ok - and result.resolution is not None - and result.resolution.rung == "grounder" - and result.resolution.grounder_model != "local" - ) - else 0 - ) - ) + return model_calls_off_box(result) @staticmethod def _result_local_model_calls(result: StepResult) -> int: - return int( - result.ok - and result.resolution is not None - and result.resolution.rung == "grounder" - and result.resolution.grounder_model == "local" - ) + return model_calls_in_process(result) def _initial_external_network_calls( self, prior: Literal["none", "observed", "unknown"] @@ -6944,11 +6933,13 @@ def _run_step(self, step: Step, **kwargs: Any) -> StepResult: timer, previous = step_timing.start_step() result: Optional[StepResult] = None + self._egress.step_id = step.id try: result = self._run_step_timed(step, **kwargs) return result finally: step_timing.end_step(previous) + self._egress.drain(result) if result is not None: result.timings = timer.result_ms(result.elapsed_ms or None) @@ -10094,6 +10085,7 @@ def _identity_gate_error( step, resolution, frame_png, params, workflow, bundle_dir ) ) + self._egress.drain(result) if ( check.status in {"verified", "mismatch"} and check.mode == "pixel" From 8972556ed58673295bef675f377518e7ab957fc2 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 12:50:51 -0500 Subject: [PATCH 06/26] fix(flow): a drift-oracle yes is a hint for the reviewer, never a pass Fail-open class: model-verdict-overrides-deterministic-refutation. On read-only and navigation steps a state-verifier "yes" cleared a failed text_present or region_stable postcondition. Now every failed postcondition stays failed and the step halts for a person; the yes is recorded on postcondition_drift_rescues (field kept for compatibility) and printed as a hint. The three tests that pinned the rescue now pin the halt. --- packages/flow/docs/deployment/ON_PREM_VLM.md | 15 ++-- .../flow/openadapt_flow/runtime/replayer.py | 48 ++++++----- packages/flow/tests/test_drift_oracle.py | 79 +++++++++++-------- 3 files changed, 77 insertions(+), 65 deletions(-) diff --git a/packages/flow/docs/deployment/ON_PREM_VLM.md b/packages/flow/docs/deployment/ON_PREM_VLM.md index d0177bbe55..5a79ed05d2 100644 --- a/packages/flow/docs/deployment/ON_PREM_VLM.md +++ b/packages/flow/docs/deployment/ON_PREM_VLM.md @@ -62,9 +62,10 @@ unqualified**: the appliance validation measured it non-functional at native frames are downscaled below ~1024px first) and ~12.5% false-rescue on genuinely-ambiguous in-progress screens (a `"Saving…"` read as saved). See [docs/LIMITS.md](../LIMITS.md) for the measured trap-set numbers before -relying on it. Because of that false-rescue rate, the replayer never asks the -oracle about a step that can change a record (see the drift-oracle entry -below). +relying on it. Because of that false-rescue rate, a "yes" never clears a +failed postcondition: it is a hint shown to the person who reviews the halt, +and the replayer doesn't ask at all about a step that can change a record (see +the drift-oracle entry below). ## Fail-safe behaviour (mandatory) @@ -199,9 +200,11 @@ handles into the `Replayer`. tier can only veto; a down appliance means more halts, never a wrong click. - **Drift-oracle postcondition** (`RemoteStateVerifier`): after deterministic checks and one settle retry fail, the replayer asks the verifier only about - render-drift-sensitive `text_present` and `region_stable` conditions. Only a - confident `yes` rescues the condition. A `no`, `uncertain`, error, or appliance - outage keeps the failure. Every call and rescue is recorded in the run result. + render-drift-sensitive `text_present` and `region_stable` conditions. The + answer never clears the failure: the step halts and goes to a person, and a + confident `yes` is recorded on the step (`postcondition_drift_rescues`) and + printed as a hint that the failure may be render drift. Every call is + recorded in the run result and counted as a model call. The replayer does not ask at all on an irreversible or effect-bearing step (the same steps the run gate treats as consequential, plus steps waiting for risk review). There a failed check stays failed. Unless the workflow has its diff --git a/packages/flow/openadapt_flow/runtime/replayer.py b/packages/flow/openadapt_flow/runtime/replayer.py index d2dc11fe43..59a925de8a 100644 --- a/packages/flow/openadapt_flow/runtime/replayer.py +++ b/packages/flow/openadapt_flow/runtime/replayer.py @@ -8296,10 +8296,10 @@ def _run_step_on_active_surface( for r in result.postcondition_drift_rescues ) print( - " drift-oracle: " + " drift-oracle hint: the VLM says " f"{len(result.postcondition_drift_rescues)}" - " postcondition(s) confirmed by VLM under render " - "drift — " + rescued + " failed postcondition(s) hold (render drift?); " + "they stay failed for a person to review — " + rescued ) if not postconditions_ok: if selection_error is not None: @@ -18296,9 +18296,9 @@ def _postcondition_confirms_a_write( :func:`transaction.classify_transaction_outcome` reports ``RECONCILIATION_REQUIRED`` for the halted run. - Read-only and navigation steps keep the drift-oracle rescue. A wrong - "yes" there lets the run reach the next step, which still runs its own - identity, risk, and postcondition checks before it acts. + On read-only and navigation steps the drift oracle is asked, but its + "yes" is only a hint for the person who reviews the halt (see + :meth:`_drift_oracle_rescue`): the postcondition stays failed. """ if step.risk_review_required: return True @@ -18310,23 +18310,21 @@ def _drift_oracle_rescue( frame_png: bytes, result: Optional[StepResult], ) -> list[Any]: - """Give each deterministically-failed, render-drift-sensitive - postcondition one confirmation pass through the VLM state-verifier. + """Ask the VLM state-verifier about each deterministically-failed, + render-drift-sensitive postcondition, as a hint for the reviewer. - VETO-SAFE by construction: + A model "yes" never clears a failed postcondition: every one stays + failed, so the step halts and goes to a person. A "yes" is recorded on + ``result.postcondition_drift_rescues`` (and printed) so the reviewer + sees that the failure may be render drift. * The caller never invokes this on an irreversible or effect-bearing step (see :meth:`_postcondition_confirms_a_write`). - * Only ``text_present`` and ``region_stable`` are eligible — the kinds - a theme/scale/font re-render can legitimately break. Structural - postconditions (``url_changed`` etc.) and ``text_absent`` are NEVER - rescued: those failures are real, not render drift. - * A postcondition is rescued ONLY on a confident ``"yes"``; ``"no"``, - ``"uncertain"``, and any appliance outage keep it failed (halt). - * Every call and every rescue is recorded on ``result`` for the report - (and counted as a model call), so a rescue is auditable, never silent. - - Returns the postconditions that remain failed after the pass. + * Only ``text_present`` and ``region_stable`` are asked about — the + kinds a theme/scale/font re-render can legitimately break. + * Every call is recorded on ``result`` and counted as a model call. + + Returns the postconditions that remain failed: all of ``failed_pcs``. """ assert self.state_verifier is not None # guaranteed by the caller (line ~2618) survivors: list[Any] = [] @@ -18341,13 +18339,11 @@ def _drift_oracle_rescue( confirmed = self.state_verifier.holds(frame_png, expected) except Exception: confirmed = False # fail-safe: any error keeps the halt - if confirmed: - if result is not None: - result.postcondition_drift_rescues.append( - self._describe_postcondition(pc) - ) - else: - survivors.append(pc) + if confirmed and result is not None: + result.postcondition_drift_rescues.append( + self._describe_postcondition(pc) + ) + survivors.append(pc) # a model "yes" is a hint, never a pass return survivors @staticmethod diff --git a/packages/flow/tests/test_drift_oracle.py b/packages/flow/tests/test_drift_oracle.py index 7a38db90fe..ed6f621177 100644 --- a/packages/flow/tests/test_drift_oracle.py +++ b/packages/flow/tests/test_drift_oracle.py @@ -1,14 +1,16 @@ -"""Drift-oracle: the optional VLM state-verifier that may CONFIRM a -render-drift-sensitive postcondition which deterministically false-failed. - -Veto-safe by construction — these tests pin that: -* only a confident "yes" rescues; "no"/"uncertain"/outage keep the halt, -* structural / text_absent postconditions are NEVER rescued, -* every call and rescue is recorded on the StepResult for the report, +"""Drift-oracle: the optional VLM state-verifier asked about a +render-drift-sensitive postcondition which failed deterministically. + +Its answer is a hint for the person who reviews the halt, never a pass. These +tests pin that: +* a confident "yes" is recorded as a hint, and the postcondition stays failed; + "no"/"uncertain"/outage record nothing, +* structural / text_absent postconditions are never asked about, +* every call and hint is recorded on the StepResult for the report, * with no verifier configured (the default) behaviour is unchanged, -* an irreversible or effect-bearing step is never rescued: its failed - postcondition stays failed (a run with no handler halts with transaction - outcome RECONCILIATION_REQUIRED), while a navigation step keeps the rescue. +* an irreversible or effect-bearing step never asks the oracle; a run with no + handler halts at a write with transaction outcome RECONCILIATION_REQUIRED, + and a navigation step halts too, with the hint on its result. """ from __future__ import annotations @@ -77,6 +79,8 @@ class _Verifier: """Scripted state-verifier. ``answer`` is 'yes'/'no'/'uncertain' or 'boom' to raise (simulate an outage the client failed to swallow).""" + MAY_EGRESS = True # an appliance verifier: the frame leaves the box + def __init__(self, answer: str): self.answer = answer self.calls = 0 @@ -119,7 +123,11 @@ def _text_present_pc(text: str = "Patient list") -> Postcondition: def _check(vision, verifier, pc, tmp_path, step=None): rp = Replayer( - _Backend(), vision=vision, state_verifier=verifier, poll_interval_s=0.0 + _Backend(), + vision=vision, + state_verifier=verifier, + allow_model_grounding=True, + poll_interval_s=0.0, ) step = step if step is not None else _step(pc) result = StepResult(step_id=step.id, intent=step.intent, ok=False) @@ -130,11 +138,11 @@ def _check(vision, verifier, pc, tmp_path, step=None): # -------------------------------------------------------------------------- -def test_confident_yes_rescues_a_drifted_text_postcondition(tmp_path): +def test_confident_yes_is_a_hint_not_a_pass(tmp_path): vision = _Vision(present=set()) # "Patient list" not readable (drift) verifier = _Verifier("yes") ok, failed, result = _check(vision, verifier, _text_present_pc(), tmp_path) - assert ok is True and failed == [] + assert ok is False and failed == ["text_present 'Patient list'"] assert result.postcondition_drift_rescues == ["text_present 'Patient list'"] assert result.drift_oracle_calls == 1 assert verifier.calls == 1 @@ -179,7 +187,7 @@ def test_text_absent_is_never_rescued(tmp_path): assert result.drift_oracle_calls == 0 -def test_region_stable_is_rescuable(tmp_path): +def test_region_stable_yes_is_only_a_hint(tmp_path): pc = Postcondition( kind=PostconditionKind.REGION_STABLE, region=(10, 10, 40, 20), @@ -187,7 +195,8 @@ def test_region_stable_is_rescuable(tmp_path): timeout_s=0.0, ) ok, failed, result = _check(_Vision(set()), _Verifier("yes"), pc, tmp_path) - assert ok is True and failed == [] + assert ok is False and failed + assert len(result.postcondition_drift_rescues) == 1 assert result.drift_oracle_calls == 1 @@ -278,7 +287,11 @@ def _run(tmp_path, steps, verifier, workflow=None): ] backend = FakeBackend() report = Replayer( - backend, vision=vision, state_verifier=verifier, poll_interval_s=0.0 + backend, + vision=vision, + state_verifier=verifier, + allow_model_grounding=True, + poll_interval_s=0.0, ).run( workflow if workflow is not None else Workflow(name="wf", steps=steps), bundle_dir=bundle, @@ -289,7 +302,6 @@ def _run(tmp_path, steps, verifier, workflow=None): def test_run_halts_with_reconciliation_when_oracle_says_yes_on_a_write(tmp_path): verifier = _Verifier("yes") - navigate = _step(_text_present_pc("Claims"), step_id="nav") submit = _step( _text_present_pc("Claim submitted"), step_id="submit", @@ -298,13 +310,10 @@ def test_run_halts_with_reconciliation_when_oracle_says_yes_on_a_write(tmp_path) risk="irreversible", ) after = _step(_text_present_pc("Done"), step_id="after") - report, backend = _run(tmp_path, [navigate, submit, after], verifier) + report, backend = _run(tmp_path, [submit, after], verifier) assert report.success is False - nav_result, submit_result = report.results[:2] - # The navigation step was rescued as before. - assert nav_result.ok is True - assert nav_result.postcondition_drift_rescues == ["text_present 'Claims'"] + (submit_result,) = report.results # The write was delivered, its screen check failed, and the oracle was # never asked. assert submit_result.ok is False @@ -312,10 +321,10 @@ def test_run_halts_with_reconciliation_when_oracle_says_yes_on_a_write(tmp_path) assert submit_result.drift_oracle_calls == 0 assert submit_result.postcondition_drift_rescues == [] assert "Postconditions failed" in (submit_result.error or "") - assert verifier.calls == 1 # the navigation step only + assert verifier.calls == 0 # Fail-closed: the run stops at the write and never reaches the next step. - assert [r.step_id for r in report.results] == ["nav", "submit"] - assert len(backend.actions) == 2 + assert [r.step_id for r in report.results] == ["submit"] + assert len(backend.actions) == 1 # The write may have landed, so a person checks the record. The run never # says it stopped before saving. assert report.transaction_outcome == "RECONCILIATION_REQUIRED" @@ -325,7 +334,7 @@ def test_run_halts_with_reconciliation_when_oracle_says_yes_on_a_write(tmp_path) assert "Stopped before saving" not in plain.label + plain.meaning -def test_run_keeps_the_rescue_on_navigation_steps(tmp_path): +def test_run_halts_on_a_navigation_step_the_oracle_says_holds(tmp_path): verifier = _Verifier("yes") steps = [ _step(_text_present_pc("Patient list"), step_id="nav1"), @@ -338,14 +347,18 @@ def test_run_keeps_the_rescue_on_navigation_steps(tmp_path): ] report, backend = _run(tmp_path, steps, verifier) - assert report.success is True - assert [r.postcondition_drift_rescues for r in report.results] == [ - ["text_present 'Patient list'"], - ["text_present 'Search'"], + # The model's "yes" is a hint on the halted step, not a pass: the run + # stops at the first step for a person to review. + assert report.success is False + assert [r.step_id for r in report.results] == ["nav1"] + assert report.results[0].ok is False + assert report.results[0].postcondition_drift_rescues == [ + "text_present 'Patient list'" ] - assert [r.drift_oracle_calls for r in report.results] == [1, 1] - assert verifier.calls == 2 - assert len(backend.actions) == 2 + assert report.results[0].drift_oracle_calls == 1 + assert report.model_calls == 1 + assert verifier.calls == 1 + assert len(backend.actions) == 1 def _program_with_handler(step: Step) -> Workflow: From a873de803b10b9da3c4d8a672202520698a709a8 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 12:50:51 -0500 Subject: [PATCH 07/26] fix(flow): pass VLM_VLLM_URL to the vLLM backend Fail-open class: config-silently-ignored. create_app built the vLLM backend without cfg.vllm_url, so it always sent frames to localhost:8000 whatever the operator configured. --- packages/flow/openadapt_flow/services/vlm_service/app.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/flow/openadapt_flow/services/vlm_service/app.py b/packages/flow/openadapt_flow/services/vlm_service/app.py index c10ad6fdf1..dff3f39b24 100644 --- a/packages/flow/openadapt_flow/services/vlm_service/app.py +++ b/packages/flow/openadapt_flow/services/vlm_service/app.py @@ -102,7 +102,13 @@ def create_app( backend is constructed from ``config.backend`` and loaded on startup. """ cfg = config or ServiceConfig.from_env() - bk = backend if backend is not None else build_backend(cfg.backend, cfg.model) + if backend is not None: + bk = backend + elif (cfg.backend or "stub").lower() == "vllm": + # VLM_VLLM_URL names the vLLM server; only that backend takes it. + bk = build_backend(cfg.backend, cfg.model, base_url=cfg.vllm_url) + else: + bk = build_backend(cfg.backend, cfg.model) def _handle(payload: object) -> object: """Blocking per-request work; runs in the batcher's worker thread.""" From 74fe91b92e473b461afe5b265020c7777c80c7a9 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 12:50:52 -0500 Subject: [PATCH 08/26] fix(flow): refuse cleartext off-box endpoints under regulated; no fallback from a pinned model Fail-open classes: cleartext-phi-warned-not-refused, weaker-fallback-on-unavailable. Under the regulated profile an appliance (or grounding_model base_url) over http to a non-loopback host is now not wired; only https, or http to loopback, is allowed. When a grounding model is pinned and can't be wired (unavailable or refused) the appliance grounder no longer stands in for it: the grounding rung stays off and an unresolved target halts for a person. --- packages/flow/openadapt_flow/deployment.py | 28 ++++++++++++- .../openadapt_flow/runtime/model_transport.py | 41 +++++++++++++++++++ 2 files changed, 67 insertions(+), 2 deletions(-) create mode 100644 packages/flow/openadapt_flow/runtime/model_transport.py diff --git a/packages/flow/openadapt_flow/deployment.py b/packages/flow/openadapt_flow/deployment.py index c667d64721..6fd082b8b7 100644 --- a/packages/flow/openadapt_flow/deployment.py +++ b/packages/flow/openadapt_flow/deployment.py @@ -1819,6 +1819,18 @@ def build_replayer( if not ok: print(f"PHI mode: {reason}; replaying FULLY LOCAL.") appliance = None + regulated = ( + getattr(governed_authorization, "execution_profile", None) == "regulated" + ) + if appliance is not None and regulated: + from openadapt_flow.runtime.model_transport import regulated_transport_refusal + + refusal = regulated_transport_refusal( + os.environ.get("OPENADAPT_FLOW_VLM_URL", "") + ) + if refusal is not None: + print(f"Regulated profile: {refusal}; the appliance is NOT wired.") + appliance = None if appliance is not None: print( "Using on-prem VLM appliance at " @@ -1849,6 +1861,15 @@ def build_replayer( if not ok: print(f"PHI mode: {reason}; replaying FULLY LOCAL.") wire = False + if wire and regulated and (grounding_cfg.base_url or "").strip(): + from openadapt_flow.runtime.model_transport import ( + regulated_transport_refusal, + ) + + refusal = regulated_transport_refusal(grounding_cfg.base_url) + if refusal is not None: + print(f"Regulated profile: {refusal}; replaying FULLY LOCAL.") + wire = False if wire: model_grounder = build_model_grounder(grounding_cfg) if model_grounder is not None: @@ -1860,9 +1881,12 @@ def build_replayer( ) # The configured model grounder takes precedence as the VLM fallback; the - # on-prem appliance grounder is used only when no model grounder is wired. + # on-prem appliance grounder is used only when no model is pinned. A pinned + # model that can't be wired (unavailable, refused) never falls back to + # another placement or model: the grounding rung stays off and a target + # the deterministic rungs can't resolve halts for a person. fallback = model_grounder - if fallback is None and appliance is not None: + if fallback is None and appliance is not None and not grounding_cfg.enabled: fallback = appliance.grounder local_model: Optional[Any] = None if runtime_config is not None and runtime_config.local_grounding: diff --git a/packages/flow/openadapt_flow/runtime/model_transport.py b/packages/flow/openadapt_flow/runtime/model_transport.py new file mode 100644 index 0000000000..bbb72be458 --- /dev/null +++ b/packages/flow/openadapt_flow/runtime/model_transport.py @@ -0,0 +1,41 @@ +"""Which model endpoints a regulated run may send frames to. + +Under the ``regulated`` execution profile a frame may leave the process only +over TLS (``https``), or over plain ``http`` to this machine's loopback +interface. Every other URL is refused: cleartext to another host, any other +scheme, and anything that doesn't parse. +""" + +from __future__ import annotations + +import ipaddress +from typing import Optional +from urllib.parse import urlsplit + + +def _loopback(host: str) -> bool: + if host == "localhost": + return True + try: + return ipaddress.ip_address(host).is_loopback + except ValueError: + return False + + +def regulated_transport_refusal(url: str) -> Optional[str]: + """Why a regulated run must not send frames to ``url``, or None if it may.""" + + try: + parts = urlsplit((url or "").strip()) + host = (parts.hostname or "").lower() + except ValueError: + return "the model endpoint URL does not parse" + if not host: + return "the model endpoint URL names no host" + if parts.scheme == "https": + return None + if parts.scheme == "http" and _loopback(host): + return None + if parts.scheme == "http": + return f"the model endpoint {host} is cleartext http off this machine" + return f"the model endpoint scheme {parts.scheme!r} is not https" From db1f3e59dbc3bef90a37f1764c84bc5efc34ef31 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 12:51:01 -0500 Subject: [PATCH 09/26] test(flow): pin the egress ledger, placement split and transport rule; map the capability --- CAPABILITIES.md | 1 + packages/flow/tests/test_model_failclosed.py | 151 +++++++++++++++++++ 2 files changed, 152 insertions(+) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index cad88c6b1c..fe801aec05 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -348,6 +348,7 @@ improvising or retrying when something is off. | Named sections for every compiled program ("Who: title, first name, last name", "Contact", "Create New Patient"), found without a model from the save, the recorded form structure, the fields and any narration; a person can rename, merge or split them on the review screen | Released | Unit tests; the certified OpenEMR referral bundle and a real recording of it on a local test copy with made-up patients | `openadapt-flow sections`; [SECTIONS.md](packages/flow/docs/SECTIONS.md) | | Encrypt PHI at rest: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, and the run directories of sealed bundles; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md) | | Encryption at rest under a configured or locally generated key (0600): durable checkpoints and attended state by default; with `OPENADAPT_FLOW_AT_REST=strict`, every recording, bundle and run directory too. Each plaintext write is logged on stderr and in a ledger that Desktop shows as a notice | On main | Synthetic (key, opt-out, strict-mode, run-directory and attended-state audit-hook tests) | `openadapt_flow.at_rest`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md#default-opt-out-and-strict-mode) | +| Model calls fail closed: a component with no `MAY_EGRESS` marker counts as sending frames off the box and needs the egress opt-in; a model "yes" from the drift oracle is a hint for the person reviewing the halt, never a pass; identity-VLM calls count as model calls, split by placement (off-box into `model_calls`, in process into `local_model_calls`), so off-box identity crops never report no external calls; every frame sent off the box is first written to a local append-only ledger (`egress-ledger.jsonl` beside the run directory, hashes and sizes only) and is not sent if that write fails; the regulated profile refuses a cleartext appliance or grounding endpoint that is not loopback; a pinned grounding model that can't be wired never falls back to the appliance | On main | Unit tests (`tests/test_model_failclosed.py`, `tests/test_drift_oracle.py`) | `runtime/model_egress.py`, `runtime/model_transport.py`, [ON_PREM_VLM.md](packages/flow/docs/deployment/ON_PREM_VLM.md) | | Signed receipts (Seals), countersigned and timestamped, offline by default | Released | Unit tests, real TSA tokens | `openadapt-flow seal`, `countersign`, `local-seal` | | Offline Seals signed with a key the customer holds: a key file, the OS keychain, or a PKCS#11 token or HSM; pinned keys with rotation and revocation; no fallback to a generated key | On main ([#1392](https://github.com/OpenAdaptAI/OpenAdapt/pull/1392)) | Unit tests with synthetic data (keychain and PKCS#11 through stand-ins) | `openadapt-flow local-seal --key`, `local-seal key create`, `pin`, `revoke`; `openadapt seal verify FOLDER` checks every sealed run in a folder; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#customer-held-keys) | | Anchor an offline Seal in the public Sigstore Rekor transparency log (opt-in; sends one digest and the public key), and verify the anchor offline from the stored inclusion proof | Released ([#1394](https://github.com/OpenAdaptAI/OpenAdapt/pull/1394)) | Unit tests against a simulated Rekor log; real public Rekor entries and Sigstore TSA tokens for the landing demo's referral runs, verified offline in tests; Ed25519ph matches the RFC 8032 test vector | `openadapt-flow local-seal anchor`, `local-seal verify --require-anchor`; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#optional-anchor-a-seal-in-a-public-transparency-log) | diff --git a/packages/flow/tests/test_model_failclosed.py b/packages/flow/tests/test_model_failclosed.py index d2e116ec80..9859d6543f 100644 --- a/packages/flow/tests/test_model_failclosed.py +++ b/packages/flow/tests/test_model_failclosed.py @@ -12,6 +12,8 @@ appliance. 6. A pinned model that is unavailable never falls back to another placement or model. +7. Every frame sent off the box is on a local append-only ledger, written + before the call, halted runs included; no ledger line, no call. """ from __future__ import annotations @@ -320,3 +322,152 @@ def test_unavailable_pinned_model_never_falls_back_to_appliance(wiring, monkeypa ) _build(runtime_config=runtime, phi_mode=False) assert not isinstance(wiring.get("fallback"), RemoteGrounder) + + +def test_regulated_profile_keeps_tls_and_loopback_appliances(wiring, monkeypatch): + for url in ("https://10.20.30.40:8443", "http://127.0.0.1:8000"): + wiring.clear() + monkeypatch.setenv("OPENADAPT_FLOW_VLM_URL", url) + runtime = RuntimeSection(phi_grounding_allowlist=["10.20.30.40", "127.0.0.1"]) + authorization = SimpleNamespace( + execution_profile="regulated", qualification_case_id=None + ) + _build( + runtime_config=runtime, + phi_mode=True, + governed_authorization=authorization, + ) + assert _wired_appliance_handles(wiring) == [ + "identity_vlm", + "state_verifier", + "grounder", + ], url + + +@pytest.mark.parametrize( + "url, allowed", + [ + ("https://vlm.internal:8443", True), + ("http://127.0.0.1:8000", True), + ("http://[::1]:8000", True), + ("http://localhost:8000", True), + ("http://10.20.30.40:8000", False), + ("http://localhost.evil.example:8000", False), + ("ftp://vlm.internal", False), + ("vlm.internal:8000", False), + ("", False), + ], +) +def test_regulated_transport_rule(url, allowed): + from openadapt_flow.runtime.model_transport import regulated_transport_refusal + + assert (regulated_transport_refusal(url) is None) is allowed + + +def test_appliance_still_backs_an_unpinned_run(wiring, monkeypatch): + monkeypatch.setenv("OPENADAPT_FLOW_VLM_URL", "https://vlm.internal:8443") + _build(runtime_config=RuntimeSection(), phi_mode=False) + assert isinstance(wiring.get("fallback"), RemoteGrounder) + + +# -------------------------------------------------------------------------- +# 7. The egress ledger, and grounder calls that abstained. +# -------------------------------------------------------------------------- + + +class _OffBoxGrounder: + MAY_EGRESS = True + base_url = "https://vlm.internal:8443" + + def __init__(self) -> None: + self.calls = 0 + + def locate(self, screen_png, intent, ocr_text=None): + self.calls += 1 + return None # abstains after the frame was sent + + +def _ledger_lines(path): + import json + + return [json.loads(line) for line in path.read_text().splitlines()] + + +def test_off_box_frame_is_ledgered_before_the_call(tmp_path, monkeypatch): + monkeypatch.delenv("OPENADAPT_FLOW_EGRESS_LEDGER", raising=False) + inner = _OffBoxGrounder() + rp = Replayer(FakeBackend(), grounder=inner, allow_model_grounding=True) + rp._egress.bind_run(tmp_path / "runs" / "r1") + rp._egress.step_id = "s1" + frame = _png() + assert rp.grounder.locate(frame, "open the chart") is None + assert inner.calls == 1 + (line,) = _ledger_lines(tmp_path / "runs" / "egress-ledger.jsonl") + assert line["component"] == "grounder" + assert line["destination"] == "vlm.internal" + assert line["run"] == "r1" and line["step"] == "s1" + import hashlib + + assert line["frames"] == [ + {"sha256": hashlib.sha256(frame).hexdigest(), "bytes": len(frame)} + ] + mode = (tmp_path / "runs" / "egress-ledger.jsonl").stat().st_mode & 0o777 + assert mode == 0o600 + + # The abstaining call still counts as an off-box model call. + result = StepResult(step_id="s1", intent="open the chart", ok=False) + rp._egress.drain(result) + assert result.grounder_calls == 1 + assert Replayer._result_model_calls(result) == 1 + + +def test_no_ledger_line_means_no_call(tmp_path, monkeypatch): + blocker = tmp_path / "not-a-dir" + blocker.write_text("") + monkeypatch.setenv("OPENADAPT_FLOW_EGRESS_LEDGER", str(blocker / "ledger.jsonl")) + inner = _OffBoxGrounder() + vlm = _OffBoxIdentityVLM("same") + verifier = _Verifier("yes") + rp = Replayer( + FakeBackend(), + grounder=inner, + identity_vlm=vlm, + state_verifier=verifier, + allow_model_grounding=True, + ) + rp._egress.bind_run(tmp_path / "run") + crop = _crop_png() + assert rp.grounder.locate(crop, "x") is None + assert rp.identity_vlm.same_or_different(crop, crop) == "different" + assert rp.state_verifier.holds(crop, "x") is False + assert (inner.calls, vlm.calls, verifier.calls) == (0, 0, 0) + + +def test_halted_run_frames_are_on_the_ledger(tmp_path, monkeypatch): + from tests.test_drift_oracle import _run, _text_present_pc + + monkeypatch.delenv("OPENADAPT_FLOW_EGRESS_LEDGER", raising=False) + verifier = _Verifier("yes") + report, _backend = _run( + tmp_path, [_step(_text_present_pc("Patient list"))], verifier + ) + assert report.success is False + (line,) = _ledger_lines(tmp_path / "egress-ledger.jsonl") + assert line["component"] == "state_verifier" + assert line["step"] == "s1" + assert report.model_calls == 1 + + +def test_in_process_identity_vlm_counts_as_local(monkeypatch, tmp_path): + vlm = _OffBoxIdentityVLM("different") + vlm.MAY_EGRESS = False + rp = Replayer(FakeBackend(), identity_vlm=vlm) + crop = _crop_png() + monkeypatch.setattr(rp, "_identifier_crops", lambda *a, **k: (crop, crop)) + step, workflow, res = _identity_step() + result = StepResult(step_id=step.id, intent=step.intent, ok=False) + rp._identity_gate_error(step, res, crop, {}, workflow, tmp_path, result) + assert vlm.calls == 1 + assert Replayer._result_model_calls(result) == 0 + assert Replayer._result_local_model_calls(result) == 1 + assert rp._egress.entries == [] From 8b0c7129105518f2ca67e302550a888c029c5ff1 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 18:15:41 -0500 Subject: [PATCH 10/26] docs(flow): describe the regulated transport rule, egress ledger and no-fallback rule Fail-open classes: cleartext-phi-warned-not-refused, unrecorded-egress, weaker-fallback-on-unavailable (documentation only). --- packages/flow/docs/deployment/ON_PREM_VLM.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/packages/flow/docs/deployment/ON_PREM_VLM.md b/packages/flow/docs/deployment/ON_PREM_VLM.md index 5a79ed05d2..8bbf751114 100644 --- a/packages/flow/docs/deployment/ON_PREM_VLM.md +++ b/packages/flow/docs/deployment/ON_PREM_VLM.md @@ -246,7 +246,22 @@ through. Scrubbing here would **defeat the safety check**, not add safety. 3. **In-flight PHI, treated as such.** The crop is PHI moving inside the trust boundary. Run the appliance HTTPS-only on the LAN, gate it with the bearer token (`VLM_SERVICE_TOKEN`), and keep it inside the same network zone as the - runners. + runners. Under the `regulated` execution profile the runner enforces the + transport: it wires an appliance or `grounding_model.base_url` only over + `https`, or over `http` to loopback, and prints why it refused any other URL. +4. **Every frame sent off the box is on a local ledger.** Before each off-box + call the runner appends one line to `egress-ledger.jsonl` beside the run + directory (or the file `OPENADAPT_FLOW_EGRESS_LEDGER` names). The line holds + the frame's SHA-256 and size, the component, the destination host, the run, + the step and the time, and never pixels or text. The file is append-only, + mode `0600` and fsynced per line. If the line can't be written, the frame is + not sent and the component gives its fail-safe answer, so the step halts. + Halted runs are on the ledger too, because each line is written when its + frame is sent. +5. **No fallback to another model.** When `grounding_model` is pinned and + can't be wired, the appliance grounder does not stand in for it. The + grounding rung stays off, and a target the deterministic rungs can't resolve + halts for a person. An operator auditing the appliance should confirm no reverse proxy, WSGI, or model-server logs the request body — that is the only way a crop could persist. From 0b70133995955708caf435a27863a789b7c9a036 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 19:33:56 -0500 Subject: [PATCH 11/26] refactor(flow): move per-step model-call counts out of ir.py [fail-open: budget] --- llms-full.txt | 1 + packages/flow/openadapt_flow/ir.py | 17 +++--------- .../flow/openadapt_flow/model_call_counts.py | 27 +++++++++++++++++++ 3 files changed, 32 insertions(+), 13 deletions(-) create mode 100644 packages/flow/openadapt_flow/model_call_counts.py diff --git a/llms-full.txt b/llms-full.txt index cfb52865db..f20c0a7c96 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -790,6 +790,7 @@ improvising or retrying when something is off. | Named sections for every compiled program ("Who: title, first name, last name", "Contact", "Create New Patient"), found without a model from the save, the recorded form structure, the fields and any narration; a person can rename, merge or split them on the review screen | Released | Unit tests; the certified OpenEMR referral bundle and a real recording of it on a local test copy with made-up patients | `openadapt-flow sections`; [SECTIONS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SECTIONS.md) | | Encrypt PHI at rest: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, and the run directories of sealed bundles; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md) | | Encryption at rest under a configured or locally generated key (0600): durable checkpoints and attended state by default; with `OPENADAPT_FLOW_AT_REST=strict`, every recording, bundle and run directory too. Each plaintext write is logged on stderr and in a ledger that Desktop shows as a notice | On main | Synthetic (key, opt-out, strict-mode, run-directory and attended-state audit-hook tests) | `openadapt_flow.at_rest`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md#default-opt-out-and-strict-mode) | +| Model calls fail closed: a component with no `MAY_EGRESS` marker counts as sending frames off the box and needs the egress opt-in; a model "yes" from the drift oracle is a hint for the person reviewing the halt, never a pass; identity-VLM calls count as model calls, split by placement (off-box into `model_calls`, in process into `local_model_calls`), so off-box identity crops never report no external calls; every frame sent off the box is first written to a local append-only ledger (`egress-ledger.jsonl` beside the run directory, hashes and sizes only) and is not sent if that write fails; the regulated profile refuses a cleartext appliance or grounding endpoint that is not loopback; a pinned grounding model that can't be wired never falls back to the appliance | On main | Unit tests (`tests/test_model_failclosed.py`, `tests/test_drift_oracle.py`) | `runtime/model_egress.py`, `runtime/model_transport.py`, [ON_PREM_VLM.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/deployment/ON_PREM_VLM.md) | | Receipts: one signed record per run, with any outcome (`receipt.json`, a DSSE envelope over an in-toto `record/run/v1` statement): one line per write with its check, strength and what it didn't check; digests, enums, counts and salted commitments only, never screenshots, typed values, URLs or page text; the outcome copied, never upgraded; signer roles from a pinned registry (this computer, customer key, OpenAdapt Cloud countersignature, public log, demo), unknown key, role or schema fails closed; a public card is the same envelope with only allow-listed values opened (`openadapt.public-disclosure/v1`) | Branch ([#2394](https://github.com/OpenAdaptAI/OpenAdapt/pull/2394)) | Unit tests with synthetic runs (stopped runs, tampered report and payload, unknown signer, embedded image refused); 15 shared vectors for the Python, Cloud and web verifiers | `openadapt verify `, `openadapt receipt verify\|view\|publish\|unpublish`; [RECEIPTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/RECEIPTS.md); [vectors](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/types/tests/vectors/record-run-v1/README.md) | | Older signed formats still verify, labelled "older format": offline and public Seals (`local-seal/v1`, `public-seal/v1`), Cloud-signed Execute receipts (`seal-signature/v1`), run summaries (`run-receipt/v2`), write and transaction receipts; Seals countersigned and timestamped | Released | Unit tests, real TSA tokens | `openadapt verify`; `openadapt-flow countersign`, `local-seal`; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md) | | Encrypt a bundle at rest under one encrypted index | Released | Unit tests | `openadapt-flow encrypt` (`seal` is a hidden alias for one release) | diff --git a/packages/flow/openadapt_flow/ir.py b/packages/flow/openadapt_flow/ir.py index eb79d9d360..530449fded 100644 --- a/packages/flow/openadapt_flow/ir.py +++ b/packages/flow/openadapt_flow/ir.py @@ -47,6 +47,7 @@ from openadapt_flow import run_invocation as _run_invocation from openadapt_flow.approval_mode.model import ApprovalModeItemEvidence from openadapt_flow.input_evidence import FreshActuationEvent as FreshActuationEvent +from openadapt_flow.model_call_counts import ModelCallCounts from openadapt_flow.job_authoring import ( JobAuthoringBinding, check_workflow_input, @@ -5134,7 +5135,7 @@ class CheckToClickRecheck(BaseModel): settled_on: Optional[int] = Field(default=None, ge=1) -class StepResult(BaseModel): +class StepResult(ModelCallCounts): step_id: str intent: str ok: bool @@ -5249,20 +5250,10 @@ class StepResult(BaseModel): "as proof that settled-state detection ran." ), ) - # Drift-oracle hints: postconditions that deterministically FAILED and that - # the optional VLM state-verifier said hold. A hint only: the - # postcondition stays failed and the step halts for a person to review - # (recorded for audit; empty unless a state verifier is configured). + # Drift-oracle hints: FAILED postconditions the optional VLM state-verifier + # said hold. A hint only: they stay failed and the step halts for a person. postcondition_drift_rescues: list[str] = Field(default_factory=list) drift_oracle_calls: int = 0 # VLM state-verifier calls this step - # Model calls by placement (runtime.model_egress): identity-VLM calls that - # sent crops off the box, ones that ran in process, and off-box grounder - # calls (abstentions included). Omitted from the JSON when zero. - identity_vlm_calls: int = Field(default=0, ge=0, exclude_if=lambda v: v == 0) - local_identity_vlm_calls: int = Field( - default=0, ge=0, exclude_if=lambda v: v == 0 - ) - grounder_calls: int = Field(default=0, ge=0, exclude_if=lambda v: v == 0) #: The uniform page scale (for example 1.25 under 125% zoom) at which a #: ``region_stable`` check found its recorded content, when it was found #: only there. Set only when this step's own click showed the same scale. diff --git a/packages/flow/openadapt_flow/model_call_counts.py b/packages/flow/openadapt_flow/model_call_counts.py new file mode 100644 index 0000000000..54f9197fe6 --- /dev/null +++ b/packages/flow/openadapt_flow/model_call_counts.py @@ -0,0 +1,27 @@ +"""Per-step model-call counts by placement, kept out of ``ir.py``. + +:class:`~openadapt_flow.ir.StepResult` inherits these fields. The replayer's +egress recorder (:mod:`openadapt_flow.runtime.model_egress`) fills them: +identity-VLM calls that sent crops off the box, identity-VLM calls that ran in +process, and off-box grounder calls (abstentions and failed steps included). +Each field is omitted from the JSON when zero, so reports and receipts written +before these fields existed keep their bytes. +""" + +from __future__ import annotations + +from typing import Any + +from pydantic import BaseModel, Field + + +def _count() -> Any: + return Field(default=0, ge=0, exclude_if=lambda v: v == 0) + + +class ModelCallCounts(BaseModel): + """Model calls one step made, split by where the frame went.""" + + identity_vlm_calls: int = _count() + local_identity_vlm_calls: int = _count() + grounder_calls: int = _count() From d872a91a0156e45ebe3c6342b942fb72c93429fb Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 19:47:10 -0500 Subject: [PATCH 12/26] refactor(flow): keep the per-step model-call counts in ir.py within its budget Fail-open class: none (refactor). Inline the three counts, drop the extra module that cost ir.py an import, regenerate the schema surface. --- packages/flow/openadapt_flow/ir.py | 23 ++++++------ .../flow/openadapt_flow/model_call_counts.py | 27 -------------- .../{runtime => }/model_transport.py | 0 .../schema_surface/openadapt_flow.ir.json | 36 +++++++++++++++++++ 4 files changed, 47 insertions(+), 39 deletions(-) delete mode 100644 packages/flow/openadapt_flow/model_call_counts.py rename packages/flow/openadapt_flow/{runtime => }/model_transport.py (100%) diff --git a/packages/flow/openadapt_flow/ir.py b/packages/flow/openadapt_flow/ir.py index 530449fded..c58c4a5290 100644 --- a/packages/flow/openadapt_flow/ir.py +++ b/packages/flow/openadapt_flow/ir.py @@ -47,7 +47,6 @@ from openadapt_flow import run_invocation as _run_invocation from openadapt_flow.approval_mode.model import ApprovalModeItemEvidence from openadapt_flow.input_evidence import FreshActuationEvent as FreshActuationEvent -from openadapt_flow.model_call_counts import ModelCallCounts from openadapt_flow.job_authoring import ( JobAuthoringBinding, check_workflow_input, @@ -5135,7 +5134,7 @@ class CheckToClickRecheck(BaseModel): settled_on: Optional[int] = Field(default=None, ge=1) -class StepResult(ModelCallCounts): +class StepResult(BaseModel): step_id: str intent: str ok: bool @@ -5177,10 +5176,9 @@ class StepResult(ModelCallCounts): # effects were declared with no verifier configured). None is also used for # an explicitly approved but unverified GUI write; the separate # ``effect_approved_unverified`` flag makes that risk acceptance visible. - # ``effect_results`` - # holds one human-readable verdict line per declared effect, for the - # audit trail (mirrors the identity check's report surface). ZERO model - # calls on this path — effect verification reads the system of record. + # ``effect_results`` holds one human-readable verdict line per declared + # effect for the audit trail. ZERO model calls on this path: effect + # verification reads the system of record. effect_verified: Optional[bool] = None effect_approved_unverified: bool = False # A governed identity/effect/postcondition refusal is not an ordinary @@ -5206,12 +5204,9 @@ class StepResult(ModelCallCounts): "continuation_preempted", ] ] = None - # One stable, NON-secret-bearing SHA-256 digest per verified effect, taken - # AFTER the effect's ValueExpr contract was bound to THIS run's params - # (P0-3). Records THAT a parameterized run verified against its own resolved - # record/value/idempotency-key (and lets an auditor confirm two runs - # resolved differently) without persisting the underlying value (e.g. a - # patient identifier). Empty when the step declared no effects. + # One NON-secret SHA-256 digest per verified effect, taken AFTER its + # ValueExpr contract was bound to THIS run's params (P0-3): proof a run + # verified its own record/value/idempotency key, without the value. effect_contract_hashes: list[str] = Field(default_factory=list) # How this step's write was PERFORMED: "api" when actuated via an # ApiBinding (GUI resolve/act skipped), None when it went through the GUI @@ -5254,6 +5249,10 @@ class StepResult(ModelCallCounts): # said hold. A hint only: they stay failed and the step halts for a person. postcondition_drift_rescues: list[str] = Field(default_factory=list) drift_oracle_calls: int = 0 # VLM state-verifier calls this step + # Model calls by placement (runtime.model_egress); omitted when zero. + identity_vlm_calls: int = Field(default=0, ge=0, exclude_if=lambda v: v == 0) + local_identity_vlm_calls: int = Field(default=0, ge=0, exclude_if=lambda v: v == 0) + grounder_calls: int = Field(default=0, ge=0, exclude_if=lambda v: v == 0) #: The uniform page scale (for example 1.25 under 125% zoom) at which a #: ``region_stable`` check found its recorded content, when it was found #: only there. Set only when this step's own click showed the same scale. diff --git a/packages/flow/openadapt_flow/model_call_counts.py b/packages/flow/openadapt_flow/model_call_counts.py deleted file mode 100644 index 54f9197fe6..0000000000 --- a/packages/flow/openadapt_flow/model_call_counts.py +++ /dev/null @@ -1,27 +0,0 @@ -"""Per-step model-call counts by placement, kept out of ``ir.py``. - -:class:`~openadapt_flow.ir.StepResult` inherits these fields. The replayer's -egress recorder (:mod:`openadapt_flow.runtime.model_egress`) fills them: -identity-VLM calls that sent crops off the box, identity-VLM calls that ran in -process, and off-box grounder calls (abstentions and failed steps included). -Each field is omitted from the JSON when zero, so reports and receipts written -before these fields existed keep their bytes. -""" - -from __future__ import annotations - -from typing import Any - -from pydantic import BaseModel, Field - - -def _count() -> Any: - return Field(default=0, ge=0, exclude_if=lambda v: v == 0) - - -class ModelCallCounts(BaseModel): - """Model calls one step made, split by where the frame went.""" - - identity_vlm_calls: int = _count() - local_identity_vlm_calls: int = _count() - grounder_calls: int = _count() diff --git a/packages/flow/openadapt_flow/runtime/model_transport.py b/packages/flow/openadapt_flow/model_transport.py similarity index 100% rename from packages/flow/openadapt_flow/runtime/model_transport.py rename to packages/flow/openadapt_flow/model_transport.py diff --git a/packages/flow/tests/fixtures/schema_surface/openadapt_flow.ir.json b/packages/flow/tests/fixtures/schema_surface/openadapt_flow.ir.json index 8080bbc3ec..5cb5c42a5f 100644 --- a/packages/flow/tests/fixtures/schema_surface/openadapt_flow.ir.json +++ b/packages/flow/tests/fixtures/schema_surface/openadapt_flow.ir.json @@ -33886,6 +33886,24 @@ "title": "Drift Oracle Calls", "type": "integer" }, + "identity_vlm_calls": { + "default": 0, + "minimum": 0, + "title": "Identity Vlm Calls", + "type": "integer" + }, + "local_identity_vlm_calls": { + "default": 0, + "minimum": 0, + "title": "Local Identity Vlm Calls", + "type": "integer" + }, + "grounder_calls": { + "default": 0, + "minimum": 0, + "title": "Grounder Calls", + "type": "integer" + }, "postcondition_page_scale": { "anyOf": [ { @@ -47667,6 +47685,24 @@ "title": "Drift Oracle Calls", "type": "integer" }, + "identity_vlm_calls": { + "default": 0, + "minimum": 0, + "title": "Identity Vlm Calls", + "type": "integer" + }, + "local_identity_vlm_calls": { + "default": 0, + "minimum": 0, + "title": "Local Identity Vlm Calls", + "type": "integer" + }, + "grounder_calls": { + "default": 0, + "minimum": 0, + "title": "Grounder Calls", + "type": "integer" + }, "postcondition_page_scale": { "anyOf": [ { From bede781bf06b28e51b20ce3895444e7f3a3244bf Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 19:47:10 -0500 Subject: [PATCH 13/26] fix(flow): refuse an empty pinned model; read the regulated profile from either source Fail-open class: silent model fallback (an empty grounding_model.model became the shipped default) and transport check bypass (the regulated check read only the authorization's profile and the env URL, not the URL the appliance client sends to). --- packages/flow/docs/deployment/ON_PREM_VLM.md | 7 ++-- packages/flow/openadapt_flow/deployment.py | 34 +++++++++++++------- 2 files changed, 26 insertions(+), 15 deletions(-) diff --git a/packages/flow/docs/deployment/ON_PREM_VLM.md b/packages/flow/docs/deployment/ON_PREM_VLM.md index 8bbf751114..3b2c8922f4 100644 --- a/packages/flow/docs/deployment/ON_PREM_VLM.md +++ b/packages/flow/docs/deployment/ON_PREM_VLM.md @@ -259,9 +259,10 @@ through. Scrubbing here would **defeat the safety check**, not add safety. Halted runs are on the ledger too, because each line is written when its frame is sent. 5. **No fallback to another model.** When `grounding_model` is pinned and - can't be wired, the appliance grounder does not stand in for it. The - grounding rung stays off, and a target the deterministic rungs can't resolve - halts for a person. + can't be wired, the appliance grounder does not stand in for it. A pinned + section must name its `model`; an empty one is refused, never given a + default. The grounding rung stays off, and a target the deterministic rungs + can't resolve halts for a person. An operator auditing the appliance should confirm no reverse proxy, WSGI, or model-server logs the request body — that is the only way a crop could persist. diff --git a/packages/flow/openadapt_flow/deployment.py b/packages/flow/openadapt_flow/deployment.py index 248b828447..c2ba5889ba 100644 --- a/packages/flow/openadapt_flow/deployment.py +++ b/packages/flow/openadapt_flow/deployment.py @@ -799,8 +799,8 @@ class GroundingModelConfig(BaseModel): #: Root URL of an ``openai_compatible`` endpoint (``/chat/completions`` is #: appended). Required for ``openai_compatible``; ignored for ``anthropic``. base_url: str = "" - #: The vision-capable model id to request. For ``anthropic`` an empty value - #: uses the shipped default; for ``openai_compatible`` it is required. + #: The vision-capable model id to request. Required for both providers: an + #: enabled section with no model is refused, never given a default. model: str = "" #: NAME of the environment variable holding the API key (never the key #: itself). Empty => no auth header sent (a loopback vLLM/Ollama needs none); @@ -1683,9 +1683,17 @@ def build_model_grounder(cfg: GroundingModelConfig) -> Optional[Any]: api_key = os.environ.get(cfg.api_key_env, "") if cfg.api_key_env else "" if provider == "anthropic": - from openadapt_flow.runtime.grounder import _DEFAULT_MODEL, AnthropicGrounder + from openadapt_flow.runtime.grounder import AnthropicGrounder - model = (cfg.model or "").strip() or _DEFAULT_MODEL + model = (cfg.model or "").strip() + if not model: + # A pinned grounding model must name its model: an empty value + # never silently becomes the shipped default. + print( + "grounding_model.provider 'anthropic' requires a model; " + "replaying FULLY LOCAL." + ) + return None try: client = None if api_key: @@ -1819,15 +1827,17 @@ def build_replayer( if not ok: print(f"PHI mode: {reason}; replaying FULLY LOCAL.") appliance = None - regulated = ( - getattr(governed_authorization, "execution_profile", None) == "regulated" - ) + # Regulated if either the authorization or the deployment names it. + regulated = "regulated" in { + getattr(governed_authorization, "execution_profile", None), + getattr(runtime_config, "profile", None), + } if appliance is not None and regulated: - from openadapt_flow.runtime.model_transport import regulated_transport_refusal + from openadapt_flow.model_transport import regulated_transport_refusal - refusal = regulated_transport_refusal( - os.environ.get("OPENADAPT_FLOW_VLM_URL", "") - ) + # The URL the appliance client actually sends to. + sent_to = getattr(getattr(appliance, "client", None), "_base_url", "") + refusal = regulated_transport_refusal(sent_to or "") if refusal is not None: print(f"Regulated profile: {refusal}; the appliance is NOT wired.") appliance = None @@ -1862,7 +1872,7 @@ def build_replayer( print(f"PHI mode: {reason}; replaying FULLY LOCAL.") wire = False if wire and regulated and (grounding_cfg.base_url or "").strip(): - from openadapt_flow.runtime.model_transport import ( + from openadapt_flow.model_transport import ( regulated_transport_refusal, ) From 7c770d36d4d7250b124d3950bbbfaaeb6a4ea38e Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 19:47:11 -0500 Subject: [PATCH 14/26] fix(flow): split the receipt model-call rule by placement Fail-open class: unreported egress. Off-box model calls require observed external calls on the receipt; in-process calls never do. The transport rule moves down to the policy layer next to deployment. --- packages/flow/import_layers.json | 2 + .../openadapt_flow/model_call_evidence.py | 39 +++++++++++++++++++ packages/flow/openadapt_flow/receipt.py | 11 ++++-- 3 files changed, 48 insertions(+), 4 deletions(-) create mode 100644 packages/flow/openadapt_flow/model_call_evidence.py diff --git a/packages/flow/import_layers.json b/packages/flow/import_layers.json index ea85e8a5d9..a37566aa76 100644 --- a/packages/flow/import_layers.json +++ b/packages/flow/import_layers.json @@ -66,6 +66,8 @@ "openadapt_flow.deployment", "openadapt_flow.form_tx.receipt", "openadapt_flow.key_rotation", + "openadapt_flow.model_call_evidence", + "openadapt_flow.model_transport", "openadapt_flow.offline_seal", "openadapt_flow.policy", "openadapt_flow.production_qualification", diff --git a/packages/flow/openadapt_flow/model_call_evidence.py b/packages/flow/openadapt_flow/model_call_evidence.py new file mode 100644 index 0000000000..8a024b49ec --- /dev/null +++ b/packages/flow/openadapt_flow/model_call_evidence.py @@ -0,0 +1,39 @@ +"""The receipt rule for model calls, split by where the frame went. + +A signed record's ``model_calls`` counts only calls that may have sent a frame +off the box: drift-oracle calls, off-box identity-VLM calls and off-box +grounder calls (:func:`openadapt_flow.runtime.model_egress.model_calls_off_box`). +Calls that ran in process are counted on the run report as +``local_model_calls`` and never enter ``model_calls``. + +The two placements carry different rules: + +* **Off the box.** Any off-box call is model evidence, and the record must say + ``external_network_calls == "observed"``. A record that counts off-box calls + and says ``"none"`` is refused, so off-box identity crops can never be + reported as a run with no external calls. +* **In process.** An in-process call sends nothing over the network, so it + never requires ``"observed"`` and never makes a record with no off-box calls + claim model evidence. + +The receipt (:class:`openadapt_flow.receipt.RunReceipt`) applies +:func:`model_call_evidence_error`; the terminal verification payload +checks the same two rules in its own validator. +""" + +from __future__ import annotations + +from collections.abc import Iterable +from typing import Optional + + +def model_call_evidence_error( + off_box_calls: int, evidence_classes: Iterable[str], network: str +) -> Optional[str]: + """Why a record's off-box model-call count contradicts it, or None.""" + + if (off_box_calls > 0) != ("model" in set(evidence_classes)): + return "model-call count and evidence class disagree" + if off_box_calls > 0 and network != "observed": + return "model calls require observed external network calls" + return None diff --git a/packages/flow/openadapt_flow/receipt.py b/packages/flow/openadapt_flow/receipt.py index 91c8a7d324..a72bb38e5f 100644 --- a/packages/flow/openadapt_flow/receipt.py +++ b/packages/flow/openadapt_flow/receipt.py @@ -339,10 +339,13 @@ def _complete_verified_contract(self) -> "RunReceipt": and self.effect_assurance != _ASSURANCE_BY_TIER[self.effect_tier_reached] ): raise ValueError("effect assurance disagrees with the effect tier") - if (self.model_calls > 0) != ("model" in self.evidence_classes): - raise ValueError("model-call count and evidence class disagree") - if self.model_calls > 0 and self.external_network_calls != "observed": - raise ValueError("model calls require observed external network calls") + # ``model_calls`` is off-box calls only; in-process ones never count. + from openadapt_flow.model_call_evidence import model_call_evidence_error + + if error := model_call_evidence_error( + self.model_calls, self.evidence_classes, self.external_network_calls + ): + raise ValueError(error) expected = hashlib.sha256(self.canonical_json(include_digest=False)).hexdigest() if self.receipt_digest != expected: raise ValueError("receipt digest does not match its canonical payload") From ae517cf9d6a6a74302a7cb5200f2101011c45691 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 19:47:11 -0500 Subject: [PATCH 15/26] fix(flow): drop undrained model-call counts when a new run binds Fail-open class: misattributed model calls. Counts from a step that raised never land on the next run's first step. Tests pin the empty-model refusal, the receipt placement split, and mark the resume test's verifier as remote. --- .../openadapt_flow/runtime/model_egress.py | 7 +- .../flow/tests/test_execution_profiles.py | 4 + packages/flow/tests/test_model_failclosed.py | 77 ++++++++++++++++++- 3 files changed, 84 insertions(+), 4 deletions(-) diff --git a/packages/flow/openadapt_flow/runtime/model_egress.py b/packages/flow/openadapt_flow/runtime/model_egress.py index e8afe3dff6..10f00330ec 100644 --- a/packages/flow/openadapt_flow/runtime/model_egress.py +++ b/packages/flow/openadapt_flow/runtime/model_egress.py @@ -93,6 +93,9 @@ def bind_run(self, run_dir: Path, run_id: Optional[str] = None) -> None: run_dir = Path(run_dir) self.ledger_path = Path(override) if override else run_dir.parent / LEDGER_NAME self.run_ref = run_id or run_dir.name + # Counts a raised step never drained belong to the aborted run (its + # frames are on the ledger); they never land on this run's first step. + self._pending = dict.fromkeys(self._pending, 0) def admit(self, kind: str, component: Any, *frames: bytes) -> bool: """Record a frame about to leave the box. False means: don't send.""" @@ -141,9 +144,7 @@ def wrap(self, kind: str, component: Any) -> Any: if component is None: return None if isinstance(component, FallbackGrounder): - return FallbackGrounder( - [self.wrap(kind, g) for g in component._grounders] - ) + return FallbackGrounder([self.wrap(kind, g) for g in component._grounders]) off_box = component_may_egress(component) if kind == "identity_vlm": return _IdentityVLM(self, component, off_box) diff --git a/packages/flow/tests/test_execution_profiles.py b/packages/flow/tests/test_execution_profiles.py index 5fb2e4eec2..741151ddbf 100644 --- a/packages/flow/tests/test_execution_profiles.py +++ b/packages/flow/tests/test_execution_profiles.py @@ -281,6 +281,9 @@ def wait_settled_result(self, backend, **kwargs): class _CountingStateVerifier: + # A remote verifier: its calls are the run's external network evidence. + MAY_EGRESS = True + def __init__(self, *, holds: bool) -> None: self.result = holds self.calls = 0 @@ -2873,6 +2876,7 @@ def test_resume_preserves_failed_leg_model_and_network_evidence(tmp_path): FakeBackend(), vision=_ReadyVision(), state_verifier=verifier, + allow_model_grounding=True, governed_authorization=authorization, durable=True, require_settled=True, diff --git a/packages/flow/tests/test_model_failclosed.py b/packages/flow/tests/test_model_failclosed.py index 9859d6543f..0c4ab50706 100644 --- a/packages/flow/tests/test_model_failclosed.py +++ b/packages/flow/tests/test_model_failclosed.py @@ -324,6 +324,19 @@ def test_unavailable_pinned_model_never_falls_back_to_appliance(wiring, monkeypa assert not isinstance(wiring.get("fallback"), RemoteGrounder) +def test_empty_pinned_model_is_refused_not_defaulted(wiring, monkeypatch, capsys): + from openadapt_flow.deployment import build_model_grounder + + cfg = GroundingModelConfig(enabled=True, provider="anthropic", model=" ") + assert build_model_grounder(cfg) is None + assert "requires a model" in capsys.readouterr().out + + # Wired through build_replayer: no default model, and no appliance either. + monkeypatch.setenv("OPENADAPT_FLOW_VLM_URL", "https://vlm.internal:8443") + _build(runtime_config=RuntimeSection(grounding_model=cfg), phi_mode=False) + assert wiring.get("fallback") is None + + def test_regulated_profile_keeps_tls_and_loopback_appliances(wiring, monkeypatch): for url in ("https://10.20.30.40:8443", "http://127.0.0.1:8000"): wiring.clear() @@ -359,7 +372,7 @@ def test_regulated_profile_keeps_tls_and_loopback_appliances(wiring, monkeypatch ], ) def test_regulated_transport_rule(url, allowed): - from openadapt_flow.runtime.model_transport import regulated_transport_refusal + from openadapt_flow.model_transport import regulated_transport_refusal assert (regulated_transport_refusal(url) is None) is allowed @@ -471,3 +484,65 @@ def test_in_process_identity_vlm_counts_as_local(monkeypatch, tmp_path): assert Replayer._result_model_calls(result) == 0 assert Replayer._result_local_model_calls(result) == 1 assert rp._egress.entries == [] + + +# -------------------------------------------------------------------------- +# 3, receipt side. The model-call rule is split by placement. +# -------------------------------------------------------------------------- + + +def _receipt_report(*, model_calls, local_model_calls, network): + from tests.test_run_receipt import _report + + base = _report() + classes = list(base.outcome_envelope.evidence_classes) + if model_calls: + classes = sorted({*classes, "model"}) + report = _report( + model_calls=model_calls, + outcome_envelope=base.outcome_envelope.model_copy( + update={"evidence_classes": classes, "external_network_calls": network} + ), + ) + report.local_model_calls = local_model_calls + return report + + +def test_receipt_refuses_off_box_calls_with_no_external_calls(): + from openadapt_flow.model_call_evidence import model_call_evidence_error + from openadapt_flow.receipt import build_receipt + + assert model_call_evidence_error(1, ["model"], "none") is not None + with pytest.raises(Exception, match="observed external network"): + build_receipt( + _receipt_report(model_calls=1, local_model_calls=0, network="none") + ) + receipt = build_receipt( + _receipt_report(model_calls=1, local_model_calls=0, network="observed") + ) + assert receipt.model_calls == 1 and receipt.external_network_calls == "observed" + + +def test_receipt_lets_in_process_calls_say_no_external_calls(): + from openadapt_flow.model_call_evidence import model_call_evidence_error + from openadapt_flow.receipt import build_receipt + + assert model_call_evidence_error(0, [], "none") is None + receipt = build_receipt( + _receipt_report(model_calls=0, local_model_calls=2, network="none") + ) + assert receipt.model_calls == 0 + assert receipt.external_network_calls == "none" + assert "model" not in receipt.evidence_classes + + +def test_counts_from_a_raised_step_never_land_on_the_next_run(tmp_path): + from openadapt_flow.runtime.model_egress import EgressRecorder + + recorder = EgressRecorder() + recorder.count("identity_vlm_calls") + recorder.drain(None) # the step raised: no result to put them on + recorder.bind_run(tmp_path / "run-2") + fresh = StepResult(step_id="s1", intent="x", ok=True) + recorder.drain(fresh) + assert fresh.identity_vlm_calls == 0 From 916e42b5421ccd504243c8ae08cbc44c6c736d92 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 19:47:11 -0500 Subject: [PATCH 16/26] docs: lower the replayer and ir budgets; describe the receipt and empty-model rules Fail-open class: none (docs). --- CAPABILITIES.md | 2 +- packages/flow/docs/design/DECOMPOSITION.md | 4 ++-- packages/flow/openadapt_flow/runtime/replayer.py | 10 +++++----- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 8d87364c85..7a52f240e9 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -350,7 +350,7 @@ improvising or retrying when something is off. | Named sections for every compiled program ("Who: title, first name, last name", "Contact", "Create New Patient"), found without a model from the save, the recorded form structure, the fields and any narration; a person can rename, merge or split them on the review screen | Released | Unit tests; the certified OpenEMR referral bundle and a real recording of it on a local test copy with made-up patients | `openadapt-flow sections`; [SECTIONS.md](packages/flow/docs/SECTIONS.md) | | Encrypt PHI at rest: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, and the run directories of sealed bundles; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md) | | Encryption at rest under a configured or locally generated key (0600): durable checkpoints and attended state by default; with `OPENADAPT_FLOW_AT_REST=strict`, every recording, bundle and run directory too. Each plaintext write is logged on stderr and in a ledger that Desktop shows as a notice | On main | Synthetic (key, opt-out, strict-mode, run-directory and attended-state audit-hook tests) | `openadapt_flow.at_rest`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md#default-opt-out-and-strict-mode) | -| Model calls fail closed: a component with no `MAY_EGRESS` marker counts as sending frames off the box and needs the egress opt-in; a model "yes" from the drift oracle is a hint for the person reviewing the halt, never a pass; identity-VLM calls count as model calls, split by placement (off-box into `model_calls`, in process into `local_model_calls`), so off-box identity crops never report no external calls; every frame sent off the box is first written to a local append-only ledger (`egress-ledger.jsonl` beside the run directory, hashes and sizes only) and is not sent if that write fails; the regulated profile refuses a cleartext appliance or grounding endpoint that is not loopback; a pinned grounding model that can't be wired never falls back to the appliance | On main | Unit tests (`tests/test_model_failclosed.py`, `tests/test_drift_oracle.py`) | `runtime/model_egress.py`, `runtime/model_transport.py`, [ON_PREM_VLM.md](packages/flow/docs/deployment/ON_PREM_VLM.md) | +| Model calls fail closed: a component with no `MAY_EGRESS` marker counts as sending frames off the box and needs the egress opt-in; a model "yes" from the drift oracle is a hint for the person reviewing the halt, never a pass; identity-VLM calls count as model calls, split by placement (off-box into `model_calls`, in process into `local_model_calls`), so off-box identity crops never report no external calls; every frame sent off the box is first written to a local append-only ledger (`egress-ledger.jsonl` beside the run directory, hashes and sizes only) and is not sent if that write fails; a signed record that counts off-box model calls must say external calls were observed, while in-process calls never require it; the regulated profile refuses a cleartext appliance or grounding endpoint that is not loopback; a pinned grounding model that can't be wired, or names no model, never falls back to a default model or to the appliance | On main | Unit tests (`tests/test_model_failclosed.py`, `tests/test_drift_oracle.py`) | `runtime/model_egress.py`, `model_transport.py`, `model_call_evidence.py`, [ON_PREM_VLM.md](packages/flow/docs/deployment/ON_PREM_VLM.md) | | Receipts: one signed record per run, with any outcome (`receipt.json`, a DSSE envelope over an in-toto `record/run/v1` statement): one line per write with its check, strength and what it didn't check; digests, enums, counts and salted commitments only, never screenshots, typed values, URLs or page text; the outcome copied, never upgraded; signer roles from a pinned registry (this computer, customer key, OpenAdapt Cloud countersignature, public log, demo), unknown key, role or schema fails closed; a public card is the same envelope with only allow-listed values opened (`openadapt.public-disclosure/v1`) | Branch ([#2394](https://github.com/OpenAdaptAI/OpenAdapt/pull/2394)) | Unit tests with synthetic runs (stopped runs, tampered report and payload, unknown signer, embedded image refused); 15 shared vectors for the Python, Cloud and web verifiers | `openadapt verify `, `openadapt receipt verify\|view\|publish\|unpublish`; [RECEIPTS.md](packages/flow/docs/RECEIPTS.md); [vectors](packages/types/tests/vectors/record-run-v1/README.md) | | Older signed formats still verify, labelled "older format": offline and public Seals (`local-seal/v1`, `public-seal/v1`), Cloud-signed Execute receipts (`seal-signature/v1`), run summaries (`run-receipt/v2`), write and transaction receipts; Seals countersigned and timestamped | Released | Unit tests, real TSA tokens | `openadapt verify`; `openadapt-flow countersign`, `local-seal`; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md) | | Encrypt a bundle at rest under one encrypted index | Released | Unit tests | `openadapt-flow encrypt` (`seal` is a hidden alias for one release) | diff --git a/packages/flow/docs/design/DECOMPOSITION.md b/packages/flow/docs/design/DECOMPOSITION.md index aa0e4991a6..2533bdfc57 100644 --- a/packages/flow/docs/design/DECOMPOSITION.md +++ b/packages/flow/docs/design/DECOMPOSITION.md @@ -607,10 +607,10 @@ PR #2295 raised `replayer.py`, `ir.py`, `interactive_recorder.py` and `playwrigh | File | Line budget | |---|---:| -| `packages/flow/openadapt_flow/runtime/replayer.py` | 19229 | +| `packages/flow/openadapt_flow/runtime/replayer.py` | 19217 | | `packages/flow/openadapt_flow/__main__.py` | 14331 | | `packages/flow/openadapt_flow/qualification/__init__.py` | 4891 | -| `packages/flow/openadapt_flow/ir.py` | 6830 | +| `packages/flow/openadapt_flow/ir.py` | 6829 | | `packages/desktop/openadapt_desktop/dispatch.py` | 6524 | | `packages/capture/openadapt_capture/recorder.py` | 4836 | | `packages/flow/openadapt_flow/interactive_recorder.py` | 4808 | diff --git a/packages/flow/openadapt_flow/runtime/replayer.py b/packages/flow/openadapt_flow/runtime/replayer.py index 215034bc58..e091bd7424 100644 --- a/packages/flow/openadapt_flow/runtime/replayer.py +++ b/packages/flow/openadapt_flow/runtime/replayer.py @@ -195,11 +195,6 @@ runtime_param_text, runtime_params_for_gui, ) -from openadapt_flow.runtime.model_egress import ( - EgressRecorder, - model_calls_in_process, - model_calls_off_box, -) from openadapt_flow.runtime.dialog_delivery import ( _DIALOG_WAIT_S as _DIALOG_WAIT_S, ) @@ -250,6 +245,11 @@ from openadapt_flow.runtime.known_ids import ( lookalike_class as known_ids_lookalike_class, ) +from openadapt_flow.runtime.model_egress import ( + EgressRecorder, + model_calls_in_process, + model_calls_off_box, +) from openadapt_flow.runtime.program_predicates import ( evaluate_program_predicate, exact_png_size, From d10be252003b209da63722c1ccc94be732d0033f Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 19:47:21 -0500 Subject: [PATCH 17/26] docs: refresh llms-full.txt Fail-open class: none (docs). --- llms-full.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/llms-full.txt b/llms-full.txt index f20c0a7c96..f451d1d0df 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -790,7 +790,7 @@ improvising or retrying when something is off. | Named sections for every compiled program ("Who: title, first name, last name", "Contact", "Create New Patient"), found without a model from the save, the recorded form structure, the fields and any narration; a person can rename, merge or split them on the review screen | Released | Unit tests; the certified OpenEMR referral bundle and a real recording of it on a local test copy with made-up patients | `openadapt-flow sections`; [SECTIONS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SECTIONS.md) | | Encrypt PHI at rest: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, and the run directories of sealed bundles; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md) | | Encryption at rest under a configured or locally generated key (0600): durable checkpoints and attended state by default; with `OPENADAPT_FLOW_AT_REST=strict`, every recording, bundle and run directory too. Each plaintext write is logged on stderr and in a ledger that Desktop shows as a notice | On main | Synthetic (key, opt-out, strict-mode, run-directory and attended-state audit-hook tests) | `openadapt_flow.at_rest`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md#default-opt-out-and-strict-mode) | -| Model calls fail closed: a component with no `MAY_EGRESS` marker counts as sending frames off the box and needs the egress opt-in; a model "yes" from the drift oracle is a hint for the person reviewing the halt, never a pass; identity-VLM calls count as model calls, split by placement (off-box into `model_calls`, in process into `local_model_calls`), so off-box identity crops never report no external calls; every frame sent off the box is first written to a local append-only ledger (`egress-ledger.jsonl` beside the run directory, hashes and sizes only) and is not sent if that write fails; the regulated profile refuses a cleartext appliance or grounding endpoint that is not loopback; a pinned grounding model that can't be wired never falls back to the appliance | On main | Unit tests (`tests/test_model_failclosed.py`, `tests/test_drift_oracle.py`) | `runtime/model_egress.py`, `runtime/model_transport.py`, [ON_PREM_VLM.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/deployment/ON_PREM_VLM.md) | +| Model calls fail closed: a component with no `MAY_EGRESS` marker counts as sending frames off the box and needs the egress opt-in; a model "yes" from the drift oracle is a hint for the person reviewing the halt, never a pass; identity-VLM calls count as model calls, split by placement (off-box into `model_calls`, in process into `local_model_calls`), so off-box identity crops never report no external calls; every frame sent off the box is first written to a local append-only ledger (`egress-ledger.jsonl` beside the run directory, hashes and sizes only) and is not sent if that write fails; a signed record that counts off-box model calls must say external calls were observed, while in-process calls never require it; the regulated profile refuses a cleartext appliance or grounding endpoint that is not loopback; a pinned grounding model that can't be wired, or names no model, never falls back to a default model or to the appliance | On main | Unit tests (`tests/test_model_failclosed.py`, `tests/test_drift_oracle.py`) | `runtime/model_egress.py`, `model_transport.py`, `model_call_evidence.py`, [ON_PREM_VLM.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/deployment/ON_PREM_VLM.md) | | Receipts: one signed record per run, with any outcome (`receipt.json`, a DSSE envelope over an in-toto `record/run/v1` statement): one line per write with its check, strength and what it didn't check; digests, enums, counts and salted commitments only, never screenshots, typed values, URLs or page text; the outcome copied, never upgraded; signer roles from a pinned registry (this computer, customer key, OpenAdapt Cloud countersignature, public log, demo), unknown key, role or schema fails closed; a public card is the same envelope with only allow-listed values opened (`openadapt.public-disclosure/v1`) | Branch ([#2394](https://github.com/OpenAdaptAI/OpenAdapt/pull/2394)) | Unit tests with synthetic runs (stopped runs, tampered report and payload, unknown signer, embedded image refused); 15 shared vectors for the Python, Cloud and web verifiers | `openadapt verify `, `openadapt receipt verify\|view\|publish\|unpublish`; [RECEIPTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/RECEIPTS.md); [vectors](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/types/tests/vectors/record-run-v1/README.md) | | Older signed formats still verify, labelled "older format": offline and public Seals (`local-seal/v1`, `public-seal/v1`), Cloud-signed Execute receipts (`seal-signature/v1`), run summaries (`run-receipt/v2`), write and transaction receipts; Seals countersigned and timestamped | Released | Unit tests, real TSA tokens | `openadapt verify`; `openadapt-flow countersign`, `local-seal`; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md) | | Encrypt a bundle at rest under one encrypted index | Released | Unit tests | `openadapt-flow encrypt` (`seal` is a hidden alias for one release) | From 94cf6813958483dd7fa73534b7783d7fe71c406e Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 20:27:33 -0500 Subject: [PATCH 18/26] fix(flow): check a built model grounder at the URL its client sends to Fail-open class: transport check bypass. The regulated and PHI checks read the configured base_url, so an Anthropic client taking ANTHROPIC_BASE_URL from the environment could send cleartext off the box. Found by the Gemini review. --- packages/flow/openadapt_flow/deployment.py | 34 ++++++++++++------- .../flow/openadapt_flow/model_transport.py | 15 ++++++++ 2 files changed, 36 insertions(+), 13 deletions(-) diff --git a/packages/flow/openadapt_flow/deployment.py b/packages/flow/openadapt_flow/deployment.py index c2ba5889ba..427542a209 100644 --- a/packages/flow/openadapt_flow/deployment.py +++ b/packages/flow/openadapt_flow/deployment.py @@ -1871,24 +1871,32 @@ def build_replayer( if not ok: print(f"PHI mode: {reason}; replaying FULLY LOCAL.") wire = False - if wire and regulated and (grounding_cfg.base_url or "").strip(): + if wire: + model_grounder = build_model_grounder(grounding_cfg) + if model_grounder is not None and (regulated or phi_on): from openadapt_flow.model_transport import ( + built_endpoint, regulated_transport_refusal, ) - refusal = regulated_transport_refusal(grounding_cfg.base_url) - if refusal is not None: - print(f"Regulated profile: {refusal}; replaying FULLY LOCAL.") - wire = False - if wire: - model_grounder = build_model_grounder(grounding_cfg) - if model_grounder is not None: - print( - "Model grounder wired: " - f"{type(model_grounder).__name__} " - f"(provider={grounding_cfg.provider}). WARNING: " - "screenshots WILL leave the box for this run." + # Check the URL the built client sends to, not the config. + sent_to = built_endpoint(model_grounder) + refusal = regulated_transport_refusal(sent_to) if regulated else None + if refusal is None and phi_on: + ok, reason = phi_grounding_endpoint_allowed( + _host_of(sent_to), allowlist=allowlist, attested=attested ) + refusal = None if ok else reason + if refusal is not None: + print(f"Model grounder refused: {refusal}; replaying FULLY LOCAL.") + model_grounder = None + if model_grounder is not None: + print( + "Model grounder wired: " + f"{type(model_grounder).__name__} " + f"(provider={grounding_cfg.provider}). WARNING: " + "screenshots WILL leave the box for this run." + ) # The configured model grounder takes precedence as the VLM fallback; the # on-prem appliance grounder is used only when no model is pinned. A pinned diff --git a/packages/flow/openadapt_flow/model_transport.py b/packages/flow/openadapt_flow/model_transport.py index bbb72be458..d0229dff70 100644 --- a/packages/flow/openadapt_flow/model_transport.py +++ b/packages/flow/openadapt_flow/model_transport.py @@ -39,3 +39,18 @@ def regulated_transport_refusal(url: str) -> Optional[str]: if parts.scheme == "http": return f"the model endpoint {host} is cleartext http off this machine" return f"the model endpoint scheme {parts.scheme!r} is not https" + + +def built_endpoint(component: object) -> str: + """The URL a built model client actually sends to, or ``""`` if unknown. + + Reads the constructed object, not the configuration, so a URL the client + library takes from its own environment (``ANTHROPIC_BASE_URL``) is seen. + """ + + for holder in (component, getattr(component, "_client", None)): + for name in ("_url", "_base_url", "base_url"): + url = getattr(holder, name, None) + if url: + return str(url) + return "" From 5ed33badd4ebc2075d00659389e3782651570c95 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 20:27:33 -0500 Subject: [PATCH 19/26] fix(flow): no ledger bound means no off-box model call Fail-open class: unledgered egress. A replayer driven outside run() sent frames with no ledger line; now it sends only when OPENADAPT_FLOW_EGRESS_LEDGER names a ledger. Found by the Gemini review. --- .../openadapt_flow/runtime/model_egress.py | 19 +++++++----- packages/flow/tests/test_drift_oracle.py | 1 + packages/flow/tests/test_model_failclosed.py | 30 +++++++++++++++++++ 3 files changed, 43 insertions(+), 7 deletions(-) diff --git a/packages/flow/openadapt_flow/runtime/model_egress.py b/packages/flow/openadapt_flow/runtime/model_egress.py index 10f00330ec..142e6ce989 100644 --- a/packages/flow/openadapt_flow/runtime/model_egress.py +++ b/packages/flow/openadapt_flow/runtime/model_egress.py @@ -77,8 +77,7 @@ def __init__(self) -> None: self.ledger_path: Optional[Path] = None self.run_ref: Optional[str] = None self.step_id: Optional[str] = None - #: Every ledger line this recorder made, also when no run is bound - #: (a replayer driven outside ``run``, as unit tests do). + #: Every ledger line this recorder wrote. self.entries: list[dict[str, Any]] = [] self._pending = { "identity_vlm_calls": 0, @@ -112,11 +111,17 @@ def admit(self, kind: str, component: Any, *frames: bytes) -> bool: if isinstance(f, (bytes, bytearray)) ], } - if self.ledger_path is not None: - try: - append_ledger_line(self.ledger_path, entry) - except OSError: - return False + # No run bound (a replayer driven outside ``run``): only the ledger + # ``OPENADAPT_FLOW_EGRESS_LEDGER`` names will do; with none, don't send. + path = self.ledger_path + if path is None and os.environ.get(LEDGER_ENV, "").strip(): + path = Path(os.environ[LEDGER_ENV].strip()) + if path is None: + return False + try: + append_ledger_line(path, entry) + except OSError: + return False self.entries.append(entry) return True diff --git a/packages/flow/tests/test_drift_oracle.py b/packages/flow/tests/test_drift_oracle.py index ed6f621177..9a2e1aef8d 100644 --- a/packages/flow/tests/test_drift_oracle.py +++ b/packages/flow/tests/test_drift_oracle.py @@ -129,6 +129,7 @@ def _check(vision, verifier, pc, tmp_path, step=None): allow_model_grounding=True, poll_interval_s=0.0, ) + rp._egress.bind_run(tmp_path / "run") # off-box frames need a ledger step = step if step is not None else _step(pc) result = StepResult(step_id=step.id, intent=step.intent, ok=False) ok, _frame, failed = rp._check_postconditions(step, _png(), tmp_path, {}, result) diff --git a/packages/flow/tests/test_model_failclosed.py b/packages/flow/tests/test_model_failclosed.py index 0c4ab50706..4a59803769 100644 --- a/packages/flow/tests/test_model_failclosed.py +++ b/packages/flow/tests/test_model_failclosed.py @@ -177,6 +177,7 @@ def _identity_step() -> tuple[Step, Workflow, Resolution]: def test_identity_vlm_call_counts_as_model_call(monkeypatch, tmp_path, verdict): vlm = _OffBoxIdentityVLM(verdict) rp = Replayer(FakeBackend(), identity_vlm=vlm, allow_model_grounding=True) + rp._egress.bind_run(tmp_path / "run") crop = _crop_png() monkeypatch.setattr(rp, "_identifier_crops", lambda *a, **k: (crop, crop)) step, workflow, res = _identity_step() @@ -191,6 +192,7 @@ def test_off_box_identity_crops_never_report_no_external_calls(monkeypatch, tmp_ vlm = _OffBoxIdentityVLM("different") rp = Replayer(FakeBackend(), identity_vlm=vlm, allow_model_grounding=True) + rp._egress.bind_run(tmp_path / "run") crop = _crop_png() monkeypatch.setattr(rp, "_identifier_crops", lambda *a, **k: (crop, crop)) step, workflow, res = _identity_step() @@ -546,3 +548,31 @@ def test_counts_from_a_raised_step_never_land_on_the_next_run(tmp_path): fresh = StepResult(step_id="s1", intent="x", ok=True) recorder.drain(fresh) assert fresh.identity_vlm_calls == 0 + + +def test_no_bound_ledger_means_no_off_box_call(monkeypatch): + from openadapt_flow.runtime.model_egress import LEDGER_ENV, EgressRecorder + + monkeypatch.delenv(LEDGER_ENV, raising=False) + recorder = EgressRecorder() + grounder = _OffBoxGrounder() + wrapped = recorder.wrap("grounder", grounder) + assert wrapped.locate(b"frame", "click Save") is None + assert grounder.calls == 0 and recorder.entries == [] + + +def test_model_grounder_checked_at_the_url_its_client_uses(wiring, monkeypatch): + # The Anthropic SDK takes ANTHROPIC_BASE_URL from the environment; the + # regulated check must see that URL, not the empty configured base_url. + pytest.importorskip("anthropic") + monkeypatch.setenv("ANTHROPIC_BASE_URL", "http://10.20.30.40:8080") + monkeypatch.setenv("ANTHROPIC_API_KEY", "test-not-a-key") + monkeypatch.setenv("OPENADAPT_FLOW_SEND_UNSCRUBBED", "wiring unit test") + runtime = RuntimeSection( + profile="regulated", + grounding_model=GroundingModelConfig( + enabled=True, provider="anthropic", model="pinned-m" + ), + ) + _build(runtime_config=runtime, phi_mode=False) + assert wiring.get("fallback") is None From a57af170753c6e395a27152211b7be4653859166 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 20:27:41 -0500 Subject: [PATCH 20/26] docs(flow): ledger refusal when unbound; transport checked at the client URL Fail-open class: none (docs). --- packages/flow/docs/deployment/ON_PREM_VLM.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/flow/docs/deployment/ON_PREM_VLM.md b/packages/flow/docs/deployment/ON_PREM_VLM.md index 3b2c8922f4..11a5eac05a 100644 --- a/packages/flow/docs/deployment/ON_PREM_VLM.md +++ b/packages/flow/docs/deployment/ON_PREM_VLM.md @@ -247,15 +247,17 @@ through. Scrubbing here would **defeat the safety check**, not add safety. boundary. Run the appliance HTTPS-only on the LAN, gate it with the bearer token (`VLM_SERVICE_TOKEN`), and keep it inside the same network zone as the runners. Under the `regulated` execution profile the runner enforces the - transport: it wires an appliance or `grounding_model.base_url` only over - `https`, or over `http` to loopback, and prints why it refused any other URL. + transport: it wires an appliance or a grounding model only over `https`, or + over `http` to loopback, and prints why it refused any other URL. It checks + the URL the built client sends to, including one the client library reads + from its own environment. 4. **Every frame sent off the box is on a local ledger.** Before each off-box call the runner appends one line to `egress-ledger.jsonl` beside the run directory (or the file `OPENADAPT_FLOW_EGRESS_LEDGER` names). The line holds the frame's SHA-256 and size, the component, the destination host, the run, the step and the time, and never pixels or text. The file is append-only, - mode `0600` and fsynced per line. If the line can't be written, the frame is - not sent and the component gives its fail-safe answer, so the step halts. + mode `0600` and fsynced per line. If the line can't be written, or no + ledger is set (a replayer driven outside a run), the frame is not sent and the component gives its fail-safe answer, so the step halts. Halted runs are on the ledger too, because each line is written when its frame is sent. 5. **No fallback to another model.** When `grounding_model` is pinned and From e565505ac4a489997f4e725f4afaeb8cd9951cad Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 20:31:17 -0500 Subject: [PATCH 21/26] docs: mark the fail-closed model row as on a branch (#2497) Fail-open class: none (docs). --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 7a52f240e9..dbcc13ae81 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -350,7 +350,7 @@ improvising or retrying when something is off. | Named sections for every compiled program ("Who: title, first name, last name", "Contact", "Create New Patient"), found without a model from the save, the recorded form structure, the fields and any narration; a person can rename, merge or split them on the review screen | Released | Unit tests; the certified OpenEMR referral bundle and a real recording of it on a local test copy with made-up patients | `openadapt-flow sections`; [SECTIONS.md](packages/flow/docs/SECTIONS.md) | | Encrypt PHI at rest: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, and the run directories of sealed bundles; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md) | | Encryption at rest under a configured or locally generated key (0600): durable checkpoints and attended state by default; with `OPENADAPT_FLOW_AT_REST=strict`, every recording, bundle and run directory too. Each plaintext write is logged on stderr and in a ledger that Desktop shows as a notice | On main | Synthetic (key, opt-out, strict-mode, run-directory and attended-state audit-hook tests) | `openadapt_flow.at_rest`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md#default-opt-out-and-strict-mode) | -| Model calls fail closed: a component with no `MAY_EGRESS` marker counts as sending frames off the box and needs the egress opt-in; a model "yes" from the drift oracle is a hint for the person reviewing the halt, never a pass; identity-VLM calls count as model calls, split by placement (off-box into `model_calls`, in process into `local_model_calls`), so off-box identity crops never report no external calls; every frame sent off the box is first written to a local append-only ledger (`egress-ledger.jsonl` beside the run directory, hashes and sizes only) and is not sent if that write fails; a signed record that counts off-box model calls must say external calls were observed, while in-process calls never require it; the regulated profile refuses a cleartext appliance or grounding endpoint that is not loopback; a pinned grounding model that can't be wired, or names no model, never falls back to a default model or to the appliance | On main | Unit tests (`tests/test_model_failclosed.py`, `tests/test_drift_oracle.py`) | `runtime/model_egress.py`, `model_transport.py`, `model_call_evidence.py`, [ON_PREM_VLM.md](packages/flow/docs/deployment/ON_PREM_VLM.md) | +| Model calls fail closed: a component with no `MAY_EGRESS` marker counts as sending frames off the box and needs the egress opt-in; a model "yes" from the drift oracle is a hint for the person reviewing the halt, never a pass; identity-VLM calls count as model calls, split by placement (off-box into `model_calls`, in process into `local_model_calls`), so off-box identity crops never report no external calls; every frame sent off the box is first written to a local append-only ledger (`egress-ledger.jsonl` beside the run directory, hashes and sizes only) and is not sent if that write fails; a signed record that counts off-box model calls must say external calls were observed, while in-process calls never require it; the regulated profile refuses a cleartext appliance or grounding endpoint that is not loopback; a pinned grounding model that can't be wired, or names no model, never falls back to a default model or to the appliance | Branch ([#2497](https://github.com/OpenAdaptAI/OpenAdapt/pull/2497)) | Unit tests (`tests/test_model_failclosed.py`, `tests/test_drift_oracle.py`) | `runtime/model_egress.py`, `model_transport.py`, `model_call_evidence.py`, [ON_PREM_VLM.md](packages/flow/docs/deployment/ON_PREM_VLM.md) | | Receipts: one signed record per run, with any outcome (`receipt.json`, a DSSE envelope over an in-toto `record/run/v1` statement): one line per write with its check, strength and what it didn't check; digests, enums, counts and salted commitments only, never screenshots, typed values, URLs or page text; the outcome copied, never upgraded; signer roles from a pinned registry (this computer, customer key, OpenAdapt Cloud countersignature, public log, demo), unknown key, role or schema fails closed; a public card is the same envelope with only allow-listed values opened (`openadapt.public-disclosure/v1`) | Branch ([#2394](https://github.com/OpenAdaptAI/OpenAdapt/pull/2394)) | Unit tests with synthetic runs (stopped runs, tampered report and payload, unknown signer, embedded image refused); 15 shared vectors for the Python, Cloud and web verifiers | `openadapt verify `, `openadapt receipt verify\|view\|publish\|unpublish`; [RECEIPTS.md](packages/flow/docs/RECEIPTS.md); [vectors](packages/types/tests/vectors/record-run-v1/README.md) | | Older signed formats still verify, labelled "older format": offline and public Seals (`local-seal/v1`, `public-seal/v1`), Cloud-signed Execute receipts (`seal-signature/v1`), run summaries (`run-receipt/v2`), write and transaction receipts; Seals countersigned and timestamped | Released | Unit tests, real TSA tokens | `openadapt verify`; `openadapt-flow countersign`, `local-seal`; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md) | | Encrypt a bundle at rest under one encrypted index | Released | Unit tests | `openadapt-flow encrypt` (`seal` is a hidden alias for one release) | diff --git a/llms-full.txt b/llms-full.txt index f451d1d0df..74f142d211 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -790,7 +790,7 @@ improvising or retrying when something is off. | Named sections for every compiled program ("Who: title, first name, last name", "Contact", "Create New Patient"), found without a model from the save, the recorded form structure, the fields and any narration; a person can rename, merge or split them on the review screen | Released | Unit tests; the certified OpenEMR referral bundle and a real recording of it on a local test copy with made-up patients | `openadapt-flow sections`; [SECTIONS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SECTIONS.md) | | Encrypt PHI at rest: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, and the run directories of sealed bundles; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md) | | Encryption at rest under a configured or locally generated key (0600): durable checkpoints and attended state by default; with `OPENADAPT_FLOW_AT_REST=strict`, every recording, bundle and run directory too. Each plaintext write is logged on stderr and in a ledger that Desktop shows as a notice | On main | Synthetic (key, opt-out, strict-mode, run-directory and attended-state audit-hook tests) | `openadapt_flow.at_rest`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md#default-opt-out-and-strict-mode) | -| Model calls fail closed: a component with no `MAY_EGRESS` marker counts as sending frames off the box and needs the egress opt-in; a model "yes" from the drift oracle is a hint for the person reviewing the halt, never a pass; identity-VLM calls count as model calls, split by placement (off-box into `model_calls`, in process into `local_model_calls`), so off-box identity crops never report no external calls; every frame sent off the box is first written to a local append-only ledger (`egress-ledger.jsonl` beside the run directory, hashes and sizes only) and is not sent if that write fails; a signed record that counts off-box model calls must say external calls were observed, while in-process calls never require it; the regulated profile refuses a cleartext appliance or grounding endpoint that is not loopback; a pinned grounding model that can't be wired, or names no model, never falls back to a default model or to the appliance | On main | Unit tests (`tests/test_model_failclosed.py`, `tests/test_drift_oracle.py`) | `runtime/model_egress.py`, `model_transport.py`, `model_call_evidence.py`, [ON_PREM_VLM.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/deployment/ON_PREM_VLM.md) | +| Model calls fail closed: a component with no `MAY_EGRESS` marker counts as sending frames off the box and needs the egress opt-in; a model "yes" from the drift oracle is a hint for the person reviewing the halt, never a pass; identity-VLM calls count as model calls, split by placement (off-box into `model_calls`, in process into `local_model_calls`), so off-box identity crops never report no external calls; every frame sent off the box is first written to a local append-only ledger (`egress-ledger.jsonl` beside the run directory, hashes and sizes only) and is not sent if that write fails; a signed record that counts off-box model calls must say external calls were observed, while in-process calls never require it; the regulated profile refuses a cleartext appliance or grounding endpoint that is not loopback; a pinned grounding model that can't be wired, or names no model, never falls back to a default model or to the appliance | Branch ([#2497](https://github.com/OpenAdaptAI/OpenAdapt/pull/2497)) | Unit tests (`tests/test_model_failclosed.py`, `tests/test_drift_oracle.py`) | `runtime/model_egress.py`, `model_transport.py`, `model_call_evidence.py`, [ON_PREM_VLM.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/deployment/ON_PREM_VLM.md) | | Receipts: one signed record per run, with any outcome (`receipt.json`, a DSSE envelope over an in-toto `record/run/v1` statement): one line per write with its check, strength and what it didn't check; digests, enums, counts and salted commitments only, never screenshots, typed values, URLs or page text; the outcome copied, never upgraded; signer roles from a pinned registry (this computer, customer key, OpenAdapt Cloud countersignature, public log, demo), unknown key, role or schema fails closed; a public card is the same envelope with only allow-listed values opened (`openadapt.public-disclosure/v1`) | Branch ([#2394](https://github.com/OpenAdaptAI/OpenAdapt/pull/2394)) | Unit tests with synthetic runs (stopped runs, tampered report and payload, unknown signer, embedded image refused); 15 shared vectors for the Python, Cloud and web verifiers | `openadapt verify `, `openadapt receipt verify\|view\|publish\|unpublish`; [RECEIPTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/RECEIPTS.md); [vectors](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/types/tests/vectors/record-run-v1/README.md) | | Older signed formats still verify, labelled "older format": offline and public Seals (`local-seal/v1`, `public-seal/v1`), Cloud-signed Execute receipts (`seal-signature/v1`), run summaries (`run-receipt/v2`), write and transaction receipts; Seals countersigned and timestamped | Released | Unit tests, real TSA tokens | `openadapt verify`; `openadapt-flow countersign`, `local-seal`; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md) | | Encrypt a bundle at rest under one encrypted index | Released | Unit tests | `openadapt-flow encrypt` (`seal` is a hidden alias for one release) | From 45a0b3a8dbf9fb8a7837e34da1ac4ac19158ab79 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 21:22:43 -0500 Subject: [PATCH 22/26] fix(flow): open the egress ledger as a binary descriptor Fail-open class: none (correctness). On Windows a plain os.open wrote CRLF into the ledger; the binary-descriptor contract test caught it in CI. --- packages/flow/openadapt_flow/runtime/model_egress.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/flow/openadapt_flow/runtime/model_egress.py b/packages/flow/openadapt_flow/runtime/model_egress.py index 142e6ce989..82a4c60d9b 100644 --- a/packages/flow/openadapt_flow/runtime/model_egress.py +++ b/packages/flow/openadapt_flow/runtime/model_egress.py @@ -45,7 +45,10 @@ def append_ledger_line(path: Path, entry: dict[str, Any]) -> None: path.parent.mkdir(parents=True, exist_ok=True) data = (json.dumps(entry, sort_keys=True, separators=(",", ":")) + "\n").encode() - fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600) + from openadapt_flow.private_file import open_binary + + # Binary: on Windows a plain os.open would write CRLF into the ledger. + fd = open_binary(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600) try: while data: written = os.write(fd, data) From fbbea65afa13f349e4f123974a845da2d5023324 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 21:34:17 -0500 Subject: [PATCH 23/26] test(flow): mark the resolver fuzz grounder as in process Fail-open class: none (test). An unmarked grounder now counts as egress, so the in-process fuzz stub declares MAY_EGRESS = False. --- packages/flow/tests/test_resolver_fuzz.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/flow/tests/test_resolver_fuzz.py b/packages/flow/tests/test_resolver_fuzz.py index 88385fc40d..69bdcf1e05 100644 --- a/packages/flow/tests/test_resolver_fuzz.py +++ b/packages/flow/tests/test_resolver_fuzz.py @@ -128,6 +128,8 @@ def find_text( class FakeGrounder: + MAY_EGRESS = False # in process; an unmarked grounder counts as egress + def __init__(self, result=None): self.result = result From 36abd6ac60e72c2181c7c03c852ec62005999f95 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 23:44:37 -0500 Subject: [PATCH 24/26] fix(flow): count each model send, record the real host, lazy egress recorder - Replayer._egress is created on first use when __init__ did not run, and the model components already set are wrapped then, so a replayer built with __new__ neither crashes nor sends an unledgered frame. - AnthropicGrounder turns off the SDK's retries (max_retries=0, also on an injected client), so one ledger line and one counted call is one send. - The egress ledger reads the destination with built_endpoint, so pinned Anthropic (httpx.URL base) and OpenAI-compatible (_url) hosts are named. - The local identity fake in test_local_vlm_gold_crop declares MAY_EGRESS = False. --- packages/flow/openadapt_flow/deployment.py | 2 +- .../flow/openadapt_flow/runtime/grounder.py | 8 +- .../openadapt_flow/runtime/model_egress.py | 26 +++--- .../flow/openadapt_flow/runtime/replayer.py | 25 +++++- .../flow/tests/test_local_vlm_gold_crop.py | 2 + packages/flow/tests/test_model_failclosed.py | 81 +++++++++++++++++++ 6 files changed, 132 insertions(+), 12 deletions(-) diff --git a/packages/flow/openadapt_flow/deployment.py b/packages/flow/openadapt_flow/deployment.py index d60594efa1..f6e91daa50 100644 --- a/packages/flow/openadapt_flow/deployment.py +++ b/packages/flow/openadapt_flow/deployment.py @@ -1699,7 +1699,7 @@ def build_model_grounder(cfg: GroundingModelConfig) -> Optional[Any]: if api_key: import anthropic - client = anthropic.Anthropic(api_key=api_key) + client = anthropic.Anthropic(api_key=api_key, max_retries=0) return AnthropicGrounder(model=model, client=client) except ImportError: print( diff --git a/packages/flow/openadapt_flow/runtime/grounder.py b/packages/flow/openadapt_flow/runtime/grounder.py index f9a6769e83..6a3d4901eb 100644 --- a/packages/flow/openadapt_flow/runtime/grounder.py +++ b/packages/flow/openadapt_flow/runtime/grounder.py @@ -601,7 +601,13 @@ def __init__(self, model: str = _DEFAULT_MODEL, client: object = None) -> None: "Install it with: pip install 'openadapt-flow[grounder]'" ) from exc self._model = model - self._client = client if client is not None else anthropic.Anthropic() + # One locate is one send: the SDK's own retries (two by default) would + # resend the frame behind one egress-ledger line and one counted call. + if client is None: + client = anthropic.Anthropic(max_retries=0) + elif callable(getattr(client, "with_options", None)): + client = client.with_options(max_retries=0) + self._client = client self._outbound = _OutboundScreen(None) def locate( diff --git a/packages/flow/openadapt_flow/runtime/model_egress.py b/packages/flow/openadapt_flow/runtime/model_egress.py index 82a4c60d9b..cc501bd9da 100644 --- a/packages/flow/openadapt_flow/runtime/model_egress.py +++ b/packages/flow/openadapt_flow/runtime/model_egress.py @@ -61,15 +61,23 @@ def append_ledger_line(path: Path, entry: dict[str, Any]) -> None: def _destination(component: Any) -> str: - """The host a component sends to, or ``"unknown"``.""" - - for holder in (component, getattr(component, "_client", None)): - for name in ("base_url", "_base_url"): - url = getattr(holder, name, None) - if isinstance(url, str) and url: - host = urlsplit(url if "//" in url else f"//{url}").hostname - if host: - return host + """The host a component sends to, or ``"unknown"``. + + Reads the built client the same way the regulated-transport check does + (:func:`openadapt_flow.model_transport.built_endpoint`), so a ``_url`` or an + ``httpx.URL`` base is recorded too. + """ + + from openadapt_flow.model_transport import built_endpoint + + url = built_endpoint(component) + if url: + try: + host = urlsplit(url if "//" in url else f"//{url}").hostname + except ValueError: + host = None + if host: + return host return "unknown" diff --git a/packages/flow/openadapt_flow/runtime/replayer.py b/packages/flow/openadapt_flow/runtime/replayer.py index e091bd7424..b779de16b2 100644 --- a/packages/flow/openadapt_flow/runtime/replayer.py +++ b/packages/flow/openadapt_flow/runtime/replayer.py @@ -469,6 +469,29 @@ class Replayer(QualificationFaultInjection, AssetsHealingAndEvidence): None uses ``$OPENADAPT_JIT_KEY_DIR`` or ``~/.openadapt/jit``. """ + @property + def _egress(self) -> EgressRecorder: + """The egress recorder, created on first use when ``__init__`` didn't run. + + A replayer built without ``__init__`` (``Replayer.__new__``, a stubbed + constructor) never wrapped its model components. Here they are wrapped + before the recorder is returned, so a frame still can't leave the box + unledgered, and an off-box call made outside ``run`` is refused (an + unbound recorder admits nothing unless ``OPENADAPT_FLOW_EGRESS_LEDGER`` + names a ledger). + """ + + recorder = self.__dict__.get("_egress_recorder") + if recorder is None: + recorder = EgressRecorder() + self.__dict__["_egress_recorder"] = recorder + for kind in ("grounder", "identity_vlm", "state_verifier"): + component = self.__dict__.get(kind) + if component is not None: + self.__dict__[kind] = recorder.wrap(kind, component) + return recorder + + # Display-scale state (see __init__); class defaults keep partially # constructed replayers, as some tests build them, on recorded geometry. _render_scale_attempted: bool = False @@ -614,7 +637,7 @@ def __init__( # facade exposing find_template/ocr/wait_settled/...). self.vision: Any = vision # Frames sent off the box are ledgered and counted by placement. - self._egress = EgressRecorder() + self.__dict__["_egress_recorder"] = EgressRecorder() self.grounder = self._egress.wrap("grounder", grounder) # Whether the deterministic structural ACTION rung (top of the ladder) # may run. True (default) = product behavior: on a structure-bearing diff --git a/packages/flow/tests/test_local_vlm_gold_crop.py b/packages/flow/tests/test_local_vlm_gold_crop.py index 8e33c0661a..57a61ae3d6 100644 --- a/packages/flow/tests/test_local_vlm_gold_crop.py +++ b/packages/flow/tests/test_local_vlm_gold_crop.py @@ -270,6 +270,8 @@ def compare(self, crop_a: bytes, crop_b: bytes) -> IdentityVerdict: class _FakeLocalIdentity: + MAY_EGRESS = False # in process: no frame leaves the box + def __init__(self, answer: str): self.answer = answer diff --git a/packages/flow/tests/test_model_failclosed.py b/packages/flow/tests/test_model_failclosed.py index 4a59803769..bc7536b14e 100644 --- a/packages/flow/tests/test_model_failclosed.py +++ b/packages/flow/tests/test_model_failclosed.py @@ -576,3 +576,84 @@ def test_model_grounder_checked_at_the_url_its_client_uses(wiring, monkeypatch): ) _build(runtime_config=runtime, phi_mode=False) assert wiring.get("fallback") is None + + +def test_each_model_send_is_one_ledgered_counted_call(tmp_path, monkeypatch): + # The Anthropic SDK retries twice by default, so one ledgered, counted call + # could send the same frame three times. The grounder turns retries off: + # three sends must be three ledger lines and three counted calls. + anthropic = pytest.importorskip("anthropic") + import httpx + + from openadapt_flow.runtime.grounder import AnthropicGrounder + from openadapt_flow.runtime.model_egress import LEDGER_ENV, EgressRecorder + + sends = [] + + def overloaded(request): + sends.append(request) + return httpx.Response( + 529, json={"type": "error", "error": {"type": "overloaded_error"}} + ) + + client = anthropic.Anthropic( + api_key="test-not-a-key", + base_url="https://model.example.test", + http_client=httpx.Client(transport=httpx.MockTransport(overloaded)), + ) + assert client.max_retries > 0 # the SDK default this guards against + monkeypatch.setenv("OPENADAPT_FLOW_SEND_UNSCRUBBED", "retry count unit test") + ledger = tmp_path / "egress-ledger.jsonl" + monkeypatch.setenv(LEDGER_ENV, str(ledger)) + recorder = EgressRecorder() + grounder = recorder.wrap( + "grounder", AnthropicGrounder(model="pinned-m", client=client) + ) + for _ in range(3): + with pytest.raises(anthropic.APIStatusError): + grounder.locate(_png(), "click Save") + assert len(sends) == 3 + result = StepResult(step_id="s1", intent="click Save", ok=False) + recorder.drain(result) + assert result.grounder_calls == 3 + lines = _ledger_lines(ledger) + assert len(lines) == 3 + assert {line["destination"] for line in lines} == {"model.example.test"} + + +def test_ledger_names_the_openai_compatible_host(tmp_path, monkeypatch): + from openadapt_flow.runtime.grounder import OpenAICompatibleGrounder + from openadapt_flow.runtime.model_egress import LEDGER_ENV, EgressRecorder + + class _Refusing: + def post(self, url, **kwargs): + return SimpleNamespace(status_code=503) + + monkeypatch.setenv("OPENADAPT_FLOW_SEND_UNSCRUBBED", "host unit test") + ledger = tmp_path / "egress-ledger.jsonl" + monkeypatch.setenv(LEDGER_ENV, str(ledger)) + grounder = EgressRecorder().wrap( + "grounder", + OpenAICompatibleGrounder( + base_url="https://vlm.example.test/v1", model="m", client=_Refusing() + ), + ) + assert grounder.locate(_png(), "click Save") is None + (line,) = _ledger_lines(ledger) + assert line["destination"] == "vlm.example.test" + + +def test_replayer_built_without_init_still_ledgers_off_box_calls(monkeypatch): + # A Replayer made with __new__ gets its recorder on first use, and the + # components already set are wrapped, so nothing is sent unrecorded. + from openadapt_flow.runtime.model_egress import LEDGER_ENV + + monkeypatch.delenv(LEDGER_ENV, raising=False) + rp = Replayer.__new__(Replayer) + inner = _OffBoxGrounder() + rp.grounder = inner + recorder = rp._egress + assert rp._egress is recorder + assert rp.grounder is not inner + assert rp.grounder.locate(b"frame", "click Save") is None # no ledger bound + assert inner.calls == 0 From 4b3fd41dd60c449dcc16383129e8e8009b7a43fc Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 23:46:56 -0500 Subject: [PATCH 25/26] fix(flow): keep the fail-closed row as a capabilities/ row file Main now assembles CAPABILITIES.md from capabilities/. The merged page kept this PR's row, but the next refresh would drop it, so the row is a row file and the two generated pages match main. Also: the lazy recorder's docstring says it wraps only the components set at first access, and the Anthropic client is re-optioned only when it is an SDK client. --- CAPABILITIES.md | 1 - ...105-model-calls-fail-closed-a-component-with-no.md | 1 + llms-full.txt | 1 - packages/flow/openadapt_flow/runtime/grounder.py | 8 ++++++-- packages/flow/openadapt_flow/runtime/replayer.py | 11 +++++------ 5 files changed, 12 insertions(+), 10 deletions(-) create mode 100644 capabilities/11-recording-privacy-and-proof/0105-model-calls-fail-closed-a-component-with-no.md diff --git a/CAPABILITIES.md b/CAPABILITIES.md index ce54ea70af..0694f95760 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -380,7 +380,6 @@ improvising or retrying when something is off. | Named sections for every compiled program ("Who: title, first name, last name", "Contact", "Create New Patient"), found without a model from the save, the recorded form structure, the fields and any narration; a person can rename, merge or split them on the review screen | Released | Unit tests; the certified OpenEMR referral bundle and a real recording of it on a local test copy with made-up patients | `openadapt-flow sections`; [SECTIONS.md](packages/flow/docs/SECTIONS.md) | | Encrypt PHI at rest: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, and the run directories of sealed bundles; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md) | | Encryption at rest under a configured or locally generated key (0600): durable checkpoints and attended state by default; with `OPENADAPT_FLOW_AT_REST=strict`, every recording, bundle and run directory too. Each plaintext write is logged on stderr and in a ledger that Desktop shows as a notice | On main | Synthetic (key, opt-out, strict-mode, run-directory and attended-state audit-hook tests) | `openadapt_flow.at_rest`; [phi_at_rest.md](packages/flow/docs/phi_at_rest.md#default-opt-out-and-strict-mode) | -| Model calls fail closed: a component with no `MAY_EGRESS` marker counts as sending frames off the box and needs the egress opt-in; a model "yes" from the drift oracle is a hint for the person reviewing the halt, never a pass; identity-VLM calls count as model calls, split by placement (off-box into `model_calls`, in process into `local_model_calls`), so off-box identity crops never report no external calls; every frame sent off the box is first written to a local append-only ledger (`egress-ledger.jsonl` beside the run directory, hashes and sizes only) and is not sent if that write fails; a signed record that counts off-box model calls must say external calls were observed, while in-process calls never require it; the regulated profile refuses a cleartext appliance or grounding endpoint that is not loopback; a pinned grounding model that can't be wired, or names no model, never falls back to a default model or to the appliance | Branch ([#2497](https://github.com/OpenAdaptAI/OpenAdapt/pull/2497)) | Unit tests (`tests/test_model_failclosed.py`, `tests/test_drift_oracle.py`) | `runtime/model_egress.py`, `model_transport.py`, `model_call_evidence.py`, [ON_PREM_VLM.md](packages/flow/docs/deployment/ON_PREM_VLM.md) | | Receipts: one signed record per run, with any outcome (`receipt.json`, a DSSE envelope over an in-toto `record/run/v1` statement): one line per write with its check, strength and what it didn't check; digests, enums, counts and salted commitments only, never screenshots, typed values, URLs or page text; the outcome copied, never upgraded; signer roles from a pinned registry (this computer, customer key, OpenAdapt Cloud countersignature, public log, demo), unknown key, role or schema fails closed; a public card is the same envelope with only allow-listed values opened (`openadapt.public-disclosure/v1`) | Branch ([#2394](https://github.com/OpenAdaptAI/OpenAdapt/pull/2394)) | Unit tests with synthetic runs (stopped runs, tampered report and payload, unknown signer, embedded image refused); 15 shared vectors for the Python, Cloud and web verifiers | `openadapt verify `, `openadapt receipt verify\|view\|publish\|unpublish`; [RECEIPTS.md](packages/flow/docs/RECEIPTS.md); [vectors](packages/types/tests/vectors/record-run-v1/README.md) | | Older signed formats still verify, labelled "older format": offline and public Seals (`local-seal/v1`, `public-seal/v1`), Cloud-signed Execute receipts (`seal-signature/v1`), run summaries (`run-receipt/v2`), write and transaction receipts; Seals countersigned and timestamped | Released | Unit tests, real TSA tokens | `openadapt verify`; `openadapt-flow countersign`, `local-seal`; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md) | | Encrypt a bundle at rest under one encrypted index | Released | Unit tests | `openadapt-flow encrypt` (`seal` is a hidden alias for one release) | diff --git a/capabilities/11-recording-privacy-and-proof/0105-model-calls-fail-closed-a-component-with-no.md b/capabilities/11-recording-privacy-and-proof/0105-model-calls-fail-closed-a-component-with-no.md new file mode 100644 index 0000000000..6f688a0433 --- /dev/null +++ b/capabilities/11-recording-privacy-and-proof/0105-model-calls-fail-closed-a-component-with-no.md @@ -0,0 +1 @@ +| Model calls fail closed: a component with no `MAY_EGRESS` marker counts as sending frames off the box and needs the egress opt-in; a model "yes" from the drift oracle is a hint for the person reviewing the halt, never a pass; identity-VLM calls count as model calls, split by placement (off-box into `model_calls`, in process into `local_model_calls`), so off-box identity crops never report no external calls; every frame sent off the box is first written to a local append-only ledger (`egress-ledger.jsonl` beside the run directory, hashes and sizes only) and is not sent if that write fails; a signed record that counts off-box model calls must say external calls were observed, while in-process calls never require it; the regulated profile refuses a cleartext appliance or grounding endpoint that is not loopback; a pinned grounding model that can't be wired, or names no model, never falls back to a default model or to the appliance | Branch ([#2497](https://github.com/OpenAdaptAI/OpenAdapt/pull/2497)) | Unit tests (`tests/test_model_failclosed.py`, `tests/test_drift_oracle.py`) | `runtime/model_egress.py`, `model_transport.py`, `model_call_evidence.py`, [ON_PREM_VLM.md](packages/flow/docs/deployment/ON_PREM_VLM.md) | diff --git a/llms-full.txt b/llms-full.txt index e8e0d17285..f4e616d698 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -851,7 +851,6 @@ improvising or retrying when something is off. | Named sections for every compiled program ("Who: title, first name, last name", "Contact", "Create New Patient"), found without a model from the save, the recorded form structure, the fields and any narration; a person can rename, merge or split them on the review screen | Released | Unit tests; the certified OpenEMR referral bundle and a real recording of it on a local test copy with made-up patients | `openadapt-flow sections`; [SECTIONS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SECTIONS.md) | | Encrypt PHI at rest: every bundle file that can hold patient data under one sealed index (unknown files refused), web recordings from the first frame, and the run directories of sealed bundles; compile, induce, scaffold-verifier, qualify, admit, run, resume, undo, visualize, explain, emit-skill, for-each, sections, check mark, compose, process, variants, route, teach and push read them in memory through one artifact reader and refuse without the key; teach keeps its skill library and taught bundle sealed, and push keeps its sanitized review copy and approved archive encrypted until the upload | On main | Synthetic (no-plaintext audit-hook test over record, compile and a VERIFIED run; per-frame cost measured) | `openadapt-flow seal`, `record`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md) | | Encryption at rest under a configured or locally generated key (0600): durable checkpoints and attended state by default; with `OPENADAPT_FLOW_AT_REST=strict`, every recording, bundle and run directory too. Each plaintext write is logged on stderr and in a ledger that Desktop shows as a notice | On main | Synthetic (key, opt-out, strict-mode, run-directory and attended-state audit-hook tests) | `openadapt_flow.at_rest`; [phi_at_rest.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/phi_at_rest.md#default-opt-out-and-strict-mode) | -| Model calls fail closed: a component with no `MAY_EGRESS` marker counts as sending frames off the box and needs the egress opt-in; a model "yes" from the drift oracle is a hint for the person reviewing the halt, never a pass; identity-VLM calls count as model calls, split by placement (off-box into `model_calls`, in process into `local_model_calls`), so off-box identity crops never report no external calls; every frame sent off the box is first written to a local append-only ledger (`egress-ledger.jsonl` beside the run directory, hashes and sizes only) and is not sent if that write fails; a signed record that counts off-box model calls must say external calls were observed, while in-process calls never require it; the regulated profile refuses a cleartext appliance or grounding endpoint that is not loopback; a pinned grounding model that can't be wired, or names no model, never falls back to a default model or to the appliance | Branch ([#2497](https://github.com/OpenAdaptAI/OpenAdapt/pull/2497)) | Unit tests (`tests/test_model_failclosed.py`, `tests/test_drift_oracle.py`) | `runtime/model_egress.py`, `model_transport.py`, `model_call_evidence.py`, [ON_PREM_VLM.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/deployment/ON_PREM_VLM.md) | | Receipts: one signed record per run, with any outcome (`receipt.json`, a DSSE envelope over an in-toto `record/run/v1` statement): one line per write with its check, strength and what it didn't check; digests, enums, counts and salted commitments only, never screenshots, typed values, URLs or page text; the outcome copied, never upgraded; signer roles from a pinned registry (this computer, customer key, OpenAdapt Cloud countersignature, public log, demo), unknown key, role or schema fails closed; a public card is the same envelope with only allow-listed values opened (`openadapt.public-disclosure/v1`) | Branch ([#2394](https://github.com/OpenAdaptAI/OpenAdapt/pull/2394)) | Unit tests with synthetic runs (stopped runs, tampered report and payload, unknown signer, embedded image refused); 15 shared vectors for the Python, Cloud and web verifiers | `openadapt verify `, `openadapt receipt verify\|view\|publish\|unpublish`; [RECEIPTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/RECEIPTS.md); [vectors](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/types/tests/vectors/record-run-v1/README.md) | | Older signed formats still verify, labelled "older format": offline and public Seals (`local-seal/v1`, `public-seal/v1`), Cloud-signed Execute receipts (`seal-signature/v1`), run summaries (`run-receipt/v2`), write and transaction receipts; Seals countersigned and timestamped | Released | Unit tests, real TSA tokens | `openadapt verify`; `openadapt-flow countersign`, `local-seal`; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md) | | Encrypt a bundle at rest under one encrypted index | Released | Unit tests | `openadapt-flow encrypt` (`seal` is a hidden alias for one release) | diff --git a/packages/flow/openadapt_flow/runtime/grounder.py b/packages/flow/openadapt_flow/runtime/grounder.py index 6a3d4901eb..cbaa95f9df 100644 --- a/packages/flow/openadapt_flow/runtime/grounder.py +++ b/packages/flow/openadapt_flow/runtime/grounder.py @@ -605,8 +605,12 @@ def __init__(self, model: str = _DEFAULT_MODEL, client: object = None) -> None: # resend the frame behind one egress-ledger line and one counted call. if client is None: client = anthropic.Anthropic(max_retries=0) - elif callable(getattr(client, "with_options", None)): - client = client.with_options(max_retries=0) + else: + with_options = getattr(client, "with_options", None) + if callable(with_options) and isinstance( + getattr(client, "max_retries", None), int + ): + client = with_options(max_retries=0) self._client = client self._outbound = _OutboundScreen(None) diff --git a/packages/flow/openadapt_flow/runtime/replayer.py b/packages/flow/openadapt_flow/runtime/replayer.py index 6196c4ea7c..679e7b36a2 100644 --- a/packages/flow/openadapt_flow/runtime/replayer.py +++ b/packages/flow/openadapt_flow/runtime/replayer.py @@ -479,11 +479,11 @@ def _egress(self) -> EgressRecorder: """The egress recorder, created on first use when ``__init__`` didn't run. A replayer built without ``__init__`` (``Replayer.__new__``, a stubbed - constructor) never wrapped its model components. Here they are wrapped - before the recorder is returned, so a frame still can't leave the box - unledgered, and an off-box call made outside ``run`` is refused (an - unbound recorder admits nothing unless ``OPENADAPT_FLOW_EGRESS_LEDGER`` - names a ledger). + constructor) never wrapped its model components. The components set + at the first access are wrapped then, before the recorder is returned; + one assigned after that is not. An off-box call made outside ``run`` is + refused (an unbound recorder admits nothing unless + ``OPENADAPT_FLOW_EGRESS_LEDGER`` names a ledger). """ recorder = self.__dict__.get("_egress_recorder") @@ -496,7 +496,6 @@ def _egress(self) -> EgressRecorder: self.__dict__[kind] = recorder.wrap(kind, component) return recorder - # Display-scale state (see __init__); class defaults keep partially # constructed replayers, as some tests build them, on recorded geometry. _render_scale_attempted: bool = False From fd5689df521df14bc9c4816f38e8a0f9d6445226 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 23:50:05 -0500 Subject: [PATCH 26/26] fix(flow): wrap model components on every assignment, not just at init Replayer.grounder, identity_vlm and state_verifier are now properties whose setters wrap through the egress recorder. A component assigned after construction is ledgered and counted like one passed to __init__; an egress-capable one needs allow_model_grounding (else EgressNotPermitted) and marks the run's screenshots as possibly leaving the box. Wrapping is idempotent per recorder, so re-assigning a wrapped component never ledgers a send twice. --- .../openadapt_flow/runtime/model_egress.py | 2 + .../flow/openadapt_flow/runtime/replayer.py | 82 ++++++++++++++++--- packages/flow/tests/test_model_failclosed.py | 63 ++++++++++++-- 3 files changed, 129 insertions(+), 18 deletions(-) diff --git a/packages/flow/openadapt_flow/runtime/model_egress.py b/packages/flow/openadapt_flow/runtime/model_egress.py index cc501bd9da..6b63b63ac2 100644 --- a/packages/flow/openadapt_flow/runtime/model_egress.py +++ b/packages/flow/openadapt_flow/runtime/model_egress.py @@ -159,6 +159,8 @@ def wrap(self, kind: str, component: Any) -> Any: if component is None: return None + if isinstance(component, _Wrapped) and component._recorder is self: + return component # already wrapped here: never ledger a send twice if isinstance(component, FallbackGrounder): return FallbackGrounder([self.wrap(kind, g) for g in component._grounders]) off_box = component_may_egress(component) diff --git a/packages/flow/openadapt_flow/runtime/replayer.py b/packages/flow/openadapt_flow/runtime/replayer.py index 679e7b36a2..2737a76e1e 100644 --- a/packages/flow/openadapt_flow/runtime/replayer.py +++ b/packages/flow/openadapt_flow/runtime/replayer.py @@ -478,24 +478,80 @@ class Replayer( def _egress(self) -> EgressRecorder: """The egress recorder, created on first use when ``__init__`` didn't run. - A replayer built without ``__init__`` (``Replayer.__new__``, a stubbed - constructor) never wrapped its model components. The components set - at the first access are wrapped then, before the recorder is returned; - one assigned after that is not. An off-box call made outside ``run`` is - refused (an unbound recorder admits nothing unless - ``OPENADAPT_FLOW_EGRESS_LEDGER`` names a ledger). + Every assignment to ``grounder``, ``identity_vlm`` or + ``state_verifier`` goes through :meth:`_set_model_component`, which + wraps the component with this recorder. A replayer built without + ``__init__`` (``Replayer.__new__``, a stubbed constructor) therefore + gets its recorder here, at the first assignment or call. An unbound + recorder admits nothing unless ``OPENADAPT_FLOW_EGRESS_LEDGER`` names + a ledger, so an off-box call made outside ``run`` is refused. """ recorder = self.__dict__.get("_egress_recorder") if recorder is None: recorder = EgressRecorder() self.__dict__["_egress_recorder"] = recorder - for kind in ("grounder", "identity_vlm", "state_verifier"): - component = self.__dict__.get(kind) - if component is not None: - self.__dict__[kind] = recorder.wrap(kind, component) return recorder + def _get_model_component(self, kind: str) -> Any: + try: + return self.__dict__["_model_" + kind] + except KeyError: + raise AttributeError(kind) from None + + def _set_model_component(self, kind: str, component: Any) -> None: + """Wrap ``component`` for recording and store it, at any time. + + Assigning a component after construction gets the same treatment as + passing it to ``__init__``: one that may send a frame off the box + needs ``allow_model_grounding`` (else :class:`EgressNotPermitted`), + marks the run as one whose screenshots may leave the box, and is + ledgered and counted on every call. + """ + + from openadapt_flow.runtime.grounder import component_may_egress + + if component_may_egress(component): + if not self.__dict__.get("allow_model_grounding", False): + raise EgressNotPermitted( + f"refusing to wire an egress-capable {kind} that could " + "send a screenshot off the box: pass " + "allow_model_grounding=True (CLI: --allow-model-grounding) " + "to opt in explicitly." + ) + self.__dict__["_screenshots_may_leave_box"] = True + self.__dict__["_model_" + kind] = self._egress.wrap(kind, component) + + @property + def grounder(self) -> Any: + """The grounder, wrapped for egress recording on every assignment.""" + + return self._get_model_component("grounder") + + @grounder.setter + def grounder(self, component: Any) -> None: + self._set_model_component("grounder", component) + + @property + def identity_vlm(self) -> Any: + """The identity VLM, wrapped for egress recording on every assignment.""" + + return self._get_model_component("identity_vlm") + + @identity_vlm.setter + def identity_vlm(self, component: Any) -> None: + self._set_model_component("identity_vlm", component) + + @property + def state_verifier(self) -> Any: + """The state verifier, wrapped for egress recording on every assignment.""" + + return self._get_model_component("state_verifier") + + @state_verifier.setter + def state_verifier(self, component: Any) -> None: + self._set_model_component("state_verifier", component) + # Display-scale state (see __init__); class defaults keep partially # constructed replayers, as some tests build them, on recorded geometry. _render_scale_attempted: bool = False @@ -642,7 +698,7 @@ def __init__( self.vision: Any = vision # Frames sent off the box are ledgered and counted by placement. self.__dict__["_egress_recorder"] = EgressRecorder() - self.grounder = self._egress.wrap("grounder", grounder) + self.grounder = grounder # Whether the deterministic structural ACTION rung (top of the ladder) # may run. True (default) = product behavior: on a structure-bearing # backend, resolve the recorded target as a DOM/UIA element. Set False @@ -835,7 +891,7 @@ def __init__( # OFF by default like the grounder: an IdentityVLM verifier or None. # When None the ladder runs structured-text + pixel-compare + OCR + # halt with no model dependency. - self.identity_vlm = self._egress.wrap("identity_vlm", identity_vlm) + self.identity_vlm = identity_vlm # Optional complete known-ID list (runtime.known_ids): lifts a # look-alike identifier abstain only when no listed twin exists. self.known_ids = known_ids @@ -850,7 +906,7 @@ def __init__( # it is asked about a render-drift-sensitive postcondition that failed # deterministically. Its "yes" is a hint for the person who reviews # the halt; the postcondition stays failed. - self.state_verifier = self._egress.wrap("state_verifier", state_verifier) + self.state_verifier = state_verifier self.poll_interval_s = poll_interval_s if not math.isfinite(settle_readiness_timeout_s) or ( settle_readiness_timeout_s <= 0 diff --git a/packages/flow/tests/test_model_failclosed.py b/packages/flow/tests/test_model_failclosed.py index bc7536b14e..bf8ebd7331 100644 --- a/packages/flow/tests/test_model_failclosed.py +++ b/packages/flow/tests/test_model_failclosed.py @@ -643,17 +643,70 @@ def post(self, url, **kwargs): assert line["destination"] == "vlm.example.test" +def test_component_assigned_after_first_access_is_ledgered_and_counted( + tmp_path, monkeypatch +): + # Assigning a model component after construction (and after the recorder + # is in use) wraps it exactly as __init__ does, so its send is counted. + monkeypatch.delenv("OPENADAPT_FLOW_EGRESS_LEDGER", raising=False) + rp = Replayer(FakeBackend(), allow_model_grounding=True) + rp._egress.bind_run(tmp_path / "runs" / "r1") + rp._egress.step_id = "s1" + assert rp._screenshots_may_leave_box is False + inner = _OffBoxGrounder() + rp.grounder = inner + rp.grounder = rp.grounder # re-assigning a wrapped component never double-wraps + assert rp.grounder is not inner + assert rp._screenshots_may_leave_box is True + assert rp.grounder.locate(_png(), "open the chart") is None + assert inner.calls == 1 + (line,) = _ledger_lines(tmp_path / "runs" / "egress-ledger.jsonl") + assert line["component"] == "grounder" and line["destination"] == "vlm.internal" + result = StepResult(step_id="s1", intent="open the chart", ok=False) + rp._egress.drain(result) + assert result.grounder_calls == 1 + + vlm = _OffBoxIdentityVLM("same") + rp.identity_vlm = vlm + verifier = _Verifier("yes") + rp.state_verifier = verifier + crop = _crop_png() + rp.identity_vlm.same_or_different(crop, crop) + rp.state_verifier.holds(crop, "x") + assert (vlm.calls, verifier.calls) == (1, 1) + assert len(_ledger_lines(tmp_path / "runs" / "egress-ledger.jsonl")) == 3 + + +def test_off_box_component_assigned_without_opt_in_is_refused(monkeypatch): + monkeypatch.delenv("OPENADAPT_FLOW_EGRESS_LEDGER", raising=False) + rp = Replayer(FakeBackend()) + with pytest.raises(EgressNotPermitted): + rp.grounder = _OffBoxGrounder() + with pytest.raises(EgressNotPermitted): + rp.identity_vlm = _OffBoxIdentityVLM("same") + with pytest.raises(EgressNotPermitted): + rp.state_verifier = _Verifier("yes") + assert rp.grounder is None and rp._screenshots_may_leave_box is False + + # A replayer built without __init__ has no opt-in either. + bare = Replayer.__new__(Replayer) + with pytest.raises(EgressNotPermitted): + bare.grounder = _OffBoxGrounder() + + def test_replayer_built_without_init_still_ledgers_off_box_calls(monkeypatch): - # A Replayer made with __new__ gets its recorder on first use, and the - # components already set are wrapped, so nothing is sent unrecorded. + # A Replayer made with __new__ gets its recorder on first use, and an + # opted-in component assigned to it is wrapped, so nothing is sent + # unrecorded (here: no ledger is bound, so the send is refused). from openadapt_flow.runtime.model_egress import LEDGER_ENV monkeypatch.delenv(LEDGER_ENV, raising=False) rp = Replayer.__new__(Replayer) - inner = _OffBoxGrounder() - rp.grounder = inner recorder = rp._egress assert rp._egress is recorder + rp.allow_model_grounding = True + inner = _OffBoxGrounder() + rp.grounder = inner assert rp.grounder is not inner - assert rp.grounder.locate(b"frame", "click Save") is None # no ledger bound + assert rp.grounder.locate(b"frame", "click Save") is None assert inner.calls == 0