From db419682659a3b2e5b3320bea789f6b1aeeba53b Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 00:42:27 -0500 Subject: [PATCH 01/18] wip: handoff ledger --- .../handoff_receiver/docker-compose.yml | 60 ++++ packages/flow/benchmark/openemr_live/setup.sh | 8 +- .../flow/openadapt_flow/handoffs/__init__.py | 49 +++ .../flow/openadapt_flow/handoffs/ledger.py | 336 ++++++++++++++++++ 4 files changed, 450 insertions(+), 3 deletions(-) create mode 100644 packages/flow/benchmark/handoff_receiver/docker-compose.yml create mode 100644 packages/flow/openadapt_flow/handoffs/__init__.py create mode 100644 packages/flow/openadapt_flow/handoffs/ledger.py diff --git a/packages/flow/benchmark/handoff_receiver/docker-compose.yml b/packages/flow/benchmark/handoff_receiver/docker-compose.yml new file mode 100644 index 0000000000..1666d69d82 --- /dev/null +++ b/packages/flow/benchmark/handoff_receiver/docker-compose.yml @@ -0,0 +1,60 @@ +# The receiving clinic for the referral-intake handoff tests: a second, +# separate, synthetic OpenEMR 7.0.3 with its own database. Nothing here is +# shared with any other OpenEMR stack. Ports are loopback only. +# +# docker compose -f docker-compose.yml up -d --wait +# OPENEMR_COMPOSE_FILE=$PWD/docker-compose.yml \ +# OPENEMR_BASE_HTTPS=https://127.0.0.1:9781 \ +# eval "$(../openemr_live/setup.sh)" +# +# See README.md. + +name: ho-openemr + +services: + mysql: + image: mariadb:11.4 + command: + - mariadbd + - --character-set-server=utf8mb4 + - --collation-server=utf8mb4_general_ci + - --innodb-buffer-pool-size=96M + - --performance-schema=OFF + environment: + MYSQL_ROOT_PASSWORD: root + healthcheck: + test: ["CMD", "healthcheck.sh", "--connect", "--innodb_initialized"] + interval: 10s + timeout: 5s + retries: 30 + volumes: + - receiver_db:/var/lib/mysql + + openemr: + image: openemr/openemr:7.0.3 + ports: + - "127.0.0.1:9780:80" + - "127.0.0.1:9781:443" + environment: + MYSQL_HOST: mysql + MYSQL_ROOT_PASS: root + MYSQL_USER: openemr + MYSQL_PASS: openemr + OE_USER: admin + OE_PASS: pass + depends_on: + mysql: + condition: service_healthy + healthcheck: + test: ["CMD", "test", "-f", "/var/www/localhost/htdocs/openemr/sites/default/sqlconf.php"] + interval: 15s + timeout: 5s + retries: 80 + volumes: + - receiver_sites:/var/www/localhost/htdocs/openemr/sites + - receiver_logs:/var/log + +volumes: + receiver_db: + receiver_sites: + receiver_logs: diff --git a/packages/flow/benchmark/openemr_live/setup.sh b/packages/flow/benchmark/openemr_live/setup.sh index cc787fcb72..99b5452874 100755 --- a/packages/flow/benchmark/openemr_live/setup.sh +++ b/packages/flow/benchmark/openemr_live/setup.sh @@ -24,9 +24,11 @@ set -euo pipefail # --- config ----------------------------------------------------------------- -COMPOSE_FILE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/docker-compose.yml" +# OPENEMR_COMPOSE_FILE and OPENEMR_BASE_HTTPS point this script at another +# stack (benchmark/handoff_receiver uses them). +COMPOSE_FILE="${OPENEMR_COMPOSE_FILE:-$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/docker-compose.yml}" DC=(docker compose -f "$COMPOSE_FILE") -BASE_HTTPS="https://localhost:9390" +BASE_HTTPS="${OPENEMR_BASE_HTTPS:-https://localhost:9390}" FHIR_BASE="${BASE_HTTPS}/apis/default/fhir" OE_USER="admin" OE_PASS="pass" @@ -36,7 +38,7 @@ OE_PASS="pass" # - OpenEMR's FHIR API exposes Observation/Encounter READ only (there is no # `user/Observation.write`), so the live write path is a FHIR Patient # POST, independently read back through FHIR. -SCOPES="openid offline_access api:fhir user/Patient.read user/Patient.write user/Observation.read user/Encounter.read" +SCOPES="${OPENEMR_SCOPES:-openid offline_access api:fhir user/Patient.read user/Patient.write user/Observation.read user/Encounter.read}" log() { echo "[setup] $*" >&2; } # MariaDB 11.x ships the `mariadb` client (not `mysql`). diff --git a/packages/flow/openadapt_flow/handoffs/__init__.py b/packages/flow/openadapt_flow/handoffs/__init__.py new file mode 100644 index 0000000000..0edf4c638b --- /dev/null +++ b/packages/flow/openadapt_flow/handoffs/__init__.py @@ -0,0 +1,49 @@ +"""Handoffs: did the other party record what we sent? + +A handoff is one thing a run sends to another party's system: a claim to a +payer, a referral to a receiving clinic. A counterparty confirmation is +evidence, read from that other system, of what it recorded. Each handoff +moves through four states: + +- ``sent``: we sent it, and nothing from the other side has said so yet; +- ``acknowledged``: the other side says it has it, without saying what it + recorded (an X12 999 or a 277CA ``A1``), or says it won't take it; +- ``recorded_as_intended``: the other side recorded it, and every field we + compared matches what we sent (or, for a status-only report, it accepted + it: see ``strength``); +- ``recorded_differently``: the other side recorded it, and these fields + differ from what we sent (field ids only, never the values). + +One mechanism serves every producer: a local ledger of handoffs +(:mod:`.ledger`), readers that look at the other system (:mod:`.readers`), +one comparator (:mod:`.intake`), and the mapping of the existing deferred +claim check onto handoffs (:mod:`.payer`). :mod:`.line` turns a handoff into +the receipt's ``counterparty_confirmation`` line. No engine code names an +app, a payer or a clinic: what to read, and how each field compares, is a +profile (data). + +No model calls. The ledger holds no record values: keys and field values are +HMAC-SHA256 digests under a salt kept in the ledger directory (0600). +""" + +from openadapt_flow.handoffs.ledger import ( + FieldSpec, + Handoff, + HandoffLedger, + HandoffState, + Observation, + ReadMethod, + Reason, + Strength, +) + +__all__ = [ + "FieldSpec", + "Handoff", + "HandoffLedger", + "HandoffState", + "Observation", + "ReadMethod", + "Reason", + "Strength", +] diff --git a/packages/flow/openadapt_flow/handoffs/ledger.py b/packages/flow/openadapt_flow/handoffs/ledger.py new file mode 100644 index 0000000000..73daebf9f4 --- /dev/null +++ b/packages/flow/openadapt_flow/handoffs/ledger.py @@ -0,0 +1,336 @@ +"""The handoff ledger: what we sent, to whom, and what they say they recorded. + +One JSON file per handoff in a private directory (0700, files 0600). A +handoff keeps: + +- when it was sent and when someone must follow up (``follow_up_due``); +- who the other party is, as a short label, and who follows up; +- the item's key and each sent field's value, only as HMAC-SHA256 digests of + the normalized value under the ledger's salt, so a read-back can compare + without the ledger ever holding a value; +- every observation, in order. An observation is never edited or removed. + +The handoff's state is its latest observation's state, or ``sent`` with none. +An observation that learned nothing new (the receiver was unreachable, the +key matched two records) carries the previous state with a reason. +""" + +from __future__ import annotations + +import hashlib +import hmac +import json +import os +import secrets +from contextlib import contextmanager +from datetime import datetime, timedelta, timezone +from pathlib import Path +from typing import Iterator, Literal, Mapping, Optional + +from pydantic import BaseModel, ConfigDict, Field + +from openadapt_flow.runtime.effects.readback_values import ValueKind, normalize_value + +SCHEMA: Literal["openadapt.handoff/v1"] = "openadapt.handoff/v1" + +HandoffState = Literal[ + "sent", "acknowledged", "recorded_as_intended", "recorded_differently" +] +#: How the other system was read. +ReadMethod = Literal[ + "x12_999", "x12_277ca", "report_csv", "report_text", "api_readback", "ui_readback" +] +#: ``field_readback``: the fields were read back and compared. +#: ``status_only``: the other side gave a status for the item, not its fields. +Strength = Literal["field_readback", "status_only", "none"] +#: Why an observation needs a person, or learned nothing new. +Reason = Literal[ + "rejected_by_counterparty", + "conflicting_report", + "ambiguous_key", + "receiver_unreachable", + "not_found", + "no_answer_by_deadline", +] +#: The receipt schema's kinds of other system. +SystemKind = Literal[ + "ehr", + "payer_portal", + "bank", + "erp", + "crm", + "government_portal", + "email", + "other", +] +#: Reasons that need a person even before the follow-up time. +ATTENTION: frozenset[str] = frozenset( + {"rejected_by_counterparty", "conflicting_report", "ambiguous_key"} +) +Status = Literal["needs_follow_up", "waiting", "done"] + +_FIELD_ID = r"^[a-z][a-z0-9_]{0,47}$" +_DIGEST = r"^[0-9a-f]{64}$" +_LABEL_MAX = 80 +_SALT_FILE = ".salt" +_LOCK_FILE = ".lock" + + +def now_utc() -> datetime: + return datetime.now(timezone.utc) + + +def iso_seconds(moment: datetime) -> str: + """Whole seconds in UTC with a ``Z``, as the receipt line takes it.""" + return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def parse_iso(text: str) -> datetime: + return datetime.fromisoformat(text.replace("Z", "+00:00")) + + +class _Closed(BaseModel): + model_config = ConfigDict(extra="forbid") + + +class FieldSpec(_Closed): + """One field we sent: how it compares, and its value's digest.""" + + kind: ValueKind = "text" + digest: str = Field(pattern=_DIGEST) + #: For a date written day-first or month-first (``dmy``/``mdy``). + date_order: Optional[Literal["dmy", "mdy"]] = None + + +class Observation(_Closed): + """One look at the other system. Never edited after it is written.""" + + state: HandoffState + observed_at: str + read_method: ReadMethod + strength: Strength + #: Field ids that differ from what we sent (never the values). + differing_fields: list[str] = Field(default_factory=list, max_length=64) + #: For each differing field, the digest of the value the other side holds + #: (``missing`` when it holds none). Private: it opens only in the + #: receipt's private openings. + observed_digests: dict[str, str] = Field(default_factory=dict) + reason: Optional[Reason] = None + #: SHA-256 of the report or read-back body this came from. + evidence_sha256: Optional[str] = Field(default=None, pattern=_DIGEST) + + +class Handoff(_Closed): + schema_version: Literal["openadapt.handoff/v1"] = SCHEMA + id: str = Field(pattern=r"^handoff:[0-9a-f]{32}$") + sent_at: str + follow_up_due: str + #: The other party, for people ("payer 277CA", "receiving clinic"). + counterparty: str = Field(max_length=_LABEL_MAX) + system_kind: SystemKind = "other" + #: Who follows up when it is overdue or differs ("billing", "referrals desk"). + follow_up: str = Field(default="the sender", max_length=_LABEL_MAX) + key_digest: str = Field(pattern=_DIGEST) + fields: dict[str, FieldSpec] = Field(default_factory=dict, max_length=64) + #: Where it came from: a deferred check's id, or a run's id. + source: Optional[str] = Field(default=None, max_length=128) + run_id: Optional[str] = Field(default=None, max_length=128) + step: Optional[int] = Field(default=None, ge=0, le=10_000) + observations: list[Observation] = Field(default_factory=list) + + @property + def state(self) -> HandoffState: + return self.observations[-1].state if self.observations else "sent" + + @property + def last(self) -> Optional[Observation]: + return self.observations[-1] if self.observations else None + + def overdue(self, now: Optional[datetime] = None) -> bool: + return parse_iso(self.follow_up_due) <= (now or now_utc()) + + def status(self, now: Optional[datetime] = None) -> Status: + """``done`` only when recorded as intended and nothing since says + otherwise; ``needs_follow_up`` when it differs, was refused, is + ambiguous, or is past its follow-up time; else ``waiting``.""" + + last = self.last + reason = last.reason if last is not None else None + if self.state == "recorded_as_intended" and reason is None: + return "done" + if ( + self.state == "recorded_differently" + or reason in ATTENTION + or self.overdue(now) + ): + return "needs_follow_up" + return "waiting" + + +class LedgerError(ValueError): + """The ledger refused a change. The message carries no record values.""" + + +class HandoffLedger: + """A directory of handoffs, changed only under a file lock.""" + + def __init__(self, directory: str | Path) -> None: + self.directory = Path(directory) + + # -- storage ------------------------------------------------------------ + def _ensure(self) -> None: + self.directory.mkdir(parents=True, exist_ok=True) + os.chmod(self.directory, 0o700) + + @contextmanager + def _locked(self) -> Iterator[None]: + self._ensure() + import fcntl + + with open(self.directory / _LOCK_FILE, "a+") as handle: + os.chmod(self.directory / _LOCK_FILE, 0o600) + fcntl.flock(handle, fcntl.LOCK_EX) + try: + yield + finally: + fcntl.flock(handle, fcntl.LOCK_UN) + + def _salt(self) -> bytes: + path = self.directory / _SALT_FILE + if not path.exists(): + self._ensure() + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, "w") as handle: + handle.write(secrets.token_hex(32)) + return bytes.fromhex(path.read_text().strip()) + + def digest(self, text: str) -> str: + return hmac.new(self._salt(), text.encode("utf-8"), hashlib.sha256).hexdigest() + + def field_digest( + self, value: str, kind: ValueKind, date_order: Optional[str] = None + ) -> Optional[str]: + """The digest of ``value`` normalized for ``kind``; None if it doesn't + parse as that kind (a date that reads two ways, a word for a number).""" + + normal = normalize_value(str(value), kind, date_order=date_order) + return None if normal is None else self.digest(f"{kind}\x00{normal}") + + def _path(self, handoff_id: str) -> Path: + return self.directory / f"{handoff_id.split(':', 1)[1]}.json" + + def _write(self, handoff: Handoff) -> None: + path = self._path(handoff.id) + tmp = path.with_suffix(".tmp") + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w") as handle: + handle.write(handoff.model_dump_json(indent=2)) + os.replace(tmp, path) + + def get(self, handoff_id: str) -> Optional[Handoff]: + path = self._path(handoff_id) + if not path.exists(): + return None + return Handoff.model_validate_json(path.read_text()) + + def entries(self) -> list[Handoff]: + if not self.directory.exists(): + return [] + found = [ + Handoff.model_validate_json(path.read_text()) + for path in sorted(self.directory.glob("*.json")) + ] + return sorted(found, key=lambda h: (h.sent_at, h.id)) + + def with_key(self, key: str) -> list[Handoff]: + digest = self.digest(key) + return [h for h in self.entries() if h.key_digest == digest] + + # -- changes ------------------------------------------------------------ + def send( + self, + key: str, + fields: Mapping[str, tuple[str, ValueKind] | tuple[str, ValueKind, str]], + *, + counterparty: str, + follow_up_hours: float, + system_kind: SystemKind = "other", + follow_up: str = "the sender", + source: Optional[str] = None, + run_id: Optional[str] = None, + step: Optional[int] = None, + now: Optional[datetime] = None, + ) -> Handoff: + """Record that we sent the item ``key`` with these field values. + + ``fields`` maps a field id to ``(value, kind)`` or ``(value, kind, + date_order)``. A value that doesn't normalize for its kind is refused, + since it could never be compared. A key that another open handoff + already uses is refused: a read-back couldn't tell them apart. + """ + + if not key: + raise LedgerError("a handoff needs the item's key") + if follow_up_hours <= 0: + raise LedgerError("follow_up_hours must be positive") + specs: dict[str, FieldSpec] = {} + for field_id, spec in fields.items(): + value, kind = spec[0], spec[1] + order = spec[2] if len(spec) > 2 else None # type: ignore[misc] + digest = self.field_digest(value, kind, order) + if digest is None: + raise LedgerError(f"field {field_id!r} doesn't read as a {kind}") + specs[field_id] = FieldSpec(kind=kind, digest=digest, date_order=order) + moment = now or now_utc() + with self._locked(): + key_digest = self.digest(key) + for other in self.entries(): + if other.key_digest == key_digest and other.status(moment) != "done": + raise LedgerError("another open handoff already uses this key") + handoff = Handoff( + id=f"handoff:{secrets.token_hex(16)}", + sent_at=iso_seconds(moment), + follow_up_due=iso_seconds(moment + timedelta(hours=follow_up_hours)), + counterparty=counterparty[:_LABEL_MAX], + system_kind=system_kind, + follow_up=follow_up[:_LABEL_MAX], + key_digest=key_digest, + fields=specs, + source=source, + run_id=run_id, + step=step, + ) + self._write(handoff) + return handoff + + def adopt(self, handoff: Handoff) -> Handoff: + """Add a handoff made elsewhere (a deferred check) unless it exists.""" + + with self._locked(): + existing = self.get(handoff.id) + if existing is not None: + return existing + self._write(handoff) + return handoff + + def observe(self, handoff_id: str, observation: Observation) -> Handoff: + """Append one observation. Earlier ones are never changed.""" + + with self._locked(): + current = self.get(handoff_id) + if current is None: + raise LedgerError("no such handoff") + updated = current.model_copy( + update={"observations": [*current.observations, observation]} + ) + self._write(updated) + return updated + + +def evidence_digest(body: str | bytes) -> str: + data = body.encode("utf-8") if isinstance(body, str) else body + return hashlib.sha256(data).hexdigest() + + +def dump_json(handoff: Handoff) -> str: + return json.dumps(handoff.model_dump(mode="json"), sort_keys=True) From 254f617921aabcd2f4a3dee40517edd201caadd3 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 00:49:26 -0500 Subject: [PATCH 02/18] wip: handoffs mechanism, payer and read-back producers, handoff list --- openadapt/cli.py | 4 + openadapt/cli_tasks.py | 1 + packages/flow/openadapt_flow/__main__.py | 4 + packages/flow/openadapt_flow/cli_deferred.py | 21 +- packages/flow/openadapt_flow/cli_handoff.py | 206 +++++++ packages/flow/openadapt_flow/cli_tasks.py | 1 + .../flow/openadapt_flow/handoffs/intake.py | 124 +++++ .../flow/openadapt_flow/handoffs/ledger.py | 31 +- packages/flow/openadapt_flow/handoffs/line.py | 223 ++++++++ .../flow/openadapt_flow/handoffs/payer.py | 231 ++++++++ .../flow/openadapt_flow/handoffs/readers.py | 213 +++++++ .../runtime/effects/deferred_report.py | 23 +- packages/flow/tests/test_handoffs.py | 518 ++++++++++++++++++ 13 files changed, 1590 insertions(+), 10 deletions(-) create mode 100644 packages/flow/openadapt_flow/cli_handoff.py create mode 100644 packages/flow/openadapt_flow/handoffs/intake.py create mode 100644 packages/flow/openadapt_flow/handoffs/line.py create mode 100644 packages/flow/openadapt_flow/handoffs/payer.py create mode 100644 packages/flow/openadapt_flow/handoffs/readers.py create mode 100644 packages/flow/tests/test_handoffs.py diff --git a/openadapt/cli.py b/openadapt/cli.py index cae0993eb0..ffc870577b 100644 --- a/openadapt/cli.py +++ b/openadapt/cli.py @@ -1421,6 +1421,10 @@ def flow(command_ctx: click.Context) -> None: ("record", "Record a workflow. Uses the same options as flow record."), ("compile", "Compile a recording. Uses the same options as flow compile."), ("run", "Run a bundle with its checks. Uses the same options as flow run."), + ( + "handoff", + "Handoffs to other parties: what they recorded, and who follows up.", + ), ): main.add_command( _FlowAliasCommand( diff --git a/openadapt/cli_tasks.py b/openadapt/cli_tasks.py index c43bbb993c..fadad271d1 100644 --- a/openadapt/cli_tasks.py +++ b/openadapt/cli_tasks.py @@ -65,6 +65,7 @@ "fleet": "services fleet", "for-each": "run --for-each", "guard": "run --guard", + "handoff": "handoff", "induce": "compile --induce", "intake": "teach --intake", "item-approval": "approve --item", diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index b3a3b13912..bcc7c8e5e6 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -13169,6 +13169,10 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None: register_deferred_parser(sub) + from openadapt_flow.cli_handoff import register_handoff_parser + + register_handoff_parser(sub) + from openadapt_flow.cli_undo import register as _register_undo _register_undo( diff --git a/packages/flow/openadapt_flow/cli_deferred.py b/packages/flow/openadapt_flow/cli_deferred.py index 8daa007a53..498eec1698 100644 --- a/packages/flow/openadapt_flow/cli_deferred.py +++ b/packages/flow/openadapt_flow/cli_deferred.py @@ -17,6 +17,7 @@ from openadapt_flow.reports.parse import ReportError, ReportFormat if TYPE_CHECKING: # pragma: no cover + from openadapt_flow.handoffs.payer import SettleRecorder from openadapt_flow.runtime.effects.deferred_report import ( DeferredReportSpec, PendingLedger, @@ -130,6 +131,19 @@ def _ui_final_from_config(path: Optional[str]) -> list[Any]: ] +def _recorder( + ledger: "PendingLedger", report_format: Optional[str], report: Optional[Path] +) -> "SettleRecorder": + """Record what the report says into the claim's handoff (``handoff list``).""" + + import hashlib + + from openadapt_flow.handoffs.payer import SettleRecorder + + sha = hashlib.sha256(report.read_bytes()).hexdigest() if report else None + return SettleRecorder(ledger, report_format or "", sha) + + def cmd_deferred_settle(args: argparse.Namespace) -> int: from openadapt_flow.runtime.effects.deferred_report import settle_report_file @@ -188,11 +202,13 @@ def cmd_deferred_settle(args: argparse.Namespace) -> int: issued_at = datetime.fromisoformat(args.report_time) if issued_at.tzinfo is None: raise ValueError("--report-time needs a time zone") + recorder = _recorder(ledger, fmt.format, Path(args.report)) settled = settle_report_file( - ledger, Path(args.report), fmt, issued_at=issued_at + ledger, Path(args.report), fmt, issued_at=issued_at, observer=recorder ) else: - settled = ledger.settle(None, None) + recorder = _recorder(ledger, None, None) + settled = ledger.settle(None, None, observer=recorder) except (OSError, ValueError, ReportError) as exc: print(f"deferred settle: {exc}", file=sys.stderr) return 2 @@ -201,6 +217,7 @@ def cmd_deferred_settle(args: argparse.Namespace) -> int: word = "VERIFIED" if item.state == "verified" else "RECONCILIATION_REQUIRED" print(f"{item.id}: {word} ({item.reason}; code {item.code})") print(f"Settled {len(settled)}; {len(waiting)} still waiting.") + print("Open handoffs: openadapt-flow handoff list --ledger " + str(ledger.directory)) return 0 diff --git a/packages/flow/openadapt_flow/cli_handoff.py b/packages/flow/openadapt_flow/cli_handoff.py new file mode 100644 index 0000000000..a8ecaab07f --- /dev/null +++ b/packages/flow/openadapt_flow/cli_handoff.py @@ -0,0 +1,206 @@ +"""``openadapt-flow handoff list``: open handoffs by state, and who follows up. + +A handoff is one thing a run sent to another party's system (a claim to a +payer, a referral to a receiving clinic). ``handoff list`` reads handoff +ledgers and shows which ones still need someone to follow up: + + openadapt-flow handoff list --ledger /var/lib/openadapt/deferred + openadapt-flow handoff list --config deployment.yaml --all + openadapt-flow handoff list --ledger DIR --run runs/claim-0412 --json + +A deferred-check ledger (``effects.deferred_report.ledger``) is read as the +payer handoffs beside it (``/handoffs``), created on first read. Any +other directory is read as a handoff ledger. See ``docs/HANDOFFS.md``. + +The ``send`` and ``verify`` subcommands belong to the handoff group too; +this module registers only ``list``. +""" + +from __future__ import annotations + +import argparse +import json +import sys +from datetime import datetime +from pathlib import Path +from typing import TYPE_CHECKING, Optional + +if TYPE_CHECKING: # pragma: no cover + from openadapt_flow.handoffs.ledger import Handoff, HandoffLedger + +_STATE_WORDS = { + "sent": "sent, no answer yet", + "acknowledged": "acknowledged", + "recorded_as_intended": "recorded as intended", + "recorded_differently": "recorded differently", +} +_REASON_WORDS = { + "rejected_by_counterparty": "they refused it", + "conflicting_report": "their reports disagree", + "ambiguous_key": "the key matches more than one item", + "receiver_unreachable": "their system could not be read", + "not_found": "not in their system", + "no_answer_by_deadline": "no answer by the follow-up time", +} +_GROUPS = ( + ("needs_follow_up", "Needs follow-up"), + ("waiting", "Waiting"), + ("done", "Done"), +) + + +def register_handoff_parser(sub: argparse._SubParsersAction) -> None: + parser = sub.add_parser( + "handoff", + help="Handoffs to other parties: what they recorded, and who follows up", + allow_abbrev=False, + ) + verbs = parser.add_subparsers(dest="handoff_cmd", required=True) + listing = verbs.add_parser( + "list", + help="Open handoffs by state, with who still needs to follow up", + allow_abbrev=False, + ) + listing.add_argument( + "--ledger", + action="append", + default=[], + help="A handoff ledger, or a deferred-check ledger (repeatable)", + ) + listing.add_argument( + "--config", + default=None, + help="deployment.yaml whose effects.deferred_report names the ledger", + ) + listing.add_argument( + "--all", action="store_true", help="Also list the handoffs that are done" + ) + listing.add_argument( + "--run", + default=None, + help="Only this run's handoffs (its directory, holding report.json)", + ) + listing.add_argument( + "--json", + action="store_true", + help="Print JSON: each handoff's status and its receipt line", + ) + listing.set_defaults(func=cmd_handoff_list) + + +def _ledgers(args: argparse.Namespace) -> list["HandoffLedger"]: + from openadapt_flow.handoffs.ledger import HandoffLedger + from openadapt_flow.handoffs.payer import sync + from openadapt_flow.runtime.effects.deferred_report import PendingLedger + + dirs = [Path(d) for d in args.ledger] + if args.config: + from openadapt_flow.cli_deferred import _from_config + + spec = _from_config(args.config) + if spec is not None: + dirs.append(Path(spec.ledger)) + if not dirs: + raise ValueError("name a ledger with --ledger or --config") + found: list[HandoffLedger] = [] + for directory in dirs: + if not directory.is_dir(): + raise ValueError(f"no ledger at {directory}") + pending = PendingLedger(directory) + if any(e for e in _quiet_entries(pending)): + found.append(sync(pending)) + else: + found.append(HandoffLedger(directory)) + return found + + +def _quiet_entries(pending: object) -> list[object]: + try: + return list(pending.entries()) # type: ignore[attr-defined] + except Exception: # noqa: BLE001 - not a deferred ledger + return [] + + +def _describe(handoff: "Handoff") -> str: + last = handoff.evidence + words = _STATE_WORDS[handoff.state] + if last is not None and last.counterparty_accepted and last.reason is None: + words = "accepted (status only, fields not compared)" + if handoff.state == "recorded_differently" and last is not None: + words += ": " + ", ".join(last.differing_fields) + latest = handoff.last + if latest is not None and latest.reason is not None: + words += f"; {_REASON_WORDS[latest.reason]}" + return words + + +def _when(text: str) -> str: + return text.replace("T", " ").removesuffix(":00Z").removesuffix("Z") + + +def cmd_handoff_list(args: argparse.Namespace) -> int: + from openadapt_flow.handoffs.ledger import now_utc + from openadapt_flow.handoffs.line import handoffs_for_run, to_line + + try: + ledgers = _ledgers(args) + if args.run: + report = json.loads((Path(args.run) / "report.json").read_text("utf-8")) + handoffs = handoffs_for_run(report, ledgers) + else: + handoffs = [h for ledger in ledgers for h in ledger.entries()] + except (OSError, ValueError) as exc: + print(f"handoff list: {exc}", file=sys.stderr) + return 2 + now: datetime = now_utc() + if args.json: + out = [] + for handoff in handoffs: + status = handoff.status(now) + if status == "done" and not args.all and not args.run: + continue + item = to_line(handoff) + out.append( + { + "id": handoff.id, + "status": status, + "state": handoff.state, + "counterparty": handoff.counterparty, + "follow_up": handoff.follow_up, + "follow_up_due": handoff.follow_up_due, + "sent_at": handoff.sent_at, + "differing_fields": list( + handoff.evidence.differing_fields if handoff.evidence else [] + ), + "reason": handoff.last.reason if handoff.last else None, + "receipt_line": item.line, + } + ) + print(json.dumps(out, indent=2)) + return 0 + if not handoffs: + print("No handoffs.") + return 0 + grouped: dict[str, list["Handoff"]] = {key: [] for key, _ in _GROUPS} + for handoff in handoffs: + grouped[handoff.status(now)].append(handoff) + for key, title in _GROUPS: + items = grouped[key] + if key == "done" and not args.all: + if items: + print(f"{title}: {len(items)} (--all lists them)") + continue + print(f"{title} ({len(items)})") + for handoff in items: + overdue = " OVERDUE" if handoff.overdue(now) and key != "done" else "" + print(f" {handoff.counterparty}: {_describe(handoff)}") + print( + f" sent {_when(handoff.sent_at)}, follow up by " + f"{_when(handoff.follow_up_due)}{overdue}" + + (f"; who: {handoff.follow_up}" if key == "needs_follow_up" else "") + ) + print() + return 0 + + +__all__ = ["register_handoff_parser"] diff --git a/packages/flow/openadapt_flow/cli_tasks.py b/packages/flow/openadapt_flow/cli_tasks.py index 8d18591838..eadf134b71 100644 --- a/packages/flow/openadapt_flow/cli_tasks.py +++ b/packages/flow/openadapt_flow/cli_tasks.py @@ -64,6 +64,7 @@ "fleet": "services fleet", "for-each": "run --for-each", "guard": "run --guard", + "handoff": "handoff", "induce": "compile --induce", "intake": "teach --intake", "item-approval": "approve --item", diff --git a/packages/flow/openadapt_flow/handoffs/intake.py b/packages/flow/openadapt_flow/handoffs/intake.py new file mode 100644 index 0000000000..20e9021ad4 --- /dev/null +++ b/packages/flow/openadapt_flow/handoffs/intake.py @@ -0,0 +1,124 @@ +"""Read a handoff back from the other party's system and record what it shows. + +One comparator for every producer. For the item's key, the reader answers +``found`` (with fields), ``not_found``, ``ambiguous`` or ``unreachable``: + +| Read | Observation | +|---|---| +| found, every field matches | ``recorded_as_intended`` | +| found, some fields differ | ``recorded_differently`` with those field ids | +| not_found | unchanged (``sent`` stays ``sent``), reason ``not_found`` | +| ambiguous | unchanged, reason ``ambiguous_key`` | +| unreachable | unchanged, reason ``receiver_unreachable`` | + +A field matches when the value the other side holds normalizes, for the +field's kind, to the same digest as the value we sent (``text`` ignores case +and runs of whitespace, ``code`` ignores separators, ``date`` compares the +calendar date; see :mod:`openadapt_flow.runtime.effects.readback_values`). +A value the other side doesn't hold, or that doesn't parse, differs. + +A record that was confirmed and then can't be found (or now matches two +records) goes back to ``sent``: nothing confirms it any more. An unreachable +receiver changes nothing it had confirmed. +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Optional + +from openadapt_flow.handoffs.ledger import ( + Handoff, + HandoffLedger, + HandoffState, + LedgerError, + Observation, + ReadMethod, + Reason, + Strength, + iso_seconds, + now_utc, +) +from openadapt_flow.handoffs.readers import Reader, ReadResult + + +_REASONS: dict[str, Reason] = { + "not_found": "not_found", + "ambiguous": "ambiguous_key", + "unreachable": "receiver_unreachable", +} + + +def judge( + ledger: HandoffLedger, handoff: Handoff, result: ReadResult, method: ReadMethod +) -> Observation: + """The observation one read gives, without writing it.""" + + previous: HandoffState = handoff.state + observed_at = iso_seconds(now_utc()) + if result.status != "found": + reason: Reason = _REASONS[result.status] + state = previous + if reason != "receiver_unreachable" and previous.startswith("recorded_"): + state = "sent" + last = handoff.last + strength: Strength = ( + "none" if state == "sent" or last is None else last.strength + ) + return Observation( + state=state, + observed_at=observed_at, + read_method=method, + strength=strength, + reason=reason, + evidence_sha256=result.evidence_sha256, + ) + differing: list[str] = [] + digests: dict[str, str] = {} + for field_id, spec in sorted(handoff.fields.items()): + value = result.fields.get(field_id) + seen = ( + None + if value is None + else ledger.field_digest(value, spec.kind, spec.date_order) + ) + digests[field_id] = seen or "missing" + if seen != spec.digest: + differing.append(field_id) + return Observation( + state="recorded_differently" if differing else "recorded_as_intended", + observed_at=observed_at, + read_method=method, + strength="field_readback", + differing_fields=differing, + observed_digests=digests, + evidence_sha256=result.evidence_sha256, + ) + + +def check( + ledger: HandoffLedger, + handoff_id: str, + key: str, + reader: Reader, +) -> Handoff: + """Read the item back through ``reader`` and append the observation.""" + + handoff = ledger.get(handoff_id) + if handoff is None: + raise LedgerError("no such handoff") + if ledger.digest(key) != handoff.key_digest: + raise LedgerError("that key isn't this handoff's key") + if not handoff.fields: + raise LedgerError("this handoff sent no fields to compare") + result = reader.read(key) + return ledger.observe(handoff_id, judge(ledger, handoff, result, reader.read_method)) + + +def needs_follow_up( + ledger: HandoffLedger, now: Optional[datetime] = None +) -> list[Handoff]: + return [h for h in ledger.entries() if h.status(now) == "needs_follow_up"] + + +__all__ = ["check", "judge", "needs_follow_up"] diff --git a/packages/flow/openadapt_flow/handoffs/ledger.py b/packages/flow/openadapt_flow/handoffs/ledger.py index 73daebf9f4..25c68f0317 100644 --- a/packages/flow/openadapt_flow/handoffs/ledger.py +++ b/packages/flow/openadapt_flow/handoffs/ledger.py @@ -111,10 +111,14 @@ class Observation(_Closed): strength: Strength #: Field ids that differ from what we sent (never the values). differing_fields: list[str] = Field(default_factory=list, max_length=64) - #: For each differing field, the digest of the value the other side holds + #: For each compared field, the digest of the value the other side holds #: (``missing`` when it holds none). Private: it opens only in the #: receipt's private openings. observed_digests: dict[str, str] = Field(default_factory=dict) + #: A status-only report accepted the item (a 277CA ``A2``). It still says + #: nothing about the fields, so the state stays ``acknowledged``; the + #: handoff needs no follow-up. + counterparty_accepted: bool = False reason: Optional[Reason] = None #: SHA-256 of the report or read-back body this came from. evidence_sha256: Optional[str] = Field(default=None, pattern=_DIGEST) @@ -140,23 +144,38 @@ class Handoff(_Closed): @property def state(self) -> HandoffState: - return self.observations[-1].state if self.observations else "sent" + evidence = self.evidence + return evidence.state if evidence is not None else "sent" @property def last(self) -> Optional[Observation]: return self.observations[-1] if self.observations else None + @property + def evidence(self) -> Optional[Observation]: + """The latest observation that learned something: an unreachable + receiver says nothing about the record, so it never replaces an + earlier read. The latest one when every read failed.""" + + for observation in reversed(self.observations): + if observation.reason != "receiver_unreachable": + return observation + return self.last + def overdue(self, now: Optional[datetime] = None) -> bool: return parse_iso(self.follow_up_due) <= (now or now_utc()) def status(self, now: Optional[datetime] = None) -> Status: - """``done`` only when recorded as intended and nothing since says - otherwise; ``needs_follow_up`` when it differs, was refused, is + """``done`` only when recorded as intended (or accepted by a + status-only report) and nothing since says otherwise; ``needs_follow_up`` when it differs, was refused, is ambiguous, or is past its follow-up time; else ``waiting``.""" - last = self.last + last = self.evidence reason = last.reason if last is not None else None - if self.state == "recorded_as_intended" and reason is None: + if reason is None and ( + self.state == "recorded_as_intended" + or (last is not None and last.counterparty_accepted) + ): return "done" if ( self.state == "recorded_differently" diff --git a/packages/flow/openadapt_flow/handoffs/line.py b/packages/flow/openadapt_flow/handoffs/line.py new file mode 100644 index 0000000000..a76b011883 --- /dev/null +++ b/packages/flow/openadapt_flow/handoffs/line.py @@ -0,0 +1,223 @@ +"""Turn a handoff into the receipt's ``counterparty_confirmation`` line. + +This is the one place that knows the signed shape +(``openadapt_types.receipt.Confirmation`` in ``record/run/v1``). The ledger +keeps richer, local-only detail; this module maps it onto the closed line +and the values its commitments open to: + +| Ledger | Line | +|---|---| +| ``x12_999``, ``x12_277ca``, ``report_csv``, ``report_text`` | ``read_method: acknowledgment_message`` | +| ``api_readback`` | ``api`` | +| ``ui_readback`` | ``portal_read_back`` | +| ``field_readback`` | ``strength: read_back`` | +| ``status_only`` | ``acknowledgment`` | +| ``sent`` (any) | ``none`` | +| differing field ids | ``differing_count``; each compared field opens as ``:`` with ``:differs`` when it differs | + +The counterparty opens as ``:cp-<16 hex>`` (a digest of its +label, never the label), ``observed_at`` as whole seconds in UTC, and the +reason only when the schema allows it for the state. A reason the schema +doesn't allow there stays in the ledger and is left off the line, so a line +is never inconsistent. + +When ``openadapt_types.receipt`` is installed (it carries the schema from +``record/run/v1`` with confirmations), :func:`build_confirmations` also +commits the values and validates each line against the real model. Without +it, the lines and the values to commit come back unchecked, for a writer +that commits them itself. +""" + +from __future__ import annotations + +import hashlib +from dataclasses import dataclass, field +from typing import Any, Mapping, Optional, Sequence + +from openadapt_flow.handoffs.ledger import Handoff, HandoffLedger + +KIND = "counterparty_confirmation" + +_READ_METHOD = { + "x12_999": "acknowledgment_message", + "x12_277ca": "acknowledgment_message", + "report_csv": "acknowledgment_message", + "report_text": "acknowledgment_message", + "api_readback": "api", + "ui_readback": "portal_read_back", +} +_STRENGTH = {"field_readback": "read_back", "status_only": "acknowledgment"} +#: The schema's rule: which reasons each state may carry. Mirrors +#: ``openadapt_types.receipt.REASONS_FOR_STATE``; a test keeps them equal. +REASONS_FOR_STATE: Mapping[str, frozenset[str]] = { + "sent": frozenset( + { + "rejected_by_counterparty", + "ambiguous_key", + "receiver_unreachable", + "not_found", + "no_answer_by_deadline", + } + ), + "acknowledged": frozenset({"ambiguous_key", "not_found", "no_answer_by_deadline"}), + "recorded_as_intended": frozenset({"conflicting_report"}), + "recorded_differently": frozenset({"conflicting_report"}), +} +#: The read a handoff has before anything came back: nothing, so the line's +#: method is the one the producer will use. +_DEFAULT_METHOD = {"payer_portal": "acknowledgment_message"} + + +@dataclass(frozen=True) +class ConfirmationLine: + """One line and the values its commitments open to (private).""" + + line: dict[str, Any] + #: ``counterparty``, ``observed_at``, ``reason``, ``field.N`` -> value. + values: dict[str, str] + #: Field ids in ``field.N`` order, for the local view only. + field_ids: tuple[str, ...] = field(default=()) + + +def counterparty_ref(handoff: Handoff) -> str: + label = hashlib.sha256(handoff.counterparty.encode("utf-8")).hexdigest()[:16] + return f"{handoff.system_kind}:cp-{label}" + + +def to_line(handoff: Handoff) -> ConfirmationLine: + """The line for ``handoff`` as it stands now (its latest observation).""" + + last = handoff.evidence + state = last.state if last is not None else "sent" + if last is not None: + method = _READ_METHOD[last.read_method] + strength = "none" if state == "sent" else _STRENGTH.get(last.strength, "none") + observed_at = last.observed_at + reason = last.reason if last.reason in REASONS_FOR_STATE[state] else None + else: + method = _DEFAULT_METHOD.get(handoff.system_kind, "api") + strength = "none" + observed_at = handoff.sent_at + reason = None + values: dict[str, str] = { + "counterparty": counterparty_ref(handoff), + "observed_at": observed_at, + } + if reason is not None: + values["reason"] = reason + field_ids: list[str] = [] + differing = 0 + if last is not None and last.strength == "field_readback" and state != "sent": + for index, field_id in enumerate(sorted(handoff.fields)[:32]): + seen = last.observed_digests.get(field_id) or handoff.fields[field_id].digest + if seen == "missing": + seen = hashlib.sha256(b"missing").hexdigest() + differs = field_id in last.differing_fields + differing += differs + values[f"field.{index}"] = ( + f"{field_id[:32]}:{seen}" + (":differs" if differs else "") + ) + field_ids.append(field_id) + line = { + "kind": KIND, + "for_step": handoff.step, + "system_kind": handoff.system_kind, + "read_method": method, + "state": state, + "strength": strength, + "differing_count": differing, + } + return ConfirmationLine(line=line, values=values, field_ids=tuple(field_ids)) + + +def build_confirmations( + handoffs: Sequence[Handoff], *, salt: Optional[Any] = None +) -> tuple[list[dict[str, Any]], dict[str, dict[str, str]]]: + """Signed-shape lines for ``predicate.confirmations`` and their openings. + + Needs ``openadapt_types.receipt`` with confirmations; raises ImportError + without it. Each line is validated against the schema's model. + """ + + from openadapt_types import receipt as r + + lines: list[dict[str, Any]] = [] + openings: dict[str, dict[str, str]] = {} + for index, handoff in enumerate(handoffs): + item = to_line(handoff) + values = {r.confirmation_path(index, k): v for k, v in item.values.items()} + commitments, opened = r.make_openings(values, salt=salt) + line = { + **item.line, + "commitments": {k.split(".", 2)[2]: v for k, v in commitments.items()}, + } + r.Confirmation.model_validate(line) + lines.append(line) + openings.update(opened) + return lines, openings + + +def handoffs_for_run( + report: Mapping[str, Any], ledgers: Sequence[HandoffLedger] +) -> list[Handoff]: + """The handoffs a run made, each with ``step`` set to its write's index. + + A deferred claim check is found by the ``deferred_check`` id on the + step's effect evidence; any other handoff by its ``run_id`` and ``step``. + """ + + by_source: dict[str, Handoff] = {} + by_run: list[Handoff] = [] + run_id = report.get("run_id") + for ledger in ledgers: + for handoff in ledger.entries(): + if handoff.source: + by_source[handoff.source] = handoff + if run_id and handoff.run_id == run_id: + by_run.append(handoff) + found: dict[str, Handoff] = {h.id: h for h in by_run} + results = report.get("results") + for index, result in enumerate(results if isinstance(results, list) else []): + if not isinstance(result, Mapping): + continue + for evidence in result.get("effect_evidence") or []: + entry_id = evidence.get("deferred_check") if isinstance(evidence, Mapping) else None + handoff = by_source.get(entry_id) if entry_id else None + if handoff is not None: + found[handoff.id] = handoff.model_copy(update={"step": index}) + return sorted(found.values(), key=lambda h: (h.step or 0, h.sent_at, h.id)) + + +def attach_confirmations( + statement: dict[str, Any], + openings: dict[str, dict[str, str]], + handoffs: Sequence[Handoff], + *, + salt: Optional[Any] = None, +) -> tuple[dict[str, Any], dict[str, dict[str, str]]]: + """Put the handoffs' lines into a ``record/run/v1`` statement before it + is signed: ``predicate.confirmations`` and their openings. A handoff + whose step has no line on the statement is attached without a step.""" + + steps = {line["step"] for line in statement["predicate"].get("lines", [])} + placed = [ + h if h.step in steps else h.model_copy(update={"step": None}) + for h in handoffs + ] + lines, opened = build_confirmations(placed, salt=salt) + out = {**statement, "predicate": {**statement["predicate"], "confirmations": lines}} + if not lines: + out["predicate"].pop("confirmations") + return out, {**openings, **opened} + + +__all__ = [ + "KIND", + "attach_confirmations", + "handoffs_for_run", + "REASONS_FOR_STATE", + "ConfirmationLine", + "build_confirmations", + "counterparty_ref", + "to_line", +] diff --git a/packages/flow/openadapt_flow/handoffs/payer.py b/packages/flow/openadapt_flow/handoffs/payer.py new file mode 100644 index 0000000000..e84cf8961f --- /dev/null +++ b/packages/flow/openadapt_flow/handoffs/payer.py @@ -0,0 +1,231 @@ +"""Payer acknowledgments as handoffs: the deferred claim check, seen from +the other side. + +A claim saved with a deferred check (``effects.kind: deferred_report``) is a +handoff to the payer. Its handoff lives beside the deferred ledger, in +``/handoffs``, with the same id digits (``deferred:`` -> +``handoff:``). ``deferred settle`` records what each report says about +it, including a row that settles nothing yet: + +| The report says | Handoff | +|---|---| +| nothing yet | ``sent``, follow-up due at the check's deadline | +| received (999 ``A`` or ``E``; 277CA ``A1``; any other pending status) | ``acknowledged`` | +| accepted (277CA ``A2``) | ``acknowledged``, accepted: no follow-up | +| rejected (999 ``R``/``M``/``W``/``X``; 277CA ``A3``/``A4``/``A6``/``A7``/``A8``) | ``sent``, reason ``rejected_by_counterparty`` | +| two rows that disagree | ``acknowledged``, reason ``conflicting_report`` | +| two waiting claims on one key | unchanged, reason ``ambiguous_key`` | +| nothing by the deadline | unchanged, reason ``no_answer_by_deadline`` | + +An acknowledgment is never ``recorded_as_intended``: a 277CA ``A2`` says the +payer accepted the claim into adjudication, not what it recorded for each +field. Only a read-back that compares the fields says that. + +Only the X12 formats are a counterparty's own answer. A CSV export or a +saved status page may be the sending system's own report, so those entries +are not handoffs unless the caller says they are (``exports=True``). + +The deferred check's own settlement is unchanged: this only listens. +""" + +from __future__ import annotations + +from datetime import datetime +from pathlib import Path +from typing import Optional + +from openadapt_flow.handoffs.ledger import ( + Handoff, + HandoffLedger, + Observation, + ReadMethod, + iso_seconds, + now_utc, + parse_iso, +) +from openadapt_flow.reports.parse import ReportRow +from openadapt_flow.runtime.effects.deferred_report import PendingCheck, PendingLedger + +COUNTERPARTY_FORMATS = ("x12-999", "x12-277ca") +EXPORT_FORMATS = ("csv", "text") +_METHOD: dict[str, ReadMethod] = { + "x12-999": "x12_999", + "x12-277ca": "x12_277ca", + "csv": "report_csv", + "text": "report_text", +} + + +def handoff_ledger(pending: PendingLedger) -> HandoffLedger: + return HandoffLedger(Path(pending.directory) / "handoffs") + + +def handoff_id(entry: PendingCheck) -> str: + return "handoff:" + entry.id.split(":", 1)[1] + + +def _is_handoff(entry: PendingCheck, exports: bool) -> bool: + formats = COUNTERPARTY_FORMATS + (EXPORT_FORMATS if exports else ()) + return entry.report_format in formats + + +def as_handoff(entry: PendingCheck, *, follow_up: str = "billing") -> Handoff: + return Handoff( + id=handoff_id(entry), + sent_at=iso_seconds(parse_iso(entry.created_at)), + follow_up_due=iso_seconds(parse_iso(entry.deadline)), + counterparty=entry.describe[:80], + system_kind="payer_portal", + follow_up=follow_up, + key_digest=entry.key_digest, + source=entry.id, + ) + + +def observation_for( + current: Handoff, + row: Optional[ReportRow], + waiting_on_key: int, + method: ReadMethod, + *, + evidence_sha256: Optional[str], + now: Optional[datetime] = None, +) -> Observation: + """What one report row (or the deadline) says about a payer handoff.""" + + at = iso_seconds(now or now_utc()) + previous = current.state + last = current.evidence + kept_strength = "none" if previous == "sent" or last is None else last.strength + if row is None: + return Observation( + state=previous, + observed_at=at, + read_method=last.read_method if last is not None else method, + strength=kept_strength, + reason="no_answer_by_deadline", + ) + if waiting_on_key > 1: + return Observation( + state=previous, + observed_at=at, + read_method=method, + strength=kept_strength, + reason="ambiguous_key", + evidence_sha256=evidence_sha256, + ) + if row.status == "rejected": + return Observation( + state="sent", + observed_at=at, + read_method=method, + strength="none", + reason="rejected_by_counterparty", + evidence_sha256=evidence_sha256, + ) + return Observation( + state="acknowledged", + observed_at=at, + read_method=method, + strength="status_only", + reason="conflicting_report" if row.status == "conflicting" else None, + counterparty_accepted=row.status == "accepted", + evidence_sha256=evidence_sha256, + ) + + +def _same(a: Observation, b: Observation) -> bool: + keep = ("state", "reason", "counterparty_accepted", "evidence_sha256") + return all(getattr(a, k) == getattr(b, k) for k in keep) + + +class SettleRecorder: + """The observer ``PendingLedger.settle`` calls; records into handoffs. + + The same report read twice adds nothing the second time. + """ + + def __init__( + self, + pending: PendingLedger, + report_format: str, + report_sha256: Optional[str], + *, + exports: bool = False, + follow_up: str = "billing", + ) -> None: + self.handoffs = handoff_ledger(pending) + self.method = _METHOD.get(report_format, "report_text") + self.report_sha256 = report_sha256 + self.exports = exports + self.follow_up = follow_up + self.recorded = 0 + + def __call__( + self, entry: PendingCheck, row: Optional[ReportRow], waiting_on_key: int + ) -> None: + if not _is_handoff(entry, self.exports): + return + current = self.handoffs.adopt(as_handoff(entry, follow_up=self.follow_up)) + observation = observation_for( + current, + row, + waiting_on_key, + self.method, + evidence_sha256=self.report_sha256, + ) + if current.last is not None and _same(current.last, observation): + return + self.handoffs.observe(current.id, observation) + self.recorded += 1 + + +def sync( + pending: PendingLedger, *, exports: bool = False, follow_up: str = "billing" +) -> HandoffLedger: + """Make sure every deferred claim check has its handoff. + + A claim that settled before its handoff existed gets one observation from + the settlement (accepted, rejected, expired); the settlement's reason + text names which. + """ + + handoffs = handoff_ledger(pending) + for entry in pending.entries(): + if not _is_handoff(entry, exports): + continue + current = handoffs.adopt(as_handoff(entry, follow_up=follow_up)) + if current.observations or entry.state == "waiting": + continue + method = _METHOD.get(entry.report_format, "report_text") + at = parse_iso(entry.settled_at) if entry.settled_at else None + reason_text = (entry.reason or "").casefold() + if entry.state == "verified": + row: Optional[ReportRow] = ReportRow("", "accepted", entry.code or "") + count = 1 + elif entry.code == "deadline": + row, count = None, 0 + elif "same report key" in reason_text: + row, count = ReportRow("", "pending", entry.code or ""), 2 + elif "rejected" in reason_text: + row, count = ReportRow("", "rejected", entry.code or ""), 1 + else: + row, count = ReportRow("", "conflicting", entry.code or ""), 1 + handoffs.observe( + current.id, + observation_for( + current, row, count, method, evidence_sha256=entry.settled_by, now=at + ), + ) + return handoffs + + +__all__ = [ + "COUNTERPARTY_FORMATS", + "SettleRecorder", + "as_handoff", + "handoff_id", + "handoff_ledger", + "observation_for", + "sync", +] diff --git a/packages/flow/openadapt_flow/handoffs/readers.py b/packages/flow/openadapt_flow/handoffs/readers.py new file mode 100644 index 0000000000..e9c6caf250 --- /dev/null +++ b/packages/flow/openadapt_flow/handoffs/readers.py @@ -0,0 +1,213 @@ +"""Readers: look up one item in the other party's system. + +A reader takes the item's key and answers with what the other system holds +for it, as flat ``field id -> value`` text: + +- ``found``: exactly one record has the key; +- ``not_found``: none does (it never arrived, or not yet); +- ``ambiguous``: more than one does, so none of them confirms anything; +- ``unreachable``: the read failed (network, a 4xx or 5xx, an expired + token, a body that isn't what the profile says). Never read as + ``not_found``. + +What to read is a profile (data), not code. :class:`FhirSearchProfile` reads +any FHIR R4 server: a search by one parameter and a path per field. A UI +read-back plugs in the same way, by returning a :class:`ReadResult`. +""" + +from __future__ import annotations + +import hashlib +import json +import os +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Literal, Mapping, Optional, Protocol + +from pydantic import BaseModel, ConfigDict, Field + +from openadapt_flow.fhir_read import fhir_read_headers, next_page_url +from openadapt_flow.handoffs.ledger import ReadMethod +from openadapt_flow.runtime.effects.fhir import extract_path +from openadapt_flow.runtime.effects.readback_values import ValueKind + +ReadStatus = Literal["found", "not_found", "ambiguous", "unreachable"] + + +@dataclass(frozen=True) +class ReadResult: + status: ReadStatus + #: For ``found``: each profile field's value as text, None when absent. + fields: dict[str, Optional[str]] = field(default_factory=dict) + #: SHA-256 of the body read, for the observation's evidence digest. + evidence_sha256: Optional[str] = None + + +class Reader(Protocol): + read_method: ReadMethod + + def read(self, key: str) -> ReadResult: ... + + +class FieldPath(BaseModel): + model_config = ConfigDict(extra="forbid") + + #: Dotted path in the resource (``birthDate``, ``name.family``, + #: ``telecom[system=phone].value``). + path: str + kind: ValueKind = "text" + date_order: Optional[Literal["dmy", "mdy"]] = None + + +class FhirSearchProfile(BaseModel): + """How to find one item in a FHIR R4 server and read its fields.""" + + model_config = ConfigDict(extra="forbid") + + resource: str = Field(pattern=r"^[A-Z][A-Za-z]{1,63}$") + #: The search parameter that finds the item by its key (``identifier``). + key_param: str = Field(pattern=r"^[a-z][a-z0-9_:.-]{0,63}$") + #: How the key is written into the search (``urn:x|{key}``). + key_template: str = "{key}" + #: Where each returned record holds the key. Every record the search + #: returns is checked here too, so a server that ignores the search + #: parameter (and returns everything) can't make a wrong record "found". + key_path: str + fields: dict[str, FieldPath] = Field(min_length=1, max_length=64) + #: The other party, for people. + counterparty: str = Field(default="the receiver", max_length=80) + system_kind: Literal[ + "ehr", + "payer_portal", + "bank", + "erp", + "crm", + "government_portal", + "email", + "other", + ] = "other" + + @classmethod + def load(cls, path: str | Path) -> "FhirSearchProfile": + import yaml + + return cls.model_validate(yaml.safe_load(Path(path).read_text())) + + +def _text(value: Any) -> Optional[str]: + if value is None or isinstance(value, (dict, list)): + return None + return str(value) + + +class FhirSearchReader: + """Read one item from a FHIR R4 server by a profile. + + ``base_url`` is the FHIR base; the token comes from ``token`` or the + environment variable ``token_env`` and is never logged. Follows ``next`` + links on the same origin, so a second match on page two still counts. + """ + + read_method: ReadMethod = "api_readback" + + def __init__( + self, + profile: FhirSearchProfile, + base_url: str, + *, + token: Optional[str] = None, + token_env: Optional[str] = None, + verify_tls: bool = True, + timeout: float = 20.0, + client: Any = None, + ) -> None: + self.profile = profile + self.base_url = base_url.rstrip("/") + self._token = token if token is not None else ( + os.environ.get(token_env) if token_env else None + ) + self._verify = verify_tls + self._timeout = timeout + self._client = client + + def _get(self, url: str, params: Optional[Mapping[str, str]]) -> Any: + headers = fhir_read_headers() + if self._token: + headers["Authorization"] = f"Bearer {self._token}" + if self._client is not None: + return self._client.get(url, params=params, headers=headers) + import httpx + + with httpx.Client(verify=self._verify, timeout=self._timeout) as client: + return client.get(url, params=params, headers=headers) + + def read(self, key: str) -> ReadResult: + from urllib.parse import urlsplit + + url: Optional[str] = f"{self.base_url}/{self.profile.resource}" + params: Optional[dict[str, str]] = { + self.profile.key_param: self.profile.key_template.format(key=key) + } + origin = urlsplit(self.base_url)[:2] + matches: list[dict[str, Any]] = [] + digest = hashlib.sha256() + pages = 0 + while url is not None: + pages += 1 + if pages > 20: + return ReadResult("unreachable") + try: + response = self._get(url, params) + except Exception: # noqa: BLE001 - any transport failure + return ReadResult("unreachable") + if not 200 <= int(getattr(response, "status_code", 0)) < 300: + return ReadResult("unreachable") + body = response.content if hasattr(response, "content") else b"" + digest.update(body if isinstance(body, bytes) else str(body).encode()) + try: + bundle = json.loads(body) + except (TypeError, ValueError): + return ReadResult("unreachable") + if not isinstance(bundle, dict) or bundle.get("resourceType") != "Bundle": + return ReadResult("unreachable") + entries = bundle.get("entry", []) + if not isinstance(entries, list): + return ReadResult("unreachable") + for entry in entries: + resource = entry.get("resource") if isinstance(entry, dict) else None + if not isinstance(resource, dict): + return ReadResult("unreachable") + if resource.get("resourceType") == "OperationOutcome": + continue + if resource.get("resourceType") != self.profile.resource: + return ReadResult("unreachable") + if _text(extract_path(resource, self.profile.key_path)) == key: + matches.append(resource) + try: + url = next_page_url(bundle) + except ValueError: + return ReadResult("unreachable") + if url is not None and urlsplit(url)[:2] != origin: + return ReadResult("unreachable") + params = None + evidence = digest.hexdigest() + if not matches: + return ReadResult("not_found", evidence_sha256=evidence) + if len(matches) > 1: + return ReadResult("ambiguous", evidence_sha256=evidence) + record = matches[0] + fields = { + field_id: _text(extract_path(record, spec.path)) + for field_id, spec in self.profile.fields.items() + } + return ReadResult("found", fields=fields, evidence_sha256=evidence) + + +__all__ = [ + "FhirSearchProfile", + "FhirSearchReader", + "FieldPath", + "ReadResult", + "ReadStatus", + "Reader", +] diff --git a/packages/flow/openadapt_flow/runtime/effects/deferred_report.py b/packages/flow/openadapt_flow/runtime/effects/deferred_report.py index 62cd0bb3e2..18bf82c932 100644 --- a/packages/flow/openadapt_flow/runtime/effects/deferred_report.py +++ b/packages/flow/openadapt_flow/runtime/effects/deferred_report.py @@ -43,7 +43,7 @@ from dataclasses import dataclass from datetime import datetime, timedelta, timezone from pathlib import Path -from typing import Any, Iterator, Literal, Mapping, Optional +from typing import Any, Callable, Iterator, Literal, Mapping, Optional from pydantic import BaseModel, ConfigDict, Field, model_validator @@ -137,6 +137,11 @@ class PendingCheck(BaseModel): UI_READBACK_FORMAT = "ui-readback" +#: Hears each waiting entry a report mentions: ``(entry, row, n)``, or +#: ``(entry, None, 0)`` when the entry expired. +SettleObserver = Callable[["PendingCheck", Optional[ReportRow], int], None] + + @dataclass(frozen=True) class Settlement: id: str @@ -359,6 +364,7 @@ def settle( *, issued_at: Optional[datetime] = None, now: Optional[datetime] = None, + observer: Optional[SettleObserver] = None, ) -> list[Settlement]: """Expire overdue entries, then settle waiting ones against a report. @@ -368,6 +374,13 @@ def settle( or the caller's report time for a CSV or text report), and only entries waiting on that exact report format. ``report_text`` None only expires entries. + + ``observer``, when given, hears about every waiting entry the report + mentions, including a row that is still pending (a 999 ``A``, a + 277CA ``A1``), which settles nothing: ``observer(entry, row, n)`` + with ``n`` the number of waiting entries on that key, and + ``observer(entry, None, 0)`` for an entry that expired. It never + changes what settles (:mod:`openadapt_flow.handoffs.payer`). """ moment = now or _now() @@ -398,6 +411,8 @@ def settle( entry.id, "reconciliation_required", "deadline", reason ) ) + if observer is not None: + observer(entry, None, 0) else: still.append(entry) if report_text is None or fmt is None: @@ -424,6 +439,9 @@ def settle( by_digest.setdefault(entry.key_digest, []).append(entry) for digest, entries in by_digest.items(): row = rows.get(digest) + if row is not None and observer is not None: + for entry in entries: + observer(entry, row, len(entries)) if row is None or row.status == "pending": continue if len(entries) > 1: @@ -615,12 +633,13 @@ def settle_report_file( fmt: ReportFormat, *, issued_at: Optional[datetime] = None, + observer: Optional[SettleObserver] = None, ) -> list[Settlement]: """Settle against a report file. A CSV or text report needs its issue time (``issued_at``); an X12 report carries its own.""" text = Path(report_path).read_text(encoding="utf-8", errors="strict") - return ledger.settle(text, fmt, issued_at=issued_at) + return ledger.settle(text, fmt, issued_at=issued_at, observer=observer) __all__ = [ diff --git a/packages/flow/tests/test_handoffs.py b/packages/flow/tests/test_handoffs.py new file mode 100644 index 0000000000..775ec1ebc6 --- /dev/null +++ b/packages/flow/tests/test_handoffs.py @@ -0,0 +1,518 @@ +"""Handoffs and counterparty confirmations: unit tests. + +Two producers over one mechanism: the deferred claim check seen as payer +handoffs (synthetic X12 999 and 277CA), and a field read-back from the +receiving system (a fake reader here; the real OpenEMR receiver is in +``test_handoffs_live_openemr.py``). Synthetic data only. +""" + +from __future__ import annotations + +import json +from datetime import datetime, timedelta, timezone +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from openadapt_flow.handoffs import intake, line, payer +from openadapt_flow.handoffs.ledger import HandoffLedger, LedgerError +from openadapt_flow.handoffs.readers import ( + FhirSearchProfile, + FhirSearchReader, + ReadResult, +) +from openadapt_flow.reports.parse import ReportFormat +from openadapt_flow.runtime.effects.deferred_report import PendingLedger +from tests.test_deferred_report import ( + ACK_999, + ACK_277CA, + FMT_277, + HASH, + SETTLE_AT, + T0, +) + +FMT_999 = ReportFormat(format="x12-999") +LATER = SETTLE_AT + timedelta(days=5) + + +# -- payer acknowledgments -------------------------------------------------------- + + +def _claims(tmp_path: Path, fmt: ReportFormat, keys: list[str], hours: float = 48): + pending = PendingLedger(tmp_path / "deferred") + entries = { + key: pending.add( + key=key, + effect_contract_hash=HASH, + fmt=fmt, + describe=f"payer {fmt.format}", + deadline_hours=hours, + now=T0, + ) + for key in keys + } + return pending, entries + + +def _settle(pending: PendingLedger, text, fmt, now=SETTLE_AT): + sha = None if text is None else "0" * 64 + recorder = payer.SettleRecorder(pending, fmt.format if fmt else "", sha) + settled = pending.settle(text, fmt, now=now, observer=recorder) + return settled, payer.handoff_ledger(pending) + + +def _h(handoffs: HandoffLedger, entry): + return handoffs.get(payer.handoff_id(entry)) + + +def test_a_submitted_claim_is_sent_with_follow_up_due_at_the_deadline(tmp_path): + pending, entries = _claims(tmp_path, FMT_277, ["CLM-1001"]) + handoffs = payer.sync(pending) + h = _h(handoffs, entries["CLM-1001"]) + assert h.state == "sent" + assert h.follow_up_due == "2026-10-20T06:00:00Z" + assert h.status(SETTLE_AT) == "waiting" + assert h.status(LATER) == "needs_follow_up" + assert h.system_kind == "payer_portal" + assert "CLM-1001" not in (handoffs.directory / f"{h.id[8:]}.json").read_text() + + +def test_277ca_received_accepted_and_rejected(tmp_path): + pending, e = _claims(tmp_path, FMT_277, ["CLM-1001", "CLM-1002", "CLM-1003"]) + settled, handoffs = _settle(pending, ACK_277CA, FMT_277) + # The deferred check settles exactly as before. + assert {s.id: s.state for s in settled} == { + e["CLM-1001"].id: "verified", + e["CLM-1002"].id: "reconciliation_required", + } + accepted = _h(handoffs, e["CLM-1001"]) + rejected = _h(handoffs, e["CLM-1002"]) + received = _h(handoffs, e["CLM-1003"]) + assert (accepted.state, accepted.last.counterparty_accepted) == ("acknowledged", True) + assert accepted.status(LATER) == "done" + assert (rejected.state, rejected.last.reason) == ("sent", "rejected_by_counterparty") + assert rejected.status(SETTLE_AT) == "needs_follow_up" + assert (received.state, received.last.reason) == ("acknowledged", None) + assert received.status(SETTLE_AT) == "waiting" + assert received.status(LATER) == "needs_follow_up" + for h in (accepted, rejected, received): + assert h.last.read_method == "x12_277ca" + assert h.state != "recorded_as_intended" # status only, never fields + + +def test_999_accepted_file_is_acknowledged_and_rejected_file_is_not(tmp_path): + pending, e = _claims(tmp_path, FMT_999, ["17:0001", "17:0002"]) + _, handoffs = _settle(pending, ACK_999, FMT_999) + ok = _h(handoffs, e["17:0001"]) + bad = _h(handoffs, e["17:0002"]) + assert (ok.state, ok.last.counterparty_accepted) == ("acknowledged", False) + assert (bad.state, bad.last.reason) == ("sent", "rejected_by_counterparty") + + +def test_the_same_report_twice_adds_nothing(tmp_path): + pending, e = _claims(tmp_path, FMT_277, ["CLM-1003"]) + _settle(pending, ACK_277CA, FMT_277) + _, handoffs = _settle(pending, ACK_277CA, FMT_277) + assert len(_h(handoffs, e["CLM-1003"]).observations) == 1 + + +def test_no_answer_by_the_deadline_keeps_the_state_and_needs_follow_up(tmp_path): + pending, e = _claims(tmp_path, FMT_277, ["CLM-1003", "CLM-9999"], hours=8) + _settle(pending, ACK_277CA, FMT_277) # CLM-1003 received (A1) + _, handoffs = _settle(pending, None, None, now=LATER) + received = _h(handoffs, e["CLM-1003"]) + silent = _h(handoffs, e["CLM-9999"]) + assert (received.state, received.last.reason) == ( + "acknowledged", + "no_answer_by_deadline", + ) + assert (silent.state, silent.last.reason) == ("sent", "no_answer_by_deadline") + assert received.status(LATER) == silent.status(LATER) == "needs_follow_up" + + +def test_two_claims_on_one_key_are_ambiguous(tmp_path): + pending, _ = _claims(tmp_path, FMT_277, ["CLM-1001"]) + twin = pending.add( + key="CLM-1001", + effect_contract_hash=HASH, + fmt=FMT_277, + describe="payer x12-277ca", + deadline_hours=48, + now=T0, + ) + _, handoffs = _settle(pending, ACK_277CA, FMT_277) + h = _h(handoffs, twin) + assert (h.state, h.last.reason) == ("sent", "ambiguous_key") + assert h.status(SETTLE_AT) == "needs_follow_up" + + +def test_sync_maps_claims_settled_before_handoffs_existed(tmp_path): + pending, e = _claims(tmp_path, FMT_277, ["CLM-1001", "CLM-1002"]) + pending.settle(ACK_277CA, FMT_277, now=SETTLE_AT) # no observer + handoffs = payer.sync(pending) + assert _h(handoffs, e["CLM-1001"]).last.counterparty_accepted + assert _h(handoffs, e["CLM-1002"]).last.reason == "rejected_by_counterparty" + + +def test_export_reports_are_not_counterparty_handoffs_by_default(tmp_path): + fmt = ReportFormat(format="csv", key_column="k", status_column="s", accept=["ok"]) + pending, _ = _claims(tmp_path, fmt, ["ORD-1"]) + assert payer.sync(pending).entries() == [] + assert len(payer.sync(pending, exports=True).entries()) == 1 + + +# -- read-back of what the receiver recorded ----------------------------------- + + +FIELDS = { + "given_name": ("Avery", "text"), + "family_name": ("Quill", "text"), + "birth_date": ("1984-03-09", "date"), + "sex": ("female", "code"), +} +RECORD = { + "given_name": "Avery", + "family_name": "Quill", + "birth_date": "1984-03-09", + "sex": "female", +} + + +class Fake: + read_method = "api_readback" + + def __init__(self, result: ReadResult) -> None: + self.result = result + + def read(self, key: str) -> ReadResult: + return self.result + + +def _referral(tmp_path: Path, key: str = "REF-0001", hours: float = 24): + ledger = HandoffLedger(tmp_path / "handoffs") + h = ledger.send( + key, + FIELDS, + counterparty="receiving clinic", + system_kind="ehr", + follow_up="referrals desk", + follow_up_hours=hours, + run_id="run-1", + step=2, + ) + return ledger, h + + +def _found(**changes): + return ReadResult("found", fields={**RECORD, **changes}, evidence_sha256="1" * 64) + + +def test_recorded_as_intended(tmp_path): + ledger, h = _referral(tmp_path) + after = intake.check(ledger, h.id, "REF-0001", Fake(_found())) + assert after.state == "recorded_as_intended" + assert after.status() == "done" + assert after.last.strength == "field_readback" + + +@pytest.mark.parametrize( + "changes,differs", + [ + ({"birth_date": "1984-03-10"}, ["birth_date"]), + ({"birth_date": "1984-09-03"}, ["birth_date"]), # day and month swapped + ({"family_name": "Quil"}, ["family_name"]), + ({"sex": "male"}, ["sex"]), + ({"given_name": None}, ["given_name"]), # dropped field + ({"birth_date": "unknown"}, ["birth_date"]), # unparseable + ({"birth_date": "1984-03-10", "sex": "male"}, ["birth_date", "sex"]), + ], +) +def test_recorded_differently_names_only_the_field_ids(tmp_path, changes, differs): + ledger, h = _referral(tmp_path) + after = intake.check(ledger, h.id, "REF-0001", Fake(_found(**changes))) + assert after.state == "recorded_differently" + assert after.last.differing_fields == differs + assert after.status() == "needs_follow_up" + text = (ledger.directory / f"{h.id[8:]}.json").read_text() + for value in [*RECORD.values(), *changes.values(), "REF-0001"]: + if value and len(value) > 3: + assert value not in text + + +@pytest.mark.parametrize( + "changes", + [ + {"given_name": "AVERY", "family_name": " quill "}, + {"birth_date": "1984-03-09T00:00:00"}, + {"birth_date": "March 9, 1984"}, + {"sex": "FEMALE"}, + ], +) +def test_benign_formatting_is_no_false_alarm(tmp_path, changes): + ledger, h = _referral(tmp_path) + after = intake.check(ledger, h.id, "REF-0001", Fake(_found(**changes))) + assert after.state == "recorded_as_intended", after.last.differing_fields + + +def test_never_arrived_stays_sent_and_is_due(tmp_path): + ledger, h = _referral(tmp_path, hours=1) + after = intake.check(ledger, h.id, "REF-0001", Fake(ReadResult("not_found"))) + assert (after.state, after.last.reason) == ("sent", "not_found") + assert after.status() == "waiting" + assert after.status(datetime.now(timezone.utc) + timedelta(hours=2)) == ( + "needs_follow_up" + ) + + +def test_ambiguous_and_unreachable_confirm_nothing(tmp_path): + ledger, h = _referral(tmp_path) + after = intake.check(ledger, h.id, "REF-0001", Fake(ReadResult("ambiguous"))) + assert (after.state, after.last.reason) == ("sent", "ambiguous_key") + assert after.status() == "needs_follow_up" + after = intake.check(ledger, h.id, "REF-0001", Fake(ReadResult("unreachable"))) + assert after.last.reason == "receiver_unreachable" + assert after.state == "sent" + + +def test_unreachable_never_undoes_a_confirmation_but_not_found_does(tmp_path): + ledger, h = _referral(tmp_path) + intake.check(ledger, h.id, "REF-0001", Fake(_found())) + after = intake.check(ledger, h.id, "REF-0001", Fake(ReadResult("unreachable"))) + assert after.state == "recorded_as_intended" and after.status() == "done" + after = intake.check(ledger, h.id, "REF-0001", Fake(ReadResult("not_found"))) + assert after.state == "sent" + + +def test_the_ledger_refuses_what_it_could_never_compare(tmp_path): + ledger = HandoffLedger(tmp_path / "handoffs") + with pytest.raises(LedgerError): + ledger.send("K", {"d": ("03/04/2020", "date")}, counterparty="x", follow_up_hours=1) + ledger.send("K", {"d": ("2020-03-04", "date")}, counterparty="x", follow_up_hours=1) + with pytest.raises(LedgerError): # a second open handoff on the same key + ledger.send("K", {"d": ("2020-03-04", "date")}, counterparty="x", follow_up_hours=1) + ledger2, h = _referral(tmp_path / "b") + with pytest.raises(LedgerError): + intake.check(ledger2, h.id, "REF-OTHER", Fake(_found())) + assert ledger2.directory.stat().st_mode & 0o777 == 0o700 + + +# -- the FHIR reader --------------------------------------------------------------- + +PROFILE = FhirSearchProfile( + resource="Patient", + key_param="identifier", + key_path="identifier.value", + fields={ + "family_name": {"path": "name.family"}, + "birth_date": {"path": "birthDate", "kind": "date"}, + }, +) + + +def _patient(key: str, family: str = "Quill") -> dict: + return { + "resourceType": "Patient", + "identifier": [{"value": key}], + "name": [{"family": family}], + "birthDate": "1984-03-09", + } + + +class Client: + def __init__(self, *pages, status: int = 200) -> None: + self.pages = list(pages) + self.status = status + self.calls: list = [] + + def get(self, url, params=None, headers=None): + self.calls.append((url, params, headers)) + body = self.pages.pop(0) if self.pages else {} + return SimpleNamespace(status_code=self.status, content=json.dumps(body).encode()) + + +def _bundle(*resources, next_url=None): + out = {"resourceType": "Bundle", "entry": [{"resource": r} for r in resources]} + if next_url: + out["link"] = [{"relation": "next", "url": next_url}] + return out + + +def _reader(client): + return FhirSearchReader(PROFILE, "https://receiver.test/fhir", token="t", client=client) + + +def test_fhir_reader_found_not_found_and_key_check(): + found = _reader(Client(_bundle(_patient("REF-1")))).read("REF-1") + assert found.status == "found" + assert found.fields == {"family_name": "Quill", "birth_date": "1984-03-09"} + # A server that ignores the search parameter returns everyone: only the + # record that carries the key counts. + noisy = _reader(Client(_bundle(_patient("REF-2"), _patient("REF-1")))).read("REF-1") + assert noisy.status == "found" + assert _reader(Client(_bundle(_patient("REF-2")))).read("REF-1").status == ( + "not_found" + ) + + +def test_fhir_reader_ambiguous_across_pages_and_fails_closed(): + client = Client( + _bundle(_patient("REF-1"), next_url="https://receiver.test/fhir/Patient?p=2"), + _bundle(_patient("REF-1", "Other")), + ) + assert _reader(client).read("REF-1").status == "ambiguous" + assert client.calls[0][2]["Authorization"] == "Bearer t" + assert _reader(Client(_bundle(), status=401)).read("REF-1").status == "unreachable" + assert _reader(Client({"resourceType": "Patient"})).read("REF-1").status == ( + "unreachable" + ) + off_origin = Client(_bundle(next_url="https://elsewhere.test/fhir/Patient?p=2")) + assert _reader(off_origin).read("REF-1").status == "unreachable" + + +# -- the receipt line ---------------------------------------------------------------- + + +def test_lines_follow_the_schema_rules(tmp_path): + ledger, h = _referral(tmp_path) + assert line.to_line(h).line["state"] == "sent" + assert line.to_line(h).line["strength"] == "none" + h = intake.check(ledger, h.id, "REF-0001", Fake(_found(birth_date="1984-03-10"))) + item = line.to_line(h) + assert item.line == { + "kind": "counterparty_confirmation", + "for_step": 2, + "system_kind": "ehr", + "read_method": "api", + "state": "recorded_differently", + "strength": "read_back", + "differing_count": 1, + } + assert item.values["counterparty"].startswith("ehr:cp-") + assert [v.endswith(":differs") for k, v in sorted(item.values.items()) if k.startswith("field.")] == [ + True, + False, + False, + False, + ] + pending, e = _claims(tmp_path, FMT_277, ["CLM-1001", "CLM-1002"]) + _, handoffs = _settle(pending, ACK_277CA, FMT_277) + accepted = line.to_line(_h(handoffs, e["CLM-1001"])).line + rejected = line.to_line(_h(handoffs, e["CLM-1002"])) + assert (accepted["state"], accepted["read_method"], accepted["strength"]) == ( + "acknowledged", + "acknowledgment_message", + "acknowledgment", + ) + assert rejected.line["state"] == "sent" + assert rejected.values["reason"] == "rejected_by_counterparty" + + +def test_lines_validate_against_the_receipt_schema_and_sign(tmp_path): + r = pytest.importorskip("openadapt_types.receipt") + if not hasattr(r, "Confirmation"): + pytest.skip("openadapt-types without counterparty confirmations") + pytest.importorskip("cryptography") + assert {k: set(v) for k, v in line.REASONS_FOR_STATE.items()} == { + k: set(v) for k, v in r.REASONS_FOR_STATE.items() + } + from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat + import base64 + + from openadapt_flow.receipt_record import build_statement + + ledger, h = _referral(tmp_path) + states = [h] + states.append(intake.check(ledger, h.id, "REF-0001", Fake(_found()))) + ledger2, h2 = _referral(tmp_path / "2") + states.append( + intake.check(ledger2, h2.id, "REF-0001", Fake(_found(sex="male"))) + ) + pending, e = _claims(tmp_path, FMT_277, ["CLM-1001", "CLM-1002", "CLM-1003"]) + _, handoffs = _settle(pending, ACK_277CA, FMT_277) + states += [_h(handoffs, x) for x in e.values()] + report = { + "run_id": "run-1", + "execution_outcome": "VERIFIED", + "results": [ + {"ok": True}, + {"ok": True}, + {"ok": True, "effect_verified": True, "effect_field_checks": [1]}, + ], + } + statement, openings = build_statement(report, "a" * 64, flow_version="3.4.0") + statement, openings = line.attach_confirmations(statement, openings, states) + key = Ed25519PrivateKey.generate() + raw = key.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw) + kid = r.key_id(raw) + envelope = r.sign_statement(statement, [(kid, key.sign)]) + registry = r.parse_registry( + { + "schema": r.REGISTRY_SCHEMA, + "keys": [ + { + "key_id": kid, + "public_key": base64.b64encode(raw).decode(), + "role": "this_computer", + } + ], + } + ) + result = r.verify_receipt( + envelope, registry, openings=r.private_openings(envelope, openings) + ) + assert result.ok, (result.reason, result.detail) + assert len(result.confirmation_lines) == 6 + assert result.confirmation_lines[1].startswith("Confirmed in the other party's system") + assert "1 field differs" in result.confirmation_lines[2] + assert result.confirmation_lines[3].startswith("Acknowledged by the other party") + assert result.confirmation_lines[4].startswith("Sent to the other party") + + +# -- the CLI ----------------------------------------------------------------------- + + +def test_handoff_list_groups_by_who_must_follow_up(tmp_path, capsys): + from openadapt_flow.__main__ import main + + ledger, h = _referral(tmp_path) + intake.check(ledger, h.id, "REF-0001", Fake(_found(birth_date="1984-03-10"))) + pending, _ = _claims(tmp_path, FMT_277, ["CLM-1001", "CLM-1002", "CLM-1003"]) + _settle(pending, ACK_277CA, FMT_277) + code = main( + ["handoff", "list", "--ledger", str(ledger.directory), "--ledger", str(pending.directory)] + ) + out = capsys.readouterr().out + assert code == 0 + needs = out.split("Needs follow-up")[1].split("Waiting")[0] + assert "recorded differently: birth_date" in needs + assert "who: referrals desk" in needs + assert "they refused it" in needs and "who: billing" in needs + assert "CLM-" not in out and "REF-0001" not in out and "1984" not in out + assert "Done: 1 (--all lists them)" in out + code = main(["handoff", "list", "--ledger", str(ledger.directory), "--json"]) + data = json.loads(capsys.readouterr().out) + assert data[0]["receipt_line"]["state"] == "recorded_differently" + assert data[0]["differing_fields"] == ["birth_date"] + + +def test_handoff_list_for_one_run_sets_the_claims_step(tmp_path, capsys): + from openadapt_flow.__main__ import main + + pending, e = _claims(tmp_path, FMT_277, ["CLM-1001"]) + run = tmp_path / "run" + run.mkdir() + report = { + "run_id": "r", + "results": [ + {"ok": True}, + {"ok": True, "effect_evidence": [{"deferred_check": e["CLM-1001"].id}]}, + ], + } + (run / "report.json").write_text(json.dumps(report)) + assert main(["handoff", "list", "--ledger", str(pending.directory), "--run", str(run), "--json"]) == 0 + data = json.loads(capsys.readouterr().out) + assert [d["receipt_line"]["for_step"] for d in data] == [1] + assert data[0]["state"] == "sent" From 13c6e3f68127ce5ad57d7c1c4991a7ec78b16af1 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 00:58:18 -0500 Subject: [PATCH 03/18] wip: docs, receiver harness, live test --- CAPABILITIES.md | 5 + .../flow/benchmark/handoff_receiver/README.md | 66 +++++ .../handoff_receiver/referral_cases.py | 264 ++++++++++++++++++ packages/flow/docs/HANDOFFS.md | 157 +++++++++++ .../commands/03-run-and-answer/handoff.md | 1 + .../flow/openadapt_flow/handoffs/ledger.py | 10 +- packages/flow/openadapt_flow/handoffs/line.py | 7 +- .../handoffs/fhir-patient-intake.yaml | 18 ++ .../flow/tests/test_handoffs_live_openemr.py | 35 +++ 9 files changed, 560 insertions(+), 3 deletions(-) create mode 100644 packages/flow/benchmark/handoff_receiver/README.md create mode 100644 packages/flow/benchmark/handoff_receiver/referral_cases.py create mode 100644 packages/flow/docs/HANDOFFS.md create mode 100644 packages/flow/docs/commands/03-run-and-answer/handoff.md create mode 100644 packages/flow/tests/fixtures/handoffs/fhir-patient-intake.yaml create mode 100644 packages/flow/tests/test_handoffs_live_openemr.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 1c71807699..5ea62e7c7b 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -196,6 +196,10 @@ improvising or retrying when something is off. | Learn the record check from the recording, when the person looks the record up after saving | Released ([#1290](https://github.com/OpenAdaptAI/OpenAdapt/pull/1290)) | Synthetic | `record --verify` | | A record check's duplicate key can be several fields together, such as last name, first name and birth date: the check fails when more than one record carries all of them, counting records that were already there | Released ([#1393](https://github.com/OpenAdaptAI/OpenAdapt/issues/1393)) | Synthetic (OpenEMR-shaped patient rows) | verify.yaml `record.duplicate_key: [lname, fname, DOB]`, `confirm_params(idempotency_key=[...])`, `Effect.composite_key` | | Checked later: a save confirmed by a later report or acknowledgment, never counted as done until then | Released ([#1297](https://github.com/OpenAdaptAI/OpenAdapt/pull/1297)) | Synthetic | `SAVED_AWAITING_CHECK` | +| Counterparty confirmations for payer claims: each claim with a deferred check is a handoff, and the payer's 999 or 277CA moves it to `acknowledged` (received or accepted, status only) or back to `sent` with a reason (rejected, no answer by the deadline, two claims on one key). The deferred check settles exactly as before | In a pull request | Synthetic (X12 999 and 277CA fixtures, unit tests) | `deferred settle`, `openadapt_flow/handoffs/payer.py`, [HANDOFFS.md](packages/flow/docs/HANDOFFS.md) | +| Counterparty confirmations by read-back: the sender records what it sent (as digests), then reads the other party's system by a profile (data) and reports `recorded_as_intended`, `recorded_differently` with the differing field ids, or `sent` with a reason (not found, matched twice, unreachable). One comparator for every producer | In a pull request | Real app: a second, synthetic OpenEMR 7.0.3 as the receiving clinic, written through its REST API and read back through FHIR with a read-only token (RESULTS_LINK) | `openadapt_flow/handoffs/`, [HANDOFFS.md](packages/flow/docs/HANDOFFS.md) | +| Open handoffs by state, with who still needs to follow up | In a pull request | Unit tests | `openadapt handoff list` | +| Receipt lines for counterparty confirmations (`predicate.confirmations[]` in `record/run/v1`), committed and checked against the receipt schema | In a pull request | Unit tests: a statement with six confirmations signs and verifies | `openadapt_flow/handoffs/line.py` | | Keep the server's own answer to a save as lower-level evidence on the receipt | Released ([#1298](https://github.com/OpenAdaptAI/OpenAdapt/pull/1298)) | Synthetic | receipts | | A ledger of what changed before a stop, a write-ordering lint, and undo steps a person approves | Released ([#1263](https://github.com/OpenAdaptAI/OpenAdapt/pull/1263)) | Synthetic (MockMed) | change ledger | | Propose an undo for each saving step (another recording, captured traffic, or the old value), keep it only if a test copy shows every record restored, and offer it after a stop once a person approves it | Released ([#1346](https://github.com/OpenAdaptAI/OpenAdapt/pull/1346)) | Synthetic (MockMed, MockLoan, live browser) | `openadapt-flow undo propose`, `undo accept`; [AFTER_A_STOP.md](packages/flow/docs/AFTER_A_STOP.md) | @@ -417,6 +421,7 @@ A test fails when a command has no file or this list is out of date. - `console` - `deferred` - `explain` +- `handoff`: Show open handoffs to other parties (claims, referrals) by state, and who still needs to follow up. It reads local ledgers only. See `packages/flow/docs/HANDOFFS.md`. - `item-approval` - `replay` - `resume` diff --git a/packages/flow/benchmark/handoff_receiver/README.md b/packages/flow/benchmark/handoff_receiver/README.md new file mode 100644 index 0000000000..fcf0a5ec6c --- /dev/null +++ b/packages/flow/benchmark/handoff_receiver/README.md @@ -0,0 +1,66 @@ +# Referral intake: a real, synthetic OpenEMR as the receiving clinic + +These are the real-app cases for counterparty confirmations by read-back +(see [HANDOFFS.md](../../docs/HANDOFFS.md)). A synthetic referring clinic +sends referrals to a **second, separate OpenEMR 7.0.3** that plays the +receiving clinic. OpenAdapt reads the receiver back and says whether each +referral was recorded as intended, recorded differently, or never arrived. + +- **Sender:** `referral_cases.Sender`, a SQLite outbox of generated synthetic + patients. +- **Delivery:** the receiving clinic's intake, written through OpenEMR's + standard REST API (`/apis/default/api/patient`), with the sender's + referral id as the patient's external id. It makes mistakes on purpose. +- **Read-back:** OpenEMR's FHIR R4 `Patient` search, with a separate + read-only token, by the profile in + [`tests/fixtures/handoffs/fhir-patient-intake.yaml`](../../tests/fixtures/handoffs/fhir-patient-intake.yaml). + It never reads the delivery call's answer. + +## Bring-up (lab, WSL Docker) + +```bash +docker compose -f docker-compose.yml up -d # project ho-openemr, loopback 9780/9781 +# wait for "Starting apache!" in the logs (about 8 minutes on first boot), then: +OPENEMR_COMPOSE_FILE=$PWD/docker-compose.yml OPENEMR_BASE_HTTPS=https://127.0.0.1:9781 \ +OPENEMR_SCOPES="openid api:oemr api:fhir user/patient.read user/patient.write user/Patient.read user/Patient.write" \ + ../openemr_live/setup.sh > write.env +OPENEMR_COMPOSE_FILE=$PWD/docker-compose.yml OPENEMR_BASE_HTTPS=https://127.0.0.1:9781 \ +OPENEMR_SCOPES="openid api:fhir user/Patient.read" \ + ../openemr_live/setup.sh > read.env +``` + +Export these from the two tokens: + +- `HANDOFF_RECEIVER_API_BASE=https://127.0.0.1:9781/apis/default/api` +- `HANDOFF_RECEIVER_WRITE_TOKEN` (from `write.env`) +- `HANDOFF_RECEIVER_FHIR_BASE=https://127.0.0.1:9781/apis/default/fhir` +- `HANDOFF_RECEIVER_READ_TOKEN` (from `read.env`; a POST with it gets 401) +- `HANDOFF_RECEIVER_VERIFY_TLS=0` (self-signed certificate) + +Then run: + +```bash +pytest tests/test_handoffs_live_openemr.py # or: +python -m benchmark.handoff_receiver.referral_cases --repeat 5 --out results.json +``` + +Tear down with `docker compose -f docker-compose.yml down -v`. + +## Cases + +Each case is repeated with a fresh synthetic patient. The table is in +`referral_cases.py`, and results are in [`results/`](results/). + +| Case | What the intake does | Expected | +|---|---|---| +| intended | records it as sent | `recorded_as_intended` | +| benign_format | names in capitals with extra spaces | `recorded_as_intended` (no false alarm) | +| wrong_date | birth date one day later | `recorded_differently` [birth_date] | +| swapped_date | day and month swapped | `recorded_differently` [birth_date] | +| wrong_patient_field | another family name | `recorded_differently` [family_name] | +| wrong_sex | the other sex | `recorded_differently` [sex] | +| never_arrived | drops it | `sent`, `not_found` (follow-up due) | +| duplicate | records it twice | `sent`, `ambiguous_key` | +| unreachable | records it; the read goes to a closed port | `sent`, `receiver_unreachable` | + +Synthetic data only. diff --git a/packages/flow/benchmark/handoff_receiver/referral_cases.py b/packages/flow/benchmark/handoff_receiver/referral_cases.py new file mode 100644 index 0000000000..b25ac32d88 --- /dev/null +++ b/packages/flow/benchmark/handoff_receiver/referral_cases.py @@ -0,0 +1,264 @@ +"""Referral intake cases against a real, synthetic OpenEMR receiver. + +The sender is a synthetic referring clinic: a SQLite outbox that creates +referrals with generated, synthetic patients. Each referral goes to the +receiver (a second, separate OpenEMR in Docker, see README.md) through a +delivery channel that plays the receiving clinic's intake. The channel +writes through OpenEMR's standard REST API (``/apis/default/api/patient``) +and can, on purpose, get something wrong. + +OpenAdapt reads the receiver back through its FHIR API, with a separate +read-only token, by the profile in +``tests/fixtures/handoffs/fhir-patient-intake.yaml``. It never reads the +delivery call's own answer. + +Cases (each repeated ``repeat`` times with a fresh patient): + +| Case | Delivery | Expected | +|---|---|---| +| ``intended`` | as sent | ``recorded_as_intended`` | +| ``benign_format`` | names in capitals with extra spaces | ``recorded_as_intended`` (no false alarm) | +| ``wrong_date`` | birth date one day later | ``recorded_differently`` [birth_date] | +| ``swapped_date`` | day and month swapped | ``recorded_differently`` [birth_date] | +| ``wrong_patient_field`` | another family name | ``recorded_differently`` [family_name] | +| ``wrong_sex`` | the other sex | ``recorded_differently`` [sex] | +| ``never_arrived`` | dropped | ``sent``, reason ``not_found``, follow-up due | +| ``duplicate`` | delivered twice | ``sent``, reason ``ambiguous_key`` | +| ``unreachable`` | as sent; read at a closed port | ``sent``, reason ``receiver_unreachable`` | + +Synthetic data only. Run inside the lab (``remote-run.sh``), with the +``HANDOFF_RECEIVER_*`` variables from the receiver's setup. +""" + +from __future__ import annotations + +import json +import os +import random +import secrets +import sqlite3 +import time +from dataclasses import dataclass +from datetime import date, timedelta +from pathlib import Path +from typing import Any, Optional + +from openadapt_flow.handoffs import intake +from openadapt_flow.handoffs.ledger import Handoff, HandoffLedger +from openadapt_flow.handoffs.line import to_line +from openadapt_flow.handoffs.readers import FhirSearchProfile, FhirSearchReader + +PROFILE = ( + Path(__file__).resolve().parents[2] + / "tests" + / "fixtures" + / "handoffs" + / "fhir-patient-intake.yaml" +) +GIVEN = ["Avery", "Rowan", "Sage", "Quinn", "Emery", "Harper", "Reese", "Tatum"] +FAMILY = ["Quill", "Marlow", "Thorne", "Vance", "Ashby", "Corwin", "Hollis", "Pryor"] + +EXPECTED: dict[str, tuple[str, Optional[str], list[str]]] = { + "intended": ("recorded_as_intended", None, []), + "benign_format": ("recorded_as_intended", None, []), + "wrong_date": ("recorded_differently", None, ["birth_date"]), + "swapped_date": ("recorded_differently", None, ["birth_date"]), + "wrong_patient_field": ("recorded_differently", None, ["family_name"]), + "wrong_sex": ("recorded_differently", None, ["sex"]), + "never_arrived": ("sent", "not_found", []), + "duplicate": ("sent", "ambiguous_key", []), + "unreachable": ("sent", "receiver_unreachable", []), +} + + +class Sender: + """The synthetic referring clinic: an outbox of referrals.""" + + def __init__(self, path: Path, seed: int) -> None: + self.db = sqlite3.connect(path) + self.db.execute( + "create table if not exists referral (id text primary key, given text," + " family text, birth_date text, sex text, reason text)" + ) + self.rng = random.Random(seed) + + def create(self, *, unswappable: bool = False) -> dict[str, str]: + day = self.rng.randint(13, 28) if unswappable else self.rng.randint(1, 12) + month = self.rng.randint(1, 12) + if not unswappable: + while month == day: + month = self.rng.randint(1, 12) + row = { + "id": f"REF-{secrets.token_hex(6).upper()}", + "given": self.rng.choice(GIVEN), + "family": self.rng.choice(FAMILY) + secrets.token_hex(2), + "birth_date": date(self.rng.randint(1940, 2015), month, day).isoformat(), + "sex": self.rng.choice(["female", "male"]), + "reason": "synthetic referral", + } + self.db.execute( + "insert into referral values (:id, :given, :family, :birth_date, :sex," + " :reason)", + row, + ) + self.db.commit() + return row + + +def _post_patient(base: str, token: str, row: dict[str, str]) -> None: + import httpx + + body = { + "fname": row["given"], + "lname": row["family"], + "DOB": row["birth_date"], + "sex": row["sex"].capitalize() if row["sex"] in ("female", "male") else row["sex"], + "pubpid": row["id"], + "street": "", + "postal_code": "", + "city": "", + "state": "", + "country_code": "", + "phone_contact": "", + "race": "", + "ethnicity": "", + } + with httpx.Client(verify=_verify(), timeout=30) as client: + response = client.post( + f"{base}/patient", json=body, headers={"Authorization": f"Bearer {token}"} + ) + if response.status_code >= 300 or response.json().get("validationErrors"): + raise RuntimeError(f"delivery failed: HTTP {response.status_code}") + + +def _verify() -> bool: + return os.environ.get("HANDOFF_RECEIVER_VERIFY_TLS", "1") != "0" + + +def deliver(case: str, row: dict[str, str], base: str, token: str) -> None: + """The receiving clinic's intake, getting it wrong on purpose.""" + + sent = dict(row) + born = date.fromisoformat(row["birth_date"]) + if case == "never_arrived": + return + if case == "benign_format": + sent["given"] = f" {row['given'].upper()} " + sent["family"] = row["family"].upper() + elif case == "wrong_date": + sent["birth_date"] = (born + timedelta(days=1)).isoformat() + elif case == "swapped_date": + sent["birth_date"] = date(born.year, born.day, born.month).isoformat() + elif case == "wrong_patient_field": + sent["family"] = row["family"] + "s" + elif case == "wrong_sex": + sent["sex"] = "male" if row["sex"] == "female" else "female" + _post_patient(base, token, sent) + if case == "duplicate": + _post_patient(base, token, sent) + + +@dataclass +class CaseResult: + case: str + referral: str + state: str + reason: Optional[str] + differing: list[str] + line: dict[str, Any] + ok: bool + seconds: float + + +def run_cases( + work: Path, *, repeat: int = 5, seed: int = 20261121, cases: Optional[list[str]] = None +) -> list[CaseResult]: + api = os.environ["HANDOFF_RECEIVER_API_BASE"] + write_token = os.environ["HANDOFF_RECEIVER_WRITE_TOKEN"] + fhir = os.environ["HANDOFF_RECEIVER_FHIR_BASE"] + read_token = os.environ["HANDOFF_RECEIVER_READ_TOKEN"] + profile = FhirSearchProfile.load(PROFILE) + reader = FhirSearchReader(profile, fhir, token=read_token, verify_tls=_verify()) + closed = FhirSearchReader( + profile, "https://127.0.0.1:9789/apis/default/fhir", token=read_token, + verify_tls=False, timeout=5, + ) + sender = Sender(work / "sender.sqlite", seed) + ledger = HandoffLedger(work / "handoffs") + results: list[CaseResult] = [] + for name in cases or list(EXPECTED): + for _ in range(repeat): + row = sender.create(unswappable=False) + started = time.monotonic() + handoff: Handoff = ledger.send( + row["id"], + { + "given_name": (row["given"], "text"), + "family_name": (row["family"], "text"), + "birth_date": (row["birth_date"], "date"), + "sex": (row["sex"], "code"), + }, + counterparty=profile.counterparty, + system_kind=profile.system_kind, + follow_up="referrals desk", + follow_up_hours=24, + step=0, + ) + deliver(name, row, api, write_token) + used = closed if name == "unreachable" else reader + after = intake.check(ledger, handoff.id, row["id"], used) + last = after.last + assert last is not None + want_state, want_reason, want_fields = EXPECTED[name] + got = (after.state, last.reason, list(last.differing_fields)) + results.append( + CaseResult( + case=name, + referral=row["id"], + state=after.state, + reason=last.reason, + differing=list(last.differing_fields), + line=to_line(after).line, + ok=got == (want_state, want_reason, want_fields), + seconds=round(time.monotonic() - started, 3), + ) + ) + return results + + +def summarize(results: list[CaseResult]) -> dict[str, Any]: + by_case: dict[str, dict[str, Any]] = {} + for item in results: + entry = by_case.setdefault( + item.case, + {"expected": list(EXPECTED[item.case]), "runs": 0, "as_expected": 0, "got": {}}, + ) + entry["runs"] += 1 + entry["as_expected"] += item.ok + label = f"{item.state}|{item.reason}|{','.join(item.differing)}" + entry["got"][label] = entry["got"].get(label, 0) + 1 + return { + "receiver": "OpenEMR 7.0.3 (docker, synthetic, second instance)", + "read": "FHIR R4 Patient search, read-only token", + "delivery": "OpenEMR standard REST API (write token)", + "cases": by_case, + "total_runs": len(results), + "as_expected": sum(r.ok for r in results), + } + + +if __name__ == "__main__": # pragma: no cover - lab entry point + import argparse + import tempfile + + parser = argparse.ArgumentParser() + parser.add_argument("--repeat", type=int, default=5) + parser.add_argument("--out", default=None) + args = parser.parse_args() + with tempfile.TemporaryDirectory() as tmp: + found = run_cases(Path(tmp), repeat=args.repeat) + summary = summarize(found) + text = json.dumps(summary, indent=2) + if args.out: + Path(args.out).write_text(text + "\n") + print(text) diff --git a/packages/flow/docs/HANDOFFS.md b/packages/flow/docs/HANDOFFS.md new file mode 100644 index 0000000000..49dca8d755 --- /dev/null +++ b/packages/flow/docs/HANDOFFS.md @@ -0,0 +1,157 @@ +# Handoffs: did the other party record what we sent? + +A handoff is one item a run sends to another party's system, such as a claim +to a payer or a referral to a receiving clinic. A read-back of your own +system can't tell you whether the other side recorded it. A **counterparty +confirmation** can: it is evidence read from the other party's system about +what that system recorded. + +Each handoff is in one of four states: + +| State | Meaning | +|---|---| +| `sent` | We sent it. The other side hasn't confirmed anything yet, or it refused the item. | +| `acknowledged` | The other side says it has the item, but not what it recorded (an X12 999, a 277CA `A1` or `A2`). | +| `recorded_as_intended` | A read-back of the other system found the item, and every compared field matches what we sent. | +| `recorded_differently` | A read-back found the item, but some fields differ. The ledger names the field ids, never the values. | + +Only a read-back that compares fields can say `recorded_*`. An +acknowledgment message says what the other side received or accepted, never +what it stored in each field. + +## See who still needs to follow up + +```bash +openadapt handoff list --ledger /var/lib/openadapt/deferred +openadapt handoff list --config deployment.yaml --all +openadapt handoff list --ledger DIR --run runs/claim-0412 --json +``` + +```text +Needs follow-up (2) + receiving clinic: recorded differently: birth_date + sent 2026-11-21 06:00, follow up by 2026-11-22 06:00; who: referrals desk + payer x12-277ca: sent, no answer yet; they refused it + sent 2026-10-18 06:00, follow up by 2026-10-20 06:00; who: billing +Waiting (1) + payer x12-277ca: acknowledged + sent 2026-10-18 06:00, follow up by 2026-10-20 06:00 + +Done: 1 (--all lists them) +``` + +A handoff needs follow-up when it was recorded differently, refused, matched +more than one record, or is past its follow-up time and still isn't +confirmed. It is done when it was recorded as intended, or a status-only +report accepted it. `openadapt-flow handoff list` is the same command. It +reads ledgers only, and never contacts the other party. + +## Producer 1: payer acknowledgments + +A claim saved with a deferred check (`effects.kind: deferred_report`, see +[EFFECT_KIT.md](EFFECT_KIT.md#checked-later-deferred_report)) is a handoff to +the payer. Its handoff record lives in `/handoffs`. `deferred settle` +records what each report says, including rows that settle nothing yet: + +| The report says | Handoff | +|---|---| +| nothing yet | `sent`, follow-up due at the check's deadline | +| received (999 `A` or `E`, 277CA `A1`, any other pending status) | `acknowledged` | +| accepted (277CA `A2`) | `acknowledged`, accepted: done | +| rejected (999 `R`, `M`, `W`, `X`; 277CA `A3`, `A4`, `A6`, `A7`, `A8`) | `sent`, reason `rejected_by_counterparty` | +| two rows that disagree | `acknowledged`, reason `conflicting_report` | +| two waiting claims on one key | unchanged, reason `ambiguous_key` | +| nothing by the deadline | unchanged, reason `no_answer_by_deadline` | + +The deferred check settles the run exactly as before; the handoff only +listens. Only X12 reports count as the payer's own answer. A CSV export or a +saved status page may be your own system's report, so those checks are not +handoffs. + +## Producer 2: a read-back of the other system + +The sender records the handoff when it sends the item, together with the +field values it sent: + +```python +from openadapt_flow.handoffs import HandoffLedger, intake +from openadapt_flow.handoffs.readers import FhirSearchProfile, FhirSearchReader + +ledger = HandoffLedger("/var/lib/openadapt/handoffs") +h = ledger.send( + referral_id, + {"family_name": (family, "text"), "birth_date": (dob, "date"), "sex": (sex, "code")}, + counterparty="receiving clinic", system_kind="ehr", + follow_up="referrals desk", follow_up_hours=24, +) +# later +profile = FhirSearchProfile.load("fhir-patient-intake.yaml") +reader = FhirSearchReader(profile, fhir_base, token_env="RECEIVER_FHIR_TOKEN") +intake.check(ledger, h.id, referral_id, reader) +``` + +The reader finds the item by its key, which is the sender's reference that +the receiver keeps. Then it reports one of these: + +| Read | Handoff | +|---|---| +| one record, every field matches | `recorded_as_intended` | +| one record, some fields differ | `recorded_differently`, with those field ids | +| no record | unchanged (`sent`), reason `not_found`; it follows up when due | +| more than one record | unchanged, reason `ambiguous_key` | +| the read failed (network, 4xx, 5xx, bad body) | unchanged, reason `receiver_unreachable`; it never undoes an earlier confirmation | + +Fields compare by kind after normalizing, the same way as on-screen +read-backs (`readback_values`). `text` ignores case and runs of whitespace. +`code` ignores separators. `date` compares the calendar date. A field the +other side doesn't hold, or holds in a form that doesn't parse, differs. + +What to read is a **profile**, which is data. `FhirSearchProfile` names the +resource, the search parameter, where each record holds the key, and a path +and kind for each field. Every record the server returns is checked for the +exact key, so a server that ignores the search parameter can't make the +wrong record "found". A UI read-back plugs in the same way: any reader that +returns a `ReadResult`. + +## On the receipt + +`openadapt_flow.handoffs.line` turns a handoff into the receipt's +`counterparty_confirmation` line (`predicate.confirmations[]` in +`record/run/v1`, [RECEIPTS.md](RECEIPTS.md)): + +| Ledger | Line | +|---|---| +| `x12_999`, `x12_277ca`, `report_csv`, `report_text` | `read_method: acknowledgment_message`, `strength: acknowledgment` | +| `api_readback` | `api`, `read_back` | +| `ui_readback` | `portal_read_back`, `read_back` | +| `sent` | `strength: none` | +| differing field ids | `differing_count`; each compared field opens as `:`, with `:differs` when it differs | + +The other party, the time and the fields are salted commitments. They open +only in `receipt.private.json`, never on a public card. A reason the schema +doesn't allow for a state stays in the local ledger and is left off the +line. `handoffs_for_run` finds a run's handoffs, and `attach_confirmations` +puts their lines on a statement before it is signed. + +## Privacy + +The ledger is a private directory (0700, files 0600). It holds no record +values. Keys and sent field values are HMAC-SHA256 digests of the normalized +value, under a salt kept in the ledger directory. A read-back compares +digests. No model calls. + +## Limits + +- **A receipt is signed once.** The lines a receipt carries are the states + at signing time, usually `sent`. Later states live in the ledger and in + `handoff list`. A follow-up record that names the receipt is still to be + designed. +- **Payer reports are status only.** They never compare fields, so a payer + handoff is never `recorded_*`. +- **The FHIR profile needs the receiver to keep the sender's key.** It must + be in a searchable identifier, so the read can find the record. +- **`handoff send` and `handoff verify`** are being built separately. Until + they land, the referral producer is the Python API above. +- **Real-app evidence covers one receiver.** That receiver is a synthetic + OpenEMR 7.0.3 read through FHIR. See + [`benchmark/handoff_receiver`](../benchmark/handoff_receiver/README.md). diff --git a/packages/flow/docs/commands/03-run-and-answer/handoff.md b/packages/flow/docs/commands/03-run-and-answer/handoff.md new file mode 100644 index 0000000000..84bca9c4db --- /dev/null +++ b/packages/flow/docs/commands/03-run-and-answer/handoff.md @@ -0,0 +1 @@ +Show open handoffs to other parties (claims, referrals) by state, and who still needs to follow up. It reads local ledgers only. See `packages/flow/docs/HANDOFFS.md`. diff --git a/packages/flow/openadapt_flow/handoffs/ledger.py b/packages/flow/openadapt_flow/handoffs/ledger.py index 25c68f0317..4b4cf7e898 100644 --- a/packages/flow/openadapt_flow/handoffs/ledger.py +++ b/packages/flow/openadapt_flow/handoffs/ledger.py @@ -21,6 +21,7 @@ import hmac import json import os +import re import secrets from contextlib import contextmanager from datetime import datetime, timedelta, timezone @@ -69,7 +70,7 @@ ) Status = Literal["needs_follow_up", "waiting", "done"] -_FIELD_ID = r"^[a-z][a-z0-9_]{0,47}$" +_FIELD_ID = re.compile(r"[a-z][a-z0-9_]{0,31}") _DIGEST = r"^[0-9a-f]{64}$" _LABEL_MAX = 80 _SALT_FILE = ".salt" @@ -293,7 +294,14 @@ def send( if follow_up_hours <= 0: raise LedgerError("follow_up_hours must be positive") specs: dict[str, FieldSpec] = {} + if len(fields) > 31: + raise LedgerError("a handoff compares at most 31 fields") for field_id, spec in fields.items(): + if not _FIELD_ID.fullmatch(field_id): + raise LedgerError( + f"field id {field_id!r} must be lower case, digits and _, " + "at most 32 characters" + ) value, kind = spec[0], spec[1] order = spec[2] if len(spec) > 2 else None # type: ignore[misc] digest = self.field_digest(value, kind, order) diff --git a/packages/flow/openadapt_flow/handoffs/line.py b/packages/flow/openadapt_flow/handoffs/line.py index a76b011883..b688bb4c9a 100644 --- a/packages/flow/openadapt_flow/handoffs/line.py +++ b/packages/flow/openadapt_flow/handoffs/line.py @@ -37,6 +37,9 @@ from openadapt_flow.handoffs.ledger import Handoff, HandoffLedger KIND = "counterparty_confirmation" +#: A line commits to at most 34 values: counterparty, observed_at, reason +#: and up to 31 fields. +_MAX_FIELDS = 31 _READ_METHOD = { "x12_999": "acknowledgment_message", @@ -108,14 +111,14 @@ def to_line(handoff: Handoff) -> ConfirmationLine: field_ids: list[str] = [] differing = 0 if last is not None and last.strength == "field_readback" and state != "sent": - for index, field_id in enumerate(sorted(handoff.fields)[:32]): + for index, field_id in enumerate(sorted(handoff.fields)[:_MAX_FIELDS]): seen = last.observed_digests.get(field_id) or handoff.fields[field_id].digest if seen == "missing": seen = hashlib.sha256(b"missing").hexdigest() differs = field_id in last.differing_fields differing += differs values[f"field.{index}"] = ( - f"{field_id[:32]}:{seen}" + (":differs" if differs else "") + f"{field_id}:{seen}" + (":differs" if differs else "") ) field_ids.append(field_id) line = { diff --git a/packages/flow/tests/fixtures/handoffs/fhir-patient-intake.yaml b/packages/flow/tests/fixtures/handoffs/fhir-patient-intake.yaml new file mode 100644 index 0000000000..378e16647f --- /dev/null +++ b/packages/flow/tests/fixtures/handoffs/fhir-patient-intake.yaml @@ -0,0 +1,18 @@ +# Counterparty profile: read a referral's patient back from a receiving +# clinic's FHIR R4 server. Data, not code: any FHIR R4 server that keeps the +# sender's reference as the patient's PT identifier reads the same way. +# +# The key is the sender's referral id, which the receiver records as the +# patient's external identifier (identifier type PT). Every returned record +# is checked for that exact value (key_path), so a server that ignores the +# search parameter can't make a wrong record "found". +resource: Patient +key_param: identifier +key_path: identifier[system=http://terminology.hl7.org/CodeSystem/v2-0203].value +counterparty: receiving clinic (synthetic) +system_kind: ehr +fields: + given_name: {path: "name[use=official].given", kind: text} + family_name: {path: "name[use=official].family", kind: text} + birth_date: {path: birthDate, kind: date} + sex: {path: gender, kind: code} diff --git a/packages/flow/tests/test_handoffs_live_openemr.py b/packages/flow/tests/test_handoffs_live_openemr.py new file mode 100644 index 0000000000..8f19c8d4d5 --- /dev/null +++ b/packages/flow/tests/test_handoffs_live_openemr.py @@ -0,0 +1,35 @@ +"""Referral intake read back from a real OpenEMR receiver (synthetic). + +Skipped unless the receiver's variables are set (see +``benchmark/handoff_receiver/README.md``); normal CI never reaches it. The +unit tests in ``test_handoffs.py`` cover the same logic with fakes. +""" + +from __future__ import annotations + +import json +import os +from pathlib import Path + +import pytest + +pytestmark = pytest.mark.skipif( + not os.environ.get("HANDOFF_RECEIVER_FHIR_BASE"), + reason="needs the synthetic OpenEMR receiver (HANDOFF_RECEIVER_*)", +) + + +def test_every_referral_case_against_the_real_receiver(tmp_path: Path) -> None: + from benchmark.handoff_receiver.referral_cases import run_cases, summarize + + repeat = int(os.environ.get("HANDOFF_RECEIVER_REPEAT", "5")) + results = run_cases(tmp_path, repeat=repeat) + summary = summarize(results) + out = os.environ.get("HANDOFF_RESULTS_OUT") + if out: + Path(out).write_text(json.dumps(summary, indent=2) + "\n") + wrong = [r for r in results if not r.ok] + assert not wrong, [(r.case, r.state, r.reason, r.differing) for r in wrong] + # No false alarm: every correctly recorded referral reads as intended. + for case in ("intended", "benign_format"): + assert summary["cases"][case]["as_expected"] == repeat From 7a41ede5b1742c3d4fc94696fbdf965635ec440a Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:11:55 -0500 Subject: [PATCH 04/18] docs: rebuild llms-full --- llms-full.txt | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/llms-full.txt b/llms-full.txt index 856523850d..bd71d31294 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -630,6 +630,10 @@ improvising or retrying when something is off. | Learn the record check from the recording, when the person looks the record up after saving | Released ([#1290](https://github.com/OpenAdaptAI/OpenAdapt/pull/1290)) | Synthetic | `record --verify` | | A record check's duplicate key can be several fields together, such as last name, first name and birth date: the check fails when more than one record carries all of them, counting records that were already there | Released ([#1393](https://github.com/OpenAdaptAI/OpenAdapt/issues/1393)) | Synthetic (OpenEMR-shaped patient rows) | verify.yaml `record.duplicate_key: [lname, fname, DOB]`, `confirm_params(idempotency_key=[...])`, `Effect.composite_key` | | Checked later: a save confirmed by a later report or acknowledgment, never counted as done until then | Released ([#1297](https://github.com/OpenAdaptAI/OpenAdapt/pull/1297)) | Synthetic | `SAVED_AWAITING_CHECK` | +| Counterparty confirmations for payer claims: each claim with a deferred check is a handoff, and the payer's 999 or 277CA moves it to `acknowledged` (received or accepted, status only) or back to `sent` with a reason (rejected, no answer by the deadline, two claims on one key). The deferred check settles exactly as before | In a pull request | Synthetic (X12 999 and 277CA fixtures, unit tests) | `deferred settle`, `openadapt_flow/handoffs/payer.py`, [HANDOFFS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFFS.md) | +| Counterparty confirmations by read-back: the sender records what it sent (as digests), then reads the other party's system by a profile (data) and reports `recorded_as_intended`, `recorded_differently` with the differing field ids, or `sent` with a reason (not found, matched twice, unreachable). One comparator for every producer | In a pull request | Real app: a second, synthetic OpenEMR 7.0.3 as the receiving clinic, written through its REST API and read back through FHIR with a read-only token (RESULTS_LINK) | `openadapt_flow/handoffs/`, [HANDOFFS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFFS.md) | +| Open handoffs by state, with who still needs to follow up | In a pull request | Unit tests | `openadapt handoff list` | +| Receipt lines for counterparty confirmations (`predicate.confirmations[]` in `record/run/v1`), committed and checked against the receipt schema | In a pull request | Unit tests: a statement with six confirmations signs and verifies | `openadapt_flow/handoffs/line.py` | | Keep the server's own answer to a save as lower-level evidence on the receipt | Released ([#1298](https://github.com/OpenAdaptAI/OpenAdapt/pull/1298)) | Synthetic | receipts | | A ledger of what changed before a stop, a write-ordering lint, and undo steps a person approves | Released ([#1263](https://github.com/OpenAdaptAI/OpenAdapt/pull/1263)) | Synthetic (MockMed) | change ledger | | Propose an undo for each saving step (another recording, captured traffic, or the old value), keep it only if a test copy shows every record restored, and offer it after a stop once a person approves it | Released ([#1346](https://github.com/OpenAdaptAI/OpenAdapt/pull/1346)) | Synthetic (MockMed, MockLoan, live browser) | `openadapt-flow undo propose`, `undo accept`; [AFTER_A_STOP.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/AFTER_A_STOP.md) | @@ -851,6 +855,7 @@ A test fails when a command has no file or this list is out of date. - `console` - `deferred` - `explain` +- `handoff`: Show open handoffs to other parties (claims, referrals) by state, and who still needs to follow up. It reads local ledgers only. See `packages/flow/docs/HANDOFFS.md`. - `item-approval` - `replay` - `resume` From 80fae9911fbd439733a5ecbbf81fcfb4b8f2326f Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:22:00 -0500 Subject: [PATCH 05/18] feat(flow): counterparty confirmations: handoff ledger, payer and read-back producers, handoff list --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- .../handoff_receiver/referral_cases.py | 24 +++- .../handoff_receiver/results/2026-11-21.json | 130 ++++++++++++++++++ packages/flow/openadapt_flow/cli_deferred.py | 4 +- packages/flow/openadapt_flow/cli_handoff.py | 2 +- .../flow/openadapt_flow/handoffs/intake.py | 5 +- .../flow/openadapt_flow/handoffs/ledger.py | 8 +- packages/flow/openadapt_flow/handoffs/line.py | 23 ++-- .../flow/openadapt_flow/handoffs/readers.py | 6 +- packages/flow/tests/test_handoffs.py | 69 ++++++++-- 11 files changed, 237 insertions(+), 38 deletions(-) create mode 100644 packages/flow/benchmark/handoff_receiver/results/2026-11-21.json diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 5ea62e7c7b..5eaf028288 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -197,7 +197,7 @@ improvising or retrying when something is off. | A record check's duplicate key can be several fields together, such as last name, first name and birth date: the check fails when more than one record carries all of them, counting records that were already there | Released ([#1393](https://github.com/OpenAdaptAI/OpenAdapt/issues/1393)) | Synthetic (OpenEMR-shaped patient rows) | verify.yaml `record.duplicate_key: [lname, fname, DOB]`, `confirm_params(idempotency_key=[...])`, `Effect.composite_key` | | Checked later: a save confirmed by a later report or acknowledgment, never counted as done until then | Released ([#1297](https://github.com/OpenAdaptAI/OpenAdapt/pull/1297)) | Synthetic | `SAVED_AWAITING_CHECK` | | Counterparty confirmations for payer claims: each claim with a deferred check is a handoff, and the payer's 999 or 277CA moves it to `acknowledged` (received or accepted, status only) or back to `sent` with a reason (rejected, no answer by the deadline, two claims on one key). The deferred check settles exactly as before | In a pull request | Synthetic (X12 999 and 277CA fixtures, unit tests) | `deferred settle`, `openadapt_flow/handoffs/payer.py`, [HANDOFFS.md](packages/flow/docs/HANDOFFS.md) | -| Counterparty confirmations by read-back: the sender records what it sent (as digests), then reads the other party's system by a profile (data) and reports `recorded_as_intended`, `recorded_differently` with the differing field ids, or `sent` with a reason (not found, matched twice, unreachable). One comparator for every producer | In a pull request | Real app: a second, synthetic OpenEMR 7.0.3 as the receiving clinic, written through its REST API and read back through FHIR with a read-only token (RESULTS_LINK) | `openadapt_flow/handoffs/`, [HANDOFFS.md](packages/flow/docs/HANDOFFS.md) | +| Counterparty confirmations by read-back: the sender records what it sent (as digests), then reads the other party's system by a profile (data) and reports `recorded_as_intended`, `recorded_differently` with the differing field ids, or `sent` with a reason (not found, matched twice, unreachable). One comparator for every producer | In a pull request | Real app: a second, synthetic OpenEMR 7.0.3 as the receiving clinic, written through its REST API and read back through FHIR with a read-only token; 180 of 180 runs as expected over 9 cases, 0 false alarms in 40 correctly recorded referrals, [results](packages/flow/benchmark/handoff_receiver/results/2026-11-21.json) | `openadapt_flow/handoffs/`, [HANDOFFS.md](packages/flow/docs/HANDOFFS.md) | | Open handoffs by state, with who still needs to follow up | In a pull request | Unit tests | `openadapt handoff list` | | Receipt lines for counterparty confirmations (`predicate.confirmations[]` in `record/run/v1`), committed and checked against the receipt schema | In a pull request | Unit tests: a statement with six confirmations signs and verifies | `openadapt_flow/handoffs/line.py` | | Keep the server's own answer to a save as lower-level evidence on the receipt | Released ([#1298](https://github.com/OpenAdaptAI/OpenAdapt/pull/1298)) | Synthetic | receipts | diff --git a/llms-full.txt b/llms-full.txt index bd71d31294..84cb7e0014 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -631,7 +631,7 @@ improvising or retrying when something is off. | A record check's duplicate key can be several fields together, such as last name, first name and birth date: the check fails when more than one record carries all of them, counting records that were already there | Released ([#1393](https://github.com/OpenAdaptAI/OpenAdapt/issues/1393)) | Synthetic (OpenEMR-shaped patient rows) | verify.yaml `record.duplicate_key: [lname, fname, DOB]`, `confirm_params(idempotency_key=[...])`, `Effect.composite_key` | | Checked later: a save confirmed by a later report or acknowledgment, never counted as done until then | Released ([#1297](https://github.com/OpenAdaptAI/OpenAdapt/pull/1297)) | Synthetic | `SAVED_AWAITING_CHECK` | | Counterparty confirmations for payer claims: each claim with a deferred check is a handoff, and the payer's 999 or 277CA moves it to `acknowledged` (received or accepted, status only) or back to `sent` with a reason (rejected, no answer by the deadline, two claims on one key). The deferred check settles exactly as before | In a pull request | Synthetic (X12 999 and 277CA fixtures, unit tests) | `deferred settle`, `openadapt_flow/handoffs/payer.py`, [HANDOFFS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFFS.md) | -| Counterparty confirmations by read-back: the sender records what it sent (as digests), then reads the other party's system by a profile (data) and reports `recorded_as_intended`, `recorded_differently` with the differing field ids, or `sent` with a reason (not found, matched twice, unreachable). One comparator for every producer | In a pull request | Real app: a second, synthetic OpenEMR 7.0.3 as the receiving clinic, written through its REST API and read back through FHIR with a read-only token (RESULTS_LINK) | `openadapt_flow/handoffs/`, [HANDOFFS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFFS.md) | +| Counterparty confirmations by read-back: the sender records what it sent (as digests), then reads the other party's system by a profile (data) and reports `recorded_as_intended`, `recorded_differently` with the differing field ids, or `sent` with a reason (not found, matched twice, unreachable). One comparator for every producer | In a pull request | Real app: a second, synthetic OpenEMR 7.0.3 as the receiving clinic, written through its REST API and read back through FHIR with a read-only token; 180 of 180 runs as expected over 9 cases, 0 false alarms in 40 correctly recorded referrals, [results](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/handoff_receiver/results/2026-11-21.json) | `openadapt_flow/handoffs/`, [HANDOFFS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFFS.md) | | Open handoffs by state, with who still needs to follow up | In a pull request | Unit tests | `openadapt handoff list` | | Receipt lines for counterparty confirmations (`predicate.confirmations[]` in `record/run/v1`), committed and checked against the receipt schema | In a pull request | Unit tests: a statement with six confirmations signs and verifies | `openadapt_flow/handoffs/line.py` | | Keep the server's own answer to a save as lower-level evidence on the receipt | Released ([#1298](https://github.com/OpenAdaptAI/OpenAdapt/pull/1298)) | Synthetic | receipts | diff --git a/packages/flow/benchmark/handoff_receiver/referral_cases.py b/packages/flow/benchmark/handoff_receiver/referral_cases.py index b25ac32d88..f1e76af81a 100644 --- a/packages/flow/benchmark/handoff_receiver/referral_cases.py +++ b/packages/flow/benchmark/handoff_receiver/referral_cases.py @@ -112,7 +112,9 @@ def _post_patient(base: str, token: str, row: dict[str, str]) -> None: "fname": row["given"], "lname": row["family"], "DOB": row["birth_date"], - "sex": row["sex"].capitalize() if row["sex"] in ("female", "male") else row["sex"], + "sex": row["sex"].capitalize() + if row["sex"] in ("female", "male") + else row["sex"], "pubpid": row["id"], "street": "", "postal_code": "", @@ -171,7 +173,11 @@ class CaseResult: def run_cases( - work: Path, *, repeat: int = 5, seed: int = 20261121, cases: Optional[list[str]] = None + work: Path, + *, + repeat: int = 5, + seed: int = 20261121, + cases: Optional[list[str]] = None, ) -> list[CaseResult]: api = os.environ["HANDOFF_RECEIVER_API_BASE"] write_token = os.environ["HANDOFF_RECEIVER_WRITE_TOKEN"] @@ -180,8 +186,11 @@ def run_cases( profile = FhirSearchProfile.load(PROFILE) reader = FhirSearchReader(profile, fhir, token=read_token, verify_tls=_verify()) closed = FhirSearchReader( - profile, "https://127.0.0.1:9789/apis/default/fhir", token=read_token, - verify_tls=False, timeout=5, + profile, + "https://127.0.0.1:9789/apis/default/fhir", + token=read_token, + verify_tls=False, + timeout=5, ) sender = Sender(work / "sender.sqlite", seed) ledger = HandoffLedger(work / "handoffs") @@ -231,7 +240,12 @@ def summarize(results: list[CaseResult]) -> dict[str, Any]: for item in results: entry = by_case.setdefault( item.case, - {"expected": list(EXPECTED[item.case]), "runs": 0, "as_expected": 0, "got": {}}, + { + "expected": list(EXPECTED[item.case]), + "runs": 0, + "as_expected": 0, + "got": {}, + }, ) entry["runs"] += 1 entry["as_expected"] += item.ok diff --git a/packages/flow/benchmark/handoff_receiver/results/2026-11-21.json b/packages/flow/benchmark/handoff_receiver/results/2026-11-21.json new file mode 100644 index 0000000000..2838aed7a9 --- /dev/null +++ b/packages/flow/benchmark/handoff_receiver/results/2026-11-21.json @@ -0,0 +1,130 @@ +{ + "receiver": "OpenEMR 7.0.3 (docker, synthetic, second instance)", + "read": "FHIR R4 Patient search, read-only token", + "delivery": "OpenEMR standard REST API (write token)", + "cases": { + "intended": { + "expected": [ + "recorded_as_intended", + null, + [] + ], + "runs": 20, + "as_expected": 20, + "got": { + "recorded_as_intended|None|": 20 + } + }, + "benign_format": { + "expected": [ + "recorded_as_intended", + null, + [] + ], + "runs": 20, + "as_expected": 20, + "got": { + "recorded_as_intended|None|": 20 + } + }, + "wrong_date": { + "expected": [ + "recorded_differently", + null, + [ + "birth_date" + ] + ], + "runs": 20, + "as_expected": 20, + "got": { + "recorded_differently|None|birth_date": 20 + } + }, + "swapped_date": { + "expected": [ + "recorded_differently", + null, + [ + "birth_date" + ] + ], + "runs": 20, + "as_expected": 20, + "got": { + "recorded_differently|None|birth_date": 20 + } + }, + "wrong_patient_field": { + "expected": [ + "recorded_differently", + null, + [ + "family_name" + ] + ], + "runs": 20, + "as_expected": 20, + "got": { + "recorded_differently|None|family_name": 20 + } + }, + "wrong_sex": { + "expected": [ + "recorded_differently", + null, + [ + "sex" + ] + ], + "runs": 20, + "as_expected": 20, + "got": { + "recorded_differently|None|sex": 20 + } + }, + "never_arrived": { + "expected": [ + "sent", + "not_found", + [] + ], + "runs": 20, + "as_expected": 20, + "got": { + "sent|not_found|": 20 + } + }, + "duplicate": { + "expected": [ + "sent", + "ambiguous_key", + [] + ], + "runs": 20, + "as_expected": 20, + "got": { + "sent|ambiguous_key|": 20 + } + }, + "unreachable": { + "expected": [ + "sent", + "receiver_unreachable", + [] + ], + "runs": 20, + "as_expected": 20, + "got": { + "sent|receiver_unreachable|": 20 + } + } + }, + "total_runs": 180, + "as_expected": 180, + "date": "2026-11-21", + "repeat_per_case": 20, + "host": "zenbook lab, WSL Docker, project ho-openemr", + "pytest": "53 passed (test_handoffs.py, test_handoffs_live_openemr.py, test_deferred_report.py) via remote-run.sh slot gate", + "branch_head": "13c6e3f68 (code identical to the PR head for these files)" +} diff --git a/packages/flow/openadapt_flow/cli_deferred.py b/packages/flow/openadapt_flow/cli_deferred.py index 498eec1698..d7c4e8f45a 100644 --- a/packages/flow/openadapt_flow/cli_deferred.py +++ b/packages/flow/openadapt_flow/cli_deferred.py @@ -217,7 +217,9 @@ def cmd_deferred_settle(args: argparse.Namespace) -> int: word = "VERIFIED" if item.state == "verified" else "RECONCILIATION_REQUIRED" print(f"{item.id}: {word} ({item.reason}; code {item.code})") print(f"Settled {len(settled)}; {len(waiting)} still waiting.") - print("Open handoffs: openadapt-flow handoff list --ledger " + str(ledger.directory)) + print( + "Open handoffs: openadapt-flow handoff list --ledger " + str(ledger.directory) + ) return 0 diff --git a/packages/flow/openadapt_flow/cli_handoff.py b/packages/flow/openadapt_flow/cli_handoff.py index a8ecaab07f..20b5dd2194 100644 --- a/packages/flow/openadapt_flow/cli_handoff.py +++ b/packages/flow/openadapt_flow/cli_handoff.py @@ -23,7 +23,7 @@ import sys from datetime import datetime from pathlib import Path -from typing import TYPE_CHECKING, Optional +from typing import TYPE_CHECKING if TYPE_CHECKING: # pragma: no cover from openadapt_flow.handoffs.ledger import Handoff, HandoffLedger diff --git a/packages/flow/openadapt_flow/handoffs/intake.py b/packages/flow/openadapt_flow/handoffs/intake.py index 20e9021ad4..0b00b84cce 100644 --- a/packages/flow/openadapt_flow/handoffs/intake.py +++ b/packages/flow/openadapt_flow/handoffs/intake.py @@ -41,7 +41,6 @@ ) from openadapt_flow.handoffs.readers import Reader, ReadResult - _REASONS: dict[str, Reason] = { "not_found": "not_found", "ambiguous": "ambiguous_key", @@ -112,7 +111,9 @@ def check( if not handoff.fields: raise LedgerError("this handoff sent no fields to compare") result = reader.read(key) - return ledger.observe(handoff_id, judge(ledger, handoff, result, reader.read_method)) + return ledger.observe( + handoff_id, judge(ledger, handoff, result, reader.read_method) + ) def needs_follow_up( diff --git a/packages/flow/openadapt_flow/handoffs/ledger.py b/packages/flow/openadapt_flow/handoffs/ledger.py index 4b4cf7e898..76f7d3406d 100644 --- a/packages/flow/openadapt_flow/handoffs/ledger.py +++ b/packages/flow/openadapt_flow/handoffs/ledger.py @@ -304,10 +304,16 @@ def send( ) value, kind = spec[0], spec[1] order = spec[2] if len(spec) > 2 else None # type: ignore[misc] + if order not in (None, "dmy", "mdy"): + raise LedgerError(f"field {field_id!r}: date order is dmy or mdy") digest = self.field_digest(value, kind, order) if digest is None: raise LedgerError(f"field {field_id!r} doesn't read as a {kind}") - specs[field_id] = FieldSpec(kind=kind, digest=digest, date_order=order) + specs[field_id] = FieldSpec( + kind=kind, + digest=digest, + date_order=order, # type: ignore[arg-type] + ) moment = now or now_utc() with self._locked(): key_digest = self.digest(key) diff --git a/packages/flow/openadapt_flow/handoffs/line.py b/packages/flow/openadapt_flow/handoffs/line.py index b688bb4c9a..aa97f68c3b 100644 --- a/packages/flow/openadapt_flow/handoffs/line.py +++ b/packages/flow/openadapt_flow/handoffs/line.py @@ -112,13 +112,15 @@ def to_line(handoff: Handoff) -> ConfirmationLine: differing = 0 if last is not None and last.strength == "field_readback" and state != "sent": for index, field_id in enumerate(sorted(handoff.fields)[:_MAX_FIELDS]): - seen = last.observed_digests.get(field_id) or handoff.fields[field_id].digest + seen = ( + last.observed_digests.get(field_id) or handoff.fields[field_id].digest + ) if seen == "missing": seen = hashlib.sha256(b"missing").hexdigest() differs = field_id in last.differing_fields differing += differs - values[f"field.{index}"] = ( - f"{field_id}:{seen}" + (":differs" if differs else "") + values[f"field.{index}"] = f"{field_id}:{seen}" + ( + ":differs" if differs else "" ) field_ids.append(field_id) line = { @@ -184,10 +186,14 @@ def handoffs_for_run( if not isinstance(result, Mapping): continue for evidence in result.get("effect_evidence") or []: - entry_id = evidence.get("deferred_check") if isinstance(evidence, Mapping) else None - handoff = by_source.get(entry_id) if entry_id else None - if handoff is not None: - found[handoff.id] = handoff.model_copy(update={"step": index}) + entry_id = ( + evidence.get("deferred_check") + if isinstance(evidence, Mapping) + else None + ) + match = by_source.get(entry_id) if entry_id else None + if match is not None: + found[match.id] = match.model_copy(update={"step": index}) return sorted(found.values(), key=lambda h: (h.step or 0, h.sent_at, h.id)) @@ -204,8 +210,7 @@ def attach_confirmations( steps = {line["step"] for line in statement["predicate"].get("lines", [])} placed = [ - h if h.step in steps else h.model_copy(update={"step": None}) - for h in handoffs + h if h.step in steps else h.model_copy(update={"step": None}) for h in handoffs ] lines, opened = build_confirmations(placed, salt=salt) out = {**statement, "predicate": {**statement["predicate"], "confirmations": lines}} diff --git a/packages/flow/openadapt_flow/handoffs/readers.py b/packages/flow/openadapt_flow/handoffs/readers.py index e9c6caf250..edd04b239c 100644 --- a/packages/flow/openadapt_flow/handoffs/readers.py +++ b/packages/flow/openadapt_flow/handoffs/readers.py @@ -123,8 +123,10 @@ def __init__( ) -> None: self.profile = profile self.base_url = base_url.rstrip("/") - self._token = token if token is not None else ( - os.environ.get(token_env) if token_env else None + self._token = ( + token + if token is not None + else (os.environ.get(token_env) if token_env else None) ) self._verify = verify_tls self._timeout = timeout diff --git a/packages/flow/tests/test_handoffs.py b/packages/flow/tests/test_handoffs.py index 775ec1ebc6..419129a9f4 100644 --- a/packages/flow/tests/test_handoffs.py +++ b/packages/flow/tests/test_handoffs.py @@ -25,8 +25,8 @@ from openadapt_flow.reports.parse import ReportFormat from openadapt_flow.runtime.effects.deferred_report import PendingLedger from tests.test_deferred_report import ( - ACK_999, ACK_277CA, + ACK_999, FMT_277, HASH, SETTLE_AT, @@ -90,9 +90,15 @@ def test_277ca_received_accepted_and_rejected(tmp_path): accepted = _h(handoffs, e["CLM-1001"]) rejected = _h(handoffs, e["CLM-1002"]) received = _h(handoffs, e["CLM-1003"]) - assert (accepted.state, accepted.last.counterparty_accepted) == ("acknowledged", True) + assert (accepted.state, accepted.last.counterparty_accepted) == ( + "acknowledged", + True, + ) assert accepted.status(LATER) == "done" - assert (rejected.state, rejected.last.reason) == ("sent", "rejected_by_counterparty") + assert (rejected.state, rejected.last.reason) == ( + "sent", + "rejected_by_counterparty", + ) assert rejected.status(SETTLE_AT) == "needs_follow_up" assert (received.state, received.last.reason) == ("acknowledged", None) assert received.status(SETTLE_AT) == "waiting" @@ -288,10 +294,14 @@ def test_unreachable_never_undoes_a_confirmation_but_not_found_does(tmp_path): def test_the_ledger_refuses_what_it_could_never_compare(tmp_path): ledger = HandoffLedger(tmp_path / "handoffs") with pytest.raises(LedgerError): - ledger.send("K", {"d": ("03/04/2020", "date")}, counterparty="x", follow_up_hours=1) + ledger.send( + "K", {"d": ("03/04/2020", "date")}, counterparty="x", follow_up_hours=1 + ) ledger.send("K", {"d": ("2020-03-04", "date")}, counterparty="x", follow_up_hours=1) with pytest.raises(LedgerError): # a second open handoff on the same key - ledger.send("K", {"d": ("2020-03-04", "date")}, counterparty="x", follow_up_hours=1) + ledger.send( + "K", {"d": ("2020-03-04", "date")}, counterparty="x", follow_up_hours=1 + ) ledger2, h = _referral(tmp_path / "b") with pytest.raises(LedgerError): intake.check(ledger2, h.id, "REF-OTHER", Fake(_found())) @@ -329,7 +339,9 @@ def __init__(self, *pages, status: int = 200) -> None: def get(self, url, params=None, headers=None): self.calls.append((url, params, headers)) body = self.pages.pop(0) if self.pages else {} - return SimpleNamespace(status_code=self.status, content=json.dumps(body).encode()) + return SimpleNamespace( + status_code=self.status, content=json.dumps(body).encode() + ) def _bundle(*resources, next_url=None): @@ -340,7 +352,9 @@ def _bundle(*resources, next_url=None): def _reader(client): - return FhirSearchReader(PROFILE, "https://receiver.test/fhir", token="t", client=client) + return FhirSearchReader( + PROFILE, "https://receiver.test/fhir", token="t", client=client + ) def test_fhir_reader_found_not_found_and_key_check(): @@ -390,7 +404,11 @@ def test_lines_follow_the_schema_rules(tmp_path): "differing_count": 1, } assert item.values["counterparty"].startswith("ehr:cp-") - assert [v.endswith(":differs") for k, v in sorted(item.values.items()) if k.startswith("field.")] == [ + assert [ + v.endswith(":differs") + for k, v in sorted(item.values.items()) + if k.startswith("field.") + ] == [ True, False, False, @@ -417,9 +435,10 @@ def test_lines_validate_against_the_receipt_schema_and_sign(tmp_path): assert {k: set(v) for k, v in line.REASONS_FOR_STATE.items()} == { k: set(v) for k, v in r.REASONS_FOR_STATE.items() } + import base64 + from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat - import base64 from openadapt_flow.receipt_record import build_statement @@ -427,9 +446,7 @@ def test_lines_validate_against_the_receipt_schema_and_sign(tmp_path): states = [h] states.append(intake.check(ledger, h.id, "REF-0001", Fake(_found()))) ledger2, h2 = _referral(tmp_path / "2") - states.append( - intake.check(ledger2, h2.id, "REF-0001", Fake(_found(sex="male"))) - ) + states.append(intake.check(ledger2, h2.id, "REF-0001", Fake(_found(sex="male")))) pending, e = _claims(tmp_path, FMT_277, ["CLM-1001", "CLM-1002", "CLM-1003"]) _, handoffs = _settle(pending, ACK_277CA, FMT_277) states += [_h(handoffs, x) for x in e.values()] @@ -465,7 +482,9 @@ def test_lines_validate_against_the_receipt_schema_and_sign(tmp_path): ) assert result.ok, (result.reason, result.detail) assert len(result.confirmation_lines) == 6 - assert result.confirmation_lines[1].startswith("Confirmed in the other party's system") + assert result.confirmation_lines[1].startswith( + "Confirmed in the other party's system" + ) assert "1 field differs" in result.confirmation_lines[2] assert result.confirmation_lines[3].startswith("Acknowledged by the other party") assert result.confirmation_lines[4].startswith("Sent to the other party") @@ -482,7 +501,14 @@ def test_handoff_list_groups_by_who_must_follow_up(tmp_path, capsys): pending, _ = _claims(tmp_path, FMT_277, ["CLM-1001", "CLM-1002", "CLM-1003"]) _settle(pending, ACK_277CA, FMT_277) code = main( - ["handoff", "list", "--ledger", str(ledger.directory), "--ledger", str(pending.directory)] + [ + "handoff", + "list", + "--ledger", + str(ledger.directory), + "--ledger", + str(pending.directory), + ] ) out = capsys.readouterr().out assert code == 0 @@ -512,7 +538,20 @@ def test_handoff_list_for_one_run_sets_the_claims_step(tmp_path, capsys): ], } (run / "report.json").write_text(json.dumps(report)) - assert main(["handoff", "list", "--ledger", str(pending.directory), "--run", str(run), "--json"]) == 0 + assert ( + main( + [ + "handoff", + "list", + "--ledger", + str(pending.directory), + "--run", + str(run), + "--json", + ] + ) + == 0 + ) data = json.loads(capsys.readouterr().out) assert [d["receipt_line"]["for_step"] for d in data] == [1] assert data[0]["state"] == "sent" From 2753093c65d2c1ac42f7212397e3d79fcc310d26 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:25:11 -0500 Subject: [PATCH 06/18] results: referral intake on the OpenEMR receiver at 80fae991 --- .../flow/benchmark/handoff_receiver/results/2026-11-21.json | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/flow/benchmark/handoff_receiver/results/2026-11-21.json b/packages/flow/benchmark/handoff_receiver/results/2026-11-21.json index 2838aed7a9..02be3ba4e1 100644 --- a/packages/flow/benchmark/handoff_receiver/results/2026-11-21.json +++ b/packages/flow/benchmark/handoff_receiver/results/2026-11-21.json @@ -126,5 +126,9 @@ "repeat_per_case": 20, "host": "zenbook lab, WSL Docker, project ho-openemr", "pytest": "53 passed (test_handoffs.py, test_handoffs_live_openemr.py, test_deferred_report.py) via remote-run.sh slot gate", - "branch_head": "13c6e3f68 (code identical to the PR head for these files)" + "code_head": "80fae9911fbd439733a5ecbbf81fcfb4b8f2326f", + "earlier_runs": [ + "13c6e3f68: 180 of 180 at 20 per case", + "13c6e3f68: 45 of 45 at 5 per case" + ] } From 66a62da69113f123c0ae29c1288c472b9587c59b Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:34:40 -0500 Subject: [PATCH 07/18] fix(flow): handoff list joins the shared handoff group; observer failures never stop a settlement; sync catches up missed settlements --- CAPABILITIES.md | 6 +-- llms-full.txt | 6 +-- openadapt/cli_tasks.py | 2 +- .../flow/benchmark/handoff_receiver/README.md | 2 +- ...DOFFS.md => COUNTERPARTY_CONFIRMATIONS.md} | 0 .../commands/03-run-and-answer/handoff.md | 1 - .../06-give-agents-the-program/handoff.md | 1 + packages/flow/openadapt_flow/__main__.py | 9 ++-- .../{cli_handoff.py => cli_handoff_list.py} | 40 +++++++++++----- packages/flow/openadapt_flow/cli_tasks.py | 2 +- .../flow/openadapt_flow/handoffs/payer.py | 31 +++++++----- .../runtime/effects/deferred_report.py | 24 ++++++++-- packages/flow/tests/test_handoffs.py | 47 +++++++++++++++++++ tests/test_handoff_launcher.py | 28 +++++++++++ 14 files changed, 158 insertions(+), 41 deletions(-) rename packages/flow/docs/{HANDOFFS.md => COUNTERPARTY_CONFIRMATIONS.md} (100%) delete mode 100644 packages/flow/docs/commands/03-run-and-answer/handoff.md create mode 100644 packages/flow/docs/commands/06-give-agents-the-program/handoff.md rename packages/flow/openadapt_flow/{cli_handoff.py => cli_handoff_list.py} (84%) create mode 100644 tests/test_handoff_launcher.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 5eaf028288..040b384595 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -196,8 +196,8 @@ improvising or retrying when something is off. | Learn the record check from the recording, when the person looks the record up after saving | Released ([#1290](https://github.com/OpenAdaptAI/OpenAdapt/pull/1290)) | Synthetic | `record --verify` | | A record check's duplicate key can be several fields together, such as last name, first name and birth date: the check fails when more than one record carries all of them, counting records that were already there | Released ([#1393](https://github.com/OpenAdaptAI/OpenAdapt/issues/1393)) | Synthetic (OpenEMR-shaped patient rows) | verify.yaml `record.duplicate_key: [lname, fname, DOB]`, `confirm_params(idempotency_key=[...])`, `Effect.composite_key` | | Checked later: a save confirmed by a later report or acknowledgment, never counted as done until then | Released ([#1297](https://github.com/OpenAdaptAI/OpenAdapt/pull/1297)) | Synthetic | `SAVED_AWAITING_CHECK` | -| Counterparty confirmations for payer claims: each claim with a deferred check is a handoff, and the payer's 999 or 277CA moves it to `acknowledged` (received or accepted, status only) or back to `sent` with a reason (rejected, no answer by the deadline, two claims on one key). The deferred check settles exactly as before | In a pull request | Synthetic (X12 999 and 277CA fixtures, unit tests) | `deferred settle`, `openadapt_flow/handoffs/payer.py`, [HANDOFFS.md](packages/flow/docs/HANDOFFS.md) | -| Counterparty confirmations by read-back: the sender records what it sent (as digests), then reads the other party's system by a profile (data) and reports `recorded_as_intended`, `recorded_differently` with the differing field ids, or `sent` with a reason (not found, matched twice, unreachable). One comparator for every producer | In a pull request | Real app: a second, synthetic OpenEMR 7.0.3 as the receiving clinic, written through its REST API and read back through FHIR with a read-only token; 180 of 180 runs as expected over 9 cases, 0 false alarms in 40 correctly recorded referrals, [results](packages/flow/benchmark/handoff_receiver/results/2026-11-21.json) | `openadapt_flow/handoffs/`, [HANDOFFS.md](packages/flow/docs/HANDOFFS.md) | +| Counterparty confirmations for payer claims: each claim with a deferred check is a handoff, and the payer's 999 or 277CA moves it to `acknowledged` (received or accepted, status only) or back to `sent` with a reason (rejected, no answer by the deadline, two claims on one key). The deferred check settles exactly as before | In a pull request | Synthetic (X12 999 and 277CA fixtures, unit tests) | `deferred settle`, `openadapt_flow/handoffs/payer.py`, [COUNTERPARTY_CONFIRMATIONS.md](packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md) | +| Counterparty confirmations by read-back: the sender records what it sent (as digests), then reads the other party's system by a profile (data) and reports `recorded_as_intended`, `recorded_differently` with the differing field ids, or `sent` with a reason (not found, matched twice, unreachable). One comparator for every producer | In a pull request | Real app: a second, synthetic OpenEMR 7.0.3 as the receiving clinic, written through its REST API and read back through FHIR with a read-only token; 180 of 180 runs as expected over 9 cases, 0 false alarms in 40 correctly recorded referrals, [results](packages/flow/benchmark/handoff_receiver/results/2026-11-21.json) | `openadapt_flow/handoffs/`, [COUNTERPARTY_CONFIRMATIONS.md](packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md) | | Open handoffs by state, with who still needs to follow up | In a pull request | Unit tests | `openadapt handoff list` | | Receipt lines for counterparty confirmations (`predicate.confirmations[]` in `record/run/v1`), committed and checked against the receipt schema | In a pull request | Unit tests: a statement with six confirmations signs and verifies | `openadapt_flow/handoffs/line.py` | | Keep the server's own answer to a save as lower-level evidence on the receipt | Released ([#1298](https://github.com/OpenAdaptAI/OpenAdapt/pull/1298)) | Synthetic | receipts | @@ -421,7 +421,6 @@ A test fails when a command has no file or this list is out of date. - `console` - `deferred` - `explain` -- `handoff`: Show open handoffs to other parties (claims, referrals) by state, and who still needs to follow up. It reads local ledgers only. See `packages/flow/docs/HANDOFFS.md`. - `item-approval` - `replay` - `resume` @@ -448,6 +447,7 @@ A test fails when a command has no file or this list is out of date. - `emit-mcp`: Write a standalone MCP `server.py` for one bundle. A pulled workflow is refused until `skill qualify` has passed, and the server refuses a run on any other app address. - `emit-skill`: Write an Agent Skills folder for one bundle. A pulled workflow is refused until `skill qualify` has passed. +- `handoff`: Handoffs to other parties. `list` shows open handoffs by state (sent, acknowledged, recorded as intended, recorded differently) and who still needs to follow up, from local ledgers only (`packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md`). - `serve-execute`: With `--config DEPLOY_YAML`, a bundle recorded on Windows, macOS, Linux, RDP or Citrix runs through `openadapt-flow run --config`, under its admission's qualification authority. **Proof:** diff --git a/llms-full.txt b/llms-full.txt index 84cb7e0014..987639d9cb 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -630,8 +630,8 @@ improvising or retrying when something is off. | Learn the record check from the recording, when the person looks the record up after saving | Released ([#1290](https://github.com/OpenAdaptAI/OpenAdapt/pull/1290)) | Synthetic | `record --verify` | | A record check's duplicate key can be several fields together, such as last name, first name and birth date: the check fails when more than one record carries all of them, counting records that were already there | Released ([#1393](https://github.com/OpenAdaptAI/OpenAdapt/issues/1393)) | Synthetic (OpenEMR-shaped patient rows) | verify.yaml `record.duplicate_key: [lname, fname, DOB]`, `confirm_params(idempotency_key=[...])`, `Effect.composite_key` | | Checked later: a save confirmed by a later report or acknowledgment, never counted as done until then | Released ([#1297](https://github.com/OpenAdaptAI/OpenAdapt/pull/1297)) | Synthetic | `SAVED_AWAITING_CHECK` | -| Counterparty confirmations for payer claims: each claim with a deferred check is a handoff, and the payer's 999 or 277CA moves it to `acknowledged` (received or accepted, status only) or back to `sent` with a reason (rejected, no answer by the deadline, two claims on one key). The deferred check settles exactly as before | In a pull request | Synthetic (X12 999 and 277CA fixtures, unit tests) | `deferred settle`, `openadapt_flow/handoffs/payer.py`, [HANDOFFS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFFS.md) | -| Counterparty confirmations by read-back: the sender records what it sent (as digests), then reads the other party's system by a profile (data) and reports `recorded_as_intended`, `recorded_differently` with the differing field ids, or `sent` with a reason (not found, matched twice, unreachable). One comparator for every producer | In a pull request | Real app: a second, synthetic OpenEMR 7.0.3 as the receiving clinic, written through its REST API and read back through FHIR with a read-only token; 180 of 180 runs as expected over 9 cases, 0 false alarms in 40 correctly recorded referrals, [results](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/handoff_receiver/results/2026-11-21.json) | `openadapt_flow/handoffs/`, [HANDOFFS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFFS.md) | +| Counterparty confirmations for payer claims: each claim with a deferred check is a handoff, and the payer's 999 or 277CA moves it to `acknowledged` (received or accepted, status only) or back to `sent` with a reason (rejected, no answer by the deadline, two claims on one key). The deferred check settles exactly as before | In a pull request | Synthetic (X12 999 and 277CA fixtures, unit tests) | `deferred settle`, `openadapt_flow/handoffs/payer.py`, [COUNTERPARTY_CONFIRMATIONS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md) | +| Counterparty confirmations by read-back: the sender records what it sent (as digests), then reads the other party's system by a profile (data) and reports `recorded_as_intended`, `recorded_differently` with the differing field ids, or `sent` with a reason (not found, matched twice, unreachable). One comparator for every producer | In a pull request | Real app: a second, synthetic OpenEMR 7.0.3 as the receiving clinic, written through its REST API and read back through FHIR with a read-only token; 180 of 180 runs as expected over 9 cases, 0 false alarms in 40 correctly recorded referrals, [results](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/handoff_receiver/results/2026-11-21.json) | `openadapt_flow/handoffs/`, [COUNTERPARTY_CONFIRMATIONS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md) | | Open handoffs by state, with who still needs to follow up | In a pull request | Unit tests | `openadapt handoff list` | | Receipt lines for counterparty confirmations (`predicate.confirmations[]` in `record/run/v1`), committed and checked against the receipt schema | In a pull request | Unit tests: a statement with six confirmations signs and verifies | `openadapt_flow/handoffs/line.py` | | Keep the server's own answer to a save as lower-level evidence on the receipt | Released ([#1298](https://github.com/OpenAdaptAI/OpenAdapt/pull/1298)) | Synthetic | receipts | @@ -855,7 +855,6 @@ A test fails when a command has no file or this list is out of date. - `console` - `deferred` - `explain` -- `handoff`: Show open handoffs to other parties (claims, referrals) by state, and who still needs to follow up. It reads local ledgers only. See `packages/flow/docs/HANDOFFS.md`. - `item-approval` - `replay` - `resume` @@ -882,6 +881,7 @@ A test fails when a command has no file or this list is out of date. - `emit-mcp`: Write a standalone MCP `server.py` for one bundle. A pulled workflow is refused until `skill qualify` has passed, and the server refuses a run on any other app address. - `emit-skill`: Write an Agent Skills folder for one bundle. A pulled workflow is refused until `skill qualify` has passed. +- `handoff`: Handoffs to other parties. `list` shows open handoffs by state (sent, acknowledged, recorded as intended, recorded differently) and who still needs to follow up, from local ledgers only (`packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md`). - `serve-execute`: With `--config DEPLOY_YAML`, a bundle recorded on Windows, macOS, Linux, RDP or Citrix runs through `openadapt-flow run --config`, under its admission's qualification authority. **Proof:** diff --git a/openadapt/cli_tasks.py b/openadapt/cli_tasks.py index fadad271d1..713a371dea 100644 --- a/openadapt/cli_tasks.py +++ b/openadapt/cli_tasks.py @@ -65,7 +65,7 @@ "fleet": "services fleet", "for-each": "run --for-each", "guard": "run --guard", - "handoff": "handoff", + "handoff": "verify handoff", "induce": "compile --induce", "intake": "teach --intake", "item-approval": "approve --item", diff --git a/packages/flow/benchmark/handoff_receiver/README.md b/packages/flow/benchmark/handoff_receiver/README.md index fcf0a5ec6c..e89c71bd89 100644 --- a/packages/flow/benchmark/handoff_receiver/README.md +++ b/packages/flow/benchmark/handoff_receiver/README.md @@ -1,7 +1,7 @@ # Referral intake: a real, synthetic OpenEMR as the receiving clinic These are the real-app cases for counterparty confirmations by read-back -(see [HANDOFFS.md](../../docs/HANDOFFS.md)). A synthetic referring clinic +(see [COUNTERPARTY_CONFIRMATIONS.md](../../docs/COUNTERPARTY_CONFIRMATIONS.md)). A synthetic referring clinic sends referrals to a **second, separate OpenEMR 7.0.3** that plays the receiving clinic. OpenAdapt reads the receiver back and says whether each referral was recorded as intended, recorded differently, or never arrived. diff --git a/packages/flow/docs/HANDOFFS.md b/packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md similarity index 100% rename from packages/flow/docs/HANDOFFS.md rename to packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md diff --git a/packages/flow/docs/commands/03-run-and-answer/handoff.md b/packages/flow/docs/commands/03-run-and-answer/handoff.md deleted file mode 100644 index 84bca9c4db..0000000000 --- a/packages/flow/docs/commands/03-run-and-answer/handoff.md +++ /dev/null @@ -1 +0,0 @@ -Show open handoffs to other parties (claims, referrals) by state, and who still needs to follow up. It reads local ledgers only. See `packages/flow/docs/HANDOFFS.md`. diff --git a/packages/flow/docs/commands/06-give-agents-the-program/handoff.md b/packages/flow/docs/commands/06-give-agents-the-program/handoff.md new file mode 100644 index 0000000000..34ed4fe6af --- /dev/null +++ b/packages/flow/docs/commands/06-give-agents-the-program/handoff.md @@ -0,0 +1 @@ +Handoffs to other parties. `list` shows open handoffs by state (sent, acknowledged, recorded as intended, recorded differently) and who still needs to follow up, from local ledgers only (`packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md`). diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index bcc7c8e5e6..a65fd2d801 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -13169,10 +13169,6 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None: register_deferred_parser(sub) - from openadapt_flow.cli_handoff import register_handoff_parser - - register_handoff_parser(sub) - from openadapt_flow.cli_undo import register as _register_undo _register_undo( @@ -13226,6 +13222,11 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None: register_fleet_parser(sub) + # After any other ``handoff`` verbs: it adds ``list`` to the same group. + from openadapt_flow.cli_handoff_list import register_handoff_list + + register_handoff_list(sub) + parser.add_task_help() return parser diff --git a/packages/flow/openadapt_flow/cli_handoff.py b/packages/flow/openadapt_flow/cli_handoff_list.py similarity index 84% rename from packages/flow/openadapt_flow/cli_handoff.py rename to packages/flow/openadapt_flow/cli_handoff_list.py index 20b5dd2194..e6a7e06867 100644 --- a/packages/flow/openadapt_flow/cli_handoff.py +++ b/packages/flow/openadapt_flow/cli_handoff_list.py @@ -10,10 +10,10 @@ A deferred-check ledger (``effects.deferred_report.ledger``) is read as the payer handoffs beside it (``/handoffs``), created on first read. Any -other directory is read as a handoff ledger. See ``docs/HANDOFFS.md``. +other directory is read as a handoff ledger. See ``docs/COUNTERPARTY_CONFIRMATIONS.md``. -The ``send`` and ``verify`` subcommands belong to the handoff group too; -this module registers only ``list``. +The ``send`` and ``verify`` subcommands belong to the same group and are +registered elsewhere; this module adds only ``list``. """ from __future__ import annotations @@ -49,13 +49,29 @@ ) -def register_handoff_parser(sub: argparse._SubParsersAction) -> None: - parser = sub.add_parser( - "handoff", - help="Handoffs to other parties: what they recorded, and who follows up", - allow_abbrev=False, - ) - verbs = parser.add_subparsers(dest="handoff_cmd", required=True) +def _handoff_verbs(sub: argparse._SubParsersAction) -> argparse._SubParsersAction: + """The ``handoff`` group's subcommands, made if no one registered it yet. + + ``handoff send`` and ``handoff verify`` live in another module; whichever + registers first makes the group, and the other adds its verbs to it. + """ + + parser = sub.choices.get("handoff") + if parser is None: + parser = sub.add_parser( + "handoff", + help="Handoffs to other parties: what they recorded, and who follows up", + allow_abbrev=False, + ) + return parser.add_subparsers(dest="handoff_command", required=True) + for action in parser._actions: + if isinstance(action, argparse._SubParsersAction): + return action + return parser.add_subparsers(dest="handoff_command", required=True) + + +def register_handoff_list(sub: argparse._SubParsersAction) -> None: + verbs = _handoff_verbs(sub) listing = verbs.add_parser( "list", help="Open handoffs by state, with who still needs to follow up", @@ -130,6 +146,8 @@ def _describe(handoff: "Handoff") -> str: words += ": " + ", ".join(last.differing_fields) latest = handoff.last if latest is not None and latest.reason is not None: + if handoff.state == "sent": + words = "sent" words += f"; {_REASON_WORDS[latest.reason]}" return words @@ -203,4 +221,4 @@ def cmd_handoff_list(args: argparse.Namespace) -> int: return 0 -__all__ = ["register_handoff_parser"] +__all__ = ["register_handoff_list"] diff --git a/packages/flow/openadapt_flow/cli_tasks.py b/packages/flow/openadapt_flow/cli_tasks.py index eadf134b71..3cb3ccf013 100644 --- a/packages/flow/openadapt_flow/cli_tasks.py +++ b/packages/flow/openadapt_flow/cli_tasks.py @@ -64,7 +64,7 @@ "fleet": "services fleet", "for-each": "run --for-each", "guard": "run --guard", - "handoff": "handoff", + "handoff": "verify handoff", "induce": "compile --induce", "intake": "teach --intake", "item-approval": "approve --item", diff --git a/packages/flow/openadapt_flow/handoffs/payer.py b/packages/flow/openadapt_flow/handoffs/payer.py index e84cf8961f..4d23221f03 100644 --- a/packages/flow/openadapt_flow/handoffs/payer.py +++ b/packages/flow/openadapt_flow/handoffs/payer.py @@ -134,8 +134,10 @@ def observation_for( ) -def _same(a: Observation, b: Observation) -> bool: - keep = ("state", "reason", "counterparty_accepted", "evidence_sha256") +def _same(a: Observation, b: Observation, *, evidence: bool = True) -> bool: + keep = ("state", "reason", "counterparty_accepted") + ( + ("evidence_sha256",) if evidence else () + ) return all(getattr(a, k) == getattr(b, k) for k in keep) @@ -183,11 +185,13 @@ def __call__( def sync( pending: PendingLedger, *, exports: bool = False, follow_up: str = "billing" ) -> HandoffLedger: - """Make sure every deferred claim check has its handoff. + """Make sure every deferred claim check has its handoff, up to date. - A claim that settled before its handoff existed gets one observation from - the settlement (accepted, rejected, expired); the settlement's reason - text names which. + A claim that settled without the observer hearing it (before handoffs + existed, or expired by another caller of ``settle``) gets one observation + from the settlement (accepted, rejected, expired); the settlement's + reason text names which. A settlement the observer already recorded adds + nothing. """ handoffs = handoff_ledger(pending) @@ -195,7 +199,7 @@ def sync( if not _is_handoff(entry, exports): continue current = handoffs.adopt(as_handoff(entry, follow_up=follow_up)) - if current.observations or entry.state == "waiting": + if entry.state == "waiting": continue method = _METHOD.get(entry.report_format, "report_text") at = parse_iso(entry.settled_at) if entry.settled_at else None @@ -211,12 +215,15 @@ def sync( row, count = ReportRow("", "rejected", entry.code or ""), 1 else: row, count = ReportRow("", "conflicting", entry.code or ""), 1 - handoffs.observe( - current.id, - observation_for( - current, row, count, method, evidence_sha256=entry.settled_by, now=at - ), + observation = observation_for( + current, row, count, method, evidence_sha256=entry.settled_by, now=at ) + # Already recorded by ``deferred settle``'s observer: nothing new. + if current.last is not None and _same( + current.last, observation, evidence=False + ): + continue + handoffs.observe(current.id, observation) return handoffs diff --git a/packages/flow/openadapt_flow/runtime/effects/deferred_report.py b/packages/flow/openadapt_flow/runtime/effects/deferred_report.py index 18bf82c932..c091e77de5 100644 --- a/packages/flow/openadapt_flow/runtime/effects/deferred_report.py +++ b/packages/flow/openadapt_flow/runtime/effects/deferred_report.py @@ -411,8 +411,7 @@ def settle( entry.id, "reconciliation_required", "deadline", reason ) ) - if observer is not None: - observer(entry, None, 0) + _notify(observer, entry, None, 0) else: still.append(entry) if report_text is None or fmt is None: @@ -439,9 +438,9 @@ def settle( by_digest.setdefault(entry.key_digest, []).append(entry) for digest, entries in by_digest.items(): row = rows.get(digest) - if row is not None and observer is not None: + if row is not None: for entry in entries: - observer(entry, row, len(entries)) + _notify(observer, entry, row, len(entries)) if row is None or row.status == "pending": continue if len(entries) > 1: @@ -477,6 +476,23 @@ def settle( return settled +def _notify( + observer: Optional[SettleObserver], + entry: PendingCheck, + row: Optional[ReportRow], + count: int, +) -> None: + """Tell the observer, which never changes what settles: its failure is + swallowed (it can catch up later from the settled entries).""" + + if observer is None: + return + try: + observer(entry, row, count) + except Exception: # noqa: BLE001 - an observer must never stop a settlement + return + + def _issued_after(stamp: datetime, created: datetime) -> bool: """Whether a report issued at ``stamp`` can speak about a save made at ``created``. A report time without a zone (X12) gets the clock slack.""" diff --git a/packages/flow/tests/test_handoffs.py b/packages/flow/tests/test_handoffs.py index 419129a9f4..c5bb3d1454 100644 --- a/packages/flow/tests/test_handoffs.py +++ b/packages/flow/tests/test_handoffs.py @@ -555,3 +555,50 @@ def test_handoff_list_for_one_run_sets_the_claims_step(tmp_path, capsys): data = json.loads(capsys.readouterr().out) assert [d["receipt_line"]["for_step"] for d in data] == [1] assert data[0]["state"] == "sent" + + +def test_a_failing_observer_never_changes_what_settles(tmp_path): + pending, e = _claims(tmp_path, FMT_277, ["CLM-1001", "CLM-1002", "CLM-1003"]) + + def broken(entry, row, count): + raise OSError("disk full") + + settled = pending.settle(ACK_277CA, FMT_277, now=SETTLE_AT, observer=broken) + assert {s.id: s.state for s in settled} == { + e["CLM-1001"].id: "verified", + e["CLM-1002"].id: "reconciliation_required", + } + # The handoffs catch up from the settled entries. + handoffs = payer.sync(pending) + assert _h(handoffs, e["CLM-1001"]).last.counterparty_accepted + assert _h(handoffs, e["CLM-1002"]).last.reason == "rejected_by_counterparty" + + +def test_sync_catches_up_a_settlement_the_observer_missed(tmp_path): + pending, e = _claims(tmp_path, FMT_277, ["CLM-1003"], hours=8) + _settle(pending, ACK_277CA, FMT_277) # A1: acknowledged + pending.settle(None, None, now=LATER) # expired by a caller with no observer + handoffs = payer.sync(pending) + h = _h(handoffs, e["CLM-1003"]) + assert (h.state, h.last.reason) == ("acknowledged", "no_answer_by_deadline") + before = len(h.observations) + assert len(_h(payer.sync(pending), e["CLM-1003"]).observations) == before + + +def test_sync_adds_nothing_after_the_observer_recorded_it(tmp_path): + pending, e = _claims(tmp_path, FMT_277, ["CLM-1001", "CLM-1002"]) + _, handoffs = _settle(pending, ACK_277CA, FMT_277) + counts = {k: len(_h(handoffs, v).observations) for k, v in e.items()} + handoffs = payer.sync(pending) + assert {k: len(_h(handoffs, v).observations) for k, v in e.items()} == counts + + +def test_a_refused_claim_reads_as_refused_not_unanswered(tmp_path, capsys): + from openadapt_flow.__main__ import main + + pending, _ = _claims(tmp_path, FMT_277, ["CLM-1002"]) + _settle(pending, ACK_277CA, FMT_277) + assert main(["handoff", "list", "--ledger", str(pending.directory)]) == 0 + out = capsys.readouterr().out + assert "sent; they refused it" in out + assert "no answer yet" not in out diff --git a/tests/test_handoff_launcher.py b/tests/test_handoff_launcher.py new file mode 100644 index 0000000000..2ab6b80f02 --- /dev/null +++ b/tests/test_handoff_launcher.py @@ -0,0 +1,28 @@ +"""``openadapt handoff list`` reaches Flow's ``handoff list`` unchanged.""" + +from __future__ import annotations + +import pytest +from click.testing import CliRunner + +pytest.importorskip("openadapt_flow.handoffs") + +from openadapt import cli # noqa: E402 + + +def test_root_handoff_list_runs_flow_handoff_list(tmp_path): + from openadapt_flow.handoffs.ledger import HandoffLedger + + ledger = HandoffLedger(tmp_path / "handoffs") + ledger.send( + "REF-1", + {"birth_date": ("2001-02-03", "date")}, + counterparty="receiving clinic", + follow_up_hours=1, + ) + result = CliRunner().invoke( + cli.main, ["handoff", "list", "--ledger", str(ledger.directory)] + ) + assert result.exit_code == 0, result.output + assert "Waiting (1)" in result.output + assert "receiving clinic: sent, no answer yet" in result.output From 1741f4db3782418dff757cb47c1692d682808160 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:40:45 -0500 Subject: [PATCH 08/18] refactor(cli): use the shared handoff_group helper when it is installed --- packages/flow/openadapt_flow/cli_handoff_list.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/packages/flow/openadapt_flow/cli_handoff_list.py b/packages/flow/openadapt_flow/cli_handoff_list.py index e6a7e06867..b92e8d6abe 100644 --- a/packages/flow/openadapt_flow/cli_handoff_list.py +++ b/packages/flow/openadapt_flow/cli_handoff_list.py @@ -70,8 +70,19 @@ def _handoff_verbs(sub: argparse._SubParsersAction) -> argparse._SubParsersActio return parser.add_subparsers(dest="handoff_command", required=True) +def _group(sub: argparse._SubParsersAction) -> argparse._SubParsersAction: + """The shared group: ``cli_handoff.handoff_group`` where it exists (the + module with ``send`` and ``verify``), else the same rule here.""" + + try: + from openadapt_flow.cli_handoff import handoff_group + except ImportError: + return _handoff_verbs(sub) + return handoff_group(sub) + + def register_handoff_list(sub: argparse._SubParsersAction) -> None: - verbs = _handoff_verbs(sub) + verbs = _group(sub) listing = verbs.add_parser( "list", help="Open handoffs by state, with who still needs to follow up", From 6bf5c4a828e9f8c1031d524c63351b7266a25c73 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:41:07 -0500 Subject: [PATCH 09/18] docs: share the handoff command note with #2414 --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- .../flow/docs/commands/06-give-agents-the-program/handoff.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 040b384595..2da28dc4d1 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -447,7 +447,7 @@ A test fails when a command has no file or this list is out of date. - `emit-mcp`: Write a standalone MCP `server.py` for one bundle. A pulled workflow is refused until `skill qualify` has passed, and the server refuses a run on any other app address. - `emit-skill`: Write an Agent Skills folder for one bundle. A pulled workflow is refused until `skill qualify` has passed. -- `handoff`: Handoffs to other parties. `list` shows open handoffs by state (sent, acknowledged, recorded as intended, recorded differently) and who still needs to follow up, from local ledgers only (`packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md`). +- `handoff`: Agent-to-agent handoffs: `send` attaches a run's receipt to what one agent hands another (inline, detached beside a file, or POSTed to a webhook); `verify` checks one on arrival against your pinned keys (who signed, what was checked, and that a valid signature proves who signed, not that the claim is true); `key` and `trust` exchange receipt keys between parties; `list` shows handoffs to other parties and what their systems confirmed. - `serve-execute`: With `--config DEPLOY_YAML`, a bundle recorded on Windows, macOS, Linux, RDP or Citrix runs through `openadapt-flow run --config`, under its admission's qualification authority. **Proof:** diff --git a/llms-full.txt b/llms-full.txt index 987639d9cb..35cb1bd33c 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -881,7 +881,7 @@ A test fails when a command has no file or this list is out of date. - `emit-mcp`: Write a standalone MCP `server.py` for one bundle. A pulled workflow is refused until `skill qualify` has passed, and the server refuses a run on any other app address. - `emit-skill`: Write an Agent Skills folder for one bundle. A pulled workflow is refused until `skill qualify` has passed. -- `handoff`: Handoffs to other parties. `list` shows open handoffs by state (sent, acknowledged, recorded as intended, recorded differently) and who still needs to follow up, from local ledgers only (`packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md`). +- `handoff`: Agent-to-agent handoffs: `send` attaches a run's receipt to what one agent hands another (inline, detached beside a file, or POSTed to a webhook); `verify` checks one on arrival against your pinned keys (who signed, what was checked, and that a valid signature proves who signed, not that the claim is true); `key` and `trust` exchange receipt keys between parties; `list` shows handoffs to other parties and what their systems confirmed. - `serve-execute`: With `--config DEPLOY_YAML`, a bundle recorded on Windows, macOS, Linux, RDP or Citrix runs through `openadapt-flow run --config`, under its admission's qualification authority. **Proof:** diff --git a/packages/flow/docs/commands/06-give-agents-the-program/handoff.md b/packages/flow/docs/commands/06-give-agents-the-program/handoff.md index 34ed4fe6af..af830da10d 100644 --- a/packages/flow/docs/commands/06-give-agents-the-program/handoff.md +++ b/packages/flow/docs/commands/06-give-agents-the-program/handoff.md @@ -1 +1 @@ -Handoffs to other parties. `list` shows open handoffs by state (sent, acknowledged, recorded as intended, recorded differently) and who still needs to follow up, from local ledgers only (`packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md`). +Agent-to-agent handoffs: `send` attaches a run's receipt to what one agent hands another (inline, detached beside a file, or POSTed to a webhook); `verify` checks one on arrival against your pinned keys (who signed, what was checked, and that a valid signature proves who signed, not that the claim is true); `key` and `trust` exchange receipt keys between parties; `list` shows handoffs to other parties and what their systems confirmed. From 838b91ddb419b983795217ea6f6d0e6d8d49ccfa Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 02:05:52 -0500 Subject: [PATCH 10/18] feat: receipts carry the run's handoff lines; signed follow-up receipts with a verified chain --- CAPABILITIES.md | 3 +- llms-full.txt | 3 +- .../flow/docs/COUNTERPARTY_CONFIRMATIONS.md | 60 +++- .../flow/openadapt_flow/cli_handoff_list.py | 68 +++- .../flow/openadapt_flow/handoffs/followup.py | 186 +++++++++++ .../flow/openadapt_flow/handoffs/ledger.py | 3 + packages/flow/openadapt_flow/handoffs/line.py | 32 +- .../flow/openadapt_flow/handoffs/registry.py | 45 +++ .../flow/openadapt_flow/receipt_record.py | 28 +- .../runtime/effects/deferred_report.py | 18 + packages/flow/tests/test_handoff_receipts.py | 313 ++++++++++++++++++ packages/types/openadapt_types/receipt.py | 143 ++++++++ .../types/tests/test_receipt_follow_up.py | 103 ++++++ 13 files changed, 985 insertions(+), 20 deletions(-) create mode 100644 packages/flow/openadapt_flow/handoffs/followup.py create mode 100644 packages/flow/openadapt_flow/handoffs/registry.py create mode 100644 packages/flow/tests/test_handoff_receipts.py create mode 100644 packages/types/tests/test_receipt_follow_up.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 2da28dc4d1..f27755631c 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -199,7 +199,8 @@ improvising or retrying when something is off. | Counterparty confirmations for payer claims: each claim with a deferred check is a handoff, and the payer's 999 or 277CA moves it to `acknowledged` (received or accepted, status only) or back to `sent` with a reason (rejected, no answer by the deadline, two claims on one key). The deferred check settles exactly as before | In a pull request | Synthetic (X12 999 and 277CA fixtures, unit tests) | `deferred settle`, `openadapt_flow/handoffs/payer.py`, [COUNTERPARTY_CONFIRMATIONS.md](packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md) | | Counterparty confirmations by read-back: the sender records what it sent (as digests), then reads the other party's system by a profile (data) and reports `recorded_as_intended`, `recorded_differently` with the differing field ids, or `sent` with a reason (not found, matched twice, unreachable). One comparator for every producer | In a pull request | Real app: a second, synthetic OpenEMR 7.0.3 as the receiving clinic, written through its REST API and read back through FHIR with a read-only token; 180 of 180 runs as expected over 9 cases, 0 false alarms in 40 correctly recorded referrals, [results](packages/flow/benchmark/handoff_receiver/results/2026-11-21.json) | `openadapt_flow/handoffs/`, [COUNTERPARTY_CONFIRMATIONS.md](packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md) | | Open handoffs by state, with who still needs to follow up | In a pull request | Unit tests | `openadapt handoff list` | -| Receipt lines for counterparty confirmations (`predicate.confirmations[]` in `record/run/v1`), committed and checked against the receipt schema | In a pull request | Unit tests: a statement with six confirmations signs and verifies | `openadapt_flow/handoffs/line.py` | +| Receipts carry the run's handoffs as counterparty confirmation lines (`predicate.confirmations[]` in `record/run/v1`), written by the after-run receipt hook | In a pull request | Unit tests, and a real replayer run whose receipt carries its claim's `sent` line and verifies | `openadapt_flow/handoffs/line.py`, `receipt_record.py` | +| Follow-up receipts: each later change in a handoff's state is a separately signed `record/run/v1` record naming the original receipt (`follows`), and the chain verifies in order (`verify_chain`) | In a pull request | Unit tests: a three-record chain verifies; wrong original, out of sequence, changed fields and empty updates are refused | `openadapt handoff list --run RUN --sign-updates`, `openadapt_flow/handoffs/followup.py` | | Keep the server's own answer to a save as lower-level evidence on the receipt | Released ([#1298](https://github.com/OpenAdaptAI/OpenAdapt/pull/1298)) | Synthetic | receipts | | A ledger of what changed before a stop, a write-ordering lint, and undo steps a person approves | Released ([#1263](https://github.com/OpenAdaptAI/OpenAdapt/pull/1263)) | Synthetic (MockMed) | change ledger | | Propose an undo for each saving step (another recording, captured traffic, or the old value), keep it only if a test copy shows every record restored, and offer it after a stop once a person approves it | Released ([#1346](https://github.com/OpenAdaptAI/OpenAdapt/pull/1346)) | Synthetic (MockMed, MockLoan, live browser) | `openadapt-flow undo propose`, `undo accept`; [AFTER_A_STOP.md](packages/flow/docs/AFTER_A_STOP.md) | diff --git a/llms-full.txt b/llms-full.txt index 35cb1bd33c..92f9e3bd0c 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -633,7 +633,8 @@ improvising or retrying when something is off. | Counterparty confirmations for payer claims: each claim with a deferred check is a handoff, and the payer's 999 or 277CA moves it to `acknowledged` (received or accepted, status only) or back to `sent` with a reason (rejected, no answer by the deadline, two claims on one key). The deferred check settles exactly as before | In a pull request | Synthetic (X12 999 and 277CA fixtures, unit tests) | `deferred settle`, `openadapt_flow/handoffs/payer.py`, [COUNTERPARTY_CONFIRMATIONS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md) | | Counterparty confirmations by read-back: the sender records what it sent (as digests), then reads the other party's system by a profile (data) and reports `recorded_as_intended`, `recorded_differently` with the differing field ids, or `sent` with a reason (not found, matched twice, unreachable). One comparator for every producer | In a pull request | Real app: a second, synthetic OpenEMR 7.0.3 as the receiving clinic, written through its REST API and read back through FHIR with a read-only token; 180 of 180 runs as expected over 9 cases, 0 false alarms in 40 correctly recorded referrals, [results](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/handoff_receiver/results/2026-11-21.json) | `openadapt_flow/handoffs/`, [COUNTERPARTY_CONFIRMATIONS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md) | | Open handoffs by state, with who still needs to follow up | In a pull request | Unit tests | `openadapt handoff list` | -| Receipt lines for counterparty confirmations (`predicate.confirmations[]` in `record/run/v1`), committed and checked against the receipt schema | In a pull request | Unit tests: a statement with six confirmations signs and verifies | `openadapt_flow/handoffs/line.py` | +| Receipts carry the run's handoffs as counterparty confirmation lines (`predicate.confirmations[]` in `record/run/v1`), written by the after-run receipt hook | In a pull request | Unit tests, and a real replayer run whose receipt carries its claim's `sent` line and verifies | `openadapt_flow/handoffs/line.py`, `receipt_record.py` | +| Follow-up receipts: each later change in a handoff's state is a separately signed `record/run/v1` record naming the original receipt (`follows`), and the chain verifies in order (`verify_chain`) | In a pull request | Unit tests: a three-record chain verifies; wrong original, out of sequence, changed fields and empty updates are refused | `openadapt handoff list --run RUN --sign-updates`, `openadapt_flow/handoffs/followup.py` | | Keep the server's own answer to a save as lower-level evidence on the receipt | Released ([#1298](https://github.com/OpenAdaptAI/OpenAdapt/pull/1298)) | Synthetic | receipts | | A ledger of what changed before a stop, a write-ordering lint, and undo steps a person approves | Released ([#1263](https://github.com/OpenAdaptAI/OpenAdapt/pull/1263)) | Synthetic (MockMed) | change ledger | | Propose an undo for each saving step (another recording, captured traffic, or the old value), keep it only if a test copy shows every record restored, and offer it after a stop once a person approves it | Released ([#1346](https://github.com/OpenAdaptAI/OpenAdapt/pull/1346)) | Synthetic (MockMed, MockLoan, live browser) | `openadapt-flow undo propose`, `undo accept`; [AFTER_A_STOP.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/AFTER_A_STOP.md) | diff --git a/packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md b/packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md index 49dca8d755..4436be0fa9 100644 --- a/packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md +++ b/packages/flow/docs/COUNTERPARTY_CONFIRMATIONS.md @@ -130,8 +130,57 @@ returns a `ReadResult`. The other party, the time and the fields are salted commitments. They open only in `receipt.private.json`, never on a public card. A reason the schema doesn't allow for a state stays in the local ledger and is left off the -line. `handoffs_for_run` finds a run's handoffs, and `attach_confirmations` -puts their lines on a statement before it is signed. +line. + +**The run's receipt carries its handoffs.** When the run ends, the receipt +hook adds a line for each of the run's handoffs, usually `sent`: + +- a deferred claim check is found from its step's evidence; +- any other handoff is found by its `run_id`, which can be the report's + `run_id` or the run directory. + +The hook looks in the ledgers the run used in this process (a deferred check +and `HandoffLedger.send` note theirs). It also looks in any ledgers listed in +`OPENADAPT_HANDOFF_LEDGERS`, separated by the OS path separator. + +## Follow-up receipts + +A receipt is signed once, but a handoff keeps changing after that: it is +sent, then acknowledged, then recorded. Each change gets its own small +signed record: + +```bash +openadapt handoff list --ledger DIR --run runs/claim-0412 --sign-updates +``` + +This signs `receipt.update-N.json`, a `record/run/v1` statement that: + +- copies the original receipt's predicate unchanged; +- names the original's payload digest in `follows`, with `sequence` N; +- carries only the confirmation lines that changed since they were last + signed. A new read of the same state is not a change. + +The openings go in `receipt.update-N.private.json` (0600). Which handoff +each signed line belongs to is kept in `receipt.handoffs.json` (0600). That +file is local only and holds handoff ids, never values. + +`handoff list --run` verifies the chain with +`openadapt_types.receipt.verify_chain` and prints it: + +```text +Signed history (receipt and 2 update(s), verified) + Sent to the other party at 2026-11-21T06:00:00Z, not confirmed + Update 1: Confirmed in the other party's system at 2026-11-21T07:10:02Z + Update 2: Recorded differently in the other party's system at 2026-11-21T09:30:41Z: 1 field differs +``` + +The chain is refused in any of these cases: + +- any record fails to verify; +- a follow-up names another receipt; +- a follow-up skips or repeats a sequence number; +- a follow-up changes anything it copies from the original; +- a follow-up carries no confirmation. Such a follow-up can't be signed. ## Privacy @@ -142,10 +191,9 @@ digests. No model calls. ## Limits -- **A receipt is signed once.** The lines a receipt carries are the states - at signing time, usually `sent`. Later states live in the ledger and in - `handoff list`. A follow-up record that names the receipt is still to be - designed. +- **Follow-ups aren't signed automatically.** `--sign-updates` signs them + when someone runs it; no scheduler does. The TypeScript verifiers don't + check follow-up chains yet, and no shared test vectors exist for them. - **Payer reports are status only.** They never compare fields, so a payer handoff is never `recorded_*`. - **The FHIR profile needs the receiver to keep the sender's key.** It must diff --git a/packages/flow/openadapt_flow/cli_handoff_list.py b/packages/flow/openadapt_flow/cli_handoff_list.py index b92e8d6abe..be63cda65f 100644 --- a/packages/flow/openadapt_flow/cli_handoff_list.py +++ b/packages/flow/openadapt_flow/cli_handoff_list.py @@ -23,7 +23,7 @@ import sys from datetime import datetime from pathlib import Path -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: # pragma: no cover from openadapt_flow.handoffs.ledger import Handoff, HandoffLedger @@ -112,6 +112,12 @@ def register_handoff_list(sub: argparse._SubParsersAction) -> None: action="store_true", help="Print JSON: each handoff's status and its receipt line", ) + listing.add_argument( + "--sign-updates", + action="store_true", + help="With --run: sign a follow-up receipt for the handoffs whose state " + "changed since the run's receipt (receipt.update-N.json)", + ) listing.set_defaults(func=cmd_handoff_list) @@ -175,12 +181,19 @@ def cmd_handoff_list(args: argparse.Namespace) -> int: ledgers = _ledgers(args) if args.run: report = json.loads((Path(args.run) / "report.json").read_text("utf-8")) - handoffs = handoffs_for_run(report, ledgers) + handoffs = handoffs_for_run(report, ledgers, Path(args.run)) else: handoffs = [h for ledger in ledgers for h in ledger.entries()] except (OSError, ValueError) as exc: print(f"handoff list: {exc}", file=sys.stderr) return 2 + if args.sign_updates and not args.run: + print("handoff list: --sign-updates needs --run", file=sys.stderr) + return 2 + history = _history(Path(args.run), ledgers, args.sign_updates) if args.run else None + if history is not None and history.get("error"): + print(f"handoff list: {history['error']}", file=sys.stderr) + return 2 now: datetime = now_utc() if args.json: out = [] @@ -205,7 +218,10 @@ def cmd_handoff_list(args: argparse.Namespace) -> int: "receipt_line": item.line, } ) - print(json.dumps(out, indent=2)) + if history is not None: + print(json.dumps({"handoffs": out, "signed_history": history}, indent=2)) + else: + print(json.dumps(out, indent=2)) return 0 if not handoffs: print("No handoffs.") @@ -229,7 +245,53 @@ def cmd_handoff_list(args: argparse.Namespace) -> int: + (f"; who: {handoff.follow_up}" if key == "needs_follow_up" else "") ) print() + if history is not None: + _print_history(history) return 0 +def _history( + run_dir: Path, ledgers: list["HandoffLedger"], sign: bool +) -> Optional[dict[str, object]]: + """The run's signed handoff history: its receipt and follow-ups, verified + against this computer's key and pinned keys. With ``sign``, first sign a + follow-up for what changed.""" + + from openadapt_types import receipt as r + + if not (run_dir / r.RECEIPT_FILE).is_file(): + return {"error": "no receipt.json in the run"} if sign else None + try: + from openadapt_flow.handoffs.followup import sign_updates, verify_history + from openadapt_flow.offline_seal import seal_home, signer_for + from openadapt_flow.receipt_record import local_registry + + signed = None + if sign: + signed = sign_updates(run_dir, ledgers, signer=signer_for(seal_home())) + chain = verify_history(run_dir, local_registry()) + except ImportError: + return {"error": "openadapt-types has no follow-up receipts"} + except (OSError, ValueError) as exc: + return {"error": str(exc)} + return { + "signed_now": signed.name if signed is not None else None, + "verified": bool(chain.ok), + "reason": chain.reason, + "updates": len(chain.updates), + "lines": list(chain.lines), + } + + +def _print_history(history: dict[str, object]) -> None: + if history.get("signed_now"): + print(f"Signed {history['signed_now']}") + if not history["verified"]: + print(f"Signed history: not verified ({history['reason']})") + return + print(f"Signed history (receipt and {history['updates']} update(s), verified)") + for line in history["lines"]: # type: ignore[attr-defined] + print(f" {line}") + + __all__ = ["register_handoff_list"] diff --git a/packages/flow/openadapt_flow/handoffs/followup.py b/packages/flow/openadapt_flow/handoffs/followup.py new file mode 100644 index 0000000000..87cf6ba8c4 --- /dev/null +++ b/packages/flow/openadapt_flow/handoffs/followup.py @@ -0,0 +1,186 @@ +"""Follow-up receipts: a signed record of each change after the run's receipt. + +A run's receipt is signed once, when the run ends, so its handoff lines are +usually ``sent``. When a handoff later changes (acknowledged, recorded as +intended, recorded differently), :func:`sign_updates` signs a small +follow-up record: a ``record/run/v1`` statement that repeats the original's +predicate, names the original's payload digest in ``follows``, counts its +place in the chain (``sequence``), and carries only the confirmation lines +that changed. ``openadapt_types.receipt.verify_chain`` checks the chain, and +``handoff list --run`` shows it. + +Files in the run folder: + +- ``receipt.update-N.json``: the N-th follow-up (a DSSE envelope); +- ``receipt.update-N.private.json``: its openings (0600); +- ``receipt.handoffs.json``: which handoff each signed line belongs to, and + the line as signed, so a later update signs only what changed (0600, + local only: it names handoff ids, never values). +""" + +from __future__ import annotations + +import base64 +import json +import os +from pathlib import Path +from typing import Any, Mapping, Optional, Sequence + +from openadapt_flow.handoffs.ledger import Handoff, HandoffLedger +from openadapt_flow.handoffs.line import ( + build_confirmations, + handoffs_for_run, + place, + to_line, +) + +SIDECAR = "receipt.handoffs.json" +SCHEMA = "openadapt.receipt-handoffs/v1" + + +def update_file(sequence: int) -> str: + return f"receipt.update-{sequence}.json" + + +def update_private_file(sequence: int) -> str: + return f"receipt.update-{sequence}.private.json" + + +def _signature(handoff: Handoff) -> dict[str, Any]: + """What a signed line says, minus when it was observed: a new read of + the same state is not a change.""" + + item = to_line(handoff) + values = {k: v for k, v in item.values.items() if k != "observed_at"} + return {**item.line, "values": values} + + +def _write_json(path: Path, payload: Any, *, private: bool) -> None: + tmp = path.with_name(path.name + ".tmp") + fd = os.open( + tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600 if private else 0o644 + ) + with os.fdopen(fd, "w") as handle: + handle.write(json.dumps(payload, indent=2, sort_keys=True) + "\n") + os.replace(tmp, path) + + +def _sidecar(run_dir: Path) -> dict[str, Any]: + path = run_dir / SIDECAR + if not path.is_file(): + return {"schema": SCHEMA, "records": []} + data = json.loads(path.read_text("utf-8")) + if data.get("schema") != SCHEMA: + raise ValueError(f"{SIDECAR} is not {SCHEMA}") + return data + + +def record_signed(run_dir: Path, file: str, handoffs: Sequence[Handoff]) -> None: + """Remember which handoffs a signed record's lines are, in line order.""" + + data = _sidecar(run_dir) + data["records"].append( + { + "file": file, + "lines": [{"handoff": h.id, "signed": _signature(h)} for h in handoffs], + } + ) + _write_json(run_dir / SIDECAR, data, private=True) + + +def last_signed(run_dir: Path) -> dict[str, dict[str, Any]]: + """Each handoff's latest signed line, across the receipt and its updates.""" + + latest: dict[str, dict[str, Any]] = {} + for record in _sidecar(run_dir)["records"]: + for item in record["lines"]: + latest[item["handoff"]] = item["signed"] + return latest + + +def updates(run_dir: Path) -> list[Path]: + found = [] + sequence = 1 + while (run_dir / update_file(sequence)).is_file(): + found.append(run_dir / update_file(sequence)) + sequence += 1 + return found + + +def sign_updates( + run_dir: str | Path, + ledgers: Sequence[HandoffLedger], + *, + signer: Any, +) -> Optional[Path]: + """Sign one follow-up for every handoff of the run whose line changed + since it was last signed. None when nothing changed. Needs the run's + receipt (``receipt.json``).""" + + from openadapt_types import receipt as r + + from openadapt_flow.offline_seal import loads_strict + + run_dir = Path(run_dir) + original = loads_strict((run_dir / r.RECEIPT_FILE).read_text("utf-8")) + report = loads_strict((run_dir / "report.json").read_text("utf-8")) + signed = last_signed(run_dir) + statement = r.loads_strict(base64.b64decode(original["payload"])) + changed: list[Handoff] = [] + for handoff in place(statement, handoffs_for_run(report, list(ledgers), run_dir)): + if signed.get(handoff.id) != _signature(handoff): + changed.append(handoff) + if not changed: + return None + sequence = len(updates(run_dir)) + 1 + lines, openings = build_confirmations(changed) + follow_up = r.follow_up_statement(original, sequence, lines) + kid = r.key_id(signer.public_raw()) + envelope = r.sign_statement(follow_up, [(kid, signer.sign)]) + out = run_dir / update_file(sequence) + _write_json( + run_dir / update_private_file(sequence), + r.private_openings(envelope, openings), + private=True, + ) + _write_json(out, envelope, private=False) + record_signed(run_dir, out.name, changed) + return out + + +def verify_history(run_dir: str | Path, registry: Sequence[Any]) -> Any: + """``verify_chain`` over the run's receipt and its follow-ups, with + their private openings when present.""" + + from openadapt_types import receipt as r + + from openadapt_flow.offline_seal import loads_strict + + run_dir = Path(run_dir) + + def load(name: str) -> Optional[Mapping[str, Any]]: + path = run_dir / name + return loads_strict(path.read_text("utf-8")) if path.is_file() else None + + original = load(r.RECEIPT_FILE) + if original is None: + return None + chain = [loads_strict(p.read_text("utf-8")) for p in updates(run_dir)] + return r.verify_chain( + original, + chain, + registry, + openings=load(r.PRIVATE_FILE), + update_openings=[load(update_private_file(i + 1)) for i in range(len(chain))], + ) + + +__all__ = [ + "SIDECAR", + "last_signed", + "record_signed", + "sign_updates", + "update_file", + "updates", + "verify_history", +] diff --git a/packages/flow/openadapt_flow/handoffs/ledger.py b/packages/flow/openadapt_flow/handoffs/ledger.py index 76f7d3406d..565aa4c006 100644 --- a/packages/flow/openadapt_flow/handoffs/ledger.py +++ b/packages/flow/openadapt_flow/handoffs/ledger.py @@ -334,6 +334,9 @@ def send( step=step, ) self._write(handoff) + from openadapt_flow.handoffs.registry import note_ledger + + note_ledger(self.directory) return handoff def adopt(self, handoff: Handoff) -> Handoff: diff --git a/packages/flow/openadapt_flow/handoffs/line.py b/packages/flow/openadapt_flow/handoffs/line.py index aa97f68c3b..ea3aefd3de 100644 --- a/packages/flow/openadapt_flow/handoffs/line.py +++ b/packages/flow/openadapt_flow/handoffs/line.py @@ -163,22 +163,30 @@ def build_confirmations( def handoffs_for_run( - report: Mapping[str, Any], ledgers: Sequence[HandoffLedger] + report: Mapping[str, Any], + ledgers: Sequence[HandoffLedger], + run_dir: Optional[Any] = None, ) -> list[Handoff]: """The handoffs a run made, each with ``step`` set to its write's index. A deferred claim check is found by the ``deferred_check`` id on the - step's effect evidence; any other handoff by its ``run_id`` and ``step``. + step's effect evidence; any other handoff by its ``run_id``, which names + the report's ``run_id`` or the run directory (its path or its name). """ by_source: dict[str, Handoff] = {} by_run: list[Handoff] = [] - run_id = report.get("run_id") + names = {report.get("run_id")} + if run_dir is not None: + from pathlib import Path + + names |= {str(Path(run_dir)), str(Path(run_dir).resolve()), Path(run_dir).name} + names.discard(None) for ledger in ledgers: for handoff in ledger.entries(): if handoff.source: by_source[handoff.source] = handoff - if run_id and handoff.run_id == run_id: + if handoff.run_id and handoff.run_id in names: by_run.append(handoff) found: dict[str, Handoff] = {h.id: h for h in by_run} results = report.get("results") @@ -197,6 +205,16 @@ def handoffs_for_run( return sorted(found.values(), key=lambda h: (h.step or 0, h.sent_at, h.id)) +def place(statement: Mapping[str, Any], handoffs: Sequence[Handoff]) -> list[Handoff]: + """The handoffs as the statement will carry them: a handoff whose step + has no line on the statement goes on without a step.""" + + steps = {line["step"] for line in statement["predicate"].get("lines", [])} + return [ + h if h.step in steps else h.model_copy(update={"step": None}) for h in handoffs + ] + + def attach_confirmations( statement: dict[str, Any], openings: dict[str, dict[str, str]], @@ -208,10 +226,7 @@ def attach_confirmations( is signed: ``predicate.confirmations`` and their openings. A handoff whose step has no line on the statement is attached without a step.""" - steps = {line["step"] for line in statement["predicate"].get("lines", [])} - placed = [ - h if h.step in steps else h.model_copy(update={"step": None}) for h in handoffs - ] + placed = place(statement, handoffs) lines, opened = build_confirmations(placed, salt=salt) out = {**statement, "predicate": {**statement["predicate"], "confirmations": lines}} if not lines: @@ -223,6 +238,7 @@ def attach_confirmations( "KIND", "attach_confirmations", "handoffs_for_run", + "place", "REASONS_FOR_STATE", "ConfirmationLine", "build_confirmations", diff --git a/packages/flow/openadapt_flow/handoffs/registry.py b/packages/flow/openadapt_flow/handoffs/registry.py new file mode 100644 index 0000000000..d55420cd3e --- /dev/null +++ b/packages/flow/openadapt_flow/handoffs/registry.py @@ -0,0 +1,45 @@ +"""Which handoff ledgers a run used, so its receipt can carry their lines. + +A deferred claim check and ``HandoffLedger.send`` note their ledger here +while the run is going. The receipt hook (``receipt_record.receipt_after_run``) +reads the noted ledgers, plus any listed in ``OPENADAPT_HANDOFF_LEDGERS`` +(directories separated by the OS path separator), and attaches the lines of +the handoffs that belong to the run. Process-local: a receipt written by a +later process names its ledgers through the variable. +""" + +from __future__ import annotations + +import os +from pathlib import Path +from typing import Mapping, Optional + +from openadapt_flow.handoffs.ledger import HandoffLedger + +ENV = "OPENADAPT_HANDOFF_LEDGERS" +_NOTED: list[Path] = [] + + +def note_ledger(directory: str | Path) -> None: + path = Path(directory).resolve() + if path not in _NOTED: + _NOTED.append(path) + + +def forget() -> None: + """Clear the noted ledgers (tests).""" + _NOTED.clear() + + +def ledgers_for(env: Optional[Mapping[str, str]] = None) -> list[HandoffLedger]: + env = os.environ if env is None else env + paths = list(_NOTED) + for item in (env.get(ENV) or "").split(os.pathsep): + if item.strip(): + path = Path(item.strip()).expanduser().resolve() + if path not in paths: + paths.append(path) + return [HandoffLedger(path) for path in paths if path.is_dir()] + + +__all__ = ["ENV", "forget", "ledgers_for", "note_ledger"] diff --git a/packages/flow/openadapt_flow/receipt_record.py b/packages/flow/openadapt_flow/receipt_record.py index 0b53ffed34..57b5249f5b 100644 --- a/packages/flow/openadapt_flow/receipt_record.py +++ b/packages/flow/openadapt_flow/receipt_record.py @@ -261,9 +261,13 @@ def write_receipt_record( signer: Optional["SealSigner"] = None, home: Optional[Path] = None, flow_version: Optional[str] = None, + handoff_ledgers: Sequence[Any] = (), ) -> dict[str, Any]: """Write ``receipt.json`` and ``receipt.private.json`` for a finished run. + ``handoff_ledgers`` (``openadapt_flow.handoffs.HandoffLedger``): the run's + handoffs in them go on the receipt as counterparty confirmation lines. + Idempotent: an existing receipt over the same report bytes is kept. A receipt over different bytes is never silently replaced. """ @@ -309,6 +313,18 @@ def write_receipt_record( if flow_version is None: from openadapt_flow import __version__ as flow_version statement, openings = build_statement(report, digest, flow_version=flow_version) + placed: list[Any] = [] + if handoff_ledgers: + from openadapt_flow.handoffs.line import ( + attach_confirmations, + handoffs_for_run, + place, + ) + + handoffs = handoffs_for_run(report, list(handoff_ledgers), run_dir) + if handoffs: + placed = place(statement, handoffs) + statement, openings = attach_confirmations(statement, openings, handoffs) chosen = signer or signer_for(home) try: kid = r.key_id(chosen.public_raw()) @@ -317,6 +333,10 @@ def write_receipt_record( raise ReceiptRecordError(exc.code, str(exc)) from exc _write(run_dir / PRIVATE_FILE, r.private_openings(envelope, openings), private=True) _write(out, envelope) + if placed: + from openadapt_flow.handoffs.followup import record_signed + + record_signed(run_dir, RECEIPT_FILE, placed) return envelope @@ -335,8 +355,14 @@ def receipt_after_run( try: from openadapt_flow.offline_seal import seal_home, signer_for + from openadapt_flow.handoffs.registry import ledgers_for + home = seal_home(env) - write_receipt_record(Path(run_dir), signer=signer_for(home, env=env)) + write_receipt_record( + Path(run_dir), + signer=signer_for(home, env=env), + handoff_ledgers=ledgers_for(env), + ) except ImportError: return "receipt not written: openadapt-types is older than 0.25" except ReceiptRecordError as exc: diff --git a/packages/flow/openadapt_flow/runtime/effects/deferred_report.py b/packages/flow/openadapt_flow/runtime/effects/deferred_report.py index c091e77de5..3fe45ab247 100644 --- a/packages/flow/openadapt_flow/runtime/effects/deferred_report.py +++ b/packages/flow/openadapt_flow/runtime/effects/deferred_report.py @@ -618,6 +618,7 @@ def verify( unavailable=True, assurance=UNCHECKED, ) + _record_handoff(self.ledger, entry) return EffectVerdict( verdict=Verdict.INDETERMINATE, kind=expected.kind, @@ -631,6 +632,23 @@ def verify( ) +def _record_handoff(ledger: PendingLedger, entry: PendingCheck) -> None: + """The claim is now a handoff (``sent``), so the run's receipt can carry + its line. Never changes the check: a failure here is ignored, and + ``handoff list`` adds the handoff later from the pending entry.""" + + try: + from openadapt_flow.handoffs import payer + from openadapt_flow.handoffs.registry import note_ledger + + if entry.report_format in payer.COUNTERPARTY_FORMATS: + handoffs = payer.handoff_ledger(ledger) + handoffs.adopt(payer.as_handoff(entry)) + note_ledger(handoffs.directory) + except Exception: # noqa: BLE001 - bookkeeping must never fail the save + return + + def build_deferred_report_verifier( spec: DeferredReportSpec, params: Optional[Mapping[str, object]] = None ) -> DeferredReportVerifier: diff --git a/packages/flow/tests/test_handoff_receipts.py b/packages/flow/tests/test_handoff_receipts.py new file mode 100644 index 0000000000..f8ee49fc0d --- /dev/null +++ b/packages/flow/tests/test_handoff_receipts.py @@ -0,0 +1,313 @@ +"""Receipts carry handoff lines, and follow-up receipts record later changes. + +A real run through the replayer saves a claim with a deferred check; the +after-run hook writes the receipt with the claim's ``sent`` line. A referral +handoff of the same run is read back later, and ``sign_updates`` signs a +follow-up for each change. ``verify_chain`` checks the chain. Synthetic data. +""" + +from __future__ import annotations + +import base64 +import json +from datetime import datetime, timezone +from pathlib import Path + +import pytest + +r = pytest.importorskip("openadapt_types.receipt") +if not hasattr(r, "verify_chain"): + pytest.skip("openadapt-types without follow-up receipts", allow_module_level=True) +pytest.importorskip("cryptography") + +from openadapt_flow.handoffs import followup, intake, registry # noqa: E402 +from openadapt_flow.handoffs.ledger import HandoffLedger # noqa: E402 +from openadapt_flow.handoffs.payer import SettleRecorder, handoff_ledger # noqa: E402 +from openadapt_flow.handoffs.readers import ReadResult # noqa: E402 +from openadapt_flow.ir import ( # noqa: E402 + ActionKind, + Postcondition, + PostconditionKind, + Step, + Workflow, +) +from openadapt_flow.runtime.effects.deferred_report import ( # noqa: E402 + DeferredReportVerifier, + PendingLedger, +) +from openadapt_flow.runtime.replayer import Replayer # noqa: E402 +from tests.test_deferred_report import ( # noqa: E402 + FMT_277, + _claim_effect, + _spec, + ack_277ca, +) +from tests.test_replayer import FakeBackend, FakeVision, Match # noqa: E402 + +FIELDS = { + "family_name": ("Quill", "text"), + "birth_date": ("1984-03-09", "date"), +} + + +class Fake: + read_method = "api_readback" + + def __init__(self, result: ReadResult) -> None: + self.result = result + + def read(self, key: str) -> ReadResult: + return self.result + + +def _found(**changes: str) -> ReadResult: + fields = {"family_name": "Quill", "birth_date": "1984-03-09", **changes} + return ReadResult("found", fields=fields) + + +@pytest.fixture +def env(tmp_path, monkeypatch): + registry.forget() + monkeypatch.setenv("OPENADAPT_SEAL_HOME", str(tmp_path / "seal")) + monkeypatch.delenv("OPENADAPT_RECEIPT", raising=False) + monkeypatch.delenv(registry.ENV, raising=False) + yield {"OPENADAPT_SEAL_HOME": str(tmp_path / "seal")} + registry.forget() + + +def _run(tmp_path: Path) -> Path: + workflow = Workflow( + name="claim", + steps=[ + Step( + id="submit", + intent="submit claim", + action=ActionKind.KEY, + key="Enter", + risk="irreversible", + expect=[ + Postcondition( + kind=PostconditionKind.TEXT_PRESENT, + text="Submitted", + timeout_s=0.2, + ) + ], + effects=[_claim_effect()], + ) + ], + ) + vision = FakeVision() + vision.text_results = { + "Submitted": Match(point=(50, 10), region=(30, 5, 40, 10), confidence=0.9) + } + bundle = tmp_path / "bundle" + (bundle / "templates").mkdir(parents=True) + run_dir = tmp_path / "run" + verifier = DeferredReportVerifier(_spec(tmp_path), "CLM-1001") + report = Replayer( + FakeBackend(), vision=vision, effect_verifier=verifier, poll_interval_s=0.01 + ).run(workflow, bundle_dir=bundle, run_dir=run_dir) + assert report.transaction_outcome == "SAVED_AWAITING_CHECK" + return run_dir + + +def _registry(tmp_path: Path): + from openadapt_flow.receipt_record import local_registry + + return local_registry(tmp_path / "seal") + + +def _payload(path: Path) -> dict: + envelope = json.loads(path.read_text()) + return json.loads(base64.b64decode(envelope["payload"])) + + +def test_a_real_run_writes_a_receipt_that_carries_the_claims_line(tmp_path, env): + from openadapt_flow.receipt_record import receipt_after_run, verify_run_receipt + + run_dir = _run(tmp_path) + note = receipt_after_run(run_dir, env) + assert note and note.startswith("receipt:"), note + confirmations = _payload(run_dir / "receipt.json")["predicate"]["confirmations"] + assert [ + (c["for_step"], c["system_kind"], c["read_method"], c["state"]) + for c in confirmations + ] == [(0, "payer_portal", "acknowledgment_message", "sent")] + result = verify_run_receipt(run_dir, _registry(tmp_path)) + assert result.ok, (result.reason, result.detail) + assert result.confirmation_lines[0].startswith("Sent to the other party") + sidecar = run_dir / followup.SIDECAR + assert sidecar.stat().st_mode & 0o777 == 0o600 + assert "CLM-1001" not in sidecar.read_text() + + +def test_a_run_without_handoffs_has_a_receipt_without_confirmations(tmp_path, env): + from openadapt_flow.receipt_record import receipt_after_run + + run_dir = _run(tmp_path) + registry.forget() + # The claim's ledger isn't noted or named: nothing to attach. + receipt_after_run(run_dir, env) + assert "confirmations" not in _payload(run_dir / "receipt.json")["predicate"] + + +def test_follow_ups_record_each_change_and_verify_as_a_chain(tmp_path, env): + from openadapt_flow.offline_seal import signer_for + from openadapt_flow.receipt_record import receipt_after_run + + run_dir = _run(tmp_path) + referrals = HandoffLedger(tmp_path / "referrals") + referral = referrals.send( + "REF-1", + FIELDS, + counterparty="receiving clinic", + system_kind="ehr", + follow_up_hours=24, + run_id=str(run_dir), + step=0, + ) + receipt_after_run(run_dir, env) + states = [ + c["state"] + for c in _payload(run_dir / "receipt.json")["predicate"]["confirmations"] + ] + assert sorted(states) == ["sent", "sent"] + signer = signer_for(tmp_path / "seal") + claims = handoff_ledger(PendingLedger(tmp_path / "ledger")) + ledgers = [claims, referrals] + + # Nothing changed yet: no update. + assert followup.sign_updates(run_dir, ledgers, signer=signer) is None + + # The referral is recorded as intended: update 1 carries only its line. + intake.check(referrals, referral.id, "REF-1", Fake(_found())) + first = followup.sign_updates(run_dir, ledgers, signer=signer) + assert first is not None and first.name == "receipt.update-1.json" + p1 = _payload(first)["predicate"] + assert [c["state"] for c in p1["confirmations"]] == ["recorded_as_intended"] + original = _payload(run_dir / "receipt.json") + assert p1["follows"]["sequence"] == 1 + assert p1["lines"] == original["predicate"]["lines"] + + # The payer acknowledges the claim, and the referral now reads + # differently: update 2 carries both changes. + pending = PendingLedger(tmp_path / "ledger") + pending.settle( + ack_277ca(datetime.now(timezone.utc).replace(tzinfo=None)), + FMT_277, + observer=SettleRecorder(pending, "x12-277ca", None), + ) + intake.check(referrals, referral.id, "REF-1", Fake(_found(birth_date="1984-03-10"))) + second = followup.sign_updates(run_dir, ledgers, signer=signer) + assert second is not None and second.name == "receipt.update-2.json" + assert sorted( + c["state"] for c in _payload(second)["predicate"]["confirmations"] + ) == [ + "acknowledged", + "recorded_differently", + ] + assert followup.sign_updates(run_dir, ledgers, signer=signer) is None + + chain = followup.verify_history(run_dir, _registry(tmp_path)) + assert chain.ok, (chain.reason, chain.detail) + assert len(chain.lines) == 5 + assert all(line.startswith("Sent to the other party") for line in chain.lines[:2]) + assert [line.split(":")[0] for line in chain.lines[2:]] == [ + "Update 1", + "Update 2", + "Update 2", + ] + assert chain.lines[2].startswith("Update 1: Confirmed in the other party's system") + assert any("1 field differs" in line for line in chain.lines[3:]) + assert any("Acknowledged by the other party" in line for line in chain.lines[3:]) + + +def _chain_setup(tmp_path, env): + from openadapt_flow.offline_seal import signer_for + from openadapt_flow.receipt_record import receipt_after_run + + run_dir = _run(tmp_path) + referrals = HandoffLedger(tmp_path / "referrals") + referral = referrals.send( + "REF-1", + FIELDS, + counterparty="receiving clinic", + system_kind="ehr", + follow_up_hours=24, + run_id=str(run_dir), + step=0, + ) + receipt_after_run(run_dir, env) + signer = signer_for(tmp_path / "seal") + intake.check(referrals, referral.id, "REF-1", Fake(_found())) + followup.sign_updates(run_dir, [referrals], signer=signer) + intake.check(referrals, referral.id, "REF-1", Fake(_found(birth_date="1984-03-10"))) + followup.sign_updates(run_dir, [referrals], signer=signer) + return run_dir, signer + + +def test_a_broken_chain_is_refused(tmp_path, env): + run_dir, signer = _chain_setup(tmp_path, env) + registry_ = _registry(tmp_path) + original = json.loads((run_dir / "receipt.json").read_text()) + one = json.loads((run_dir / "receipt.update-1.json").read_text()) + two = json.loads((run_dir / "receipt.update-2.json").read_text()) + assert r.verify_chain(original, [one, two], registry_).ok + assert r.verify_chain(original, [two, one], registry_).reason == "out_of_sequence" + assert r.verify_chain(original, [two], registry_).reason == "out_of_sequence" + assert r.verify_chain(one, [], registry_).reason == "original_is_follow_up" + kid = r.key_id(signer.public_raw()) + + def resign(statement): + return r.sign_statement(statement, [(kid, signer.sign)]) + + wrong = _payload(run_dir / "receipt.update-1.json") + wrong["predicate"]["follows"]["receipt"]["sha256"] = "0" * 64 + assert r.verify_chain(original, [resign(wrong)], registry_).reason == ( + "wrong_original" + ) + changed = _payload(run_dir / "receipt.update-1.json") + changed["predicate"]["model_calls"] = 7 + assert r.verify_chain(original, [resign(changed)], registry_).reason == ( + "changed_original" + ) + tampered = dict(one, payload=two["payload"]) + assert r.verify_chain(original, [tampered], registry_).reason == "update_refused" + empty = _payload(run_dir / "receipt.update-1.json") + empty["predicate"]["confirmations"] = [] + with pytest.raises(ValueError, match="at least one confirmation"): + resign(empty) + + +def test_handoff_list_signs_updates_and_shows_the_history(tmp_path, env, capsys): + from openadapt_flow.__main__ import main + from openadapt_flow.receipt_record import receipt_after_run + + run_dir = _run(tmp_path) + referrals = HandoffLedger(tmp_path / "referrals") + referral = referrals.send( + "REF-1", + FIELDS, + counterparty="receiving clinic", + system_kind="ehr", + follow_up_hours=24, + run_id=str(run_dir), + step=0, + ) + receipt_after_run(run_dir, env) + intake.check(referrals, referral.id, "REF-1", Fake(_found())) + argv = [ + "handoff", + "list", + "--ledger", + str(referrals.directory), + "--run", + str(run_dir), + ] + assert main([*argv, "--sign-updates"]) == 0 + out = capsys.readouterr().out + assert "Signed receipt.update-1.json" in out + assert "Signed history (receipt and 1 update(s), verified)" in out + assert "Update 1: Confirmed in the other party's system" in out + assert main(argv) == 0 + assert "Signed receipt.update" not in capsys.readouterr().out diff --git a/packages/types/openadapt_types/receipt.py b/packages/types/openadapt_types/receipt.py index 92dcb3ef69..6451b8bd37 100644 --- a/packages/types/openadapt_types/receipt.py +++ b/packages/types/openadapt_types/receipt.py @@ -284,6 +284,14 @@ class Confirmation(_Closed): commitments: dict[StrictStr, StrictStr] = Field(min_length=2, max_length=34) +class Follows(_Closed): + """The receipt a follow-up record updates: the SHA-256 of the original + receipt's DSSE payload bytes, and this update's place in the chain.""" + + receipt: Digest + sequence: Count = Field(ge=1, le=MAX_LINES) + + class RunPredicateV1(_Closed): program: Program started_hour: StrictStr = Field(pattern=_HOUR) @@ -299,6 +307,11 @@ class RunPredicateV1(_Closed): confirmations: list[Confirmation] = Field(default_factory=list, max_length=64) #: The approval binding; omitted when the run recorded none. approval: Optional[Approval] = None + #: Set only on a follow-up record: a later, separately signed statement + #: that repeats the original receipt's predicate and carries only the + #: counterparty confirmations that changed since. Omitted otherwise, so a + #: receipt is byte-identical to one made before follow-ups existed. + follows: Optional[Follows] = None class RunStatementV1(_Closed): @@ -313,6 +326,8 @@ def wire(self) -> dict[str, Any]: del out["predicate"]["confirmations"] if out["predicate"]["approval"] is None: del out["predicate"]["approval"] + if out["predicate"]["follows"] is None: + del out["predicate"]["follows"] for subject in out["subject"]: if subject["media_type"] is None: del subject["media_type"] @@ -362,6 +377,8 @@ def _check_approval(a: Approval) -> Optional[str]: def _check_consistent(statement: RunStatementV1) -> Optional[str]: """A closed statement that contradicts itself is refused, never repaired.""" p = statement.predicate + if p.follows is not None and not p.confirmations: + return "a follow-up record carries at least one confirmation" names = [s.name for s in statement.subject] if len(set(names)) != len(names) or not {"report.json", "report.canonical"} & set( names @@ -1135,6 +1152,132 @@ def confirmation_line(c: Confirmation, observed_at: Optional[str] = None) -> str return f"Sent to the other party{at}, not confirmed" +# -- follow-up records ------------------------------------------------------------ + +#: Predicate fields a follow-up copies from its original, unchanged. +FOLLOW_UP_COPIED: Final = ( + "program", + "started_hour", + "outcome", + "reason_code", + "steps", + "lines", + "checks", + "model_calls", + "disclosure", + "approval", +) +#: Why a chain of follow-ups is refused (beyond a refusal of one record). +ChainRefusal = Literal[ + "original_refused", + "original_is_follow_up", + "update_refused", + "not_a_follow_up", + "wrong_original", + "out_of_sequence", + "changed_original", +] + + +def payload_sha256(envelope: Mapping[str, Any]) -> str: + """SHA-256 of an envelope's DSSE payload bytes: what ``follows`` names.""" + return hashlib.sha256( + base64.b64decode(str(envelope["payload"]), validate=True) + ).hexdigest() + + +@dataclass(frozen=True) +class ChainVerification: + ok: bool + reason: Optional[ChainRefusal] = None + detail: str = "" + original: Optional[ReceiptVerification] = None + updates: tuple[ReceiptVerification, ...] = () + #: The original's confirmation lines, then ``Update N: `` for each + #: follow-up's lines, in order. Never merged with the signer lines. + lines: tuple[str, ...] = () + + +def follow_up_statement( + original: Mapping[str, Any], sequence: int, confirmations: Sequence[Any] +) -> dict[str, Any]: + """A follow-up statement: ``original``'s statement (a dict from its + payload) with only the changed ``confirmations`` and ``follows`` set. + ``original`` is the original receipt's envelope.""" + payload = loads_strict(base64.b64decode(str(original["payload"]), validate=True)) + predicate = {k: v for k, v in payload["predicate"].items() if k in FOLLOW_UP_COPIED} + predicate["confirmations"] = list(confirmations) + predicate["follows"] = { + "receipt": {"sha256": payload_sha256(original)}, + "sequence": sequence, + } + return {**payload, "predicate": predicate} + + +def verify_chain( + original: Mapping[str, Any], + updates: Sequence[Mapping[str, Any]], + registry: Sequence[RoleKey], + *, + openings: Optional[Mapping[str, Any]] = None, + update_openings: Sequence[Optional[Mapping[str, Any]]] = (), +) -> ChainVerification: + """Verify a receipt and its follow-up records, in order. + + Each follow-up must verify on its own, name the original's payload + digest in ``follows``, count 1, 2, 3 in ``sequence``, and copy every + other predicate field and the subjects unchanged. Any failure refuses + the whole chain. A valid chain shows the original's confirmation lines + and then each update's, labelled ``Update N``. + """ + first = verify_receipt(original, registry, openings=openings) + if not first.ok or first.statement is None: + return ChainVerification(False, "original_refused", first.detail, first) + base = first.statement + if "follows" in base["predicate"]: + return ChainVerification( + False, "original_is_follow_up", "the first record is a follow-up", first + ) + digest = payload_sha256(original) + lines = list(first.confirmation_lines) + checked: list[ReceiptVerification] = [] + for index, update in enumerate(updates): + opened = update_openings[index] if index < len(update_openings) else None + result = verify_receipt(update, registry, openings=opened) + checked.append(result) + if not result.ok or result.statement is None: + return ChainVerification( + False, + "update_refused", + f"update {index + 1}: {result.reason}", + first, + tuple(checked), + ) + predicate = result.statement["predicate"] + follows = predicate.get("follows") + if not isinstance(follows, Mapping): + return ChainVerification( + False, "not_a_follow_up", f"update {index + 1}", first, tuple(checked) + ) + if follows["receipt"]["sha256"] != digest: + return ChainVerification( + False, "wrong_original", f"update {index + 1}", first, tuple(checked) + ) + if follows["sequence"] != index + 1: + return ChainVerification( + False, "out_of_sequence", f"update {index + 1}", first, tuple(checked) + ) + same = result.statement["subject"] == base["subject"] and all( + predicate.get(k) == base["predicate"].get(k) for k in FOLLOW_UP_COPIED + ) + if not same: + return ChainVerification( + False, "changed_original", f"update {index + 1}", first, tuple(checked) + ) + lines += [f"Update {index + 1}: {line}" for line in result.confirmation_lines] + return ChainVerification(True, None, "", first, tuple(checked), tuple(lines)) + + def _check_openings( openings: Any, commitments: Mapping[str, str], diff --git a/packages/types/tests/test_receipt_follow_up.py b/packages/types/tests/test_receipt_follow_up.py new file mode 100644 index 0000000000..56ddbcde17 --- /dev/null +++ b/packages/types/tests/test_receipt_follow_up.py @@ -0,0 +1,103 @@ +"""Follow-up records: a later signed update to a receipt's counterparty lines.""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path + +import pytest + +pytest.importorskip("cryptography") + +from openadapt_types import receipt as r # noqa: E402 + +_GEN = Path(__file__).parent / "vectors" / "record-run-v1" / "generate.py" +_spec = importlib.util.spec_from_file_location("receipt_vector_generate", _GEN) +gen = importlib.util.module_from_spec(_spec) +assert _spec.loader is not None +_spec.loader.exec_module(gen) + + +def _registry(): + return r.parse_registry(gen.REGISTRY) + + +def _sign(statement): + return r.sign_statement(statement, [gen.signer("this_computer")]) + + +def _original(): + statement, openings = gen._confirmed("sent") + return _sign(statement), openings + + +def _update(original, sequence, state): + updated, _ = gen._confirmed(state) + return _sign( + r.follow_up_statement(original, sequence, updated["predicate"]["confirmations"]) + ) + + +def test_a_chain_verifies_and_labels_each_update(): + original, openings = _original() + one = _update(original, 1, "acknowledged") + two = _update(original, 2, "recorded_as_intended") + chain = r.verify_chain( + original, + [one, two], + _registry(), + openings=r.private_openings(original, openings), + ) + assert chain.ok, chain + assert chain.lines == ( + "Sent to the other party at 2026-11-20T23:41:07Z, not confirmed", + "Update 1: Acknowledged by the other party", + "Update 2: Confirmed in the other party's system", + ) + + +def test_a_receipt_without_follows_is_byte_identical(): + statement, _ = gen._confirmed("sent") + assert ( + "follows" not in r.RunStatementV1.model_validate(statement).wire()["predicate"] + ) + + +@pytest.mark.parametrize( + "build,reason", + [ + (lambda o: [_update(o, 2, "acknowledged")], "out_of_sequence"), + (lambda o: [_sign(gen._confirmed("acknowledged")[0])], "not_a_follow_up"), + ], +) +def test_broken_chains_are_refused(build, reason): + original, _ = _original() + chain = r.verify_chain(original, build(original), _registry()) + assert (chain.ok, chain.reason) == (False, reason) + + +def test_a_follow_up_naming_another_receipt_or_changing_it_is_refused(): + original, _ = _original() + update = _update(original, 1, "acknowledged") + stmt = r.follow_up_statement( + original, 1, gen._confirmed("acknowledged")[0]["predicate"]["confirmations"] + ) + stmt["predicate"]["follows"]["receipt"]["sha256"] = "0" * 64 + assert ( + r.verify_chain(original, [_sign(stmt)], _registry()).reason == "wrong_original" + ) + changed = r.follow_up_statement( + original, 1, gen._confirmed("acknowledged")[0]["predicate"]["confirmations"] + ) + changed["predicate"]["model_calls"] = 9 + assert ( + r.verify_chain(original, [_sign(changed)], _registry()).reason + == "changed_original" + ) + assert r.verify_chain(update, [], _registry()).reason == "original_is_follow_up" + + +def test_an_empty_follow_up_cannot_be_signed(): + original, _ = _original() + with pytest.raises(ValueError, match="at least one confirmation"): + _sign(r.follow_up_statement(original, 1, [])) From dc07e1fe79e4c469a629205a10997e604121cb13 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 10:01:32 -0500 Subject: [PATCH 11/18] fix(handoffs): fail closed on lines that can't hold every compared field to_line refuses a handoff with more than 31 compared fields, or whose differing field ids aren't among them, so differing_count always matches judge(); the ledger model caps fields at 31. handoffs_for_run matches the report's run_id or the run directory's resolved path, never its bare folder name. sign_updates verifies the run's receipt against the signing key before copying it. write_receipt_record reports an unplaceable handoff as a receipt error. --- .../flow/openadapt_flow/handoffs/followup.py | 10 ++++- .../flow/openadapt_flow/handoffs/ledger.py | 3 +- packages/flow/openadapt_flow/handoffs/line.py | 39 +++++++++++++---- .../flow/openadapt_flow/receipt_record.py | 9 +++- packages/flow/tests/test_handoff_receipts.py | 31 ++++++++++++++ packages/flow/tests/test_handoffs.py | 42 +++++++++++++++++++ 6 files changed, 122 insertions(+), 12 deletions(-) diff --git a/packages/flow/openadapt_flow/handoffs/followup.py b/packages/flow/openadapt_flow/handoffs/followup.py index 87cf6ba8c4..092825d843 100644 --- a/packages/flow/openadapt_flow/handoffs/followup.py +++ b/packages/flow/openadapt_flow/handoffs/followup.py @@ -123,6 +123,15 @@ def sign_updates( run_dir = Path(run_dir) original = loads_strict((run_dir / r.RECEIPT_FILE).read_text("utf-8")) + # Copy only a receipt that verifies, and only extend one this key signed: + # verify_chain refuses a follow-up from any other key. + kid = r.key_id(signer.public_raw()) + own = r.RoleKey( + kid, base64.b64encode(signer.public_raw()).decode("ascii"), "this_computer" + ) + checked = r.verify_receipt(original, [own]) + if not checked.ok: + raise ValueError(f"the run's receipt does not verify: {checked.reason}") report = loads_strict((run_dir / "report.json").read_text("utf-8")) signed = last_signed(run_dir) statement = r.loads_strict(base64.b64decode(original["payload"])) @@ -135,7 +144,6 @@ def sign_updates( sequence = len(updates(run_dir)) + 1 lines, openings = build_confirmations(changed) follow_up = r.follow_up_statement(original, sequence, lines) - kid = r.key_id(signer.public_raw()) envelope = r.sign_statement(follow_up, [(kid, signer.sign)]) out = run_dir / update_file(sequence) _write_json( diff --git a/packages/flow/openadapt_flow/handoffs/ledger.py b/packages/flow/openadapt_flow/handoffs/ledger.py index 565aa4c006..b197911375 100644 --- a/packages/flow/openadapt_flow/handoffs/ledger.py +++ b/packages/flow/openadapt_flow/handoffs/ledger.py @@ -136,7 +136,8 @@ class Handoff(_Closed): #: Who follows up when it is overdue or differs ("billing", "referrals desk"). follow_up: str = Field(default="the sender", max_length=_LABEL_MAX) key_digest: str = Field(pattern=_DIGEST) - fields: dict[str, FieldSpec] = Field(default_factory=dict, max_length=64) + #: At most 31 fields: every compared field must fit on the receipt line. + fields: dict[str, FieldSpec] = Field(default_factory=dict, max_length=31) #: Where it came from: a deferred check's id, or a run's id. source: Optional[str] = Field(default=None, max_length=128) run_id: Optional[str] = Field(default=None, max_length=128) diff --git a/packages/flow/openadapt_flow/handoffs/line.py b/packages/flow/openadapt_flow/handoffs/line.py index ea3aefd3de..eee3378223 100644 --- a/packages/flow/openadapt_flow/handoffs/line.py +++ b/packages/flow/openadapt_flow/handoffs/line.py @@ -111,7 +111,15 @@ def to_line(handoff: Handoff) -> ConfirmationLine: field_ids: list[str] = [] differing = 0 if last is not None and last.strength == "field_readback" and state != "sent": - for index, field_id in enumerate(sorted(handoff.fields)[:_MAX_FIELDS]): + # Fail closed: every compared field must fit on the line, and every + # differing field must be one of them, so differing_count is never + # short of what judge() found. + if len(handoff.fields) > _MAX_FIELDS: + raise ValueError(f"a handoff line holds at most {_MAX_FIELDS} fields") + unknown = set(last.differing_fields) - set(handoff.fields) + if unknown: + raise ValueError("a differing field is not one the handoff compared") + for index, field_id in enumerate(sorted(handoff.fields)): seen = ( last.observed_digests.get(field_id) or handoff.fields[field_id].digest ) @@ -123,6 +131,10 @@ def to_line(handoff: Handoff) -> ConfirmationLine: ":differs" if differs else "" ) field_ids.append(field_id) + if state == "recorded_differently" and not differing: + raise ValueError( + "a recorded_differently read-back names no differing field" + ) line = { "kind": KIND, "for_step": handoff.step, @@ -171,22 +183,33 @@ def handoffs_for_run( A deferred claim check is found by the ``deferred_check`` id on the step's effect evidence; any other handoff by its ``run_id``, which names - the report's ``run_id`` or the run directory (its path or its name). + the report's ``run_id`` or the run directory's resolved path. """ by_source: dict[str, Handoff] = {} by_run: list[Handoff] = [] - names = {report.get("run_id")} - if run_dir is not None: - from pathlib import Path + from pathlib import Path + + run_id = report.get("run_id") + # The resolved directory only, never its bare name: two runs can share a + # folder name. + directory = Path(run_dir).resolve() if run_dir is not None else None + + def ours(value: Optional[str]) -> bool: + if not value: + return False + if isinstance(run_id, str) and run_id and value == run_id: + return True + path = Path(value) + return ( + directory is not None and path.is_absolute() and path.resolve() == directory + ) - names |= {str(Path(run_dir)), str(Path(run_dir).resolve()), Path(run_dir).name} - names.discard(None) for ledger in ledgers: for handoff in ledger.entries(): if handoff.source: by_source[handoff.source] = handoff - if handoff.run_id and handoff.run_id in names: + if ours(handoff.run_id): by_run.append(handoff) found: dict[str, Handoff] = {h.id: h for h in by_run} results = report.get("results") diff --git a/packages/flow/openadapt_flow/receipt_record.py b/packages/flow/openadapt_flow/receipt_record.py index 5b7c8e221d..40bf182491 100644 --- a/packages/flow/openadapt_flow/receipt_record.py +++ b/packages/flow/openadapt_flow/receipt_record.py @@ -330,8 +330,13 @@ def write_receipt_record( handoffs = handoffs_for_run(report, list(handoff_ledgers), run_dir) if handoffs: - placed = place(statement, handoffs) - statement, openings = attach_confirmations(statement, openings, handoffs) + try: + placed = place(statement, handoffs) + statement, openings = attach_confirmations( + statement, openings, handoffs + ) + except ValueError as exc: + raise ReceiptRecordError("handoff_unplaceable", str(exc)) from exc chosen = signer or signer_for(home) try: kid = r.key_id(chosen.public_raw()) diff --git a/packages/flow/tests/test_handoff_receipts.py b/packages/flow/tests/test_handoff_receipts.py index f8ee49fc0d..10c838277c 100644 --- a/packages/flow/tests/test_handoff_receipts.py +++ b/packages/flow/tests/test_handoff_receipts.py @@ -279,6 +279,37 @@ def resign(statement): resign(empty) +def test_sign_updates_refuses_a_receipt_it_cannot_verify_or_did_not_sign(tmp_path, env): + from openadapt_flow.offline_seal import signer_for + + run_dir, signer = _chain_setup(tmp_path, env) + referrals = HandoffLedger(tmp_path / "referrals") + (referral,) = referrals.entries() + intake.check(referrals, referral.id, "REF-1", Fake(_found())) + receipt = run_dir / "receipt.json" + good = receipt.read_text() + envelope = json.loads(good) + other = _payload(receipt) + other["predicate"]["model_calls"] = 9 + receipt.write_text( + json.dumps( + dict( + envelope, + payload=r.sign_statement( + other, [(r.key_id(signer.public_raw()), signer.sign)] + )["payload"], + ) + ) + ) + with pytest.raises(ValueError, match="does not verify"): + followup.sign_updates(run_dir, [referrals], signer=signer) + receipt.write_text(good) + stranger = signer_for(tmp_path / "stranger-seal") + with pytest.raises(ValueError, match="does not verify"): + followup.sign_updates(run_dir, [referrals], signer=stranger) + assert not (run_dir / "receipt.update-3.json").exists() + + def test_handoff_list_signs_updates_and_shows_the_history(tmp_path, env, capsys): from openadapt_flow.__main__ import main from openadapt_flow.receipt_record import receipt_after_run diff --git a/packages/flow/tests/test_handoffs.py b/packages/flow/tests/test_handoffs.py index c5bb3d1454..9d05972fb9 100644 --- a/packages/flow/tests/test_handoffs.py +++ b/packages/flow/tests/test_handoffs.py @@ -427,6 +427,48 @@ def test_lines_follow_the_schema_rules(tmp_path): assert rejected.values["reason"] == "rejected_by_counterparty" +def test_a_line_fails_closed_when_a_compared_field_would_not_fit(tmp_path): + ledger, h = _referral(tmp_path) + h = intake.check(ledger, h.id, "REF-0001", Fake(_found(birth_date="1984-03-10"))) + spec = next(iter(h.fields.values())) + wide = h.model_construct( + **{**dict(h), "fields": {f"f{i:02d}": spec for i in range(32)}} + ) + with pytest.raises(ValueError, match="at most 31 fields"): + line.to_line(wide) + with pytest.raises(ValueError): + type(h).model_validate({**h.model_dump(), "fields": dict(wide.fields)}) + last = h.observations[-1].model_copy(update={"differing_fields": ["not_sent"]}) + stray = h.model_copy(update={"observations": [*h.observations[:-1], last]}) + with pytest.raises(ValueError, match="not one the handoff compared"): + line.to_line(stray) + + +def test_run_match_never_by_folder_name(tmp_path): + """A handoff belongs to a run by its run_id or resolved path only.""" + ledger = HandoffLedger(tmp_path / "handoffs") + run_dir = tmp_path / "r" / "run-a" + run_dir.mkdir(parents=True) + for run_id, key in [ + ("run-a", "REF-0001"), # the folder's bare name: another run's id + (str(tmp_path / "o" / "run-a"), "REF-0002"), # same name, other folder + (str(run_dir), "REF-0003"), + ("rpt-1", "REF-0004"), + ]: + ledger.send( + key, + FIELDS, + counterparty="receiving clinic", + system_kind="ehr", + follow_up="referrals desk", + follow_up_hours=24, + run_id=run_id, + step=0, + ) + found = line.handoffs_for_run({"run_id": "rpt-1"}, [ledger], run_dir) + assert sorted(h.run_id for h in found) == sorted(["rpt-1", str(run_dir)]) + + def test_lines_validate_against_the_receipt_schema_and_sign(tmp_path): r = pytest.importorskip("openadapt_types.receipt") if not hasattr(r, "Confirmation"): From 754add8fa7c1aae9e8e76c816accfd669d24522a Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 10:10:27 -0500 Subject: [PATCH 12/18] fix(handoffs): extend only a signed history that verifies sign_updates verifies the receipt and every update already written, against the signing key alone, before it signs the next one. handoff list exits 1 when the run's signed history does not verify. --- .../flow/openadapt_flow/cli_handoff_list.py | 10 +++++++--- .../flow/openadapt_flow/handoffs/followup.py | 15 ++++++++++----- packages/flow/tests/test_handoff_receipts.py | 18 ++++++++++++++++++ 3 files changed, 35 insertions(+), 8 deletions(-) diff --git a/packages/flow/openadapt_flow/cli_handoff_list.py b/packages/flow/openadapt_flow/cli_handoff_list.py index be63cda65f..5852d18be3 100644 --- a/packages/flow/openadapt_flow/cli_handoff_list.py +++ b/packages/flow/openadapt_flow/cli_handoff_list.py @@ -194,6 +194,8 @@ def cmd_handoff_list(args: argparse.Namespace) -> int: if history is not None and history.get("error"): print(f"handoff list: {history['error']}", file=sys.stderr) return 2 + # A signed history that doesn't verify fails the command, after listing. + status_code = 1 if history is not None and not history.get("verified") else 0 now: datetime = now_utc() if args.json: out = [] @@ -222,10 +224,12 @@ def cmd_handoff_list(args: argparse.Namespace) -> int: print(json.dumps({"handoffs": out, "signed_history": history}, indent=2)) else: print(json.dumps(out, indent=2)) - return 0 + return status_code if not handoffs: print("No handoffs.") - return 0 + if history is not None: + _print_history(history) + return status_code grouped: dict[str, list["Handoff"]] = {key: [] for key, _ in _GROUPS} for handoff in handoffs: grouped[handoff.status(now)].append(handoff) @@ -247,7 +251,7 @@ def cmd_handoff_list(args: argparse.Namespace) -> int: print() if history is not None: _print_history(history) - return 0 + return status_code def _history( diff --git a/packages/flow/openadapt_flow/handoffs/followup.py b/packages/flow/openadapt_flow/handoffs/followup.py index 092825d843..5dd6e36840 100644 --- a/packages/flow/openadapt_flow/handoffs/followup.py +++ b/packages/flow/openadapt_flow/handoffs/followup.py @@ -123,15 +123,20 @@ def sign_updates( run_dir = Path(run_dir) original = loads_strict((run_dir / r.RECEIPT_FILE).read_text("utf-8")) - # Copy only a receipt that verifies, and only extend one this key signed: - # verify_chain refuses a follow-up from any other key. + # Extend only a chain that verifies as it stands, signed by this key + # alone: the receipt and every update already written. verify_chain + # refuses a follow-up from any other key. kid = r.key_id(signer.public_raw()) own = r.RoleKey( kid, base64.b64encode(signer.public_raw()).decode("ascii"), "this_computer" ) - checked = r.verify_receipt(original, [own]) - if not checked.ok: - raise ValueError(f"the run's receipt does not verify: {checked.reason}") + existing = verify_history(run_dir, [own]) + if existing is None or not existing.ok: + reason = existing.reason if existing is not None else "no receipt" + detail = ( + f" ({existing.detail})" if existing is not None and existing.detail else "" + ) + raise ValueError(f"the run's receipt does not verify: {reason}{detail}") report = loads_strict((run_dir / "report.json").read_text("utf-8")) signed = last_signed(run_dir) statement = r.loads_strict(base64.b64decode(original["payload"])) diff --git a/packages/flow/tests/test_handoff_receipts.py b/packages/flow/tests/test_handoff_receipts.py index 10c838277c..f1fe6b464f 100644 --- a/packages/flow/tests/test_handoff_receipts.py +++ b/packages/flow/tests/test_handoff_receipts.py @@ -308,6 +308,14 @@ def test_sign_updates_refuses_a_receipt_it_cannot_verify_or_did_not_sign(tmp_pat with pytest.raises(ValueError, match="does not verify"): followup.sign_updates(run_dir, [referrals], signer=stranger) assert not (run_dir / "receipt.update-3.json").exists() + # A tampered update already in the chain is never extended. + update = run_dir / "receipt.update-2.json" + good_update = update.read_text() + one = json.loads((run_dir / "receipt.update-1.json").read_text()) + update.write_text(json.dumps(dict(json.loads(good_update), payload=one["payload"]))) + with pytest.raises(ValueError, match="does not verify"): + followup.sign_updates(run_dir, [referrals], signer=signer) + assert not (run_dir / "receipt.update-3.json").exists() def test_handoff_list_signs_updates_and_shows_the_history(tmp_path, env, capsys): @@ -342,3 +350,13 @@ def test_handoff_list_signs_updates_and_shows_the_history(tmp_path, env, capsys) assert "Update 1: Confirmed in the other party's system" in out assert main(argv) == 0 assert "Signed receipt.update" not in capsys.readouterr().out + # A history that no longer verifies fails the command, and nothing new + # is signed on top of it. + update = run_dir / "receipt.update-1.json" + envelope = json.loads(update.read_text()) + update.write_text(json.dumps(dict(envelope, signatures=[]))) + assert main(argv) == 1 + assert "Signed history: not verified" in capsys.readouterr().out + intake.check(referrals, referral.id, "REF-1", Fake(_found(birth_date="1984-03-10"))) + assert main([*argv, "--sign-updates"]) == 2 + assert not (run_dir / "receipt.update-2.json").exists() From cdbc61150ec4d69f57fc47f982863c165a421a7f Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 10:18:50 -0500 Subject: [PATCH 13/18] fix(handoffs): no update file is ever left out of a run's history updates() lists every receipt.update-N.json and fails closed on a gap in the numbering, an unexpected update file name, or a private update with no update beside it. --- .../flow/openadapt_flow/handoffs/followup.py | 37 ++++++++++++++++--- packages/flow/tests/test_handoff_receipts.py | 14 +++++++ 2 files changed, 45 insertions(+), 6 deletions(-) diff --git a/packages/flow/openadapt_flow/handoffs/followup.py b/packages/flow/openadapt_flow/handoffs/followup.py index 5dd6e36840..603058bf4b 100644 --- a/packages/flow/openadapt_flow/handoffs/followup.py +++ b/packages/flow/openadapt_flow/handoffs/followup.py @@ -23,6 +23,7 @@ import base64 import json import os +import re from pathlib import Path from typing import Any, Mapping, Optional, Sequence @@ -98,13 +99,37 @@ def last_signed(run_dir: Path) -> dict[str, dict[str, Any]]: return latest +_UPDATE_NAME = re.compile(r"^receipt\.update-(.*)\.json$") + + def updates(run_dir: Path) -> list[Path]: - found = [] - sequence = 1 - while (run_dir / update_file(sequence)).is_file(): - found.append(run_dir / update_file(sequence)) - sequence += 1 - return found + """Every ``receipt.update-N.json`` in the run, in order. + + Fails closed (ValueError) on a gap in the numbering or a name that isn't + ``receipt.update-.json`` / ``.private.json`` with N counted from 1, so + no update file is ever silently left out of the history. + """ + numbers: list[int] = [] + private_numbers: set[int] = set() + for path in Path(run_dir).iterdir(): + match = _UPDATE_NAME.match(path.name) + if not match: + continue + stem = match.group(1) + if stem.endswith(".private"): + stem = stem[: -len(".private")] + private = True + else: + private = False + if not re.fullmatch(r"[1-9][0-9]{0,5}", stem): + raise ValueError(f"unexpected update file {path.name}") + (private_numbers.add if private else numbers.append)(int(stem)) + numbers.sort() + if numbers != list(range(1, len(numbers) + 1)): + raise ValueError("the run's update files skip a number") + if not private_numbers <= set(numbers): + raise ValueError("a private update file has no update beside it") + return [Path(run_dir) / update_file(n) for n in numbers] def sign_updates( diff --git a/packages/flow/tests/test_handoff_receipts.py b/packages/flow/tests/test_handoff_receipts.py index f1fe6b464f..f91f72e90e 100644 --- a/packages/flow/tests/test_handoff_receipts.py +++ b/packages/flow/tests/test_handoff_receipts.py @@ -308,6 +308,20 @@ def test_sign_updates_refuses_a_receipt_it_cannot_verify_or_did_not_sign(tmp_pat with pytest.raises(ValueError, match="does not verify"): followup.sign_updates(run_dir, [referrals], signer=stranger) assert not (run_dir / "receipt.update-3.json").exists() + # An update past a gap is never ignored: the history fails closed. + one_path = run_dir / "receipt.update-1.json" + saved = one_path.read_text() + one_path.rename(run_dir / "receipt.update-9.json") + with pytest.raises(ValueError, match="skip a number"): + followup.verify_history(run_dir, _registry(tmp_path)) + with pytest.raises(ValueError, match="skip a number"): + followup.sign_updates(run_dir, [referrals], signer=signer) + (run_dir / "receipt.update-9.json").unlink() + one_path.write_text(saved) + (run_dir / "receipt.update-x.json").write_text("{}") + with pytest.raises(ValueError, match="unexpected update file"): + followup.updates(run_dir) + (run_dir / "receipt.update-x.json").unlink() # A tampered update already in the chain is never extended. update = run_dir / "receipt.update-2.json" good_update = update.read_text() From a8e2098c1b570b98cd9d69ee981ade8aa5a721e6 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 11:58:35 -0500 Subject: [PATCH 14/18] fix(handoffs): close the round-3 fail-opens in follow-ups and read-back Instance fixes, named by class until the shared fail-open harness lands: - wrong subject: sign_updates picks handoffs only from the report the receipt signed; a key names one delivery, never reused. - missing evidence: a signed update missing from the run (or updates without their receipt) breaks the history; a FHIR search with an error OperationOutcome or a total it didn't return is unreachable. - race: an update's sequence is claimed with O_EXCL, never overwritten. - wrong reading: the receiver's values are read in the receiver's date order; with none declared, an ambiguous date counts as differing. --- .../flow/openadapt_flow/cli_handoff_list.py | 3 +- .../flow/openadapt_flow/handoffs/followup.py | 36 ++++++++++++-- .../flow/openadapt_flow/handoffs/intake.py | 10 ++-- .../flow/openadapt_flow/handoffs/ledger.py | 7 ++- .../flow/openadapt_flow/handoffs/readers.py | 33 ++++++++++++- packages/flow/tests/test_handoff_receipts.py | 17 +++++++ packages/flow/tests/test_handoffs.py | 47 +++++++++++++++++++ 7 files changed, 141 insertions(+), 12 deletions(-) diff --git a/packages/flow/openadapt_flow/cli_handoff_list.py b/packages/flow/openadapt_flow/cli_handoff_list.py index 5852d18be3..91e2a31919 100644 --- a/packages/flow/openadapt_flow/cli_handoff_list.py +++ b/packages/flow/openadapt_flow/cli_handoff_list.py @@ -263,7 +263,8 @@ def _history( from openadapt_types import receipt as r - if not (run_dir / r.RECEIPT_FILE).is_file(): + orphans = any(run_dir.glob("receipt.update-*.json")) + if not (run_dir / r.RECEIPT_FILE).is_file() and not orphans: return {"error": "no receipt.json in the run"} if sign else None try: from openadapt_flow.handoffs.followup import sign_updates, verify_history diff --git a/packages/flow/openadapt_flow/handoffs/followup.py b/packages/flow/openadapt_flow/handoffs/followup.py index 603058bf4b..c5fda6b2a5 100644 --- a/packages/flow/openadapt_flow/handoffs/followup.py +++ b/packages/flow/openadapt_flow/handoffs/followup.py @@ -21,6 +21,7 @@ from __future__ import annotations import base64 +import hashlib import json import os import re @@ -162,9 +163,17 @@ def sign_updates( f" ({existing.detail})" if existing is not None and existing.detail else "" ) raise ValueError(f"the run's receipt does not verify: {reason}{detail}") - report = loads_strict((run_dir / "report.json").read_text("utf-8")) - signed = last_signed(run_dir) + raw_report = (run_dir / "report.json").read_bytes() statement = r.loads_strict(base64.b64decode(original["payload"])) + subjects = { + x["name"]: x["digest"]["sha256"] for x in statement.get("subject") or [] + } + if subjects.get("report.json") != hashlib.sha256(raw_report).hexdigest(): + # Wrong-subject class: choose the handoffs from the very report the + # receipt signed, never a later or another run's report. + raise ValueError("report.json is not the report the receipt signed") + report = loads_strict(raw_report.decode("utf-8")) + signed = last_signed(run_dir) changed: list[Handoff] = [] for handoff in place(statement, handoffs_for_run(report, list(ledgers), run_dir)): if signed.get(handoff.id) != _signature(handoff): @@ -176,6 +185,13 @@ def sign_updates( follow_up = r.follow_up_statement(original, sequence, lines) envelope = r.sign_statement(follow_up, [(kid, signer.sign)]) out = run_dir / update_file(sequence) + # Race class: a sequence is claimed exclusively, so two signers can't + # write the same update; the loser fails and signs nothing. + try: + fd = os.open(out, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644) + except FileExistsError: + raise ValueError(f"{out.name} was written by another signer") from None + os.close(fd) _write_json( run_dir / update_private_file(sequence), r.private_openings(envelope, openings), @@ -201,9 +217,23 @@ def load(name: str) -> Optional[Mapping[str, Any]]: return loads_strict(path.read_text("utf-8")) if path.is_file() else None original = load(r.RECEIPT_FILE) + found = updates(run_dir) if original is None: + if found or (run_dir / SIDECAR).is_file(): + # Missing-evidence class: signed updates without their receipt are + # a broken history, not an unsigned run. + raise ValueError("signed updates are here but receipt.json is missing") return None - chain = [loads_strict(p.read_text("utf-8")) for p in updates(run_dir)] + # Missing-evidence class: every update the sidecar says was signed must + # still be here, so a dropped last update can't shorten the history. + recorded = [ + rec["file"] + for rec in _sidecar(run_dir)["records"] + if rec["file"] != r.RECEIPT_FILE + ] + if sorted(recorded) != sorted(p.name for p in found): + raise ValueError("the signed updates don't match the record of what was signed") + chain = [loads_strict(p.read_text("utf-8")) for p in found] return r.verify_chain( original, chain, diff --git a/packages/flow/openadapt_flow/handoffs/intake.py b/packages/flow/openadapt_flow/handoffs/intake.py index 0b00b84cce..1d34014888 100644 --- a/packages/flow/openadapt_flow/handoffs/intake.py +++ b/packages/flow/openadapt_flow/handoffs/intake.py @@ -76,11 +76,11 @@ def judge( digests: dict[str, str] = {} for field_id, spec in sorted(handoff.fields.items()): value = result.fields.get(field_id) - seen = ( - None - if value is None - else ledger.field_digest(value, spec.kind, spec.date_order) - ) + # Wrong-reading class: the receiver's text is read in the receiver's + # date order. With none declared, a date that reads two ways doesn't + # normalize and counts as differing, never as the sender's date. + order = result.date_orders.get(field_id) + seen = None if value is None else ledger.field_digest(value, spec.kind, order) digests[field_id] = seen or "missing" if seen != spec.digest: differing.append(field_id) diff --git a/packages/flow/openadapt_flow/handoffs/ledger.py b/packages/flow/openadapt_flow/handoffs/ledger.py index b197911375..4eb4ba95f2 100644 --- a/packages/flow/openadapt_flow/handoffs/ledger.py +++ b/packages/flow/openadapt_flow/handoffs/ledger.py @@ -319,8 +319,11 @@ def send( with self._locked(): key_digest = self.digest(key) for other in self.entries(): - if other.key_digest == key_digest and other.status(moment) != "done": - raise LedgerError("another open handoff already uses this key") + # Wrong-subject class: a key names one delivery. A done + # handoff's record would otherwise confirm a second delivery + # under the same key that never arrived. + if other.key_digest == key_digest: + raise LedgerError("another handoff already uses this key") handoff = Handoff( id=f"handoff:{secrets.token_hex(16)}", sent_at=iso_seconds(moment), diff --git a/packages/flow/openadapt_flow/handoffs/readers.py b/packages/flow/openadapt_flow/handoffs/readers.py index edd04b239c..f217a74a33 100644 --- a/packages/flow/openadapt_flow/handoffs/readers.py +++ b/packages/flow/openadapt_flow/handoffs/readers.py @@ -41,6 +41,9 @@ class ReadResult: fields: dict[str, Optional[str]] = field(default_factory=dict) #: SHA-256 of the body read, for the observation's evidence digest. evidence_sha256: Optional[str] = None + #: The receiver's own date order per field (``dmy``/``mdy``), when its + #: profile declares one. The sender's order never reads its values. + date_orders: dict[str, Optional[str]] = field(default_factory=dict) class Reader(Protocol): @@ -154,6 +157,8 @@ def read(self, key: str) -> ReadResult: matches: list[dict[str, Any]] = [] digest = hashlib.sha256() pages = 0 + seen = 0 + declared_total: Optional[int] = None while url is not None: pages += 1 if pages > 20: @@ -180,11 +185,26 @@ def read(self, key: str) -> ReadResult: if not isinstance(resource, dict): return ReadResult("unreachable") if resource.get("resourceType") == "OperationOutcome": + # Missing-evidence class: an error outcome means the search + # is partial, so its matches prove nothing. + issues = resource.get("issue") or [] + if not isinstance(issues, list) or any( + not isinstance(i, dict) + or i.get("severity") not in ("information", "warning") + for i in issues + ): + return ReadResult("unreachable") continue if resource.get("resourceType") != self.profile.resource: return ReadResult("unreachable") + seen += 1 if _text(extract_path(resource, self.profile.key_path)) == key: matches.append(resource) + total = bundle.get("total") + if total is not None: + if type(total) is not int or total < 0: + return ReadResult("unreachable") + declared_total = total try: url = next_page_url(bundle) except ValueError: @@ -193,6 +213,9 @@ def read(self, key: str) -> ReadResult: return ReadResult("unreachable") params = None evidence = digest.hexdigest() + if declared_total is not None and declared_total != seen: + # The server says it matched more (or fewer) than it returned. + return ReadResult("unreachable", evidence_sha256=evidence) if not matches: return ReadResult("not_found", evidence_sha256=evidence) if len(matches) > 1: @@ -202,7 +225,15 @@ def read(self, key: str) -> ReadResult: field_id: _text(extract_path(record, spec.path)) for field_id, spec in self.profile.fields.items() } - return ReadResult("found", fields=fields, evidence_sha256=evidence) + return ReadResult( + "found", + fields=fields, + evidence_sha256=evidence, + date_orders={ + field_id: spec.date_order + for field_id, spec in self.profile.fields.items() + }, + ) __all__ = [ diff --git a/packages/flow/tests/test_handoff_receipts.py b/packages/flow/tests/test_handoff_receipts.py index f91f72e90e..a6a348764b 100644 --- a/packages/flow/tests/test_handoff_receipts.py +++ b/packages/flow/tests/test_handoff_receipts.py @@ -322,6 +322,23 @@ def test_sign_updates_refuses_a_receipt_it_cannot_verify_or_did_not_sign(tmp_pat with pytest.raises(ValueError, match="unexpected update file"): followup.updates(run_dir) (run_dir / "receipt.update-x.json").unlink() + # A report that isn't the one the receipt signed never picks handoffs. + report = run_dir / "report.json" + signed_report = report.read_bytes() + report.write_bytes(signed_report + b" ") + with pytest.raises(ValueError, match="not the report the receipt signed"): + followup.sign_updates(run_dir, [referrals], signer=signer) + report.write_bytes(signed_report) + # A signed update that went missing (with its openings) breaks the history. + two = run_dir / "receipt.update-2.json" + two_private = run_dir / "receipt.update-2.private.json" + kept = two.read_bytes(), two_private.read_bytes() + two.unlink() + two_private.unlink() + with pytest.raises(ValueError, match="don't match the record"): + followup.verify_history(run_dir, _registry(tmp_path)) + two.write_bytes(kept[0]) + two_private.write_bytes(kept[1]) # A tampered update already in the chain is never extended. update = run_dir / "receipt.update-2.json" good_update = update.read_text() diff --git a/packages/flow/tests/test_handoffs.py b/packages/flow/tests/test_handoffs.py index 9d05972fb9..bd9abe4fb7 100644 --- a/packages/flow/tests/test_handoffs.py +++ b/packages/flow/tests/test_handoffs.py @@ -385,6 +385,53 @@ def test_fhir_reader_ambiguous_across_pages_and_fails_closed(): assert _reader(off_origin).read("REF-1").status == "unreachable" +def test_fhir_reader_fails_closed_on_a_partial_search(): + error = {"resourceType": "OperationOutcome", "issue": [{"severity": "error"}]} + assert _reader(Client(_bundle(_patient("REF-1"), error))).read("REF-1").status == ( + "unreachable" + ) + note = {"resourceType": "OperationOutcome", "issue": [{"severity": "warning"}]} + assert _reader(Client(_bundle(_patient("REF-1"), note))).read("REF-1").status == ( + "found" + ) + short = {**_bundle(_patient("REF-1")), "total": 2} + assert _reader(Client(short)).read("REF-1").status == "unreachable" + + +def test_a_key_names_one_delivery(tmp_path): + ledger, h = _referral(tmp_path) + intake.check(ledger, h.id, "REF-0001", Fake(_found())) + with pytest.raises(LedgerError, match="already uses this key"): + _referral(tmp_path) + + +def test_receiver_dates_are_read_in_the_receivers_order(tmp_path): + ledger = HandoffLedger(tmp_path / "handoffs") + h = ledger.send( + "REF-0009", + {**FIELDS, "birth_date": ("03/09/1984", "date", "mdy")}, + counterparty="receiving clinic", + follow_up_hours=24, + system_kind="ehr", + run_id="run-1", + step=2, + ) + # The receiver's text reads two ways and its profile declares no order: + # never read in the sender's order, so it counts as differing. + ambiguous = ReadResult("found", fields={**RECORD, "birth_date": "03/09/1984"}) + after = intake.check(ledger, h.id, "REF-0009", Fake(ambiguous)) + assert after.state == "recorded_differently" + assert after.last.differing_fields == ["birth_date"] + declared = ReadResult( + "found", + fields={**RECORD, "birth_date": "03/09/1984"}, + date_orders={"birth_date": "mdy"}, + ) + assert intake.check(ledger, h.id, "REF-0009", Fake(declared)).state == ( + "recorded_as_intended" + ) + + # -- the receipt line ---------------------------------------------------------------- From e5646ed4a6ae7fc5250e1feaab853abe2ed776eb Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 12:39:42 -0500 Subject: [PATCH 15/18] fix(handoffs): one signer per run, recoverable publication, sidecar orphans, FHIR totals Round-4 items, named by class: - race: sign_updates holds an exclusive per-run lock from the history check through publication; a pending note written before any update file lets the next call complete or roll back an interrupted publication. - missing evidence: a sidecar left without its receipt is a broken history in the read-only listing too; FHIR pages that disagree on the total are unreachable. --- .../flow/openadapt_flow/cli_handoff_list.py | 6 +- .../flow/openadapt_flow/handoffs/followup.py | 93 ++++++++++++++++--- .../flow/openadapt_flow/handoffs/readers.py | 3 + packages/flow/tests/test_handoff_receipts.py | 28 ++++++ packages/flow/tests/test_handoffs.py | 7 ++ 5 files changed, 125 insertions(+), 12 deletions(-) diff --git a/packages/flow/openadapt_flow/cli_handoff_list.py b/packages/flow/openadapt_flow/cli_handoff_list.py index 91e2a31919..3ba7d8d59a 100644 --- a/packages/flow/openadapt_flow/cli_handoff_list.py +++ b/packages/flow/openadapt_flow/cli_handoff_list.py @@ -263,7 +263,11 @@ def _history( from openadapt_types import receipt as r - orphans = any(run_dir.glob("receipt.update-*.json")) + from openadapt_flow.handoffs.followup import SIDECAR + + orphans = ( + any(run_dir.glob("receipt.update-*.json")) or (run_dir / SIDECAR).is_file() + ) if not (run_dir / r.RECEIPT_FILE).is_file() and not orphans: return {"error": "no receipt.json in the run"} if sign else None try: diff --git a/packages/flow/openadapt_flow/handoffs/followup.py b/packages/flow/openadapt_flow/handoffs/followup.py index c5fda6b2a5..5ac9aaa519 100644 --- a/packages/flow/openadapt_flow/handoffs/followup.py +++ b/packages/flow/openadapt_flow/handoffs/followup.py @@ -133,6 +133,43 @@ def updates(run_dir: Path) -> list[Path]: return [Path(run_dir) / update_file(n) for n in numbers] +def _pending_path(run_dir: Path) -> Path: + return run_dir / ".receipt-update.pending.json" + + +def _finish_pending(run_dir: Path, registry: Sequence[Any]) -> None: + """Complete or roll back an update whose publication was interrupted. + + The pending note is written before any update file; if the update it + names is now a whole signed record, its sidecar entry is added, and + otherwise the partial files are removed. Either way the note goes.""" + from openadapt_types import receipt as r + + from openadapt_flow.offline_seal import loads_strict + + pending = _pending_path(run_dir) + if not pending.is_file(): + return + note = json.loads(pending.read_text("utf-8")) + out = run_dir / str(note["file"]) + private = run_dir / str(note["private"]) + complete = False + try: + envelope = loads_strict(out.read_text("utf-8")) + complete = r.verify_receipt(envelope, registry).ok and private.is_file() + except (OSError, ValueError): + complete = False + if complete: + data = _sidecar(run_dir) + if note["file"] not in [rec["file"] for rec in data["records"]]: + data["records"].append({"file": note["file"], "lines": note["lines"]}) + _write_json(run_dir / SIDECAR, data, private=True) + else: + for partial in (out, private): + partial.unlink(missing_ok=True) + pending.unlink() + + def sign_updates( run_dir: str | Path, ledgers: Sequence[HandoffLedger], @@ -141,21 +178,46 @@ def sign_updates( ) -> Optional[Path]: """Sign one follow-up for every handoff of the run whose line changed since it was last signed. None when nothing changed. Needs the run's - receipt (``receipt.json``).""" + receipt (``receipt.json``). + Race class: one signer at a time per run (an exclusive lock from the + history check through publication), and an interrupted publication is + completed or rolled back by the next call.""" + + run_dir = Path(run_dir) + lock = run_dir / ".receipt-update.lock" + try: + fd = os.open(lock, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + except FileExistsError: + raise ValueError( + f"another signer holds {lock.name}; remove it if no signer is running" + ) from None + os.close(fd) + try: + return _sign_updates_locked(run_dir, ledgers, signer=signer) + finally: + lock.unlink(missing_ok=True) + + +def _sign_updates_locked( + run_dir: Path, + ledgers: Sequence[HandoffLedger], + *, + signer: Any, +) -> Optional[Path]: from openadapt_types import receipt as r from openadapt_flow.offline_seal import loads_strict - run_dir = Path(run_dir) - original = loads_strict((run_dir / r.RECEIPT_FILE).read_text("utf-8")) - # Extend only a chain that verifies as it stands, signed by this key - # alone: the receipt and every update already written. verify_chain - # refuses a follow-up from any other key. kid = r.key_id(signer.public_raw()) own = r.RoleKey( kid, base64.b64encode(signer.public_raw()).decode("ascii"), "this_computer" ) + _finish_pending(run_dir, [own]) + original = loads_strict((run_dir / r.RECEIPT_FILE).read_text("utf-8")) + # Extend only a chain that verifies as it stands, signed by this key + # alone: the receipt and every update already written. verify_chain + # refuses a follow-up from any other key. existing = verify_history(run_dir, [own]) if existing is None or not existing.ok: reason = existing.reason if existing is not None else "no receipt" @@ -187,11 +249,19 @@ def sign_updates( out = run_dir / update_file(sequence) # Race class: a sequence is claimed exclusively, so two signers can't # write the same update; the loser fails and signs nothing. - try: - fd = os.open(out, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644) - except FileExistsError: - raise ValueError(f"{out.name} was written by another signer") from None - os.close(fd) + if out.exists(): + raise ValueError(f"{out.name} was written by another signer") + # Durable before any update file: what this update is, so an + # interrupted publication can be completed or rolled back. + _write_json( + _pending_path(run_dir), + { + "file": out.name, + "private": update_private_file(sequence), + "lines": [{"handoff": h.id, "signed": _signature(h)} for h in changed], + }, + private=True, + ) _write_json( run_dir / update_private_file(sequence), r.private_openings(envelope, openings), @@ -199,6 +269,7 @@ def sign_updates( ) _write_json(out, envelope, private=False) record_signed(run_dir, out.name, changed) + _pending_path(run_dir).unlink() return out diff --git a/packages/flow/openadapt_flow/handoffs/readers.py b/packages/flow/openadapt_flow/handoffs/readers.py index f217a74a33..ca8bdfa99d 100644 --- a/packages/flow/openadapt_flow/handoffs/readers.py +++ b/packages/flow/openadapt_flow/handoffs/readers.py @@ -204,6 +204,9 @@ def read(self, key: str) -> ReadResult: if total is not None: if type(total) is not int or total < 0: return ReadResult("unreachable") + if declared_total is not None and total != declared_total: + # Pages that disagree on the total can hide a partial search. + return ReadResult("unreachable") declared_total = total try: url = next_page_url(bundle) diff --git a/packages/flow/tests/test_handoff_receipts.py b/packages/flow/tests/test_handoff_receipts.py index a6a348764b..24d294951b 100644 --- a/packages/flow/tests/test_handoff_receipts.py +++ b/packages/flow/tests/test_handoff_receipts.py @@ -339,6 +339,34 @@ def test_sign_updates_refuses_a_receipt_it_cannot_verify_or_did_not_sign(tmp_pat followup.verify_history(run_dir, _registry(tmp_path)) two.write_bytes(kept[0]) two_private.write_bytes(kept[1]) + # One signer at a time: a held lock refuses, and signs nothing. + lock = run_dir / ".receipt-update.lock" + lock.write_text("") + with pytest.raises(ValueError, match="another signer holds"): + followup.sign_updates(run_dir, [referrals], signer=signer) + lock.unlink() + # A publication interrupted after its files but before the sidecar is + # completed by the next call, never left as a broken history. + import json as _json + + sidecar = run_dir / followup.SIDECAR + data = _json.loads(sidecar.read_text()) + last = data["records"].pop() + sidecar.write_text(_json.dumps(data)) + (run_dir / ".receipt-update.pending.json").write_text( + _json.dumps( + { + "file": last["file"], + "private": last["file"].replace(".json", ".private.json"), + "lines": last["lines"], + } + ) + ) + with pytest.raises(ValueError): # the history doesn't verify meanwhile + followup.verify_history(run_dir, _registry(tmp_path)) + followup._finish_pending(run_dir, _registry(tmp_path)) # what the next call runs + assert not (run_dir / ".receipt-update.pending.json").exists() + assert followup.verify_history(run_dir, _registry(tmp_path)).ok # A tampered update already in the chain is never extended. update = run_dir / "receipt.update-2.json" good_update = update.read_text() diff --git a/packages/flow/tests/test_handoffs.py b/packages/flow/tests/test_handoffs.py index bd9abe4fb7..de3905fd1d 100644 --- a/packages/flow/tests/test_handoffs.py +++ b/packages/flow/tests/test_handoffs.py @@ -396,6 +396,13 @@ def test_fhir_reader_fails_closed_on_a_partial_search(): ) short = {**_bundle(_patient("REF-1")), "total": 2} assert _reader(Client(short)).read("REF-1").status == "unreachable" + # Pages that disagree on the total are a partial search. + first = { + **_bundle(_patient("REF-1"), next_url="https://receiver.test/fhir/Patient?p=2"), + "total": 2, + } + second = {**_bundle(_patient("REF-2")), "total": 1} + assert _reader(Client(first, second)).read("REF-1").status == "unreachable" def test_a_key_names_one_delivery(tmp_path): From a45b39b518443058eac90eb22efed37c25403b54 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 19:44:57 -0500 Subject: [PATCH 16/18] style: sort receipt_record.py imports --- packages/flow/openadapt_flow/receipt_record.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/flow/openadapt_flow/receipt_record.py b/packages/flow/openadapt_flow/receipt_record.py index 6e3b89187f..8a119768dd 100644 --- a/packages/flow/openadapt_flow/receipt_record.py +++ b/packages/flow/openadapt_flow/receipt_record.py @@ -566,9 +566,8 @@ def receipt_after_run( if not (Path(run_dir) / "report.json").is_file(): return None try: - from openadapt_flow.offline_seal import seal_home - from openadapt_flow.handoffs.registry import ledgers_for + from openadapt_flow.offline_seal import seal_home write_receipt_record( Path(run_dir), From 94981d6fef5302b56ae7eda9bb656eacc797f215 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 03:01:29 -0500 Subject: [PATCH 17/18] fix(ci): duplicate handoff task key, benchmark parser abbreviations, artifact inventory After merging main: openadapt and flow cli_tasks listed 'handoff' twice (ruff F601); the handoff_receiver benchmark parser sets allow_abbrev=False; public-artifacts.json lists the handoff_receiver compose file and results. --- openadapt/cli_tasks.py | 1 - packages/flow/benchmark/handoff_receiver/referral_cases.py | 2 +- packages/flow/openadapt_flow/cli_tasks.py | 1 - packages/flow/public-artifacts.json | 2 ++ 4 files changed, 3 insertions(+), 3 deletions(-) diff --git a/openadapt/cli_tasks.py b/openadapt/cli_tasks.py index d27fc14901..298ac8056b 100644 --- a/openadapt/cli_tasks.py +++ b/openadapt/cli_tasks.py @@ -65,7 +65,6 @@ "fleet": "services fleet", "for-each": "run --for-each", "guard": "run --guard", - "handoff": "verify handoff", "hooks": "setup hooks", "induce": "compile --induce", "intake": "teach --intake", diff --git a/packages/flow/benchmark/handoff_receiver/referral_cases.py b/packages/flow/benchmark/handoff_receiver/referral_cases.py index f1e76af81a..1e4863caf0 100644 --- a/packages/flow/benchmark/handoff_receiver/referral_cases.py +++ b/packages/flow/benchmark/handoff_receiver/referral_cases.py @@ -265,7 +265,7 @@ def summarize(results: list[CaseResult]) -> dict[str, Any]: import argparse import tempfile - parser = argparse.ArgumentParser() + parser = argparse.ArgumentParser(allow_abbrev=False) parser.add_argument("--repeat", type=int, default=5) parser.add_argument("--out", default=None) args = parser.parse_args() diff --git a/packages/flow/openadapt_flow/cli_tasks.py b/packages/flow/openadapt_flow/cli_tasks.py index b28da425db..a0bac30176 100644 --- a/packages/flow/openadapt_flow/cli_tasks.py +++ b/packages/flow/openadapt_flow/cli_tasks.py @@ -64,7 +64,6 @@ "fleet": "services fleet", "for-each": "run --for-each", "guard": "run --guard", - "handoff": "verify handoff", "hooks": "setup hooks", "induce": "compile --induce", "intake": "teach --intake", diff --git a/packages/flow/public-artifacts.json b/packages/flow/public-artifacts.json index 32c9b4bad1..311f27c559 100644 --- a/packages/flow/public-artifacts.json +++ b/packages/flow/public-artifacts.json @@ -803,6 +803,8 @@ "benchmark/grounding_eval/results_sweep.json", "benchmark/halt_cleanup/results/openemr.json", "benchmark/handoff_real_run/2026-11-21/evidence.json", + "benchmark/handoff_receiver/docker-compose.yml", + "benchmark/handoff_receiver/results/2026-11-21.json", "benchmark/harness2_scorer/evidence/base/results.json", "benchmark/harness2_scorer/evidence/harness2/results.json", "benchmark/harness2_scorer/evidence/harness2_readback/results.json", From d88fe0df12183528af607345370044f052e44d58 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 03:52:53 -0500 Subject: [PATCH 18/18] fix(types): type the handoff send fields as text for mypy --- packages/flow/openadapt_flow/cli_handoff.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/flow/openadapt_flow/cli_handoff.py b/packages/flow/openadapt_flow/cli_handoff.py index 44465f4cd8..862f84db48 100644 --- a/packages/flow/openadapt_flow/cli_handoff.py +++ b/packages/flow/openadapt_flow/cli_handoff.py @@ -16,7 +16,7 @@ import urllib.parse import urllib.request from pathlib import Path -from typing import Any, Optional +from typing import Any, Literal, Optional def handoff_group(sub: argparse._SubParsersAction) -> argparse._SubParsersAction: @@ -235,7 +235,7 @@ def record_in_ledger( value = json.loads(data.decode("utf-8")) except (UnicodeDecodeError, ValueError): value = None - fields: dict[str, tuple[str, str]] = {} + fields: dict[str, tuple[str, Literal["text"]]] = {} key = None if isinstance(value, dict): if key_field is not None: