From 99d9b3f91c70614e7a5d129a87aca054a1871654 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 14:59:36 -0500 Subject: [PATCH 1/4] fix(handoff): read an encrypted run's receipt card through its sealed set; refuse sandbox runs and say why A strict at-rest run already gets a receipt: receipt.json is a plaintext structural file of the sealed set. The public card (receipt.card.json) is sealed with the run, and receipt_for_run read it as plaintext, so get_handoff with public=true failed on every encrypted run. It now reads through sealed_set, in memory, and writes nothing. public_reveal reads the report the same way, so an encrypted tutorial run's card opens the same fields as a plaintext one. Sandbox runs stay receipt-less: record/run/v1 has no field that marks a run as synthetic, and the key's role lives in the receiver's registry, not the signed statement. get_handoff now refuses mode=sandbox results before reading any run folder, with a message the A2A text part carries. Docs: A2A.md 'When a run has no receipt' no longer lists strict runs; HANDOFF_RECEIPTS.md and the A2A capability row updated. --- CAPABILITIES.md | 6 +- ...2agent-protocol-adapter-openadapt-agent.md | 2 +- capabilities/CAPABILITIES.md.sha256 | 2 +- llms-full.txt | 40 +++- packages/agent/tests/test_handoff_e2e.py | 8 + packages/agent/tests/test_handoff_sandbox.py | 115 +++++++++++ packages/flow/docs/A2A.md | 24 ++- packages/flow/docs/HANDOFF_RECEIPTS.md | 4 +- .../openadapt_flow/agent/handoff_tools.py | 15 ++ packages/flow/openadapt_flow/handoff.py | 13 +- .../flow/openadapt_flow/receipt_record.py | 6 +- packages/flow/tests/test_handoff_at_rest.py | 187 ++++++++++++++++++ 12 files changed, 406 insertions(+), 16 deletions(-) create mode 100644 packages/agent/tests/test_handoff_sandbox.py create mode 100644 packages/flow/tests/test_handoff_at_rest.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 1dcbe2088b..77817229e2 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -176,6 +176,7 @@ improvising or retrying when something is off. | 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". 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` | | Grade a file, PDF or email check by who produced it: a file the acting session wrote or downloaded, or one with no declared producer, is at most `same_screen`; one a separate session fetched is at most `separate_session`; only a declared `system_of_record` producer reaches `system_of_record`. A store that overlaps the acting session's folders (named ones, the user's Downloads, a Playwright download folder) is graded as the acting session's whatever is declared. Under a strong declared producer, a scan that reads a file in a browser download folder beneath the store, or a symlink out of it, is refused as INDETERMINATE. The verdict's `read_evidence.provenance` names the producer and whether it was declared or observed | On main | Unit tests through each of the four readers (mixed store, symlink, system-owned positive case); a PDF downloaded by headless Chromium from a loopback app, the same bytes from a separate browser context and from the app's store, and a headless download landing beneath a broader store | `runtime/effects/artifact_provenance.py`, `effects.artifact_producer`, `packages/flow/tests/test_effect_artifact_provenance.py` | +| One strict matcher decides whether text on a screen or page proves a value or a commit: `MATCH`, `MISMATCH` or `AMBIGUOUS`, and only `MATCH` passes. A value must be bound to its label at the start of its field, with nothing but unit words beside it, or be the whole field. A value merely found on the page, inside a longer token (`250` in `$1,250.00`, `John Smith` in `John Smith-Jones`), or under a label with two values never passes. A commit phrase must be new, plainly stated, and not next to a question, a negation or a control label. The launcher's transducer read-back and the kernel's read-back oracles use it; [the migration page](packages/types/docs/evidence-migration.md) lists the callers that don't yet | On main | Adversarial corpus with pinned verdicts, Hypothesis properties, a parity test against Flow's read-back matcher, and strict expected-failure tests for each caller not yet migrated | `openadapt_types/evidence.py`, `openadapt/transducer_obligations.py`, `openadapt_kernel/oracles.py` | | Check a value where a careful person would look again: an effect location (`openadapt.effect-location/v1`) is pack data for one place an intended value shows (path and start condition, locator, expected value, codec, expected count, optional baseline). One summary row can cover two values ("Name (DOB)"), and a date can be split over three fields. Every planned value is `held`, `refuted` or `not_checked`; a place that can't be reached, found or read is `not_checked`. The check level follows the start condition (a new session is level 3), and the engine holds no application words | PR [#2500](https://github.com/OpenAdaptAI/OpenAdapt/pull/2500), not yet used by a runner | Unit tests and the fail-open harness (synthetic readings only) | `openadapt_flow/effect_location/`, [EFFECT_LOCATION.md](packages/flow/docs/EFFECT_LOCATION.md) | | 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) | @@ -234,6 +235,7 @@ improvising or retrying when something is off. | Propose an undo for each saving step (another recording, captured traffic, or the old value), keep it only if a test copy shows every record restored, and offer it after a stop once a person approves it | Released ([#1346](https://github.com/OpenAdaptAI/OpenAdapt/pull/1346)) | Synthetic (MockMed, MockLoan, live browser) | `openadapt-flow undo propose`, `undo accept`; [AFTER_A_STOP.md](packages/flow/docs/AFTER_A_STOP.md) | | Roll a stopped run back on its own: the approved compensation for each change, latest first, an uncertain write only when a fresh read shows it landed, then a read of the whole database: every row the run touched back as it was and nothing else changed (`ROLLED_BACK`), or the exact rows a person repairs (`RECONCILIATION_REQUIRED`). A compensation runs only while every change in the store is positively the run's own by the app's audit log, so another user's work is never compensated away, and a hard delete runs only where the deployment allows it (void, restore or discard otherwise). `rollback qualify` stops the run before and after every save on a test copy and keeps only compensations that restore the whole store. On a desktop or remote-display backend a screen compensation runs only after the run's and the compensation's start screens are checked on the same backend | On main ([#1634](https://github.com/OpenAdaptAI/OpenAdapt/pull/1634)); desktop in [#1771](https://github.com/OpenAdaptAI/OpenAdapt/pull/1771) | MockMed, live browser through the CLI; SQLite whole-database tests (web and desktop paths) | `openadapt-flow rollback qualify`, `rollback:` in deployment.yaml; [ROLLBACK.md](packages/flow/docs/ROLLBACK.md) | | Leave the screen clean after an item that halted before any write: close dialogs and cancel forms with the recordings' own controls, re-enter, confirm the start screen and read the records back before the session takes another item. A session that doesn't come back is marked dirty and takes no more items; a cleanup that changed a record makes the item's write uncertain and stops the run. `cleanup qualify` tries the cleanup after every step on a test copy and refuses one that changes a record | Released ([#1607](https://github.com/OpenAdaptAI/OpenAdapt/pull/1607)) | Synthetic (scripted three-screen app through the real replayer and pool) and real app (pinned OpenEMR: a halted New Patient item left the confirmation dialog open; re-entry closed it, the form was empty, no patient row changed and the next item's first steps ran with no model calls; a signed-out screen was marked dirty; [results](packages/flow/benchmark/halt_cleanup/results/openemr.json)) | `openadapt-flow cleanup qualify`; [HALT_CLEANUP.md](packages/flow/docs/HALT_CLEANUP.md) | +| Commit-boundary kernel, an optional alpha extra: `pip install 'openadapt[kernel]'` adds `openadapt kernel` (or install `openadapt-kernel` alone for its own command), an experimental runtime with shadow, draft and autopilot modes and signed receipts that does not depend on `openadapt-flow`. `pip install openadapt` leaves it out, and the extra is capped below the next minor version because its API may change before 1.0 | On main | Synthetic (its own suite, headless Chromium tests included, runs in the required `ci` check on every kernel change) | [packages/kernel](packages/kernel/README.md) | ## Approvals @@ -334,6 +336,7 @@ improvising or retrying when something is off. | Self-repair's new clicks outside a browser: on a native app a click is admitted by its accessibility element (role, name, ancestry, window; unique in the pinned window), on pixels only by the record check, and either way only when a system-of-record verifier covers every save under `standard` or `regulated`; the new step carries the dialog around it as a screen pre-check, and only a person approves the fix | On main ([#1709](https://github.com/OpenAdaptAI/OpenAdapt/pull/1709)) | Synthetic, partly live: on OpenAdapt's native Cocoa test app with SQLite, through live macOS AX, the stop, the element identity read, the admission and the refusals without a record check ran with no wrong write; qualified end to end on macOS AX ([#1715](https://github.com/OpenAdaptAI/OpenAdapt/pull/1715)): stop, admitted click, probe, replay and fault campaigns, one approval, resumed run `VERIFIED`; and on its GTK3 counterpart through live Linux AT-SPI, in CI, the same end to end. `run --self-repair` and repair by default start the app for each probe from `repair.session` ([#1717](https://github.com/OpenAdaptAI/OpenAdapt/pull/1717); [benchmark/repair_every_backend](packages/flow/benchmark/repair_every_backend/README.md)) | `openadapt_flow/repair/element_identity.py`, [REPAIR_ON_EVERY_BACKEND.md](packages/flow/docs/REPAIR_ON_EVERY_BACKEND.md) | | Keep pixel-path runs working across display scaling and font smoothing changes | Released ([#1286](https://github.com/OpenAdaptAI/OpenAdapt/pull/1286)) | Synthetic (in-process RDP and canvas renderings: 17 of 24 healthy runs across 100–175%, up from 3; 0 wrong saves) | [benchmark/pixel_scale](packages/flow/benchmark/pixel_scale/README.md) | | Find icons again on Citrix, RDP and VNC after a display-scale, zoom, font, theme or codec change, with a local model that counts look-alikes and stops on a tie (`--local-grounding`, off by default) | Released ([#1596](https://github.com/OpenAdaptAI/OpenAdapt/pull/1596)) | Synthetic (Chromium-drawn clinic screen, pixels only: icons found under 21 of 26 conditions, template matching 8; 0 wrong targets in 65; whole runs unchanged, 4 of 39 in both arms, because the layout, identity and census checks stop first). Held out on real AVC444 RDP frames: 0 wrong picks, 6 right, 75 abstentions in 81 | [benchmark/pixel_grounding](packages/flow/benchmark/pixel_grounding/README.md), `runtime/local_grounder.py` | +| Find an icon-only click target again after a light/dark theme change on Citrix, RDP and VNC, by edge orientation with the sign removed, refusing when another place on the screen scores close, the match is away from the recorded place, or the clicked control itself differs | In a pull request ([#2790](https://github.com/OpenAdaptAI/OpenAdapt/pull/2790)) | Synthetic (Chromium-drawn clinic screen, pixels only, recorded light and replayed dark at 100% and 150%: whole runs 8 of 13 healthy and 7 of 13 reordered, up from 6 and 5; wrong-record runs 13 of 13 stopped; 0 wrong targets or wrong saves) | [benchmark/pixel_grounding](packages/flow/benchmark/pixel_grounding/README.md#whole-runs), `vision/polarity_match.py` | | Pre-approved repairs: a signed policy lists low-risk changes that apply without a person, a test-record run before each queue, and one approval for every item halted the same way | Released ([#1294](https://github.com/OpenAdaptAI/OpenAdapt/pull/1294)) | Synthetic | standard changes | | Repair a pinned bundle: the fix runs the pinned bundle's own qualification campaign on a test copy, keeps every write, effect, identity rule and record check, and is re-admitted with signed lineage (at most three repairs, no revoked key) that the pin verifies | On main | Synthetic | [SELF_REPAIR.md](packages/flow/docs/SELF_REPAIR.md#a-pinned-bundle-re-qualify-and-re-admit) | | Repair by default: once a repair agent is configured (outside a browser, with `repair.session`, [#1717](https://github.com/OpenAdaptAI/OpenAdapt/pull/1717)), every stop that wrote nothing goes to it without anyone starting it; a stop after a possible write goes to reconciliation; every stop is a row in a ledger with the funnel from stop to resumed item | Released ([#1360](https://github.com/OpenAdaptAI/OpenAdapt/pull/1360)) | Synthetic (MockMed, 22 drift modes, real Claude agent: 6 of 21 repairable stops resumed and verified, 0 wrong saves in 66 runs); routing over recorded OpenEMR stops; live openIMIS relabel: 3 of 3 reached repair and stopped with no wrong save; silent-saves 1.1.0 UI-change blocks: 18 of 28 items that always stopped now correct, 0 wrong | `run` (on by default, `--no-auto-repair`), `repair:` in `deploy.yaml`, [benchmark/auto_repair](packages/flow/benchmark/auto_repair/README.md) | @@ -355,7 +358,7 @@ improvising or retrying when something is off. | Admit a draft by a person, an admitter key, or an agent under a person-signed policy, including self-admission when the policy allows it | Released | Unit tests | [JIT_ADMISSION.md](packages/flow/docs/JIT_ADMISSION.md) | | MCP server: your agent decides what to enter, OpenAdapt makes the entry and checks it | Released | Synthetic sandbox | `openadapt-agent`, [packages/agent](packages/agent/README.md) | | Agent-to-agent handoffs: when one agent hands a result to another, the run's signed receipt (`record/run/v1`) goes with it (`openadapt handoff send`, inline, detached beside a file, or POSTed to a webhook), and the receiver checks it against keys it pins (`openadapt handoff verify`). The verdict gives the signer role from the receiver's registry, integrity, checks passed and not checked, and "confirmed in the other party's system" lines; it always says a valid signature proves who signed, not that the claim is true, binds the payload as the receipt's `payload` subject (re-signed by the run's own key; other bytes or no payload subject are refused), and counts a confirmation as independent only when it was read from the other party's system. Over MCP, `serve --handoffs` adds `get_handoff` and `verify_handoff`. The private openings never travel | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Unit tests over receipts from Flow's own writer and the shared `record/run/v1` confirmation vectors and the shared payload vectors (good, tampered, unknown signer, bound, mismatched and missing payload, detached file, local webhook); MCP and A2A end to end with the stubbed run process; a two-party test of 20 handoffs over HTTP (0 false accepts, 0 true rejects); one real headless MockMed run handed off over the CLI and checked against the receiver's own record ([benchmark/handoff_real_run](packages/flow/benchmark/handoff_real_run/README.md)); `--ledger` tested against #2415's `HandoffLedger` | `openadapt handoff`, `openadapt_flow/handoff.py`, [HANDOFFS.md](packages/flow/docs/HANDOFFS.md), draft format [HANDOFF_RECEIPTS.md](packages/flow/docs/HANDOFF_RECEIPTS.md) | -| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact when Flow wrote one (sandbox and strict at-rest runs have none), a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](packages/flow/docs/A2A.md) | +| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact when Flow wrote one (sandbox runs have none, and the text part says why; strict at-rest runs carry theirs, read through the sealed run), a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; a real strict-mode sealed run folder whose receipt and card go through `get_handoff` and `verify_handoff`; a simulated sandbox run refused over MCP and A2A; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](packages/flow/docs/A2A.md) | | Teach over MCP: an agent does a new task once through OpenAdapt; the run is read back, compiled and admitted (a person confirms the record check; the agent admits only under a person-signed policy), and becomes a tool it calls with no model calls. Web, and Windows, macOS, Linux, RDP and Citrix with a person approving each save | On main ([#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed over MCP, and through the real RDP and Citrix backends); a native Cocoa app with SQLite through `MacOSBackend`, taught, confirmed, admitted under a signed policy and called (canary and taught run `VERIFIED`, 0 model calls; [teach_desktop](packages/flow/benchmark/teach_desktop/README.md)) | `openadapt-agent serve --teach`, [packages/agent](packages/agent/README.md#teach-a-new-workflow-from-your-agent) | | Turn a read-only browser task into a tool for the coding agent you already use: `openadapt setup` registers the MCP server and a skill in Claude Code, Cursor, Codex and Gemini CLI (idempotent, `--dry-run`, `--undo`); `openadapt setup --app deploy.yaml --verify verify.yaml` sets the agent up to teach saves in one web, desktop, RDP or Citrix app instead, each read back from the system of record. Read-only teaching runs only where a guard stops writes before they leave (the browser); `serve --teach-browser --config` naming a desktop, RDP or Citrix app is refused; the agent does the task once through `teach_start`/`teach_act`/`teach_finish`, the task must end in a download, the file is checked (columns, a column between two inputs or equal to one, fewest rows), the compiled steps are replayed once with no model, and the agent gets a `taught_` tool that downloads a checked file with new inputs. The browser sends no POST, PUT, PATCH or DELETE and stays on one site; a compiled run stops when a control is missing, matches more than one element, or is relabelled | Released ([#1502](https://github.com/OpenAdaptAI/OpenAdapt/pull/1502)) | Real headless Chromium on the local example portal (scripted MCP client, in CI); a real Claude Code agent taught the export from the guide's prompt and called the tool with new dates (2026-10-24, one run) | `openadapt setup`, `openadapt-agent serve --teach-browser`, [FIRST_TOOL.md](packages/flow/docs/FIRST_TOOL.md) | | Verify any agent's own writes: `openadapt verify` reads the system of record before and after a write, against a contract the operator owns (REST, FHIR, SQL, GraphQL), and returns a verified receipt (`openadapt.effect-receipt/v1`) or a refusal (`REFUTED`, `UNCERTAIN`), never an unverified success. Python SDK (`openadapt.verify`, which is `openadapt_flow.verifier`: `begin_write`, `verify_write`, `verified_write`) wraps a write in any agent framework; the MCP server (`openadapt verify serve`) offers `verify_begin`, `verify_check` and `verify_recheck` to any MCP client | Released ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589)) | Synthetic (MockMed's fault server over real HTTP: correct write, wrong record, not saved, saved twice, unreadable store) | `openadapt verify`, [VERIFY_WRITES.md](packages/flow/docs/VERIFY_WRITES.md) | @@ -406,6 +409,7 @@ improvising or retrying when something is off. | Offline Seals signed with a key the customer holds: a key file, the OS keychain, or a PKCS#11 token or HSM; pinned keys with rotation and revocation; no fallback to a generated key | On main ([#1392](https://github.com/OpenAdaptAI/OpenAdapt/pull/1392)) | Unit tests with synthetic data (keychain and PKCS#11 through stand-ins) | `openadapt-flow local-seal --key`, `local-seal key create`, `pin`, `revoke`; `openadapt seal verify FOLDER` checks every sealed run in a folder; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#customer-held-keys) | | Anchor an offline Seal in the public Sigstore Rekor transparency log (opt-in; sends one digest and the public key), and verify the anchor offline from the stored inclusion proof | Released ([#1394](https://github.com/OpenAdaptAI/OpenAdapt/pull/1394)) | Unit tests against a simulated Rekor log; real public Rekor entries and Sigstore TSA tokens for the landing demo's referral runs, verified offline in tests; Ed25519ph matches the RFC 8032 test vector | `openadapt-flow local-seal anchor`, `local-seal verify --require-anchor`; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#optional-anchor-a-seal-in-a-public-transparency-log) | | Signed write receipts: a verifier verdict with its scope (stores read, window, strength) and a plain not-checked list, signed as a COSE_Sign1 (IETF SCITT shape) and logged in a local Merkle transparency log; checked offline against pinned keys; a receipt that claims more than its scope is neither issued nor accepted; optional Rekor anchor | On main | Unit tests on the real verifier (SQLite) and shadow proxy; COSE checked through python-cwt | `openadapt-flow receipt verify`, `receipt keys export`, `receipt anchor`; `verify_write(..., write_receipt=True)`; `shadow --receipts`; [WRITE_RECEIPTS.md](packages/flow/docs/WRITE_RECEIPTS.md) | +| Python `openadapt.wrap` receipts signed with this computer's `openadapt trust init` key by default (or `signing_key=`), naming the key by id and fingerprint; with no key a receipt says `digest_only` and `signed: false`, and `wrap` never creates a key. `verify_wrap_receipt` and `openadapt verify` accept a receipt only when its signature verifies against a key you pinned, never the key the receipt carries; an unknown signer or a digest-only receipt is not verified. A plain `check=` callable is recorded as `caller_check`, and a check can't raise its own `checked_how` | On main | Unit tests with real Ed25519 keys: an unsigned receipt with a recomputed digest and a receipt signed by its own embedded key both fail, through the SDK and `openadapt verify` | `openadapt.wrap`, `openadapt.verify_wrap_receipt`, `openadapt verify FILE [--keys FILE]`, `openadapt trust init` | | Per-run accounting ledger for any executor (an OpenAdapt agent, a compiled program, another agent, a person): one value-free row per run with the outcome (VERIFIED, ESCALATED, CAUGHT_ERROR, FAILED, UNKNOWN) and a closed reason, a person's minutes from approval, question, exception and second-factor intervals, model calls and cost (unknown is null, never zero), field names with their checks, and the read-back tier; values only in a local 0600 sidecar; collected from the files guard, verify-run, compiled runs, wrap, item approvals and compile-agent already write, plus readiness shadow runs, guard ledger rows, P7 fallback results and P6 exception answers; a person's decline is ESCALATED, not a caught error | On main | Unit tests with synthetic data: the outcome rule as a table over every engine outcome enum, fixtures for each source (copies of the shadow, guarded-save, fallback and exception files from a synthetic MockMed end-to-end run), the real commit guard against MockMed's fault server end to end, exports scanned for every fixture value and checked with the real Presidio scrubber, push payloads validated against the JSON Schema, push refused with no key | `openadapt-flow ledger add`, `list`, `show`, `summary`, `export`, `push`; [RUN_LEDGER.md](packages/flow/docs/RUN_LEDGER.md) | | See a run's Seal offline: one HTML page that checks the Ed25519 signature over the run's exact report in the browser, draws the Seal from it, replays the run over its program map, and lets the reader tamper with a copy; no network requests; the quickstart ends on the person's own. One screen: map left, Seal and verdict top right, Summary, Steps, Evidence and Raw tabs; light and dark | On main ([#1566](https://github.com/OpenAdaptAI/OpenAdapt/pull/1566)) | A real quickstart run's Seal opened from `file://` in Chromium (valid, tampered, no requests; a link to one step, keyboard tabs and steps, theme switch, phone layout); RFC 8032 test vectors; a published OpenEMR Seal's Rekor entry and timestamp | `openadapt seal view RUN_DIR`; `openadapt quickstart`; [`@openadapt/seal-view`](packages/seal-view/README.md) | | Sign in to OpenAdapt Cloud from the terminal: `openadapt login` with no token prints a sign-in link (opened only with `--open`), listens on 127.0.0.1 for the browser's redirect, and redeems Cloud's one-use code with an S256 PKCE verifier that never leaves the process. A first-time user gets a workspace on the way. The credential goes to the OS keychain entry `push` and `report-run` read; a stored token is re-validated as before, and `--token` and `--no-browser` keep the token path | On main | Unit tests with a real loopback listener (state mismatch, refusal, malformed code, timeout, browser opened only on request); end to end against Cloud's `/auth/loopback` and pairing routes in mock mode, both Connect and Cancel | `openadapt login`; [browser_login.py](packages/flow/openadapt_flow/browser_login.py) | diff --git a/capabilities/10-computer-use-agents/0070-a2a-agent2agent-protocol-adapter-openadapt-agent.md b/capabilities/10-computer-use-agents/0070-a2a-agent2agent-protocol-adapter-openadapt-agent.md index f2f3ee77a0..eba941347e 100644 --- a/capabilities/10-computer-use-agents/0070-a2a-agent2agent-protocol-adapter-openadapt-agent.md +++ b/capabilities/10-computer-use-agents/0070-a2a-agent2agent-protocol-adapter-openadapt-agent.md @@ -1 +1 @@ -| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact when Flow wrote one (sandbox and strict at-rest runs have none), a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](packages/flow/docs/A2A.md) | +| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact when Flow wrote one (sandbox runs have none, and the text part says why; strict at-rest runs carry theirs, read through the sealed run), a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; a real strict-mode sealed run folder whose receipt and card go through `get_handoff` and `verify_handoff`; a simulated sandbox run refused over MCP and A2A; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](packages/flow/docs/A2A.md) | diff --git a/capabilities/CAPABILITIES.md.sha256 b/capabilities/CAPABILITIES.md.sha256 index b178c64d02..a1c810d801 100644 --- a/capabilities/CAPABILITIES.md.sha256 +++ b/capabilities/CAPABILITIES.md.sha256 @@ -1 +1 @@ -6b0c7d386eb68b516766993b4afb1ffe6a0ea4461851850db38a845a47648b81 +4f48ad227eb6272e3c9fe873e843d7ddb7aef7636814952d0a010b91a045e50a diff --git a/llms-full.txt b/llms-full.txt index 128c26753b..97ce8b9951 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -120,7 +120,7 @@ Full methodology, benchmark tables, and verifiable raw runs: **[openadapt.ai/pro | Package | Role | Source | |---|---|---| | [`openadapt`](https://pypi.org/project/openadapt/) | Unified CLI (`quickstart`, `wrap`, `connect`, `record`, `compile`, `run`, `verify`, `kernel`, `agent`, `mcpify`) | [`openadapt/`](https://github.com/OpenAdaptAI/OpenAdapt/tree/main/openadapt) | -| [`openadapt-kernel`](https://github.com/OpenAdaptAI/OpenAdapt/tree/main/packages/kernel) | Commit-boundary kernel: default-deny write ledger, wire/DOM commit interceptor, stepwise live-DOM healer, cross-rail oracles, Ed25519 receipts, stdio MCP | [`packages/kernel/`](https://github.com/OpenAdaptAI/OpenAdapt/tree/main/packages/kernel) | +| [`openadapt-kernel`](https://github.com/OpenAdaptAI/OpenAdapt/tree/main/packages/kernel) | Optional alpha extra (`pip install 'openadapt[kernel]'`). Commit-boundary kernel: default-deny write ledger, wire/DOM commit interceptor, stepwise live-DOM healer, cross-rail oracles, Ed25519 receipts, stdio MCP | [`packages/kernel/`](https://github.com/OpenAdaptAI/OpenAdapt/tree/main/packages/kernel) | | [`openadapt-flow`](https://pypi.org/project/openadapt-flow/) | Demonstration compiler, certification, qualification, governed replay, auto-repair, and BYOC connector | [`packages/flow/`](https://github.com/OpenAdaptAI/OpenAdapt/tree/main/packages/flow) | | [`openadapt-agent`](https://pypi.org/project/openadapt-agent/) | MCP server, Agent Skills export, and A2A handoffs | [`packages/agent/`](https://github.com/OpenAdaptAI/OpenAdapt/tree/main/packages/agent) | | [`openadapt-verify`](https://pypi.org/project/openadapt-verify/) | Standalone Python SDK (`@verified`, `checked_write`, local JIT compiler, `mcpify`) | [`packages/verify/`](https://github.com/OpenAdaptAI/OpenAdapt/tree/main/packages/verify) | @@ -347,6 +347,7 @@ improvising or retrying when something is off. | 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". 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` | | Grade a file, PDF or email check by who produced it: a file the acting session wrote or downloaded, or one with no declared producer, is at most `same_screen`; one a separate session fetched is at most `separate_session`; only a declared `system_of_record` producer reaches `system_of_record`. A store that overlaps the acting session's folders (named ones, the user's Downloads, a Playwright download folder) is graded as the acting session's whatever is declared. Under a strong declared producer, a scan that reads a file in a browser download folder beneath the store, or a symlink out of it, is refused as INDETERMINATE. The verdict's `read_evidence.provenance` names the producer and whether it was declared or observed | On main | Unit tests through each of the four readers (mixed store, symlink, system-owned positive case); a PDF downloaded by headless Chromium from a loopback app, the same bytes from a separate browser context and from the app's store, and a headless download landing beneath a broader store | `runtime/effects/artifact_provenance.py`, `effects.artifact_producer`, `packages/flow/tests/test_effect_artifact_provenance.py` | +| One strict matcher decides whether text on a screen or page proves a value or a commit: `MATCH`, `MISMATCH` or `AMBIGUOUS`, and only `MATCH` passes. A value must be bound to its label at the start of its field, with nothing but unit words beside it, or be the whole field. A value merely found on the page, inside a longer token (`250` in `$1,250.00`, `John Smith` in `John Smith-Jones`), or under a label with two values never passes. A commit phrase must be new, plainly stated, and not next to a question, a negation or a control label. The launcher's transducer read-back and the kernel's read-back oracles use it; [the migration page](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/types/docs/evidence-migration.md) lists the callers that don't yet | On main | Adversarial corpus with pinned verdicts, Hypothesis properties, a parity test against Flow's read-back matcher, and strict expected-failure tests for each caller not yet migrated | `openadapt_types/evidence.py`, `openadapt/transducer_obligations.py`, `openadapt_kernel/oracles.py` | | Check a value where a careful person would look again: an effect location (`openadapt.effect-location/v1`) is pack data for one place an intended value shows (path and start condition, locator, expected value, codec, expected count, optional baseline). One summary row can cover two values ("Name (DOB)"), and a date can be split over three fields. Every planned value is `held`, `refuted` or `not_checked`; a place that can't be reached, found or read is `not_checked`. The check level follows the start condition (a new session is level 3), and the engine holds no application words | PR [#2500](https://github.com/OpenAdaptAI/OpenAdapt/pull/2500), not yet used by a runner | Unit tests and the fail-open harness (synthetic readings only) | `openadapt_flow/effect_location/`, [EFFECT_LOCATION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/EFFECT_LOCATION.md) | | 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) | @@ -405,6 +406,7 @@ improvising or retrying when something is off. | Propose an undo for each saving step (another recording, captured traffic, or the old value), keep it only if a test copy shows every record restored, and offer it after a stop once a person approves it | Released ([#1346](https://github.com/OpenAdaptAI/OpenAdapt/pull/1346)) | Synthetic (MockMed, MockLoan, live browser) | `openadapt-flow undo propose`, `undo accept`; [AFTER_A_STOP.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/AFTER_A_STOP.md) | | Roll a stopped run back on its own: the approved compensation for each change, latest first, an uncertain write only when a fresh read shows it landed, then a read of the whole database: every row the run touched back as it was and nothing else changed (`ROLLED_BACK`), or the exact rows a person repairs (`RECONCILIATION_REQUIRED`). A compensation runs only while every change in the store is positively the run's own by the app's audit log, so another user's work is never compensated away, and a hard delete runs only where the deployment allows it (void, restore or discard otherwise). `rollback qualify` stops the run before and after every save on a test copy and keeps only compensations that restore the whole store. On a desktop or remote-display backend a screen compensation runs only after the run's and the compensation's start screens are checked on the same backend | On main ([#1634](https://github.com/OpenAdaptAI/OpenAdapt/pull/1634)); desktop in [#1771](https://github.com/OpenAdaptAI/OpenAdapt/pull/1771) | MockMed, live browser through the CLI; SQLite whole-database tests (web and desktop paths) | `openadapt-flow rollback qualify`, `rollback:` in deployment.yaml; [ROLLBACK.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/ROLLBACK.md) | | Leave the screen clean after an item that halted before any write: close dialogs and cancel forms with the recordings' own controls, re-enter, confirm the start screen and read the records back before the session takes another item. A session that doesn't come back is marked dirty and takes no more items; a cleanup that changed a record makes the item's write uncertain and stops the run. `cleanup qualify` tries the cleanup after every step on a test copy and refuses one that changes a record | Released ([#1607](https://github.com/OpenAdaptAI/OpenAdapt/pull/1607)) | Synthetic (scripted three-screen app through the real replayer and pool) and real app (pinned OpenEMR: a halted New Patient item left the confirmation dialog open; re-entry closed it, the form was empty, no patient row changed and the next item's first steps ran with no model calls; a signed-out screen was marked dirty; [results](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/halt_cleanup/results/openemr.json)) | `openadapt-flow cleanup qualify`; [HALT_CLEANUP.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HALT_CLEANUP.md) | +| Commit-boundary kernel, an optional alpha extra: `pip install 'openadapt[kernel]'` adds `openadapt kernel` (or install `openadapt-kernel` alone for its own command), an experimental runtime with shadow, draft and autopilot modes and signed receipts that does not depend on `openadapt-flow`. `pip install openadapt` leaves it out, and the extra is capped below the next minor version because its API may change before 1.0 | On main | Synthetic (its own suite, headless Chromium tests included, runs in the required `ci` check on every kernel change) | [packages/kernel](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/kernel/README.md) | ## Approvals @@ -505,6 +507,7 @@ improvising or retrying when something is off. | Self-repair's new clicks outside a browser: on a native app a click is admitted by its accessibility element (role, name, ancestry, window; unique in the pinned window), on pixels only by the record check, and either way only when a system-of-record verifier covers every save under `standard` or `regulated`; the new step carries the dialog around it as a screen pre-check, and only a person approves the fix | On main ([#1709](https://github.com/OpenAdaptAI/OpenAdapt/pull/1709)) | Synthetic, partly live: on OpenAdapt's native Cocoa test app with SQLite, through live macOS AX, the stop, the element identity read, the admission and the refusals without a record check ran with no wrong write; qualified end to end on macOS AX ([#1715](https://github.com/OpenAdaptAI/OpenAdapt/pull/1715)): stop, admitted click, probe, replay and fault campaigns, one approval, resumed run `VERIFIED`; and on its GTK3 counterpart through live Linux AT-SPI, in CI, the same end to end. `run --self-repair` and repair by default start the app for each probe from `repair.session` ([#1717](https://github.com/OpenAdaptAI/OpenAdapt/pull/1717); [benchmark/repair_every_backend](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/repair_every_backend/README.md)) | `openadapt_flow/repair/element_identity.py`, [REPAIR_ON_EVERY_BACKEND.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/REPAIR_ON_EVERY_BACKEND.md) | | Keep pixel-path runs working across display scaling and font smoothing changes | Released ([#1286](https://github.com/OpenAdaptAI/OpenAdapt/pull/1286)) | Synthetic (in-process RDP and canvas renderings: 17 of 24 healthy runs across 100–175%, up from 3; 0 wrong saves) | [benchmark/pixel_scale](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/pixel_scale/README.md) | | Find icons again on Citrix, RDP and VNC after a display-scale, zoom, font, theme or codec change, with a local model that counts look-alikes and stops on a tie (`--local-grounding`, off by default) | Released ([#1596](https://github.com/OpenAdaptAI/OpenAdapt/pull/1596)) | Synthetic (Chromium-drawn clinic screen, pixels only: icons found under 21 of 26 conditions, template matching 8; 0 wrong targets in 65; whole runs unchanged, 4 of 39 in both arms, because the layout, identity and census checks stop first). Held out on real AVC444 RDP frames: 0 wrong picks, 6 right, 75 abstentions in 81 | [benchmark/pixel_grounding](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/pixel_grounding/README.md), `runtime/local_grounder.py` | +| Find an icon-only click target again after a light/dark theme change on Citrix, RDP and VNC, by edge orientation with the sign removed, refusing when another place on the screen scores close, the match is away from the recorded place, or the clicked control itself differs | In a pull request ([#2790](https://github.com/OpenAdaptAI/OpenAdapt/pull/2790)) | Synthetic (Chromium-drawn clinic screen, pixels only, recorded light and replayed dark at 100% and 150%: whole runs 8 of 13 healthy and 7 of 13 reordered, up from 6 and 5; wrong-record runs 13 of 13 stopped; 0 wrong targets or wrong saves) | [benchmark/pixel_grounding](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/pixel_grounding/README.md#whole-runs), `vision/polarity_match.py` | | Pre-approved repairs: a signed policy lists low-risk changes that apply without a person, a test-record run before each queue, and one approval for every item halted the same way | Released ([#1294](https://github.com/OpenAdaptAI/OpenAdapt/pull/1294)) | Synthetic | standard changes | | Repair a pinned bundle: the fix runs the pinned bundle's own qualification campaign on a test copy, keeps every write, effect, identity rule and record check, and is re-admitted with signed lineage (at most three repairs, no revoked key) that the pin verifies | On main | Synthetic | [SELF_REPAIR.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SELF_REPAIR.md#a-pinned-bundle-re-qualify-and-re-admit) | | Repair by default: once a repair agent is configured (outside a browser, with `repair.session`, [#1717](https://github.com/OpenAdaptAI/OpenAdapt/pull/1717)), every stop that wrote nothing goes to it without anyone starting it; a stop after a possible write goes to reconciliation; every stop is a row in a ledger with the funnel from stop to resumed item | Released ([#1360](https://github.com/OpenAdaptAI/OpenAdapt/pull/1360)) | Synthetic (MockMed, 22 drift modes, real Claude agent: 6 of 21 repairable stops resumed and verified, 0 wrong saves in 66 runs); routing over recorded OpenEMR stops; live openIMIS relabel: 3 of 3 reached repair and stopped with no wrong save; silent-saves 1.1.0 UI-change blocks: 18 of 28 items that always stopped now correct, 0 wrong | `run` (on by default, `--no-auto-repair`), `repair:` in `deploy.yaml`, [benchmark/auto_repair](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/auto_repair/README.md) | @@ -526,7 +529,7 @@ improvising or retrying when something is off. | Admit a draft by a person, an admitter key, or an agent under a person-signed policy, including self-admission when the policy allows it | Released | Unit tests | [JIT_ADMISSION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/JIT_ADMISSION.md) | | MCP server: your agent decides what to enter, OpenAdapt makes the entry and checks it | Released | Synthetic sandbox | `openadapt-agent`, [packages/agent](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/agent/README.md) | | Agent-to-agent handoffs: when one agent hands a result to another, the run's signed receipt (`record/run/v1`) goes with it (`openadapt handoff send`, inline, detached beside a file, or POSTed to a webhook), and the receiver checks it against keys it pins (`openadapt handoff verify`). The verdict gives the signer role from the receiver's registry, integrity, checks passed and not checked, and "confirmed in the other party's system" lines; it always says a valid signature proves who signed, not that the claim is true, binds the payload as the receipt's `payload` subject (re-signed by the run's own key; other bytes or no payload subject are refused), and counts a confirmation as independent only when it was read from the other party's system. Over MCP, `serve --handoffs` adds `get_handoff` and `verify_handoff`. The private openings never travel | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Unit tests over receipts from Flow's own writer and the shared `record/run/v1` confirmation vectors and the shared payload vectors (good, tampered, unknown signer, bound, mismatched and missing payload, detached file, local webhook); MCP and A2A end to end with the stubbed run process; a two-party test of 20 handoffs over HTTP (0 false accepts, 0 true rejects); one real headless MockMed run handed off over the CLI and checked against the receiver's own record ([benchmark/handoff_real_run](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/handoff_real_run/README.md)); `--ledger` tested against #2415's `HandoffLedger` | `openadapt handoff`, `openadapt_flow/handoff.py`, [HANDOFFS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFFS.md), draft format [HANDOFF_RECEIPTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFF_RECEIPTS.md) | -| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact when Flow wrote one (sandbox and strict at-rest runs have none), a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/A2A.md) | +| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact when Flow wrote one (sandbox runs have none, and the text part says why; strict at-rest runs carry theirs, read through the sealed run), a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; a real strict-mode sealed run folder whose receipt and card go through `get_handoff` and `verify_handoff`; a simulated sandbox run refused over MCP and A2A; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/A2A.md) | | Teach over MCP: an agent does a new task once through OpenAdapt; the run is read back, compiled and admitted (a person confirms the record check; the agent admits only under a person-signed policy), and becomes a tool it calls with no model calls. Web, and Windows, macOS, Linux, RDP and Citrix with a person approving each save | On main ([#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed over MCP, and through the real RDP and Citrix backends); a native Cocoa app with SQLite through `MacOSBackend`, taught, confirmed, admitted under a signed policy and called (canary and taught run `VERIFIED`, 0 model calls; [teach_desktop](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/teach_desktop/README.md)) | `openadapt-agent serve --teach`, [packages/agent](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/agent/README.md#teach-a-new-workflow-from-your-agent) | | Turn a read-only browser task into a tool for the coding agent you already use: `openadapt setup` registers the MCP server and a skill in Claude Code, Cursor, Codex and Gemini CLI (idempotent, `--dry-run`, `--undo`); `openadapt setup --app deploy.yaml --verify verify.yaml` sets the agent up to teach saves in one web, desktop, RDP or Citrix app instead, each read back from the system of record. Read-only teaching runs only where a guard stops writes before they leave (the browser); `serve --teach-browser --config` naming a desktop, RDP or Citrix app is refused; the agent does the task once through `teach_start`/`teach_act`/`teach_finish`, the task must end in a download, the file is checked (columns, a column between two inputs or equal to one, fewest rows), the compiled steps are replayed once with no model, and the agent gets a `taught_` tool that downloads a checked file with new inputs. The browser sends no POST, PUT, PATCH or DELETE and stays on one site; a compiled run stops when a control is missing, matches more than one element, or is relabelled | Released ([#1502](https://github.com/OpenAdaptAI/OpenAdapt/pull/1502)) | Real headless Chromium on the local example portal (scripted MCP client, in CI); a real Claude Code agent taught the export from the guide's prompt and called the tool with new dates (2026-10-24, one run) | `openadapt setup`, `openadapt-agent serve --teach-browser`, [FIRST_TOOL.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/FIRST_TOOL.md) | | Verify any agent's own writes: `openadapt verify` reads the system of record before and after a write, against a contract the operator owns (REST, FHIR, SQL, GraphQL), and returns a verified receipt (`openadapt.effect-receipt/v1`) or a refusal (`REFUTED`, `UNCERTAIN`), never an unverified success. Python SDK (`openadapt.verify`, which is `openadapt_flow.verifier`: `begin_write`, `verify_write`, `verified_write`) wraps a write in any agent framework; the MCP server (`openadapt verify serve`) offers `verify_begin`, `verify_check` and `verify_recheck` to any MCP client | Released ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589)) | Synthetic (MockMed's fault server over real HTTP: correct write, wrong record, not saved, saved twice, unreadable store) | `openadapt verify`, [VERIFY_WRITES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_WRITES.md) | @@ -577,6 +580,7 @@ improvising or retrying when something is off. | Offline Seals signed with a key the customer holds: a key file, the OS keychain, or a PKCS#11 token or HSM; pinned keys with rotation and revocation; no fallback to a generated key | On main ([#1392](https://github.com/OpenAdaptAI/OpenAdapt/pull/1392)) | Unit tests with synthetic data (keychain and PKCS#11 through stand-ins) | `openadapt-flow local-seal --key`, `local-seal key create`, `pin`, `revoke`; `openadapt seal verify FOLDER` checks every sealed run in a folder; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#customer-held-keys) | | Anchor an offline Seal in the public Sigstore Rekor transparency log (opt-in; sends one digest and the public key), and verify the anchor offline from the stored inclusion proof | Released ([#1394](https://github.com/OpenAdaptAI/OpenAdapt/pull/1394)) | Unit tests against a simulated Rekor log; real public Rekor entries and Sigstore TSA tokens for the landing demo's referral runs, verified offline in tests; Ed25519ph matches the RFC 8032 test vector | `openadapt-flow local-seal anchor`, `local-seal verify --require-anchor`; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#optional-anchor-a-seal-in-a-public-transparency-log) | | Signed write receipts: a verifier verdict with its scope (stores read, window, strength) and a plain not-checked list, signed as a COSE_Sign1 (IETF SCITT shape) and logged in a local Merkle transparency log; checked offline against pinned keys; a receipt that claims more than its scope is neither issued nor accepted; optional Rekor anchor | On main | Unit tests on the real verifier (SQLite) and shadow proxy; COSE checked through python-cwt | `openadapt-flow receipt verify`, `receipt keys export`, `receipt anchor`; `verify_write(..., write_receipt=True)`; `shadow --receipts`; [WRITE_RECEIPTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRITE_RECEIPTS.md) | +| Python `openadapt.wrap` receipts signed with this computer's `openadapt trust init` key by default (or `signing_key=`), naming the key by id and fingerprint; with no key a receipt says `digest_only` and `signed: false`, and `wrap` never creates a key. `verify_wrap_receipt` and `openadapt verify` accept a receipt only when its signature verifies against a key you pinned, never the key the receipt carries; an unknown signer or a digest-only receipt is not verified. A plain `check=` callable is recorded as `caller_check`, and a check can't raise its own `checked_how` | On main | Unit tests with real Ed25519 keys: an unsigned receipt with a recomputed digest and a receipt signed by its own embedded key both fail, through the SDK and `openadapt verify` | `openadapt.wrap`, `openadapt.verify_wrap_receipt`, `openadapt verify FILE [--keys FILE]`, `openadapt trust init` | | Per-run accounting ledger for any executor (an OpenAdapt agent, a compiled program, another agent, a person): one value-free row per run with the outcome (VERIFIED, ESCALATED, CAUGHT_ERROR, FAILED, UNKNOWN) and a closed reason, a person's minutes from approval, question, exception and second-factor intervals, model calls and cost (unknown is null, never zero), field names with their checks, and the read-back tier; values only in a local 0600 sidecar; collected from the files guard, verify-run, compiled runs, wrap, item approvals and compile-agent already write, plus readiness shadow runs, guard ledger rows, P7 fallback results and P6 exception answers; a person's decline is ESCALATED, not a caught error | On main | Unit tests with synthetic data: the outcome rule as a table over every engine outcome enum, fixtures for each source (copies of the shadow, guarded-save, fallback and exception files from a synthetic MockMed end-to-end run), the real commit guard against MockMed's fault server end to end, exports scanned for every fixture value and checked with the real Presidio scrubber, push payloads validated against the JSON Schema, push refused with no key | `openadapt-flow ledger add`, `list`, `show`, `summary`, `export`, `push`; [RUN_LEDGER.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/RUN_LEDGER.md) | | See a run's Seal offline: one HTML page that checks the Ed25519 signature over the run's exact report in the browser, draws the Seal from it, replays the run over its program map, and lets the reader tamper with a copy; no network requests; the quickstart ends on the person's own. One screen: map left, Seal and verdict top right, Summary, Steps, Evidence and Raw tabs; light and dark | On main ([#1566](https://github.com/OpenAdaptAI/OpenAdapt/pull/1566)) | A real quickstart run's Seal opened from `file://` in Chromium (valid, tampered, no requests; a link to one step, keyboard tabs and steps, theme switch, phone layout); RFC 8032 test vectors; a published OpenEMR Seal's Rekor entry and timestamp | `openadapt seal view RUN_DIR`; `openadapt quickstart`; [`@openadapt/seal-view`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/seal-view/README.md) | | Sign in to OpenAdapt Cloud from the terminal: `openadapt login` with no token prints a sign-in link (opened only with `--open`), listens on 127.0.0.1 for the browser's redirect, and redeems Cloud's one-use code with an S256 PKCE verifier that never leaves the process. A first-time user gets a workspace on the way. The credential goes to the OS keychain entry `push` and `report-run` read; a stored token is re-validated as before, and `--token` and `--no-browser` keep the token path | On main | Unit tests with a real loopback listener (state mismatch, refusal, malformed code, timeout, browser opened only on request); end to end against Cloud's `/auth/loopback` and pairing routes in mock mode, both Connect and Cancel | `openadapt login`; [browser_login.py](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/openadapt_flow/browser_login.py) | @@ -1117,6 +1121,38 @@ are part of the qualification boundary, so this does not qualify arbitrary fresh workers. A script-hosted application's own code is covered by its declared version, not the host executable's hash. +## Windows approval: controls without their own window + +Before a save, an approval on Windows reads the app window to check that +nothing changed while the person decided. A text box or label with its own +window is read through two independent sources that must agree, so a value +cut short by the app's accessibility provider stops the item. A control drawn +by its parent, such as a grid cell, a grid column header or the title bar, +has no second source. Its UI Automation value is read twice and must match, +and the screen text over it is still read. If the provider cuts that value +short, a change in the hidden part that also leaves the visible text the same +is not detected. Some providers give such a control no RuntimeId at all +(WinForms grid cells and column headers). That control is then bound by its +path: each element up to an ancestor that has a RuntimeId, by type, position +and index among its siblings, read again before and after each of the two +reads. If a provider swaps in another element with the same type, position +and index, the check reads it as the same control; a changed value still +shows in the two reads or in the screen text. A scroll or resize between the +reads stops the item. A grid or list cell, a header or the title bar is +included even when its provider reports it as editable (WinForms does so +for a read-only grid); a text box never is. These values are used only for +that check: they are never complete values, read-back evidence or the basis +of a VERIFIED result. Read-back, not the approval check, verifies what a +save wrote. An +editable control, a password field, a control whose password status is +unknown, or one whose two reads differ still stops the item. + +A native Windows stale-identity fault covers the whole screen, so the +keyboard lease that checks the target refuses and the save halts. The fault +receipt then binds to the engine's own plain screenshot, and only when its +SHA-256 equals the frame the fault driver signed. Otherwise no receipt is +recorded and the campaign rejects the case. + ## Validated on Every published result used synthetic patients, claims and records. diff --git a/packages/agent/tests/test_handoff_e2e.py b/packages/agent/tests/test_handoff_e2e.py index d0bffb73b3..bad8b30006 100644 --- a/packages/agent/tests/test_handoff_e2e.py +++ b/packages/agent/tests/test_handoff_e2e.py @@ -18,6 +18,7 @@ import asyncio import base64 +import contextlib import hashlib import json import socket @@ -107,6 +108,13 @@ def _free_port() -> int: @pytest.fixture() def a2a_url(bridge): + with _serve_a2a(bridge) as url: + yield url + + +@contextlib.contextmanager +def _serve_a2a(bridge): + """Serve ``bridge`` over A2A on a free local port; yield its base URL.""" config = a2a_server.A2AConfig(port=_free_port()) server = uvicorn.Server( uvicorn.Config( diff --git a/packages/agent/tests/test_handoff_sandbox.py b/packages/agent/tests/test_handoff_sandbox.py new file mode 100644 index 0000000000..8cbf0a0915 --- /dev/null +++ b/packages/agent/tests/test_handoff_sandbox.py @@ -0,0 +1,115 @@ +"""Sandbox runs never carry a receipt, over MCP or A2A, and say why. + +A ``record/run/v1`` receipt has no field that marks a run as synthetic, and a +receiver's own key registry, not the signed statement, decides what a key +means. A receipt for a sandbox run, signed with this computer's key, would +read like proof about a real system, so ``get_handoff`` refuses sandbox runs +before it reads any run folder. +""" + +from __future__ import annotations + +import asyncio +import json +from pathlib import Path + +import pytest + +pytest.importorskip("a2a.server.routes") +pytest.importorskip("uvicorn") +pytest.importorskip("cryptography") + +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey # noqa: E402 +from openadapt_types import receipt as r # noqa: E402 +from test_handoff_e2e import ( # noqa: E402 + WRITE_REPORT_RESULTS, + _registry, + _result_from, + _send, + _serve_a2a, +) + +from openadapt_agent.bridge import AgentBridge, BridgeError # noqa: E402 +from openadapt_agent.runner import RunnerConfig # noqa: E402 +from openadapt_agent.sandbox import SANDBOX_WORKFLOW, SandboxEngine # noqa: E402 +from openadapt_flow import handoff as h # noqa: E402 +from openadapt_flow.agent.handoff_tools import ( # noqa: E402 + SANDBOX_NO_RECEIPT, + HandoffTools, +) +from openadapt_flow.receipt_record import write_receipt_record # noqa: E402 +from openadapt_flow.seal_keys import SoftwareSigner # noqa: E402 + + +@pytest.fixture() +def signer(): + return SoftwareSigner(Ed25519PrivateKey.generate(), "generated") + + +@pytest.fixture() +def sandbox_bridge(tmp_path, signer): + runs = tmp_path / "sandbox" + engine = SandboxEngine(runs, engine="simulated") + bridge = AgentBridge(None, RunnerConfig(runs_dir=runs), sandbox=engine, mode="sandbox") + bridge.handoffs = HandoffTools(registry=_registry(signer), signer=signer) + yield bridge + engine.close() + + +def _run(bridge, request_id): + return bridge.dispatch( + "run_workflow", + { + "workflow": SANDBOX_WORKFLOW, + "inputs": {"note": "Synthetic follow-up"}, + "request_id": request_id, + }, + ) + + +def _plant_receipt(run_dir: Path, signer) -> None: + """A real signed receipt in a sandbox run's folder (no sandbox path writes one).""" + run_dir.mkdir(parents=True, exist_ok=True) + report = { + "workflow_name": SANDBOX_WORKFLOW, + "execution_outcome": "VERIFIED", + "run_id": run_dir.name, + "started_at": "2026-11-21T01:02:03Z", + "change_ledger": [], + "results": WRITE_REPORT_RESULTS, + } + (run_dir / "report.json").write_text(json.dumps(report)) + write_receipt_record(run_dir, signer=signer, flow_version="3.4.0") + assert (run_dir / r.RECEIPT_FILE).is_file() + + +@pytest.mark.parametrize("public", [False, True]) +def test_a_sandbox_run_never_carries_a_receipt_and_says_why(sandbox_bridge, signer, public): + result = _run(sandbox_bridge, "sandbox-handoff-1") + assert result["mode"] == "sandbox" and result["outcome"] == "done" + # Even with a real signed receipt in the run's folder, the result never + # travels with one. + _plant_receipt(Path(sandbox_bridge.runner_config.runs_dir) / result["run_id"], signer) + assert "get_handoff" in [spec.name for spec in sandbox_bridge.list_tool_specs()] + with pytest.raises(BridgeError) as caught: + sandbox_bridge.dispatch("get_handoff", {"run_id": result["run_id"], "public": public}) + assert SANDBOX_NO_RECEIPT in str(caught.value) + + +def test_a2a_sandbox_artifact_says_why_it_has_no_receipt(sandbox_bridge): + with _serve_a2a(sandbox_bridge) as url: + task = asyncio.run( + _send( + url, + { + "skill": SANDBOX_WORKFLOW, + "inputs": {"note": "Synthetic follow-up"}, + "request_id": "sandbox-a2a-0001", + }, + ) + ) + assert _result_from(task)["mode"] == "sandbox" + parts = [part for artifact in task.artifacts for part in artifact.parts] + assert not [p for p in parts if p.HasField("raw") and p.media_type == h.MEDIA_TYPE] + texts = [p.text for p in parts if p.HasField("text")] + assert any(SANDBOX_NO_RECEIPT in text for text in texts), texts diff --git a/packages/flow/docs/A2A.md b/packages/flow/docs/A2A.md index 0201cd1a62..5d4105304a 100644 --- a/packages/flow/docs/A2A.md +++ b/packages/flow/docs/A2A.md @@ -35,16 +35,26 @@ a write; the server answers `TaskNotCancelableError`. ## When a run has no receipt Flow writes `receipt.json` after every `openadapt-flow run` and `replay`. -Three kinds of run have none: - -- **Sandbox runs.** `--mode sandbox` runs on a synthetic app, not through - the Flow CLI. -- **Encrypted runs.** With `OPENADAPT_FLOW_AT_REST=strict`, the run folder is - encrypted at rest and Flow writes no receipt. +Two kinds of run have none: + +- **Sandbox runs.** `--mode sandbox` runs on MockMed, a synthetic app, not + through the Flow CLI. `get_handoff` refuses any result whose `mode` is + `sandbox`, before it reads the run folder. A `record/run/v1` receipt has no + field that marks a run as synthetic, and the receiver's key registry, not + the signed statement, decides what a key means. A sandbox receipt signed + with this computer's key would therefore read like proof about a real + system. The result's `mode: "sandbox"` is the marker instead. - **Runs with receipts off.** Runs with `OPENADAPT_RECEIPT=off`. For these, `get_handoff` refuses, and the A2A artifact carries the run result -without a handoff. +with a text part that says why, and no handoff. + +Encrypted runs do have one. With `OPENADAPT_FLOW_AT_REST=strict` the run +folder is encrypted at rest, and the receipt is still written: `receipt.json` +stays plaintext beside the run, and the public card (`receipt.card.json`) is +sealed with it ([phi_at_rest.md](phi_at_rest.md), "Receipts"). `get_handoff` +reads both through the run's sealed set, in memory, and writes nothing. The +signed statement is the same as for a plaintext run of the same report. ## Same rules as MCP diff --git a/packages/flow/docs/HANDOFF_RECEIPTS.md b/packages/flow/docs/HANDOFF_RECEIPTS.md index 4acc9e431e..366ddccc73 100644 --- a/packages/flow/docs/HANDOFF_RECEIPTS.md +++ b/packages/flow/docs/HANDOFF_RECEIPTS.md @@ -157,7 +157,9 @@ These rules apply to the verdict: `openadapt agent serve --handoffs` adds two read-only tools: - **`get_handoff {run_id}`** returns the run's public result as the payload, - with its receipt attached. + with its receipt attached. It reads an encrypted run's receipt through the + run's sealed set. It refuses sandbox runs and runs without a receipt + ([A2A.md](A2A.md), "When a run has no receipt"). - **`verify_handoff {handoff}`** returns the verdict, checked against the server's pinned keys. diff --git a/packages/flow/openadapt_flow/agent/handoff_tools.py b/packages/flow/openadapt_flow/agent/handoff_tools.py index 7ad1f6a567..2ae21bd31e 100644 --- a/packages/flow/openadapt_flow/agent/handoff_tools.py +++ b/packages/flow/openadapt_flow/agent/handoff_tools.py @@ -25,6 +25,17 @@ HANDOFF_TOOLS = ("get_handoff", "verify_handoff") +#: Why a sandbox run never carries a receipt. A ``record/run/v1`` receipt has +#: no field that marks a run as synthetic, and the receiver's key registry, +#: not the signed statement, decides a key's role. So a receipt for a sandbox +#: run, signed with this computer's key, would read like proof about a real +#: system. Sandbox results say ``mode: "sandbox"`` instead. +SANDBOX_NO_RECEIPT = ( + "sandbox runs carry no receipt: they run on a synthetic app, and a signed " + "receipt has no field that marks a run as synthetic, so it could pass for " + "proof about a real system. The result's mode says sandbox." +) + class HandoffTools: """The handoff tool surface over one bridge's runs folder.""" @@ -136,6 +147,10 @@ def get( from openadapt_flow.handoff import HandoffError, make_handoff, receipt_for_run result = result_for(run_id) + if result.get("mode") == "sandbox": + # Checked before any run folder is read, so a sandbox run that + # somehow has a receipt file still never travels with one. + raise BridgeError(f"no handoff for this run: {SANDBOX_NO_RECEIPT}") if result.get("outcome") == "running": raise BridgeError("the run is still running; it has no receipt yet") try: diff --git a/packages/flow/openadapt_flow/handoff.py b/packages/flow/openadapt_flow/handoff.py index 4191be4811..7b8e264be4 100644 --- a/packages/flow/openadapt_flow/handoff.py +++ b/packages/flow/openadapt_flow/handoff.py @@ -294,12 +294,21 @@ def bind_payload( def receipt_for_run(run_dir: Path, *, public: bool = False) -> dict[str, Any]: - """Read a run's ``receipt.json`` (or its public card) for attaching.""" + """Read a run's ``receipt.json`` (or its public card) for attaching. + + Reads through the run's sealed set, so an encrypted run works: the + receipt is plaintext on disk there, the card is sealed with the run and + is opened in memory only. Nothing is written. + """ from openadapt_types import receipt as r + from openadapt_flow import sealed_set + path = Path(run_dir) / (r.CARD_FILE if public else r.RECEIPT_FILE) try: - return _check_receipt_document(_loads_strict(path.read_text("utf-8"))) + if not sealed_set.is_file(path): + raise FileNotFoundError(path.name) + return _check_receipt_document(_loads_strict(sealed_set.read_bytes(path))) except FileNotFoundError: raise HandoffError(f"no {path.name} in that run folder") from None except (OSError, UnicodeDecodeError, ValueError) as exc: diff --git a/packages/flow/openadapt_flow/receipt_record.py b/packages/flow/openadapt_flow/receipt_record.py index 4935e25da3..40a451cc37 100644 --- a/packages/flow/openadapt_flow/receipt_record.py +++ b/packages/flow/openadapt_flow/receipt_record.py @@ -772,7 +772,11 @@ def public_reveal(run_dir: Path) -> list[str]: summary = read_run_summary(run_dir) or {} reveal = ["flow_version"] try: - report = loads_strict((Path(run_dir) / "report.json").read_text("utf-8")) + # Through the sealed set, so an encrypted run's card opens the same + # fields as a plaintext run's. + from openadapt_flow import sealed_set + + report = loads_strict(sealed_set.read_text(Path(run_dir) / "report.json")) except (OSError, ValueError): report = {} if ( diff --git a/packages/flow/tests/test_handoff_at_rest.py b/packages/flow/tests/test_handoff_at_rest.py new file mode 100644 index 0000000000..85d5c0b899 --- /dev/null +++ b/packages/flow/tests/test_handoff_at_rest.py @@ -0,0 +1,187 @@ +"""Handoffs from an encrypted run (``OPENADAPT_FLOW_AT_REST=strict``). + +A real sealed run folder, the receipt written by the same hook the CLI calls +after a run (``receipt_after_run``), and the handoff built and checked the way +``get_handoff`` and ``verify_handoff`` do. The receipt must be the same as for +a plaintext run of the same report, and nothing but the allow-listed receipt +files may sit on disk in plaintext. +""" + +from __future__ import annotations + +import base64 +import hashlib +import json +from pathlib import Path +from typing import Any, Iterator + +import pytest + +pytest.importorskip("cryptography") + +from openadapt_types import receipt as r # noqa: E402 + +from openadapt_flow import at_rest, crypto, sealed_set # noqa: E402 +from openadapt_flow import handoff as h +from openadapt_flow.agent.bridge import BridgeError # noqa: E402 +from openadapt_flow.agent.handoff_tools import HandoffTools # noqa: E402 +from openadapt_flow.offline_seal import signer_for # noqa: E402 +from openadapt_flow.receipt_record import receipt_after_run # noqa: E402 +from tests.test_handoff import REPORT # noqa: E402 + +#: A marker in the report's text that must never reach disk in plaintext. +MARKER = "Type the triage note" + + +@pytest.fixture() +def env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[dict[str, str]]: + for name in ( + at_rest.OPT_OUT_ENV, + at_rest.MODE_ENV, + at_rest.ENCRYPT_ENV, + crypto.ENV_KEY, + sealed_set.RECORDING_ENV_KEY, + "OPENADAPT_POLICY", + "OPENADAPT_RECEIPT", + "OPENADAPT_SEAL_KEY", + ): + monkeypatch.delenv(name, raising=False) + home = tmp_path / "seal-home" + monkeypatch.setenv("OPENADAPT_SEAL_HOME", str(home)) + monkeypatch.setenv(at_rest.HOME_ENV, str(tmp_path / "at-rest-home")) + at_rest._reset_for_tests() + yield {"OPENADAPT_SEAL_HOME": str(home)} + at_rest._reset_for_tests() + + +def _report_bytes() -> bytes: + return json.dumps(REPORT, indent=2).encode("utf-8") + + +def _sealed_run(root: Path) -> Path: + run = root / "run-handoff-1" + with sealed_set.writing(run, "run", crypto.resolve_key(None)): + sealed_set.write_bytes(run / "report.json", _report_bytes()) + assert sealed_set.is_sealed(run) + return run + + +def _plain_run(root: Path) -> Path: + run = root / "run-handoff-1" + run.mkdir(parents=True) + (run / "report.json").write_bytes(_report_bytes()) + return run + + +def _statement(receipt: dict[str, Any]) -> dict[str, Any]: + envelope = receipt["envelope"] if r.is_receipt_card(receipt) else receipt + return json.loads(base64.b64decode(envelope["payload"])) + + +def _without_salts(statement: dict[str, Any]) -> dict[str, Any]: + """The statement with its salted commitments left out (salts are random).""" + predicate = dict(statement["predicate"]) + predicate.pop("disclosure", None) + return {**statement, "predicate": predicate} + + +def _registry(signer: Any) -> list[r.RoleKey]: + return r.parse_registry( + { + "schema": r.REGISTRY_SCHEMA, + "keys": [{**signer.registry_entry(), "role": "this_computer"}], + } + ) + + +def _assert_no_plaintext_leak(run: Path) -> None: + opened = sealed_set.open_set(run) + opened.verify_all() + for path in run.rglob("*"): + if not path.is_file(): + continue + rel = path.relative_to(run).as_posix() + kind = sealed_set.classify("run", rel) + if kind is not None and kind.classification == "structural": + continue + assert MARKER.encode() not in path.read_bytes(), rel + + +@pytest.mark.parametrize("public", [False, True]) +def test_a_strict_run_gets_the_same_receipt_and_a_handoff_that_verifies( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + env: dict[str, str], + public: bool, +) -> None: + signer = signer_for(Path(env["OPENADAPT_SEAL_HOME"])) + + plain = _plain_run(tmp_path / "plain") + note = receipt_after_run(plain, env=env) + assert note is not None and note.startswith("receipt:"), note + + monkeypatch.setenv(at_rest.MODE_ENV, "strict") + at_rest._reset_for_tests() + assert at_rest.strict() + sealed = _sealed_run(tmp_path / "sealed") + note = receipt_after_run(sealed, env={**env, at_rest.MODE_ENV: "strict"}) + assert note is not None and note.startswith("receipt:"), note + + # The receipt files the docs allow in plaintext are plaintext; the report + # is not. + assert (sealed / r.RECEIPT_FILE).is_file() + assert not (sealed / "report.json").is_file() + _assert_no_plaintext_leak(sealed) + + # Same statement whether the run is encrypted or not. + plain_receipt = h.receipt_for_run(plain, public=public) + sealed_receipt = h.receipt_for_run(sealed, public=public) + assert _without_salts(_statement(sealed_receipt)) == _without_salts( + _statement(plain_receipt) + ) + assert _statement(sealed_receipt)["subject"][0]["digest"]["sha256"] == ( + hashlib.sha256(_report_bytes()).hexdigest() + ) + if public: + # The card is sealed with the run on disk and opened in memory; it + # opens the same fields either way. + assert (sealed / f"{r.CARD_FILE}.enc").is_file() + assert not (sealed / r.CARD_FILE).exists() + assert sorted(sealed_receipt["openings"]) == sorted(plain_receipt["openings"]) + + # get_handoff through the tool the bridge calls, then verify_handoff. + tools = HandoffTools() + result = {"outcome": "done", "run_id": sealed.name, "mode": "production"} + doc = tools.get( + sealed.name, + public=public, + result_for=lambda _run_id: result, + run_dir_for=lambda _run_id: sealed, + ) + verdict = h.verify_handoff(doc, _registry(signer)) + assert verdict.ok, verdict.to_dict() + assert verdict.integrity == "intact" + assert verdict.outcome == "VERIFIED" + assert verdict.payload["bound"] is True + + # Building the handoff wrote nothing new in plaintext. + _assert_no_plaintext_leak(sealed) + + +def test_a_strict_run_without_its_key_refuses_instead_of_reading_ciphertext( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, env: dict[str, str] +) -> None: + monkeypatch.setenv(at_rest.MODE_ENV, "strict") + at_rest._reset_for_tests() + sealed = _sealed_run(tmp_path / "sealed") + assert receipt_after_run(sealed, env={**env, at_rest.MODE_ENV: "strict"}) + # Plant ciphertext where a plaintext receipt is expected: the handoff + # refuses; it never passes the bytes on. + (sealed / r.RECEIPT_FILE).write_bytes(b'{"ciphertext": "AAAA"}') + with pytest.raises(BridgeError, match="no handoff for this run"): + HandoffTools().get( + sealed.name, + public=False, + result_for=lambda _run_id: {"outcome": "done"}, + run_dir_for=lambda _run_id: sealed, + ) From 14d05b44d33021181434375019d35ce9341d442a Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 15:05:36 -0500 Subject: [PATCH 2/4] fix(handoff): keep receipt.json readable without the at-rest key; test strict runs through the bridge receipt_for_run reads receipt.json as it is again (plaintext on disk, no key needed) and uses the sealed set only for the sealed public card. New tests: no-key strict run (receipt travels, card refuses clearly), a strict sealed run through the bridge's get_handoff, and the encrypted tutorial card opening the same fields. The e2e fixture's report now has a change ledger and effect evidence, so its receipt is VERIFIED as the test expects (it said UNKNOWN: incomplete_write_coverage). --- CAPABILITIES.md | 2 +- ...2agent-protocol-adapter-openadapt-agent.md | 2 +- capabilities/CAPABILITIES.md.sha256 | 2 +- llms-full.txt | 2 +- .../tests/test_handoff_at_rest_bridge.py | 105 ++++++++++++++++++ packages/agent/tests/test_handoff_e2e.py | 22 +++- packages/flow/docs/A2A.md | 6 +- packages/flow/docs/HANDOFF_RECEIPTS.md | 4 +- packages/flow/openadapt_flow/handoff.py | 17 ++- packages/flow/tests/test_handoff_at_rest.py | 60 +++++++++- 10 files changed, 205 insertions(+), 17 deletions(-) create mode 100644 packages/agent/tests/test_handoff_at_rest_bridge.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 77817229e2..d18406d225 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -358,7 +358,7 @@ improvising or retrying when something is off. | Admit a draft by a person, an admitter key, or an agent under a person-signed policy, including self-admission when the policy allows it | Released | Unit tests | [JIT_ADMISSION.md](packages/flow/docs/JIT_ADMISSION.md) | | MCP server: your agent decides what to enter, OpenAdapt makes the entry and checks it | Released | Synthetic sandbox | `openadapt-agent`, [packages/agent](packages/agent/README.md) | | Agent-to-agent handoffs: when one agent hands a result to another, the run's signed receipt (`record/run/v1`) goes with it (`openadapt handoff send`, inline, detached beside a file, or POSTed to a webhook), and the receiver checks it against keys it pins (`openadapt handoff verify`). The verdict gives the signer role from the receiver's registry, integrity, checks passed and not checked, and "confirmed in the other party's system" lines; it always says a valid signature proves who signed, not that the claim is true, binds the payload as the receipt's `payload` subject (re-signed by the run's own key; other bytes or no payload subject are refused), and counts a confirmation as independent only when it was read from the other party's system. Over MCP, `serve --handoffs` adds `get_handoff` and `verify_handoff`. The private openings never travel | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Unit tests over receipts from Flow's own writer and the shared `record/run/v1` confirmation vectors and the shared payload vectors (good, tampered, unknown signer, bound, mismatched and missing payload, detached file, local webhook); MCP and A2A end to end with the stubbed run process; a two-party test of 20 handoffs over HTTP (0 false accepts, 0 true rejects); one real headless MockMed run handed off over the CLI and checked against the receiver's own record ([benchmark/handoff_real_run](packages/flow/benchmark/handoff_real_run/README.md)); `--ledger` tested against #2415's `HandoffLedger` | `openadapt handoff`, `openadapt_flow/handoff.py`, [HANDOFFS.md](packages/flow/docs/HANDOFFS.md), draft format [HANDOFF_RECEIPTS.md](packages/flow/docs/HANDOFF_RECEIPTS.md) | -| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact when Flow wrote one (sandbox runs have none, and the text part says why; strict at-rest runs carry theirs, read through the sealed run), a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; a real strict-mode sealed run folder whose receipt and card go through `get_handoff` and `verify_handoff`; a simulated sandbox run refused over MCP and A2A; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](packages/flow/docs/A2A.md) | +| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact when Flow wrote one (sandbox runs have none, and the text part says why; strict at-rest runs carry theirs, the card opened through the sealed run), a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; a strict-mode sealed run folder (stubbed Flow process, real sealed set and receipt hook) whose receipt and card go through the bridge's `get_handoff` and `verify_handoff`; a simulated sandbox run refused over MCP and A2A; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](packages/flow/docs/A2A.md) | | Teach over MCP: an agent does a new task once through OpenAdapt; the run is read back, compiled and admitted (a person confirms the record check; the agent admits only under a person-signed policy), and becomes a tool it calls with no model calls. Web, and Windows, macOS, Linux, RDP and Citrix with a person approving each save | On main ([#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed over MCP, and through the real RDP and Citrix backends); a native Cocoa app with SQLite through `MacOSBackend`, taught, confirmed, admitted under a signed policy and called (canary and taught run `VERIFIED`, 0 model calls; [teach_desktop](packages/flow/benchmark/teach_desktop/README.md)) | `openadapt-agent serve --teach`, [packages/agent](packages/agent/README.md#teach-a-new-workflow-from-your-agent) | | Turn a read-only browser task into a tool for the coding agent you already use: `openadapt setup` registers the MCP server and a skill in Claude Code, Cursor, Codex and Gemini CLI (idempotent, `--dry-run`, `--undo`); `openadapt setup --app deploy.yaml --verify verify.yaml` sets the agent up to teach saves in one web, desktop, RDP or Citrix app instead, each read back from the system of record. Read-only teaching runs only where a guard stops writes before they leave (the browser); `serve --teach-browser --config` naming a desktop, RDP or Citrix app is refused; the agent does the task once through `teach_start`/`teach_act`/`teach_finish`, the task must end in a download, the file is checked (columns, a column between two inputs or equal to one, fewest rows), the compiled steps are replayed once with no model, and the agent gets a `taught_` tool that downloads a checked file with new inputs. The browser sends no POST, PUT, PATCH or DELETE and stays on one site; a compiled run stops when a control is missing, matches more than one element, or is relabelled | Released ([#1502](https://github.com/OpenAdaptAI/OpenAdapt/pull/1502)) | Real headless Chromium on the local example portal (scripted MCP client, in CI); a real Claude Code agent taught the export from the guide's prompt and called the tool with new dates (2026-10-24, one run) | `openadapt setup`, `openadapt-agent serve --teach-browser`, [FIRST_TOOL.md](packages/flow/docs/FIRST_TOOL.md) | | Verify any agent's own writes: `openadapt verify` reads the system of record before and after a write, against a contract the operator owns (REST, FHIR, SQL, GraphQL), and returns a verified receipt (`openadapt.effect-receipt/v1`) or a refusal (`REFUTED`, `UNCERTAIN`), never an unverified success. Python SDK (`openadapt.verify`, which is `openadapt_flow.verifier`: `begin_write`, `verify_write`, `verified_write`) wraps a write in any agent framework; the MCP server (`openadapt verify serve`) offers `verify_begin`, `verify_check` and `verify_recheck` to any MCP client | Released ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589)) | Synthetic (MockMed's fault server over real HTTP: correct write, wrong record, not saved, saved twice, unreadable store) | `openadapt verify`, [VERIFY_WRITES.md](packages/flow/docs/VERIFY_WRITES.md) | diff --git a/capabilities/10-computer-use-agents/0070-a2a-agent2agent-protocol-adapter-openadapt-agent.md b/capabilities/10-computer-use-agents/0070-a2a-agent2agent-protocol-adapter-openadapt-agent.md index eba941347e..7816b2d4ee 100644 --- a/capabilities/10-computer-use-agents/0070-a2a-agent2agent-protocol-adapter-openadapt-agent.md +++ b/capabilities/10-computer-use-agents/0070-a2a-agent2agent-protocol-adapter-openadapt-agent.md @@ -1 +1 @@ -| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact when Flow wrote one (sandbox runs have none, and the text part says why; strict at-rest runs carry theirs, read through the sealed run), a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; a real strict-mode sealed run folder whose receipt and card go through `get_handoff` and `verify_handoff`; a simulated sandbox run refused over MCP and A2A; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](packages/flow/docs/A2A.md) | +| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact when Flow wrote one (sandbox runs have none, and the text part says why; strict at-rest runs carry theirs, the card opened through the sealed run), a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; a strict-mode sealed run folder (stubbed Flow process, real sealed set and receipt hook) whose receipt and card go through the bridge's `get_handoff` and `verify_handoff`; a simulated sandbox run refused over MCP and A2A; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](packages/flow/docs/A2A.md) | diff --git a/capabilities/CAPABILITIES.md.sha256 b/capabilities/CAPABILITIES.md.sha256 index a1c810d801..979d60cfee 100644 --- a/capabilities/CAPABILITIES.md.sha256 +++ b/capabilities/CAPABILITIES.md.sha256 @@ -1 +1 @@ -4f48ad227eb6272e3c9fe873e843d7ddb7aef7636814952d0a010b91a045e50a +7b00a15c4e8f4f60a1869f08c356683525ba7221fa413db050e074b08a09f3e7 diff --git a/llms-full.txt b/llms-full.txt index 97ce8b9951..42bb313eb5 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -529,7 +529,7 @@ improvising or retrying when something is off. | Admit a draft by a person, an admitter key, or an agent under a person-signed policy, including self-admission when the policy allows it | Released | Unit tests | [JIT_ADMISSION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/JIT_ADMISSION.md) | | MCP server: your agent decides what to enter, OpenAdapt makes the entry and checks it | Released | Synthetic sandbox | `openadapt-agent`, [packages/agent](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/agent/README.md) | | Agent-to-agent handoffs: when one agent hands a result to another, the run's signed receipt (`record/run/v1`) goes with it (`openadapt handoff send`, inline, detached beside a file, or POSTed to a webhook), and the receiver checks it against keys it pins (`openadapt handoff verify`). The verdict gives the signer role from the receiver's registry, integrity, checks passed and not checked, and "confirmed in the other party's system" lines; it always says a valid signature proves who signed, not that the claim is true, binds the payload as the receipt's `payload` subject (re-signed by the run's own key; other bytes or no payload subject are refused), and counts a confirmation as independent only when it was read from the other party's system. Over MCP, `serve --handoffs` adds `get_handoff` and `verify_handoff`. The private openings never travel | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Unit tests over receipts from Flow's own writer and the shared `record/run/v1` confirmation vectors and the shared payload vectors (good, tampered, unknown signer, bound, mismatched and missing payload, detached file, local webhook); MCP and A2A end to end with the stubbed run process; a two-party test of 20 handoffs over HTTP (0 false accepts, 0 true rejects); one real headless MockMed run handed off over the CLI and checked against the receiver's own record ([benchmark/handoff_real_run](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/handoff_real_run/README.md)); `--ledger` tested against #2415's `HandoffLedger` | `openadapt handoff`, `openadapt_flow/handoff.py`, [HANDOFFS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFFS.md), draft format [HANDOFF_RECEIPTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HANDOFF_RECEIPTS.md) | -| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact when Flow wrote one (sandbox runs have none, and the text part says why; strict at-rest runs carry theirs, read through the sealed run), a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; a real strict-mode sealed run folder whose receipt and card go through `get_handoff` and `verify_handoff`; a simulated sandbox run refused over MCP and A2A; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/A2A.md) | +| A2A (Agent2Agent) protocol adapter: `openadapt agent serve --a2a` serves compiled workflows as A2A 1.0 skills with the official `a2a-sdk` (`openadapt[a2a]`): Agent Card at `/.well-known/agent-card.json`, JSON-RPC and HTTP+JSON, runs as tasks with status updates, the run's receipt as a handoff artifact when Flow wrote one (sandbox runs have none, and the text part says why; strict at-rest runs carry theirs, the card opened through the sealed run), a `verify_handoff` skill, and the draft extension `https://openadapt.ai/extensions/handoff-receipt/v1`. Every call passes the MCP server's gate; person confirmations are not served; only `done` is completed. Loopback by default, a bearer token anywhere else, browser `Origin` and unknown `Host` refused | On main ([#2414](https://github.com/OpenAdaptAI/OpenAdapt/pull/2414)) | Synthetic: the official `a2a-sdk` 1.3.1 client against the server over HTTP on 127.0.0.1, with a governed run whose Flow process is stubbed and whose receipt Flow's writer signs; a strict-mode sealed run folder (stubbed Flow process, real sealed set and receipt hook) whose receipt and card go through the bridge's `get_handoff` and `verify_handoff`; a simulated sandbox run refused over MCP and A2A; the official A2A TCK (a2aproject/a2a-tck at 5e6f37c): 110 automated checks passed and 11 failed, MUST 76.0%. The failures are 10 SDK-scenario tests that expect the TCK's own scripted agent, and the SDK's error Content-Type ([benchmark/a2a_tck](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/a2a_tck/README.md)) | `openadapt_flow/agent/a2a_server.py`, [A2A.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/A2A.md) | | Teach over MCP: an agent does a new task once through OpenAdapt; the run is read back, compiled and admitted (a person confirms the record check; the agent admits only under a person-signed policy), and becomes a tool it calls with no model calls. Web, and Windows, macOS, Linux, RDP and Citrix with a person approving each save | On main ([#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed over MCP, and through the real RDP and Citrix backends); a native Cocoa app with SQLite through `MacOSBackend`, taught, confirmed, admitted under a signed policy and called (canary and taught run `VERIFIED`, 0 model calls; [teach_desktop](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/teach_desktop/README.md)) | `openadapt-agent serve --teach`, [packages/agent](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/agent/README.md#teach-a-new-workflow-from-your-agent) | | Turn a read-only browser task into a tool for the coding agent you already use: `openadapt setup` registers the MCP server and a skill in Claude Code, Cursor, Codex and Gemini CLI (idempotent, `--dry-run`, `--undo`); `openadapt setup --app deploy.yaml --verify verify.yaml` sets the agent up to teach saves in one web, desktop, RDP or Citrix app instead, each read back from the system of record. Read-only teaching runs only where a guard stops writes before they leave (the browser); `serve --teach-browser --config` naming a desktop, RDP or Citrix app is refused; the agent does the task once through `teach_start`/`teach_act`/`teach_finish`, the task must end in a download, the file is checked (columns, a column between two inputs or equal to one, fewest rows), the compiled steps are replayed once with no model, and the agent gets a `taught_` tool that downloads a checked file with new inputs. The browser sends no POST, PUT, PATCH or DELETE and stays on one site; a compiled run stops when a control is missing, matches more than one element, or is relabelled | Released ([#1502](https://github.com/OpenAdaptAI/OpenAdapt/pull/1502)) | Real headless Chromium on the local example portal (scripted MCP client, in CI); a real Claude Code agent taught the export from the guide's prompt and called the tool with new dates (2026-10-24, one run) | `openadapt setup`, `openadapt-agent serve --teach-browser`, [FIRST_TOOL.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/FIRST_TOOL.md) | | Verify any agent's own writes: `openadapt verify` reads the system of record before and after a write, against a contract the operator owns (REST, FHIR, SQL, GraphQL), and returns a verified receipt (`openadapt.effect-receipt/v1`) or a refusal (`REFUTED`, `UNCERTAIN`), never an unverified success. Python SDK (`openadapt.verify`, which is `openadapt_flow.verifier`: `begin_write`, `verify_write`, `verified_write`) wraps a write in any agent framework; the MCP server (`openadapt verify serve`) offers `verify_begin`, `verify_check` and `verify_recheck` to any MCP client | Released ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589)) | Synthetic (MockMed's fault server over real HTTP: correct write, wrong record, not saved, saved twice, unreadable store) | `openadapt verify`, [VERIFY_WRITES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_WRITES.md) | diff --git a/packages/agent/tests/test_handoff_at_rest_bridge.py b/packages/agent/tests/test_handoff_at_rest_bridge.py new file mode 100644 index 0000000000..57cfadba09 --- /dev/null +++ b/packages/agent/tests/test_handoff_at_rest_bridge.py @@ -0,0 +1,105 @@ +"""``get_handoff`` through the bridge for a run encrypted at rest (strict mode). + +The Flow process is stubbed, but it leaves what a strict run leaves: a sealed +run folder whose report is ciphertext on disk, and the receipt written by the +same hook the CLI calls after a run (``receipt_after_run``). +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +pytest.importorskip("cryptography") + +from conftest import FlowCliStub # noqa: E402 +from test_handoff_e2e import WRITE_REPORT_RESULTS, _registry # noqa: E402 + +import openadapt_agent.runner as runner_mod # noqa: E402 +from openadapt_flow import at_rest, crypto, sealed_set # noqa: E402 +from openadapt_flow import handoff as h # noqa: E402 +from openadapt_flow.agent.bridge import AgentBridge # noqa: E402 +from openadapt_flow.agent.handoff_tools import HandoffTools # noqa: E402 +from openadapt_flow.offline_seal import signer_for # noqa: E402 +from openadapt_flow.receipt_record import receipt_after_run # noqa: E402 + + +class SealedRunStub(FlowCliStub): + """`openadapt-flow run` under strict at rest, stubbed: a sealed run folder.""" + + def __init__(self, env: dict[str, str], **kwargs): + super().__init__(**kwargs) + self.env = env + self.notes: list[str | None] = [] + + def __call__(self, cmd, *args, **kwargs): + import subprocess + + self.calls.append(list(cmd)) + run_dir = Path(cmd[cmd.index("--run-dir") + 1]) + with sealed_set.writing(run_dir, "run", crypto.resolve_key(None)): + sealed_set.write_text(run_dir / "report.json", json.dumps(self.report)) + self.notes.append(receipt_after_run(run_dir, env=self.env)) + return subprocess.CompletedProcess(cmd, self.exit_code, stdout="", stderr="") + + +@pytest.fixture() +def strict_env(tmp_path, monkeypatch): + for name in ( + at_rest.OPT_OUT_ENV, + at_rest.ENCRYPT_ENV, + crypto.ENV_KEY, + sealed_set.RECORDING_ENV_KEY, + "OPENADAPT_POLICY", + "OPENADAPT_RECEIPT", + "OPENADAPT_SEAL_KEY", + ): + monkeypatch.delenv(name, raising=False) + env = { + "OPENADAPT_SEAL_HOME": str(tmp_path / "seal-home"), + at_rest.HOME_ENV: str(tmp_path / "at-rest-home"), + at_rest.MODE_ENV: "strict", + } + for key, value in env.items(): + monkeypatch.setenv(key, value) + at_rest._reset_for_tests() + yield env + at_rest._reset_for_tests() + + +@pytest.mark.parametrize("public", [False, True]) +def test_a_strict_run_hands_off_its_receipt_through_the_bridge( + monkeypatch, bundles_root, runner_config, success_report, strict_env, public +): + signer = signer_for(Path(strict_env["OPENADAPT_SEAL_HOME"])) + report = dict( + success_report, + results=WRITE_REPORT_RESULTS, + started_at="2026-11-21T01:02:03Z", + change_ledger=[], + ) + stub = SealedRunStub(strict_env, exit_code=0, report=report) + monkeypatch.setattr(runner_mod, "_run_flow_process", stub) + bridge = AgentBridge(bundles_root, runner_config, allow_run=True, mode="production") + bridge.handoffs = HandoffTools(registry=_registry(signer), signer=signer) + + workflow = next(iter(bridge.catalog)) + result = bridge.dispatch( + "run_workflow", + {"workflow": workflow, "inputs": {"note": "x"}, "request_id": "strict-0001"}, + ) + assert stub.notes and str(stub.notes[0]).startswith("receipt:"), stub.notes + run_dir = Path(runner_config.runs_dir) / result["run_id"] + assert sealed_set.is_sealed(run_dir) + assert not (run_dir / "report.json").exists() + + doc = bridge.dispatch("get_handoff", {"run_id": result["run_id"], "public": public}) + verdict = h.verify_handoff(doc, _registry(signer)) + assert verdict.ok, verdict.to_dict() + assert verdict.payload["bound"] is True + # The receipt says what the run's report says; never upgraded. + assert verdict.outcome == "VERIFIED" + assert doc["payload"]["content"]["outcome"] == result["outcome"] + sealed_set.open_set(run_dir).verify_all() diff --git a/packages/agent/tests/test_handoff_e2e.py b/packages/agent/tests/test_handoff_e2e.py index bad8b30006..e59330a063 100644 --- a/packages/agent/tests/test_handoff_e2e.py +++ b/packages/agent/tests/test_handoff_e2e.py @@ -56,6 +56,20 @@ "ok": True, "effect_verified": True, "postconditions_ok": True, + # A write is confirmed only with a declared effect contract and its + # evidence (as in Flow's tests/test_handoff.py); without them the + # receipt says UNKNOWN (effect_not_declared). + "effect_contract_hashes": ["sha256:" + "a" * 64], + "effect_evidence": [ + { + "effect_contract_hash": "sha256:" + "a" * 64, + "substrate": "api", + "initial_verdict": "confirmed", + "final_verdict": "confirmed", + "observed_effect": "present", + "verification_tier": 1, + } + ], }, ] @@ -91,7 +105,13 @@ def signer(): @pytest.fixture() def bridge(monkeypatch, bundles_root, runner_config, success_report, signer): - report = dict(success_report, results=WRITE_REPORT_RESULTS, started_at="2026-11-21T01:02:03Z") + report = dict( + success_report, + results=WRITE_REPORT_RESULTS, + started_at="2026-11-21T01:02:03Z", + # No change ledger means unknown write coverage: the receipt says UNKNOWN. + change_ledger=[], + ) monkeypatch.setattr( runner_mod, "_run_flow_process", ReceiptWritingStub(signer, exit_code=0, report=report) ) diff --git a/packages/flow/docs/A2A.md b/packages/flow/docs/A2A.md index 5d4105304a..73c8f3876a 100644 --- a/packages/flow/docs/A2A.md +++ b/packages/flow/docs/A2A.md @@ -53,8 +53,10 @@ Encrypted runs do have one. With `OPENADAPT_FLOW_AT_REST=strict` the run folder is encrypted at rest, and the receipt is still written: `receipt.json` stays plaintext beside the run, and the public card (`receipt.card.json`) is sealed with it ([phi_at_rest.md](phi_at_rest.md), "Receipts"). `get_handoff` -reads both through the run's sealed set, in memory, and writes nothing. The -signed statement is the same as for a plaintext run of the same report. +reads `receipt.json` as it is, so it needs no at-rest key. With `public`, it +opens the card through the run's sealed set, in memory; without the key that +refuses. It writes nothing. The signed statement is the same as for a +plaintext run of the same report. ## Same rules as MCP diff --git a/packages/flow/docs/HANDOFF_RECEIPTS.md b/packages/flow/docs/HANDOFF_RECEIPTS.md index 366ddccc73..0b2e9dc3bd 100644 --- a/packages/flow/docs/HANDOFF_RECEIPTS.md +++ b/packages/flow/docs/HANDOFF_RECEIPTS.md @@ -157,8 +157,8 @@ These rules apply to the verdict: `openadapt agent serve --handoffs` adds two read-only tools: - **`get_handoff {run_id}`** returns the run's public result as the payload, - with its receipt attached. It reads an encrypted run's receipt through the - run's sealed set. It refuses sandbox runs and runs without a receipt + with its receipt attached. For an encrypted run it opens the public card + through the run's sealed set. It refuses sandbox runs and runs without a receipt ([A2A.md](A2A.md), "When a run has no receipt"). - **`verify_handoff {handoff}`** returns the verdict, checked against the server's pinned keys. diff --git a/packages/flow/openadapt_flow/handoff.py b/packages/flow/openadapt_flow/handoff.py index 7b8e264be4..c10680f83f 100644 --- a/packages/flow/openadapt_flow/handoff.py +++ b/packages/flow/openadapt_flow/handoff.py @@ -296,9 +296,10 @@ def bind_payload( def receipt_for_run(run_dir: Path, *, public: bool = False) -> dict[str, Any]: """Read a run's ``receipt.json`` (or its public card) for attaching. - Reads through the run's sealed set, so an encrypted run works: the - receipt is plaintext on disk there, the card is sealed with the run and - is opened in memory only. Nothing is written. + ``receipt.json`` is plaintext on disk even beside an encrypted run, so it + is read directly and needs no at-rest key. An encrypted run seals its + card with the run, so the card is read through the run's sealed set, in + memory only (it needs the key). Nothing is written. """ from openadapt_types import receipt as r @@ -306,9 +307,13 @@ def receipt_for_run(run_dir: Path, *, public: bool = False) -> dict[str, Any]: path = Path(run_dir) / (r.CARD_FILE if public else r.RECEIPT_FILE) try: - if not sealed_set.is_file(path): - raise FileNotFoundError(path.name) - return _check_receipt_document(_loads_strict(sealed_set.read_bytes(path))) + if public and sealed_set.is_sealed_path(path): + if not sealed_set.is_file(path): + raise FileNotFoundError(path.name) + raw: str | bytes = sealed_set.read_bytes(path) + else: + raw = path.read_text("utf-8") + return _check_receipt_document(_loads_strict(raw)) except FileNotFoundError: raise HandoffError(f"no {path.name} in that run folder") from None except (OSError, UnicodeDecodeError, ValueError) as exc: diff --git a/packages/flow/tests/test_handoff_at_rest.py b/packages/flow/tests/test_handoff_at_rest.py index 85d5c0b899..21c947818b 100644 --- a/packages/flow/tests/test_handoff_at_rest.py +++ b/packages/flow/tests/test_handoff_at_rest.py @@ -26,7 +26,7 @@ from openadapt_flow.agent.bridge import BridgeError # noqa: E402 from openadapt_flow.agent.handoff_tools import HandoffTools # noqa: E402 from openadapt_flow.offline_seal import signer_for # noqa: E402 -from openadapt_flow.receipt_record import receipt_after_run # noqa: E402 +from openadapt_flow.receipt_record import public_reveal, receipt_after_run # noqa: E402 from tests.test_handoff import REPORT # noqa: E402 #: A marker in the report's text that must never reach disk in plaintext. @@ -168,7 +168,39 @@ def test_a_strict_run_gets_the_same_receipt_and_a_handoff_that_verifies( _assert_no_plaintext_leak(sealed) -def test_a_strict_run_without_its_key_refuses_instead_of_reading_ciphertext( +def test_a_strict_run_without_the_at_rest_key_still_hands_off_its_receipt( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, env: dict[str, str] +) -> None: + signer = signer_for(Path(env["OPENADAPT_SEAL_HOME"])) + monkeypatch.setenv(at_rest.MODE_ENV, "strict") + at_rest._reset_for_tests() + sealed = _sealed_run(tmp_path / "sealed") + assert receipt_after_run(sealed, env={**env, at_rest.MODE_ENV: "strict"}) + + # Another computer, or this one after the key moved: no at-rest key. + monkeypatch.setenv(at_rest.HOME_ENV, str(tmp_path / "empty-at-rest-home")) + at_rest._reset_for_tests() + + def get(public: bool) -> dict[str, Any]: + return HandoffTools().get( + sealed.name, + public=public, + result_for=lambda _run_id: {"outcome": "done", "mode": "production"}, + run_dir_for=lambda _run_id: sealed, + ) + + # receipt.json is plaintext on disk: it travels without the key. + verdict = h.verify_handoff(get(False), _registry(signer)) + assert verdict.ok and verdict.outcome == "VERIFIED" + # The card is sealed with the run: without the key, a clear refusal. + with pytest.raises(BridgeError) as caught: + get(True) + assert str(caught.value) == ( + "no handoff for this run: receipt.card.json is not a readable receipt" + ) + + +def test_a_tampered_receipt_in_a_strict_run_is_refused_not_passed_on( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, env: dict[str, str] ) -> None: monkeypatch.setenv(at_rest.MODE_ENV, "strict") @@ -185,3 +217,27 @@ def test_a_strict_run_without_its_key_refuses_instead_of_reading_ciphertext( result_for=lambda _run_id: {"outcome": "done"}, run_dir_for=lambda _run_id: sealed, ) + + +def test_an_encrypted_tutorial_run_s_card_opens_the_same_fields( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, env: dict[str, str] +) -> None: + """The card opens the program name only for the synthetic tutorial, and + reads the signed report to decide; an encrypted report must decide the same.""" + report = json.dumps({"governed_approval_source": "openadapt-flow-tutorial"}) + summary = json.dumps({"provenance": "synthetic-tutorial"}) + + plain = tmp_path / "plain" + plain.mkdir() + (plain / "report.json").write_text(report) + (plain / "run-summary.json").write_text(summary) + + monkeypatch.setenv(at_rest.MODE_ENV, "strict") + at_rest._reset_for_tests() + sealed = tmp_path / "sealed" + with sealed_set.writing(sealed, "run", crypto.resolve_key(None)): + sealed_set.write_text(sealed / "report.json", report) + sealed_set.write_text(sealed / "run-summary.json", summary) + + assert public_reveal(plain) == ["flow_version", "program_name"] + assert public_reveal(sealed) == public_reveal(plain) From 42ae43575e6a408e4482c9f8a4848fb66e0206cb Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 30 Nov 2026 18:19:19 -0500 Subject: [PATCH 3/4] fix(handoff): bind each receipt to its run and decide eligibility from the stored mode A receipt is attached only when its signed report.json digest matches the run's own report, read through the sealed set; a receipt from another run signed by the same key is refused (receipt_run_mismatch), and an encrypted run without its at-rest key is refused (run_report_unreadable). get_handoff now requires the stored run record to be finished with an attended or production mode that matches the result. RunService results carry the record's original mode, so an interrupted or refreshed run reopened under another mode keeps its sandbox provenance. --- packages/agent/tests/test_handoff_sandbox.py | 103 +++++++++++++++++ packages/flow/docs/A2A.md | 16 ++- packages/flow/openadapt_flow/agent/bridge.py | 1 + .../openadapt_flow/agent/handoff_tools.py | 31 +++++- packages/flow/openadapt_flow/agent/service.py | 11 +- packages/flow/openadapt_flow/handoff.py | 82 +++++++++++++- packages/flow/tests/test_handoff_at_rest.py | 104 +++++++++++++++--- 7 files changed, 320 insertions(+), 28 deletions(-) diff --git a/packages/agent/tests/test_handoff_sandbox.py b/packages/agent/tests/test_handoff_sandbox.py index 8cbf0a0915..685b0db32b 100644 --- a/packages/agent/tests/test_handoff_sandbox.py +++ b/packages/agent/tests/test_handoff_sandbox.py @@ -34,6 +34,7 @@ from openadapt_agent.sandbox import SANDBOX_WORKFLOW, SandboxEngine # noqa: E402 from openadapt_flow import handoff as h # noqa: E402 from openadapt_flow.agent.handoff_tools import ( # noqa: E402 + NO_PROVENANCE, SANDBOX_NO_RECEIPT, HandoffTools, ) @@ -113,3 +114,105 @@ def test_a2a_sandbox_artifact_says_why_it_has_no_receipt(sandbox_bridge): assert not [p for p in parts if p.HasField("raw") and p.media_type == h.MEDIA_TYPE] texts = [p.text for p in parts if p.HasField("text")] assert any(SANDBOX_NO_RECEIPT in text for text in texts), texts + + +# -- provenance comes from the stored record, not the server's current mode -- + + +def _production_bridge(bundles_root, runs, signer): + bridge = AgentBridge( + bundles_root, RunnerConfig(runs_dir=runs), allow_run=True, mode="production" + ) + bridge.handoffs = HandoffTools(registry=_registry(signer), signer=signer) + return bridge + + +def _orphan(bridge, run_id, mode): + """A run record left running by a process that is gone (pid None).""" + store = bridge.service.store + record = store.new_record( + request_id=f"req-{run_id}", workflow=SANDBOX_WORKFLOW, mode="sandbox", run_id=run_id + ) + if mode is None: + del record["mode"] + else: + record["mode"] = mode + record["pid"] = None + store.write(record) + return record + + +@pytest.mark.parametrize("public", [False, True]) +def test_a_finished_sandbox_run_reopened_under_production_never_carries_a_receipt( + sandbox_bridge, bundles_root, signer, public +): + result = _run(sandbox_bridge, "sandbox-restart-1") + runs = Path(sandbox_bridge.runner_config.runs_dir) + _plant_receipt(runs / result["run_id"], signer) + production = _production_bridge(bundles_root, runs, signer) + reopened = production.dispatch("get_run", {"run_id": result["run_id"], "wait_seconds": 0}) + assert reopened["mode"] == "sandbox" + with pytest.raises(BridgeError) as caught: + production.dispatch("get_handoff", {"run_id": result["run_id"], "public": public}) + assert SANDBOX_NO_RECEIPT in str(caught.value) + + +def test_an_interrupted_sandbox_run_recovered_under_production_keeps_its_mode( + bundles_root, tmp_path, signer +): + runs = tmp_path / "runs" + production = _production_bridge(bundles_root, runs, signer) + run_id = "run-sandbox-orphan-1" + _orphan(production, run_id, "sandbox") + # A genuine receipt for this run's own report sits in its folder. + _plant_receipt(runs / run_id, signer) + # Restarted under production: get_run rebuilds the interrupted result + # from the stored record, which ran in sandbox mode. + result = production.dispatch("get_run", {"run_id": run_id, "wait_seconds": 0}) + assert result["reason"] == "interrupted" and result["mode"] == "sandbox" + stored = production.service.store.read(run_id) + assert stored["state"] == "finished" and stored["mode"] == "sandbox" + assert stored["result"]["mode"] == "sandbox" + with pytest.raises(BridgeError) as caught: + production.dispatch("get_handoff", {"run_id": run_id}) + assert SANDBOX_NO_RECEIPT in str(caught.value) + + +@pytest.mark.parametrize("mode", [None, "staging"]) +def test_a_run_record_without_a_known_mode_never_carries_a_receipt( + bundles_root, tmp_path, signer, mode +): + runs = tmp_path / "runs" + production = _production_bridge(bundles_root, runs, signer) + run_id = "run-no-provenance-1" + _orphan(production, run_id, mode) + _plant_receipt(runs / run_id, signer) + production.dispatch("get_run", {"run_id": run_id, "wait_seconds": 0}) + stored = production.service.store.read(run_id) + assert stored["state"] == "finished" and stored.get("mode") == mode + with pytest.raises(BridgeError) as caught: + production.dispatch("get_handoff", {"run_id": run_id}) + assert NO_PROVENANCE in str(caught.value) + + +@pytest.mark.parametrize( + "record", + [ + None, + {"state": "running", "mode": "production"}, + {"state": "finished", "mode": "attended"}, # disagrees with the result + {"state": "finished"}, + ], +) +def test_get_handoff_needs_a_finished_record_whose_mode_matches(tmp_path, signer, record): + run = tmp_path / "run-direct-1" + _plant_receipt(run, signer) + with pytest.raises(BridgeError) as caught: + HandoffTools(registry=_registry(signer), signer=signer).get( + run.name, + public=False, + result_for=lambda _run_id: {"outcome": "done", "mode": "production"}, + run_dir_for=lambda _run_id: run, + record_for=lambda _run_id: record, + ) + assert NO_PROVENANCE in str(caught.value) diff --git a/packages/flow/docs/A2A.md b/packages/flow/docs/A2A.md index 87864e34aa..44ea4413cb 100644 --- a/packages/flow/docs/A2A.md +++ b/packages/flow/docs/A2A.md @@ -92,10 +92,18 @@ Encrypted runs do have one. With `OPENADAPT_FLOW_AT_REST=strict` the run folder is encrypted at rest, and the receipt is still written: `receipt.json` stays plaintext beside the run, and the public card (`receipt.card.json`) is sealed with it ([phi_at_rest.md](phi_at_rest.md), "Receipts"). `get_handoff` -reads `receipt.json` as it is, so it needs no at-rest key. With `public`, it -opens the card through the run's sealed set, in memory; without the key that -refuses. It writes nothing. The signed statement is the same as for a -plaintext run of the same report. +reads `receipt.json` as it is. With `public`, it opens the card through the +run's sealed set, in memory. Either way it attaches the receipt only when the +receipt's signed `report.json` digest matches this run's own report, read +through the sealed set; a receipt from another run, even one signed by the +same key, is refused. That check needs the at-rest key, so without it +`get_handoff` refuses. It writes nothing. The signed statement is the same +as for a plaintext run of the same report. + +Whether a run may carry a receipt at all is decided from its stored run +record: the record must be finished and name `attended` or `production` as +the mode it ran under. A runs folder reopened under another mode keeps each +run's original mode, and a record with no known mode gets no receipt. ## Same rules as MCP diff --git a/packages/flow/openadapt_flow/agent/bridge.py b/packages/flow/openadapt_flow/agent/bridge.py index feb0a20bff..8d34fe3f79 100644 --- a/packages/flow/openadapt_flow/agent/bridge.py +++ b/packages/flow/openadapt_flow/agent/bridge.py @@ -880,6 +880,7 @@ def _handoff_dispatch(self, name: str, arguments: dict) -> dict: "get_run", {"run_id": run_id, "wait_seconds": 0} ), run_dir_for=self._safe_run_dir, + record_for=self.service.store.read, ) def _list_workflows(self) -> dict: diff --git a/packages/flow/openadapt_flow/agent/handoff_tools.py b/packages/flow/openadapt_flow/agent/handoff_tools.py index 2ae21bd31e..d662dcea4c 100644 --- a/packages/flow/openadapt_flow/agent/handoff_tools.py +++ b/packages/flow/openadapt_flow/agent/handoff_tools.py @@ -13,7 +13,7 @@ from __future__ import annotations from pathlib import Path -from typing import Any, Callable, Optional, Sequence +from typing import Any, Callable, Mapping, Optional, Sequence _READ_ONLY = { "readOnlyHint": True, @@ -36,6 +36,14 @@ "proof about a real system. The result's mode says sandbox." ) +#: The modes whose runs may carry a receipt, read from the run's stored +#: record (the mode it ran under), never from this server's current mode. +RECEIPT_MODES = ("attended", "production") +NO_PROVENANCE = ( + "the run's stored record doesn't show a finished run in attended or " + "production mode, so its receipt isn't attached" +) + class HandoffTools: """The handoff tool surface over one bridge's runs folder.""" @@ -142,17 +150,36 @@ def get( public: bool, result_for: Callable[[str], dict[str, Any]], run_dir_for: Callable[[str], Path], + record_for: Callable[[str], Optional[Mapping[str, Any]]], ) -> dict[str, Any]: + """The run's result with its receipt attached, or a refusal. + + ``record_for`` returns the run's stored record. Whether a receipt may + travel is decided from that record's own mode, after ``result_for`` + has settled the run: a sandbox, unfinished or unlabelled record never + gets one, whatever mode this server runs in now. + """ from openadapt_flow.agent.bridge import BridgeError from openadapt_flow.handoff import HandoffError, make_handoff, receipt_for_run result = result_for(run_id) - if result.get("mode") == "sandbox": + if result.get("mode") == "sandbox" or result.get("sandbox"): # Checked before any run folder is read, so a sandbox run that # somehow has a receipt file still never travels with one. raise BridgeError(f"no handoff for this run: {SANDBOX_NO_RECEIPT}") if result.get("outcome") == "running": raise BridgeError("the run is still running; it has no receipt yet") + record = record_for(run_id) + if not isinstance(record, Mapping): + raise BridgeError(f"no handoff for this run: {NO_PROVENANCE}") + if record.get("mode") == "sandbox": + raise BridgeError(f"no handoff for this run: {SANDBOX_NO_RECEIPT}") + if ( + record.get("state") != "finished" + or record.get("mode") not in RECEIPT_MODES + or record.get("mode") != result.get("mode") + ): + raise BridgeError(f"no handoff for this run: {NO_PROVENANCE}") try: receipt = receipt_for_run(run_dir_for(run_id), public=public) return make_handoff( diff --git a/packages/flow/openadapt_flow/agent/service.py b/packages/flow/openadapt_flow/agent/service.py index bf385391d8..00468fb61c 100644 --- a/packages/flow/openadapt_flow/agent/service.py +++ b/packages/flow/openadapt_flow/agent/service.py @@ -26,7 +26,7 @@ from openadapt_flow.agent.approval import report_approval, waiting_for_person from openadapt_flow.agent.cards import WorkflowCard, coerce_inputs, input_problems -from openadapt_flow.agent.contract import REASONS, build_result, reason_for_run +from openadapt_flow.agent.contract import MODES, REASONS, build_result, reason_for_run from openadapt_flow.agent.runner import FlowRunner, is_safe_run_id from openadapt_flow.agent.runs import RunStore, pid_alive from openadapt_flow.readback_ladder import checked_how_from_report @@ -295,12 +295,19 @@ def __init__( def _result( self, reason: str, record: Mapping[str, Any], **extra: Any ) -> dict[str, Any]: + # A result says the mode its run was recorded under, never this + # server's: a runs folder reopened under another mode (an interrupted + # run rebuilt on restart, a reviewed run refreshed) keeps its sandbox + # provenance. Only a record with no recognized mode falls back to this + # server's mode for display; get_handoff decides from the stored + # record and refuses one whose mode is missing or unknown. + stored_mode = record.get("mode") return build_result( reason, workflow=record.get("workflow"), run_id=record.get("run_id"), request_id=record.get("request_id"), - mode=self.mode, + mode=stored_mode if stored_mode in MODES else self.mode, **extra, ) diff --git a/packages/flow/openadapt_flow/handoff.py b/packages/flow/openadapt_flow/handoff.py index c10680f83f..81b316d883 100644 --- a/packages/flow/openadapt_flow/handoff.py +++ b/packages/flow/openadapt_flow/handoff.py @@ -36,6 +36,7 @@ import base64 import hashlib +import hmac import json from dataclasses import dataclass, field from pathlib import Path @@ -57,7 +58,19 @@ class HandoffError(ValueError): - """A handoff that can't be built (never a verification result).""" + """A handoff that can't be built (never a verification result). + + ``code`` is a closed reason when the refusal has one (``RUN_BINDING_CODES``). + """ + + def __init__(self, message: str = "", *, code: Optional[str] = None) -> None: + super().__init__(message) + self.code = code + + +#: Why a run's receipt was not attached: it names another run's report, or +#: this run's report could not be read to check that it doesn't. +RUN_BINDING_CODES = ("receipt_run_mismatch", "run_report_unreadable") def _sha256(data: bytes) -> str: @@ -293,13 +306,67 @@ def bind_payload( return bound +def _report_subject(receipt: Mapping[str, Any]) -> Optional[str]: + """The SHA-256 the receipt's signed statement names for ``report.json``.""" + from openadapt_types import receipt as r + + envelope = receipt["envelope"] if r.is_receipt_card(receipt) else receipt + try: + statement = r.loads_strict( + base64.b64decode(str(envelope["payload"]), validate=True) + ) + subjects = [ + s + for s in statement.get("subject") or [] + if isinstance(s, Mapping) and s.get("name") == "report.json" + ] + except (AttributeError, KeyError, TypeError, ValueError): + return None + if len(subjects) != 1 or not isinstance(subjects[0].get("digest"), Mapping): + return None + digest = subjects[0]["digest"].get("sha256") + return digest if isinstance(digest, str) else None + + +def _check_run_binding(run_dir: Path, receipt: Mapping[str, Any]) -> None: + """Refuse a receipt that is not over this run's own ``report.json``. + + A receipt in the folder can be genuine, signed by this computer's key, + and still belong to another run. Its signed ``report.json`` subject must + equal the SHA-256 of this run's report. An encrypted run's report is read + through its sealed set, whose authenticated index checks the bytes; with + no at-rest key nothing authenticates the report, so the receipt is + refused rather than attached unbound. Fails closed. + """ + from openadapt_flow import sealed_set + + signed = _report_subject(receipt) + path = Path(run_dir) / "report.json" + try: + if path.is_symlink(): + raise OSError("report.json is a symlink") + raw = sealed_set.read_bytes(path) + except Exception: # noqa: BLE001 - no readable report, no binding + raise HandoffError( + "this run's report can't be read (an encrypted run needs its " + "at-rest key), so its receipt can't be matched to the run", + code="run_report_unreadable", + ) from None + if signed is None or not hmac.compare_digest(signed, _sha256(raw)): + raise HandoffError( + "the receipt in that run folder is for a different run's report", + code="receipt_run_mismatch", + ) + + def receipt_for_run(run_dir: Path, *, public: bool = False) -> dict[str, Any]: """Read a run's ``receipt.json`` (or its public card) for attaching. - ``receipt.json`` is plaintext on disk even beside an encrypted run, so it - is read directly and needs no at-rest key. An encrypted run seals its - card with the run, so the card is read through the run's sealed set, in - memory only (it needs the key). Nothing is written. + ``receipt.json`` is plaintext on disk even beside an encrypted run. An + encrypted run seals its card with the run, so the card is read through + the run's sealed set, in memory only. Either way the receipt must be over + this run's own report (:func:`_check_run_binding`), which for an + encrypted run needs the at-rest key. Nothing is written. """ from openadapt_types import receipt as r @@ -313,13 +380,15 @@ def receipt_for_run(run_dir: Path, *, public: bool = False) -> dict[str, Any]: raw: str | bytes = sealed_set.read_bytes(path) else: raw = path.read_text("utf-8") - return _check_receipt_document(_loads_strict(raw)) + receipt = _check_receipt_document(_loads_strict(raw)) except FileNotFoundError: raise HandoffError(f"no {path.name} in that run folder") from None except (OSError, UnicodeDecodeError, ValueError) as exc: if isinstance(exc, HandoffError): raise raise HandoffError(f"{path.name} is not a readable receipt") from None + _check_run_binding(Path(run_dir), receipt) + return receipt # -- verification ---------------------------------------------------------------- @@ -722,6 +791,7 @@ def detached_path(payload_path: Path) -> Path: "SCHEMA", "VERDICT_SCHEMA", "RECEIVER_STATES", + "RUN_BINDING_CODES", "ReceiverRecord", "Verdict", "bind_payload", diff --git a/packages/flow/tests/test_handoff_at_rest.py b/packages/flow/tests/test_handoff_at_rest.py index 21c947818b..bc0346ed71 100644 --- a/packages/flow/tests/test_handoff_at_rest.py +++ b/packages/flow/tests/test_handoff_at_rest.py @@ -54,25 +54,30 @@ def env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Iterator[dict[str, s at_rest._reset_for_tests() -def _report_bytes() -> bytes: - return json.dumps(REPORT, indent=2).encode("utf-8") +def _report_bytes(**changes: Any) -> bytes: + return json.dumps({**REPORT, **changes}, indent=2).encode("utf-8") -def _sealed_run(root: Path) -> Path: - run = root / "run-handoff-1" +def _sealed_run(root: Path, name: str = "run-handoff-1", **changes: Any) -> Path: + run = root / name with sealed_set.writing(run, "run", crypto.resolve_key(None)): - sealed_set.write_bytes(run / "report.json", _report_bytes()) + sealed_set.write_bytes(run / "report.json", _report_bytes(**changes)) assert sealed_set.is_sealed(run) return run -def _plain_run(root: Path) -> Path: - run = root / "run-handoff-1" +def _plain_run(root: Path, name: str = "run-handoff-1", **changes: Any) -> Path: + run = root / name run.mkdir(parents=True) - (run / "report.json").write_bytes(_report_bytes()) + (run / "report.json").write_bytes(_report_bytes(**changes)) return run +def _finished(mode: str = "production") -> Any: + """``record_for``: the stored record of a finished run in ``mode``.""" + return lambda run_id: {"run_id": run_id, "state": "finished", "mode": mode} + + def _statement(receipt: dict[str, Any]) -> dict[str, Any]: envelope = receipt["envelope"] if r.is_receipt_card(receipt) else receipt return json.loads(base64.b64decode(envelope["payload"])) @@ -157,6 +162,7 @@ def test_a_strict_run_gets_the_same_receipt_and_a_handoff_that_verifies( public=public, result_for=lambda _run_id: result, run_dir_for=lambda _run_id: sealed, + record_for=_finished(), ) verdict = h.verify_handoff(doc, _registry(signer)) assert verdict.ok, verdict.to_dict() @@ -168,10 +174,11 @@ def test_a_strict_run_gets_the_same_receipt_and_a_handoff_that_verifies( _assert_no_plaintext_leak(sealed) -def test_a_strict_run_without_the_at_rest_key_still_hands_off_its_receipt( +def test_a_strict_run_without_the_at_rest_key_refuses_its_receipt( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, env: dict[str, str] ) -> None: - signer = signer_for(Path(env["OPENADAPT_SEAL_HOME"])) + """Without the key nothing authenticates which run's report the plaintext + receipt.json is over, so it is refused rather than attached unbound.""" monkeypatch.setenv(at_rest.MODE_ENV, "strict") at_rest._reset_for_tests() sealed = _sealed_run(tmp_path / "sealed") @@ -187,11 +194,19 @@ def get(public: bool) -> dict[str, Any]: public=public, result_for=lambda _run_id: {"outcome": "done", "mode": "production"}, run_dir_for=lambda _run_id: sealed, + record_for=_finished(), ) - # receipt.json is plaintext on disk: it travels without the key. - verdict = h.verify_handoff(get(False), _registry(signer)) - assert verdict.ok and verdict.outcome == "VERIFIED" + # receipt.json is plaintext on disk, but the report it must match is not + # readable without the key: refused, with a closed code underneath. + with pytest.raises(BridgeError) as caught: + get(False) + assert str(caught.value).startswith( + "no handoff for this run: this run's report can't be read" + ) + with pytest.raises(h.HandoffError) as direct: + h.receipt_for_run(sealed) + assert direct.value.code == "run_report_unreadable" # The card is sealed with the run: without the key, a clear refusal. with pytest.raises(BridgeError) as caught: get(True) @@ -214,10 +229,71 @@ def test_a_tampered_receipt_in_a_strict_run_is_refused_not_passed_on( HandoffTools().get( sealed.name, public=False, - result_for=lambda _run_id: {"outcome": "done"}, + result_for=lambda _run_id: {"outcome": "done", "mode": "production"}, run_dir_for=lambda _run_id: sealed, + record_for=_finished(), + ) + + +@pytest.mark.parametrize("strict", [False, True]) +@pytest.mark.parametrize("public", [False, True]) +def test_a_receipt_from_another_run_signed_by_the_same_key_is_refused( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + env: dict[str, str], + strict: bool, + public: bool, +) -> None: + """Two runs, two different reports, one key: each receipt is genuine, but + a receipt moved into the other run's folder must not travel with it.""" + signer = signer_for(Path(env["OPENADAPT_SEAL_HOME"])) + run_env = dict(env) + if strict: + monkeypatch.setenv(at_rest.MODE_ENV, "strict") + at_rest._reset_for_tests() + run_env[at_rest.MODE_ENV] = "strict" + make = _sealed_run if strict else _plain_run + first = make(tmp_path / "a", "run-a", run_id="run-a") + second = make( + tmp_path / "b", + "run-b", + run_id="run-b", + started_at="2026-11-22T04:05:06Z", + workflow_name="Another workflow", + ) + for run in (first, second): + assert receipt_after_run(run, env=run_env) + + def get(run: Path) -> dict[str, Any]: + return HandoffTools(signer=signer).get( + run.name, + public=public, + result_for=lambda _run_id: {"outcome": "done", "mode": "production"}, + run_dir_for=lambda _run_id: run, + record_for=_finished(), ) + # Each run's own receipt hands off and verifies. + for run in (first, second): + assert h.verify_handoff(get(run), _registry(signer)).ok + + # Move run-b's receipt into run-a's folder: same key, wrong run. + name = r.CARD_FILE if public else r.RECEIPT_FILE + if public and strict: + # The card is sealed with the run: move it through the sealed set. + sealed_set.write_bytes(first / name, sealed_set.read_bytes(second / name)) + else: + (first / name).write_bytes((second / name).read_bytes()) + with pytest.raises(BridgeError) as caught: + get(first) + assert str(caught.value) == ( + "no handoff for this run: the receipt in that run folder is for a " + "different run's report" + ) + with pytest.raises(h.HandoffError) as direct: + h.receipt_for_run(first, public=public) + assert direct.value.code == "receipt_run_mismatch" + def test_an_encrypted_tutorial_run_s_card_opens_the_same_fields( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, env: dict[str, str] From 33fcca14d2e03102c29289f808e8f0ad7344e1e7 Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 1 Dec 2026 10:09:53 -0500 Subject: [PATCH 4/4] ci: add the at-rest handoff test file to the shard durations --- scripts/ci/flow_test_durations.json | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/ci/flow_test_durations.json b/scripts/ci/flow_test_durations.json index f2748f5217..87afa399be 100644 --- a/scripts/ci/flow_test_durations.json +++ b/scripts/ci/flow_test_durations.json @@ -339,6 +339,7 @@ "tests/test_halt_cleanup.py": 1.1, "tests/test_halt_detail.py": 10.1, "tests/test_halt_learn_loop.py": 1.0, + "tests/test_handoff_at_rest.py": 0.8, "tests/test_hard_invariants.py": 0.3, "tests/test_hardening_flywheel.py": 19.0, "tests/test_harness2_adapter.py": 9.2,