diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 1dcbe2088b..40f274149d 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -161,6 +161,8 @@ improvising or retrying when something is off. | Compile one or more demonstrations into a deterministic program | Released | Real app (OpenEMR referral, 62 timed runs) | `openadapt-flow record`, `compile`; [packages/flow](packages/flow/README.md) | | Try the three acts on a real app: `openadapt quickstart --app openemr` runs the certified OpenEMR referral program in Docker, five referrals at once checked in OpenEMR's record, then a possible duplicate stopped before saving; without Docker or a clone it says so and exits 2 | On main ([#1431](https://github.com/OpenAdaptAI/OpenAdapt/pull/1431)) | Real app (local OpenEMR 8.0.0.3, synthetic patients) | `openadapt quickstart --app openemr`; [docs/quickstart](docs/quickstart/README.md#on-a-real-app---app-openemr) | | Run the quickstart without taking over the screen: `uvx --python 3.12 openadapt@latest quickstart` keeps the browser hidden and shows progress in the terminal (`--watch` shows the window, `--open` opens the Seal page), runs a run whose starting screen never settles once more in a new folder and otherwise says why in plain words, and reruns itself with Python 3.12 under `uvx` on an unsupported Python. Flow's page settle hands a page that draws no frames (a covered headed window) to the screenshot check instead of waiting out its timeout | On main ([#2365](https://github.com/OpenAdaptAI/OpenAdapt/pull/2365)) | Unit tests; headless terminal captures at 80, 120 and 250 columns for Terminal.app, WezTerm and iTerm2 settings; a headed covered-window run is not reproduced here | `openadapt quickstart`; [openadapt/quickstart](openadapt/quickstart/__init__.py), [_page_quiescence.py](packages/flow/openadapt_flow/backends/_page_quiescence.py) | +| Check each quickstart save the way a person would: on MockMed the program is compiled from a copy of the demonstration with no database snapshots, certified under the shipped `screen-write` policy (record-write without the idempotency-key rule; the run's at-most-once ledger holds off repeated saves), and run with the on-screen read-back as its only verifier. A run is VERIFIED only when the screen after the save shows the form closed and no error, and the reopened record shows every typed value under its label. A second run on an app that drops the note but still says it saved stops at the reopened record (0 of 1 typed values), is not marked done, and is left for a person; nothing reads the app's database | PR [#2883](https://github.com/OpenAdaptAI/OpenAdapt/pull/2883) | Synthetic (MockMed; real headless runs on macOS, unit tests with fakes and a plain-output snapshot) | `openadapt quickstart`; [screen_check.py](openadapt/quickstart/screen_check.py), [screen-write.yaml](packages/flow/openadapt_flow/policies/screen-write.yaml) | +| See a crash and a restart in the quickstart: on MockMed, Act 3 runs a batch of two new notes in a separate worker process, stops it with SIGKILL after note 1's save is checked, and restarts the batch with the same on-disk write ledger (`IdempotencyLedger`); the replayer finds note 1's key and sends no save for it (its report: idempotent replay, 0 actions), then saves note 2; each patient's chart is reopened in a browser afterwards and the encounters showing the note are counted. Each note has its own copy of the clinic app, as in Act 2 | On main ([#2840](https://github.com/OpenAdaptAI/OpenAdapt/pull/2840)) | Synthetic (MockMed; real headless runs on macOS, unit tests with fakes) | `openadapt quickstart`; [restart.py](openadapt/quickstart/restart.py) | | Classify common local edits without a person (select-all, Enter in a field or dropdown, an in-form tab, an informational dialog's dismiss), only when the recording's network capture shows no write and a runtime check confirms only the expected change | Released ([#1366](https://github.com/OpenAdaptAI/OpenAdapt/pull/1366)) | Synthetic; OpenEMR referral recording re-admitted offline (violations 12 to 1 under `permissive`) | [LOCAL_EDIT_CLASSIFICATION.md](packages/flow/docs/design/LOCAL_EDIT_CLASSIFICATION.md), `compiler/local_edit.py` | | Keep the empty search result a person confirmed through (a duplicate check's "No matches were found.") as an exact check after the click that opens the dialog and again right before Confirm, so a run whose dialog lists a match stops before the save; only fixed-vocabulary search-result statements shown once, never text with a name or search term, and a confirmation dialog without one is noted in `compile_notes.json` | On main | Real app frames (an OpenEMR referral recording, compiled offline) | `compiler/empty_result_guard.py` | | Mine that check in any language: induction keeps the one line a named dialog adds (not its title or buttons, not a question, no typed value or number) when two or more demonstrations whose typed values all differ show the same line, refuses when the demonstrations disagree on a mined check instead of copying the first one's, and qualification then needs a business-rule run that halts at it | On main | Synthetic (a search dialog recorded in Chromium by the real recorder, German statement, real OCR) | `compiler/empty_result_guard.py`, `compiler/induction.py` | @@ -174,8 +176,9 @@ improvising or retrying when something is off. | Fill a multi-step browser form or quote wizard from an intake record, stop for an operator on a prefill that disagrees with the intake or a question the intake does not answer (decided in a Chrome side panel), submit once, and give every typed, selected or kept field a read-back verdict: `passed`, `failed` or `not_checked`. A field it cannot read back is `not_checked`, never passed; such a submit ends `readback_incomplete` with no receipt | On main, prototype; not on PyPI until Flow 3.4.0 ([#2308](https://github.com/OpenAdaptAI/OpenAdapt/pull/2308)) | Synthetic only. Four quote portals built separately from the layer, 32 scored cases, pre-registered: 6 correct submissions, 0 wrong values submitted, 0 verified (every field on the one workable portal is `not_checked`, because its summary is plain text). The surface cannot see iframe or shadow-DOM forms or fill type-aheads, so 3 of 4 portals submitted nothing. Estimator, session-timeout and type-ahead traps were never reached. Rule proposals from repeated operator answers (`form_tx/learning.py`) had no measured effect: none qualified ([RESULTS](packages/flow/benchmark/form_tx_heldout_run/RESULTS.md)) | `openadapt_flow/form_tx/`, [FORM_TX.md](packages/flow/docs/FORM_TX.md) | | Never retry an uncertain save (`RECONCILIATION_REQUIRED`) | Released | Synthetic (fault server) | [VERIFICATION.md](packages/flow/docs/VERIFICATION.md) | | One check-level scale, 0 to 5, from "unchecked" to "counterparty confirmed" | Released | Unit tests | `openadapt_flow/check_level.py` | -| One receipt word per check, the same on every path: `VERIFIED` only at level 3 (a separate session) or 4 (the system of record), always with the basis that produced the evidence (`separate_session`, `system_api`, `activity_log`, `db_frame` or `owned_connection`); `SHOWN` for an acting-screen re-read, `CONFIRMED` for the counterparty, `ATTESTED` for an operator and `RECORDED` for the rest. `VERIFIED` means "as of the read-back time the read-back showed this value", not "persisted". 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` | +| One receipt word per check, the same on every path: `VERIFIED` always names the basis that earned it. The baseline is the check a careful person does after a save, basis `post_save_screen` (level 1): the form left edit mode, no error is shown, and every intended value was read on the screen, field by field, and matched; a banner or toast alone never earns it, and a value that was not read means `RECORDED`. The same check after reopening the record is `reopened_record` (level 2); stronger evidence is a stronger basis on the same word (`separate_session` or `fresh_reload` at level 3; `system_api`, `activity_log`, `db_frame` or `owned_connection` at level 4). A run or policy can require a stronger level: under `Regulated` a screen check is not `VERIFIED`. `CONFIRMED` is the counterparty, `ATTESTED` an operator and `RECORDED` 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, `tx` receipts and the kernel's receipt bridge 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). `openadapt.wrap` takes its word from the Contract's read-back receipt; a declared `checked_how` alone is `RECORDED`. In a browser the runtime records each save's post-save screen check (counts and flags only); on a backend that can't read the page, a run checked only on its screen gets a `RECORDED` receipt. When reloading can't repeat the save, the runtime then reopens the record on a fresh page load and reads every value again (`reopened_record`, level 2); a value the browser showed but the server didn't keep stops the run. Where it can't reopen safely, the check stays at level 1 and such a value can pass. Older receipts that say `SHOWN` still verify and are labelled as the older format. Receipts without the block still verify | On main | Unit tests (shared cases across the types ladder, the run receipt block, the kernel bridge and `openadapt.wrap`; signed `record/run/v1` vectors checked by the Python and JavaScript verifiers); real headless runs on MockMed, compiled without database access: a clean save's receipt is `VERIFIED` / `reopened_record`, and a save whose note the server dropped stops at the reopen (`packages/flow/benchmark/post_save_screen/`). Not yet shown on a held-out app | `openadapt_types/check_level.py`, `openadapt_types/evidence_scope.py`, `openadapt_flow/evidence_basis.py`, `openadapt_kernel/receipt_bridge.py`, `openadapt/wrap_sdk.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 +237,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 +338,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 +360,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`, signed (A2A 1.0 section 8.4, EdDSA JWS by the Seal key that signs receipts; no server if the key can't be opened), 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, 2026-11-30, sandbox server with `--a2a-tck-scenarios`): 121 automated checks passed, 0 failed, 142 skipped (gRPC, push, cancel, auth scenarios), MUST 78.7% because the TCK counts skipped and manual checks as not passed ([benchmark/a2a_tck](packages/flow/benchmark/a2a_tck/README.md)); a second implementation, the A2A JavaScript SDK 1.3.0, ran a workflow and verified a second key's handoff over JSON-RPC and HTTP+JSON and checked the card signature with independent JWS and RFC 8785 libraries, all on one computer ([benchmark/a2a_interop](packages/flow/benchmark/a2a_interop/README.md)); the card signature verified by the `a2a-sdk` verifier and refused when changed, unpinned or relabelled (the TCK leaves signing to manual checks) | `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) | @@ -377,6 +382,7 @@ improvising or retrying when something is off. | Task ledger per job: rules locked when the job opens and enforced on every run, item status set only from OpenAdapt's own results, and yes-or-no questions a person answers on the phone or in Desktop, including when a run stops | Released ([#1332](https://github.com/OpenAdaptAI/OpenAdapt/pull/1332)) | Synthetic (30-item MockMed worklist, scripted agent, no model calls) | MCP tools `open_job`, `get_job`, `add_items`, `record_evidence`, `ask_user`, `get_answer`, `change_constraint`, `close_job`; [Track a long job](packages/agent/README.md#track-a-long-job) | | Limit a teaching agent to the declared task on every teach path (`compile_agent`, `compile-agent`, teach over MCP, the airbag guard): typed text must be a declared value, links and browser requests to other origins are refused, writes are checked before they are sent, and the record is read back before a draft exists. Injected instructions in record notes, banners, tooltips, alt text and server responses are blocked or caught on MockMed through each path (scripted agent; a live-model mode is off by default). Self-repair refuses a control that leaves the app | Released ([#1359](https://github.com/OpenAdaptAI/OpenAdapt/pull/1359), [#1386](https://github.com/OpenAdaptAI/OpenAdapt/pull/1386)) | Synthetic | `openadapt_flow.teach_scope`, [THREAT_MODEL.md](packages/flow/docs/THREAT_MODEL.md) | | Teach authorization: a person signs what a teaching agent may do (task, origins, inputs, the one write, forbidden actions and controls) with their approver key, and every teach path is bound to it or refused. Verified with the approver roster's own verifier, so an unknown, removed or wrong key, an unpinned root, a changed statement or another task refuses. Admission of every JIT draft needs one (`teach_auth_not_recorded` otherwise), as do an agent-demonstrated fix's approval and self-repair of an agent-taught program; browser-teach writes are bound to it, and the airbag handoff's drafts are refused | On main ([#1436](https://github.com/OpenAdaptAI/OpenAdapt/pull/1436)) | Synthetic (real approver keys, real roster, real admission) | `openadapt-flow teach-authorization`, [TEACH_AUTHORIZATION.md](packages/flow/docs/TEACH_AUTHORIZATION.md) | +| Self-serve admission in two questions: `openadapt wrap --person NAME` asks once before run 1 ("Allow it?", with the origins, the values passed, the declared text and the one record it may save) and records the answer as a signed teach authorization, creating the person's approver key and roster on first use with no passphrase prompt (derived from the local key unless `OPENADAPT_JIT_KEY_PASSPHRASE` is set); inputs are bound by digest. After run 1 it asks once "Admit this program if its test save verifies?" for the record checks, step review and admission, and admits only after the canary is VERIFIED. Run 1's save gate allows the one save after the right-record check and refuses a second. A retry reuses the permission while it covers the run; unpinned, only a roster rooted in the person's own key is trusted | In PR | Synthetic (real approver keys, roster and statements in unit tests; the CLI wiring with a stubbed signer); the staging run is pending | [WRAP_PUBLISH.md](packages/flow/docs/WRAP_PUBLISH.md#4-wrap-the-task), `openadapt_flow.wrap.person_authorization`, `openadapt_flow.wrap.person_prompts` | | Compile an agent's first verified run from a prompt (`compile-agent`), and a code-as-action authoring agent | Released ([#1277](https://github.com/OpenAdaptAI/OpenAdapt/pull/1277), [#1305](https://github.com/OpenAdaptAI/OpenAdapt/pull/1305)); the agent harness behind it runs on every backend, on main ([#1283](https://github.com/OpenAdaptAI/OpenAdapt/pull/1283)) | Synthetic | `compile-agent` | | An agent records a native app by control: `AuthoringSession.observe()` lists the app's controls from UI Automation (Windows), Accessibility (macOS) or AT-SPI (Linux), each with its element identity (role, name, ancestry, window, process); a click by node is re-read before input and refused when that identity changed, has a twin in the window, or the tree was cut short. `compile-agent --config` and `serve-execute --config` build the app from the deployment's backend | [#1870](https://github.com/OpenAdaptAI/OpenAdapt/pull/1870) | Windows 11 Pro x64, Patient Notes (in-tree WinForms, synthetic SQLite): 11 of 11 identities re-read equal, five clicks recorded by UIA locator, the note read back from SQLite; macOS Calculator, read only: 20 of 20; Linux, the GTK3 fixture in Xvfb: recorded by control, the effect file as oracle, a click on one of two identical buttons refused ([benchmark/native_authoring](packages/flow/benchmark/native_authoring/README.md)) | `openadapt_flow/authoring.py`, `authoring_tree()` on each native backend | | Score harness optimizers (Harness², Meta-Harness) on GUI tasks with the record read-back as the reward, with full trace export | Released ([#1299](https://github.com/OpenAdaptAI/OpenAdapt/pull/1299), [#1300](https://github.com/OpenAdaptAI/OpenAdapt/pull/1300), [#1301](https://github.com/OpenAdaptAI/OpenAdapt/pull/1301)) | Synthetic (scripted proposer) | `benchmark/harness/harness2/` (source checkout) | @@ -406,6 +412,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/README.md b/README.md index d314c3f497..0beff5768e 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ safe_agent = openadapt.wrap(your_agent, wal=WriteAheadSagaLog("session.wal")) ### Try It in 30 Seconds -Run the quickstart against a bundled demo app (no account or API key required). It shows a task once, runs the compiled program and checks the save in the app's database, then stops the runner partway through a batch and restarts it: the restart skips the note that was already saved and saves only the next one. +Run the quickstart against a bundled demo app (no account or API key required). A script records a task in a demo clinic app, OpenAdapt compiles it into a program, and the program runs three ways. A normal save is VERIFIED after OpenAdapt checks the screen and reopens the record. A save to a faulty server, which drops the note but reports success, is STOPPED for a person to check. In a batch whose runner is killed after note 1 and restarted, note 1 is skipped and each note is saved once. ```bash uvx --python 3.12 openadapt@latest quickstart diff --git a/capabilities/04-the-core-a-checked-entry-every-time/0033-check-each-quickstart-save-the-way-a-person.md b/capabilities/04-the-core-a-checked-entry-every-time/0033-check-each-quickstart-save-the-way-a-person.md new file mode 100644 index 0000000000..a0f0a69e8a --- /dev/null +++ b/capabilities/04-the-core-a-checked-entry-every-time/0033-check-each-quickstart-save-the-way-a-person.md @@ -0,0 +1 @@ +| Check each quickstart save the way a person would: on MockMed the program is compiled from a copy of the demonstration with no database snapshots, certified under the shipped `screen-write` policy (record-write without the idempotency-key rule; the run's at-most-once ledger holds off repeated saves), and run with the on-screen read-back as its only verifier. A run is VERIFIED only when the screen after the save shows the form closed and no error, and the reopened record shows every typed value under its label. A second run on an app that drops the note but still says it saved stops at the reopened record (0 of 1 typed values), is not marked done, and is left for a person; nothing reads the app's database | PR [#2883](https://github.com/OpenAdaptAI/OpenAdapt/pull/2883) | Synthetic (MockMed; real headless runs on macOS, unit tests with fakes and a plain-output snapshot) | `openadapt quickstart`; [screen_check.py](openadapt/quickstart/screen_check.py), [screen-write.yaml](packages/flow/openadapt_flow/policies/screen-write.yaml) | diff --git a/capabilities/04-the-core-a-checked-entry-every-time/0035-see-a-crash-and-a-restart-in-the-quickstart.md b/capabilities/04-the-core-a-checked-entry-every-time/0035-see-a-crash-and-a-restart-in-the-quickstart.md index 676f69c8da..73266a03de 100644 --- a/capabilities/04-the-core-a-checked-entry-every-time/0035-see-a-crash-and-a-restart-in-the-quickstart.md +++ b/capabilities/04-the-core-a-checked-entry-every-time/0035-see-a-crash-and-a-restart-in-the-quickstart.md @@ -1 +1 @@ -| See a crash and a restart in the quickstart: on MockMed, Act 3 runs a batch of two new notes in a separate worker process, stops it with SIGKILL after note 1's save is checked, and restarts the batch with the same on-disk write ledger (`IdempotencyLedger`); the replayer finds note 1's key and sends no save for it (its report: idempotent replay, 0 actions), then saves note 2; each note's database is read afterwards. Each note has its own copy of the clinic's database, as in Act 2 | On main ([#2840](https://github.com/OpenAdaptAI/OpenAdapt/pull/2840)) | Synthetic (MockMed; real headless runs on macOS, unit tests with fakes) | `openadapt quickstart`; [restart.py](openadapt/quickstart/restart.py) | +| See a crash and a restart in the quickstart: on MockMed, Act 3 runs a batch of two new notes in a separate worker process, stops it with SIGKILL after note 1's save is checked, and restarts the batch with the same on-disk write ledger (`IdempotencyLedger`); the replayer finds note 1's key and sends no save for it (its report: idempotent replay, 0 actions), then saves note 2; each patient's chart is reopened in a browser afterwards and the encounters showing the note are counted. Each note has its own copy of the clinic app, as in Act 2 | On main ([#2840](https://github.com/OpenAdaptAI/OpenAdapt/pull/2840)) | Synthetic (MockMed; real headless runs on macOS, unit tests with fakes) | `openadapt quickstart`; [restart.py](openadapt/quickstart/restart.py) | diff --git a/capabilities/CAPABILITIES.md.sha256 b/capabilities/CAPABILITIES.md.sha256 index b178c64d02..f103e8261f 100644 --- a/capabilities/CAPABILITIES.md.sha256 +++ b/capabilities/CAPABILITIES.md.sha256 @@ -1 +1 @@ -6b0c7d386eb68b516766993b4afb1ffe6a0ea4461851850db38a845a47648b81 +7cd6868b9e4d87a3b91cc56012fcb3ae35c03b2eb59ddbf3b4baaf3eafa3393f diff --git a/docs/getting-started/quickstart.md b/docs/getting-started/quickstart.md index 838f53473d..5ebec4672d 100644 --- a/docs/getting-started/quickstart.md +++ b/docs/getting-started/quickstart.md @@ -41,7 +41,7 @@ After the tutorial run, the quickstart starts a batch of two notes in a separate worker process and stops that process with SIGKILL after note 1 is saved and checked. It restarts the batch with the same write ledger on disk. The restart finds note 1 in the ledger and sends no save for it, then saves -note 2. Each note is in its database once. +note 2. Reopening each chart shows each note once. ## Run the manual demo lifecycle diff --git a/docs/quickstart/README.md b/docs/quickstart/README.md index 735899145a..facf69d3b9 100644 --- a/docs/quickstart/README.md +++ b/docs/quickstart/README.md @@ -17,30 +17,40 @@ the quickstart ran before) against the new quickstart, three rounds each, interleaved, from `scripts/quickstart_timing.py`. -## The three acts on MockMed +## The quickstart on MockMed ```bash uvx --python 3.12 openadapt@latest quickstart ``` -- **Act 1, show it once.** A demonstration in MockMed, a synthetic clinic - app, compiled into a program. -- **Act 2, run it.** The program on a new note, checked in the app's +- **Record the task, then compile a program.** A script records the task in + MockMed, a synthetic clinic app, and OpenAdapt compiles the recording. +- **Run it on a new note.** The save is checked twice: the screen after the save (the form closed, no + error shown), then the record reopened with the typed note read back under + its label. The program is compiled from a copy of the demonstration with no + database snapshots, certified under the `screen-write` policy, and run with + the on-screen read-back as its only verifier; nothing reads the app's database. -- **Act 3, stop it mid-batch, then restart.** A batch of two new notes runs +- **Run it against a faulty server.** The demo server keeps the encounter + but drops its note and still reports success. The screen after the save + looks right and shows the note; the reopened record doesn't have it. + OpenAdapt stops, doesn't mark the save done, and leaves the record for a + person to check. +- **Kill the runner mid-batch, then restart it.** A batch of two new notes runs in a separate worker process. Each note's run reserves its key in the engine's write ledger (`IdempotencyLedger`, in `restart/ledger/` under the output folder) before its first action and records the outcome after the - record check. When note 1 is saved and checked, the quickstart stops the + check. When note 1 is saved and checked, the quickstart stops the worker with SIGKILL, before note 2 starts. It then runs the batch again in its own process with the same ledger: the replayer finds note 1's key and sends no save for it (its report shows an idempotent replay with 0 - actions), and note 2 runs and saves. Last, it reads each note's database - and counts the note there. That count alone would not catch a resend: - MockMed's demo save carries a fixed key the app de-duplicates on. The - evidence that no second save was sent is note 1's restart report. Each note has its own copy of the - clinic's database, as in Act 2, because the tutorial program writes one - record per patient. `--no-restart` skips this act. + actions), and note 2 runs and saves. Last, it reopens each patient's chart + in a browser and counts the encounters showing the note. That count alone + would not catch a resend: MockMed's demo save carries a fixed key the app + de-duplicates on. The evidence that no second save was sent is note 1's + restart report. Each note has its own copy of the clinic app, as in Act 2, + because the program reads the first encounter on the chart. + `--no-restart` skips this act. ## On a real app: `--app openemr` diff --git a/llms-full.txt b/llms-full.txt index 8eb6d5d8cd..e72cdc46f8 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -75,7 +75,7 @@ safe_agent = openadapt.wrap(your_agent, wal=WriteAheadSagaLog("session.wal")) ### Try It in 30 Seconds -Run the quickstart against a bundled demo app (no account or API key required). It shows a task once, runs the compiled program and checks the save in the app's database, then stops the runner partway through a batch and restarts it: the restart skips the note that was already saved and saves only the next one. +Run the quickstart against a bundled demo app (no account or API key required). A script records a task in a demo clinic app, OpenAdapt compiles it into a program, and the program runs three ways. A normal save is VERIFIED after OpenAdapt checks the screen and reopens the record. A save to a faulty server, which drops the note but reports success, is STOPPED for a person to check. In a batch whose runner is killed after note 1 and restarted, note 1 is skipped and each note is saved once. ```bash uvx --python 3.12 openadapt@latest quickstart @@ -373,7 +373,8 @@ improvising or retrying when something is off. | Compile one or more demonstrations into a deterministic program | Released | Real app (OpenEMR referral, 62 timed runs) | `openadapt-flow record`, `compile`; [packages/flow](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/README.md) | | Try the three acts on a real app: `openadapt quickstart --app openemr` runs the certified OpenEMR referral program in Docker, five referrals at once checked in OpenEMR's record, then a possible duplicate stopped before saving; without Docker or a clone it says so and exits 2 | On main ([#1431](https://github.com/OpenAdaptAI/OpenAdapt/pull/1431)) | Real app (local OpenEMR 8.0.0.3, synthetic patients) | `openadapt quickstart --app openemr`; [docs/quickstart](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/docs/quickstart/README.md#on-a-real-app---app-openemr) | | Run the quickstart without taking over the screen: `uvx --python 3.12 openadapt@latest quickstart` keeps the browser hidden and shows progress in the terminal (`--watch` shows the window, `--open` opens the Seal page), runs a run whose starting screen never settles once more in a new folder and otherwise says why in plain words, and reruns itself with Python 3.12 under `uvx` on an unsupported Python. Flow's page settle hands a page that draws no frames (a covered headed window) to the screenshot check instead of waiting out its timeout | On main ([#2365](https://github.com/OpenAdaptAI/OpenAdapt/pull/2365)) | Unit tests; headless terminal captures at 80, 120 and 250 columns for Terminal.app, WezTerm and iTerm2 settings; a headed covered-window run is not reproduced here | `openadapt quickstart`; [openadapt/quickstart](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/openadapt/quickstart/__init__.py), [_page_quiescence.py](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/openadapt_flow/backends/_page_quiescence.py) | -| See a crash and a restart in the quickstart: on MockMed, Act 3 runs a batch of two new notes in a separate worker process, stops it with SIGKILL after note 1's save is checked, and restarts the batch with the same on-disk write ledger (`IdempotencyLedger`); the replayer finds note 1's key and sends no save for it (its report: idempotent replay, 0 actions), then saves note 2; each note's database is read afterwards. Each note has its own copy of the clinic's database, as in Act 2 | On main ([#2840](https://github.com/OpenAdaptAI/OpenAdapt/pull/2840)) | Synthetic (MockMed; real headless runs on macOS, unit tests with fakes) | `openadapt quickstart`; [restart.py](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/openadapt/quickstart/restart.py) | +| Check each quickstart save the way a person would: on MockMed the program is compiled from a copy of the demonstration with no database snapshots, certified under the shipped `screen-write` policy (record-write without the idempotency-key rule; the run's at-most-once ledger holds off repeated saves), and run with the on-screen read-back as its only verifier. A run is VERIFIED only when the screen after the save shows the form closed and no error, and the reopened record shows every typed value under its label. A second run on an app that drops the note but still says it saved stops at the reopened record (0 of 1 typed values), is not marked done, and is left for a person; nothing reads the app's database | PR [#2883](https://github.com/OpenAdaptAI/OpenAdapt/pull/2883) | Synthetic (MockMed; real headless runs on macOS, unit tests with fakes and a plain-output snapshot) | `openadapt quickstart`; [screen_check.py](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/openadapt/quickstart/screen_check.py), [screen-write.yaml](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/openadapt_flow/policies/screen-write.yaml) | +| See a crash and a restart in the quickstart: on MockMed, Act 3 runs a batch of two new notes in a separate worker process, stops it with SIGKILL after note 1's save is checked, and restarts the batch with the same on-disk write ledger (`IdempotencyLedger`); the replayer finds note 1's key and sends no save for it (its report: idempotent replay, 0 actions), then saves note 2; each patient's chart is reopened in a browser afterwards and the encounters showing the note are counted. Each note has its own copy of the clinic app, as in Act 2 | On main ([#2840](https://github.com/OpenAdaptAI/OpenAdapt/pull/2840)) | Synthetic (MockMed; real headless runs on macOS, unit tests with fakes) | `openadapt quickstart`; [restart.py](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/openadapt/quickstart/restart.py) | | Classify common local edits without a person (select-all, Enter in a field or dropdown, an in-form tab, an informational dialog's dismiss), only when the recording's network capture shows no write and a runtime check confirms only the expected change | Released ([#1366](https://github.com/OpenAdaptAI/OpenAdapt/pull/1366)) | Synthetic; OpenEMR referral recording re-admitted offline (violations 12 to 1 under `permissive`) | [LOCAL_EDIT_CLASSIFICATION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/design/LOCAL_EDIT_CLASSIFICATION.md), `compiler/local_edit.py` | | Keep the empty search result a person confirmed through (a duplicate check's "No matches were found.") as an exact check after the click that opens the dialog and again right before Confirm, so a run whose dialog lists a match stops before the save; only fixed-vocabulary search-result statements shown once, never text with a name or search term, and a confirmation dialog without one is noted in `compile_notes.json` | On main | Real app frames (an OpenEMR referral recording, compiled offline) | `compiler/empty_result_guard.py` | | Mine that check in any language: induction keeps the one line a named dialog adds (not its title or buttons, not a question, no typed value or number) when two or more demonstrations whose typed values all differ show the same line, refuses when the demonstrations disagree on a mined check instead of copying the first one's, and qualification then needs a business-rule run that halts at it | On main | Synthetic (a search dialog recorded in Chromium by the real recorder, German statement, real OCR) | `compiler/empty_result_guard.py`, `compiler/induction.py` | @@ -387,7 +388,7 @@ improvising or retrying when something is off. | Fill a multi-step browser form or quote wizard from an intake record, stop for an operator on a prefill that disagrees with the intake or a question the intake does not answer (decided in a Chrome side panel), submit once, and give every typed, selected or kept field a read-back verdict: `passed`, `failed` or `not_checked`. A field it cannot read back is `not_checked`, never passed; such a submit ends `readback_incomplete` with no receipt | On main, prototype; not on PyPI until Flow 3.4.0 ([#2308](https://github.com/OpenAdaptAI/OpenAdapt/pull/2308)) | Synthetic only. Four quote portals built separately from the layer, 32 scored cases, pre-registered: 6 correct submissions, 0 wrong values submitted, 0 verified (every field on the one workable portal is `not_checked`, because its summary is plain text). The surface cannot see iframe or shadow-DOM forms or fill type-aheads, so 3 of 4 portals submitted nothing. Estimator, session-timeout and type-ahead traps were never reached. Rule proposals from repeated operator answers (`form_tx/learning.py`) had no measured effect: none qualified ([RESULTS](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/form_tx_heldout_run/RESULTS.md)) | `openadapt_flow/form_tx/`, [FORM_TX.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/FORM_TX.md) | | Never retry an uncertain save (`RECONCILIATION_REQUIRED`) | Released | Synthetic (fault server) | [VERIFICATION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFICATION.md) | | One check-level scale, 0 to 5, from "unchecked" to "counterparty confirmed" | Released | Unit tests | `openadapt_flow/check_level.py` | -| One receipt word per check, the same on every path: `VERIFIED` only at level 3 (a separate session) or 4 (the system of record), always with the basis that produced the evidence (`separate_session`, `system_api`, `activity_log`, `db_frame` or `owned_connection`); `SHOWN` for an acting-screen re-read, `CONFIRMED` for the counterparty, `ATTESTED` for an operator and `RECORDED` for the rest. `VERIFIED` means "as of the read-back time the read-back showed this value", not "persisted". 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` | +| One receipt word per check, the same on every path: `VERIFIED` always names the basis that earned it. The baseline is the check a careful person does after a save, basis `post_save_screen` (level 1): the form left edit mode, no error is shown, and every intended value was read on the screen, field by field, and matched; a banner or toast alone never earns it, and a value that was not read means `RECORDED`. The same check after reopening the record is `reopened_record` (level 2); stronger evidence is a stronger basis on the same word (`separate_session` or `fresh_reload` at level 3; `system_api`, `activity_log`, `db_frame` or `owned_connection` at level 4). A run or policy can require a stronger level: under `Regulated` a screen check is not `VERIFIED`. `CONFIRMED` is the counterparty, `ATTESTED` an operator and `RECORDED` 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, `tx` receipts and the kernel's receipt bridge 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). `openadapt.wrap` takes its word from the Contract's read-back receipt; a declared `checked_how` alone is `RECORDED`. In a browser the runtime records each save's post-save screen check (counts and flags only); on a backend that can't read the page, a run checked only on its screen gets a `RECORDED` receipt. When reloading can't repeat the save, the runtime then reopens the record on a fresh page load and reads every value again (`reopened_record`, level 2); a value the browser showed but the server didn't keep stops the run. Where it can't reopen safely, the check stays at level 1 and such a value can pass. Older receipts that say `SHOWN` still verify and are labelled as the older format. Receipts without the block still verify | On main | Unit tests (shared cases across the types ladder, the run receipt block, the kernel bridge and `openadapt.wrap`; signed `record/run/v1` vectors checked by the Python and JavaScript verifiers); real headless runs on MockMed, compiled without database access: a clean save's receipt is `VERIFIED` / `reopened_record`, and a save whose note the server dropped stops at the reopen (`packages/flow/benchmark/post_save_screen/`). Not yet shown on a held-out app | `openadapt_types/check_level.py`, `openadapt_types/evidence_scope.py`, `openadapt_flow/evidence_basis.py`, `openadapt_kernel/receipt_bridge.py`, `openadapt/wrap_sdk.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) | @@ -571,7 +572,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`, signed (A2A 1.0 section 8.4, EdDSA JWS by the Seal key that signs receipts; no server if the key can't be opened), 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, 2026-11-30, sandbox server with `--a2a-tck-scenarios`): 121 automated checks passed, 0 failed, 142 skipped (gRPC, push, cancel, auth scenarios), MUST 78.7% because the TCK counts skipped and manual checks as not passed ([benchmark/a2a_tck](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/a2a_tck/README.md)); a second implementation, the A2A JavaScript SDK 1.3.0, ran a workflow and verified a second key's handoff over JSON-RPC and HTTP+JSON and checked the card signature with independent JWS and RFC 8785 libraries, all on one computer ([benchmark/a2a_interop](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/a2a_interop/README.md)); the card signature verified by the `a2a-sdk` verifier and refused when changed, unpinned or relabelled (the TCK leaves signing to manual checks) | `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/openadapt/quickstart/engine.py b/openadapt/quickstart/engine.py index afda903c96..f7929251fb 100644 --- a/openadapt/quickstart/engine.py +++ b/openadapt/quickstart/engine.py @@ -2,17 +2,18 @@ Every number the quickstart prints comes from here, and everything here comes from the engine's own artifacts: the recorder's ``events.jsonl``, the compiled -workflow, each run's report, the demo app's database (read out of band, at a -path the app never calls), and Act 3's write ledger. Nothing is scripted -output. - -The stages are the tutorial's own (:mod:`openadapt_flow.tutorial`): record -against MockMed's database-backed server, compile with mined record checks, -certify under ``clinical-write``, and run under the Standard profile through -the unchanged fail-closed run gate. The quickstart adds two things: the -program runs on a new note (the demonstration typed another), and the record -checks read that run's note (``bind_effect_params``) so a new note can be checked. -Act 3 (stop the runner mid-batch, restart it) is :mod:`openadapt.quickstart.restart`. +workflow, each run's report, and Act 3's write ledger. Nothing is scripted +output, and nothing reads the demo app's database. + +The demonstration is the tutorial's own (:mod:`openadapt_flow.tutorial`). It +is compiled the way a customer without database access gets it +(:mod:`openadapt.quickstart.screen_check`): each save is checked the way a +careful person checks it, on the screen after the save and then in the +record reopened. Runs go through the unchanged fail-closed run gate under the +``screen-write`` policy and the Standard profile. The program runs on a new +note (the demonstration typed another), and the check reads that run's note +(``bind_effect_params``). Act 3 (stop the runner mid-batch, restart it) is +:mod:`openadapt.quickstart.restart`. """ from __future__ import annotations @@ -27,6 +28,7 @@ from typing import TYPE_CHECKING, Any, Callable, Optional, Sequence from openadapt.quickstart.scene import MOCKMED +from openadapt.quickstart.screen_check import ScreenCheck if TYPE_CHECKING: from openadapt.quickstart.restart import RestartFacts @@ -54,7 +56,7 @@ class DemoStep: @dataclass class RunFacts: - """One run of the program, read from its own report and the database.""" + """One run of the program, read from its own report.""" index: int note: str @@ -62,12 +64,16 @@ class RunFacts: execution_outcome: str transaction_outcome: Optional[str] checked: bool + #: Records the app holds after the run, when an engine reads them (the + #: OpenEMR variant); 0 for MockMed, which is checked on screen only. records: int model_calls: int cost_usd: float effects_required: int effects_confirmed: int seconds: float + #: What the save's check read on screen, from the run's report. + check: ScreenCheck = field(default_factory=ScreenCheck) #: The engine's plain-language result for this run ("Done and checked", #: "Stopped before saving", ...), from its transaction outcome. plain_label: str = "" @@ -163,6 +169,59 @@ def report_md(self) -> Path: return self.run_dir / "REPORT.md" +@dataclass +class CatchFacts: + """The save that only looks fine: the app drops the note but says saved. + + Everything comes from the run's own report: how it ended, what the save's + screen showed, what the reopened record showed, and whether the run left + the decision to a person. + """ + + run_dir: Path + note: str + execution_outcome: str + transaction_outcome: Optional[str] + check: ScreenCheck + #: The run left a pending decision for a person. + escalated: bool + model_calls: int + seconds: float + #: The screen after the save showed the typed note (read off the screen + #: the run stopped on, before the record was reopened). + screen_showed_note: bool = False + #: That screen said the encounter was saved. + screen_said_saved: bool = False + + @property + def stopped(self) -> bool: + return self.execution_outcome == "HALTED" + + @property + def caught(self) -> bool: + """Stopped at the reopened record, not for some other reason. + + True only when the save's screen looked right (the form closed, no + error) and the reopened record was read and fell short. + """ + + return ( + self.stopped + and self.check.screen_ok + and self.check.reopened + and self.check.fields_intended > 0 + and self.check.fields_matched < self.check.fields_intended + ) + + @property + def verified(self) -> bool: + return self.execution_outcome == "VERIFIED" + + @property + def report_md(self) -> Path: + return self.run_dir / "REPORT.md" + + @dataclass class SealFacts: """Offline Seals over the verified runs' reports.""" @@ -278,53 +337,53 @@ def run_program( note: Optional[str], visible: bool, ) -> RunFacts: - """Run the compiled program once on a fresh copy of the clinic's database. + """Run the compiled program once on a fresh copy of the clinic app. - ``note`` is this run's input when the engine accepts run inputs; None - replays the demonstrated note. The facts come from the run's own report - and an out-of-band read of the database. + ``note`` is this run's input; None replays the demonstrated note. The + facts come from the run's own report: its outcome and what the save's + check read on the screen and in the reopened record. """ from openadapt_flow.plain_outcome import plain_result - from openadapt_flow.receipt import _build_tutorial_receipt, write_receipt from openadapt_flow.report import render_run_report - from openadapt_flow.tutorial import TUTORIAL_NOTE, _records, run_tutorial_workflow + from openadapt_flow.tutorial import TUTORIAL_NOTE + + from openadapt.quickstart.screen_check import ( + all_saves_reopened, + read_report, + run_checked, + screen_check, + ) - extra: dict[str, Any] = {} - if note is not None and _accepts(run_tutorial_workflow, "params"): - extra["params"] = {"note": note} - else: + if note is None: note = str(workflow.params.get("note", TUTORIAL_NOTE)) started = time.monotonic() - report = run_tutorial_workflow( + report = run_checked( base_url=base_url, workflow=workflow, bundle_dir=bundle_dir, run_dir=run_dir, - headed=visible, - **extra, + params={"note": note}, + visible=visible, ) - records = _records(base_url) seconds = time.monotonic() - started - render_run_report(run_dir) + try: + render_run_report(run_dir) + except (ImportError, OSError, ValueError, KeyError, TypeError, RuntimeError): + pass # REPORT.md is a convenience; report.json is the record required, confirmed = _effect_counts(report) + if report.execution_outcome == "VERIFIED": + _write_run_summary(report, run_dir) + data = read_report(run_dir) + check = screen_check(data) checked = ( report.execution_outcome == "VERIFIED" and report.transaction_outcome == "VERIFIED" and required > 0 and confirmed == required - and any(record.get("note") == note for record in records) + and all_saves_reopened(data) + and check.reopened_ok ) - if report.execution_outcome == "VERIFIED": - receipt_enabled = True - try: - from openadapt_flow.receipt_record import mode_enabled - - receipt_enabled = mode_enabled() - except ImportError: - pass - if receipt_enabled: - write_receipt(_build_tutorial_receipt(report), run_dir) facts = RunFacts( index=index, note=note, @@ -332,7 +391,7 @@ def run_program( execution_outcome=str(report.execution_outcome), transaction_outcome=report.transaction_outcome, checked=checked, - records=len(records), + records=0, model_calls=int(report.model_calls), cost_usd=float(getattr(report, "est_model_cost_usd", 0.0) or 0.0), effects_required=required, @@ -346,12 +405,94 @@ def run_program( report.transaction_outcome, getattr(getattr(report, "halt", None), "reason", ""), ), + check=check, ) if facts.not_ready: facts.explanation = not_ready_explanation(visible) return facts +def _write_run_summary(report: Any, run_dir: Path) -> None: + """Write the run's summary card (``run-summary.json``) the finale reads.""" + + from openadapt_flow.receipt import _build_tutorial_receipt, write_receipt + + enabled = True + try: + from openadapt_flow.receipt_record import mode_enabled + + enabled = mode_enabled() + except ImportError: + pass + if enabled: + try: + write_receipt(_build_tutorial_receipt(report), run_dir) + except Exception: # noqa: BLE001 - the card is a convenience; report.json stands + pass + + +def _squash(text: str) -> str: + """Lower case, no spaces: OCR'd screen text drops some of them.""" + + return "".join(str(text).lower().split()) + + +def run_looks_fine( + *, + base_url: str, + workflow: Any, + bundle_dir: Path, + run_dir: Path, + note: str, + visible: bool, +) -> CatchFacts: + """Run the program once more, on an app that drops the note but says saved. + + The same program, gate and check as every other run; only the app differs + (:data:`~openadapt.quickstart.screen_check.LOOKS_FINE_ENTRY`). + """ + + from openadapt_flow.report import render_run_report + + from openadapt.quickstart.screen_check import ( + LOOKS_FINE_ENTRY, + escalated, + read_report, + run_checked, + screen_check, + ) + + started = time.monotonic() + report = run_checked( + base_url=base_url, + workflow=workflow, + bundle_dir=bundle_dir, + run_dir=run_dir, + params={"note": note}, + entry_query=LOOKS_FINE_ENTRY, + visible=visible, + ) + seconds = time.monotonic() - started + try: + render_run_report(run_dir) + except (ImportError, OSError, ValueError, KeyError, TypeError, RuntimeError): + pass + data = read_report(run_dir) + seen = _squash(" ".join((data.get("halt") or {}).get("observed_texts") or [])) + return CatchFacts( + run_dir=run_dir, + note=note, + execution_outcome=str(report.execution_outcome), + transaction_outcome=report.transaction_outcome, + check=screen_check(data), + screen_showed_note=bool(note) and _squash(note) in seen, + screen_said_saved="saved" in seen, + escalated=escalated(run_dir), + model_calls=int(report.model_calls), + seconds=seconds, + ) + + def _artifact_is_file(path: Path) -> bool: """Whether a run file exists, encrypted or not.""" from openadapt_flow import sealed_set @@ -439,52 +580,40 @@ def record(self, on_step: Callable[[DemoStep], None]) -> list[DemoStep]: def compile(self) -> int: """Compile and certify the recording; return the program's step count.""" - from openadapt_flow.compiler import compile_recording - from openadapt_flow.tutorial import ( - TUTORIAL_WORKFLOW_NAME, - certify_tutorial, - consequential_step, - ) + from openadapt_flow.tutorial import TUTORIAL_WORKFLOW_NAME + + from openadapt.quickstart.screen_check import compile_checked - workflow = compile_recording( - self.recording_dir, - self.bundle_dir, - name=TUTORIAL_WORKFLOW_NAME, - mine_effects=True, - bind_effect_params=True, + self.workflow = compile_checked( + self.recording_dir, self.bundle_dir, TUTORIAL_WORKFLOW_NAME ) - consequential_step(workflow) - certify_tutorial(workflow) - self.workflow = workflow - return len(workflow.steps) + return len(self.workflow.steps) @property def program_name(self) -> str: return str(getattr(self.workflow, "name", "") or "") def readback_fields(self) -> list[tuple[str, Optional[str], Optional[str]]]: - """The fields each run's record check reads back, from the compiled bundle. + """The fields each run's check reads in the reopened record. - One ``(field, literal, param)`` per field the save's ``record_written`` - check matches: a fixed value, or the run input it is bound to. Empty - when the bundle has no such check or can't be read. + One ``(label, literal, param)`` per field the save's check reads: a + fixed value, or the run input it is bound to. Empty when the bundle + has no such check or can't be read. """ return readback_fields(self.bundle_dir / "workflow.json") def note_param(self) -> bool: - """True when the engine can give each run its own note.""" - - from openadapt_flow.tutorial import run_tutorial_workflow + """True: each run is given its own note (the check reads that note).""" - return _accepts(run_tutorial_workflow, "params") + return True # -- act 2 ------------------------------------------------------------ def run( self, index: int, note: Optional[str], folder: Optional[str] = None ) -> RunFacts: - """Run the program once, in this process, on a fresh database.""" + """Run the program once, in this process, on a fresh copy of the app.""" assert self._base_url is not None and self.workflow is not None return run_program( @@ -547,7 +676,7 @@ def run_all( """Run the program once per note, in the worker processes when started. Each run is a complete checked run in its own browser, against its own - copy of the clinic's database. A run a worker can't take (a worker + copy of the clinic app. A run a worker can't take (a worker that failed to start, or one that stalled) runs here instead, so every note still gets its own checked run. """ @@ -590,6 +719,24 @@ def finish(run: RunFacts) -> None: run.repeated = True on_finish(run) + # -- the save that only looks fine ------------------------------------ + + #: The note of the run whose app drops it but says saved. + looks_fine_note = RUN_NOTES[1] + + def looks_fine(self) -> CatchFacts: + """Run the program on an app that drops the note but says it saved.""" + + assert self._base_url is not None and self.workflow is not None + return run_looks_fine( + base_url=self._base_url, + workflow=self.workflow, + bundle_dir=self.bundle_dir, + run_dir=self.root / "run-looks-fine", + note=self.looks_fine_note, + visible=self.visible, + ) + # -- act 3 ------------------------------------------------------------ def before_prompt(self) -> None: @@ -765,31 +912,31 @@ def return_focus_to_terminal( def readback_fields( workflow_json: Path, ) -> list[tuple[str, Optional[str], Optional[str]]]: - """``(field, literal, param)`` for the first ``record_written`` check in a bundle.""" + """``(label, literal, param)`` for each field the save's check reads.""" from openadapt_flow import sealed_set try: workflow = json.loads(sealed_set.read_text(workflow_json)) - except (OSError, ValueError): + except (OSError, ValueError, sealed_set.SealedSetError): return [] for step in workflow.get("steps") or []: for effect in step.get("effects") or []: - if effect.get("kind") != "record_written": - continue + readback = effect.get("readback") or {} fields = [] - for name, binding in (effect.get("match") or {}).items(): - binding = binding if isinstance(binding, dict) else {} - literal = binding.get("literal") - param = binding.get("param") + for item in readback.get("fields") or []: + value = item.get("value") or {} + literal = value.get("literal") + param = value.get("param") fields.append( ( - str(name), + str(item.get("label") or item.get("name") or ""), None if literal is None else str(literal), None if param is None else str(param), ) ) - return fields + if fields: + return fields return [] @@ -825,6 +972,7 @@ def open_page(page: Path) -> bool: __all__ = [ "RUN_NOTES", "BreakFacts", + "CatchFacts", "DemoStep", "FlowEngine", "RunFacts", diff --git a/openadapt/quickstart/restart.py b/openadapt/quickstart/restart.py index c01e245da2..0b67181c6f 100644 --- a/openadapt/quickstart/restart.py +++ b/openadapt/quickstart/restart.py @@ -2,21 +2,22 @@ A batch of two new notes runs in a separate worker process. Each note's run goes through the same governed path as Act 2 (the Standard run gate, the -record check against the app's database) and, in addition, through the -engine's at-most-once write ledger (``IdempotencyLedger``, kept on disk in the -output folder): the replayer reserves the note's key in the ledger before its -first action and records the outcome after the record check. +check on the save's screen and in the reopened record) and, in addition, +through the engine's at-most-once write ledger (``IdempotencyLedger``, kept on +disk in the output folder): the replayer reserves the note's key in the +ledger before its first action and records the outcome after the check. When note 1's run has returned, the worker is stopped with ``SIGKILL`` before it starts note 2. The batch then starts again in this process with the same ledger. The replayer finds note 1's key already reserved and does not run -it (``idempotent_replay``); note 2 runs and saves. Last, each note's database -is read out of band and the note is counted there. - -Each note has its own copy of the clinic's database, as each run in Act 2 -does: the tutorial program writes one logical record per patient, so two -notes can't both be checked in one database. Every number shown comes from -the run reports, the ledger and the databases; nothing is scripted output. +it (``idempotent_replay``); note 2 runs and saves. Last, each patient's chart +is reopened in a browser and the encounters showing each note are counted on +screen. + +Each note has its own copy of the clinic app, as each run in Act 2 does: the +program reads the first encounter on the chart, so two notes on one chart +can't both be checked. Every number shown comes from the run reports, the +ledger and the reopened charts; nothing is scripted output. """ from __future__ import annotations @@ -60,14 +61,14 @@ def says_verified(value: object) -> bool: @dataclass class NoteRun: - """One note's run, read from its report, the ledger and its database.""" + """One note's run, read from its report and the ledger.""" index: int note: str run_dir: Path execution_outcome: str transaction_outcome: Optional[str] - #: Saved, and the record check confirmed it in the database. + #: Saved, and the check confirmed it on screen and in the reopened record. checked: bool #: The replayer found this note's key in the ledger and did not run it. skipped: bool @@ -97,8 +98,9 @@ class RestartFacts: signal: str = "" #: The runs after the restart, one per note. after: list[NoteRun] = field(default_factory=list) - #: How many records hold each note, in that note's database. - copies: list[int] = field(default_factory=list) + #: How many encounters show each note on its reopened chart (None when + #: the chart couldn't be read). + copies: list[Optional[int]] = field(default_factory=list) seconds: float = 0.0 #: Why the act couldn't run (no second process, for example), if so. error: Optional[str] = None @@ -112,7 +114,7 @@ def model_calls(self) -> int: @property def held(self) -> bool: """Note 1 saved, the worker stopped, note 1 skipped, note 2 saved, - and each note in its database exactly once.""" + and each note on its reopened chart exactly once.""" if self.error or self.restart_error or not self.killed: return False @@ -143,38 +145,12 @@ def ledger_key(batch: str, index: int) -> str: return f"quickstart-batch/{batch}/note-{index}" -def _verifier(base_url: str) -> Any: - """The tutorial's record check: it reads the app's database over HTTP.""" - - from openadapt_flow import tutorial - - build = getattr(tutorial, "_build_demo_effect_verifier", None) - if build is not None: - return build(base_url) - from openadapt_flow.deployment import EffectsConfig, build_effect_verifier - from openadapt_flow.mockmed.fault_server import MOCKMED_RECORDS_READ_CONTRACT - - verifier = build_effect_verifier( - EffectsConfig.model_validate( - { - **MOCKMED_RECORDS_READ_CONTRACT, - "base_url": base_url, - "timeout_s": 2.0, - "poll_interval_s": 0.05, - } - ) - ) - if verifier is None: - raise RuntimeError("the record contract built no verifier") - return verifier - - -def note_count(base_url: str, note: str) -> int: - """How many records in the database at ``base_url`` hold ``note``.""" +def note_count(base_url: str, note: str) -> Optional[int]: + """How many encounters on the reopened chart at ``base_url`` show ``note``.""" - from openadapt_flow.tutorial import _records + from openadapt.quickstart.screen_check import chart_copies - return sum(1 for record in _records(base_url) if record.get("note") == note) + return chart_copies(base_url, note) def run_note( @@ -191,75 +167,52 @@ def run_note( ) -> NoteRun: """Run the program once for ``note`` under the ledger key ``key``. - The tutorial's own run (the Standard run gate, the record check), with - the engine's at-most-once ledger attached, and without resetting the - database first. + The quickstart's own run (the Standard run gate, the check on screen and + in the reopened record), with the engine's at-most-once ledger attached, + and without resetting the app first. """ - from openadapt_flow.backends.playwright_backend import PlaywrightBackend - from openadapt_flow.deployment import DeploymentConfig, PolicySection - from openadapt_flow.execution_profiles import ( - ExecutionProfile, - execution_profile_contract, - ) - from openadapt_flow.run_gate import build_runtime_authorization, evaluate_run_gate - from openadapt_flow.runtime import Replayer from openadapt_flow.transaction import IdempotencyLedger - from openadapt_flow.tutorial import TUTORIAL_ENTRY_QUERY, TUTORIAL_POLICY - - base = base_url.rstrip("/") - entry_url = f"{base}/{TUTORIAL_ENTRY_QUERY}" - verifier = _verifier(base_url) - gate = evaluate_run_gate( - workflow, - bundle_dir=bundle_dir, - deployment=DeploymentConfig(policy=PolicySection(policy=TUTORIAL_POLICY)), - effect_verifier=verifier, - profile_contract=execution_profile_contract(ExecutionProfile.STANDARD), - effective_durable=True, - effective_require_settled=True, - ) - if not gate.passed: - raise RuntimeError( - f"the standard run gate refused the program:\n{gate.render()}" - ) - params = {"note": note} - authorization = build_runtime_authorization( - workflow, gate, approval_source="openadapt-quickstart", params=params + + from openadapt.quickstart.screen_check import ( + all_saves_reopened, + read_report, + run_checked, ) + ledger = IdempotencyLedger(ledger_path) started = time.monotonic() - backend, close = PlaywrightBackend.launch(entry_url, headless=not visible) try: - report = Replayer( - backend, - effect_verifier=verifier, - governed_authorization=authorization, - durable=True, - require_settled=True, - idempotency_ledger=ledger, - ).run( - workflow.model_copy(deep=True), - params=params, + report = run_checked( + base_url=base_url, + workflow=workflow, bundle_dir=bundle_dir, run_dir=run_dir, - execution_target_kind="web", - execution_origin=base, - execution_entry_url=entry_url, + params={"note": note}, + visible=visible, + reset=False, + ledger=ledger, idempotency_key=key, + approval_source="openadapt-quickstart", ) + seconds = time.monotonic() - started + try: + from openadapt_flow.report import render_run_report + + render_run_report(run_dir) + except ( + ImportError, + OSError, + ValueError, + KeyError, + TypeError, + RuntimeError, + ) as exc: + # REPORT.md is a convenience; report.json is the record either way. + _log.debug("REPORT.md not rendered for %s: %s", run_dir, exc) + record = ledger.lookup(key) finally: - close() - seconds = time.monotonic() - started - try: - from openadapt_flow.report import render_run_report - - render_run_report(run_dir) - except (ImportError, OSError, ValueError, KeyError, TypeError, RuntimeError) as exc: - # REPORT.md is a convenience; report.json is the record either way. - _log.debug("REPORT.md not rendered for %s: %s", run_dir, exc) - record = ledger.lookup(key) - ledger.close() + ledger.close() envelope = getattr(report, "outcome_envelope", None) required = int(envelope.required_contracts.effect) if envelope else 0 confirmed = int(envelope.passed_contracts.effect) if envelope else 0 @@ -275,7 +228,7 @@ def run_note( and says_verified(report.transaction_outcome) and required > 0 and confirmed == required - and note_count(base_url, note) >= 1 + and all_saves_reopened(read_report(run_dir)) ) return NoteRun( index=index, diff --git a/openadapt/quickstart/restart_view.py b/openadapt/quickstart/restart_view.py index 08cfb67021..9de093d0e0 100644 --- a/openadapt/quickstart/restart_view.py +++ b/openadapt/quickstart/restart_view.py @@ -23,11 +23,15 @@ def note_status(run: NoteRun, marks: Any) -> str: if run.skipped: done = says_verified(run.ledger_outcome) - why = "the ledger has it as done" if done else "the ledger has it as started" - return f"{marks.dot} Skipped: {why}, no save sent" + why = ( + "logged as saved before the kill" + if done + else "logged as started before the kill" + ) + return f"{marks.dot} SKIPPED: {why}" if run.checked: - return f"{marks.ok} checked in the database" - return f"{marks.stop} {run.transaction_outcome or run.execution_outcome}" + return f"{marks.ok} VERIFIED" + return f"{marks.stop} STOPPED: {run.transaction_outcome or run.execution_outcome}" def note_row(run: NoteRun, total: int, marks: Any) -> str: @@ -43,33 +47,34 @@ def stop_line(facts: RestartFacts, marks: Any) -> str: count = len(facts.before) after = f"after note {count}" if count else "before any note" how = "with SIGKILL" if facts.signal else "hard" - return f"{marks.stop} Runner process stopped {how} {after}, before note {count + 1}" + return f"{marks.stop} Runner killed {how} {after}, before note {count + 1}" def copies_line(facts: RestartFacts) -> str: - """How many records hold each note, read from the database after the restart.""" + """How many encounters show each note on its reopened chart.""" if not facts.copies: - return "not read" + return "not reopened" + if any(count is None for count in facts.copies): + return "the chart couldn't be read" parts = [] for index, count in enumerate(facts.copies, 1): - noun = "record" if count == 1 else "records" + noun = "encounter" if count == 1 else "encounters" parts.append(f"note {index}: {count} {noun}") - # MockMed drops a save whose key it already holds, so a count of 1 alone - # can't rule out a resend. Say "saved once" only when the restart report + # The demo app drops a save whose key it already holds, so a count of 1 + # alone can't rule out a resend. Say "once" only when the restart report # shows note 1 skipped with no actions (``held``). if facts.held and all(count == 1 for count in facts.copies): - return "each note saved once (" + ", ".join(parts) + ")" + return "each note appears once" return ", ".join(parts) def why_line(facts: RestartFacts) -> str: if facts.held: return ( - "OpenAdapt records each note in a ledger on disk before it saves " - "it, and records the outcome after the record check. On restart it " - "found note 1 marked done, so it sent no save for note 1 and saved " - "only note 2." + "OpenAdapt logs each note on disk before saving it and marks it " + "done after checking it. After the restart, the log showed note 1 " + "as done, so it was skipped." ) if facts.restart_error: return ( @@ -84,6 +89,8 @@ def summary_line(facts: RestartFacts) -> Optional[str]: if not facts.held: return None + if facts.copies and all(count == 1 for count in facts.copies): + return None # "each note appears once" already says it return ( "The runner was killed partway through the batch. On restart, " "OpenAdapt sent no save for note 1 and saved note 2." @@ -117,10 +124,11 @@ def plain_lines(facts: RestartFacts, marks: Any) -> list[str]: total = len(facts.notes) lines = [note_row(run, total, marks) for run in facts.before] lines.append(stop_line(facts, marks)) - lines.append("Restarted with the same ledger:") + lines.append("After restart:") lines.extend(note_row(run, total, marks) for run in facts.after) - lines.append(f"The database: {copies_line(facts)}") - lines.append(f"Why: {why_line(facts)}") + lines.append(f"Reopened the records: {copies_line(facts)}") + if not facts.held: + lines.append(f"Why: {why_line(facts)}") return lines diff --git a/openadapt/quickstart/scene.py b/openadapt/quickstart/scene.py index 6fced1d9d0..3a44ba3b90 100644 --- a/openadapt/quickstart/scene.py +++ b/openadapt/quickstart/scene.py @@ -1,8 +1,9 @@ """The words that differ between the quickstart's apps. -MockMed (the default) ends with a crash and a restart: the runner is stopped -partway through a batch of two notes and started again, and it saves neither -note twice. OpenEMR's Act 3 is a referral that matches an existing chart: the +MockMed (the default) checks each save on screen and in the reopened record, +catches a save that only looks fine, and ends with a crash and a restart: the +runner is stopped partway through a batch of two notes and started again, and +it saves neither note twice. OpenEMR's Act 3 is a referral that matches an existing chart: the program stops before saving. Everything else in the story and the views is shared; a :class:`Scene` holds what is not. """ @@ -28,7 +29,7 @@ class Scene: act1_where: str #: Act 2's inputs, plural ("notes": "the program on 5 new notes"). inputs_noun: str - #: Where each run is checked ("checked in the database"). + #: A checked run's status ("VERIFIED"). checked_in: str #: Act 3's step line. act3_title: str @@ -44,9 +45,8 @@ class Scene: #: fields (see :meth:`run_detail`). run_detail_template: str = ( "run {index}: execution {execution}, transaction {transaction}, profile " - "standard, record checks {confirmed}/{required} confirmed by an " - "independent read of the database, {records} record(s) after the run; " - "report {report}" + "standard, policy screen-write, checks {confirmed}/{required} confirmed " + "on screen and in the reopened record; report {report}" ) #: What one record is called ("record": "0 new records"). record_noun: str = "record" @@ -57,9 +57,24 @@ class Scene: compiled_template: str = "Compiled into a program: {steps} steps." #: The first step's line once the app is up, and its dim detail. ready: str = "Clinic app ready" - ready_detail: str = "synthetic data, on this computer" - #: The record's name in the read-back card ("The database"). - record_title: str = "The database" + ready_detail: str = "on this computer" + #: The record's name in the read-back card ("The reopened record"). + record_title: str = "The reopened record" + #: True to show a checked run as rows (Typed, After the save, Reopened + #: the record, Verdict), the same rows as the run against a faulty server. + verdict_rows: bool = False + #: How Act 2's total names checked runs ("4 of 5 saved and checked"). + checked_total: str = "saved and checked" + #: The Act 2 card's title when every run checked out. + clean_title: str = "Saved and checked" + #: The heading over the fields the card reads back; empty for the default. + readback_title: str = "" + #: The act with a save that only looks fine; empty when the app has none. + looks_fine_title: str = "" + #: What is different about that save, said before it runs. + looks_fine_setup: str = "" + #: What the spinner says while it runs. + looks_fine_running: str = "" # The rest is for an Act 3 that stops before a save (OpenEMR's). @@ -183,20 +198,23 @@ def break_detail(self, broken: "BreakFacts") -> list[str]: MOCKMED = Scene( intro=( - "show a task once, run it, then stop it mid-batch and watch the " - "restart skip what was already saved." + "OpenAdapt turns a task shown once into a program and checks every " + "save it makes. Here a script stands in for you, in a demo clinic app." ), starting="Starting the synthetic clinic app", - act1_where="a demonstration in a synthetic clinic app", + act1_where="in the demo clinic app", inputs_noun="notes", - checked_in="checked in the database", - act3_title="Stop it mid-batch, then restart", - act3_subtitle="the runner is stopped after note 1 of 2 and started again", - act3_setup=( - "A batch of 2 new notes, each in its own copy of the clinic's database. " - "The runner process is stopped hard after note 1 saves, then started " - "again." - ), + checked_in="VERIFIED", + checked_total="VERIFIED", + clean_title="VERIFIED", + readback_title="Reopened the record", + verdict_rows=True, + looks_fine_title="Run it against a faulty server", + looks_fine_setup=("The demo server drops the note but still reports success."), + looks_fine_running="Saving, then reopening the record", + act3_title="Kill the runner mid-batch, then restart it", + act3_subtitle="the runner is killed after note 1 of 2 and restarted", + act3_setup=("A batch of 2 notes. The runner is killed after note 1 is saved."), confirm_prompt="Press Enter to start the batch", act3_running="Running the batch, stopping the runner, restarting it", ) diff --git a/openadapt/quickstart/screen_check.py b/openadapt/quickstart/screen_check.py new file mode 100644 index 0000000000..63d1b2597a --- /dev/null +++ b/openadapt/quickstart/screen_check.py @@ -0,0 +1,320 @@ +"""Check each save the way a careful person does: the screen, then the record. + +The quickstart's program is compiled from a copy of the demonstration that +keeps no system-of-record snapshots, the way a customer without database +access records it. So the compiler mines the check a person makes after +saving: the save's screen (the form closed, no error, the typed value shown +under its label), and then the record reopened. A run is checked only when +the reopened record shows every typed value. + +Every run goes through the engine's fail-closed run gate under the shipped +``screen-write`` policy and the Standard profile, with +:class:`~openadapt_flow.runtime.effects.onscreen.OnScreenReadbackVerifier` +as its only verifier. Nothing here reads the app's database. +""" + +from __future__ import annotations + +import json +import shutil +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Optional + +#: The shipped policy the quickstart's program is certified and gated under. +SCREEN_POLICY = "screen-write" +#: The demo app with its server-side save path. ``partial`` keeps the record +#: but drops its note while the app still says the encounter was saved. +CLEAN_ENTRY = "?fault=ok#tasks" +LOOKS_FINE_ENTRY = "?fault=partial#tasks" + +_SOR_KEYS = ("sor_before", "sor_after", "sor_t_before", "sor_t_after") + + +class ScreenCheckError(RuntimeError): + """The program can't be checked on screen; the quickstart stops.""" + + +@dataclass +class ScreenCheck: + """What one save's check read, from the run's own report.""" + + #: How the save was checked: "reopened", "same_screen" or "unchecked". + checked_how: str = "unchecked" + fields_intended: int = 0 + fields_read: int = 0 + fields_matched: int = 0 + #: The form closed after the save (None: not observed). + left_edit_mode: Optional[bool] = None + #: An error was shown after the save (None: not observed). + error_shown: Optional[bool] = None + #: The only sign of the save was a banner (None: not observed). + banner_only: Optional[bool] = None + #: The record was opened again and read. + reopened: bool = False + + @property + def screen_ok(self) -> bool: + """The save's own screen looked right: the form closed, no error.""" + + return self.left_edit_mode is True and self.error_shown is False + + @property + def reopened_ok(self) -> bool: + return ( + self.reopened + and self.checked_how == "reopened" + and self.fields_intended > 0 + and self.fields_matched == self.fields_intended + ) + + +def _plain_recording(src: Path, out: Path) -> None: + """A copy of the recording ``src`` without system-of-record snapshots.""" + + from openadapt_flow import sealed_set + + shutil.rmtree(out, ignore_errors=True) + (out / "frames").mkdir(parents=True) + (out / "meta.json").write_text(sealed_set.read_text(src / "meta.json")) + lines = [] + for line in sealed_set.read_text(src / "events.jsonl").splitlines(): + if not line.strip(): + continue + event = json.loads(line) + for key in _SOR_KEYS: + event.pop(key, None) + lines.append(json.dumps(event)) + (out / "events.jsonl").write_text("\n".join(lines) + "\n") + for frame in (src / "frames").iterdir(): + name = frame.name[: -len(".enc")] if frame.name.endswith(".enc") else frame.name + (out / "frames" / name).write_bytes( + sealed_set.read_bytes(src / "frames" / name) + ) + + +def compile_checked(recording: Path, bundle: Path, name: str) -> Any: + """Compile ``recording`` into a program whose save is checked on screen. + + Returns the certified workflow. Raises :class:`ScreenCheckError` when the + program has no single save with an on-screen check, or when it is not + certified under :data:`SCREEN_POLICY`. + """ + + from openadapt_flow.compiler import compile_recording + from openadapt_flow.policy import evaluate_policy, load_policy + + plain = recording.parent / f"{recording.name}-for-compile" + _plain_recording(recording, plain) + try: + workflow = compile_recording( + plain, + bundle, + name=name, + mine_effects=True, + bind_effect_params=True, + ) + finally: + shutil.rmtree(plain, ignore_errors=True) + # The quickstart acts as the person who reviews the program: it keeps the + # check on the save and drops the read-backs the compiler hung on + # navigation clicks (reversible steps). Nobody admitted those, and the + # runtime refuses to run with them. The save's own check is untouched. + for step in workflow.steps: + if step.risk != "irreversible": + step.effects = [] + workflow.save(bundle) # re-seals the manifest, as `check admit` does + saves = [s for s in workflow.steps if s.risk == "irreversible" and s.effects] + if len(saves) != 1: + raise ScreenCheckError( + "expected exactly one save with a check; observed " + f"{[step.id for step in saves]}" + ) + if any(effect.readback is None for effect in saves[0].effects): + raise ScreenCheckError("the save's check does not read the screen") + report = evaluate_policy( + workflow, + load_policy(SCREEN_POLICY), + require_current_risk_certification=True, + ) + if not report.passed: + raise ScreenCheckError( + f"the program is NOT certified under {SCREEN_POLICY!r}:\n{report.render()}" + ) + return workflow + + +def run_checked( + *, + base_url: str, + workflow: Any, + bundle_dir: Path, + run_dir: Path, + params: Optional[dict[str, str]], + entry_query: str = CLEAN_ENTRY, + visible: bool = False, + reset: bool = True, + ledger: Any = None, + idempotency_key: Optional[str] = None, + approval_source: str = "openadapt-flow-tutorial", +) -> Any: + """Run the program once through the run gate; return the engine's report.""" + + from openadapt_flow.backends.playwright_backend import PlaywrightBackend + from openadapt_flow.deployment import DeploymentConfig, PolicySection + from openadapt_flow.execution_profiles import ( + ExecutionProfile, + execution_profile_contract, + ) + from openadapt_flow.run_gate import build_runtime_authorization, evaluate_run_gate + from openadapt_flow.runtime import Replayer + from openadapt_flow.runtime.effects.onscreen import OnScreenReadbackVerifier + + base = base_url.rstrip("/") + if reset: + from openadapt_flow.tutorial import _http_json + + # A fresh copy of the clinic app for this run. + _http_json(f"{base}/api/reset", method="POST", body={}) + entry_url = f"{base}/{entry_query}" + verifier = OnScreenReadbackVerifier() + gate = evaluate_run_gate( + workflow, + bundle_dir=bundle_dir, + deployment=DeploymentConfig(policy=PolicySection(policy=SCREEN_POLICY)), + effect_verifier=verifier, + profile_contract=execution_profile_contract(ExecutionProfile.STANDARD), + effective_durable=True, + effective_require_settled=True, + ) + if not gate.passed: + raise ScreenCheckError( + f"the standard run gate refused the program; nothing ran:\n{gate.render()}" + ) + replay_params = { + **{str(k): str(v) for k, v in (getattr(workflow, "params", {}) or {}).items()}, + **(params or {}), + } + authorization = build_runtime_authorization( + workflow, gate, approval_source=approval_source, params=replay_params + ) + extra: dict[str, Any] = {} + if ledger is not None: + extra["idempotency_key"] = idempotency_key + backend, close = PlaywrightBackend.launch(entry_url, headless=not visible) + verifier.bind_backend(backend) + try: + return Replayer( + backend, + effect_verifier=verifier, + governed_authorization=authorization, + durable=True, + require_settled=True, + **({"idempotency_ledger": ledger} if ledger is not None else {}), + ).run( + workflow.model_copy(deep=True), + params=replay_params, + bundle_dir=bundle_dir, + run_dir=run_dir, + execution_target_kind="web", + execution_origin=base, + execution_entry_url=entry_url, + **extra, + ) + finally: + close() + + +def read_report(run_dir: Path) -> dict[str, Any]: + """The run's ``report.json``, encrypted or not; empty when unreadable.""" + + from openadapt_flow import sealed_set + + try: + return json.loads(sealed_set.read_text(run_dir / "report.json")) + except (OSError, ValueError, sealed_set.SealedSetError): + return {} + + +def _flag(value: Any) -> Optional[bool]: + """A flag the run observed (True or False), else None.""" + + return value if isinstance(value, bool) else None + + +def screen_check(report: dict[str, Any]) -> ScreenCheck: + """The save's check, as the run's report records it.""" + + readback = report.get("readback") or {} + saves = readback.get("saves") or [] + if not saves: + return ScreenCheck() + save = saves[0] + raw = save.get("screen_check") or {} + return ScreenCheck( + checked_how=str(save.get("checked_how") or "unchecked"), + fields_intended=int(raw.get("fields_intended") or 0), + fields_read=int(raw.get("fields_read") or 0), + fields_matched=int(raw.get("fields_matched") or 0), + left_edit_mode=_flag(raw.get("left_edit_mode")), + error_shown=_flag(raw.get("error_shown")), + banner_only=_flag(raw.get("banner_only")), + reopened=raw.get("reopened") is True, + ) + + +def all_saves_reopened(report: dict[str, Any]) -> bool: + """True when every save in the report was checked by reopening its record.""" + + saves = (report.get("readback") or {}).get("saves") or [] + return bool(saves) and all( + str(save.get("checked_how")) == "reopened" for save in saves + ) + + +def escalated(run_dir: Path) -> bool: + """True when the run left a decision for a person (a pending escalation).""" + + return any(run_dir.glob("pending_escalation.json*")) + + +def chart_copies(base_url: str, note: str, patient: str = "p1") -> Optional[int]: + """How many encounters on the patient's chart show ``note``, read on screen. + + Opens the chart in a new browser page, the way a person reopens it, and + reads each listed encounter's text. None when the chart can't be read. + """ + + from openadapt_flow.backends.playwright_backend import PlaywrightBackend + + url = f"{base_url.rstrip('/')}/?fault=ok#patient/{patient}" + try: + backend, close = PlaywrightBackend.launch(url, headless=True) + try: + page = backend.page + # The chart reloads its saved encounters after the page loads. + page.wait_for_load_state("networkidle") + page.wait_for_timeout(200) + items = page.locator("#encounter-list li").all_inner_texts() + finally: + close() + except Exception: # noqa: BLE001 - an unread chart is reported as unread + return None + wanted = f"Note: {note}" + return sum(1 for text in items if wanted in " ".join(text.split())) + + +__all__ = [ + "CLEAN_ENTRY", + "LOOKS_FINE_ENTRY", + "SCREEN_POLICY", + "ScreenCheck", + "ScreenCheckError", + "all_saves_reopened", + "chart_copies", + "compile_checked", + "escalated", + "read_report", + "run_checked", + "screen_check", +] diff --git a/openadapt/quickstart/story.py b/openadapt/quickstart/story.py index 60102765da..5cb6cb44a2 100644 --- a/openadapt/quickstart/story.py +++ b/openadapt/quickstart/story.py @@ -1,8 +1,10 @@ -"""The quickstart in three acts: show it once, run it, stop and restart it. +"""The quickstart: show it once, run it, catch a bad save, stop and restart it. -On MockMed, Act 3 stops the runner partway through a batch and restarts it -(:mod:`openadapt.quickstart.restart`); on OpenEMR it runs a referral that -matches an existing chart, where the program stops before saving. +On MockMed, after the program's first run, one run saves on an app that drops +the note but still says it saved: the reopened record catches it. The last act +stops the runner partway through a batch and restarts it +(:mod:`openadapt.quickstart.restart`). On OpenEMR the last act runs a referral +that matches an existing chart, where the program stops before saving. This module decides what happens and in what order. The engine adapter (:mod:`openadapt.quickstart.engine`) does the work and measures it; the view @@ -21,6 +23,7 @@ from openadapt.quickstart.engine import ( RUN_NOTES, BreakFacts, + CatchFacts, DemoStep, RunFacts, SealFacts, @@ -133,6 +136,8 @@ class Outcome: act1_seconds: float = 0.0 runs: list[RunFacts] = field(default_factory=list) act2_seconds: float = 0.0 + #: MockMed: the save that only looks fine (the app drops the note). + catch: Optional[CatchFacts] = None #: OpenEMR's Act 3: the referral that matches an existing chart. broken: Optional[BreakFacts] = None #: MockMed's Act 3: the batch, the hard stop and the restart. @@ -157,6 +162,8 @@ def checked(self) -> int: @property def model_calls(self) -> int: calls = sum(run.model_calls for run in self.runs) + if self.catch is not None: + calls += self.catch.model_calls if self.broken is not None: calls += self.broken.model_calls if self.restart is not None: @@ -201,6 +208,10 @@ def act3_running(self) -> Any: ... def break_result(self, broken: BreakFacts) -> None: ... + def looks_fine_running(self) -> Any: ... + + def looks_fine_result(self, facts: CatchFacts) -> None: ... + def restart_result(self, facts: "RestartFacts") -> None: ... def finale(self, outcome: Outcome, steps: NextSteps) -> None: ... @@ -245,7 +256,7 @@ def run_story( prepare_restart = getattr(engine, "prepare_restart", None) if last_act and prepare_restart is not None: prepare_restart() - view.act(1, "Show it once", _act1_subtitle(engine.visible, scene)) + view.act(1, "Record the task", _act1_subtitle(engine.visible, scene)) act_start = clock() outcome.demo_steps = engine.record(view.demo_step) with view.compiling(): @@ -310,11 +321,24 @@ def finished(run: RunFacts) -> None: # Sign the checked runs' reports while Act 3 runs; the finale waits. sealing = _in_background(lambda: engine.seal(list(outcome.runs))) - # Act 3: stop it mid-batch and restart it (MockMed), or a referral + # A save that only looks fine (MockMed): the app keeps the record but + # drops the note and still says it saved. + act = 3 + looks_fine = getattr(engine, "looks_fine", None) + if looks_fine is not None and scene.looks_fine_title and not skip_break: + view.act(act, scene.looks_fine_title, scene.looks_fine_setup) + with view.looks_fine_running(): + outcome.catch = looks_fine() + view.looks_fine_result(outcome.catch) + if verbose: + view.detail(_catch_detail(outcome.catch)) + act += 1 + + # Last: stop it mid-batch and restart it (MockMed), or a referral # that matches an existing chart (OpenEMR). paging = None if last_act and not skip_break: - view.act(3, scene.act3_title, scene.act3_subtitle) + view.act(act, scene.act3_title, scene.act3_subtitle) view.act3_setup() if interactive: waited = clock() @@ -350,6 +374,18 @@ def finished(run: RunFacts) -> None: return outcome +def _catch_detail(facts: CatchFacts) -> list[str]: + check = facts.check + return [ + f"execution {facts.execution_outcome}, transaction " + f"{facts.transaction_outcome}, checked {check.checked_how}, fields " + f"{check.fields_matched}/{check.fields_intended} matched " + f"({check.fields_read} read), form closed {check.left_edit_mode}, " + f"error shown {check.error_shown}, escalated {facts.escalated}", + f"report {facts.report_md}", + ] + + def _break_act( engine: Any, view: View, outcome: Outcome, scene: Scene, verbose: bool ) -> Any: diff --git a/openadapt/quickstart/view.py b/openadapt/quickstart/view.py index f1541553b1..7375c0fac4 100644 --- a/openadapt/quickstart/view.py +++ b/openadapt/quickstart/view.py @@ -23,7 +23,7 @@ from typing import IO, Any, Iterator, Mapping, Optional, Sequence from openadapt.quickstart import restart_view -from openadapt.quickstart.engine import BreakFacts, DemoStep, RunFacts +from openadapt.quickstart.engine import BreakFacts, CatchFacts, DemoStep, RunFacts from openadapt.quickstart.notices import ( Notices, collect_notices, @@ -31,6 +31,7 @@ plaintext_line, ) from openadapt.quickstart.scene import MOCKMED, Scene +from openadapt.quickstart.screen_check import ScreenCheck from openadapt.quickstart.seal_link import SealCard, read_card from openadapt.quickstart.story import ( REAL_SEALS_URL, @@ -43,6 +44,8 @@ _LABEL_WIDTH = 40 #: The number of steps in the story (the app, show, compile, run, act 3). STEPS = 5 +#: With the save that only looks fine (MockMed). +STEPS_WITH_CATCH = 6 #: Below this many columns the screen and the record stack instead of sitting #: side by side. _SIDE_BY_SIDE = 80 @@ -134,12 +137,12 @@ def skipped_break_line(scene: Scene = MOCKMED) -> str: return f"Skipped the last part ({scene.act3_title.lower()}): it would stop the same way." -def runs_total_line(outcome: Outcome, marks: Marks) -> str: +def runs_total_line(outcome: Outcome, marks: Marks, scene: Scene = MOCKMED) -> str: dot = f" {marks.dot} " return dot.join( [ - f"{outcome.checked} of {len(outcome.runs)} saved and checked", - f"{outcome.model_calls} AI calls", + f"{outcome.checked} of {len(outcome.runs)} {scene.checked_total}", + f"{outcome.model_calls} model calls", f"${outcome.cost_usd:.2f}", seconds(outcome.act2_seconds), ] @@ -177,6 +180,195 @@ def reconcile_line(broken: BreakFacts) -> Optional[str]: ) +def after_save_rows(check: ScreenCheck) -> list[tuple[Optional[bool], str]]: + """What the screen showed right after the save, as ``(ok, words)``. + + ``ok`` is None for a flag the run didn't observe. + """ + + closed = {True: "form closed", False: "form still open"} + error = {False: "no error shown", True: "an error was shown"} + return [ + (check.left_edit_mode, closed.get(check.left_edit_mode, "form not observed")), + ( + None if check.error_shown is None else not check.error_shown, + error.get(check.error_shown, "errors not observed"), + ), + ] + + +def _mark(ok: Optional[bool], marks: Marks) -> str: + if ok is None: + return marks.dot + return marks.ok if ok else marks.no + + +def reopened_words(check: ScreenCheck) -> str: + """What reopening the record showed: how many typed values were there.""" + + if not check.reopened: + return "not reopened" + if check.fields_intended == 1: + return "typed value found" if check.fields_matched else "typed value not found" + return f"{check.fields_matched} of {check.fields_intended} typed values found" + + +def checked_on_screen(run: RunFacts) -> bool: + """True when the run's report says how its save was checked on screen.""" + + return run.check.reopened or run.check.left_edit_mode is not None + + +ROW_LABELS = ("Typed", "After the save", "Reopened the record", "Verdict") + + +def after_save_line(check: ScreenCheck, marks: Marks) -> str: + """What the screen showed after the save, as plain words. + + No checkmarks: a screen that looks saved is not the verdict. + """ + + return f" {marks.dot} ".join(words for _ok, words in after_save_rows(check)) + + +def checked_rows(outcome: Outcome, marks: Marks) -> Optional[list[tuple[str, str]]]: + """A checked run as the same four rows as the faulty-server run. + + None when no run checked out, or the run wasn't checked on screen. + """ + + run = readback_run(outcome) + if run is None or not checked_on_screen(run): + return None + fields = readback_rows(outcome) + if fields: + reopened = " ".join(f"{marks.ok} {name} {value}" for name, value in fields) + else: + reopened = f"{marks.ok} {reopened_words(run.check)}" + return list( + zip( + ROW_LABELS, + ( + f'"{run.note}"', + after_save_line(run.check, marks), + reopened, + f"{marks.ok} VERIFIED", + ), + ) + ) + + +def field_name(outcome: Outcome) -> Optional[str]: + """The one field each save checks ("Note"), when there is exactly one.""" + + names = [name for name, _literal, _param in outcome.readback] + return names[0] if len(names) == 1 else None + + +def catch_screen_line(facts: CatchFacts, marks: Marks) -> str: + """The screen right after the bad save: what a glance would have seen.""" + + parts = [words for _ok, words in after_save_rows(facts.check)] + if facts.screen_said_saved: + parts.append('"saved" message') + if facts.screen_showed_note: + parts.append("note shown") + return f" {marks.dot} ".join(parts) + + +def catch_reopened_line( + facts: CatchFacts, marks: Marks, name: Optional[str] = None +) -> str: + mark = marks.ok if facts.check.reopened_ok else marks.no + check = facts.check + if name and check.reopened and check.fields_intended == 1: + if check.fields_matched: + return f'{mark} {name} "{facts.note}"' + return f"{mark} {name}: typed value not found" + return f"{mark} {reopened_words(check)}" + + +def catch_verdict(facts: CatchFacts) -> str: + """OpenAdapt's verdict on the bad save, in one word and a reason.""" + + if facts.caught: + flagged = ( + facts.transaction_outcome == "RECONCILIATION_REQUIRED" or facts.escalated + ) + return ( + "STOPPED: a person needs to check the record" + if flagged + else "STOPPED, not marked done" + ) + if facts.stopped: + return "STOPPED, for another reason (see the report)" + if facts.verified: + return "VERIFIED (expected a stop; treat this build as broken)" + return facts.execution_outcome + + +def catch_next(facts: CatchFacts) -> Optional[str]: + """Who decides next, when the run left the decision to a person.""" + + if facts.caught: + return None # the verdict already says a person checks it + if facts.transaction_outcome == "RECONCILIATION_REQUIRED" or facts.escalated: + return "A person checks the record before anything is retried." + return None + + +def catch_aha(facts: CatchFacts) -> Optional[str]: + """The one-line summary, only when the run showed all of it.""" + + # The rows above already say it: the screen looked right, the reopened + # record didn't. A closing sentence would only repeat them. + return None + + +def tally_line(outcome: Outcome, marks: Marks) -> Optional[str]: + """Every save this quickstart made, by verdict, from the run facts. + + A note the restart skipped sent no save, and a run that stopped before + its first click never reached one; neither is counted. + """ + + if outcome.catch is None and outcome.restart is None: + return None + verdicts: list[str] = [] + for run in outcome.runs: + if run.not_ready: + continue + verdicts.append( + "VERIFIED" if run.checked else _stop_word(run.execution_outcome) + ) + if outcome.catch is not None: + catch = outcome.catch + verdicts.append( + "VERIFIED" if catch.verified else _stop_word(catch.execution_outcome) + ) + restart = outcome.restart + if restart is not None and not restart.error: + for note in restart.before + restart.after: + if note.skipped: + continue + verdicts.append( + "VERIFIED" if note.checked else _stop_word(note.execution_outcome) + ) + dot = f" {marks.dot} " + parts = [f"{marks.ok} {verdicts.count('VERIFIED')} VERIFIED"] + if verdicts.count("STOPPED"): + parts.append(f"{marks.stop} {verdicts.count('STOPPED')} STOPPED") + if verdicts.count("other"): + parts.append(f"{marks.no} {verdicts.count('other')} not VERIFIED") + parts.append(f"{outcome.model_calls} model calls") + noun = "save" if len(verdicts) == 1 else "saves" + return f"{len(verdicts)} {noun}{dot}" + dot.join(parts) + + +def _stop_word(execution_outcome: str) -> str: + return "STOPPED" if execution_outcome == "HALTED" else "other" + + def ready_detail(scene: Scene, summary: Optional[str]) -> str: return summary or scene.ready_detail @@ -213,8 +405,7 @@ def compile_seconds(outcome: Outcome, scene: Scene = MOCKMED) -> float: def program_detail(outcome: Outcome, scene: Scene) -> str: noun = "step" if outcome.program_steps == 1 else "steps" detail = f"{outcome.program_steps} {noun}" - if outcome.program_name: - detail += f", {outcome.program_name}" + detail += f", in {display_path(outcome.root / 'bundle')}" return detail if scene.act1_live else f"{detail}, certified under clinical-write" @@ -240,13 +431,14 @@ def all_clear(outcome: Outcome) -> bool: # that ran and went another way is. restart = outcome.restart restart_ok = restart is None or bool(restart.error) or restart.held - return all_clear_runs(outcome) and broke_ok and restart_ok + catch_ok = outcome.catch is None or outcome.catch.caught + return all_clear_runs(outcome) and broke_ok and restart_ok and catch_ok -def clean_title(outcome: Outcome) -> str: +def clean_title(outcome: Outcome, scene: Scene = MOCKMED) -> str: if all_clear_runs(outcome): - return "Saved and checked" - return f"{outcome.checked} of {len(outcome.runs)} saved and checked" + return scene.clean_title + return f"{outcome.checked} of {len(outcome.runs)} {scene.checked_total}" def readback_run(outcome: Outcome) -> Optional[RunFacts]: @@ -281,6 +473,8 @@ def readback_rows(outcome: Outcome) -> list[tuple[str, str]]: def readback_heading(run: RunFacts, scene: Scene) -> str: + if scene.readback_title: + return scene.readback_title where = scene.record_title if where.startswith("The "): where = "the " + where[4:] @@ -313,7 +507,7 @@ def seal_card(outcome: Outcome) -> Optional[SealCard]: def card_outcome(card: Optional[SealCard]) -> str: if card is None: return "Signed" - return "Saved and checked" if card.outcome == "VERIFIED" else card.outcome.title() + return "VERIFIED" if card.outcome == "VERIFIED" else card.outcome.upper() def seal_rows(outcome: Outcome, card: Optional[SealCard], marks: Marks) -> list[str]: @@ -322,7 +516,7 @@ def seal_rows(outcome: Outcome, card: Optional[SealCard], marks: Marks) -> list[ dot = f" {marks.dot} " lines = [] if card is not None: - checks = "record check" + ("" if card.effects_required == 1 else "s") + checks = "save check" + ("" if card.effects_required == 1 else "s") lines.append( dot.join( [ @@ -334,7 +528,7 @@ def seal_rows(outcome: Outcome, card: Optional[SealCard], marks: Marks) -> list[ ) lines.append(f"ed25519 over report sha256 {card.short_digest}") if outcome.seal is not None: - lines.append("Signed by this computer") + lines.append("Signed on this computer") reports = "report" if outcome.seal.sealed == 1 else "reports" lines.append( f"key {outcome.seal.key_id}{dot}{outcome.seal.sealed} {reports} signed" @@ -398,6 +592,11 @@ def failure_step(outcome: Outcome) -> tuple[str, str]: "A run didn't check out. Read its report", str(display_path(failed.report_md)), ) + if outcome.catch is not None and not outcome.catch.caught: + return ( + "The save that only looked fine wasn't caught. Read its report", + str(display_path(outcome.catch.report_md)), + ) if outcome.broken is not None: return ( "The referral didn't stop the program. Read its report", @@ -472,6 +671,8 @@ def _init_shared(self) -> None: self._demo: list[DemoStep] = [] self._show_subtitle = "" self._expected: list[str] = [] + #: The one field each save checks, once Act 2 knows it. + self._field: Optional[str] = None @contextlib.contextmanager def collect_notices(self) -> Iterator[None]: @@ -543,7 +744,8 @@ def _say(self, text: str = "") -> None: self.stream.flush() def _step(self, number: int, text: str) -> None: - self._say(f"[{number}/{STEPS}] {text}") + total = STEPS_WITH_CATCH if self.scene.looks_fine_title else STEPS + self._say(f"[{number}/{total}] {text}") @contextlib.contextmanager def _quiet(self) -> Iterator[None]: @@ -578,13 +780,15 @@ def act(self, number: int, title: str, subtitle: str) -> None: self._flush_ready() dot = self.marks.dot if number == 1: - self._step(2, f"Show it once {dot} {subtitle}") + self._step(2, f"Record the task {dot} {subtitle}") elif number == 2: heading, how = run_heading(subtitle) self._step(4, f"{heading} {dot} {how}" if how else heading) else: self._say() - self._step(5, self.scene.act3_title) + self._step(number + 2, title) + if title == self.scene.looks_fine_title and subtitle: + self._say(f" {subtitle}") def demo_step(self, step: DemoStep) -> None: self._demo.append(step) @@ -598,7 +802,7 @@ def compiling(self): def compiled(self, outcome: Outcome) -> None: self._step( 3, - f"{self.marks.ok} Turn it into a program {self.marks.dot} " + f"{self.marks.ok} Compile a program {self.marks.dot} " f"{program_detail(outcome, self.scene)} {seconds(compile_seconds(outcome, self.scene))}", ) @@ -615,12 +819,23 @@ def run_row(self, run: RunFacts, total: int) -> None: ) def runs_total(self, outcome: Outcome) -> None: - self._say(f" {runs_total_line(outcome, self.marks)}") + self._field = field_name(outcome) + self._say(f" {runs_total_line(outcome, self.marks, self.scene)}") self._say() + rows = checked_rows(outcome, self.marks) if self.scene.verdict_rows else None + if rows and all_clear_runs(outcome): + width = max(len(label) for label in ROW_LABELS) + 3 + for label, text in rows: + self._say(f" {label + ':':<{width}}{text}") + return mark = self.marks.ok if all_clear_runs(outcome) else self.marks.stop - self._say(f"{mark} {clean_title(outcome)}") + self._say(f"{mark} {clean_title(outcome, self.scene)}") rows = readback_rows(outcome) run = readback_run(outcome) + if run is not None and checked_on_screen(run): + self._say(" After the save:") + for ok, words in after_save_rows(run.check): + self._say(f" {_mark(ok, self.marks)} {words}") if rows and run is not None: self._say(f" {readback_heading(run, self.scene)}:") width = max(len(name) for name, _ in rows) @@ -657,6 +872,30 @@ def confirm(self, prompt: str) -> None: def act3_running(self): return self._quiet() + def looks_fine_running(self): + return self._quiet() + + def looks_fine_result(self, facts: CatchFacts) -> None: + labels = ("Typed:", "After the save:", "Reopened the record:", "Verdict:") + width = max(len(label) for label in labels) + 2 + typed, after, reopened, verdict = (f"{label:<{width}}" for label in labels) + self._say(f' {typed}"{facts.note}"') + self._say(f" {after}{catch_screen_line(facts, self.marks)}") + self._say( + f" {reopened}{catch_reopened_line(facts, self.marks, self._field)}" + ) + mark = self.marks.stop if facts.stopped else self.marks.no + self._say( + f" {verdict}{mark} {catch_verdict(facts)} {seconds(facts.seconds)}" + ) + then = catch_next(facts) + if then: + self._say(f" {then}") + aha = catch_aha(facts) + if aha: + self._say() + self._say(aha) + def restart_result(self, facts: Any) -> None: for line in restart_view.plain_lines(facts, self.marks): self._say(f" {line}") @@ -667,7 +906,7 @@ def restart_result(self, facts: Any) -> None: def break_result(self, broken: BreakFacts) -> None: scene = self.scene - labels = ("The screen:", f"{scene.record_title}:", "OpenAdapt:") + labels = ("The screen:", f"{scene.record_title}:", "Verdict:") width = max(len(label) for label in labels) + 2 screen, record, openadapt = (f"{label:<{width}}" for label in labels) self._say(f" {screen}{scene.screen_line(broken)}") @@ -687,6 +926,10 @@ def break_result(self, broken: BreakFacts) -> None: def finale(self, outcome: Outcome, steps: NextSteps) -> None: self._say() + tally = tally_line(outcome, self.marks) + if tally: + self._say(f"Total: {tally}") + self._say() card = seal_card(outcome) if outcome.seal is not None: self._say(f"Your receipt: {card_outcome(card)}") @@ -696,7 +939,7 @@ def finale(self, outcome: Outcome, steps: NextSteps) -> None: if page is not None: self._say(f" Open it: {display_path(page)}") self._say(f" {seal_page_note(outcome)}") - self._say(f" Real receipts from OpenEMR runs: {REAL_SEALS_URL}") + self._say(f" Example receipts from OpenEMR runs: {REAL_SEALS_URL}") self._publish(outcome, steps) self._say() if all_clear(outcome): @@ -793,8 +1036,10 @@ def __init__( from openadapt.quickstart.images import image_protocol + # record=True keeps what was printed (not the spinners), so the + # finale can save the run as one picture (quickstart.svg). self.console = console or Console( - file=stream, highlight=False, soft_wrap=False, width=width + file=stream, highlight=False, soft_wrap=False, width=width, record=True ) if width is None and console is None and self.console.width > MAX_WIDTH: self.console.width = MAX_WIDTH @@ -820,7 +1065,9 @@ def __init__( # -- helpers ---------------------------------------------------------- def _pause(self, value: float) -> None: - if self.animate: + # A short hold after a verdict, so a person can read it. Only on a + # live terminal, never in CI; it never stands in for work. + if self.animate and not os.environ.get("CI"): time.sleep(value) def _spin(self, title: str, detail: str = "") -> _Spinner: @@ -917,15 +1164,32 @@ def setup_progress(self, text: str, milestone: bool) -> None: def setup_done(self, text: str) -> None: self._ready = ready_detail(self.scene, text) + def _title(self, text: str) -> None: + """Name the terminal tab or window (OSC 0), on a live terminal only.""" + + if not self.animate: + return + clean = "".join(ch for ch in text if ch.isprintable()) + try: + self.console.file.write(f"\x1b]0;{clean}\x07") + self.console.file.flush() + except (OSError, ValueError): + pass + def act(self, number: int, title: str, subtitle: str) -> None: + self._title(f"OpenAdapt quickstart: {title}") if number == 1: if self._ready is None: self._ready = ready_detail(self.scene, None) self._flush_ready() self._show_subtitle = subtitle - self._spin("Show it once", subtitle) + self._spin("Record the task", subtitle) elif number == 2: self._run_title, self._run_detail = run_heading(subtitle) + elif title == self.scene.looks_fine_title: + self.console.print() + self._step_line(self.marks.arrow, "bold yellow", title) + self.console.print(f" [dim]{_escape(subtitle)}[/]") else: self.console.print() @@ -940,7 +1204,7 @@ def compiling(self) -> Iterator[None]: self._step_line( self.marks.ok, "green", - "Show it once", + "Record the task", show_detail(self._demo, self._show_subtitle), show_seconds(self._demo), ) @@ -953,14 +1217,14 @@ def compiling(self) -> Iterator[None]: (0, 0, 0, 3), ) ) - with self._spinning("Turn it into a program", "compiling the demonstration"): + with self._spinning("Compile a program", "from the recording"): yield def compiled(self, outcome: Outcome) -> None: self._step_line( self.marks.ok, "green", - "Turn it into a program", + "Compile a program", program_detail(outcome, self.scene), compile_seconds(outcome, self.scene), ) @@ -970,7 +1234,9 @@ def compiled(self, outcome: Outcome) -> None: def _run_text(self, run: RunFacts) -> str: if run.checked: mark = f"[green]{self.marks.ok}[/]" - status = "checked" + (" on a second try" if run.repeated else "") + status = self.scene.checked_in + ( + " on a second try" if run.repeated else "" + ) else: mark = f"[red]{self.marks.stop}[/]" status = ( @@ -1056,10 +1322,34 @@ def runs_total(self, outcome: Outcome) -> None: detail, outcome.act2_seconds, ) + self._field = field_name(outcome) + rows = checked_rows(outcome, self.marks) if self.scene.verdict_rows else None + if rows and clean: + # One run: its step line already says VERIFIED; the rows say how. + if len(outcome.runs) > 1: + for run in sorted(outcome.runs, key=lambda r: r.index): + self.console.print(self._run_text(run)) + self._rows(rows, verdict_style="bold green") + return for run in sorted(outcome.runs, key=lambda r: r.index): self.console.print(self._run_text(run)) self._clean_card(outcome) + def _rows(self, rows: list[tuple[str, str]], verdict_style: str) -> None: + """Typed / After the save / Reopened the record / Verdict, indented.""" + + from rich.padding import Padding + from rich.table import Table + + grid = Table.grid(padding=(0, 2)) + grid.add_column(no_wrap=True, width=len("Reopened the record")) + grid.add_column(overflow="fold") + styles = ("bold", "green", "green", verdict_style) + for (label, text), style in zip(rows, styles): + head = "[bold]Verdict[/]" if label == "Verdict" else f"[dim]{label}[/]" + grid.add_row(head, f"[{style}]{_escape(text)}[/]") + self.console.print(Padding(grid, (0, 0, 0, 3))) + def _clean_card(self, outcome: Outcome) -> None: from rich.panel import Panel from rich.table import Table @@ -1067,12 +1357,30 @@ def _clean_card(self, outcome: Outcome) -> None: clean = all_clear_runs(outcome) rows = readback_rows(outcome) run = readback_run(outcome) + after = ( + after_save_rows(run.check) + if run is not None and checked_on_screen(run) + else [] + ) tone = "green" if clean else "red" def card(shown: int) -> Any: from rich.console import Group parts: list[Any] = [] + if after: + parts.append("[dim]After the save[/]") + lines = Table.grid(padding=(0, 2)) + lines.add_column(no_wrap=True) + for i, (ok, words) in enumerate(after): + if i >= shown or ok is None: + mark = f"[dim]{self.marks.dot}[/]" + elif ok: + mark = f"[green]{self.marks.ok}[/]" + else: + mark = f"[red]{self.marks.no}[/]" + lines.add_row(f" {mark} {_escape(words)}") + parts.extend([lines, ""]) if rows and run is not None: parts.append(f"[dim]{_escape(readback_heading(run, self.scene))}[/]") fields = Table.grid(padding=(0, 2)) @@ -1081,7 +1389,7 @@ def card(shown: int) -> Any: for i, (name, value) in enumerate(rows): mark = ( f"[green]{self.marks.ok}[/]" - if i < shown + if i + len(after) < shown else f"[dim]{self.marks.dot}[/]" ) fields.add_row( @@ -1094,7 +1402,7 @@ def card(shown: int) -> Any: ) return Panel( Group(*parts), - title=f"[bold {tone}] {_escape(clean_title(outcome))} [/]", + title=f"[bold {tone}] {_escape(clean_title(outcome, self.scene))} [/]", title_align="left", border_style=tone, expand=False, @@ -1102,7 +1410,8 @@ def card(shown: int) -> Any: ) self.console.print() - if self.animate and rows: + ticks = len(after) + len(rows) + if self.animate and ticks: from rich.live import Live with Live( @@ -1112,11 +1421,11 @@ def card(shown: int) -> Any: redirect_stdout=False, redirect_stderr=False, ) as live: - for shown in range(1, len(rows) + 1): + for shown in range(1, ticks + 1): time.sleep(_TICK_S) live.update(card(shown), refresh=True) else: - self.console.print(card(len(rows))) + self.console.print(card(ticks)) def not_ready(self, explanation: str, skipped_break: bool) -> None: self.console.print(f"[yellow]{_escape(explanation)}[/]") @@ -1124,12 +1433,8 @@ def not_ready(self, explanation: str, skipped_break: bool) -> None: self.console.print(f"[dim]{_escape(skipped_break_line(self.scene))}[/]") def act3_setup(self) -> None: - self._step_line( - self.marks.arrow, - "bold yellow", - self.scene.act3_title, - self.scene.act3_setup, - ) + self._step_line(self.marks.arrow, "bold yellow", self.scene.act3_title) + self.console.print(f" [dim]{_escape(self.scene.act3_setup)}[/]") def _ask(self, prompt: str) -> str: return self.console.input(f"[bold]{_escape(prompt)}[/]") @@ -1143,6 +1448,47 @@ def confirm(self, prompt: str) -> None: def act3_running(self): return self._spinning(self.scene.act3_title, self.scene.act3_running) + def looks_fine_running(self): + return self._spinning( + self.scene.looks_fine_title, self.scene.looks_fine_running + ) + + def looks_fine_result(self, facts: CatchFacts) -> None: + from rich.padding import Padding + from rich.table import Table + + label = len("Reopened the record") + grid = Table.grid(padding=(0, 2)) + grid.add_column(no_wrap=True, width=label) + grid.add_column(overflow="fold") + grid.add_row("[dim]Typed[/]", f'[bold]"{_escape(facts.note)}"[/]') + screen = catch_screen_line(facts, self.marks) + grid.add_row("[dim]After the save[/]", f"[green]{_escape(screen)}[/]") + self.console.print(Padding(grid, (0, 0, 0, 3))) + self._pause(0.4) + reopened = catch_reopened_line(facts, self.marks, self._field) + tone = "green" if facts.check.reopened_ok else "bold red" + last = Table.grid(padding=(0, 2)) + last.add_column(no_wrap=True, width=label) + last.add_column(overflow="fold") + last.add_row("[dim]Reopened the record[/]", f"[{tone}]{_escape(reopened)}[/]") + style = "bold yellow" if facts.caught else "bold red" + mark = self.marks.stop if facts.stopped else self.marks.no + last.add_row( + "[bold]Verdict[/]", + f"[{style}]{mark} {_escape(catch_verdict(facts))}[/] " + f"[dim]{seconds(facts.seconds)}[/]", + ) + self.console.print(Padding(last, (0, 0, 0, 3))) + then = catch_next(facts) + if then: + self.console.print(f" [dim]{_escape(then)}[/]") + aha = catch_aha(facts) + if aha: + self._pause(0.3) + self.console.print() + self.console.print(_escape(aha)) + def restart_result(self, facts: Any) -> None: if facts.error: self.console.print( @@ -1164,13 +1510,16 @@ def row(run: Any) -> None: tone = "bold yellow" if facts.killed else "bold red" stop = restart_view.stop_line(facts, self.marks) self.console.print(f" [{tone}]{_escape(stop)}[/]") - self.console.print(" [bold]Restarted with the same ledger:[/]") + self.console.print(" [bold]After restart:[/]") for run in facts.after: row(run) tone = "green" if facts.held else "red" copies = restart_view.copies_line(facts) - self.console.print(f" [bold]The database:[/] [{tone}]{_escape(copies)}[/]") - self.console.print(f"[dim]{_escape(restart_view.why_line(facts))}[/]") + self.console.print( + f" [bold]Reopened the records:[/] [{tone}]{_escape(copies)}[/]" + ) + if not facts.held: + self.console.print(f"[dim]{_escape(restart_view.why_line(facts))}[/]") summary = restart_view.summary_line(facts) if summary: self.console.print() @@ -1237,7 +1586,7 @@ def _verdicts(self, broken: BreakFacts) -> None: verdict = openadapt_verdict(broken, self.marks, scene) style = "bold yellow" if broken.stopped else "bold red" grid.add_row( - "[bold]OpenAdapt[/]", + "[bold]Verdict[/]", f"[{style}]{_escape(verdict)}[/] [dim]{seconds(broken.seconds)}[/]", ) self.console.print(grid) @@ -1329,7 +1678,7 @@ def _seal(self, outcome: Outcome, card: Optional[SealCard]) -> None: if self.hyperlinks else REAL_SEALS_URL ) - links.add_row("[dim]Real receipts[/]", f"[cyan]{real}[/]") + links.add_row("[dim]OpenEMR receipts[/]", f"[cyan]{real}[/]") self.console.print(links) def finale(self, outcome: Outcome, steps: NextSteps) -> None: @@ -1338,6 +1687,10 @@ def finale(self, outcome: Outcome, steps: NextSteps) -> None: self._stop_spin() self.console.print() + tally = tally_line(outcome, self.marks) + if tally: + self.console.print(f"[bold]Total[/] {_escape(tally)}") + self.console.print() if outcome.seal is not None: self._seal(outcome, seal_card(outcome)) runs = publish_runs(outcome) @@ -1389,6 +1742,26 @@ def say(line: str) -> None: self.console.print(f"[dim]{_escape(notice)}[/]") if steps.shadow: self.console.print(f"[yellow]{_escape(steps.shadow)}[/]") + picture = self._save_picture(outcome.root) + if picture is not None: + self.console.print( + f"[dim]A picture of this run:[/] " + f"{self._link(picture, str(display_path(picture)))}", + soft_wrap=True, + ) + self._title("OpenAdapt quickstart: done") + + def _save_picture(self, root: Path) -> Optional[Path]: + """Save what this run printed as ``quickstart.svg`` in its folder.""" + + if not getattr(self.console, "record", False) or not root.is_dir(): + return None + path = root / "quickstart.svg" + try: + self.console.save_svg(str(path), title="openadapt quickstart") + except (OSError, ValueError): + return None + return path def detail(self, lines: list[str]) -> None: for line in lines: diff --git a/openadapt/quickstart/workers.py b/openadapt/quickstart/workers.py index dfce13abcc..81f6402dff 100644 --- a/openadapt/quickstart/workers.py +++ b/openadapt/quickstart/workers.py @@ -2,7 +2,7 @@ Each worker starts while Act 1 is still demonstrating and compiling: it loads the engine, starts its own browser, and serves its own copy of the clinic app -with its own database. When the program is ready, each worker runs it once +with its own copy of the clinic app. When the program is ready, each worker runs it once for one note, through the same governed path as any run (the Standard run gate, identity checks, postconditions, the database read-back), and sends back the facts. Nothing is shared between runs but the program on disk, which @@ -151,9 +151,12 @@ def _worker_main(conn: Connection, visible: bool, browser: str = "") -> None: def _facts(fields: dict[str, Any]) -> Any: from openadapt.quickstart.engine import RunFacts + from openadapt.quickstart.screen_check import ScreenCheck fields = dict(fields) fields["run_dir"] = Path(fields["run_dir"]) + if isinstance(fields.get("check"), dict): + fields["check"] = ScreenCheck(**fields["check"]) return RunFacts(**fields) diff --git a/packages/flow/openadapt_flow/policies/screen-write.yaml b/packages/flow/openadapt_flow/policies/screen-write.yaml new file mode 100644 index 0000000000..ab63f604b5 --- /dev/null +++ b/packages/flow/openadapt_flow/policies/screen-write.yaml @@ -0,0 +1,29 @@ +name: screen-write +description: >- + Strict gate for irreversible writes, for systems the runner can't read + except through their screens: no unarmed clicks, no vacuous steps, identity + required on every record-navigation and write step, a declared effect check + on every write (it may read the screen after the save and then the reopened + record, instead of a database or API), no unconfirmed effect bindings, and + human sign-off for any thinly-evidenced step. It is record-write without + the idempotency-key rule; repeated saves are held off by the run's + at-most-once ledger instead. +prohibit_unarmed_clicks: true +prohibit_vacuous_postconditions: true +require_identity_for: + - entity_navigation + - write +require_system_effects_for: + - write +prohibit_unconfirmed_effect_bindings: true +require_screen_postconditions_for: + - write + - save + - submit + - create + - update + - delete + - confirm + - send +max_unverified_steps: 0 +require_human_approval_below_confidence: 0.8 diff --git a/packages/flow/public-artifacts.json b/packages/flow/public-artifacts.json index 9332d824c1..0fb823630c 100644 --- a/packages/flow/public-artifacts.json +++ b/packages/flow/public-artifacts.json @@ -2487,6 +2487,7 @@ "openadapt_flow/policies/clinical-write.yaml", "openadapt_flow/policies/permissive.yaml", "openadapt_flow/policies/record-write.yaml", + "openadapt_flow/policies/screen-write.yaml", "openadapt_flow/registry_trusted_root.json", "openadapt_flow/secret_field_vocabulary.json", "openadapt_flow/taskgen/profiles/mockmed.yaml", diff --git a/packages/flow/tests/test_policy.py b/packages/flow/tests/test_policy.py index 06176a0b1a..4d3e43fcfa 100644 --- a/packages/flow/tests/test_policy.py +++ b/packages/flow/tests/test_policy.py @@ -306,8 +306,11 @@ def test_builtins_present(self): assert "permissive" in names assert "clinical-write" in names assert "record-write" in names + assert "screen-write" in names - @pytest.mark.parametrize("name", ["permissive", "clinical-write", "record-write"]) + @pytest.mark.parametrize( + "name", ["permissive", "clinical-write", "record-write", "screen-write"] + ) def test_example_policies_parse(self, name): pol = load_policy(name) assert isinstance(pol, Policy) @@ -355,6 +358,47 @@ def refusals(name: str) -> list[tuple[str, str | None]]: assert refusals("record-write") assert refusals("record-write") == refusals("clinical-write") + def test_screen_write_is_record_write_without_the_idempotency_key_rule(self): + # screen-write is for a customer without database or API access: a + # write's declared check may read the screen after the save and the + # reopened record. Such a check carries no system idempotency key, so + # that one rule is dropped (the run's at-most-once ledger holds off a + # repeated save). Every other rule is pinned to record-write. + def rules(policy: Policy) -> dict: + return policy.model_dump( + exclude={"name", "description", "require_idempotency_key_for"} + ) + + screen, record = load_policy("screen-write"), load_policy("record-write") + assert rules(screen) == rules(record) + assert not screen.require_idempotency_key_for + assert "write" in screen.require_system_effects_for + assert not re.search(r"clinic|patient|emr\b", screen.description, re.I) + + def test_screen_write_refuses_a_save_with_no_check_and_passes_a_checked_one( + self, + ): + unchecked = _clean_workflow() + report = evaluate_policy(unchecked, load_policy("screen-write")) + assert not report.passed + assert any( + v.rule == "require_system_effects_for" and v.step_id == "step_001" + for v in report.violations + ) + + checked = _clean_workflow() + checked.steps[1].effects = [ + Effect( + kind=EffectKind.FIELD_EQUALS, + value=ValueExpr(literal="Follow-up in two weeks"), + ) + ] + assert evaluate_policy(checked, load_policy("screen-write")).passed + + def test_screen_write_refuses_a_gappy_bundle(self): + report = evaluate_policy(_gappy_workflow(), load_policy("screen-write")) + assert not report.passed + def test_an_app_selects_record_write_in_its_verify_yaml(self): from openadapt_flow.qualify.config import CampaignConfig diff --git a/tests/snapshots/quickstart_openemr_plain.snapshot b/tests/snapshots/quickstart_openemr_plain.snapshot index a31baa9691..f6c3810301 100644 --- a/tests/snapshots/quickstart_openemr_plain.snapshot +++ b/tests/snapshots/quickstart_openemr_plain.snapshot @@ -3,19 +3,19 @@ Synthetic data only. Files go to openadapt-quickstart restoring the synthetic baseline [1/5] ✓ OpenEMR ready · OpenEMR 8.0.0.3 at http://127.0.0.1:9741: reused the running copy 5.7s -[2/5] Show it once · a referral as it was demonstrated once in OpenEMR 8.0.0.3 +[2/5] Record the task · a referral as it was demonstrated once in OpenEMR 8.0.0.3 ✓ Title: "Ms." 2.1s ✓ First name: "OpenAdapt" 5.2s ✓ Click Create New Patient 34.5s ✓ Click Confirm Create New Patient 36.8s -[3/5] ✓ Turn it into a program · 29 steps, openemr-create-synthetic-patient, certified under clinical-write 0.5s +[3/5] ✓ Compile a program · 29 steps, in openadapt-quickstart/bundle, certified under clinical-write 0.5s [4/5] Run it on 5 new referrals · all at once 1/5 Ines Carvalho ✓ checked in OpenEMR's record 30.1s 2/5 Theo Lindqvist ✓ checked in OpenEMR's record 30.2s 3/5 Grace Adeyemi ✓ checked in OpenEMR's record 30.3s 4/5 Arlo Whitcombe ✓ checked in OpenEMR's record 30.4s 5/5 Priya Raman ✓ checked in OpenEMR's record 30.5s - 5 of 5 saved and checked · 0 AI calls · $0.00 · 0.5s + 5 of 5 saved and checked · 0 model calls · $0.00 · 0.5s ✓ Saved and checked 5 of 5 runs · 0 model calls · $0.00 · 0.5s @@ -24,15 +24,15 @@ Synthetic data only. Files go to openadapt-quickstart OpenEMR already has a chart for Rosa Delgado. The next referral is a Rosa Delgado with another birth date. The screen: "a matching chart: Delgado, Rosa, born 1958-03-27" OpenEMR's record: 0 new charts - OpenAdapt: ■ Stopped before saving: possible duplicate 24.5s + Verdict: ■ Stopped before saving: possible duplicate 24.5s Why: OpenEMR's duplicate check found an existing chart. The program saves only when it finds none, so it stopped before saving. The demonstration clicked Confirm Create New Patient here. Replaying those clicks would have saved a possible duplicate. OpenAdapt stopped. Your receipt: Signed - Signed by this computer + Signed on this computer key seal-ed25519-0123456789abcdef · 5 reports signed - Real receipts from OpenEMR runs: https://openadapt.ai/seals + Example receipts from OpenEMR runs: https://openadapt.ai/seals Next: Give your agent this task as a tool claude mcp add openadapt -- openadapt agent serve --bundles openadapt-quickstart/bundle diff --git a/tests/snapshots/quickstart_plain.snapshot b/tests/snapshots/quickstart_plain.snapshot index 19ee886e8e..7944c5cd71 100644 --- a/tests/snapshots/quickstart_plain.snapshot +++ b/tests/snapshots/quickstart_plain.snapshot @@ -1,48 +1,52 @@ -OpenAdapt quickstart: show a task once, run it, then stop it mid-batch and watch the restart skip what was already saved. +OpenAdapt quickstart: OpenAdapt turns a task shown once into a program and checks every save it makes. Here a script stands in for you, in a demo clinic app. Synthetic data only. Files go to openadapt-quickstart -[1/5] ✓ Clinic app ready · synthetic data, on this computer -[2/5] Show it once · a demonstration in a synthetic clinic app, in a hidden browser +[1/6] ✓ Clinic app ready · on this computer +[2/6] Record the task · in the demo clinic app, in a hidden browser ✓ Click Open 0.4s ✓ Click New Encounter 0.7s ✓ Click Triage 0.9s ✓ Click Note 1.1s ✓ Type "Synthetic follow-up in two weeks" 1.3s ✓ Click Save Encounter 1.6s -[3/5] ✓ Turn it into a program · 6 steps, local-quickstart 0.0s -[4/5] Run it on 5 new notes · all at once - 1/5 Follow-up in two weeks ✓ checked in the database 2.6s - 2/5 Recheck blood pressure next month ✓ checked in the database 2.7s - 3/5 Refer to physical therapy ✓ checked in the database 2.8s - 4/5 Repeat labs before next visit ✓ checked in the database 2.9s - 5/5 No change to the care plan ✓ checked in the database 3.0s - 5 of 5 saved and checked · 0 AI calls · $0.00 · 0.5s +[3/6] ✓ Compile a program · 6 steps, in openadapt-quickstart/bundle 0.0s +[4/6] Run it on 5 new notes · all at once + 1/5 Follow-up in two weeks ✓ VERIFIED 2.6s + 2/5 Recheck blood pressure next month ✓ VERIFIED 2.7s + 3/5 Refer to physical therapy ✓ VERIFIED 2.8s + 4/5 Repeat labs before next visit ✓ VERIFIED 2.9s + 5/5 No change to the care plan ✓ VERIFIED 3.0s + 5 of 5 VERIFIED · 0 model calls · $0.00 · 0.5s -✓ Saved and checked - The record, read back from the database: - ✓ patient_id p1 - ✓ type Triage - ✓ note "Follow-up in two weeks" - 5 of 5 runs · 0 model calls · $0.00 · 0.5s + Typed: "Follow-up in two weeks" + After the save: form closed · no error shown + Reopened the record: ✓ Note "Follow-up in two weeks" + Verdict: ✓ VERIFIED -[5/5] Stop it mid-batch, then restart - A batch of 2 new notes, each in its own copy of the clinic's database. The runner process is stopped hard after note 1 saves, then started again. - 1/2 Refer to physical therapy ✓ checked in the database 3.1s - ■ Runner process stopped with SIGKILL after note 1, before note 2 - Restarted with the same ledger: - 1/2 Refer to physical therapy · Skipped: the ledger has it as done, no save sent 0.4s - 2/2 Repeat labs before next visit ✓ checked in the database 3.2s - The database: each note saved once (note 1: 1 record, note 2: 1 record) - Why: OpenAdapt records each note in a ledger on disk before it saves it, and records the outcome after the record check. On restart it found note 1 marked done, so it sent no save for note 1 and saved only note 2. +[5/6] Run it against a faulty server + The demo server drops the note but still reports success. + Typed: "Recheck blood pressure next month" + After the save: form closed · no error shown · "saved" message · note shown + Reopened the record: ✗ Note: typed value not found + Verdict: ■ STOPPED: a person needs to check the record 2.9s -The runner was killed partway through the batch. On restart, OpenAdapt sent no save for note 1 and saved note 2. +[6/6] Kill the runner mid-batch, then restart it + A batch of 2 notes. The runner is killed after note 1 is saved. + 1/2 Refer to physical therapy ✓ VERIFIED 3.1s + ■ Runner killed with SIGKILL after note 1, before note 2 + After restart: + 1/2 Refer to physical therapy · SKIPPED: logged as saved before the kill 0.4s + 2/2 Repeat labs before next visit ✓ VERIFIED 3.2s + Reopened the records: each note appears once + +Total: 8 saves · ✓ 7 VERIFIED · ■ 1 STOPPED · 0 model calls Your receipt: Signed - Signed by this computer + Signed on this computer key seal-ed25519-0123456789abcdef · 5 reports signed Open it: openadapt-quickstart/run-1/seal.html checks the signature in your browser, offline; nothing is uploaded - Real receipts from OpenEMR runs: https://openadapt.ai/seals + Example receipts from OpenEMR runs: https://openadapt.ai/seals Next: Give your agent this task as a tool claude mcp add openadapt -- openadapt agent serve --allow-run diff --git a/tests/test_quickstart.py b/tests/test_quickstart.py index 11fcd2814a..5fd410d836 100644 --- a/tests/test_quickstart.py +++ b/tests/test_quickstart.py @@ -35,6 +35,7 @@ from openadapt.quickstart.engine import ( RUN_NOTES, BreakFacts, + CatchFacts, DemoStep, RunFacts, SealFacts, @@ -51,6 +52,7 @@ ) from openadapt.quickstart.restart import NoteRun, RestartFacts from openadapt.quickstart.scene import MOCKMED, OPENEMR +from openadapt.quickstart.screen_check import ScreenCheck from openadapt.quickstart.story import NextSteps, Outcome, run_story from openadapt.quickstart.view import Marks, PlainView, RichView, make_view, more_lines @@ -99,6 +101,41 @@ def _run(root: Path, index: int, **overrides) -> RunFacts: effects_confirmed=2, seconds=2.5 + index / 10, plain_label="Done and checked", + check=_check(), + ) + return replace(facts, **overrides) + + +def _check(**overrides) -> ScreenCheck: + """A save checked on screen and in the reopened record, unless overridden.""" + + check = ScreenCheck( + checked_how="reopened", + fields_intended=1, + fields_read=1, + fields_matched=1, + left_edit_mode=True, + error_shown=False, + banner_only=False, + reopened=True, + ) + return replace(check, **overrides) + + +def _catch(root: Path, **overrides) -> CatchFacts: + """The save that only looks fine, caught at the reopened record.""" + + facts = CatchFacts( + run_dir=root / "run-looks-fine", + note=RUN_NOTES[1], + execution_outcome="HALTED", + transaction_outcome="RECONCILIATION_REQUIRED", + check=_check(checked_how="unchecked", fields_read=0, fields_matched=0), + escalated=True, + model_calls=0, + seconds=2.9, + screen_showed_note=True, + screen_said_saved=True, ) return replace(facts, **overrides) @@ -180,6 +217,7 @@ def __init__( runs: Optional[dict[int, dict]] = None, broken: Optional[dict] = None, restart: Optional[dict] = None, + catch: Optional[dict] = None, act3: str = "restart", program_steps: int = 6, seal: Optional[SealFacts] = SealFacts("seal-ed25519-0123456789abcdef", 5), @@ -196,11 +234,13 @@ def __init__( self._runs = runs or {} self._broken = broken or {} self._restart = restart or {} + self._catch = catch or {} if act3 == "break": # OpenEMR's Act 3: the story finds no restart and runs break_it. self.scene = OPENEMR self.crash_restart = None self.prepare_restart = None + self.looks_fine = None else: self.scene = MOCKMED self._program_steps = program_steps @@ -232,11 +272,11 @@ def program_name(self): return "local-quickstart" def readback_fields(self): - return [ - ("patient_id", "p1", None), - ("type", "Triage", None), - ("note", None, "note"), - ] + return [("Note", None, "note")] + + def looks_fine(self): + self.calls.append("looks fine") + return _catch(self.root, **self._catch) def note_param(self): return self._note_param @@ -346,12 +386,13 @@ def test_plain_output_runs_the_three_acts_in_order(root): "record", "compile", *(f"run {index}" for index in range(1, 6)), + "looks fine", "restart", "exit", "seal pages", ] assert engine.calls.index("seal") > engine.calls.index("run 5") - steps = [output.index(f"\n[{n}/5] ") for n in (1, 2, 3, 4, 5)] + steps = [output.index(f"\n[{n}/6] ") for n in (1, 2, 3, 4, 5, 6)] assert steps == sorted(steps) assert "\x1b[" not in output @@ -368,7 +409,9 @@ def test_plain_output_has_no_internal_vocabulary(root): "RECONCILIATION_REQUIRED", "REJECTED_POLICY", "HALTED", - "VERIFIED", + # VERIFIED, STOPPED and SKIPPED are the verdict words a receipt shows; + # the quickstart uses them on purpose. The database is not the check. + "database", "system of record", "tier", "fixture", @@ -478,16 +521,16 @@ def test_numbers_follow_the_runs(root): ) output, outcome = _plain(engine) - assert "Turn it into a program · 9 steps, local-quickstart" in output + assert "Compile a program · 9 steps, in openadapt-quickstart/bundle" in output assert "Click Go" in output and "3.8s" in output assert "11.2s" in output # run 2's own time assert "■ Stopped before saving" in output - assert "4 of 5 saved and checked · 3 AI calls · $0.04" in output + assert "4 of 5 VERIFIED · 3 model calls · $0.04" in output assert "5 of 5" not in output assert "0 AI calls" not in output # The four checked runs. assert "key seal-ed25519-0123456789abcdef · 4 reports signed" in output - assert "■ 4 of 5 saved and checked" in output + assert "■ 4 of 5 VERIFIED" in output assert "4 of 5 runs · 3 model calls · $0.04 · " in output # A run that didn't check out replaces the next step with its report. assert "Next: A run didn't check out. Read its report" in output @@ -498,30 +541,23 @@ def test_numbers_follow_the_runs(root): def test_a_repeated_run_says_so(root): output, _ = _plain(FakeEngine(root, runs={3: {"repeated": True}})) - assert "✓ checked in the database (on a second try)" in output + assert "✓ VERIFIED (on a second try)" in output assert output.count("second try") == 1 def test_act_three_shows_the_stop_the_skip_and_one_save_per_note(root): output, outcome = _plain(FakeEngine(root)) - act = output[output.index("[5/5] ") :] - assert act.startswith("[5/5] Stop it mid-batch, then restart\n") + act = output[output.index("[6/6] ") :] + assert act.startswith("[6/6] Kill the runner mid-batch, then restart it\n") lines = [line.strip() for line in act.splitlines()] - at = lines.index( - "■ Runner process stopped with SIGKILL after note 1, before note 2" - ) + at = lines.index("■ Runner killed with SIGKILL after note 1, before note 2") assert lines[at - 1].startswith("1/2 Refer to physical therapy") - assert lines[at - 1].endswith("✓ checked in the database 3.1s") - assert lines[at + 1] == "Restarted with the same ledger:" - assert "· Skipped: the ledger has it as done, no save sent 0.4s" in lines[at + 2] + assert lines[at - 1].endswith("✓ VERIFIED 3.1s") + assert lines[at + 1] == "After restart:" + assert "· SKIPPED: logged as saved before the kill 0.4s" in lines[at + 2] assert lines[at + 3].startswith("2/2 Repeat labs before next visit") - assert lines[at + 4] == ( - "The database: each note saved once (note 1: 1 record, note 2: 1 record)" - ) - assert ( - "The runner was killed partway through the batch. On restart, " - "OpenAdapt sent no save for note 1 and saved note 2." in output - ) + assert lines[at + 4] == ("Reopened the records: each note appears once") + assert "Reopened the records: each note appears once" in output assert outcome.restart is not None and outcome.restart.held assert "Next: Give your agent this task as a tool" in output @@ -529,9 +565,10 @@ def test_act_three_shows_the_stop_the_skip_and_one_save_per_note(root): @pytest.mark.parametrize( ("overrides", "shown"), [ - ({"copies": [2, 1]}, "note 1: 2 records, note 2: 1 record"), + ({"copies": [2, 1]}, "note 1: 2 encounters, note 2: 1 encounter"), + ({"copies": [None, 1]}, "Reopened the records: the chart couldn't be read"), ({"killed": False}, "✗ The runner was still running; it was not stopped"), - ({"before": []}, "stopped with SIGKILL before any note, before note 1"), + ({"before": []}, "killed with SIGKILL before any note, before note 1"), ], ) def test_a_restart_that_went_another_way_says_what_happened(root, overrides, shown): @@ -576,7 +613,7 @@ def test_a_note_two_the_restart_skipped_is_not_a_success(root): output, _ = _plain( FakeEngine(root, restart={"after": [facts.after[0], second], "copies": [1, 0]}) ) - assert "note 2: 0 records" in output + assert "note 2: 0 encounters" in output assert "sent no save for note 1 and saved note 2" not in output @@ -630,8 +667,8 @@ def test_a_stop_the_check_did_not_cause_is_not_the_demonstration(root): def test_an_engine_without_run_inputs_does_not_claim_new_notes(root): output, _ = _plain(FakeEngine(root, note_param=False)) # Act 3's batch always gives each run its note; Act 2 is what this checks. - assert "new notes" not in output[: output.index("[5/5]")] - assert "[4/5] Run it 5 times · all at once" in output + assert "new notes" not in output[: output.index("[5/6]")] + assert "[4/6] Run it 5 times · all at once" in output @pytest.mark.parametrize( @@ -663,7 +700,7 @@ def test_the_finale_names_the_persons_own_seal_then_the_real_ones(root): ) assert ( finale[at + 2] - == " Real receipts from OpenEMR runs: https://openadapt.ai/seals" + == " Example receipts from OpenEMR runs: https://openadapt.ai/seals" ) # The person's own Seal opens; the side-by-side page does not. assert opened == [root / "run-1" / "seal.html"] @@ -714,7 +751,7 @@ def test_no_prompt_without_a_terminal(root, monkeypatch): root, visible=False, last_act=True, verbose=False, steps=_steps, stream=stream ) assert "Press Enter" not in stream.getvalue() - assert "[5/5] Stop it mid-batch, then restart" in stream.getvalue() + assert "[6/6] Kill the runner mid-batch, then restart it" in stream.getvalue() def test_a_terminal_gets_the_prompt_and_waiting_is_not_counted(root, monkeypatch): @@ -886,13 +923,20 @@ def test_terminal_view_tells_the_story_with_boxes_and_one_next_step(root): assert "\x1b[" in output assert "✓ Clinic app ready" in text assert "Open › New Encounter › Triage › Note" in text - assert "─ Saved and checked ─" in text - assert '✓ note "Follow-up in two weeks"' in text - assert "Stop it mid-batch, then restart" in text - assert "■ Runner process stopped with SIGKILL after note 1, before note 2" in text - assert "Skipped: the ledger has it as done, no save sent" in text - assert "The database: each note saved once" in text - assert "The screen" not in text + assert "─ VERIFIED ─" not in text # rows, not a card + assert "✓ VERIFIED" in text + assert "form closed · no error shown" in text + assert "Reopened the record" in text + assert '✓ Note "Follow-up in two weeks"' in text + assert "Run it against a faulty server" in text + assert "✗ Note: typed value not found" in text + assert "■ STOPPED: a person needs to check the record" in text + assert "Kill the runner mid-batch, then restart it" in text + assert "■ Runner killed with SIGKILL after note 1, before note 2" in text + assert "SKIPPED: logged as saved before the kill" in text + assert "Reopened the records: each note appears once" in text + assert "database" not in text + assert "─ The screen" not in text assert "◆ Your receipt" in text and "●─●─●─●─●─◆" in text assert "claude mcp add openadapt -- openadapt agent serve --allow-run" in text assert text.count("Next ") == 1 @@ -945,12 +989,11 @@ def test_the_seal_card_reads_the_runs_receipt(root): (run / "receipt.json").write_text(json.dumps(RECEIPT)) (run / "seal.json").write_text(json.dumps(SEAL)) plain, _ = _plain(FakeEngine(root)) - assert "Your receipt: Saved and checked" in plain - assert "6 of 6 steps · 2 of 2 record checks · 0 model calls" in plain + assert "Your receipt: VERIFIED" in plain + assert "6 of 6 steps · 2 of 2 save checks · 0 model calls" in plain assert "ed25519 over report sha256 6dd4a7f2d1ea" in plain - assert "VERIFIED" not in plain text = _visible(_rich(root, {})) - assert "6 of 6 steps · 2 of 2 record checks · 0 model calls" in text + assert "6 of 6 steps · 2 of 2 save checks · 0 model calls" in text RECEIPT = { @@ -1605,3 +1648,96 @@ def fake_run_story(engine, view, **kwargs): stream=_Terminal(), ) assert seen["interactive"] is False + + +# --------------------------------------------------------------------------- +# The save that only looks fine +# --------------------------------------------------------------------------- + + +def test_the_save_that_only_looks_fine_is_stopped_at_the_reopened_record(root): + output, outcome = _plain(FakeEngine(root)) + act = output[output.index("[5/6] ") : output.index("[6/6] ")] + assert act.startswith("[5/6] Run it against a faulty server\n") + assert "drops the note but still reports success" in act + assert '"Recheck blood pressure next month"' in act + assert 'form closed · no error shown · "saved" message · note shown' in act + assert "✗ Note: typed value not found" in act + assert "■ STOPPED: a person needs to check the record" in act + assert "A person checks the record before anything is retried." not in act + assert "Only the reopened record" not in act + assert outcome.catch is not None and outcome.catch.caught + assert "Total: 8 saves · ✓ 7 VERIFIED · ■ 1 STOPPED" in output + + +def test_a_screen_flag_the_run_did_not_observe_is_not_claimed(root): + check = _check( + checked_how="unchecked", + fields_read=0, + fields_matched=0, + error_shown=None, + ) + output, outcome = _plain( + FakeEngine(root, catch={"check": check, "screen_showed_note": False}) + ) + act = output[output.index("[5/6] ") : output.index("[6/6] ")] + assert "· errors not observed" in act + assert "no error shown" not in act + assert "note shown" not in act + # Without the error flag the save's screen wasn't seen to look right, so + # the stop isn't attributed to the reopened record. + assert outcome.catch is not None and not outcome.catch.caught + assert "Only the reopened record" not in act + assert "Next: The save that only looked fine wasn't caught" in output + + +def test_a_save_that_only_looks_fine_but_verified_fails_the_quickstart(root): + output, outcome = _plain( + FakeEngine( + root, + catch={ + "execution_outcome": "VERIFIED", + "transaction_outcome": "VERIFIED", + "check": _check(), + "escalated": False, + }, + ) + ) + assert "VERIFIED (expected a stop; treat this build as broken)" in output + assert "Next: The save that only looked fine wasn't caught" in output + assert "claude mcp add" not in output + + +def test_openemr_has_no_looks_fine_act(root): + engine = FakeEngine(root, act3="break") + output, outcome = _plain(engine) + assert "looks fine" not in engine.calls + assert outcome.catch is None + assert "[5/5] " in output + + +def test_flagged_for_review_only_when_the_run_left_it_to_a_person(root): + from openadapt.quickstart.view import catch_verdict + + assert catch_verdict(_catch(root)) == "STOPPED: a person needs to check the record" + unflagged = _catch(root, transaction_outcome="HALTED", escalated=False) + assert unflagged.caught + assert catch_verdict(unflagged) == "STOPPED, not marked done" + + +def test_the_total_counts_only_saves_and_names_every_verdict(root): + from openadapt.quickstart.view import tally_line + + marks = Marks("utf-8") + outcome = Outcome(root=root) + outcome.runs = [ + _run(root, 1), + _run(root, 2, checked=False, execution_outcome="HALTED"), + _run(root, 3, checked=False, execution_outcome="FAILED"), + # Stopped before its first click: it never reached a save. + _run(root, 4, checked=False, execution_outcome="HALTED", not_ready=True), + ] + outcome.catch = _catch(root) + line = tally_line(outcome, marks) + assert line is not None + assert line.startswith("4 saves · ✓ 1 VERIFIED · ■ 2 STOPPED · ✗ 1 not VERIFIED") diff --git a/tests/test_quickstart_restart.py b/tests/test_quickstart_restart.py index 8a0802a37e..ef72c55f5f 100644 --- a/tests/test_quickstart_restart.py +++ b/tests/test_quickstart_restart.py @@ -166,7 +166,7 @@ def test_kill_stops_the_worker_with_sigkill(monkeypatch): def test_saved_once_needs_the_skip_not_just_one_record_each(): """MockMed drops a resend whose key it already has, so [1, 1] alone can't - show "saved once": the line needs note 1 skipped with no actions.""" + show "appears once": the line needs note 1 skipped with no actions.""" from openadapt.quickstart.restart import RestartFacts from openadapt.quickstart.restart_view import copies_line @@ -182,8 +182,8 @@ def test_saved_once_needs_the_skip_not_just_one_record_each(): ] resent.copies = [1, 1] assert not resent.held - assert "saved once" not in copies_line(resent) - assert copies_line(resent) == "note 1: 1 record, note 2: 1 record" + assert "appears once" not in copies_line(resent) + assert copies_line(resent) == "note 1: 1 encounter, note 2: 1 encounter" held = replace( resent, @@ -193,4 +193,4 @@ def test_saved_once_needs_the_skip_not_just_one_record_each(): ], ) assert held.held - assert copies_line(held).startswith("each note saved once (") + assert copies_line(held) == "each note appears once" diff --git a/tests/test_quickstart_robust.py b/tests/test_quickstart_robust.py index 8252c46e7e..5d7ec0569f 100644 --- a/tests/test_quickstart_robust.py +++ b/tests/test_quickstart_robust.py @@ -202,7 +202,7 @@ def test_a_wide_terminal_draws_at_most_max_width(root, monkeypatch, columns): # Only an unbroken file:// address may run past the cap. assert all("file://" in line for line in long), long # Each step's timing sits right after its text, not at the right edge. - for title in ("Show it once", "Turn it into a program"): + for title in ("Record the task", "Compile a program"): line = next(line for line in lines if title in line) assert line.rstrip().endswith("s") and len(line.rstrip()) < 80, line