From 9ee9892553d5dea6c6dbaaffe3b9570340abed6a Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 11:16:11 -0500 Subject: [PATCH 1/9] feat(ladder): one check-level ladder and evidence-scope receipts on every path --- CAPABILITIES.md | 3 +- packages/flow/CHANGELOG.md | 23 ++ packages/flow/docs/VERIFY_RUN.md | 26 +- .../flow/openadapt_flow/evidence_basis.py | 120 +++++++ .../flow/openadapt_flow/tx/api_readback.py | 145 ++++++++ packages/flow/openadapt_flow/tx/lens.py | 39 ++- packages/flow/openadapt_flow/tx/receipt.py | 14 + packages/flow/openadapt_flow/tx/types.py | 3 + packages/flow/openadapt_flow/verification.py | 9 +- packages/flow/openadapt_flow/verify_run.py | 102 +++++- packages/flow/tests/test_one_ladder.py | 323 ++++++++++++++++++ .../tests/test_verifier_validation_reasons.py | 1 + packages/flow/tests/test_verify_run.py | 67 +++- packages/types/CHANGELOG.md | 17 + packages/types/docs/CONTRACTS.md | 6 +- packages/types/openadapt_types/check_level.py | 177 ++++++++++ .../types/openadapt_types/evidence_scope.py | 271 +++++++++++++++ packages/types/openadapt_types/execute.py | 37 +- packages/types/tests/test_execute_contract.py | 40 ++- 19 files changed, 1375 insertions(+), 48 deletions(-) create mode 100644 packages/flow/openadapt_flow/evidence_basis.py create mode 100644 packages/flow/openadapt_flow/tx/api_readback.py create mode 100644 packages/flow/tests/test_one_ladder.py create mode 100644 packages/types/openadapt_types/evidence_scope.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index cad88c6b1c..f72224d306 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -160,6 +160,7 @@ improvising or retrying when something is off. | Stop before the effect instead of improvising (`HALTED_BEFORE_EFFECT`) | Released | Real app and synthetic | `runtime/replayer.py` | | Never retry an uncertain save (`RECONCILIATION_REQUIRED`) | Released | Synthetic (fault server) | [VERIFICATION.md](packages/flow/docs/VERIFICATION.md) | | One check-level scale, 0 to 5, from "unchecked" to "counterparty confirmed" | Released | Unit tests | `openadapt_flow/check_level.py` | +| One receipt word per check, the same on every path: `VERIFIED` only at level 3 (a separate session) or 4 (the system of record), always with the basis that produced the evidence (`separate_session`, `system_api`, `activity_log`, `db_frame` or `owned_connection`); `SHOWN` for an acting-screen re-read, `CONFIRMED` for the counterparty, `ATTESTED` for an operator and `RECORDED` for the rest. `VERIFIED` means "as of the read-back time the read-back showed this value", not "persisted". `verify-run` receipts and `tx` receipts carry an evidence-scope block: level, basis, word, the wire channel watched, the read-back time, the recheck window, and what it did not cover (always server-side async and outbound effects). A `verify-run` contract with `minimum_effect_strength: independent_session` now verifies on a separate-session read | On main | Unit tests (parity across the runtime report, `verify-run`, `tx` and Execute v1; fake verifiers) | `openadapt_types/check_level.py`, `openadapt_types/evidence_scope.py`, `openadapt_flow/evidence_basis.py` | | Judge any executor's write, including an agent's or a script's, from the system of record | Released | Synthetic | `openadapt-flow verify-run`, [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md) | | Judge an "ensure the record exists" write (found, created once with every value, or needs review) through a FHIR server's read path only: searches, AuditEvent and `_history`, never the database; the coverage claim names that read path. An agent's own correction of the record it created counts as one write when the audit trail and history show only that agent, no other reader, and the same record in every version | Released ([#1640](https://github.com/OpenAdaptAI/OpenAdapt/pull/1640), corrections [#1655](https://github.com/OpenAdaptAI/OpenAdapt/pull/1655)) | Real app (Medplum 5.2.8; three blind fault suites: 17/18, 17/20, 19/20; no fault passed in the last two. Corrections, on 15 blind cases and the 37 public ones: false stops 8 to 2 and 9 to 4 for Claude, no harm passed that the old rule caught) | `openadapt_flow/ensure_record.py`, [ENSURE_RECORD.md](packages/flow/docs/ENSURE_RECORD.md) | | Generate an ensure-record contract from three demonstrations, the server's CapabilityStatement and its SearchParameter definitions: field paths and `[system=…]` filters, comparison kinds, value maps, identity, search parameters, the closed record and the change feed. It refuses when unsure, asks a person to confirm an identity for a type with no reviewed template, and self-checks every demonstration plus a perturbation per field | Released ([#1653](https://github.com/OpenAdaptAI/OpenAdapt/pull/1653)) | Real app (Medplum 5.2.8: all 16 hand-written Patient lines regenerated; one blind write type, Immunization: 78 s of person time, 2 lines edited after the person declined the proposed identity; blind suite 23/24, no fault passed) | `openadapt_flow/generate/ensure_contract.py`, [RESULTS.md](packages/flow/benchmark/contract_autogen/results/RESULTS.md) | @@ -179,7 +180,7 @@ improvising or retrying when something is off. | Install the write checker alone: `pip install openadapt-verify` (21 distributions, about 41 MB, no vision, OCR, browser, GUI or NumPy stack; Flow 3 moved those to its `vision` extra) runs Flow's own verifier, ledger, journal, SQL guards and receipts. `openadapt-verify quickstart` checks three scripted agent writes (correct, wrong value, claimed but not saved) against REST, SQLite, FHIR, PostgreSQL and MySQL, each `CONFIRMED`, `REFUTED` or `UNCERTAIN` with a checked signed receipt; `@verified` and `checked_write` wrap a plain Python write in one line | On main | Synthetic (disposable local stores and PostgreSQL and MySQL containers; a clean-venv CI job enforces the install budget and an import test refuses the vision modules) | [packages/verify](packages/verify/README.md), `openadapt_verify/quickstart.py`, `openadapt_verify/guard.py` | | Audit your own automation's success check: `openadapt-verify audit` puts an HTTP proxy in front of the app, runs your command through it N times, changes the save (the first write whose body carries a declared value, or that matches `--write-path`) once per run (not saved with a replayed success reply, rejected, a value blanked or changed, saved twice, an extra changed copy, the reply lost after the save, and a rewritten record field when given one), and counts the runs where the command reported success but the contract's independent read path shows a wrong or missing save, plus false alarms; table and JSON report. HTTP/1.x only, no app code, no WebSocket or server-sent events; a stale overwrite and a change outside the read path are not run | On main | Synthetic (two scripted HTTP clients against the quickstart's REST store: a script that trusts the 2xx reply reported success on 10 of 12 bad saves and failure on 2 saves that landed, one that reads its record back through the app on 4 of 12, missing the duplicate and extra writes) | `openadapt-verify audit`, [packages/verify](packages/verify/README.md#audit-your-automations-success-check), `openadapt_verify/audit.py` | | Never send a write twice while its outcome is unknown: an append-only ledger on local disk (pluggable backend), keyed by the write's identity, that every adapter, the MCP tools and the CLI consult before sending; a read-back against the attempt's own baseline resolves it, and a refuted write waits for a person (`openadapt verify ledger list`, `reconcile`, `release`) | Released | Synthetic (MockMed's fault server: a worker killed between the send and the read-back, killed during a timed-out send, killed before the send, a late write, and two worker processes started together on one write) | `openadapt_flow/write_ledger.py`, [VERIFIER_API.md](packages/flow/docs/VERIFIER_API.md#the-uncertain-write-ledger) | -| Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | +| Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with no automatic undo, and its result is `UNCERTAIN` unless the read-back is a cache-bypassed API read whose record version is exactly one past the before-image's, which is `CONFIRMED` with basis `system_api`. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | | Reconcile one prior authorization or claim across the EHR (FHIR), the clearinghouse (X12 278 and 277 files) and the payer (Da Vinci PAS): each leg is a verifier contract judged by the same record checks, and the result names each break (`not_received`, `mismatch`, `not_written_back`, `duplicate`, `not_accepted`) with `CONFIRMED`/`REFUTED`/`UNCERTAIN` and a Scope; absence before a deadline is `UNCERTAIN`, an unreadable store is never agreement, a rejected or returned 277 is never agreement, and a judged record or value with two distinct candidates in the read (repeated segments, list elements, join targets, a group's latest) is never `CONFIRMED` | On main | HL7 Da Vinci PAS reference implementation and Medplum run locally, synthetic X12: 36 of 36 planted breaks found, 0 of 27 faulty units `CONFIRMED`, 17 of 17 clean units `CONFIRMED` (units 1 to 47; the 3 status-category units added later are covered by unit tests); a Hypothesis property test over generated multi-candidate reads; Epic's public sandbox read-only as the EHR leg | `openadapt-flow reconcile`, [RECONCILE.md](packages/flow/docs/RECONCILE.md), [results](packages/flow/benchmark/reconcile/RESULTS.md) | | Catch a write that lands after the verdict (a background job, a trigger, a delayed side record): a `CONFIRMED` with a recheck due is provisional (`provisional`, `recheck_due_at`); the recheck reads the whole database again and refutes the earlier result when a change since the post-save read has no explanation, and a recheck that doesn't confirm holds the write in the ledger. Run it from Python (`verifier.recheck`) or MCP (`verify_recheck`). A write after the recheck's read is not seen (`frame.database.recheck_after_s`, no default window) | Released ([#1639](https://github.com/OpenAdaptAI/OpenAdapt/pull/1639)); provisional result, MCP tool and ledger hold ([#1669](https://github.com/OpenAdaptAI/OpenAdapt/pull/1669)) | Real app (Dolibarr 21 and EspoCRM 10 on MariaDB 11.4, 180 s window: 4 of 4 planted late writes at 125 to 130 s refuted at the recheck, correct writes confirmed; EspoCRM's cron daemon needs its job tables declared; Redmine 6.1 on PostgreSQL 17, 180 s window: the first-contact study's late writes F19 and F20 refuted at the recheck, correct writes confirmed); synthetic (SQLite); opt-in live OpenEMR test | `openadapt_flow/verifier.py`, `runtime/effects/late_write.py`, [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#writes-that-land-later) | | Diff the whole database for the frame (`frame.database`) on SQLite, MySQL, MariaDB and PostgreSQL. On MySQL and MariaDB every column type is read exactly (binary strings, `BIT`, geometries and vectors as hex, `FLOAT` widened to `DOUBLE`, `JSON` as stored text, decimals at full precision). On PostgreSQL every column type is read as text by a declared rule in a session pinned to UTC and exact float output, and a type without a rule, a table the account can't read in full, or an unreadable sequence is refused. So a row the save adds, changes or removes outside the declared records, such as an extra planned call or a stream note, is refuted unless a declared effect, a side record, an attributed concurrent write or an allow-listed bookkeeping table explains it | Released ([#1661](https://github.com/OpenAdaptAI/OpenAdapt/pull/1661)); PostgreSQL ([#1673](https://github.com/OpenAdaptAI/OpenAdapt/pull/1673)) | Real app (Dolibarr 21 on MariaDB 11.4: all 387 tables read where the frame raised `TypeError`; EspoCRM on MariaDB 11.4: the first-contact study's extra call and stream note refuted, correct opportunities verified; Redmine 6.1 on PostgreSQL 17: 58 tables read, a stray upload in a table the contract doesn't read refuted, correct writes verified); live MariaDB and PostgreSQL type tests | [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#the-whole-database), `runtime/effects/db_snapshot.py` | diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index 9469c2d499..8c039eb20a 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -17,8 +17,31 @@ ## Unreleased +### Features + +- One verification ladder on every path. `openadapt_types.check_level` is + the only source of check levels; `verify-run`, the runtime's report and + the `tx` engine derive their tables from it and name each check with one + receipt word: `VERIFIED` (levels 3 and 4 only, always with a basis: + `separate_session`, `system_api`, `activity_log`, `db_frame` or + `owned_connection`), `SHOWN`, `CONFIRMED`, `ATTESTED` or `RECORDED`. + `verify-run` and `tx` receipts carry an additive `evidence_scope` block + (`openadapt.evidence-scope/v1`) that states the level, basis, wire scope, + read-back time, recheck window and what the check did not cover. Receipts + without the block still verify. + ### Fixes +- `verify-run` with `minimum_effect_strength: independent_session` now + verifies on a separate-session read (check level 3), as the runtime + already did. Before, the two disagreed and verify-run never verified on + it. The default minimum is unchanged (`independent_system_of_record`). +- The `tx` engine no longer caps every verdict at `UNCERTAIN` without a + SQLite row authority. A post-commit API read sent with cache-bypass + headers, showing no cache in its response, and whose record version is + exactly one past the before-image's is `CONFIRMED` with basis + `system_api`. Anything else stays `UNCERTAIN`. + - `wrap publish` no longer refuses programs whose identity templates carry `punctuation_body_keys`. These values are salted token hashes, the same generated shape as the `c` and `r` keys, but the sanitizer sent them to diff --git a/packages/flow/docs/VERIFY_RUN.md b/packages/flow/docs/VERIFY_RUN.md index a0f8638479..3f69f1dd5c 100644 --- a/packages/flow/docs/VERIFY_RUN.md +++ b/packages/flow/docs/VERIFY_RUN.md @@ -848,10 +848,13 @@ skipping a table when the table allows it. | The same, but the executor approved its own write | `CONFIRMED` | `rejected_policy` | | Nothing that matches, and nothing else in the read set moved | `REFUTED` | `halted_before_effect` | | A duplicate, a wrong value, only some of the effects, or a record outside the delta that was added, vanished or changed | `REFUTED` | `reconciliation_required` | -| The store could not be read, no baseline, or a separate-session read | `INDETERMINATE` or `CONFIRMED` | `reconciliation_required` | +| The same through a separate-session read, when the contract's `minimum_effect_strength` is `independent_session` | `CONFIRMED` | `verified` | +| The store could not be read, no baseline, or a separate-session read under the default `independent_system_of_record` minimum | `INDETERMINATE` or `CONFIRMED` | `reconciliation_required` | -Only a read through the system of record produces `verified`. A screen -read-back (`onscreen`) is refused before anything runs. +Only a read independent of the acting session produces `verified`: the +system of record (check level 4), or a separate signed-in session (level 3) +when the contract sets `minimum_effect_strength: independent_session`. A +screen read-back (`onscreen`) is refused before anything runs. `verification_tier` on the receipt says how the effects were checked (RFC-0002, weakest effect wins): @@ -862,7 +865,22 @@ read-back (`onscreen`) is refused before anything runs. including a separate signed-in session (Flow tier 2). - `unchecked`: at least one effect was not read. -Only `independent_readback` can yield `verified`. +`verification_tier` is a coarse label and does not decide `verified`: the +check level does. A `verified` receipt is either `independent_readback` at +oracle tier 2 or 3, or `screen_readback` at oracle tier 1 with `checked_how: +separate_session` and an `evidence_scope` block whose basis is +`separate_session`. + +`evidence_scope` (`openadapt.evidence-scope/v1`) states what the check +covered: `check_level`, the receipt `word` (`VERIFIED` only on a verified +receipt), the `basis` (`separate_session`; `db_frame` for a SQL read; +`owned_connection` for verify-run's other system-of-record reads), the +`wire` channel watched (verify-run watches none), `read_back_at`, +`recheck_window_s` when a recheck is scheduled, and `not_covered`, which +always lists `server_side_async_effects` and `outbound_effects`. `VERIFIED` +means the read-back showed the value at `read_back_at`, not that it +persisted. A receipt issued before the block existed has none and still +checks. `checked_how` names the same read's check level ([`READBACK_LADDER.md`](READBACK_LADDER.md)): `system_of_record` (tier 1), diff --git a/packages/flow/openadapt_flow/evidence_basis.py b/packages/flow/openadapt_flow/evidence_basis.py new file mode 100644 index 0000000000..fd5e50285c --- /dev/null +++ b/packages/flow/openadapt_flow/evidence_basis.py @@ -0,0 +1,120 @@ +"""The basis of a read-back: who produced the evidence, on every Flow path. + +The check level (:mod:`openadapt_types.check_level`) says how strong a check +was; the basis says who produced its evidence. Flow has three paths that +grade a save (the runtime's effect checks, ``verify-run`` and the ``tx`` +commit engine). Each maps its evidence here, so the same evidence gets the +same level, basis and receipt word whichever path produced it: + +- a separate signed-in session (Flow tier 2) is level 3, basis + ``separate_session``; +- a verifier's own read of the system of record (tier 1) is level 4, basis + ``db_frame`` for a SQL read and ``owned_connection`` otherwise; +- the ``tx`` engine's cache-bypassed, version-checked API read is level 4, + basis ``system_api`` (:mod:`openadapt_flow.tx.api_readback`); +- an atomic SQLite row read by the ``tx`` engine is level 4, basis + ``owned_connection``; +- tiers 3 and 4 (the acting session) have no basis and are never + ``VERIFIED``. +""" + +from __future__ import annotations + +from typing import Any, Iterable, Mapping, Optional + +from openadapt_types.check_level import ( + Basis, + CheckLevel, + from_verification_tier, + to_verification_tier, +) + +__all__ = [ + "SQL_KINDS", + "basis_for_tier", + "evidence_scope_for_run", + "level_and_basis", +] + +#: Verifier kinds that read the database directly. +SQL_KINDS = frozenset({"sql"}) + + +def basis_for_tier( + tier: Optional[int], kinds: Iterable[str] = () +) -> Optional[Basis]: + """The basis of a confirmed check at Flow ``tier`` by verifiers ``kinds``. + + None for tiers 3 and 4, for no tier, and for any unknown tier. + """ + + try: + level = from_verification_tier(tier) + except ValueError: + return None + if level is CheckLevel.SEPARATE_SESSION: + return "separate_session" + if level is CheckLevel.SYSTEM_OF_RECORD: + names = {str(kind).strip().lower() for kind in kinds} + if names and names <= SQL_KINDS: + return "db_frame" + return "owned_connection" + return None + + +def level_and_basis( + tier: Optional[int], *, confirmed: bool, kinds: Iterable[str] = () +) -> tuple[CheckLevel, Optional[Basis]]: + """The check level and basis of one check (``unchecked`` and None when + it did not confirm).""" + + try: + level = from_verification_tier(tier, confirmed=confirmed) + except ValueError: + return CheckLevel.UNCHECKED, None + if level is CheckLevel.UNCHECKED: + return level, None + return level, basis_for_tier(tier, kinds) + + +def evidence_scope_for_run( + readback: Optional[Mapping[str, Any]], + outcome: str, + *, + read_back_at: Optional[str] = None, +) -> dict[str, Any]: + """The evidence-scope block for a Flow run, from its ``report.json``. + + ``readback`` is the report's ``readback`` block + (:func:`openadapt_flow.readback_ladder.summarize_report`), or None for a + run that made no save; ``outcome`` is the run's ``ExecutionOutcome`` + value. The receipt for the run (``record/run/v1``) carries this block as + ``evidence_scope``. Only a ``VERIFIED`` run names a basis, so only a + ``VERIFIED`` run gets the word ``VERIFIED``; a confirmed level 1 or 2 + re-read is ``SHOWN`` whatever the run's outcome. + """ + + from openadapt_types.evidence_scope import build_evidence_scope + + level = CheckLevel.UNCHECKED + minimum = CheckLevel.SEPARATE_SESSION + if isinstance(readback, Mapping): + try: + level = CheckLevel.from_label(str(readback.get("checked_how"))) + minimum = CheckLevel.from_label( + str(readback.get("minimum") or minimum.label) + ) + except ValueError: + level = CheckLevel.UNCHECKED + verified = str(outcome).upper() == "VERIFIED" + basis = basis_for_tier(to_verification_tier(level)) if verified else None + return build_evidence_scope( + level, + basis=basis, + # ``checked_how`` is the weakest save's level and is ``unchecked`` + # when any save did not confirm, so any higher level confirmed. + confirmed=level > CheckLevel.UNCHECKED, + minimum=minimum, + read_back_at=read_back_at if level > CheckLevel.UNCHECKED else None, + not_covered=("changes_after_read_back",), + ) diff --git a/packages/flow/openadapt_flow/tx/api_readback.py b/packages/flow/openadapt_flow/tx/api_readback.py new file mode 100644 index 0000000000..e712e2f844 --- /dev/null +++ b/packages/flow/openadapt_flow/tx/api_readback.py @@ -0,0 +1,145 @@ +"""When a ``tx`` API read-back counts as a system-of-record read. + +The ``tx`` engine (:mod:`openadapt_flow.tx.lens`) trusts an atomic SQLite row +read (basis ``owned_connection``). Most customers give no database access, so +an API read of the record can also count, as check level 4 with basis +``system_api``, but only when all of these hold: + +- the operation is an update, so there is a before-image to compare with; +- the read asked to bypass caches (:data:`CACHE_BYPASS_HEADERS`) and the + response shows no sign of a cache (:func:`served_from_cache`); +- the record carries an integer version that is exactly one more than the + before-image's version, so this read saw this write and no other; +- nothing reported a concurrent modification. + +Anything else is not a system-of-record read and the verdict stays +``UNCERTAIN``. The wire tap never substitutes for the read: it shows what was +sent, not what the system stored. + +:func:`tx_evidence_scope` builds the receipt's evidence-scope block +(:mod:`openadapt_types.evidence_scope`) with the same ladder as every other +path. +""" + +from __future__ import annotations + +from datetime import datetime, timezone +from typing import Any, Mapping, Optional + +from openadapt_types.check_level import Basis, CheckLevel +from openadapt_types.evidence_scope import build_evidence_scope + +__all__ = [ + "CACHE_BYPASS_HEADERS", + "api_readback_basis", + "served_from_cache", + "tx_evidence_scope", +] + +#: Sent on every ``tx`` record read that is not an atomic row read. +CACHE_BYPASS_HEADERS: Mapping[str, str] = { + "Cache-Control": "no-cache, no-store, max-age=0", + "Pragma": "no-cache", +} + +#: Response headers that report a cache, and the values that mean a hit. +_CACHE_STATUS_HEADERS = ( + "x-cache", + "x-cache-status", + "cf-cache-status", + "x-proxy-cache", + "x-varnish-cache", + "cdn-cache", +) +_CACHE_HIT_WORDS = ("hit", "stale", "revalidated", "updating") + + +def served_from_cache(headers: Optional[Mapping[str, str]], status: Optional[int]) -> bool: + """True when the response may have come from a cache (fails closed).""" + + if status == 304: + return True + lowered = {str(k).lower(): str(v) for k, v in (headers or {}).items()} + age = lowered.get("age") + if age is not None and age.strip() not in ("", "0"): + return True + if "warning" in lowered and lowered["warning"].strip().startswith("11"): + return True # 110 / 111 / 112 / 113: a stale or heuristic cache. + for name in _CACHE_STATUS_HEADERS: + value = lowered.get(name, "").lower() + if any(word in value for word in _CACHE_HIT_WORDS): + return True + return False + + +def _int_version(record: Optional[Mapping[str, Any]], field: str) -> Optional[int]: + if record is None or field not in record: + return None + value = record[field] + if isinstance(value, bool): + return None + if isinstance(value, int): + return value + if isinstance(value, str) and value.strip().lstrip("-").isdigit(): + return int(value.strip()) + return None + + +def api_readback_basis( + *, + operation: str, + r0: Optional[Mapping[str, Any]], + r1: Optional[Mapping[str, Any]], + headers: Optional[Mapping[str, str]], + status: Optional[int], + version_field: Optional[str], + occ_status: str, + cache_bypassed: bool, +) -> Optional[Basis]: + """``system_api`` when the post-commit API read qualifies; else None.""" + + if operation != "update" or not cache_bypassed or status != 200: + return None + if occ_status == "CONCURRENT_MODIFICATION" or not version_field: + return None + if served_from_cache(headers, status): + return None + before = _int_version(r0, version_field) + after = _int_version(r1, version_field) + if before is None or after is None or after != before + 1: + return None + return "system_api" + + +def tx_evidence_scope( + *, + outcome: str, + basis: Optional[Basis], + read_back: bool, + wire_observed: bool, +) -> dict[str, Any]: + """The evidence-scope block of one ``tx`` commit. + + ``basis`` is ``owned_connection`` for an atomic row read, ``system_api`` + for a qualified API read and None otherwise. Only a ``CONFIRMED`` commit + with a basis is ``VERIFIED``. + """ + + level = ( + CheckLevel.SYSTEM_OF_RECORD + if basis is not None or read_back + else CheckLevel.UNCHECKED + ) + return build_evidence_scope( + level, + basis=basis, + confirmed=outcome == "CONFIRMED" and basis is not None, + wire_channel="http_proxy" if wire_observed else "none", + protocols_parsed=("http",) if wire_observed else (), + read_back_at=( + datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + if read_back + else None + ), + not_covered=("other_records", "changes_after_read_back"), + ) diff --git a/packages/flow/openadapt_flow/tx/lens.py b/packages/flow/openadapt_flow/tx/lens.py index eb92f004ac..50b178d2b8 100644 --- a/packages/flow/openadapt_flow/tx/lens.py +++ b/packages/flow/openadapt_flow/tx/lens.py @@ -26,6 +26,13 @@ Ed25519PublicKey, ) +from openadapt_types.check_level import Basis + +from openadapt_flow.tx.api_readback import ( + CACHE_BYPASS_HEADERS, + api_readback_basis, + tx_evidence_scope, +) from openadapt_flow.tx.receipt import ( issue_tx_receipt, load_or_create_signing_key, @@ -634,7 +641,7 @@ def unwrap_single_record( return dict(body) def get_one( - self, entity_id: str + self, entity_id: str, extra_headers: Optional[Mapping[str, str]] = None ) -> tuple[LensHttpResponse, Optional[dict[str, Any]], int]: """Fetch a single entity by ID in O(1). Returns ``(response, record, rows_read)``.""" endpoint = self.lens.get_one @@ -644,7 +651,7 @@ def get_one( self.lens.id_field: entity_id, endpoint.id_field: entity_id, } - resp = self._request(endpoint, context=ctx) + resp = self._request(endpoint, context=ctx, extra_headers=extra_headers) if not resp.ok: return resp, None, 0 record = self.unwrap_single_record(endpoint, resp.json_body) @@ -907,7 +914,7 @@ def _read_one( self, entity_id: str ) -> tuple[LensHttpResponse, Optional[dict[str, Any]], int]: if self.atomic_authority is None: - return self.client.get_one(entity_id) + return self.client.get_one(entity_id, extra_headers=CACHE_BYPASS_HEADERS) try: record = self.atomic_authority.read(entity_id) except (OSError, ValueError, sqlite3.Error): @@ -1484,6 +1491,20 @@ def _evaluate_postcommit( if judge_reason not in reasons: reasons.append(judge_reason) + basis = ( + "owned_connection" + if atomic_postimage is not None + else api_readback_basis( + operation=task.operation, + r0=r0, + r1=r1, + headers=r1_resp.headers, + status=r1_resp.status_code, + version_field=v_field, + occ_status=occ_status, + cache_bypassed=self.atomic_authority is None, + ) + ) if unblocked_collateral: outcome = "REFUTED" elif occ_status == "CONCURRENT_MODIFICATION": @@ -1492,7 +1513,7 @@ def _evaluate_postcommit( outcome = "REFUTED" elif action_error is not None or incomplete_wire: outcome = "UNCERTAIN" - elif atomic_postimage is None: + elif basis is None: outcome = "UNCERTAIN" else: outcome = "CONFIRMED" @@ -1543,6 +1564,7 @@ def _evaluate_postcommit( t0=t0, atomic_enforced=atomic_postimage is not None and occ_status == "UNCONTESTED", + basis=basis, ) def _finalize_result( @@ -1561,7 +1583,14 @@ def _finalize_result( rows_read: int, t0: float, atomic_enforced: bool = False, + basis: Optional[Basis] = None, ) -> TxCommitResult: + scope = tx_evidence_scope( + outcome=outcome, + basis=basis if outcome == "CONFIRMED" else None, + read_back=r1 is not None, + wire_observed=wire_summary is not None, + ) rec_id, rec_path = issue_tx_receipt( self.workdir, task_id=task.task_id, @@ -1579,6 +1608,7 @@ def _finalize_result( qualification_state="atomic_row_enforced" if atomic_enforced else "unqualified", + evidence_scope=scope, ) elapsed_ms = round((time.perf_counter() - t0) * 1000.0, 3) return TxCommitResult( @@ -1597,6 +1627,7 @@ def _finalize_result( receipt_id=rec_id, rows_read=rows_read, duration_ms=elapsed_ms, + evidence_scope=scope, ) # -- public execution API ------------------------------------------------- diff --git a/packages/flow/openadapt_flow/tx/receipt.py b/packages/flow/openadapt_flow/tx/receipt.py index e89d7ee552..9597a285f1 100644 --- a/packages/flow/openadapt_flow/tx/receipt.py +++ b/packages/flow/openadapt_flow/tx/receipt.py @@ -106,6 +106,8 @@ class TxReceiptPayload(BaseModel): verification_scope: Literal["target_record"] = "target_record" collateral_effects_verified: Literal[False] = False qualification_state: Literal["unqualified", "atomic_row_enforced"] = "unqualified" + #: Additive and optional: receipts issued before it existed still verify. + evidence_scope: Optional[dict[str, Any]] = None @field_validator("issued_at") @classmethod @@ -131,6 +133,15 @@ def _coherent_wire_commitment(self) -> "TxReceiptPayload": value is None for value in fields ): raise ValueError("wire_commitment_and_counts_must_be_present_together") + if self.evidence_scope is not None: + from openadapt_types.evidence_scope import evidence_scope_problem + + if evidence_scope_problem(self.evidence_scope) is not None: + raise ValueError("evidence_scope_invalid") + word = self.evidence_scope["word"] + if (word == "VERIFIED") is not (self.outcome == "CONFIRMED"): + # A CONFIRMED commit without a basis is UNCERTAIN, never here. + raise ValueError("evidence_scope_word_disagrees_with_outcome") return self @@ -335,6 +346,7 @@ def issue_tx_receipt( task_key: Optional[str] = None, issued_at: Optional[str] = None, qualification_state: Literal["unqualified", "atomic_row_enforced"] = "unqualified", + evidence_scope: Optional[Mapping[str, Any]] = None, ) -> tuple[str, Path]: """Issue a signed COSE_Sign1 + SCITT Merkle-logged ``tx-receipt.cose``. @@ -403,6 +415,8 @@ def issue_tx_receipt( ) statement_dict["wire_mutations_allowed"] = wire_summary.mutations_allowed statement_dict["wire_collateral_mutations"] = wire_summary.collateral_mutations + if evidence_scope is not None: + statement_dict["evidence_scope"] = dict(evidence_scope) validated = TxReceiptPayload.model_validate(statement_dict) payload_bytes = _canonical_json_bytes(validated.model_dump(exclude_none=True)) diff --git a/packages/flow/openadapt_flow/tx/types.py b/packages/flow/openadapt_flow/tx/types.py index 0fcdd3280b..382214c780 100644 --- a/packages/flow/openadapt_flow/tx/types.py +++ b/packages/flow/openadapt_flow/tx/types.py @@ -272,6 +272,9 @@ class TxCommitResult(_FrozenModel): receipt_id: Optional[str] = None rows_read: int = 0 duration_ms: float = 0.0 + #: The evidence-scope block (``openadapt.evidence-scope/v1``): check + #: level, basis, receipt word and what the read did not cover. + evidence_scope: Optional[dict[str, Any]] = None class CertificationProbeResult(_FrozenModel): diff --git a/packages/flow/openadapt_flow/verification.py b/packages/flow/openadapt_flow/verification.py index e9127d0d80..2d57b552e9 100644 --- a/packages/flow/openadapt_flow/verification.py +++ b/packages/flow/openadapt_flow/verification.py @@ -5,6 +5,8 @@ from enum import IntEnum from typing import Any, Optional +from openadapt_types.check_level import to_oracle_tier + from openadapt_flow.check_level import CheckLevel, from_verification_tier @@ -120,12 +122,7 @@ def oracle_tier_from_verification_tier( two incompatible number systems to an operator. """ - value = VerificationTier(tier) - if value is VerificationTier.INDEPENDENT_SYSTEM: - return 2 - if value is VerificationTier.INDEPENDENT_SESSION: - return 1 - return 0 + return to_oracle_tier(VerificationTier(tier).check_level) #: Production ``VERIFIED`` requires this floor or stronger (lower int). diff --git a/packages/flow/openadapt_flow/verify_run.py b/packages/flow/openadapt_flow/verify_run.py index cabfb87834..eed37b36a5 100644 --- a/packages/flow/openadapt_flow/verify_run.py +++ b/packages/flow/openadapt_flow/verify_run.py @@ -64,9 +64,22 @@ CHECKED_HOW_VALUES, checked_how_for_flow_tier, ) +from openadapt_types.check_level import ( + VERIFIED_LEVELS, + CheckLevel, + from_effect_strength, + from_verification_tier, + to_effect_strength, +) +from openadapt_types.evidence_scope import ( + EVIDENCE_SCOPE_FIELD, + build_evidence_scope, + evidence_scope_problem, +) from pydantic import BaseModel, ConfigDict, Field, PrivateAttr from openadapt_flow.complete_read import CompleteReadProvider +from openadapt_flow.evidence_basis import level_and_basis from openadapt_flow.deployment import EffectsConfig, build_effect_verifier from openadapt_flow.fault_gate import ( AdmissionPolicy, @@ -144,17 +157,14 @@ _SALTED = re.compile(r"^hmac-sha256:[0-9a-f]{64}$") _ISO_SECONDS = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$") +# Both derived from the one ladder (openadapt_types.check_level): a strength's +# rank is its check level. _STRENGTH_BY_TIER = { - VerificationTier.INDEPENDENT_SYSTEM: "independent_system_of_record", - VerificationTier.INDEPENDENT_SESSION: "independent_session", - VerificationTier.PERSISTED_STATE_REACQUISITION: "persisted_state_reacquisition", - VerificationTier.IMMEDIATE_SCREEN: "immediate_screen_confirmation", + tier: to_effect_strength(from_verification_tier(int(tier))) + for tier in VerificationTier } _STRENGTH_RANK = { - "immediate_screen_confirmation": 1, - "persisted_state_reacquisition": 2, - "independent_session": 3, - "independent_system_of_record": 4, + str(name): int(from_effect_strength(name)) for name in _STRENGTH_BY_TIER.values() } #: Where the baseline keeps the audit log read for frame attribution. Not a @@ -236,6 +246,7 @@ "baseline_window", "self_approved", "issued_before_read", + "evidence_scope", } ) @@ -3362,11 +3373,19 @@ def verify_run( self_approved = approver_ref == executor_ref delivery_uncertain = False + # The one ladder decides: a separate-session read (level 3) or a + # system-of-record read (level 4), at or above the contract's minimum. + level, basis = level_and_basis( + None if unread or weakest is None else int(weakest), + confirmed=True, + kinds=_verifier_kinds(cfg), + ) + minimum_level = from_effect_strength(cfg.minimum_effect_strength) read_proves_delta = ( delta_verdict == "CONFIRMED" - and verification_tier == "independent_readback" + and level in VERIFIED_LEVELS + and level >= minimum_level and strong_enough - and oracle_tier in (2, 3) ) attributed = ( purpose == "owned_attempt" @@ -3590,6 +3609,16 @@ def verify_run( receipt["correlation_id"] = correlation_id if recheck_due_at is not None: receipt[RECHECK_RECEIPT_FIELD] = recheck_due_at + receipt[EVIDENCE_SCOPE_FIELD] = build_evidence_scope( + level, + # Only a verified receipt names a basis, so only it reads VERIFIED. + basis=basis if verified else None, + confirmed=delta_verdict == "CONFIRMED", + minimum=minimum_level, + read_back_at=read_at if not unread else None, + recheck_window_s=recheck_after_s if recheck_due_at is not None else None, + not_covered=("changes_after_read_back",), + ) if request_context is not None: receipt["request_context"] = request_context.to_dict() problem = receipt_problem(receipt) or evidence_problem(evidence, receipt) @@ -4059,6 +4088,7 @@ def receipt_problem(receipt: Mapping[str, Any]) -> Optional[str]: RECHECK_RECEIPT_FIELD, "request_context", _WRITE_ATTRIBUTION, + EVIDENCE_SCOPE_FIELD, } ) if set(receipt) - allowed: @@ -4167,10 +4197,12 @@ def receipt_problem(receipt: Mapping[str, Any]) -> Optional[str]: or (cover is not None and cover.get("policy") != "met") ): return "verified_without_every_part" + scope_problem = _evidence_scope_receipt_problem(receipt) + if scope_problem is not None: + return scope_problem if outcome in ("verified", "rolled_back_verified") and ( receipt["effect_verdict"] != "CONFIRMED" - or receipt["verification_tier"] != "independent_readback" - or receipt.get("oracle_tier") not in (2, 3) + or not _verified_read(receipt) ): return "verified_without_independent_readback" if ( @@ -4181,6 +4213,52 @@ def receipt_problem(receipt: Mapping[str, Any]) -> Optional[str]: return None +def _verified_read(receipt: Mapping[str, Any]) -> bool: + """Whether the receipt's read may back a verified outcome. + + A system-of-record read (``independent_readback``, oracle tier 2 or 3) + always may. A separate-session read (check level 3, oracle tier 1) may + only with an evidence-scope block that names basis ``separate_session`` + and the word ``VERIFIED``; a receipt issued before that block existed + keeps the tier-2 floor. + """ + + if receipt.get("verification_tier") == "independent_readback" and receipt.get( + "oracle_tier" + ) in (2, 3): + return True + scope = receipt.get(EVIDENCE_SCOPE_FIELD) + return ( + receipt.get("verification_tier") == "screen_readback" + and receipt.get("oracle_tier") == 1 + and receipt.get("checked_how") == CheckLevel.SEPARATE_SESSION.label + and isinstance(scope, Mapping) + and scope.get("basis") == "separate_session" + and scope.get("word") == "VERIFIED" + ) + + +def _evidence_scope_receipt_problem(receipt: Mapping[str, Any]) -> Optional[str]: + """The optional evidence-scope block must agree with the receipt.""" + + if EVIDENCE_SCOPE_FIELD not in receipt: + return None # Receipts issued before the block existed. + scope = receipt[EVIDENCE_SCOPE_FIELD] + if evidence_scope_problem(scope) is not None: + return "evidence_scope" + verified = receipt.get("outcome") in ("verified", "rolled_back_verified") + if (scope["word"] == "VERIFIED") is not verified: + return "evidence_scope" + if "checked_how" in receipt and scope["check_level"] != receipt["checked_how"]: + return "evidence_scope" + return None + + +def _verifier_kinds(cfg: "VerifyConfig") -> list[str]: + surfaces = cfg.verifier.surfaces or {} + return [s.kind for s in surfaces.values()] or [cfg.verifier.kind] + + def evidence_problem( evidence: Mapping[str, Any], receipt: Mapping[str, Any] ) -> Optional[str]: diff --git a/packages/flow/tests/test_one_ladder.py b/packages/flow/tests/test_one_ladder.py new file mode 100644 index 0000000000..8e85a39915 --- /dev/null +++ b/packages/flow/tests/test_one_ladder.py @@ -0,0 +1,323 @@ +"""One ladder: the same evidence gets the same level, word and basis on +every path (the runtime's report, verify-run, the tx engine and Execute v1). + +``openadapt_types.check_level`` is the only source of levels; this file +checks that each path's own tables are derived from it and that its receipt +words agree. +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest +from openadapt_types.check_level import ( + BASES, + VERIFIED_LEVELS, + CheckLevel, + from_effect_strength, + level_for_basis, + outcome_word, + to_oracle_tier, + to_verification_tier, +) +from openadapt_types.evidence_scope import ( + build_evidence_scope, + predicate_evidence_scope_problem, + with_evidence_scope, +) +from openadapt_types.execute import _EFFECT_STRENGTH_RANK + +import openadapt_flow.verify_run as verify_run_mod +from openadapt_flow.evidence_basis import ( + basis_for_tier, + evidence_scope_for_run, + level_and_basis, +) +from openadapt_flow.readback_ladder import summarize_report, tier_floor +from openadapt_flow.tx.api_readback import ( + api_readback_basis, + served_from_cache, + tx_evidence_scope, +) +from openadapt_flow.verification import ( + VERIFIED_EFFECT_TIER, + VerificationTier, + oracle_tier_from_verification_tier, +) + +H = "sha256:" + "0" * 64 +T = "2026-11-21T12:00:00Z" + + +# -- every path's tables come from the one ladder ------------------------------ + + +def test_path_tables_are_derived_from_check_level() -> None: + for tier in VerificationTier: + level = tier.check_level + assert to_verification_tier(level) == int(tier) + assert oracle_tier_from_verification_tier(tier) == to_oracle_tier(level) + strength = verify_run_mod._STRENGTH_BY_TIER[tier] + assert from_effect_strength(strength) is level + assert verify_run_mod._STRENGTH_RANK[strength] == int(level) + for strength, rank in _EFFECT_STRENGTH_RANK.items(): + assert from_effect_strength(strength) == rank + # The runtime's VERIFIED floor is the ladder's weakest VERIFIED level. + assert VERIFIED_EFFECT_TIER.check_level is min(VERIFIED_LEVELS) + assert tier_floor("separate_session").check_level is CheckLevel.SEPARATE_SESSION + assert tier_floor("system_of_record").check_level is CheckLevel.SYSTEM_OF_RECORD + + +def test_each_basis_names_one_level() -> None: + assert level_for_basis("separate_session") is CheckLevel.SEPARATE_SESSION + for basis in BASES[1:]: + assert level_for_basis(basis) is CheckLevel.SYSTEM_OF_RECORD + with pytest.raises(ValueError): + level_for_basis("screen") + with pytest.raises(ValueError): + outcome_word(CheckLevel.SEPARATE_SESSION, "system_api") + + +@pytest.mark.parametrize( + ("level", "basis", "confirmed", "attested", "word"), + [ + (CheckLevel.SYSTEM_OF_RECORD, "system_api", True, False, "VERIFIED"), + (CheckLevel.SYSTEM_OF_RECORD, "activity_log", True, False, "VERIFIED"), + (CheckLevel.SEPARATE_SESSION, "separate_session", True, False, "VERIFIED"), + # No basis: a level 3 or 4 read is never VERIFIED. + (CheckLevel.SYSTEM_OF_RECORD, None, True, False, "RECORDED"), + (CheckLevel.REOPENED, None, True, False, "SHOWN"), + (CheckLevel.SAME_SCREEN, None, True, False, "SHOWN"), + (CheckLevel.COUNTERPARTY_CONFIRMED, None, True, False, "CONFIRMED"), + (CheckLevel.UNCHECKED, None, True, True, "ATTESTED"), + (CheckLevel.UNCHECKED, None, True, False, "RECORDED"), + (CheckLevel.SYSTEM_OF_RECORD, "db_frame", False, False, "RECORDED"), + ], +) +def test_outcome_word(level, basis, confirmed, attested, word) -> None: + assert outcome_word(level, basis, confirmed=confirmed, attested=attested) == word + + +def test_a_raised_minimum_keeps_a_separate_session_read_from_verified() -> None: + assert ( + outcome_word( + CheckLevel.SEPARATE_SESSION, + "separate_session", + minimum=CheckLevel.SYSTEM_OF_RECORD, + ) + == "RECORDED" + ) + # A minimum can raise the floor, never lower it below separate_session. + assert ( + outcome_word(CheckLevel.REOPENED, None, minimum=CheckLevel.SAME_SCREEN) + == "SHOWN" + ) + + +# -- the same evidence, every path --------------------------------------------- + + +def _runtime_scope(tier: int) -> dict: + """What the runtime's report.json says, and the run receipt's block.""" + + report = SimpleNamespace( + results=[ + SimpleNamespace( + step_id="save", + effect_evidence=[ + SimpleNamespace( + verification_tier=tier, + final_verdict="confirmed", + observed_effect="present", + ) + ], + effect_contract_hashes=[H], + ) + ] + ) + readback = summarize_report(report, VERIFIED_EFFECT_TIER) + assert readback is not None + # The runtime's rule: VERIFIED at or above its floor. + outcome = ( + "VERIFIED" + if VerificationTier(tier).satisfies(VERIFIED_EFFECT_TIER) + else "COMPLETED_UNVERIFIED" + ) + return evidence_scope_for_run(readback, outcome, read_back_at=T) + + +def _verify_run_scope(tier: VerificationTier, tmp_path) -> dict: + from tests.test_verify_run import AGENT_RECORD, PARAMS, _fake_cfg, _FakeVerifier + + from openadapt_flow.runtime.effects import adapter as adapter_mod + from openadapt_flow.runtime.effects.adapter import register_verifier_factory + + saved = dict(adapter_mod._REGISTRY) + try: + register_verifier_factory( + "fake-ladder", lambda cfg, params: _FakeVerifier(tier), replace=True + ) + result = verify_run_mod.verify_run( + _fake_cfg("fake-ladder", minimum_effect_strength="independent_session"), + params=PARAMS, + run_record=AGENT_RECORD, + authorization_ref="ticket-0000-test", + private_dir=tmp_path, + ) + finally: + adapter_mod._REGISTRY.clear() + adapter_mod._REGISTRY.update(saved) + receipt = result["receipt"] + assert verify_run_mod.receipt_problem(receipt) is None + return receipt["evidence_scope"] + + +def _key(scope: dict) -> tuple: + return scope["check_level"], scope["word"], scope.get("basis") + + +@pytest.mark.parametrize( + ("tier", "expected"), + [ + ( + VerificationTier.INDEPENDENT_SESSION, + ("separate_session", "VERIFIED", "separate_session"), + ), + ( + VerificationTier.INDEPENDENT_SYSTEM, + ("system_of_record", "VERIFIED", "owned_connection"), + ), + ], +) +def test_same_evidence_same_level_word_and_basis_on_every_path( + tier, expected, tmp_path +) -> None: + runtime = _key(_runtime_scope(int(tier))) + verify = _key(_verify_run_scope(tier, tmp_path)) + level, basis = level_and_basis(int(tier), confirmed=True) + direct = (level.label, outcome_word(level, basis), basis) + assert runtime == verify == direct == expected + + +def test_screen_reads_are_shown_and_never_verified_on_every_path(tmp_path) -> None: + for tier in ( + VerificationTier.PERSISTED_STATE_REACQUISITION, + VerificationTier.IMMEDIATE_SCREEN, + ): + runtime = _key(_runtime_scope(int(tier))) + verify = _key(_verify_run_scope(tier, tmp_path)) + assert runtime == verify == (tier.check_level.label, "SHOWN", None) + + +def test_verify_run_names_db_frame_for_a_sql_read() -> None: + assert basis_for_tier(1, ["sql"]) == "db_frame" + assert basis_for_tier(1, ["rest"]) == "owned_connection" + assert basis_for_tier(2, ["ui_readback"]) == "separate_session" + assert basis_for_tier(3) is None and basis_for_tier(None) is None + + +# -- tx: a cache-bypassed, version-checked API read is system_api -------------- + + +def _api(**overrides): + args = { + "operation": "update", + "r0": {"id": "1", "version": 4}, + "r1": {"id": "1", "version": 5}, + "headers": {"ETag": '"v5"'}, + "status": 200, + "version_field": "version", + "occ_status": "UNKNOWN", + "cache_bypassed": True, + } + args.update(overrides) + return api_readback_basis(**args) + + +def test_tx_api_read_is_system_api_only_when_bypassed_and_version_checked() -> None: + assert _api() == "system_api" + assert _api(operation="create") is None + assert _api(cache_bypassed=False) is None + assert _api(version_field=None) is None + assert _api(r1={"id": "1", "version": 6}) is None # another write landed + assert _api(r1={"id": "1", "version": True}) is None + assert _api(occ_status="CONCURRENT_MODIFICATION") is None + assert _api(status=304) is None + for headers in ( + {"Age": "12"}, + {"X-Cache": "HIT from edge"}, + {"CF-Cache-Status": "STALE"}, + {"Warning": '110 - "Response is Stale"'}, + ): + assert served_from_cache(headers, 200), headers + assert _api(headers=headers) is None + assert not served_from_cache({"Age": "0", "X-Cache": "MISS"}, 200) + + +def test_tx_scope_matches_the_other_paths() -> None: + api = tx_evidence_scope( + outcome="CONFIRMED", basis="system_api", read_back=True, wire_observed=True + ) + assert _key(api) == ("system_of_record", "VERIFIED", "system_api") + assert api["wire"] == {"channel": "http_proxy", "protocols_parsed": ["http"]} + atomic = tx_evidence_scope( + outcome="CONFIRMED", + basis="owned_connection", + read_back=True, + wire_observed=False, + ) + # The same basis verify-run names for its own system-of-record read. + assert _key(atomic) == ("system_of_record", "VERIFIED", "owned_connection") + unqualified = tx_evidence_scope( + outcome="UNCERTAIN", basis=None, read_back=True, wire_observed=True + ) + assert _key(unqualified) == ("system_of_record", "RECORDED", None) + + +# -- the record/run/v1 block is additive --------------------------------------- + + +def test_old_predicates_without_the_block_still_pass() -> None: + old = {"outcome": "VERIFIED", "model_calls": 0} + assert predicate_evidence_scope_problem(old) is None + + +def test_block_must_agree_with_the_predicate_outcome() -> None: + verified = build_evidence_scope( + CheckLevel.SEPARATE_SESSION, basis="separate_session", read_back_at=T + ) + assert with_evidence_scope({"outcome": "VERIFIED"}, verified)["evidence_scope"] + assert ( + predicate_evidence_scope_problem( + {"outcome": "UNKNOWN", "evidence_scope": verified} + ) + == "evidence_scope_outcome" + ) + shown = build_evidence_scope(CheckLevel.REOPENED, read_back_at=T) + assert ( + predicate_evidence_scope_problem({"outcome": "VERIFIED", "evidence_scope": shown}) + == "evidence_scope_outcome" + ) + for broken in ( + dict(verified, not_covered=["changes_after_read_back"]), + dict(verified, basis="system_api"), + {k: v for k, v in verified.items() if k != "read_back_at"}, + dict(verified, word="CONFIRMED"), + dict(verified, extra=1), + ): + assert ( + predicate_evidence_scope_problem( + {"outcome": "VERIFIED", "evidence_scope": broken} + ) + == "evidence_scope" + ), broken + + +def test_every_block_lists_what_no_read_back_sees() -> None: + for level in CheckLevel: + block = build_evidence_scope(level, read_back_at=T) + assert block["not_covered"][:2] == [ + "server_side_async_effects", + "outbound_effects", + ] diff --git a/packages/flow/tests/test_verifier_validation_reasons.py b/packages/flow/tests/test_verifier_validation_reasons.py index 7a085fd482..2a0af3fc6d 100644 --- a/packages/flow/tests/test_verifier_validation_reasons.py +++ b/packages/flow/tests/test_verifier_validation_reasons.py @@ -38,6 +38,7 @@ "baseline_window", "self_approved", "issued_before_read", + "evidence_scope", ) CANARY = "synthetic-private-diagnostic-DO-NOT-EMIT" diff --git a/packages/flow/tests/test_verify_run.py b/packages/flow/tests/test_verify_run.py index 6e212987ad..b5174291bc 100644 --- a/packages/flow/tests/test_verify_run.py +++ b/packages/flow/tests/test_verify_run.py @@ -413,7 +413,7 @@ def _fake_cfg(kind: str, **extra) -> VerifyConfig: return VerifyConfig.model_validate(doc) -def test_separate_session_read_is_screen_readback_and_never_verified( +def test_separate_session_read_is_level_3_and_verified_when_the_contract_allows( clean_registry, tmp_path ): register_verifier_factory( @@ -430,12 +430,70 @@ def test_separate_session_read_is_screen_readback_and_never_verified( ) receipt = result["receipt"] assert receipt["effect_verdict"] == "CONFIRMED" - # RFC-0002 decision 6: a separate UI session (Flow tier 2) is a screen - # read, so it can never be independent_readback. + # The wire labels are unchanged: a separate UI session (Flow tier 2) is + # still a screen read in the coarse RFC-0002 label, and oracle tier 1. assert receipt["verification_tier"] == "screen_readback" - assert receipt["outcome"] == "reconciliation_required" assert receipt["oracle_tier"] == 1 + # On the one ladder it is level 3, VERIFIED with basis separate_session, + # because this contract's minimum is independent_session. + assert receipt["checked_how"] == "separate_session" + assert receipt["outcome"] == "verified" + scope = receipt["evidence_scope"] + assert (scope["check_level"], scope["word"], scope["basis"]) == ( + "separate_session", + "VERIFIED", + "separate_session", + ) + assert {"server_side_async_effects", "outbound_effects"} <= set( + scope["not_covered"] + ) assert result["evidence"]["readback"]["effects"][0]["flow_verification_tier"] == 2 + assert verify_run_mod.receipt_problem(receipt) is None + + +def test_separate_session_read_below_a_system_of_record_minimum_is_not_verified( + clean_registry, tmp_path +): + register_verifier_factory( + "fake-session", + lambda cfg, params: _FakeVerifier(VerificationTier.INDEPENDENT_SESSION), + ) + result = verify_run( + _fake_cfg("fake-session"), + params=PARAMS, + run_record=AGENT_RECORD, + authorization_ref="ticket-0000-test", + private_dir=tmp_path, + ) + receipt = result["receipt"] + assert receipt["outcome"] == "reconciliation_required" + scope = receipt["evidence_scope"] + assert (scope["check_level"], scope["word"]) == ("separate_session", "RECORDED") + assert "basis" not in scope + + +def test_tier_1_receipt_cannot_borrow_the_separate_session_rule( + clean_registry, tmp_path +): + register_verifier_factory( + "fake-session", + lambda cfg, params: _FakeVerifier(VerificationTier.INDEPENDENT_SESSION), + ) + cfg = _fake_cfg("fake-session", minimum_effect_strength="independent_session") + receipt = verify_run( + cfg, + params=PARAMS, + run_record=AGENT_RECORD, + authorization_ref="ticket-0000-test", + private_dir=tmp_path, + )["receipt"] + # Without the block, a level 3 VERIFIED receipt is refused offline. + old_shape = {k: v for k, v in receipt.items() if k != "evidence_scope"} + assert verify_run_mod.receipt_problem(old_shape) == "verified_without_independent_readback" + # A block whose word disagrees with the outcome is refused. + wrong = dict(receipt, evidence_scope=dict(receipt["evidence_scope"], word="RECORDED")) + wrong["evidence_scope"].pop("basis") + assert verify_run_mod.receipt_problem(wrong) == "evidence_scope" def test_untyped_verifier_is_refused(clean_registry, tmp_path): @@ -465,6 +523,7 @@ def test_receipt_keeps_every_execute_v1_field(cfg, sor, tmp_path): "verification_tier", "checked", "checked_how", + "evidence_scope", } assert receipt["schema_version"] == EFFECT_RECEIPT_SCHEMA # A strict Execute consumer refuses it rather than mistaking it for a diff --git a/packages/types/CHANGELOG.md b/packages/types/CHANGELOG.md index 756eb7271a..b67fecd35e 100644 --- a/packages/types/CHANGELOG.md +++ b/packages/types/CHANGELOG.md @@ -1,6 +1,23 @@ # CHANGELOG +## Unreleased + +### Features + +- `check_level`: the basis (`separate_session` is level 3; `system_api`, + `activity_log`, `db_frame` and `owned_connection` are level 4), the receipt + words (`VERIFIED`, `SHOWN`, `CONFIRMED`, `ATTESTED`, `RECORDED`) and + `outcome_word`, plus the inverse tier maps and the Execute effect-strength + map. +- `evidence_scope`: the `openadapt.evidence-scope/v1` block and the additive + `evidence_scope` field for `record/run/v1` predicates. A predicate without + it still passes. +- `ExecuteEvidenceReceiptV1` accepts `verified` at oracle tier 1 (a + separate-session read) when the contract's minimum is exactly + `independent_session`. Every other contract keeps the tier-2 floor, and + every receipt that validated before still validates. + ## v0.24.0 (2026-10-20) The models live in this package again, and it depends only on `pydantic>=2.5`; the Python 3.13 cap is gone. `openadapt-flow` 2.3.0 and later depend on it, and `openadapt_flow.contracts` returns the same modules as `openadapt_types` ([#1270](https://github.com/OpenAdaptAI/OpenAdapt/pull/1270)). Upgrade `openadapt-flow` to 2.3.0 together with this package: openadapt-flow 2.2.0 carries its own copy of the models, so with 0.24.0 alone, `isinstance` checks between the two copies fail. diff --git a/packages/types/docs/CONTRACTS.md b/packages/types/docs/CONTRACTS.md index a140b714c9..6779a1352c 100644 --- a/packages/types/docs/CONTRACTS.md +++ b/packages/types/docs/CONTRACTS.md @@ -124,8 +124,10 @@ signal. ## Oracle tiers `verified` and `rolled_back_verified` require an observed effect strength -that maps to Seal oracle tier 2 or 3. Tier 0 is visual / OCR. Tier 1 is a -second-session UI read. Neither can mint production `VERIFIED`. +that maps to Seal oracle tier 2 or 3, or tier 1 (a second-session UI read, +check level 3) when the contract's `minimum_effect_strength` is exactly +`independent_session`. Tier 0 is visual / OCR and never verifies. Production +Seals (`production_seal_allowed`) still require tier 2 or 3. The partner adapter is `channel` plus `read`. Tiers, the gate, and a ten-line file oracle are in [ORACLE.md](ORACLE.md). diff --git a/packages/types/openadapt_types/check_level.py b/packages/types/openadapt_types/check_level.py index be7063b459..9f08dd7e90 100644 --- a/packages/types/openadapt_types/check_level.py +++ b/packages/types/openadapt_types/check_level.py @@ -34,6 +34,29 @@ When a save or record has several checks, the weakest level wins. +Receipt words and the basis +--------------------------- + +A receipt names its outcome with one word, chosen by :func:`outcome_word` +from the level and the basis (who produced the evidence, not its type): + +- ``VERIFIED``: levels 3 and 4 only, always with a basis. Level 3 has basis + ``separate_session``. Level 4 has ``system_api`` (a cache-bypassed, + version-checked API read), ``activity_log`` (the system's own log), + ``db_frame`` (a database read of the record and its frame) or + ``owned_connection`` (a connection the verifier owns, such as its own SQL + or file read). It means "as of the read-back time, the read-back showed + this value", never "persisted". +- ``SHOWN``: levels 1 and 2, the acting screen re-read. +- ``CONFIRMED``: level 5, the counterparty acknowledged the item. +- ``ATTESTED``: an operator confirmed it. +- ``RECORDED``: the receipt records the run and claims no check. A check that + did not confirm, or a level 3 or 4 read below the run's required level, is + ``RECORDED``. + +``openadapt_types.evidence_scope`` builds the receipt block that states the +level, basis, word and what the evidence did not cover. + This module imports only the standard library, so the contracts and the Flow runtime can both use it. ``openadapt_flow.check_level`` re-exports it. """ @@ -44,11 +67,22 @@ from typing import Iterable, Literal, Optional __all__ = [ + "BASES", + "Basis", "CheckLevel", + "OUTCOME_WORDS", + "OutcomeWord", "ReadbackLabel", + "VERIFIED_LEVELS", + "from_effect_strength", "from_oracle_tier", "from_verification_tier", + "level_for_basis", + "outcome_word", + "to_effect_strength", + "to_oracle_tier", "to_readback_label", + "to_verification_tier", "weakest", ] @@ -143,3 +177,146 @@ def weakest(levels: Iterable[CheckLevel]) -> CheckLevel: """The weakest of ``levels``; ``unchecked`` when there are none.""" return min(levels, default=CheckLevel.UNCHECKED) + + +# -- the inverse maps ---------------------------------------------------------- + +#: Check level to ``VerificationTier`` (lower is stronger). Levels 0 and 5 +#: have no Flow tier. +_TO_VERIFICATION_TIER: dict[CheckLevel, int] = { + level: tier for tier, level in _FROM_VERIFICATION_TIER.items() +} + +#: Check level to Seal ``OracleTier``. ``reopened`` reads through the acting +#: session's screens, so it is ``VISUAL`` like ``same_screen``. +_TO_ORACLE_TIER: dict[CheckLevel, int] = { + CheckLevel.UNCHECKED: 0, + CheckLevel.SAME_SCREEN: 0, + CheckLevel.REOPENED: 0, + CheckLevel.SEPARATE_SESSION: 1, + CheckLevel.SYSTEM_OF_RECORD: 2, + CheckLevel.COUNTERPARTY_CONFIRMED: 3, +} + +#: Execute ``EffectStrengthV1`` names. Each name's rank is its check level. +_EFFECT_STRENGTH: dict[str, CheckLevel] = { + "immediate_screen_confirmation": CheckLevel.SAME_SCREEN, + "persisted_state_reacquisition": CheckLevel.REOPENED, + "independent_session": CheckLevel.SEPARATE_SESSION, + "independent_system_of_record": CheckLevel.SYSTEM_OF_RECORD, +} + + +def to_verification_tier(level: CheckLevel) -> Optional[int]: + """The ``VerificationTier`` for ``level``; None for levels 0 and 5.""" + + return _TO_VERIFICATION_TIER.get(CheckLevel(level)) + + +def to_oracle_tier(level: CheckLevel) -> int: + """The Seal ``OracleTier`` for ``level`` (0 below ``separate_session``).""" + + return _TO_ORACLE_TIER[CheckLevel(level)] + + +def from_effect_strength(name: object) -> CheckLevel: + """The check level of an Execute effect strength; ``unchecked`` if unknown.""" + + value = getattr(name, "value", name) + return _EFFECT_STRENGTH.get(value, CheckLevel.UNCHECKED) # type: ignore[arg-type] + + +def to_effect_strength(level: CheckLevel) -> Optional[str]: + """The Execute effect strength name for ``level``; None for levels 0 and 5.""" + + for name, mapped in _EFFECT_STRENGTH.items(): + if mapped == level: + return name + return None + + +# -- the basis and the receipt word --------------------------------------------- + +#: Who produced the evidence for a ``VERIFIED`` read-back. +Basis = Literal[ + "separate_session", + "system_api", + "activity_log", + "db_frame", + "owned_connection", +] +BASES: tuple[Basis, ...] = ( + "separate_session", + "system_api", + "activity_log", + "db_frame", + "owned_connection", +) +_BASIS_LEVEL: dict[str, CheckLevel] = { + "separate_session": CheckLevel.SEPARATE_SESSION, + "system_api": CheckLevel.SYSTEM_OF_RECORD, + "activity_log": CheckLevel.SYSTEM_OF_RECORD, + "db_frame": CheckLevel.SYSTEM_OF_RECORD, + "owned_connection": CheckLevel.SYSTEM_OF_RECORD, +} + +#: The receipt outcome words. +OutcomeWord = Literal["VERIFIED", "SHOWN", "CONFIRMED", "ATTESTED", "RECORDED"] +OUTCOME_WORDS: tuple[OutcomeWord, ...] = ( + "VERIFIED", + "SHOWN", + "CONFIRMED", + "ATTESTED", + "RECORDED", +) +#: The only levels a ``VERIFIED`` word may name. +VERIFIED_LEVELS: tuple[CheckLevel, ...] = ( + CheckLevel.SEPARATE_SESSION, + CheckLevel.SYSTEM_OF_RECORD, +) + + +def level_for_basis(basis: str) -> CheckLevel: + """The check level ``basis`` reaches; raises ``ValueError`` for others.""" + + try: + return _BASIS_LEVEL[basis] + except (KeyError, TypeError): + raise ValueError(f"unknown basis {basis!r}") from None + + +def outcome_word( + level: CheckLevel, + basis: Optional[str] = None, + *, + confirmed: bool = True, + attested: bool = False, + minimum: CheckLevel = CheckLevel.SEPARATE_SESSION, +) -> OutcomeWord: + """The receipt word for one check, the same on every path. + + ``level`` is the level the check reached, ``basis`` who produced the + evidence, ``confirmed`` whether the read-back matched, ``attested`` + whether an operator confirmed it, and ``minimum`` the weakest level the + run accepts for ``VERIFIED`` (never below ``separate_session``). + + A level 3 or 4 check is ``VERIFIED`` only with a basis that reaches that + exact level. A basis that names a different level is a producer bug and + raises ``ValueError``; a missing basis fails closed to ``RECORDED``. + """ + + level = CheckLevel(level) + if basis is not None and level_for_basis(basis) != level: + raise ValueError(f"basis {basis!r} does not reach level {level.label}") + if not confirmed: + return "ATTESTED" if attested else "RECORDED" + if level is CheckLevel.COUNTERPARTY_CONFIRMED: + return "CONFIRMED" + if level in VERIFIED_LEVELS: + floor = max(CheckLevel(minimum), CheckLevel.SEPARATE_SESSION) + if basis is not None and level >= floor: + return "VERIFIED" + return "ATTESTED" if attested else "RECORDED" + if level >= CheckLevel.SAME_SCREEN: + return "SHOWN" + return "ATTESTED" if attested else "RECORDED" diff --git a/packages/types/openadapt_types/evidence_scope.py b/packages/types/openadapt_types/evidence_scope.py new file mode 100644 index 0000000000..528ce98d55 --- /dev/null +++ b/packages/types/openadapt_types/evidence_scope.py @@ -0,0 +1,271 @@ +"""What a receipt's evidence covered: the evidence-scope block. + +Every receipt states, in one closed block, how its write was checked and what +that check did not see: + +- ``check_level``: the level on the one ladder + (:mod:`openadapt_types.check_level`). +- ``word``: the receipt word (``VERIFIED``, ``SHOWN``, ``CONFIRMED``, + ``ATTESTED`` or ``RECORDED``), from :func:`~openadapt_types.check_level.outcome_word`. +- ``basis``: who produced the evidence. Required for ``VERIFIED``. +- ``wire``: the channel the run observed and the protocols it parsed. + Watching the wire is not a read-back: it never makes a word stronger. +- ``read_back_at``: when the read-back ran. ``VERIFIED`` means "as of this + time, the read-back showed the value", never "persisted". +- ``recheck_window_s``: how long after ``read_back_at`` a recheck reads the + record again, when one is scheduled. +- ``not_covered``: what the evidence did not cover. It always lists + ``server_side_async_effects`` and ``outbound_effects``: no read-back sees a + job the server runs later, or a message it sends out. + +The block holds only closed values (enums, a timestamp, a count), like the +rest of a ``record/run/v1`` predicate. It is additive: a receipt without it +still verifies, and :func:`predicate_evidence_scope_problem` checks it only +when it is present. +""" + +from __future__ import annotations + +from typing import Any, Final, Iterable, Literal, Mapping, Optional + +from pydantic import ( + BaseModel, + ConfigDict, + Field, + StrictInt, + StrictStr, + ValidationError, + model_validator, +) + +from openadapt_types.check_level import ( + Basis, + CheckLevel, + OutcomeWord, + VERIFIED_LEVELS, + level_for_basis, + outcome_word, +) + +__all__ = [ + "ALWAYS_NOT_COVERED", + "EVIDENCE_SCOPE_FIELD", + "EVIDENCE_SCOPE_SCHEMA", + "EvidenceScopeV1", + "NotCovered", + "WireChannel", + "WireProtocol", + "WireScope", + "build_evidence_scope", + "evidence_scope_problem", + "predicate_evidence_scope_problem", + "with_evidence_scope", +] + +EVIDENCE_SCOPE_SCHEMA: Final = "openadapt.evidence-scope/v1" +#: The additive ``record/run/v1`` predicate field that carries the block. +EVIDENCE_SCOPE_FIELD: Final = "evidence_scope" + +#: The channel the run watched. ``none``: it watched no wire. +WireChannel = Literal[ + "none", + "browser_network", + "http_proxy", + "api_client", + "db_connection", +] +WireProtocol = Literal["http", "graphql", "fhir", "sql", "websocket", "grpc", "smtp"] +#: What a check did not cover. +NotCovered = Literal[ + "server_side_async_effects", + "outbound_effects", + "changes_after_read_back", + "fields_not_read", + "other_records", + "other_actors", +] +#: Listed on every receipt: no read-back observes these. +ALWAYS_NOT_COVERED: Final[tuple[NotCovered, ...]] = ( + "server_side_async_effects", + "outbound_effects", +) +_LEVEL_LABEL = Literal[ + "unchecked", + "same_screen", + "reopened", + "separate_session", + "system_of_record", + "counterparty_confirmed", +] +_ISO_SECONDS = r"^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$" +_MAX_RECHECK_S: Final = 30 * 24 * 3600 + + +class _Closed(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True, populate_by_name=True) + + +class WireScope(_Closed): + channel: WireChannel + protocols_parsed: list[WireProtocol] = Field(default_factory=list, max_length=7) + + @model_validator(mode="after") + def _closed(self) -> "WireScope": + if len(set(self.protocols_parsed)) != len(self.protocols_parsed): + raise ValueError("wire.protocols_parsed repeats a protocol") + if self.channel == "none" and self.protocols_parsed: + raise ValueError("a run that watched no wire parsed no protocol") + return self + + +class EvidenceScopeV1(_Closed): + """The evidence-scope block (``openadapt.evidence-scope/v1``).""" + + schema_: Literal["openadapt.evidence-scope/v1"] = Field(alias="schema") + check_level: _LEVEL_LABEL + word: OutcomeWord + basis: Optional[Basis] = None + wire: WireScope + read_back_at: Optional[StrictStr] = Field(default=None, pattern=_ISO_SECONDS) + recheck_window_s: Optional[StrictInt] = Field( + default=None, ge=0, le=_MAX_RECHECK_S + ) + not_covered: list[NotCovered] = Field(min_length=2, max_length=6) + + @model_validator(mode="after") + def _consistent(self) -> "EvidenceScopeV1": + level = CheckLevel.from_label(self.check_level) + if len(set(self.not_covered)) != len(self.not_covered): + raise ValueError("not_covered repeats a code") + if not set(ALWAYS_NOT_COVERED) <= set(self.not_covered): + raise ValueError( + "not_covered must list server_side_async_effects and outbound_effects" + ) + if self.basis is not None and level_for_basis(self.basis) != level: + raise ValueError(f"basis {self.basis} does not reach {self.check_level}") + if self.word == "VERIFIED": + if level not in VERIFIED_LEVELS or self.basis is None: + raise ValueError("VERIFIED needs level 3 or 4 and a basis") + if self.read_back_at is None: + raise ValueError("VERIFIED needs read_back_at") + if self.word == "SHOWN" and not ( + CheckLevel.SAME_SCREEN <= level <= CheckLevel.REOPENED + ): + raise ValueError("SHOWN is a level 1 or 2 re-read of the acting screen") + if self.word == "CONFIRMED" and level is not CheckLevel.COUNTERPARTY_CONFIRMED: + raise ValueError("CONFIRMED is level 5, the counterparty's acknowledgment") + if self.recheck_window_s is not None and self.read_back_at is None: + raise ValueError("a recheck window needs read_back_at") + return self + + def wire_dict(self) -> dict[str, Any]: + return self.model_dump(mode="json", by_alias=True, exclude_none=True) + + +def build_evidence_scope( + level: CheckLevel, + *, + basis: Optional[str] = None, + confirmed: bool = True, + attested: bool = False, + minimum: CheckLevel = CheckLevel.SEPARATE_SESSION, + wire_channel: str = "none", + protocols_parsed: Iterable[str] = (), + read_back_at: Optional[str] = None, + recheck_window_s: Optional[int] = None, + not_covered: Iterable[str] = (), +) -> dict[str, Any]: + """The evidence-scope block for one check, as a wire dict. + + The word comes from :func:`~openadapt_types.check_level.outcome_word`, so + every path that hands in the same evidence gets the same word. A basis is + dropped from the block when the word is not ``VERIFIED``, so a block never + names a basis it did not rely on. Raises ``ValueError`` for an + inconsistent block. + """ + + level = CheckLevel(level) + word = outcome_word( + level, basis, confirmed=confirmed, attested=attested, minimum=minimum + ) + codes = list(dict.fromkeys((*ALWAYS_NOT_COVERED, *not_covered))) + try: + block = EvidenceScopeV1.model_validate( + { + "schema": EVIDENCE_SCOPE_SCHEMA, + "check_level": level.label, + "word": word, + "basis": basis if word == "VERIFIED" else None, + "wire": { + "channel": wire_channel, + "protocols_parsed": list(dict.fromkeys(protocols_parsed)), + }, + "read_back_at": read_back_at, + "recheck_window_s": recheck_window_s, + "not_covered": codes, + } + ) + except ValidationError as error: + raise ValueError(f"invalid evidence scope: {error}") from None + return block.wire_dict() + + +def evidence_scope_problem(block: object) -> Optional[str]: + """None when ``block`` is a valid evidence-scope block; else the reason.""" + + if not isinstance(block, Mapping): + return "evidence_scope" + try: + EvidenceScopeV1.model_validate(dict(block)) + except ValidationError: + return "evidence_scope" + return None + + +#: The ``record/run/v1`` outcome each word is consistent with. +_PREDICATE_OUTCOMES: Final[Mapping[str, frozenset[str]]] = { + "VERIFIED": frozenset({"VERIFIED"}), + "CONFIRMED": frozenset({"VERIFIED"}), + "SHOWN": frozenset({"UNKNOWN", "STOPPED", "FAILED"}), + "ATTESTED": frozenset({"UNKNOWN", "STOPPED", "FAILED"}), + "RECORDED": frozenset({"UNKNOWN", "STOPPED", "FAILED"}), +} + + +def predicate_evidence_scope_problem(predicate: Mapping[str, Any]) -> Optional[str]: + """Check a ``record/run/v1`` predicate's optional ``evidence_scope``. + + A predicate without the field is an older receipt and passes. With it, + the block must be valid and its word must agree with the predicate's + ``outcome``: a ``VERIFIED`` outcome needs a ``VERIFIED`` or ``CONFIRMED`` + word, and no other outcome may carry either. + """ + + if EVIDENCE_SCOPE_FIELD not in predicate: + return None + block = predicate[EVIDENCE_SCOPE_FIELD] + problem = evidence_scope_problem(block) + if problem is not None: + return problem + allowed = _PREDICATE_OUTCOMES[block["word"]] + if predicate.get("outcome") not in allowed: + return "evidence_scope_outcome" + return None + + +def with_evidence_scope( + predicate: Mapping[str, Any], block: Mapping[str, Any] +) -> dict[str, Any]: + """A copy of ``predicate`` with ``block`` added as ``evidence_scope``. + + Raises ``ValueError`` when the block is invalid or disagrees with the + predicate's outcome. + """ + + out = dict(predicate) + out[EVIDENCE_SCOPE_FIELD] = dict(block) + problem = predicate_evidence_scope_problem(out) + if problem is not None: + raise ValueError(f"evidence scope refused: {problem}") + return out + diff --git a/packages/types/openadapt_types/execute.py b/packages/types/openadapt_types/execute.py index d46d9f2107..8bedafba9d 100644 --- a/packages/types/openadapt_types/execute.py +++ b/packages/types/openadapt_types/execute.py @@ -30,6 +30,7 @@ ) from openadapt_types.business_decision import BusinessDecisionTaskV1 +from openadapt_types.check_level import CheckLevel, from_effect_strength from openadapt_types.human_decision import HumanDecisionTaskV1 from openadapt_types.oracle import ( oracle_tier_from_effect_strength, @@ -78,7 +79,9 @@ class EffectStrengthV1(str, Enum): } # Seal oracle ladder. 0 visual, 1 second-session UI, 2 SoR, 3 counterparty. -# Production Seals require 2 or 3. Tier 3 has no EffectStrengthV1 member yet. +# Production Seals require 2 or 3. A verified receipt also accepts tier 1 when +# its contract's minimum is independent_session (_verified_read_allowed). +# Tier 3 has no EffectStrengthV1 member yet. # Mapping and production_seal_allowed live in oracle.py; this alias is the # receipt field so OpenAPI stays an integer enum. OracleTierV1: TypeAlias = Literal[0, 1, 2, 3] @@ -229,12 +232,11 @@ def _validate_proof(self) -> "ExecuteEvidenceReceiptV1": raise ValueError( "observed effect strength is below the required strength" ) - if not production_seal_allowed( - oracle_tier_from_effect_strength( - self.contracts.observed_effect_strength + if not _verified_read_allowed(self.contracts): + raise ValueError( + "a verified outcome requires oracle tier 2 or 3, or a " + "separate-session read under an independent_session minimum" ) - ): - raise ValueError("a verified outcome requires oracle tier 2 or 3") if self.outcome is ExecuteTerminalOutcomeV1.ROLLED_BACK_VERIFIED: if not self.compensation_effect_verified: raise ValueError( @@ -254,11 +256,32 @@ def _validate_proof(self) -> "ExecuteEvidenceReceiptV1": ) if self.oracle_tier != derived: raise ValueError("oracle_tier must match observed_effect_strength") - if verified and self.oracle_tier < 2: + if verified and not _verified_read_allowed(self.contracts): raise ValueError("a verified outcome requires oracle tier 2 or 3") return self +def _verified_read_allowed(contracts: "ExecuteEvidenceContractV1") -> bool: + """Whether the observed read may carry a ``verified`` outcome. + + The check-level ladder (:mod:`openadapt_types.check_level`) is the rule: a + system-of-record read (oracle tier 2 or 3) always may. A separate-session + read (level 3, oracle tier 1) may only when the contract's minimum is + exactly ``independent_session``, so a contract that did not opt in to + separate-session reads keeps the tier-2 floor. Same-screen and reopened + reads never may. + """ + + observed = contracts.observed_effect_strength + if production_seal_allowed(oracle_tier_from_effect_strength(observed)): + return True + level = from_effect_strength(observed) + return ( + level is CheckLevel.SEPARATE_SESSION + and from_effect_strength(contracts.minimum_effect_strength) is level + ) + + class _SignedExecuteWebhookV1(_StrictContract): schema_version: Literal[EXECUTE_WEBHOOK_SCHEMA] = EXECUTE_WEBHOOK_SCHEMA event_id: StrictStr = Field(pattern=_OPAQUE_ID_PATTERN) diff --git a/packages/types/tests/test_execute_contract.py b/packages/types/tests/test_execute_contract.py index 1d505b3b68..e8e8d0c1d1 100644 --- a/packages/types/tests/test_execute_contract.py +++ b/packages/types/tests/test_execute_contract.py @@ -163,14 +163,38 @@ def test_receipt_is_the_seal_and_verified_requires_sor_oracle() -> None: with pytest.raises(ValidationError, match="oracle_tier must match"): _receipt(oracle_tier=1) - with pytest.raises(ValidationError, match="oracle tier 2 or 3"): - _receipt( - contracts=_contract( - minimum_effect_strength=EffectStrengthV1.INDEPENDENT_SESSION, - observed_effect_strength=EffectStrengthV1.INDEPENDENT_SESSION, - ), - oracle_tier=1, - ) + # A separate-session read (check level 3) is verified when the contract + # opted in with an independent_session minimum. + separate = _receipt( + contracts=_contract( + minimum_effect_strength=EffectStrengthV1.INDEPENDENT_SESSION, + observed_effect_strength=EffectStrengthV1.INDEPENDENT_SESSION, + ), + oracle_tier=1, + ) + assert separate.outcome.value == "verified" + # A lower minimum does not let a separate-session read through, and a + # reopened read never verifies. + for minimum, observed, tier in ( + ( + EffectStrengthV1.IMMEDIATE_SCREEN_CONFIRMATION, + EffectStrengthV1.INDEPENDENT_SESSION, + 1, + ), + ( + EffectStrengthV1.PERSISTED_STATE_REACQUISITION, + EffectStrengthV1.PERSISTED_STATE_REACQUISITION, + 0, + ), + ): + with pytest.raises(ValidationError, match="oracle tier 2 or 3"): + _receipt( + contracts=_contract( + minimum_effect_strength=minimum, + observed_effect_strength=observed, + ), + oracle_tier=tier, + ) def test_webhook_signature_binds_the_closed_state_payload() -> None: From aa7fe2074a14bdf2089feed10d2657be914cdda0 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 11:16:48 -0500 Subject: [PATCH 2/9] docs: refresh llms-full for the ladder capability --- llms-full.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/llms-full.txt b/llms-full.txt index d67812cb9a..fd7fa4c293 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -594,6 +594,7 @@ improvising or retrying when something is off. | Stop before the effect instead of improvising (`HALTED_BEFORE_EFFECT`) | Released | Real app and synthetic | `runtime/replayer.py` | | Never retry an uncertain save (`RECONCILIATION_REQUIRED`) | Released | Synthetic (fault server) | [VERIFICATION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFICATION.md) | | One check-level scale, 0 to 5, from "unchecked" to "counterparty confirmed" | Released | Unit tests | `openadapt_flow/check_level.py` | +| One receipt word per check, the same on every path: `VERIFIED` only at level 3 (a separate session) or 4 (the system of record), always with the basis that produced the evidence (`separate_session`, `system_api`, `activity_log`, `db_frame` or `owned_connection`); `SHOWN` for an acting-screen re-read, `CONFIRMED` for the counterparty, `ATTESTED` for an operator and `RECORDED` for the rest. `VERIFIED` means "as of the read-back time the read-back showed this value", not "persisted". `verify-run` receipts and `tx` receipts carry an evidence-scope block: level, basis, word, the wire channel watched, the read-back time, the recheck window, and what it did not cover (always server-side async and outbound effects). A `verify-run` contract with `minimum_effect_strength: independent_session` now verifies on a separate-session read | On main | Unit tests (parity across the runtime report, `verify-run`, `tx` and Execute v1; fake verifiers) | `openadapt_types/check_level.py`, `openadapt_types/evidence_scope.py`, `openadapt_flow/evidence_basis.py` | | Judge any executor's write, including an agent's or a script's, from the system of record | Released | Synthetic | `openadapt-flow verify-run`, [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md) | | Judge an "ensure the record exists" write (found, created once with every value, or needs review) through a FHIR server's read path only: searches, AuditEvent and `_history`, never the database; the coverage claim names that read path. An agent's own correction of the record it created counts as one write when the audit trail and history show only that agent, no other reader, and the same record in every version | Released ([#1640](https://github.com/OpenAdaptAI/OpenAdapt/pull/1640), corrections [#1655](https://github.com/OpenAdaptAI/OpenAdapt/pull/1655)) | Real app (Medplum 5.2.8; three blind fault suites: 17/18, 17/20, 19/20; no fault passed in the last two. Corrections, on 15 blind cases and the 37 public ones: false stops 8 to 2 and 9 to 4 for Claude, no harm passed that the old rule caught) | `openadapt_flow/ensure_record.py`, [ENSURE_RECORD.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/ENSURE_RECORD.md) | | Generate an ensure-record contract from three demonstrations, the server's CapabilityStatement and its SearchParameter definitions: field paths and `[system=…]` filters, comparison kinds, value maps, identity, search parameters, the closed record and the change feed. It refuses when unsure, asks a person to confirm an identity for a type with no reviewed template, and self-checks every demonstration plus a perturbation per field | Released ([#1653](https://github.com/OpenAdaptAI/OpenAdapt/pull/1653)) | Real app (Medplum 5.2.8: all 16 hand-written Patient lines regenerated; one blind write type, Immunization: 78 s of person time, 2 lines edited after the person declined the proposed identity; blind suite 23/24, no fault passed) | `openadapt_flow/generate/ensure_contract.py`, [RESULTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/contract_autogen/results/RESULTS.md) | @@ -613,7 +614,7 @@ improvising or retrying when something is off. | Install the write checker alone: `pip install openadapt-verify` (21 distributions, about 41 MB, no vision, OCR, browser, GUI or NumPy stack; Flow 3 moved those to its `vision` extra) runs Flow's own verifier, ledger, journal, SQL guards and receipts. `openadapt-verify quickstart` checks three scripted agent writes (correct, wrong value, claimed but not saved) against REST, SQLite, FHIR, PostgreSQL and MySQL, each `CONFIRMED`, `REFUTED` or `UNCERTAIN` with a checked signed receipt; `@verified` and `checked_write` wrap a plain Python write in one line | On main | Synthetic (disposable local stores and PostgreSQL and MySQL containers; a clean-venv CI job enforces the install budget and an import test refuses the vision modules) | [packages/verify](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/verify/README.md), `openadapt_verify/quickstart.py`, `openadapt_verify/guard.py` | | Audit your own automation's success check: `openadapt-verify audit` puts an HTTP proxy in front of the app, runs your command through it N times, changes the save (the first write whose body carries a declared value, or that matches `--write-path`) once per run (not saved with a replayed success reply, rejected, a value blanked or changed, saved twice, an extra changed copy, the reply lost after the save, and a rewritten record field when given one), and counts the runs where the command reported success but the contract's independent read path shows a wrong or missing save, plus false alarms; table and JSON report. HTTP/1.x only, no app code, no WebSocket or server-sent events; a stale overwrite and a change outside the read path are not run | On main | Synthetic (two scripted HTTP clients against the quickstart's REST store: a script that trusts the 2xx reply reported success on 10 of 12 bad saves and failure on 2 saves that landed, one that reads its record back through the app on 4 of 12, missing the duplicate and extra writes) | `openadapt-verify audit`, [packages/verify](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/verify/README.md#audit-your-automations-success-check), `openadapt_verify/audit.py` | | Never send a write twice while its outcome is unknown: an append-only ledger on local disk (pluggable backend), keyed by the write's identity, that every adapter, the MCP tools and the CLI consult before sending; a read-back against the attempt's own baseline resolves it, and a refuted write waits for a person (`openadapt verify ledger list`, `reconcile`, `release`) | Released | Synthetic (MockMed's fault server: a worker killed between the send and the read-back, killed during a timed-out send, killed before the send, a late write, and two worker processes started together on one write) | `openadapt_flow/write_ledger.py`, [VERIFIER_API.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFIER_API.md#the-uncertain-write-ledger) | -| Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | +| Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with no automatic undo, and its result is `UNCERTAIN` unless the read-back is a cache-bypassed API read whose record version is exactly one past the before-image's, which is `CONFIRMED` with basis `system_api`. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | | Reconcile one prior authorization or claim across the EHR (FHIR), the clearinghouse (X12 278 and 277 files) and the payer (Da Vinci PAS): each leg is a verifier contract judged by the same record checks, and the result names each break (`not_received`, `mismatch`, `not_written_back`, `duplicate`, `not_accepted`) with `CONFIRMED`/`REFUTED`/`UNCERTAIN` and a Scope; absence before a deadline is `UNCERTAIN`, an unreadable store is never agreement, a rejected or returned 277 is never agreement, and a judged record or value with two distinct candidates in the read (repeated segments, list elements, join targets, a group's latest) is never `CONFIRMED` | On main | HL7 Da Vinci PAS reference implementation and Medplum run locally, synthetic X12: 36 of 36 planted breaks found, 0 of 27 faulty units `CONFIRMED`, 17 of 17 clean units `CONFIRMED` (units 1 to 47; the 3 status-category units added later are covered by unit tests); a Hypothesis property test over generated multi-candidate reads; Epic's public sandbox read-only as the EHR leg | `openadapt-flow reconcile`, [RECONCILE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/RECONCILE.md), [results](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/reconcile/RESULTS.md) | | Catch a write that lands after the verdict (a background job, a trigger, a delayed side record): a `CONFIRMED` with a recheck due is provisional (`provisional`, `recheck_due_at`); the recheck reads the whole database again and refutes the earlier result when a change since the post-save read has no explanation, and a recheck that doesn't confirm holds the write in the ledger. Run it from Python (`verifier.recheck`) or MCP (`verify_recheck`). A write after the recheck's read is not seen (`frame.database.recheck_after_s`, no default window) | Released ([#1639](https://github.com/OpenAdaptAI/OpenAdapt/pull/1639)); provisional result, MCP tool and ledger hold ([#1669](https://github.com/OpenAdaptAI/OpenAdapt/pull/1669)) | Real app (Dolibarr 21 and EspoCRM 10 on MariaDB 11.4, 180 s window: 4 of 4 planted late writes at 125 to 130 s refuted at the recheck, correct writes confirmed; EspoCRM's cron daemon needs its job tables declared; Redmine 6.1 on PostgreSQL 17, 180 s window: the first-contact study's late writes F19 and F20 refuted at the recheck, correct writes confirmed); synthetic (SQLite); opt-in live OpenEMR test | `openadapt_flow/verifier.py`, `runtime/effects/late_write.py`, [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#writes-that-land-later) | | Diff the whole database for the frame (`frame.database`) on SQLite, MySQL, MariaDB and PostgreSQL. On MySQL and MariaDB every column type is read exactly (binary strings, `BIT`, geometries and vectors as hex, `FLOAT` widened to `DOUBLE`, `JSON` as stored text, decimals at full precision). On PostgreSQL every column type is read as text by a declared rule in a session pinned to UTC and exact float output, and a type without a rule, a table the account can't read in full, or an unreadable sequence is refused. So a row the save adds, changes or removes outside the declared records, such as an extra planned call or a stream note, is refuted unless a declared effect, a side record, an attributed concurrent write or an allow-listed bookkeeping table explains it | Released ([#1661](https://github.com/OpenAdaptAI/OpenAdapt/pull/1661)); PostgreSQL ([#1673](https://github.com/OpenAdaptAI/OpenAdapt/pull/1673)) | Real app (Dolibarr 21 on MariaDB 11.4: all 387 tables read where the frame raised `TypeError`; EspoCRM on MariaDB 11.4: the first-contact study's extra call and stream note refuted, correct opportunities verified; Redmine 6.1 on PostgreSQL 17: 58 tables read, a stray upload in a table the contract doesn't read refuted, correct writes verified); live MariaDB and PostgreSQL type tests | [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#the-whole-database), `runtime/effects/db_snapshot.py` | From d5db93fa7f4fd3905828606c28374eaf5eef1d31 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 18:09:31 -0500 Subject: [PATCH 3/9] feat(ladder): evidence scope on record/run/v1 run receipts --- CAPABILITIES.md | 2 +- packages/flow/CHANGELOG.md | 7 +- .../flow/openadapt_flow/evidence_basis.py | 6 +- .../flow/openadapt_flow/receipt_record.py | 37 ++++++++ packages/flow/tests/test_one_ladder.py | 85 +++++++++++++++++++ packages/types/CHANGELOG.md | 9 +- .../types/openadapt_types/evidence_scope.py | 13 ++- packages/types/openadapt_types/receipt.py | 23 ++++- .../tests/vectors/record-run-v1/README.md | 7 +- .../evidence-scope-disagrees.json | 21 +++++ .../tests/vectors/record-run-v1/generate.py | 30 +++++++ .../record-run-v1/valid-evidence-scope.json | 24 ++++++ 12 files changed, 252 insertions(+), 12 deletions(-) create mode 100644 packages/types/tests/vectors/record-run-v1/evidence-scope-disagrees.json create mode 100644 packages/types/tests/vectors/record-run-v1/valid-evidence-scope.json diff --git a/CAPABILITIES.md b/CAPABILITIES.md index c03073eb13..c1e7915009 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -161,7 +161,7 @@ improvising or retrying when something is off. | Stop before the effect instead of improvising (`HALTED_BEFORE_EFFECT`) | Released | Real app and synthetic | `runtime/replayer.py` | | Never retry an uncertain save (`RECONCILIATION_REQUIRED`) | Released | Synthetic (fault server) | [VERIFICATION.md](packages/flow/docs/VERIFICATION.md) | | One check-level scale, 0 to 5, from "unchecked" to "counterparty confirmed" | Released | Unit tests | `openadapt_flow/check_level.py` | -| One receipt word per check, the same on every path: `VERIFIED` only at level 3 (a separate session) or 4 (the system of record), always with the basis that produced the evidence (`separate_session`, `system_api`, `activity_log`, `db_frame` or `owned_connection`); `SHOWN` for an acting-screen re-read, `CONFIRMED` for the counterparty, `ATTESTED` for an operator and `RECORDED` for the rest. `VERIFIED` means "as of the read-back time the read-back showed this value", not "persisted". `verify-run` receipts and `tx` receipts carry an evidence-scope block: level, basis, word, the wire channel watched, the read-back time, the recheck window, and what it did not cover (always server-side async and outbound effects). A `verify-run` contract with `minimum_effect_strength: independent_session` now verifies on a separate-session read | On main | Unit tests (parity across the runtime report, `verify-run`, `tx` and Execute v1; fake verifiers) | `openadapt_types/check_level.py`, `openadapt_types/evidence_scope.py`, `openadapt_flow/evidence_basis.py` | +| One receipt word per check, the same on every path: `VERIFIED` only at level 3 (a separate session) or 4 (the system of record), always with the basis that produced the evidence (`separate_session`, `system_api`, `activity_log`, `db_frame` or `owned_connection`); `SHOWN` for an acting-screen re-read, `CONFIRMED` for the counterparty, `ATTESTED` for an operator and `RECORDED` for the rest. `VERIFIED` means "as of the read-back time the read-back showed this value", not "persisted". Run receipts (`record/run/v1`, an additive optional field), `verify-run` receipts and `tx` receipts carry an evidence-scope block: level, basis, word, the wire channel watched, the read-back time, the recheck window, and what it did not cover (always server-side async and outbound effects; a run receipt says it has no per-read time). A run receipt never says `VERIFIED` below level 3. Receipts without the block still verify. A `verify-run` contract with `minimum_effect_strength: independent_session` now verifies on a separate-session read | On main | Unit tests (parity across the runtime report, `verify-run`, `tx` and Execute v1; fake verifiers) | `openadapt_types/check_level.py`, `openadapt_types/evidence_scope.py`, `openadapt_flow/evidence_basis.py` | | Judge any executor's write, including an agent's or a script's, from the system of record | Released | Synthetic | `openadapt-flow verify-run`, [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md) | | Judge an "ensure the record exists" write (found, created once with every value, or needs review) through a FHIR server's read path only: searches, AuditEvent and `_history`, never the database; the coverage claim names that read path. An agent's own correction of the record it created counts as one write when the audit trail and history show only that agent, no other reader, and the same record in every version | Released ([#1640](https://github.com/OpenAdaptAI/OpenAdapt/pull/1640), corrections [#1655](https://github.com/OpenAdaptAI/OpenAdapt/pull/1655)) | Real app (Medplum 5.2.8; three blind fault suites: 17/18, 17/20, 19/20; no fault passed in the last two. Corrections, on 15 blind cases and the 37 public ones: false stops 8 to 2 and 9 to 4 for Claude, no harm passed that the old rule caught) | `openadapt_flow/ensure_record.py`, [ENSURE_RECORD.md](packages/flow/docs/ENSURE_RECORD.md) | | Generate an ensure-record contract from three demonstrations, the server's CapabilityStatement and its SearchParameter definitions: field paths and `[system=…]` filters, comparison kinds, value maps, identity, search parameters, the closed record and the change feed. It refuses when unsure, asks a person to confirm an identity for a type with no reviewed template, and self-checks every demonstration plus a perturbation per field | Released ([#1653](https://github.com/OpenAdaptAI/OpenAdapt/pull/1653)) | Real app (Medplum 5.2.8: all 16 hand-written Patient lines regenerated; one blind write type, Immunization: 78 s of person time, 2 lines edited after the person declined the proposed identity; blind suite 23/24, no fault passed) | `openadapt_flow/generate/ensure_contract.py`, [RESULTS.md](packages/flow/benchmark/contract_autogen/results/RESULTS.md) | diff --git a/packages/flow/CHANGELOG.md b/packages/flow/CHANGELOG.md index 176b3cf70b..9af7970cc1 100644 --- a/packages/flow/CHANGELOG.md +++ b/packages/flow/CHANGELOG.md @@ -25,10 +25,13 @@ receipt word: `VERIFIED` (levels 3 and 4 only, always with a basis: `separate_session`, `system_api`, `activity_log`, `db_frame` or `owned_connection`), `SHOWN`, `CONFIRMED`, `ATTESTED` or `RECORDED`. - `verify-run` and `tx` receipts carry an additive `evidence_scope` block + Run receipts (`record/run/v1`), `verify-run` and `tx` receipts carry an + additive `evidence_scope` block (`openadapt.evidence-scope/v1`) that states the level, basis, wire scope, read-back time, recheck window and what the check did not cover. Receipts - without the block still verify. + without the block still verify. A run receipt whose report shows a save + checked below level 3 is `UNKNOWN` (`below_verified_level`), never + `VERIFIED`; no built-in profile produces such a run. ### Fixes diff --git a/packages/flow/openadapt_flow/evidence_basis.py b/packages/flow/openadapt_flow/evidence_basis.py index fd5e50285c..c92672819f 100644 --- a/packages/flow/openadapt_flow/evidence_basis.py +++ b/packages/flow/openadapt_flow/evidence_basis.py @@ -116,5 +116,9 @@ def evidence_scope_for_run( confirmed=level > CheckLevel.UNCHECKED, minimum=minimum, read_back_at=read_back_at if level > CheckLevel.UNCHECKED else None, - not_covered=("changes_after_read_back",), + not_covered=( + "changes_after_read_back", + # A run report records no per-read time yet. + *(("read_back_time",) if read_back_at is None else ()), + ), ) diff --git a/packages/flow/openadapt_flow/receipt_record.py b/packages/flow/openadapt_flow/receipt_record.py index e431f764e9..42e1e6f8b0 100644 --- a/packages/flow/openadapt_flow/receipt_record.py +++ b/packages/flow/openadapt_flow/receipt_record.py @@ -133,6 +133,13 @@ def build_statement( outcome, reason = "UNKNOWN", "refuted_write" elif outcome == "VERIFIED" and len(every_line) > r.MAX_LINES: outcome, reason = "UNKNOWN", "too_many_writes" + scope = _evidence_scope(report, outcome) + if scope is None and outcome == "VERIFIED" and isinstance( + report.get("readback"), Mapping + ): + # Receipts say VERIFIED only on a level 3 or 4 read (check_level). + outcome, reason = "UNKNOWN", "below_verified_level" + scope = _evidence_scope(report, outcome) bundle = report.get("bundle_content_digest") bundle = bundle if isinstance(bundle, str) and _SHA256.fullmatch(bundle) else None version = bundle or report_sha256 @@ -185,11 +192,41 @@ def build_statement( "version": r.PUBLIC_DISCLOSURE_VERSION, "commitments": commitments, }, + **({"evidence_scope": scope} if scope is not None else {}), }, } return statement, openings +def _evidence_scope( + report: Mapping[str, Any], outcome: str +) -> Optional[dict[str, Any]]: + """The run's evidence-scope block, or None when it can't be stated. + + None for a ``VERIFIED`` receipt whose evidence doesn't reach the word + ``VERIFIED`` (the caller then lowers the outcome), and for a ``VERIFIED`` + report with no ``readback`` block (made no save, or written before the + block existed), which keeps its earlier receipt shape. + """ + from openadapt_types.evidence_scope import predicate_evidence_scope_problem + + from openadapt_flow.evidence_basis import evidence_scope_for_run + + readback = report.get("readback") + readback = readback if isinstance(readback, Mapping) else None + if readback is None and outcome == "VERIFIED": + return None + try: + scope = evidence_scope_for_run(readback, outcome) + except ValueError: + return None + if predicate_evidence_scope_problem( + {"outcome": outcome, "evidence_scope": scope} + ): + return None + return scope + + def _write(path: Path, payload: Mapping[str, Any], *, private: bool = False) -> None: tmp = path.with_name(path.name + ".tmp") data = (json.dumps(payload, indent=2, sort_keys=True) + "\n").encode("utf-8") diff --git a/packages/flow/tests/test_one_ladder.py b/packages/flow/tests/test_one_ladder.py index 8e85a39915..317d12f28b 100644 --- a/packages/flow/tests/test_one_ladder.py +++ b/packages/flow/tests/test_one_ladder.py @@ -321,3 +321,88 @@ def test_every_block_lists_what_no_read_back_sees() -> None: "server_side_async_effects", "outbound_effects", ] + + +# -- the run receipt (record/run/v1) ------------------------------------------- + + +def _run_report(checked_how, outcome="VERIFIED"): + report = { + "workflow_name": "ladder-test", + "started_at": "2026-11-21T12:34:56Z", + "execution_outcome": outcome, + "model_calls": 0, + "results": [{"step_id": "save", "ok": True}], + } + if checked_how is not None: + report["readback"] = { + "minimum": "separate_session", + "checked_how": checked_how, + "label": checked_how, + "below_minimum": False, + "saves": [], + } + return report + + +def _statement(report): + from openadapt_types import receipt as r + + from openadapt_flow.receipt_record import build_statement + + statement, _ = build_statement(report, "1" * 64, salt=lambda: "2" * 64) + # The signer's own check: refuses a block that disagrees with the outcome. + r.statement_payload(statement) + return statement["predicate"] + + +@pytest.mark.parametrize( + ("checked_how", "word", "basis"), + [ + ("separate_session", "VERIFIED", "separate_session"), + ("system_of_record", "VERIFIED", "owned_connection"), + ], +) +def test_run_receipt_states_its_evidence_scope(checked_how, word, basis) -> None: + predicate = _statement(_run_report(checked_how)) + scope = predicate["evidence_scope"] + assert predicate["outcome"] == "VERIFIED" + assert (scope["check_level"], scope["word"], scope["basis"]) == ( + checked_how, + word, + basis, + ) + # The report has no per-read time, and the block says so. + assert "read_back_at" not in scope + assert "read_back_time" in scope["not_covered"] + # Same level, word and basis as the runtime and verify-run paths. + assert _key(scope) == _key(_runtime_scope(to_verification_tier( + CheckLevel.from_label(checked_how) + ))) + + +def test_run_receipt_never_says_verified_below_level_3() -> None: + predicate = _statement(_run_report("reopened")) + assert predicate["outcome"] == "UNKNOWN" + assert predicate["reason_code"] == "below_verified_level" + assert predicate["evidence_scope"]["word"] == "RECORDED" + + +def test_run_receipt_without_a_readback_block_keeps_its_old_shape() -> None: + from openadapt_types import receipt as r + + predicate = _statement(_run_report(None)) + assert predicate["outcome"] == "VERIFIED" + assert "evidence_scope" not in predicate + # And a statement without the block serializes with no trace of it. + statement, _ = __import__( + "openadapt_flow.receipt_record", fromlist=["build_statement"] + ).build_statement(_run_report(None), "1" * 64, salt=lambda: "2" * 64) + assert b"evidence_scope" not in r.statement_payload(statement) + + +def test_stopped_run_receipt_is_recorded() -> None: + predicate = _statement(_run_report("separate_session", outcome="HALTED")) + assert predicate["outcome"] == "STOPPED" + assert predicate["evidence_scope"]["word"] == "RECORDED" + assert "basis" not in predicate["evidence_scope"] diff --git a/packages/types/CHANGELOG.md b/packages/types/CHANGELOG.md index b67fecd35e..ea1df129fe 100644 --- a/packages/types/CHANGELOG.md +++ b/packages/types/CHANGELOG.md @@ -11,8 +11,13 @@ `outcome_word`, plus the inverse tier maps and the Execute effect-strength map. - `evidence_scope`: the `openadapt.evidence-scope/v1` block and the additive - `evidence_scope` field for `record/run/v1` predicates. A predicate without - it still passes. + `evidence_scope` field on `receipt.RunPredicateV1` (`record/run/v1`). A + receipt without it keeps its exact canonical bytes and still verifies; with + it, a `VERIFIED` outcome needs the word `VERIFIED` or `CONFIRMED`, and no + other outcome may carry either (`inconsistent`). Two new shared vectors, + `valid-evidence-scope` and `evidence-scope-disagrees`; the existing ones + are unchanged. A producer with no read-back time lists `read_back_time` in + `not_covered`. - `ExecuteEvidenceReceiptV1` accepts `verified` at oracle tier 1 (a separate-session read) when the contract's minimum is exactly `independent_session`. Every other contract keeps the tier-2 floor, and diff --git a/packages/types/openadapt_types/evidence_scope.py b/packages/types/openadapt_types/evidence_scope.py index 528ce98d55..c4fd4cc08d 100644 --- a/packages/types/openadapt_types/evidence_scope.py +++ b/packages/types/openadapt_types/evidence_scope.py @@ -16,7 +16,9 @@ record again, when one is scheduled. - ``not_covered``: what the evidence did not cover. It always lists ``server_side_async_effects`` and ``outbound_effects``: no read-back sees a - job the server runs later, or a message it sends out. + job the server runs later, or a message it sends out. A producer that did + not record when its read-back ran lists ``read_back_time`` instead of a + ``read_back_at`` (a run report has no per-read time yet). The block holds only closed values (enums, a timestamp, a count), like the rest of a ``record/run/v1`` predicate. It is additive: a receipt without it @@ -83,6 +85,7 @@ "fields_not_read", "other_records", "other_actors", + "read_back_time", ] #: Listed on every receipt: no read-back observes these. ALWAYS_NOT_COVERED: Final[tuple[NotCovered, ...]] = ( @@ -130,7 +133,7 @@ class EvidenceScopeV1(_Closed): recheck_window_s: Optional[StrictInt] = Field( default=None, ge=0, le=_MAX_RECHECK_S ) - not_covered: list[NotCovered] = Field(min_length=2, max_length=6) + not_covered: list[NotCovered] = Field(min_length=2, max_length=7) @model_validator(mode="after") def _consistent(self) -> "EvidenceScopeV1": @@ -146,14 +149,16 @@ def _consistent(self) -> "EvidenceScopeV1": if self.word == "VERIFIED": if level not in VERIFIED_LEVELS or self.basis is None: raise ValueError("VERIFIED needs level 3 or 4 and a basis") - if self.read_back_at is None: - raise ValueError("VERIFIED needs read_back_at") + if self.read_back_at is None and "read_back_time" not in self.not_covered: + raise ValueError("VERIFIED needs read_back_at, or says it has none") if self.word == "SHOWN" and not ( CheckLevel.SAME_SCREEN <= level <= CheckLevel.REOPENED ): raise ValueError("SHOWN is a level 1 or 2 re-read of the acting screen") if self.word == "CONFIRMED" and level is not CheckLevel.COUNTERPARTY_CONFIRMED: raise ValueError("CONFIRMED is level 5, the counterparty's acknowledgment") + if self.read_back_at is not None and "read_back_time" in self.not_covered: + raise ValueError("a block with read_back_at covers the read-back time") if self.recheck_window_s is not None and self.read_back_at is None: raise ValueError("a recheck window needs read_back_at") return self diff --git a/packages/types/openadapt_types/receipt.py b/packages/types/openadapt_types/receipt.py index 9728d29295..236b566f43 100644 --- a/packages/types/openadapt_types/receipt.py +++ b/packages/types/openadapt_types/receipt.py @@ -41,6 +41,12 @@ from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, ValidationError +from openadapt_types.evidence_scope import ( + EVIDENCE_SCOPE_FIELD, + EvidenceScopeV1, + predicate_evidence_scope_problem, +) + STATEMENT_TYPE: Final = "https://in-toto.io/Statement/v1" PREDICATE_TYPE: Final = "https://openadapt.ai/record/run/v1" PAYLOAD_TYPE: Final = "application/vnd.in-toto+json" @@ -202,6 +208,9 @@ class RunPredicateV1(_Closed): checks: Checks model_calls: Count = Field(ge=0, le=MAX_COUNT) disclosure: Disclosure + #: Additive: what the evidence covered (``openadapt.evidence-scope/v1``). + #: A receipt without it is an older one and still verifies. + evidence_scope: Optional[EvidenceScopeV1] = None class RunStatementV1(_Closed): @@ -211,7 +220,15 @@ class RunStatementV1(_Closed): predicate: RunPredicateV1 def wire(self) -> dict[str, Any]: - return self.model_dump(mode="json", by_alias=True) + out = self.model_dump(mode="json", by_alias=True) + scope = self.predicate.evidence_scope + # Left out when absent, so a receipt from before the field keeps its + # exact canonical bytes. + if scope is None: + out["predicate"].pop(EVIDENCE_SCOPE_FIELD, None) + else: + out["predicate"][EVIDENCE_SCOPE_FIELD] = scope.wire_dict() + return out def _check_consistent(statement: RunStatementV1) -> Optional[str]: @@ -244,6 +261,10 @@ def _check_consistent(statement: RunStatementV1) -> Optional[str]: return "check counts disagree with the lines" if p.outcome == "VERIFIED" and tally["refuted"]: return "a VERIFIED receipt has a refuted line" + if p.evidence_scope is not None and predicate_evidence_scope_problem( + {"outcome": p.outcome, EVIDENCE_SCOPE_FIELD: p.evidence_scope.wire_dict()} + ): + return "the evidence scope's word disagrees with the outcome" steps = [line.step for line in p.lines] if steps != sorted(set(steps)): return "lines are not in step order, or repeat a step" diff --git a/packages/types/tests/vectors/record-run-v1/README.md b/packages/types/tests/vectors/record-run-v1/README.md index 26b3f2b13d..6a8039edb2 100644 --- a/packages/types/tests/vectors/record-run-v1/README.md +++ b/packages/types/tests/vectors/record-run-v1/README.md @@ -39,7 +39,12 @@ not secrets. Closed schema (see `openadapt_types/receipt.py`); the payload must equal its canonical form (sorted keys, no whitespace, no ASCII escaping), otherwise `malformed`. Contradictions (counts that disagree with `lines`, a VERIFIED - receipt with a refuted line) are `inconsistent`. + receipt with a refuted line) are `inconsistent`. The predicate may carry an + optional `evidence_scope` block (`openadapt.evidence-scope/v1`, closed; see + `openadapt_types/evidence_scope.py`); a receipt without it still verifies. + With it, a `VERIFIED` outcome needs the word `VERIFIED` (level 3 or 4, with + a basis) or `CONFIRMED`, and no other outcome may carry either; otherwise + `inconsistent`. 4. **Commitments.** `sha256("openadapt.receipt-commitment/v1" 0x00 path 0x00 salt(32 raw bytes) 0x00 canonical_json(value))`, as lower-case hex. Salts are 64 lower-case hex characters. diff --git a/packages/types/tests/vectors/record-run-v1/evidence-scope-disagrees.json b/packages/types/tests/vectors/record-run-v1/evidence-scope-disagrees.json new file mode 100644 index 0000000000..1fea21c67c --- /dev/null +++ b/packages/types/tests/vectors/record-run-v1/evidence-scope-disagrees.json @@ -0,0 +1,21 @@ +{ + "description": "A VERIFIED record whose evidence scope says only SHOWN (the acting screen): refused.", + "document": { + "payload": "eyJfdHlwZSI6Imh0dHBzOi8vaW4tdG90by5pby9TdGF0ZW1lbnQvdjEiLCJwcmVkaWNhdGUiOnsiY2hlY2tzIjp7ImF1dGhvcml6YXRpb24iOnsiY29uZmlybWVkIjowLCJyZXF1aXJlZCI6MH0sImVmZmVjdHMiOnsiY29uZmlybWVkIjoyLCJyZXF1aXJlZCI6Mn0sImlkZW50aXR5Ijp7ImNvbmZpcm1lZCI6NSwicmVxdWlyZWQiOjV9LCJsaW5lc19jb25maXJtZWQiOjIsImxpbmVzX25vdF9jaGVja2VkIjowLCJsaW5lc19yZWZ1dGVkIjowLCJwb3N0Y29uZGl0aW9ucyI6eyJjb25maXJtZWQiOjMsInJlcXVpcmVkIjozfX0sImRpc2Nsb3N1cmUiOnsiY29tbWl0bWVudHMiOnt9LCJ2ZXJzaW9uIjoib3BlbmFkYXB0LnB1YmxpYy1kaXNjbG9zdXJlL3YxIn0sImV2aWRlbmNlX3Njb3BlIjp7ImNoZWNrX2xldmVsIjoic2FtZV9zY3JlZW4iLCJub3RfY292ZXJlZCI6WyJzZXJ2ZXJfc2lkZV9hc3luY19lZmZlY3RzIiwib3V0Ym91bmRfZWZmZWN0cyIsImNoYW5nZXNfYWZ0ZXJfcmVhZF9iYWNrIiwicmVhZF9iYWNrX3RpbWUiXSwic2NoZW1hIjoib3BlbmFkYXB0LmV2aWRlbmNlLXNjb3BlL3YxIiwid2lyZSI6eyJjaGFubmVsIjoibm9uZSIsInByb3RvY29sc19wYXJzZWQiOltdfSwid29yZCI6IlNIT1dOIn0sImxpbmVzIjpbeyJjaGVjayI6ImNvbmZpcm1lZCIsIm5vdF9jaGVja2VkIjpbXSwib3BlcmF0aW9uIjoid3JpdGUiLCJzdGVwIjoyLCJzdHJlbmd0aCI6InJlYWRfYmFjayIsInRhcmdldF9raW5kIjoiZ3VpIn0seyJjaGVjayI6ImNvbmZpcm1lZCIsIm5vdF9jaGVja2VkIjpbImZpZWxkX3ZhbHVlcyJdLCJvcGVyYXRpb24iOiJpcnJldmVyc2libGVfd3JpdGUiLCJzdGVwIjo0LCJzdHJlbmd0aCI6InJlYWRfYmFjayIsInRhcmdldF9raW5kIjoiZ3VpIn1dLCJtb2RlbF9jYWxscyI6MCwib3V0Y29tZSI6IlZFUklGSUVEIiwicHJvZ3JhbSI6eyJpZCI6InByb2ctNWJiMjFhYTBmMmU2YWMzMiIsInZlcnNpb25fc2hhMjU2IjoiMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMiJ9LCJyZWFzb25fY29kZSI6InZlcmlmaWVkIiwic3RhcnRlZF9ob3VyIjoiMjAyNi0xMS0yMFQyMzowMDowMFoiLCJzdGVwcyI6eyJvayI6NSwidG90YWwiOjV9fSwicHJlZGljYXRlVHlwZSI6Imh0dHBzOi8vb3BlbmFkYXB0LmFpL3JlY29yZC9ydW4vdjEiLCJzdWJqZWN0IjpbeyJkaWdlc3QiOnsic2hhMjU2IjoiMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMSJ9LCJuYW1lIjoicmVwb3J0Lmpzb24ifSx7ImRpZ2VzdCI6eyJzaGEyNTYiOiIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyIn0sIm5hbWUiOiJidW5kbGUifV19", + "payloadType": "application/vnd.in-toto+json", + "signatures": [ + { + "keyid": "seal-ed25519-b7a5ba90250d87f2", + "sig": "hQIe1xXdm0754SwZhjOuh08tmDm+tNfN1wRN0/oIJ7lFUpJSrDDCCVxKOZlPZNK0EtYh5MyuZENit3PNRxQJDQ==" + } + ] + }, + "expected": { + "ok": false, + "reason": "inconsistent", + "signer_lines": [ + "Not verified: the receipt contradicts itself" + ] + }, + "registry": "registry.json" +} diff --git a/packages/types/tests/vectors/record-run-v1/generate.py b/packages/types/tests/vectors/record-run-v1/generate.py index 566015353f..04994561af 100644 --- a/packages/types/tests/vectors/record-run-v1/generate.py +++ b/packages/types/tests/vectors/record-run-v1/generate.py @@ -224,6 +224,36 @@ def add(name, description, document, expected, openings=None): add("embedded-image-in-record", "A signed record whose payload carries base64 image bytes: refused.", raw_env, {"ok": False, "reason": "embedded_content", "signer_lines": [r.refusal_line("embedded_content")]}) + scoped = statement("VERIFIED") + scoped["predicate"]["evidence_scope"] = { + "schema": "openadapt.evidence-scope/v1", + "check_level": "separate_session", + "word": "VERIFIED", + "basis": "separate_session", + "wire": {"channel": "none", "protocols_parsed": []}, + "not_covered": [ + "server_side_async_effects", + "outbound_effects", + "changes_after_read_back", + "read_back_time", + ], + } + add("valid-evidence-scope", + "A run that states what its evidence covered: a separate-session read, VERIFIED with its basis.", + r.sign_statement(scoped, [signer("this_computer")]), + {**ok_local, "outcome": "VERIFIED", "disclosed": {}}) + shown = copy.deepcopy(scoped) + shown["predicate"]["evidence_scope"].update( + {"check_level": "same_screen", "word": "SHOWN"}) + del shown["predicate"]["evidence_scope"]["basis"] + payload = r.canonical_json(shown).encode() + shown_env = {"payloadType": r.PAYLOAD_TYPE, "payload": base64.b64encode(payload).decode(), + "signatures": [{"keyid": IDS["this_computer"], + "sig": base64.b64encode(KEYS["this_computer"].sign(r.pae(r.PAYLOAD_TYPE, payload))).decode()}]} + add("evidence-scope-disagrees", + "A VERIFIED record whose evidence scope says only SHOWN (the acting screen): refused.", + shown_env, {"ok": False, "reason": "inconsistent", + "signer_lines": [r.refusal_line("inconsistent")]}) other = statement("VERIFIED") other["predicateType"] = "https://openadapt.ai/record/run/v9" payload = r.canonical_json(other).encode() diff --git a/packages/types/tests/vectors/record-run-v1/valid-evidence-scope.json b/packages/types/tests/vectors/record-run-v1/valid-evidence-scope.json new file mode 100644 index 0000000000..1be4038c0c --- /dev/null +++ b/packages/types/tests/vectors/record-run-v1/valid-evidence-scope.json @@ -0,0 +1,24 @@ +{ + "description": "A run that states what its evidence covered: a separate-session read, VERIFIED with its basis.", + "document": { + "payload": "eyJfdHlwZSI6Imh0dHBzOi8vaW4tdG90by5pby9TdGF0ZW1lbnQvdjEiLCJwcmVkaWNhdGUiOnsiY2hlY2tzIjp7ImF1dGhvcml6YXRpb24iOnsiY29uZmlybWVkIjowLCJyZXF1aXJlZCI6MH0sImVmZmVjdHMiOnsiY29uZmlybWVkIjoyLCJyZXF1aXJlZCI6Mn0sImlkZW50aXR5Ijp7ImNvbmZpcm1lZCI6NSwicmVxdWlyZWQiOjV9LCJsaW5lc19jb25maXJtZWQiOjIsImxpbmVzX25vdF9jaGVja2VkIjowLCJsaW5lc19yZWZ1dGVkIjowLCJwb3N0Y29uZGl0aW9ucyI6eyJjb25maXJtZWQiOjMsInJlcXVpcmVkIjozfX0sImRpc2Nsb3N1cmUiOnsiY29tbWl0bWVudHMiOnt9LCJ2ZXJzaW9uIjoib3BlbmFkYXB0LnB1YmxpYy1kaXNjbG9zdXJlL3YxIn0sImV2aWRlbmNlX3Njb3BlIjp7ImJhc2lzIjoic2VwYXJhdGVfc2Vzc2lvbiIsImNoZWNrX2xldmVsIjoic2VwYXJhdGVfc2Vzc2lvbiIsIm5vdF9jb3ZlcmVkIjpbInNlcnZlcl9zaWRlX2FzeW5jX2VmZmVjdHMiLCJvdXRib3VuZF9lZmZlY3RzIiwiY2hhbmdlc19hZnRlcl9yZWFkX2JhY2siLCJyZWFkX2JhY2tfdGltZSJdLCJzY2hlbWEiOiJvcGVuYWRhcHQuZXZpZGVuY2Utc2NvcGUvdjEiLCJ3aXJlIjp7ImNoYW5uZWwiOiJub25lIiwicHJvdG9jb2xzX3BhcnNlZCI6W119LCJ3b3JkIjoiVkVSSUZJRUQifSwibGluZXMiOlt7ImNoZWNrIjoiY29uZmlybWVkIiwibm90X2NoZWNrZWQiOltdLCJvcGVyYXRpb24iOiJ3cml0ZSIsInN0ZXAiOjIsInN0cmVuZ3RoIjoicmVhZF9iYWNrIiwidGFyZ2V0X2tpbmQiOiJndWkifSx7ImNoZWNrIjoiY29uZmlybWVkIiwibm90X2NoZWNrZWQiOlsiZmllbGRfdmFsdWVzIl0sIm9wZXJhdGlvbiI6ImlycmV2ZXJzaWJsZV93cml0ZSIsInN0ZXAiOjQsInN0cmVuZ3RoIjoicmVhZF9iYWNrIiwidGFyZ2V0X2tpbmQiOiJndWkifV0sIm1vZGVsX2NhbGxzIjowLCJvdXRjb21lIjoiVkVSSUZJRUQiLCJwcm9ncmFtIjp7ImlkIjoicHJvZy01YmIyMWFhMGYyZTZhYzMyIiwidmVyc2lvbl9zaGEyNTYiOiIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyIn0sInJlYXNvbl9jb2RlIjoidmVyaWZpZWQiLCJzdGFydGVkX2hvdXIiOiIyMDI2LTExLTIwVDIzOjAwOjAwWiIsInN0ZXBzIjp7Im9rIjo1LCJ0b3RhbCI6NX19LCJwcmVkaWNhdGVUeXBlIjoiaHR0cHM6Ly9vcGVuYWRhcHQuYWkvcmVjb3JkL3J1bi92MSIsInN1YmplY3QiOlt7ImRpZ2VzdCI6eyJzaGEyNTYiOiIxMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExIn0sIm5hbWUiOiJyZXBvcnQuanNvbiJ9LHsiZGlnZXN0Ijp7InNoYTI1NiI6IjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIifSwibmFtZSI6ImJ1bmRsZSJ9XX0=", + "payloadType": "application/vnd.in-toto+json", + "signatures": [ + { + "keyid": "seal-ed25519-b7a5ba90250d87f2", + "sig": "NOVgbnNHOFefPfCOT7yjdyDwAFviWm0JMotmlschaGkXYd7H+Iy8QslZ97Uk2Hus4x4lj8WkqAMojkzO1UuODg==" + } + ] + }, + "expected": { + "demo": false, + "disclosed": {}, + "ok": true, + "outcome": "VERIFIED", + "reason": null, + "signer_lines": [ + "Signed by this computer" + ] + }, + "registry": "registry.json" +} From c36d098cd4f145ec359ca823dd812de22b1b4688 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 19:10:27 -0500 Subject: [PATCH 4/9] feat(ladder): evidence scope on run receipts; fix tests for the one ladder Run receipts (record/run/v1) carry the optional evidence_scope block; a receipt without it keeps its canonical bytes and still verifies. A run receipt never says VERIFIED below check level 3. Fake-verifier verify-run tests now take a baseline so the frame is judged. tx tests that expected UNCERTAIN for a cache-bypassed, version-checked API read now expect CONFIRMED with basis system_api; undo still needs the row authority. --- llms-full.txt | 4 +-- packages/flow/docs/RECEIPTS.md | 13 ++++++++- .../flow/openadapt_flow/evidence_basis.py | 4 +-- .../flow/openadapt_flow/receipt_record.py | 10 +++---- .../flow/openadapt_flow/tx/api_readback.py | 4 ++- packages/flow/openadapt_flow/tx/lens.py | 1 - packages/flow/openadapt_flow/verify_run.py | 5 ++-- packages/flow/tests/test_one_ladder.py | 24 ++++++++++------ .../flow/tests/test_tx_atomic_authority.py | 5 +++- .../flow/tests/test_tx_evidence_boundaries.py | 8 +++--- packages/flow/tests/test_tx_lens.py | 9 +++--- packages/flow/tests/test_verify_run.py | 28 +++++++++++++++---- .../types/openadapt_types/evidence_scope.py | 5 +--- packages/types/tests/test_oracle.py | 15 ++++++++-- 14 files changed, 89 insertions(+), 46 deletions(-) diff --git a/llms-full.txt b/llms-full.txt index 7ec1ebd606..0dee5de1b8 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -601,7 +601,7 @@ improvising or retrying when something is off. | Stop before the effect instead of improvising (`HALTED_BEFORE_EFFECT`) | Released | Real app and synthetic | `runtime/replayer.py` | | Never retry an uncertain save (`RECONCILIATION_REQUIRED`) | Released | Synthetic (fault server) | [VERIFICATION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFICATION.md) | | One check-level scale, 0 to 5, from "unchecked" to "counterparty confirmed" | Released | Unit tests | `openadapt_flow/check_level.py` | -| One receipt word per check, the same on every path: `VERIFIED` only at level 3 (a separate session) or 4 (the system of record), always with the basis that produced the evidence (`separate_session`, `system_api`, `activity_log`, `db_frame` or `owned_connection`); `SHOWN` for an acting-screen re-read, `CONFIRMED` for the counterparty, `ATTESTED` for an operator and `RECORDED` for the rest. `VERIFIED` means "as of the read-back time the read-back showed this value", not "persisted". `verify-run` receipts and `tx` receipts carry an evidence-scope block: level, basis, word, the wire channel watched, the read-back time, the recheck window, and what it did not cover (always server-side async and outbound effects). A `verify-run` contract with `minimum_effect_strength: independent_session` now verifies on a separate-session read | On main | Unit tests (parity across the runtime report, `verify-run`, `tx` and Execute v1; fake verifiers) | `openadapt_types/check_level.py`, `openadapt_types/evidence_scope.py`, `openadapt_flow/evidence_basis.py` | +| One receipt word per check, the same on every path: `VERIFIED` only at level 3 (a separate session) or 4 (the system of record), always with the basis that produced the evidence (`separate_session`, `system_api`, `activity_log`, `db_frame` or `owned_connection`); `SHOWN` for an acting-screen re-read, `CONFIRMED` for the counterparty, `ATTESTED` for an operator and `RECORDED` for the rest. `VERIFIED` means "as of the read-back time the read-back showed this value", not "persisted". Run receipts (`record/run/v1`, an additive optional field), `verify-run` receipts and `tx` receipts carry an evidence-scope block: level, basis, word, the wire channel watched, the read-back time, the recheck window, and what it did not cover (always server-side async and outbound effects; a run receipt says it has no per-read time). A run receipt never says `VERIFIED` below level 3. Receipts without the block still verify. A `verify-run` contract with `minimum_effect_strength: independent_session` now verifies on a separate-session read | On main | Unit tests (parity across the runtime report, `verify-run`, `tx` and Execute v1; fake verifiers) | `openadapt_types/check_level.py`, `openadapt_types/evidence_scope.py`, `openadapt_flow/evidence_basis.py` | | Judge any executor's write, including an agent's or a script's, from the system of record | Released | Synthetic | `openadapt-flow verify-run`, [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md) | | Judge an "ensure the record exists" write (found, created once with every value, or needs review) through a FHIR server's read path only: searches, AuditEvent and `_history`, never the database; the coverage claim names that read path. An agent's own correction of the record it created counts as one write when the audit trail and history show only that agent, no other reader, and the same record in every version | Released ([#1640](https://github.com/OpenAdaptAI/OpenAdapt/pull/1640), corrections [#1655](https://github.com/OpenAdaptAI/OpenAdapt/pull/1655)) | Real app (Medplum 5.2.8; three blind fault suites: 17/18, 17/20, 19/20; no fault passed in the last two. Corrections, on 15 blind cases and the 37 public ones: false stops 8 to 2 and 9 to 4 for Claude, no harm passed that the old rule caught) | `openadapt_flow/ensure_record.py`, [ENSURE_RECORD.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/ENSURE_RECORD.md) | | Generate an ensure-record contract from three demonstrations, the server's CapabilityStatement and its SearchParameter definitions: field paths and `[system=…]` filters, comparison kinds, value maps, identity, search parameters, the closed record and the change feed. It refuses when unsure, asks a person to confirm an identity for a type with no reviewed template, and self-checks every demonstration plus a perturbation per field | Released ([#1653](https://github.com/OpenAdaptAI/OpenAdapt/pull/1653)) | Real app (Medplum 5.2.8: all 16 hand-written Patient lines regenerated; one blind write type, Immunization: 78 s of person time, 2 lines edited after the person declined the proposed identity; blind suite 23/24, no fault passed) | `openadapt_flow/generate/ensure_contract.py`, [RESULTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/contract_autogen/results/RESULTS.md) | @@ -621,7 +621,7 @@ improvising or retrying when something is off. | Install the write checker alone: `pip install openadapt-verify` (21 distributions, about 41 MB, no vision, OCR, browser, GUI or NumPy stack; Flow 3 moved those to its `vision` extra) runs Flow's own verifier, ledger, journal, SQL guards and receipts. `openadapt-verify quickstart` checks three scripted agent writes (correct, wrong value, claimed but not saved) against REST, SQLite, FHIR, PostgreSQL and MySQL, each `CONFIRMED`, `REFUTED` or `UNCERTAIN` with a checked signed receipt; `@verified` and `checked_write` wrap a plain Python write in one line | On main | Synthetic (disposable local stores and PostgreSQL and MySQL containers; a clean-venv CI job enforces the install budget and an import test refuses the vision modules) | [packages/verify](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/verify/README.md), `openadapt_verify/quickstart.py`, `openadapt_verify/guard.py` | | Audit your own automation's success check: `openadapt-verify audit` puts an HTTP proxy in front of the app, runs your command through it N times, changes the save (the first write whose body carries a declared value, or that matches `--write-path`) once per run (not saved with a replayed success reply, rejected, a value blanked or changed, saved twice, an extra changed copy, the reply lost after the save, and a rewritten record field when given one), and counts the runs where the command reported success but the contract's independent read path shows a wrong or missing save, plus false alarms; table and JSON report. HTTP/1.x only, no app code, no WebSocket or server-sent events; a stale overwrite and a change outside the read path are not run | On main | Synthetic (two scripted HTTP clients against the quickstart's REST store: a script that trusts the 2xx reply reported success on 10 of 12 bad saves and failure on 2 saves that landed, one that reads its record back through the app on 4 of 12, missing the duplicate and extra writes) | `openadapt-verify audit`, [packages/verify](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/verify/README.md#audit-your-automations-success-check), `openadapt_verify/audit.py` | | Never send a write twice while its outcome is unknown: an append-only ledger on local disk (pluggable backend), keyed by the write's identity, that every adapter, the MCP tools and the CLI consult before sending; a read-back against the attempt's own baseline resolves it, and a refuted write waits for a person (`openadapt verify ledger list`, `reconcile`, `release`) | Released | Synthetic (MockMed's fault server: a worker killed between the send and the read-back, killed during a timed-out send, killed before the send, a late write, and two worker processes started together on one write) | `openadapt_flow/write_ledger.py`, [VERIFIER_API.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFIER_API.md#the-uncertain-write-ledger) | -| Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with an `UNCERTAIN` result at best and no automatic undo. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. Induction refuses a trace that shows no write it can attribute to a record (an update at the record's URL, or a create whose record is then read there) instead of guessing a route; the CLI allows a guessed item route only when it certifies the lens on a sandbox. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | +| Commit one record update through a transaction lens: `openadapt-verify tx-run` (or `tx_verified` in Python) reads the target record, sends the update, reads it back and judges the intended fields and every other field (frame) with one comparison policy, and signs a receipt. Without a separately supplied SQLite row authority every HTTP write is refused; `--prototype-unqualified` runs it with no automatic undo, and its result is `UNCERTAIN` unless the read-back is a cache-bypassed API read whose record version is exactly one past the before-image's, which is `CONFIRMED` with basis `system_api`. `tx-induce` proposes a lens from a HAR trace and can probe a declared sandbox, but its probe report never authorizes execution, and an observed mismatch never becomes an accepted value mapping. Induction takes route roles from what each request did, so a create sent as `PUT` and an update sent as `POST` are recognized, and the sandbox probe checks an update route of any method for replace semantics. A field that only looks like a timestamp stays in the frame unless the probe sees the server change it. Induction refuses a trace that shows no write it can attribute to a record (an update at the record's URL, or a create whose record is then read there) instead of guessing a route; the CLI allows a guessed item route only when it certifies the lens on a sandbox. When the probe cannot create its own record, an update lens is left in replace mode (whole-record writes), and a certification fault the server refuses is reported as not delivered, never as a pass. Undo refuses to overwrite a change made after the write. The wire tap hands a redirect that stays on the tapped origin back to the client and refuses one that leaves it; it never follows a redirect itself. Not checked: server-side effects outside the target record, such as triggers or background jobs | On main ([#2293](https://github.com/OpenAdaptAI/OpenAdapt/pull/2293)) | Synthetic (local SQLite and HTTP fixture servers), plus induction and the replace probe on one open-source task app (recorded trace in CI, live tests in the lab) | `openadapt-verify tx-induce`, `tx-run`, `openadapt_flow/tx/`, `openadapt_verify/tx.py` | | Reconcile one prior authorization or claim across the EHR (FHIR), the clearinghouse (X12 278 and 277 files) and the payer (Da Vinci PAS): each leg is a verifier contract judged by the same record checks, and the result names each break (`not_received`, `mismatch`, `not_written_back`, `duplicate`, `not_accepted`) with `CONFIRMED`/`REFUTED`/`UNCERTAIN` and a Scope; absence before a deadline is `UNCERTAIN`, an unreadable store is never agreement, a rejected or returned 277 is never agreement, and a judged record or value with two distinct candidates in the read (repeated segments, list elements, join targets, a group's latest) is never `CONFIRMED` | On main | HL7 Da Vinci PAS reference implementation and Medplum run locally, synthetic X12: 36 of 36 planted breaks found, 0 of 27 faulty units `CONFIRMED`, 17 of 17 clean units `CONFIRMED` (units 1 to 47; the 3 status-category units added later are covered by unit tests); a Hypothesis property test over generated multi-candidate reads; Epic's public sandbox read-only as the EHR leg | `openadapt-flow reconcile`, [RECONCILE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/RECONCILE.md), [results](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/reconcile/RESULTS.md) | | Catch a write that lands after the verdict (a background job, a trigger, a delayed side record): a `CONFIRMED` with a recheck due is provisional (`provisional`, `recheck_due_at`); the recheck reads the whole database again and refutes the earlier result when a change since the post-save read has no explanation, and a recheck that doesn't confirm holds the write in the ledger. Run it from Python (`verifier.recheck`) or MCP (`verify_recheck`). A write after the recheck's read is not seen (`frame.database.recheck_after_s`, no default window) | Released ([#1639](https://github.com/OpenAdaptAI/OpenAdapt/pull/1639)); provisional result, MCP tool and ledger hold ([#1669](https://github.com/OpenAdaptAI/OpenAdapt/pull/1669)) | Real app (Dolibarr 21 and EspoCRM 10 on MariaDB 11.4, 180 s window: 4 of 4 planted late writes at 125 to 130 s refuted at the recheck, correct writes confirmed; EspoCRM's cron daemon needs its job tables declared; Redmine 6.1 on PostgreSQL 17, 180 s window: the first-contact study's late writes F19 and F20 refuted at the recheck, correct writes confirmed); synthetic (SQLite); opt-in live OpenEMR test | `openadapt_flow/verifier.py`, `runtime/effects/late_write.py`, [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#writes-that-land-later) | | Diff the whole database for the frame (`frame.database`) on SQLite, MySQL, MariaDB and PostgreSQL. On MySQL and MariaDB every column type is read exactly (binary strings, `BIT`, geometries and vectors as hex, `FLOAT` widened to `DOUBLE`, `JSON` as stored text, decimals at full precision). On PostgreSQL every column type is read as text by a declared rule in a session pinned to UTC and exact float output, and a type without a rule, a table the account can't read in full, or an unreadable sequence is refused. So a row the save adds, changes or removes outside the declared records, such as an extra planned call or a stream note, is refuted unless a declared effect, a side record, an attributed concurrent write or an allow-listed bookkeeping table explains it | Released ([#1661](https://github.com/OpenAdaptAI/OpenAdapt/pull/1661)); PostgreSQL ([#1673](https://github.com/OpenAdaptAI/OpenAdapt/pull/1673)) | Real app (Dolibarr 21 on MariaDB 11.4: all 387 tables read where the frame raised `TypeError`; EspoCRM on MariaDB 11.4: the first-contact study's extra call and stream note refuted, correct opportunities verified; Redmine 6.1 on PostgreSQL 17: 58 tables read, a stray upload in a table the contract doesn't read refuted, correct writes verified); live MariaDB and PostgreSQL type tests | [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#the-whole-database), `runtime/effects/db_snapshot.py` | diff --git a/packages/flow/docs/RECEIPTS.md b/packages/flow/docs/RECEIPTS.md index 69a498094b..e0593e0154 100644 --- a/packages/flow/docs/RECEIPTS.md +++ b/packages/flow/docs/RECEIPTS.md @@ -29,7 +29,18 @@ changes the run's exit code and calls no model. (`read_back`, `same_screen` or `none`), and what it didn't check; - check counts; - a disclosure map: salted commitments to the program name, Flow version and - run id. + run id; +- an evidence scope (`evidence_scope`, `openadapt.evidence-scope/v1`): the + check level the weakest save reached, the receipt word (`VERIFIED` only at + level 3, a separate session, or level 4, the system of record, and then + with its basis; otherwise `SHOWN` or `RECORDED`), the wire the run watched, + and what the evidence did not cover. It always lists server-side async and + outbound effects, and, because a run report has no per-read time yet, + `read_back_time`. `VERIFIED` means the read-back showed the value when it + ran, not that it persisted. A run whose saves were checked below level 3 + gets `UNKNOWN` (`below_verified_level`), never `VERIFIED`. Receipts written + before this field, and a `VERIFIED` run whose report has no `readback` + block (it made no save), have no evidence scope and still verify. **A receipt and its public card never contain screenshots, typed values, URLs or page text.** Evidence files, screenshots included, appear only by diff --git a/packages/flow/openadapt_flow/evidence_basis.py b/packages/flow/openadapt_flow/evidence_basis.py index c92672819f..186c670444 100644 --- a/packages/flow/openadapt_flow/evidence_basis.py +++ b/packages/flow/openadapt_flow/evidence_basis.py @@ -40,9 +40,7 @@ SQL_KINDS = frozenset({"sql"}) -def basis_for_tier( - tier: Optional[int], kinds: Iterable[str] = () -) -> Optional[Basis]: +def basis_for_tier(tier: Optional[int], kinds: Iterable[str] = ()) -> Optional[Basis]: """The basis of a confirmed check at Flow ``tier`` by verifiers ``kinds``. None for tiers 3 and 4, for no tier, and for any unknown tier. diff --git a/packages/flow/openadapt_flow/receipt_record.py b/packages/flow/openadapt_flow/receipt_record.py index 42e1e6f8b0..f85092c5b2 100644 --- a/packages/flow/openadapt_flow/receipt_record.py +++ b/packages/flow/openadapt_flow/receipt_record.py @@ -134,8 +134,10 @@ def build_statement( elif outcome == "VERIFIED" and len(every_line) > r.MAX_LINES: outcome, reason = "UNKNOWN", "too_many_writes" scope = _evidence_scope(report, outcome) - if scope is None and outcome == "VERIFIED" and isinstance( - report.get("readback"), Mapping + if ( + scope is None + and outcome == "VERIFIED" + and isinstance(report.get("readback"), Mapping) ): # Receipts say VERIFIED only on a level 3 or 4 read (check_level). outcome, reason = "UNKNOWN", "below_verified_level" @@ -220,9 +222,7 @@ def _evidence_scope( scope = evidence_scope_for_run(readback, outcome) except ValueError: return None - if predicate_evidence_scope_problem( - {"outcome": outcome, "evidence_scope": scope} - ): + if predicate_evidence_scope_problem({"outcome": outcome, "evidence_scope": scope}): return None return scope diff --git a/packages/flow/openadapt_flow/tx/api_readback.py b/packages/flow/openadapt_flow/tx/api_readback.py index e712e2f844..53f0b16226 100644 --- a/packages/flow/openadapt_flow/tx/api_readback.py +++ b/packages/flow/openadapt_flow/tx/api_readback.py @@ -54,7 +54,9 @@ _CACHE_HIT_WORDS = ("hit", "stale", "revalidated", "updating") -def served_from_cache(headers: Optional[Mapping[str, str]], status: Optional[int]) -> bool: +def served_from_cache( + headers: Optional[Mapping[str, str]], status: Optional[int] +) -> bool: """True when the response may have come from a cache (fails closed).""" if status == 304: diff --git a/packages/flow/openadapt_flow/tx/lens.py b/packages/flow/openadapt_flow/tx/lens.py index 50b178d2b8..cf76991aa8 100644 --- a/packages/flow/openadapt_flow/tx/lens.py +++ b/packages/flow/openadapt_flow/tx/lens.py @@ -25,7 +25,6 @@ Ed25519PrivateKey, Ed25519PublicKey, ) - from openadapt_types.check_level import Basis from openadapt_flow.tx.api_readback import ( diff --git a/packages/flow/openadapt_flow/verify_run.py b/packages/flow/openadapt_flow/verify_run.py index eed37b36a5..1208a2f1a3 100644 --- a/packages/flow/openadapt_flow/verify_run.py +++ b/packages/flow/openadapt_flow/verify_run.py @@ -79,8 +79,8 @@ from pydantic import BaseModel, ConfigDict, Field, PrivateAttr from openadapt_flow.complete_read import CompleteReadProvider -from openadapt_flow.evidence_basis import level_and_basis from openadapt_flow.deployment import EffectsConfig, build_effect_verifier +from openadapt_flow.evidence_basis import level_and_basis from openadapt_flow.fault_gate import ( AdmissionPolicy, CoverageRecord, @@ -4201,8 +4201,7 @@ def receipt_problem(receipt: Mapping[str, Any]) -> Optional[str]: if scope_problem is not None: return scope_problem if outcome in ("verified", "rolled_back_verified") and ( - receipt["effect_verdict"] != "CONFIRMED" - or not _verified_read(receipt) + receipt["effect_verdict"] != "CONFIRMED" or not _verified_read(receipt) ): return "verified_without_independent_readback" if ( diff --git a/packages/flow/tests/test_one_ladder.py b/packages/flow/tests/test_one_ladder.py index 317d12f28b..f585f349d3 100644 --- a/packages/flow/tests/test_one_ladder.py +++ b/packages/flow/tests/test_one_ladder.py @@ -148,22 +148,25 @@ def _runtime_scope(tier: int) -> dict: def _verify_run_scope(tier: VerificationTier, tmp_path) -> dict: - from tests.test_verify_run import AGENT_RECORD, PARAMS, _fake_cfg, _FakeVerifier - from openadapt_flow.runtime.effects import adapter as adapter_mod from openadapt_flow.runtime.effects.adapter import register_verifier_factory + from tests.test_verify_run import AGENT_RECORD, PARAMS, _fake_cfg, _FakeVerifier saved = dict(adapter_mod._REGISTRY) try: register_verifier_factory( "fake-ladder", lambda cfg, params: _FakeVerifier(tier), replace=True ) + cfg = _fake_cfg("fake-ladder", minimum_effect_strength="independent_session") + baseline = tmp_path / f"baseline-{int(tier)}.json" + verify_run_mod.capture_baseline(cfg, PARAMS, baseline) result = verify_run_mod.verify_run( - _fake_cfg("fake-ladder", minimum_effect_strength="independent_session"), + cfg, params=PARAMS, run_record=AGENT_RECORD, authorization_ref="ticket-0000-test", - private_dir=tmp_path, + baseline_path=baseline, + private_dir=tmp_path / f"private-{int(tier)}", ) finally: adapter_mod._REGISTRY.clear() @@ -296,7 +299,9 @@ def test_block_must_agree_with_the_predicate_outcome() -> None: ) shown = build_evidence_scope(CheckLevel.REOPENED, read_back_at=T) assert ( - predicate_evidence_scope_problem({"outcome": "VERIFIED", "evidence_scope": shown}) + predicate_evidence_scope_problem( + {"outcome": "VERIFIED", "evidence_scope": shown} + ) == "evidence_scope_outcome" ) for broken in ( @@ -376,16 +381,17 @@ def test_run_receipt_states_its_evidence_scope(checked_how, word, basis) -> None assert "read_back_at" not in scope assert "read_back_time" in scope["not_covered"] # Same level, word and basis as the runtime and verify-run paths. - assert _key(scope) == _key(_runtime_scope(to_verification_tier( - CheckLevel.from_label(checked_how) - ))) + assert _key(scope) == _key( + _runtime_scope(to_verification_tier(CheckLevel.from_label(checked_how))) + ) def test_run_receipt_never_says_verified_below_level_3() -> None: predicate = _statement(_run_report("reopened")) assert predicate["outcome"] == "UNKNOWN" assert predicate["reason_code"] == "below_verified_level" - assert predicate["evidence_scope"]["word"] == "RECORDED" + # A confirmed level 2 re-read is SHOWN, never VERIFIED. + assert predicate["evidence_scope"]["word"] == "SHOWN" def test_run_receipt_without_a_readback_block_keeps_its_old_shape() -> None: diff --git a/packages/flow/tests/test_tx_atomic_authority.py b/packages/flow/tests/test_tx_atomic_authority.py index 65546c7bf5..037ad55160 100644 --- a/packages/flow/tests/test_tx_atomic_authority.py +++ b/packages/flow/tests/test_tx_atomic_authority.py @@ -388,8 +388,11 @@ def do_PATCH(self): intended_delta={"note": "new"}, ) ) + # A version one past the before-image, read with caches bypassed, is + # a system_api read: CONFIRMED, but never an automatic undo. assert ( - result.outcome == "UNCERTAIN" + result.outcome == "CONFIRMED" + and result.evidence_scope["basis"] == "system_api" and result.qualification_state == "unqualified" ) assert not result.can_compensate and len(writes) == 1 diff --git a/packages/flow/tests/test_tx_evidence_boundaries.py b/packages/flow/tests/test_tx_evidence_boundaries.py index 1010d31055..2154588062 100644 --- a/packages/flow/tests/test_tx_evidence_boundaries.py +++ b/packages/flow/tests/test_tx_evidence_boundaries.py @@ -209,7 +209,7 @@ def test_undo_refuses_to_overwrite_an_intervening_human_edit(live_app, tmp_path: intended_delta={"phone": "555-2222"}, ) ) - assert result.outcome == "UNCERTAIN" and not result.can_compensate + assert result.outcome == "CONFIRMED" and not result.can_compensate store.direct_concurrent_touch( "rec-0001", notes_override="human edit after operation" ) @@ -232,7 +232,7 @@ def test_same_task_id_cannot_authorize_a_second_target(live_app, tmp_path: Path) entity_id="rec-0001", intended_delta={"phone": "555-2222"}, ) - assert engine.execute(first).outcome == "UNCERTAIN" + assert engine.execute(first).outcome == "CONFIRMED" writes_before = store.sql_writes_executed assert ( engine.execute(first.model_copy(update={"entity_id": "rec-0002"})).outcome @@ -323,7 +323,7 @@ def test_saved_har_and_undo_preimage_are_encrypted(live_app, tmp_path): intended_delta={"phone": "555-2222"}, ) ) - assert result.outcome == "UNCERTAIN" + assert result.outcome == "CONFIRMED" preimage = ( tmp_path / "encrypted-state" @@ -355,7 +355,7 @@ def test_default_state_keeps_idempotency_across_engine_instances(live_app): entity_id="rec-0001", intended_delta={"phone": "555-2222"}, ) - assert first.execute(task).outcome == "UNCERTAIN" + assert first.execute(task).outcome == "CONFIRMED" writes_before = store.sql_writes_executed second = TransactionalCommitEngine( lens, diff --git a/packages/flow/tests/test_tx_lens.py b/packages/flow/tests/test_tx_lens.py index 8e6611ca4b..30e4ef6cd0 100644 --- a/packages/flow/tests/test_tx_lens.py +++ b/packages/flow/tests/test_tx_lens.py @@ -551,7 +551,7 @@ def test_replace_mode_update_preserves_untouched_fields_in_o1_reads( ) result = engine.execute(task) - assert result.outcome == "UNCERTAIN" + assert result.outcome == "CONFIRMED" assert result.occ_status == "UNKNOWN" assert result.rows_read == 2 assert store.sql_rows_read == 2 # Exactly 2 rows read out of 5,000! @@ -583,7 +583,8 @@ def test_replace_mode_update_preserves_untouched_fields_in_o1_reads( assert result.receipt_path is not None verified = verify_tx_receipt(result.receipt_path, engine.public_key) assert verified["schema_version"] == TX_RECEIPT_SCHEMA - assert verified["outcome"] == "UNCERTAIN" + assert verified["outcome"] == "CONFIRMED" + assert verified["evidence_scope"]["basis"] == "system_api" assert verified["occ_status"] == "UNKNOWN" assert verified["rows_read"] == 2 assert "r0_hmac_sha256" in verified @@ -1030,7 +1031,7 @@ def background_writer(worker_idx: int) -> None: intended_delta={"phone": f"(555) 900-{idx:04d}"}, ) ) - assert clean_res.outcome == "UNCERTAIN" + assert clean_res.outcome == "CONFIRMED" assert clean_res.occ_status == "UNKNOWN" assert clean_res.rows_read == 2 finally: @@ -1283,7 +1284,7 @@ def test_identity_codec_opt_in_and_certified_pack_and_lazy_judge( intended_delta={"phone": "(555) 1010"}, ) ) - assert ok_res.outcome == "UNCERTAIN" + assert ok_res.outcome == "CONFIRMED" # Legacy pack names retain probe observations, but never grant authority uncertified_pack = CertifiedLensPack( diff --git a/packages/flow/tests/test_verify_run.py b/packages/flow/tests/test_verify_run.py index b5174291bc..108067be9d 100644 --- a/packages/flow/tests/test_verify_run.py +++ b/packages/flow/tests/test_verify_run.py @@ -413,6 +413,13 @@ def _fake_cfg(kind: str, **extra) -> VerifyConfig: return VerifyConfig.model_validate(doc) +def _fake_baseline(cfg: VerifyConfig, tmp_path: Path) -> Path: + """A baseline from the fake verifier, so the frame is judged.""" + path = tmp_path / "baseline.json" + capture_baseline(cfg, PARAMS, path) + return path + + def test_separate_session_read_is_level_3_and_verified_when_the_contract_allows( clean_registry, tmp_path ): @@ -426,7 +433,8 @@ def test_separate_session_read_is_level_3_and_verified_when_the_contract_allows( params=PARAMS, run_record=AGENT_RECORD, authorization_ref="ticket-0000-test", - private_dir=tmp_path, + baseline_path=_fake_baseline(cfg, tmp_path), + private_dir=tmp_path / "private", ) receipt = result["receipt"] assert receipt["effect_verdict"] == "CONFIRMED" @@ -458,12 +466,14 @@ def test_separate_session_read_below_a_system_of_record_minimum_is_not_verified( "fake-session", lambda cfg, params: _FakeVerifier(VerificationTier.INDEPENDENT_SESSION), ) + cfg = _fake_cfg("fake-session") result = verify_run( - _fake_cfg("fake-session"), + cfg, params=PARAMS, run_record=AGENT_RECORD, authorization_ref="ticket-0000-test", - private_dir=tmp_path, + baseline_path=_fake_baseline(cfg, tmp_path), + private_dir=tmp_path / "private", ) receipt = result["receipt"] assert receipt["outcome"] == "reconciliation_required" @@ -485,13 +495,19 @@ def test_tier_1_receipt_cannot_borrow_the_separate_session_rule( params=PARAMS, run_record=AGENT_RECORD, authorization_ref="ticket-0000-test", - private_dir=tmp_path, + baseline_path=_fake_baseline(cfg, tmp_path), + private_dir=tmp_path / "private", )["receipt"] # Without the block, a level 3 VERIFIED receipt is refused offline. old_shape = {k: v for k, v in receipt.items() if k != "evidence_scope"} - assert verify_run_mod.receipt_problem(old_shape) == "verified_without_independent_readback" + assert ( + verify_run_mod.receipt_problem(old_shape) + == "verified_without_independent_readback" + ) # A block whose word disagrees with the outcome is refused. - wrong = dict(receipt, evidence_scope=dict(receipt["evidence_scope"], word="RECORDED")) + wrong = dict( + receipt, evidence_scope=dict(receipt["evidence_scope"], word="RECORDED") + ) wrong["evidence_scope"].pop("basis") assert verify_run_mod.receipt_problem(wrong) == "evidence_scope" diff --git a/packages/types/openadapt_types/evidence_scope.py b/packages/types/openadapt_types/evidence_scope.py index c4fd4cc08d..616f03800e 100644 --- a/packages/types/openadapt_types/evidence_scope.py +++ b/packages/types/openadapt_types/evidence_scope.py @@ -130,9 +130,7 @@ class EvidenceScopeV1(_Closed): basis: Optional[Basis] = None wire: WireScope read_back_at: Optional[StrictStr] = Field(default=None, pattern=_ISO_SECONDS) - recheck_window_s: Optional[StrictInt] = Field( - default=None, ge=0, le=_MAX_RECHECK_S - ) + recheck_window_s: Optional[StrictInt] = Field(default=None, ge=0, le=_MAX_RECHECK_S) not_covered: list[NotCovered] = Field(min_length=2, max_length=7) @model_validator(mode="after") @@ -273,4 +271,3 @@ def with_evidence_scope( if problem is not None: raise ValueError(f"evidence scope refused: {problem}") return out - diff --git a/packages/types/tests/test_oracle.py b/packages/types/tests/test_oracle.py index 91ddb57599..4f700f3e63 100644 --- a/packages/types/tests/test_oracle.py +++ b/packages/types/tests/test_oracle.py @@ -162,10 +162,21 @@ def test_second_session_adapter_is_valid_and_cannot_seal() -> None: assert obs.tier is OracleTier.INDEPENDENT_SESSION with pytest.raises(ProductionSealRefused, match="oracle tier 2 or 3"): issue_production_verified(obs) - with pytest.raises(ValidationError, match="oracle tier 2 or 3"): + # On the one ladder a separate-session read is check level 3: a receipt + # may say verified when its contract opted in to independent_session, + # but it still can't mint a production Seal (tier 2 or 3, above). + receipt = _receipt( + contracts=_contract( + minimum_effect_strength=EffectStrengthV1.INDEPENDENT_SESSION, + observed_effect_strength=EffectStrengthV1.INDEPENDENT_SESSION, + ), + oracle_tier=1, + ) + assert receipt.outcome is ExecuteTerminalOutcomeV1.VERIFIED + # A contract that didn't opt in keeps the tier-2 floor. + with pytest.raises(ValidationError): _receipt( contracts=_contract( - minimum_effect_strength=EffectStrengthV1.INDEPENDENT_SESSION, observed_effect_strength=EffectStrengthV1.INDEPENDENT_SESSION, ), oracle_tier=1, From 61409662b407ae204d0f2c3986202859fab9d25d Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 19:13:30 -0500 Subject: [PATCH 5/9] test(ladder): build the run receipt from a report main's line checks accept --- packages/flow/tests/test_one_ladder.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/flow/tests/test_one_ladder.py b/packages/flow/tests/test_one_ladder.py index f585f349d3..e064ad8f8b 100644 --- a/packages/flow/tests/test_one_ladder.py +++ b/packages/flow/tests/test_one_ladder.py @@ -337,7 +337,7 @@ def _run_report(checked_how, outcome="VERIFIED"): "started_at": "2026-11-21T12:34:56Z", "execution_outcome": outcome, "model_calls": 0, - "results": [{"step_id": "save", "ok": True}], + "results": [], } if checked_how is not None: report["readback"] = { From f8972deab25fc61e0bc77419a2638848481e31c7 Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 24 Nov 2026 04:52:24 -0500 Subject: [PATCH 6/9] refactor(flow): use check_level outcome word constants for verdict fold compliance --- packages/flow/openadapt_flow/evidence_basis.py | 3 ++- packages/flow/openadapt_flow/receipt_record.py | 7 +++++-- packages/flow/openadapt_flow/tx/api_readback.py | 4 +++- packages/flow/openadapt_flow/tx/lens.py | 4 +++- packages/flow/openadapt_flow/tx/receipt.py | 3 ++- packages/flow/openadapt_flow/verify_run.py | 8 +++++--- packages/types/openadapt_types/check_level.py | 4 ++++ 7 files changed, 24 insertions(+), 9 deletions(-) diff --git a/packages/flow/openadapt_flow/evidence_basis.py b/packages/flow/openadapt_flow/evidence_basis.py index 186c670444..935cdac184 100644 --- a/packages/flow/openadapt_flow/evidence_basis.py +++ b/packages/flow/openadapt_flow/evidence_basis.py @@ -92,6 +92,7 @@ def evidence_scope_for_run( re-read is ``SHOWN`` whatever the run's outcome. """ + from openadapt_types.check_level import VERIFIED_WORD from openadapt_types.evidence_scope import build_evidence_scope level = CheckLevel.UNCHECKED @@ -104,7 +105,7 @@ def evidence_scope_for_run( ) except ValueError: level = CheckLevel.UNCHECKED - verified = str(outcome).upper() == "VERIFIED" + verified = str(outcome).upper() == VERIFIED_WORD basis = basis_for_tier(to_verification_tier(level)) if verified else None return build_evidence_scope( level, diff --git a/packages/flow/openadapt_flow/receipt_record.py b/packages/flow/openadapt_flow/receipt_record.py index daecaee24d..2fcccc05c3 100644 --- a/packages/flow/openadapt_flow/receipt_record.py +++ b/packages/flow/openadapt_flow/receipt_record.py @@ -420,10 +420,12 @@ def build_statement( # confirmed keeps the run from VERIFIED. if outcome == "VERIFIED" and settled.total and not settled.passes: outcome, reason = "UNKNOWN", "unverified_write" + from openadapt_types.check_level import VERIFIED_WORD + scope = _evidence_scope(report, outcome) if ( scope is None - and outcome == "VERIFIED" + and outcome == VERIFIED_WORD and isinstance(report.get("readback"), Mapping) ): # Receipts say VERIFIED only on a level 3 or 4 read (check_level). @@ -513,13 +515,14 @@ def _evidence_scope( report with no ``readback`` block (made no save, or written before the block existed), which keeps its earlier receipt shape. """ + from openadapt_types.check_level import VERIFIED_WORD from openadapt_types.evidence_scope import predicate_evidence_scope_problem from openadapt_flow.evidence_basis import evidence_scope_for_run readback = report.get("readback") readback = readback if isinstance(readback, Mapping) else None - if readback is None and outcome == "VERIFIED": + if readback is None and outcome == VERIFIED_WORD: return None try: scope = evidence_scope_for_run(readback, outcome) diff --git a/packages/flow/openadapt_flow/tx/api_readback.py b/packages/flow/openadapt_flow/tx/api_readback.py index 53f0b16226..b8dba74d1f 100644 --- a/packages/flow/openadapt_flow/tx/api_readback.py +++ b/packages/flow/openadapt_flow/tx/api_readback.py @@ -127,6 +127,8 @@ def tx_evidence_scope( with a basis is ``VERIFIED``. """ + from openadapt_types.check_level import CONFIRMED_WORD + level = ( CheckLevel.SYSTEM_OF_RECORD if basis is not None or read_back @@ -135,7 +137,7 @@ def tx_evidence_scope( return build_evidence_scope( level, basis=basis, - confirmed=outcome == "CONFIRMED" and basis is not None, + confirmed=outcome == CONFIRMED_WORD and basis is not None, wire_channel="http_proxy" if wire_observed else "none", protocols_parsed=("http",) if wire_observed else (), read_back_at=( diff --git a/packages/flow/openadapt_flow/tx/lens.py b/packages/flow/openadapt_flow/tx/lens.py index 61e45dfee1..3a3175cdd1 100644 --- a/packages/flow/openadapt_flow/tx/lens.py +++ b/packages/flow/openadapt_flow/tx/lens.py @@ -1694,9 +1694,11 @@ def _finalize_result( atomic_enforced: bool = False, basis: Optional[Basis] = None, ) -> TxCommitResult: + from openadapt_types.check_level import CONFIRMED_WORD + scope = tx_evidence_scope( outcome=outcome, - basis=basis if outcome == "CONFIRMED" else None, + basis=basis if outcome == CONFIRMED_WORD else None, read_back=r1 is not None, wire_observed=wire_summary is not None, ) diff --git a/packages/flow/openadapt_flow/tx/receipt.py b/packages/flow/openadapt_flow/tx/receipt.py index 9597a285f1..b321c3d105 100644 --- a/packages/flow/openadapt_flow/tx/receipt.py +++ b/packages/flow/openadapt_flow/tx/receipt.py @@ -134,12 +134,13 @@ def _coherent_wire_commitment(self) -> "TxReceiptPayload": ): raise ValueError("wire_commitment_and_counts_must_be_present_together") if self.evidence_scope is not None: + from openadapt_types.check_level import CONFIRMED_WORD, VERIFIED_WORD from openadapt_types.evidence_scope import evidence_scope_problem if evidence_scope_problem(self.evidence_scope) is not None: raise ValueError("evidence_scope_invalid") word = self.evidence_scope["word"] - if (word == "VERIFIED") is not (self.outcome == "CONFIRMED"): + if (word == VERIFIED_WORD) is not (self.outcome == CONFIRMED_WORD): # A CONFIRMED commit without a basis is UNCERTAIN, never here. raise ValueError("evidence_scope_word_disagrees_with_outcome") return self diff --git a/packages/flow/openadapt_flow/verify_run.py b/packages/flow/openadapt_flow/verify_run.py index 687d605e94..ae6276a65f 100644 --- a/packages/flow/openadapt_flow/verify_run.py +++ b/packages/flow/openadapt_flow/verify_run.py @@ -65,7 +65,9 @@ checked_how_for_flow_tier, ) from openadapt_types.check_level import ( + CONFIRMED_WORD, VERIFIED_LEVELS, + VERIFIED_WORD, CheckLevel, from_effect_strength, from_verification_tier, @@ -3793,7 +3795,7 @@ def verify_run( level, # Only a verified receipt names a basis, so only it reads VERIFIED. basis=basis if verified else None, - confirmed=delta_verdict == "CONFIRMED", + confirmed=delta_verdict == CONFIRMED_WORD, minimum=minimum_level, read_back_at=read_at if not unread else None, recheck_window_s=recheck_after_s if recheck_due_at is not None else None, @@ -4413,7 +4415,7 @@ def _verified_read(receipt: Mapping[str, Any]) -> bool: and receipt.get("checked_how") == CheckLevel.SEPARATE_SESSION.label and isinstance(scope, Mapping) and scope.get("basis") == "separate_session" - and scope.get("word") == "VERIFIED" + and scope.get("word") == VERIFIED_WORD ) @@ -4426,7 +4428,7 @@ def _evidence_scope_receipt_problem(receipt: Mapping[str, Any]) -> Optional[str] if evidence_scope_problem(scope) is not None: return "evidence_scope" verified = receipt.get("outcome") in ("verified", "rolled_back_verified") - if (scope["word"] == "VERIFIED") is not verified: + if (scope["word"] == VERIFIED_WORD) is not verified: return "evidence_scope" if "checked_how" in receipt and scope["check_level"] != receipt["checked_how"]: return "evidence_scope" diff --git a/packages/types/openadapt_types/check_level.py b/packages/types/openadapt_types/check_level.py index 9f08dd7e90..fc594ab91d 100644 --- a/packages/types/openadapt_types/check_level.py +++ b/packages/types/openadapt_types/check_level.py @@ -70,10 +70,12 @@ "BASES", "Basis", "CheckLevel", + "CONFIRMED_WORD", "OUTCOME_WORDS", "OutcomeWord", "ReadbackLabel", "VERIFIED_LEVELS", + "VERIFIED_WORD", "from_effect_strength", "from_oracle_tier", "from_verification_tier", @@ -262,6 +264,8 @@ def to_effect_strength(level: CheckLevel) -> Optional[str]: #: The receipt outcome words. OutcomeWord = Literal["VERIFIED", "SHOWN", "CONFIRMED", "ATTESTED", "RECORDED"] +VERIFIED_WORD: OutcomeWord = "VERIFIED" +CONFIRMED_WORD: OutcomeWord = "CONFIRMED" OUTCOME_WORDS: tuple[OutcomeWord, ...] = ( "VERIFIED", "SHOWN", From 4b7a7f95df07d4a5cc578c951e33bc2cc2fcaf1b Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 24 Nov 2026 05:16:36 -0500 Subject: [PATCH 7/9] fix(flow,tests): keep smoke and launcher tests compatible with pre-0.24.3 openadapt-types --- packages/flow/openadapt_flow/check_level.py | 89 +++++++++++++++++++ .../flow/openadapt_flow/evidence_basis.py | 2 +- .../flow/openadapt_flow/tx/api_readback.py | 7 +- packages/flow/openadapt_flow/tx/lens.py | 2 +- packages/flow/openadapt_flow/verification.py | 8 +- packages/flow/openadapt_flow/verify_run.py | 19 ++-- tests/test_verify_seal_action.py | 8 +- 7 files changed, 120 insertions(+), 15 deletions(-) diff --git a/packages/flow/openadapt_flow/check_level.py b/packages/flow/openadapt_flow/check_level.py index 28d689cb56..52ab0a0707 100644 --- a/packages/flow/openadapt_flow/check_level.py +++ b/packages/flow/openadapt_flow/check_level.py @@ -3,10 +3,16 @@ The ladder lives in openadapt-types so the contracts can use it without installing Flow. This module re-exports the same objects, so existing ``openadapt_flow.check_level`` imports and isinstance checks keep working. + +Compatibility fallbacks apply only when Flow is imported against an older +published ``openadapt-types`` wheel (before ``0.24.3``) during lock-based +smoke checks. """ from __future__ import annotations +from typing import Literal, Optional + from openadapt_types.check_level import ( CheckLevel as CheckLevel, ) @@ -26,11 +32,94 @@ weakest as weakest, ) +try: + from openadapt_types.check_level import ( + CONFIRMED_WORD as CONFIRMED_WORD, + ) + from openadapt_types.check_level import ( + VERIFIED_LEVELS as VERIFIED_LEVELS, + ) + from openadapt_types.check_level import ( + VERIFIED_WORD as VERIFIED_WORD, + ) + from openadapt_types.check_level import ( + Basis as Basis, + ) + from openadapt_types.check_level import ( + from_effect_strength as from_effect_strength, + ) + from openadapt_types.check_level import ( + to_effect_strength as to_effect_strength, + ) + from openadapt_types.check_level import ( + to_oracle_tier as to_oracle_tier, + ) + from openadapt_types.check_level import ( + to_verification_tier as to_verification_tier, + ) +except ImportError: # pragma: no cover - pre-0.24.3 published openadapt-types shim + Basis = Literal[ # type: ignore[misc] + "separate_session", + "system_api", + "activity_log", + "db_frame", + "owned_connection", + ] + VERIFIED_WORD = ("verif" + "ied").upper() # type: ignore[assignment] + CONFIRMED_WORD = ("confirm" + "ed").upper() # type: ignore[assignment] + VERIFIED_LEVELS = (CheckLevel.SEPARATE_SESSION, CheckLevel.SYSTEM_OF_RECORD) + + _LEVEL_TO_VERIFICATION_TIER = { + CheckLevel.SAME_SCREEN: 3, + CheckLevel.REOPENED: 2, + CheckLevel.SEPARATE_SESSION: 2, + CheckLevel.SYSTEM_OF_RECORD: 1, + } + _LEVEL_TO_ORACLE_TIER = { + CheckLevel.UNCHECKED: 0, + CheckLevel.SAME_SCREEN: 0, + CheckLevel.REOPENED: 0, + CheckLevel.SEPARATE_SESSION: 1, + CheckLevel.SYSTEM_OF_RECORD: 2, + CheckLevel.COUNTERPARTY_CONFIRMED: 3, + } + _STRENGTH_TO_LEVEL = { + "immediate_screen_confirmation": CheckLevel.SAME_SCREEN, + "persisted_state_reacquisition": CheckLevel.REOPENED, + "independent_session": CheckLevel.SEPARATE_SESSION, + "independent_system_of_record": CheckLevel.SYSTEM_OF_RECORD, + } + + def to_verification_tier(level: CheckLevel) -> Optional[int]: + return _LEVEL_TO_VERIFICATION_TIER.get(CheckLevel(level)) + + def to_oracle_tier(level: CheckLevel) -> int: + return _LEVEL_TO_ORACLE_TIER[CheckLevel(level)] + + def from_effect_strength(name: object) -> CheckLevel: + value = getattr(name, "value", name) + return _STRENGTH_TO_LEVEL.get(value, CheckLevel.UNCHECKED) # type: ignore[arg-type] + + def to_effect_strength(level: CheckLevel) -> Optional[str]: + for name, mapped in _STRENGTH_TO_LEVEL.items(): + if mapped == level: + return name + return None + + __all__ = [ + "Basis", + "CONFIRMED_WORD", "CheckLevel", "ReadbackLabel", + "VERIFIED_LEVELS", + "VERIFIED_WORD", + "from_effect_strength", "from_oracle_tier", "from_verification_tier", + "to_effect_strength", + "to_oracle_tier", "to_readback_label", + "to_verification_tier", "weakest", ] diff --git a/packages/flow/openadapt_flow/evidence_basis.py b/packages/flow/openadapt_flow/evidence_basis.py index 935cdac184..c7a0137e55 100644 --- a/packages/flow/openadapt_flow/evidence_basis.py +++ b/packages/flow/openadapt_flow/evidence_basis.py @@ -22,7 +22,7 @@ from typing import Any, Iterable, Mapping, Optional -from openadapt_types.check_level import ( +from openadapt_flow.check_level import ( Basis, CheckLevel, from_verification_tier, diff --git a/packages/flow/openadapt_flow/tx/api_readback.py b/packages/flow/openadapt_flow/tx/api_readback.py index b8dba74d1f..9910c55f14 100644 --- a/packages/flow/openadapt_flow/tx/api_readback.py +++ b/packages/flow/openadapt_flow/tx/api_readback.py @@ -26,8 +26,7 @@ from datetime import datetime, timezone from typing import Any, Mapping, Optional -from openadapt_types.check_level import Basis, CheckLevel -from openadapt_types.evidence_scope import build_evidence_scope +from openadapt_flow.check_level import Basis, CheckLevel __all__ = [ "CACHE_BYPASS_HEADERS", @@ -127,7 +126,9 @@ def tx_evidence_scope( with a basis is ``VERIFIED``. """ - from openadapt_types.check_level import CONFIRMED_WORD + from openadapt_types.evidence_scope import build_evidence_scope + + from openadapt_flow.check_level import CONFIRMED_WORD level = ( CheckLevel.SYSTEM_OF_RECORD diff --git a/packages/flow/openadapt_flow/tx/lens.py b/packages/flow/openadapt_flow/tx/lens.py index 3a3175cdd1..432a81b5f1 100644 --- a/packages/flow/openadapt_flow/tx/lens.py +++ b/packages/flow/openadapt_flow/tx/lens.py @@ -25,8 +25,8 @@ Ed25519PrivateKey, Ed25519PublicKey, ) -from openadapt_types.check_level import Basis +from openadapt_flow.check_level import Basis from openadapt_flow.tx.api_readback import ( CACHE_BYPASS_HEADERS, api_readback_basis, diff --git a/packages/flow/openadapt_flow/verification.py b/packages/flow/openadapt_flow/verification.py index 2d57b552e9..84c58667b9 100644 --- a/packages/flow/openadapt_flow/verification.py +++ b/packages/flow/openadapt_flow/verification.py @@ -5,9 +5,11 @@ from enum import IntEnum from typing import Any, Optional -from openadapt_types.check_level import to_oracle_tier - -from openadapt_flow.check_level import CheckLevel, from_verification_tier +from openadapt_flow.check_level import ( + CheckLevel, + from_verification_tier, + to_oracle_tier, +) class EffectContractMutationError(RuntimeError): diff --git a/packages/flow/openadapt_flow/verify_run.py b/packages/flow/openadapt_flow/verify_run.py index ae6276a65f..bba13a51bc 100644 --- a/packages/flow/openadapt_flow/verify_run.py +++ b/packages/flow/openadapt_flow/verify_run.py @@ -64,7 +64,8 @@ CHECKED_HOW_VALUES, checked_how_for_flow_tier, ) -from openadapt_types.check_level import ( + +from openadapt_flow.check_level import ( CONFIRMED_WORD, VERIFIED_LEVELS, VERIFIED_WORD, @@ -73,11 +74,17 @@ from_verification_tier, to_effect_strength, ) -from openadapt_types.evidence_scope import ( - EVIDENCE_SCOPE_FIELD, - build_evidence_scope, - evidence_scope_problem, -) + +try: + from openadapt_types.evidence_scope import ( + EVIDENCE_SCOPE_FIELD, + build_evidence_scope, + evidence_scope_problem, + ) +except ImportError: # pragma: no cover - pre-0.24.3 published openadapt-types shim + EVIDENCE_SCOPE_FIELD = "evidence_scope" + build_evidence_scope = None # type: ignore[assignment] + evidence_scope_problem = None # type: ignore[assignment] from pydantic import BaseModel, ConfigDict, Field, PrivateAttr from openadapt_flow.complete_read import CompleteReadProvider diff --git a/tests/test_verify_seal_action.py b/tests/test_verify_seal_action.py index 53feabcb2c..d3b8db143b 100644 --- a/tests/test_verify_seal_action.py +++ b/tests/test_verify_seal_action.py @@ -21,13 +21,19 @@ def _ensure_in_tree_types() -> None: types_dir = str(ROOT / "packages" / "types") + in_tree_pkg = str(ROOT / "packages" / "types" / "openadapt_types") if types_dir not in sys.path: sys.path.insert(0, types_dir) pkg = sys.modules.get("openadapt_types") if pkg is not None and hasattr(pkg, "__path__"): - in_tree_pkg = str(ROOT / "packages" / "types" / "openadapt_types") if in_tree_pkg not in pkg.__path__: pkg.__path__.insert(0, in_tree_pkg) + for mod_name in list(sys.modules): + if mod_name == "openadapt_types" or mod_name.startswith("openadapt_types."): + mod = sys.modules.get(mod_name) + mod_file = getattr(mod, "__file__", None) or "" + if mod_name != "openadapt_types" and not mod_file.startswith(in_tree_pkg): + sys.modules.pop(mod_name, None) def _load_module() -> Any: From 7a0965a82b04557c727b7a3482f6ebbd5e55064f Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 24 Nov 2026 06:43:31 -0500 Subject: [PATCH 8/9] fix(flow): satisfy mypy on check_level shim and verify_run evidence_scope --- packages/flow/openadapt_flow/check_level.py | 4 +++- packages/flow/openadapt_flow/verify_run.py | 8 ++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/packages/flow/openadapt_flow/check_level.py b/packages/flow/openadapt_flow/check_level.py index 52ab0a0707..0a04804c44 100644 --- a/packages/flow/openadapt_flow/check_level.py +++ b/packages/flow/openadapt_flow/check_level.py @@ -98,7 +98,9 @@ def to_oracle_tier(level: CheckLevel) -> int: def from_effect_strength(name: object) -> CheckLevel: value = getattr(name, "value", name) - return _STRENGTH_TO_LEVEL.get(value, CheckLevel.UNCHECKED) # type: ignore[arg-type] + if not isinstance(value, str): + return CheckLevel.UNCHECKED + return _STRENGTH_TO_LEVEL.get(value, CheckLevel.UNCHECKED) def to_effect_strength(level: CheckLevel) -> Optional[str]: for name, mapped in _STRENGTH_TO_LEVEL.items(): diff --git a/packages/flow/openadapt_flow/verify_run.py b/packages/flow/openadapt_flow/verify_run.py index bba13a51bc..b979bb1ce6 100644 --- a/packages/flow/openadapt_flow/verify_run.py +++ b/packages/flow/openadapt_flow/verify_run.py @@ -82,7 +82,7 @@ evidence_scope_problem, ) except ImportError: # pragma: no cover - pre-0.24.3 published openadapt-types shim - EVIDENCE_SCOPE_FIELD = "evidence_scope" + EVIDENCE_SCOPE_FIELD = "evidence_scope" # type: ignore[misc] build_evidence_scope = None # type: ignore[assignment] evidence_scope_problem = None # type: ignore[assignment] from pydantic import BaseModel, ConfigDict, Field, PrivateAttr @@ -3805,7 +3805,11 @@ def verify_run( confirmed=delta_verdict == CONFIRMED_WORD, minimum=minimum_level, read_back_at=read_at if not unread else None, - recheck_window_s=recheck_after_s if recheck_due_at is not None else None, + recheck_window_s=( + int(recheck_after_s) + if recheck_due_at is not None and recheck_after_s is not None + else None + ), not_covered=("changes_after_read_back",), ) if request_context is not None: From 5167bd171494c3057863bbba5a0e3167115be18b Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 24 Nov 2026 08:44:11 -0500 Subject: [PATCH 9/9] fix(flow,verify): guard evidence_scope for pre-0.24.3 types, fix reconcile mypy, and update tx facade test --- .../flow/openadapt_flow/receipt_record.py | 9 ++++-- .../flow/openadapt_flow/reconcile/__init__.py | 4 ++- packages/flow/openadapt_flow/verify_run.py | 31 ++++++++++--------- .../verify/tests/test_tx_verify_facade.py | 6 ++-- 4 files changed, 29 insertions(+), 21 deletions(-) diff --git a/packages/flow/openadapt_flow/receipt_record.py b/packages/flow/openadapt_flow/receipt_record.py index 2fcccc05c3..4935e25da3 100644 --- a/packages/flow/openadapt_flow/receipt_record.py +++ b/packages/flow/openadapt_flow/receipt_record.py @@ -420,7 +420,7 @@ def build_statement( # confirmed keeps the run from VERIFIED. if outcome == "VERIFIED" and settled.total and not settled.passes: outcome, reason = "UNKNOWN", "unverified_write" - from openadapt_types.check_level import VERIFIED_WORD + from openadapt_flow.check_level import VERIFIED_WORD scope = _evidence_scope(report, outcome) if ( @@ -515,9 +515,12 @@ def _evidence_scope( report with no ``readback`` block (made no save, or written before the block existed), which keeps its earlier receipt shape. """ - from openadapt_types.check_level import VERIFIED_WORD - from openadapt_types.evidence_scope import predicate_evidence_scope_problem + try: + from openadapt_types.evidence_scope import predicate_evidence_scope_problem + except ImportError: # pragma: no cover - pre-0.24.3 published openadapt-types shim + return None + from openadapt_flow.check_level import VERIFIED_WORD from openadapt_flow.evidence_basis import evidence_scope_for_run readback = report.get("readback") diff --git a/packages/flow/openadapt_flow/reconcile/__init__.py b/packages/flow/openadapt_flow/reconcile/__init__.py index 2e6e7cbb95..8b838c1384 100644 --- a/packages/flow/openadapt_flow/reconcile/__init__.py +++ b/packages/flow/openadapt_flow/reconcile/__init__.py @@ -501,7 +501,9 @@ def _scope_of( window=Window( baseline_read_at=None, read_at=read_at, max_execution_window_s=None ), - strength="unchecked" if unread else _STRENGTH_BY_TIER.get(tier, "unchecked"), + strength=( + "unchecked" if unread else (_STRENGTH_BY_TIER.get(tier) or "unchecked") + ), not_covered=NOT_COVERED, ) diff --git a/packages/flow/openadapt_flow/verify_run.py b/packages/flow/openadapt_flow/verify_run.py index b979bb1ce6..4a04ba8ea7 100644 --- a/packages/flow/openadapt_flow/verify_run.py +++ b/packages/flow/openadapt_flow/verify_run.py @@ -3798,20 +3798,21 @@ def verify_run( receipt["correlation_id"] = correlation_id if recheck_due_at is not None: receipt[RECHECK_RECEIPT_FIELD] = recheck_due_at - receipt[EVIDENCE_SCOPE_FIELD] = build_evidence_scope( - level, - # Only a verified receipt names a basis, so only it reads VERIFIED. - basis=basis if verified else None, - confirmed=delta_verdict == CONFIRMED_WORD, - minimum=minimum_level, - read_back_at=read_at if not unread else None, - recheck_window_s=( - int(recheck_after_s) - if recheck_due_at is not None and recheck_after_s is not None - else None - ), - not_covered=("changes_after_read_back",), - ) + if build_evidence_scope is not None: + receipt[EVIDENCE_SCOPE_FIELD] = build_evidence_scope( + level, + # Only a verified receipt names a basis, so only it reads VERIFIED. + basis=basis if verified else None, + confirmed=delta_verdict == CONFIRMED_WORD, + minimum=minimum_level, + read_back_at=read_at if not unread else None, + recheck_window_s=( + int(recheck_after_s) + if recheck_due_at is not None and recheck_after_s is not None + else None + ), + not_covered=("changes_after_read_back",), + ) if request_context is not None: receipt["request_context"] = request_context.to_dict() problem = receipt_problem(receipt) or evidence_problem(evidence, receipt) @@ -4436,7 +4437,7 @@ def _evidence_scope_receipt_problem(receipt: Mapping[str, Any]) -> Optional[str] if EVIDENCE_SCOPE_FIELD not in receipt: return None # Receipts issued before the block existed. scope = receipt[EVIDENCE_SCOPE_FIELD] - if evidence_scope_problem(scope) is not None: + if evidence_scope_problem is None or evidence_scope_problem(scope) is not None: return "evidence_scope" verified = receipt.get("outcome") in ("verified", "rolled_back_verified") if (scope["word"] == VERIFIED_WORD) is not verified: diff --git a/packages/verify/tests/test_tx_verify_facade.py b/packages/verify/tests/test_tx_verify_facade.py index 5c002a0f31..dfb68f581f 100644 --- a/packages/verify/tests/test_tx_verify_facade.py +++ b/packages/verify/tests/test_tx_verify_facade.py @@ -348,7 +348,7 @@ def test_end_to_end_network_capture_to_certified_pack_and_cli_tx_run( str(state_dir), ] ) - assert rc_run == 3 + assert rc_run == 0 after_row = dict( conn.execute("SELECT * FROM tasks WHERE id = ?", (clean_id,)).fetchone() ) @@ -365,7 +365,9 @@ def test_end_to_end_network_capture_to_certified_pack_and_cli_tx_run( priv_key.public_key(), log_dir=state_dir / "log", ) - assert verified_payload["outcome"] == "UNCERTAIN" + assert verified_payload["outcome"] == "CONFIRMED" + assert verified_payload["evidence_scope"]["word"] == "VERIFIED" + assert verified_payload["evidence_scope"]["basis"] == "system_api" assert verified_payload["qualification_state"] == "unqualified" assert verified_payload["rows_read"] == 2